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, SatinChainConfigError> { - let Entries { mut entries, duplicate } = config + let mut entries = config .deserialize_map(EntriesVisitor) .map_err(|error| SatinChainConfigError::Malformed(error.to_string()))?; - if let Some(key) = duplicate { - return Err(SatinChainConfigError::DuplicateKey(key)); - } if let Some(unknown) = entries.keys().find(|key| !SATIN_CHAIN_CONFIG_KEYS.contains(&key.as_str())) { @@ -175,8 +171,6 @@ pub enum SatinChainConfigError { Malformed(String), /// A key that starts with `satin` but is not `satinTime`. UnknownKey(String), - /// A key that starts with `satin`, given twice. - DuplicateKey(String), /// A key whose value is not of its type. InvalidValue { /// The key. @@ -195,7 +189,6 @@ impl fmt::Display for SatinChainConfigError { write!(f, "the chain configuration is malformed: {message}") } Self::UnknownKey(key) => write!(f, "`{key}` is not a Satin chain-configuration key"), - Self::DuplicateKey(key) => write!(f, "`{key}` is given twice"), Self::InvalidValue { key, expected } => write!(f, "`{key}` must be {expected}"), Self::Schedule(error) => write!(f, "{error}"), } @@ -218,19 +211,12 @@ enum Entry { Other, } -/// A configuration object's entries whose key starts with [`PREFIX`], and the first such key -/// given twice, if one was. -struct Entries { - entries: BTreeMap, - duplicate: Option, -} - -/// Collects a configuration object's entries whose key starts with [`PREFIX`], and skips the -/// others' values without keeping them. +/// Collects a configuration object's entries whose key starts with [`PREFIX`], the last copy of a +/// key given twice, and skips the others' values without keeping them. struct EntriesVisitor; impl<'de> Visitor<'de> for EntriesVisitor { - type Value = Entries; + type Value = BTreeMap; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("a chain configuration object") @@ -238,19 +224,14 @@ impl<'de> Visitor<'de> for EntriesVisitor { fn visit_map>(self, mut map: A) -> Result { let mut entries = BTreeMap::new(); - let mut duplicate = None; while let Some(key) = map.next_key::()? { if is_satin_key(&key) { - let entry = map.next_value::()?; - if entries.contains_key(&key) { - duplicate.get_or_insert_with(|| key.clone()); - } - entries.insert(key, entry); + entries.insert(key, map.next_value::()?); } else { map.next_value::()?; } } - Ok(Entries { entries, duplicate }) + Ok(entries) } } @@ -323,13 +304,16 @@ impl<'de> Visitor<'de> for EntryVisitor { /// `arbitrary_precision` feature, which a node's dependencies may switch on, hands every number /// over as a one-entry map from [`ARBITRARY_PRECISION_NUMBER`] to the number's text. That /// number is read as the same number is read without the feature, so the feature changes - /// nothing a reader accepts. + /// nothing a reader accepts: its text is decimal digits alone, with no sign, which a JSON + /// number cannot carry and `u64::from_str` would otherwise take. fn visit_map>(self, mut map: A) -> Result { let mut entry = Entry::Other; if let Some(key) = map.next_key::()? { if key == ARBITRARY_PRECISION_NUMBER { let text = map.next_value::()?; - entry = text.parse::().map_or(Entry::Other, Entry::Unsigned); + if text.bytes().all(|byte| byte.is_ascii_digit()) { + entry = text.parse::().map_or(Entry::Other, Entry::Unsigned); + } } else { map.next_value::()?; } @@ -527,27 +511,48 @@ mod tests { } } - /// A key given twice is refused where the deserializer shows both, as in the object's text; a - /// `serde_json::Value` has already kept the last one, and a key of another fork given twice is - /// not read. + /// A key given twice is read as its last copy, by every reader: the object's text through a + /// `serde_json::Deserializer`, which shows both copies, reads what a `serde_json::Value`, which + /// kept the last one, reads — the last copy, whether the first is valid or not. A key of + /// another fork given twice is not read. #[test] - fn test_a_key_given_twice_is_refused() { + fn test_the_last_copy_of_a_key_given_twice_is_read() { + let streamed = |text: &str| { + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(text)) + }; + let as_value = |text: &str| parse(&serde_json::from_str::(text).unwrap()); let text = genesis_config().to_string(); - let twice = text.replacen("\"satinTime\":", "\"satinTime\":1,\"satinTime\":", 1); - assert_eq!( - SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&twice)), - Err(SatinChainConfigError::DuplicateKey(SATIN_TIME_KEY.into())) - ); + let given = |first: &str, last: &str| { + text.replacen( + "\"satinTime\":1800000000", + &format!("\"satinTime\":{first},\"satinTime\":{last}"), + 1, + ) + }; + let refused = Err(SatinChainConfigError::InvalidValue { + key: SATIN_TIME_KEY, + expected: "an integer from 0 to 2^64 - 1", + }); + let at = |time| Ok(Some(SatinChainConfig { activation_time: time })); + for (first, last, expected) in [ + ("1", "1800000000", at(ACTIVATION)), + ("1800000000", "7", at(7)), + ("\"a string\"", "1800000000", at(ACTIVATION)), + ("1800000000", "\"a string\"", refused), + ] { + let twice = given(first, last); + assert_ne!(twice, text, "{first}, then {last}"); + assert_eq!(streamed(&twice), expected, "{first}, then {last}"); + assert_eq!(as_value(&twice), expected, "{first}, then {last}"); + } let other = text.replacen("\"chainId\":", "\"chainId\":1,\"chainId\":", 1); - assert_eq!( - SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&other)), - Ok(Some(config())) - ); + assert_eq!(streamed(&other), Ok(Some(config()))); } /// A number `serde_json` hands over as its `arbitrary_precision` feature does — a map from - /// its token to the number's text — reads as the number, and what the text does not hold as - /// an integer in 64 bits is refused as the number would be; any other map is refused. + /// its token to the number's text — reads as the number. Text that is not an integer in 64 + /// bits written in decimal digits alone — with a sign before them, for one — is refused as the + /// number would be; any other map is refused. #[test] fn test_an_arbitrary_precision_number_reads_as_the_number() { let with_time = |value: Value| { @@ -563,7 +568,9 @@ mod tests { key: SATIN_TIME_KEY, expected: "an integer from 0 to 2^64 - 1", }); - for text in ["1.5", "-1", "18446744073709551616", "1e3"] { + // Decimal digits alone: no sign, which `u64::from_str` would take and the number form + // cannot carry. + for text in ["1.5", "-1", "+7", "+1800000000", "", "18446744073709551616", "1e3"] { assert_eq!(with_time(number(text)), refused, "{text}"); } let mut two = number("1"); @@ -613,9 +620,5 @@ mod tests { .to_string(), "`satinTime` must be an integer" ); - assert_eq!( - SatinChainConfigError::DuplicateKey("satinTime".into()).to_string(), - "`satinTime` is given twice" - ); } } diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 52a91f768..1274ca0ef 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -3,10 +3,11 @@ //! The limits come from two places, by who must agree on them: //! //! - [`ProtocolLimits`] are the limits every node holds a chain's blocks and transactions to, fixed -//! per spec: the per-transaction limits the EVM enforces and the block's data-size budget. +//! per spec: the per-transaction limits the EVM enforces and the block's data-size, KV-update and +//! state-growth budgets. //! - [`BlockLimits`] is the building policy a node passes in the block execution context: the //! limits only a builder applies — a transaction's declared gas, the encoded sizes and the -//! data-availability sizes — and a cap a builder may put on the block's data-size budget below +//! data-availability sizes — and the caps a builder may put on the block's three budgets below //! the protocol's. It never loosens a protocol limit ([`BlockLimits::within`]), and a validator //! leaves it at its default, which restricts nothing. //! @@ -18,11 +19,12 @@ //! its own gas limit, encoded size and data-availability size, and what each of those would add //! to the block. //! -//! The one limit only known after execution — the data-size bytes a transaction kept — is -//! accumulated when the transaction commits. The transaction that crosses it is therefore still -//! packed, and the ones after it are refused; this is what keeps a block full rather than dropping -//! the work already done. A block whose counter has reached its limit refuses every later -//! transaction before it starts — a deposit excepted — so the overshoot is bounded by one +//! The limits only known after execution — the data-size bytes, the write records and the state +//! growth a transaction kept — are accumulated when the transaction commits. The transaction that +//! reaches one is therefore still packed, and the ones after it are refused, the refusal naming the +//! first reached of data size, KV updates and state growth; this is what keeps a block full rather +//! than dropping the work already done. A block whose counter has reached its limit refuses every +//! later transaction before it starts — a deposit excepted — so the overshoot is bounded by one //! transaction, besides what deposits add. //! //! # Deposits @@ -30,11 +32,11 @@ //! A deposit is an L1 message the chain cannot censor: the block derived from L1 must include it, //! and the builder does not choose it. So no limit only a builder applies refuses a deposit — its //! declared gas, its encoded size and its data-availability size, and what those add to the block -//! — and a deposit does not count towards the block's data-availability size. The data-size limit -//! is a packing budget for the transactions the builder chooses, so it does not refuse a deposit -//! either. A deposit still counts towards it, and towards the block's encoded size, so the -//! transactions after it find the room it used. The one limit that holds a deposit is -//! the block's gas limit, which is the header's. +//! — and a deposit does not count towards the block's data-availability size. The data-size, +//! KV-update and state-growth limits are packing budgets for the transactions the builder chooses, +//! so they do not refuse a deposit either. A deposit still counts towards each, and towards the +//! block's encoded size, so the transactions after it find the room it used. The one limit that +//! holds a deposit is the block's gas limit, which is the header's. //! //! A Mega System Transaction, the protocol's own oracle update, which the sequencer must be able //! to include whatever the block holds, is refused by none of those limits either and counts as a @@ -48,11 +50,14 @@ //! # Which dimensions are enforced //! //! The three gas ledgers the block counts ([`BlockGasCounters`]) have no block limit beside the -//! block's gas limit, the header's: state gas prices the state a block adds, so the block's gas -//! limit bounds it, and the history bytes beside the history ledger are reported, not limited. The -//! write-record count, which is the block's KV count, is reported and has no limit: every record -//! weighs forty bytes of data size, so a block held to -//! [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) keeps at most 327,680 records. +//! block's gas limit, the header's, and the history bytes beside the history ledger are reported, +//! not limited. The write-record count, which is the block's KV count, is held to +//! [`BLOCK_KV_UPDATE_LIMIT`](crate::constants::BLOCK_KV_UPDATE_LIMIT); every record weighs forty +//! bytes of data size, so a block held to [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) +//! keeps at most 327,680 records, and at the spec's numbers the data size binds first. The state +//! growth is held to [`BLOCK_STATE_GROWTH_LIMIT`](crate::constants::BLOCK_STATE_GROWTH_LIMIT): +//! state gas prices the state a block adds, but the block's gas limit does not stand in for the +//! count. use alloy_primitives::TxHash; @@ -64,7 +69,9 @@ use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ constants::{ - BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, + BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, BLOCK_KV_UPDATE_LIMIT, + BLOCK_STATE_GROWTH_LIMIT, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, TX_KV_UPDATE_LIMIT, + TX_STATE_GROWTH_LIMIT, }, BlockGasCounters, EvmTxRuntimeLimits, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, MegaSpecId, MegaTxLimitExceededError, @@ -83,9 +90,9 @@ use crate::{ /// transaction that crosses one is stopped, or a frame reverted, and that is the result its /// receipt records. There is no tighter setting a builder could run a transaction under and still /// agree with a validator; a builder that wants to avoid such a transaction leaves it out. -/// - The block's data-size budget holds what a block's transactions keep together. A validator -/// refuses a block that packs a transaction after the block reached it; a builder may pack -/// tighter ([`BlockLimits`]), never looser. +/// - The block's data-size, KV-update and state-growth budgets hold what a block's transactions +/// keep together. A validator refuses a block that packs a transaction after the block reached +/// one of them; a builder may pack tighter ([`BlockLimits`]), never looser. /// /// A tool or a test that runs under other values says so explicitly /// ([`MegaContext::with_tx_runtime_limits`](crate::MegaContext::with_tx_runtime_limits), @@ -93,8 +100,10 @@ use crate::{ /// in block execution `MegaBlockExecutor::with_protocol_limits`, which exists for tests and tools /// only); what it computes is then a counterfactual, not the chain's result. /// -/// It serializes in the shape a tool takes an override in: camelCase, every field required, no -/// other field accepted. +/// It serializes in the shape a tool takes an override in: camelCase, no other field accepted, and +/// every field required but the KV-update and state-growth limits, of a transaction and of a +/// block, which the shape's first published version did not have: a file without them takes the +/// default spec's. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProtocolLimits { @@ -102,15 +111,39 @@ pub struct ProtocolLimits { /// data size, per transaction and per frame, and gas detention's two caps. pub tx_runtime_limits: EvmTxRuntimeLimits, /// The most data-size bytes a block's transactions may keep together. The transaction that - /// reaches it is packed; after it, only a deposit is. + /// reaches it is packed; after it, only a deposit or a Mega System Transaction is. pub block_txs_data_limit: u64, + /// The most write records a block's transactions may keep together: their KV count. The + /// transaction that reaches it is packed; after it, only a deposit or a Mega System + /// Transaction is. A file without it takes the default spec's. + #[serde(default = "default_block_kv_update_limit")] + pub block_kv_update_limit: u64, + /// The most new accounts and new slots a block's transactions may keep together: their state + /// growth. The transaction that reaches it is packed; after it, only a deposit or a Mega + /// System Transaction is. The block's gas limit does not stand in for it. A file without it + /// takes the default spec's. + #[serde(default = "default_block_state_growth_limit")] + pub block_state_growth_limit: u64, +} + +/// The default spec's block KV-update budget, for a limits file that does not name one. +fn default_block_kv_update_limit() -> u64 { + ProtocolLimits::for_spec(MegaSpecId::default()).block_kv_update_limit +} + +/// The default spec's block state-growth budget, for a limits file that does not name one. +fn default_block_state_growth_limit() -> u64 { + ProtocolLimits::for_spec(MegaSpecId::default()).block_state_growth_limit } impl ProtocolLimits { /// The limits a block of `spec`, and every transaction in it, is held to. /// /// [`MegaSpecId::SATIN`]: a transaction keeps at most [`TX_DATA_LIMIT`] (13,107,200) bytes of - /// data size, and a block's transactions together at most [`BLOCK_DATA_LIMIT`] (13,107,200); + /// data size, [`TX_KV_UPDATE_LIMIT`] (500,000) write records and [`TX_STATE_GROWTH_LIMIT`] + /// (1,000) new accounts and slots, and a block's transactions together at most + /// [`BLOCK_DATA_LIMIT`] (13,107,200), [`BLOCK_KV_UPDATE_LIMIT`] (500,000) and + /// [`BLOCK_STATE_GROWTH_LIMIT`] (1,000); /// every frame gets 98/100 of what its parent has left, the transaction's own frame what the /// transaction has left, with no further per-frame cap; a read of volatile data caps the /// transaction's compute at its compute at the read plus [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] or @@ -123,11 +156,15 @@ impl ProtocolLimits { MegaSpecId::SATIN => Self { tx_runtime_limits: EvmTxRuntimeLimits { tx_data_size_limit: TX_DATA_LIMIT, + tx_kv_update_limit: TX_KV_UPDATE_LIMIT, + tx_state_growth_limit: TX_STATE_GROWTH_LIMIT, frame_data_size_limit: u64::MAX, block_env_access_compute_gas_limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, oracle_access_compute_gas_limit: ORACLE_ACCESS_COMPUTE_GAS, }, block_txs_data_limit: BLOCK_DATA_LIMIT, + block_kv_update_limit: BLOCK_KV_UPDATE_LIMIT, + block_state_growth_limit: BLOCK_STATE_GROWTH_LIMIT, }, } } @@ -138,7 +175,12 @@ impl ProtocolLimits { /// For runs that take every limit out — the execution-spec gate's equivalence mode and tests — /// never for executing the chain. pub const fn no_limits() -> Self { - Self { tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), block_txs_data_limit: u64::MAX } + Self { + tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), + block_txs_data_limit: u64::MAX, + block_kv_update_limit: u64::MAX, + block_state_growth_limit: u64::MAX, + } } /// Sets the limits every transaction runs under. @@ -152,10 +194,22 @@ impl ProtocolLimits { self.block_txs_data_limit = limit; self } + + /// Sets the block's KV-update limit. + pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { + self.block_kv_update_limit = limit; + self + } + + /// Sets the block's state-growth limit. + pub const fn with_block_state_growth_limit(mut self, limit: u64) -> Self { + self.block_state_growth_limit = limit; + self + } } -/// The building policy one block is packed under: the limits only a builder applies, and the cap -/// it may put on the block's data-size budget below the protocol's. +/// The building policy one block is packed under: the limits only a builder applies, and the caps +/// it may put on the block's data-size, KV-update and state-growth budgets below the protocol's. /// /// A node passes it in the block execution context. None of it is a protocol value: the /// protocol's limits are [`ProtocolLimits`], which the block executor reads from the spec's @@ -169,8 +223,11 @@ impl ProtocolLimits { /// data-availability size limits are the builder's alone: the protocol holds a transaction's /// declared gas to the block's gas limit, and what a block writes to its data-size budget, which /// counts calldata. -/// - [`block_txs_data_limit`](Self::block_txs_data_limit) is the builder's cap on the protocol's -/// data-size budget: the block executor holds a block to the smaller of the two. +/// - [`block_txs_data_limit`](Self::block_txs_data_limit), +/// [`block_kv_update_limit`](Self::block_kv_update_limit) and +/// [`block_state_growth_limit`](Self::block_state_growth_limit) are the builder's caps on the +/// protocol's packing budgets: the block executor holds a block to the smaller of each pair. None +/// of them refuses a deposit or a Mega System Transaction. /// /// The block's gas limit is not here: it is the header's, which the block executor takes from the /// block environment ([`BlockLimiter::block_gas_limit`]). @@ -195,6 +252,14 @@ pub struct BlockLimits { /// A builder's cap: the block is held to the smaller of this and /// [`ProtocolLimits::block_txs_data_limit`]. pub block_txs_data_limit: u64, + /// The most write records the block's transactions may keep together, as + /// [`block_txs_data_limit`](Self::block_txs_data_limit) holds their bytes: a builder's cap on + /// [`ProtocolLimits::block_kv_update_limit`]. + pub block_kv_update_limit: u64, + /// The most new accounts and new slots the block's transactions may keep together, as + /// [`block_txs_data_limit`](Self::block_txs_data_limit) holds their bytes: a builder's cap on + /// [`ProtocolLimits::block_state_growth_limit`]. + pub block_state_growth_limit: u64, } impl Default for BlockLimits { @@ -215,18 +280,25 @@ impl BlockLimits { tx_da_size_limit: u64::MAX, block_da_size_limit: u64::MAX, block_txs_data_limit: u64::MAX, + block_kv_update_limit: u64::MAX, + block_state_growth_limit: u64::MAX, } } - /// These limits held within `protocol`: the block's data-size budget is the smaller of this - /// policy's cap and the protocol's limit, so a builder's setting can tighten the budget and - /// never loosen it. The limits only a builder applies are kept as they are. + /// These limits held within `protocol`: each of the block's packing budgets — data size, KV + /// updates, state growth — is the smaller of this policy's cap and the protocol's limit, so a + /// builder's setting can tighten a budget and never loosen it. The limits only a builder + /// applies are kept as they are. /// /// A cap above the protocol's limit gives way to it without a word; a node that wants to /// refuse or report such a setting compares the two itself. pub fn within(self, protocol: &ProtocolLimits) -> Self { Self { block_txs_data_limit: self.block_txs_data_limit.min(protocol.block_txs_data_limit), + block_kv_update_limit: self.block_kv_update_limit.min(protocol.block_kv_update_limit), + block_state_growth_limit: self + .block_state_growth_limit + .min(protocol.block_state_growth_limit), ..self } } @@ -266,6 +338,18 @@ impl BlockLimits { self.block_txs_data_limit = limit; self } + + /// Caps the block's KV count. + pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { + self.block_kv_update_limit = limit; + self + } + + /// Caps the block's state growth. + pub const fn with_block_state_growth_limit(mut self, limit: u64) -> Self { + self.block_state_growth_limit = limit; + self + } } /// What one committed transaction adds to a block's counters. @@ -273,7 +357,7 @@ impl BlockLimits { pub struct BlockUsage { /// The gas by ledger, and the gas the receipt reports ([`MegaGasUsage::gas_used`]). pub gas: MegaGasUsage, - /// The data-size bytes and write records the transaction kept. + /// The data-size bytes, write records and state growth the transaction kept. pub usage: LimitUsage, /// The transaction's EIP-2718 encoded size, in bytes. pub tx_size: u64, @@ -303,7 +387,7 @@ pub struct BlockLimiter { pub block_gas_used: u64, /// The gas the block's transactions spent, by ledger. pub gas: BlockGasCounters, - /// The data-size bytes and write records the block's transactions kept. + /// The data-size bytes, write records and state growth the block's transactions kept. pub usage: LimitUsage, /// The encoded size of the block's transaction bodies, in bytes. pub block_tx_size_used: u64, @@ -433,6 +517,9 @@ impl BlockLimiter { )); } + // The three packing budgets, known only after a transaction ran: the transaction that + // reaches one is packed, and every later one is skipped before it runs. Where several are + // reached, the skip names the first of data size, KV updates and state growth. if self.usage.data_size >= self.limits.block_txs_data_limit { return Err(invalid_tx( tx_hash, @@ -442,9 +529,26 @@ impl BlockLimiter { }, )); } + if self.usage.write_records >= self.limits.block_kv_update_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::KvUpdateLimit { + block_used: self.usage.write_records, + limit: self.limits.block_kv_update_limit, + }, + )); + } + if self.usage.state_growth >= self.limits.block_state_growth_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::StateGrowthLimit { + block_used: self.usage.state_growth, + limit: self.limits.block_state_growth_limit, + }, + )); + } - // `self.gas` and `self.usage.write_records` are accumulated and not checked: none of them - // has a block limit. + // `self.gas` is accumulated and not checked: no ledger has a block limit. Ok(()) } @@ -481,8 +585,8 @@ mod tests { use alloy_primitives::B256; /// Satin's limits, written out so a change to one is a visible diff: 13,107,200 bytes of data - /// size per transaction and per block, no per-frame cap beyond the 98/100 share, and - /// detention's caps at 20,000,000 each. + /// size, 500,000 write records and 1,000 new accounts and slots, per transaction and per block, + /// no per-frame cap beyond the 98/100 share, and detention's caps at 20,000,000 each. /// /// They also hold what a chain configuration's load-time check used to hold a chain's values /// to: no limit is zero, a transaction's data size holds at least a body, and both detention @@ -496,26 +600,36 @@ mod tests { ProtocolLimits { tx_runtime_limits: EvmTxRuntimeLimits { tx_data_size_limit: 13_107_200, + tx_kv_update_limit: 500_000, + tx_state_growth_limit: 1_000, frame_data_size_limit: u64::MAX, block_env_access_compute_gas_limit: 20_000_000, oracle_access_compute_gas_limit: 20_000_000, }, block_txs_data_limit: 13_107_200, + block_kv_update_limit: 500_000, + block_state_growth_limit: 1_000, } ); let EvmTxRuntimeLimits { tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, } = limits.tx_runtime_limits; for limit in [ tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, limits.block_txs_data_limit, + limits.block_kv_update_limit, + limits.block_state_growth_limit, ] { assert_ne!(limit, 0); } @@ -525,19 +639,23 @@ mod tests { } /// The limits serialize in the shape a tool takes an override in, written out here: camelCase, - /// the per-transaction limits nested. A field left out is an error rather than a zero, and so - /// is one the type does not have. + /// the per-transaction limits nested. A field the shape's first published version had is + /// required, so leaving it out is an error rather than a zero, and so is a field the type does + /// not have; a file in that version, without the KV-update and state-growth limits, is read + /// with the spec's values for them. #[test] fn test_protocol_limits_round_trip() { let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); let limits = satin .with_tx_runtime_limits(satin.tx_runtime_limits.with_frame_data_size_limit(1)) - .with_block_txs_data_limit(7); + .with_block_txs_data_limit(7) + .with_block_kv_update_limit(8) + .with_block_state_growth_limit(9); let json = serde_json::to_string(&limits).expect("serializes"); assert_eq!( json, - r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":7}"# + r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"txKvUpdateLimit":500000,"txStateGrowthLimit":1000,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":7,"blockKvUpdateLimit":8,"blockStateGrowthLimit":9}"# ); assert_eq!(serde_json::from_str::(&json).expect("deserializes"), limits); @@ -545,6 +663,25 @@ mod tests { assert!(serde_json::from_str::(&missing).is_err(), "{missing}"); let missing_tx = json.replace(r#""frameDataSizeLimit":1,"#, ""); assert!(serde_json::from_str::(&missing_tx).is_err(), "{missing_tx}"); + + // A file in the first published version of the shape. + let first = r#"{"txRuntimeLimits":{"txDataSizeLimit":350,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":5,"oracleAccessComputeGasLimit":6},"blockTxsDataLimit":7}"#; + let read = serde_json::from_str::(first).expect("a first-version file"); + let expected = satin + .with_tx_runtime_limits( + satin + .tx_runtime_limits + .with_tx_data_size_limit(350) + .with_frame_data_size_limit(1) + .with_block_env_access_compute_gas_limit(5) + .with_oracle_access_compute_gas_limit(6), + ) + .with_block_txs_data_limit(7); + assert_eq!(read, expected, "the newer limits at Satin's values"); + assert_eq!(read.block_kv_update_limit, 500_000); + assert_eq!(read.block_state_growth_limit, 1_000); + assert_eq!(read.tx_runtime_limits.tx_kv_update_limit, 500_000); + assert_eq!(read.tx_runtime_limits.tx_state_growth_limit, 1_000); let unknown = json.replace(r#""blockTxsDataLimit":7"#, r#""blockTxsDataLimit":7,"x":1"#); assert!(serde_json::from_str::(&unknown).is_err(), "{unknown}"); } @@ -553,10 +690,16 @@ mod tests { /// so a limit added later cannot be left out of it. #[test] fn test_no_protocol_limits_leaves_every_limit_unlimited() { - let ProtocolLimits { tx_runtime_limits, block_txs_data_limit } = - ProtocolLimits::no_limits(); + let ProtocolLimits { + tx_runtime_limits, + block_txs_data_limit, + block_kv_update_limit, + block_state_growth_limit, + } = ProtocolLimits::no_limits(); assert_eq!(tx_runtime_limits, EvmTxRuntimeLimits::no_limits()); - assert_eq!(block_txs_data_limit, u64::MAX); + for limit in [block_txs_data_limit, block_kv_update_limit, block_state_growth_limit] { + assert_eq!(limit, u64::MAX); + } } /// The default building policy restricts nothing, so a validator that leaves it holds a block @@ -572,6 +715,8 @@ mod tests { tx_da_size_limit, block_da_size_limit, block_txs_data_limit, + block_kv_update_limit, + block_state_growth_limit, } = BlockLimits::default(); for limit in [ tx_gas_limit, @@ -580,6 +725,8 @@ mod tests { tx_da_size_limit, block_da_size_limit, block_txs_data_limit, + block_kv_update_limit, + block_state_growth_limit, ] { assert_eq!(limit, u64::MAX); } @@ -590,17 +737,28 @@ mod tests { crate::constants::BLOCK_DATA_LIMIT, "held within the protocol's, the default policy is the protocol's" ); + let held = BlockLimits::default().within(&ProtocolLimits::for_spec(MegaSpecId::SATIN)); + assert_eq!( + (held.block_kv_update_limit, held.block_state_growth_limit), + (crate::constants::BLOCK_KV_UPDATE_LIMIT, crate::constants::BLOCK_STATE_GROWTH_LIMIT), + "and the protocol's KV and state-growth budgets" + ); } - /// A builder's cap on the block's data-size budget holds the block only where it is below the - /// protocol's limit: it tightens, and never loosens. The limits only a builder applies pass - /// through. + /// A builder's cap on each of the block's packing budgets — data size, KV updates, state growth + /// — holds the block only where it is below the protocol's limit: it tightens, and never + /// loosens. The limits only a builder applies pass through. #[test] fn test_a_building_policy_tightens_a_budget_and_never_loosens_it() { - let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN).with_block_txs_data_limit(300); + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN) + .with_block_txs_data_limit(300) + .with_block_kv_update_limit(301) + .with_block_state_growth_limit(302); let tighter = BlockLimits::no_limits() .with_block_txs_data_limit(30) + .with_block_kv_update_limit(31) + .with_block_state_growth_limit(32) .with_tx_gas_limit(1) .with_tx_encode_size_limit(2) .with_block_txs_encode_size_limit(3) @@ -608,9 +766,14 @@ mod tests { .with_block_da_size_limit(5); assert_eq!(tighter.within(&protocol), tighter, "every cap is below the protocol's"); - let looser = BlockLimits::no_limits().with_block_txs_data_limit(3_000); + let looser = BlockLimits::no_limits() + .with_block_txs_data_limit(3_000) + .with_block_kv_update_limit(3_001) + .with_block_state_growth_limit(3_002); let held = looser.within(&protocol); assert_eq!(held.block_txs_data_limit, 300, "a cap above the protocol's gives way to it"); + assert_eq!(held.block_kv_update_limit, 301, "for the KV count too"); + assert_eq!(held.block_state_growth_limit, 302, "and for the state growth"); assert_eq!( BlockLimits { tx_gas_limit: 7, ..held }, BlockLimits { tx_gas_limit: 7, ..BlockLimits::no_limits().within(&protocol) }, @@ -633,7 +796,7 @@ mod tests { history_bytes: u64::MAX, ..Default::default() }, - usage: LimitUsage { data_size: u64::MAX, write_records: u64::MAX }, + usage: LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: 0 }, tx_size: u64::MAX, da_size: u64::MAX, da_footprint: u64::MAX, @@ -683,7 +846,8 @@ mod tests { history: u64::MAX - 1, history_bytes: u64::MAX - 1, }; - limiter.usage = LimitUsage { data_size: u64::MAX - 1, write_records: u64::MAX - 1 }; + limiter.usage = + LimitUsage { data_size: u64::MAX - 1, write_records: u64::MAX - 1, state_growth: 0 }; limiter.block_tx_size_used = u64::MAX - 1; limiter.block_da_size_used = u64::MAX - 1; limiter.block_da_footprint_used = u64::MAX - 1; @@ -700,7 +864,10 @@ mod tests { history_bytes: u64::MAX, } ); - assert_eq!(limiter.usage, LimitUsage { data_size: u64::MAX, write_records: u64::MAX }); + assert_eq!( + limiter.usage, + LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: 0 } + ); assert_eq!(limiter.block_tx_size_used, u64::MAX); assert_eq!(limiter.block_da_size_used, u64::MAX); assert_eq!(limiter.block_da_footprint_used, u64::MAX); @@ -733,7 +900,7 @@ mod tests { let mut limiter = BlockLimiter::new(BlockLimits::no_limits().with_block_txs_data_limit(1_000), u64::MAX); let deposit = BlockUsage { - usage: LimitUsage { data_size: 600, write_records: 0 }, + usage: LimitUsage { data_size: 600, write_records: 0, state_growth: 0 }, is_deposit: true, ..Default::default() }; @@ -934,7 +1101,7 @@ mod tests { history_bytes: 250, ..Default::default() }, - usage: LimitUsage { data_size: 0, write_records: 30 }, + usage: LimitUsage { data_size: 0, write_records: 30, state_growth: 0 }, ..Default::default() }; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 83243b51c..786b84620 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -145,6 +145,20 @@ pub enum MegaBlockLimitExceededError { /// The block's data-size limit. limit: u64, }, + /// The block's transactions have kept their write records: their KV count. + KvUpdateLimit { + /// The write records the block has kept. + block_used: u64, + /// The block's KV-update limit. + limit: u64, + }, + /// The block's transactions have kept their state growth: new accounts and new slots. + StateGrowthLimit { + /// The new accounts and new slots the block has kept. + block_used: u64, + /// The block's state-growth limit. + limit: u64, + }, /// The transaction's body does not fit in what the block has left. TransactionEncodeSizeLimit { /// The bytes the block's transaction bodies already take. @@ -170,6 +184,8 @@ impl MegaBlockLimitExceededError { pub const fn block_used(&self) -> u64 { match self { Self::TransactionDataLimit { block_used, .. } | + Self::KvUpdateLimit { block_used, .. } | + Self::StateGrowthLimit { block_used, .. } | Self::TransactionEncodeSizeLimit { block_used, .. } | Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, } @@ -179,6 +195,8 @@ impl MegaBlockLimitExceededError { pub const fn limit(&self) -> u64 { match self { Self::TransactionDataLimit { limit, .. } | + Self::KvUpdateLimit { limit, .. } | + Self::StateGrowthLimit { limit, .. } | Self::TransactionEncodeSizeLimit { limit, .. } | Self::DataAvailabilitySizeLimit { limit, .. } => *limit, } @@ -191,6 +209,12 @@ impl fmt::Display for MegaBlockLimitExceededError { Self::TransactionDataLimit { block_used, limit } => { write!(f, "Block transactions data limit reached: block_used={block_used} >= limit={limit}") } + Self::KvUpdateLimit { block_used, limit } => { + write!(f, "Block KV update limit reached: block_used={block_used} >= limit={limit}") + } + Self::StateGrowthLimit { block_used, limit } => { + write!(f, "Block state growth limit reached: block_used={block_used} >= limit={limit}") + } Self::TransactionEncodeSizeLimit { block_used, tx_used, limit } => write!( f, "Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}" @@ -404,6 +428,8 @@ mod tests { fn test_block_limit_error_reports_block_usage_and_limit() { let cases = [ (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), + (MegaBlockLimitExceededError::KvUpdateLimit { block_used: 2, limit: 11 }, 2, 11), + (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 3, limit: 12 }, 3, 12), ( MegaBlockLimitExceededError::TransactionEncodeSizeLimit { block_used: 4, diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index d11367e6f..50be6afb5 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -15,18 +15,23 @@ //! | [`MAX_INITCODE_SIZE`] | 1,048,576 | the most bytes an initcode may hold | the spec configuration | //! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | Satin's protocol limits | //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | Satin's protocol limits | +//! | [`TX_KV_UPDATE_LIMIT`] | 500,000 | write records one transaction may keep (as Rex6's KV updates) | Satin's protocol limits | +//! | [`BLOCK_KV_UPDATE_LIMIT`] | 500,000 | write records one block's transactions may keep (as Rex6) | Satin's protocol limits | +//! | [`TX_STATE_GROWTH_LIMIT`] | 1,000 | new accounts and slots one transaction may keep (as Rex6) | Satin's protocol limits | +//! | [`BLOCK_STATE_GROWTH_LIMIT`] | 1,000 | new accounts and slots one block's transactions may keep (as Rex6) | Satin's protocol limits | //! | [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the block environment or the beneficiary (as Rex6) | Satin's protocol limits | //! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | Satin's protocol limits | //! | [`MAX_TX_COMPUTE_GAS`] | 199,987,900 | the most compute one transaction can spend: the execution cap less EIP-2780's base cost and one warm account access | tests of the protocol limits, whose detention caps are below it | +//! | [`PRE_BLOCK_CALL_GAS_LIMIT`] | 31,566,720 | gas limit of every pre-block system call: 30,000,000 of regular gas and a reservoir of sixteen fresh slots | the block's pre-block calls | //! //! The Satin gas schedule builds its state-gas entries from the EIP-8037 byte counts at //! [`COST_PER_STATE_BYTE`], read through [`SatinPrices`](crate::SatinPrices) so a measurement //! build can run other byte prices without touching this table. [`SLOT_STATE_GAS`] and //! [`ACCOUNT_STATE_GAS`] are two of those products written out: the tests assert the schedule //! against them, and changing one of the two moves a test rather than a price. -//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`] and the two detention caps are Satin's protocol limits -//! ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)). No limit holds state growth: -//! state gas prices it. +//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`], the KV-update and state-growth limits and the two +//! detention caps are Satin's protocol limits +//! ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)). use revm::{ context_interface::cfg::gas::WARM_STORAGE_READ_COST, @@ -72,6 +77,21 @@ pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; /// The most data one block may produce, 12.5 MiB as in Rex6. Provisional. pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; +/// The most write records one transaction may keep: its KV count, as Rex6's KV-update limit. +/// Provisional. +pub const TX_KV_UPDATE_LIMIT: u64 = 500_000; + +/// The most write records one block's transactions may keep together, as Rex6's. Provisional. +pub const BLOCK_KV_UPDATE_LIMIT: u64 = 500_000; + +/// The most new accounts and new storage slots one transaction may keep, net, as Rex6's +/// state-growth limit. Provisional. +pub const TX_STATE_GROWTH_LIMIT: u64 = 1_000; + +/// The most new accounts and new storage slots one block's transactions may keep together, as +/// Rex6's. Provisional. +pub const BLOCK_STATE_GROWTH_LIMIT: u64 = 1_000; + /// The compute a transaction may still spend once it read the block environment or the block /// beneficiary's account: its compute at the read plus this. The value and its relative reading /// are Rex6's. Provisional. @@ -94,6 +114,24 @@ pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; pub const MAX_TX_COMPUTE_GAS: u64 = TX_GAS_LIMIT_CAP - eip2780::TX_BASE_COST - WARM_STORAGE_READ_COST; +/// The gas limit every pre-block system call runs on — the EIP-2935 and EIP-4788 calls and the +/// `SequencerRegistry`'s `applyPendingChanges()` — whatever the block's gas limit. Provisional. +/// +/// It is the 30,000,000 of regular gas a system call runs on at most +/// ([`SYSTEM_CALL_REGULAR_GAS_LIMIT`](crate::SYSTEM_CALL_REGULAR_GAS_LIMIT)), and a state-gas +/// reservoir of sixteen fresh storage slots at the minimum SALT bucket, which every system call +/// prices at: `30,000,000 + 16 × SLOT_STATE_GAS = 30,000,000 + 16 × 97,920 = 31,566,720`. +/// +/// Where the EIP-2935 and EIP-4788 addresses hold those EIPs' own code, the most fresh slots one +/// pre-block call writes is six: an `applyPendingChanges()` that applies both roles, writing for +/// each its current address, its history's length and the history's new entry, where all three +/// were empty. The EIP-4788 call writes two, and the EIP-2935 call one. So the reservoir holds what +/// any of them writes more than twice over, and at the byte prices of this table no pre-block +/// call's state gas spills onto its regular gas; at a dearer state byte, or under other code at +/// those addresses, what the reservoir does not hold spills onto the 30,000,000. +pub const PRE_BLOCK_CALL_GAS_LIMIT: u64 = + crate::SYSTEM_CALL_REGULAR_GAS_LIMIT + 16 * SLOT_STATE_GAS; + #[cfg(test)] mod tests { use super::*; @@ -111,5 +149,6 @@ mod tests { // The data-size limits and the detention caps are written out with the protocol limits // that read them, in `ProtocolLimits::for_spec`'s own test. assert_eq!(MAX_TX_COMPUTE_GAS, 199_987_900); + assert_eq!(PRE_BLOCK_CALL_GAS_LIMIT, 31_566_720); } } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 03d3fe786..7dd04b1b6 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,39 +1,36 @@ //! The execution context of the Satin engine. -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - use delegate::delegate; use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpSpecId}; use revm::{ context::{ - BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, - Transaction, + BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Journal, + LocalContext, Transaction, + }, + context_interface::{ + cfg::{gas::GasTracker, GasId}, + context::CodeDeposit, }, - context_interface::{cfg::GasId, context::CodeDeposit}, primitives::{Address, Bytes, StorageKey}, - Database, Journal, + Database, }; use crate::{ constants, evm::{ history::transaction_body_bytes, - inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - system::{ - self, - keyless::{self, KeylessFrame}, - }, + limit::{Accounts, Counted}, + system::{self, keyless}, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, VolatileDataAccess, + LimitUsage, MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, + VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` -/// transaction type. +/// transaction type, on revm's own journal. pub(crate) type MegaInnerContext = Context, DB, Journal, L1BlockInfo>; @@ -46,8 +43,9 @@ pub(crate) type MegaInnerContext = /// configuration), so they cannot drift apart. /// /// Every context accessor delegates to the wrapped context, and so does every -/// [`Host`](revm::interpreter::Host) method except the three that stage what a state-writing -/// opcode did and the ones that load volatile data (see the `host` module). It also carries the +/// [`Host`](revm::interpreter::Host) method except the two instruction hooks, which meter a +/// completed write and a frame start, and the ones that load volatile data (see the `host` +/// module). It also carries the /// common execution layer's state for the running transaction ([`AdditionalLimit`]), gas /// detention's ([`Detention`]), the SALT bucket multipliers that transaction has priced state /// gas with ([`BucketMultipliers`]) and the reads of the Oracle's storage it made through the @@ -60,9 +58,6 @@ pub struct MegaContext>, pub(crate) block_hash_record: BlockHashRecord, /// The SALT bucket multipliers the running transaction has read. bucket_multipliers: BucketMultipliers, @@ -79,9 +74,9 @@ pub struct MegaContext, + /// The creation the running transaction's `keylessDeploy` call started, while it runs. See + /// the [`keyless`](crate::system::keyless) module. + pub(crate) keyless_creation: Option, /// Whether the context runs the neutral configuration. See [`MegaContext::with_neutral_cfg`]. #[cfg(any(test, feature = "test-utils"))] neutral: bool, @@ -106,16 +101,15 @@ impl MegaContext { external_envs: ExternalEnvs, ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); - let inner = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); + let limits = ProtocolLimits::for_spec(spec).tx_runtime_limits; + let inner: MegaInnerContext = + Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); Self { inner, cfg, external_envs, - additional_limit: AdditionalLimit::new( - ProtocolLimits::for_spec(spec).tx_runtime_limits, - ), + additional_limit: AdditionalLimit::new(limits), detention: Detention::default(), - upfront_records: Vec::new(), block_hash_record: BlockHashRecord::default(), bucket_multipliers: BucketMultipliers::default(), bucket_record: BucketRecord::default(), @@ -123,7 +117,7 @@ impl MegaContext { system_originated: false, system_call: false, prices_history: true, - keyless_frame: None, + keyless_creation: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, } @@ -133,9 +127,9 @@ impl MegaContext { /// /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas schedule, /// the EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch and its - /// disabling flag, the system-call state-gas margin, the chain-id check and the two code-size - /// limits. Every other field (chain id, the other disabled checks, blob schedule) is taken - /// from `cfg`. + /// disabling flag, the chain-id check, the two code-size limits and the fork's switch back to + /// revm 40.0.3's journal semantics. Every other field (chain id, the other disabled checks, + /// blob schedule) is taken from `cfg`. /// /// A context that ran the neutral configuration returns to the spec's. pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { @@ -159,9 +153,13 @@ impl MegaContext { /// /// - Every field is taken from `cfg`, including the ones [`with_cfg`](Self::with_cfg) sets from /// the spec: the gas schedule, the EIP-8037, EIP-2780 and EIP-7708 switches, the execution - /// cap and the code-size limits. + /// cap and the code-size limits. The one exception is the fork's switch back to revm 40.0.3's + /// journal semantics, which stays off: the journal's semantics are part of the machinery + /// under test, not of what is priced. /// - No transaction pays history gas, and none has its schedule swapped for its history /// exemption: every transaction runs `cfg`'s schedule. + /// - A system call's gas is not split: its whole gas limit is regular gas, as revm's own runner + /// has it. /// - SALT pricing needs nothing here: without a SALT environment every bucket is minimal, and /// the multiplier is one. /// - Gas detention is not part of the configuration: its caps are runtime limits, which the @@ -172,7 +170,9 @@ impl MegaContext { /// journal execute. The precompile set is the EVM's, not the context's: a caller that wants /// the fixture fork's replaces it on the [`MegaEvm`](crate::MegaEvm). #[cfg(any(test, feature = "test-utils"))] - pub fn with_neutral_cfg(mut self, cfg: CfgEnv) -> Self { + pub fn with_neutral_cfg(mut self, mut cfg: CfgEnv) -> Self { + // The journal's semantics are part of the machinery, not of what is priced. + cfg.legacy_journal_semantics = false; self.inner = self.inner.with_cfg(op_cfg(&cfg)); self.cfg = cfg; self.neutral = true; @@ -241,10 +241,16 @@ impl MegaContext { /// Enforces `limits` on every transaction from now on, in place of the spec's: a tool's or a /// test's counterfactual. pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { - self.additional_limit.set_limits(limits); + self.set_tx_runtime_limits(limits); self } + /// Holds every transaction from the next one on to `limits`: the data-size limit and gas + /// detention alike. + pub(crate) const fn set_tx_runtime_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.additional_limit.set_limits(limits); + } + /// The block hashes execution has read on this context. /// /// The record belongs to one block: block execution empties it when the block starts, so it @@ -288,6 +294,20 @@ impl MegaContext { &self.additional_limit } + /// What the running (or last) transaction keeps so far: its data-size bytes and write records, + /// with every running frame counted as if it succeeds. It is what the transaction's outcome + /// reports ([`MegaTransactionOutcome::usage`](crate::MegaTransactionOutcome::usage)) once it + /// ran, and what the data-size limit holds it to; the next transaction or system call resets + /// it. + pub fn limit_usage(&self) -> LimitUsage { + self.additional_limit.usage() + } + + /// The accounts the running transaction holds, read for the write records a write makes. + pub(crate) fn accounts(&self) -> Accounts<'_> { + Accounts::of(self.journal_ref(), self.additional_limit.counts_transfer_logs()) + } + /// Gas detention for the running (or last) transaction: the volatile data it read and the /// compute limit that set. See the `access` module. pub const fn detention(&self) -> &Detention { @@ -424,8 +444,36 @@ impl MegaContext { self.system_call } + /// Whether the running execution's gas is split as EIP-8037 splits a system call's: at most + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`](crate::SYSTEM_CALL_REGULAR_GAS_LIMIT) of it regular gas, + /// the rest its state-gas reservoir. Every system call's is, whatever the caller's + /// configuration: which pool pays the protocol's own state writes, and what `GAS` reads inside + /// a system contract, are part of executing the chain. No transaction's is, and under the + /// neutral configuration no system call's either, as revm's own runner has it. + pub(crate) fn splits_system_call_gas(&self) -> bool { + #[cfg(any(test, feature = "test-utils"))] + if self.neutral { + return false; + } + self.system_call + } + + /// Whether the destruction table prices state gas: a destruction of an account created in the + /// transaction gives back the state gas of the parts the transaction made, and from that mark + /// the account keeps no further state gas. So under the spec's configuration, which charges + /// EIP-8037 state gas. The neutral configuration prices as the fixture's fork does, and + /// EIP-8037 gives back no state gas for this destruction; the table's counts are the same + /// under both. + pub(crate) fn destruction_table_prices_state_gas(&self) -> bool { + #[cfg(any(test, feature = "test-utils"))] + if self.neutral { + return false; + } + self.inner.cfg.is_amsterdam_eip8037_enabled() + } + /// Prepares the common execution layer for a transaction or a system call that is, or is not, - /// `system_originated`. + /// `system_originated`: the layer begins it, counting its body. /// /// The SALT bucket multipliers and the oracle reads go with it: they are what one transaction /// read, so the next one reads its own. @@ -436,22 +484,19 @@ impl MegaContext { /// it uses is counted all the same. A user's deposit is not system-originated and is held /// to every one of them. fn prepare(&mut self, system_originated: bool) { - self.additional_limit.reset(); - self.additional_limit.set_transfer_logs(emits_transfer_logs(&self.inner.cfg)); + let transfer_logs = emits_transfer_logs(&self.inner.cfg); self.bucket_multipliers.reset(); self.oracle_reads.clear(); - // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call - // unanswered. - self.keyless_frame = None; + // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call's + // creation unsettled. + self.keyless_creation = None; self.system_originated = system_originated; let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; self.set_history_exempt(exempt); - if system_originated { - self.additional_limit.exempt(); - } // The body is data size whether or not the transaction pays history for it. A deposit, // a system transaction and a system call are exempt from the charge, not from the count. - self.additional_limit.record_tx_body(transaction_body_bytes(self.tx())); + let body = transaction_body_bytes(self.tx()); + self.additional_limit.begin_transaction(system_originated, transfer_logs, body); // The protocol's own transactions are not detained: they maintain the volatile data. let limits = self.additional_limit.limits(); self.detention.reset( @@ -550,13 +595,11 @@ impl MegaContext { /// transfer log is data size like any log, and pays no history gas: Ethereum prices it at /// nothing, and it is not a byte the transaction chose to write (see the `limit` module). /// -/// A system call runs as EIP-8037 has it: on at most the base 30,000,000 of regular gas, the -/// rest of its gas limit being its state-gas reservoir, which the state it writes draws first. -/// The switch for it is set on whatever the caller's configuration says, because which pool pays -/// the protocol's own state writes, and what `GAS` reads inside a system contract, are part of -/// executing the chain. It reaches system calls only: every transaction's gas is split by the -/// execution cap as before, the system-address transaction's included, which is a deposit and -/// not a system call. +/// The journal runs with the fork's journal semantics, not revm 40.0.3's: a storage slot warmed +/// while cold inside the current transaction keeps its EIP-2200 baseline, and a reverted code +/// change restores the code the account had. The fork's switch back to revm 40.0.3's semantics +/// exists for the engine that reproduces that version; it is set off here whatever the caller's +/// configuration says, since the journal's own copy of it is written from this configuration. /// /// The chain-id check is on, whatever the caller's configuration says: a transaction that carries /// a chain id must carry the chain's, and one of a type other than legacy must carry one. Which @@ -568,10 +611,10 @@ pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg.tx_gas_limit_cap = Some(constants::TX_GAS_LIMIT_CAP); cfg.enable_amsterdam_eip7708 = true; cfg.amsterdam_eip7708_disabled = false; - cfg.system_call_state_gas_margin_in_reservoir = true; cfg.tx_chain_id_check = true; cfg.limit_contract_code_size = Some(constants::MAX_CONTRACT_SIZE); cfg.limit_contract_initcode_size = Some(constants::MAX_INITCODE_SIZE); + cfg.legacy_journal_semantics = false; cfg } @@ -626,24 +669,39 @@ impl ContextTr for MegaContext) -> Result<(), Bytes> { - let destroyed = self - .journal_ref() - .state - .get(&deposit.address) - .is_some_and(|account| account.is_selfdestructed()); - if keyless::refuses_empty_deposit(&mut self.keyless_frame, deposit, destroyed) { + fn admit_code_deposit( + &mut self, + deposit: &CodeDeposit<'_>, + gas: &mut GasTracker, + ) -> Result<(), Bytes> { + // Destroyed in this transaction: the flag revm keeps for the whole journal may stand from + // an earlier transaction on it. + let destroyed = self.accounts().is_destroyed(deposit.address); + if keyless::refuses_empty_deposit(&mut self.keyless_creation, deposit, destroyed) { return Err(Bytes::new()); } - self.additional_limit.on_code_deposit(deposit) + let check = self.additional_limit.draw(gas, &Counted::bytes(deposit.code.len() as u64)); + if check.exceeded_limit() { + return Err(self.additional_limit.note_frame_stop(&check)); + } + Ok(()) } } @@ -675,12 +733,21 @@ mod tests { assert_eq!(cfg.cap, Some(constants::TX_GAS_LIMIT_CAP), "execution cap"); assert!(cfg.eip7708, "EIP-7708 must be on"); assert!(!cfg.eip7708_disabled, "EIP-7708 must not be disabled"); - assert!(cfg.margin, "a system call's gas above 30M must be its reservoir"); assert!(cfg.chain_id_check, "the chain id must be checked"); assert_eq!(cfg.code_size, Some(constants::MAX_CONTRACT_SIZE), "contract size"); assert_eq!(cfg.initcode_size, Some(constants::MAX_INITCODE_SIZE), "initcode size"); assert_eq!(cfg.gas_params.table(), satin_gas_params().table(), "gas schedule"); + assert!(!cfg.legacy, "revm 40.0.3's journal semantics must stay off"); } + assert_journal_runs_the_spec_switches(ctx); + } + + /// The journal's own copies of the switches it reads, as the context's cfg sync delivered + /// them: the fork's journal semantics, and EIP-7708 transfer logs on. + fn assert_journal_runs_the_spec_switches(ctx: &MegaContext) { + let journal = &ctx.journal_ref().inner; + assert!(!journal.legacy_journal_semantics(), "the journal keeps the fork's semantics"); + assert!(journal.amsterdam_eip7708_enabled(), "the journal emits transfer logs"); } /// The configuration fields the spec fixes, read out of either view. @@ -690,11 +757,11 @@ mod tests { cap: Option, eip7708: bool, eip7708_disabled: bool, - margin: bool, chain_id_check: bool, code_size: Option, initcode_size: Option, gas_params: &'a GasParams, + legacy: bool, } impl<'a> Fixed<'a> { @@ -705,11 +772,11 @@ mod tests { cap: cfg.tx_gas_limit_cap, eip7708: cfg.enable_amsterdam_eip7708, eip7708_disabled: cfg.amsterdam_eip7708_disabled, - margin: cfg.system_call_state_gas_margin_in_reservoir, chain_id_check: cfg.tx_chain_id_check, code_size: cfg.limit_contract_code_size, initcode_size: cfg.limit_contract_initcode_size, gas_params: &cfg.gas_params, + legacy: cfg.legacy_journal_semantics, } } } @@ -756,11 +823,11 @@ mod tests { cfg.tx_gas_limit_cap = Some(1 << 24); cfg.enable_amsterdam_eip7708 = false; cfg.amsterdam_eip7708_disabled = true; - cfg.system_call_state_gas_margin_in_reservoir = false; cfg.tx_chain_id_check = false; cfg.limit_contract_code_size = Some(24 * 1024); cfg.limit_contract_initcode_size = Some(48 * 1024); cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); + cfg.legacy_journal_semantics = true; }); assert_satin_cfg(&ctx); @@ -768,6 +835,32 @@ mod tests { assert_eq!(ctx.cfg().chain_id, 4326); } + /// The switch back to revm 40.0.3's journal semantics is the legacy engine's. A configuration + /// carrying every switch at the legacy engine's values — it exports that one on — changes + /// nothing the journal reads: the fork's semantics and transfer logs stay as the spec fixes + /// them, in `cfg` and in the journal's copies, under the spec's configuration and the neutral + /// one. + #[test] + fn test_a_legacy_engine_cfg_does_not_change_the_journal_switches() { + let ctx = context_with(|cfg| { + cfg.enable_amsterdam_eip8037 = false; + cfg.enable_amsterdam_eip2780 = false; + cfg.enable_amsterdam_eip7708 = false; + cfg.legacy_journal_semantics = true; + }); + assert_satin_cfg(&ctx); + + let neutral = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg({ + let mut cfg = osaka_cfg(); + cfg.legacy_journal_semantics = true; + cfg + }); + assert!(neutral.is_neutral()); + assert!(!neutral.mega_cfg().legacy_journal_semantics); + assert!(!neutral.cfg().legacy_journal_semantics); + assert!(!neutral.journal_ref().inner.legacy_journal_semantics()); + } + /// The op-revm view is the `MegaETH` view keyed by the base spec, field for field. #[test] fn test_with_cfg_spec_consistency() { @@ -903,6 +996,25 @@ mod tests { assert!(!ctx.is_system_call(), "nor is a system transaction, which the protocol sends"); } + /// A system call's gas is split as EIP-8037 has it; a transaction's is not, a system-address + /// transaction's neither, and under the neutral configuration no system call's is. + #[test] + fn test_only_a_system_call_splits_its_gas() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert!(!ctx.splits_system_call_gas()); + ctx.on_new_system_call(); + assert!(ctx.splits_system_call_gas()); + ctx.on_new_tx(false); + assert!(!ctx.splits_system_call_gas(), "a transaction is split by the execution cap"); + ctx.on_new_tx(true); + assert!(!ctx.splits_system_call_gas(), "so is a system-address transaction"); + + let mut neutral = + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(osaka_cfg()); + neutral.on_new_system_call(); + assert!(!neutral.splits_system_call_gas(), "as revm's own runner has it"); + } + /// Two contexts may read one SALT environment — a node builds an EVM per transaction over /// the block's environments — and each keeps the multipliers it read to itself. #[test] @@ -1046,24 +1158,12 @@ mod tests { /// transaction reads the configuration afresh, and Satin's emits them. #[test] fn test_a_transaction_counts_transfer_logs_where_revm_emits_them() { - let endowed_creation = - revm::interpreter::FrameInput::Create(Box::new(revm::interpreter::CreateInputs::new( - Address::repeat_byte(0x11), - revm::interpreter::CreateScheme::Create, - U256::from(1), - revm::primitives::Bytes::new(), - 0, - 0, - ))); let counts = |cfg: CfgEnv| { let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg); ctx.set_tx(call_from(Address::repeat_byte(0x11))); ctx.on_new_tx(false); - assert_eq!( - ctx.additional_limit.frame_start_transfer_log(&endowed_creation), - emits_transfer_logs(ctx.cfg()), - ); + assert_eq!(ctx.additional_limit.counts_transfer_logs(), emits_transfer_logs(ctx.cfg())); emits_transfer_logs(ctx.cfg()) }; let with = |enabled: bool, disabled: bool| { @@ -1084,7 +1184,7 @@ mod tests { }); ctx.set_tx(call_from(Address::repeat_byte(0x11))); ctx.on_new_tx(false); - assert!(ctx.additional_limit.frame_start_transfer_log(&endowed_creation)); + assert!(ctx.additional_limit.counts_transfer_logs()); } /// A context is not neutral unless it is asked to be. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 0db00ef6f..329a8da8b 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1,8 +1,11 @@ //! The Satin handler and the frame lifecycle of [`MegaEvm`]. //! //! [`MegaHandler`] runs a transaction through op-revm's [`OpHandler`] and overrides the phases -//! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] and [`InspectorEvmTr`] itself, so the -//! frame lifecycle (`frame_init`, `frame_run`, `frame_return_result`) is `MegaETH`'s own. +//! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] itself, so a frame's start and its +//! return to its caller (`frame_init`, `frame_return_result`) are `MegaETH`'s own; its frame run is +//! revm's, but for an action set on a frame before it runs, which it returns as revm's inspected +//! run does. Its [`InspectorEvmTr`] is revm's inspected lifecycle unchanged, which starts and +//! returns frames through the same two methods. #[cfg(not(feature = "std"))] use alloc as std; @@ -13,52 +16,57 @@ use op_revm::{ transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpHaltReason, OpTransactionError, }; -use std::vec::Vec; +use std::{collections::BTreeMap, vec::Vec}; use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ context::{ result::{FromStringError, InvalidTransaction, ResultGas}, transaction::TransactionType, - ContextError, ContextTr, FrameStack, JournalTr, Transaction, + ContextError, ContextTr, FrameStack, Journal, JournalTr, Transaction, }, context_interface::{ - cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, - journaled_state::{account::JournaledAccountTr, entry::JournalEntry, JournalCheckpoint}, + cfg::{ + gas::{GasTracker, PoolAmounts, PoolId, StartCharge}, + GasId, GasParams, StateGasCharge, StateGasSite, + }, + journaled_state::{entry::JournalEntry, JournalCheckpoint}, Host, }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, execution::runtime_oog_unwind, - instructions::InstructionProvider, + pre_execution::Eip7702AuthFacts, EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, PreExecutionOutput, }, - inspector::{ - handler::{frame_start, inspect_instructions}, - InspectorEvmTr, InspectorHandler, JournalExt, - }, + inspector::{InspectorEvmTr, InspectorHandler, JournalExt}, interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, - InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, + interpreter::EthInterpreter, interpreter_action::FrameInit, interpreter_types::LoopControl, + CallScheme, FrameInput, Gas, InitialAndFloorGas, InstructionResult, InterpreterAction, + InterpreterResult, }, - primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT, U256}, - Inspector, Journal, + primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, + Inspector, }; use crate::{ access::ComputeStop, - charge_write_records_history, - evm::inspector::{ - frame_end_checked, journal_position, revert_journal_to, ResultSource, StepGuard, - UpfrontRecord, - }, - history_gas, synthetic_frame_result, + charge_write_records_history, history_gas, + limit::{Counted, CreatorBefore}, + synthetic_frame_result, system::keyless, - Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, - PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, + write_record_history_gas, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, + MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; +#[cfg(debug_assertions)] +use crate::limit::StartRecords; + +/// The regular gas a system call runs on, at most: EIP-8037's system-call budget. The rest of its +/// gas limit is its state-gas reservoir ([`MegaHandler`]'s `tx_gas`). +pub const SYSTEM_CALL_REGULAR_GAS_LIMIT: u64 = 30_000_000; + /// The Satin handler. /// /// It wraps op-revm's [`OpHandler`] and delegates every phase `MegaETH` does not extend to it. @@ -66,17 +74,19 @@ use crate::{ #[derive(Debug)] pub struct MegaHandler { op: OpHandler, - /// Whether validation found the caller of a deposit-like transaction empty, so executing it - /// creates that account. Read by the pre-execution phase, which charges for the account - /// before the transaction runs; by then the caller has been materialised and the fact is no - /// longer visible in the state. - deposit_creates_caller: Cell, + /// The reservoir the transaction's result settled with, read by + /// [`post_execution`](Handler::post_execution) where revm builds the result's gas, and + /// consumed by the report once the result is built + /// ([`execution_result`](Handler::execution_result)) or by the error path + /// ([`catch_error`](Handler::catch_error)), so a handler reused for a system call, whose path + /// makes no capture, reports the system call's own reservoir. + settled_reservoir: Cell>, } impl MegaHandler { /// Creates a handler. pub fn new() -> Self { - Self { op: OpHandler::new(), deposit_creates_caller: Cell::new(false) } + Self { op: OpHandler::new(), settled_reservoir: Cell::new(None) } } } @@ -153,7 +163,9 @@ where /// /// Validation refused every transaction whose body, with a record for each entry of its /// authorization list, crosses the data-size limit, so neither the body nor the authorities' - /// records cross it here, and no limit stops the transaction before its first frame. + /// records cross it here. The KV-update and state-growth limits can be crossed here, by the + /// authorization list: a list that would cross either is not applied, and the transaction's + /// own frame is stopped before it runs. fn pre_execution( &self, evm: &mut Self::Evm, @@ -166,19 +178,33 @@ where // out-of-gas creation cannot be replayed. revm's own pre-execution never needs the bump, // because only an EIP-7702 transaction, always a call, can bail out there; the two // charges made here can fail for a creation too. - if self.deposit_creates_caller.get() && !charge_created_caller(evm.ctx_mut(), gas) { - runtime_oog_unwind(evm.ctx(), checkpoint)?; - return Ok(None); + if deposit_created_caller(evm.ctx()) { + evm.ctx_mut().additional_limit.count_created_caller(); + if !charge_created_caller(evm.ctx_mut(), gas) { + runtime_oog_unwind(evm.ctx(), checkpoint)?; + return Ok(None); + } } - let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { - runtime_oog_unwind(evm.ctx(), checkpoint)?; - return Ok(None); + // The authorization list is decided before it is applied: a list that would keep more + // records or create more accounts than the transaction's limits allow is skipped whole, + // charged nothing, and the transaction's own frame returns the stop before it runs. + let stop = hold_authorization_list(evm.ctx_mut())?; + let eip7702_refund = if let Some(stop) = stop { + evm.ctx_mut().additional_limit.skip_authorization_list(stop); + 0 + } else { + let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { + runtime_oog_unwind(evm.ctx(), checkpoint)?; + return Ok(None); + }; + eip7702_refund }; - let applied = record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + let (applied, created) = applied_authorities(evm.ctx_mut(), checkpoint.journal_i); if !charge_records_made_outside_a_frame(evm.ctx_mut(), gas, applied) { runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); } + evm.ctx_mut().additional_limit.count_authorities(applied, created); Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -197,36 +223,24 @@ where self.validate_env_as(evm, system_address, true) } - /// Notes whether this transaction's caller is an account executing it creates, then deducts - /// the caller as op-revm does, which is what creates it. - /// - /// Only a deposit-like transaction can have one: every other transaction pays a fee, which - /// an empty account cannot. The account is charged for in - /// [`pre_execution`](Handler::pre_execution). + /// Deducts the caller as op-revm does. fn validate_against_state_and_deduct_caller( &self, evm: &mut Self::Evm, init_and_floor_gas: &mut InitialAndFloorGas, ) -> Result<(), Self::Error> { - self.deposit_creates_caller.set(deposit_creates_caller(evm.ctx_mut())?); self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } - /// revm's intrinsic gas, with the history gas of the transaction's body added to the - /// EIP-8037 intrinsic state-gas slot. + /// revm's intrinsic gas, held to a gas limit that covers the history gas of the transaction's + /// body as well, which [`tx_gas`](Handler::tx_gas) charges. /// /// The body's bytes are fixed before the transaction runs, so their price is part of what a /// gas limit has to cover for the transaction to be valid at all: a limit that falls short is /// rejected before inclusion rather than included as an out-of-gas that burns the whole limit. /// revm made that check on its own figure, so the grown figure is checked again here, with the - /// same error naming the same two numbers. - /// - /// The slot it rides in is the state one because that is the pool EIP-8037 pays it from: the - /// reservoir first, spilling onto the regular budget only past it, so a body does not take the - /// execution cap away from computation. The cap check revm made stands as it was — it tests - /// the regular intrinsic gas, which this does not touch — and - /// [`post_execution`](Handler::post_execution) takes the body back out of the state gas the - /// result reports. + /// same error naming the same two numbers. The cap check revm made stands as it was: it tests + /// the regular intrinsic gas, which the body's history does not touch. /// /// A transaction exempt from history gas carries none of it /// ([`MegaContext::prices_history`](crate::MegaContext::prices_history)), so its intrinsic gas @@ -247,11 +261,11 @@ where if !evm.ctx_ref().additional_limit.admits_tx_body(authorizations) { return Err(InvalidTransaction::Str(TX_BODY_OVER_DATA_SIZE_LIMIT.into()).into()); } - let mut gas = self.op.validate_initial_tx_gas(evm)?; + let gas = self.op.validate_initial_tx_gas(evm)?; if !evm.ctx_ref().prices_history() { return Ok(gas); } - let bytes = evm.ctx_ref().additional_limit.body_bytes(); + let bytes = evm.ctx_ref().additional_limit.body(); // A byte count with no price saturates, which no gas limit covers: the transaction is // rejected for not covering its own intrinsic gas. let history = history_gas(bytes).unwrap_or(u64::MAX); @@ -264,75 +278,122 @@ where InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas }.into() ); } - gas.set_initial_state_gas(gas.initial_state_gas_final() + history); evm.ctx_mut().additional_limit.set_intrinsic_history(history, bytes); Ok(gas) } - /// revm's first frame, with a read of the block beneficiary's account marked for gas detention - /// when the transaction's recipient delegates to the beneficiary: revm resolves that delegate - /// through the journal, where the Host does not see it. + /// revm's transaction-level gas, with the history gas of the transaction's body charged on + /// it, and a system call's split as EIP-8037 has it: at most [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] + /// 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. + /// + /// The body's history is intrinsic: it comes out of the reservoir first and its excess off the + /// regular budget, as EIP-8037's intrinsic state gas does, so a body does not take the + /// execution cap away from computation; and, as intrinsic gas, no reservoir a frame hands back + /// unwinds it onto the regular budget, so it is charged as no spill. It is charged here rather + /// than before the first frame because revm's runtime out-of-gas fallback rebuilds the + /// transaction's gas through this phase, and a transaction that runs out of gas there keeps its + /// body charged. Validation admitted no gas limit that cannot pay for it + /// ([`validate_initial_tx_gas`](Handler::validate_initial_tx_gas)). + /// + /// revm builds a system call's gas here, on no intrinsic gas, and so does its runtime + /// out-of-gas fallback, which a system call does not reach: it carries no value and its target + /// is no delegator. Every transaction's gas is split by the execution cap alone, the + /// system-address transaction's included, which is a deposit and not a system call; and under + /// the neutral configuration a system call's is not split, as revm's own runner has it. + fn tx_gas(&self, evm: &mut Self::Evm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + let mut gas = self.op.tx_gas(evm, init_and_floor_gas); + let history = evm.ctx_ref().additional_limit.intrinsic_history_gas(); + if history != 0 { + let spilled = gas.state_gas_spilled(); + let charged = gas.record_history_cost(history); + debug_assert!(charged, "validation admits no gas limit that cannot pay for the body"); + gas.set_state_gas_spilled(spilled); + } + if evm.ctx_ref().splits_system_call_gas() { + let margin = gas.remaining().saturating_sub(SYSTEM_CALL_REGULAR_GAS_LIMIT); + gas.set_remaining(gas.remaining() - margin); + gas.set_reservoir(gas.reservoir() + margin); + } + gas + } + + /// revm's first frame, on the transaction's pool, carrying as its start charge the history + /// charged before execution for the write record it makes; with a read of the block + /// beneficiary's account marked for gas detention when the transaction's recipient delegates + /// to the beneficiary: revm resolves that delegate through the journal, where the Host does + /// not see it. + /// + /// The pools are what the transaction has left of its data-size, KV-update and state-growth + /// limits once its body, the records of the authorities it applied, the accounts they created + /// and a deposit's created caller are counted, the data size under the frame cap + /// ([`AdditionalLimit::first_frame_pools`](crate::AdditionalLimit)); revm hands the frame the + /// whole of each. fn first_frame_input( &mut self, evm: &mut Self::Evm, gas: &mut GasTracker, ) -> Result, Self::Error> { - let Some(frame) = self.op.first_frame_input(evm, gas)? else { + gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); + let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge // for the account the frame adds, a call's recipient or a creation's account, or the // access to the code a delegated recipient runs, warm or cold. A price of that account // charge that could not be read ends here too: the lookup recorded its cause, which - // fails the transaction when it settles. In each case revm drops the phase's partial - // charges by rebuilding the transaction's gas from its intrinsic cost, and the history - // charged for the first frame's write record went with them: the settlement must not - // give it back a second time, into a reservoir a transaction below the execution cap - // never had. - evm.ctx_mut().additional_limit.set_top_level_write_record_gas(0); + // fails the transaction when it settles. In each case revm takes the phase's state + // back, the authorizations with their records, and drops its partial charges by + // rebuilding the transaction's gas from its intrinsic cost, the history charged for + // the first frame's write record included, which no frame carries back. + evm.ctx_mut().additional_limit.take_back_authorities(); return Ok(None); }; + let charge = StartCharge::new( + evm.ctx_ref().additional_limit.first_frame_charge(), + PoolAmounts::ZERO, + ); + match &mut frame.frame_input { + FrameInput::Call(inputs) => inputs.charged_start = charge, + FrameInput::Create(inputs) => inputs.set_charged_start(charge), + FrameInput::Empty => {} + } evm.ctx_mut().mark_beneficiary_delegate(); Ok(Some(frame)) } - /// Settles the outermost frame: pops its lane, then settles its gas into the transaction's as - /// op-revm does (op-revm replaces revm's settlement, so revm's never runs here): a transaction - /// whose own frame a limit stopped settles like an EIP-8037 revert, its unspent regular gas - /// and reservoir back to the sender. - /// Keeps the history gas the transaction spent: what the body was charged, and what the frames - /// charged net of what they gave back; and the history bytes it appended, which are what those - /// charges were made for. + /// Settles the outermost frame into the transaction's gas as op-revm does (op-revm replaces + /// revm's settlement, so revm's never runs here): a transaction whose own frame a limit stopped + /// settles like an EIP-8037 revert, its unspent regular gas and reservoir back to the sender. + /// + /// The write record the transaction's own frame makes was charged before execution and rides + /// on the frame's input as its start charge, which the settlement gives back when the frame + /// did not succeed, the way EIP-8037 gives back the state gas of the account that frame would + /// have created. A frame answered without returning through + /// [`frame_return_result`](EvmTr::frame_return_result) — revm's answer to the first frame, an + /// interceptor's, an inspector's — closes its start and gives up its stop here. + /// + /// Keeps the history gas the transaction spent, which its gas holds once the frame settled into + /// it: what the body was charged, and what the frames charged net of what they gave back; and + /// the history bytes it appended, which are what those charges were made for. fn last_frame_result( &mut self, evm: &mut Self::Evm, frame_result: &mut FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { - evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); + let layer = &mut evm.ctx_mut().additional_limit; + layer.close_start(0, frame_result.instruction_result().is_ok()); + layer.take_frame_stop(frame_result, true); self.op.last_frame_result(evm, frame_result, parent_gas)?; - // The write record the transaction's own frame makes was charged before execution; a - // frame that failed keeps no such write, so the charge goes back the way EIP-8037 gives - // back the state gas of the account that frame would have created. - let instruction_result = frame_result.instruction_result(); - if !instruction_result.is_ok() { - parent_gas.refill_history(evm.ctx_ref().additional_limit.top_level_write_record_gas()); - if instruction_result.is_halt() { - parent_gas.spend_all(); - } - *frame_result.gas_mut().tracker_mut() = *parent_gas; - } let priced = evm.ctx_ref().prices_history(); - let layer = &mut evm.ctx_mut().additional_limit; - let history = layer - .intrinsic_history_gas() - .saturating_add_signed(frame_result.gas().history_gas_spent()); - layer.set_history_gas_spent(history); - layer.settle_history_bytes(priced); + let history = 0_u64.saturating_add_signed(frame_result.gas().history_gas_spent()); + evm.ctx_mut().additional_limit.settle_history(priced, history); Ok(()) } - /// revm's post-execution, on the intrinsic gas with the body's history taken back out of the - /// state slot it rode in: the result's state gas is state gas alone, and the history the - /// transaction spent is reported on its own ledger. + /// revm's post-execution, with the reservoir the transaction leaves unspent read first, where + /// revm builds the result's gas: before the EIP-7623 floor check, which absorbs the reservoir + /// into the floor's cost when the floor binds. The refund before it does not move the + /// reservoir. fn post_execution( &self, evm: &mut Self::Evm, @@ -340,9 +401,7 @@ where init_and_floor_gas: InitialAndFloorGas, eip7702_gas_refund: i64, ) -> Result { - let history = evm.ctx_ref().additional_limit.intrinsic_history_gas(); - let init_and_floor_gas = init_and_floor_gas - .with_initial_state_gas(init_and_floor_gas.initial_state_gas_final() - history); + self.settled_reservoir.set(Some(exec_result.gas().reservoir())); self.op.post_execution(evm, exec_result, init_and_floor_gas, eip7702_gas_refund) } @@ -371,26 +430,54 @@ where self.op.reward_beneficiary(evm, exec_result) } + /// op-revm's result, and the reservoir it settled with reported + /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)). + /// + /// revm's system-call path settles without [`post_execution`](Handler::post_execution): the + /// result it hands over here is the settled one, and the capture it finds is none, since the + /// report of the execution before consumed it. A deposit that halts is not a result: op-revm + /// turns it into a failed deposit, which leaves no reservoir. fn execution_result( &mut self, evm: &mut Self::Evm, result: FrameResult, result_gas: revm::context::result::ResultGas, ) -> Result, Self::Error> { - self.op.execution_result(evm, result, result_gas) + let reservoir = self.settled_reservoir.take().unwrap_or_else(|| result.gas().reservoir()); + let result = self.op.execution_result(evm, result, result_gas)?; + evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); + Ok(result) } /// op-revm's error handling, which answers a deposit's transaction error with a failed-deposit /// halt and discards everything the deposit did. The halt is what the transaction reports; /// what the deposit counted stands, the body and the Oracle hints it forwarded before it /// halted, as for any transaction that halts. Any other error refuses the transaction, and the - /// layer's state is reset by the next one. + /// layer's state is reset by the next one. A reservoir captured for a result that is not + /// reported is dropped here, so the next execution on this handler does not report it. + /// + /// A failed deposit still bumps its caller's nonce and mints, so one whose caller had no + /// account creates it: one account of state growth, which the transaction reports and its + /// block counts, though it pays no state gas for it and no limit stops a deposit that already + /// failed. fn catch_error( &self, evm: &mut Self::Evm, error: Self::Error, ) -> Result, Self::Error> { - self.op.catch_error(evm, error) + self.settled_reservoir.take(); + let result = self.op.catch_error(evm, error); + let failed_deposit = matches!( + result, + Ok(revm::context::result::ExecutionResult::Halt { + reason: OpHaltReason::FailedDeposit, + .. + }) + ); + if failed_deposit && deposit_created_caller(evm.ctx()) { + evm.ctx_mut().additional_limit.count_created_caller(); + } + result } } @@ -405,8 +492,8 @@ where Frame = EthFrame, Inspector: Inspector, EthInterpreter>, >, - // Implied by `EvmTrError`, but the `ContextTr>` bound above stops - // the compiler from normalizing the context's database type down to `DB`. + // Implied by `EvmTrError`, but the `ContextTr>` bound above + // stops the compiler from normalizing the context's database type down to `DB`. ERROR: EvmTrError + From + From> @@ -444,48 +531,73 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - if let Some(result) = self.answered_before_building(&frame_init) { + // The frame on top of the stack, if any, is the caller, which suspends on this start. + if self.inner.frame_stack.index().is_some() { + suspend(&mut self.inner.ctx, self.inner.frame_stack.get(), &mut frame_init); + } + if let Some(result) = call_too_deep(&frame_init) { return Ok(ItemOrResult::Result(result)); } + if frame_init.depth == 0 { + if let Some(mut result) = stop_before_the_first_frame(&mut self.inner.ctx, &frame_init) + { + let gas_limit = input_gas_limit(&frame_init.frame_input); + settle_answer(&mut self.inner.ctx, 0, gas_limit, &mut result); + return Ok(ItemOrResult::Result(result)); + } + } let keyless = keyless::is_dispatched(&self.inner.ctx, &frame_init); let answer = if keyless { keyless::ready(&mut self.inner.ctx, &mut frame_init)? @@ -494,136 +606,185 @@ impl EvmTr for MegaEvm Ok(frame.interpreter.input.target_address), - ItemOrResult::Result(result) => Err(result), - } + if hold == PrecompileHold::Crossing { + // revm never decides the start: what it would have counted is held to the limits as + // the hypothetical the answer gives way to. A creation is never a precompile's. + let mut result = crossing_answer(&frame_init.frame_input); + let verdict = ctx.additional_limit.hypothetical_start(&start.counted, start.shares); + stop_the_answer_at(ctx, &start, &mut result, verdict); + settle_answer(ctx, depth, gas_limit, &mut result); + return Ok(ItemOrResult::Result(result)); + } + let decided = match self.inner.frame_init(frame_init)? { + ItemOrResult::Item(_) => None, + ItemOrResult::Result(result) => Some(result), }; let ctx = &mut self.inner.ctx; - #[cfg(debug_assertions)] - assert_start_as_counted(ctx, counted, outcome.as_ref().err()); - debug_assert!(!keyless || outcome.is_ok(), "revm builds a keylessDeploy call's frame"); - match outcome { - Ok(address) => { - ctx.additional_limit.set_frame_address(address); - if keyless { - ctx.keyless_frame = Some(keyless::KeylessFrame::Built); - } - Ok(ItemOrResult::Item(self.inner.frame_stack.get())) - } - Err(mut result) => { - if let PrecompileHold::Clamped(withheld) = hold { - Detention::restore_forward(result.interpreter_result_mut(), withheld); - } - let succeeded = result.instruction_result().is_ok(); - settle_answer(ctx, depth, gas_limit, &mut result); - match start { - Some(start) => take_back_a_stopped_answer(ctx, start, succeeded, &result), - None => debug_assert!( - !succeeded || result.instruction_result().is_ok(), - "an answer became the stop with no compute limit set" - ), + let Some(mut result) = decided else { + ctx.additional_limit.open_start(depth, start.creator); + let frame = self.inner.frame_stack.get(); + let gas = frame.interpreter.gas.tracker_mut(); + let verdict = ctx.additional_limit.count_start(gas, &start.counted, start.credit); + #[cfg(debug_assertions)] + start.assert_made(ctx); + ctx.detention.on_frame_run(&mut frame.interpreter.gas, depth); + let first = if verdict.exceeded_limit() { + Some(stop_action(ctx, frame, &verdict)) + } else if keyless { + Some(keyless::start(ctx, frame)?) + } else { + None + }; + match first { + Some(action @ InterpreterAction::Return(_)) => { + let result = end_before_it_runs(ctx, frame, action)?; + self.inner.frame_stack.pop(); + return Ok(ItemOrResult::Result(result)); } - Ok(ItemOrResult::Result(result)) + Some(action) => frame.interpreter.bytecode.set_action(action), + None => {} } + return Ok(ItemOrResult::Item(self.inner.frame_stack.get())); + }; + debug_assert!(!keyless, "revm builds a keylessDeploy call's frame"); + if let PrecompileHold::Clamped(withheld) = hold { + Detention::restore_forward(result.interpreter_result_mut(), withheld); } + let succeeded = result.instruction_result().is_ok(); + // A creation revm answers creates nothing: refused on its creator's account, it bumped + // nothing; failed onto an occupied address, it is held to nothing at its start, and its + // failure takes its records and transfer log back. Its creator's record, if revm bumped the + // nonce, is counted on the creator as the answer returns, as a built creation's is. + ctx.additional_limit.open_start(depth, start.creator); + if let FrameResult::Call(_) = result { + let verdict = if succeeded { + let gas = result.gas_mut().tracker_mut(); + ctx.additional_limit.count_start(gas, &start.counted, start.credit) + } else { + ctx.additional_limit.hypothetical_start(&start.counted, start.shares) + }; + stop_the_answer_at(ctx, &start, &mut result, verdict); + } + settle_answer(ctx, depth, gas_limit, &mut result); + take_back_a_stopped_answer(ctx, start.mark, succeeded, &result); + Ok(ItemOrResult::Result(result)) } - /// Runs the frame on top of the stack, unless it has a stop to return: its own, when what a - /// child left it put it over a limit. Then the frame returns the stop without running another - /// instruction (see [`before_frame_run`]). A `keylessDeploy` call's - /// frame runs no instruction at all: its actions are made by hand ([`keyless::run`]). - /// - /// Gas detention holds the frame to the compute limit before it runs, and settles the frame - /// once it suspends on a child or returns (see [`after_frame_run`]). + /// revm's frame run. The actions the engine makes for a frame outside an instruction — the + /// creation a `keylessDeploy` call starts and the call's answer ([`EvmTr::frame_init`], + /// [`EvmTr::frame_return_result`]), and the stop of a frame a child returned into over a limit + /// ([`EvmTr::frame_return_result`]) — are set on the frame's interpreter, and revm's run, plain + /// or inspected, returns an action set before it runs without running an instruction or calling + /// the inspector's `step`. #[inline] fn frame_run( &mut self, ) -> Result, ContextDbError> { - let evm = &mut self.inner; - let frame = evm.frame_stack.get(); - let ctx = &mut evm.ctx; - let action = match before_frame_run(ctx, frame) { - Some(action) => action, - None if keyless::runs(ctx, frame) => keyless::run(ctx, frame)?, - None => frame.interpreter.run_plain( - evm.instruction.instruction_table(), - evm.instruction.gas_table(), - ctx, - ), - }; - let mut next = frame.process_next_action(ctx, action); - after_frame_run(ctx, frame, &mut next); - next.inspect(|next| { - if next.is_result() { - frame.set_finished(true); - } - }) + self.inner.frame_run() + } + + /// Classifies the result of the frame on top of the stack, which ran and returns, for gas + /// detention ([`end_frame`]). revm's loops, plain and inspected, hand it here once the frame's + /// last action was processed — `return_create` included — and before anything else sees it: + /// the inspector's `call_end`, `create_end` and `frame_end`, then + /// [`frame_return_result`](EvmTr::frame_return_result) and the caller or, for the transaction's + /// own frame, [`last_frame_result`](Handler::last_frame_result). So a frame that crossed the + /// compute limit ends with the stop for all of them, an inspector included. + /// + /// A result [`frame_init`](EvmTr::frame_init) returns does not come here: a frame that ends + /// before it runs is classified where it ends ([`end_before_it_runs`]), and an answer is held + /// to the limit by [`settle_answer`]. + #[inline] + fn frame_run_result( + &mut self, + result: &mut FrameResult, + ) -> Result<(), ContextDbError> { + let depth = self.inner.frame_stack.get().depth; + end_frame(&mut self.inner.ctx, result, depth); + Ok(()) } - /// Pops the returning frame's lane (merged on success, discarded on failure), then returns the - /// result to the caller as revm does. + /// Returns the result to the caller as revm does, in this order: + /// + /// 1. its start is closed: a frame that kept nothing has what the transaction keeps restored to + /// what it kept when its start began, and one that kept its start gives its caller back what + /// the start's credit is ([`close_start`](crate::AdditionalLimit)), refilled on the result + /// before revm merges it, which lands in the caller's pools as a refill after the merge + /// would; + /// 2. revm merges the result into the caller; a creation's creator is then counted the record + /// of the nonce revm bumped for it, held to its budget and then to the transaction's limit + /// ([`hold_creator`]), the caller is held to the transaction's limits with what the frames + /// keep after the return — a failure restores what they kept at its start, which a hint sent + /// meanwhile may leave above a limit + /// ([`AdditionalLimit::hold_caller`](crate::AdditionalLimit)) — and, by gas detention, to + /// the compute limit for its resume ([`on_frame_run`](Detention::on_frame_run)): a caller + /// over a limit returns the stop without running another instruction, set on its interpreter + /// for its run to return. /// /// The creation a `keylessDeploy` call started returns into the call: what the call answers is - /// read off the creation's result before revm merges it ([`keyless::returning`]), and settled - /// into the call after ([`keyless::settle`]). + /// read off the creation's result before revm merges it ([`keyless::returning`]), settled into + /// the call after, the signer's nonce record counted there ([`keyless::settle`]), and set on + /// the call's interpreter, unless it has a stop to return ([`keyless::answer`]). + /// + /// A frame that ran was classified when its run returned + /// ([`frame_run_result`](EvmTr::frame_run_result)); what arrives here is the result the caller + /// settles, an inspector's rewrite included, which is taken as given. #[inline] fn frame_return_result( &mut self, - result: FrameResult, + mut result: FrameResult, ) -> Result, ContextDbError> { - let refund = self.inner.ctx.additional_limit.on_frame_return(&result); + let stack = &mut self.inner.frame_stack; + let (depth, outermost) = match stack.index() { + Some(index) if stack.get().is_finished() => (stack.get().depth, index == 0), + Some(_) => (stack.get().depth + 1, false), + None => (0, true), + }; + let layer = &mut self.inner.ctx.additional_limit; + let (credit, creator) = layer.close_start(depth, result.instruction_result().is_ok()); + if credit != 0 { + result.gas_mut().refill_history(credit); + } + layer.take_frame_stop(&result, outermost); let creation = keyless::returning(&self.inner.ctx, &mut self.inner.frame_stack, &result); let returned = self.inner.frame_return_result(result)?; - // The history of the records the caller paid for and the frame did not keep, given back - // after the merge that adopted the frame's pools. `Some` means the outermost frame - // returned, whose caller is the transaction: it paid for no record of it. if returned.is_some() { - debug_assert_eq!(refund, 0, "the outermost frame's caller is the transaction"); return Ok(returned); } - let caller = &mut self.inner.frame_stack.get().interpreter.gas; - caller.refill_history(refund); - if let Some(creation) = creation { - keyless::settle(&mut self.inner.ctx, caller, creation)?; - } - Ok(returned) + let ctx = &mut self.inner.ctx; + let caller = self.inner.frame_stack.get(); + let (stop, deployment) = match creation { + Some(creation) => { + let gas = &mut caller.interpreter.gas; + let (deployment, stop) = keyless::settle(ctx, gas, creation, creator)?; + (stop, Some(deployment)) + } + None => { + let bumped = creator.filter(|creator| ctx.accounts().bumped(creator)); + let gas = caller.interpreter.gas.tracker_mut(); + (bumped.and_then(|creator| hold_creator(ctx, gas, &creator)), None) + } + }; + let stop = stop.or_else(|| ctx.additional_limit.hold_caller()); + ctx.detention.on_frame_run(&mut caller.interpreter.gas, caller.depth); + let action = match (stop, deployment) { + (Some(stop), _) => stop_action(ctx, caller, &stop), + (None, Some(deployment)) => keyless::answer(ctx, &deployment, caller.interpreter.gas), + (None, None) => return Ok(None), + }; + caller.interpreter.bytecode.set_action(action); + Ok(None) } } @@ -668,178 +829,151 @@ where &mut evm.inspector, ) } +} - /// revm's inspected frame start, with the lanes kept aligned: a frame the inspector answers - /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it, and its - /// answer settles as a frame that never started ([`answered_by_inspector`]). - /// - /// A frame nothing may start, one past the call-stack limit, is answered by - /// [`EvmTr::frame_init`], after the inspector's `frame_start`, as every frame revm does not - /// build is, and the inspector is told it ended. - /// - /// A keyless deployment is seen as the frames it is made of: the transaction's `keylessDeploy` - /// call, and the creation it starts, one journal depth below it, as its child. The call's - /// frame runs no code, so the inspector is not told an interpreter was initialized for it. - #[inline] - fn inspect_frame_init( - &mut self, - mut frame_init: FrameInit, - ) -> Result, ContextDbError> { - // An inspector may have rewritten the input the opcode left pending, or rewrite it at the - // frame's start: the caller's answer is asked again on the input it leaves. - let _ = self.inner.ctx.additional_limit.take_start_refused(); - let (ctx, inspector) = self.ctx_inspector(); - // What the calling opcode charged upfront, before the inspector's hooks can rewrite the - // call it charged for. - let upfront = UpfrontRecord::of(&frame_init.frame_input); - if let Some(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - let output = answered_by_inspector(ctx, inspector, &frame_init, output, upfront); - return Ok(ItemOrResult::Result(output)); - } - let (frame_input, depth) = (frame_init.frame_input.clone(), frame_init.depth); - // What the start journals begins here. A start answered with a success without a frame - // is revm's — a call to a precompile or to an account with no code, which takes its - // checkpoint before it journals anything — or an interceptor's, which journals nothing. - let start = journal_position(ctx); - let logs_i = start.log_i; - if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { - let (ctx, inspector) = self.ctx_inspector(); - // Logs the frame journaled without running: the EIP-7708 transfer log, and the logs - // of a precompile. - if ctx.journal().logs().len() != logs_i { - inspect_logs(ctx, inspector, logs_i); - } - // Custom precompiles gather their logs outside the journal. - if let FrameResult::Call(outcome) = &output { - if outcome.was_precompile_called { - for log in outcome.precompile_call_logs.clone() { - inspector.log(ctx, log); - } - } - } - let source = ResultSource::Engine(start); - frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, source, upfront); - return Ok(ItemOrResult::Result(output)); - } - let (ctx, inspector, frame) = self.ctx_inspector_frame(); - ctx.upfront_records.resize(depth, None); - ctx.upfront_records.push(upfront); - if ctx.journal().logs().len() != logs_i { - inspect_logs(ctx, inspector, logs_i); - } - if !keyless::runs(ctx, frame) { - inspector.initialize_interp(&mut frame.interpreter, ctx); - } - Ok(ItemOrResult::Item(frame)) - } +/// Settles `caller`, the frame on top of the stack, which suspends to start `child`: gas detention +/// keeps its compute for the child's start to add to the transaction's, with the stipend revm +/// gives a value call's child, which the caller did not forward +/// ([`on_frame_suspend`](Detention::on_frame_suspend)), and the share of its pool the child starts +/// with is held to the frame cap ([`cap_the_shares`]). +/// +/// It runs where the start reaches [`EvmTr::frame_init`]: under an inspector, after the +/// inspector's `frame_start` saw the start. A start the inspector answers itself settles nothing: +/// the caller resumes on the answer as its opcode left it. +#[inline] +fn suspend( + ctx: &mut MegaContext, + caller: &mut EthFrame, + child: &mut FrameInit, +) { + let stipend = value_call_stipend(&child.frame_input, ctx.gas_params().call_stipend()); + ctx.detention.on_frame_suspend(&caller.interpreter.gas, caller.depth, stipend); + let caps = ctx.additional_limit.frame_caps(); + cap_the_shares(ctx.gas_params(), caps, &mut caller.interpreter.gas, child); +} - /// revm's inspected frame run, with the stop short-circuit of [`EvmTr::frame_run`]: a frame - /// with a stop to return returns it without a step, and the inspector sees it end. A - /// `keylessDeploy` call's frame makes its actions by hand, as on the plain path, with no step. - /// - /// The step callbacks run through [`StepGuard`], so a charge the inspector makes on the - /// interpreter's gas and the frame cannot pay does not classify the frame's end. - #[inline] - fn inspect_frame_run( - &mut self, - ) -> Result, ContextDbError> { - let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); - let action = match before_frame_run(ctx, frame) { - Some(action) => action, - None if keyless::runs(ctx, frame) => keyless::run(ctx, frame)?, - None => inspect_instructions( - ctx, - &mut frame.interpreter, - StepGuard(&mut *inspector), - instructions.instruction_table(), - instructions.gas_table(), - ), - }; - let mut next = frame.process_next_action(ctx, action); - after_frame_run(ctx, frame, &mut next); - if let Ok(ItemOrResult::Result(result)) = &mut next { - let source = ResultSource::Engine(frame.checkpoint); - let upfront = ctx.upfront_records.get(frame.depth).copied().flatten(); - frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, source, upfront); - frame.set_finished(true); - } - next - } +/// The action of `frame` that stops it at the limit `verdict` names before it runs another +/// instruction: a revert carrying `MegaLimitExceeded` on the gas the frame holds. A frame revm just +/// built whose start crossed the limit returns it before its first instruction: its journal +/// checkpoint takes back what the start moved and its transfer log, and a creation keeps its +/// creator's nonce bump, which revm makes before the checkpoint, its record counted on the creator +/// once the creation returned. A creator that record put over a limit returns it on its resume. +#[cold] +#[inline(never)] +fn stop_action( + ctx: &mut MegaContext, + frame: &EthFrame, + verdict: &LimitCheck, +) -> InterpreterAction { + let output = ctx.additional_limit.note_frame_stop(verdict); + InterpreterAction::new_return(InstructionResult::Revert, output, frame.interpreter.gas) } -/// The action of a frame about to run: the stop it returns without running an instruction, when -/// it has one ([`stop_before_run`](crate::AdditionalLimit::stop_before_run)); `None` otherwise, -/// and the frame runs. -/// -/// A frame runs here for the first time or after a child returned into it. A stop is always the -/// latter: the child was a failed creation whose nonce record, which lands on its creator, put the -/// creator over a limit, its budget or the transaction's, and the creator reverts alone, as for a -/// write of its own. A child that crossed a limit itself reverted alone, and its caller resumes. +/// Ends `frame`, which revm just built, with `action`, the return made for it before it runs an +/// instruction — the stop its start crossed, or a `keylessDeploy` call's refusal — as revm's +/// frame run ends a frame that returns: revm settles the frame's journal checkpoint and builds its +/// result, which gas detention then classifies ([`end_frame`]). /// -/// Either way gas detention sees the frame first: a frame's first run adds its caller's compute -/// to the transaction's, a resume takes it back, and the frame's spendable gas is held to what the -/// compute limit leaves it — which is how a child's read of volatile data caps every caller it -/// returns into. -#[inline] -fn before_frame_run( +/// The frame never ran an instruction, so it is returned as an answer is, off the stack: its +/// caller resumes on it, and an inspector sees it start and end, and neither an interpreter nor +/// what its start journaled when the return reverts it. +#[cold] +#[inline(never)] +fn end_before_it_runs( ctx: &mut MegaContext, frame: &mut EthFrame, -) -> Option { - ctx.detention.on_frame_run(&mut frame.interpreter.gas, frame.depth); - let stop = ctx.additional_limit.stop_before_run()?; - Some(InterpreterAction::new_return( - InstructionResult::Revert, - ctx.additional_limit.note_frame_stop(&stop), - frame.interpreter.gas, - )) + action: InterpreterAction, +) -> Result>> { + let next = + frame.process_next_action::<_, ContextDbError>>(ctx, action); + let ItemOrResult::Result(mut result) = next? else { + unreachable!("a frame that returns has a result") + }; + end_frame(ctx, &mut result, frame.depth); + Ok(result) } -/// Settles gas detention once the frame ran: a frame that suspends on a child keeps its compute -/// for the child's start to add to the transaction's; a frame that returns is classified. -/// -/// The frame's result is read here, after revm processed its last action — `return_create` -/// included, whose deposit and hash charges are the creating frame's own compute — and before -/// revm hands it to the caller or, for the transaction's own frame, to -/// [`last_frame_result`](Handler::last_frame_result), which overwrites its gas with the -/// transaction's. +/// Classifies `result`, the result of a frame at `depth` that ran, for gas detention, once revm +/// processed the frame's last action — `return_create` included, whose deposit and hash charges +/// are the creating frame's own compute. /// /// A frame that ran out of gas on a charge the withheld part of its gas would have paid crossed /// the compute limit rather than its own gas: its halt becomes the compute stop, a revert of that /// frame alone ([`stop_at_the_compute_limit`]). Every other out-of-gas halts, as it would without /// the read. #[inline] -fn after_frame_run( +fn end_frame( ctx: &mut MegaContext, - frame: &EthFrame, - next: &mut Result>, E>, + result: &mut FrameResult, + depth: usize, ) { - match next { - Ok(ItemOrResult::Item(_)) => { - ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth); - } - Ok(ItemOrResult::Result(result)) => { - let instruction_result = result.instruction_result(); - if let Some(stop) = - ctx.detention.on_frame_end(instruction_result, result.gas_mut(), frame.depth) - { - stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), stop); - } - } - Err(_) => {} + let instruction_result = result.instruction_result(); + if let Some(stop) = ctx.detention.on_frame_end(instruction_result, result.gas_mut(), depth) { + stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), stop); } } -/// Records, for gas detention, the frame revm is about to build a child of at `depth`, while no -/// read has set a limit ([`Detention::on_child_build`]): the caller is still on top of the stack. -#[inline] -fn record_caller( +/// Counts on a creator whose pools `gas` holds, once a creation it started returned into it, what +/// the nonce bump revm made for the creation made of it ([`Accounts::creator_counted`]) — `before` +/// is the creator as it stood before revm decided the creation — and answers the stop the creator +/// returns before it runs on, if the count crossed a limit: the record is held to the creator's +/// budget, then to the transaction's limit, as any count the creator makes +/// ([`draw`](crate::AdditionalLimit)). The creation's budget was taken before the record, at its +/// opcode, so the record is the creator's alone, and it is counted whether the creation succeeded +/// or not, since the bump outlives it. +/// +/// [`Accounts::creator_counted`]: crate::limit::Accounts +pub(crate) fn hold_creator( ctx: &mut MegaContext, - frame_stack: &mut FrameStack>, - depth: usize, -) { - if depth > 0 && ctx.detention.records_callers() { - debug_assert_eq!(frame_stack.index(), Some(depth - 1), "the caller is on top"); - ctx.detention.on_child_build(depth, &frame_stack.get().interpreter.gas); + gas: &mut GasTracker, + before: &CreatorBefore, +) -> Option { + let counted = ctx.accounts().creator_counted(before); + let check = ctx.additional_limit.draw(gas, &counted); + check.exceeded_limit().then_some(check) +} + +/// Holds the share of each of its caller's pools the frame `child` starts with to the share of what +/// the caller has left, its remaining clamped to its budget, and to that pool's frame cap in +/// `caps`, and gives what it forwarded above that back to the caller, whose pools `caller` holds. +/// +/// A frame's remaining is `min(budget, max(0, budget − net))`: a frame whose net is negative — it +/// took back a record or removed state a frame above it made — holds more in its pool than the +/// budget it was given, and the share it forwards is of that budget, not of the pool, so a negative +/// net never enlarges a child's budget. The fork forwarded the schedule's share of the pool the +/// opcode found ([`GasParams::pool_forward_share`]); the caller had that pool and the share +/// together, and its budget is that less its net draw. +#[inline] +fn cap_the_shares(params: &GasParams, caps: PoolAmounts, caller: &mut Gas, child: &mut FrameInit) { + let mut shares = match &child.frame_input { + FrameInput::Call(inputs) => inputs.pool_shares, + FrameInput::Create(inputs) => inputs.pool_shares(), + FrameInput::Empty => return, + }; + let mut capped = false; + for pool in PoolId::ALL { + let share = shares.get(pool); + let mut allowed = caps.get(pool); + let spent = caller.pool_spent(pool); + if spent < 0 { + let had = caller.pool_remaining(pool).saturating_add(share); + let budget = had.saturating_add_signed(spent); + allowed = allowed.min(params.pool_forward_share(pool, budget)); + } + let Some(excess) = share.checked_sub(allowed).filter(|excess| *excess != 0) else { + continue; + }; + caller.set_pool_remaining(pool, caller.pool_remaining(pool).saturating_add(excess)); + shares.set(pool, allowed); + capped = true; + } + if !capped { + return; + } + match &mut child.frame_input { + FrameInput::Call(inputs) => inputs.pool_shares = shares, + FrameInput::Create(inputs) => inputs.set_pool_shares(shares), + FrameInput::Empty => {} } } @@ -895,7 +1029,9 @@ enum PrecompileHold { /// The price does not tell whether the input passes the checks a precompile makes after its gas /// check, so an input priced past the allowance and within the forward is the stop even when /// those checks would fail the call. A call revm refuses on its caller's account — a value it -/// cannot fund — runs no precompile, and revm answers it as without the limit. +/// cannot fund — runs no precompile, and revm answers it as without the limit: the answer given +/// without running is not given in its place, which a comparison of the caller's balance with the +/// value decides, as revm's transfer does. /// /// A precompile the engine cannot price is run on the allowance and sees it as its gas limit /// ([`Clamped`](PrecompileHold::Clamped), with what was taken off the forward); its answer gets the @@ -907,12 +1043,11 @@ fn hold_precompile( precompiles: &PrecompilesMap, priced: &PricedPrecompiles, frame_init: &mut FrameInit, - refused: bool, ) -> PrecompileHold { if ctx.detention.compute_limit().is_none() { return PrecompileHold::Unheld; } - hold_detained_precompile(ctx, precompiles, priced, frame_init, refused) + hold_detained_precompile(ctx, precompiles, priced, frame_init) } /// [`hold_precompile`] once a read set a compute limit. @@ -922,7 +1057,6 @@ fn hold_detained_precompile( precompiles: &PrecompilesMap, priced: &PricedPrecompiles, frame_init: &mut FrameInit, - refused: bool, ) -> PrecompileHold { let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return PrecompileHold::Unheld; @@ -941,7 +1075,16 @@ fn hold_detained_precompile( inputs.gas_limit = allowance; return PrecompileHold::Clamped(withheld); }; - if price <= allowance || price > inputs.gas_limit || refused { + if price <= allowance || price > inputs.gas_limit { + return PrecompileHold::Unheld; + } + let caller = ctx.journal_ref().state.get(&inputs.caller); + let unfunded = inputs + .value + .transfer() + .zip(caller) + .is_some_and(|(value, caller)| caller.info.balance < value); + if unfunded { return PrecompileHold::Unheld; } PrecompileHold::Crossing @@ -959,7 +1102,7 @@ fn crossing_answer(input: &FrameInput) -> FrameResult { } /// The gas limit of the frame `input` starts. -const fn input_gas_limit(input: &FrameInput) -> u64 { +pub(crate) const fn input_gas_limit(input: &FrameInput) -> u64 { match input { FrameInput::Call(inputs) => inputs.gas_limit, FrameInput::Create(inputs) => inputs.gas_limit(), @@ -967,6 +1110,15 @@ const fn input_gas_limit(input: &FrameInput) -> u64 { } } +/// The stipend revm adds to the gas limit of the frame `input` starts, `call_stipend` for a call +/// that transfers value and nothing for any other: gas the caller never paid. +pub(crate) fn value_call_stipend(input: &FrameInput, call_stipend: u64) -> u64 { + match input { + FrameInput::Call(inputs) if inputs.transfers_value() => call_stipend, + _ => 0, + } +} + /// Turns a frame that crossed gas detention's compute limit into the compute stop: a revert of /// that frame alone carrying `MegaLimitExceeded` (kind: compute). The frame's gas is what it had /// before the charge that crossed, which goes back with the revert to its caller. The caller @@ -974,7 +1126,8 @@ const fn input_gas_limit(input: &FrameInput) -> u64 { /// crossed, so a caller that carries on is stopped at its next charge past it. /// /// The crossing charge's size is not kept, so the stop reports the transaction's compute at the -/// crossing as what was used ([`LimitCheck::ExceedsLimit`]): what its regular ledger bills. +/// crossing as what was used ([`LimitCheck::ExceedsLimit`]): what its regular ledger bills, and +/// the stipends of its value calls on top. fn stop_at_the_compute_limit( ctx: &mut MegaContext, result: &mut InterpreterResult, @@ -1010,18 +1163,21 @@ impl MegaEvm { }; crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth, caller_remaining) } +} - /// Step 1 of [`EvmTr::frame_init`], the pre-frame check: answers a frame nothing may start, one - /// past the call-stack limit ([`call_too_deep`]), with the empty lane that stands in for it. On - /// the inspected path it comes after the inspector's `frame_start`. - #[inline] - fn answered_before_building(&mut self, frame_init: &FrameInit) -> Option { - let answer = call_too_deep(frame_init); - if answer.is_some() { - self.inner.ctx.additional_limit.push_empty_frame(); - } - answer - } +/// Marks where `journal` stands, without changing its depth: a checkpoint opened and committed at +/// once, which [`revert_to`] takes the journal back to. +pub(crate) fn mark(journal: &mut Journal) -> JournalCheckpoint { + let position = journal.checkpoint(); + journal.checkpoint_commit(); + position +} + +/// Takes back every journal entry, log and self-destruct made since `mark`, as revm takes back a +/// frame that fails; the journal's depth is left as it is. +pub(crate) fn revert_to(journal: &mut Journal, mark: JournalCheckpoint) { + let _ = journal.checkpoint(); + journal.checkpoint_revert(mark); } /// Takes the journal back to `start`, where a frame's start began, when revm answered the frame @@ -1040,53 +1196,349 @@ fn take_back_a_stopped_answer( result: &FrameResult, ) { if succeeded && !result.instruction_result().is_ok() { - revert_journal_to(ctx, start); + revert_to(ctx.journal_mut(), start); + } +} + +/// What holding a frame's start to the limits needs of it once revm consumed its input: where the +/// start began, what it counts and what a stop answering it carries. +struct FrameStart { + /// Where the journal stood before revm decided the start: what revm journals for it — a + /// creator's nonce bump, the value the start moves and its transfer log, a precompile's + /// writes — comes after. + mark: JournalCheckpoint, + /// The records and transfer log the start makes on its frame, read off the journal before + /// revm decides it. + counted: Counted, + /// What the start's caller gets back once the frame returned with its start kept: what it + /// paid for the records on the frame, less the price of those the start makes, and the price + /// of those it takes back. + credit: u64, + /// The gas limit the frame's caller forwarded, before gas detention held a precompile to less. + gas_limit: u64, + /// The reservoir the frame inherits. + reservoir: u64, + /// The shares of its caller's pools the frame starts with: its budgets. + shares: PoolAmounts, + /// For a creation a frame makes, its creator as it stands before revm decides the start, which + /// tells once the creation returned what revm's nonce bump made of it. The transaction's own + /// creation has none: its sender's account is the transaction body's. + creator: Option, + /// The records the start makes, for a debug build to hold what revm then made to. + #[cfg(debug_assertions)] + made: MadeRecords, +} + +impl FrameStart { + /// The start of the frame `frame_init` asks for, about to be decided by revm: where the + /// journal stands, the records it makes on its frame as the journal's state stands + /// ([`Accounts::start_records`](crate::limit::Accounts)), and a creation's creator. A + /// creation's creator record is not among the records: it is the creator's, counted from the + /// bump once the creation returned. + fn of( + ctx: &mut MegaContext, + frame_init: &FrameInit, + ) -> Result> { + // A creation's creator and address are loaded before revm decides the start, as revm + // loads them itself, outside the creation's checkpoint, once it decides it: the creator + // first thing, the address once the creator funds the endowment and its nonce bumps. The + // `CREATE` opcode loaded the address already unless EIP-8037 is off, and the creator is + // the frame that runs it, so only an inspector's rewrite, or EIP-8037 off, makes a load + // here that revm would not have made yet; neither changes what revm decides. An address an + // earlier transaction on the same journal left there is not loaded until it is again. + let mut creator = None; + if let FrameInput::Create(inputs) = &frame_init.frame_input { + let info = &ctx.journal_mut().load_account(inputs.caller())?.data.info; + let bumps = info.balance >= inputs.value() && info.nonce != u64::MAX; + let created = inputs.created_address(info.nonce); + if bumps && !ctx.accounts().is_loaded(created) { + ctx.journal_mut().load_account(created)?; + } + if frame_init.depth > 0 { + creator = Some(ctx.accounts().creator_before(inputs.caller())); + } + } + let accounts = ctx.accounts(); + let (records, growth, charged, reservoir, shares) = match &frame_init.frame_input { + FrameInput::Call(inputs) => { + let value = inputs.value.transfer().unwrap_or_default(); + ( + accounts.transfer_records(inputs.caller, inputs.target_address, value), + accounts.transfer_growth(inputs.caller, inputs.target_address, value), + inputs.charged_start.history, + inputs.reservoir, + inputs.pool_shares, + ) + } + FrameInput::Create(inputs) => { + let created = inputs.created_address(account_nonce(ctx, inputs.caller())); + ( + accounts.creation_records(inputs.caller(), Some(created), inputs.value()), + accounts.creation_growth(inputs.caller(), created, inputs.value()), + inputs.charged_start().history, + inputs.reservoir(), + inputs.pool_shares(), + ) + } + FrameInput::Empty => unreachable!( + "a frame input always names a call or a creation, as revm's frame init asserts" + ), + }; + let on_frame = records.on_frame(); + let credit = if ctx.prices_history() { + let price = |records| write_record_history_gas(records).unwrap_or(0); + charged.saturating_sub(price(on_frame.added)).saturating_add(price(on_frame.taken)) + } else { + 0 + }; + #[cfg(debug_assertions)] + let made = MadeRecords::before(ctx, frame_init, records); + Ok(Self { + mark: mark(ctx.journal_mut()), + counted: records.counted().with_growth(growth, 0), + credit, + gas_limit: input_gas_limit(&frame_init.frame_input), + reservoir, + shares, + creator, + #[cfg(debug_assertions)] + made, + }) + } + + /// Asserts revm's start made the records counted for it, read off the journal once revm built + /// the frame. + #[cfg(debug_assertions)] + fn assert_made(&self, ctx: &MegaContext) { + self.made.assert_after(ctx); + } +} + +/// The accounts a start makes its records of on its frame and whether the transaction had changed +/// each before it, for a debug build to hold the records the start counted to what revm's start +/// made of them. +#[cfg(debug_assertions)] +#[derive(Debug)] +struct MadeRecords { + /// The records predicted. + records: StartRecords, + /// The accounts, each with whether it was changed before the start. + accounts: MadeOn, +} + +/// The accounts a start makes its records of on its frame. +#[cfg(debug_assertions)] +#[derive(Debug)] +enum MadeOn { + /// A call's sender and recipient. + Call([(Address, bool); 2]), + /// A creation's created account. Its creator's record is the creator's, read off the journal + /// once the creation returned. + Creation((Address, bool)), +} + +#[cfg(debug_assertions)] +impl MadeRecords { + /// The accounts the start `frame_init` asks for writes, read before revm decides it, and the + /// `records` predicted for it. + fn before( + ctx: &MegaContext, + frame_init: &FrameInit, + records: StartRecords, + ) -> Self { + let journal = ctx.accounts(); + let read = |address: Address| (address, journal.is_changed(address)); + let accounts = match &frame_init.frame_input { + FrameInput::Call(inputs) => { + MadeOn::Call([read(inputs.caller), read(inputs.target_address)]) + } + FrameInput::Create(inputs) => { + let nonce = account_nonce(ctx, inputs.caller()); + MadeOn::Creation(read(inputs.created_address(nonce))) + } + FrameInput::Empty => MadeOn::Call([read(Address::ZERO); 2]), + }; + Self { records, accounts } + } + + /// Asserts the frame revm built made the records predicted: a call's two sides changed and + /// returned as its transfer's records say, a creation's created account as its record says. + fn assert_after( + &self, + ctx: &MegaContext, + ) { + use crate::limit::RecordDelta; + let accounts = ctx.accounts(); + let made = |(address, before): (Address, bool)| { + RecordDelta::of_account(before, accounts.is_changed(address)) + }; + match self.accounts { + MadeOn::Call([first, second]) => { + let made = if first.0 == second.0 { + RecordDelta::NONE + } else { + made(first).with(made(second)) + }; + debug_assert_eq!(made, self.records.transfer, "a call's start made its records"); + } + MadeOn::Creation(created) => { + let record = RecordDelta::of_account(false, self.records.created); + debug_assert_eq!( + made(created), + record, + "a creation made its created account's record" + ); + } + } + } +} + +/// The nonce of an account the journal holds; zero for one it does not. +fn account_nonce( + ctx: &MegaContext, + address: Address, +) -> u64 { + ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// Holds `answer`, revm's or gas detention's answer to the call `start` began, to `verdict`: a +/// crossing is the stop the answer gives way to, on the gas its caller forwarded, untouched, as a +/// frame stopped before it ran ([`stop_the_answer`]). What a successful answer's start moved is +/// taken back with it ([`take_back_a_stopped_answer`]); a failed one's revm took back itself. +fn stop_the_answer_at( + ctx: &mut MegaContext, + start: &FrameStart, + answer: &mut FrameResult, + verdict: LimitCheck, +) { + if verdict.exceeded_limit() { + let output = ctx.additional_limit.note_frame_stop(&verdict); + stop_the_answer(answer, start, output); } } -/// Settles `output`, the answer an inspector gave the frame `frame_init` starts in its place, as -/// [`EvmTr::frame_init`] settles an answer: the depth guard still holds, so an answer cannot reach -/// past the call-stack limit; an empty lane stands in for the frame, and the answer is held to the -/// compute limit ([`settle_answer`]). Then the inspector is told the frame ended, and the answer -/// settles as a frame that kept nothing: the frame never started, so no value moved and no account -/// was added, and the upfront state gas its caller's opcode was charged comes back whatever the -/// answer ([`frame_end_checked`]). -fn answered_by_inspector( +/// Rewrites `answer`, to the call `start` began, into the stop `output`: a revert on the gas the +/// call's caller forwarded, untouched, with the reservoir and the pools the call inherited, and no +/// precompile output, as [`synthetic_frame_result`] answers a frame that never started. +#[cold] +#[inline(never)] +fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) { + let FrameResult::Call(outcome) = answer else { + unreachable!("only a call is held to the limits once revm answered it") + }; + let mut gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); + gas.tracker_mut().set_pools_remaining(start.shares); + let allowance = outcome.result.gas.history_allowance(); + gas.set_history_allowance(allowance); + outcome.result = InterpreterResult::new(InstructionResult::Revert, output, gas); + outcome.was_precompile_called = false; + outcome.precompile_call_logs.clear(); +} + +/// The answer to the transaction's own frame `frame_init` when its authorization list was skipped +/// for a limit ([`AdditionalLimit::skip_authorization_list`](crate::AdditionalLimit)): the stop, +/// before the frame runs and before revm moves anything for it, on the gas its input carries, with +/// the reservoir and the start charge, which the first frame's settlement gives back. +fn stop_before_the_first_frame( ctx: &mut MegaContext, - inspector: &mut INSP, frame_init: &FrameInit, - output: FrameResult, - upfront: Option, -) -> FrameResult -where - INSP: Inspector, EthInterpreter>, -{ - let mut output = call_too_deep(frame_init).unwrap_or(output); - ctx.additional_limit.push_empty_frame(); - let gas_limit = input_gas_limit(&frame_init.frame_input); - settle_answer(ctx, frame_init.depth, gas_limit, &mut output); - let (input, depth) = (&frame_init.frame_input, frame_init.depth); - frame_end_checked(ctx, inspector, input, &mut output, depth, ResultSource::Inspector, upfront); - output +) -> Option { + let stop = ctx.additional_limit.take_pre_frame_stop()?; + let output = ctx.additional_limit.note_frame_stop(&stop); + Some(synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, output)) } -/// Answers a frame a limit stops before it is built with the stop: a revert with the stop's -/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) output, as a [`synthetic_frame_result`] that -/// settles like a frame revm ran. +/// Decides the transaction's EIP-7702 authorization list before it is applied, as the spec has +/// it: the whole list is simulated in order — each entry with a chain id that is neither zero nor +/// the chain's, a nonce of `2^64 − 1` or a signature that recovers no authority skipped unread; +/// every other authority loaded once, with its code, and skipped when that code is not a +/// delegation; a nonce compared with the authority's effective one, which the simulation bumps +/// for each entry it accepts — and the totals it would keep are held to the transaction's KV and +/// state-growth limits. The stop when they cross one, KV updates first; `None` when they fit, or +/// when the list is too short to cross either. /// -/// A creation still bumps its creator's nonce, as one that starts and reverts does: a nested -/// creation's caller sees an ordinary failed creation, and a creation transaction whose own frame -/// is stopped at its start cannot be replayed. -fn stop_before_building( +/// The simulation writes nothing and warms nothing: the loads are taken back to a journal mark, +/// which leaves the accounts in the transaction's state, cold, so a stateless witness holds every +/// authority the simulation read. A database error reading one is the transaction's error. +fn hold_authorization_list( ctx: &mut MegaContext, - frame_init: &FrameInit, - check: &LimitCheck, -) -> Result>> { - if let FrameInput::Create(inputs) = &frame_init.frame_input { - let _ = ctx.journal_mut().load_account_mut(inputs.caller())?.data.bump_nonce(); +) -> Result, DB::Error> { + if ctx.tx().tx_type() != TransactionType::Eip7702 { + return Ok(None); + } + let entries = ctx.tx().authorization_list_len() as u64; + if !ctx.additional_limit.authorization_list_may_cross(entries) { + return Ok(None); + } + let (records, created) = simulate_authorization_list(ctx)?; + let check = ctx.additional_limit.hold_authorization_list(records, created); + Ok(check.exceeded_limit().then_some(check)) +} + +/// What one authority of a simulated authorization list stands at. +struct SimulatedAuthority { + address: Address, + /// Its nonce, bumped by every entry the simulation accepted. + nonce: u64, + /// Whether its code is empty or a delegation, which an entry needs to apply. + applies: bool, + /// Whether the transaction's state did not hold it, so applying an entry creates it. + absent: bool, + /// Whether an entry for it was accepted. + accepted: bool, +} + +/// The write records and the created accounts the transaction's authorization list would keep +/// were it applied ([`hold_authorization_list`]): one record for each distinct authority an +/// accepted entry changes, the sender's account being the body's, and one created account for each +/// distinct authority it would create. +fn simulate_authorization_list( + ctx: &mut MegaContext, +) -> Result<(u64, u64), DB::Error> { + let chain_id = ctx.cfg().chain_id; + let caller = ctx.tx().caller(); + let entries = Eip7702AuthFacts::collect(ctx.tx(), chain_id); + let start = mark(ctx.journal_mut()); + let mut authorities: Vec = Vec::new(); + // Each authority's place in `authorities`, so a list of any length is simulated without a + // scan of what it has seen. + let mut seen: BTreeMap = BTreeMap::new(); + for entry in &entries { + let Some(authority) = entry.authority else { continue }; + let index = match seen.get(&authority) { + Some(index) => *index, + None => { + let account = ctx.journal_mut().load_account_with_code(authority)?.data; + let applies = account + .info + .code + .as_ref() + .is_none_or(|code| code.is_empty() || code.is_eip7702()); + let absent = + account.info.is_empty() && account.is_loaded_as_not_existing_not_touched(); + authorities.push(SimulatedAuthority { + address: authority, + nonce: account.info.nonce, + applies, + absent, + accepted: false, + }); + seen.insert(authority, authorities.len() - 1); + authorities.len() - 1 + } + }; + let simulated = &mut authorities[index]; + if !simulated.applies || entry.nonce != simulated.nonce { + continue; + } + simulated.nonce += 1; + simulated.accepted = true; } - let output = ctx.additional_limit.note_frame_stop(check); - Ok(synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, output)) + revert_to(ctx.journal_mut(), start); + let accepted = authorities.iter().filter(|authority| authority.accepted); + let records = accepted.clone().filter(|authority| authority.address != caller).count(); + let created = accepted.filter(|authority| authority.absent).count(); + Ok((records as u64, created as u64)) } /// The depth guard: a frame past the call-stack limit, of any call scheme or a creation, answered @@ -1095,13 +1547,13 @@ fn stop_before_building( /// revm checks the depth first when it builds a frame, before it moves value or bumps a creator's /// nonce. The guard gives the same answer before anything else sees the frame: an interceptor or an /// inspector answers before revm builds anything, so without the guard a system contract could be -/// reached at any depth; and a start's writes are counted before revm decides it, so without the -/// guard a creation past the limit would count its creator's nonce record — which outlives a failed -/// creation — for a nonce revm never bumps. +/// reached at any depth; and a call's start is held to the limits whatever revm answers but a +/// value its caller cannot fund, so without the guard a call past the limit would be held to them +/// as a start revm made. /// /// No transaction reaches the limit: regular gas is capped by the execution cap and every call -/// forwards at most sixty-three sixty-fourths of what its caller has left, so a frame at depth -/// 1,024 has a few gas. +/// forwards at most 98/100 of what its caller has left, so a frame at depth 1,024 has less than a +/// gas. fn call_too_deep(frame_init: &FrameInit) -> Option { (frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { synthetic_frame_result( @@ -1112,95 +1564,23 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { }) } -/// Asserts that revm started a frame the way the data size counted its start, once revm has built -/// the frame or answered it: that revm refused exactly the start [`caller_refuses_start`] -/// predicted, and journaled exactly the EIP-7708 transfer log counted. `counted` is whether the -/// start counts a transfer log when revm makes it -/// ([`frame_start_transfer_log`](crate::AdditionalLimit)), `refused` whether it was predicted -/// refused and so counted nothing, `logs_i` the journal's log count before revm acted, and -/// `answer` revm's answer when it did not build the frame. -/// -/// The count is made before revm decides, from the frame's input and its caller's account, so this -/// is where a divergence from revm's own rules would show. revm refuses a start on its caller's -/// account with `OutOfFunds`, for a value the caller cannot fund, and with a `Return` for a -/// creation whose creator's nonce cannot be bumped — the one creation it answers with a success. -/// It refuses a start past the call-stack limit too, but the depth guard answers that start -/// before revm sees it ([`call_too_deep`]), so revm never answers one. A built frame has run no -/// instruction yet, so the move is all revm has done. An answered call -/// moved the value when it succeeded — a call to an account with no code, a precompile — and took -/// the move back when it failed. A creation revm answers never moved value: it refused before its -/// checkpoint, or reverted it (a creation onto an occupied address). Only transfer logs are -/// compared: a precompile may journal logs of its own. -#[cfg(debug_assertions)] -fn assert_start_as_counted( - ctx: &MegaContext, - (counted, refused, logs_i): (bool, bool, usize), - answer: Option<&FrameResult>, -) { - debug_assert!( - answer.is_none_or(|answer| answer.instruction_result() != InstructionResult::CallTooDeep), - "the depth guard answers every start past the call-stack limit" - ); - let refused_by_revm = match answer { - None => false, - Some(FrameResult::Call(outcome)) => outcome.result.result == InstructionResult::OutOfFunds, - Some(FrameResult::Create(outcome)) => matches!( - outcome.result.result, - InstructionResult::OutOfFunds | InstructionResult::Return - ), - }; - debug_assert_eq!(refused, refused_by_revm, "the start revm refused is the one predicted"); - let moved = match answer { - None => true, - Some(FrameResult::Call(outcome)) => outcome.result.result.is_ok(), - Some(FrameResult::Create(_)) => false, - }; - let journaled = ctx.journal_ref().logs()[logs_i..] - .iter() - .filter(|log| log.address == revm::primitives::eip7708::ETH_TRANSFER_LOG_ADDRESS) - .count(); - debug_assert_eq!( - journaled, - usize::from(counted && moved), - "the transfer log counted is the one revm journaled" - ); -} - -/// Hands the logs journaled since `logs_i` to the inspector, outside any interpreter. -#[cold] -#[inline(never)] -fn inspect_logs( - ctx: &mut MegaContext, - inspector: &mut INSP, - logs_i: usize, -) where - INSP: Inspector, EthInterpreter>, -{ - let logs = ctx.journal().logs()[logs_i..].to_vec(); - for log in logs { - inspector.log(ctx, log); - } -} - -/// Whether executing this transaction creates its caller's account: a deposit-like transaction -/// whose caller is empty, which the deposit path materialises by bumping its nonce or by minting -/// to it. +/// Whether executing this transaction created its caller's account: a deposit-like transaction +/// whose caller was empty when the transaction loaded it, which the deposit path materialised by +/// bumping its nonce or by minting to it. /// -/// Read before op-revm deducts the caller, which is what materialises the account, and after -/// [`validate_env`](Handler::validate_env), which promoted a system-address transaction: a -/// deposit-like transaction is a deposit by then. Every other transaction pays a fee its caller +/// Read once op-revm deducted the caller, which loaded it and is what materialised it, off the +/// info revm keeps of the account as the transaction first loaded it (`Account::original_info`), +/// and after [`validate_env`](Handler::validate_env), which promoted a system-address transaction: +/// a deposit-like transaction is a deposit by then. Every other transaction pays a fee its caller /// must hold, so it has an account already. -/// -/// The read loads the caller as op-revm's deduction then does: the transaction's caller starts -/// warm, so the read changes nothing the transaction pays. -fn deposit_creates_caller( - ctx: &mut MegaContext, -) -> Result { +fn deposit_created_caller( + ctx: &MegaContext, +) -> bool { if ctx.tx().tx_type() != DEPOSIT_TRANSACTION_TYPE { - return Ok(false); + return false; } let caller = ctx.tx().caller(); - Ok(ctx.journal_mut().load_account(caller)?.data.info.is_empty()) + ctx.journal_ref().state.get(&caller).is_some_and(|account| account.original_info().is_empty()) } /// Charges the state gas of the account a deposit-like transaction creates for its caller, as @@ -1216,127 +1596,73 @@ fn charge_created_caller( gas.record_state_cost(state_gas) } -/// Whether revm refuses to start the frame `input` asks for on what its caller's account holds: -/// a value the caller cannot fund, which revm answers with `OutOfFunds`, and a creation whose -/// creator's nonce cannot be bumped, which it answers with a `Return` and no address. revm checks -/// both before it moves or writes anything, so a start it refuses makes no write record and -/// journals no transfer log: it is charged nothing and counted nothing. -/// -/// A creation onto an occupied address is the one refusal not predicted. revm decides it on the -/// created address's account after the start is counted, and reading that account here would load -/// it, changing what the transaction has warmed. So the creation's records and transfer log are -/// counted, and a crossing they cause stops the creation before revm could refuse it; without a -/// crossing, revm's refusal fails the creation and its lane goes with it. -pub(crate) fn caller_refuses_start( - ctx: &MegaContext, - input: &FrameInput, -) -> bool { - match input { - FrameInput::Call(inputs) => { - inputs.transfers_value() && - caller_refuses(ctx, inputs.caller, inputs.call_value(), false) - } - FrameInput::Create(inputs) => caller_refuses(ctx, inputs.caller(), inputs.value(), true), - FrameInput::Empty => false, - } -} - -/// [`caller_refuses_start`] for the frame `input` asks for, as the opcode starting it — or, for the -/// transaction's own frame, the charge of its record before execution — already found it: nothing -/// between the two changes the caller's account, so a second lookup of it would give the same -/// answer. A debug build makes the lookup and asserts that it does. -/// -/// A start that moves no value and creates nothing is never refused there, and takes nothing. -#[inline] -fn start_refused( - ctx: &mut MegaContext, - input: &FrameInput, -) -> bool { - let refusable = match input { - FrameInput::Call(inputs) => inputs.transfers_value(), - FrameInput::Create(_) => true, - FrameInput::Empty => false, - }; - if !refusable { - return false; - } - let Some(refused) = ctx.additional_limit.take_start_refused() else { - return caller_refuses_start(ctx, input); - }; - debug_assert_eq!( - refused, - caller_refuses_start(ctx, input), - "the answer staged for a frame's start is the one its caller's account gives" - ); - refused -} - -/// Whether `caller`'s account refuses a frame start that moves `value` and, for a `creation`, -/// bumps its nonce: the balance revm's transfer checks, and the nonce revm's creation bumps. -/// -/// The account is read from the journal as it stands, without loading or warming anything, and it -/// is always there. A transaction's sender is loaded by validation, which also credits a deposit's -/// mint (`validate_against_state_and_deduct_caller`, revm's and op-revm's). Any other caller is the -/// account a running frame runs as, which revm loaded to start that frame: a call's target before -/// its value moves, a creation's address when it creates the account. -fn caller_refuses( - ctx: &MegaContext, - caller: Address, - value: U256, - creation: bool, -) -> bool { - let account = ctx.journal_ref().state.get(&caller); - debug_assert!(account.is_some(), "a frame's caller is loaded before the frame starts"); - account.is_some_and(|account| { - account.info.balance < value || (creation && account.info.nonce == u64::MAX) - }) -} - -/// Records the account writes of the EIP-7702 authorities applied since journal entry -/// `journal_i`, and answers how many there are: each applied authorization bumps its authority's +/// The account writes of the EIP-7702 authorities applied since journal entry `journal_i`, and the +/// accounts among them the application created: each applied authorization bumps its authority's /// nonce once, so the distinct authorities other than the sender are the accounts written. The /// sender's write is part of the transaction body. -fn record_applied_authorities( +/// +/// An authority the application created is one revm charged the account's state gas for: one +/// that was empty, loaded as not existing and untouched when the application reached it. Read +/// after the application, that is an authority the database answered no account for, empty at +/// the transaction's start, and touched first by the application — revm's flag of a touched +/// account outlives the transaction that set it on a journal that runs several, so an authority an +/// earlier transaction touched was touched before. Validation's bump of the sender comes first, +/// and never makes the sender a new account. +fn applied_authorities( ctx: &mut MegaContext, journal_i: usize, -) -> u64 { +) -> (u64, u64) { if ctx.tx().tx_type() != TransactionType::Eip7702 { - return 0; + return (0, 0); } let caller = ctx.tx().caller(); - let target = ctx.tx().kind().to().copied(); - let mut authorities: Vec
= ctx.journal_ref().journal()[journal_i..] - .iter() - .filter_map(|entry| match entry { - JournalEntry::NonceBump { address } if *address != caller => Some(*address), - _ => None, - }) - .collect(); + let mut authorities: Vec
= Vec::new(); + let mut touched: Vec
= Vec::new(); + for entry in &ctx.journal_ref().journal()[journal_i..] { + match entry { + JournalEntry::NonceBump { address } if *address != caller => authorities.push(*address), + JournalEntry::AccountTouched { address } => touched.push(*address), + _ => {} + } + } authorities.sort_unstable(); authorities.dedup(); - let target_is_authority = - target.is_some_and(|target| authorities.binary_search(&target).is_ok()); - let applied = authorities.len() as u64; - ctx.additional_limit.record_applied_authorities(caller, applied, target_is_authority); + touched.sort_unstable(); // An applied authority that is the block beneficiary wrote the beneficiary's account. if authorities.binary_search(&ctx.block().beneficiary).is_ok() { ctx.detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); } - applied + let state = &ctx.journal_ref().state; + let created = authorities + .iter() + .filter(|authority| { + touched.binary_search(authority).is_ok() && + state.get(*authority).is_some_and(|account| { + account.is_loaded_as_not_existing() && account.original_info().is_empty() + }) + }) + .count(); + (authorities.len() as u64, created as u64) } /// Charges the history of the write records a transaction makes outside any frame: one per -/// applied authority, and the one its own frame makes — the recipient of its value, or the -/// account it creates. +/// applied authority, and the one its own frame makes — the recipient of its value, when the +/// value changes an account the transaction has not changed, or the account it creates. +/// +/// The recipient's record is predicted as the journal's state stands before the first frame +/// ([`Accounts::transfer_records`](crate::limit::Accounts)): a recipient that is the sender, or an +/// authority the transaction applied, is changed already, and gets none; the sender's side never +/// makes one, validation having changed its account. A creation's account is charged as a record, +/// as a `CREATE` opcode charges it; the transaction has changed no account but its sender before +/// its first frame, so the account it creates is one it had not changed. /// /// The authorities' records are the transaction's own and outlive a first frame that fails; the -/// first frame's record does not, so what it cost is kept for the settlement to give back, and -/// whether it makes one is left for that frame's lane to check its own count against. A first -/// frame revm refuses to start on its sender's account makes no record, and is charged none -/// ([`caller_refuses_start`]): among the transactions that pay history, that is a creation from an -/// account whose nonce cannot be bumped, which only a caller that turned the nonce check off can -/// run, and which revm answers with a success. The answer is left for the first frame's init, -/// which asks the same of the same account. +/// first frame's record does not, so what it cost is kept for that frame to carry as its start +/// charge, which its failure gives back. A first frame revm refuses to start on its sender's +/// account makes no record, and gets the charge back as any frame that kept nothing does: among +/// the transactions that pay history, that is a creation from an account whose nonce cannot be +/// bumped, which only a caller that turned the nonce check off can run, and which revm answers +/// with a success and no address. /// `false` when the transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &mut MegaContext, @@ -1347,25 +1673,20 @@ fn charge_records_made_outside_a_frame( return true; } let tx = ctx.tx(); - let writes_a_record = match tx.kind() { - TxKind::Create => true, + let first_frame = match tx.kind() { + TxKind::Create => 1, TxKind::Call(to) => { - !tx.value().is_zero() && - to != tx.caller() && - !ctx.additional_limit.target_is_authority() + let predicted = ctx.accounts().transfer_records(tx.caller(), to, tx.value()).transfer; + debug_assert_eq!(predicted.taken, 0, "the sender's value returns no account"); + predicted.added } }; - let (caller, value, creation) = (tx.caller(), tx.value(), tx.kind().is_create()); - let top_level_record = writes_a_record && { - let refused = caller_refuses(ctx, caller, value, creation); - ctx.additional_limit.stage_start_refused(refused); - !refused + let Some((first_frame, _)) = + charge_write_records_history(gas, first_frame, applied_authorities) + else { + return false; }; - let charged = - charge_write_records_history(gas, u64::from(top_level_record), applied_authorities); - let Some((top_level, _)) = charged else { return false }; - ctx.additional_limit.set_top_level_write_record_gas(top_level); - ctx.additional_limit.stage_top_level_records(u64::from(top_level_record)); + ctx.additional_limit.set_first_frame_charge(first_frame); true } @@ -1374,11 +1695,10 @@ mod tests { use super::*; use crate::{test_utils::MemoryDatabase, MegaSpecId}; use alloy_primitives::{address, U256}; - use revm::interpreter::{ - gas::WithheldCrossing, CallInput, CallInputs, CallValue, SharedMemory, + use revm::{ + context_interface::journaled_state::account::JournaledAccountTr, + interpreter::{gas::WithheldCrossing, CallInput, CallInputs, CallValue, SharedMemory}, }; - #[cfg(debug_assertions)] - use revm::interpreter::{CreateInputs, CreateScheme}; use std::boxed::Box; const CALLER: Address = address!("00000000000000000000000000000000000e0001"); @@ -1399,23 +1719,21 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: true, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, })) } - /// A `CREATE` its opcode charged the created account for. - #[cfg(debug_assertions)] - fn creation() -> FrameInput { - let mut inputs = - CreateInputs::new(CALLER, CreateScheme::Create, U256::ZERO, Bytes::new(), 100_000, 0); - inputs.set_charged_create_state_gas(true); - inputs.set_charged_state_gas_address(TARGET); - FrameInput::Create(Box::new(inputs)) - } - /// A context whose transaction read the block environment before its first frame under a cap /// of `cap`, so a frame at depth 0 starts with an allowance of `cap`. fn detained(cap: u64) -> MegaContext { - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + detained_on(MemoryDatabase::default(), cap) + } + + /// [`detained`] over `db`. + fn detained_on(db: MemoryDatabase, cap: u64) -> MegaContext { + let mut ctx = MegaContext::new(db, MegaSpecId::SATIN); ctx.detention.reset(true, cap, cap); ctx.detention.mark_before_execution(VolatileDataAccess::TIMESTAMP); ctx @@ -1439,6 +1757,9 @@ mod tests { scheme: CallScheme::StaticCall, is_static: true, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, })), } } @@ -1451,9 +1772,8 @@ mod tests { dispatched: &PrecompilesMap, to: Address, forward: u64, - refused: bool, ) -> (PrecompileHold, u64) { - hold_input(cap, priced, dispatched, to, &[0; 32], forward, refused) + hold_input(cap, priced, dispatched, to, &[0; 32], forward) } /// [`hold`] for a call of `input`. @@ -1464,19 +1784,18 @@ mod tests { to: Address, input: &[u8], forward: u64, - refused: bool, ) -> (PrecompileHold, u64) { let ctx = detained(cap); let mut frame_init = static_call(to, input, forward); - let held = hold_precompile(&ctx, dispatched, priced, &mut frame_init, refused); + let held = hold_precompile(&ctx, dispatched, priced, &mut frame_init); (held, input_gas_limit(&frame_init.frame_input)) } /// A precompile the engine prices is decided from its price before it runs: within the /// allowance, and past its whole forward, it runs on the forward as without the limit; past /// the allowance and within the forward, it is answered without running, out of gas and - /// marked as a crossing whose record is the forward. A call revm refuses on its caller's - /// account runs as without the limit. + /// marked as a crossing whose record is the forward. A value call its caller cannot fund, + /// which revm refuses before it runs the precompile, runs as without the limit. #[test] fn test_a_priced_precompile_is_decided_from_its_price() { const KZG: Address = crate::kzg_point_evaluation::ADDRESS; @@ -1484,27 +1803,46 @@ mod tests { let (priced, map) = (PricedPrecompiles::default(), crate::satin_precompiles_map()); // Within the allowance: runs on the forward. - let (held, ran_on) = hold(PRICE, &priced, &map, KZG, 3 * PRICE, false); + let (held, ran_on) = hold(PRICE, &priced, &map, KZG, 3 * PRICE); assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); // Past the allowance, within the forward: the crossing, without running. for forward in [PRICE, 3 * PRICE] { - let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, forward, false); + let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, forward); assert_eq!((held, ran_on), (PrecompileHold::Crossing, forward), "the input as it was"); } // Past the whole forward: a plain out-of-gas, run on the forward. - let (held, ran_on) = hold(PRICE / 2, &priced, &map, KZG, PRICE - 1, false); + let (held, ran_on) = hold(PRICE / 2, &priced, &map, KZG, PRICE - 1); assert_eq!((held, ran_on), (PrecompileHold::Unheld, PRICE - 1)); - // Refused on the caller's account: revm answers it without running the precompile. - let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, 3 * PRICE, true); - assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + // A value call past the allowance, within the forward: the crossing when its caller can + // fund the value; revm's refusal, without running the precompile, when it cannot. A + // `DELEGATECALL` moves nothing, whatever value it carries for its callee to read and + // whatever its caller holds: the crossing. + for (scheme, balance, held) in [ + (CallScheme::Call, 1_u64, PrecompileHold::Crossing), + (CallScheme::Call, 0, PrecompileHold::Unheld), + (CallScheme::DelegateCall, 0, PrecompileHold::Crossing), + ] { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(balance)); + let mut ctx = detained_on(db, PRICE - 1); + ctx.journal_mut().load_account(CALLER).unwrap(); + let mut frame_init = static_call(KZG, &[0; 32], 3 * PRICE); + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { unreachable!() }; + (inputs.scheme, inputs.is_static) = (scheme, false); + inputs.value = match scheme { + CallScheme::DelegateCall => CallValue::Apparent(U256::from(1)), + _ => CallValue::Transfer(U256::from(1)), + }; + let case = format!("{scheme:?} holding {balance}"); + assert_eq!(hold_precompile(&ctx, &map, &priced, &mut frame_init), held, "{case}"); + } // A forward within the allowance, and a call to anything but a precompile, run as they are. - let (held, ran_on) = hold(3 * PRICE, &priced, &map, KZG, 3 * PRICE, false); + let (held, ran_on) = hold(3 * PRICE, &priced, &map, KZG, 3 * PRICE); assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); - let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE, false); + let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE); assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); } @@ -1542,9 +1880,8 @@ mod tests { for (precompile, pair, limit, price) in wrappers { let to = *precompile.address(); let two_pairs = std::vec![0; 2 * pair]; - let hold = |cap, input: &[u8], forward| { - hold_input(cap, &priced, &map, to, input, forward, false) - }; + let hold = + |cap, input: &[u8], forward| hold_input(cap, &priced, &map, to, input, forward); // Within the allowance: runs on the forward. assert_eq!(hold(price, &two_pairs, 3 * price), (PrecompileHold::Unheld, 3 * price)); @@ -1611,7 +1948,7 @@ mod tests { (&foreign, KZG), (&foreign, pairing), ] { - let (held, ran_on) = hold(1_000, priced, &map, to, 300_000, false); + let (held, ran_on) = hold(1_000, priced, &map, to, 300_000); let clamped = PrecompileHold::Clamped(NonZeroU64::new(299_000).unwrap()); assert_eq!(held, clamped, "{to}"); assert_eq!(ran_on, 1_000, "{to}: run on the allowance"); @@ -1630,7 +1967,7 @@ mod tests { ] { let case = format!("succeeded {succeeded}, now {result:?}"); let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let start = journal_position(&mut ctx); + let start = mark(ctx.journal_mut()); // What the answer wrote: a bump of the recipient's nonce. let _ = ctx.journal_mut().load_account_mut(TARGET).unwrap().data.bump_nonce(); let answer = synthetic_frame_result(&value_call(), result, Bytes::new()); @@ -1640,74 +1977,77 @@ mod tests { } } - /// The guard trips on a transfer log the data size counted for a frame revm built and did not - /// journal. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the transfer log counted is the one revm journaled")] - fn test_a_transfer_log_counted_and_not_journaled_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - assert_start_as_counted(&ctx, (true, false, 0), None); - } - - /// The guard trips on a start revm refused on its caller's account that was not predicted, - /// which the data size would have counted. + /// One handler runs one transaction, and what a phase learns about it is kept on the handler: + /// the reservoir the transaction settled with is read where revm builds its result's gas and + /// reported once the result is built. A handler reused for a system call, whose path builds + /// no result gas and skips that read, reports the system call's own reservoir: the capture is + /// consumed by the report, and by the error path, which gives no report. A transaction below + /// the execution cap leaves a capture of nothing, one above it a capture of its own margin, and + /// a deposit that halts a capture its failed-deposit result never reports; after each, a + /// system call on revm's default gas limit reports the margin above the system-call budget. #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the start revm refused is the one predicted")] - fn test_a_refusal_not_predicted_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let unfunded = - synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); - assert_start_as_counted(&ctx, (true, false, 0), Some(&unfunded)); - } - - /// The guard trips on a start predicted refused that revm made, which the data size did not - /// count. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the start revm refused is the one predicted")] - fn test_a_predicted_refusal_revm_did_not_make_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - assert_start_as_counted(&ctx, (false, true, 0), None); - } - - /// The guard trips on a start revm answered past the call-stack limit, which the depth guard - /// answers before revm sees it, for a creation and a call alike. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the depth guard answers every start past the call-stack limit")] - fn test_a_start_revm_answered_past_the_depth_limit_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - for input in [creation(), value_call()] { - let too_deep = - synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); - assert_start_as_counted(&ctx, (false, false, 0), Some(&too_deep)); + fn test_a_reused_handler_reports_each_executions_own_reservoir() { + use crate::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{op_transaction, zero_fee_l1_block_info}, + MegaTransaction, SYSTEM_CALL_REGULAR_GAS_LIMIT, + }; + use alloy_op_evm::OpTx; + use revm::{ + context::{ContextSetters, TxEnv}, + handler::{system_call::SYSTEM_CALL_GAS_LIMIT, SystemCallTx}, + inspector::NoOpInspector, + }; + const HALTS: Address = address!("00000000000000000000000000000000000e0003"); + const DEFAULT_RESERVOIR: u64 = SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT; + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(TARGET, Bytes::new()) + .account_code(HALTS, Bytes::from_static(&[revm::bytecode::opcode::INVALID])); + let mut evm = MegaEvm::new( + MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()), + ); + let mut handler = MegaHandler::< + MegaEvm, + crate::MegaEvmError, + EthFrame, + >::new(); + let room = 100_000 + history_gas(crate::TX_BODY_SIZE).unwrap(); + let tx = |to: Address, gas_limit: u64, nonce: u64| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + nonce, + gas_limit, + kind: TxKind::Call(to), + ..Default::default() + })) + }; + let mut deposit = tx(HALTS, room, 0); + deposit.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); + deposit.0.base.gas_price = 0; + + for (case, tx, succeeds) in [ + ("below the cap", tx(TARGET, room, 0), true), + ("above the cap", tx(TARGET, TX_GAS_LIMIT_CAP + 10_000_000, 1), true), + ("a halting deposit", deposit, false), + ] { + evm.inner.ctx.set_tx(tx); + let result = handler.run(&mut evm).expect(case); + assert_eq!(result.is_success(), succeeds, "{case}: {result:?}"); + let settled = evm.ctx().additional_limit().reservoir_remaining(); + assert_ne!(settled, DEFAULT_RESERVOIR, "{case}: the capture would show"); + + let call = MegaTransaction::new_system_tx_with_caller(CALLER, TARGET, Bytes::new()); + evm.inner.ctx.set_tx(call); + evm.inner.ctx.on_new_system_call(); + let result = handler.run_system_call(&mut evm).expect("the system call runs"); + assert!(result.is_success(), "{case}: {result:?}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + DEFAULT_RESERVOIR, + "{case}: the system call's own reservoir, not the capture" + ); } } - - /// The guard expects no log where nothing moved, whatever the input would count: a start - /// revm refuses on its caller's account, predicted — a value call it answers `OutOfFunds`, a - /// creation whose creator's nonce cannot be bumped, answered with a `Return` — and one it - /// fails otherwise — a creation onto an occupied address, a failing precompile; and none for - /// a frame nothing was counted for. - #[test] - #[cfg(debug_assertions)] - fn test_the_guard_expects_no_transfer_log_where_nothing_moved() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - assert_start_as_counted(&ctx, (false, false, 0), None); - let overflow = synthetic_frame_result(&creation(), InstructionResult::Return, Bytes::new()); - assert_start_as_counted(&ctx, (true, true, 0), Some(&overflow)); - let unfunded = - synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); - assert_start_as_counted(&ctx, (true, true, 0), Some(&unfunded)); - let collision = - synthetic_frame_result(&creation(), InstructionResult::CreateCollision, Bytes::new()); - assert_start_as_counted(&ctx, (true, false, 0), Some(&collision)); - let failed = - synthetic_frame_result(&value_call(), InstructionResult::PrecompileError, Bytes::new()); - assert_start_as_counted(&ctx, (true, false, 0), Some(&failed)); - let answered = synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); - assert_start_as_counted(&ctx, (false, false, 0), Some(&answered)); - } } diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 32b7a45d9..827f9bf17 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -365,13 +365,15 @@ mod tests { .tx_runtime_limits .with_tx_data_size_limit(crate::TX_BODY_SIZE + 40); let stopped = run(&MegaEvmFactory::new().with_tx_runtime_limits(one_record)); + // The second record crosses the transaction's own frame's budget, the record the body + // leaves of the limit, which is named. assert_eq!( stopped.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: crate::TX_BODY_SIZE + 40, - used: crate::TX_BODY_SIZE + 2 * 40, - frame_local: false, + limit: 40, + used: 2 * 40, + frame_local: true, }) ); diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index f26b53696..e2dc505d1 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -1,28 +1,28 @@ -//! Frame results built without running a frame, and how they settle. +//! Frame results built without running a frame. //! //! `MegaETH` answers some frames itself: the depth guard, a transaction stopped by a limit, the //! system contract interceptors, a `keylessDeploy` call carrying value, and a precompile call gas //! detention answers from its price without running it. Such a result goes back to the caller like -//! any frame's, and the caller settles it the way revm settles a frame it ran: +//! any frame's, through revm's own frame return, which settles it as a frame revm ran: //! //! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) //! is priced for refund when the frame failed; -//! 2. [`handle_reservoir_remaining_gas`] merges the frame's gas into the caller's: unused regular -//! gas back on success and revert, the frame's reservoir adopted as the caller's own; -//! 3. the refund is refilled into the caller's reservoir. +//! 2. the frame's gas merges into the caller's: unused regular gas back on success and revert, the +//! frame's reservoir added to what the caller kept, and the frame's pools absorbed into the +//! caller's; +//! 3. the refund is refilled into the caller's reservoir, and the start charge the frame carries — +//! what its caller paid for the records its start makes — is given back when it failed. //! //! The contract for a synthetic result is that it settles exactly like revm's own: its gas carries -//! the reservoir the frame inherited ([`untouched_call_gas`], [`with_pools_of`]), never -//! `Gas::new(limit)`, which would carry none and bill the sender for the whole reservoir; and it -//! carries the calling opcode's upfront-charge flags, so step 1 refunds the charge. -//! [`synthetic_frame_result`] builds one; [`settle_frame_result`] is that settlement, for a caller -//! that settles a result into its own gas outside revm's frame return. +//! the reservoir and the shares of the pools the frame inherited ([`untouched_call_gas`], +//! [`untouched_create_gas`]), never `Gas::new(limit)`, which would carry no reservoir and +//! unlimited pools, billing the sender for the whole reservoir and lifting the caller's budgets; +//! and it carries the calling opcode's upfront-charge flags and start charge, so step 1 and step 3 +//! refund them. [`synthetic_frame_result`] builds one. use alloy_primitives::Bytes; use revm::{ - context::{result::FromStringError, ContextTr}, - context_interface::{cfg::gas::GasTracker, context::take_error, Host}, - handler::{handle_reservoir_remaining_gas, FrameResult}, + handler::FrameResult, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, InterpreterResult, @@ -30,39 +30,29 @@ use revm::{ }; /// The gas of a call result built without running the callee: the call's whole gas limit -/// unspent, and the reservoir the call inherited. +/// unspent, the reservoir the call inherited, and the shares of its caller's pools it was given, +/// undrawn. #[inline] pub const fn untouched_call_gas(inputs: &CallInputs) -> Gas { - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir) + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + gas.tracker_mut().set_pools_remaining(inputs.pool_shares); + gas } /// The gas of a creation result built without running the init code: its whole gas limit -/// unspent, and the reservoir the creation inherited. +/// unspent, the reservoir the creation inherited, and the shares of its creator's pools it was +/// given, undrawn. #[inline] -pub fn untouched_create_gas(inputs: &CreateInputs) -> Gas { - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()) -} - -/// `gas_limit` of fresh regular gas carrying `source`'s EIP-8037 pools: its reservoir, the state -/// and history gas it charged, and the part of those charges that spilled onto regular gas. -/// -/// For a result whose regular gas is rebuilt (a precompile's output normalised to the gas limit -/// the caller forwarded): the caller keeps the frame's state and history charges on success and -/// rolls them back on failure, so a rebuilt `Gas` that dropped them would hand the caller an -/// empty reservoir and charges the frame never made. -#[inline] -pub const fn with_pools_of(gas_limit: u64, source: &Gas) -> Gas { - let mut gas = Gas::new(gas_limit); - gas.set_reservoir(source.reservoir()); - gas.set_state_gas_spent(source.state_gas_spent()); - gas.set_state_gas_spilled(source.state_gas_spilled()); - gas.set_history_gas_spent(source.history_gas_spent()); +pub const fn untouched_create_gas(inputs: &CreateInputs) -> Gas { + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()); + gas.tracker_mut().set_pools_remaining(inputs.pool_shares()); gas } /// A result for the frame `input` would start, built without running it: `result` with -/// `output`, the frame's gas untouched and the inherited reservoir carried, and the calling -/// opcode's upfront state-gas flags, as revm builds the results of the frames it answers itself. +/// `output`, the frame's gas untouched, the inherited reservoir and pool shares carried, and the +/// calling opcode's upfront state-gas flags and start charge, as revm builds the results of the +/// frames it answers itself. pub fn synthetic_frame_result( input: &FrameInput, result: InstructionResult, @@ -75,6 +65,7 @@ pub fn synthetic_frame_result( address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: inputs.charged_start(), }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), } @@ -95,48 +86,15 @@ pub fn synthetic_call_result( precompile_call_logs: Default::default(), charged_new_account_state_gas: inputs.charged_new_account_state_gas, charged_state_gas_address: inputs.target_address, + charged_start: inputs.charged_start, }) } -/// Settles `result`'s gas into `caller_gas` exactly as revm's frame return does: the calling -/// opcode's upfront state-gas charge priced for refund, [`handle_reservoir_remaining_gas`], then -/// the refund refilled into the caller's reservoir. -/// -/// `ctx` prices the refund through the same hook the charge went through; a failed lookup is -/// the error the hook recorded. -pub fn settle_frame_result( - ctx: &mut CTX, - caller_gas: &mut GasTracker, - result: &mut FrameResult, -) -> Result<(), ERROR> -where - CTX: ContextTr + Host, - ERROR: From<::Error> + FromStringError, -{ - take_error::(ctx.error())?; - let refund = match result.refundable_state_gas_charge() { - Some(charge) => match ctx.state_gas_charge(charge) { - Some(refund) => Some(refund), - None => { - take_error::(ctx.error())?; - return Err(ERROR::from_string("state gas price lookup failed".into())); - } - }, - None => None, - }; - let instruction_result = result.instruction_result(); - handle_reservoir_remaining_gas(instruction_result, caller_gas, result.gas_mut().tracker_mut()); - if let Some(refund) = refund { - caller_gas.refill_reservoir(refund); - } - Ok(()) -} - #[cfg(test)] mod tests { use super::*; use alloy_primitives::{address, Address, U256}; - use revm::interpreter::{CallInput, CallScheme, CallValue}; + use revm::interpreter::{CallInput, CallScheme, CallValue, PoolAmounts}; const TARGET: Address = address!("0000000000000000000000000000000000001234"); @@ -154,6 +112,9 @@ mod tests { is_static: false, reservoir, charged_new_account_state_gas: charged, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, } } @@ -168,21 +129,6 @@ mod tests { assert_ne!(gas, Gas::new(50_000)); } - /// Rebuilding the regular gas keeps every EIP-8037 pool of the source. - #[test] - fn test_with_pools_of_keeps_the_pools() { - let mut source = Gas::new_with_regular_gas_and_reservoir(100, 1_000); - assert!(source.record_state_cost(1_050)); - assert!(source.record_history_cost(20)); - let rebuilt = with_pools_of(70, &source); - assert_eq!(rebuilt.limit(), 70); - assert_eq!(rebuilt.remaining(), 70); - assert_eq!(rebuilt.reservoir(), source.reservoir()); - assert_eq!(rebuilt.state_gas_spent(), 1_050); - assert_eq!(rebuilt.state_gas_spilled(), source.state_gas_spilled()); - assert_eq!(rebuilt.history_gas_spent(), 20); - } - /// A synthetic call result carries the return range, the untouched gas and the upfront /// charge flags of its inputs. #[test] @@ -203,57 +149,4 @@ mod tests { assert_eq!(outcome.charged_state_gas_address, TARGET); assert!(!outcome.was_precompile_called); } - - /// Settling a failed synthetic call into its caller returns the forwarded gas, keeps the - /// caller's reservoir, and refunds the new-account charge the calling opcode made, as revm's - /// frame return does. - #[test] - fn test_settle_frame_result_refunds_the_upfront_charge() { - use revm::{ - context::{CfgEnv, Context}, - context_interface::cfg::{GasId, GasParams}, - database::EmptyDB, - primitives::hardfork::SpecId, - MainContext, - }; - let mut cfg = CfgEnv::new_with_spec(SpecId::AMSTERDAM); - cfg.enable_amsterdam_eip8037 = true; - cfg.gas_params = GasParams::new_spec(SpecId::AMSTERDAM); - let new_account = cfg.gas_params.get(GasId::new_account_state_gas()); - assert!(new_account > 0); - let mut ctx = Context::mainnet().with_db(EmptyDB::default()).with_cfg(cfg); - - // The caller forwarded 9,000 gas and charged a new account from its 1M reservoir. - let reservoir = 1_000_000; - let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); - assert!(caller.record_state_cost(new_account)); - let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); - let mut result = - synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); - - settle_frame_result::<_, revm::context::result::EVMError>( - &mut ctx, - &mut caller, - &mut result, - ) - .unwrap(); - assert_eq!(caller.remaining(), 100_000, "the forwarded gas comes back"); - assert_eq!(caller.reservoir(), reservoir, "the charge is refunded to the reservoir"); - assert_eq!(caller.state_gas_spent(), 0); - - // A successful synthetic result keeps the charge: the account exists. - let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); - assert!(caller.record_state_cost(new_account)); - let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); - let mut result = synthetic_frame_result(&input, InstructionResult::Stop, Bytes::new()); - settle_frame_result::<_, revm::context::result::EVMError>( - &mut ctx, - &mut caller, - &mut result, - ) - .unwrap(); - assert_eq!(caller.remaining(), 100_000); - assert_eq!(caller.reservoir(), reservoir - new_account); - assert_eq!(caller.state_gas_spent(), new_account as i64); - } } diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs index fbf3be94a..d02b7f7d4 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -61,22 +61,22 @@ pub(crate) fn charge_write_records_history( /// The history bytes the allowance of a value-transferring call covers: one three-topic event /// carrying a single word, which is what a `receive()` hook emits. -pub const STORAGE_CALL_STIPEND_BYTES: u64 = LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32; +pub const HISTORY_ALLOWANCE_BYTES: u64 = LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32; /// The history allowance a value-transferring `CALL` or `CALLCODE` grants the frame it starts. /// /// EVM's own `CALL_STIPEND` buys the recipient of a transfer enough computation to notice it; on /// a chain that prices the bytes a log appends it buys no log at all, so a `receive()` hook that /// emits an event would be unreachable through `transfer()`. The allowance is that stipend's -/// counterpart on the history ledger: [`STORAGE_CALL_STIPEND_BYTES`] at the cost per history +/// counterpart on the history ledger: [`HISTORY_ALLOWANCE_BYTES`] at the cost per history /// byte, enough for one event and nothing else. /// /// It is separate from the frame's gas in every sense. It never enters the frame's `Gas`, so no /// settlement can hand it back as gas; it pays history charges and only those, so it cannot buy /// computation or a write record; and what it pays for appears on no ledger, because no pool of /// the transaction's gas paid it. -pub fn storage_call_stipend() -> u64 { - history_gas(STORAGE_CALL_STIPEND_BYTES).unwrap_or(u64::MAX) +pub fn history_allowance_gas() -> u64 { + history_gas(HISTORY_ALLOWANCE_BYTES).unwrap_or(u64::MAX) } /// The data-size bytes of `tx`'s body: the fixed body, the calldata, one record per EIP-7702 @@ -152,10 +152,10 @@ mod tests { if runs_at_measurement_prices() { return; } - assert_eq!(STORAGE_CALL_STIPEND_BYTES, log_history_bytes(3, 32)); - assert_eq!(STORAGE_CALL_STIPEND_BYTES, 160); - assert_eq!(storage_call_stipend(), 160 * COST_PER_HISTORY_BYTE); - assert_eq!(storage_call_stipend(), history_gas(log_history_bytes(3, 32)).unwrap()); + assert_eq!(HISTORY_ALLOWANCE_BYTES, log_history_bytes(3, 32)); + assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); + assert_eq!(history_allowance_gas(), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(history_allowance_gas(), history_gas(log_history_bytes(3, 32)).unwrap()); } /// Every way a transaction moves value, as a name, a database, the transaction at a gas limit diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index cade09497..dc40bdfa2 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -1,16 +1,17 @@ //! The Host of the Satin engine. //! -//! # The Host only observes +//! # Writes are counted once their opcode completed //! -//! revm hands the Host the facts of every state-writing opcode: an `SSTORE`'s original, present and -//! new values, a log's topics and data, a `SELFDESTRUCT`'s balance and beneficiary. The Host -//! stages them ([`AdditionalLimit::stage_record`](crate::AdditionalLimit)) and records nothing. -//! The opcode's wrapper commits the staged record after the opcode completed, and charges the -//! frame the history the record costs; it discards the record, and charges nothing, when the -//! opcode failed. Recording in the Host would count a write the opcode's own failure then takes -//! back: `SSTORE` charges its dynamic gas after the Host call, and an out-of-gas there halts the -//! frame with the record already counted — and would have charged the frame for a byte the chain -//! never carries. +//! revm hands the Host the facts of every state-writing opcode twice: as it makes the write (an +//! `SSTORE`'s slot, a log, a `SELFDESTRUCT`'s beneficiary), and once the opcode completed, in the +//! completed-write hook ([`write_completed`](revm::context_interface::Host::write_completed)), +//! after every charge the opcode makes. The Host counts nothing in the first: the write methods +//! only write, whoever calls them. The hook commits the write's record to the running frame, holds +//! it to the limits and charges the frame the history the record costs. Counting at the write +//! would count one the opcode's own failure then takes back: `SSTORE` charges its dynamic gas after +//! the write, and an out-of-gas there halts the frame with the record already counted — and would +//! have charged the frame for a byte the chain never carries. A tool's write through the Host, an +//! inspector's log among them, reaches no hook, and is not counted. //! //! `block_hash` serves the read and records it, so a stateless witness learns of a `BLOCKHASH` //! that bypassed the journal. @@ -51,7 +52,20 @@ //! through this hook. A frame that fails instead rolls its own charges back by the amounts it //! recorded while running, without asking for a price at all. Both cancel exactly, for different //! reasons: the re-priced sites because the multiplier of a bucket is read once per transaction, -//! the rolled-back amounts because nothing but this hook priced them in the first place. +//! the rolled-back amounts because nothing but this hook priced them in the first place. The one +//! exception is an inspector's: a call's upfront charge is given back for the account its frame's +//! inputs name, as revm reads it, so an inspector that rewrites the target has it priced there. +//! +//! A charge on an account created in the transaction and destroyed since is priced at nothing: +//! its destruction gave back what the transaction had charged for it, at the prices charged and +//! outside that rule, so a re-pricing after the mark gives nothing back a second time, and the +//! account keeps no further state gas. +//! +//! The destruction gives the account's leaf back only when no account stood at the address at the +//! transaction's start: the database answered none for it, `None` from +//! [`Database::basic`](revm::Database::basic), or an earlier transaction on the same journal +//! destroyed it. A database that answers an empty account for an address it holds none for gives +//! that leaf back to no destruction: an empty account is a leaf the state holds. //! //! Every other Host method delegates to op-revm's context. @@ -63,9 +77,12 @@ use delegate::delegate; use revm::{ context::ContextTr, context_interface::{ - cfg::{GasId, GasParams, StateGasSite}, + cfg::{ + gas::{GasTracker, PoolAmounts, StartCharge}, + GasId, GasParams, StateGasCharge, StateGasSite, + }, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, - host::LoadError, + host::{CompletedWrite, FrameStart, LoadError, WriteVerdict}, journaled_state::AccountInfoLoad, }, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, @@ -73,8 +90,10 @@ use revm::{ }; use crate::{ - system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, StagedRecord, - VolatileDataAccess, + charge_write_records_history, history_gas, + limit::{DestroyedParts, HistoryBytes}, + system::ORACLE_CONTRACT_ADDRESS, + ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -93,6 +112,22 @@ impl revm::context_interface::Host fn is_amsterdam_eip8037_enabled(&self) -> bool; fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; + // A write is counted once its opcode completed, in `write_completed`: what the Host's + // write methods are called with, by an opcode or by a tool, counts nothing. + fn sstore( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + ) -> Option>; + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn log(&mut self, log: Log); } } @@ -175,7 +210,10 @@ impl revm::context_interface::Host self.inner.sload_skip_cold_load(address, key, skip_cold_load) } - /// Loads the account, marking a read of the block beneficiary's. + /// Loads the account, marking a read of the block beneficiary's, or refusing it in a frame + /// whose volatile-data access is off, when the load is a read: when an opcode's read wrapper + /// makes it. `CREATE`'s and `CREATE2`'s loads of their creator and of the created address are + /// no reads (see [`Detention`](crate::Detention)). #[inline] fn load_account_info_skip_cold_load( &mut self, @@ -197,42 +235,23 @@ impl revm::context_interface::Host /// Prices one EIP-8037 state gas unit, scaling the schedule's entry by the SALT bucket /// capacity of the account — or, for a slot-scoped entry, of the storage slot — the charge - /// lands on. - /// - /// `state gas = schedule entry x m`, where `m` is the bucket's capacity in minimum buckets. - /// A charge in a minimum-capacity bucket pays the schedule's own number, and a charge in a - /// bucket eight times as large pays eight times as much: state that crowds a region of the - /// trie costs what it makes everyone else pay to carry it. Only the state dimension scales; - /// regular gas is never touched by `m`. + /// lands on ([`priced_state_gas`](MegaContext::priced_state_gas)). /// - /// Two charges are priced without reading SALT at all: an entry the schedule prices at zero, - /// which `m` cannot move off zero, and every charge of a system-originated transaction, - /// which prices at the minimum bucket by rule (see - /// [`is_system_originated`](crate::MegaContext::is_system_originated)). + /// A charge on an account created in the transaction and destroyed since is priced at + /// nothing: from that mark until the transaction ends the account keeps no further state gas, + /// so an `SSTORE` of one of its slots neither charges nor refills fresh-slot state gas, and + /// code its own constructor deposits after destroying it is charged no state gas, whatever gas + /// the frame holds. The destruction gave back what the transaction had charged for the + /// account at the prices charged, outside this rule. The neutral configuration prices as the + /// fixture's fork does ([`destruction_table_prices_state_gas`]). /// - /// Reporting nothing is how a failed capacity lookup travels: the cause is recorded in the - /// context error the way [`Host::sload`](revm::context_interface::Host::sload) records a - /// database failure, and the charge site turns it into a bail-out that the transaction - /// surfaces as an error. A price the engine could not look up is never replaced by one - /// nobody chose. + /// [`destruction_table_prices_state_gas`]: MegaContext::destruction_table_prices_state_gas #[inline] fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option { - let base = self.inner.cfg.gas_params.get(id); - if base == 0 || self.is_system_originated() { - return Some(base); - } - let multiplier = match site.slot { - Some(slot) => self.slot_bucket_multiplier(site.address, slot), - None => self.account_bucket_multiplier(site.address), - }; - match multiplier { - Ok(multiplier) => Some(base.saturating_mul(multiplier)), - Err(error) => { - *self.error() = - Err(ContextError::Custom(format!("SALT bucket lookup failed: {error}"))); - None - } + if self.destruction_table_prices_state_gas() && self.accounts().is_destroyed(site.address) { + return Some(0); } + self.priced_state_gas(id, site) } /// Serves the hash and records that this block read it. @@ -249,46 +268,8 @@ impl revm::context_interface::Host Some(hash) } - /// Writes the slot and stages the write's values. - #[inline] - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result, LoadError> { - let load = self.inner.sstore_skip_cold_load(address, key, value, skip_cold_load)?; - self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); - Ok(load) - } - - /// Writes the slot and stages the write's values. - #[inline] - fn sstore( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - ) -> Option> { - let load = self.inner.sstore(address, key, value)?; - self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); - Some(load) - } - - /// Stages the log's topic count and data length, then appends it. - #[inline] - fn log(&mut self, log: Log) { - self.additional_limit.stage_record(StagedRecord::Log { - topics: log.topics().len() as u8, - data_len: log.data.data.len() as u64, - }); - self.inner.log(log); - } - - /// Destructs the account and stages whether value moved and where to, marking a read of the - /// block beneficiary's account when it is either end: the source's balance is read and - /// cleared, the target's read and credited. + /// Destructs the account, marking a read of the block beneficiary's account when it is either + /// end: the source's balance is read and cleared, the target's read and credited. #[inline] fn selfdestruct( &mut self, @@ -305,16 +286,220 @@ impl revm::context_interface::Host if volatile { self.detention.observe(VolatileDataAccess::BENEFICIARY_BALANCE); } - self.additional_limit.stage_record(StagedRecord::SelfDestruct { - had_value: load.data.had_value, - to_other_account: target != address, - beneficiary: target, - }); Ok(load) } + + /// Counts the record of a write an opcode completed on the running frame's pool, holds it to + /// the limits, and charges the frame the history it costs. revm calls it at the end of + /// `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT`, after every charge the opcode makes, so a write + /// the opcode's own failure takes back is never counted. + /// + /// The record is held to the limits first, and only then is its history charged: a record the + /// limit rejects is not kept, so its history is no charge, and the stop is what the frame + /// reports — a revert whose output is the stop's + /// [`MegaLimitExceeded`](crate::MegaLimitExceeded), on the frame's gas, so its caller resumes + /// as after any revert. A record the limit accepts is charged, and a charge the frame cannot + /// pay, or a byte count with no price, is an ordinary out-of-gas. + /// + /// A log's history is drawn from the frame's history allowance first, and the frame's gas pays + /// the rest ([`history_allowance_gas`](crate::history_allowance_gas)): a write record is the + /// frame's own to pay for, and a record taken back — a slot written back to its original + /// value, an account a `SELFDESTRUCT` returns to what the transaction loaded — gives back what + /// the frame's gas paid, never what an allowance did. Both sides are priced the same way, so a + /// record taken back cancels its own charge exactly, whichever frame made it: a refill below + /// zero is reconciled when the frame merges into its caller. A write that takes records back + /// and makes others is refilled before it is charged, so what it nets to nothing costs + /// nothing. + /// + /// The first effective `SELFDESTRUCT` of an account created in the transaction gives back every + /// part of it the transaction made ([`DestroyedParts`]) to the destroying frame, whichever + /// frame paid: what the parts take back is in the same check as what the operation adds, so + /// the positive effects are held after the give-back; once the check passed, each part's + /// state gas is refilled at the price it was charged, with the history of its records and of + /// its code, before the operation's own records are charged. From that mark an `SSTORE` of + /// one of the account's slots counts nothing, and the pricing hook prices its state gas at + /// nothing ([`state_gas_price`](revm::context_interface::Host::state_gas_price)). + /// + /// A completed `SSTORE` holds the frame to the compute limit again: a slot restored to its + /// original value refills the state gas (revm, before this hook) and the history gas (here) + /// that spilled onto regular gas, and the spill may predate the limit. + #[inline] + fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { + let (from_allowance, holds_again) = match write { + CompletedWrite::Sstore { .. } => (false, true), + CompletedWrite::Log { .. } => (true, false), + CompletedWrite::SelfDestruct { .. } => (false, false), + }; + let (counted, history, destroyed) = self.accounts().write_counted(&write); + let check = self.additional_limit.draw(gas, &counted); + if check.exceeded_limit() { + return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); + } + let state_given_back = match write { + CompletedWrite::SelfDestruct { address, .. } => destroyed + .as_ref() + .is_none_or(|parts| self.refill_destroyed_parts(address, parts, gas)), + CompletedWrite::Sstore { .. } | CompletedWrite::Log { .. } => true, + }; + if !state_given_back { + return WriteVerdict::OutOfGas; + } + if self.prices_history() { + let HistoryBytes { appended, taken } = history; + if taken != 0 { + gas.refill_history(history_gas(taken).unwrap_or(0)); + } + if let Some(parts) = &destroyed { + let code = usize::try_from(parts.code).unwrap_or(usize::MAX); + gas.refill_history(self.inner.cfg.gas_params.code_deposit_history_gas(code)); + } + if appended != 0 { + let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; + let cost = if from_allowance { gas.draw_history_allowance(cost) } else { cost }; + if !gas.record_history_cost(cost) { + return WriteVerdict::OutOfGas; + } + } + } + if holds_again { + self.detention.hold(gas); + } + WriteVerdict::Continue + } + + /// Charges the running frame the history of the write records the frame it is starting makes + /// — the accounts a value transfer changes from what the transaction loaded, a creation's + /// created account when the transaction had not changed it, and its creator's nonce — as the + /// journal's state stands ([`Accounts::start_records`](crate::limit::Accounts)). revm calls it + /// at `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, once the opcode + /// made every charge and took the gas it forwards, and before it builds the frame's input. + /// + /// It is a price, made at the opcode as revm charges a new account's gas at `CALL`, and counts + /// nothing: the records themselves are counted once revm decided the start, the frame's on the + /// pool it starts with and the creator's on the creator once the creation returned. + /// + /// The charge comes out of what the caller kept rather than out of what the callee gets, so + /// the frame's allowance is free for what the recipient does. What the frame's own records + /// cost is declared on the start ([`FrameStart::charge`]), which the fork carries on the + /// frame's input and gives back to the caller when the frame fails; the creator's record + /// outlives the creation and is not declared. The frame's input copies the caller's + /// reservoir after the charge, so the frame, or the answer revm gives in its place, + /// inherits the reservoir the charge left. An opcode that starts no frame — a creation the + /// balance, the nonce or the depth refuses, an out-of-gas before the forward — never calls + /// it, and makes no records; with EIP-8037 off, such a creation calls it without the address + /// it would take, which makes none either. A start revm then refuses — a value the caller + /// cannot fund, a frame past the call-stack limit — makes no records, and the charge comes + /// back when it returns, as does what a frame that ran did not keep. + /// + /// A charge the caller cannot pay, or a price that does not fit in a `u64`, fails the opcode + /// with an out-of-gas and starts no frame, even where revm would have refused the start. The + /// gas the opcode forwarded goes back to the caller first, so the halt burns it with the rest: + /// the frame never ran, and gas detention must not count the forward as compute. The halt's + /// record of what the frame had, which detention reads where the frame ends, is written again + /// once the forward is back: a failed charge recorded the gas left after the forward was + /// taken, and a price that could not be computed failed before any charge. + #[inline] + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + let charge = if self.prices_history() { + let records = + self.accounts().start_records(start.kind, start.caller, start.target, start.value); + let on_frame = records.on_frame().added; + let creator = u64::from(records.creator); + let Some((charge, _)) = charge_write_records_history(gas, on_frame, creator) else { + gas.erase_cost(start.forward); + gas.set_failed_charge_remaining(Some(gas.remaining())); + return false; + }; + charge + } else { + 0 + }; + start.charge = StartCharge::new(charge, PoolAmounts::ZERO); + true + } } impl MegaContext { + /// Prices one EIP-8037 state gas unit `id` at `site`, scaling the schedule's entry by the SALT + /// bucket capacity of the account — or, for a slot-scoped entry, of the storage slot — the + /// charge lands on. + /// + /// `state gas = schedule entry x m`, where `m` is the bucket's capacity in minimum buckets. + /// A charge in a minimum-capacity bucket pays the schedule's own number, and a charge in a + /// bucket eight times as large pays eight times as much: state that crowds a region of the + /// trie costs what it makes everyone else pay to carry it. Only the state dimension scales; + /// regular gas is never touched by `m`. + /// + /// Two charges are priced without reading SALT at all: an entry the schedule prices at zero, + /// which `m` cannot move off zero, and every charge of a system-originated transaction, + /// which prices at the minimum bucket by rule (see + /// [`is_system_originated`](crate::MegaContext::is_system_originated)). + /// + /// Reporting nothing is how a failed capacity lookup travels: the cause is recorded in the + /// context error the way [`Host::sload`](revm::context_interface::Host::sload) records a + /// database failure, and the charge site turns it into a bail-out that the transaction + /// surfaces as an error. A price the engine could not look up is never replaced by one + /// nobody chose. + fn priced_state_gas(&mut self, id: GasId, site: StateGasSite) -> Option { + let base = self.inner.cfg.gas_params.get(id); + if base == 0 || self.is_system_originated() { + return Some(base); + } + let multiplier = match site.slot { + Some(slot) => self.slot_bucket_multiplier(site.address, slot), + None => self.account_bucket_multiplier(site.address), + }; + match multiplier { + Ok(multiplier) => Some(base.saturating_mul(multiplier)), + Err(error) => { + *self.error() = + Err(ContextError::Custom(format!("SALT bucket lookup failed: {error}"))); + None + } + } + } + + /// Refills on `gas`, the destroying frame's, the state gas of the `parts` of the account at + /// `address` its first effective destruction gives back, each at the price it was charged: + /// the leaf's new account, the code deposit's bytes and each slot made non-zero, priced at the + /// site the charge landed on, so SALT gives back what it scaled. The leaf was charged once as a + /// new account, by whichever site made it — a value transfer, a `SELFDESTRUCT`'s balance, the + /// transaction's value, or the creation itself — and every such charge is the same entry. The + /// account is destroyed by now, which the pricing hook prices at nothing, so the parts are + /// priced as they were charged, before the mark ([`priced_state_gas`](Self::priced_state_gas)). + /// + /// Nothing is refilled where the transaction's state gas is not the spec's: the neutral + /// configuration prices as the fixture's fork does, and EIP-8037 gives back nothing for this + /// destruction. `false` when a price could not be looked up, whose cause is recorded and fails + /// the transaction. + fn refill_destroyed_parts( + &mut self, + address: Address, + parts: &DestroyedParts, + gas: &mut GasTracker, + ) -> bool { + if !self.destruction_table_prices_state_gas() { + return true; + } + debug_assert_eq!( + self.inner.cfg.gas_params.get(GasId::new_account_state_gas()), + self.inner.cfg.gas_params.get(GasId::create_state_gas()), + "a leaf a creation charged comes back at the price of one a transfer charged" + ); + let account = StateGasSite::account(address); + let leaf = parts.leaf.then(|| StateGasCharge::one(GasId::new_account_state_gas(), account)); + let code = (parts.code != 0) + .then(|| StateGasCharge::units(GasId::code_deposit_state_gas(), account, parts.code)); + let slots = parts.slots.iter().map(|&key| { + StateGasCharge::one(GasId::sstore_set_state_gas(), StateGasSite::slot(address, key)) + }); + for charge in leaf.into_iter().chain(code).chain(slots) { + let Some(price) = self.priced_state_gas(charge.id, charge.site) else { return false }; + gas.refill_reservoir(charge.total(price)); + } + true + } + /// Reads the block-environment field `access` stands for: `false` when the read is refused, /// and the accessor answers zero instead of the field. #[inline] @@ -395,11 +580,12 @@ mod tests { use alloy_primitives::{address, Bytes}; use revm::context::JournalTr; - /// The Host stages what each state-writing call observed and counts nothing: counting is the - /// opcode wrapper's, after the opcode completed. + /// The Host's write methods count nothing, whoever calls them — an opcode, or a tool such as + /// an inspector appending a log in its `step`: a write is counted once its opcode completed, + /// through the completed-write hook, which only revm's write instructions call. #[test] - fn test_host_stages_observations_and_counts_nothing() { - use crate::{test_utils::MemoryDatabase, MegaSpecId}; + fn test_host_writes_count_nothing() { + use crate::{test_utils::MemoryDatabase, LimitUsage, MegaSpecId, WRITE_RECORD_SIZE}; use revm::{context_interface::Host, primitives::LogData}; const CONTRACT: Address = address!("00000000000000000000000000000000000000c1"); @@ -409,40 +595,27 @@ mod tests { ctx.inner.journaled_state.load_account(CONTRACT).unwrap(); let slot = Host::sstore(&mut ctx, CONTRACT, U256::from(1), U256::from(9)).unwrap(); - assert_eq!( - ctx.additional_limit.staged_record(), - Some(&StagedRecord::Sstore(slot.data.clone())), - "the non-Berlin entry point stages too" - ); assert_eq!(slot.data.new_value, U256::from(9)); - let slot = - Host::sstore_skip_cold_load(&mut ctx, CONTRACT, U256::from(1), U256::from(4), false) - .unwrap(); - assert_eq!(ctx.additional_limit.staged_record(), Some(&StagedRecord::Sstore(slot.data))); - + Host::sstore_skip_cold_load(&mut ctx, CONTRACT, U256::from(2), U256::from(4), false) + .unwrap(); let log = Log { address: CONTRACT, data: LogData::new(vec![B256::ZERO, B256::ZERO], Bytes::from_static(b"abc")).unwrap(), }; Host::log(&mut ctx, log); - assert_eq!( - ctx.additional_limit.staged_record(), - Some(&StagedRecord::Log { topics: 2, data_len: 3 }) - ); + let destructed = Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); + assert!(destructed.data.had_value); + assert_eq!(ctx.limit_usage(), LimitUsage::ZERO, "the Host counts nothing"); - Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); - assert_eq!( - ctx.additional_limit.staged_record(), - Some(&StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary: BENEFICIARY, - }) - ); + // The hook is what counts: the slot's first change is one write record, and a slot made + // non-zero from an original of zero is one of state growth. + let mut gas = GasTracker::new(1_000_000, 1_000_000, 0); + let write = + CompletedWrite::Sstore { address: CONTRACT, key: U256::from(1), result: &slot.data }; + assert_eq!(Host::write_completed(&mut ctx, write, &mut gas), WriteVerdict::Continue); assert_eq!( - ctx.additional_limit.usage(), - crate::LimitUsage::ZERO, - "the Host counts nothing" + ctx.limit_usage(), + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1, state_growth: 1 } ); } } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs deleted file mode 100644 index 88d30da55..000000000 --- a/crates/mega-evm/src/evm/inspector.rs +++ /dev/null @@ -1,670 +0,0 @@ -//! What an inspector may do to a Satin transaction, and what its rewrites do not change. -//! -//! An inspector is not a passive observer. A callback holding a live interpreter can write to its -//! gas and its pending action, a callback holding a frame's inputs can change them or answer the -//! frame itself, and every `*_end` callback can rewrite a result's classification, gas and output. -//! Satin keeps no ledger beside revm's `Gas` (compute is the regular gas spent), so an inspector -//! that changes the gas changes what the transaction owes, and a rewriting inspector gets what it -//! asked for, within the bounds below. Rewriting is a tool feature — Foundry's cheatcodes are built -//! on it — supported and unmeasured. -//! -//! # Where an inspector runs -//! -//! - **A user transaction** runs every callback: `initialize_interp`, `step` and `step_end`, -//! `log_full`, `log` for what a frame journals without running an instruction (an EIP-7708 -//! transfer log, a precompile's logs), `frame_start` and `frame_end`, `call` and `call_end`, -//! `create` and `create_end`, and `selfdestruct`. A keyless deployment is seen as the frames it -//! is made of: its `keylessDeploy` call, which runs no instruction and so gets no -//! `initialize_interp` and no step, and the creation below it. The inspector may rewrite anything -//! outside block execution, within the bounds below. -//! - **A system transaction** — a system-address transaction, promoted to a deposit before its -//! first callback — runs through the same handler and the same callbacks, and may be rewritten -//! the same way. It is the protocol's own work, held to no per-transaction limit, so no limit -//! stops any of its frames. -//! - **A pre-block system call** — the EIP-2935 and EIP-4788 calls, and the `SequencerRegistry`'s -//! `applyPendingChanges()` — runs on the handler's plain system-call path, as alloy-evm's -//! `transact_system_call` runs one: no callback, whatever inspector the EVM holds, so a block's -//! tracer sees the block's transactions and nothing of its preparation. A tool that wants to -//! watch a system call runs it through revm's `InspectSystemCallEvm`, which does hand it to the -//! inspector, with every exemption a system call has. -//! - **The end of a block** runs no code: the post-block balance increments are database writes. No -//! callback runs, and the EVM handed back carries the inspector with what it collected. -//! -//! # The admission gate -//! -//! [`TrustedObserver`] is a declaration, made in source about one inspector type, that none of its -//! callbacks writes anything back. A [`MegaEvm`](crate::MegaEvm) built with -//! [`with_trusted_inspector`](crate::MegaEvm::with_trusted_inspector) carries the declaration, and -//! [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what block execution -//! refuses on: a rewriting inspector has no route to a block. [`DeclaredObserver`] carries the -//! declaration for a tracer whose type cannot, and in debug builds checks it around every callback. -//! -//! Block execution checks the gate before anything changes wherever an outcome is produced or -//! chosen: the pre-block changes, the execution of a transaction — a system transaction as a user -//! one — the end of the block, and -//! [`commit_transaction_outcome`](crate::MegaBlockExecutor::commit_transaction_outcome), the commit -//! of an outcome a builder chose among candidates. 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, which passed the gate before it ran and which no inspector enabled since can reach. -//! So a declared observer sees the block's transactions, user and system alike, and a rewriting -//! inspector sees nothing of a block: it is refused before the pre-block calls, which it would not -//! run on anyway, and before any transaction. -//! -//! # What a rewrite does not change -//! -//! - **A frame that kept nothing.** A frame the 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 — Foundry's `expectRevert` -//! turns a failed call into a success — the caller sees the success, the output and the regular -//! gas the inspector chose, and nothing else of the frame: no state or history gas, no refund and -//! no write record for writes the journal does not hold, and the upfront state gas its caller's -//! opcode was charged for an account the frame did not add comes back, at the price of the -//! account it was charged for: a call whose target the inspector's `call` hook rewrote gives the -//! charge back as recorded before the hook ran. A creation revived this way hands its creator the -//! address the inspector gave, with nothing deployed there. -//! - **A success rewritten into a failure keeps nothing either.** A frame the inspector turns from -//! a success into a failure — Foundry's `expectRevert` on a call that did not revert — has its -//! journal taken back to its checkpoint, as revm takes back a frame that fails: the frame's own, -//! or, for a start revm answers without building a frame (a call to a precompile or to an account -//! with no code), where the start began. So the state follows the failure its ledgers settle as: -//! no account, slot, code, value moved or log of the frame's is kept, and a creation keeps its -//! creator's nonce bump, which revm makes before the creation's checkpoint, as one that fails -//! does. Everything journaled since the checkpoint goes, what the inspector itself wrote to the -//! journal during the frame or in the callback that rewrote its result included; where revm fails -//! a frame the checkpoint is gone before `call_end`, so a write made there stays. The journal's -//! depth is left as it was. -//! -//! A limit stop is the revert of the frame that crossed the limit, and a rewrite of it is a -//! rewrite of a failure like any other: it settles as above, and the transaction reports no stop -//! once the result of its own frame is no longer the stop's revert. Every other rewrite is the -//! tool's business. -//! -//! # What an inspector's writes to gas cannot do -//! -//! - **Gas changed at a frame's end has no effect.** The instruction that ends a frame copies the -//! frame's gas into the result it returns, so what `step_end` writes to the interpreter's gas -//! after it reaches nobody. A tool that changes what a frame returns changes its result, in -//! `call_end`, `create_end` or `frame_end`: that gas is what the caller, or the transaction's -//! settlement, takes in. -//! - **An inspector cannot overdraw a frame.** A charge the frame's spendable gas cannot pay is -//! refused and takes nothing, and the frame is not halted: the interpreter does not ask the -//! callback what it did. A tool that wants a frame out of gas says so through its result. Under -//! gas detention the refusal of an opcode's charge the withheld part would have paid is the -//! crossing; the refusal of an inspector's is not, and classifies nothing ([`StepGuard`]). -//! - **Gas an inspector puts back carries the split it was taken with.** The part gas detention -//! withholds is in the frame's `Gas`, and detention sets it where it can have moved: at a read of -//! volatile data, when the frame starts or resumes, and after an `SSTORE`. An inspector that -//! overwrites the interpreter's gas — Foundry's `pauseGasMetering` puts a snapshot back before -//! every instruction — overwrites the split with it, and the frame runs on the snapshot's split -//! until detention next sets it. Only the crossing record is kept from a callback's write. -//! - **An answer carries only the regular gas the inspector chose.** A frame the inspector answered -//! never ran, so it drew nothing from the reservoir: whatever `Gas` the answer is built on — -//! `Gas::new(limit)`, as Foundry answers a cheatcode, carries no reservoir — its caller merges -//! back the reservoir it forwarded, and none of the state gas, history gas or refund the answer -//! carries. The gas of a result a frame ran to produce is the inspector's to rewrite, reservoir -//! included. - -use revm::{ - context::{ContextTr, JournalTr}, - context_interface::{cfg::StateGasCharge, journaled_state::JournalCheckpoint, Host}, - handler::FrameResult, - inspector::{handler::frame_end, JournalExt, NoOpInspector}, - interpreter::{ - CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, - Interpreter, InterpreterTypes, - }, - primitives::{Address, Bytes, Log, U256}, - Database, Inspector, -}; - -use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext}; - -/// A declaration, made in source about one inspector type, that none of its callbacks writes -/// anything back to the EVM: nothing to an interpreter's gas or pending action, nothing to a -/// frame's inputs, nothing to a result's classification, gas or output, and no frame answered -/// itself. It may read anything and write its own state. -/// -/// The declaration is what block execution admits an inspected transaction on. -/// -/// - Implement it for one concrete type at a time, never as a blanket implementation, so each -/// declaration is a line someone wrote about a type they had read. -/// - Do not implement it for an inspector that answers a frame, edits inputs or rewrites a result, -/// however rarely. -/// - A foreign inspector type (a `revm-inspectors` tracer) is wrapped in [`DeclaredObserver`], -/// which is local here and carries the declaration. -/// - The test utilities' inspectors are not declared: they are not part of the gate. -pub trait TrustedObserver {} - -/// The inspector an EVM runs with when none was given observes nothing. -impl TrustedObserver for NoOpInspector {} - -/// A declared observer lent by reference stays declared: `&mut T` is declared exactly when `T` -/// is. -impl TrustedObserver for &mut T {} - -/// Carries a [`TrustedObserver`] declaration for an inspector whose type cannot carry one. -/// -/// It forwards every callback to the inspector inside and adds nothing. `DeclaredObserver(tracer)` -/// says "this tracer writes nothing back", moved from a type definition to the line that wraps -/// the value. -/// -/// A debug build checks the declaration around every callback and panics at the one that breaks -/// it: the interpreter's gas, pending action, stack depth and memory size, the frame's inputs, -/// the frame result, and the journal's entries and logs must be as they were, and no frame may be -/// answered. Writes the check cannot see (a stack word replaced in place, a context field outside -/// the journal) are still false declarations; the check is a tripwire, not a proof. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct DeclaredObserver(pub I); - -impl DeclaredObserver { - /// Declares `inspector` a read-only observer. - pub const fn new(inspector: I) -> Self { - Self(inspector) - } - - /// The inspector inside. - pub fn into_inner(self) -> I { - self.0 - } -} - -impl TrustedObserver for DeclaredObserver {} - -impl Inspector for DeclaredObserver -where - I: Inspector, - CTX: ContextTr, - INTR: InterpreterTypes, -{ - #[inline] - fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = snapshot(interp, context); - self.0.initialize_interp(interp, context); - assert_unwritten(before, interp, context, "initialize_interp"); - } - - #[inline] - fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = snapshot(interp, context); - self.0.step(interp, context); - assert_unwritten(before, interp, context, "step"); - } - - #[inline] - fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = snapshot(interp, context); - self.0.step_end(interp, context); - assert_unwritten(before, interp, context, "step_end"); - } - - #[inline] - fn log(&mut self, context: &mut CTX, log: Log) { - let before = journal_snapshot(context); - self.0.log(context, log); - assert_journal_unwritten(before, context, "log"); - } - - #[inline] - fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let before = snapshot(interp, context); - self.0.log_full(interp, context, log); - assert_unwritten(before, interp, context, "log_full"); - } - - #[inline] - fn frame_start( - &mut self, - context: &mut CTX, - frame_input: &mut FrameInput, - ) -> Option { - let before = - cfg!(debug_assertions).then(|| (frame_input.clone(), journal_snapshot(context))); - let answer = self.0.frame_start(context, frame_input); - debug_assert!(answer.is_none(), "a declared observer answered a frame in `frame_start`"); - if let Some((input, journal)) = before { - debug_assert!(&input == frame_input, "a declared observer rewrote a frame's inputs"); - assert_journal_unwritten(journal, context, "frame_start"); - } - answer - } - - #[inline] - fn frame_end( - &mut self, - context: &mut CTX, - frame_input: &FrameInput, - frame_result: &mut FrameResult, - ) { - let before = result_snapshot(frame_result); - let journal = journal_snapshot(context); - self.0.frame_end(context, frame_input, frame_result); - assert_result_unwritten(before, frame_result, "frame_end"); - assert_journal_unwritten(journal, context, "frame_end"); - } - - #[inline] - fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { - let before = cfg!(debug_assertions).then(|| inputs.clone()); - let journal = journal_snapshot(context); - let answer = self.0.call(context, inputs); - debug_assert!(answer.is_none(), "a declared observer answered a call"); - if let Some(before) = before { - debug_assert!(&before == inputs, "a declared observer rewrote a call's inputs"); - } - assert_journal_unwritten(journal, context, "call"); - answer - } - - #[inline] - fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { - let before = cfg!(debug_assertions).then(|| outcome.clone()); - let journal = journal_snapshot(context); - self.0.call_end(context, inputs, outcome); - if let Some(before) = before { - debug_assert!(&before == outcome, "a declared observer rewrote a call result"); - } - assert_journal_unwritten(journal, context, "call_end"); - } - - #[inline] - fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { - let before = cfg!(debug_assertions).then(|| inputs.clone()); - let journal = journal_snapshot(context); - let answer = self.0.create(context, inputs); - debug_assert!(answer.is_none(), "a declared observer answered a creation"); - if let Some(before) = before { - debug_assert!(&before == inputs, "a declared observer rewrote a creation's inputs"); - } - assert_journal_unwritten(journal, context, "create"); - answer - } - - #[inline] - fn create_end( - &mut self, - context: &mut CTX, - inputs: &CreateInputs, - outcome: &mut CreateOutcome, - ) { - let before = cfg!(debug_assertions).then(|| outcome.clone()); - let journal = journal_snapshot(context); - self.0.create_end(context, inputs, outcome); - if let Some(before) = before { - debug_assert!(&before == outcome, "a declared observer rewrote a creation result"); - } - assert_journal_unwritten(journal, context, "create_end"); - } - - #[inline] - fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { - self.0.selfdestruct(contract, target, value); - } -} - -/// Hands a running frame's instruction-loop callbacks to the inspector inside, and keeps what they -/// do to the interpreter's gas from classifying the frame. -/// -/// A regular charge the frame's spendable gas cannot pay is refused, and when the part gas -/// detention withholds would have paid it the refusal is recorded as the crossing, which stops the -/// transaction at the compute limit when the frame ends. An opcode's refused charge halts the -/// frame at once, so its record is the frame's end. An inspector's does not: the interpreter never -/// sees it fail and the frame runs on. So the record a callback leaves is put back to what it was -/// before the callback, and the frame ends on the charges it made itself. -/// -/// It stands in for the inspector in revm's instruction loop alone (`inspect_instructions`), which -/// makes the four callbacks forwarded here and no other; frame starts and ends reach the inspector -/// itself. The other callbacks are left to the trait's no-op defaults rather than forwarded, -/// because the loop never makes them and a forward nothing reaches is one nothing tests. So a -/// callback the loop gains in a later revision of the fork reaches no inspector until it is -/// forwarded here: a fork upgrade checks the loop's callbacks against this list. -pub(crate) struct StepGuard<'a, I>(pub(crate) &'a mut I); - -impl Inspector for StepGuard<'_, I> -where - I: Inspector, - INTR: InterpreterTypes, -{ - #[inline] - fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let crossing = interp.gas.withheld_crossing(); - self.0.step(interp, context); - interp.gas.set_withheld_crossing(crossing); - } - - #[inline] - fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let crossing = interp.gas.withheld_crossing(); - self.0.step_end(interp, context); - interp.gas.set_withheld_crossing(crossing); - } - - #[inline] - fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let crossing = interp.gas.withheld_crossing(); - self.0.log_full(interp, context, log); - interp.gas.set_withheld_crossing(crossing); - } - - #[inline] - fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { - self.0.selfdestruct(contract, target, value); - } -} - -/// The journal's entry and log counts, for the debug-build proof. `None` in release builds. -type JournalSnapshot = Option<(usize, usize)>; - -#[inline] -fn journal_snapshot>(context: &CTX) -> JournalSnapshot { - cfg!(debug_assertions) - .then(|| (context.journal_ref().journal().len(), context.journal_ref().logs().len())) -} - -#[inline] -fn assert_journal_unwritten>( - before: JournalSnapshot, - context: &CTX, - callback: &str, -) { - if let Some(before) = before { - debug_assert_eq!( - before, - journal_snapshot(context).expect("debug build"), - "a declared observer wrote to the journal in `{callback}`" - ); - } -} - -/// An interpreter's and the journal's state, for the debug-build proof. -type Snapshot = (GasSnapshot, JournalSnapshot); - -#[inline] -fn snapshot>( - interp: &Interpreter, - context: &CTX, -) -> Snapshot { - (gas_snapshot(interp), journal_snapshot(context)) -} - -#[inline] -fn assert_unwritten>( - (gas, journal): Snapshot, - interp: &Interpreter, - context: &CTX, - callback: &str, -) { - assert_gas_unwritten(gas, interp, callback); - assert_journal_unwritten(journal, context, callback); -} - -/// An interpreter's gas, pending action, stack depth and memory size, for the debug-build proof. -/// `None` in release builds. -type GasSnapshot = Option<(revm::interpreter::Gas, bool, usize, usize)>; - -#[inline] -fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { - use revm::interpreter::interpreter_types::{LoopControl, MemoryTr, StackTr}; - cfg!(debug_assertions) - .then(|| (interp.gas, interp.bytecode.is_end(), interp.stack.len(), interp.memory.size())) -} - -#[inline] -fn assert_gas_unwritten( - before: GasSnapshot, - interp: &Interpreter, - callback: &str, -) { - if let Some(before) = before { - debug_assert_eq!( - before, - gas_snapshot(interp).expect("debug build"), - "a declared observer wrote to the interpreter in `{callback}`" - ); - } -} - -/// A frame result's classification, gas and output, and a creation's address, for the -/// debug-build proof. -type ResultSnapshot = Option<(revm::interpreter::InterpreterResult, Option
)>; - -#[inline] -fn result_snapshot(result: &FrameResult) -> ResultSnapshot { - cfg!(debug_assertions).then(|| { - let address = match result { - FrameResult::Call(_) => None, - FrameResult::Create(outcome) => outcome.address, - }; - (result.interpreter_result().clone(), address) - }) -} - -#[inline] -fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callback: &str) { - if let Some(before) = before { - debug_assert!( - before == result_snapshot(result).expect("debug build"), - "a declared observer rewrote a frame result in `{callback}`" - ); - } -} - -/// What the calling opcode charged upfront for a call, as it stood before the inspector could see -/// the call: whether it charged the new-account state gas, and for which address. -/// -/// An inspector's `call` hook holds the call's inputs mutably, and a rewritten target would -/// otherwise be the address the charge is given back at, priced in another SALT bucket than the one -/// it was made in. The record is taken before `frame_start` and written into the frame's result -/// when the frame ends, whatever produced the result. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct UpfrontRecord { - charged_new_account_state_gas: bool, - charged_state_gas_address: Address, -} - -impl UpfrontRecord { - /// The record of the call `input` starts; none for any other frame, whose creation inputs keep - /// what they charged and where in fields an inspector's hook cannot write. - pub(crate) fn of(input: &FrameInput) -> Option { - match input { - FrameInput::Call(inputs) => Some(Self { - charged_new_account_state_gas: inputs.charged_new_account_state_gas, - charged_state_gas_address: inputs.target_address, - }), - _ => None, - } - } - - /// `input` with the call's upfront charge as the record has it. - fn restore(self, input: &FrameInput) -> FrameInput { - let mut input = input.clone(); - if let FrameInput::Call(inputs) = &mut input { - inputs.charged_new_account_state_gas = self.charged_new_account_state_gas; - inputs.target_address = self.charged_state_gas_address; - } - input - } -} - -/// Where the result [`frame_end_checked`] hands the inspector came from. -#[derive(Clone, Copy, Debug)] -pub(crate) enum ResultSource { - /// The inspector answered the frame in place of running it: nothing of the frame is in the - /// journal. - Inspector, - /// The engine produced it — a frame that ran, or a start revm or the engine answered without - /// building a frame — and what the frame journaled begins at the checkpoint: the frame's own, - /// or where the journal stood when the start began. - Engine(JournalCheckpoint), -} - -/// Hands a frame's end to the inspector, then settles what its rewrite does not change. -/// -/// - **A frame that kept nothing.** A frame the inspector answered in place of running, and a frame -/// that failed before the inspector saw it, made no write the journal kept. Whatever the -/// inspector left the result saying, it settles into its caller as such a frame does -/// ([`settle_kept_nothing`]). -/// - **A success rewritten into a failure.** The journal follows the result: what the frame -/// journaled is taken back to its checkpoint, as revm takes back a frame that fails, so the state -/// holds none of the writes the failure's settlement bills nothing for. A frame the inspector -/// answered journaled nothing, so nothing is taken back for it. -/// -/// Every place a frame result reaches the inspector goes through here, so both cover a result -/// a frame ran to produce and one answered without running. -#[inline] -pub(crate) fn frame_end_checked( - context: &mut MegaContext, - inspector: &mut INSP, - frame_input: &FrameInput, - frame_result: &mut FrameResult, - depth: usize, - source: ResultSource, - upfront: Option, -) where - DB: Database, - ExtEnvs: ExternalEnvTypes, - INTR: InterpreterTypes, - INSP: Inspector, INTR, FrameInput, FrameResult>, -{ - let before = frame_result.instruction_result(); - frame_end(context, inspector, frame_input, frame_result); - // What the opcode charged is what was recorded before the inspector saw the call, not what its - // hooks left in the inputs. - let restored = upfront.and_then(|record| { - (UpfrontRecord::of(frame_input) != Some(record)).then(|| record.restore(frame_input)) - }); - let frame_input = restored.as_ref().unwrap_or(frame_input); - if upfront.is_some() { - carry_upfront_flags(frame_input, frame_result); - } - let answered = match source { - ResultSource::Inspector => true, - ResultSource::Engine(checkpoint) => { - if before.is_ok() && !frame_result.instruction_result().is_ok() { - revert_journal_to(context, checkpoint); - } - false - } - }; - if answered || !before.is_ok() { - settle_kept_nothing(context, frame_input, frame_result, depth, answered); - } -} - -/// Settles the result of a frame at `depth` that kept nothing in the journal — one an inspector -/// answered in place of running, or one whose checkpoint was reverted before the inspector saw its -/// result — as such a frame settles, whatever the inspector made of the result. -/// -/// The calling opcode's upfront state-gas charge — the account a value call adds, the account a -/// creation adds, or EIP-2780's for the transaction's own frame — is given back: the frame added -/// no account. The result carries the frame's own upfront-charge flags again, so a result that -/// fails gets it back from revm's settlement, as revm's own do; one an inspector answered carries -/// none of them otherwise. -/// -/// A frame the inspector answered (`answered`) never ran, so it drew nothing from its pools: its -/// answer's gas carries nothing but the regular gas the inspector chose. Whatever `Gas` the answer -/// was built on — `Gas::new(limit)`, which carries no reservoir, or one carrying charges — its -/// state and history charges are rolled back, its refund is dropped, and its reservoir is the one -/// the frame inherited, so its caller merges back the reservoir it forwarded. The rollback comes -/// first: it unwinds the charges against the answer's own reservoir, which the inherited one then -/// replaces, so a charge the answer carries is counted neither in the reservoir nor on a ledger. -/// -/// A result that says success is not one revm's settlement treats as keeping nothing, so it is made -/// to settle like the failure it stands for, save what the inspector chose — the success its caller -/// sees, the output, the regular gas: -/// -/// - its state and history charges are rolled back and its refunds dropped, as a failure's are, -/// before its caller merges them; -/// - the upfront charge comes back through it: the result holds it as state its frame gave back, as -/// a frame that restored a slot its caller filled does, and its caller's merge nets it out; -/// - for the transaction's own frame, the history of the write record charged before execution for -/// its start comes back the same way; -/// - its lane is discarded as a failure's is, so nothing it counted reaches its caller, which gets -/// back the history it paid for the records. -fn settle_kept_nothing( - context: &mut MegaContext, - input: &FrameInput, - result: &mut FrameResult, - depth: usize, - answered: bool, -) { - carry_upfront_flags(input, result); - let success = result.instruction_result().is_ok(); - let gas = result.gas_mut(); - if answered || success { - gas.rollback_state_gas(); - gas.set_refunded(0); - } - if answered { - gas.set_reservoir(inherited_reservoir(input)); - } - if !success { - return; - } - // A creation answered with a success and no address is one revm's settlement gives the - // charge back for itself. - let upfront = upfront_charge(input).filter(|_| result.refundable_state_gas_charge().is_none()); - // A failed lookup records its cause, which fails the transaction before the result settles. - let upfront = upfront.map_or(Some(0), |charge| context.state_gas_charge(charge)); - let history = - if depth == 0 { context.additional_limit.top_level_write_record_gas() } else { 0 }; - let gas = result.gas_mut(); - gas.refill_reservoir(upfront.unwrap_or_default()); - gas.refill_history(history); - context.additional_limit.discard_returning_lane(); -} - -/// Where the journal stands: the checkpoint a frame starting now would take, taken without -/// changing the journal's depth. -#[inline] -pub(crate) fn journal_position( - context: &mut MegaContext, -) -> JournalCheckpoint { - let journal = context.journal_mut(); - let checkpoint = journal.checkpoint(); - journal.checkpoint_commit(); - checkpoint -} - -/// Takes back every journal entry, log and self-destruct made since `checkpoint`, as revm takes -/// back a frame that fails, and leaves the journal's depth as it is: the frame's own checkpoint was -/// already closed, so one is opened for the revert to close. -pub(crate) fn revert_journal_to( - context: &mut MegaContext, - checkpoint: JournalCheckpoint, -) { - let journal = context.journal_mut(); - let _ = journal.checkpoint(); - journal.checkpoint_revert(checkpoint); -} - -/// Sets `result`'s upfront-charge flags to those of `input`, the frame it answers: what revm's -/// settlement reads to give the calling opcode's upfront state-gas charge back. -fn carry_upfront_flags(input: &FrameInput, result: &mut FrameResult) { - match (input, result) { - (FrameInput::Call(inputs), FrameResult::Call(outcome)) => { - outcome.charged_new_account_state_gas = inputs.charged_new_account_state_gas; - outcome.charged_state_gas_address = inputs.target_address; - } - (FrameInput::Create(inputs), FrameResult::Create(outcome)) => { - outcome.charged_create_state_gas = inputs.charged_create_state_gas(); - outcome.charged_state_gas_address = inputs.charged_state_gas_address(); - } - _ => {} - } -} - -/// The reservoir the frame `input` starts inherits from its caller. -const fn inherited_reservoir(input: &FrameInput) -> u64 { - match input { - FrameInput::Call(inputs) => inputs.reservoir, - FrameInput::Create(inputs) => inputs.reservoir(), - FrameInput::Empty => 0, - } -} - -/// The upfront state-gas charge the calling opcode made for the frame `input` starts: the charge -/// revm's settlement gives back when that frame fails. -fn upfront_charge(input: &FrameInput) -> Option { - synthetic_frame_result(input, InstructionResult::Revert, Bytes::new()) - .refundable_state_gas_charge() -} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 7494f5e2c..2634d68eb 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,57 +1,41 @@ //! The instruction table of the Satin engine. //! -//! Every opcode runs revm's own instruction, except the ones that write state the resource -//! limits count. Three of them write it themselves — `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` -//! — and four write it by starting a frame: `CALL`, `CALLCODE`, `CREATE` and `CREATE2`. +//! Every opcode runs revm's own instruction, except the ones that can read volatile data. //! -//! The first three run in a wrapper that commits what the Host staged for them after the opcode -//! completed: -//! -//! 1. discard any record staged before the opcode (nothing may commit it for this one); -//! 2. run revm's instruction, whose Host call stages the record and which charges the state gas of -//! a fresh slot or a new beneficiary; -//! 3. discard the record if the opcode failed; if it completed, commit it; -//! 4. charge the frame the history gas of what the record appends — and give it back when the -//! record was taken away, as a slot written back to its original value takes its own back. -//! -//! The history a record costs is its data size, so the charge and the count cannot drift apart: -//! a log pays for its address, its topics and its data, a storage write or a destructed account's -//! beneficiary for the forty bytes of one write record. -//! -//! A commit that crosses a limit stops the opcode's frame with a revert whose output is -//! [`MegaLimitExceeded`](crate::MegaLimitExceeded), and its caller resumes as after any revert -//! (see [`AdditionalLimit`](crate::AdditionalLimit) for the stop). A history charge the frame -//! cannot pay is an ordinary out-of-gas, which burns the frame's gas the way any other does. -//! -//! The other four run in a wrapper that charges their frame for the write records the frame it -//! starts makes — a value transfer's sender and recipient, a creation's creator nonce and created -//! account — before the frame runs, so the gas it forwards is not reduced by them and its -//! allowance is free for what the recipient does. What the frame does not keep goes back to the -//! caller when it returns. The frame the opcode is suspending on carries the caller's reservoir, -//! which the charge has just moved, so the wrapper writes the reservoir it left into the frame's -//! input; and a caller that cannot pay the charge drops that frame before it fails, because an -//! interpreter halts on an instruction's error only when no frame is pending. +//! The opcodes that write state the resource limits count are revm's own, and are metered inside +//! revm's instructions, through two Host hooks (see the `host` module). Three write it themselves — +//! `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` — and revm calls the completed-write hook at the end +//! of each, once the write is in the journal and every charge the opcode makes has been made: the +//! Host counts the write, holds it to the limits and charges the history it costs there, and a +//! failed opcode never reaches the hook, so it counts nothing. Four write it by starting a frame — +//! `CALL`, `CALLCODE`, `CREATE` and `CREATE2` — and revm calls the frame-start hook at every call +//! and creation, once the opcode took the gas it forwards and before it builds the frame's input: +//! the Host charges the caller the history of the write records the start makes there, so the +//! frame inherits the reservoir the charge left, and a caller that cannot pay starts no frame. //! //! Every opcode that can read volatile data — the block-environment opcodes, the account opcodes, //! `SLOAD`, the four calls and `SELFDESTRUCT` — runs in a wrapper that settles the reads its Host //! calls made (see the `access` module): //! -//! 1. discard any read observed or refused before the opcode; -//! 2. keep the frame's gas, when the frame's reads are refused; -//! 3. run the instruction (or the wrapper above it), whose Host calls observe or refuse the reads; -//! 4. on a refusal, hand the frame back the gas it had before the opcode and revert it with +//! 1. keep the frame's gas, when the frame's reads are refused; +//! 2. run revm's instruction as a read, whose Host calls observe or refuse the reads; +//! 3. on a refusal, hand the frame back the gas it had before the opcode and revert it with //! `VolatileDataAccessDisabled`; otherwise, once the opcode completed, commit the reads, which //! holds the frame's spendable gas to what the compute limit leaves it. //! -//! `SSTORE` also holds its frame to the compute limit again once it completed: a slot restored to -//! its original value refills regular gas. +//! The Host observes or refuses a load only while a wrapper runs its opcode. `CREATE` and +//! `CREATE2` are not wrapped: they load their creator's account and the created address's through +//! the Host, to check the creator's balance and nonce and to price the created account, and those +//! loads are no volatile reads, neither refused nor marked, whichever of the two accounts is the +//! block beneficiary's: a value call's check of its caller's balance is no read either. //! //! An opcode whose charge fails with an out-of-gas halts its frame, and the halt zeroes the gas -//! the frame had left before the frame returns. Every wrapper above notes that gas for gas -//! detention first, which does not count what a halt burns as compute; so does a wrapper around -//! the opcodes whose own charge has no bound, `KECCAK256` and the four copies into memory, and -//! around `EXP`, whose exponent charge reaches 1,600. The one charge no wrapper sees is an -//! opcode's static gas, which the interpreter's step loop makes before the opcode runs. +//! the frame had left before the frame returns. The revm fork records that gas 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; +//! gas detention reads the record where the frame ends, and does not count what a halt burns as +//! compute. The one hook that writes the record itself is the frame-start hook, when the caller +//! cannot pay a start: it hands the forward back to the caller first. //! //! A wrapper keeps the static gas the table charges for its opcode, so the gas schedule is //! unchanged. The static gas table is Amsterdam's ([`satin_gas_table`]). @@ -64,31 +48,29 @@ use revm::{ bytecode::opcode::{ - BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, CALLDATACOPY, CODECOPY, COINBASE, - CREATE, CREATE2, DELEGATECALL, DIFFICULTY, EXP, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, - GASLIMIT, KECCAK256, LOG0, LOG1, LOG2, LOG3, LOG4, MCOPY, NUMBER, RETURNDATACOPY, - SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, TIMESTAMP, + BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, COINBASE, DELEGATECALL, + DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, NUMBER, SELFBALANCE, + SELFDESTRUCT, SLOAD, SLOTNUM, STATICCALL, TIMESTAMP, }, context_interface::Host, handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{arithmetic, block_info, contract, host, memory, system}, + instructions::{block_info, contract, host}, interpreter::EthInterpreter, interpreter_types::LoopControl, FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, InterpreterAction, }, - primitives::{hardfork::SpecId, Bytes}, + primitives::hardfork::SpecId, Database, }; use crate::{ - charge_write_records_history, history_gas, limit::HistoryBytes, volatile_data_access_disabled_revert_data, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; -use super::{caller_refuses_start, satin_gas_table, MegaInstructions}; +use super::{input_gas_limit, satin_gas_table, value_call_stipend, MegaInstructions}; /// The context an instruction of the Satin engine runs with. type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, EthInterpreter>; @@ -96,29 +78,20 @@ type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, Eth /// An instruction of the Satin engine. type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; -/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated, -/// the opcodes that write state the limits count wrapped, and the opcodes that can read volatile -/// data wrapped, on the Satin static gas table. +/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated and +/// the opcodes that can read volatile data wrapped, on the Satin static gas table. pub(crate) fn mega_instructions( spec: SpecId, ) -> MegaInstructions { let mut table = instruction_table(); enable_amsterdam_opcodes(&mut table); let mut instructions = EthInstructions::new(table, satin_gas_table(), spec); - let wrappers: [(u8, InstructionFn); 34] = [ - (SSTORE, sstore::), - (LOG0, log::<0, DB, ExtEnvs>), - (LOG1, log::<1, DB, ExtEnvs>), - (LOG2, log::<2, DB, ExtEnvs>), - (LOG3, log::<3, DB, ExtEnvs>), - (LOG4, log::<4, DB, ExtEnvs>), + let wrappers: [(u8, InstructionFn); 20] = [ (SELFDESTRUCT, selfdestruct::), (CALL, call::), (CALLCODE, call::), - (DELEGATECALL, volatile_call::), - (STATICCALL, volatile_call::), - (CREATE, create::), - (CREATE2, create::), + (DELEGATECALL, call::), + (STATICCALL, call::), (COINBASE, coinbase::), (TIMESTAMP, timestamp::), (NUMBER, number::), @@ -134,12 +107,6 @@ pub(crate) fn mega_instructions( (EXTCODECOPY, extcodecopy::), (EXTCODEHASH, extcodehash::), (SLOAD, sload::), - (KECCAK256, keccak256::), - (CALLDATACOPY, calldatacopy::), - (CODECOPY, codecopy::), - (RETURNDATACOPY, returndatacopy::), - (MCOPY, mcopy::), - (EXP, exp::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -148,273 +115,14 @@ pub(crate) fn mega_instructions( instructions } -/// Runs `inner`, commits the record its Host call staged once it completed, and settles the -/// history gas the record costs. -/// -/// An opcode completes when it returns `Ok` or stops the frame successfully (`SELFDESTRUCT` -/// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the -/// staged write back with it. -/// -/// The record is held to the data-size limit first, and only then is its history charged. A record -/// the limit rejects is not kept, so its history is not a charge and the stop is what the frame -/// reports. A record the limit accepts is charged, and a charge the frame cannot pay is an -/// out-of-gas. -#[inline(always)] -fn commit_after( - context: Ctx<'_, DB, ExtEnvs>, - inner: InstructionFn, -) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - host.additional_limit.discard_staged_record(); - let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - let completed = match result { - Ok(()) => true, - Err(result) => result.is_ok(), - }; - if !completed { - host.additional_limit.discard_staged_record(); - return note_halt(interpreter, host, result); - } - let (check, history) = host.additional_limit.commit_staged_record(); - if check.exceeded_limit() { - return Err(stop_frame(interpreter, host.additional_limit.note_frame_stop(&check))); - } - if host.prices_history() { - let settled = settle_history::(interpreter, host, history); - if settled.is_err() { - return note_halt(interpreter, host, settled); - } - } - result -} - -/// Charges the running frame the history gas of the bytes a record appends, or gives back the -/// history of a record that was taken away. -/// -/// Both sides are priced the same way, so a record taken back cancels its own charge exactly, -/// whichever frame made it: a refill below zero is reconciled when the frame merges into its -/// caller. A byte count with no price and a charge the frame cannot pay are both an out-of-gas. -/// -/// With `FROM_ALLOWANCE` the frame's history allowance pays what it can of the charge before the -/// frame's gas pays the rest ([`storage_call_stipend`](crate::storage_call_stipend)). Only the -/// log site sets it: a write record is the frame's own to pay for, and a record taken back gives -/// back what the frame's gas paid, never what the allowance did — the allowance is spent, not -/// lent. -#[inline] -fn settle_history( - interpreter: &mut Interpreter, - host: &mut MegaContext, - history: HistoryBytes, -) -> Result<(), InstructionResult> { - match history { - HistoryBytes::None => Ok(()), - HistoryBytes::Appended(bytes) => { - let Some(cost) = history_gas(bytes) else { return Err(InstructionResult::OutOfGas) }; - let drawn = - if FROM_ALLOWANCE { host.additional_limit.try_consume_stipend(cost) } else { 0 }; - if interpreter.gas.record_history_cost(cost - drawn) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) - } - } - HistoryBytes::Taken(bytes) => { - interpreter.gas.refill_history(history_gas(bytes).unwrap_or(0)); - Ok(()) - } - } -} - -/// Stops the running frame with the revert a crossed limit asks for: its output is the stop's -/// [`MegaLimitExceeded`](crate::MegaLimitExceeded), `output`, and its gas is the frame's, so the -/// caller gets the unspent part back. -#[cold] -#[inline(never)] -fn stop_frame(interpreter: &mut Interpreter, output: Bytes) -> InstructionResult { - if interpreter.bytecode.action().is_some() { - // A `SELFDESTRUCT` or a return the opcode already set gives way to the stop. - let _ = interpreter.take_next_action(); - } - let result = InstructionResult::Revert; - interpreter.bytecode.set_action(InterpreterAction::new_return(result, output, interpreter.gas)); - result -} - -/// `SSTORE`, committing the slot's write record, then holding the frame to the compute limit -/// again: a slot restored to its original value refills the state and history gas that spilled -/// onto regular gas, and the spill may predate the limit. -fn sstore( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - let result = commit_after::( - InstructionContext { interpreter: &mut *interpreter, host: &mut *host }, - host::sstore, - ); - // Only a restore refills, and a restore takes a record back rather than adding one, so it - // never crosses a limit: no stop's result is pending when the frame is held again. - host.detention.hold(&mut interpreter.gas); - result -} - -/// `LOG0`..`LOG4`, committing the log's bytes. -fn log( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - commit_after::(context, host::log::>) -} - -/// `SELFDESTRUCT`, committing the beneficiary's write record and the read of the block -/// beneficiary's account when it is either end. -fn selfdestruct( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - read_volatile(context, |context| commit_after::(context, host::selfdestruct)) -} - -/// Runs `inner` and charges the frame the history of the write records the frame `inner` starts -/// will make. -/// -/// The charge is made after revm's instruction has computed the gas it forwards, so it comes out -/// of what the caller kept rather than out of what the callee gets. An opcode that starts no frame -/// — a creation the balance, the nonce or the depth refuses, an out-of-gas — makes no records and -/// is charged nothing. Neither is a frame revm will refuse on its caller's account — a value call -/// the caller cannot fund ([`caller_refuses_start`]) — which the data size does not count either; -/// the answer is left for the frame's init, which would otherwise read the caller's account again. -/// A frame revm refuses for another reason — one past the call-stack limit — makes no records, -/// and its failure gives the charge back. A charge the caller cannot pay fails the opcode with an -/// out-of-gas, which takes the frame the opcode was suspending on with it ([`abandon_frame`]). -/// -/// revm's instruction has also charged the caller the state gas of the account the frame would -/// add — a value transfer's new recipient, a created account; a frame revm refuses gives it back. -/// -/// The frame inherits the reservoir the charge left, not the one the caller held before it -/// ([`inherit_reservoir`]). -#[inline(always)] -fn charge_frame_start( - context: Ctx<'_, DB, ExtEnvs>, - inner: InstructionFn, -) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - // An opcode that starts a frame suspends with the frame's input as its action; one that ends - // otherwise — a creation the balance cannot fund, an out-of-gas — leaves no such action and - // makes no records. - let records = match interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(input)) => { - let refused = caller_refuses_start(host, input); - host.additional_limit.stage_start_refused(refused); - if refused { - return result; - } - host.additional_limit.frame_start_records(input) - } - _ => return note_halt(interpreter, host, result), - }; - if !host.prices_history() { - return result; - } - let charged = charge_write_records_history( - interpreter.gas.tracker_mut(), - records.on_lane, - u64::from(records.caller), - ); - let Some((on_lane, caller)) = charged else { return abandon_frame(interpreter, host) }; - inherit_reservoir(interpreter); - host.additional_limit.stage_frame_charge(records, on_lane, caller); - result -} - -/// Fails the running opcode with an out-of-gas and drops the frame it was suspending on. -/// -/// The four frame-starting opcodes set the frame's input as the interpreter's action inside -/// revm's instruction, before this wrapper runs. An interpreter halts on an instruction's error -/// only when no action is pending, so a frame left pending here would start anyway — and make -/// write records nobody paid for, at any gas limit at which the caller keeps less after the -/// 63/64 forward than its records cost. -/// -/// The gas the opcode forwarded to the dropped frame goes back to the caller, which the halt then -/// burns with the rest: it never ran, so gas detention counts it with what the halt burns rather -/// than as compute. A value call's stipend was never the caller's, and is not handed back. -#[cold] -#[inline(never)] -fn abandon_frame( - interpreter: &mut Interpreter, - host: &mut MegaContext, -) -> InstructionExecResult { - if let InterpreterAction::NewFrame(input) = interpreter.take_next_action() { - interpreter.gas.erase_cost(forwarded_gas(&input, host.gas_params().call_stipend())); - } - note_halt(interpreter, host, Err(InstructionResult::OutOfGas)) -} - -/// Passes `result` on, first noting for gas detention what the running frame has left when -/// `result` is an out-of-gas the interpreter will halt the frame on: the halt zeroes it before the -/// frame returns, and it is what the halt burns rather than what the frame ran. -/// -/// The interpreter halts on an instruction's error only when no action is pending; an opcode that -/// set one ends its frame with that action instead, and burns nothing. -#[inline(always)] -fn note_halt( - interpreter: &mut Interpreter, - host: &mut MegaContext, - result: InstructionExecResult, -) -> InstructionExecResult { - if result == Err(InstructionResult::OutOfGas) && interpreter.bytecode.action().is_none() { - host.detention.note_halt(interpreter.gas.remaining()); - } - result -} - -/// Hands the frame the running opcode is suspending on the reservoir its caller has now. -/// -/// revm's `CALL`, `CALLCODE`, `CREATE` and `CREATE2` copy the caller's reservoir into the frame's -/// input, and they do it before this wrapper charges anything. A returning frame's reservoir is -/// adopted by its caller rather than merged into it, so a frame that inherited the reservoir as -/// it stood before the charge would hand the charge straight back — and a frame answered without -/// running, whose gas is built from the same field, would hand it back a second time. Writing the -/// post-charge reservoir into the input closes both. -#[inline] -fn inherit_reservoir(interpreter: &mut Interpreter) { - let reservoir = interpreter.gas.reservoir(); - if let Some(InterpreterAction::NewFrame(input)) = interpreter.bytecode.action() { - match input { - FrameInput::Call(inputs) => inputs.reservoir = reservoir, - FrameInput::Create(inputs) => inputs.set_reservoir(reservoir), - FrameInput::Empty => {} - } - } -} - -/// `CALL` and `CALLCODE`, charging the caller for the records a value transfer writes and -/// committing the read of the block beneficiary's account when the callee, or the EIP-7702 -/// delegate it runs, is the beneficiary. -/// -/// `CALLCODE` runs the callee's code in the caller's own account, so the two records of a `CALL` -/// — the sender's and the recipient's — are one here. +/// `CALL`, `CALLCODE`, `DELEGATECALL` and `STATICCALL`, committing the read of the block +/// beneficiary's account when the callee, or the EIP-7702 delegate it runs, is the beneficiary. fn call( context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - read_volatile(context, |context| charge_frame_start(context, contract::call::)) -} - -/// `DELEGATECALL` and `STATICCALL`, committing the read of the block beneficiary's account when -/// the callee, or the EIP-7702 delegate it runs, is the beneficiary. They carry no value and write -/// nothing, so no record is charged. -fn volatile_call( - context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { read_volatile(context, contract::call::) } -/// `CREATE` and `CREATE2`, charging the creator for the created account's record and for its own -/// nonce. -fn create( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - charge_frame_start(context, contract::create::) -} - /// Runs `inner` and settles the reads of volatile data its Host calls made: a refused read /// reverts the frame with `VolatileDataAccessDisabled`, and a read the opcode completed is /// committed, capping the frame at what the compute limit leaves it. @@ -432,11 +140,12 @@ fn read_volatile( inner: impl FnOnce(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult, ) -> InstructionExecResult { let InstructionContext { interpreter, host } = context; - host.detention.discard_stale_reads(); + host.detention.begin_read(); let gas = host.detention.is_refusing().then_some(interpreter.gas); let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + host.detention.end_read(); if !host.detention.has_reads() { - return note_halt(interpreter, host, result); + return result; } settle_reads(interpreter, host, result, gas) } @@ -461,7 +170,7 @@ fn settle_reads( } }; if !completed { - return note_halt(interpreter, host, result); + return result; } // A completed opcode leaves no result pending: a `SELFDESTRUCT`'s is built from the frame's // gas once the wrapper returned, and a stop fails the opcode. @@ -471,7 +180,7 @@ fn settle_reads( } _ => 0, }; - host.detention.commit_reads(observed, &mut interpreter.gas, interpreter.input.depth, forwarded); + host.detention.commit_reads(observed, &mut interpreter.gas, forwarded); result } @@ -500,14 +209,7 @@ fn refuse( /// The regular gas the running frame paid for the frame `input` starts: the frame's limit, less /// a value call's stipend, which nobody paid. fn forwarded_gas(input: &FrameInput, call_stipend: u64) -> u64 { - match input { - FrameInput::Call(inputs) if inputs.transfers_value() => { - inputs.gas_limit.saturating_sub(call_stipend) - } - FrameInput::Call(inputs) => inputs.gas_limit, - FrameInput::Create(inputs) => inputs.gas_limit(), - FrameInput::Empty => 0, - } + input_gas_limit(input).saturating_sub(value_call_stipend(input, call_stipend)) } /// Defines an opcode that reads volatile data — a block-environment field, an account or a slot — @@ -538,6 +240,7 @@ volatile_read! { extcodecopy => host::extcodecopy, "EXTCODECOPY", "the block beneficiary's account"; extcodehash => host::extcodehash, "EXTCODEHASH", "the block beneficiary's account"; sload => host::sload, "SLOAD", "the Oracle's storage"; + selfdestruct => host::selfdestruct, "SELFDESTRUCT", "the block beneficiary's account"; } /// `BLOCKHASH`, committing the read of the block number and of the hash. @@ -554,31 +257,6 @@ fn blockhash( }) } -/// Defines an opcode whose own charge no other wrapper sees, as revm's instruction with what the -/// frame had left noted when the charge fails ([`note_halt`]): the charge of `KECCAK256` and of -/// the four copies into memory has no bound, and `EXP`'s exponent charge reaches 1,600. -macro_rules! unbounded_charge { - ($($name:ident => $inner:path, $opcode:literal;)*) => {$( - #[doc = concat!("`", $opcode, "`, noting what the frame had when its charge fails.")] - fn $name( - context: Ctx<'_, DB, ExtEnvs>, - ) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - let result = $inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - note_halt(interpreter, host, result) - } - )*}; -} - -unbounded_charge! { - keccak256 => system::keccak256, "KECCAK256"; - calldatacopy => system::calldatacopy, "CALLDATACOPY"; - codecopy => system::codecopy, "CODECOPY"; - returndatacopy => system::returndatacopy, "RETURNDATACOPY"; - mcopy => memory::mcopy, "MCOPY"; - exp => arithmetic::exp, "EXP"; -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 8893e7efc..f033533c5 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -1,9 +1,42 @@ //! The Satin EVM. //! //! [`MegaEvm`] runs transactions on a [`MegaContext`] configured for the Satin spec through -//! [`MegaHandler`], which wraps op-revm's handler. The EVM implements revm's frame lifecycle -//! itself (see [`execution`](self::execution)), which is where `MegaETH`'s frame-level mechanisms -//! plug in. +//! [`MegaHandler`], which wraps op-revm's handler. The EVM implements revm's frame start and +//! return itself (see [`execution`](self::execution)), which is where `MegaETH`'s frame-level +//! mechanisms plug in. +//! +//! # Inspectors +//! +//! An inspector runs as revm runs it: through revm's inspected handler and frame lifecycle, +//! unchanged, which start a frame, hand over the result of its run and return it through the same +//! three methods the plain path does. The engine does nothing for an inspector, and an inspector +//! keeps its own consistency. +//! +//! - **A rewrite is taken as given.** revm commits or reverts a frame's journal checkpoint before +//! the inspector sees its result, and the caller settles the result the inspector hands back — +//! its classification, output and gas, reservoir and byte pool included — and an answer the +//! inspector gives in place of a frame never reaches the engine's frame start: the depth guard, +//! the interceptors and gas detention see none of it, and it settles on the gas it is built on. +//! - **A callback's writes to gas are the inspector's.** A charge a frame cannot pay is refused, +//! and leaves its record on the frame's gas as an opcode's does: a crossing of the withheld part +//! 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 record. An inspector that overwrites the interpreter's gas +//! overwrites gas detention's split and the byte pool with it, until detention next holds the +//! frame. +//! - **What an inspector sees.** A frame's end as the engine settled it: a frame that crossed gas +//! detention's compute limit ends with the stop, which the engine makes of its out-of-gas once +//! its run returns and before the inspector's `call_end`, `create_end` and `frame_end` see it, as +//! the caller and the receipt do. A frame whose start crossed a limit ends with the stop before +//! it runs, and is seen to start and end as an answer is. A `keylessDeploy` call's frame runs no +//! instruction: the action made for it before each of its runs is set on its interpreter, and +//! revm's inspected run returns an action set before it runs without a `step`, and hands a frame +//! built with one to no `initialize_interp`, so the inspector sees the call start, its creation, +//! and the call end. A frame a child returned into over a limit returns the stop the same way, +//! with no `step` after the child's end. +//! - **Where an inspector runs.** Every transaction, the system-address transaction included. A +//! pre-block call runs on the handler's plain system-call path, with no callback; a tool runs a +//! system call through revm's `InspectSystemCallEvm` to watch it. The end of a block runs no +//! code. mod context; mod execution; @@ -11,7 +44,6 @@ mod factory; mod frame; mod history; mod host; -mod inspector; mod instructions; mod precompiles; mod prices; @@ -26,7 +58,6 @@ pub use execution::*; pub use factory::*; pub use frame::*; pub use history::*; -pub use inspector::*; pub use precompiles::*; pub use prices::*; pub use result::*; @@ -92,9 +123,6 @@ pub struct MegaEvm, /// Whether [`alloy_evm::Evm::transact_raw`] runs the inspector. inspect: bool, - /// Whether the inspector's type carries a [`TrustedObserver`] declaration. Set only by the - /// constructors that require the declaration; true without an inspector. - trusted_inspector: bool, /// Which precompile calls gas detention may price from the Satin table. priced_precompiles: PricedPrecompiles, } @@ -110,12 +138,7 @@ impl MegaEvm MegaEvm { /// Replaces the inspector with a tool's. The new inspector runs on every alloy-evm /// [`transact`](alloy_evm::Evm::transact) until it is disabled again. /// - /// The inspector may rewrite what execution produces (see the `inspector` module), so the - /// EVM reports [`has_rewriting_inspector`](Self::has_rewriting_inspector) while it runs, and - /// block execution refuses it. + /// The inspector may rewrite what execution produces (see the module documentation). The engine + /// does not refuse one in block execution: a node decides which inspectors run on block + /// production. pub fn with_inspector(self, inspector: I) -> MegaEvm { MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true, - trusted_inspector: false, priced_precompiles: self.priced_precompiles, } } - /// Replaces the inspector with one whose type is declared a [`TrustedObserver`]: it writes - /// nothing back, so the transactions it observes are the ones the chain executes, and block - /// execution admits them. - pub fn with_trusted_inspector( - self, - inspector: I, - ) -> MegaEvm { - MegaEvm { - inner: self.inner.with_inspector(inspector), - inspect: true, - trusted_inspector: true, - priced_precompiles: self.priced_precompiles, - } - } - - /// Whether the EVM runs an inspector that may rewrite what execution produces: an enabled - /// inspector that did not arrive through - /// [`with_trusted_inspector`](Self::with_trusted_inspector). - /// - /// The admission gate block execution refuses a transaction on. - pub const fn has_rewriting_inspector(&self) -> bool { - self.inspect && !self.trusted_inspector - } - /// The execution context. pub const fn ctx(&self) -> &MegaContext { &self.inner.ctx @@ -221,7 +219,7 @@ impl MegaEvm { /// Enforces `limits` on every transaction this EVM runs from now on. pub const fn set_tx_runtime_limits(&mut self, limits: crate::EvmTxRuntimeLimits) { - self.inner.ctx.additional_limit.set_limits(limits); + self.inner.ctx.set_tx_runtime_limits(limits); } /// The limits every transaction this EVM runs is held to. @@ -290,8 +288,8 @@ where ExtEnvs: ExternalEnvTypes, { /// Executes `tx`, through the inspector when one is enabled, and returns its outcome: the - /// result and state, the gas by ledger, the usage the common execution layer counted, the - /// limit that stopped the transaction, if any, and the reads of the Oracle's storage it made + /// result and state, the gas by ledger, the usage the common execution layer counted, the limit + /// that stopped the transaction, if any, and the reads of the Oracle's storage it made /// through the oracle service. Nothing is committed. pub fn execute_transaction( &mut self, @@ -303,11 +301,12 @@ where result_and_state.result.gas(), layer.history_gas_spent(), layer.history_bytes(), + layer.reservoir_remaining(), ); Ok(MegaTransactionOutcome { result_and_state, gas, - usage: layer.usage(), + usage: self.inner.ctx.limit_usage(), limit_exceeded: layer.limit_exceeded().copied(), oracle_reads: self.inner.ctx.oracle_reads().reads().to_vec(), }) @@ -392,20 +391,6 @@ where { } -/// revm's system-call transaction from `caller` to `contract` with `data` -/// ([`SystemCallTx::new_system_tx_with_caller`]), on `gas_limit` instead of revm's -/// [`SYSTEM_CALL_GAS_LIMIT`](revm::handler::SYSTEM_CALL_GAS_LIMIT). -fn system_tx_with_gas_limit( - caller: Address, - contract: Address, - data: Bytes, - gas_limit: u64, -) -> MegaTransaction { - let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); - tx.0.base.gas_limit = gas_limit; - tx -} - impl SystemCallEvm for MegaEvm { fn system_call_one_with_caller( &mut self, @@ -422,25 +407,26 @@ impl SystemCallEvm for MegaEvm MegaEvm { - /// Runs a system call from `caller` to `contract` with `data` on `gas_limit`, and returns its - /// result and state. Nothing is committed. + /// Runs a pre-block system call from `caller` to `contract` with `data`, and returns its result + /// and state. Nothing is committed. /// - /// It is [`transact_system_call`](alloy_evm::Evm::transact_system_call) on the gas limit the - /// caller names instead of revm's [`SYSTEM_CALL_GAS_LIMIT`]. The limit is split as every - /// system call's is: at most [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] of it is regular gas and the - /// rest is the call's state-gas reservoir, so a limit above 30,000,000 widens the reservoir - /// and never the regular budget. The block's pre-block calls run through it. + /// It is [`transact_system_call`](alloy_evm::Evm::transact_system_call) on the pre-block + /// budget, [`PRE_BLOCK_CALL_GAS_LIMIT`], instead of revm's [`SYSTEM_CALL_GAS_LIMIT`]: at most + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] of it is regular gas, as of every system call, and the + /// rest is the call's state-gas reservoir. What the call left of its reservoir is + /// [`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining). /// + /// [`PRE_BLOCK_CALL_GAS_LIMIT`]: crate::constants::PRE_BLOCK_CALL_GAS_LIMIT /// [`SYSTEM_CALL_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_GAS_LIMIT - /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_REGULAR_GAS_LIMIT - pub fn transact_system_call_with_gas_limit( + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: crate::SYSTEM_CALL_REGULAR_GAS_LIMIT + pub(crate) fn transact_pre_block_system_call( &mut self, caller: Address, contract: Address, data: Bytes, - gas_limit: u64, ) -> Result, EVMError> { - let tx = system_tx_with_gas_limit(caller, contract, data, gas_limit); + let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); + tx.0.base.gas_limit = crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; let result = self.run_system_call(tx).map_err(map_op_err)?; Ok(ResultAndState::new(result, ExecuteEvm::finalize(self))) } @@ -553,7 +539,7 @@ mod tests { use revm::{ context::{result::InvalidTransaction, ContextSetters, Transaction, TxEnv}, database::State, - handler::{SYSTEM_CALL_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT}, + handler::system_call::SYSTEM_CALL_GAS_LIMIT, DatabaseRef, }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; @@ -734,35 +720,29 @@ mod tests { assert_eq!(evm.ctx().tx().kind(), TxKind::Call(CALLEE)); } - /// The gas limit a caller names is the system call's: the part above 30M is its reservoir, - /// and a limit below 30M is regular gas alone. + /// A pre-block call runs on the pre-block budget whatever the block's gas limit: 30M of + /// regular gas and the rest of the budget as its reservoir. #[test] - fn test_transact_system_call_with_gas_limit_uses_passed_value() { - let mut db = funded_db(); - let mut evm = MegaEvm::new(context(&mut db)); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) - .unwrap(); - assert!(result.result.is_success()); - assert_eq!(evm.ctx().tx().gas_limit(), 123_456_789); - assert_eq!( - result.result.gas().reservoir_remaining(), - 123_456_789 - SYSTEM_CALL_REGULAR_GAS_LIMIT, - "an empty callee draws nothing from the reservoir", - ); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 1_000_000) - .unwrap(); - assert!(result.result.is_success()); - assert_eq!(evm.ctx().tx().gas_limit(), 1_000_000); - assert_eq!(result.result.gas().reservoir_remaining(), 0); + fn test_a_pre_block_call_runs_on_the_pre_block_budget() { + use crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; + for block_gas_limit in [1_000_000, 10_000_000_000] { + let mut db = funded_db(); + let block = BlockEnv { gas_limit: block_gas_limit, ..Default::default() }; + let mut evm = MegaEvm::new(context(&mut db).with_block(block)); + let result = evm.transact_pre_block_system_call(CALLER, CALLEE, Bytes::new()).unwrap(); + assert!(result.result.is_success()); + assert_eq!(evm.ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT, "{block_gas_limit}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT, + "an empty callee draws nothing from the reservoir", + ); + } } /// The default system-call entry point runs on revm's system-call gas limit whatever the /// block's gas limit is: its regular budget is the base 30M, and the margin above it is the - /// reservoir. Only an explicit gas limit moves either. + /// reservoir. #[test] fn test_default_system_call_keeps_the_30m_regular_budget() { let mut db = funded_db(); @@ -777,7 +757,7 @@ mod tests { assert_eq!(evm.ctx().tx().gas_limit(), 31_566_720); assert_eq!(SYSTEM_CALL_GAS_LIMIT, 31_566_720); assert_eq!( - result.result.gas().reservoir_remaining(), + evm.ctx().additional_limit().reservoir_remaining(), 31_566_720 - 30_000_000, "30M of it is regular gas", ); diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 1ebe4fddb..954fdde2c 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -52,14 +52,17 @@ use alloy_evm::{ precompiles::{DynPrecompile, Precompile as _, PrecompilesMap}, Database, }; +use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ + context::{BlockEnv, CfgEnv}, handler::PrecompileProvider, interpreter::{CallInputs, InterpreterResult}, precompile::Precompiles, primitives::{Address, AddressSet, HashMap, OnceLock}, + Context, Journal, }; -use crate::{ExternalEnvTypes, MegaContext, MegaInnerContext, MegaSpecId}; +use crate::{ExternalEnvTypes, MegaContext, MegaSpecId, MegaTransaction}; /// The Satin precompile set: op-revm's Karst set with `MegaETH`'s KZG price. pub fn satin_precompiles() -> &'static Precompiles { @@ -185,10 +188,16 @@ pub mod kzg_point_evaluation { .with_required_gas(required_gas); } -/// Runs the Satin precompile set on a [`MegaContext`]. -/// -/// alloy-evm implements the provider for revm's plain context; every method here hands it the -/// context [`MegaContext`] wraps, which is that context. +/// The context [`MegaContext`] wraps: op-revm's context shape over revm's own journal, the one +/// alloy-evm implements the provider for. +type InnerContext = + Context, DB, Journal, L1BlockInfo>; + +/// Runs the Satin precompile set on a [`MegaContext`], as alloy-evm runs it on the context +/// [`MegaContext`] wraps: the precompile gets the call's input and an +/// [`EvmInternals`](alloy_evm::EvmInternals) over revm's journal, and its output is turned into +/// the call's result the way revm turns any precompile's. A precompile's writes through the +/// internals reach the journal as any tool's do, and count none of the transaction's bytes. impl PrecompileProvider> for PrecompilesMap { @@ -197,7 +206,7 @@ impl PrecompileProvider bool { + fn set_spec(&mut self, _spec: OpSpecId) -> bool { false } @@ -207,17 +216,19 @@ impl PrecompileProvider, inputs: &CallInputs, ) -> Result, String> { - PrecompileProvider::>::run(self, &mut context.inner, inputs) + PrecompileProvider::>::run(self, &mut context.inner, inputs) } + /// The addresses of the set, as alloy-evm's provider answers them. #[inline] fn warm_addresses(&self) -> &AddressSet { - PrecompileProvider::>::warm_addresses(self) + PrecompileProvider::>::warm_addresses(self) } + /// Whether the set holds `address`, as alloy-evm's provider answers it. #[inline] fn contains(&self, address: &Address) -> bool { - PrecompileProvider::>::contains(self, address) + PrecompileProvider::>::contains(self, address) } } @@ -273,6 +284,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, } } diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index b3873f90d..8662b8a57 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -46,7 +46,8 @@ pub struct MegaTransactionOutcome { /// is [`LimitUsage::write_records`]. pub usage: LimitUsage, /// The crossing that produced the result of the transaction's own frame, if one did: a - /// transaction-level limit, or that frame's own data-size budget. The result is then a revert + /// transaction-level limit, or that frame's own budget in data size, KV updates or state + /// growth. The result is then a revert /// whose output is its [`MegaLimitExceeded`](crate::MegaLimitExceeded); this, not the output, /// tells a limit stop from a contract reverting with the same bytes, or re-raising those a /// frame below it was stopped with. @@ -117,18 +118,26 @@ pub struct MegaGasUsage { impl MegaGasUsage { /// The ledgers of a transaction that settled into `result_gas`, spent `history` gas on - /// history and appended `history_bytes` bytes of it. + /// history, appended `history_bytes` bytes of it and left `reservoir_remaining` of its + /// reservoir unspent. /// /// [`ResultGas`] has no history field; its total includes history gas, which is taken back - /// out of regular here. - pub const fn new(result_gas: &ResultGas, history: u64, history_bytes: u64) -> Self { + /// out of regular here. Nor does it carry the reservoir: the handler reads that off the + /// settled result + /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)). + pub const fn new( + result_gas: &ResultGas, + history: u64, + history_bytes: u64, + reservoir_remaining: u64, + ) -> Self { let state = result_gas.state_gas_spent_final(); Self { regular: result_gas.total_gas_spent().saturating_sub(state).saturating_sub(history), state, history, history_bytes, - reservoir_remaining: result_gas.reservoir_remaining(), + reservoir_remaining, floor: result_gas.floor_gas(), gas_used: result_gas.tx_gas_used(), } @@ -159,19 +168,19 @@ mod tests { .with_state_gas_spent(state) .with_refunded(refunded) .with_floor_gas(floor) - .with_reservoir_remaining(5_000) } /// The three ledgers add up to the raw spend; the receipt figure is the spend less the refund. #[test] fn test_ledgers_split_the_raw_spend() { - let gas = MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000, 125); + let gas = + MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000, 125, 5_000); assert_eq!(gas.regular, 60_000); assert_eq!(gas.state, 30_000); assert_eq!(gas.history, 10_000); assert_eq!(gas.history_bytes, 125, "a byte count, carried as it was given"); assert_eq!(gas.regular + gas.state + gas.history, 100_000); - assert_eq!(gas.reservoir_remaining, 5_000); + assert_eq!(gas.reservoir_remaining, 5_000, "carried as it was given"); assert_eq!(gas.gas_used, 96_000); assert_eq!(gas.block_execution_gas(), 60_000); } @@ -179,7 +188,7 @@ mod tests { /// The floor binds the receipt figure and the block's execution gas, not the ledgers. #[test] fn test_floor_binds_receipt_and_block_execution_gas() { - let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000, 0); + let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000, 0, 0); assert_eq!(gas.regular, 25_000); assert_eq!(gas.floor, 45_000); assert_eq!(gas.gas_used, 45_000); diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 793908eac..f4c1da8b2 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -2,16 +2,28 @@ //! //! Satin takes the Amsterdam schedule — the one that carries EIP-8037 state gas, EIP-8038's //! state-access prices, the EIP-2780 intrinsic decomposition, the EIP-7976 calldata floor and -//! EIP-7981 access-list data — and changes exactly two things: +//! EIP-7981 access-list data — and changes exactly four things: //! //! 1. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte //! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than //! Glamsterdam's; -//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), the one entry outside -//! Amsterdam's table: upstream leaves it at zero, and Satin gives it the cost of one history -//! byte, which is what makes a deployment pay for the bytes every node has to carry. +//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), and the history allowance a +//! value-transferring call gives the frame it starts, the entries outside Amsterdam's table: +//! upstream leaves them at zero, and Satin gives deposited code the cost of one history byte per +//! byte, which is what makes a deployment pay for the bytes every node has to carry, and the +//! allowance the cost of [`HISTORY_ALLOWANCE_BYTES`]; +//! 3. the share of its caller's pools — data size, KV updates, state growth — and of its caller's +//! EIP-8037 reservoir a frame starts with: upstream forwards the whole of each, and Satin's +//! caller keeps [`FRAME_KEPT_PERCENT`] of what it has left (`GasId::pool_kept_percent`, +//! `GasId::reservoir_kept_percent`). The fork rounds the two differently, as the spec does: a +//! pool's share is `floor(remaining × 98 / 100)`, and the reservoir's `remaining − remaining × 2 +//! / 100`, so a caller keeps nothing of a reservoir below 50. The transaction's own frame and a +//! system call's outermost frame take the whole reservoir; +//! 4. the regular gas a call or creation forwards: at most `remaining − remaining × 2 / 100` of +//! what its caller has left, Rex6's rule, in place of EIP-150's 63/64 +//! ([`FORWARD_REDUCTION_QUOTIENT`], the fork's `GasId::call_stipend_reduction`). //! -//! Every regular-gas entry is Amsterdam's, so state creation is split between the two dimensions +//! Every regular-gas price is Amsterdam's, so state creation is split between the two dimensions //! as Amsterdam splits it: the regular part is the access and write work EIP-8038 prices, and the //! new state itself is state gas alone. A value `CALL` that creates its recipient pays the 11,300 //! of its value transfer, which carries the account write, and no new-account regular gas; a @@ -37,7 +49,16 @@ use revm::{ primitives::{eip8037, hardfork::SpecId, OnceLock}, }; -use crate::evm::prices::{active_satin_prices, SatinPrices}; +use crate::{ + evm::{ + history::HISTORY_ALLOWANCE_BYTES, + prices::{active_satin_prices, SatinPrices}, + }, + limit::{ + DATA_SIZE_POOL, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, KV_UPDATE_POOL, + STATE_GROWTH_POOL, + }, +}; /// A schedule entry and the number of bytes it prices: the entry is that many bytes at a byte /// price. @@ -62,7 +83,27 @@ pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ /// Deposited code is the one history charge the schedule prices, because it is the one revm makes /// itself: `return_create` writes the code and charges the entry for its length. Every other /// history charge is made by the engine, which prices its own byte counts (the `history` module). -pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[(GasId::code_deposit_history_gas, 1)]; +/// The allowance a value-transferring call gives the frame it starts is in the schedule because +/// revm's call instruction gives it, where it gives the call stipend; only a log the frame emits +/// draws on it ([`history_allowance_gas`](crate::history_allowance_gas)). +pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[ + (GasId::code_deposit_history_gas, 1), + (GasId::call_history_allowance, HISTORY_ALLOWANCE_BYTES), +]; + +/// The part of its pool, in per cent, a caller keeps when it starts a frame, which starts with the +/// rest: its budget, [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what the +/// caller has left. revm's forward of a pool rounds the share down, as the budget's rule does. +pub(crate) const FRAME_KEPT_PERCENT: u64 = + 100 - FRAME_DATA_SHARE_NUMERATOR * 100 / FRAME_DATA_SHARE_DENOMINATOR; +const _: () = + assert!((FRAME_DATA_SHARE_NUMERATOR * 100).is_multiple_of(FRAME_DATA_SHARE_DENOMINATOR)); + +/// The quotient of EIP-150's reduction of the regular gas a call or creation forwards: the fork +/// forwards `remaining − remaining / quotient`, and 50 is Rex6's rule, +/// `remaining − remaining × 2 / 100`, in place of upstream's 64. +pub(crate) const FORWARD_REDUCTION_QUOTIENT: u64 = 100 / FRAME_KEPT_PERCENT; +const _: () = assert!(100 % FRAME_KEPT_PERCENT == 0); /// The Satin gas schedule at the prices in effect. /// @@ -87,7 +128,7 @@ pub fn satin_gas_params_history_exempt() -> GasParams { TABLE .get_or_init(|| { let mut params = satin_gas_params(); - params.override_gas(HISTORY_GAS_PRICED.iter().map(|&(id, _)| (id(), 0))); + params.override_gas([(GasId::code_deposit_history_gas(), 0)]); params }) .clone() @@ -111,6 +152,13 @@ pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { params.override_gas( HISTORY_GAS_PRICED.iter().map(|&(id, bytes)| (id(), prices.cphb.fixed_size_gas(bytes))), ); + params.override_gas([ + (GasId::pool_kept_percent(DATA_SIZE_POOL), FRAME_KEPT_PERCENT), + (GasId::pool_kept_percent(KV_UPDATE_POOL), FRAME_KEPT_PERCENT), + (GasId::pool_kept_percent(STATE_GROWTH_POOL), FRAME_KEPT_PERCENT), + (GasId::reservoir_kept_percent(), FRAME_KEPT_PERCENT), + (GasId::call_stipend_reduction(), FORWARD_REDUCTION_QUOTIENT), + ]); params } @@ -143,7 +191,12 @@ mod tests { for slot in 0..=u8::MAX { let id = GasId::new(slot); let rebuilt = STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || - HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id); + HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) || + id == GasId::pool_kept_percent(DATA_SIZE_POOL) || + id == GasId::pool_kept_percent(KV_UPDATE_POOL) || + id == GasId::pool_kept_percent(STATE_GROWTH_POOL) || + id == GasId::reservoir_kept_percent() || + id == GasId::call_stipend_reduction(); if rebuilt { continue; } @@ -218,22 +271,95 @@ mod tests { } } - /// The schedule an exempt transaction runs prices no history byte and is otherwise the same - /// table. + /// The schedule an exempt transaction runs prices no deposited byte and is otherwise the same + /// table: an exempt transaction is charged no history by the engine, so the allowance, which + /// only a history charge draws, is left as it is. #[test] fn test_the_exempt_schedule_only_drops_the_history_price() { let exempt = satin_gas_params_history_exempt(); let satin = satin_gas_params(); - assert_eq!(exempt.get(GasId::code_deposit_history_gas()), 0); + let id = GasId::code_deposit_history_gas(); + assert_eq!(exempt.get(id), 0); for slot in 0..=u8::MAX { - let id = GasId::new(slot); - if HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) { - continue; + let other = GasId::new(slot); + if other != id { + assert_eq!(exempt.get(other), satin.get(other), "{} must not move", other.name()); } - assert_eq!(exempt.get(id), satin.get(id), "{} must not move", id.name()); } } + /// A frame starts with 98 per cent of what its caller has left of its data-size, KV-update and + /// state-growth budgets, which revm forwards at every frame start as the schedule's share of + /// each pool, the caller keeping 2 per cent, rounded down as the budget's rule is; upstream + /// forwards the whole pool. + #[test] + fn test_a_frame_is_forwarded_98_percent_of_its_callers_pools() { + let satin = satin_gas_params(); + for id in [DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL] { + assert_eq!(satin.get(GasId::pool_kept_percent(id)), 2); + assert_eq!(amsterdam().get(GasId::pool_kept_percent(id)), 0); + for pool in [0, 1, 49, 50, 51, 99, 100, 101, 9_690, u64::MAX] { + let floor = (u128::from(pool) * 98 / 100) as u64; + assert_eq!(satin.pool_forward_share(id, pool), floor, "{pool}"); + } + } + } + + /// A call or creation forwards at most `remaining − remaining × 2 / 100` of its caller's + /// regular gas, Rex6's rule, which the fork's EIP-150 reduction gives with a quotient of 50; + /// upstream's is 64, the 63/64 rule. + #[test] + fn test_a_call_forwards_at_most_98_percent_of_its_callers_regular_gas() { + let satin = satin_gas_params(); + assert_eq!(satin.get(GasId::call_stipend_reduction()), 50); + assert_eq!(amsterdam().get(GasId::call_stipend_reduction()), 64); + for (remaining, forward) in + [(0, 0), (1, 1), (49, 49), (50, 49), (99, 98), (1_000, 980), (10_000, 9_800)] + { + assert_eq!(satin.call_stipend_reduction(remaining), forward, "{remaining}"); + } + assert_eq!(amsterdam().call_stipend_reduction(1_000), 985, "EIP-150's 63/64"); + assert_eq!(amsterdam().call_stipend_reduction(50), 50, "EIP-150's 63/64"); + } + + /// A frame starts with the reservoir its caller has left less the caller's 2 per cent, the + /// division truncating, so a caller keeps nothing of a reservoir below 50 and the child gets + /// 98 of 99; upstream forwards the whole reservoir. + #[test] + fn test_a_frame_is_forwarded_its_callers_reservoir_less_two_percent() { + let satin = satin_gas_params(); + assert_eq!(satin.get(GasId::reservoir_kept_percent()), 2); + assert_eq!(amsterdam().get(GasId::reservoir_kept_percent()), 0); + for (reservoir, share) in [ + (0, 0), + (1, 1), + (49, 49), + (50, 49), + (99, 98), + (100, 98), + (149, 147), + (1_000, 980), + (1_000_000, 980_000), + (u64::MAX, u64::MAX - u64::MAX / 50), + ] { + assert_eq!(satin.reservoir_forward_share(reservoir), share, "{reservoir}"); + assert_eq!(amsterdam().reservoir_forward_share(reservoir), reservoir, "{reservoir}"); + } + } + + /// The history allowance a value-transferring call gives the frame it starts is + /// [`HISTORY_ALLOWANCE_BYTES`] at the cost per history byte, the same figure the engine + /// prices its history at; Osaka and Amsterdam give none. + #[test] + fn test_a_value_call_is_given_the_history_allowance() { + let id = GasId::call_history_allowance(); + assert_eq!(satin_gas_params().get(id), crate::history_allowance_gas()); + let constants = satin_gas_params_at(SatinPrices::CONSTANTS); + assert_eq!(constants.get(id), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(osaka().get(id), 0); + assert_eq!(amsterdam().get(id), 0); + } + /// Deposited code costs one history byte per byte, which is the whole of Satin's history /// schedule. Osaka and Amsterdam price no history byte at all. #[test] @@ -284,6 +410,7 @@ mod tests { (GasId::code_deposit_state_gas(), 313), (GasId::tx_eip7702_state_gas_bytecode(), 7_188), (GasId::code_deposit_history_gas(), 400), + (GasId::call_history_allowance(), 160 * 400), ]; for slot in 0..=u8::MAX { let id = GasId::new(slot); diff --git a/crates/mega-evm/src/evm/validation.rs b/crates/mega-evm/src/evm/validation.rs index 60d72f154..855f77da0 100644 --- a/crates/mega-evm/src/evm/validation.rs +++ b/crates/mega-evm/src/evm/validation.rs @@ -144,11 +144,10 @@ pub fn validate_transaction_stateless( let handler = MegaHandler::<_, MegaEvmError, EthFrame>::new(); handler.validate_env_as(&mut evm, system_address, false)?; let gas = handler.validate_initial_tx_gas(&mut evm)?; - let history = evm.ctx().additional_limit.intrinsic_history_gas(); Ok(IntrinsicGas { regular: gas.initial_regular_gas(), - state: gas.initial_state_gas_final() - history, - history, + state: gas.initial_state_gas_final(), + history: evm.ctx().additional_limit.intrinsic_history_gas(), floor: gas.floor_gas(), }) } diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 28f859579..8bd049186 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -32,13 +32,12 @@ pub use access::{ VolatileDataAccess, }; pub use block::{ - chain_activation, estimated_da_size, hardfork_schedule, mainnet_hardforks, - pre_block_call_gas_limit, read_l1_block_info, testnet_hardforks, - transact_beacon_root_contract_call, transact_blockhashes_contract_call, BlockGasCounters, - BlockLimiter, BlockLimits, BlockUsage, ChainActivation, EnrichedMegaTx, MegaBlockExecutionCtx, - MegaBlockExecutionError, MegaBlockExecutionResult, MegaBlockExecutor, MegaBlockExecutorFactory, - MegaBlockLimitExceededError, MegaBlockTxResult, MegaFinishedBlock, MegaHardfork, - MegaHardforkConfig, MegaHardforks, MegaTransactionExt, MegaTxLimitExceededError, + chain_activation, estimated_da_size, hardfork_schedule, mainnet_hardforks, read_l1_block_info, + testnet_hardforks, transact_beacon_root_contract_call, transact_blockhashes_contract_call, + BlockGasCounters, BlockLimiter, BlockLimits, BlockUsage, ChainActivation, EnrichedMegaTx, + MegaBlockExecutionCtx, MegaBlockExecutionError, MegaBlockExecutionResult, MegaBlockExecutor, + MegaBlockExecutorFactory, MegaBlockLimitExceededError, MegaBlockTxResult, MegaFinishedBlock, + MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaTransactionExt, MegaTxLimitExceededError, ProtocolLimits, SatinChainConfig, SatinChainConfigError, ScheduleError, CHAIN_ACTIVATIONS, L1_BLOCK_INFO_SLOTS, MAINNET_CHAIN_ID, SATIN_CHAIN_CONFIG_KEYS, SATIN_TIME_KEY, SYSTEM_ADDRESS, TESTNET_CHAIN_ID, @@ -46,16 +45,16 @@ pub use block::{ #[cfg(feature = "satin-price-override")] pub use evm::install_satin_prices; pub use evm::{ - active_satin_prices, history_gas, kzg_point_evaluation, name, satin_gas_params, - satin_gas_params_at, satin_gas_params_history_exempt, satin_precompiles, satin_precompiles_map, - settle_frame_result, spec_cfg, storage_call_stipend, synthetic_call_result, - synthetic_frame_result, transaction_body_bytes, tx_body_history_bytes, untouched_call_gas, - untouched_create_gas, validate_transaction_stateless, with_pools_of, write_record_history_gas, - BlockHashRecord, BucketRecord, BytePrice, DeclaredObserver, DynPrecompilesBuilder, EthSpecId, - IntrinsicGas, MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, - MegaSpecId, MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, - SatinPriceError, SatinPrices, TrustedObserver, CPHB_ENV_VAR, CPSB_ENV_VAR, HISTORY_GAS_PRICED, - LEGACY_SPEC_NAMES, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, + active_satin_prices, history_allowance_gas, history_gas, kzg_point_evaluation, name, + satin_gas_params, satin_gas_params_at, satin_gas_params_history_exempt, satin_precompiles, + satin_precompiles_map, spec_cfg, synthetic_call_result, synthetic_frame_result, + transaction_body_bytes, tx_body_history_bytes, untouched_call_gas, untouched_create_gas, + validate_transaction_stateless, write_record_history_gas, BlockHashRecord, BucketRecord, + BytePrice, DynPrecompilesBuilder, EthSpecId, IntrinsicGas, MegaContext, MegaEvm, MegaEvmError, + MegaEvmFactory, MegaGasUsage, MegaHandler, MegaSpecId, MegaTransactionOutcome, OpSpecId, + OracleRead, OracleReadRecord, ParseMegaSpecError, SatinPriceError, SatinPrices, CPHB_ENV_VAR, + CPSB_ENV_VAR, HISTORY_ALLOWANCE_BYTES, HISTORY_GAS_PRICED, LEGACY_SPEC_NAMES, + STATE_GAS_REPRICED, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; #[cfg(any(test, feature = "test-utils"))] pub use external::{ @@ -67,7 +66,7 @@ pub use external::{ }; pub use limit::{ decode_mega_limit_exceeded, log_history_bytes, AdditionalLimit, EvmTxRuntimeLimits, LimitCheck, - LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, StagedRecord, ACCESS_LIST_ADDRESS_SIZE, + LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, @@ -79,7 +78,7 @@ pub use types::{ /* Items the crate's modules share through the root, not part of the public surface */ pub(crate) use block::transact_pre_block_call; pub(crate) use evm::{ - charge_write_records_history, MegaInnerContext, MegaInstructions, PricedPrecompiles, + charge_write_records_history, hold_creator, MegaInstructions, PricedPrecompiles, }; /* Re-export of upstream crates, so consumers build against the exact versions used here */ diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs deleted file mode 100644 index 6c6d19214..000000000 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ /dev/null @@ -1,706 +0,0 @@ -//! The per-frame tracker of data-size bytes and write records. -//! -//! Every frame on the call stack has a lane. What a frame writes is counted on its lane; when the -//! frame returns, a success merges the lane into its caller's and a failure discards it, the way -//! the journal keeps or reverts the writes themselves. What is counted outside any frame (the -//! records of applied EIP-7702 authorities) and what the outermost frame kept sit on the -//! transaction's own lane. -//! -//! The history bytes a frame appends beside its write records — its logs, and the code it -//! deposits when it is a creation — ride on the same lanes and follow the same rule, so what a -//! transaction reports it appended is what it kept. -//! -//! Every operation is O(1): the totals are cached and kept in step with each change. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use alloy_primitives::Address; - -use super::{LimitUsage, WRITE_RECORD}; - -/// One frame's lane. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Lane { - /// History gas the caller paid for the records on this lane, which the frame's failure gives - /// back to it. - pub(crate) history_charge: u64, - /// History gas the caller paid for the record of its own account - /// ([`holds_caller_record`](Self::holds_caller_record)), which follows that record's own - /// lifetime: a value transfer's sender record dies with the frame, a creation's nonce record - /// outlives it. - pub(crate) caller_history_charge: u64, - /// Whether the writes this lane stands for were recorded at all. False for a frame answered - /// without running, whose caller paid for records nothing ever made. - pub(crate) records_made: bool, - /// What the frame, and the children it kept, counted. - pub(crate) used: LimitUsage, - /// What the frame, and the children it kept, took back: a slot written back to its original - /// value. - pub(crate) refund: LimitUsage, - /// The account the frame runs as. `None` until known (a creation learns it at frame init). - pub(crate) address: Option
, - /// Whether a write to the frame's own account is already counted, so a value transfer or a - /// creation from the frame does not count it again. - pub(crate) account_recorded: bool, - /// Whether this lane holds the record of its caller's account, made when the frame started - /// (a value transfer's sender, a creation's creator). Its failure discards that record, so the - /// caller's account is no longer recorded either. - pub(crate) holds_caller_record: bool, - /// Whether the caller's record on this lane is a creator's nonce, which survives the - /// creation's failure once the nonce was bumped. - pub(crate) creator_record: bool, - /// The most data-size bytes the frame may keep, `u64::MAX` where the frame has no budget. - pub(crate) budget: u64, - /// What is left of the history allowance this frame was granted, if it was granted one. It - /// never enters the frame's gas, and what it does not spend disappears with the frame. - pub(crate) stipend_remaining: u64, - /// The history bytes the frame, and the children it kept, appended that are not write - /// records: the logs it emitted and, when it is a creation, the code it deposits. Its write - /// records are history too, and are counted in [`used`](Self::used), as are these bytes. - pub(crate) log_and_code_bytes: u64, -} - -impl Lane { - /// A lane for a frame running as `address`, whose caller paid `history_charge` for the - /// records the frame's start makes on it. - pub(crate) const fn new( - address: Option
, - account_recorded: bool, - budget: u64, - history_charge: u64, - ) -> Self { - Self { - used: LimitUsage::ZERO, - refund: LimitUsage::ZERO, - history_charge, - caller_history_charge: 0, - records_made: true, - address, - account_recorded, - holds_caller_record: false, - creator_record: false, - budget, - stipend_remaining: 0, - log_and_code_bytes: 0, - } - } - - /// A lane for a frame that does not run: a result built without an interpreter. Its caller - /// paid `history_charge` for records nothing made, so all of it comes back. - pub(crate) const fn empty(history_charge: u64) -> Self { - Self { records_made: false, ..Self::new(None, false, u64::MAX, history_charge) } - } - - /// The history gas the caller gets back when this frame returns. - /// - /// Everything, when the writes were never recorded; what the frame's failure discards, when - /// they were; nothing, when the frame kept them. A creation's nonce record survives the - /// creation's failure, so the caller keeps paying for it. - pub(crate) const fn history_refund(&self, success: bool) -> u64 { - if !self.records_made { - return self.history_charge.saturating_add(self.caller_history_charge); - } - if success { - return 0; - } - if self.creator_record { - self.history_charge - } else { - self.history_charge.saturating_add(self.caller_history_charge) - } - } - - /// Whether the frame's return hands its caller what no check held the caller to: a failed - /// creation's nonce record, which outlives it and lands on the creator's lane - /// ([`FrameLimitTracker::pop`]), or a success past the frame's own budget, which no frame - /// returns — a frame past its budget failed, and a failure an inspector rewrites into a success - /// has its lane discarded first ([`FrameLimitTracker::discard_running_lane`]) — and which is - /// held all the same. - /// - /// Any other return hands the caller nothing, or what the frame kept within its budget, which - /// is at most the share of what the caller had left. - pub(crate) const fn hands_caller_unchecked(&self, success: bool) -> bool { - if success { - // A lane that stands in for a creation's discarded one carries its creator's nonce - // record, which the discard already landed on the creator. - self.net().exceeds_data_size(self.budget) || (!self.records_made && self.creator_record) - } else { - self.creator_record - } - } - - /// What the frame keeps if it succeeds. - pub(crate) const fn net(&self) -> LimitUsage { - self.used.saturating_sub(self.refund) - } - - /// The data-size bytes the frame may still keep. - pub(crate) const fn remaining_budget(&self) -> u64 { - self.budget.saturating_sub(self.net().data_size) - } -} - -/// The lanes of the running transaction. -#[derive(Clone, Debug, Default)] -pub(crate) struct FrameLimitTracker { - /// What the transaction counted outside any running frame, and what the outermost frame kept. - tx_used: LimitUsage, - /// What the outermost frame kept of its refunds. - tx_refund: LimitUsage, - /// One lane per frame on the call stack, the running frame last. - lanes: Vec, - /// `tx_used` plus every lane's `used`. - total_used: LimitUsage, - /// `tx_refund` plus every lane's `refund`. - total_refund: LimitUsage, - /// The log and code bytes the outermost frame kept, plus every lane's. - log_and_code_bytes: u64, -} - -impl FrameLimitTracker { - /// Clears the tracker for a new transaction, keeping its allocation. - pub(crate) fn reset(&mut self) { - self.tx_used = LimitUsage::ZERO; - self.tx_refund = LimitUsage::ZERO; - self.lanes.clear(); - self.total_used = LimitUsage::ZERO; - self.total_refund = LimitUsage::ZERO; - self.log_and_code_bytes = 0; - } - - /// The number of lanes, which is the number of frames on the call stack. - pub(crate) fn depth(&self) -> usize { - self.lanes.len() - } - - /// What the transaction keeps if every running frame succeeds. - pub(crate) const fn net(&self) -> LimitUsage { - self.total_used.saturating_sub(self.total_refund) - } - - /// The history bytes the transaction appended beside its write records — its logs and the - /// code it deposited — with every running frame counted as if it succeeds. - pub(crate) const fn log_and_code_bytes(&self) -> u64 { - self.log_and_code_bytes - } - - /// The running frame's lane. - pub(crate) fn current(&self) -> Option<&Lane> { - self.lanes.last() - } - - /// The running frame's lane, mutably. - pub(crate) fn current_mut(&mut self) -> Option<&mut Lane> { - self.lanes.last_mut() - } - - /// Grants the running frame a history allowance of `amount`. - /// - /// Must run right after the frame's lane was pushed: the allowance belongs to the frame that - /// is starting, not to the one that granted it. - pub(crate) fn grant_stipend(&mut self, amount: u64) { - if let Some(lane) = self.lanes.last_mut() { - lane.stipend_remaining = amount; - } - } - - /// Draws up to `amount` from the running frame's allowance and reports what it gave. The - /// caller pays the rest out of the frame's gas. - pub(crate) fn consume_stipend(&mut self, amount: u64) -> u64 { - let Some(lane) = self.lanes.last_mut() else { return 0 }; - let drawn = lane.stipend_remaining.min(amount); - lane.stipend_remaining -= drawn; - drawn - } - - /// Pushes the lane of a frame that starts. - pub(crate) fn push(&mut self, lane: Lane) { - self.total_used = self.total_used.saturating_add(lane.used); - self.total_refund = self.total_refund.saturating_add(lane.refund); - self.lanes.push(lane); - } - - /// Counts `usage` on the running frame's lane, or on the transaction's outside any frame. - pub(crate) fn record(&mut self, usage: LimitUsage) { - match self.lanes.last_mut() { - Some(lane) => lane.used = lane.used.saturating_add(usage), - None => self.tx_used = self.tx_used.saturating_add(usage), - } - self.total_used = self.total_used.saturating_add(usage); - } - - /// Counts `bytes` of a log or of deposited code on the running frame's lane, or on the - /// transaction's outside any frame. - pub(crate) fn record_log_and_code_bytes(&mut self, bytes: u64) { - if let Some(lane) = self.lanes.last_mut() { - lane.log_and_code_bytes = lane.log_and_code_bytes.saturating_add(bytes); - } - self.log_and_code_bytes = self.log_and_code_bytes.saturating_add(bytes); - } - - /// Counts `usage` on the transaction's own lane, whatever frame is running: what it stands - /// for is outside the state, so no frame's failure takes it back. - pub(crate) fn record_tx(&mut self, usage: LimitUsage) { - self.tx_used = self.tx_used.saturating_add(usage); - self.total_used = self.total_used.saturating_add(usage); - } - - /// Takes `usage` back on the running frame's lane. Outside any frame nothing is taken back. - pub(crate) fn refund(&mut self, usage: LimitUsage) { - if let Some(lane) = self.lanes.last_mut() { - lane.refund = lane.refund.saturating_add(usage); - self.total_refund = self.total_refund.saturating_add(usage); - } - } - - /// Records the running frame's caller's account on the running frame's lane, unless the - /// caller's lane already counts it. A `creator` record is a creation's nonce, and - /// `history_charge` is what the caller paid for the record. - /// - /// Must run right after the running frame's lane was pushed, with the caller's lane below it. - pub(crate) fn record_caller(&mut self, creator: bool, history_charge: u64) { - let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; - if caller.account_recorded { - return; - } - caller.account_recorded = true; - lane.holds_caller_record = true; - lane.creator_record = creator; - lane.caller_history_charge = history_charge; - lane.used = lane.used.saturating_add(WRITE_RECORD); - self.total_used = self.total_used.saturating_add(WRITE_RECORD); - } - - /// Settles the running frame's lane as its failure would, before the frame returns: what it - /// counted is discarded, its caller's record with it, and an empty lane stands in for it, - /// holding the history its caller gets back for records the failure did not keep. So the frame - /// returns into its caller as a frame that made nothing, whatever it is popped with. - /// - /// For a frame whose journal checkpoint was reverted and whose result then became a success - /// all the same: the lane follows the checkpoint, not the result. - /// - /// A creation's nonce record outlives its failure, so it has landed on the creator's lane - /// unchecked, and the stand-in remembers it: the creator is held to its budget when the - /// stand-in returns, as it is when the creation fails. - pub(crate) fn discard_running_lane(&mut self) { - let Some(lane) = self.pop(false) else { return }; - let mut standing_in = Lane::empty(lane.history_refund(false)); - standing_in.creator_record = lane.creator_record; - self.lanes.push(standing_in); - } - - /// Takes the record of the running frame's own account back from its lane, where a child - /// left it: the nonce record of a creation that failed, whose bump is being taken back. - /// Returns whether the account was recorded, and so whether there was a record to take. - pub(crate) fn take_back_own_record(&mut self) -> bool { - let Some(lane) = self.lanes.last_mut() else { return false }; - if !lane.account_recorded { - return false; - } - lane.account_recorded = false; - lane.used = lane.used.saturating_sub(WRITE_RECORD); - self.total_used = self.total_used.saturating_sub(WRITE_RECORD); - true - } - - /// Pops the lane of the frame that returned: `success` merges it into its caller's lane (or - /// the transaction's), a failure discards it. - /// - /// A creator's record outlives the creation's failure and lands on the caller's lane, which - /// nothing here holds to its budget; any other record of the caller dies with it, and the - /// caller's account stops counting as recorded. - #[inline] - pub(crate) fn pop(&mut self, success: bool) -> Option { - let lane = self.lanes.pop()?; - if success { - match self.lanes.last_mut() { - Some(caller) => { - caller.used = caller.used.saturating_add(lane.used); - caller.refund = caller.refund.saturating_add(lane.refund); - caller.log_and_code_bytes = - caller.log_and_code_bytes.saturating_add(lane.log_and_code_bytes); - if lane.address.is_some() && lane.address == caller.address { - caller.account_recorded |= lane.account_recorded; - } - } - None => { - self.tx_used = self.tx_used.saturating_add(lane.used); - self.tx_refund = self.tx_refund.saturating_add(lane.refund); - } - } - return Some(lane); - } - self.total_used = self.total_used.saturating_sub(lane.used); - self.total_refund = self.total_refund.saturating_sub(lane.refund); - self.log_and_code_bytes = self.log_and_code_bytes.saturating_sub(lane.log_and_code_bytes); - if let Some(caller) = self.lanes.last_mut() { - if lane.creator_record { - caller.used = caller.used.saturating_add(WRITE_RECORD); - self.total_used = self.total_used.saturating_add(WRITE_RECORD); - } else if lane.holds_caller_record { - caller.account_recorded = false; - } - } - Some(lane) - } - - /// Whether the return of `returned`, the lane just popped with `success`, handed the running - /// frame what no check held it to ([`Lane::hands_caller_unchecked`]). - /// - /// A return into no lane hands nothing that needs holding: what the transaction's own frame - /// keeps goes to the transaction, which has no budget of its own and whose total the return - /// does not grow, and no frame runs on after it. - pub(crate) fn hands_unchecked(&self, returned: &Lane, success: bool) -> bool { - !self.lanes.is_empty() && returned.hands_caller_unchecked(success) - } - - /// [`net`](Self::net) recomputed from the lanes, for checking the cache. - #[cfg(test)] - pub(crate) fn net_uncached(&self) -> LimitUsage { - let mut used = self.tx_used; - let mut refund = self.tx_refund; - for lane in &self.lanes { - used = used.saturating_add(lane.used); - refund = refund.saturating_add(lane.refund); - } - used.saturating_sub(refund) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::address; - - const ADDR: Address = address!("0000000000000000000000000000000000001234"); - - const fn bytes(data_size: u64) -> LimitUsage { - LimitUsage { data_size, write_records: 0 } - } - - /// The depth and the running lane follow the frame stack: a push adds a lane and a pop takes - /// the running one away, whatever the frame's outcome. - #[test] - fn test_depth_and_the_running_lane_follow_the_frame_stack() { - let mut t = FrameLimitTracker::default(); - assert_eq!(t.depth(), 0); - assert!(t.current().is_none(), "no frame has started"); - t.push(Lane::new(Some(ADDR), false, 7, 0)); - t.push(Lane::empty(0)); - assert_eq!(t.depth(), 2); - assert_eq!(t.current().unwrap().address, None, "the empty lane is the running one"); - assert!(t.pop(false).is_some()); - assert_eq!(t.depth(), 1); - assert_eq!(t.current().unwrap().budget, 7); - assert!(t.pop(true).is_some()); - assert_eq!(t.depth(), 0); - assert!(t.current().is_none()); - assert!(t.pop(true).is_none(), "there is nothing left to pop"); - } - - /// Recording a caller on an empty stack, or on a lane with no caller below it, is a no-op. - #[test] - fn test_record_caller_without_a_caller_lane_is_noop() { - let mut t = FrameLimitTracker::default(); - t.record_caller(true, 0); - assert_eq!(t.net(), LimitUsage::ZERO); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record_caller(true, 0); - assert_eq!(t.net(), LimitUsage::ZERO); - assert!(!t.current().unwrap().holds_caller_record); - } - - /// A frame's caller is recorded once per caller frame: a second child finds it recorded. - #[test] - fn test_record_caller_records_a_caller_once() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - assert!(t.pop(true).is_some()); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - assert!(!t.current().unwrap().holds_caller_record, "the caller is recorded already"); - assert_eq!(t.net(), WRITE_RECORD); - } - - /// The cached totals match the lanes after every push, record, refund and pop. - #[test] - fn test_net_usage_cache_matches_uncached() { - let mut t = FrameLimitTracker::default(); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), LimitUsage::ZERO); - - // Outside any frame, usage goes to the transaction and nothing is taken back. - t.record(bytes(100)); - t.refund(bytes(50)); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), bytes(100)); - - // Frame 1. - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record(bytes(30)); - t.refund(bytes(10)); - assert_eq!(t.net(), t.net_uncached()); - - // Frame 2, nested. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(15)); - t.refund(bytes(3)); - assert_eq!(t.net(), t.net_uncached()); - - // Frame 3 fails: its usage and refund leave the totals. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(11)); - t.refund(bytes(2)); - let before_revert = t.net(); - let popped = t.pop(false).expect("frame 3 popped"); - assert_eq!((popped.used, popped.refund), (bytes(11), bytes(2))); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), bytes(before_revert.data_size - 9)); - - // Frame 3 again, succeeding: merging moves usage, the totals do not change. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(6)); - t.refund(bytes(1)); - let before_success = t.net(); - t.pop(true); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), before_success); - - // Frame 2 succeeds into frame 1; frame 1 fails. - t.pop(true); - assert_eq!(t.net(), t.net_uncached()); - let frame_1 = t.pop(false).expect("frame 1 popped"); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), bytes(100), "only the transaction's own usage is left"); - assert_eq!(frame_1.net(), bytes(30 + 15 + 6 - 10 - 3 - 1)); - - t.reset(); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), LimitUsage::ZERO); - assert_eq!(t.depth(), 0); - } - - /// Log and code bytes follow the frame that appended them: a running frame counts as if it - /// succeeds, a success hands them to its caller, a failure discards them, and what was - /// counted outside any frame is the transaction's. - #[test] - fn test_log_and_code_bytes_follow_their_frame() { - let mut t = FrameLimitTracker::default(); - t.record_log_and_code_bytes(5); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record_log_and_code_bytes(10); - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record_log_and_code_bytes(100); - assert_eq!(t.log_and_code_bytes(), 115); - - let failed = t.pop(false).expect("the child popped"); - assert_eq!(failed.log_and_code_bytes, 100); - assert_eq!(t.log_and_code_bytes(), 15, "the failed child's bytes are gone"); - - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record_log_and_code_bytes(20); - t.pop(true); - assert_eq!(t.log_and_code_bytes(), 35); - assert_eq!( - t.current().unwrap().log_and_code_bytes, - 30, - "the kept child's are its caller's" - ); - - t.pop(false); - assert_eq!(t.log_and_code_bytes(), 5, "only what was outside the outermost frame is left"); - - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record_log_and_code_bytes(7); - t.pop(true); - assert_eq!(t.log_and_code_bytes(), 12, "the outermost frame's success keeps its bytes"); - - t.reset(); - assert_eq!(t.log_and_code_bytes(), 0); - } - - /// A refund larger than the usage clamps the net at zero. - #[test] - fn test_net_usage_saturates_when_refund_exceeds_used() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(10)); - t.refund(bytes(100)); - assert_eq!(t.net(), LimitUsage::ZERO); - assert_eq!(t.net(), t.net_uncached()); - t.pop(true); - assert_eq!(t.net(), LimitUsage::ZERO); - assert_eq!(t.net(), t.net_uncached()); - } - - /// A value transfer's sender record dies with the child that failed, and the caller can be - /// recorded again; a creator's record survives the creation's failure. - #[test] - fn test_failed_child_discards_sender_record_but_keeps_creator_record() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(false, 0); - t.record(WRITE_RECORD); - t.pop(false); - assert_eq!(t.net(), LimitUsage::ZERO); - assert!(!t.current().unwrap().account_recorded, "the sender record died with the child"); - - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - t.record(WRITE_RECORD); - t.pop(false); - assert_eq!(t.net(), WRITE_RECORD, "the creator's nonce outlives the creation"); - assert!(t.current().unwrap().account_recorded); - assert_eq!(t.net(), t.net_uncached()); - } - - /// A return hands its caller what no check held the caller to in two cases: the nonce record - /// a failed creation leaves its creator, and a success past the frame's own budget. A success - /// within its budget hands over no more than that budget, and any other failure hands over - /// nothing. - #[test] - fn test_what_a_return_hands_its_caller_unchecked() { - let budget = 200; - // The record of the caller's account the child holds (a creator's or a sender's), the - // bytes it counted beside it, and whether it succeeded. - for (creator, counted, success, unchecked) in [ - (false, 160, true, false), - (true, 160, true, false), - (false, 161, true, true), - (false, 161, false, false), - (false, 0, false, false), - (true, 0, false, true), - ] { - let case = format!("creator {creator}, {counted} bytes, success {success}"); - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(None, true, budget, 0)); - t.record_caller(creator, 0); - t.record(bytes(counted)); - let lane = t.pop(success).unwrap(); - assert_eq!(lane.hands_caller_unchecked(success), unchecked, "{case}"); - let handed = t.net(); - let past_budget = handed.exceeds_data_size(budget); - if success { - assert_eq!(past_budget, unchecked, "{case}: a success hands over what it kept"); - } else { - assert_eq!(handed != LimitUsage::ZERO, unchecked, "{case}: a failure, the record"); - } - } - } - - /// The return of the transaction's own frame hands nothing unchecked, whatever it kept: there - /// is no lane left to hand it to. With a frame below it, the same return does. - #[test] - fn test_a_return_into_no_lane_hands_nothing_unchecked() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, 200, 0)); - t.record(bytes(201)); - let lane = t.pop(true).unwrap(); - assert!(lane.hands_caller_unchecked(true), "it kept more than its budget"); - assert!(!t.hands_unchecked(&lane, true), "but no frame is left to hand it to"); - - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - assert!(t.hands_unchecked(&lane, true), "a caller is"); - assert!(!t.hands_unchecked(&lane, false), "which a failure hands nothing"); - } - - /// A lane discarded before its frame returns keeps nothing, whatever it is popped with: what - /// it counted leaves the totals, its caller's account stops counting as recorded, and the - /// empty lane in its place hands the caller back what the failure gives back — here the - /// charges for the lane's record and for the caller's own. - #[test] - fn test_a_discarded_lane_keeps_nothing_and_gives_the_failures_history_back() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record(bytes(10)); - t.push(Lane::new(None, false, 100, 7)); - t.record_caller(false, 3); - t.record(WRITE_RECORD); - t.record_log_and_code_bytes(5); - t.discard_running_lane(); - - assert_eq!(t.depth(), 2, "an empty lane stands in for the frame"); - let lane = *t.current().unwrap(); - assert!(!lane.records_made); - assert_eq!(lane.used, LimitUsage::ZERO); - assert_eq!(lane.address, None); - assert_eq!(lane.budget, u64::MAX); - assert_eq!(t.net(), bytes(10), "only the caller's count is left"); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.log_and_code_bytes(), 0); - assert!(!t.lanes[0].account_recorded, "the caller's record went with the frame"); - - let popped = t.pop(true).unwrap(); - assert_eq!(popped.history_refund(true), 7 + 3, "the lane's record and the caller's"); - assert!(!t.hands_unchecked(&popped, true), "it hands nothing"); - assert_eq!(t.net(), bytes(10)); - - // A creator's nonce record outlives the creation: the discard lands it on the creator, - // and the history the creator paid for it is not given back. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record_caller(true, 4); - t.discard_running_lane(); - assert_eq!(t.net(), bytes(10).saturating_add(WRITE_RECORD)); - let popped = t.pop(true).unwrap(); - assert_eq!(popped.history_refund(true), 0); - assert!(t.hands_unchecked(&popped, true), "the creator is held to its budget with it"); - - // With no lane to discard, nothing happens. - let mut empty = FrameLimitTracker::default(); - empty.discard_running_lane(); - assert_eq!(empty.depth(), 0); - } - - /// The creator record a failed creation left its creator is taken back once, and a lane with - /// no record of its own account has nothing to take. - #[test] - fn test_take_back_own_record_takes_the_creator_record_once() { - let mut t = FrameLimitTracker::default(); - assert!(!t.take_back_own_record(), "no lane"); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record(bytes(7)); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - t.pop(false); - assert_eq!(t.net(), bytes(7).saturating_add(WRITE_RECORD)); - - assert!(t.take_back_own_record()); - assert_eq!(t.net(), bytes(7), "the record, and nothing else, is gone"); - assert!(!t.current().unwrap().account_recorded); - assert!(!t.take_back_own_record(), "taken once"); - assert_eq!(t.net(), bytes(7)); - assert_eq!(t.net(), t.net_uncached()); - } - - /// A child running as its caller's account hands its record flag back on success. - #[test] - fn test_same_account_child_merges_the_recorded_flag() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); - t.pop(true); - assert!(t.current().unwrap().account_recorded); - - let other = address!("0000000000000000000000000000000000005678"); - t.push(Lane::new(Some(other), false, u64::MAX, 0)); - t.push(Lane::new(Some(other), false, u64::MAX, 0)); - t.current_mut().unwrap().account_recorded = true; - t.pop(false); - assert!(!t.current().unwrap().account_recorded, "a failed child hands nothing back"); - - t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); - assert_eq!(t.depth(), 3); - t.pop(true); - assert!(!t.current().unwrap().account_recorded, "another account's flag is its own"); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.pop(true); - assert!(!t.current().unwrap().account_recorded, "an unknown account is not the caller's"); - } -} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6cc04a504..4e772df15 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,62 +1,87 @@ //! The per-transaction state of the common execution layer. -use alloy_primitives::{Address, Bytes}; +use alloy_primitives::Bytes; use revm::{ - context_interface::context::CodeDeposit, + context_interface::cfg::gas::{GasTracker, PoolAmounts, PoolId}, handler::FrameResult, - interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, + interpreter::InstructionResult, }; +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + use super::{ - frame_limit::{FrameLimitTracker, Lane}, - record::{HistoryBytes, RecordEffect, StagedRecord}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, WRITE_RECORD_SIZE, + CreatorBefore, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, COUNTED, DATA_SIZE_POOL, + KV_UPDATE_POOL, STATE_GROWTH_POOL, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; -use crate::storage_call_stipend; -/// What the common execution layer tracks for the running transaction: the per-frame lanes of -/// data-size bytes and write records, the record the Host staged for the running opcode, the stops -/// its frames return, and whether it is exempt from every limit. +/// What the common execution layer tracks for the running transaction: what it keeps of the +/// data-size, KV-update and state-growth limits and of the frame budgets, the stops its frames +/// return, whether it is exempt from every limit, and the figures the settled transaction reports. +/// +/// It lives on the [`MegaContext`](crate::MegaContext), is begun before each transaction and +/// system call, and is driven by the Host's hooks (a completed write, a frame's start, a code +/// deposit) and by the frame lifecycle (a start revm decided, a frame's return, the stops). +/// +/// # The three counted dimensions +/// +/// Data size, KV updates (write records) and state growth are each limited per transaction and +/// per frame ([`COUNTED`]). A frame's budget in a dimension is a pool on its gas tracker +/// ([`LimitKind::pool`]), which the revm fork forwards and settles as it does the reservoir: the +/// transaction's own frame gets what the transaction has left once its body and the counts made +/// before it are counted ([`first_frame_pools`](Self::first_frame_pools)), every child the +/// schedule's share of what its caller has left (98/100: the caller keeps +/// `GasId::pool_kept_percent`) under the frame cap, a failing frame's draws go back to its pool and +/// a successful one hands its signed net to its caller. A count is drawn where it is made, on the +/// pool of the frame that makes it ([`draw`](Self::draw)): a completed write's record or log, a +/// frame start's records and transfer log on the started frame, deployed code on the creating +/// frame. A creator's nonce record is the creating frame's own, drawn on its pools once the +/// creation returned into it with the nonce bumped ([`close_start`](Self::close_start) hands back +/// what tells): the creation's budgets were taken before it. /// -/// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and -/// system call, and is driven by the Host (staging), the opcode wrappers (commit and discard) -/// and the frame lifecycle (lanes, stops). +/// The transaction's limits are held beside the pools, on what the transaction keeps +/// ([`usage`](Self::usage)): its body, its Oracle hints, the records of its applied authorities, +/// and what its frames keep ([`Kept`]), counted with every draw and restored to what it was at a +/// start when that start's frame kept nothing ([`close_start`](Self::close_start)). The transfer +/// logs the transaction reports apart from its bytes are kept beside them, and restored with them. +/// +/// An operation that crosses more than one dimension stops on the first of them in [`COUNTED`]'s +/// order, and inside a dimension the frame's budget is tested before the transaction's limit: the +/// stop names the budget when the budget is crossed, the transaction's limit only when it is not. +/// A fall — a record taken back, a byte given back — crosses nothing. /// /// # The stop /// /// A limit crossed stops the frame that crossed it with a revert, not a halt: the frame reverts /// with [`MegaLimitExceeded`](crate::MegaLimitExceeded) as its output, whether it crossed the /// transaction's limit or its own frame budget, and its caller resumes as after any revert. What -/// the frame counted goes with it, so a caller that resumes is back within the limits, and a +/// the frame counted goes with it, so a caller that resumes is back within the limits, but where +/// the failure put back a record a frame above made while an Oracle hint the failed frame sent +/// stays: the caller is then stopped as it resumes ([`hold_caller`](Self::hold_caller)). A /// transaction never keeps more than its limit: a caller that carries on is held to what is left, -/// and a charge that crosses again stops the frame that makes it. A crossing the transaction's -/// own frame makes is the transaction's result, which settles like any EIP-8037 revert: its -/// unspent regular gas and the reservoir go back to the sender, who pays only for what ran. -/// Exceptional halts (a real out-of-gas, an invalid opcode) are not limit stops and still burn the -/// frame's gas. +/// and a charge that crosses again stops the frame that makes it. A crossing the transaction's own +/// frame makes is the transaction's result, which settles like any EIP-8037 revert: its unspent +/// regular gas and the reservoir go back to the sender, who pays only for what ran. Exceptional +/// halts (a real out-of-gas, an invalid opcode) are not limit stops and still burn the frame's gas. /// /// # The exemption /// /// The protocol's own work is held to none of the per-transaction limits: a system-originated -/// transaction and a system call are marked exempt before their body is counted, and the mark is +/// transaction and a system call are begun exempt, before their body is counted, and the mark is /// sticky for the transaction ([`is_exempt`](Self::is_exempt)). Every stop the layer hands out -/// comes from one place ([`crossed`](Self::crossed)), which answers an exempt transaction with -/// [`LimitCheck::WithinLimit`] whatever it crossed — a transaction limit or a frame budget, in -/// any dimension. -/// What the transaction uses is counted all the same, so its usage is reported as any other +/// comes from [`crossed`](Self::crossed), which answers an exempt transaction with +/// [`LimitCheck::WithinLimit`] whatever it crossed, and an exempt transaction's pools are +/// unlimited. What it uses is counted all the same, so its usage is reported as any other /// transaction's is. #[derive(Clone, Debug, Default)] pub struct AdditionalLimit { - pub(crate) tracker: FrameLimitTracker, - staged: Option, limits: EvmTxRuntimeLimits, /// Whether the transaction is exempt from every per-transaction limit, sticky for the - /// transaction. See [`exempt`](Self::exempt). + /// transaction. See [`is_exempt`](Self::is_exempt). exempt: bool, - /// The stop the frame a child returned into must return instead of running on, when what the - /// child left it put it over a limit. See [`on_frame_return`](Self::on_frame_return). - resume_stop: Option, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, /// The crossing the result of the frame returning next was made of, noted where the stop /// became that result ([`note_frame_stop`](Self::note_frame_stop)) and taken when the frame /// returns. @@ -64,1344 +89,833 @@ pub struct AdditionalLimit { /// The crossing that produced the result of the transaction's own frame, if one did. See /// [`limit_exceeded`](Self::limit_exceeded). limit_exceeded: Option, - /// Whether the transaction's call target is an applied EIP-7702 authority, whose account - /// write the transaction's lane already counts. - target_is_authority: bool, - /// The transaction's sender, whose account write is part of the transaction body: a frame - /// running as the sender never records it. - sender: Address, - /// Whether the transaction's first frame reached frame init. When it did not, the runtime - /// phase before it ran out of gas and took back the authorizations applied before it. The - /// body stays; see [`on_last_frame_return`](Self::on_last_frame_return). - frame_began: bool, - /// Data-size bytes of the transaction's body. Recorded before any frame and kept on every - /// path, including an out-of-gas before the first frame, which clears the rest of the tracker. - body_bytes: u64, - /// The history gas validation charged for the transaction's body, part of + /// The data-size bytes of the transaction's body. + body: u64, + /// The data-size bytes of the Oracle hints the transaction forwarded, never taken back. + hints: u64, + /// The write records of the EIP-7702 authorities the transaction applied. + authorities: u64, + /// The accounts the EIP-7702 authorities the transaction applied created. + created_authorities: u64, + /// Whether the transaction created its caller's account before its first frame: a + /// deposit-like transaction whose caller had none. Never taken back. + created_caller: bool, + /// The stop the transaction's own frame returns before it runs, when its authorization list + /// would have kept more than a limit allows and was skipped + /// ([`skip_authorization_list`](Self::skip_authorization_list)). + pre_frame_stop: Option, + /// What the transaction's frames keep, every running frame counted as if it succeeds. + kept: Kept, + /// One per start revm decided whose result has not returned, the latest last. + decided: Vec, + /// The history gas of the transaction's body, part of /// [`history_gas_spent`](Self::history_gas_spent). intrinsic_history_gas: u64, - /// The bytes of the transaction's body that - /// [`intrinsic_history_gas`](Self::intrinsic_history_gas) paid for, part of - /// [`history_bytes`](Self::history_bytes). + /// The bytes of the body that [`intrinsic_history_gas`](Self::intrinsic_history_gas) paid + /// for, part of [`history_bytes`](Self::history_bytes). intrinsic_history_bytes: u64, - /// The history gas of the write record the transaction's own frame makes — its value's - /// recipient, or the account it creates — charged before the first frame and given back when - /// that frame fails. - top_level_write_record_gas: u64, - /// The write records the transaction's own frame makes, as the charge of their history before - /// execution found them, for [`push_lane`](Self::push_lane) to check its own count against. - /// See [`stage_top_level_records`](Self::stage_top_level_records). - pending_top_level_records: Option, - /// The history gas the running opcode charged its own frame for the records the frame it is - /// starting will make, waiting for that frame's lane to be pushed. - pending_frame_charge: FrameCharge, - /// Whether revm refuses, on its caller's account, the start of the frame the last - /// frame-starting opcode suspended on — or, before the first frame, the transaction's own - /// frame — as that opcode, or the charge of the transaction's record, found it. See - /// [`stage_start_refused`](Self::stage_start_refused). - pending_start_refused: Option, + /// The history gas charged before the first frame for the write record that frame makes, + /// which the frame carries as its start charge. + first_frame_charge: u64, /// The history gas the settled transaction spent. history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, - /// Whether the running transaction's value movements journal EIP-7708 transfer logs, which - /// revm emits itself and the data size counts where the value moves. - transfer_logs: bool, + /// The EIP-8037 reservoir the settled transaction left unspent. + reservoir_remaining: u64, } -impl AdditionalLimit { - /// A layer enforcing `limits`. - pub fn new(limits: EvmTxRuntimeLimits) -> Self { - Self { limits, ..Default::default() } - } - - /// The limits enforced. - pub const fn limits(&self) -> &EvmTxRuntimeLimits { - &self.limits - } - - /// Replaces the limits enforced from the next transaction on. - pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { - self.limits = limits; - } - - /// Clears the state for a new transaction, keeping allocations and the limits. - pub(crate) fn reset(&mut self) { - self.tracker.reset(); - self.staged = None; - self.exempt = false; - self.resume_stop = None; - self.frame_stop = None; - self.limit_exceeded = None; - self.target_is_authority = false; - self.sender = Address::ZERO; - self.frame_began = false; - self.body_bytes = 0; - self.intrinsic_history_gas = 0; - self.intrinsic_history_bytes = 0; - self.top_level_write_record_gas = 0; - self.pending_top_level_records = None; - self.pending_frame_charge = FrameCharge::NONE; - self.pending_start_refused = None; - self.history_gas_spent = 0; - self.history_bytes = 0; - self.transfer_logs = false; - } - - /// Records whether the running transaction's value movements journal EIP-7708 transfer logs. - /// Called for every transaction, after the reset, from the configuration revm emits them by. - pub(crate) const fn set_transfer_logs(&mut self, emitted: bool) { - self.transfer_logs = emitted; - } - - /// Whether starting `input` journals an EIP-7708 transfer log in the running transaction. - /// See [`moves_value`]. - pub(crate) fn frame_start_transfer_log(&self, input: &FrameInput) -> bool { - self.transfer_logs && moves_value(input) - } - - /* The stops and the exemption */ - - /// The crossing that produced the result of the transaction's own frame, if one did: what - /// [`MegaTransactionOutcome::limit_exceeded`](crate::MegaTransactionOutcome) reports. - /// - /// It is a crossing the transaction's own frame made, of the transaction's limit or of its own - /// budget. A crossing below that frame produced the result of the frame that crossed, which its - /// caller caught: a caller that then reverts with the same bytes made its own result, and is no - /// stop. Neither is a stop an inspector rewrote into another result: the frame's result must - /// still be the stop's revert. - /// - /// It is the running transaction's, or the last one's until the next transaction or system - /// call starts: each resets it first. - pub const fn limit_exceeded(&self) -> Option<&LimitCheck> { - self.limit_exceeded.as_ref() - } +/// What a transaction's frames keep: the signed net of each counted dimension, indexed by its +/// pool, and, among the bytes, the EIP-7708 transfer logs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Kept { + /// The net count of each dimension: what the frames added less what they took back. + net: [i64; PoolId::COUNT], + /// EIP-7708 transfer logs. + transfer_logs: u64, +} - /// Notes `stop` as the crossing the result of the frame returning next is made of, and gives - /// the [`MegaLimitExceeded`](crate::MegaLimitExceeded) revert data that frame stops with. - /// - /// Every site that turns a crossing into a frame's result takes the revert data from here, and - /// the frame returns before any other does: so the stop is the returning frame's when - /// [`on_frame_return`](Self::on_frame_return) takes it, and the transaction's when that frame - /// is the transaction's own ([`limit_exceeded`](Self::limit_exceeded)). - pub(crate) fn note_frame_stop(&mut self, stop: &LimitCheck) -> Bytes { - debug_assert!(stop.exceeded_limit(), "only a crossing stops a frame"); - self.frame_stop = Some(*stop); - stop.revert_data() +impl Kept { + /// The net count of `kind`. + const fn net(&self, kind: LimitKind) -> i64 { + match kind.pool() { + Some(pool) => self.net[pool.index()], + None => 0, + } } +} - /// Whether the running transaction is exempt from every per-transaction limit. - pub const fn is_exempt(&self) -> bool { - self.exempt - } +/// What one write, or one frame start, adds to what a frame keeps and takes back from it, in each +/// counted dimension. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counted { + /// What it adds, per pool: data-size bytes (records, a log's bytes, deployed code, a transfer + /// log), write records, new accounts and slots. + pub(crate) added: PoolAmounts, + /// What it takes back, per pool: the records of accounts and slots returned to what the + /// transaction loaded, with their bytes; accounts and slots it removes. + pub(crate) taken: PoolAmounts, + /// Whether an EIP-7708 transfer log is among the bytes added. + pub(crate) transfer_log: bool, +} - /// Exempts the running transaction from every per-transaction limit, until the next - /// transaction resets the layer. - /// - /// Called for the protocol's own work — a system-originated transaction and a system call — - /// before its body is counted. See the type's documentation. - pub(crate) const fn exempt(&mut self) { - self.exempt = true; - } +impl Counted { + /// Nothing counted. + pub(crate) const NONE: Self = + Self { added: PoolAmounts::ZERO, taken: PoolAmounts::ZERO, transfer_log: false }; - /// The verdict on `used` crossing `kind`'s `limit`, a frame budget when `frame_local` and a - /// transaction-level limit otherwise: the stop the running frame reverts with, alone, its - /// [`LimitCheck::revert_data`] naming the limit crossed. - /// - /// Every stop the layer hands out comes from here, gas detention's included, so this is where - /// the exemption applies: an exempt transaction's verdict is [`LimitCheck::WithinLimit`], - /// whatever it crossed. - pub(crate) const fn crossed( - &self, - kind: LimitKind, - limit: u64, - used: u64, - frame_local: bool, - ) -> LimitCheck { - if self.exempt { - return LimitCheck::WithinLimit; + /// `added` write records made and `taken` taken back, with an EIP-7708 transfer log when + /// `transfer_log`: each record is [`WRITE_RECORD_SIZE`] bytes and one KV update. + pub(crate) const fn records(added: u64, taken: u64, transfer_log: bool) -> Self { + let log = if transfer_log { TRANSFER_LOG_SIZE } else { 0 }; + Self { + added: PoolAmounts::ZERO + .with(DATA_SIZE_POOL, WRITE_RECORD_SIZE.saturating_mul(added).saturating_add(log)) + .with(KV_UPDATE_POOL, added), + taken: PoolAmounts::ZERO + .with(DATA_SIZE_POOL, WRITE_RECORD_SIZE.saturating_mul(taken)) + .with(KV_UPDATE_POOL, taken), + transfer_log, } - LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// Checks the data-size limit after the running frame counted something: what the - /// transaction keeps against its limit, then what the running frame keeps against its budget. - /// A record that crosses both names the transaction's limit. - fn check(&self) -> LimitCheck { - let (kept, limit) = (self.tracker.net(), self.limits.tx_data_size_limit); - if kept.exceeds_data_size(limit) { - return self.crossed(LimitKind::DataSize, limit, kept.data_size, false); - } - if let Some(lane) = self.tracker.current() { - let (kept, budget) = (lane.net(), lane.budget); - if kept.exceeds_data_size(budget) { - return self.crossed(LimitKind::DataSize, budget, kept.data_size, true); - } + /// This count with `rise` new accounts or slots and `fall` accounts or slots it removes: its + /// state growth. + pub(crate) const fn with_growth(self, rise: u64, fall: u64) -> Self { + Self { + added: self.added.with(STATE_GROWTH_POOL, rise), + taken: self.taken.with(STATE_GROWTH_POOL, fall), + transfer_log: self.transfer_log, } - LimitCheck::WithinLimit } - /// The stop the running frame returns instead of running another instruction: the one - /// [`on_frame_return`](Self::on_frame_return) left for a caller its child put over a limit. - /// Taking it clears it, which stops one frame. - pub(crate) const fn stop_before_run(&mut self) -> Option { - self.resume_stop.take() + /// `bytes` bytes that are no write record: a log's, or deployed code. + pub(crate) const fn bytes(bytes: u64) -> Self { + Self { added: PoolAmounts::ZERO.with(DATA_SIZE_POOL, bytes), ..Self::NONE } } - /// What the transaction keeps so far: its data-size bytes and write records, with every - /// running frame counted as if it succeeds. - pub fn usage(&self) -> LimitUsage { - self.tracker.net() + /// This count with `bytes` more bytes that are no write record taken back: deployed code a + /// destruction takes back. + pub(crate) const fn plus_bytes_taken(self, bytes: u64) -> Self { + let taken = self.taken.get(DATA_SIZE_POOL).saturating_add(bytes); + Self { taken: self.taken.with(DATA_SIZE_POOL, taken), ..self } } - /// The history gas the last settled transaction spent. - pub const fn history_gas_spent(&self) -> u64 { - self.history_gas_spent + /// This count and `other` added together: one operation's two parts, whose transfer logs are + /// at most one between them. + pub(crate) fn plus(self, other: Self) -> Self { + debug_assert!(!(self.transfer_log && other.transfer_log), "one transfer log per operation"); + let mut sum = Self { transfer_log: self.transfer_log || other.transfer_log, ..self }; + for pool in PoolId::ALL { + sum.added.set(pool, self.added.get(pool).saturating_add(other.added.get(pool))); + sum.taken.set(pool, self.taken.get(pool).saturating_add(other.taken.get(pool))); + } + sum } - /// The history gas validation charged for the transaction's body: the bytes the transaction - /// carries and the write records its inclusion makes, which are known before it runs. - /// - /// It rides in the EIP-8037 intrinsic state-gas slot, so the reservoir pays it first, and the - /// settled result takes it back out of the state gas it reports: it is history, not state. - pub const fn intrinsic_history_gas(&self) -> u64 { - self.intrinsic_history_gas + /// The data-size bytes it adds. + pub(crate) const fn bytes_added(&self) -> u64 { + self.added.get(DATA_SIZE_POOL) } - /// Records the history gas validation charged for the transaction's body, and the `bytes` of - /// the body it paid for. - pub(crate) const fn set_intrinsic_history(&mut self, gas: u64, bytes: u64) { - self.intrinsic_history_gas = gas; - self.intrinsic_history_bytes = bytes; + /// The data-size bytes it takes back. + pub(crate) const fn bytes_taken(&self) -> u64 { + self.taken.get(DATA_SIZE_POOL) } - /// The history bytes the last settled transaction appended, whoever paid for them, which a - /// transaction reports as [`MegaGasUsage::history_bytes`](crate::MegaGasUsage::history_bytes); - /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of - /// their price. - pub const fn history_bytes(&self) -> u64 { - self.history_bytes + /// Whether it adds nothing and takes nothing back. + const fn is_none(&self) -> bool { + self.added.is_zero() && self.taken.is_zero() } - /// Settles [`history_bytes`](Self::history_bytes) from what the transaction kept: `priced` is - /// whether it pays history at all. Called once the outermost frame's lane is popped, when - /// everything the transaction kept sits on its own lane. - pub(crate) fn settle_history_bytes(&mut self, priced: bool) { - self.history_bytes = if priced { - self.intrinsic_history_bytes - .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.tracker.net().write_records)) - .saturating_add(self.tracker.log_and_code_bytes()) - } else { - 0 - }; - } - - /// The history gas charged before the first frame for the write record that frame makes: the - /// recipient of the transaction's value, or the account it creates. - /// - /// A first frame that fails keeps no such write, so the charge is given back with the rest of - /// what the failure discards. - pub(crate) const fn top_level_write_record_gas(&self) -> u64 { - self.top_level_write_record_gas - } - - /// Records the history gas charged for the transaction's own write record. - pub(crate) const fn set_top_level_write_record_gas(&mut self, gas: u64) { - self.top_level_write_record_gas = gas; + /// What it adds to `pool` less what it takes back from it. + const fn rise(&self, pool: PoolId) -> i128 { + self.added.get(pool) as i128 - self.taken.get(pool) as i128 } +} - /// Leaves the write records the transaction's own frame makes, as the charge of their history - /// before execution found them, for [`push_lane`](Self::push_lane) to check its own count - /// against when it pushes that frame's lane - /// ([`check_top_level_records`](Self::check_top_level_records)). - /// - /// Only a transaction that pays history is charged, and so leaves one. A first frame answered - /// or refused before its lane is pushed leaves it for the next transaction's reset to clear. - pub(crate) const fn stage_top_level_records(&mut self, records: u64) { - self.pending_top_level_records = Some(records); - } +/// A start revm decided whose result has not returned. +#[derive(Clone, Copy, Debug)] +struct Decided { + /// The started frame's depth, which its result returns at. + depth: usize, + /// What the frames kept when the start began, before its own records. + at_start: Kept, + /// The history gas the start's caller gets back once the frame returned with its start kept: + /// the price of the records the start took back, less what the caller paid for records the + /// start did not make. + credit: u64, + /// For a creation, its creator as it stood before revm decided the start, which tells once the + /// creation returned what record its nonce bump made. + creator: Option, +} - /// Draws up to `amount` from the running frame's history allowance and reports what it gave; - /// the caller pays the rest out of the frame's own gas. - /// - /// Only a history charge may draw, and only the one a log makes: a write record, a state - /// charge and a unit of computation are all paid for by the frame's gas alone. See - /// [`storage_call_stipend`](crate::storage_call_stipend). - #[inline] - pub(crate) fn try_consume_stipend(&mut self, amount: u64) -> u64 { - self.tracker.consume_stipend(amount) +impl AdditionalLimit { + /// A layer enforcing `limits`. + pub fn new(limits: EvmTxRuntimeLimits) -> Self { + Self { limits, ..Default::default() } } - /// Whether the transaction's call target is an applied EIP-7702 authority, whose account - /// write the transaction's own lane already counts, so its first frame writes no recipient. - pub(crate) const fn target_is_authority(&self) -> bool { - self.target_is_authority + /// The limits enforced. + pub const fn limits(&self) -> &EvmTxRuntimeLimits { + &self.limits } - /// Leaves the history gas the running opcode just charged its frame for the records the frame - /// it starts will make: `on_lane` for the records that frame's failure discards, `caller` for - /// the record of the caller's own account, and `records`, the answer the charge was computed - /// from, for [`push_lane`](Self::push_lane) to check its own against. - /// - /// The next lane pushed takes it, whether that is the frame's own or the empty one of a frame - /// answered without running. - #[inline] - pub(crate) const fn stage_frame_charge( - &mut self, - records: FrameStartRecords, - on_lane: u64, - caller: u64, - ) { - self.pending_frame_charge = FrameCharge { records: Some(records), on_lane, caller }; + /// Replaces the limits enforced from the next transaction on. + pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.limits = limits; } - /// Leaves whether revm refuses the start of the frame about to start on its caller's account, - /// for the frame's init to take ([`take_start_refused`](Self::take_start_refused)) rather than - /// read the caller's account again: found by the opcode starting the frame, or, for the - /// transaction's own frame, by the charge of its record before execution. + /// Clears the state for a new transaction, keeping allocations and the limits, and begins it: + /// exempt from every limit or not, its value movements journaling transfer logs or not, its + /// body weighing `body` bytes. /// - /// Only a start revm can refuse there — a call that transfers value, a creation — takes it. - /// One an opcode makes finds the answer that opcode staged, which stages one for every frame - /// it starts and so replaces whatever an earlier start left. The transaction's own frame finds - /// the one its record's charge staged, or none: the reset cleared what the transaction before - /// it left. A start answered before its init leaves its answer for no other start to take. - /// The one start past the first frame no opcode makes, a keyless deployment's creation, is - /// cleared for ([`set_frame_creator`](Self::set_frame_creator)), and so is every start on the - /// inspected path, whose inspector may rewrite the input. - #[inline] - pub(crate) const fn stage_start_refused(&mut self, refused: bool) { - self.pending_start_refused = Some(refused); - } - - /// Takes what [`stage_start_refused`](Self::stage_start_refused) left for the frame about to - /// start, if anything. - #[inline] - pub(crate) const fn take_start_refused(&mut self) -> Option { - self.pending_start_refused.take() - } - - /// Records the history gas the settled transaction spent. - pub(crate) const fn set_history_gas_spent(&mut self, history_gas_spent: u64) { - self.history_gas_spent = history_gas_spent; + /// The exemption is decided before the body is counted: the protocol's own work is exempt + /// whatever it carries. + pub(crate) fn begin_transaction(&mut self, exempt: bool, transfer_logs: bool, body: u64) { + self.exempt = exempt; + self.transfer_logs = transfer_logs; + self.frame_stop = None; + self.limit_exceeded = None; + self.body = body; + self.hints = 0; + self.authorities = 0; + self.created_authorities = 0; + self.created_caller = false; + self.pre_frame_stop = None; + self.kept = Kept::default(); + self.decided.clear(); + self.intrinsic_history_gas = 0; + self.intrinsic_history_bytes = 0; + self.first_frame_charge = 0; + self.history_gas_spent = 0; + self.history_bytes = 0; + self.reservoir_remaining = 0; } - /* Observe, stage, commit */ + /* What the transaction keeps */ - /// The record the Host staged for the running opcode, if any. - pub const fn staged_record(&self) -> Option<&StagedRecord> { - self.staged.as_ref() - } - - /// Stages the facts the Host observed. Called by the Host, which records nothing itself. - #[inline] - pub(crate) fn stage_record(&mut self, record: StagedRecord) { - self.staged = Some(record); + /// What the transaction keeps so far, every running frame counted as if it succeeds: its + /// data-size bytes, write records and state growth, each the dimension's net, never below zero. + pub(crate) const fn usage(&self) -> LimitUsage { + LimitUsage { + data_size: positive(self.net(LimitKind::DataSize)), + write_records: positive(self.net(LimitKind::KvUpdate)), + state_growth: positive(self.net(LimitKind::StateGrowth)), + } } - /// Commits the staged record to the running frame's lane, and reports the history bytes it - /// appends or takes back. Called by an opcode's wrapper once the opcode completed; a crossed - /// limit in the verdict stops the opcode's frame, and the wrapper charges the history. - /// - /// A `SELFDESTRUCT` that moved value to another account also counts the EIP-7708 transfer log - /// revm journaled for the move, with the beneficiary's record and in the same check. The log - /// is the running frame's, as the move is: the frame's own journal checkpoint takes both back - /// when the frame fails, and its lane the bytes. It is data size and nothing else — no write - /// record, and no history: the bytes reported are the record's alone. - #[inline] - pub(crate) fn commit_staged_record(&mut self) -> (LimitCheck, HistoryBytes) { - let Some(record) = self.staged.take() else { - return (LimitCheck::WithinLimit, HistoryBytes::None); - }; - let effect = record.effect(self.sender); - let history = effect.history_bytes(); - // A log's bytes are history beside the write records; a record's are counted as one. - if let (StagedRecord::Log { .. }, HistoryBytes::Appended(bytes)) = (&record, history) { - self.tracker.record_log_and_code_bytes(bytes); - } - let counted = match effect { - RecordEffect::None => LimitUsage::ZERO, - RecordEffect::Record(usage) => usage, - RecordEffect::Refund(usage) => { - self.tracker.refund(usage); - return (LimitCheck::WithinLimit, history); + /// The transaction's net count of `kind`: what sits on no frame — the body, the hints, the + /// authorities' records and the accounts they created, the caller a deposit created — and + /// what the frames keep. + const fn net(&self, kind: LimitKind) -> i128 { + let frames = self.kept.net(kind) as i128; + let outside = match kind { + LimitKind::DataSize => { + self.body as i128 + + self.hints as i128 + + WRITE_RECORD_SIZE as i128 * self.authorities as i128 } + LimitKind::KvUpdate => self.authorities as i128, + LimitKind::StateGrowth => { + self.created_authorities as i128 + self.created_caller as i128 + } + LimitKind::ComputeGas => 0, }; - let counted = if self.transfer_logs && record.moves_value() { - counted.saturating_add(TRANSFER_LOG) - } else { - counted - }; - if counted == LimitUsage::ZERO { - return (LimitCheck::WithinLimit, history); - } - self.tracker.record(counted); - (self.check(), history) + outside + frames } - /// Discards the staged record. Called by an opcode's wrapper on entry, so a record staged - /// outside a wrapper cannot be committed for the wrong opcode, and when the opcode failed, - /// which takes the observed write back with it. - #[inline] - pub(crate) fn discard_staged_record(&mut self) { - self.staged = None; + /// The transaction's limit on `kind`. + const fn tx_limit(&self, kind: LimitKind) -> u64 { + match kind { + LimitKind::DataSize => self.limits.tx_data_size_limit, + LimitKind::KvUpdate => self.limits.tx_kv_update_limit, + LimitKind::StateGrowth => self.limits.tx_state_growth_limit, + LimitKind::ComputeGas => u64::MAX, + } } - /* Transaction-level records */ - - /// Counts the transaction's body: its envelope, the writes its inclusion makes, its calldata, - /// its authorizations and its access list. - /// - /// The bytes are the transaction's, recorded before any frame, so a revert does not take them - /// back, and neither does an out-of-gas before the first frame. The count is all it does: - /// validation holds the body to the limit ([`admits_tx_body`](Self::admits_tx_body)) on this - /// same count, and refuses a transaction it does not admit, so a transaction that runs never - /// crosses the limit with its body. - pub(crate) fn record_tx_body(&mut self, bytes: u64) { - self.body_bytes = bytes; - if bytes != 0 { - self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); - } + /// The data-size bytes of the transaction's body, which it counts before any frame and no + /// revert takes back. + pub(crate) const fn body(&self) -> u64 { + self.body } - /// The data-size bytes of the running transaction's body, as - /// [`record_tx_body`](Self::record_tx_body) counted them. - pub(crate) const fn body_bytes(&self) -> u64 { - self.body_bytes + /// Whether the transaction's value movements journal EIP-7708 transfer logs. + pub(crate) const fn counts_transfer_logs(&self) -> bool { + self.transfer_logs } - /// Whether the running transaction's body, with one write record for each of its - /// `authorizations`, fits its data-size limit: what validation holds a transaction to. + /// Whether the transaction's body, with one write record for each of its `authorizations`, + /// fits its data-size limit: what validation holds a transaction to. /// /// Every entry of the authorization list counts, whether it will apply or not, so the figure is /// an upper bound on what the transaction counts before its first frame — the body, then one /// record for each distinct authority that applies — and a transaction validation admits /// cannot cross the limit there. An exempt transaction is held to nothing. - pub(crate) fn admits_tx_body(&self, authorizations: u64) -> bool { + pub(crate) const fn admits_tx_body(&self, authorizations: u64) -> bool { self.exempt || - !LimitUsage { data_size: self.body_bytes, write_records: 0 } - .saturating_add(WRITE_RECORD.times(authorizations)) - .exceeds_data_size(self.limits.tx_data_size_limit) + self.body.saturating_add(WRITE_RECORD_SIZE.saturating_mul(authorizations)) <= + self.limits.tx_data_size_limit } - /// Counts the `bytes` of an Oracle hint, the payload a `sendHint` call hands to the node's - /// oracle service. - /// - /// The bytes are counted before the payload is decoded, so a caller cannot make the node - /// materialise a payload for free by appending bytes an ABI decoder ignores. They are the - /// transaction's, not the calling frame's, and no frame's budget holds them. Nothing the frame - /// or the transaction does afterwards takes them back, not even for a payload that fails to - /// decode and is never forwarded, for two separate reasons: a payload forwarded to the oracle - /// service cannot be taken back, and admitting a payload and decoding it is work done whether - /// or not it decodes. - /// - /// The limit is checked before the bytes are counted. A hint that would cross it is the stop, - /// with the usage it would have reached, and is neither forwarded nor counted: its payload - /// never left the machine, so the transaction keeps none of it, as it keeps nothing of a log - /// that crossed the limit. - pub(crate) fn record_hint_bytes(&mut self, bytes: u64) -> LimitCheck { - let hint = LimitUsage { data_size: bytes, write_records: 0 }; - let (reached, limit) = - (self.tracker.net().saturating_add(hint), self.limits.tx_data_size_limit); - if reached.exceeds_data_size(limit) { - let stop = self.crossed(LimitKind::DataSize, limit, reached.data_size, false); - if stop.exceeded_limit() { - return stop; - } - } - self.tracker.record_tx(hint); - LimitCheck::WithinLimit - } - - /// Records the account writes of the applied EIP-7702 authorities other than the sender: - /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is - /// one of them, from the transaction's `sender`. + /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts + /// other than the transaction's sender, and the `created` accounts among them the application + /// created, made before the first frame. An out-of-gas before the first frame takes them back + /// ([`take_back_authorities`](Self::take_back_authorities)). /// /// The records cannot cross the data-size limit: validation admitted the body with a record for /// every entry of the authorization list ([`admits_tx_body`](Self::admits_tx_body)), and only - /// an entry can apply. A debug build asserts it. - pub(crate) fn record_applied_authorities( - &mut self, - sender: Address, - authorities: u64, - target_is_authority: bool, - ) { - self.sender = sender; - self.target_is_authority = target_is_authority; - self.tracker.record(WRITE_RECORD.times(authorities)); + /// an entry can apply. Neither they nor the created accounts cross the KV or the state-growth + /// limit: a list that would was skipped before it was applied + /// ([`hold_authorization_list`](Self::hold_authorization_list)). A debug build asserts both. + pub(crate) fn count_authorities(&mut self, authorities: u64, created: u64) { + self.authorities = authorities; + self.created_authorities = created; debug_assert!( - self.exempt || !self.tracker.net().exceeds_data_size(self.limits.tx_data_size_limit), + self.exempt || !self.usage().exceeds_data_size(self.limits.tx_data_size_limit), "validation admits no body whose authority records cross the data-size limit" ); + debug_assert!( + self.exempt || + (authorities == 0 && created == 0) || + [LimitKind::KvUpdate, LimitKind::StateGrowth] + .iter() + .all(|&kind| self.net(kind) <= self.tx_limit(kind) as i128), + "an authorization list that would cross the KV or state-growth limit is skipped" + ); } - /* Frame lanes */ + /// Takes back the authorities' records and the accounts they created, which an out-of-gas + /// before the first frame takes back with the authorizations. + pub(crate) const fn take_back_authorities(&mut self) { + self.authorities = 0; + self.created_authorities = 0; + } - /// Pushes the lane of a frame about to start and counts the writes its start makes: - /// - /// - a call that transfers value: the sender's account (once per sender frame) and the - /// recipient's, one record when they are the same account; - /// - a creation: the created account, and the creator's nonce (once per creator frame); - /// - the transaction's own frame: the value recipient or the created account. - /// - /// The sender's account is part of the transaction body and never a record here: a frame - /// running as the sender (reached through an EIP-7702 delegation) counts it as recorded, and - /// a value transfer to the sender records no recipient. - /// - /// A frame whose start moves value to another account also counts the EIP-7708 transfer log - /// revm journals for the move, on the frame's own lane and in the same check as its records. - /// revm moves the value, and emits the log, only once it builds the frame, inside the journal - /// checkpoint it makes for it; the count comes before that, so a crossing answers the frame - /// with the stop before any value moves. After the checkpoint it could not: a frame revm - /// answers without running — a call to an account with no code, a precompile — has committed - /// its checkpoint by the time its answer returns, and rewriting the answer would not take the - /// move back. The lane follows the checkpoint from then on: a frame that fails discards both - /// the log and its bytes. - /// - /// So the count is a prediction of what revm will do ([module documentation](super)), and it - /// is called only for a start revm makes as far as the caller's account decides it: a start - /// revm refuses there, and one past the call-stack limit, which the depth guard answers before - /// it is counted, get an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)). - /// - /// A crossed limit in the verdict means the frame must not run: it is answered with the stop. - pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) -> LimitCheck { - self.frame_began = true; - self.push_lane(input, depth); - if self.frame_start_transfer_log(input) { - self.tracker.record(TRANSFER_LOG); - } - self.check() + /// Counts the caller account a deposit-like transaction creates before its first frame: one + /// account of state growth on the transaction, which no failure takes back, the deposit's own + /// included. It is one account, so it cannot cross a state-growth limit of one or more by + /// itself, and it is held to none: under a limit of nothing it leaves the first frame nothing. + /// A deposit carries no authorization list, so nothing else is counted before its frame. + pub(crate) const fn count_created_caller(&mut self) { + self.created_caller = true; } - /// Holds the code a creation deposits to the data-size limit, and names the stop when it - /// crosses it: the bytes are counted on the creation's own lane. - /// - /// Called through - /// [`ContextTr::admit_code_deposit`](revm::context::ContextTr::admit_code_deposit), which - /// `return_create` asks once it decided to deposit the code — the code passed every check - /// and every deposit charge is recorded — and before it commits the creation's journal - /// checkpoint. A stop refuses the deposit: `return_create` reverts the checkpoint, so the code - /// is not written, puts the frame's gas back to what it had before the deposit's charges, and - /// ends the creation as a revert carrying the stop. The bytes stay on the lane until the frame - /// returns; a success merges them into the caller, and the failure — the stop included — - /// discards them. - /// - /// A creation `return_create` fails itself is never offered: a revert or a halt of the init - /// code, code it refuses, and a creation that cannot pay one of the deposit's charges, which - /// runs out of gas whatever the limit. Empty code deposits nothing and is held to nothing. - /// - /// The same bytes are history beside the write records, counted here on the same lane, so the - /// history a transaction reports it appended and the data size it kept move together: a - /// creation that deposits nothing, or whose deposit fails, appends neither. - pub(crate) fn on_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { - let bytes = deposit.code.len() as u64; - if bytes == 0 { - return Ok(()); - } - debug_assert!(self.tracker.current().is_some(), "a creation returns on its own lane"); - self.tracker.record(LimitUsage { data_size: bytes, write_records: 0 }); - self.tracker.record_log_and_code_bytes(bytes); - let check = self.check(); + /// Whether an authorization list of `entries` could keep more than the transaction's KV or + /// state-growth limit allows: each entry changes one authority at most and creates one at + /// most, so a list no longer than what both limits leave cannot cross them, and needs no + /// simulation. + pub(crate) const fn authorization_list_may_cross(&self, entries: u64) -> bool { + let records = self.tx_limit(LimitKind::KvUpdate) as i128 - self.net(LimitKind::KvUpdate); + let created = + self.tx_limit(LimitKind::StateGrowth) as i128 - self.net(LimitKind::StateGrowth); + !self.exempt && (entries as i128 > records || entries as i128 > created) + } + + /// The verdict on an authorization list that would keep `records` write records and create + /// `created` accounts were it applied, before the first frame: KV updates first, then state + /// growth, each against the transaction's limit, since no frame budget exists yet. + pub(crate) const fn hold_authorization_list(&self, records: u64, created: u64) -> LimitCheck { + let counted = Counted::records(records, 0, false).with_growth(created, 0); + let check = self.transaction_crossed(LimitKind::KvUpdate, &counted, false); if check.exceeded_limit() { - return Err(self.note_frame_stop(&check)); + return check; } - Ok(()) + self.transaction_crossed(LimitKind::StateGrowth, &counted, false) } - /// The data-size budget of the frame about to start. - /// - /// The transaction's own frame gets what the transaction has left, and never more than the - /// frame cap ([`frame_data_size_limit`](EvmTxRuntimeLimits::frame_data_size_limit)). A child - /// gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent - /// has left, under the same cap. What the parent has left is its budget minus what it has - /// already kept, so a parent that has spent part of its budget forwards a smaller share. - fn frame_budget(&self) -> u64 { - let forwarded = match self.tracker.current() { - Some(caller) => share_of_remaining(caller.remaining_budget()), - None => self.limits.tx_data_size_limit.saturating_sub(self.tracker.net().data_size), - }; - forwarded.min(self.limits.frame_data_size_limit) + /// Skips the transaction's authorization list, which would have kept more than `stop` allows: + /// none of it is applied or counted, and the transaction's own frame returns `stop` before it + /// runs ([`take_pre_frame_stop`](Self::take_pre_frame_stop)). + pub(crate) fn skip_authorization_list(&mut self, stop: LimitCheck) { + debug_assert!(stop.exceeded_limit(), "only a crossing skips the list"); + self.pre_frame_stop = Some(stop); } - fn push_lane(&mut self, input: &FrameInput, depth: usize) { - let budget = self.frame_budget(); - // What the caller paid for these records at its opcode. The transaction's own frame has - // no such caller: its record is charged before execution and given back by the settlement - // ([`top_level_write_record_gas`](Self::top_level_write_record_gas)). - let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - match input { - FrameInput::Call(inputs) => { - let target = inputs.target_address; - let transfers_value = inputs.transfers_value(); - if depth == 0 { - self.sender = inputs.caller; - let written_outside = target == inputs.caller || self.target_is_authority; - let records = u64::from(transfers_value && !written_outside); - self.check_top_level_records(records); - self.tracker.push(Lane::new( - Some(target), - written_outside || transfers_value, - budget, - 0, - )); - self.tracker.record(WRITE_RECORD.times(records)); - return; - } - let records = self.records_the_caller_paid_for(input, charge.records); - let inherited = self.tracker.current().is_some_and(|caller| { - caller.address == Some(target) && caller.account_recorded - }); - let is_sender = target == self.sender; - self.tracker.push(Lane::new( - Some(target), - inherited || is_sender || transfers_value, - budget, - charge.on_lane, - )); - if records.caller { - self.tracker.record_caller(false, charge.caller); - } - self.tracker.record(WRITE_RECORD.times(records.on_lane)); - if grants_stipend(inputs) { - self.tracker.grant_stipend(storage_call_stipend()); - } - } - FrameInput::Create(inputs) => { - let records = self.records_the_caller_paid_for(input, charge.records); - self.tracker.push(Lane::new(None, true, budget, charge.on_lane)); - self.tracker.record(WRITE_RECORD.times(records.on_lane)); - if depth == 0 { - self.sender = inputs.caller(); - self.check_top_level_records(records.on_lane); - } else if records.caller { - self.tracker.record_caller(true, charge.caller); - } - } - // No frame starts from an empty input: revm's own frame init is `unreachable!` on - // one. - FrameInput::Empty => unreachable!( - "a frame input always names a call or a creation, as revm's frame init asserts" - ), - } + /// The stop the transaction's own frame returns before it runs, if its authorization list was + /// skipped; taken once. + pub(crate) const fn take_pre_frame_stop(&mut self) -> Option { + self.pre_frame_stop.take() } - /// The records starting `input` makes, checked against the answer the caller's charge was - /// computed from. - /// - /// The two are separate answers to the same question, asked at two points: the charge at the - /// opcode, on the input revm's instruction built, or at a `keylessDeploy` call's first run, on - /// the creation it starts; and the count here, on the input that survived interception. They - /// agree because nothing between the two changes the input: an interceptor answers a frame or - /// lets it start as it is, and a creation reaches none. A divergence trips here in every debug - /// build rather than mis-charging the caller and mis-splitting the refund its failure gets - /// back. - fn records_the_caller_paid_for( - &self, - input: &FrameInput, - charged: Option, - ) -> FrameStartRecords { - let records = self.frame_start_records(input); - if let Some(charged) = charged { - debug_assert_eq!( - charged, records, - "the records a frame's start makes changed after its caller was charged for them", - ); + /// The pools of the transaction's own frame: what the transaction has left of each limit once + /// its body and the counts made before the frame are counted, the data size under the frame + /// cap; unlimited for an exempt transaction. + pub(crate) const fn first_frame_pools(&self) -> PoolAmounts { + if self.exempt { + return PoolAmounts::UNLIMITED; + } + let caps = self.frame_caps(); + let mut pools = PoolAmounts::UNLIMITED; + let mut index = 0; + while index < COUNTED.len() { + let kind = COUNTED[index]; + let Some(pool) = kind.pool() else { unreachable!() }; + let left = self.tx_limit(kind) as i128 - self.net(kind); + let left = if left < 0 { + 0 + } else if left > u64::MAX as i128 { + u64::MAX + } else { + left as u64 + }; + let cap = caps.get(pool); + pools.set(pool, if left < cap { left } else { cap }); + index += 1; } - records + pools } - /// Checks the write records the transaction's own frame makes on its lane, `counted` here, - /// against the ones its history was charged for before execution - /// ([`stage_top_level_records`](Self::stage_top_level_records)). - /// - /// The two are separate answers to the same question: the charge, on the transaction, and the - /// count here, on the frame input revm built from it. They agree because that input carries - /// the transaction's own caller, target and value, and both read the same answer to whether - /// the target is an applied authority. An inspector that rewrites the input so that the answer - /// changes splits them, as it does for a frame an opcode starts - /// ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)). A divergence trips - /// here in every debug build rather than charging history for a record the data size does not - /// count, or counting one no history paid for. - fn check_top_level_records(&mut self, counted: u64) { - if let Some(charged) = self.pending_top_level_records.take() { - debug_assert_eq!( - charged, counted, - "the transaction's own frame makes other write records than its history was \ - charged for", - ); + /// The most each of a frame's pools may start with: the data-size frame cap, and no cap on the + /// other pools; nothing for an exempt transaction. + pub(crate) const fn frame_caps(&self) -> PoolAmounts { + if self.exempt { + return PoolAmounts::UNLIMITED; } + PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, self.limits.frame_data_size_limit) } - /// The write records starting `input` makes at a depth above the transaction's own frame, for - /// the opcode that starts it: `on_lane` are the records the frame's failure discards, `caller` - /// whether its start also writes the caller's own account. + /* Verdicts */ + + /// The verdict on `used` crossing `kind`'s `limit`, a frame budget when `frame_local` and a + /// transaction-level limit otherwise: the stop the running frame reverts with, alone, its + /// [`LimitCheck::revert_data`] naming the limit crossed. /// - /// The caller pays for both at the opcode, before it forwards gas, so the frame's own budget - /// carries none of them — which is what lets a value transfer's allowance pay for what the - /// recipient does with it. - pub(crate) fn frame_start_records(&self, input: &FrameInput) -> FrameStartRecords { - let caller_recorded = self.tracker.current().is_some_and(|lane| lane.account_recorded); - match input { - FrameInput::Call(inputs) => { - if !inputs.transfers_value() { - return FrameStartRecords::NONE; - } - let target = inputs.target_address; - let writes_target = target != inputs.caller && target != self.sender; - FrameStartRecords { on_lane: u64::from(writes_target), caller: !caller_recorded } - } - FrameInput::Create(_) => FrameStartRecords { on_lane: 1, caller: !caller_recorded }, - FrameInput::Empty => FrameStartRecords::NONE, + /// Every stop comes from here, so this is where the exemption applies: an exempt transaction's + /// verdict is [`LimitCheck::WithinLimit`], whatever it crossed. + pub(crate) const fn crossed( + &self, + kind: LimitKind, + limit: u64, + used: u64, + frame_local: bool, + ) -> LimitCheck { + if self.exempt { + return LimitCheck::WithinLimit; } + LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// Sets the account the running frame runs as, once known (a creation's address). - pub(crate) fn set_frame_address(&mut self, address: Address) { - if let Some(lane) = self.tracker.current_mut() { - lane.address = Some(address); - } + /// The verdict on a frame budget of `kind`, whose pool holds `remaining` after a net draw of + /// `spent`, crossed by `rise` more: the budget is the pool the frame started with, which its + /// pool and its net draw add up to, and what it used is its net draw with the rise in. + fn budget_crossed(&self, kind: LimitKind, remaining: u64, spent: i64, rise: u64) -> LimitCheck { + let budget = remaining.saturating_add_signed(spent); + let used = positive(spent as i128 + rise as i128); + self.crossed(kind, budget, used, true) } - /// Makes the running frame start its creation as `creator`: the frame of a `keylessDeploy` - /// call, which runs no code of its own and starts the creation its signer signed. - /// - /// The creation's start writes the creator's nonce, so the frame's lane runs as the creator: - /// the creation records that write as its creator's, on the frame's lane once the creation - /// fails, unless the creator is the transaction's sender, whose account the body counts. - /// - /// No opcode starts the creation, so nothing staged the answer to whether its creator's - /// account refuses it. Clearing the staged answer is defensive: the only answer staged for the - /// call's own start is that of a call carrying value, which is answered before its frame is - /// built and so never starts a creation. Nothing staged can reach the creation; the clear is - /// kept so that none ever does. - pub(crate) fn set_frame_creator(&mut self, creator: Address) { - self.pending_start_refused = None; - let sender = self.sender; - if let Some(lane) = self.tracker.current_mut() { - lane.address = Some(creator); - lane.account_recorded = creator == sender; + /// The verdict on the transaction keeping `counted` more of `kind`: its limit crossed, or + /// within. A count that does not rise crosses nothing, unless `held` asks for the transaction + /// to be held to its limit whatever it counts. + const fn transaction_crossed( + &self, + kind: LimitKind, + counted: &Counted, + held: bool, + ) -> LimitCheck { + let Some(pool) = kind.pool() else { return LimitCheck::WithinLimit }; + let rise = counted.rise(pool); + if !held && rise <= 0 { + return LimitCheck::WithinLimit; + } + let used = self.net(kind) + rise; + let limit = self.tx_limit(kind); + if used > limit as i128 { + return self.crossed(kind, limit, positive(used), false); } + LimitCheck::WithinLimit } - /// Takes back the nonce record a failed creation left its creator, when the nonce bump it - /// stands for is taken back: the running frame is a `keylessDeploy` call whose lane runs as - /// the signer ([`set_frame_creator`](Self::set_frame_creator)). A signer that is the - /// transaction's sender has no such record, its account being the body's. - /// - /// A stop the record left the frame, by putting it over a limit, goes with it: the frame is - /// held to its limits again without the record. Returns whether a record was taken back. - pub(crate) fn take_back_creator_record(&mut self) -> bool { - let sender = self.sender; - if self.tracker.current().is_none_or(|lane| lane.address == Some(sender)) || - !self.tracker.take_back_own_record() - { - return false; + /// The verdict on `counted` kept on a frame whose pools hold `remaining` after net draws of + /// `spent`: in each counted dimension in order, the frame's budget, then the transaction's + /// limit; the first crossing is the verdict. `held` holds the transaction to its limits + /// whatever `counted` adds. + fn check( + &self, + remaining: PoolAmounts, + spent: [i64; PoolId::COUNT], + counted: &Counted, + held: bool, + ) -> LimitCheck { + for kind in COUNTED { + let Some(pool) = kind.pool() else { continue }; + let rise = counted.rise(pool); + if rise > 0 && rise > remaining.get(pool) as i128 { + let check = self.budget_crossed( + kind, + remaining.get(pool), + spent[pool.index()], + rise as u64, + ); + if check.exceeded_limit() { + return check; + } + } + let check = self.transaction_crossed(kind, counted, held); + if check.exceeded_limit() { + return check; + } } - let check = self.check(); - self.resume_stop = check.exceeded_limit().then_some(check); - true + LimitCheck::WithinLimit } - /// Discards the lane of the frame about to return as its failure would, and stands an empty - /// lane in for it, which gives the caller back, when it is popped, the history the failure - /// gives back. - /// - /// For a frame whose journal checkpoint was reverted and whose result an inspector then - /// rewrote into a success: nothing the frame counted was kept, so none of it reaches its - /// caller, whatever the result says. - pub(crate) fn discard_returning_lane(&mut self) { - self.tracker.discard_running_lane(); + /// The pools `gas` holds and the nets it drew on them. + fn pools_of(gas: &GasTracker) -> (PoolAmounts, [i64; PoolId::COUNT]) { + (gas.pools_remaining(), PoolId::ALL.map(|pool| gas.pool_spent(pool))) } - /// Pushes the lane of a frame answered without running: a result built without an - /// interpreter keeps the lanes aligned with the frames revm returns. - /// - /// Such a frame records none of the writes its caller paid for, so the whole charge sits on - /// the lane and comes back when it is popped, whatever the answer was. - pub(crate) fn push_empty_frame(&mut self) { - self.frame_began = true; - let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); + /// Counts what the frame whose pools `gas` holds keeps of `counted`, held to the frame's + /// budgets and the transaction's limits in the order [`check`](Self::check) holds them: the + /// amounts `counted` takes back go back to each pool first, and the amounts it adds are drawn. + /// A crossing counts nothing and draws nothing, and is the stop the frame reverts with. A + /// count that adds nothing and takes nothing holds nothing. + pub(crate) fn draw(&mut self, gas: &mut GasTracker, counted: &Counted) -> LimitCheck { + if counted.is_none() { + return LimitCheck::WithinLimit; + } + let (remaining, spent) = Self::pools_of(gas); + let check = self.check(remaining, spent, counted, false); + if check.exceeded_limit() { + return check; + } + Self::apply(gas, counted); + self.count(counted); + LimitCheck::WithinLimit } - /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, - /// a failure discards it, a stop's included, so the caller resumes within its limits. - /// - /// Two returns would add to a caller what no check has held it to, and after them the caller is - /// held to its limits with what it now holds; a crossing is the stop it returns before it runs - /// on ([`stop_before_run`](Self::stop_before_run)), naming its budget or the transaction's - /// limit. - /// - /// - A failed creation leaves its creator the nonce record. The creation counted that record on - /// its own lane, against its own share, and a creation stopped for crossing that share still - /// bumps the nonce — so a creator with fewer bytes left than a record would keep one it may - /// not. - /// - A success past the frame's own budget would hand the caller more than the share it gave. - /// No frame returns one: a frame past its budget failed, and a failure an inspector rewrites - /// into a success has its lane discarded before it returns - /// ([`discard_returning_lane`](Self::discard_returning_lane)). It is held all the same. - /// - /// Any other return leaves the caller within its limits, and is not checked: a failure hands - /// it nothing, and a success hands it no more than the share it gave. Neither is the return of - /// the transaction's own frame, which has no caller to hold. A debug build asserts that the - /// check would have found nothing to stop. - /// - /// The crossing the result is made of, the stop noted for the frame - /// ([`note_frame_stop`](Self::note_frame_stop)), is the transaction's - /// [`limit_exceeded`](Self::limit_exceeded) when the frame is the transaction's own and its - /// result is still the stop's revert. - /// - /// Returns the history gas the caller paid for records this frame did not keep, which the - /// caller gets back once the frame has merged into it. - #[must_use = "the history of the records the frame did not keep goes back to its caller"] - pub(crate) fn on_frame_return(&mut self, result: &FrameResult) -> u64 { - let noted = self.frame_stop.take(); - if self.tracker.depth() == 1 { - self.limit_exceeded = noted.filter(|stop| is_the_revert_of(result, stop)); - } - // A charge an opcode of this frame made for a child that never started died with that - // opcode, which failed after making it. - self.pending_frame_charge = FrameCharge::NONE; - let success = result.instruction_result().is_ok(); - let lane = self.tracker.pop(success); - let refund = lane.as_ref().map_or(0, |lane| lane.history_refund(success)); - let unchecked = lane.is_some_and(|lane| self.tracker.hands_unchecked(&lane, success)); - self.resume_stop = if unchecked { - let check = self.check(); - check.exceeded_limit().then_some(check) - } else { + /// Draws `counted` on the pools `gas` holds, which the checks made sure can pay it. + fn apply(gas: &mut GasTracker, counted: &Counted) { + for pool in PoolId::ALL { + gas.refill_pool(pool, counted.taken.get(pool)); + let drew = gas.record_pool(pool, counted.added.get(pool)); debug_assert!( - self.check().within_limit(), - "a frame's return put its caller over a limit no check held it to" + drew || gas.pool_remaining(pool) == u64::MAX, + "the checks admit the draw" ); - None - }; - refund + if !drew { + gas.clear_pool_crossing(pool); + } + } } - /// Settles the transaction's outermost frame: pops its lane unless the frame already - /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever - /// it ran. + /// Adds `counted` to what the frames keep. /// - /// A transaction whose first frame never reached frame init ran out of gas in the runtime - /// phase before it: the out-of-gas took back the authorizations applied before it, so their - /// records go too, and the halt stays a halt. The body is not one of those records. It is put - /// back after the reset. Nothing counted before the first frame can have crossed a limit, - /// validation having held the body and the authorities' records to it, so the halt is what the - /// transaction reports. An exemption stays: it is the transaction's, not its frames'. - pub(crate) fn on_last_frame_return(&mut self, result: &FrameResult) { - if !self.frame_began { - let body = self.body_bytes; - self.tracker.reset(); - self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); - return; - } - debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); - if self.tracker.depth() == 1 { - // The outermost frame has no caller that paid for its records: the transaction did, - // before execution, and the settlement gives that charge back. - let refund = self.on_frame_return(result); - debug_assert_eq!(refund, 0, "the outermost frame's caller is the transaction"); + /// What a frame takes back the transaction's frames counted: a record or a byte taken back was + /// counted by a frame that is still on the stack or merged into one, so the transaction's net + /// stays at or above zero, which a debug build asserts. A frame's own net goes below zero when + /// it takes back what another frame counted — a slot its caller wrote, cleared, or the parts of + /// an account the transaction created, given back to the frame that destroys it — and the + /// signed net merges into its caller as any net does. + fn count(&mut self, counted: &Counted) { + let kept = &mut self.kept; + for pool in PoolId::ALL { + let net = &mut kept.net[pool.index()]; + *net = net + .saturating_add_unsigned(counted.added.get(pool)) + .saturating_sub_unsigned(counted.taken.get(pool)); } + debug_assert!( + kept.net[DATA_SIZE_POOL.index()] >= 0 && kept.net[KV_UPDATE_POOL.index()] >= 0, + "a frame takes back only what the transaction's frames keep" + ); + kept.transfer_logs += u64::from(counted.transfer_log); } -} - -/// `remaining` × [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`], rounded down. -/// -/// The share is `N / D = 1 − 1 / K` with `K = D / (D − N)` a whole number, so the floor of the -/// product is `remaining − ⌈remaining / K⌉`, which stays in `u64` and never wraps. A `u128` -/// product would call the 128-bit division routine on every frame start, where a division of a -/// `u64` by a constant compiles to a multiplication. -const fn share_of_remaining(remaining: u64) -> u64 { - const N: u64 = FRAME_DATA_SHARE_NUMERATOR; - const D: u64 = FRAME_DATA_SHARE_DENOMINATOR; - const _: () = assert!(N < D && D.is_multiple_of(D - N)); - const K: u64 = D / (D - N); - remaining - remaining.div_ceil(K) -} -/// Whether `result` is the revert `stop` makes a frame return: a revert whose output is the -/// stop's [`MegaLimitExceeded`](crate::MegaLimitExceeded). -fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { - let result = result.interpreter_result(); - result.result == InstructionResult::Revert && result.output == stop.revert_data() -} + /// The verdict on a start revm is not asked to decide — a call gas detention answers without + /// running the precompile it targets — had revm made it: `counted`, the records and transfer + /// log its value transfer would make, held to `shares`, the pools its frame would start with, + /// and to the transaction's limits. Nothing is counted. + pub(crate) fn hypothetical_start(&self, counted: &Counted, shares: PoolAmounts) -> LimitCheck { + self.check(shares, [0; PoolId::COUNT], counted, true) + } -/// Whether starting `input` moves value from one account to another, which is what revm journals -/// an EIP-7708 transfer log for: a call that transfers value to an account other than its caller — -/// the transaction's own value, a value `CALL` — and a creation with an endowment, the -/// transaction's own or a `CREATE`'s or a `CREATE2`'s. -/// -/// A `CALLCODE` transfers its value from the calling account to itself, as a `CALL` to itself does, -/// and revm moves nothing and emits nothing for either. `DELEGATECALL` and `STATICCALL` transfer -/// no value at all. -fn moves_value(input: &FrameInput) -> bool { - match input { - FrameInput::Call(inputs) => { - inputs.transfers_value() && inputs.target_address != inputs.caller + /// Admits an Oracle hint of `bytes`: held to the transaction's limit before it is counted, and + /// never taken back once counted. A hint is on no frame's budget. + pub(crate) fn admit_hint(&mut self, bytes: u64) -> LimitCheck { + let check = self.transaction_crossed(LimitKind::DataSize, &Counted::bytes(bytes), false); + if check.within_limit() { + self.hints = self.hints.saturating_add(bytes); } - FrameInput::Create(inputs) => !inputs.value().is_zero(), - FrameInput::Empty => false, + check } -} -/// Whether the frame `inputs` starts is granted a history allowance: a value-transferring `CALL` -/// or `CALLCODE` below the transaction's own frame. -/// -/// `DELEGATECALL` and `STATICCALL` carry no value, and the transaction's own frame is not a call -/// anybody made — its sender chose the gas limit. -fn grants_stipend(inputs: &CallInputs) -> bool { - matches!(inputs.scheme, CallScheme::Call | CallScheme::CallCode) && inputs.transfers_value() -} - -/// The write records a frame's start makes, split by whose failure takes them back. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct FrameStartRecords { - /// Records on the frame's own lane, which its failure discards. - pub(crate) on_lane: u64, - /// Whether the frame's start also writes its caller's account. - pub(crate) caller: bool, -} + /* A frame's start */ -impl FrameStartRecords { - /// No record at all. - pub(crate) const NONE: Self = Self { on_lane: 0, caller: false }; -} - -/// The history gas a caller paid for the records the frame it starts makes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct FrameCharge { - /// The records the charge was computed from, when an opcode made one. The transaction's own - /// frame has no such opcode, and neither has a frame of a transaction that prices no history. - records: Option, - /// What the records on the frame's own lane cost. - on_lane: u64, - /// What the record of the caller's own account cost. - caller: u64, -} - -impl FrameCharge { - /// Nothing charged. - const NONE: Self = Self { records: None, on_lane: 0, caller: 0 }; -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::{address, Address, Bytes, U256}; - use revm::interpreter::{CallInput, CallValue}; - - const SENDER: Address = address!("00000000000000000000000000000000000f0001"); - const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); - const TARGET: Address = address!("00000000000000000000000000000000000f0003"); - - #[test] - fn test_share_of_remaining_is_the_floor_of_the_exact_product() { - let exact = |x: u64| { - (u128::from(x) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / - u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 - }; - let mut x = 0x9e37_79b9_7f4a_7c15_u64; - let edges = [0, 1, 49, 50, 51, 99, 100, 101, u64::MAX, u64::MAX - 1, u64::MAX / 100 * 100]; - for v in edges.into_iter().chain((0..100_000).map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x >> (x % 64) - })) { - assert_eq!(share_of_remaining(v), exact(v), "{v}"); - } + /// Opens the start of the frame at `depth` that revm just decided, before its records are + /// counted: what the frames keep now is what the frame's failure restores + /// ([`close_start`](Self::close_start)). A creation's `creator`, read before revm decided it, + /// is handed back when the creation returns. + pub(crate) fn open_start(&mut self, depth: usize, creator: Option) { + self.decided.push(Decided { depth, at_start: self.kept, credit: 0, creator }); } - fn call_inputs(scheme: CallScheme, value: U256) -> CallInputs { - CallInputs { - input: CallInput::Bytes(Bytes::new()), - return_memory_offset: 0..0, - gas_limit: 100_000, - bytecode_address: Address::ZERO, - known_bytecode: Default::default(), - target_address: Address::ZERO, - caller: Address::ZERO, - value: CallValue::Transfer(value), - scheme, - is_static: false, - reservoir: 0, - charged_new_account_state_gas: false, + /// Holds the start revm just decided, whose frame's pools `gas` holds, to the limits, and + /// counts `counted`, the records and transfer log it made, on those pools + /// ([`draw`](Self::draw)): the verdict is the stop the frame returns before it runs, or the + /// one its answer gives way to. `credit` is what the start's caller gets back once the frame + /// returned with its start kept. + /// + /// A start is held to the transaction's limits whatever it counts, nothing included: what the + /// transaction keeps may already stand above a limit, as a frame that resumes may find it + /// ([`hold_caller`](Self::hold_caller)), and the caller a deposit-like transaction created is + /// counted unchecked ([`count_created_caller`](Self::count_created_caller)); a start is where + /// a frame first meets it. + pub(crate) fn count_start( + &mut self, + gas: &mut GasTracker, + counted: &Counted, + credit: u64, + ) -> LimitCheck { + let (remaining, spent) = Self::pools_of(gas); + let check = self.check(remaining, spent, counted, true); + if check.exceeded_limit() { + return check; } + Self::apply(gas, counted); + self.count(counted); + if let Some(start) = self.decided.last_mut() { + start.credit = credit; + } + LimitCheck::WithinLimit } - /// A `CALL` from `caller` to `target` carrying `value`. - fn call_from_to(caller: Address, target: Address, value: U256) -> FrameInput { - FrameInput::Call(Box::new(CallInputs { - caller, - target_address: target, - ..call_inputs(CallScheme::Call, value) - })) - } - - /// A hint is held to the transaction's data-size limit before it is counted: one that fits is - /// counted, one that would cross is the stop at the usage it would have reached and leaves the - /// count as it was, and a later one that fits is counted, the crossing having stopped nothing - /// but its own call. An exempt transaction's is counted whatever it crosses. - #[test] - fn test_a_hint_that_would_cross_the_limit_is_not_counted() { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100); - let kept = |limit: &AdditionalLimit| limit.usage().data_size; - - let mut limit = AdditionalLimit::new(limits); - limit.record_tx_body(40); - assert_eq!(limit.record_hint_bytes(59), LimitCheck::WithinLimit); - assert_eq!(kept(&limit), 99); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: 101, - frame_local: false, + /// Closes the start of the frame whose result returns at `depth`, `kept` or not, and answers + /// the history its caller gets back for it, with the creator of a creation as it stood before + /// revm decided the start: a frame whose result says it failed has what the frames keep + /// restored to what they kept when its start began, as its pools are, and its caller gets + /// nothing back; one that kept its start, the start's credit. + /// + /// A creation's creator is what its nonce record is read from once the result merged into the + /// creator ([`Accounts::creator_counted`](super::Accounts)): the record is the creator's, so it + /// is counted after the creation's own counts are closed, and outlives the creation's failure. + /// + /// A result revm did not decide the start of — the depth guard's, an interceptor's, an + /// inspector's — has no start to close, and no creator: revm bumped no nonce for it. The depth + /// guard's and an interceptor's carry the start charge their input declared, which revm gives + /// back; an inspector's carries what the inspector built it with. + pub(crate) fn close_start(&mut self, depth: usize, kept: bool) -> (u64, Option) { + let Some(&start) = self.decided.last().filter(|start| start.depth == depth) else { + return (0, None); }; - assert_eq!(limit.record_hint_bytes(2), stop, "two more bytes cross"); - assert_eq!(kept(&limit), 99, "the hint that crossed is not counted"); - assert_eq!(limit.record_hint_bytes(1), LimitCheck::WithinLimit, "one more fits exactly"); - assert_eq!(kept(&limit), 100, "and is counted"); - - let mut exempt = AdditionalLimit::new(limits); - exempt.exempt(); - exempt.record_tx_body(40); - assert_eq!(exempt.record_hint_bytes(61), LimitCheck::WithinLimit); - assert_eq!(kept(&exempt), 101, "an exempt transaction's hint is counted"); + self.decided.pop(); + if kept { + (start.credit, start.creator) + } else { + self.kept = start.at_start; + (0, start.creator) + } } - /// A layer with the transaction's own frame started: `SENDER` calling `CALLEE`, which has - /// recorded nothing of its own yet. - fn with_the_transactions_frame() -> AdditionalLimit { - let mut limit = AdditionalLimit::default(); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit + /// The stop the frame a child just returned into returns before it runs on, if what the + /// transaction keeps now stands above one of its limits: in each counted dimension in order, + /// held whatever the return counted. + /// + /// A child's success hands its caller nothing the limits did not hold as it was counted. A + /// failure restores what the frames kept when its start began, which is more than they keep + /// now when the child took back records or state a frame above it made, while what the + /// transaction keeps on no frame stays: an Oracle hint the child sent into the room the take + /// back freed leaves the transaction above its limit, and the caller is stopped for it. + pub(crate) fn hold_caller(&self) -> Option { + for kind in COUNTED { + let check = self.transaction_crossed(kind, &Counted::NONE, true); + if check.exceeded_limit() { + return Some(check); + } + } + None } - /// The records a frame's start makes are counted from the answer its caller was charged for: - /// a value transfer records the caller's account and the recipient's, the two the charge was - /// computed from. - #[test] - fn test_the_records_counted_are_the_records_the_caller_was_charged_for() { - let mut limit = with_the_transactions_frame(); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - let records = limit.frame_start_records(&inner); - assert_eq!(records, FrameStartRecords { on_lane: 1, caller: true }); - - limit.stage_frame_charge(records, 1, 1); - limit.on_frame_init(&inner, 1); - assert_eq!( - limit.usage(), - LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }, - ); - } + /* The stops and the exemption */ - /// A frame answered without running — by the depth guard, a stop, an interceptor or an - /// inspector — keeps none of the records its caller paid for, whatever its answer: its lane is - /// empty, the whole charge comes back, and the transaction's history bytes are its body alone. + /// The crossing that produced the result of the transaction's own frame, if one did: what + /// [`MegaTransactionOutcome::limit_exceeded`](crate::MegaTransactionOutcome) reports. /// - /// The depth guard's answer is reached here rather than through a transaction: under the - /// execution cap no call chain reaches the call-stack limit, because each call forwards at most - /// sixty-three sixty-fourths of what its caller has left, and 200,000,000 gas leaves about - /// twenty at depth 1,024. A stop's and an interceptor's answers are also reached through - /// transactions, in the history-byte tests. - #[test] - fn test_a_frame_answered_without_running_keeps_nothing_whatever_the_answer() { - const BODY: u64 = crate::TX_BODY_SIZE; - for answer in - [InstructionResult::CallTooDeep, InstructionResult::Revert, InstructionResult::Stop] - { - let mut limit = with_the_transactions_frame(); - limit.set_intrinsic_history(1, BODY); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(limit.frame_start_records(&inner), 1_000, 2_000); - limit.push_empty_frame(); - - let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); - assert_eq!(limit.on_frame_return(&result), 3_000, "{answer:?}: all of it back"); - assert_eq!(limit.usage(), LimitUsage::ZERO, "{answer:?}: nothing kept"); - - let outer = call_from_to(SENDER, CALLEE, U256::ZERO); - let result = - crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); - limit.on_last_frame_return(&result); - limit.settle_history_bytes(true); - assert_eq!(limit.history_bytes(), BODY, "{answer:?}: the body alone"); - } + /// It is a crossing the transaction's own frame made, of the transaction's limit or of its own + /// budget. A crossing below that frame produced the result of the frame that crossed, which its + /// caller caught: a caller that then reverts with the same bytes made its own result, and is no + /// stop. Neither is a stop an inspector rewrote into another result: the frame's result must + /// still be the stop's revert. + /// + /// It is the running transaction's, or the last one's until the next transaction or system + /// call starts: each resets it first. + pub const fn limit_exceeded(&self) -> Option<&LimitCheck> { + self.limit_exceeded.as_ref() } - /// A charge computed from a different answer than the count is what a rewrite that turns one - /// kind of frame into another would make. It trips rather than passing silently, because the - /// charge and the refund its failure gets back would both be wrong. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_charge_computed_from_another_answer_trips() { - let mut limit = with_the_transactions_frame(); - limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + /// Notes `stop` as the crossing the result of the frame returning next is made of, and gives + /// the [`MegaLimitExceeded`](crate::MegaLimitExceeded) revert data that frame stops with. + /// + /// Every site that turns a crossing into a frame's result takes the revert data from here, and + /// the frame returns before any other does: so the stop is the returning frame's when its + /// result returns ([`take_frame_stop`](Self::take_frame_stop)), and the transaction's when + /// that frame is the transaction's own ([`limit_exceeded`](Self::limit_exceeded)). + pub(crate) fn note_frame_stop(&mut self, stop: &LimitCheck) -> Bytes { + debug_assert!(stop.exceeded_limit(), "only a crossing stops a frame"); + self.frame_stop = Some(*stop); + stop.revert_data() } - /// The transaction's own frame counts on its lane the write records its history was charged - /// for before execution: its value's recipient, unless that is the sender or an applied - /// authority, and the account a creation makes. - #[test] - fn test_the_transactions_own_frame_counts_the_records_its_history_paid_for() { - let one = U256::from(1); - let rows = [ - ("a value call", call_from_to(SENDER, CALLEE, one), false, 1), - ("a call without value", call_from_to(SENDER, CALLEE, U256::ZERO), false, 0), - ("a value call to the sender", call_from_to(SENDER, SENDER, one), false, 0), - ("a value call to an applied authority", call_from_to(SENDER, CALLEE, one), true, 0), - ("a creation", creation(SENDER, U256::ZERO), false, 1), - ("an endowed creation", creation(SENDER, one), false, 1), - ]; - for (name, input, target_is_authority, records) in rows { - let authority = u64::from(target_is_authority); - let mut limit = AdditionalLimit::default(); - limit.record_applied_authorities(SENDER, authority, target_is_authority); - limit.stage_top_level_records(records); - limit.on_frame_init(&input, 0); - assert_eq!(limit.usage().write_records, authority + records, "{name}"); - assert_eq!(limit.pending_top_level_records, None, "{name}: taken once"); + /// Takes the stop noted for the frame whose `result` returns now; for the transaction's own + /// frame (`outermost`), it is the transaction's [`limit_exceeded`](Self::limit_exceeded) while + /// the result is still the stop's revert. A frame with no stop noted leaves the transaction's + /// as it is: the transaction's own frame returns through here once. + pub(crate) fn take_frame_stop(&mut self, result: &FrameResult, outermost: bool) { + let Some(noted) = self.frame_stop.take() else { return }; + if outermost { + self.limit_exceeded = Some(noted).filter(|stop| is_the_revert_of(result, stop)); } } - /// A transaction's own frame that would count a record its history did not pay for trips the - /// check, rather than counting data size no history matches. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] - fn test_a_top_level_record_its_history_did_not_pay_for_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(0); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + /// Whether the running transaction is exempt from every per-transaction limit. + pub const fn is_exempt(&self) -> bool { + self.exempt } - /// A transaction's own frame that makes no record its history was charged for trips the check, - /// rather than keeping history no data size matches. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] - fn test_a_top_level_charge_for_a_record_the_frame_does_not_make_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(1); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - } + /* What the transaction pays before its first frame */ - /// A creation as the transaction's own frame is checked too: one whose history paid for no - /// record of the account it creates trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] - fn test_a_top_level_creation_its_history_did_not_pay_for_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(0); - limit.on_frame_init(&creation(SENDER, U256::ZERO), 0); + /// The history gas of the transaction's body: the bytes the transaction carries and the write + /// records its inclusion makes, which are known before it runs. The transaction's gas pays it + /// before the first frame, reservoir first, as intrinsic gas. + pub const fn intrinsic_history_gas(&self) -> u64 { + self.intrinsic_history_gas } - /// A child frame's budget is 98% of what its parent has left, three frames down, and the - /// transaction's own frame gets what the transaction has left. - #[test] - fn test_a_child_frame_gets_98_percent_of_what_its_parent_has_left() { - let mut limit = - AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(10_000)); - limit.tracker.record_tx(LimitUsage { data_size: 310, write_records: 0 }); - - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let first = 10_000 - 310; - assert_eq!(limit.tracker.current().unwrap().budget, first); - - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); - let child = share_of_remaining(first); - assert_eq!(child, 9_496); - assert_eq!(limit.tracker.current().unwrap().budget, child); - - limit.on_frame_init(&call_from_to(TARGET, SENDER, U256::ZERO), 2); - let grandchild = share_of_remaining(child); - assert_eq!(limit.tracker.current().unwrap().budget, grandchild); - - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 3); - assert_eq!( - limit.tracker.current().unwrap().budget, - share_of_remaining(grandchild), - "the fourth frame, at depth 3, still takes 98% of what is left" - ); + /// Records the history gas the transaction's body costs, and the `bytes` of the body it pays + /// for. + pub(crate) const fn set_intrinsic_history(&mut self, gas: u64, bytes: u64) { + self.intrinsic_history_gas = gas; + self.intrinsic_history_bytes = bytes; } - /// The frame cap binds when it is tighter than the share of what the parent has left. - #[test] - fn test_the_frame_cap_binds_when_it_is_tighter_than_the_share() { - let mut limit = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_frame_data_size_limit(100), - ); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!(limit.tracker.current().unwrap().budget, 100); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); - assert_eq!(limit.tracker.current().unwrap().budget, 98); + /// Records the history gas charged before execution for the write record the transaction's own + /// frame makes: the recipient of its value, or the account it creates. The frame carries it as + /// its start charge, which its failure gives back. + pub(crate) const fn set_first_frame_charge(&mut self, gas: u64) { + self.first_frame_charge = gas; } - /// A layer with a frame cap of 100 bytes and the transaction's own frame started, which is - /// what the cap gives it; `CALLEE`'s call to `TARGET`, the child, is started below it with - /// 98 of them. - fn with_a_child_of_a_capped_frame() -> (AdditionalLimit, FrameInput) { - let mut limit = - AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100)); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let child = call_from_to(CALLEE, TARGET, U256::ZERO); - limit.on_frame_init(&child, 1); - assert_eq!(limit.tracker.current().unwrap().budget, 98); - (limit, child) + /// The history gas charged before execution for the write record the transaction's own frame + /// makes. + pub(crate) const fn first_frame_charge(&self) -> u64 { + self.first_frame_charge } - /// A success is checked on its return only when it kept more than its own budget, which no - /// frame returns and the check guards against all the same. Within its budget it hands the - /// caller no more than the caller's share, and the caller runs on unchecked; past it, the - /// caller is held to its own budget with what it now keeps, and stops when that crosses it. - #[test] - fn test_a_success_past_its_budget_holds_its_caller_to_the_caller_budget() { - for (kept, caller_stopped) in [(98, false), (99, false), (100, false), (101, true)] { - let (mut limit, child) = with_a_child_of_a_capped_frame(); - limit.tracker.record(LimitUsage { data_size: kept, write_records: 0 }); - let result = - crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&result); - let stop = limit.stop_before_run(); - let expected = caller_stopped.then_some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: kept, - frame_local: true, - }); - assert_eq!(stop, expected, "a child that kept {kept} bytes"); - assert_eq!(limit.usage().data_size, kept, "the success merged what it kept"); - } - } + /* What the settled transaction reports */ - /// The premise the unchecked returns rest on is asserted in a debug build. A success within a - /// budget wider than the share its caller gave it — what a share computed wrong would give — - /// puts the caller over its own budget with no check to catch it, and trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "no check held it to")] - fn test_a_success_that_hands_its_caller_more_than_its_share_trips() { - let (mut limit, child) = with_a_child_of_a_capped_frame(); - limit.tracker.current_mut().unwrap().budget = u64::MAX; - limit.tracker.record(LimitUsage { data_size: 101, write_records: 0 }); - let result = crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&result); + /// The history gas the last settled transaction spent. + pub const fn history_gas_spent(&self) -> u64 { + self.history_gas_spent } - /// Whether a start's caller refuses it is staged by the opcode that found it and taken once, - /// by the frame's init. Nothing is left for a later start: a reset drops what the transaction - /// before it left, and a keyless deployment's creation, which no opcode starts, drops what was - /// staged for its call. - #[test] - fn test_a_staged_start_answer_is_taken_once() { - let mut limit = with_the_transactions_frame(); - assert_eq!(limit.take_start_refused(), None, "nothing staged"); - for refused in [false, true] { - limit.stage_start_refused(refused); - assert_eq!(limit.take_start_refused(), Some(refused)); - assert_eq!(limit.take_start_refused(), None, "taken once"); - } - - limit.stage_start_refused(true); - limit.set_frame_creator(TARGET); - assert_eq!(limit.take_start_refused(), None, "the creation's is not the call's"); - - limit.stage_start_refused(true); - limit.reset(); - assert_eq!(limit.take_start_refused(), None, "the next transaction's is not this one's"); + /// The EIP-8037 reservoir the last settled transaction or system call left unspent, which + /// its sender gets back, as a transaction reports it + /// ([`MegaGasUsage::reservoir_remaining`](crate::MegaGasUsage::reservoir_remaining)). It is + /// read before the EIP-7623 floor absorbs it, and a failed deposit leaves none. + pub const fn reservoir_remaining(&self) -> u64 { + self.reservoir_remaining } - /// Limits every dimension holds at zero: anything a transaction counts crosses one. - fn zero_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0).with_frame_data_size_limit(0) + /// Records the reservoir the settled transaction or system call left unspent. + pub(crate) const fn set_reservoir_remaining(&mut self, reservoir: u64) { + self.reservoir_remaining = reservoir; } - /// Counts a body, then starts the transaction's frame and a value call's, and reports the - /// verdicts of the two starts. - fn count_a_transaction(limit: &mut AdditionalLimit) -> [LimitCheck; 2] { - limit.record_tx_body(crate::TX_BODY_SIZE); - let first = limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let records = limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - [first, records] + /// The history bytes the last settled transaction appended, whoever paid for them, which a + /// transaction reports as [`MegaGasUsage::history_bytes`](crate::MegaGasUsage::history_bytes); + /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of + /// their price. + pub const fn history_bytes(&self) -> u64 { + self.history_bytes } - /// A transaction that is not exempt is stopped wherever it crosses a limit: counting the - /// body checks nothing, the first check, at its frame's start, is the stop, and a later start - /// that crosses again is a stop of its own, with the usage it reached, not the first one's. - #[test] - fn test_a_transaction_that_is_not_exempt_is_stopped() { - let mut limit = AdditionalLimit::new(zero_limits()); - let [first, records] = count_a_transaction(&mut limit); - let stop = |used| LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 0, - used, - frame_local: false, + /// Settles the history figures once the transaction's own frame returned: `spent`, the history + /// gas its gas spent, and the history bytes it appended when it pays history at all (`priced`), + /// which are its body and the bytes it keeps but for its Oracle hints and its transfer logs. + pub(crate) fn settle_history(&mut self, priced: bool, spent: u64) { + self.history_gas_spent = spent; + self.history_bytes = if priced { + self.intrinsic_history_bytes + .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) + .saturating_add(positive(self.kept.net(LimitKind::DataSize) as i128)) + .saturating_sub(TRANSFER_LOG_SIZE.saturating_mul(self.kept.transfer_logs)) + } else { + 0 }; - assert_eq!(first, stop(crate::TX_BODY_SIZE), "the body crosses at the first check"); - assert_eq!(records, stop(crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE)); - assert!(!limit.is_exempt()); } +} - /// Validation admits a body whose bytes, with one record for each entry of the authorization - /// list, are within the transaction's limit, and nothing over it; an exempt transaction - /// whatever it carries. +/// `value`, or zero when it is negative, as a `u64` that saturates. +const fn positive(value: i128) -> u64 { + if value <= 0 { + 0 + } else if value > u64::MAX as i128 { + u64::MAX + } else { + value as u64 + } +} + +/// Whether `result` is the revert `stop` makes a frame return: a revert whose output is the +/// stop's [`MegaLimitExceeded`](crate::MegaLimitExceeded). +fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { + let result = result.interpreter_result(); + result.result == InstructionResult::Revert && result.output == stop.revert_data() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A count is none exactly when it adds and takes back nothing in every pool: `NONE` and the + /// default are, and so is a count of no records or no bytes; a count that adds or takes back + /// a record, adds bytes or a transfer log, or moves state growth either way is not. #[test] - fn test_validation_admits_a_body_and_its_authority_records_within_the_limit() { - let body = crate::TX_BODY_SIZE + 2 * crate::AUTHORIZATION_SIZE; - let at = body + 2 * WRITE_RECORD_SIZE; - let layer = |limit: u64, exempt: bool| { - let mut layer = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), - ); - if exempt { - layer.exempt(); - } - layer.record_tx_body(body); - layer - }; - assert!(layer(at, false).admits_tx_body(2), "at the limit"); - assert!(!layer(at - 1, false).admits_tx_body(2), "one byte over it"); - assert!(layer(at - 1, false).admits_tx_body(1), "one record fewer"); - assert!(!layer(body - 1, false).admits_tx_body(0), "the body alone over it"); - assert!(layer(0, true).admits_tx_body(2), "an exempt transaction"); - assert_eq!(layer(at, false).body_bytes(), body); - assert_eq!(layer(at, false).usage().data_size, body, "the body is counted"); + fn test_a_count_is_none_only_when_it_moves_no_pool() { + let cases = [ + ("NONE", Counted::NONE, true), + ("the default", Counted::default(), true), + ("no records", Counted::records(0, 0, false), true), + ("no bytes", Counted::bytes(0), true), + ("no growth", Counted::NONE.with_growth(0, 0), true), + ("a record made", Counted::records(1, 0, false), false), + ("a record taken back", Counted::records(0, 1, false), false), + ("a transfer log", Counted::records(0, 0, true), false), + ("bytes", Counted::bytes(1), false), + ("a rise", Counted::NONE.with_growth(1, 0), false), + ("a fall", Counted::NONE.with_growth(0, 1), false), + ]; + for (case, counted, none) in cases { + assert_eq!(counted.is_none(), none, "{case}: {counted:?}"); + } } - /// An exempt transaction is stopped by no limit, in any dimension, at the transaction or at a - /// frame: every verdict is within the limits and no caller is stopped. What it uses is counted - /// all the same. + /// An exempt layer answers every crossing as within the limits, in any dimension and at the + /// transaction or at a frame; the next transaction begins held to its limits again. #[test] - fn test_an_exempt_transaction_is_stopped_by_no_limit() { - let mut limit = AdditionalLimit::new(zero_limits()); - limit.exempt(); - assert_eq!(count_a_transaction(&mut limit), [LimitCheck::WithinLimit; 2]); + fn test_the_exemption_answers_every_crossing_and_lasts_one_transaction() { + let mut limit = AdditionalLimit::default(); + limit.begin_transaction(true, false, 0); + assert!(limit.is_exempt()); for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { for frame_local in [false, true] { let verdict = limit.crossed(kind, 0, 1, frame_local); assert_eq!(verdict, LimitCheck::WithinLimit, "{kind:?}, frame-local {frame_local}"); } } - assert_eq!(limit.stop_before_run(), None); + limit.begin_transaction(false, false, 0); + assert!(!limit.is_exempt()); assert_eq!( - limit.usage(), - LimitUsage { data_size: crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 }, - ); - - let result = crate::synthetic_frame_result( - &call_from_to(CALLEE, TARGET, U256::from(1)), - InstructionResult::Stop, - Bytes::new(), + limit.crossed(LimitKind::ComputeGas, 0, 1, false), + LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: 0, + used: 1, + frame_local: false + }, + "the next transaction is held to its limits" ); - let _ = limit.on_frame_return(&result); - assert_eq!(limit.stop_before_run(), None, "the caller runs on"); } /// Validation admits no body whose authority records cross the data-size limit, so a debug @@ -1411,292 +925,10 @@ mod tests { #[cfg(debug_assertions)] #[should_panic(expected = "validation admits no body whose authority records cross")] fn test_authority_records_that_cross_the_limit_trip() { - let mut limit = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE), - ); - limit.record_tx_body(crate::TX_BODY_SIZE); - limit.record_applied_authorities(SENDER, 2, false); - } - - /// Applied authorities are recorded for an exempt transaction, whatever they cross. - #[test] - fn test_an_exempt_transaction_records_its_authorities() { - let mut limit = AdditionalLimit::new(zero_limits()); - limit.exempt(); - limit.record_applied_authorities(SENDER, 2, false); - assert_eq!(limit.usage(), WRITE_RECORD.times(2)); - } - - /// The exemption is the transaction's: a reset clears it, and the next transaction is held to - /// its limits again. An out-of-gas before the first frame keeps it. - #[test] - fn test_the_exemption_lasts_one_transaction() { - let mut limit = AdditionalLimit::new(zero_limits()); - limit.exempt(); - let result = crate::synthetic_frame_result( - &call_from_to(SENDER, CALLEE, U256::ZERO), - InstructionResult::OutOfGas, - Bytes::new(), - ); - limit.on_last_frame_return(&result); - assert!(limit.is_exempt(), "an out-of-gas before the first frame keeps the exemption"); - - limit.reset(); - assert!(!limit.is_exempt()); - let [first, ..] = count_a_transaction(&mut limit); - assert!(first.exceeded_limit(), "after a reset the transaction is held to its limits"); - } - - /// A layer whose transaction's value movements journal transfer logs, under `limits`. - fn logging(limits: EvmTxRuntimeLimits) -> AdditionalLimit { + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE); let mut limit = AdditionalLimit::new(limits); - limit.set_transfer_logs(true); - limit - } - - /// A creation from `caller` endowing the account it creates with `value`. - fn creation(caller: Address, value: U256) -> FrameInput { - FrameInput::Create(Box::new(revm::interpreter::CreateInputs::new( - caller, - revm::interpreter::CreateScheme::Create, - value, - Bytes::new(), - 100_000, - 0, - ))) - } - - /// Exactly the frame starts that move value to another account count a transfer log: a value - /// call to another account and an endowed creation, at the transaction's own frame and below - /// it. A call to itself, a `CALLCODE`, a valueless call of any scheme, a `DELEGATECALL`, a - /// `STATICCALL` and a creation without an endowment count none; and nothing counts one when - /// the transaction's value movements journal no log. - #[test] - fn test_a_frame_start_counts_a_transfer_log_where_value_moves() { - let one = U256::from(1); - let scheme = |scheme, value| { - FrameInput::Call(Box::new(CallInputs { - caller: CALLEE, - target_address: if scheme == CallScheme::CallCode { CALLEE } else { TARGET }, - ..call_inputs(scheme, value) - })) - }; - for (input, moves) in [ - (call_from_to(CALLEE, TARGET, one), true), - (call_from_to(CALLEE, CALLEE, one), false), - (call_from_to(CALLEE, TARGET, U256::ZERO), false), - (scheme(CallScheme::CallCode, one), false), - (scheme(CallScheme::StaticCall, U256::ZERO), false), - (creation(CALLEE, one), true), - (creation(CALLEE, U256::ZERO), false), - ] { - assert_eq!(moves_value(&input), moves, "{input:?}"); - assert!(!with_the_transactions_frame().frame_start_transfer_log(&input), "off"); - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!(limit.frame_start_transfer_log(&input), moves, "{input:?}"); - let before = limit.usage(); - limit.on_frame_init(&input, 1); - let records = limit.usage().write_records - before.write_records; - assert_eq!( - limit.usage().data_size - before.data_size, - WRITE_RECORD_SIZE * records + if moves { TRANSFER_LOG_SIZE } else { 0 }, - "{input:?}", - ); - } - let delegate = FrameInput::Call(Box::new(CallInputs { - value: CallValue::Apparent(one), - ..call_inputs(CallScheme::DelegateCall, one) - })); - assert!(!moves_value(&delegate), "a delegate call carries its caller's value, no transfer"); - - // The transaction's own frame: its value to another account, and its endowed creation. - for (input, moves) in [ - (call_from_to(SENDER, CALLEE, one), true), - (call_from_to(SENDER, SENDER, one), false), - (creation(SENDER, one), true), - ] { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&input, 0); - let log = limit.usage().data_size - WRITE_RECORD_SIZE * limit.usage().write_records; - assert_eq!(log, if moves { TRANSFER_LOG_SIZE } else { 0 }, "{input:?}"); - } - } - - /// A transfer log is data size and nothing else: no write record, and no history byte — the - /// transaction's history is its body and its records, whatever it moved. - #[test] - fn test_a_transfer_log_is_data_size_and_never_history() { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.set_intrinsic_history(1, crate::TX_BODY_SIZE); - limit.record_tx_body(crate::TX_BODY_SIZE); - let outer = call_from_to(SENDER, CALLEE, U256::from(1)); - limit.on_frame_init(&outer, 0); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(limit.frame_start_records(&inner), 0, 0); - limit.on_frame_init(&inner, 1); - assert_eq!( - limit.usage(), - LimitUsage { - data_size: crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE, - write_records: 2, - }, - "the recipient of each move — the inner one's caller is the outer one's — and two logs", - ); - - let result = crate::synthetic_frame_result(&inner, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&result); - let result = crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); - limit.on_last_frame_return(&result); - limit.settle_history_bytes(true); - assert_eq!(limit.history_bytes(), crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE); - } - - /// A frame that fails takes its transfer log back with its records, as revm's checkpoint - /// takes back the move and the log. - #[test] - fn test_a_failed_frame_gives_its_transfer_log_back() { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.on_frame_init(&inner, 1); - assert_eq!(limit.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); - - let result = crate::synthetic_frame_result(&inner, InstructionResult::Revert, Bytes::new()); - let _ = limit.on_frame_return(&result); - assert_eq!(limit.usage(), LimitUsage::ZERO); - } - - /// A frame start whose transfer log crosses a limit is stopped there, before revm moves the - /// value, with a stop that names the limit it crossed, its own budget or the transaction's - /// limit. The records alone - /// fit, so it is the log that crosses; at exactly the limit it holds. - #[test] - fn test_a_frame_start_whose_transfer_log_crosses_is_stopped() { - let records = 2 * WRITE_RECORD_SIZE; - let needs = records + TRANSFER_LOG_SIZE; - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - // The smallest frame cap whose share, the budget of a child of the first frame, holds it. - let cap = (needs..).find(|cap| share_of_remaining(*cap) >= needs).unwrap(); - assert_eq!(share_of_remaining(cap), needs); - for (cap, fits) in [(cap, true), (cap - 1, false)] { - let mut limit = - logging(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap)); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let check = limit.on_frame_init(&inner, 1); - if fits { - assert_eq!(check, LimitCheck::WithinLimit, "exactly the budget"); - } else { - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: needs - 1, - used: needs, - frame_local: true, - }, - ); - } - } - - // The transaction's own value: one record, the recipient's, and the log. - let first = call_from_to(SENDER, CALLEE, U256::from(1)); - let needs = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; - for (tx_limit, fits) in [(needs, true), (needs - 1, false), (WRITE_RECORD_SIZE, false)] { - let mut limit = - logging(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit)); - let check = limit.on_frame_init(&first, 0); - if fits { - assert_eq!(check, LimitCheck::WithinLimit, "exactly the limit"); - continue; - } - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: tx_limit, - used: needs, - frame_local: false, - }, - ); - } - } - - /// A `SELFDESTRUCT` that moved value to another account counts its transfer log with the - /// beneficiary's record, in one check, and reports the record's history alone. To the sender, - /// whose account the body counts, it is the log alone, and the log alone can cross. - #[test] - fn test_a_destruction_counts_its_transfer_log_with_its_beneficiary() { - let destruction = |beneficiary| StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary, - }; - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_record(destruction(TARGET)); - let (check, history) = limit.commit_staged_record(); - assert_eq!(check, LimitCheck::WithinLimit); - assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); - assert_eq!( - limit.usage(), - LimitUsage { data_size: WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, - ); - - let mut limit = - logging(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1)); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_record(destruction(SENDER)); - let (check, history) = limit.commit_staged_record(); - assert_eq!(history, HistoryBytes::None); - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: TRANSFER_LOG_SIZE - 1, - used: TRANSFER_LOG_SIZE, - frame_local: false, - }, - "the log alone crosses", - ); - - let mut limit = AdditionalLimit::default(); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_record(destruction(TARGET)); - let _ = limit.commit_staged_record(); - assert_eq!(limit.usage(), WRITE_RECORD, "no log, no bytes"); - } - - /// The transfer logs are the transaction's to set: a reset turns them off until the next - /// transaction sets them again. - #[test] - fn test_a_reset_turns_the_transfer_logs_off() { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - let input = call_from_to(SENDER, CALLEE, U256::from(1)); - assert!(limit.frame_start_transfer_log(&input)); - limit.reset(); - assert!(!limit.frame_start_transfer_log(&input)); - } - - /// The allowance follows the transfer, and only the two schemes that can carry one: a `CALL` - /// or a `CALLCODE` that moves value is granted one, and nothing else is — a valueless call of - /// either scheme, and `DELEGATECALL` and `STATICCALL`, which take no value word at all. - #[test] - fn test_only_a_value_call_or_callcode_is_granted_an_allowance() { - for scheme in [ - CallScheme::Call, - CallScheme::CallCode, - CallScheme::DelegateCall, - CallScheme::StaticCall, - ] { - let carries_value = matches!(scheme, CallScheme::Call | CallScheme::CallCode); - assert_eq!( - grants_stipend(&call_inputs(scheme, U256::from(1))), - carries_value, - "{scheme:?} with value", - ); - assert!(!grants_stipend(&call_inputs(scheme, U256::ZERO)), "{scheme:?} without value"); - } + limit.begin_transaction(false, false, crate::TX_BODY_SIZE); + limit.count_authorities(2, 0); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 226bf53c8..d29dcc328 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -6,15 +6,20 @@ //! data-size limit below, and detention for compute gas. //! //! Gas detention caps compute, [`LimitKind::ComputeGas`]: its state lives beside this module, in -//! [`Detention`](crate::Detention), because what it meters is gas rather than anything the lanes -//! count, and it holds a frame to the cap with the gas the frame may spend. It stops the frame that -//! crosses the cap with the same revert ([`AdditionalLimit`]), with the compute the transaction may -//! reach as the limit, and its compute at the crossing as what was used +//! [`Detention`](crate::Detention), because what it meters is gas rather than bytes, and it holds a +//! frame to the cap with the gas the frame may spend. It stops the frame +//! that crosses the cap with the same revert ([`AdditionalLimit`]), with the compute the +//! transaction may reach as the limit, and its compute at the crossing as what was used //! ([`LimitCheck::ExceedsLimit`]). //! -//! It also counts what the data-size limit meters, at the sites the bytes are made: data-size -//! bytes and write records, on a lane per frame ([`AdditionalLimit`]). The Host stages what it -//! observes ([`StagedRecord`]) and the opcode commits it once it completed. +//! What the data-size limit meters — data-size bytes, among them the write records — is drawn from +//! the byte pool on each frame's gas tracker, which the revm fork forwards to a child as its share +//! and settles as it does the reservoir: a frame that fails gives its draws back, and a frame that +//! succeeds hands its caller what it kept. A write an opcode makes is drawn once the opcode +//! completed, in the Host's completed-write hook, which revm calls after every charge the opcode +//! makes; a frame start's records once revm decided the start, on the pool its frame starts with. +//! [`AdditionalLimit`] holds the transaction's limit beside the pools, on what the transaction +//! keeps, with the stops and the settled figures. //! //! # The data-size limit //! @@ -23,8 +28,13 @@ //! counted, and a child gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of //! what its parent has left, under [`EvmTxRuntimeLimits::frame_data_size_limit`]. A frame that //! crosses either reverts alone, its caller resumes, and what the frame counted goes with it, so -//! the caller is back within both ([`AdditionalLimit`]). The budget is what keeps a caller's own -//! work safe from what it calls: a child inherits its caller's whole reservoir, so gas does not +//! the caller is back within both ([`AdditionalLimit`]), but in one case: a failed child's rollback +//! restores what the frames above it kept at its start, a record of theirs it took back included, +//! while an Oracle hint it admitted stays counted, so a hint sent into the room such a take-back +//! freed leaves the transaction over its data-size limit, and the caller returns that limit's stop +//! before it runs another instruction ([`AdditionalLimit::hold_caller`](AdditionalLimit)), whether +//! the child reverted, halted or was itself stopped. The budget is what keeps a caller's own +//! work safe from what it calls: a child inherits 98/100 of its caller's reservoir, so gas does not //! bound the bytes it can append, and without a budget a callee could take the transaction to its //! limit and leave its caller nothing to carry on with once it catches the stop. A creation //! stopped at its start still bumps its creator's nonce, and the record of that write lands on the @@ -36,36 +46,49 @@ //! - the body, before any frame; neither a revert nor an out-of-gas takes it back; //! - the records of the applied EIP-7702 authorities, before the first frame; //! - the records a frame's start makes, when the frame starts; -//! - a storage write's record, a log's bytes and the record of a `SELFDESTRUCT`'s beneficiary, once -//! the opcode completed; -//! - deployed code, on the creation's lane before the creation is committed, so a crossing leaves +//! - a storage write's record, a log's bytes and the records of a `SELFDESTRUCT` — the account it +//! clears and its beneficiary — once the opcode completed; +//! - deployed code, on the creation's pool before the creation is committed, so a crossing leaves //! no code behind. Only code revm would deposit counts: code starting with `0xEF` or over the //! code-size limit, and a creation that cannot pay for its deposit, fail the creation alone and //! are not counted; -//! - an Oracle hint's payload, on the transaction's own lane, before it is forwarded; +//! - an Oracle hint's payload, as the transaction's own, before it is forwarded; //! - an EIP-7708 transfer log, which revm journals itself for every value movement, where the value //! moves: with the records of the frame start that moves it — the transaction's own value, a -//! value `CALL`, a creation's endowment — before revm builds the frame, so a crossing answers the -//! frame with the stop before any value moves; and with a `SELFDESTRUCT`'s beneficiary once the -//! opcode completed. Each is counted by the rule a `LOG3` of one word is ([`TRANSFER_LOG_SIZE`]), -//! on the lane of the frame whose journal checkpoint holds the move, so the failure that takes -//! the move back takes the bytes back. +//! value `CALL`, a creation's endowment — and with a `SELFDESTRUCT`'s beneficiary once the opcode +//! completed. Each is counted by the rule a `LOG3` of one word is ([`TRANSFER_LOG_SIZE`]), on the +//! pool of the frame whose journal checkpoint holds the move, so the failure that takes the move +//! back takes the bytes back. //! -//! A frame start is counted before revm decides it, so what it counts is a prediction of what revm -//! will do. As far as the caller's account decides it, the prediction is revm's own: 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 nothing and is charged nothing, and no limit -//! stops it. The caller's account is read from the journal without loading anything. The one -//! refusal decided after the count is a creation onto an occupied address, which revm reads off -//! the created address's account only once it builds the frame: its records and transfer log are -//! counted, so a crossing they cause stops the creation where revm would have failed it, and -//! without a crossing the failure discards them. +//! A frame start's records are read off the journal before revm decides the start, as the hook +//! that charges its caller for them reads them, and counted and held to the limits once revm +//! decided it, on the pool its frame starts with; a debug build holds them to what revm's start +//! made of the accounts. A frame revm builds returns the stop on its first run when its start +//! crossed a limit, and its revert takes back the value revm moved and the transfer log it +//! journaled; an answer revm gives without building a frame — a call to an account with no code, to +//! a precompile — gives way to the stop, and what its start moved is taken back with it. A start +//! revm refuses on its caller's account — a value its caller cannot fund, a creation whose +//! creator's nonce cannot be bumped — moves and writes nothing, so it counts nothing and no limit +//! stops it; its opcode, which reads the caller's account first, charged nothing for its records. +//! A start an inspector rewrote 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. +//! +//! A creator's nonce record is counted from what revm did, not predicted: the creator is read +//! before revm decides the creation and again once the creation returned into it, and a nonce revm +//! bumped is counted on the creator then, held to the creator's budget and then to the +//! transaction's limit, a crossing stopping the creator before it runs on. The creation's budget +//! is the share of what the creator had left at its opcode, taken before the record. The record +//! outlives the creation's failure: a creation revm fails after the bump, onto an occupied address, +//! is held to nothing at its start, and its failure discards its records and transfer log, but the +//! creator's record is counted all the same. //! //! A record is checked against the limits before its history is charged: a record the limit //! rejects is not kept, so it is not charged, and the stop is what its frame reports. At a frame //! start the order is the other way round — the caller pays for the records at its opcode, before -//! the frame starts and its records are counted — so a caller that cannot pay runs out of gas -//! first. +//! revm decides the start and its records are held to the limits — so a caller that cannot pay +//! runs out of gas first, whether or not revm would have refused the start. //! //! Nothing counted before the first frame crosses the limit: validation refuses a transaction //! whose body, with a record for each entry of its authorization list, exceeds it @@ -75,25 +98,47 @@ //! //! # Write records //! -//! The write-record count the lanes keep is the KV count a node reports: one record per account -//! or storage write the transaction keeps, deduplicated per frame, taken back with a slot written -//! back to its original value and with the frame that fails. The sender's account and the accounts -//! fees are credited to are the body's, not records. No limit holds the count: a record weighs -//! [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so the data-size -//! limit bounds the records, and history gas prices each of them. +//! The write-record count [`AdditionalLimit`] keeps is the KV count a node reports: one record per +//! account or storage write the transaction keeps, following the net change — a slot's while its +//! value differs from its original, an account's while its nonce, balance or code differs from what +//! the transaction loaded, whichever writes changed it, a creation's created account included — +//! taken back by a write that returns the slot or the account and with the frame that fails. The +//! sender's account and the fee credits the settlement makes are the body's, not records; a write +//! execution makes to a fee account that is not the sender is a record like a write to any other +//! account. The KV-update limit holds the count, per transaction at +//! [`EvmTxRuntimeLimits::tx_kv_update_limit`] and per frame at the same 98/100 share of what the +//! parent has left, on the KV-update pool ([`KV_UPDATE_POOL`]). A record also weighs +//! [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so at the spec's +//! numbers the data-size limit binds first; history gas prices each of them. +//! +//! # The order of the counted dimensions +//! +//! An operation that crosses more than one of data size, KV updates and state growth stops on the +//! first of them in that order ([`COUNTED`]). Inside each, the frame's budget is tested before the +//! transaction's limit, and the stop names the budget when the budget is crossed — which a frame +//! that crosses the transaction's limit does too, unless Oracle hints, on no frame's budget, used +//! what the transaction had left. //! //! # State growth //! -//! No limit holds the state a transaction adds. EIP-8037 charges state gas for exactly that state, -//! at the SALT price of the bucket it lands in, so state growth is bounded by what it costs: the -//! transaction's gas limit and the block's. +//! The state growth [`AdditionalLimit`] keeps is the net count of the new accounts and new slots a +//! transaction keeps, one unit where EIP-8037 charges the state gas of one: a slot an `SSTORE` +//! makes non-zero from an original of zero, which a write back to zero takes back; an account a +//! value transfer, a creation, a `SELFDESTRUCT`'s balance, an applied authorization, a deposit or a +//! keyless signer's nonce bump creates. A failed frame's net goes with it, and a negative net never +//! enlarges a child's budget. The state-growth limit holds the count, per transaction at +//! [`EvmTxRuntimeLimits::tx_state_growth_limit`] and per frame at the same 98/100 share, on the +//! state-growth pool ([`STATE_GROWTH_POOL`]). EIP-8037 still prices the same state, at the SALT +//! price of the bucket it lands in; the count is what stops the 1,001st slot. //! //! # The limits //! //! They are the per-transaction half of //! [`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec), which for Satin holds a -//! transaction to [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, every frame to -//! its share of it, and a detained transaction to detention's caps. +//! transaction to [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, +//! [`TX_KV_UPDATE_LIMIT`](crate::constants::TX_KV_UPDATE_LIMIT) write records and +//! [`TX_STATE_GROWTH_LIMIT`](crate::constants::TX_STATE_GROWTH_LIMIT) new accounts and slots, every +//! frame to its share of each, and a detained transaction to detention's caps. //! //! # The exemption //! @@ -101,8 +146,9 @@ //! transaction ([`crate::system::is_system_originated`]) and a system call — the pre-block calls //! among them — are exempt ([`AdditionalLimit::is_exempt`]), sticky for the transaction, and the //! one place every stop comes from answers that they are within the limits whatever they cross: -//! the data size and the frame budgets. It is the set that pays no history gas, exempt for the -//! same reason: the protocol's maintenance must not fail on a resource limit. What such a +//! the data size, the KV updates, the state growth and the frame budgets. It is the set that pays +//! no history gas, exempt for the same reason: the protocol's maintenance must not fail on a +//! resource limit. What such a //! transaction uses is counted all the same and reported in its usage and in the block's counters, //! as a deposit's is. A user's deposit is not in the set and is held to every limit. //! @@ -128,19 +174,37 @@ //! recipient is the block beneficiary or a fee vault pays a record the body already bound. It is //! an over-charge, never an under-charge. -mod frame_limit; #[allow(clippy::module_inception)] mod limit; mod record; pub use limit::AdditionalLimit; -pub(crate) use limit::FrameStartRecords; -pub(crate) use record::HistoryBytes; -pub use record::StagedRecord; +pub(crate) use limit::Counted; +pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes}; +#[cfg(debug_assertions)] +pub(crate) use record::{RecordDelta, StartRecords}; use alloy_primitives::Bytes; use alloy_sol_types::SolError; -use revm::context::result::ExecutionResult; +use revm::{context::result::ExecutionResult, interpreter::PoolId}; + +/// The pool of a frame's gas tracker that is the frame's data-size budget: the bytes the frame +/// may still keep. +pub(crate) const DATA_SIZE_POOL: PoolId = PoolId::new(0); + +/// The pool of a frame's gas tracker that is the frame's KV-update budget: the write records the +/// frame may still keep. +pub(crate) const KV_UPDATE_POOL: PoolId = PoolId::new(1); + +/// The pool of a frame's gas tracker that is the frame's state-growth budget: the new accounts +/// and new storage slots the frame may still keep, net. +pub(crate) const STATE_GROWTH_POOL: PoolId = PoolId::new(2); + +/// The dimensions the common execution layer counts and limits, each drawn from the pool of a +/// frame's gas tracker it names ([`LimitKind::pool`]), in the order an operation that crosses more +/// than one of them stops on: data size, KV updates, state growth. +pub(crate) const COUNTED: [LimitKind; 3] = + [LimitKind::DataSize, LimitKind::KvUpdate, LimitKind::StateGrowth]; /// Bytes of one write record: the key and value delta one account or storage write leaves in /// the state diff. @@ -212,10 +276,11 @@ pub const FRAME_DATA_SHARE_NUMERATOR: u64 = 98; /// Denominator of [`FRAME_DATA_SHARE_NUMERATOR`]. pub const FRAME_DATA_SHARE_DENOMINATOR: u64 = 100; -/// What a transaction or a frame counts: data-size bytes and write records. +/// What a transaction or a frame counts: data-size bytes, write records and state growth, each the +/// dimension's net, never below zero. /// -/// The write-record count is the KV count a node reports; no limit holds it. Every record weighs -/// [`WRITE_RECORD_SIZE`] bytes of data size and is taken back with them, so +/// The write-record count is the KV count a node reports, which the KV-update limit holds. Every +/// record weighs [`WRITE_RECORD_SIZE`] bytes of data size and is taken back with them, so /// `write_records × WRITE_RECORD_SIZE` never exceeds `data_size`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct LimitUsage { @@ -223,15 +288,20 @@ pub struct LimitUsage { pub data_size: u64, /// Account and storage write records: the KV count. pub write_records: u64, + /// New accounts and new storage slots, net: the state growth. + pub state_growth: u64, } -/// Limits one transaction's data size and its compute after a read of volatile data. +/// Limits one transaction's data size, its write records, its state growth and its compute after +/// a read of volatile data. /// -/// [`tx_data_size_limit`](Self::tx_data_size_limit) is what the transaction may keep: a frame -/// whose count crosses it reverts alone. A frame's own budget is derived from it: the transaction's -/// frame gets what the transaction has left, and each child gets [`FRAME_DATA_SHARE_NUMERATOR`] / -/// [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent has left. Crossing a frame budget reverts -/// that frame alone. +/// [`tx_data_size_limit`](Self::tx_data_size_limit), +/// [`tx_kv_update_limit`](Self::tx_kv_update_limit) and +/// [`tx_state_growth_limit`](Self::tx_state_growth_limit) are what the transaction may keep: a +/// frame whose count crosses one reverts alone. A frame's own budget in each is derived from it: +/// the transaction's frame gets what the transaction has left, and each child gets +/// [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent has left. +/// Crossing a frame budget reverts that frame alone. /// /// [`frame_data_size_limit`](Self::frame_data_size_limit) is a further cap on every frame's budget. /// @@ -251,6 +321,17 @@ pub struct EvmTxRuntimeLimits { /// The most data-size bytes the transaction may keep. Crossing it reverts the frame that /// crosses it. pub tx_data_size_limit: u64, + /// The most write records the transaction may keep: its KV count. Crossing it reverts the + /// frame that crosses it, and every frame's KV budget is its share of what its parent has + /// left. A limits file without it takes the default spec's. + #[serde(default = "default_tx_kv_update_limit")] + pub tx_kv_update_limit: u64, + /// The most new accounts and new storage slots the transaction may keep, net: its state + /// growth. Crossing it reverts the frame that crosses it, and every frame's state-growth + /// budget is its share of what its parent has left. A limits file without it takes the + /// default spec's. + #[serde(default = "default_tx_state_growth_limit")] + pub tx_state_growth_limit: u64, /// A cap on every frame's data-size budget, applied after the share of what its parent has /// left. Crossing it reverts the frame alone. pub frame_data_size_limit: u64, @@ -271,6 +352,16 @@ pub struct EvmTxRuntimeLimits { pub oracle_access_compute_gas_limit: u64, } +/// The default spec's transaction KV-update limit, for a limits file that does not name one. +fn default_tx_kv_update_limit() -> u64 { + EvmTxRuntimeLimits::default().tx_kv_update_limit +} + +/// The default spec's transaction state-growth limit, for a limits file that does not name one. +fn default_tx_state_growth_limit() -> u64 { + EvmTxRuntimeLimits::default().tx_state_growth_limit +} + impl Default for EvmTxRuntimeLimits { /// The limits of the default spec's table: what a [`MegaContext`](crate::MegaContext) of that /// spec runs under. @@ -293,6 +384,8 @@ impl EvmTxRuntimeLimits { pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, + tx_kv_update_limit: u64::MAX, + tx_state_growth_limit: u64::MAX, frame_data_size_limit: u64::MAX, block_env_access_compute_gas_limit: u64::MAX, oracle_access_compute_gas_limit: u64::MAX, @@ -305,6 +398,18 @@ impl EvmTxRuntimeLimits { self } + /// Sets the most write records the transaction may keep. + pub const fn with_tx_kv_update_limit(mut self, limit: u64) -> Self { + self.tx_kv_update_limit = limit; + self + } + + /// Sets the most new accounts and new storage slots the transaction may keep, net. + pub const fn with_tx_state_growth_limit(mut self, limit: u64) -> Self { + self.tx_state_growth_limit = limit; + self + } + /// Caps every frame's data-size budget at `limit`. pub const fn with_frame_data_size_limit(mut self, limit: u64) -> Self { self.frame_data_size_limit = limit; @@ -325,44 +430,39 @@ impl EvmTxRuntimeLimits { } } -/// One write record. -pub(crate) const WRITE_RECORD: LimitUsage = - LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; - -/// One EIP-7708 transfer log: data size, and no write record. -pub(crate) const TRANSFER_LOG: LimitUsage = - LimitUsage { data_size: TRANSFER_LOG_SIZE, write_records: 0 }; - impl LimitUsage { /// Nothing counted. - pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; + pub const ZERO: Self = Self { data_size: 0, write_records: 0, state_growth: 0 }; - /// Whether `self` keeps more data-size bytes than `limit`, the one dimension a limit holds. + /// Whether `self` keeps more data-size bytes than `limit`: what validation holds a body to. pub(crate) const fn exceeds_data_size(self, limit: u64) -> bool { self.data_size > limit } - /// Both counters added, saturating. + /// Every counter added, saturating. pub const fn saturating_add(self, other: Self) -> Self { Self { data_size: self.data_size.saturating_add(other.data_size), write_records: self.write_records.saturating_add(other.write_records), + state_growth: self.state_growth.saturating_add(other.state_growth), } } - /// Both counters subtracted, saturating at zero. + /// Every counter subtracted, saturating at zero. pub const fn saturating_sub(self, other: Self) -> Self { Self { data_size: self.data_size.saturating_sub(other.data_size), write_records: self.write_records.saturating_sub(other.write_records), + state_growth: self.state_growth.saturating_sub(other.state_growth), } } - /// Both counters multiplied by `n`, saturating. + /// Every counter multiplied by `n`, saturating. pub const fn times(self, n: u64) -> Self { Self { data_size: self.data_size.saturating_mul(n), write_records: self.write_records.saturating_mul(n), + state_growth: self.state_growth.saturating_mul(n), } } } @@ -380,15 +480,18 @@ alloy_sol_types::sol! { /// A resource dimension a limit meters. /// /// The discriminants are the `kind` of [`MegaLimitExceeded`] and keep the values the legacy engine -/// encoded, so a contract that decodes the legacy revert data decodes Satin's. The legacy engine's -/// key-value updates, `1`, and state growth, `3`, name no dimension: no limit holds the write -/// records or the state a transaction adds. +/// encoded, so a contract that decodes the legacy revert data decodes Satin's. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum LimitKind { /// Bytes of data a transaction produces; metered by the data-size limit. DataSize, + /// The write records a transaction keeps, its KV count; metered by the KV-update limit. + KvUpdate, /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, + /// The new accounts and new storage slots a transaction keeps, net; metered by the + /// state-growth limit. + StateGrowth, } impl LimitKind { @@ -396,7 +499,9 @@ impl LimitKind { pub const fn as_u8(&self) -> u8 { match self { Self::DataSize => 0, + Self::KvUpdate => 1, Self::ComputeGas => 2, + Self::StateGrowth => 3, } } @@ -404,10 +509,23 @@ impl LimitKind { pub const fn from_u8(kind: u8) -> Option { match kind { 0 => Some(Self::DataSize), + 1 => Some(Self::KvUpdate), 2 => Some(Self::ComputeGas), + 3 => Some(Self::StateGrowth), _ => None, } } + + /// The pool of a frame's gas tracker the dimension is drawn from; `None` for compute, which + /// gas detention holds through the frame's gas instead. + pub(crate) const fn pool(&self) -> Option { + match self { + Self::DataSize => Some(DATA_SIZE_POOL), + Self::KvUpdate => Some(KV_UPDATE_POOL), + Self::StateGrowth => Some(STATE_GROWTH_POOL), + Self::ComputeGas => None, + } + } } /// The verdict of a limit check. @@ -430,11 +548,11 @@ pub enum LimitCheck { /// The usage that crossed it. /// /// For [`LimitKind::ComputeGas`] it is the transaction's compute before the charge that - /// would have crossed the limit, which the regular ledger bills: gas detention stops a - /// frame on a regular charge its spendable gas could not pay, does not make it, and puts - /// the frame's gas back to what it had before it. The charge's size is not kept, so this - /// is at most the limit, unless a halting frame's leftover, counted as compute, took the - /// transaction past it before the charge. + /// would have crossed the limit, which the regular ledger bills less the stipends of the + /// transaction's value calls, gas nobody paid: gas detention stops a frame on a regular + /// charge its spendable gas could not pay, does not make it, and puts the frame's gas + /// back to what it had before it. The charge's size is not kept, so this is at most the + /// limit. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, @@ -473,8 +591,8 @@ impl LimitCheck { /// A limit that stopped a transaction: the dimension, the limit and the usage that crossed it, of /// the crossing that produced the result of the transaction's own frame — a transaction-level -/// limit, or that frame's own data-size budget. It is what an RPC maps a limit stop to, in place of -/// the halt reasons the legacy engine reported one with. +/// limit, or that frame's own budget in data size, KV updates or state growth. It is what an RPC +/// maps a limit stop to, in place of the halt reasons the legacy engine reported one with. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LimitStop { /// The dimension crossed. @@ -538,8 +656,6 @@ mod tests { assert_eq!(AUTHORIZATION_SIZE, 101); assert_eq!(ACCESS_LIST_ADDRESS_SIZE, 20); assert_eq!(ACCESS_LIST_SLOT_SIZE, 32); - // A storage write and an account write are the same record. - assert_eq!(WRITE_RECORD, LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }); } /// `no_limits` leaves every dimension unlimited: it is what the execution-spec gate installs @@ -548,12 +664,16 @@ mod tests { fn test_no_limits_leaves_every_dimension_unlimited() { let EvmTxRuntimeLimits { tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, } = EvmTxRuntimeLimits::no_limits(); for limit in [ tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, @@ -574,6 +694,8 @@ mod tests { assert_eq!( default .with_tx_data_size_limit(u64::MAX) + .with_tx_kv_update_limit(u64::MAX) + .with_tx_state_growth_limit(u64::MAX) .with_block_env_access_compute_gas_limit(u64::MAX) .with_oracle_access_compute_gas_limit(u64::MAX), EvmTxRuntimeLimits::no_limits() @@ -589,15 +711,17 @@ mod tests { #[test] fn test_limit_usage_arithmetic_saturates() { - let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; - assert_eq!(max.saturating_add(WRITE_RECORD), max); - assert_eq!(LimitUsage::ZERO.saturating_sub(WRITE_RECORD), LimitUsage::ZERO); - assert_eq!(WRITE_RECORD.times(3), LimitUsage { data_size: 120, write_records: 3 }); - assert_eq!(WRITE_RECORD.times(u64::MAX).data_size, u64::MAX); + let max = + LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: u64::MAX }; + let record = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1, state_growth: 1 }; + assert_eq!(max.saturating_add(record), max); + assert_eq!(LimitUsage::ZERO.saturating_sub(record), LimitUsage::ZERO); assert_eq!( - WRITE_RECORD.saturating_add(WRITE_RECORD).saturating_sub(WRITE_RECORD), - WRITE_RECORD + record.times(3), + LimitUsage { data_size: 120, write_records: 3, state_growth: 3 } ); + assert_eq!(record.times(u64::MAX).data_size, u64::MAX); + assert_eq!(record.saturating_add(record).saturating_sub(record), record); } /// `within_limit` follows the variant, and is the exact complement of `exceeded_limit`. @@ -626,12 +750,17 @@ mod tests { assert!(frame_local.exceeded_limit()); } - /// The kinds keep the legacy engine's wire encoding: every discriminant survives the round - /// trip, and the legacy engine's key-value updates, `1`, and state growth, `3`, name no - /// dimension, nor does an unknown kind. + /// The kinds keep the legacy engine's wire encoding: data size `0`, KV updates `1`, compute + /// `2`, state growth `3`; every discriminant survives the round trip, and an unknown kind names + /// no dimension. #[test] fn test_limit_kind_keeps_its_wire_encoding() { - for (kind, expected) in [(LimitKind::DataSize, 0), (LimitKind::ComputeGas, 2)] { + for (kind, expected) in [ + (LimitKind::DataSize, 0), + (LimitKind::KvUpdate, 1), + (LimitKind::ComputeGas, 2), + (LimitKind::StateGrowth, 3), + ] { assert_eq!(kind.as_u8(), expected, "{kind:?}"); assert_eq!( LimitKind::from_u8(kind.as_u8()), @@ -639,8 +768,8 @@ mod tests { "round-trip failed for {kind:?}" ); } - for retired in [1, 3, 4, u8::MAX] { - assert_eq!(LimitKind::from_u8(retired), None, "{retired}"); + for unknown in [4, 5, u8::MAX] { + assert_eq!(LimitKind::from_u8(unknown), None, "{unknown}"); } } @@ -649,16 +778,20 @@ mod tests { /// bytes. #[test] fn test_decode_mega_limit_exceeded_accepts_exactly_the_stops_encoding() { - let kinds = [LimitKind::DataSize, LimitKind::ComputeGas]; + let kinds = [ + LimitKind::DataSize, + LimitKind::KvUpdate, + LimitKind::ComputeGas, + LimitKind::StateGrowth, + ]; for kind in kinds { let stop = LimitCheck::ExceedsLimit { kind, limit: 7, used: 8, frame_local: false }; assert_eq!(decode_mega_limit_exceeded(&stop.revert_data()), Some((kind, 7))); } let encoded = |kind: u8| MegaLimitExceeded { kind, limit: 7 }.abi_encode(); - assert_eq!(decode_mega_limit_exceeded(&encoded(1)), None, "a kind no dimension has"); - assert_eq!(decode_mega_limit_exceeded(&encoded(3)), None, "a kind no dimension has"); assert_eq!(decode_mega_limit_exceeded(&encoded(4)), None, "a kind no dimension has"); + assert_eq!(decode_mega_limit_exceeded(&encoded(5)), None, "a kind no dimension has"); assert_eq!(decode_mega_limit_exceeded(&encoded(u8::MAX)), None); let mut wide = encoded(0); wide[4 + 30] = 1; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index fe980e280..fd43e9c3a 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -1,239 +1,977 @@ -//! The facts the Host observes for the opcode that is running. +//! What a write counts: the write records it makes and takes back, by the net change of what it +//! writes, and its other bytes. +//! +//! An account's write record exists while the account's info — its nonce, balance or code — +//! differs from what the transaction loaded, revm's original info, which revm sets at the +//! account's first load in the transaction; a storage slot's while its value differs from its +//! original value. A write that changes an unchanged account or slot makes the record, a write that +//! returns one to its original takes it back, and a write to one already changed adds nothing. +//! +//! The facts are read off revm's journal as it stands where a hook runs: before a frame's start, +//! which is where its records are predicted, and after a completed write, where a `SELFDESTRUCT`'s +//! accounts are rebuilt as they were before it from the balance it moved. A creator's nonce record +//! is read off what revm did: the creator as it stood before revm decided the creation, and as it +//! stands once the creation returned. +//! +//! State growth is counted at the same sites, one unit per new account or new slot, where EIP-8037 +//! charges the state gas of one: a slot an `SSTORE` makes non-zero from an original of zero, and +//! takes back by writing it to zero again; an account that is empty under EIP-161 and that a value +//! transfer, a creation, a `SELFDESTRUCT`'s balance or a creator's nonce bump makes. +//! +//! The first effective `SELFDESTRUCT` of an account created in the transaction takes back every +//! part of it the transaction made ([`DestroyedParts`]): its leaf when it was absent at the +//! transaction's start, with the account's record and its unit of state growth; the code deposited +//! at it, with its bytes; and each slot it made non-zero from an original of zero, with its record +//! and its unit. From that mark until the transaction ends the account counts nothing more: its +//! nonce is no longer what the transaction loaded, so no write to the account makes or takes back +//! its record, a value moved to it adds no account, and an `SSTORE` of one of its slots counts +//! nothing ([`Accounts::is_destroyed`]). Every fact is the journal's: revm's flags of an account +//! created and of one destroyed in the transaction, which a failed frame's revert takes back with +//! the rest of it, the account's original info and each slot's original value. -use alloy_primitives::Address; -use revm::interpreter::SStoreResult; +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; -use super::{log_history_bytes, LimitUsage, WRITE_RECORD}; +use revm::{ + context_interface::{ + host::{CompletedWrite, FrameStartKind}, + journaled_state::entry::{JournalEntry, SelfdestructionRevertStatus}, + }, + primitives::{Address, StorageKey, KECCAK_EMPTY, U256}, + state::{Account, AccountInfo, EvmState, TransactionId}, + Journal, +}; -/// What the Host saw an opcode do, staged until the opcode completes. -/// -/// The Host only observes: it stages the facts revm hands it and records nothing. The opcode's -/// wrapper commits the staged record once the opcode completed, or discards it when the opcode -/// failed after the Host call (an out-of-gas on the gas charged after the write, say), because the -/// failure takes the write back with it. +use super::{log_history_bytes, Counted, TRANSFER_LOG_SIZE}; + +/// How a write moves the record count: the records it creates, for accounts it changes from what +/// the transaction loaded, and the records it takes back, for accounts it returns to that. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct RecordDelta { + /// Records created. + pub(crate) added: u64, + /// Records taken back. + pub(crate) taken: u64, +} + +impl RecordDelta { + /// No record moved. + pub(crate) const NONE: Self = Self { added: 0, taken: 0 }; + + /// The delta of one account whose info was changed from what the transaction loaded `before` + /// a write and is changed `after` it: a record when the write changed it, a record taken back + /// when the write returned it, and nothing otherwise. + pub(crate) const fn of_account(before: bool, after: bool) -> Self { + match (before, after) { + (false, true) => Self { added: 1, taken: 0 }, + (true, false) => Self { added: 0, taken: 1 }, + _ => Self::NONE, + } + } + + /// This delta and `other` together. + pub(crate) const fn with(self, other: Self) -> Self { + Self { added: self.added + other.added, taken: self.taken + other.taken } + } +} + +/// The write records a frame's start makes: a call's value transfer's, and a creation's created +/// account and creator nonce; and whether it journals a transfer log. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct StartRecords { + /// The records a call's value transfer makes and takes back: the accounts it changes from what + /// the transaction loaded, and those it returns to that. + pub(crate) transfer: RecordDelta, + /// Whether a creation records the account it creates: one the transaction had not changed. + /// A creation sets the account's nonce to one, so it never returns the account. + pub(crate) created: bool, + /// Whether a creation records its creator's nonce: the bump changes an account the transaction + /// had not changed. The record is the creator's, which the creation's failure leaves with it, + /// and is counted on the creator once the creation returned ([`CreatorBefore`]). + pub(crate) creator: bool, + /// Whether the start journals an EIP-7708 transfer log: value moves to another account. + pub(crate) transfer_log: bool, +} + +impl StartRecords { + /// No record and no log. + pub(crate) const NONE: Self = + Self { transfer: RecordDelta::NONE, created: false, creator: false, transfer_log: false }; + + /// The records the start makes on the started frame, which its failure takes back: a + /// transfer's, and the created account. The creator's is not among them. + pub(crate) const fn on_frame(self) -> RecordDelta { + RecordDelta { added: self.transfer.added + self.created as u64, taken: self.transfer.taken } + } + + /// What the start counts on the started frame: its records there, and its transfer log. + pub(crate) const fn counted(self) -> Counted { + let on_frame = self.on_frame(); + Counted::records(on_frame.added, on_frame.taken, self.transfer_log) + } +} + +/// The parts of an account created in the transaction that its first effective `SELFDESTRUCT` +/// gives back: each part the transaction made, which does not remain for a node to store. A part +/// that existed at the transaction's start is an ordinary deletion and is not among them. #[derive(Clone, Debug, PartialEq, Eq)] -pub enum StagedRecord { - /// An `SSTORE`: the slot's value at the start of the transaction, before the write, and - /// after it. - Sstore(SStoreResult), - /// A `LOG`: its topic count and data length. - Log { - /// Number of topics. - topics: u8, - /// Length of the data, in bytes. - data_len: u64, - }, - /// A `SELFDESTRUCT`. - SelfDestruct { - /// Whether the destructed account had a balance to move. - had_value: bool, - /// Whether the beneficiary is another account than the destructed one. - to_other_account: bool, - /// The beneficiary. - beneficiary: Address, - }, +pub(crate) struct DestroyedParts { + /// Whether the account's leaf was absent at the transaction's start: the leaf's state gas, its + /// unit of state growth and the account's write record come back. + pub(crate) leaf: bool, + /// The bytes of the code deposited at the account, which come back with their state gas, their + /// data size and their history gas. Code is no write record and no unit of state growth. + pub(crate) code: u64, + /// The slots the transaction made non-zero from an original of zero, in key order: each slot's + /// state gas, its unit of state growth and its write record come back. + pub(crate) slots: Vec, + /// The slots that held a non-zero value at the transaction's start, which the transaction + /// loaded and which still hold it: an ordinary deletion, which refills nothing and subtracts + /// nothing, and whose deletion is what makes each slot's write record. + pub(crate) deleted: u64, } -/// How a committed record changes the running frame's usage. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum RecordEffect { - /// Nothing to count. - None, - /// Count this usage. - Record(LimitUsage), - /// Take this usage back. - Refund(LimitUsage), +impl DestroyedParts { + /// The write records the parts take back: the account's, for an absent leaf, and each slot's. + fn records(&self) -> u64 { + u64::from(self.leaf) + self.slots.len() as u64 + } + + /// What the destruction counts of the parts: the records it takes back with their bytes, the + /// code's bytes and one unit of state growth per record taken back, and the records it makes + /// of the deleted slots that held a value at the start. + pub(crate) fn counted(&self) -> Counted { + let records = self.records(); + Counted::records(self.deleted, records, false) + .with_growth(0, records) + .plus_bytes_taken(self.code) + } } -/// The history bytes a committed record appends, or takes back. -/// -/// They are the record's data size and nothing else: what a log or a write record weighs in a -/// block is what the data-size limit meters it at, so the two cannot drift apart. That is the -/// pairing, and it holds per record; a transaction's two totals part where the byte table says -/// they do. +/// The accounts the running transaction holds, as revm's journal holds them, read for the records +/// a write makes. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Accounts<'a> { + state: &'a EvmState, + /// The journal's entries, which revm clears between transactions: this transaction's. + entries: &'a [JournalEntry], + transaction_id: TransactionId, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, +} + +/// Whether `info` differs from `original` in what a write record stands for: the nonce, the +/// balance or the code. +fn differs(info: &AccountInfo, original: &AccountInfo) -> bool { + info.nonce != original.nonce || + info.balance != original.balance || + info.code_hash != original.code_hash +} + +/// A creation's creator as the transaction held it before revm decided the creation's start: what +/// tells, once the creation returned, whether revm bumped the creator's nonce and what the bump +/// made of the creator ([`Accounts::creator_counted`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum HistoryBytes { - /// Nothing to charge. - None, - /// Bytes the record appends. - Appended(u64), - /// Bytes a record that was taken back no longer appends. - Taken(u64), +pub(crate) struct CreatorBefore { + /// The creator. + address: Address, + /// Its nonce. + nonce: u64, + /// Whether the transaction had changed its account from what it loaded. + changed: bool, + /// Whether its account was empty under EIP-161. + empty: bool, } -impl RecordEffect { - /// The history bytes this effect appends or takes back. - pub(crate) const fn history_bytes(self) -> HistoryBytes { - match self { - Self::None => HistoryBytes::None, - Self::Record(usage) => HistoryBytes::Appended(usage.data_size), - Self::Refund(usage) => HistoryBytes::Taken(usage.data_size), +impl<'a> Accounts<'a> { + /// The accounts `journal` holds, in a transaction whose value movements journal transfer logs + /// or not (`transfer_logs`). + pub(crate) fn of(journal: &'a Journal, transfer_logs: bool) -> Self { + Self { + state: &journal.state, + entries: &journal.journal, + transaction_id: journal.transaction_id, + transfer_logs, } } -} -impl StagedRecord { - /// What committing the record counts, per site: + /// The account at `address` as the transaction loaded it and holds it now: `None` for one + /// the transaction has not loaded, which it has not changed either. + fn loaded(&self, address: Address) -> Option<&'a Account> { + self.state.get(&address).filter(|account| account.transaction_id == self.transaction_id) + } + + /// Whether the transaction has loaded the account at `address`. An account an earlier + /// transaction on the same journal left in it is not loaded until this one loads it again. + pub(crate) fn is_loaded(&self, address: Address) -> bool { + self.loaded(address).is_some() + } + + /// Whether the transaction changed the account at `address` from what it loaded: its nonce, + /// balance or code differs from the account's original info. An account the transaction has + /// not loaded is unchanged. + pub(crate) fn is_changed(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| differs(&account.info, &account.original_info())) + } + + /// Whether the account at `address` would be changed from what the transaction loaded were + /// its balance `balance`, the rest of its info as it is. + fn changed_with_balance(&self, address: Address, balance: U256) -> bool { + match self.loaded(address) { + Some(account) => { + differs(&AccountInfo { balance, ..account.info.clone() }, &account.original_info()) + } + // What the transaction loads for an account it has not loaded is what the chain holds, + // so a balance it does not hold changes it. + None => balance != U256::ZERO, + } + } + + /// Whether the account at `address` was created in the transaction and has been destroyed + /// since: the mark the first effective `SELFDESTRUCT` of such an account leaves, which + /// stands until the transaction ends unless the destroying frame, or a frame that contains + /// it, fails. + pub(crate) fn is_destroyed(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| { + account.is_created_locally() && account.is_selfdestructed_locally() + }) + } + + /// The parts of the account at `address` its `SELFDESTRUCT` that just completed gives back, + /// read off the journal after the write: `None` unless the account was created in the + /// transaction and the destruction is its first effective one (`previously_destroyed` names + /// one the mark already stood for). + /// + /// The leaf was absent at the transaction's start when the transaction found no account + /// there ([`Self::was_absent_at_start`]), which a value transfer, a `SELFDESTRUCT`'s balance, + /// the transaction's value or the creation itself then charged as a new account; a leaf the + /// transaction found, a balance or an account empty under EIP-161 with storage, stands. The + /// code is what the account holds: non-empty code at the transaction's start collides with the + /// creation, so it is code the transaction deposited. A slot the transaction did not load has + /// no record. A slot of an account created in the transaction that the journal does not hold + /// yet loads as zero, so the slots given back are those it made non-zero; one loaded before the + /// creation, which only a tool's load reaches, keeps the value it held at the start, and the + /// deletion makes its record while it still holds that value. + pub(crate) fn destroyed_parts( + &self, + address: Address, + previously_destroyed: bool, + ) -> Option { + let account = self.loaded(address)?; + if previously_destroyed || !account.is_created_locally() { + return None; + } + let original = account.original_info(); + debug_assert_eq!(original.code_hash, KECCAK_EMPTY, "code at the start collides"); + debug_assert!(self.is_changed(address), "a creation changes its account's nonce"); + let leaf = self.was_absent_at_start(address, account); + let code = if account.info.code_hash == KECCAK_EMPTY { + 0 + } else { + account.info.code.as_ref().map_or(0, |code| code.len() as u64) + }; + let loaded = + account.storage.iter().filter(|(_, slot)| slot.transaction_id == self.transaction_id); + let mut slots = Vec::new(); + let mut deleted = 0; + for (key, slot) in loaded { + if slot.original_value.is_zero() { + if !slot.present_value.is_zero() { + slots.push(*key); + } + } else if !slot.is_changed() { + deleted += 1; + } + } + slots.sort_unstable(); + Some(DestroyedParts { leaf, code, slots, deleted }) + } + + /// Whether the transaction found no account at `address`, which it loaded as `account`, when + /// it started: its info then was empty, and no account stood there — the database answered + /// none, or an earlier transaction on the same journal destroyed the account, which its first + /// load in this transaction cleared. An account the database answered with, empty under EIP-161 + /// with storage, stood there. + /// + /// Read at the completed write of the account's `SELFDESTRUCT`. revm's flag of an account the + /// database answered none for was set at its first load on the journal and outlives the + /// transactions after it, so an earlier destruction is read off revm's entry for the one that + /// just completed: [`SelfdestructionRevertStatus::LocallySelfdestroyed`] names a first + /// destruction in this transaction of an account an earlier one destroyed. revm empties its + /// entries when a transaction ends, so they are this transaction's. + fn was_absent_at_start(&self, address: Address, account: &Account) -> bool { + if !account.original_info().is_empty() { + return false; + } + account.is_loaded_as_not_existing() || + self.entries.iter().rev().find_map(|entry| match entry { + JournalEntry::AccountDestroyed { address: destroyed, destroyed_status, .. } + if *destroyed == address => + { + Some(*destroyed_status == SelfdestructionRevertStatus::LocallySelfdestroyed) + } + _ => None, + }) == Some(true) + } + + /// Whether the account at `address` is empty under EIP-161 — no nonce, no balance, no code — + /// as the transaction holds it: a value moved to it, or a creation at it, makes a new account. + /// An account the transaction has not loaded is not known to be empty. + pub(crate) fn is_empty(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| account.info.is_empty()) + } + + /// The current balance of the account at `address`; nothing for one the transaction has not + /// loaded. + fn balance(&self, address: Address) -> U256 { + self.loaded(address).map_or(U256::ZERO, |account| account.info.balance) + } + + /// The records a transfer of `value` from `from` to `to` makes and takes back, as the journal's + /// state stands, and whether it journals a transfer log: nothing for a transfer to the same + /// account or of nothing, which revm moves nothing for, and nothing for a value `from` cannot + /// fund, which revm refuses. + pub(crate) fn transfer_records(&self, from: Address, to: Address, value: U256) -> StartRecords { + if from == to || value.is_zero() { + return StartRecords::NONE; + } + let Some(from_after) = self.balance(from).checked_sub(value) else { + return StartRecords::NONE; + }; + let to_after = self.balance(to).saturating_add(value); + let transfer = RecordDelta::of_account( + self.is_changed(from), + self.changed_with_balance(from, from_after), + ) + .with(RecordDelta::of_account( + self.is_changed(to), + self.changed_with_balance(to, to_after), + )); + StartRecords { transfer, transfer_log: self.transfer_logs, ..StartRecords::NONE } + } + + /// The records a creation by `creator` at `created` with an endowment of `value` makes, before + /// revm bumps the creator's nonce: the creator's nonce, when the bump changes an account the + /// transaction had not changed; the account it creates, when the transaction had not changed + /// it; and a transfer log for an endowment. Nothing for an endowment `creator` cannot fund, + /// which revm refuses before it bumps the nonce, nor for a creation that takes no address. + pub(crate) fn creation_records( + &self, + creator: Address, + created: Option
, + value: U256, + ) -> StartRecords { + let Some(created) = created else { return StartRecords::NONE }; + if self.balance(creator) < value { + return StartRecords::NONE; + } + StartRecords { + transfer: RecordDelta::NONE, + created: !self.is_changed(created), + creator: !self.is_changed(creator), + transfer_log: self.transfer_logs && !value.is_zero(), + } + } + + /// The creator at `address` of a creation revm is about to decide, as the transaction holds it. + /// The creator is read loaded: revm loads it first thing when it decides the creation. + pub(crate) fn creator_before(&self, address: Address) -> CreatorBefore { + CreatorBefore { + address, + nonce: self.loaded(address).map_or(0, |account| account.info.nonce), + changed: self.is_changed(address), + empty: self.is_empty(address), + } + } + + /// Whether revm bumped the nonce of the creator `before` was read of: it does for every + /// creation it decides but one it refuses on the creator's account — an endowment the creator + /// cannot fund, a nonce at its maximum — and the bump stands whatever the creation then does. + pub(crate) fn bumped(&self, before: &CreatorBefore) -> bool { + self.loaded(before.address).is_some_and(|account| account.info.nonce != before.nonce) + } + + /// What the nonce bump of the creator `before` was read of made, read off the journal once its + /// creation returned: the creator's write record when the bump changed an account the + /// transaction had not changed, and one account of state growth when the bump made an empty + /// account. The record follows the account's net change, so a keyless deployment's settlement, + /// which may set the signer's nonce back, is read once it did. + pub(crate) fn creator_counted(&self, before: &CreatorBefore) -> Counted { + let record = RecordDelta::of_account(before.changed, self.is_changed(before.address)); + let grows = before.empty && self.loaded(before.address).is_some_and(|a| !a.info.is_empty()); + Counted::records(record.added, record.taken, false).with_growth(u64::from(grows), 0) + } + + /// The account of state growth a transfer of `value` from `from` to `to` makes, as the + /// journal's state stands: one when it moves value `from` can fund to another account that is + /// empty, which the transfer creates. A `CALLCODE`'s transfer is from the calling account to + /// itself, and a `DELEGATECALL` or `STATICCALL` carries none: none of them creates an account. + pub(crate) fn transfer_growth(&self, from: Address, to: Address, value: U256) -> u64 { + let creates = + from != to && !value.is_zero() && self.balance(from) >= value && self.is_empty(to); + u64::from(creates) + } + + /// The account of state growth a creation by `creator` at `created` with an endowment of + /// `value` makes on its frame, as the journal's state stands: one when the creator can fund + /// the endowment and the address is empty, which the creation creates. An address that holds + /// a balance, a nonce or code is no new account, and a collision adds none. + pub(crate) fn creation_growth(&self, creator: Address, created: Address, value: U256) -> u64 { + u64::from(self.balance(creator) >= value && self.is_empty(created)) + } + + /// The records a frame start of `kind` by `caller` makes: a call's value transfer to `target` + /// ([`transfer_records`](Self::transfer_records)); a creation's at `target`, the address it + /// takes ([`creation_records`](Self::creation_records)). The transfer of a `CALLCODE` is from + /// the calling account to itself, and a `DELEGATECALL` or `STATICCALL` carries none: neither + /// makes a record. + pub(crate) fn start_records( + &self, + kind: FrameStartKind, + caller: Address, + target: Option
, + value: U256, + ) -> StartRecords { + match kind { + FrameStartKind::Create | FrameStartKind::Create2 => { + self.creation_records(caller, target, value) + } + FrameStartKind::Call | + FrameStartKind::CallCode | + FrameStartKind::DelegateCall | + FrameStartKind::StaticCall => target + .map_or(StartRecords::NONE, |target| self.transfer_records(caller, target, value)), + } + } + + /// The records a `SELFDESTRUCT` of `address` to `target` that moved `balance` made and took + /// back, read off the journal after the write: a destruction changes balances alone, so the + /// destructed account held `balance` before it, and a beneficiary that is another account its + /// balance less `balance`, all of which it got. + fn destruction_records(&self, address: Address, target: Address, balance: U256) -> RecordDelta { + let source = RecordDelta::of_account( + self.changed_with_balance(address, balance), + self.is_changed(address), + ); + if target == address { + return source; + } + let before = self.balance(target).saturating_sub(balance); + source.with(RecordDelta::of_account( + self.changed_with_balance(target, before), + self.is_changed(target), + )) + } + + /// What the completed write `write` counts, the history bytes it appends and takes back, and, + /// for the first effective `SELFDESTRUCT` of an account created in the transaction, the parts + /// of the account that come back: /// /// - `SSTORE`: the first change of a slot in the transaction is one write record; writing the - /// slot back to its original value takes the record back. - /// - `LOG`: its bytes, one base record for the address, one per topic and the data. - /// - `SELFDESTRUCT`: one write record for the beneficiary, when value moves to another account - /// than the destructed one and the transaction's `sender`, whose account the transaction body - /// counts. - pub(crate) fn effect(&self, sender: Address) -> RecordEffect { - match self { - Self::Sstore(slot) => { - if slot.is_original_eq_present() { + /// slot back to its original value takes the record back; a slot whose original value is zero + /// is one of state growth while it holds another, made by the write from zero and taken back + /// by the write to zero. A slot of an account created in the transaction and destroyed since + /// counts nothing ([`is_destroyed`](Self::is_destroyed)): the destruction took back what its + /// slots counted; + /// - `LOG`: its bytes, one base record for the address, one per topic and the data, which are + /// history beside the records; + /// - `SELFDESTRUCT`: the records of the accounts the move changed and returned — the + /// beneficiary, and the destructed account whose balance the move clears — and, when it moved + /// value to another account, the EIP-7708 transfer log revm journaled for the move, which is + /// data size and no history, and one of state growth when that account did not exist; and + /// what the parts it destroys take back ([`destroyed_parts`](Self::destroyed_parts)), whose + /// records are history taken back beside the move's. The code's history is the schedule's + /// charge for the deposit, which the caller gives back from the parts. + pub(crate) fn write_counted( + &self, + write: &CompletedWrite<'_>, + ) -> (Counted, HistoryBytes, Option) { + let mut destroyed = None; + let counted = match *write { + CompletedWrite::Sstore { address, .. } if self.is_destroyed(address) => Counted::NONE, + CompletedWrite::Sstore { result: slot, .. } => { + let records = if slot.is_original_eq_present() { if slot.is_original_eq_new() { - RecordEffect::None + Counted::NONE } else { - RecordEffect::Record(WRITE_RECORD) + Counted::records(1, 0, false) } } else if slot.is_original_eq_new() { - RecordEffect::Refund(WRITE_RECORD) + Counted::records(0, 1, false) } else { - RecordEffect::None - } + Counted::NONE + }; + let fresh = slot.original_value.is_zero(); + let rise = fresh && slot.present_value.is_zero() && !slot.new_value.is_zero(); + let fall = fresh && !slot.present_value.is_zero() && slot.new_value.is_zero(); + records.with_growth(u64::from(rise), u64::from(fall)) } - Self::Log { topics, data_len } => RecordEffect::Record(LimitUsage { - data_size: log_history_bytes(u64::from(*topics), *data_len), - write_records: 0, - }), - Self::SelfDestruct { had_value, to_other_account, beneficiary, .. } => { - if *had_value && *to_other_account && *beneficiary != sender { - RecordEffect::Record(WRITE_RECORD) - } else { - RecordEffect::None - } + CompletedWrite::Log { topics, data_len, .. } => { + Counted::bytes(log_history_bytes(u64::from(topics), data_len)) } - } + CompletedWrite::SelfDestruct { address, target, balance, result } => { + let records = self.destruction_records(address, target, balance); + let moved = result.had_value && target != address; + let logged = self.transfer_logs && moved; + let creates = moved && !result.target_exists; + let counted = Counted::records(records.added, records.taken, logged) + .with_growth(u64::from(creates), 0); + destroyed = self.destroyed_parts(address, result.previously_destroyed); + destroyed.as_ref().map_or(counted, |parts| counted.plus(parts.counted())) + } + }; + let log = if counted.transfer_log { TRANSFER_LOG_SIZE } else { 0 }; + let code = destroyed.as_ref().map_or(0, |parts| parts.code); + let history = HistoryBytes { + appended: counted.bytes_added() - log, + taken: counted.bytes_taken() - code, + }; + (counted, history, destroyed) } +} - /// Whether the opcode moved value to another account: a `SELFDESTRUCT` of an account that had - /// a balance, to a beneficiary other than itself. revm journals an EIP-7708 transfer log for - /// exactly that move, whoever the beneficiary is — the sender included — and none for a - /// destruction to itself, which burns the balance on Satin's base spec. - pub(crate) const fn moves_value(&self) -> bool { - matches!(self, Self::SelfDestruct { had_value: true, to_other_account: true, .. }) - } +/// The history bytes a completed write appends and takes back. +/// +/// They are the record's data size and nothing else: what a log or a write record weighs in a +/// block is what the data-size limit meters it at, so the two cannot drift apart. That is the +/// pairing, and it holds per record; a transaction's two totals part where the byte table says +/// they do. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct HistoryBytes { + /// Bytes the write appends: the records it creates and, for a log, its own bytes. + pub(crate) appended: u64, + /// Bytes the records the write took back no longer append. Deployed code a destruction takes + /// back is not among them: its history is the schedule's charge for the deposit. + pub(crate) taken: u64, } #[cfg(test)] mod tests { use super::*; - use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::{address, U256}; + use crate::{ + limit::{KV_UPDATE_POOL, STATE_GROWTH_POOL}, + test_utils::MemoryDatabase, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE, + }; + use alloy_primitives::{address, Bytes}; + use revm::{ + bytecode::Bytecode, + context::JournalTr, + context_interface::{ + context::{SStoreResult, SelfDestructResult}, + journaled_state::account::JournaledAccountTr, + }, + }; const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); const OTHER: Address = address!("0000000000000000000000000000000000000077"); + const DESTRUCTED: Address = address!("0000000000000000000000000000000000000d00"); + const MOVED: SelfDestructResult = + SelfDestructResult { had_value: true, target_exists: true, previously_destroyed: false }; - fn sstore(original: u64, present: u64, new: u64) -> StagedRecord { - StagedRecord::Sstore(SStoreResult { + fn slot(original: u64, present: u64, new: u64) -> SStoreResult { + SStoreResult { original_value: U256::from(original), present_value: U256::from(present), new_value: U256::from(new), - }) + } + } + + /// A journal holding three accounts as the transaction loaded them. + fn journal() -> Journal { + let db = MemoryDatabase::default() + .account_balance(SENDER, U256::from(10)) + .account_balance(OTHER, U256::from(4)) + .account_balance(DESTRUCTED, U256::from(5)); + let mut journal = Journal::new(db); + for address in [SENDER, OTHER, DESTRUCTED] { + journal.load_account(address).unwrap(); + } + journal + } + + /// The `SELFDESTRUCT` of `DESTRUCTED` to `target` that moved `balance`. + const fn destruction(target: Address, balance: u64) -> CompletedWrite<'static> { + CompletedWrite::SelfDestruct { + address: DESTRUCTED, + target, + balance: U256::from_limbs([balance, 0, 0, 0]), + result: &MOVED, + } + } + + /// What an `SSTORE` of `new` over a slot holding `present`, `original` at the transaction's + /// start, counts. + fn sstore_counted(original: u64, present: u64, new: u64) -> Counted { + let journal = journal(); + let slot = slot(original, present, new); + let write = CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: &slot }; + Accounts::of(&journal, false).write_counted(&write).0 } /// A slot counts once, on its first change in the transaction; writing it back to its /// original value takes the record back; every other write counts nothing. #[test] fn test_sstore_record_rules() { - assert_eq!(sstore(0, 0, 1).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sstore(5, 5, 0).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sstore(0, 1, 0).effect(SENDER), RecordEffect::Refund(WRITE_RECORD)); - assert_eq!(sstore(0, 1, 2).effect(SENDER), RecordEffect::None); - assert_eq!(sstore(3, 3, 3).effect(SENDER), RecordEffect::None); - assert_eq!(sstore(3, 4, 4).effect(SENDER), RecordEffect::None); + let records = |original, present, new| { + let counted = sstore_counted(original, present, new); + (counted.added.get(KV_UPDATE_POOL), counted.taken.get(KV_UPDATE_POOL)) + }; + assert_eq!(records(0, 0, 1), (1, 0)); + assert_eq!(records(5, 5, 0), (1, 0)); + assert_eq!(records(0, 1, 0), (0, 1)); + assert_eq!(records(0, 1, 2), (0, 0)); + assert_eq!(records(3, 3, 3), (0, 0)); + assert_eq!(records(3, 4, 4), (0, 0)); + assert_eq!(sstore_counted(0, 0, 1), Counted::records(1, 0, false).with_growth(1, 0)); + } + + /// An `SSTORE` changes state growth by the slot's original, present and new values, on the + /// spec's eight rows: a rise for original zero, present zero, new non-zero; a fall for original + /// zero, present non-zero, new zero; nothing on the six others, a slot whose original value is + /// not zero never changing it. + #[test] + fn test_an_sstore_grows_state_only_on_a_slot_whose_original_is_zero() { + let growth = |original, present, new| { + let counted = sstore_counted(original, present, new); + (counted.added.get(STATE_GROWTH_POOL), counted.taken.get(STATE_GROWTH_POOL)) + }; + let rows = [ + ((0, 0, 0), (0, 0)), + ((0, 0, 1), (1, 0)), + ((0, 1, 0), (0, 1)), + ((0, 1, 2), (0, 0)), + ((5, 0, 0), (0, 0)), + ((5, 0, 6), (0, 0)), + ((5, 5, 0), (0, 0)), + ((5, 5, 6), (0, 0)), + ]; + for ((original, present, new), expected) in rows { + assert_eq!(growth(original, present, new), expected, "{original}, {present}, {new}"); + } } - /// A log is 32 bytes for its address, 32 per topic and its data. + /// A log is 32 bytes for its address, 32 per topic and its data, all of them history; a + /// transfer log counts what a `LOG3` carrying one word counts. #[test] fn test_log_bytes() { - let log = |topics, data_len| StagedRecord::Log { topics, data_len }.effect(SENDER); - assert_eq!(log(0, 0), RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 })); - assert_eq!( - log(4, 100), - RecordEffect::Record(LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }) - ); - assert_eq!( - log(1, u64::MAX), - RecordEffect::Record(LimitUsage { data_size: u64::MAX, write_records: 0 }) - ); + let journal = journal(); + let accounts = Accounts::of(&journal, false); + let counted = |topics, data_len| { + let (counted, history, _) = + accounts.write_counted(&CompletedWrite::Log { address: OTHER, topics, data_len }); + (counted, history) + }; + assert_eq!(counted(0, 0), (Counted::bytes(32), HistoryBytes { appended: 32, taken: 0 })); + assert_eq!(counted(4, 100).0, Counted::bytes(32 + 4 * 32 + 100)); + assert_eq!(counted(1, u64::MAX).0, Counted::bytes(u64::MAX)); + assert_eq!(counted(3, 32).0.bytes_added(), TRANSFER_LOG_SIZE); + assert_eq!(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32, TRANSFER_LOG_SIZE); } - /// A record's history bytes are its data size, at every site: a log's own bytes, a write - /// record's forty, and nothing for a write that leaves no record. + /// A `SELFDESTRUCT`'s records are rebuilt from the journal after the write and the balance it + /// moved, which tells the cases the after state alone cannot: a destructed account and a + /// beneficiary the transaction had not changed are two records; a beneficiary drained earlier, + /// which the move puts back as loaded, takes its record back; a destructed account funded or + /// drained earlier, changed before the move and after it, adds none of its own; and a + /// destruction to itself moves nothing. The move's transfer log is data size and no history. #[test] - fn test_history_bytes_are_the_records_data_size() { + fn test_a_destruction_counts_what_its_move_changed() { + let records_bytes = |records| WRITE_RECORD_SIZE * records; + + let mut fresh = journal(); + fresh.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); + let (counted, history, _) = + Accounts::of(&fresh, true).write_counted(&destruction(OTHER, 5)); + assert_eq!(counted, Counted::records(2, 0, true)); + assert_eq!(history, HistoryBytes { appended: records_bytes(2), taken: 0 }); assert_eq!( - sstore(0, 0, 1).effect(SENDER).history_bytes(), - HistoryBytes::Appended(WRITE_RECORD_SIZE) + Accounts::of(&fresh, false).write_counted(&destruction(OTHER, 5)).0, + Counted::records(2, 0, false), + "no transfer logs, no log" ); + + // The destructed account sent one away and the beneficiary all it had: the move of the + // four left puts the beneficiary back as loaded, and leaves the destructed account changed. + let mut drained = journal(); + drained.transfer(DESTRUCTED, SENDER, U256::from(1)).unwrap(); + drained.transfer(OTHER, SENDER, U256::from(4)).unwrap(); + drained.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); + let (counted, history, _) = + Accounts::of(&drained, false).write_counted(&destruction(OTHER, 4)); + assert_eq!(counted, Counted::records(0, 1, false)); + assert_eq!(history, HistoryBytes { appended: 0, taken: records_bytes(1) }); + + let mut funded = journal(); + funded.transfer(SENDER, DESTRUCTED, U256::from(2)).unwrap(); + funded.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); assert_eq!( - sstore(0, 1, 0).effect(SENDER).history_bytes(), - HistoryBytes::Taken(WRITE_RECORD_SIZE) + Accounts::of(&funded, false).write_counted(&destruction(OTHER, 7)).0, + Counted::records(1, 0, false), + "the beneficiary's record alone" ); - assert_eq!(sstore(3, 3, 3).effect(SENDER).history_bytes(), HistoryBytes::None); + + // A pre-existing account destructing to itself keeps its balance: nothing changes. + let to_itself = journal(); assert_eq!( - StagedRecord::Log { topics: 3, data_len: 32 }.effect(SENDER).history_bytes(), - HistoryBytes::Appended(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32) + Accounts::of(&to_itself, true).write_counted(&destruction(DESTRUCTED, 5)).0, + Counted::NONE ); - let to_other = StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary: OTHER, + } + + /// A `SELFDESTRUCT` that moves a non-zero balance to another account that does not exist + /// creates it: one of state growth with its records. A beneficiary that exists, a destruction + /// that moves nothing and one to itself create nothing. + #[test] + fn test_a_destruction_grows_state_by_the_beneficiary_it_creates() { + let growth = |target, balance: u64, target_exists| { + let result = SelfDestructResult { + had_value: balance != 0, + target_exists, + previously_destroyed: false, + }; + let write = CompletedWrite::SelfDestruct { + address: DESTRUCTED, + target, + balance: U256::from(balance), + result: &result, + }; + let journal = journal(); + let counted = Accounts::of(&journal, true).write_counted(&write).0; + (counted.added.get(STATE_GROWTH_POOL), counted.taken.get(STATE_GROWTH_POOL)) }; - assert_eq!( - to_other.effect(SENDER).history_bytes(), - HistoryBytes::Appended(WRITE_RECORD_SIZE) - ); + let fresh = address!("00000000000000000000000000000000000000f5"); + assert_eq!(growth(fresh, 5, false), (1, 0), "a new beneficiary"); + assert_eq!(growth(OTHER, 5, true), (0, 0), "a beneficiary that exists"); + assert_eq!(growth(fresh, 0, false), (0, 0), "no balance moved"); + assert_eq!(growth(DESTRUCTED, 5, false), (0, 0), "to itself"); } - /// Only value that moves to another account is a beneficiary write. + /// What `journal` looks like once `SENDER` created an account at `created` with an endowment + /// of `endowment`, the account wrote `slots` (key, value) in order and deposited `code`. + fn created( + db: MemoryDatabase, + created: Address, + endowment: u64, + slots: &[(u64, u64)], + code: &[u8], + ) -> Journal { + let mut journal = Journal::new(db.account_balance(SENDER, U256::from(10))); + journal.load_account(SENDER).unwrap(); + journal.load_account(created).unwrap(); + let spec = journal.cfg.spec; + journal.create_account_checkpoint(SENDER, created, U256::from(endowment), spec).unwrap(); + for &(key, value) in slots { + journal.sstore(created, U256::from(key), U256::from(value)).unwrap(); + } + if !code.is_empty() { + journal.set_code(created, Bytecode::new_legacy(Bytes::copy_from_slice(code))); + } + journal + } + + /// The first effective destruction of an account created in the transaction gives back the + /// parts the transaction made: the leaf when the database held no account there, the code it + /// deposited and each slot it made non-zero, in key order, a slot written back to zero not + /// among them. A leaf the database held — with a balance, or empty under EIP-161 with storage + /// — stands. A repeated destruction and one of an account the transaction did not create give + /// back nothing; from the mark an `SSTORE` of the account's slots counts nothing. #[test] - fn test_selfdestruct_record_rules() { - let sd = |had_value, to_other_account| { - let beneficiary = OTHER; - StagedRecord::SelfDestruct { had_value, to_other_account, beneficiary }.effect(SENDER) + fn test_a_destruction_gives_back_the_parts_the_transaction_made() { + let fresh = address!("00000000000000000000000000000000000c4ea7"); + let slots = [(3, 1), (1, 7), (2, 1), (2, 0)]; + let mut made = created(MemoryDatabase::default(), fresh, 0, &slots, &[0x60, 0x00, 0xff]); + assert!(!Accounts::of(&made, true).is_destroyed(fresh)); + made.selfdestruct(fresh, OTHER, false).unwrap(); + let accounts = Accounts::of(&made, true); + let parts = DestroyedParts { + leaf: true, + code: 3, + slots: vec![U256::from(1), U256::from(3)], + deleted: 0, + }; + assert_eq!(accounts.destroyed_parts(fresh, false), Some(parts.clone())); + assert_eq!(parts.records(), 3); + assert_eq!( + parts.counted(), + Counted::records(0, 3, false).with_growth(0, 3).plus_bytes_taken(3), + "three records with their bytes, three units of growth, the code's three bytes" + ); + assert!(accounts.is_destroyed(fresh)); + assert_eq!(accounts.destroyed_parts(fresh, true), None, "a repeated destruction"); + + // The write's own count carries the parts; the code's bytes are no record's history. + let result = SelfDestructResult { + had_value: false, + target_exists: true, + previously_destroyed: false, }; - assert_eq!(sd(true, true), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sd(true, false), RecordEffect::None); - assert_eq!(sd(false, true), RecordEffect::None); - assert_eq!(sd(false, false), RecordEffect::None); - let to_sender = StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary: SENDER, + let write = CompletedWrite::SelfDestruct { + address: fresh, + target: OTHER, + balance: U256::ZERO, + result: &result, }; - assert_eq!(to_sender.effect(SENDER), RecordEffect::None, "the body counts the sender"); + let (counted, history, destroyed) = accounts.write_counted(&write); + assert_eq!(destroyed, Some(parts.clone())); + assert_eq!(counted, parts.counted()); + assert_eq!(history, HistoryBytes { appended: 0, taken: 3 * WRITE_RECORD_SIZE }); + + // After the mark a slot's write counts nothing, whichever transition it makes. + for (original, present, new) in [(0, 0, 1), (0, 1, 0), (0, 7, 8)] { + let slot = slot(original, present, new); + let write = + CompletedWrite::Sstore { address: fresh, key: U256::from(1), result: &slot }; + assert_eq!( + accounts.write_counted(&write).0, + Counted::NONE, + "{original}, {present}, {new}" + ); + } + + // A leaf the database held stands; the code and the slots still come back. + let funded = MemoryDatabase::default().account_balance(fresh, U256::from(2)); + let storage = + MemoryDatabase::default().account_storage(fresh, U256::from(9), U256::from(5)); + for (db, what) in [(funded, "a balance"), (storage, "an empty account with storage")] { + let mut made = created(db, fresh, 0, &[(1, 1)], &[]); + made.selfdestruct(fresh, OTHER, false).unwrap(); + assert_eq!( + Accounts::of(&made, true).destroyed_parts(fresh, false), + Some(DestroyedParts { + leaf: false, + code: 0, + slots: vec![U256::from(1)], + deleted: 0 + }), + "{what}" + ); + } + + // Slots that held a value at the start, loaded before the creation as only a tool loads + // them: the deletion makes the record of the one that still holds it, and the one the + // transaction wrote since keeps the record its write made. Neither refills or falls. + let held = MemoryDatabase::default() + .account_storage(fresh, U256::from(8), U256::from(4)) + .account_storage(fresh, U256::from(9), U256::from(5)); + let mut loaded = Journal::new(held.account_balance(SENDER, U256::from(10))); + loaded.load_account(SENDER).unwrap(); + loaded.load_account(fresh).unwrap(); + for key in [8, 9] { + loaded.sload(fresh, U256::from(key)).unwrap(); + } + let spec = loaded.cfg.spec; + loaded.create_account_checkpoint(SENDER, fresh, U256::ZERO, spec).unwrap(); + loaded.sstore(fresh, U256::from(8), U256::from(6)).unwrap(); + loaded.selfdestruct(fresh, OTHER, false).unwrap(); + let parts = Accounts::of(&loaded, true).destroyed_parts(fresh, false).unwrap(); + assert_eq!(parts, DestroyedParts { leaf: false, code: 0, slots: vec![], deleted: 1 }); + assert_eq!(parts.counted(), Counted::records(1, 0, false)); + + // An account the transaction did not create is an ordinary deletion. + let mut older = journal(); + older.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); + let accounts = Accounts::of(&older, true); + assert_eq!(accounts.destroyed_parts(DESTRUCTED, false), None); + assert!(!accounts.is_destroyed(DESTRUCTED)); } - /// Value moves to another account only when a destructed account had a balance and a - /// beneficiary other than itself, the sender included; a write or a log moves none. + /// An account's delta: a record when a write changes it, a record back when a write returns + /// it, and nothing when it stays as it was, changed or not. #[test] - fn test_only_a_destruction_to_another_account_moves_value() { - let sd = |had_value, to_other_account, beneficiary| StagedRecord::SelfDestruct { - had_value, - to_other_account, - beneficiary, - }; - assert!(sd(true, true, OTHER).moves_value()); - assert!(sd(true, true, SENDER).moves_value(), "the body's record is not the log"); - assert!(!sd(true, false, OTHER).moves_value(), "a destruction to itself burns"); - assert!(!sd(false, true, OTHER).moves_value(), "nothing to move"); - assert!(!sstore(0, 0, 1).moves_value()); - assert!(!StagedRecord::Log { topics: 3, data_len: 32 }.moves_value()); + fn test_an_accounts_delta_follows_its_change() { + assert_eq!(RecordDelta::of_account(false, true), RecordDelta { added: 1, taken: 0 }); + assert_eq!(RecordDelta::of_account(true, false), RecordDelta { added: 0, taken: 1 }); + assert_eq!(RecordDelta::of_account(true, true), RecordDelta::NONE); + assert_eq!(RecordDelta::of_account(false, false), RecordDelta::NONE); + assert_eq!( + RecordDelta::of_account(false, true).with(RecordDelta::of_account(true, false)), + RecordDelta { added: 1, taken: 1 } + ); } - /// A transfer log counts what a `LOG3` carrying one word counts: the same rule, not a number - /// of its own. + /// A transfer's records follow the net change of both sides, on the balances the transfer + /// leaves them; a transfer to the same account, of nothing, or of more than the sender holds + /// records nothing and journals no log. A creation records its created account and its + /// creator's nonce only where the transaction had not changed them, keeps the creator's off + /// the created frame, and journals a log for an endowment. #[test] - fn test_a_transfer_log_counts_what_a_log3_of_one_word_counts() { + fn test_a_starts_records_follow_the_net_change() { + let mut journal = journal(); + let accounts = Accounts::of(&journal, true); + let both = accounts.transfer_records(OTHER, DESTRUCTED, U256::from(1)); + assert_eq!(both.transfer, RecordDelta { added: 2, taken: 0 }); + assert!(both.transfer_log); + assert_eq!(accounts.transfer_records(OTHER, OTHER, U256::from(1)), StartRecords::NONE); + assert_eq!(accounts.transfer_records(OTHER, DESTRUCTED, U256::ZERO), StartRecords::NONE); + assert_eq!(accounts.transfer_records(OTHER, DESTRUCTED, U256::from(5)), StartRecords::NONE); + + // OTHER sent 1 to DESTRUCTED: sending it back returns both. + journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); + let back = Accounts::of(&journal, true).transfer_records(DESTRUCTED, OTHER, U256::from(1)); + assert_eq!(back.transfer, RecordDelta { added: 0, taken: 2 }); + assert_eq!(back.counted(), Counted::records(0, 2, true)); + + let created = address!("00000000000000000000000000000000000c4ea7"); + let accounts = Accounts::of(&journal, true); + let creation = accounts.creation_records(SENDER, Some(created), U256::from(1)); assert_eq!( - StagedRecord::Log { topics: 3, data_len: 32 }.effect(SENDER), - RecordEffect::Record(crate::limit::TRANSFER_LOG) + creation, + StartRecords { + transfer: RecordDelta::NONE, + created: true, + creator: true, + transfer_log: true + } ); + assert_eq!(creation.on_frame(), RecordDelta { added: 1, taken: 0 }); + let onto_changed = accounts.creation_records(OTHER, Some(DESTRUCTED), U256::ZERO); + assert!(!onto_changed.created && !onto_changed.creator && !onto_changed.transfer_log); + assert_eq!(accounts.creation_records(SENDER, None, U256::ZERO), StartRecords::NONE); + assert_eq!( + accounts.creation_records(SENDER, Some(created), U256::from(11)), + StartRecords::NONE, + "an endowment the creator cannot fund" + ); + } + + /// A creator's record is read off what revm did: nothing while its nonce is where it was + /// before the creation; once revm bumped it, a record when the bump changed an account the + /// transaction had not changed, and one account of state growth when it made an empty one. A + /// nonce set back leaves no record, unless the account keeps another change. + #[test] + fn test_a_creators_record_is_read_off_the_bump() { + let empty = address!("00000000000000000000000000000000000e3e70"); + let mut journal = journal(); + journal.load_account(empty).unwrap(); + journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); + let accounts = Accounts::of(&journal, true); + let [sender, changed, empty_before] = + [SENDER, DESTRUCTED, empty].map(|address| accounts.creator_before(address)); + for before in [sender, changed, empty_before] { + assert!(!accounts.bumped(&before), "{before:?}: nothing moved yet"); + } + + for address in [SENDER, DESTRUCTED, empty] { + assert!(journal.load_account_mut(address).unwrap().data.bump_nonce()); + } + let accounts = Accounts::of(&journal, true); + let record = Counted::records(1, 0, false); + for (before, counted) in + [(sender, record), (changed, Counted::NONE), (empty_before, record.with_growth(1, 0))] + { + assert!(accounts.bumped(&before), "{before:?}"); + assert_eq!(accounts.creator_counted(&before), counted, "{before:?}"); + } + + // A nonce set back: the unchanged account leaves no record, the one that keeps a balance + // change stands as it was. + for address in [SENDER, DESTRUCTED] { + journal.load_account_mut(address).unwrap().data.set_nonce(0); + } + let accounts = Accounts::of(&journal, true); + assert_eq!(accounts.creator_counted(&sender), Counted::NONE); + assert_eq!(accounts.creator_counted(&changed), Counted::NONE); } } diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 5f450ba7b..cf25b0016 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -9,7 +9,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - `keyless/`: native keyless deployment. The `KeylessDeploy` address, code and ABI and the semantics of a deployment (`mod.rs`); the dispatch, the call's frame and its first run — the overhead, the nine rules, the charges of the creation's start and the creation it starts (`dispatch.rs`); the creation's return into its call and the ABI answer on the call's resume (`settle.rs`); the pre-EIP-155 transaction format and the error ABI (`tx.rs`, `error.rs`). - `control.rs`: `MegaAccessControl`'s address, code, ABI and revert payloads, `SLOT_NUM_ACCESS_TYPE`, and its interceptor, which steers gas detention's switch. - `limit_control.rs`: `MegaLimitControl`'s address, code, ABI and its interceptor, which answers the compute the calling frame could still spend. -- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, its two pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness) and `transact_apply_pending_changes` (the system call on `pre_block_call_gas_limit`) — and `load_system_address`, the warming journal read of the registry's account and `_currentSystemAddress` every transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, its two pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness) and `transact_apply_pending_changes` (the system call on `PRE_BLOCK_CALL_GAS_LIMIT`) — and `load_system_address`, the warming journal read of the registry's account and `_currentSystemAddress` every transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. - `predeploys.rs`: the list of the seven predeploys (`system_contract_specs`: address, code, code hash), the EIP-7997 factory's constants, and `check_system_contract`, the read Satin's activation block makes of each: exactly the expected code, whatever the nonce, balance and storage, or `SystemContractCheckError::UnexpectedCode` naming the address and both hashes. - `intercept.rs`: the dispatch — the address test, the selector peek, the value policy and the shape of an answer. - `tx.rs`: the system-address transaction, its whitelist and shape, the per-transaction decision and the refusal of another shape from the system address (`classify_system_transaction`), and the validation that precedes its promotion to a deposit. @@ -21,9 +21,9 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - An unknown selector is never intercepted: the call falls through to the deployed bytecode, and what that bytecode answers is the contract's own. The two control contracts revert with `NotIntercepted()` from their fallback; `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data while a `keylessDeploy` call a contract makes reaches the method body's `NotIntercepted()`; the Oracle runs its other methods, and reverts with empty data on a selector it does not declare. - `CALL` and `STATICCALL` reach the dispatch. `CALLCODE` and `DELEGATECALL` run the callee's code in the caller's context, so they are refused by the scheme guard before any interceptor. - A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names (`KeylessDeploy` answers `NoEtherTransfer()`). The policy is per method and is applied after the selector matched, so a value-bearing call to an unknown selector still falls through. -- An answer is a `synthetic_call_result`: the forwarded gas untouched, the caller's reservoir carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. +- An answer is a `synthetic_call_result`: the forwarded gas untouched, the reservoir share the call inherited carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. - An interceptor that lets the frame run charges nothing: the frame starts as it was built. -- A keyless deployment's call is a real frame at depth 0 in which no code runs: revm builds it on the contract, with its journal checkpoint, its gas and the lane a depth-0 call pushes, and `frame_run` makes its actions by hand (`keyless::run`, keyed on `MegaContext::keyless_frame`). Its first run, held by gas detention as any frame's, pays the overhead and what the `CREATE` opcode charges its frame, runs its lane as the signer, and returns the creation as its child at depth 1, or a refusal. The creation returns into it through `frame_return_result`, which reads the creation's outcome before revm's merge (`keyless::returning`) and applies the nonce take-back after (`keyless::settle`); on its resume the call answers in the ABI, unless it has a stop to return. The contract's account is touched as any call's target is, and its code never runs for a dispatched call. +- A keyless deployment's call is a real frame at depth 0 in which no code runs: revm builds it on the contract, with its journal checkpoint and its gas, the byte pool among it, as any depth-0 call, and its actions are made by hand, where revm built it and where its creation returns into it, and set on its interpreter, which revm's frame run, plain or inspected, returns without running an instruction. Its first action (`keyless::start`, in `frame_init`), once gas detention held the frame as any frame's, pays the overhead and what the `CREATE` opcode charges its frame, runs as the signer, and is the creation as its child at depth 1, or a refusal, which ends the frame before it runs. The creation returns into it through `frame_return_result`, which reads the creation's outcome before revm's merge (`keyless::returning`), applies the nonce take-back after (`keyless::settle`, while `MegaContext::keyless_creation` holds what the call started) and sets the call's answer in the ABI (`keyless::answer`), unless it has a stop to return. The contract's account is touched as any call's target is, and its code never runs for a dispatched call. - What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps what the creation's start wrote, a signer's nonce spent from 0 to 1, its account and its record; a call that reverts with a stop takes the whole deployment back through its checkpoint. A creation that never started (one an inspector answered) gives the signer's account back. A deployment from nonce 1 keeps no bump when the bump is the last nonce change it made, whether it deployed or failed: the settlement sets the nonce back, so the signer stays at 1, nobody can use up its attempts, and a resubmission of one that deployed is refused `ContractAlreadyExists()`, as in the legacy engine. It takes the record and its history back with the bump, unless the creation succeeded and moved value out of the signer, whose account then keeps a write of its own. A signer whose own code spends a nonce in the constructor that survives it — on a default configuration, a delegated signer's `CREATE` or `CREATE2`, successful or not — keeps every bump, because a later bump may stand for an account and the nonce is never moved back under it; that signer ends above 1 and every later deployment of it is refused `SignerNonceTooHigh`. - The Oracle's `sendHint` is a side effect, not an answer: it forwards the hint and returns `None`, so the contract's own bytecode runs. It forwards only for a call that could deliver it — no value, some gas, a calling frame whose volatile-data access is on — and the payload is counted on the transaction's data size before it is decoded. A hint that fails one of those conditions is neither forwarded nor counted, and neither is one whose payload would cross the transaction's data-size limit: the limit is checked before the bytes are counted, the call is answered with the stop, a revert of the call alone, and the transaction keeps none of the hint's bytes. A payload that is admitted and does not decode is counted and forwards nothing. - An interceptor that acts for its caller takes the caller as the frame one level above the frame the call would start (`depth - 1`). A transaction that calls a system contract directly has no calling frame: `MegaAccessControl` then switches nothing off, enables without refusal and answers `false`, and `remainingComputeGas()` answers the transaction's own frame's regular gas, or detention's cap when it is detained from its start (its sender is the block beneficiary). @@ -69,7 +69,7 @@ The executor commits it on its own, in the order the steps run: a commit hook on ## WHERE TO LOOK - Add a method to an intercepted contract: the contract's own module, next to the selectors it already answers, and a boundary test per `tests/system/`. - Change what a call to a system contract costs: `intercept.rs` for the dispatch, the contract's module for what its own method charges. -- Change a keyless deployment: `keyless/dispatch.rs` for what is dispatched, the rules and the charges of the creation's start; `keyless/settle.rs` for the creation's return into the call and the answer; `evm/execution.rs` for where they are called — `frame_init`, `frame_run` and `frame_return_result`; `tests/system/keyless/` for the tests. +- Change a keyless deployment: `keyless/dispatch.rs` for what is dispatched, the rules and the charges of the creation's start; `keyless/settle.rs` for the creation's return into the call and the answer; `evm/execution.rs` for where they are called — `frame_init` and `frame_return_result`, which set the actions on the call's interpreter for revm's run to return; `tests/system/keyless/` for the tests. - Change the system transaction's validation: `tx.rs::validate_and_promote`, which `MegaHandler::validate_env_as` calls for both the handler's `validate_env` and the stateless pool validation (`evm/validation.rs`, which leaves the system address's nonce and code to the state). - Change what a deposit-like transaction pays for the account it creates: `evm/execution.rs`, where the charge is made in the pre-execution phase. - Add a predeploy: a spec in `predeploys.rs::system_contract_specs`, which Satin's activation block then checks; a contract Satin itself would install needs a mechanism of its own, which the engine no longer has. diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ccc65c088..990875528 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -9,9 +9,12 @@ use alloy_evm::Database; use alloy_primitives::{Address, Bytes, U256}; use alloy_sol_types::SolCall; use revm::{ - context::{Cfg, ContextError, ContextTr, JournalTr, Transaction}, + context::{Cfg, ContextError, ContextTr, JournalTr}, context_interface::{ - cfg::{GasId, StateGasCharge, StateGasSite}, + cfg::{ + gas::{PoolAmounts, StartCharge}, + GasId, StateGasCharge, StateGasSite, + }, Host, }, handler::{EthFrame, FrameResult}, @@ -24,33 +27,20 @@ use revm::{ }; use crate::{ - charge_write_records_history, - limit::FrameStartRecords, - synthetic_call_result, + charge_write_records_history, synthetic_call_result, system::{ intercept::peek_selector, keyless::{ calculate_keyless_deploy_address, decode_keyless_tx, encode_error_result, - recover_signer, settle, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + recover_signer, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, }, }, untouched_call_gas, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; -/// Where a `keylessDeploy` call's frame stands, from its start to its answer: what its first run -/// and its resume need of each other, kept on the context while the frame is on revm's stack. -#[derive(Debug)] -pub(crate) enum KeylessFrame { - /// revm built the call's frame, which has not run. - Built, - /// The call's first run started its creation, which runs. - Deploying(Started), - /// The creation returned into the call, which answers on its resume. - Returned(settle::Returned), -} - -/// What a `keylessDeploy` call's creation is settled into the call with. +/// What a `keylessDeploy` call's creation is settled into the call with, kept on the context while +/// the creation runs. #[derive(Debug)] pub(crate) struct Started { /// The address the creation deploys at. @@ -61,13 +51,12 @@ pub(crate) struct Started { /// What the call was charged for the signer's account, which the creation's start creates: /// zero when the signer had one. pub(super) signer_account_charge: u64, - /// The history the call paid for the signer's nonce record: zero when the signer is the - /// transaction's sender, which makes no record, or when the transaction pays no history. + /// The history the call paid for the signer's nonce record: zero when the transaction had + /// changed the signer's account already — the transaction's sender among them — which makes + /// no record, or when the transaction pays no history. pub(super) signer_record_charge: u64, - /// Whether the creation moves value out of the signer's account. - pub(super) moves_value: bool, /// Whether the deposit of empty code at the deploy address was refused, which reverts the - /// creation ([`refuses_empty_deposit`](settle::refuses_empty_deposit)). + /// creation ([`refuses_empty_deposit`](super::settle::refuses_empty_deposit)). pub(super) empty_deposit_refused: bool, } @@ -102,9 +91,10 @@ pub(crate) fn is_dispatched( /// would be. /// /// Any other call is built as a call to the contract, whose code it never runs: its actions are -/// made by [`run`]. The dispatch is by address and selector, whatever the address holds, so where -/// the state holds no contract code the frame is built on the contract's own. A chain Satin runs -/// on holds it, as Rex2 deployed it, and Satin's activation block checks it. +/// made by hand, its first by [`start`]. The dispatch is by address and selector, whatever the +/// address holds, so where the state holds no contract code the frame is built on the contract's +/// own. A chain Satin runs on holds it, as Rex2 deployed it, and Satin's activation block checks +/// it. #[inline(never)] pub(crate) fn ready( ctx: &mut MegaContext, @@ -119,45 +109,19 @@ pub(crate) fn ready( return Ok(None); } let mut gas = untouched_call_gas(inputs); - ctx.detention.hold(&mut gas); + ctx.detention.hold(gas.tracker_mut()); let Err(refusal) = prepare(ctx, inputs, &mut gas)? else { unreachable!("a call carrying value is refused at rule 2") }; Ok(Some(refusal.answer(inputs, gas))) } -/// Whether `frame` is a `keylessDeploy` call's, whose actions [`run`] makes in place of an -/// interpreter: the transaction's own frame, while the dispatch keeps its state. -#[inline] -pub(crate) fn runs( - ctx: &MegaContext, - frame: &EthFrame, -) -> bool { - frame.depth == 0 && ctx.keyless_frame.is_some() -} - -/// The next action of a `keylessDeploy` call's frame, made by hand: on its first run, the refusal -/// or the creation [`start`] makes; on its resume, once its creation returned into it, its answer -/// ([`settle::answer`]). -/// -/// A frame with a stop to return — a limit the nonce record a failed creation leaves the call -/// crosses — returns it before this runs, as any frame does. -#[inline(never)] -pub(crate) fn run( - ctx: &mut MegaContext, - frame: &mut EthFrame, -) -> Result> { - match ctx.keyless_frame.take() { - Some(KeylessFrame::Built) => start(ctx, frame), - Some(KeylessFrame::Returned(returned)) => { - Ok(settle::answer(ctx, &returned, frame.interpreter.gas)) - } - state => unreachable!("a keylessDeploy call runs when built or returned into: {state:?}"), - } -} - -/// The first run of a `keylessDeploy` call's frame: charges its gas and holds it to the rules, in -/// the order below, then starts the creation it stands for. +/// The first action of a `keylessDeploy` call's frame, which runs no instruction: charges its gas +/// and holds it to the rules, in the order below, then starts the creation it stands for. It is +/// made once revm built the frame and gas detention held it for its first run: a refusal ends the +/// frame before it runs, and the creation is set on the frame's interpreter, which returns it when +/// the frame runs. The call's answer is made when the creation returned into it +/// ([`answer`](super::settle::answer)). /// /// # What the call pays, and what it is held to /// @@ -206,11 +170,13 @@ pub(crate) fn run( /// # The creation /// /// The creation is started as the signer's, at the signer's Nick's-Method address -/// (`CreateScheme::Custom`), as the call's child: its share of the data-size budget, its records, -/// its forward and the reservoir it inherits. The call's lane runs as the signer, whose -/// nonce the creation's start writes. The call's journal checkpoint was taken when revm built its +/// (`CreateScheme::Custom`), as the call's child, on its forward and on its share of the reservoir +/// the call's charges left and of each of the call's pools, from which the call drew nothing. +/// The call's frame runs as the signer, whose nonce the creation's start writes; the record of +/// that nonce is the call's, counted once the creation returned +/// ([`settle`](super::settle::settle)). The call's journal checkpoint was taken when revm built its /// frame, so a call that is stopped takes that write back with the rest. -fn start( +pub(crate) fn start( ctx: &mut MegaContext, frame: &mut EthFrame, ) -> Result> { @@ -225,29 +191,30 @@ fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - ctx.additional_limit.set_frame_creator(deployment.signer); - if let Some((on_lane, caller)) = deployment.record_charges { - ctx.additional_limit.stage_frame_charge(deployment.records, on_lane, caller); - } + // The creation's shares of the call's reservoir and pools are taken out of the call, as a + // `CREATE` opcode's are: the creation's return adds what it left back to what the call kept. + let shares = gas.tracker_mut().forward_to_child(ctx.gas_params()); let mut create = CreateInputs::new( deployment.signer, CreateScheme::Custom { address: deployment.deploy_address }, deployment.value, deployment.init_code, deployment.gas_limit, - gas.reservoir(), + shares.reservoir, ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); - ctx.keyless_frame = Some(KeylessFrame::Deploying(Started { + let (on_frame, signer_record) = deployment.record_charges.unwrap_or((0, 0)); + create.set_charged_start(StartCharge::new(on_frame, PoolAmounts::ZERO)); + create.set_pool_shares(shares.pools); + ctx.keyless_creation = Some(Started { deploy_address: deployment.deploy_address, signer: deployment.signer, signer_nonce: deployment.signer_nonce, signer_account_charge: deployment.signer_account_charge, - signer_record_charge: deployment.record_charges.map_or(0, |(_, caller)| caller), - moves_value: !deployment.value.is_zero(), + signer_record_charge: signer_record, empty_deposit_refused: false, - })); + }); Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) } @@ -264,10 +231,8 @@ struct Deployment { gas_limit: u64, /// Whether the call was charged the created account. charged_create_state_gas: bool, - /// The records the creation's start makes. - records: FrameStartRecords, - /// What the call paid for them: the created account's, and the signer's. `None` when the - /// transaction pays no history. + /// What the call paid for the records the creation's start makes: the created account's, and + /// the signer's nonce. `None` when the transaction pays no history. record_charges: Option<(u64, u64)>, } @@ -381,7 +346,7 @@ fn prepare( // in a frame of it, which a read of the account started. The call is the transaction's own // frame, at depth 0. if signer == ctx.block().beneficiary { - ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas, 0); + ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas); } if signer_info.nonce > 1 { refuse!(KeylessDeployError::SignerNonceTooHigh { signer_nonce: signer_info.nonce }); @@ -428,12 +393,12 @@ fn prepare( return Ok(Err(Refusal::OutOfGas)); } } - let records = FrameStartRecords { on_lane: 1, caller: signer != ctx.tx().caller() }; + let records = ctx.accounts().creation_records(signer, Some(deploy_address), tx.value); let record_charges = if ctx.prices_history() { let charged = charge_write_records_history( gas.tracker_mut(), - records.on_lane, - u64::from(records.caller), + records.on_frame().added, + u64::from(records.creator), ); if charged.is_none() { return Ok(Err(Refusal::OutOfGas)); @@ -458,7 +423,6 @@ fn prepare( init_code: tx.input.clone(), gas_limit, charged_create_state_gas, - records, record_charges, })) } diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index e121e7df4..a6f041077 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -6,13 +6,14 @@ //! //! A `keylessDeploy(bytes,uint256)` call a transaction makes is dispatched before any interceptor //! sees it ([`is_dispatched`]), and its frame is built as any call's is, but runs no code: its -//! actions are made by hand ([`run`]). On its first run it pays the fixed overhead and what the -//! `CREATE` opcode charges its frame, then starts the creation as its child — as the signer, at -//! the signer's Nick's-Method address, with `gasLimitOverride` capped to what the call has left. -//! From there the creation is an ordinary `CREATE` frame: priced, limited and journaled as one, -//! and returned into the call as one returns into the frame that started it ([`settle`]). On its -//! resume the call answers in the `IKeylessDeploy` ABI. An inspector sees both frames: the call, -//! and the creation as its child. There is no second EVM and no state to merge. +//! actions are made by hand and set on its interpreter, which returns each when the frame runs. +//! Its first ([`start`]) pays the fixed overhead and what the `CREATE` opcode charges its frame, +//! then starts the creation as its child — as the signer, at the signer's Nick's-Method address, +//! with `gasLimitOverride` capped to what the call has left. From there the creation is an +//! ordinary `CREATE` frame: priced, limited and journaled as one, and returned into the call as +//! one returns into the frame that started it ([`settle`]). The call then answers in the +//! `IKeylessDeploy` ABI ([`answer`]). An inspector sees both frames: the call, and the creation as +//! its child. There is no second EVM and no state to merge. //! //! What the native frame means for a deployment: //! @@ -22,7 +23,10 @@ //! transaction's first frame, as for any transaction to the contract, so a witness holds them //! either way; the frame touches the account, as a call touches its target, and a call that //! reverts takes the touch back. An inspector sees one call frame, started and ended as any -//! call's, with no interpreter initialized and no step in it. +//! call's, in which no interpreter is initialized and no step runs: revm's inspected run returns +//! the action set on the frame before any `step`, and hands a frame built with one to no +//! `initialize_interp`; a call a rule refuses ends before it runs, and is seen to start and end +//! and nothing else. //! - A call carrying value is refused `NoEtherTransfer()`, having paid the overhead, before revm //! builds its frame: no value moves, and nothing its start would write is counted. //! - The dispatch is by address and selector, whatever the address holds: where the state holds no @@ -73,8 +77,8 @@ //! crosses — reverts with the stop, taking back the signer's nonce with everything else. //! //! A creation an inspector revives — a tool's `create_end` that turns a failed creation into a -//! success at an address of its own, as Foundry's `expectRevert` does — settles as a frame that -//! kept nothing, and the call answers `AddressMismatch()` when that address is not the deploy +//! success at an address of its own, as Foundry's `expectRevert` does — is taken as given, as +//! revm takes it, and the call answers `AddressMismatch()` when that address is not the deploy //! address. //! //! # The error ABI @@ -108,8 +112,8 @@ mod tx; pub use error::*; pub use tx::*; -pub(crate) use dispatch::{is_dispatched, ready, run, runs, KeylessFrame}; -pub(crate) use settle::{refuses_empty_deposit, returning, settle}; +pub(crate) use dispatch::{is_dispatched, ready, start, Started}; +pub(crate) use settle::{answer, refuses_empty_deposit, returning, settle}; use alloy_primitives::{address, Address}; diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 6ee7de062..293af60a9 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -20,11 +20,13 @@ use revm::{ }; use crate::{ + hold_creator, + limit::CreatorBefore, system::keyless::{encode_error_result, IKeylessDeploy, KeylessDeployError}, - ExternalEnvTypes, MegaContext, MegaHaltReason, + ExternalEnvTypes, LimitCheck, MegaContext, MegaHaltReason, }; -use super::dispatch::{KeylessFrame, Started}; +use super::dispatch::Started; /// What a `keylessDeploy` call answers from, once its creation returned into it. #[derive(Debug)] @@ -55,9 +57,7 @@ pub(crate) fn returning( stack: &mut FrameStack>, result: &FrameResult, ) -> Option { - if !matches!(ctx.keyless_frame, Some(KeylessFrame::Deploying(_))) { - return None; - } + ctx.keyless_creation.as_ref()?; if !returns_into_the_call(stack) { return None; } @@ -99,12 +99,12 @@ fn returns_into_the_call(stack: &mut FrameStack>) -> bo /// constructor that destroyed its own account (`destroyed`) is left as it is: the account does not /// keep what it returned, and the answer reads that off the journal ([`holds_code`]). pub(crate) fn refuses_empty_deposit( - frame: &mut Option, + creation: &mut Option, deposit: &CodeDeposit<'_>, destroyed: bool, ) -> bool { - match frame { - Some(KeylessFrame::Deploying(started)) + match creation { + Some(started) if deposit.code.is_empty() && deposit.address == started.deploy_address && !destroyed => @@ -117,7 +117,7 @@ pub(crate) fn refuses_empty_deposit( } /// Settles `creation`, which revm has just merged into the `keylessDeploy` call whose gas is -/// `gas`, and keeps what the call answers from on its resume ([`answer`]). +/// `gas`, and returns what the call answers from ([`answer`]). /// /// The merge is revm's own, as for a `CREATE`'s frame: the unspent forward, the reservoir, the /// creation's state and history gas when it succeeded, and the created account's charge when it @@ -128,25 +128,30 @@ pub(crate) fn refuses_empty_deposit( /// the creation's start never created it. And a deployment from nonce 0 keeps the creation's nonce /// bump, while from nonce 1 the bump is taken back, whether the deployment succeeded or failed, /// only when it is the last nonce change the deployment made ([`take_back_bump`]), leaving the -/// nonce at 1, as the legacy engine did; its write record and that record's history go with it, -/// unless the creation succeeded and moved value out of the signer. The call is permissionless -/// and the signed transaction public, so a nonce every failure spent would let anybody make a -/// signer's address undeployable with two failing calls; and a success that spent it would answer -/// a resubmission with `SignerNonceTooHigh` rather than `ContractAlreadyExists`. When the signer's -/// own code spent a nonce in the constructor that survived it — on a default configuration, a -/// delegated signer's `CREATE` or `CREATE2`, successful or not — nothing is taken back: a later -/// bump may stand for an account, so the nonce is never moved back under one. That signer ends -/// above 1, and a resubmission is refused `SignerNonceTooHigh`. +/// nonce at 1, as the legacy engine did; that record's history goes with it, unless the creation +/// succeeded and moved value out of the signer. The call is permissionless and the signed +/// transaction public, so a nonce every failure spent would let anybody make a signer's address +/// undeployable with two failing calls; and a success that spent it would answer a resubmission +/// with `SignerNonceTooHigh` rather than `ContractAlreadyExists`. When the signer's own code spent +/// a nonce in the constructor that survived it — on a default configuration, a delegated signer's +/// `CREATE` or `CREATE2`, successful or not — nothing is taken back: a later bump may stand for an +/// account, so the nonce is never moved back under one. That signer ends above 1, and a +/// resubmission is refused `SignerNonceTooHigh`. /// -/// It runs before the call resumes, because the record it takes back may be what put the call -/// over a limit: the call is held to its limits again without it, and the stop it returns on -/// its resume, if any, is the one that stands then. +/// Then the signer's nonce record is counted on the call, as a `CREATE`'s creator's is on the +/// creator once its creation returned ([`hold_creator`]): read off the signer's account as the +/// settlement left it — `signer` is the signer as it stood before revm decided the creation — when +/// revm bumped the nonce, held to the call's budget and then to the transaction's limit. A nonce +/// set back leaves no record to count, unless the account keeps the value the creation moved. A +/// crossing is the stop the call returns on its resume, before its answer; it runs before the +/// call resumes for that reason. pub(crate) fn settle( ctx: &mut MegaContext, gas: &mut Gas, creation: Creation, -) -> Result<(), ContextError> { - let Some(KeylessFrame::Deploying(started)) = ctx.keyless_frame.take() else { + signer: Option, +) -> Result<(Returned, Option), ContextError> { + let Some(started) = ctx.keyless_creation.take() else { unreachable!("a creation returns into a keylessDeploy call that started it") }; // The creation's start is what creates an empty signer's account. revm bumps the nonce of @@ -157,23 +162,25 @@ pub(crate) fn settle( if nonce == started.signer_nonce { gas.refill_reservoir(started.signer_account_charge); } + let bumped = signer.filter(|signer| ctx.accounts().bumped(signer)); // A deployment from nonce 1 keeps no bump of its own: a failure leaves the address // deployable, a success leaves it occupied. The creation's bump is the one above the nonce // the call started from, and it is taken back only when it is the last one: a later bump the // signer's own code made may stand for an account, so the nonce is never moved back under it. if started.signer_nonce > 0 && nonce == started.signer_nonce + 1 { - take_back_bump(ctx, gas, &started, creation.result)?; + take_back_bump(ctx, gas, &started)?; } - ctx.keyless_frame = Some(KeylessFrame::Returned(Returned { started, creation })); - Ok(()) + let stop = bumped.and_then(|signer| hold_creator(ctx, gas.tracker_mut(), &signer)); + Ok((Returned { started, creation }, stop)) } /// The action of a `keylessDeploy` call resuming on `gas` once its creation `returned` into it, a -/// stop aside: `keylessDeploy`'s return — the deployed address when the creation left code at it, -/// or the zero address and the error the creation failed with, `ExecutionReverted`, -/// `ExecutionHalted`, or `EmptyCodeDeployed` for a creation that left no code, having deployed none -/// or destroyed itself. The call succeeds, and keeps what the creation's start wrote: a signer at -/// nonce 0 whose deployment failed has spent its nonce all the same. +/// stop aside, set on the call's interpreter for its run to return: `keylessDeploy`'s return — the +/// deployed address when the creation left code at it, or the zero address and the error the +/// creation failed with, `ExecutionReverted`, `ExecutionHalted`, or `EmptyCodeDeployed` for a +/// creation that left no code, having deployed none or destroyed itself. The call succeeds, and +/// keeps what the creation's start wrote: a signer at nonce 0 whose deployment failed has spent its +/// nonce all the same. /// /// `gasUsed` is what the creation spent: its regular gas and the state and history gas it kept, /// from whichever pool paid it. It is the same whether the transaction has a state-gas reservoir @@ -224,33 +231,37 @@ fn answer_of( } /// Whether the deployment left code at `address`. The code the journal holds, not the code the -/// constructor returned: a constructor that destroyed its own account (EIP-6780) returned code -/// the account does not keep. +/// constructor returned: a constructor that destroyed its own account (EIP-6780) in this +/// transaction returned code the account does not keep. A destruction an earlier transaction on +/// the same journal made, whose mark revm keeps on the account, is not this one. fn holds_code( ctx: &MegaContext, address: Address, ) -> bool { - ctx.journal_ref().state.get(&address).is_some_and(|account| { - account.info.code_hash != KECCAK_EMPTY && !account.is_selfdestructed() - }) + let code = ctx + .journal_ref() + .state + .get(&address) + .is_some_and(|account| account.info.code_hash != KECCAK_EMPTY); + code && !ctx.accounts().is_destroyed(address) } -/// Takes back the creation's nonce bump of a signer whose nonce was already 1, with its write -/// record and that record's history, so what stands is what would stand had the creation's start -/// not bumped the nonce: the signer stays at 1, however many deployments it makes. +/// Takes back the creation's nonce bump of a signer whose nonce was already 1, with that record's +/// history, so what stands is what would stand had the creation's start not bumped the nonce: the +/// signer stays at 1, however many deployments it makes. The record itself is counted afterwards, +/// off the account as this leaves it, so a nonce set back leaves none to take back. /// -/// The record goes unless the signer's account keeps another write it stands for: the value a -/// creation that succeeded moved out of it. A creation that failed took its value transfer back -/// with the rest of its writes. +/// The record follows the signer's account: it goes when the nonce set back leaves the account +/// as the transaction loaded it, and stays when the account keeps another write it stands for — +/// the value a creation that succeeded moved out of it, or into it. A creation that failed took +/// its value transfer back with the rest of its writes. fn take_back_bump( ctx: &mut MegaContext, gas: &mut Gas, started: &Started, - result: InstructionResult, ) -> Result<(), ContextError> { ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); - let moved_value = started.moves_value && result.is_ok(); - if !moved_value && ctx.additional_limit.take_back_creator_record() { + if !ctx.accounts().is_changed(started.signer) { gas.refill_history(started.signer_record_charge); } Ok(()) diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index 10276934a..cccb146f6 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -59,7 +59,7 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// what a block-environment read's cap leaves it when its frame holds more. /// /// The figure is taken before the forward: taken after it, a caller that forwards what `GAS` -/// reports would hear back one sixty-fourth of its gas. That is the one property carried over +/// reports would hear back the 2 per cent of its gas it kept. That is the one property carried over /// from the legacy engine, whose compute never counted the gas a call forwarded. The figure /// itself departs from the legacy engine's, which came from a separate compute ledger, with /// per-frame budgets of 98/100 of the caller's remaining compute under the transaction's compute @@ -69,9 +69,9 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// It is regular gas only, capped at the execution cap: the state-gas reservoir is not compute, /// and a transaction above the cap hears the cap's share at most. It is not a promise of compute /// either: state or history gas the caller later pays out of its regular gas comes out of the -/// same figure. A frame a value call started holds its stipend in its own regular gas, and -/// detention counts the stipend outside compute, so the frame hears it counted whether or not it -/// is detained. +/// same figure. A frame a value call started holds its stipend in its own regular gas, and hears +/// it with that gas while that gas binds; what it runs on the stipend is compute like the rest, so +/// once detention's limit binds, the stipend adds nothing to what the limit leaves. /// /// The method reads and takes no value. pub(crate) fn intercept( diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index c4ab0bc23..9826675aa 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -68,8 +68,8 @@ pub use mega_system_contracts::oracle::IOracle; /// A `STATICCALL` does forward: `sendHint` is a view method and writes nothing. /// /// The payload is counted toward the transaction's data size before it is decoded -/// ([`AdditionalLimit::record_hint_bytes`](crate::AdditionalLimit)), so trailing bytes an ABI -/// decoder ignores are paid for; a payload that would cross the transaction's limit is neither +/// ([`AdditionalLimit::admit_hint`](crate::AdditionalLimit)), so trailing bytes an ABI decoder +/// ignores are paid for; a payload that would cross the transaction's limit is neither /// forwarded nor counted, and the call is answered with the stop: a revert carrying /// `MegaLimitExceeded`, on the gas it was forwarded, as the frame it would have started. So the /// data size a transaction keeps holds exactly the hints that were admitted. @@ -91,7 +91,7 @@ pub(crate) fn intercept( return None; } let payload = inputs.input.bytes(&*ctx); - let check = ctx.additional_limit.record_hint_bytes(payload.len() as u64); + let check = ctx.additional_limit.admit_hint(payload.len() as u64); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); @@ -150,6 +150,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, } } @@ -175,11 +178,11 @@ mod tests { assert_eq!(result.output, stop.revert_data()); assert_eq!(result.gas.remaining(), FORWARD, "the forward is untouched"); assert!(envs.recorded_hints().is_empty(), "nothing is forwarded"); - assert_eq!(ctx.additional_limit.usage().data_size, 0, "nothing is counted"); + assert_eq!(ctx.limit_usage().data_size, 0, "nothing is counted"); let (mut ctx, envs) = recording(payload); assert!(intercept(&mut ctx, &inputs, 1).is_none(), "the bytecode runs"); assert_eq!(envs.recorded_hints().len(), 1); - assert_eq!(ctx.additional_limit.usage().data_size, payload); + assert_eq!(ctx.limit_usage().data_size, payload); } } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index f7cda377b..ce8d987b8 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -116,7 +116,7 @@ fn read_slot( /// state. Nothing is committed. /// /// It is a system call from the EIP-4788 system address on the pre-block budget -/// ([`pre_block_call_gas_limit`](crate::pre_block_call_gas_limit)): at most 30M of regular gas, +/// ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)): 30M of regular gas, /// the rest reservoir, its state priced at the minimum SALT bucket. One call applies whichever of /// the two roles is due; the block executor makes it only when [`is_apply_pending_changes_due`] /// says one is. @@ -212,12 +212,13 @@ fn system_address_named_by(code_hash: B256, current: U256) -> Option
{ #[cfg(test)] mod tests { use super::*; - use crate::{system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId}; + use crate::{ + system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId, SYSTEM_CALL_REGULAR_GAS_LIMIT, + }; use alloy_primitives::address; use revm::{ context::{BlockEnv, ContextTr, JournalTr, Transaction}, database::{InMemoryDB, State}, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, state::{AccountInfo, Bytecode}, Database, DatabaseCommit, }; @@ -376,28 +377,23 @@ mod tests { } } - /// The call runs on the block's gas limit, of which 30M is regular gas and the rest the - /// reservoir: a registry with nothing due writes nothing, and all of the reservoir is left. + /// The call runs on the pre-block budget whatever the block's gas limit, of which 30M is + /// regular gas and the rest the reservoir: a registry with nothing due writes nothing, and all + /// of the reservoir is left, in a block of 1M and in one of 250M. #[test] - fn test_transact_apply_pending_changes_uses_block_gas_limit() { - let mut db = registry_with(&[]); - let mut evm = evm(&mut db, 250_000_000); - let outcome = transact_apply_pending_changes(&mut evm).expect("the call succeeds"); - assert_eq!(evm.ctx().tx().gas_limit(), 250_000_000); - assert_eq!( - outcome.result.gas().reservoir_remaining(), - 250_000_000 - SYSTEM_CALL_REGULAR_GAS_LIMIT - ); - } - - /// A block whose gas limit is below 30M still gives the call 30M, all of it regular gas. - #[test] - fn test_transact_apply_pending_changes_respects_30m_floor() { - let mut db = registry_with(&[]); - let mut evm = evm(&mut db, 1_000_000); - let outcome = transact_apply_pending_changes(&mut evm).expect("the call succeeds"); - assert_eq!(evm.ctx().tx().gas_limit(), SYSTEM_CALL_REGULAR_GAS_LIMIT); - assert_eq!(outcome.result.gas().reservoir_remaining(), 0); + fn test_transact_apply_pending_changes_runs_on_the_pre_block_budget() { + use crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; + for block_gas_limit in [1_000_000, 250_000_000] { + let mut db = registry_with(&[]); + let mut evm = evm(&mut db, block_gas_limit); + transact_apply_pending_changes(&mut evm).expect("the call succeeds"); + assert_eq!(evm.ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT, "{block_gas_limit}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT, + "{block_gas_limit}" + ); + } } /// A read the database cannot serve during the call is the database's error, not a verdict on diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index f3f3de534..5e46a06a6 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -8,6 +8,7 @@ mod logs; mod neutral; mod opcode_gen; mod price_guard; +mod read_only_observer; mod scenario; mod witness; @@ -19,5 +20,6 @@ pub use logs::*; pub use neutral::*; pub use opcode_gen::*; pub use price_guard::*; +pub use read_only_observer::*; pub use scenario::*; pub use witness::*; diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index 2306bee31..6abeecd7f 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -58,11 +58,11 @@ use crate::{ /// otherwise keys on the spec id; EIP-7825's execution cap; the EIP-7954 code-size limits, set /// explicitly for the same reason. /// -/// On both, a system call's whole gas limit is regular gas, as revm's runner has it: the switch -/// that makes the part above 30,000,000 a state-gas reservoir, which Satin sets, is off. Under -/// Osaka it would do nothing, EIP-8037 being off. Under Amsterdam upstream revm splits no system -/// call's gas, and no state fixture makes a system call, so neither release the gate runs can -/// tell the two apart. +/// On both, a system call's whole gas limit is regular gas, as revm's runner has it: a context on +/// the neutral configuration does not make the part above 30,000,000 a state-gas reservoir, as +/// Satin's handler does. Under Osaka the split would do nothing, EIP-8037 being off. Under +/// Amsterdam upstream revm splits no system call's gas, and no state fixture makes a system call, +/// so neither release the gate runs can tell the two apart. /// /// Every other field is revm's default: chain id 1, which a caller replaces with the fixture's. pub fn neutral_cfg(fork: EthSpecId) -> Option> { @@ -77,7 +77,6 @@ pub fn neutral_cfg(fork: EthSpecId) -> Option> { cfg.enable_amsterdam_eip2780 = amsterdam; cfg.enable_amsterdam_eip7708 = amsterdam; cfg.tx_gas_limit_cap = None; - cfg.system_call_state_gas_margin_in_reservoir = false; if amsterdam { cfg.limit_contract_code_size = Some(eip7954::MAX_CODE_SIZE); cfg.limit_contract_initcode_size = Some(eip7954::MAX_INITCODE_SIZE); @@ -185,8 +184,7 @@ mod tests { assert_eq!(cfg.max_initcode_size(), eip3860::MAX_INITCODE_SIZE); assert_eq!(cfg.max_code_size(), osaka.max_code_size()); assert_eq!(cfg.max_initcode_size(), osaka.max_initcode_size()); - assert!(!cfg.system_call_state_gas_margin_in_reservoir()); - assert!(!osaka.system_call_state_gas_margin_in_reservoir()); + assert_system_call_gas_is_whole(ctx); } /// Amsterdam's configuration carries what revm's runner derives from the Amsterdam spec id, @@ -203,8 +201,13 @@ mod tests { assert_eq!(cfg.max_code_size(), amsterdam.max_code_size()); assert_eq!(cfg.max_initcode_size(), amsterdam.max_initcode_size()); assert_eq!(cfg.max_code_size(), eip7954::MAX_CODE_SIZE); - assert!(!cfg.system_call_state_gas_margin_in_reservoir()); - assert!(!amsterdam.system_call_state_gas_margin_in_reservoir()); + assert_system_call_gas_is_whole(ctx); + } + + /// A system call on `ctx` runs on its whole gas limit as regular gas, as revm's runner has it. + fn assert_system_call_gas_is_whole(mut ctx: MegaContext) { + ctx.on_new_system_call(); + assert!(!ctx.splits_system_call_gas()); } /// Neither configuration is Satin's, and both run Satin's spec. diff --git a/crates/mega-evm/src/test_utils/read_only_observer.rs b/crates/mega-evm/src/test_utils/read_only_observer.rs new file mode 100644 index 000000000..60043b477 --- /dev/null +++ b/crates/mega-evm/src/test_utils/read_only_observer.rs @@ -0,0 +1,264 @@ +//! An observer that proves, in debug builds, that the inspector it wraps writes nothing back. + +use revm::{ + context::{ContextTr, JournalTr}, + handler::FrameResult, + inspector::JournalExt, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Interpreter, + InterpreterTypes, + }, + primitives::{Address, Log, U256}, + Inspector, +}; + +/// Wraps an inspector that is meant to write nothing back, and proves it in debug builds. +/// +/// It forwards every callback to the inspector inside and adds nothing. A debug build checks +/// around every callback and panics at the one that breaks the claim: the interpreter's gas, +/// pending action, stack depth and memory size, the frame's inputs, the frame result, and the +/// journal's entries and logs must be as they were, and no frame may be answered. Writes the check +/// cannot see (a stack word replaced in place, a context field outside the journal) are not caught; +/// the check is a tripwire, not a proof. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ReadOnlyObserver(pub I); + +impl ReadOnlyObserver { + /// Declares `inspector` a read-only observer. + pub const fn new(inspector: I) -> Self { + Self(inspector) + } + + /// The inspector inside. + pub fn into_inner(self) -> I { + self.0 + } +} + +impl Inspector for ReadOnlyObserver +where + I: Inspector, + CTX: ContextTr, + INTR: InterpreterTypes, +{ + #[inline] + fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.initialize_interp(interp, context); + assert_unwritten(before, interp, context, "initialize_interp"); + } + + #[inline] + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.step(interp, context); + assert_unwritten(before, interp, context, "step"); + } + + #[inline] + fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.step_end(interp, context); + assert_unwritten(before, interp, context, "step_end"); + } + + #[inline] + fn log(&mut self, context: &mut CTX, log: Log) { + let before = journal_snapshot(context); + self.0.log(context, log); + assert_journal_unwritten(before, context, "log"); + } + + #[inline] + fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { + let before = snapshot(interp, context); + self.0.log_full(interp, context, log); + assert_unwritten(before, interp, context, "log_full"); + } + + #[inline] + fn frame_start( + &mut self, + context: &mut CTX, + frame_input: &mut FrameInput, + ) -> Option { + let before = + cfg!(debug_assertions).then(|| (frame_input.clone(), journal_snapshot(context))); + let answer = self.0.frame_start(context, frame_input); + debug_assert!(answer.is_none(), "a read-only observer answered a frame in `frame_start`"); + if let Some((input, journal)) = before { + debug_assert!(&input == frame_input, "a read-only observer rewrote a frame's inputs"); + assert_journal_unwritten(journal, context, "frame_start"); + } + answer + } + + #[inline] + fn frame_end( + &mut self, + context: &mut CTX, + frame_input: &FrameInput, + frame_result: &mut FrameResult, + ) { + let before = result_snapshot(frame_result); + let journal = journal_snapshot(context); + self.0.frame_end(context, frame_input, frame_result); + assert_result_unwritten(before, frame_result, "frame_end"); + assert_journal_unwritten(journal, context, "frame_end"); + } + + #[inline] + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); + let answer = self.0.call(context, inputs); + debug_assert!(answer.is_none(), "a read-only observer answered a call"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a read-only observer rewrote a call's inputs"); + } + assert_journal_unwritten(journal, context, "call"); + answer + } + + #[inline] + fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); + self.0.call_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a read-only observer rewrote a call result"); + } + assert_journal_unwritten(journal, context, "call_end"); + } + + #[inline] + fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); + let answer = self.0.create(context, inputs); + debug_assert!(answer.is_none(), "a read-only observer answered a creation"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a read-only observer rewrote a creation's inputs"); + } + assert_journal_unwritten(journal, context, "create"); + answer + } + + #[inline] + fn create_end( + &mut self, + context: &mut CTX, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); + self.0.create_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a read-only observer rewrote a creation result"); + } + assert_journal_unwritten(journal, context, "create_end"); + } + + #[inline] + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + self.0.selfdestruct(contract, target, value); + } +} + +/// The journal's entry and log counts, for the debug-build proof. `None` in release builds. +type JournalSnapshot = Option<(usize, usize)>; + +#[inline] +fn journal_snapshot>(context: &CTX) -> JournalSnapshot { + cfg!(debug_assertions) + .then(|| (context.journal_ref().journal().len(), context.journal_ref().logs().len())) +} + +#[inline] +fn assert_journal_unwritten>( + before: JournalSnapshot, + context: &CTX, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + journal_snapshot(context).expect("debug build"), + "a read-only observer wrote to the journal in `{callback}`" + ); + } +} + +/// An interpreter's and the journal's state, for the debug-build proof. +type Snapshot = (GasSnapshot, JournalSnapshot); + +#[inline] +fn snapshot>( + interp: &Interpreter, + context: &CTX, +) -> Snapshot { + (gas_snapshot(interp), journal_snapshot(context)) +} + +#[inline] +fn assert_unwritten>( + (gas, journal): Snapshot, + interp: &Interpreter, + context: &CTX, + callback: &str, +) { + assert_gas_unwritten(gas, interp, callback); + assert_journal_unwritten(journal, context, callback); +} + +/// An interpreter's gas, pending action, stack depth and memory size, for the debug-build proof. +/// `None` in release builds. +type GasSnapshot = Option<(revm::interpreter::Gas, bool, usize, usize)>; + +#[inline] +fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { + use revm::interpreter::interpreter_types::{LoopControl, MemoryTr, StackTr}; + cfg!(debug_assertions) + .then(|| (interp.gas, interp.bytecode.is_end(), interp.stack.len(), interp.memory.size())) +} + +#[inline] +fn assert_gas_unwritten( + before: GasSnapshot, + interp: &Interpreter, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + gas_snapshot(interp).expect("debug build"), + "a read-only observer wrote to the interpreter in `{callback}`" + ); + } +} + +/// A frame result's classification, gas and output, and a creation's address, for the +/// debug-build proof. +type ResultSnapshot = Option<(revm::interpreter::InterpreterResult, Option
)>; + +#[inline] +fn result_snapshot(result: &FrameResult) -> ResultSnapshot { + cfg!(debug_assertions).then(|| { + let address = match result { + FrameResult::Call(_) => None, + FrameResult::Create(outcome) => outcome.address, + }; + (result.interpreter_result().clone(), address) + }) +} + +#[inline] +fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callback: &str) { + if let Some(before) = before { + debug_assert!( + before == result_snapshot(result).expect("debug build"), + "a read-only observer rewrote a frame result in `{callback}`" + ); + } +} diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 9c6557888..3ccd8f89d 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -193,11 +193,11 @@ fn test_a_block_reports_the_bytes_its_history_gas_does_not_cover() { // Each transaction: its body, the transfer's two records and the receiver's event. let per_tx = mega_evm::TX_BODY_SIZE + 2 * mega_evm::WRITE_RECORD_SIZE + - mega_evm::STORAGE_CALL_STIPEND_BYTES; + mega_evm::HISTORY_ALLOWANCE_BYTES; assert_eq!(counters.history_bytes, 2 * per_tx); assert_eq!( counters.history_bytes * mega_evm::constants::COST_PER_HISTORY_BYTE - counters.history, - 2 * mega_evm::storage_call_stipend(), + 2 * mega_evm::history_allowance_gas(), "the allowances paid for both events, and no gas ledger has them", ); @@ -313,3 +313,52 @@ fn test_an_out_of_gas_before_the_first_frame_bills_the_whole_gas_limit_to_the_bl assert_eq!(recipients_after - recipients_before, paid, "the fee recipients are credited it"); assert_eq!(balance(&mut state, FRESH), U256::ZERO, "the recipient was not created"); } + +/// The pre-block calls are the protocol's own work, and no transaction of the block: what they +/// write is counted towards none of the block's budgets. The EIP-2935 call stores the parent's +/// hash and the EIP-4788 call the block's timestamp and its beacon root, each in a fresh slot, a +/// write record and a unit of state growth were a transaction to make it, and the block's usage +/// stays zero. +#[test] +fn test_the_pre_block_calls_count_towards_no_block_budget() { + use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, + }; + use alloy_primitives::B256; + use revm::Database as _; + + // The ring buffers both contracts store in. + const BUFFER: u64 = 8_191; + let (parent, root) = (B256::repeat_byte(0x11), B256::repeat_byte(0x22)); + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); + let mut state = State::builder().with_database(db).build(); + let slots = [ + (HISTORY_STORAGE_ADDRESS, U256::from((common::BLOCK_NUMBER - 1) % BUFFER), parent.into()), + ( + BEACON_ROOTS_ADDRESS, + U256::from(common::BLOCK_TIMESTAMP % BUFFER), + U256::from(common::BLOCK_TIMESTAMP), + ), + (BEACON_ROOTS_ADDRESS, U256::from(common::BLOCK_TIMESTAMP % BUFFER + BUFFER), root.into()), + ]; + for (address, slot, _) in slots { + assert_eq!(state.storage(address, slot).unwrap(), U256::ZERO, "a fresh slot"); + } + let ctx = mega_evm::MegaBlockExecutionCtx::new( + parent, + Some(root), + Bytes::new(), + mega_evm::BlockLimits::no_limits(), + ); + let mut executor = executor(&mut state, ctx); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(executor.limiter().usage, mega_evm::LimitUsage::default()); + assert_eq!(*executor.gas(), BlockGasCounters::default()); + drop(executor); + for (address, slot, value) in slots { + assert_eq!(state.storage(address, slot).unwrap(), value, "the pre-block call stored it"); + } +} diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 6a72eb556..89a9cd9c3 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -5,8 +5,8 @@ //! make leaves that state alone. A call that does not succeed refuses the block, and its state is //! never committed: neither a commit hook nor the database sees it. //! -//! Each call runs on the pre-block budget: the block's gas limit, and never less than 30M, of -//! which at most 30M is regular gas and the rest the call's state-gas reservoir. +//! Each call runs on the pre-block budget, `PRE_BLOCK_CALL_GAS_LIMIT`, whatever the block's gas +//! limit: 30M of regular gas and the rest the call's state-gas reservoir. use alloy_eips::{ eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, @@ -20,16 +20,14 @@ use alloy_hardforks::{EthereumHardfork, ForkCondition}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{Address, Bytes, B256, U256}; use mega_evm::{ - constants::SLOT_STATE_GAS, - pre_block_call_gas_limit, + constants::{PRE_BLOCK_CALL_GAS_LIMIT, SLOT_STATE_GAS}, test_utils::{BytecodeBuilder, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, + MegaSpecId, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; use revm::{ - bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, + bytecode::opcode::{CALLDATALOAD, GAS, MLOAD, SSTORE}, database::State, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, Database, }; @@ -445,49 +443,72 @@ fn test_a_block_is_refused_when_its_beacon_root_call_halts() { assert_eq!(calls, [HISTORY_STORAGE_ADDRESS]); } -/// The pre-block budget follows the block's gas limit, so a pre-block call that costs more than -/// 30M in all still succeeds in a block that can hold it: 400 fresh slots are 39M of state gas, -/// which the reservoir above 30M pays. In a block of 30M the call has no reservoir, the state -/// gas spills onto the 30M of regular gas, and the call runs out of it. +/// Code that writes `slots` fresh storage slots, then stores the regular gas it has left in the +/// slot after them. +fn fresh_writes_then_gas(slots: u16) -> Bytes { + (0..slots) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .append(GAS) + .push_number(slots) + .append(SSTORE) + .stop() + .build() +} + +/// The pre-block budget is one constant, whatever the block's gas limit: in a block of 1M, of 30M +/// and of 250M each pre-block call runs on [`PRE_BLOCK_CALL_GAS_LIMIT`], 30M of regular gas and +/// a reservoir of sixteen fresh slots. Sixteen fresh writes run the same in each, the regular gas +/// left after them included: the reservoir pays them in a small block too. A call that costs more +/// than the budget in all — 400 fresh slots are 39M of state gas — runs out of gas in each and +/// refuses the block, in a 250M block too. #[test] -fn test_the_block_aware_budget_accepts_a_pre_block_call_above_30m() { - const SLOTS: u16 = 400; - assert_eq!(pre_block_call_gas_limit(250_000_000), 250_000_000); - assert_eq!(pre_block_call_gas_limit(1_000_000), SYSTEM_CALL_REGULAR_GAS_LIMIT); - // The slot count is sized at Satin's own price; other byte prices move the 30M boundary. - if !mega_evm::active_satin_prices().is_constants() { - return; - } - assert!(u64::from(SLOTS) * SLOT_STATE_GAS > SYSTEM_CALL_REGULAR_GAS_LIMIT); +fn test_the_pre_block_budget_does_not_follow_the_block() { + use revm::context::{ContextTr, Transaction}; - let database = || { + const HELD: u16 = 16; + const SLOTS: u16 = 400; + let database = |code: Bytes| { let mut db = common::database(); - db.set_account_code(HISTORY_STORAGE_ADDRESS, fresh_writes(SLOTS)); - db.set_account_code(BEACON_ROOTS_ADDRESS, fresh_writes(SLOTS)); + db.set_account_code(HISTORY_STORAGE_ADDRESS, code.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, code); db }; - - let mut state = State::builder().with_database(database()).build(); - let committed = CommittedStates::install(&mut state); - let mut executor = executor_with_env(&mut state, ctx(), env_with_gas_limit(250_000_000)); - executor.apply_pre_execution_changes().expect("a 250M block holds both calls"); - let states = committed.states(); - assert_eq!(states[0][&HISTORY_STORAGE_ADDRESS].storage.len(), usize::from(SLOTS)); - assert_eq!(states[1][&BEACON_ROOTS_ADDRESS].storage.len(), usize::from(SLOTS)); - drop(executor); - - let (calls, started) = start_block(database(), common::evm_env()); - assert_eq!(common::BLOCK_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT); - let err = started.expect_err("a 30M block gives the call no reservoir"); - assert!( - matches!( - &err, - BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) - if message.contains("OutOfGas") - ), - "{err}" - ); - assert!(calls.is_empty(), "{calls:?}"); + let gas_left = [1_000_000, 30_000_000, 250_000_000].map(|block_gas_limit| { + let mut state = + State::builder().with_database(database(fresh_writes_then_gas(HELD))).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = + executor_with_env(&mut state, ctx(), env_with_gas_limit(block_gas_limit)); + executor.apply_pre_execution_changes().expect("the budget holds sixteen fresh writes"); + assert_eq!(executor.evm().ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT); + let states = committed.states(); + let stored = &states[0][&HISTORY_STORAGE_ADDRESS].storage; + assert_eq!(stored.len(), usize::from(HELD) + 1, "in a block of {block_gas_limit}"); + stored[&U256::from(HELD)].present_value() + }); + assert_eq!(gas_left[0], gas_left[2], "a 1M block runs the call as a 250M block does"); + assert_eq!(gas_left[1], gas_left[2], "and so does a 30M block"); + + // The slot count is sized at Satin's own price; other byte prices move the budget's edge. + if !mega_evm::active_satin_prices().is_constants() { + return; + } + assert!(u64::from(SLOTS) * SLOT_STATE_GAS > PRE_BLOCK_CALL_GAS_LIMIT); + for block_gas_limit in [30_000_000, 250_000_000] { + let (calls, started) = + start_block(database(fresh_writes(SLOTS)), env_with_gas_limit(block_gas_limit)); + let err = started.expect_err("no block's budget holds 400 fresh slots"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { + message + }) if message.contains("OutOfGas") + ), + "{err}" + ); + assert!(calls.is_empty(), "{calls:?}"); + } } /// Starts a block at [`BLOCK_NUMBER`] over `db`. @@ -531,28 +552,18 @@ fn test_a_database_error_in_the_beacon_root_call_is_internal() { } /// What the block commits for a pre-block call is the state op-revm's own system call produces -/// for it: the same call from the same state, on the same configuration — the split -/// switched on — and the same pre-block budget. The contract stores the regular gas it had, which -/// is 30M of the 250M budget, and the word it was called with. +/// for it: the same call from the same state, on the same configuration, with the same split of +/// its gas ([`op_reference`](crate::op_reference)) and the same pre-block budget. The contract +/// stores the regular gas it had, which is 30M of the budget, and the word it was called with. #[test] fn test_a_pre_block_call_commits_the_state_op_revm_produces() { - use op_revm::{handler::OpHandler, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; + use crate::op_reference::{self, OpContext}; + use op_revm::{OpEvm, OpSpecId}; use revm::{ bytecode::opcode::{GAS, PUSH0, PUSH1, STOP}, - context::{result::EVMError, BlockEnv, CfgEnv, Context, ContextSetters, ContextTr, TxEnv}, - handler::{EthFrame, ExecuteEvm, Handler, SystemCallTx}, + context::ContextTr, inspector::NoOpInspector, - interpreter::interpreter::EthInterpreter, - Journal, }; - type OpContext = Context< - BlockEnv, - OpTransaction, - CfgEnv, - MemoryDatabase, - Journal, - L1BlockInfo, - >; let code = BytecodeBuilder::default() .append_many([GAS, PUSH0, SSTORE]) @@ -569,24 +580,22 @@ fn test_a_pre_block_call_commits_the_state_op_revm_produces() { let delivered = committed.states().into_iter().next().expect("a first step"); assert!(delivered.contains_key(&HISTORY_STORAGE_ADDRESS), "the block hashes call is first"); let (cfg, block) = (executor.evm().ctx().cfg().clone(), executor.evm().ctx().block().clone()); - assert!(cfg.system_call_state_gas_margin_in_reservoir); drop(executor); let mut op = OpEvm::new( OpContext::new(db, OpSpecId::KARST).with_cfg(cfg).with_block(block), NoOpInspector, ); - let mut tx = OpTransaction::::new_system_tx_with_caller( + let outcome = op_reference::system_call( + &mut op, mega_evm::SYSTEM_ADDRESS, HISTORY_STORAGE_ADDRESS, PARENT_HASH.0.into(), - ); - tx.base.gas_limit = pre_block_call_gas_limit(250_000_000); - op.0.ctx.set_tx(tx); - let result: Result<_, EVMError> = - OpHandler::<_, _, EthFrame>::new().run_system_call(&mut op); - assert!(result.expect("op-revm runs the call").is_success()); - let expected = op.finalize(); + PRE_BLOCK_CALL_GAS_LIMIT, + ) + .expect("op-revm runs the call"); + assert!(outcome.result.is_success()); + let expected = outcome.result_and_state.state; assert_eq!(delivered, expected, "the block commits op-revm's state"); let stored = &delivered[&HISTORY_STORAGE_ADDRESS].storage; diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index 0a2aa1ddc..d09d03ecf 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -15,7 +15,7 @@ use alloy_primitives::U256; use alloy_sol_types::SolError; use mega_evm::{ test_utils::{BytecodeBuilder, GasInspector}, - DeclaredObserver, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory, MegaLimitExceeded, MegaSpecId, ProtocolLimits, }; use revm::{context::result::ExecutionResult, database::State}; @@ -56,9 +56,9 @@ fn test_trait_path_applies_the_specs_runtime_limits() { assert_eq!(executor.protocol_limits(), &limits()); } -/// The two routes to an executor install the same limits, so neither is a way around them. +/// The routes to an executor install the same limits, so neither is a way around them. #[test] -fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { +fn test_inspector_and_plain_paths_apply_same_runtime_limits() { let trait_path = { let mut state = common::state(); let factory = common::factory(); @@ -73,12 +73,12 @@ fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { let inspector_path = { let mut state = common::state(); let factory = common::factory(); - let executor = factory.create_executor_with_trusted_inspector( + let evm = factory.evm_factory().create_evm_with_inspector( &mut state, common::evm_env(), - common::unlimited_ctx(), - DeclaredObserver::new(GasInspector::new()), + GasInspector::new(), ); + let executor = factory.create_executor(evm, common::unlimited_ctx()); *executor.evm().tx_runtime_limits() }; @@ -151,16 +151,20 @@ fn test_direct_construction_stops_a_transaction_over_the_blocks_data_size_limit( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: DATA_SIZE_LIMIT, - used: mega_evm::TX_BODY_SIZE + 2 * 40, - frame_local: false, - }) + limit: DATA_SIZE_LIMIT - mega_evm::TX_BODY_SIZE, + used: 2 * 40, + frame_local: true, + }), + "the transaction's own frame crosses its budget, what the body leaves of the limit" ); match &outcome.result { ExecutionResult::Revert { output, .. } => assert_eq!( output.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: DATA_SIZE_LIMIT } - .abi_encode(), + MegaLimitExceeded { + kind: LimitKind::DataSize.as_u8(), + limit: DATA_SIZE_LIMIT - mega_evm::TX_BODY_SIZE, + } + .abi_encode(), "the stop's revert data" ), other => panic!("expected a revert-class stop, got {other:?}"), diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 82a3430ca..f34dd1331 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -1,5 +1,5 @@ -//! The admission gate: which inspectors reach block execution, and what a declared observer sees -//! of a block's phases. +//! Inspectors in block execution: any inspector reaches a block, and what an observer sees of its +//! phases. use alloy_consensus::transaction::Recovered; use alloy_eips::{ @@ -8,21 +8,21 @@ use alloy_eips::{ }; use alloy_evm::{ block::{BlockExecutor, BlockExecutorFactory}, - Evm, EvmFactory, FromRecoveredTx, + EvmFactory, FromRecoveredTx, }; use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ - test_utils::{BytecodeBuilder, CommittedStates, GasInspector, MemoryDatabase}, - transaction_body_bytes, BlockLimits, DeclaredObserver, LimitUsage, MegaBlockExecutionCtx, - MegaBlockExecutionError, MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, - MegaTxEnvelope, + test_utils::{ + BytecodeBuilder, CommittedStates, GasInspector, MemoryDatabase, ReadOnlyObserver, + }, + transaction_body_bytes, BlockLimits, LimitUsage, MegaBlockExecutionCtx, MegaContext, + MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, MegaTxEnvelope, }; use revm::{ bytecode::opcode::{ADD, POP, PUSH0, SLOAD, SSTORE}, context::{ContextTr, JournalTr}, database::State, handler::FrameResult, - inspector::NoOpInspector, interpreter::{ CallInputs, CallOutcome, FrameInput, Gas, InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, @@ -33,175 +33,30 @@ use std::cell::Cell; use crate::common::{self, empty_call_gas, system_tx, user_tx}; -/// A declared observer reaches a block: its type says it writes nothing back, so what the block -/// executes is what the chain executes. +/// An inspector reaches a block: the engine refuses none, and a node decides which inspectors run +/// on block production. #[test] -fn test_a_declared_observer_reaches_block_execution() { +fn test_an_inspector_reaches_block_execution() { let mut state = common::state(); let factory = common::factory(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut state, - common::evm_env(), + let mut executor = factory.create_executor( + MegaEvmFactory::new().create_evm_with_inspector( + &mut state, + common::evm_env(), + GasInspector::new(), + ), common::unlimited_ctx(), - DeclaredObserver::new(GasInspector::new()), ); assert!(executor.evm().is_inspecting(), "the inspector runs"); - assert!(!executor.evm().has_rewriting_inspector(), "and is admitted"); - executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + executor.apply_pre_execution_changes().expect("the pre-block calls run"); executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 1); } -/// An inspector that arrived without the declaration does not: block execution refuses it before -/// the block's first call. The refusal is an internal error, not a verdict on the block: the -/// inspector is the node's own choice and says nothing about the block, so a validator that runs -/// one must not mark a valid block invalid. -#[test] -fn test_a_rewriting_inspector_cannot_reach_block_execution() { - let mut state = common::state(); - let factory = common::factory(); - let evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - assert!(evm.has_rewriting_inspector()); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - let err = executor - .apply_pre_execution_changes() - .expect_err("an undeclared inspector has no route to a block"); - assert!( - format!("{err}").contains("does not admit an inspector that may rewrite execution"), - "{err}" - ); - assert!(err.as_validation().is_none(), "not a verdict on the block: {err:?}"); - assert_eq!( - err.as_internal().and_then(|error| error.downcast_other::()), - Some(&MegaBlockExecutionError::RewritingInspector), - "an internal error of the node: {err:?}" - ); -} - -/// An EVM with no inspector at all is admitted, which is the ordinary case. -#[test] -fn test_a_block_without_an_inspector_is_admitted() { - let mut state = common::state(); - let factory = common::factory(); - let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - assert!(!executor.evm().is_inspecting()); - executor.apply_pre_execution_changes().expect("nothing to refuse"); -} - -/// The gate keys on what runs, not on what is held: an inspector that is disabled does not -/// rewrite anything, and the block is admitted. -#[test] -fn test_a_disabled_inspector_is_admitted() { - let mut state = common::state(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(NoOpInspector); - evm.set_inspector_enabled(false); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); -} - -/// The gate is checked at every entry point, not once: an inspector enabled after the block was -/// set up is refused by the transaction that would run under it, by the checked commit and by the -/// end of the block. -#[test] -fn test_enabling_a_rewriting_inspector_after_the_block_started_is_refused() { - let mut state = common::state(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - evm.set_inspector_enabled(false); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); - - // The one transaction that ran before the inspector was enabled is admitted. - let outcome = executor - .execute_transaction_without_commit(&user_tx(0, empty_call_gas())) - .expect("the block is still clean"); - - executor.evm_mut().set_inspector_enabled(true); - - assert!( - is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), - "no transaction runs" - ); - assert!(is_refused(executor.commit_transaction_outcome(outcome)), "nothing commits"); - assert!(executor.receipts().is_empty(), "the block packed nothing"); - assert!(is_refused(executor.finish_with_counters()), "and the block does not finish"); -} - -/// alloy-evm's `commit_transaction` cannot fail and checks nothing: it commits the outcome the -/// last execution produced, which passed the gate before it ran, so an inspector enabled since -/// cannot reach it. The next execution is the one the gate refuses. -#[test] -fn test_the_unchecked_commit_commits_what_ran_under_the_gate() { - let mut state = common::state(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - evm.set_inspector_enabled(false); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); - let outcome = executor - .execute_transaction_without_commit(&user_tx(0, empty_call_gas())) - .expect("the block is still clean"); - - executor.evm_mut().set_inspector_enabled(true); - - executor.commit_transaction(outcome); - assert_eq!(executor.receipts().len(), 1, "the outcome that ran under the gate is committed"); - assert!( - is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), - "nothing runs after" - ); - assert_eq!(executor.receipts().len(), 1); -} - -/// The gate holds for a caller that never runs the block's pre-execution changes: the check is on -/// the path that runs code, not only on the block's setup. -#[test] -fn test_a_rewriting_inspector_is_refused_without_the_pre_execution_changes() { - let mut state = common::state(); - let factory = common::factory(); - let evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - assert!( - is_refused(executor.execute_transaction_without_commit(&user_tx(0, empty_call_gas()))), - "skipping the setup is not a way past the gate" - ); - assert!(is_refused(executor.finish_with_counters()), "and neither is finishing the block"); -} - -/// Whether block execution refused the call because of the inspector. -fn is_refused(result: Result) -> bool { - match result { - Ok(_) => false, - Err(err) => format!("{err}").contains("does not admit an inspector that may rewrite"), - } -} - /// Counts the frames an inspector sees start and the instructions it sees run. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] struct Seen { @@ -243,23 +98,25 @@ fn recording_ctx() -> MegaBlockExecutionCtx { ) } -/// A declared observer sees each phase of a block as the inspector contract says: nothing of the +/// An observer sees each phase of a block as the inspector contract says: nothing of the /// pre-block calls, which run code of their own, the frames of a system transaction and of a user /// one, and nothing of the block's end, after which the EVM hands the inspector back with what it /// saw. #[test] -fn test_a_declared_observer_sees_the_transactions_of_a_block_and_nothing_else() { +fn test_an_observer_sees_the_transactions_of_a_block_and_nothing_else() { let mut state = state_with_code(); let committed = CommittedStates::install(&mut state); let factory = common::factory(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut state, - common::evm_env(), + let mut executor = factory.create_executor( + MegaEvmFactory::new().create_evm_with_inspector( + &mut state, + common::evm_env(), + ReadOnlyObserver::new(Seen::default()), + ), recording_ctx(), - DeclaredObserver::new(Seen::default()), ); - executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + executor.apply_pre_execution_changes().expect("the pre-block calls run"); let states = committed.states(); assert_eq!( common::eip_calls(&states), @@ -292,25 +149,7 @@ fn test_a_declared_observer_sees_the_transactions_of_a_block_and_nothing_else() assert_eq!(evm.inspector().0, after_user, "the block's end ran no code"); } -/// A rewriting inspector is refused at a system transaction as at a user one: the gate is the -/// entry point's, and the system transaction does not run. -#[test] -fn test_a_rewriting_inspector_is_refused_at_a_system_transaction() { - let mut state = state_with_code(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(Seen::default()); - evm.set_inspector_enabled(false); - let mut executor = factory.create_executor(evm, recording_ctx()); - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); - - executor.evm_mut().set_inspector_enabled(true); - assert!(is_refused(executor.run_transaction(&system_tx())), "the system transaction"); - assert_eq!(*executor.evm().inspector(), Seen::default(), "ran nothing"); -} - -/// An inspector works with the block executor: declared an observer, it reaches block execution and +/// An inspector works with the block executor: it /// sees the transaction's instructions — `CONTRACT` loads a slot, adds one and stores it — each /// taking gas or none, and the block finishes with the transaction's receipt. #[test] @@ -326,11 +165,13 @@ fn test_inspector_works_with_block_executor() { db.set_account_code(common::CONTRACT, increment); let mut state = State::builder().with_database(db).build(); let factory = common::factory(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut state, - common::evm_env(), + let mut executor = factory.create_executor( + MegaEvmFactory::new().create_evm_with_inspector( + &mut state, + common::evm_env(), + ReadOnlyObserver::new(GasInspector::new()), + ), common::unlimited_ctx(), - DeclaredObserver::new(GasInspector::new()), ); executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); @@ -396,10 +237,9 @@ where } /// An inspector that answers the calls below the transaction's own frame rewrites what execution -/// produces, so block execution refuses it before the transaction runs. On the EVM, the route a -/// tool takes, its answer stands in for the frame: an empty lane keeps the lanes aligned with the -/// frames, the answered call ends as every call does, and the transaction settles as one whose -/// nested call never ran. +/// produces. Block execution does not refuse it, and on the EVM alike its answer stands in for the +/// frame: it settles with the share and the start charge the frame was given, the answered call +/// ends as every call does, and the transaction settles as one whose nested call never ran. #[test] fn test_inspector_early_return_with_additional_limits() { let caller = BytecodeBuilder::default().call(CONTRACT_B, U256::ZERO).append(POP).stop().build(); @@ -417,8 +257,9 @@ fn test_inspector_early_return_with_additional_limits() { .with_inspector(SkipNestedCallInspector::default()); let factory = common::factory(); let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - assert!(is_refused(executor.execute_transaction(&tx)), "no route to a block"); - assert_eq!(executor.evm().inspector().calls_intercepted.get(), 0, "nothing ran"); + let in_block = executor.run_transaction(&tx).expect("block execution admits the inspector"); + assert!(in_block.inner.result.is_success(), "{:?}", in_block.inner.result); + assert_eq!(executor.evm().inspector().calls_intercepted.get(), 1, "the nested call answered"); let mut state = database(); let mut inspector = SkipNestedCallInspector::default(); @@ -427,6 +268,7 @@ fn test_inspector_early_return_with_additional_limits() { assert_eq!(inspector.calls_intercepted.get(), 1, "the nested call was answered"); assert_eq!(inspector.call_ends.get(), 2, "and both calls ended"); let body = transaction_body_bytes(&tx); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.gas.state, 0); + assert_eq!(in_block.inner.usage, outcome.usage, "a block and a tool settle it alike"); } diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index c29782cec..d3b942e2a 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -122,28 +122,127 @@ fn state_with_incrementing_contract( revm::database::State::builder().with_database(db).build() } -/// The block's KV count is the write records its transactions kept, summed, and no limit refuses a -/// transaction on it: three transactions that keep fifty records each are all packed. -#[test] -fn test_the_block_reports_its_kv_count_and_refuses_nothing_on_it() { - let mut state = state_with_incrementing_contract(50); - // Room in the block's gas for every transaction whatever fifty slots cost. +/// A contract that writes the fresh slots `from..from + count`, for a transaction that keeps that +/// many new slots and records. +fn fresh_writer(from: u64, count: u64) -> Bytes { + (from..from + count) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .stop() + .build() +} + +/// A second contract, which a deposit calls. +const WRITER: Address = address!("0x1000000000000000000000000000000000000009"); + +/// A block over `state` with room in its gas for every transaction, whatever the slots cost, +/// packed under `policy`. +fn counting_executor( + state: &mut revm::database::State, + policy: BlockLimits, +) -> common::TestExecutor<'_> { let mut env = common::evm_env(); env.block_env.gas_limit = 10_000_000_000; + common::executor_with_env(state, common::block_ctx(policy), env) +} + +/// The block's KV count is the write records its transactions kept, summed, and its KV-update +/// budget packs the transaction that reaches it and refuses the next one before it runs: under a +/// builder's cap of 100, two transactions that keep fifty records each are packed and a third is +/// refused. A deposit is not refused, and counts. +#[test] +fn test_the_block_kv_budget_packs_the_transaction_that_reaches_it() { + let mut state = state_with_incrementing_contract(50); + state.database.set_account_code(WRITER, fresh_writer(1, 3)); let mut executor = - common::executor_with_env(&mut state, common::block_ctx(BlockLimits::no_limits()), env); + counting_executor(&mut state, BlockLimits::no_limits().with_block_kv_update_limit(100)); executor.apply_pre_execution_changes().expect("the block starts"); - for nonce in 0..3 { + for nonce in 0..2 { executor .execute_transaction(&user_tx(nonce, incrementing_gas(50))) .unwrap_or_else(|err| panic!("transaction {nonce} is packed: {err}")); } - assert_eq!(executor.limiter().usage.write_records, 150); + assert_eq!(executor.limiter().usage.write_records, 100, "the budget is reached"); + let err = executor + .execute_transaction(&user_tx(2, incrementing_gas(50))) + .expect_err("the block has no KV updates left"); + assert!(format!("{err}").contains("Block KV update limit reached"), "{err}"); + + let deposit = common::deposit_tx_to(WRITER, Bytes::new(), incrementing_gas(3)); + executor.execute_transaction(&deposit).expect("no packing budget refuses a deposit"); + assert_eq!(executor.limiter().usage.write_records, 103, "and it counts"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 3); - assert_eq!(result.usage.write_records, 150, "the block reports its KV count"); + assert_eq!(result.usage.write_records, 103, "the block reports its KV count"); +} + +/// The block's state growth is the new accounts and slots its transactions kept, and its +/// protocol budget is 1,000: a transaction that keeps 1,000 fresh slots reaches it and is packed, +/// the next ordinary transaction is refused before it runs, and a deposit after it is not, counts +/// its new slots, and leaves the block as full for the ordinary transactions that follow. The +/// block's gas limit, ten billion here, does not stand in for the budget. +#[test] +fn test_the_block_state_growth_budget_is_the_protocols_1000() { + assert_eq!(mega_evm::constants::BLOCK_STATE_GROWTH_LIMIT, 1_000); + let mut state = state_with_incrementing_contract(1_000); + state.database.set_account_code(WRITER, fresh_writer(1, 3)); + let mut executor = counting_executor(&mut state, BlockLimits::no_limits()); + executor.apply_pre_execution_changes().expect("the block starts"); + + // Each increment's regular gas, its cold load and its write, on top of what the helper gives. + let gas = incrementing_gas(1_000) + 1_000 * 25_000; + let outcome = executor + .run_transaction(&user_tx(0, gas)) + .expect("the transaction that reaches the budget is packed"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + executor.commit_transaction_outcome(outcome).expect("and committed"); + assert_eq!(executor.limiter().usage.state_growth, 1_000); + let ordinary = || user_tx(1, incrementing_gas(1)); + let err = executor.execute_transaction(&ordinary()).expect_err("the budget is reached"); + assert!(format!("{err}").contains("Block state growth limit reached"), "{err}"); + + let deposit = common::deposit_tx_to(WRITER, Bytes::new(), incrementing_gas(3)); + executor.execute_transaction(&deposit).expect("no packing budget refuses a deposit"); + assert_eq!(executor.limiter().usage.state_growth, 1_003, "the deposit's three new slots"); + let err = executor.execute_transaction(&ordinary()).expect_err("the block is still full"); + assert!(format!("{err}").contains("Block state growth limit reached"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); + assert_eq!(result.usage.state_growth, 1_003, "the block reports its state growth"); +} + +/// Where more than one packing budget is reached, the refusal names the first of data size, KV +/// updates and state growth; the transaction is refused whichever it names. +#[test] +fn test_a_block_full_on_several_budgets_names_them_in_order() { + let cases = [ + ( + BlockLimits::no_limits() + .with_block_txs_data_limit(1) + .with_block_kv_update_limit(1) + .with_block_state_growth_limit(1), + "Block transactions data limit reached", + ), + ( + BlockLimits::no_limits().with_block_kv_update_limit(1).with_block_state_growth_limit(1), + "Block KV update limit reached", + ), + (BlockLimits::no_limits().with_block_state_growth_limit(1), "Block state growth limit"), + ]; + for (policy, named) in cases { + let mut state = state_with_incrementing_contract(1); + let mut executor = counting_executor(&mut state, policy); + executor.apply_pre_execution_changes().expect("the block starts"); + executor + .execute_transaction(&user_tx(0, incrementing_gas(1))) + .expect("the first transaction reaches every budget the case sets"); + let err = executor + .execute_transaction(&user_tx(1, incrementing_gas(1))) + .expect_err("the block is full"); + assert!(format!("{err}").contains(named), "{named}: {err}"); + } } /// A transaction refused before it runs changes nothing: no receipt, and no state. @@ -597,3 +696,158 @@ fn test_commit_time_da_footprint_check_parallel_simulation() { assert_eq!(result.receipts().len(), 1, "only the transaction that fit was packed"); assert!(result.blob_gas_used <= budget, "the block stays within its footprint budget"); } + +/// A database error, fatal as a storage failure or not as a read an EIP-7928 block access list +/// does not cover. +#[derive(Debug)] +struct AuthorityReadError { + fatal: bool, +} + +impl core::fmt::Display for AuthorityReadError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "the authority's account cannot be read (fatal: {})", self.fatal) + } +} + +impl core::error::Error for AuthorityReadError {} + +impl revm::context::DBErrorMarker for AuthorityReadError { + fn is_fatal(&self) -> bool { + self.fatal + } +} + +/// A database that refuses to read one account, if it names one, with an error that is fatal or +/// not. +#[derive(Debug)] +struct RefusesAnAccount { + db: mega_evm::test_utils::MemoryDatabase, + refused: Option
, + fatal: bool, +} + +impl revm::Database for RefusesAnAccount { + type Error = AuthorityReadError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + if self.refused == Some(address) { + return Err(AuthorityReadError { fatal: self.fatal }); + } + Ok(self.db.basic(address).expect("the memory database serves")) + } + + fn code_by_hash( + &mut self, + code_hash: alloy_primitives::B256, + ) -> Result { + Ok(self.db.code_by_hash(code_hash).expect("the memory database serves")) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + Ok(self.db.storage(address, index).expect("the memory database serves")) + } + + fn block_hash(&mut self, number: u64) -> Result { + Ok(self.db.block_hash(number).expect("the memory database serves")) + } +} + +/// An authorization list is simulated before the first frame when it may cross the transaction's +/// KV or state-growth limit, and a database error while it reads an authority gives the +/// transaction no outcome: the block executor reports it as an internal error when the database +/// declares it fatal, and refuses the block for any other, including when an earlier prefix +/// would already have crossed. Three new authorities under a state-growth limit of one: the first +/// two cross it, and the third cannot be read; served, the list is skipped and the transaction +/// included with the stop. A skipped list is not applied, so the simulation is the only read of +/// the third. +/// +/// revm's `State`, which a block runs on, declares every error of the database below it fatal and +/// only a read its EIP-7928 block access list does not cover not fatal, so a block shows the fatal +/// half. The other half is the engine's part of the same rule: it hands back the database's own +/// error, which the executor maps by its fatality (`BlockExecutionError::evm`). +#[test] +fn test_a_database_error_in_the_authorization_list_simulation_is_internal_only_when_fatal() { + use alloy_consensus::{SignableTransaction, TxEip7702}; + use alloy_eips::eip7702::{Authorization, SignedAuthorization}; + use alloy_evm::{ + block::{BlockExecutionError, BlockValidationError}, + Evm, EvmFactory, + }; + use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; + use alloy_primitives::{Signature, B256}; + use mega_evm::{LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory}; + + let authorization = |delegate: Address| { + let word = U256::from_be_bytes([0x22; 32]); + let auth = Authorization { chain_id: U256::ZERO, address: delegate, nonce: 0 }; + let signed = SignedAuthorization::new_unchecked(auth, 0, word, word); + let authority = signed.recover_authority().expect("a Nick's-Method signature recovers"); + (signed, authority) + }; + let (first, _) = authorization(CONTRACT); + let (second, _) = authorization(CALLER3); + let (third, refused) = authorization(CALLER2); + let tx = TxEip7702 { + chain_id: common::CHAIN_ID, + nonce: 0, + gas_limit: 1_000_000 + common::body_history(0) + 4 * common::new_account_state_gas(), + max_fee_per_gas: 0, + max_priority_fee_per_gas: 0, + to: CONTRACT, + value: U256::ZERO, + access_list: Default::default(), + authorization_list: vec![first, second, third], + input: Bytes::new(), + }; + let tx = Recovered::new_unchecked( + MegaTxEnvelope::Eip7702(tx.into_signed(Signature::test_signature())), + CALLER, + ); + let limits = common::loosest() + .with_tx_runtime_limits(common::loosest_tx().with_tx_state_growth_limit(1)); + let database = |refused: Option
, fatal: bool| RefusesAnAccount { + db: common::database(), + refused, + fatal, + }; + let in_a_block = |db: RefusesAnAccount| { + let mut state = revm::database::State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ) + .with_protocol_limits(limits); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction_without_commit(&tx).map(|result| result.inner.limit_exceeded) + }; + + let stop = in_a_block(database(None, false)).expect("served, the transaction is included"); + assert!( + matches!(stop, Some(LimitCheck::ExceedsLimit { kind: LimitKind::StateGrowth, .. })), + "the list is skipped and the first frame stopped: {stop:?}" + ); + let err = in_a_block(database(Some(refused), true)).expect_err("the read fails"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + assert!(err.to_string().contains("cannot be read"), "{err}"); + + for fatal in [true, false] { + let mut evm = + MegaEvmFactory::new().create_evm(database(Some(refused), fatal), common::evm_env()); + evm.set_tx_runtime_limits(limits.tx_runtime_limits); + let err = evm.transact(&tx).expect_err("the read fails"); + let err = BlockExecutionError::evm(err, B256::ZERO); + if fatal { + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + } else { + assert!( + matches!(err, BlockExecutionError::Validation(BlockValidationError::EVM { .. })), + "{err:?}" + ); + } + assert!(err.to_string().contains("cannot be read"), "{err}"); + } +} diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index f4d0c9747..829bfd4da 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -22,6 +22,11 @@ mod salt; mod schedule; mod sequencer_registry; mod sequences; +// This target compares a pre-block call alone: the reference's transactions and the reservoir it +// reads are the `satin` target's. +#[allow(dead_code)] +#[path = "../shared/op_reference.rs"] +mod op_reference; #[path = "../shared/snapshot.rs"] mod snapshot; mod stale; diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 9986d2c2d..1a893f0f4 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -247,13 +247,13 @@ fn test_a_create2_round_trip_through_the_factory() { input.extend_from_slice(&init); let expected = CREATE2_FACTORY_ADDRESS.create2_from_code(salt, init.as_ref()); // 1,000,000 of regular gas on top of the account the creation adds, the history of the body, - // and 64 times the history of the creation's two write records, at the byte prices in effect: - // the factory forwards all but a 64th of its gas to the creation and pays the records from - // the 64th it keeps. + // and 50 times the history of the creation's two write records, at the byte prices in effect: + // the factory forwards all but 2 per cent of its gas to the creation and pays the records from + // the fiftieth it keeps. let gas_limit = 1_000_000 + common::new_account_state_gas() + common::body_history(input.len() as u64) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price"); + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price"); let outcome = executor .execute_transaction_without_commit(&recovered(tx( diff --git a/crates/mega-evm/tests/block/receipt_goldens.rs b/crates/mega-evm/tests/block/receipt_goldens.rs index db9727e75..a7e811510 100644 --- a/crates/mega-evm/tests/block/receipt_goldens.rs +++ b/crates/mega-evm/tests/block/receipt_goldens.rs @@ -211,17 +211,20 @@ fn test_a_blocks_receipts_pin_their_bytes_bloom_and_cumulative_gas() { outcome.inner.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: DATA_SIZE_LIMIT, - used: stop_body + STOP_START, - frame_local: false, + limit: DATA_SIZE_LIMIT - stop_body, + used: STOP_START, + frame_local: true, }), - "the first frame's start crossed the data-size limit", + "the first frame's start crossed its budget, what the body leaves of the limit", ); let output = stop.clone().expect("the stop reverts"); assert_eq!( output.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: DATA_SIZE_LIMIT } - .abi_encode(), + MegaLimitExceeded { + kind: LimitKind::DataSize.as_u8(), + limit: DATA_SIZE_LIMIT - stop_body, + } + .abi_encode(), "the stop's revert data is MegaLimitExceeded", ); } else { diff --git a/crates/mega-evm/tests/block/system_tx_budgets.rs b/crates/mega-evm/tests/block/system_tx_budgets.rs index c647fc124..46e30fe77 100644 --- a/crates/mega-evm/tests/block/system_tx_budgets.rs +++ b/crates/mega-evm/tests/block/system_tx_budgets.rs @@ -1,6 +1,6 @@ -//! A Mega System Transaction against the block's packing budgets: like a deposit, no data-size -//! budget and no building policy refuses it, and it counts towards both; the header's gas limit and -//! the data-availability footprint still hold it. +//! A Mega System Transaction against the block's packing budgets: like a deposit, no data-size, +//! KV-update or state-growth budget and no building policy refuses it, and it counts towards them; +//! the header's gas limit and the data-availability footprint still hold it. use alloy_consensus::transaction::Recovered; use alloy_eips::Encodable2718; @@ -41,33 +41,40 @@ fn tightest_policy() -> BlockLimits { .with_tx_da_size_limit(0) .with_block_da_size_limit(0) .with_block_txs_data_limit(0) + .with_block_kv_update_limit(0) + .with_block_state_growth_limit(0) } -/// A block whose data-size budget is spent before it starts refuses an ordinary transaction and -/// admits a Mega System Transaction, which counts towards the budget all the same. +/// A block whose data-size, KV-update or state-growth budget is spent before it starts refuses an +/// ordinary transaction and admits a Mega System Transaction, which counts towards each budget all +/// the same: its body's bytes, and the system address's account, which it creates. #[test] -fn test_a_mega_system_transaction_is_admitted_at_a_full_data_size_budget() { - let mut state = common::state(); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(0)), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor - .execute_transaction(&user_tx(0, empty_call_gas())) - .expect_err("an ordinary transaction finds the budget spent"); - - let outcome = - executor.run_transaction(&system_tx()).expect("the system transaction is admitted"); - assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); - let data_size = outcome.inner.usage.data_size; - assert!(data_size > 0); - executor.commit_transaction_outcome(outcome).expect("and committed"); - - assert_eq!(executor.limiter().usage.data_size, data_size, "it counts towards the budget"); - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 1); +fn test_a_mega_system_transaction_is_admitted_at_a_full_budget() { + for (name, policy) in [ + ("data size", BlockLimits::no_limits().with_block_txs_data_limit(0)), + ("KV updates", BlockLimits::no_limits().with_block_kv_update_limit(0)), + ("state growth", BlockLimits::no_limits().with_block_state_growth_limit(0)), + ] { + let mut state = common::state(); + let mut executor = executor(&mut state, common::block_ctx(policy)); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("an ordinary transaction finds the budget spent"); + + let outcome = + executor.run_transaction(&system_tx()).expect("the system transaction is admitted"); + assert!(outcome.inner.result.is_success(), "{name}: {:?}", outcome.inner.result); + let usage = outcome.inner.usage; + assert!(usage.data_size > 0, "{name}"); + assert_eq!(usage.state_growth, 1, "{name}: the system address's new account"); + executor.commit_transaction_outcome(outcome).expect("and committed"); + + assert_eq!(executor.limiter().usage, usage, "{name}: it counts towards the budgets"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1, "{name}"); + } } /// A building policy at its tightest refuses an ordinary transaction and no system transaction: diff --git a/crates/mega-evm/tests/block/transfer_logs.rs b/crates/mega-evm/tests/block/transfer_logs.rs index 1276242de..503366e45 100644 --- a/crates/mega-evm/tests/block/transfer_logs.rs +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -59,16 +59,16 @@ fn state() -> State { } /// A gas limit for any transaction here: 1,000,000 of regular gas on top of the state of two new -/// accounts and a fresh slot, a kilobyte of history beyond the body, and 64 times the history of -/// two write records, at the byte prices in effect: [`FORWARDER`] forwards all but a 64th of its -/// gas with the value it passes on, and pays the records of the frame it starts from the 64th it -/// keeps. +/// accounts and a fresh slot, a kilobyte of history beyond the body, and 50 times the history of +/// two write records, at the byte prices in effect: [`FORWARDER`] forwards all but 2 per cent of +/// its gas with the value it passes on, and pays the records of the frame it starts from the +/// fiftieth it keeps. fn gas_limit() -> u64 { 1_000_000 + 2 * common::new_account_state_gas() + common::slot_state_gas() + common::body_history(1_000) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price") + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price") } /// A legacy transaction from `signer` with `value`. @@ -138,8 +138,8 @@ fn test_a_blocks_receipts_carry_its_transfer_logs_in_execution_order() { vec![transfer_log(DESTRUCTOR, PAYEE, U256::from(DESTRUCTOR_BALANCE))], ]; // The records each keeps: the recipient; the forwarder and the payee; the created account; - // the destruction's beneficiary. - let records = [1, 2, 1, 1]; + // the destructed account, whose balance the destruction clears, and its beneficiary. + let records = [1, 2, 1, 2]; let mut data_size = 0; let mut history_bytes = 0; @@ -261,14 +261,14 @@ fn test_a_value_left_on_a_destroyed_account_is_burned_without_a_log() { executor.apply_pre_execution_changes().expect("the block starts"); // 1,000,000 of regular gas on top of what the byte prices in effect charge: the state of up // to three new accounts — the child, the payee, the child again for the late value — the - // history of the body, and 64 times the history of the creation's two start records, because - // the factory forwards all but a 64th of its gas and pays a start's records from the 64th it - // keeps. The creation returns its unused gas before the late value call, whose single record - // costs less: the factory's is already written in this frame. + // history of the body, and 50 times the history of the creation's two start records, because + // the factory forwards all but 2 per cent of its gas and pays a start's records from the + // fiftieth it keeps. The creation returns its unused gas before the late value call, whose + // single record costs less: the factory's is already written in this frame. let gas_limit = 1_000_000 + 3 * common::new_account_state_gas() + common::body_history(0) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price"); + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price"); let tx = common::legacy_from( CALLER, 0, diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs index f8300bc5c..f4ad5185a 100644 --- a/crates/mega-evm/tests/block/witness/state.rs +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -58,16 +58,16 @@ fn deploying(runtime: &[u8]) -> Bytes { /// A gas limit with room for a creation and two new accounts at the byte prices in effect: /// 1,000,000 of regular gas on top of the state of two new accounts, a fresh slot and a short -/// runtime's deposit, a kilobyte of history beyond the body, and 64 times the history of two -/// write records — a contract that creates, or a factory that forwards all but a 64th of its gas -/// to the creation, pays the records of the frame it starts from the 64th it keeps. +/// runtime's deposit, a kilobyte of history beyond the body, and 50 times the history of two +/// write records — a contract that creates, or a factory that forwards all but 2 per cent of its +/// gas to the creation, pays the records of the frame it starts from the fiftieth it keeps. pub(super) fn creation_gas() -> u64 { 1_000_000 + 2 * common::new_account_state_gas() + common::slot_state_gas() + 64 * mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()) + common::body_history(1_000) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price") + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price") } /// An EIP-7702 call to an authority delegating to the slot writer: the authority's absent account diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs index 388e1b066..00f5d952d 100644 --- a/crates/mega-evm/tests/block/witness/stops.rs +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -1,7 +1,7 @@ //! Every stop class through the harness: a transaction stopped by the data-size and compute //! limits, a crossing at a precompile's price, which its caller catches, a crossing in an answer, -//! and a block budget refusing a later transaction. A stop is what the block records, so a -//! validator must produce the same stop from the same witness. +//! a block budget refusing a later transaction, and an authorization list a limit skips. A stop is +//! what the block records, so a validator must produce the same stop from the same witness. use alloy_primitives::{Bytes, U256}; use alloy_sol_types::SolCall; @@ -20,7 +20,8 @@ use revm::{ use super::{ basics::{slot, slot_writer}, - harness::{call, call_with_value, Case, Run}, + harness::{assert_differs, authorization, call, call_with_value, eip7702, Case, Oracle, Run}, + state::creation_gas, }; use crate::common::{self, loosest_tx, CALLER, CONTRACT}; @@ -195,3 +196,42 @@ fn test_a_stop_above_the_execution_cap_replays() { assert_stopped(run, 0, LimitKind::DataSize); assert!(run.tx(0).gas.reservoir_remaining > 0, "the reservoir came back"); } + +/// An authorization list the state-growth limit skips: two new authorities under a limit of one. +/// Before the first frame the engine loads both to decide the list would create two accounts, +/// applies none, and stops the first frame, so neither is written; the witness still holds both, +/// as accounts the chain does not have, and a validator decides the same skip from it. A witness +/// without one of them cannot replay the block. +#[test] +fn test_a_skipped_authorization_list_replays() { + let (first, first_authority) = authorization(CONTRACT, 0); + let (second, second_authority) = authorization(CALLER, 0); + assert_ne!(first_authority, second_authority); + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let limits = + common::loosest().with_tx_runtime_limits(loosest_tx().with_tx_state_growth_limit(1)); + let case = Case::new("skipped authorization list", db).limits(limits).tx(eip7702( + 0, + CONTRACT, + slot(1), + vec![first, second], + creation_gas(), + )); + let recorded = case.record(); + let mut witness = case.channel_witness(&recorded); + assert_stopped(&recorded, 0, LimitKind::StateGrowth); + for authority in [first_authority, second_authority] { + assert_eq!(recorded.record.accounts.get(&authority), Some(&None), "the list loaded it"); + assert_eq!(witness.accounts.get(&authority), Some(&None), "the channel witness holds it"); + let state = &recorded.tx(0).state; + let written = state.get(&authority).is_some_and(|account| account.is_touched()); + assert!(!written, "a skipped list writes no authority"); + } + + witness.accounts.remove(&second_authority); + let short = case.replay(&witness, &recorded.included(), Oracle::Recorded); + assert_differs("skipped authorization list, one authority short", &recorded, &short); + + case.run(); +} diff --git a/crates/mega-evm/tests/fuzz/blocks.rs b/crates/mega-evm/tests/fuzz/blocks.rs index 5adf9a2b0..57605f97d 100644 --- a/crates/mega-evm/tests/fuzz/blocks.rs +++ b/crates/mega-evm/tests/fuzz/blocks.rs @@ -151,6 +151,12 @@ pub(crate) struct Budgets { pub(crate) data: Budget, /// The policy's cap on the same, which only tightens. pub(crate) policy_data: Budget, + /// The block's KV-update budget, in write records, and the policy's cap on it. + pub(crate) kv: Budget, + pub(crate) policy_kv: Budget, + /// The block's state-growth budget, in new accounts and slots, and the policy's cap on it. + pub(crate) growth: Budget, + pub(crate) policy_growth: Budget, /// The policy's cap on a transaction's declared gas. pub(crate) policy_tx_gas: Option, /// The policy's cap on a transaction's encoded size, in bytes. @@ -163,6 +169,8 @@ fn budgets() -> impl Strategy { ( budget(300..=600, 1_000..=5_000), budget(300..=600, 1_000..=5_000), + (budget(1..=3, 4..=12), budget(1..=3, 4..=12)), + (budget(1..=3, 4..=12), budget(1..=3, 4..=12)), proptest::option::weighted( 0.3, prop_oneof![Just(100_000u32), Just(1_000_000), Just(50_000_000)], @@ -170,13 +178,21 @@ fn budgets() -> impl Strategy { proptest::option::weighted(0.3, prop_oneof![Just(80u16), Just(150), Just(2_000)]), proptest::option::weighted(0.3, prop_oneof![Just(200u16), Just(500), Just(5_000)]), ) - .prop_map(|(data, pd, tx_gas, tx_size, block_size)| Budgets { - data, - policy_data: pd, - policy_tx_gas: tx_gas, - policy_tx_size: tx_size, - policy_block_size: block_size, - }) + .prop_map( + |(data, pd, (kv, policy_kv), (growth, policy_growth), tx_gas, tx_size, block_size)| { + Budgets { + data, + policy_data: pd, + kv, + policy_kv, + growth, + policy_growth, + policy_tx_gas: tx_gas, + policy_tx_size: tx_size, + policy_block_size: block_size, + } + }, + ) } /// A block: a world with its programs (the case's transaction is not used), the transactions, the @@ -198,6 +214,8 @@ impl BlockCase { ProtocolLimits { tx_runtime_limits: self.base.world.limits.runtime(), block_txs_data_limit: self.budgets.data.value(), + block_kv_update_limit: self.budgets.kv.value(), + block_state_growth_limit: self.budgets.growth.value(), } } @@ -208,6 +226,8 @@ impl BlockCase { tx_encode_size_limit: b.policy_tx_size.map_or(u64::MAX, u64::from), block_txs_encode_size_limit: b.policy_block_size.map_or(u64::MAX, u64::from), block_txs_data_limit: b.policy_data.value(), + block_kv_update_limit: b.policy_kv.value(), + block_state_growth_limit: b.policy_growth.value(), ..BlockLimits::no_limits() } } @@ -317,8 +337,8 @@ impl BlockCase { /// Whether the block admits a transaction of `gas_limit` and `tx_size` before it runs, by the /// limiter's rules: a deposit is held to the header's gas limit alone; any other transaction to -/// the policy's per-transaction caps and to the data-size packing budget, which refuses the next -/// transaction once reached. +/// the policy's per-transaction caps and to the data-size, KV-update and state-growth packing +/// budgets, each of which refuses the next transaction once reached. fn admits_before(limiter: &BlockLimiter, gas_limit: u64, tx_size: u64, is_deposit: bool) -> bool { let limits = &limiter.limits; if !is_deposit && gas_limit > limits.tx_gas_limit { @@ -332,7 +352,9 @@ fn admits_before(limiter: &BlockLimiter, gas_limit: u64, tx_size: u64, is_deposi } tx_size <= limits.tx_encode_size_limit && tx_size.saturating_add(limiter.block_tx_size_used) <= limits.block_txs_encode_size_limit && - limiter.usage.data_size < limits.block_txs_data_limit + limiter.usage.data_size < limits.block_txs_data_limit && + limiter.usage.write_records < limits.block_kv_update_limit && + limiter.usage.state_growth < limits.block_state_growth_limit } /// Whether a refusal names a block or transaction limit rather than the transaction's validity: @@ -419,6 +441,7 @@ fn run_block(case: &BlockCase) -> Result MemoryDatabase { let mut db = MemoryDatabase::default().rex6_predeploys(SYSTEM_ADDRESS); let world = &self.world; @@ -67,7 +72,10 @@ impl Case { install(&mut db, Who::Contract.address(), &world.contract, Some(self.main.assemble())); install(&mut db, Who::A.address(), &world.a, Some(self.a.assemble())); install(&mut db, Who::B.address(), &world.b, Some(self.b.assemble())); - db.set_account_balance(Who::Beneficiary.address(), world.beneficiary_balance.wei()); + let beneficiary_balance = world.beneficiary_balance.wei(); + if !beneficiary_balance.is_zero() { + db.set_account_balance(Who::Beneficiary.address(), beneficiary_balance); + } if let Some(delegation) = world.delegation { let address = delegation.delegator.address(); let balance = db.basic_ref_balance(address); @@ -299,14 +307,23 @@ fn init_destroys(init: &super::program::InitCode) -> bool { } } -/// Installs `account` at `address`, with `code` when it has any. +/// Installs `account` at `address`, with `code` when it has any; an account that would hold nothing +/// is not installed. fn install( db: &mut MemoryDatabase, address: Address, account: &AccountShape, code: Option>, ) { - if let Some(code) = code.filter(|code| !code.is_empty()) { + let code = code.filter(|code| !code.is_empty()); + if code.is_none() && + account.balance.wei().is_zero() && + account.nonce == 0 && + account.slots.is_empty() + { + return; + } + if let Some(code) = code { db.set_account_code(address, Bytes::from(code)); } db.set_account_balance(address, account.balance.wei()); diff --git a/crates/mega-evm/tests/fuzz/gen/program.rs b/crates/mega-evm/tests/fuzz/gen/program.rs index 5a1fa45d5..79cec5908 100644 --- a/crates/mega-evm/tests/fuzz/gen/program.rs +++ b/crates/mega-evm/tests/fuzz/gen/program.rs @@ -6,7 +6,7 @@ //! the stack as it found it, so any list assembles to valid bytecode, and a program shrinks by //! dropping ops. The assembly is [`BytecodeBuilder`]'s. -use alloy_primitives::{Address, Bytes, U256}; +use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{ @@ -71,6 +71,11 @@ pub(crate) enum Target { System(SystemContract), /// A precompile. Precompile(Precompile), + /// An account the running program creates: the address one of its own `CREATE2` ops lands + /// on, the `nth` of them modulo their number, computed from `ADDRESS` as the op computes it; + /// in a program with none, the address a `CREATE2` of empty init code with salt zero would + /// land on. A program can so fund, pay or read an account before it creates it, and after. + Created { nth: u8 }, } impl Target { @@ -83,8 +88,9 @@ impl Target { } } -/// Pushes the target's address. -fn push_target(code: BytecodeBuilder, target: Target) -> BytecodeBuilder { +/// Pushes the target's address; a [`Target::Created`] resolves among `creations`, the `CREATE2` +/// ops of the program the target is in. +fn push_target(code: BytecodeBuilder, target: Target, creations: &Creations) -> BytecodeBuilder { match target { Target::Who(who) => code.push_address(who.address()), Target::SelfAddress => code.append(ADDRESS), @@ -92,6 +98,53 @@ fn push_target(code: BytecodeBuilder, target: Target) -> BytecodeBuilder { Target::Caller => code.append(CALLER), Target::System(contract) => code.push_address(contract.address()), Target::Precompile(precompile) => code.push_address(precompile.address()), + Target::Created { nth } => { + // keccak256(0xff ++ ADDRESS ++ salt ++ keccak256(init code)) over memory 11..96: its + // low twenty bytes are the address, which is all a call, an account read or a + // `SELFDESTRUCT` takes of the word. + let (salt, init_hash) = creations.resolve(nth); + code.append_many([ADDRESS, PUSH0, MSTORE]) + .push_number(0xff_u8) + .push_number(11_u8) + .append(MSTORE8) + .push_number(salt) + .push_number(32_u8) + .append(MSTORE) + .push_bytes(init_hash) + .push_number(64_u8) + .append(MSTORE) + .push_number(85_u8) + .push_number(11_u8) + .append(KECCAK256) + } + } +} + +/// The `CREATE2` ops of a program, in order, as the salt and the init code hash each lands with: +/// what a [`Target::Created`] in the program resolves to. +struct Creations(Vec<(u8, B256)>); + +impl Creations { + fn of(ops: &[Op]) -> Self { + Self( + ops.iter() + .filter_map(|op| match op { + Op::Create { salt: Some(salt), init, .. } => { + Some((*salt, keccak256(init.assemble()))) + } + _ => None, + }) + .collect(), + ) + } + + /// The salt and init code hash of the `nth` creation, modulo their number; salt zero and + /// empty init code for a program with none. + fn resolve(&self, nth: u8) -> (u8, B256) { + if self.0.is_empty() { + return (0, keccak256(InitCode::Empty.assemble())); + } + self.0[usize::from(nth) % self.0.len()] } } @@ -103,6 +156,7 @@ fn target() -> impl Strategy { 1 => Just(Target::Caller), 3 => system_contract().prop_map(Target::System), 2 => precompile().prop_map(Target::Precompile), + 3 => (0u8..4).prop_map(|nth| Target::Created { nth }), ] } @@ -338,9 +392,9 @@ fn precompile_input() -> impl Strategy { /// How much gas a call forwards. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Forward { - /// Everything (`GAS`), which the 63/64 rule caps. + /// Everything (`GAS`), which the 98/100 rule caps. All, - /// A fixed amount, which the 63/64 rule may cap lower. + /// A fixed amount, which the 98/100 rule may cap lower. Gas(u32), } @@ -629,16 +683,17 @@ pub(crate) struct Program { impl Program { /// The program's bytecode. pub(crate) fn assemble(&self) -> Vec { + let creations = Creations::of(&self.ops); let mut code = BytecodeBuilder::default(); for op in &self.ops { - code = op.assemble(code); + code = op.assemble(code, &creations); } match self.end { End::Stop => code.stop(), End::Return { len } => code.push_number(len).append_many([PUSH0, RETURN]), End::Revert { len } => code.push_number(len).append_many([PUSH0, REVERT]), End::Invalid => code.append(INVALID), - End::Selfdestruct { to } => push_target(code, to).append(SELFDESTRUCT), + End::Selfdestruct { to } => push_target(code, to, &creations).append(SELFDESTRUCT), End::Spin => { let dest = code.len() as u32; code.append(JUMPDEST) @@ -753,7 +808,8 @@ impl Op { } } - fn assemble(&self, code: BytecodeBuilder) -> BytecodeBuilder { + /// The op's bytecode, appended to `code`; a [`Target::Created`] resolves among `creations`. + fn assemble(&self, code: BytecodeBuilder, creations: &Creations) -> BytecodeBuilder { match self { Self::Sstore { slot, value } => code.sstore(U256::from(*slot), value.u256()), Self::Sload { slot } => code.push_number(*slot).append_many([SLOAD, POP]), @@ -770,7 +826,7 @@ impl Op { Self::Call { scheme, target, value, forward, args_len } => { let code = code.append_many([PUSH0, PUSH0]).push_number(*args_len).append(PUSH0); let code = if scheme.carries_value() { code.push_u256(value.wei()) } else { code }; - push_forward(push_target(code, *target), *forward) + push_forward(push_target(code, *target, creations), *forward) .append_many([scheme.opcode(), POP]) } Self::System { method, scheme, value } => { @@ -808,7 +864,7 @@ impl Op { } Self::Volatile(read) => read.assemble(code), Self::Account { target, read } => { - let code = push_target(code, *target); + let code = push_target(code, *target, creations); match read { AccountRead::Balance => code.append_many([BALANCE, POP]), AccountRead::CodeSize => code.append_many([EXTCODESIZE, POP]), diff --git a/crates/mega-evm/tests/fuzz/gen/world.rs b/crates/mega-evm/tests/fuzz/gen/world.rs index 4c2a14b61..4e807c46d 100644 --- a/crates/mega-evm/tests/fuzz/gen/world.rs +++ b/crates/mega-evm/tests/fuzz/gen/world.rs @@ -3,7 +3,10 @@ use alloy_primitives::{Address, U256}; use mega_evm::{ - constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, MAX_TX_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}, + constants::{ + BLOCK_ENV_ACCESS_COMPUTE_GAS, MAX_TX_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, + TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, + }, EvmTxRuntimeLimits, MegaSpecId, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use proptest::prelude::*; @@ -154,6 +157,36 @@ impl DataLimit { } } +/// A transaction's limit on a count — its write records or its state growth — tight enough for a +/// program's few writes +/// to reach, or the spec's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CountLimit { + /// A handful: crossed by a few writes. + Small(u8), + /// The spec's. + Spec, + Unlimited, +} + +impl CountLimit { + fn value(self, spec: u64) -> u64 { + match self { + Self::Small(n) => u64::from(n), + Self::Spec => spec, + Self::Unlimited => u64::MAX, + } + } +} + +fn count_limit() -> impl Strategy { + prop_oneof![ + 3 => (0u8..=12).prop_map(CountLimit::Small), + 2 => Just(CountLimit::Spec), + 2 => Just(CountLimit::Unlimited), + ] +} + /// A gas detention cap. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum DetentionCap { @@ -202,6 +235,8 @@ pub(crate) enum Limits { /// A valid set of tight limits. Custom { data: DataLimit, + kv: CountLimit, + growth: CountLimit, frame_data: Option, block_env_cap: DetentionCap, oracle_cap: DetentionCap, @@ -217,38 +252,45 @@ impl Limits { Self::Loosest => EvmTxRuntimeLimits::no_limits() .with_block_env_access_compute_gas_limit(MAX_TX_COMPUTE_GAS - 1) .with_oracle_access_compute_gas_limit(MAX_TX_COMPUTE_GAS - 1), - Self::Custom { data, frame_data, block_env_cap, oracle_cap } => EvmTxRuntimeLimits { - tx_data_size_limit: data.value(), - frame_data_size_limit: frame_data.map_or(u64::MAX, u64::from), - block_env_access_compute_gas_limit: block_env_cap - .value(BLOCK_ENV_ACCESS_COMPUTE_GAS), - oracle_access_compute_gas_limit: oracle_cap.value(ORACLE_ACCESS_COMPUTE_GAS), - }, + Self::Custom { data, kv, growth, frame_data, block_env_cap, oracle_cap } => { + EvmTxRuntimeLimits { + tx_data_size_limit: data.value(), + tx_kv_update_limit: kv.value(TX_KV_UPDATE_LIMIT), + tx_state_growth_limit: growth.value(TX_STATE_GROWTH_LIMIT), + frame_data_size_limit: frame_data.map_or(u64::MAX, u64::from), + block_env_access_compute_gas_limit: block_env_cap + .value(BLOCK_ENV_ACCESS_COMPUTE_GAS), + oracle_access_compute_gas_limit: oracle_cap.value(ORACLE_ACCESS_COMPUTE_GAS), + } + } } } } pub(crate) fn limits() -> impl Strategy { - let custom = ( - // The roomy data-size limits are drawn as often as the tight ones, so the compute stop is - // reached too. - prop_oneof![ - 1 => Just(DataLimit::Body), - 2 => Just(DataLimit::BodyPlusRecord), - 3 => (1u16..=2_000).prop_map(DataLimit::Small), - 3 => Just(DataLimit::Medium), - 3 => Just(DataLimit::Unlimited), - ], - proptest::option::weighted(0.3, prop_oneof![Just(1u16), Just(40), Just(200), Just(2_000)]), - detention_cap(), - detention_cap(), - ) - .prop_map(|(data, frame_data, block_env_cap, oracle_cap)| Limits::Custom { - data, - frame_data, - block_env_cap, - oracle_cap, - }); + let custom = + ( + // The roomy data-size limits are drawn as often as the tight ones, so the compute stop + // is reached too. + prop_oneof![ + 1 => Just(DataLimit::Body), + 2 => Just(DataLimit::BodyPlusRecord), + 3 => (1u16..=2_000).prop_map(DataLimit::Small), + 3 => Just(DataLimit::Medium), + 3 => Just(DataLimit::Unlimited), + ], + count_limit(), + count_limit(), + proptest::option::weighted( + 0.3, + prop_oneof![Just(1u16), Just(40), Just(200), Just(2_000)], + ), + detention_cap(), + detention_cap(), + ) + .prop_map(|(data, kv, growth, frame_data, block_env_cap, oracle_cap)| { + Limits::Custom { data, kv, growth, frame_data, block_env_cap, oracle_cap } + }); prop_oneof![3 => Just(Limits::Default), 2 => Just(Limits::Loosest), 5 => custom] } diff --git a/crates/mega-evm/tests/fuzz/harness.rs b/crates/mega-evm/tests/fuzz/harness.rs index befa05f50..2e4c6e2da 100644 --- a/crates/mega-evm/tests/fuzz/harness.rs +++ b/crates/mega-evm/tests/fuzz/harness.rs @@ -220,6 +220,22 @@ pub(crate) fn runs_at_measurement_prices() -> bool { true } +/// Whether a history byte costs a fraction of a gas at the prices in effect, as the byte-price +/// grid's 0.001 does: each history charge is then rounded on its own, and the history of bytes +/// charged apart is not the history of their sum. A history figure computed from a sum of bytes +/// holds at every other price, and the caller leaves it out here; this leaves the note the +/// byte-price grid counts. +pub(crate) fn history_rounds() -> bool { + if mega_evm::active_satin_prices().cphb.milli_gas().is_multiple_of(1_000) { + return false; + } + mega_evm::test_utils::note_price_guard(&format!( + "{} prices a history byte at a fraction of a gas", + mega_evm::CPHB_ENV_VAR + )); + true +} + /// Holds a property's coverage claim: `missing` lists the classes its run did not reach. /// /// On the default run (see [`FuzzConfig::requires_coverage`]) and at the spec's byte prices a diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index a712a150d..a1181029a 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -9,6 +9,7 @@ use std::{collections::BTreeMap, sync::Mutex}; use alloy_primitives::{Address, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, + op_revm::constants::BASE_FEE_RECIPIENT, system::is_system_originated, test_utils::{GasInspector, MemoryDatabase}, transaction_body_bytes, LimitCheck, LimitKind, MegaContext, MegaTransaction, @@ -130,6 +131,21 @@ fn pre_account(db: &mut MemoryDatabase, address: Address) -> Option Option { + db.basic(address).unwrap_or_default() +} + +/// Whether the outcome's `account` was created in the transaction and destroyed since: its first +/// effective destruction took back every part of it the transaction made — each slot it made +/// non-zero, and, where its leaf was absent at the start, the account's record and its unit of +/// state growth — and from that mark it counted nothing more. +fn destroyed_in_the_transaction(account: &revm::state::Account) -> bool { + account.is_created() && account.is_selfdestructed() +} + /// The gas ledgers, as the spec defines them: /// /// - the three ledgers add up to the raw spend: the regular ledger is defined as the spend less the @@ -279,7 +295,7 @@ fn test_property_kv_weighs_no_more_than_data_size() { context: &mut MegaContext, ) { self.steps += 1; - let usage = context.additional_limit().usage(); + let usage = context.limit_usage(); if usage.write_records * WRITE_RECORD_SIZE > usage.data_size { self.over.get_or_insert((usage, self.steps)); } @@ -317,17 +333,161 @@ fn test_property_kv_weighs_no_more_than_data_size() { "the body and the {hints} bytes of hints forwarded are counted: {usage:?}" ); if !is_exempt(&tx) { - let limit = case.world.limits.runtime().tx_data_size_limit; + let limits = case.world.limits.runtime(); + let limit = limits.tx_data_size_limit; prop_check!( usage.data_size <= limit, "a user's transaction keeps more than its limit of {limit}: {usage:?}" ); + let limit = limits.tx_kv_update_limit; + prop_check!( + usage.write_records <= limit, + "a user's transaction keeps more records than its limit of {limit}: {usage:?}" + ); } Ok(()) }, ); } +/// The write records a transaction reports are the net change of what it kept, computed from the +/// case's pre-state and the outcome's state alone: one for every storage slot whose value differs +/// from its original, and one for every account but the sender whose nonce, balance or code +/// differs from what the case's world held. The sender's account is the body's, and so are the +/// settlement's fee credits, which are taken out of the fee accounts' balances first: the fuzz +/// world prices L1 and operator fees at nothing, so the settlement credits the beneficiary its tip +/// and the base-fee vault the base fee, on the gas the receipt bills, and a transaction that pays +/// no fee — a deposit, or one the protocol sent — credits nothing. What is left of a fee account's +/// change is a write its execution made, a record like any other. +/// +/// An account the transaction created and destroyed keeps no slot's record, and the account's own +/// only where the world held an account there, a balance or an account empty under EIP-161: a +/// leaf that existed at the start is an ordinary deletion, whose record stands, and one that did +/// not is taken back with what the transaction made of it. +#[test] +fn test_property_the_record_count_is_the_net_change() { + check("record_count", CASES, || case(Flavor::Satin), check_record_count); +} + +/// What [`test_property_the_record_count_is_the_net_change`] checks of a case. +pub(crate) fn check_record_count(case: &Case) -> Result<(), proptest::test_runner::TestCaseError> { + let tx = case.transaction(); + let Ok(outcome) = case.execute() else { return Ok(()) }; + let credit = fee_credits(case, &tx, &outcome); + let mut pre = case.database(); + let mut expected = 0; + for (address, account) in &outcome.state { + if destroyed_in_the_transaction(account) { + expected += u64::from(leaf_at_start(&mut pre, *address).is_some()); + continue; + } + let slots = account.storage.values().filter(|slot| slot.is_changed()).count(); + expected += slots as u64; + if *address == tx.caller() { + continue; + } + let before = pre_account(&mut pre, *address).unwrap_or_default(); + let Some(balance) = account.info.balance.checked_sub(credit(*address)) else { + return Err(crate::harness::fail(format!("{address} holds less than its fee credit"))); + }; + let changed = account.info.nonce != before.nonce || + balance != before.balance || + account.info.code_hash != before.code_hash; + expected += u64::from(changed); + } + prop_eq!( + outcome.usage.write_records, + expected, + "the records reported are not the net change of the state" + ); + Ok(()) +} + +/// What the settlement credits each account for `tx`'s fees, which `outcome` billed: the fuzz +/// world prices L1 and operator fees at nothing, so the beneficiary gets the tip and the base-fee +/// vault the base fee, on the gas the receipt bills, and a transaction that pays no fee — a +/// deposit, or one the protocol sent — credits nothing. +fn fee_credits( + case: &Case, + tx: &MegaTransaction, + outcome: &MegaTransactionOutcome, +) -> impl Fn(Address) -> U256 { + let block = case.block(); + let basefee = u128::from(block.basefee); + let used = u128::from(outcome.gas.gas_used); + let tip = tx.effective_gas_price(basefee).saturating_sub(basefee); + let pays_fees = !is_exempt(tx); + move |address: Address| { + let mut credit = 0; + if pays_fees && address == block.beneficiary { + credit += tip * used; + } + if pays_fees && address == BASE_FEE_RECIPIENT { + credit += basefee * used; + } + U256::from(credit) + } +} + +/// The state growth a transaction reports is the net count of the new accounts and new slots it +/// kept, computed from the case's pre-state and the outcome's state alone: one for every slot whose +/// original value is zero and whose present value is not, and one for every account the case's +/// world held empty, or not at all, that the outcome holds non-empty once the settlement's fee +/// credits are taken out of its balance — a fee credit is no rise. The sender's account is the +/// body's, and is a rise only as the caller a deposit-like transaction created. +/// +/// An account the transaction created and destroyed keeps none of its slots, and its leaf only +/// where the world held it as an account empty under EIP-161: the creation added that account and +/// the destruction does not take a leaf back that existed at the start. One the world did not hold +/// is taken back, and one that held a balance was no new account. +#[test] +fn test_property_state_growth_is_the_net_count_of_new_state() { + check("state_growth", CASES, || case(Flavor::Satin), check_state_growth); +} + +/// What [`test_property_state_growth_is_the_net_count_of_new_state`] checks of a case. +pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runner::TestCaseError> { + let tx = case.transaction(); + let Ok(outcome) = case.execute() else { return Ok(()) }; + let credit = fee_credits(case, &tx, &outcome); + let deposit_like = + tx.0.deposit.source_hash != alloy_primitives::B256::ZERO || tx.caller() == SYSTEM_ADDRESS; + let mut pre = case.database(); + let mut expected = 0; + for (address, account) in &outcome.state { + if destroyed_in_the_transaction(account) { + let empty_leaf = leaf_at_start(&mut pre, *address).is_some_and(|info| info.is_empty()); + expected += u64::from(empty_leaf); + continue; + } + let slots = account + .storage + .values() + .filter(|slot| slot.original_value.is_zero() && !slot.present_value.is_zero()) + .count(); + expected += slots as u64; + if *address == tx.caller() && !deposit_like { + continue; + } + if pre_account(&mut pre, *address).is_some() { + continue; + } + let Some(balance) = account.info.balance.checked_sub(credit(*address)) else { + return Err(crate::harness::fail(format!("{address} holds less than its fee credit"))); + }; + let exists = account.info.nonce != 0 || + !balance.is_zero() || + account.info.code_hash != revm::primitives::KECCAK_EMPTY; + expected += u64::from(exists); + } + prop_eq!( + outcome.usage.state_growth, + expected, + "the state growth reported is not the net count of new state" + ); + Ok(()) +} + /// What the Oracle hints `evm`'s transaction forwarded weigh as data size. A forwarded hint's /// payload is its call's whole input: the selector, the topic, the offset and length of the data, /// and the data padded to a word. @@ -342,8 +502,9 @@ fn forwarded_hint_bytes(evm: &mega_evm::MegaEvm) -> } /// A stopped transaction keeps only what the spec says survives: the stop is the crossing of its -/// own frame, which names a limit the case runs under — the transaction's data-size limit, that -/// frame's budget, which is below it, or a compute limit, which no frame budget is — and reverts +/// own frame, which names a limit the case runs under — the transaction's data-size, KV or +/// state-growth limit, that frame's budget in one of them, which is below it, or a compute limit, +/// which no frame budget is — and reverts /// that frame and so everything below it; it is a revert carrying `MegaLimitExceeded`, with no /// log; no storage write stands; no account changes but the sender's /// nonce and fee, the fee recipients' credit, an applied EIP-7702 authority's nonce and @@ -387,17 +548,23 @@ pub(crate) fn check_survivors( "a reported stop that is within the limit\n{rendered}" ))); }; - let tx_limit = case.world.limits.runtime().tx_data_size_limit; + let runtime = case.world.limits.runtime(); + let tx_limit = match kind { + LimitKind::DataSize => runtime.tx_data_size_limit, + LimitKind::KvUpdate => runtime.tx_kv_update_limit, + LimitKind::StateGrowth => runtime.tx_state_growth_limit, + LimitKind::ComputeGas => u64::MAX, + }; match (kind, frame_local) { - (LimitKind::DataSize, false) => { - prop_eq!(limit, tx_limit, "the stop names the transaction's limit\n{rendered}"); - } - (LimitKind::DataSize, true) => { - prop_check!(limit < tx_limit, "a frame budget is below the limit\n{rendered}"); - } (LimitKind::ComputeGas, frame_local) => { prop_check!(!frame_local, "a compute stop is no frame budget\n{rendered}"); } + (_, false) => { + prop_eq!(limit, tx_limit, "the stop names the transaction's limit\n{rendered}"); + } + (_, true) => { + prop_check!(limit <= tx_limit, "a frame budget is within the limit\n{rendered}"); + } } match &outcome.result { ExecutionResult::Revert { output, .. } => { diff --git a/crates/mega-evm/tests/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 518c5f445..8c5ff81ae 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -27,12 +27,14 @@ use crate::{ gen::{ case::Case, - program::{End, Program}, + program::{End, Forward, InitCode, Op, Program, Scheme, Target}, tx::{GasTier, Price, Shape, Tx}, - world::{AccountShape, Balance, BeneficiaryIs, BlockShape, Limits, Salt, World}, + world::{ + AccountShape, Balance, BeneficiaryIs, BlockShape, Delegation, Limits, Salt, World, + }, Value, Who, }, - harness::runs_at_measurement_prices, + harness::{history_rounds, runs_at_measurement_prices}, render::render, }; @@ -114,7 +116,10 @@ fn test_an_out_of_gas_before_the_first_frame_pays_the_operator_fee_on_the_whole_ let gas = outcome.result.gas(); let gas_limit = GasTier::Tiny.limit(); assert_eq!(gas.total_gas_spent(), gas_limit, "the whole gas limit burns\n{rendered}"); - assert_eq!(gas.reservoir_remaining(), 0, "nothing comes back from a reservoir\n{rendered}"); + assert_eq!( + outcome.gas.reservoir_remaining, 0, + "nothing comes back from a reservoir\n{rendered}" + ); assert_eq!(outcome.gas.gas_used, gas_limit, "{rendered}"); let body = mega_evm::transaction_body_bytes(&case.transaction()); assert_eq!(outcome.gas.history_bytes, body, "the body alone is kept\n{rendered}"); @@ -145,3 +150,134 @@ fn test_an_out_of_gas_before_the_first_frame_pays_the_operator_fee_on_the_whole_ "the recipient is created empty: the frame never runs, so the value does not move\n{rendered}" ); } + +/// A sender delegated to `B` calls itself, so `B`'s program runs as the sender: it funds the +/// account its `CREATE2` lands on, then creates it, and the init code destroys the account back to +/// the sender. The record-count property's own check holds: the transaction reports the net change +/// of its state, and the account it funded and created, which did not exist at the start, is taken +/// back with its one record by its destruction, which a creation that records its created account +/// whether or not the transaction had changed it would count twice. The case runs on the large gas +/// tier, which the dearest byte prices do not exhaust. +#[test] +fn test_a_delegated_sender_that_funds_then_creates_reports_the_net_change() { + let mut world = plain_world(); + world.caller.balance = Balance::Small; + world.delegation = Some(Delegation { delegator: Who::Caller, delegate: Who::B }); + let b = Program { + ops: vec![ + Op::Call { + scheme: Scheme::Call, + target: Target::Created { nth: 0 }, + value: Value::One, + forward: Forward::All, + args_len: 0, + }, + Op::Create { + value: Value::Zero, + salt: Some(0), + init: InitCode::Selfdestructs { to: Who::Caller }, + }, + ], + end: End::Stop, + }; + let case = Case { + world, + tx: Tx { + shape: Shape::Call { to: Who::Caller, data_len: 0, access_list: vec![] }, + value: Value::Zero, + gas: GasTier::Large, + price: Price::Free, + nonce_ok: true, + }, + main: stop(), + a: stop(), + b, + }; + let execution = case.execute(); + let rendered = render(&execution); + let outcome = execution.as_ref().expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{rendered}"); + if let Err(error) = crate::properties::check_record_count(&case) { + panic!("{error}\n{rendered}"); + } + assert_eq!( + outcome.usage.write_records, 0, + "the account funded and created goes with its destruction\n{rendered}" + ); +} + +/// A program that funds the account its `CREATE2` lands on, named by [`Target::Created`], then +/// creates it, keeps one record for the account and one for itself: the transfer changed both, so +/// neither the creation nor the bump of the program's nonce adds a record. The creation lands on +/// the funded address, which pins that the target resolves to the address the op creates at. +/// +/// Before the created account followed the net-change rule, the creation recorded it a second +/// time: three records where two stand, and a record's history more. +#[test] +fn test_a_program_that_funds_the_account_it_then_creates_keeps_one_record_for_it() { + use alloy_primitives::{keccak256, B256, U256}; + use mega_evm::{LimitUsage, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; + + const SALT: u8 = 2; + let main = Program { + ops: vec![ + Op::Call { + scheme: Scheme::Call, + target: Target::Created { nth: 0 }, + value: Value::One, + forward: Forward::All, + args_len: 0, + }, + Op::Create { value: Value::Zero, salt: Some(SALT), init: InitCode::Empty }, + ], + end: End::Stop, + }; + let mut world = plain_world(); + world.contract.balance = Balance::Small; + let case = Case { + world, + tx: Tx { + shape: Shape::Call { to: Who::Contract, data_len: 0, access_list: vec![] }, + value: Value::Zero, + gas: GasTier::Large, + price: Price::Free, + nonce_ok: true, + }, + main, + a: stop(), + b: stop(), + }; + let execution = case.execute(); + let outcome = execution.as_ref().expect("the transaction is valid"); + let rendered = render(&execution); + assert!(outcome.result.is_success(), "{rendered}"); + + let created = Who::Contract + .address() + .create2(B256::from(U256::from(SALT)), keccak256(InitCode::Empty.assemble())); + let account = outcome.state.get(&created).expect("the account is created"); + assert_eq!( + (account.info.nonce, account.info.balance), + (1, U256::from(1)), + "the creation landed on the account the program funded\n{rendered}" + ); + let body = mega_evm::transaction_body_bytes(&case.transaction()); + assert_eq!( + outcome.usage, + LimitUsage { + data_size: body + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + write_records: 2, + state_growth: 1, + }, + "the contract and the account it funded and created, and the transfer log; the funding \ + made the account, so the creation onto it adds none\n{rendered}" + ); + if !history_rounds() { + assert_eq!( + outcome.gas.history, + mega_evm::history_gas(body + 2 * WRITE_RECORD_SIZE).expect("the bytes have a price"), + "the history of the body and two records: the creation's charge for the account came \ + back\n{rendered}" + ); + } +} diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index e70acfc35..c8123427a 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -95,7 +95,7 @@ pub(crate) fn run( ) -> (ResultAndState, LimitUsage) { let mut evm = MegaEvm::new(context(db)); let result = evm.transact_raw(tx).expect("the transaction is valid"); - let usage = evm.ctx().additional_limit().usage(); + let usage = evm.ctx().limit_usage(); (result, usage) } @@ -125,6 +125,41 @@ pub(crate) fn share(remaining: u64) -> u64 { u128::from(mega_evm::FRAME_DATA_SHARE_DENOMINATOR)) as u64 } +/// The regular gas a call or creation forwards of the `remaining` its caller holds at the forward +/// when it asks for all of it: all but the caller's 2 per cent, the division truncating. +pub(crate) const fn forward_cap(remaining: u64) -> u64 { + remaining - remaining * 2 / 100 +} + +/// The most regular gas a caller can hold at the forward of a call or creation that asks for all of +/// it and keep only `kept` once [`forward_cap`] is taken: a caller keeps a fiftieth of what it +/// holds, rounded down. +pub(crate) const fn holding_to_keep(kept: u64) -> u64 { + 50 * kept + 49 +} + +/// The reservoir a child frame is given of the `remaining` its caller has left: all but the +/// caller's 2 per cent, the division truncating, so a caller keeps nothing of a reservoir below 50. +pub(crate) const fn reservoir_share(remaining: u64) -> u64 { + remaining - remaining * 2 / 100 +} + +/// The smallest reservoir a caller can hold that hands a child exactly `share` +/// ([`reservoir_share`] takes every value, rising by one or by none at each step). +pub(crate) fn reservoir_giving(share: u64) -> u64 { + let mut remaining = share + share / 50; + while reservoir_share(remaining) > share { + remaining -= 1; + } + while reservoir_share(remaining) < share { + remaining += 1; + } + while remaining > 0 && reservoir_share(remaining - 1) == share { + remaining -= 1; + } + remaining +} + /// `tx` as a user's deposit: no fee, and a source hash a user's transaction could carry. pub(crate) fn deposit(mut tx: MegaTransaction) -> MegaTransaction { tx.0.deposit.source_hash = B256::repeat_byte(0x11); @@ -230,6 +265,31 @@ pub(crate) fn history(bytes: u64) -> u64 { u64::try_from((milli_gas + 500) / 1_000).expect("the history of the bytes fits a u64") } +/// Room for the state gas of several new accounts, including in a frame that resumes after a +/// child burned the 98/100 it was forwarded: at least 50,000,000, and 64 times what a value call +/// to a new account costs its caller at the byte prices in effect, more than the 50 times the +/// fiftieth it keeps needs. +pub(crate) fn value_call_room() -> u64 { + (64 * (account_state_gas() + history(4 * mega_evm::WRITE_RECORD_SIZE) + 50_000)).max(50_000_000) +} + +/// `usage` with `growth` new accounts and new slots kept: its state growth. +pub(crate) const fn grown(usage: LimitUsage, growth: u64) -> LimitUsage { + LimitUsage { state_growth: growth, ..usage } +} + +/// What a transaction with an empty calldata keeps: its body, `records` write records and the +/// transfer logs of `moves` value movements. +pub(crate) const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + + records * mega_evm::WRITE_RECORD_SIZE + + moves * mega_evm::TRANSFER_LOG_SIZE, + write_records: records, + state_growth: 0, + } +} + /// The history gas the body of a transaction carrying `calldata_len` bytes of calldata, and no /// access list or authorization, pays at the byte prices in effect, by hand: `TX_BODY_SIZE`, 310 /// bytes, and one byte per byte of calldata. diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index 279485668..45546c8fe 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -510,9 +510,9 @@ fn test_computation_past_the_execution_cap_is_an_ordinary_out_of_gas() { } } -/// A nested call cannot compute past the cap either. Its callee is forwarded what the cap leaves, -/// runs out of gas and fails; its caller resumes on the sixty-fourth it kept, and the transaction -/// computes less than the cap. +/// A nested call cannot compute past the cap either. Its callee is forwarded 98/100 of what the +/// cap leaves, runs out of gas and fails; its caller resumes on the 2 per cent it kept, and the +/// transaction computes less than the cap. /// /// Only above the cap: below it the gas limit bounds the callee long before the cap does. #[test] @@ -536,7 +536,7 @@ fn test_a_nested_call_cannot_compute_past_the_cap() { "the call failed, and its flag says so", ); assert!(outcome.gas.regular < TX_GAS_LIMIT_CAP, "{:?}", outcome.gas); - assert!(outcome.gas.regular > TX_GAS_LIMIT_CAP / 64 * 63, "the callee burned its share"); + assert!(outcome.gas.regular > TX_GAS_LIMIT_CAP / 100 * 98, "the callee burned its share"); } /// A transaction whose intrinsic gas alone is more computation than the cap allows is rejected diff --git a/crates/mega-evm/tests/satin/count_order.rs b/crates/mega-evm/tests/satin/count_order.rs index 569baeae1..d85e32bff 100644 --- a/crates/mega-evm/tests/satin/count_order.rs +++ b/crates/mega-evm/tests/satin/count_order.rs @@ -1,8 +1,8 @@ //! The order the two data-size counts are checked in, when one record crosses both at once. //! //! A record is counted on the transaction and on the frame that makes it: the transaction against -//! its limit, the frame against its budget. The transaction is checked first, and the first count -//! crossed is the one the stop names. Either reverts the frame that crossed it alone, and the +//! its limit, the frame against its budget. The frame's budget is checked first, and the first +//! count crossed is the one the stop names. Either reverts the frame that crossed it alone, and the //! caller goes on. use alloy_primitives::{address, Address, Bytes, U256}; @@ -25,7 +25,7 @@ const B: Address = address!("0000000000000000000000000000000000f20002"); const GAS_LIMIT: u64 = 100_000_000; /// One record that crosses the transaction's data-size limit and its frame's budget at once is -/// stopped with the transaction's limit, which is checked first. +/// stopped with the frame's budget, which is checked first. /// /// [`A`] keeps two records, so the transaction has 310 + 2 × 40 = 390 bytes when [`B`] makes the /// record that crosses, which brings it to 430 bytes, and [`B`]'s own count to 40 bytes. `A`'s @@ -34,20 +34,21 @@ const GAS_LIMIT: u64 = 100_000_000; /// gets 39. A transaction limit of 390 leaves `A` 80 bytes, and `B` none. /// /// Either way [`B`] reverts alone with `MegaLimitExceeded(kind, limit)` and [`A`] returns what it -/// reverted with: the limit named is the one the order picks. The row that crosses the frame's -/// budget alone shows that the count the first row ranks second is crossed. +/// reverted with: the limit named is the one the order picks, `B`'s budget of none in the first +/// row, where the transaction's limit is crossed too. The row that crosses the frame's budget alone +/// shows the same budget rule with room left in the transaction. /// /// Rules: [S10.48], [S10.31], [S10.33], [S10.34], [S10]. Independence: constants — the usages and /// budgets are hand arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE` and the 98/100 share. #[test] -fn test_a_record_crossing_both_counts_is_reported_for_the_transaction() { +fn test_a_record_crossing_both_counts_names_the_frame_budget() { let unlimited = EvmTxRuntimeLimits::no_limits(); let before = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE; let rows: [(&str, EvmTxRuntimeLimits, u64); 2] = [ ( - "the transaction's limit and the frame's budget: the transaction's limit", + "the transaction's limit and the frame's budget: the frame's budget", unlimited.with_tx_data_size_limit(before).with_frame_data_size_limit(120), - before, + 0, ), ("the frame's budget alone", unlimited.with_frame_data_size_limit(120), 39), ]; @@ -76,8 +77,8 @@ fn test_a_record_crossing_both_counts_is_reported_for_the_transaction() { assert_eq!(outcome.limit_exceeded, None, "{row}: no stop of the transaction's own frame"); assert_eq!( outcome.usage, - LimitUsage { data_size: before, write_records: 2 }, - "{row}: A's two records, none of B's" + LimitUsage { data_size: before, write_records: 2, state_growth: 2 }, + "{row}: A's two records and two new slots, none of B's" ); } } diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 8188ca906..01bb7e7ff 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -6,14 +6,15 @@ //! //! The body is counted before any frame and kept on every path; validation rejects a transaction //! whose body, with a record for each authorization it carries, exceeds the limit. Deployed code is -//! counted on the creation's lane, one byte per byte, before the creation is committed, and only -//! when revm would deposit it. +//! drawn on the creating frame's byte pool, one byte per byte, before the creation is committed, +//! and only when revm would deposit it. use alloy_evm::Evm; -use alloy_primitives::{address, keccak256, Address, Bytes, U256}; -use alloy_sol_types::SolError; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::{MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, @@ -21,8 +22,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADD, CALL, CREATE, CREATE2, GAS, ISZERO, LOG0, MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, - RETURNDATASIZE, SELFDESTRUCT, SSTORE, STOP, + ADD, CALL, CALLDATASIZE, CREATE, CREATE2, GAS, INVALID, ISZERO, JUMPDEST, JUMPI, LOG0, + MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, SELFDESTRUCT, SSTORE, STOP, }, context::result::{ExecutionResult, HaltReason}, context_interface::cfg::GasId, @@ -35,7 +36,8 @@ use revm::{ use crate::common::{ account_state_gas, body_history, call, call_with_data, constructor_returning, context, create, - execute_under, history, history_is_free, history_rounds, share, slot_state_gas, + execute_under, grown, history, history_is_free, history_rounds, holding_to_keep, + reservoir_giving, share, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000300000"); @@ -47,11 +49,19 @@ const D: Address = address!("0000000000000000000000000000000000300004"); const GAS_LIMIT: u64 = 20_000_000; /// [`GAS_LIMIT`] on top of twice the history of `bytes` at the byte prices in effect: enough for -/// the frame three calls down to keep `bytes`, after each caller kept a 64th of what it forwards. +/// the frame three calls down to keep `bytes`, after each caller kept a fiftieth of what it held. fn gas_for_history(bytes: u64) -> u64 { GAS_LIMIT + 2 * history(bytes) } +/// [`GAS_LIMIT`] on top of twice the state and history gas of `deployed` bytes of code at the byte +/// prices in effect: enough for a creation, which gets 98% of what its creator holds, to deposit +/// them. +fn gas_for_deposit(deployed: u64) -> u64 { + let per_byte = mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()); + GAS_LIMIT + 2 * (deployed * per_byte + history(deployed)) +} + /// The least a parent must have left for the child's share of it to hold `bytes`: a limit that /// fits a child's write by exactly its bytes still reverts the child on its own budget, which is /// 98% of the parent's room, rounded down. @@ -119,11 +129,7 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); let gas_limit = gas_for_history(budget); let result = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); - ( - result, - evm.ctx().additional_limit().limit_exceeded().copied(), - evm.ctx().additional_limit().usage(), - ) + (result, evm.ctx().additional_limit().limit_exceeded().copied(), evm.ctx().limit_usage()) }; // 32 bytes for the log's address, and the data. Exactly the budget. @@ -142,15 +148,21 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { assert!(over.result.logs().is_empty(), "the log died with D"); assert_eq!( usage, - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 3 * 40, write_records: 3 } + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + 3 * 40, + write_records: 3, + state_growth: 3 + }, + "one fresh slot in each caller" ); } -/// The same depth, with the transaction's limit tighter than the frame budgets. `D`'s log crosses -/// the transaction limit, which reverts `D` alone, with the revert data naming the transaction -/// limit: `C`, `B` and `A` resume, each writes its slot within what the transaction has left, and -/// the transaction succeeds. What it keeps is what the same chain keeps without the log: the log -/// went with `D`, and the transaction never kept more than its limit. +/// The same depth, under a transaction limit. `D`'s log crosses the transaction limit and `D`'s own +/// budget with it — a frame's budget is a share of what the transaction has left — which reverts +/// `D` alone, the revert data naming the budget, tested first: `C`, `B` and `A` resume, each +/// writes its slot within what the transaction has left, and the transaction succeeds. What it +/// keeps is what the same chain keeps without the log: the log went with `D`, and the transaction +/// never kept more than its limit. #[test] fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { const TX_LIMIT: u64 = 8_000; @@ -161,9 +173,10 @@ fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { assert!(outcome.result.is_success(), "the callers resume: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "a stop below the transaction's own frame is no stop"); - // `D` reverted with the transaction limit's stop: nothing was written before its log, so the - // log crossed it alone, and the transaction limit is checked before `D`'s budget. - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: TX_LIMIT }; + // `D` reverted with its budget's stop: nothing was written before its log, so its budget is the + // share of a share of a share of what the body leaves. + let budget = share(share(share(TX_LIMIT - mega_evm::TX_BODY_SIZE))); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; assert_eq!( evm.inspector().calls.first(), Some(&(D, InstructionResult::Revert, Bytes::from(stop.abi_encode()))), @@ -172,7 +185,11 @@ fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { assert!(stored(&outcome.state, A) && stored(&outcome.state, B) && stored(&outcome.state, C)); assert!(outcome.result.logs().is_empty(), "the log went with D"); let three_records = mega_evm::TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE; - assert_eq!(outcome.usage, LimitUsage { data_size: three_records, write_records: 3 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: three_records, write_records: 3, state_growth: 3 }, + "one fresh slot in each caller" + ); assert!(outcome.usage.data_size <= TX_LIMIT); // The same chain without the log keeps exactly as much. @@ -265,7 +282,8 @@ fn test_calldata_counts_in_the_body() { assert!(outcome.result.is_success(), "{:?}", outcome.result); outcome.usage }; - let expected = LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 50, write_records: 0 }; + let expected = + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 50, write_records: 0, state_growth: 0 }; assert_eq!(run(0), expected, "a zero byte"); assert_eq!(run(0xff), expected, "a non-zero byte"); } @@ -295,7 +313,11 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() ); assert!(kept.result.is_success(), "inspect {inspect}: {:?}", kept.result); assert_eq!(kept.limit_exceeded, None); - assert_eq!(kept.usage, LimitUsage { data_size: full, write_records: 1 }); + assert_eq!( + kept.usage, + LimitUsage { data_size: full, write_records: 1, state_growth: 1 }, + "inspect {inspect}: the created account is new" + ); assert_eq!(kept.state[&created].info.code_hash, code_hash, "inspect {inspect}"); let (over, probe) = run_create( @@ -304,18 +326,19 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() inspect, ); assert!(!over.result.is_success() && !over.result.is_halt(), "{:?}", over.result); + // The creation is the transaction's own frame, whose budget is what the body leaves. assert_eq!( over.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: full - 1, - used: full, - frame_local: false, + limit: full - 1 - body, + used: full - body, + frame_local: true, }) ); assert_eq!( over.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "the stop drops the code and the created account; the body stays" ); assert!( @@ -329,7 +352,7 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() assert_eq!(probe.creates[0].0, InstructionResult::Revert); assert_eq!( probe.creates[0].1.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: full - 1 } + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: full - 1 - body } .abi_encode() ); } @@ -340,11 +363,13 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() /// creator's nonce record stays, and the caller resumes. #[test] fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { - const CAP: u64 = 1_000; - // The transaction's frame is capped at `CAP` and has spent nothing, so the creation gets 98% - // of that. Its start records the created account and the creator's nonce before the code. + const CAP: u64 = 2_000; + // The transaction's frame is capped at `CAP` and has spent nothing when it creates, so the + // creation gets 98% of it, and the creator keeps the 40 bytes its nonce record takes once the + // creation returned. The creation's start records the created account before the code. let child_budget = share(CAP); - let at_start = 2 * WRITE_RECORD_SIZE; + assert_eq!(CAP - child_budget, WRITE_RECORD_SIZE); + let at_start = WRITE_RECORD_SIZE; let fits = child_budget - at_start; let db = |deployed| funded().account_code(A, factory_deploying(deployed)); let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(CAP); @@ -354,10 +379,11 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { let mut evm = MegaEvm::new(context(db(deployed)).with_tx_runtime_limits(limits)) .with_inspector(Probe::default()); Evm::set_inspector_enabled(&mut evm, inspect); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let result = + evm.transact_raw(call(CALLER, A, U256::ZERO, gas_for_deposit(deployed))).unwrap(); ( result, - evm.ctx().additional_limit().usage(), + evm.ctx().limit_usage(), evm.ctx().additional_limit().limit_exceeded().copied(), evm.inspector().clone(), ) @@ -369,7 +395,13 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { assert_eq!(stop, None); assert_eq!( usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + child_budget, write_records: 2 } + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE + child_budget, + write_records: 2, + state_growth: 1, + }, + "the creator's nonce record, and the creation's whole budget; the created account is \ + new" ); assert_eq!(kept.state[&created].info.code_hash, keccak256(vec![0_u8; fits as usize])); @@ -378,7 +410,11 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { assert_eq!(stop, None, "a frame budget below the transaction's own frame is no stop of it"); assert_eq!( usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 0 + }, "the creator's nonce stays; the code and the created account do not" ); assert!( @@ -399,6 +435,152 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { } } +/// A contract that runs `init` through `CREATE` with `value` wei, then returns what the creation +/// returned or reverted with: nothing once it succeeded, the stop's revert data once a limit +/// stopped it. +fn create_returning_its_output(init: &Bytes, value: u64) -> Bytes { + BytecodeBuilder::default() + .mstore(0, init) + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(value) + .append_many([CREATE, POP, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([RETURNDATASIZE, PUSH0, RETURN]) + .build() +} + +/// A creation's start counts against the creation's own budget — the share of what its creator +/// has left at its `CREATE` — the created account's record, and with an endowment the transfer +/// log. The record of the creator's nonce is the creator's: counted on it once the creation +/// returned with the nonce bumped, and held to the creator's budget, not the creation's. The +/// creator here is the transaction's own frame, with `R` bytes left under the transaction's limit. +/// +/// The largest `R` whose share falls short of the start stops the creation at its start, and the +/// creator keeps its nonce record: 40 without an endowment, a share of 39 against 40 bytes. One +/// byte more, a share of 40, starts the creation, which fills its share and leaves the creator 1 +/// byte, short of its record: the creator is stopped on its own budget once the creation +/// returned, and since it is the transaction's own frame its stop is the transaction's, the +/// creation and the bump going with it. From 80 left the creator keeps both records. With 2,000 +/// left the share is 1,960, so the creation may deposit the 1,920 bytes beyond its start and the +/// creator keeps the 40 left for its record; the 1,921st stops the creation at its deposit. With +/// an endowment the figures are 204 (a share of 199 against 200 bytes), 205, 240, and 2,160 (a +/// share of 2,116, room for 1,916). +#[test] +fn test_a_creation_is_held_to_its_share_from_its_start() { + let run = |left: u64, endowment: u64, deployed: u64| { + let db = funded() + .account_code( + A, + create_returning_its_output(&constructor_returning(deployed), endowment), + ) + .account_balance(A, U256::from(endowment)); + let tx = call(CALLER, A, U256::ZERO, gas_for_deposit(deployed)); + run_at(db, tx, mega_evm::TX_BODY_SIZE + left) + }; + let stop = |budget| MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; + let usage = |bytes, write_records| LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + bytes, + write_records, + state_growth: 0, + }; + let nonce_record_alone = usage(WRITE_RECORD_SIZE, 1); + let nothing_created = |outcome: &MegaTransactionOutcome| { + outcome.state.get(&A.create(0)).is_none_or(|account| account.info.is_empty()) + }; + let assert_stopped = |outcome: &MegaTransactionOutcome, budget: u64, case: &str| { + assert!(outcome.result.is_success(), "{case}: A resumes: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}: a stop below the transaction's frame"); + assert_eq!( + outcome.result.output().unwrap().as_ref(), + stop(budget).abi_encode(), + "{case}: the creation was stopped on its own budget", + ); + assert_eq!(outcome.usage, nonce_record_alone, "{case}: A keeps its nonce record"); + assert_eq!(outcome.state[&A].info.nonce, 1, "{case}"); + assert!(nothing_created(outcome), "{case}: nothing was created"); + }; + + // The creation's budget: the share of what the creator has left at its `CREATE`. + let budget = share; + for endowment in [0, 1] { + let log = if endowment == 0 { 0 } else { TRANSFER_LOG_SIZE }; + let at_start = WRITE_RECORD_SIZE + log; + let starts = child_room(at_start); + + let case = format!("endowment {endowment}, {} left", starts - 1); + assert_stopped(&run(starts - 1, endowment, 0), budget(starts - 1), &case); + + let case = format!("endowment {endowment}, {starts} left"); + let creator_stopped = run(starts, endowment, 0); + assert!( + matches!(creator_stopped.result, ExecutionResult::Revert { .. }), + "{case}: {:?}", + creator_stopped.result + ); + assert_eq!( + creator_stopped.result.output().unwrap().as_ref(), + stop(starts).abi_encode(), + "{case}: the creator is stopped on its own budget once the creation returned", + ); + assert_eq!( + creator_stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: starts, + used: at_start + WRITE_RECORD_SIZE, + frame_local: true, + }), + "{case}: the creation's whole share and the creator's record", + ); + assert_eq!(creator_stopped.usage, usage(0, 0), "{case}: the body alone"); + assert!( + creator_stopped.state.get(&A).is_none_or(|account| account.info.nonce == 0), + "{case}: the bump went with the creator's revert", + ); + assert!(nothing_created(&creator_stopped), "{case}: and the creation with it"); + + let kept = at_start + WRITE_RECORD_SIZE; + let case = format!("endowment {endowment}, {kept} left"); + let started = run(kept, endowment, 0); + assert!(started.result.is_success(), "{case}: {:?}", started.result); + assert_eq!(started.result.output().unwrap(), &Bytes::new(), "{case}: it started"); + assert_eq!( + started.usage, + grown(usage(WRITE_RECORD_SIZE + at_start, 2), 1), + "{case}: both records and the log; the created account is new" + ); + + let left = 2_000 + log; + let room = budget(left) - at_start; + let case = format!("endowment {endowment}, {left} left, {room} bytes deployed"); + let fits = run(left, endowment, room); + assert!(fits.result.is_success(), "{case}: {:?}", fits.result); + assert_eq!(fits.result.output().unwrap(), &Bytes::new(), "{case}: it deployed"); + assert_eq!( + fits.usage, + grown(usage(WRITE_RECORD_SIZE + budget(left), 2), 1), + "{case}: the creator's record, and exactly the creation's share; the created account \ + is new" + ); + assert_eq!( + fits.state[&A.create(0)].info.code_hash, + keccak256(vec![0_u8; room as usize]), + "{case}", + ); + + let case = format!("endowment {endowment}, {left} left, {} bytes deployed", room + 1); + assert_stopped(&run(left, endowment, room + 1), budget(left), &case); + + if endowment == 0 { + assert_eq!((starts - 1, budget(starts - 1), starts, kept), (40, 39, 41, 80)); + assert_eq!((budget(left), room), (1_960, 1_920)); + } else { + assert_eq!((starts - 1, budget(starts - 1), starts, kept), (204, 199, 205, 240)); + assert_eq!((budget(left), room), (2_116, 1_916)); + } + } +} + /// Init code that returns `len` bytes as the deployed contract, the first of them `first` and /// the rest zeros. fn constructor_returning_from(first: u8, len: u64) -> Bytes { @@ -434,17 +616,21 @@ fn factory_noting_failure(init: &Bytes) -> Bytes { /// goes with the creation. The reservoir of a gas limit far above the execution cap pays the state /// gas and the history of a contract of the largest size. /// -/// `A` has 100 bytes left: the creation's start records the created account and `A`'s nonce, and -/// the output comes on top. Afterwards `A` writes a slot to note the failure: the transaction -/// keeps the nonce record and that slot's. +/// `A` has 100 bytes left, and its creation the share of them, 98: the creation's start records +/// the created account, and the output comes on top; `A`'s nonce record is counted on `A` once the +/// creation returned. Afterwards `A` writes a slot to note the failure: the transaction keeps the +/// nonce record and that slot's. #[test] fn test_code_return_create_refuses_is_not_counted() { let limit = mega_evm::TX_BODY_SIZE + 100; let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); let at_start = 2 * WRITE_RECORD_SIZE; let max = MAX_CONTRACT_SIZE as u64; + // Three bytes past the room the creation's share leaves its output. + let past_the_share = share(100) - WRITE_RECORD_SIZE + 3; + assert_eq!(past_the_share, 61); let cases = [ - ("0xEF first", 0xEF, 21, InstructionResult::CreateContractStartingWithEF), + ("0xEF first", 0xEF, past_the_share, InstructionResult::CreateContractStartingWithEF), ("over the code-size limit", 0x00, max + 1, InstructionResult::CreateContractSizeLimit), ]; let run = |init: &Bytes, inspect: bool, gas_limit: u64| { @@ -468,8 +654,12 @@ fn test_code_return_create_refuses_is_not_counted() { assert_eq!(failure_noted(&refused), Some(U256::from(1)), "{case}: A caught it"); assert_eq!( refused.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + at_start, write_records: 2 }, - "{case}: the nonce record and the slot", + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + at_start, + write_records: 2, + state_growth: 1 + }, + "{case}: the nonce record and the slot; the slot is new", ); assert_eq!( refused.gas.history, @@ -496,15 +686,22 @@ fn test_code_return_create_refuses_is_not_counted() { assert_eq!(failure_noted(&caught), Some(U256::from(1)), "{case}"); assert_eq!( caught.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + at_start, write_records: 2 }, - "{case}: the code went with the creation", + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + at_start, + write_records: 2, + state_growth: 1 + }, + "{case}: the code went with the creation; the slot is new", ); if inspect { - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + // The creation's budget is the share of what `A` has left, which the code crosses + // with the transaction's limit. + let budget = share(limit - mega_evm::TX_BODY_SIZE); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; assert_eq!( probe.creates, [(InstructionResult::Revert, Bytes::from(stop.abi_encode()))], - "{case}: the code was counted, and crossed the limit", + "{case}: the code was counted, and crossed the creation's budget", ); } } @@ -520,15 +717,19 @@ fn run_at(db: MemoryDatabase, tx: mega_evm::MegaTransaction, limit: u64) -> Mega .unwrap() } -fn assert_stopped(outcome: &MegaTransactionOutcome, limit: u64, used: u64) { +/// Asserts the transaction's own frame was stopped crossing a transaction limit of `limit` with a +/// usage of `used`, the transaction having counted `before` before the frame: the frame's budget +/// is what the limit leaves, which the crossing crosses too, so the stop names that budget and +/// what the frame used of it. +fn assert_stopped(outcome: &MegaTransactionOutcome, before: u64, limit: u64, used: u64) { assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit, - used, - frame_local: false, + limit: limit - before, + used: used - before, + frame_local: true, }) ); } @@ -553,10 +754,14 @@ fn test_a_log_one_byte_over_stops_on_the_log() { assert!(fits.result.is_success(), "{:?}", fits.result); assert_eq!(fits.result.logs().len(), 1); assert_eq!(fits.result.logs()[0].data.data.len(), data_len as usize); - assert_eq!(fits.usage, LimitUsage { data_size: body + log_bytes + 40, write_records: 1 }); + assert_eq!( + fits.usage, + LimitUsage { data_size: body + log_bytes + 40, write_records: 1, state_growth: 1 }, + "the log, and the fresh slot" + ); let over = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + log_bytes - 1); - assert_stopped(&over, body + log_bytes - 1, body + log_bytes); + assert_stopped(&over, body, body + log_bytes - 1, body + log_bytes); assert!(over.result.logs().is_empty(), "the log that crossed was dropped"); assert_eq!(over.usage.data_size, body, "the store after the log never counted"); } @@ -579,17 +784,21 @@ fn test_a_storage_write_one_byte_over_stops_on_the_write() { let fits = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + record + 32 + 10); assert!(fits.result.is_success(), "{:?}", fits.result); assert_eq!(fits.result.logs().len(), 1); - assert_eq!(fits.usage, LimitUsage { data_size: body + record + 42, write_records: 1 }); + assert_eq!( + fits.usage, + LimitUsage { data_size: body + record + 42, write_records: 1, state_growth: 1 }, + "the fresh slot, and the log" + ); let over = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + record - 1); - assert_stopped(&over, body + record - 1, body + record); + assert_stopped(&over, body, body + record - 1, body + record); assert!(over.result.logs().is_empty(), "the log after the write never ran"); - assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); } /// A value transfer's recipient is one 40-byte record, and the move leaves a transfer log; both are /// counted when the transaction's frame starts. A limit either of them crosses stops the frame -/// there, before any value moves and before the recipient's code runs. +/// there, before the recipient's code runs, and the value goes back with the stop. #[test] fn test_an_account_write_one_byte_over_stops_on_the_recipient() { let db = || { @@ -605,13 +814,17 @@ fn test_an_account_write_one_byte_over_stops_on_the_recipient() { let fits = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), body + start + record); assert!(fits.result.is_success(), "{:?}", fits.result); assert_eq!(fits.state[&B].info.balance, U256::from(1)); - assert_eq!(fits.usage, LimitUsage { data_size: body + start + record, write_records: 2 }); + assert_eq!( + fits.usage, + LimitUsage { data_size: body + start + record, write_records: 2, state_growth: 1 }, + "B's account, the transfer log and B's fresh slot; B exists" + ); for limit in [body + record - 1, body + start - 1] { let over = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), limit); - assert_stopped(&over, limit, body + start); + assert_stopped(&over, body, limit, body + start); assert!(over.result.logs().is_empty(), "limit {limit}: no transfer log"); - assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!( over.state.get(&B).map(|account| account.info.balance).unwrap_or_default(), U256::ZERO @@ -744,14 +957,15 @@ fn bound_at(code: &Bytes, gas_limit: u64, data_limit: u64) -> Bound { } /// A gas limit above what any write here needs to be counted, at the byte prices in effect: -/// 1,000,000 on top of a new account, a fresh slot and the body, and 64 times the history of two -/// records, which a value call that forwards all but a 64th of its gas pays from the 64th it keeps. +/// 1,000,000 on top of a new account, a fresh slot and the body, and 50 times the history of two +/// records, which a value call that forwards all but 2 per cent of its gas pays from the fiftieth +/// it keeps. fn high_bound() -> u64 { 1_000_000 + account_state_gas() + slot_state_gas() + body_history(0) + - 64 * history(2 * WRITE_RECORD_SIZE) + 50 * history(2 * WRITE_RECORD_SIZE) } /// The smallest gas limit at which `code`'s write is counted rather than run out of gas. @@ -790,9 +1004,9 @@ const FRESH_SLOT_COUNTED_AT: u64 = 152_306; /// out-of-gas boundary down by exactly the record's history, at a storage write, a log and a /// `SELFDESTRUCT` alike. /// -/// A `SELFDESTRUCT` that moves value counts its transfer log with its beneficiary's record, in one -/// check, so the two cross together; the log is data size and not history, so the boundary moves -/// by the record's history alone. +/// A `SELFDESTRUCT` that moves value counts its transfer log with its two records — the account +/// it clears and its beneficiary — in one check, so the three cross together; the log is data +/// size and not history, so the boundary moves by the records' history alone. #[test] fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { let selfdestruct = BytecodeBuilder::default().push_address(B).append(SELFDESTRUCT).build(); @@ -802,8 +1016,8 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { ( "a SELFDESTRUCT that moves value", selfdestruct, - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, ), ]; for (name, code, bytes, history_bytes) in sites { @@ -863,15 +1077,14 @@ fn test_the_fresh_slot_boundary_is_the_sum_of_its_parts() { assert_eq!(record_history, WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE); } -/// The bytes a value call's start counts on the caller's lane, its own account's record, and on -/// the frame's lane, the recipient's record and the transfer log. -const START_ON_THE_CALLER: u64 = WRITE_RECORD_SIZE; -const START_ON_THE_FRAME: u64 = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; +/// The bytes a value call's start counts on the pool of the frame it starts: the caller's record +/// and the recipient's, and the transfer log. +const START: u64 = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; -/// A transaction limit the start of [`value_call_to_fresh`] fits: the caller's record, and room -/// for the frame's lane under the 98% share the new frame is given of what the caller has left. +/// A transaction limit the start of [`value_call_to_fresh`] fits: room for its bytes under the 98% +/// share the new frame is given of what the caller has left. fn start_fits() -> u64 { - mega_evm::TX_BODY_SIZE + START_ON_THE_CALLER + child_room(START_ON_THE_FRAME) + mega_evm::TX_BODY_SIZE + child_room(START) } /// At a frame start the order is the other way round, and so is the rule's outcome: the caller @@ -888,7 +1101,7 @@ fn start_fits() -> u64 { fn test_a_frame_start_is_charged_before_its_records_are_counted() { let code = value_call_to_fresh(); // `A`'s account and `FRESH`'s, and the transfer log: 240 bytes on top of the body. - let start = START_ON_THE_CALLER + START_ON_THE_FRAME; + let start = START; let crosses = mega_evm::TX_BODY_SIZE + start - 1; let fits = start_fits(); let charged_at = gas_where_the_write_is_counted(&code, crosses); @@ -905,25 +1118,26 @@ fn test_a_frame_start_is_charged_before_its_records_are_counted() { ); assert_eq!( started.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2 }, - "the frame started and its records were kept, not refused on the frame's budget", + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2, state_growth: 1 }, + "the frame started and its records were kept, not refused on the frame's budget; FRESH is \ + new", ); } -/// The frame-start order, one gas short by hand [S7.28]: a caller that forwards all but a 64th -/// keeps a 64th one gas short of the price of the two records its value call makes, under a +/// The frame-start order, one gas short by hand [S7.28]: a caller that forwards all but 2 per cent +/// keeps a fiftieth one gas short of the price of the two records its value call makes, under a /// limit those records would cross. The caller pays for the records before they are counted, so /// it runs out of gas first — a halt, no stop, nothing counted beyond the body — and the limit -/// never sees the start. One gas more, the 64th pays the records, they are counted, and the same -/// limit answers the start with the stop, which the caller catches; under a limit they fit, the -/// frame starts. +/// never sees the start. One gas more, the fiftieth pays the records, they are counted, and the +/// same limit answers the start with the stop, which the caller catches; under a limit they fit, +/// the frame starts. /// /// The gas limit is the call's intrinsic 15,000, the body's history, the caller's sixteen gas of /// pushes, the `CALL`'s regular gas — the value transfer, the cold recipient and the new account, /// 11,300, 3,000 and nothing at the schedule's prices — the recipient's state gas (charged before -/// the split), and what the caller must hold at the split for its 64th to be the records' price -/// less one: `64 (price − 1) + 63` (`constants`: the two byte prices in effect; 690,755 at the -/// spec's prices). +/// the split), and what the caller must hold at the split for its fiftieth to be the records' +/// price less one: `50 (price − 1) + 49` (`constants`: the two byte prices in effect; 592,195 at +/// the spec's prices). #[test] fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they_would_cross() { // Records that cost nothing leave no price to be short of, and records priced at a fraction @@ -932,7 +1146,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they return; } let records = history(2 * WRITE_RECORD_SIZE); - let held_at_the_split = 64 * (records - 1) + 63; + let held_at_the_split = holding_to_keep(records - 1); let params = mega_evm::satin_gas_params(); let value_call = params.get(GasId::transfer_value_cost()) + params.get(GasId::warm_storage_read_cost()) + @@ -940,7 +1154,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they params.get(GasId::new_account_cost()); let gas_limit = 15_000 + body_history(0) + 16 + value_call + account_state_gas() + held_at_the_split; - let start = START_ON_THE_CALLER + START_ON_THE_FRAME; + let start = START; let crosses = mega_evm::TX_BODY_SIZE + start - 1; let fits = start_fits(); let db = || funded().account_code(A, value_call_to_fresh()).account_balance(A, U256::from(1)); @@ -958,7 +1172,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they assert_eq!(short.limit_exceeded, None, "under a limit of {limit}: no limit saw the start"); assert_eq!( short.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "under a limit of {limit}: nothing was counted beyond the body", ); assert_eq!(short.gas.history, body_history(0), "under a limit of {limit}"); @@ -970,16 +1184,20 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they assert!(stopped.result.is_success(), "the caller catches the stop: {:?}", stopped.result); assert_eq!( read_the_answer(stopped.result.output().expect("A answers")), - Answer::Stop(LimitKind::DataSize, crosses), - "the start was answered with the stop", + Answer::Stop(LimitKind::DataSize, share(crosses - mega_evm::TX_BODY_SIZE)), + "the start was answered with the stop of the budget it starts with", + ); + assert_eq!( + stopped.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 } ); - assert_eq!(stopped.usage, LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }); let started = run_at(db(), call(CALLER, A, U256::ZERO, gas_limit + 1), fits); assert!(started.result.is_success(), "one gas more, the frame starts: {:?}", started.result); assert_eq!( started.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2 } + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2, state_growth: 1 }, + "A's account and FRESH's, and the transfer log; FRESH is new" ); assert_eq!(started.gas.history, body_history(0) + records); assert_eq!(started.gas.state, account_state_gas()); @@ -988,7 +1206,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they return; } assert_eq!(records, 2 * 40 * 88); - assert_eq!(gas_limit, 690_755); + assert_eq!(gas_limit, 592_195); } /* ---------- a child frame's write, and the order where the reservoir runs out ---------- */ @@ -1062,8 +1280,8 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported_at_a_childs_write ( "a SELFDESTRUCT that moves value", selfdestruct_to_c(), - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, ), ]; for (name, code, bytes, history_bytes) in sites { @@ -1100,8 +1318,9 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported_at_a_childs_write } /// Above the cap, where a reservoir one gas short of a record's history makes the order visible -/// [S7.27]: the record's history draws the reservoir first and spills its last gas onto the -/// child, which was forwarded exactly the gas of its write and has none left. Counted under a +/// [S7.27]: the record's history draws the reservoir share the child was given first and spills +/// its last gas onto the child, which was forwarded exactly the gas of its write and has none +/// left. Counted under a /// limit it crosses, the record is refused and nothing is charged — the transaction stops, and /// the spill the child could not pay is never asked of it. A charge made before the check would /// have run the child out of gas instead, and the limit would have reported nothing. Under a @@ -1123,7 +1342,8 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ params.get(GasId::cold_storage_cost()) + params.get(GasId::sstore_set_without_load_cost()); // (site, code, the child's regular gas up to and including the write, the state gas the write - // adds, the bytes the limit counts, the record's history bytes, the records kept) + // adds, the bytes the limit counts, the record's history bytes, the records kept, the new + // accounts and slots kept: the fresh slot, and `C`, which the destruction's wei creates) let sites = [ ( "a fresh slot", @@ -1133,6 +1353,7 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ WRITE_RECORD_SIZE, WRITE_RECORD_SIZE, 1, + 1, ), ( "a log of one byte", @@ -1142,26 +1363,33 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ mega_evm::LOG_BASE_SIZE + 1, mega_evm::LOG_BASE_SIZE + 1, 0, + 0, ), ( "a SELFDESTRUCT that moves value", selfdestruct_to_c(), 3 + (5_000 + params.selfdestruct_cost(true, true)), account_state_gas(), - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, + 2, 1, ), ]; let body = body_history(0); - for (name, code, counted_at, state, bytes, history_bytes, records) in sites { + for (name, code, counted_at, state, bytes, history_bytes, records, growth) in sites { let record = history(history_bytes); - let reservoir = body + state + record - 1; + // `A` holds what the body leaves of the reservoir, and hands `B` one gas short of the + // write's state and history, keeping the rest. + let given = state + record - 1; + let reservoir = body + reservoir_giving(given); + let a_keeps = reservoir - body - given; let gas_limit = TX_GAS_LIMIT_CAP + reservoir; let crosses = mega_evm::TX_BODY_SIZE + bytes - 1; let fits = mega_evm::TX_BODY_SIZE + child_room(bytes); let run = |forward, limit| child_outcome(&code, forward, gas_limit, limit); - let body_only = LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }; + let body_only = + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }; // One gas short of the write itself: an out-of-gas before any record exists, under either // limit, with the reservoir untouched beyond the body. @@ -1178,8 +1406,8 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ assert!(matches!(child_bound(&refused), Bound::DataSize), "{name}: {:?}", refused.result); assert_eq!( read_the_answer(refused.result.output().expect("A answers")), - Answer::Stop(LimitKind::DataSize, crosses), - "{name}: the record crossed the transaction's limit", + Answer::Stop(LimitKind::DataSize, share(crosses - mega_evm::TX_BODY_SIZE)), + "{name}: the record crossed the child's budget and the transaction's limit", ); assert_eq!(refused.gas.history, body, "{name}: the refused record was not charged"); assert_eq!(refused.gas.state, 0, "{name}: the stop gave the state gas back"); @@ -1195,16 +1423,26 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ assert_eq!(kept.gas.state, 0, "{name}"); assert_eq!(kept.gas.reservoir_remaining, reservoir - body, "{name}"); - // One gas more pays the spill: the write is kept, and the reservoir is spent to the last - // gas. + // One gas more pays the spill: the write is kept, and the share is spent to the last gas. + // What `A` kept comes back with the transaction's own frame, which merged `B`'s one gas + // of spill, and unwinds it first: all of it when `A` kept nothing, as below a reservoir + // of 50, where two per cent rounds down to nothing. let paid = run(counted_at + 1, fits); assert!(matches!(child_bound(&paid), Bound::Success), "{name}: {:?}", paid.result); - assert_eq!(paid.gas.reservoir_remaining, 0, "{name}: the reservoir spent to the last gas"); + assert_eq!( + paid.gas.reservoir_remaining, + a_keeps.saturating_sub(1), + "{name}: the share spent to the last gas" + ); assert_eq!(paid.gas.history, body + record, "{name}: the body and the record"); assert_eq!(paid.gas.state, state, "{name}: the state the write added"); assert_eq!( paid.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + bytes, write_records: records }, + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + bytes, + write_records: records, + state_growth: growth + }, "{name}", ); } @@ -1372,7 +1610,11 @@ fn test_a_child_gets_98_percent_of_what_its_parent_has_left_in_slots() { let outcome = run_slots(db, room_for(100)); assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget below is no stop"); - assert_eq!(outcome.usage, LimitUsage { data_size: room_for(kept), write_records: kept }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: room_for(kept), write_records: kept, state_growth: kept }, + "{name}: every slot kept is fresh" + ); if name == "a parent that writes after its child crossed" { let written = |address: Address| { outcome.state.get(&address).is_some_and(|account| { @@ -1398,7 +1640,12 @@ fn test_the_body_and_the_execution_add_up_to_the_stop() { call_with_data(CALLER, A, Bytes::from(vec![0xab; calldata as usize]), SLOTS_GAS_LIMIT), limit, ); - assert_stopped(&outcome, limit, limit + WRITE_RECORD_SIZE); + assert_stopped( + &outcome, + mega_evm::TX_BODY_SIZE + calldata, + limit, + limit + WRITE_RECORD_SIZE, + ); } } @@ -1447,16 +1694,16 @@ fn call_and_return_its_output(target: Address) -> Bytes { } /// A creation too big for its share still bumps its creator's nonce, and the creator's record of -/// that write outlives the creation: it lands on the creator's own lane. The creator is held to +/// that write outlives the creation: it is drawn on the creator's own pool. The creator is held to /// its budget with it before it runs on. /// -/// `A` calls `B` with 4,000 bytes left, so `B` may keep 3,920. `B` logs, then creates: the -/// creation's start records the created account and `B`'s nonce, 80 bytes against a share below -/// 80, so it is stopped with room to spare in the transaction. When the log left `B` 40 bytes, -/// `B` keeps the nonce record at exactly its budget and succeeds. When it left 39, the record puts -/// `B` one byte over: `B` reverts alone, its log and its nonce with it, and `A` resumes and -/// returns `B`'s revert. Either way the history the transaction pays is that of the bytes it -/// keeps. +/// `A` calls `B` with 4,000 bytes left, so `B` may keep 3,920. `B` logs, then creates: `B`'s nonce +/// record is counted on `B` first, and the creation's start records the created account, 40 +/// bytes against a share of what the record left `B`, which is below 40, so it is stopped with +/// room to spare in the transaction. When the log left `B` 40 bytes, `B` keeps the nonce record at +/// exactly its budget and succeeds. When it left 39, the record puts `B` one byte over: `B` +/// reverts alone, its log and its nonce with it, and `A` resumes and returns `B`'s revert. Either +/// way the history the transaction pays is that of the bytes it keeps. #[test] fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { const A_BUDGET: u64 = 4_000; @@ -1484,7 +1731,11 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { assert_eq!(fits.limit_exceeded, None, "{case}"); assert_eq!( fits.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + b_budget, write_records: 1 }, + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + b_budget, + write_records: 1, + state_growth: 0 + }, "{case}: B keeps the nonce record at exactly its budget", ); assert_eq!(fits.gas.history, history_of(fits.usage), "{case}"); @@ -1501,7 +1752,7 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { assert_eq!(over.limit_exceeded, None, "{case}: a frame budget below is no stop"); assert_eq!( over.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{case}: B's log and nonce record went with its revert", ); assert_eq!(over.gas.history, history_of(over.usage), "{case}: and their history"); @@ -1516,3 +1767,235 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { } } } + +/// Halts `B` in the first `step` it is handed once a creation it made returned into it, and counts +/// the times it was. +#[derive(Default)] +struct HaltsTheResume { + returned: bool, + handed: usize, +} + +impl Inspector, EthInterpreter> for HaltsTheResume { + fn create_end( + &mut self, + _: &mut MegaContext, + inputs: &CreateInputs, + _: &mut CreateOutcome, + ) { + self.returned |= inputs.caller() == B; + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if self.returned && interp.input.target_address == B { + self.handed += 1; + interp.halt(InstructionResult::OutOfGas); + } + } +} + +/// The stop the engine sets on a creator its failed creation's nonce record left over its budget +/// is the creator's next action: revm returns it before a `step`, so an inspector that would halt +/// the creator on its resume is never handed it, and the run is the plain run, the creator's +/// revert on its budget, in a debug build and a release build alike. +#[test] +fn test_an_inspector_that_would_halt_a_resumes_stop_is_never_handed_it() { + const A_BUDGET: u64 = 4_000; + let logged = share(A_BUDGET) - (WRITE_RECORD_SIZE - 1) - 32; + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE + A_BUDGET); + let db = || { + funded() + .account_code(A, call_and_return_its_output(B)) + .account_code(B, log_then_create(logged, false)) + }; + let tx = call(CALLER, A, U256::ZERO, GAS_LIMIT); + let plain = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(tx.clone()) + .unwrap(); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: share(A_BUDGET) }; + assert_eq!(plain.result.output().unwrap().as_ref(), stop.abi_encode(), "B returns the stop"); + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .with_inspector(HaltsTheResume::default()); + let halted = evm.execute_transaction(tx).unwrap(); + assert!(evm.inspector().returned, "B's creation returned into it"); + assert_eq!(evm.inspector().handed, 0, "B is not handed to a step before its stop"); + assert_eq!(halted.result_and_state, plain.result_and_state); + assert_eq!(halted.gas, plain.gas); + assert_eq!(halted.usage, plain.usage); +} + +/// A creation that counts nothing at its start runs, whatever its creator's nonce record will +/// cost: the record is counted on the creator once the creation returned, held to the creator's +/// budget before the creator runs on. +/// +/// `A` funds `X`, the address `B`'s empty `CREATE2` lands on, keeping two records and the transfer +/// log, and then calls `B`, whose budget is the share of the 39 bytes `A` has left. `B`'s creation +/// records nothing of its own — `X` is changed already, and it carries no endowment — so it starts +/// and returns a success. The record of `B`'s nonce then crosses `B`'s budget: `B` returns the stop +/// of that budget before it runs on, the creation and its nonce going with its revert, and `A` +/// resumes and keeps what it kept. +#[test] +fn test_a_creation_counting_nothing_runs_and_its_creator_is_stopped_at_the_return() { + let x = B.create2(B256::ZERO, keccak256([])); + let a = then_call(BytecodeBuilder::default().call(x, U256::from(1)), B).append(STOP).build(); + let b = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(CREATE2) + .append(POP) + .append(STOP) + .build(); + let kept = mega_evm::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let limit = kept + WRITE_RECORD_SIZE - 1; + // `B`'s budget: the share of what `A` has left once its transfer is kept, which the nonce + // record crosses. + let b_budget = share(limit - kept); + let b_stop = Bytes::from( + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: b_budget }.abi_encode(), + ); + for inspect in [false, true] { + let db = funded() + .account_code(A, a.clone()) + .account_balance(A, U256::from(1)) + .account_code(B, b.clone()); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(outcome.result.is_success(), "inspect {inspect}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "inspect {inspect}: A caught it"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: kept, write_records: 2, state_growth: 1 }, + "inspect {inspect}: A's transfer alone, which creates X", + ); + assert!(outcome.state.get(&B).is_none_or(|b| b.info.nonce == 0), "inspect {inspect}"); + assert_eq!(outcome.state[&x].info.nonce, 0, "inspect {inspect}: nothing created at X"); + if inspect { + let probe = evm.inspector(); + assert_eq!(probe.creates.len(), 1, "one creation: {:?}", probe.creates); + assert!(probe.creates[0].0.is_ok(), "the creation ran: {:?}", probe.creates); + assert!( + probe.calls.contains(&(B, InstructionResult::Revert, b_stop.clone())), + "B returns the stop of its own budget once the creation returned into it: {:?}", + probe.calls, + ); + } + } +} + +/// A failed frame's counts go back to what the frames kept when its start began, while an Oracle +/// hint, which is on no frame, stays: a frame that took back a record a frame above it made, sent a +/// hint into the room that freed, and failed, leaves the transaction over its limit. The frame it +/// returns into is held to the transaction's limit before it runs on, and stops, whether the frame +/// below reverted, halted or was itself stopped. +/// +/// `A` writes a fresh slot and calls `B`; `B` calls back into `A`, which writes the slot back, then +/// sends the Oracle a hint that fills the transaction's limit, and reverts, halts on an invalid +/// opcode, or writes a fresh slot of its own, which crosses the transaction's limit and stops `B`. +/// Each way `B`'s failure restores the slot's record and the hint stays: `A` returns the +/// transaction's stop as it resumes, and the transaction keeps its body and the hint, its limit +/// exactly. +#[test] +fn test_a_caller_a_failed_callee_left_over_the_transaction_limit_is_stopped() { + let hint = Bytes::from( + IOracle::sendHintCall { topic: B256::repeat_byte(0x7a), data: Bytes::from(vec![0x5a; 64]) } + .abi_encode(), + ); + let hint_bytes = hint.len() as u64; + // `A`: called by the transaction, a fresh slot and a call to `B`; called back with a byte of + // calldata, the slot written back. + let entry = then_call(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)), B) + .append(STOP) + .build_vec(); + let reentry = 4 + entry.len(); + let a = BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(u8::try_from(reentry).unwrap()) + .append(JUMPI) + .append_many(entry) + .append(JUMPDEST) + .sstore(U256::ZERO, U256::ZERO) + .stop() + .build(); + assert_eq!(a[reentry], JUMPDEST); + let limit = mega_evm::TX_BODY_SIZE + hint_bytes; + let stop = + Bytes::from(MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }.abi_encode()); + /// How `B` ends once it sent the hint. + #[derive(Clone, Copy, Debug, PartialEq)] + enum Ending { + Reverts, + Halts, + IsStopped, + } + for ending in [Ending::Reverts, Ending::Halts, Ending::IsStopped] { + for inspect in [false, true] { + // `B`: calls `A` with one byte of calldata, sends the hint, and reverts, halts, or + // writes a fresh slot past the transaction's limit, which its own budget + // holds room for: `A`'s take-back merged into it. + let b = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append_many([PUSH0, PUSH0]) + .push_address(A) + .append_many([GAS, CALL, POP]) + .mstore(0, &hint) + .append_many([PUSH0, PUSH0]) + .push_number(hint_bytes) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]); + let b = match ending { + Ending::Reverts => b.revert(), + Ending::Halts => b.append(INVALID), + Ending::IsStopped => b.sstore(U256::from(1), U256::from(1)).stop(), + }; + let db = funded() + .account_code(A, a.clone()) + .account_code(B, b.build()) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let case = format!("B {ending:?}, inspect {inspect}"); + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "{case}: {:?}", + outcome.result + ); + assert_eq!(outcome.result.output().unwrap(), &stop, "{case}: the stop"); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + WRITE_RECORD_SIZE, + frame_local: false, + }), + "{case}: the transaction's limit, which the restored record and the hint cross", + ); + assert_eq!( + outcome.usage, + LimitUsage { data_size: limit, write_records: 0, state_growth: 0 }, + "{case}: the body and the hint, never taken back", + ); + if inspect { + let b_ends = match ending { + Ending::Reverts => (B, InstructionResult::Revert, Bytes::new()), + Ending::Halts => (B, InstructionResult::InvalidFEOpcode, Bytes::new()), + Ending::IsStopped => (B, InstructionResult::Revert, stop.clone()), + }; + assert!( + evm.inspector().calls.contains(&b_ends), + "{case}: B fails as it should, with the stop of the transaction's limit when its \ + slot crossed it: {:?}", + evm.inspector().calls, + ); + } + } + } +} diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 24c041faf..5c1069362 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -12,7 +12,7 @@ use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitUsage, MegaEvm, MegaTransaction, AUTHORIZATION_SIZE, LOG_BASE_SIZE, - LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LOG_TOPIC_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -23,7 +23,8 @@ use revm::{ }; use crate::common::{ - call, call_with_data, constructor_returning, context, create, execute, execute_under, + call, call_with_data, constructor_returning, context, create, execute, execute_under, grown, + records_and_moves, }; const CALLER: Address = address!("0000000000000000000000000000000000400000"); @@ -40,7 +41,7 @@ fn funded() -> MemoryDatabase { /// What a transaction keeps: its body with `extra` body bytes, `bytes` more from its execution, /// and `records` write records among those. const fn kept(extra: u64, bytes: u64, records: u64) -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE + extra + bytes, write_records: records } + LimitUsage { data_size: TX_BODY_SIZE + extra + bytes, write_records: records, state_growth: 0 } } /// `records` write records and nothing else. @@ -48,11 +49,6 @@ const fn records(records: u64) -> LimitUsage { kept(0, records * WRITE_RECORD_SIZE, records) } -/// `records` write records and the transfer logs of `moves` value movements. -const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { - kept(0, records * WRITE_RECORD_SIZE + moves * TRANSFER_LOG_SIZE, records) -} - /// A contract that `CREATE`s `init` and stops. fn factory(init: &Bytes) -> Bytes { BytecodeBuilder::default() @@ -166,7 +162,7 @@ fn test_what_each_transaction_keeps() { "a value transfer to an account that does not exist", funded(), call(CALLER, CALLEE, U256::from(1), GAS_LIMIT), - records_and_moves(1, 1), + grown(records_and_moves(1, 1), 1), ), ( "a value transfer to the sender itself, which moves nothing", @@ -178,7 +174,7 @@ fn test_what_each_transaction_keeps() { "a creation deploying 10 bytes", funded(), create(CALLER, init.clone(), GAS_LIMIT), - kept(init.len() as u64, WRITE_RECORD_SIZE + 10, 1), + grown(kept(init.len() as u64, WRITE_RECORD_SIZE + 10, 1), 1), ), ( "a creation endowing the account it creates", @@ -188,19 +184,19 @@ fn test_what_each_transaction_keeps() { tx.0.base.value = U256::from(1); tx }, - records_and_moves(1, 1), + grown(records_and_moves(1, 1), 1), ), ( "a factory creating a contract of 10 bytes", with_code(factory(&init)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - kept(0, 2 * WRITE_RECORD_SIZE + 10, 2), + grown(kept(0, 2 * WRITE_RECORD_SIZE + 10, 2), 1), ), ( "a storage write", with_code(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records(1), + grown(records(1), 1), ), ( "a storage read", @@ -240,10 +236,11 @@ fn test_what_each_transaction_keeps() { kept(0, 0, 0), ), ( - "a value transfer the recipient passes on: its account is recorded once", + "a value transfer the recipient passes on: its account is recorded once, and the wei it \ + passes on creates LIBRARY", with_code(call_to(CALL, LIBRARY, 1).stop().build()), call(CALLER, CALLEE, U256::from(100), GAS_LIMIT), - records_and_moves(2, 2), + grown(records_and_moves(2, 2), 1), ), ( "a child that writes a slot and halts", @@ -263,21 +260,23 @@ fn test_what_each_transaction_keeps() { records(1), ), ( - "a SELFDESTRUCT that moves value to an existing account", + "a SELFDESTRUCT that moves value to an existing account: the account it clears, and \ + the beneficiary", with_code( BytecodeBuilder::default().push_address(EXISTING).append(SELFDESTRUCT).build(), ) .account_balance(CALLEE, U256::from(1_000)) .account_balance(EXISTING, U256::from(1)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records_and_moves(1, 1), + records_and_moves(2, 1), ), ( - "a SELFDESTRUCT that moves value to the sender: the body counts the sender", + "a SELFDESTRUCT that moves value to the sender: the account it clears alone, the \ + sender's account being changed already", with_code(BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build()) .account_balance(CALLEE, U256::from(1_000)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records_and_moves(0, 1), + records_and_moves(1, 1), ), ( "a SELFDESTRUCT to itself, which moves nothing", @@ -314,7 +313,7 @@ fn test_a_reverted_childs_write_and_write_back_leave_its_callers_write() { let db = funded().account_code(CALLEE, parent).account_code(LIBRARY, child); let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage, records(1)); + assert_eq!(outcome.usage, grown(records(1), 1), "the caller's fresh slot alone"); assert_eq!( outcome.state[&CALLEE].storage.get(&CALLER_SLOT).map(|slot| slot.present_value), Some(U256::from(1)), @@ -401,6 +400,6 @@ fn test_each_transaction_counts_from_zero() { for run in 0..2 { let result = evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)).unwrap(); assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(evm.ctx().additional_limit().usage(), records(1), "run {run}"); + assert_eq!(evm.ctx().limit_usage(), grown(records(1), 1), "run {run}: a fresh slot"); } } diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 3f05874bc..6ebb66a40 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -13,8 +13,9 @@ //! //! Every gas figure here is built by hand from the spec and the schedule, never read off a run //! of the engine. The creation's regular budget is set exactly: `A` calls the creator `B` with an -//! explicit gas, `B` spends a known amount before its `CREATE`, and the EIP-150 split forwards all -//! but a 64th of what `B` holds, which [`holding_for`] inverts. Each case is one gas short of a +//! explicit gas, `B` spends a known amount before its `CREATE`, and the split forwards all but 2 +//! per cent of what `B` holds under Satin (all but a 64th under Osaka's EIP-150, on the neutral +//! configuration), which [`holding_for`] inverts. Each case is one gas short of a //! charge, or exactly enough, and reads every ledger against its derivation. The data-size limit //! holds the deposit after the last of those charges and before `return_create` commits it: with //! exactly enough gas a limit the deposit crosses stops the creation, and one gas short the @@ -46,7 +47,7 @@ use crate::{ const CALLER: Address = address!("0000000000000000000000000000000000a00000"); /// Calls `B` with a chosen gas and stops. const A: Address = address!("0000000000000000000000000000000000a00001"); -/// Creates the code with all but a 64th of what it has, and stops. +/// Creates the code with all the gas the split forwards, and stops. const B: Address = address!("0000000000000000000000000000000000a00002"); /// The words of zeros the creation deploys, and their bytes. @@ -55,9 +56,9 @@ const CODE_LEN: u64 = DEPLOYED_WORDS * 32; /// The words of memory the init code touches before it returns, so that the creation is forwarded /// millions of gas at any byte price: below the execution cap `B` pays the history of the -/// creation's two write records out of the 64th it keeps, which must cover them whatever a +/// creation's two write records out of the fiftieth it keeps, which must cover them whatever a /// history byte costs — at the dearest price the grid runs, 1,000 a byte, the two records are -/// 80,000 gas, and a 64th of the memory's cost alone is 82,400. [`call_gas`] asserts it. +/// 80,000 gas, and a fiftieth of the memory's cost alone is 105,472. [`call_gas`] asserts it. const BURNT_WORDS: u64 = 51_200; /// The reservoir the runs above the execution cap carry: ample for every charge here. @@ -81,7 +82,7 @@ enum Pool { impl Pool { /// The transaction's gas limit: above the cap by [`RESERVOIR`]; below it, room for `A` to - /// forward the largest gas any case calls `B` with — a 64th more than the forward, and a + /// forward the largest gas any case calls `B` with — a 49th more than the forward, and a /// million of slack — which stays below the cap at any byte price the grid runs; or Osaka's /// own ceiling (EIP-7825 holds a transaction to 2^24 gas). fn gas_limit(self) -> u64 { @@ -89,7 +90,7 @@ impl Pool { Self::AboveCap => TX_GAS_LIMIT_CAP + RESERVOIR, Self::BelowCap => { let largest = call_gas(Self::BelowCap, deposits_at(Self::BelowCap)); - let limit = (largest * 64).div_ceil(63) + 1_000_000; + let limit = (largest * 50).div_ceil(49) + 1_000_000; assert!(limit <= TX_GAS_LIMIT_CAP, "below the cap at these prices: {limit}"); limit } @@ -121,6 +122,8 @@ impl Pool { /// `MSTORE` that puts the init code in memory, with the first word of memory; three `PUSH8`; /// EIP-3860's 2 gas for the one word of init code; and `CREATE`'s own charge, Amsterdam's /// 12,000 under Satin and 32,000 under Osaka. + /// + /// The forward's quotient is in [`Pool::quotient`]. const fn b_before_the_split(self) -> u64 { let create = match self { Self::AboveCap | Self::BelowCap => 12_000, @@ -130,6 +133,17 @@ impl Pool { } } +impl Pool { + /// The quotient of the split: a caller keeps `holding / quotient`, 50 under Satin, Rex6's + /// 98/100, and EIP-150's 64 under Osaka. + const fn quotient(self) -> u64 { + match self { + Self::AboveCap | Self::BelowCap => 50, + Self::NeutralOsaka => 64, + } + } +} + /* ---------- the figures by hand ---------- */ /// What `B` spends after the creation returns: the `POP` of its answer. @@ -189,12 +203,12 @@ fn deposits_at(pool: Pool) -> u64 { } } -/// The least gas `B` can hold at its `CREATE`'s split for the creation to be forwarded exactly -/// `forward`: EIP-150 forwards all but a 64th, `r - r / 64`, which `64 (f / 63) + f mod 63` -/// inverts. -fn holding_for(forward: u64) -> u64 { - let holding = 64 * (forward / 63) + forward % 63; - assert_eq!(holding - holding / 64, forward, "the split inverted"); +/// A gas `B` can hold at its `CREATE`'s split for the creation to be forwarded exactly `forward` in +/// `pool`: the split forwards `r - r / q`, which `q (f / (q - 1)) + f mod (q - 1)` inverts. +fn holding_for(pool: Pool, forward: u64) -> u64 { + let q = pool.quotient(); + let holding = q * (forward / (q - 1)) + forward % (q - 1); + assert_eq!(holding - holding / q, forward, "the split inverted"); holding } @@ -207,11 +221,11 @@ fn call_gas(pool: Pool, forward: u64) -> u64 { Pool::BelowCap => created_account_state_gas(), Pool::AboveCap | Pool::NeutralOsaka => 0, }; - let holding = holding_for(forward); + let holding = holding_for(pool, forward); if pool == Pool::BelowCap { assert!( - holding / 64 >= history(2 * WRITE_RECORD_SIZE) + B_AFTER, - "B's 64th pays the creation's two records and B's POP at these prices", + holding / pool.quotient() >= history(2 * WRITE_RECORD_SIZE) + B_AFTER, + "what B keeps pays the creation's two records and B's POP at these prices", ); } holding + pool.b_before_the_split() + spilled @@ -437,7 +451,11 @@ fn assert_runs_out(name: &str, pool: Pool, forward: u64, left: u64, state_charge assert!(!deployed(&outcome), "{name}: no code is left"); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + LimitUsage { + data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 0 + }, "{name}: the creator's nonce record outlives the creation, nothing else does", ); assert_ledgers(name, pool, forward, &outcome, 0, TX_BODY_SIZE + WRITE_RECORD_SIZE); @@ -469,8 +487,9 @@ fn assert_deposits(name: &str, pool: Pool, forward: u64) { let bytes = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + CODE_LEN; assert_eq!( outcome.usage, - LimitUsage { data_size: bytes, write_records: 2 }, - "{name}: the creator's nonce, the created account, and the code", + LimitUsage { data_size: bytes, write_records: 2, state_growth: 1 }, + "{name}: the creator's nonce, the created account, and the code; the created account is \ + new", ); assert_ledgers(name, pool, regular_deposit(pool), &outcome, state, bytes); } diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 4b0a209e6..75da0292b 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -1,17 +1,17 @@ //! Gas detention against EIP-7708 transfer logs: value that moves after a read of volatile data. //! //! The two meet where a frame starts and at `SELFDESTRUCT`. A frame start counts its transfer log -//! with its records before revm decides the frame — revm then moves the value, answers the frame -//! or refuses it on the caller's account — and a precompile started after a read runs on what the -//! compute limit leaves its frame. A `SELFDESTRUCT` counts its log with its beneficiary's record -//! once the opcode completed, and revm journals the move before the opcode's last charge, which -//! the cap can fail. +//! with its records, held to the limits once revm decided the frame — revm moves the value, answers +//! the frame or refuses it on the caller's account — and a precompile started after a read runs on +//! what the compute limit leaves its frame. A `SELFDESTRUCT` counts its log with its records once +//! the opcode completed, and revm journals the move before the opcode's last charge, which the cap +//! can fail. //! //! Whatever detention does to the movement, the transfer logs a receipt carries are the ones the //! data size kept: a transaction keeps its body, forty bytes a write record and 160 a transfer //! log, and a frame the cap stops keeps nothing, its movement and its log included. A debug build -//! also asserts at every frame start that revm refused exactly the start predicted and journaled -//! exactly the log counted, so every case below runs that check too. +//! also asserts at every start revm made and kept that it journaled exactly the log counted, so +//! every case below runs that check too. //! //! Each case runs with a read of the block's timestamp first, and with `PUSH0`, which costs the //! same two gas and reads nothing, in its place. @@ -30,9 +30,9 @@ use revm::{ use crate::{ detention::{ - assert_caught, assert_stopped, cold_access, context, failed_status_store, intrinsic, - memory_cost, op, run_on, spin, value_transfer, Calls, Charges, Run, BENEFICIARY, CALLER, - CAP, CHILD, CONTRACT, TIERS, + assert_caught_with_stipends, assert_stopped, assert_stopped_with_stipends, call_stipend, + cold_access, context, failed_status_store, intrinsic, memory_cost, op, run_on, spin, + value_transfer, Calls, Charges, Run, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, }, withheld_gas::{costly_modexp_input, intrinsic_with}, }; @@ -72,8 +72,8 @@ fn calls_with_value(first: u8, to: Address, gas: Option) -> Bytes { /// The regular charges [`calls_with_value`] makes after its first instruction reads, with calldata /// of `len` bytes, up to the call: the read's `POP`; `CALLDATASIZE`, two `PUSH0` and /// `CALLDATACOPY` — its static gas, the copy and the memory it expands — the call's four pushes, -/// the value's and the address's, and `GAS`; and the call's own charges, `call`, less the stipend -/// the callee is given, which nobody paid and is not compute. +/// the value's and the address's, and `GAS`; and the call's own charges, `call`, in full: the +/// stipend revm gives the callee is not taken off, since what the callee runs on it is compute. fn charges_to_the_call(len: u64, call: u64) -> Charges { let words = len.div_ceil(32); Charges::default().then(&[ @@ -91,7 +91,7 @@ fn charges_to_the_call(len: u64, call: u64) -> Charges { 3, 3, 2, - call - 2_300, + call, ]) } @@ -236,10 +236,22 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { let charges = charges_to_the_call(above.len() as u64, call_to_an_empty_precompile()) .then(&[price.unwrap()]); let intrinsic = intrinsic_with(&above, gas_limit); - assert_caught(&detained, intrinsic, charges.left(CAP), &failed_status_store()); + // The call carried value: its stipend, which came back with the answer, is gas the ledger + // never billed. + let left = charges.left(CAP); + assert_caught_with_stipends( + &detained, + intrinsic, + left, + &failed_status_store(), + call_stipend(), + ); // The answer is the stop, having spent nothing. assert_eq!(ended(&calls, MODEXP), (InstructionResult::Revert, 0)); - assert_eq!(detained.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + detained.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_counts_its_transfer_logs(&detained, body, "priced past the allowance"); assert_eq!(balance(&detained, MODEXP), U256::ZERO, "nothing moved"); assert!(plain.outcome.result.is_success()); @@ -266,19 +278,252 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { let left = Charges::default().then(&[price]).left(CAP); assert_eq!(left, CAP); assert_stopped(&detained, plain.outcome.gas.regular - price, left); - assert_eq!(detained.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + detained.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!(balance(&detained, MODEXP), U256::ZERO, "the transaction's value did not move"); } } +/// A contract that copies its calldata into memory, then, after `first`, calls `to` with it, +/// [`VALUE`] and all its gas, and returns what the call returned or reverted with. +fn calls_with_value_returning(first: u8, to: Address) -> Bytes { + op(BytecodeBuilder::default(), first) + .append_many([CALLDATASIZE, PUSH0, PUSH0, CALLDATACOPY]) + .append_many([PUSH0, PUSH0, CALLDATASIZE, PUSH0]) + .push_number(VALUE) + .push_address(to) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build() +} + +/// A value call to modexp after a read, priced past the allowance and within the forward, is +/// answered without running with gas detention's stop — unless the start it would have made +/// crosses the data size first. The start's records, modexp's and the caller's, and the transfer +/// log of the value it would move are held to the transaction's limit and to the budget its frame +/// would get before detention classifies the answer, so data size wins over compute at one start. +/// +/// Under a transaction limit, or a frame cap, that leaves the start one byte short of its records +/// and its log — which the records alone fit, so the log is what crosses — the call is answered +/// with the data-size stop, naming the budget the start crossed. With room for the start in its +/// frame's share, it is answered with the compute stop. Nothing moves either way, and the +/// transaction keeps its body alone. +#[test] +fn test_a_start_crossing_data_size_and_compute_at_once_is_the_data_size_stop() { + use alloy_sol_types::SolError; + use mega_evm::{LimitKind, MegaLimitExceeded}; + let above = costly_modexp_input(64, 0); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let share = |cap: u64| crate::common::share(cap); + let cap = (start..).find(|cap| share(*cap) == start - 1).expect("a cap whose share is short"); + let room = (start..).find(|room| share(*room) == start).expect("a room whose share fits"); + for gas_limit in TIERS { + let tx = tx_to(CALLER, CONTRACT, &above, 0, gas_limit); + let body = transaction_body_bytes(&tx); + let limits = EvmTxRuntimeLimits::default(); + let rows = [ + // The transaction's own frame gets what the body leaves, and the call's start the + // share of it, which the start crosses before the transaction's limit. + ( + "the transaction's limit", + limits.with_tx_data_size_limit(body + start - 1), + Some(share(start - 1)), + ), + ("the frame cap", limits.with_frame_data_size_limit(cap), Some(start - 1)), + ("room for the start", limits.with_tx_data_size_limit(body + room), None), + ("room under the frame cap", limits.with_frame_data_size_limit(cap + 1), None), + ]; + for (case, limits, data_size) in rows { + let db = accounts(calls_with_value_returning(TIMESTAMP, MODEXP), VALUE); + let (run, _) = run_tx(db, tx.clone(), limits, false); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + let stop = match data_size { + Some(limit) => MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, + None => MegaLimitExceeded { + kind: LimitKind::ComputeGas.as_u8(), + limit: run.limit.expect("the read set a limit"), + }, + }; + assert_eq!( + run.outcome.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{case}: the call's answer" + ); + assert_eq!(balance(&run, MODEXP), U256::ZERO, "{case}: nothing moved"); + let body_alone = LimitUsage { data_size: body, write_records: 0, state_growth: 0 }; + assert_eq!(run.outcome.usage, body_alone, "{case}"); + } + } +} + +/* ---------- a value call's own charges ---------- */ + +/// The ecrecover precompile, whose account is empty. +const ECRECOVER: Address = address!("0000000000000000000000000000000000000001"); +/// A contract that calls [`CONTRACT`] with all its gas and returns what the call returned. +const PARENT: Address = address!("0000000000000000000000000000000000d00023"); + +/// A contract that reads the block's timestamp, then calls `to` with [`VALUE`] and all its gas, +/// and returns what the call returned or reverted with. +fn reads_then_calls_with_value(to: Address) -> Bytes { + op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(VALUE) + .push_address(to) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build() +} + +/// The regular charges [`reads_then_calls_with_value`] makes after its read up to the call's value +/// transfer: the read's `POP`, the call's four `PUSH0`, the pushes of the value and the address, +/// `GAS`, and the call's static gas, the warm access every call pays before its dynamic charges. +fn charges_to_the_transfer() -> Charges { + Charges::default().then(&[2, 2, 2, 2, 2, 3, 3, 2, 100]) +} + +/// A value `CALL`'s own regular charges come before anything it starts, as any opcode's: its +/// static gas, then the value transfer, then a cold access. Under a cap one unit short of the +/// transfer, the transfer is the charge that crosses, whatever the call's target and whether or +/// not the caller can fund the value: the calling frame is stopped at the opcode, before revm +/// decides the start, so no frame starts, nothing moves, nothing is counted, no log is journaled, +/// and a funded call and an unfunded one are billed the same. A caller one frame up catches the +/// stop and ends within the limit. +/// +/// One unit more pays the transfer exactly, and the stop moves to the next regular charge — the +/// cold access, or, for a warm target, the calling frame's own `POP` once the call returned or the +/// precompile's price answered it — with the transaction's whole limit computed. +#[test] +fn test_a_value_calls_own_transfer_crossing_the_cap_stops_its_caller_before_anything_moves() { + use mega_evm::{LimitCheck, LimitKind}; + use revm::context::transaction::{AccessList, AccessListItem, TransactionType}; + + use crate::detention::{execute, stop_data}; + + let cases: [(&str, Address, bool); 4] = [ + ("a cold contract", RECEIVER, false), + ("a warm contract", RECEIVER, true), + ("a precompile", ECRECOVER, false), + ("an account with no code", PAYEE, false), + ]; + let before = charges_to_the_transfer(); + let cap = before.total() + value_transfer() - 1; + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build(); + for gas_limit in TIERS { + for (case, to, warm) in cases { + // An access list warms the target, and a legacy transaction carries none. + let tx_type = if warm { TransactionType::Eip2930 } else { TransactionType::Legacy }; + let tx = |target| { + let warmed = warm.then_some(AccessListItem { address: to, storage_keys: vec![] }); + OpTx(op_transaction(TxEnv { + tx_type: tx_type as u8, + caller: CALLER, + kind: TxKind::Call(target), + gas_limit, + access_list: AccessList(warmed.into_iter().collect()), + ..Default::default() + })) + }; + let body = transaction_body_bytes(&tx(CONTRACT)); + let body_alone = LimitUsage { data_size: body, write_records: 0, state_growth: 0 }; + let stops = MemoryDatabase::default() + .account_code(CONTRACT, BytecodeBuilder::default().stop().build()); + let intrinsic = execute(stops, tx(CONTRACT)).outcome.gas.regular; + let exec = |target, held, cap, inspected| { + let db = accounts(reads_then_calls_with_value(to), held) + .account_code(PARENT, parent.clone()); + let limits = + EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + run_tx(db, tx(target), limits, inspected) + }; + let left = before.clone().then(&[value_transfer()]).left(cap); + assert_eq!(left, value_transfer() - 1, "{case}: the transfer is one unit short"); + + for (target, frame) in [(CONTRACT, "its own frame"), (PARENT, "one frame down")] { + let mut runs = Vec::new(); + for (held, inspected) in [(VALUE, false), (VALUE, true), (VALUE - 1, true)] { + let case = format!("{case}, {frame}, holding {held}, at {gas_limit}"); + let (run, calls) = exec(target, held, cap, inspected); + if target == CONTRACT { + assert_stopped(&run, intrinsic, left); + } else { + let limit = run.limit.expect("the read set a limit"); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome); + assert_eq!(run.outcome.result.output(), Some(&stop_data(limit)), "{case}"); + assert_eq!(run.outcome.limit_exceeded, None, "{case}: the stop was caught"); + } + if inspected { + assert!(calls.iter().all(|call| call.0 != to), "{case}: no frame started"); + if target == PARENT { + assert_eq!(ended(&calls, CONTRACT).0, InstructionResult::Revert); + } + } + assert_eq!(run.outcome.usage, body_alone, "{case}: nothing counted"); + assert_eq!(run.outcome.gas.state, 0, "{case}: no state gas"); + assert!(run.outcome.result.logs().is_empty(), "{case}: no log"); + assert_eq!(balance(&run, to), U256::ZERO, "{case}: nothing moved"); + assert_eq!(balance(&run, CONTRACT), U256::from(held), "{case}"); + runs.push(run); + } + for run in &runs[1..] { + let case = format!("{case}, {frame}, at {gas_limit}"); + assert_eq!(run.outcome.result, runs[0].outcome.result, "{case}: the result"); + assert_eq!(run.outcome.gas, runs[0].outcome.gas, "{case}: the bill"); + assert_eq!(run.limit, runs[0].limit, "{case}: the limit"); + } + } + + // One unit more: the transfer is paid, and nothing after it fits. A cold target stops + // the call at its cold access, so nothing starts; a warm one is started, revm answering + // it or running its frame, and the calling frame is stopped by its own `POP` once the + // call returned, the stipend that came back with it computed and not billed. + let started = warm || to == ECRECOVER; + let stipends = if started { call_stipend() } else { 0 }; + for held in [VALUE, VALUE - 1] { + let case = format!("{case}, one unit more, holding {held}, at {gas_limit}"); + let (run, calls) = exec(CONTRACT, held, cap + 1, true); + let limit = assert_stopped_with_stipends(&run, intrinsic, 0, stipends); + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false + }), + "{case}: the transfer was paid, and the stop is a later charge" + ); + let ending = calls.iter().find(|call| call.0 == to).map(|call| call.1); + let expected = match (started, held == VALUE) { + (false, _) => None, + (true, false) => Some(InstructionResult::OutOfFunds), + // The precompile's price is past the allowance the transfer left: the stop. + (true, true) if to == ECRECOVER => Some(InstructionResult::Revert), + (true, true) => Some(InstructionResult::Stop), + }; + assert_eq!(ending, expected, "{case}: how the call to the target ended"); + assert_eq!(run.outcome.usage, body_alone, "{case}"); + assert_eq!(balance(&run, to), U256::ZERO, "{case}: the stop took the move back"); + } + } + } +} + /* ---------- a value call its caller cannot fund ---------- */ /// A value call its caller cannot fund, after a read: revm refuses it on the caller's account -/// before anything moves, so its start counts no record and no log and is charged nothing, and -/// detention settles the refusal as it settles any answer. A precompile forwarded more than the -/// allowance, run on the allowance, gets the rest of its forward back. The transaction runs as -/// without the read: the call fails with the whole forward back, nothing moves, no log, and the -/// transaction keeps its body alone. +/// before anything moves, so its start counts no record and no log, the charge for its records +/// comes back, and detention settles the refusal as it settles any answer. A precompile forwarded +/// more than the allowance, run on the allowance, gets the rest of its forward back. The +/// transaction runs as without the read: the call fails with the whole forward back, nothing moves, +/// no log, and the transaction keeps its body alone. #[test] fn test_a_value_call_its_caller_cannot_fund_after_a_read_runs_as_without_it() { let cases: [(&str, Address, Option); 4] = [ @@ -300,7 +545,7 @@ fn test_a_value_call_its_caller_cannot_fund_after_a_read_runs_as_without_it() { let body = transaction_body_bytes(&tx_to(CALLER, CONTRACT, &[0xab; 64], 0, 0)); assert_eq!( detained.outcome.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "{case}: the refused start counted nothing" ); assert!(detained.outcome.result.logs().is_empty(), "{case}"); @@ -327,15 +572,15 @@ fn destruct_after_read() -> u64 { /// A `SELFDESTRUCT` of a balance, after a read, whose frame the cap stops. /// /// - Destructing in the transaction's own frame under a cap that pays exactly the opcode, the -/// balance moves and the receipt carries the log the data size counted with the beneficiary's -/// record, as without the read. A unit less and the cold access, charged after revm journaled the -/// move and the log, crosses the cap: the opcode failed, so nothing is counted, and the stop -/// takes the move and the log back. Less than the opcode's own price, and its static charge -/// crosses before revm moves anything: the same stop. -/// - Destructing in a child, the record and the log land on the child's lane and merge into its -/// caller's. The caller then computes past the cap: the stop takes back the child's move and log -/// with the caller's lane, and the transaction keeps its body alone. Without the spin, the same -/// call keeps the log and the bytes, read or not. +/// balance moves and the receipt carries the log the data size counted with the two records — the +/// destructed account's and the beneficiary's — as without the read. A unit less and the cold +/// access, charged after revm journaled the move and the log, crosses the cap: the opcode failed, +/// so nothing is counted, and the stop takes the move and the log back. Less than the opcode's +/// own price, and its static charge crosses before revm moves anything: the same stop. +/// - Destructing in a child, the records and the log are drawn on the child's pool and merge into +/// its caller's. The caller then computes past the cap: the stop takes back the child's move and +/// log with what the caller kept, and the transaction keeps its body alone. Without the spin, the +/// same call keeps the log and the bytes, read or not. #[test] fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { let own = |first| BytecodeBuilder::default().append_many([first, POP]).selfdestruct(RECEIVER); @@ -356,13 +601,19 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { assert_as_without_read(&detained, &plain, "a cap that pays the destruction"); let logs = assert_counts_its_transfer_logs(&detained, body, "a destruction the cap pays"); assert_eq!(logs, [transfer_log(CONTRACT, RECEIVER, U256::from(VALUE))]); - assert_eq!(detained.outcome.usage.write_records, 1, "the beneficiary's record"); + assert_eq!( + detained.outcome.usage.write_records, 2, + "the destructed account's record and the beneficiary's" + ); for cap in [destruct_after_read() - 1, destruct_after_read() - cold_access() - 1] { let stopped = run_own(TIMESTAMP, cap); let left = Charges::default().then(&[2, 3, 5_000, cold_access()]).left(cap); assert_stopped(&stopped, intrinsic(gas_limit), left); assert_eq!(stopped.limit, Some(2 + cap)); - assert_eq!(stopped.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + stopped.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!(balance(&stopped, RECEIVER), U256::ZERO, "under {cap}, nothing moved"); } @@ -391,7 +642,10 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { .spin(0) .left(CAP); assert_stopped(&stopped, intrinsic(gas_limit), left); - assert_eq!(stopped.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + stopped.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!(balance(&stopped, RECEIVER), U256::ZERO, "the child's move was taken back"); } } @@ -567,7 +821,9 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { if let Some(charges) = start.stops { let left = charges(input.len() as u64).left(CAP); let intrinsic = intrinsic_with(&input, gas_limit); - assert_caught(&detained, intrinsic, left, &failed_status_store()); + // The stopped call carried value: its stipend is gas the ledger never billed. + let after = failed_status_store(); + assert_caught_with_stipends(&detained, intrinsic, left, &after, call_stipend()); assert_eq!(detained.outcome.usage.write_records, 0, "{case}"); } else { let plain = exec(PUSH0); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 32ad40f7c..7cafb61d9 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -15,10 +15,15 @@ use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, + constants::{ + BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP, + TX_STATE_GROWTH_LIMIT, + }, history_gas, system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{ + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, volatile_data_access_disabled_revert_data, write_record_history_gas, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, OracleRead, ProtocolLimits, VolatileDataAccess, @@ -84,6 +89,12 @@ pub(crate) fn value_transfer() -> u64 { crate::salt::entry(GasId::transfer_value_cost()) } +/// The stipend a call carrying value gives its callee on top of the gas it forwards, which its +/// caller does not pay. +pub(crate) fn call_stipend() -> u64 { + mega_evm::satin_gas_params().call_stipend() +} + /// What a write to a fresh slot costs beside its compute: the slot's state gas and its record's /// history, at the prices the schedule was built with. pub(crate) fn fresh_write_spill() -> u64 { @@ -207,6 +218,17 @@ pub(crate) fn stop_data(limit: u64) -> Bytes { /// charge, `left` short of the limit, so the transaction's compute, which the stop reports and its /// regular ledger bills, is the limit less `left`. Returns the limit. pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { + assert_stopped_with_stipends(run, intrinsic, left, 0) +} + +/// [`assert_stopped`] for a transaction whose value calls gave their callees `stipends` of gas in +/// all: gas nobody paid, so the regular ledger bills the transaction's compute less them. +pub(crate) fn assert_stopped_with_stipends( + run: &Run, + intrinsic: u64, + left: u64, + stipends: u64, +) -> u64 { let limit = run.limit.expect("a read set a limit"); match &run.outcome.result { ExecutionResult::Revert { output, .. } => assert_eq!(output, &stop_data(limit)), @@ -224,7 +246,7 @@ pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { ); assert_eq!( run.outcome.gas.regular, - intrinsic + used, + intrinsic + used - stipends, "the transaction computed up to the charge that crossed its limit and not one unit past it" ); assert_eq!(run.outcome.gas.state, 0, "a stop keeps no state"); @@ -241,8 +263,20 @@ pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { /// charge crosses the limit again, and that is the stop the transaction reports /// ([`assert_stopped`]). Returns the limit. pub(crate) fn assert_caught(run: &Run, intrinsic: u64, left: u64, after: &Charges) -> u64 { + assert_caught_with_stipends(run, intrinsic, left, after, 0) +} + +/// [`assert_caught`] for a transaction whose value calls gave their callees `stipends` of gas in +/// all: gas nobody paid, so the regular ledger bills the transaction's compute less them. +pub(crate) fn assert_caught_with_stipends( + run: &Run, + intrinsic: u64, + left: u64, + after: &Charges, + stipends: u64, +) -> u64 { if let Some(left) = after.crossing(left) { - return assert_stopped(run, intrinsic, left); + return assert_stopped_with_stipends(run, intrinsic, left, stipends); } let limit = run.limit.expect("a read set a limit"); assert!( @@ -253,7 +287,7 @@ pub(crate) fn assert_caught(run: &Run, intrinsic: u64, left: u64, after: &Charge assert_eq!(run.outcome.limit_exceeded, None, "a stop below the transaction's own frame"); assert_eq!( run.outcome.gas.regular, - intrinsic + limit - left + after.total(), + intrinsic + limit - left + after.total() - stipends, "the transaction computed up to the charge that crossed, then what its caller ran" ); assert!(run.outcome.gas.regular <= intrinsic + limit, "within the limit"); @@ -354,6 +388,12 @@ impl Charges { charges.then(&[2]) } + /// The charges of [`cheap_spin`]'s loop: `JUMPDEST`, the push of the loop's start and `JUMP`, + /// over and over. + pub(crate) fn cheap_spin(self) -> Self { + self.forever(&[1, 3, 8]) + } + /// The charges of [`burn`]'s `rounds` rounds: the push of the counter, then each round — /// `JUMPDEST`, `PUSH1`, `SWAP1`, `SUB`, `DUP1`, the push of the loop's start and `JUMPI` — /// then the `POP` of the counter. @@ -721,6 +761,81 @@ fn test_blobhash_is_not_volatile() { assert_eq!(run.accessed, VolatileDataAccess::empty()); } +/// A call to the EIP-2935 history contract reads the block environment: the contract's `get` runs +/// `NUMBER` before it loads the slot, so the call marks the block number, and in a frame whose +/// access is off it is refused with access type 0 before it loads the slot. A call to the EIP-4788 +/// beacon-roots contract loads storage alone, state the pre-block calls committed before the +/// block's first transaction, which is no volatile read: it marks nothing and is not refused. +#[test] +fn test_the_history_contract_reads_the_block_number_and_the_beacon_roots_contract_reads_state() { + use alloy_eips::{ + eip2935::{HISTORY_SERVE_WINDOW, HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, + }; + // The ring the beacon-roots contract keeps its timestamps and roots in. + const HISTORY_BUFFER_LENGTH: u64 = 8_191; + + let number = block().number.to::() - 1; + let hash = U256::from_be_bytes([0x11; 32]); + let timestamp = block().timestamp.to::(); + let root = U256::from_be_bytes([0x22; 32]); + let history_slot = U256::from(number % HISTORY_SERVE_WINDOW as u64); + let beacon_slot = U256::from(timestamp % HISTORY_BUFFER_LENGTH); + let db = || { + MemoryDatabase::default() + .account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()) + .account_storage(HISTORY_STORAGE_ADDRESS, history_slot, hash) + .account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()) + .account_storage(BEACON_ROOTS_ADDRESS, beacon_slot, U256::from(timestamp)) + .account_storage( + BEACON_ROOTS_ADDRESS, + beacon_slot + U256::from(HISTORY_BUFFER_LENGTH), + root, + ) + }; + let get = |to: Address, key: u64| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data: Bytes::from(U256::from(key).to_be_bytes::<32>()), + gas_limit: BELOW, + ..Default::default() + })) + }; + let answer = |value: U256| Bytes::from(value.to_be_bytes::<32>()); + + let read = execute(db(), get(HISTORY_STORAGE_ADDRESS, number)); + assert_eq!(read.outcome.result.output(), Some(&answer(hash)), "the parent's hash"); + assert_eq!(read.accessed, VolatileDataAccess::BLOCK_NUMBER); + assert!(read.limit.is_some(), "the read caps the transaction"); + let loaded = &read.outcome.state[&HISTORY_STORAGE_ADDRESS].storage; + assert!(loaded.contains_key(&history_slot), "a read the state holds"); + + let mut evm = MegaEvm::new(context(db()).with_volatile_access_disabled_from(0)); + let refused = run_on(&mut evm, get(HISTORY_STORAGE_ADDRESS, number)); + match &refused.outcome.result { + ExecutionResult::Revert { output, .. } => { + let refusal = + volatile_data_access_disabled_revert_data(VolatileDataAccess::BLOCK_NUMBER); + assert_eq!(output, &refusal); + assert_eq!(output[4..], [0; 32], "access type 0"); + } + other => panic!("the history contract is refused: {other:?}"), + } + let storage = &refused.outcome.state[&HISTORY_STORAGE_ADDRESS].storage; + assert!(!storage.contains_key(&history_slot), "refused before it loads the slot"); + + for disabled in [false, true] { + let ctx = context(db()); + let ctx = if disabled { ctx.with_volatile_access_disabled_from(0) } else { ctx }; + let run = run_on(&mut MegaEvm::new(ctx), get(BEACON_ROOTS_ADDRESS, timestamp)); + let case = format!("access disabled: {disabled}"); + assert_eq!(run.outcome.result.output(), Some(&answer(root)), "{case}: the root"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{case}"); + assert_eq!(run.limit, None, "{case}"); + } +} + /// A read answers with the block's own field: the Host marks the read and serves the value it /// loaded, whether or not the read caps anything. #[test] @@ -951,13 +1066,13 @@ fn test_spending_exactly_the_cap_completes() { } } -/// A value call's stipend is gas nobody paid, so what the callee runs on it is not compute beyond -/// what its caller's ledger shows: a value-carrying child that reads and spins stops with the -/// regular ledger at its compute before the charge that crossed, which its caller catches and -/// ends on, and so does a transaction carrying value, whose own frame is given what the -/// transaction has left and no stipend. +/// A value-called child that reads is counted from its caller's charges in full — the value call's +/// own included, though revm gave the child a stipend the caller never paid — and stops where its +/// own charges after the read reach the cap; its caller catches the stop and ends. The regular +/// ledger bills the transaction its compute less the stipend. A transaction carrying value has no +/// stipend: its own frame is given what the transaction has left, and stops the same way. #[test] -fn test_a_stipend_is_not_compute() { +fn test_a_value_called_child_reads_from_its_callers_whole_charges() { let child = spin(op(BytecodeBuilder::default(), TIMESTAMP)); let parent = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -965,6 +1080,9 @@ fn test_a_stipend_is_not_compute() { .push_address(CHILD) .append_many([GAS, CALL, STOP]) .build(); + // The caller's four `PUSH0`, its `PUSH1`, `PUSH20` and `GAS`, and the call to the cold child + // carrying value; then the child's `TIMESTAMP`. + let at_the_read = 2 * 4 + 3 + 3 + 2 + cold_access() + value_transfer() + 2; for gas_limit in TIERS { let db = MemoryDatabase::default() .account_code(CONTRACT, parent.clone()) @@ -973,7 +1091,14 @@ fn test_a_stipend_is_not_compute() { let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); // Either way the reading frame's `POP` and its loop come after the read. let left = Charges::default().then(&[2]).spin(0).left(CAP); - assert_caught(&run, intrinsic(gas_limit), left, &Charges::default()); + let limit = assert_caught_with_stipends( + &run, + intrinsic(gas_limit), + left, + &Charges::default(), + call_stipend(), + ); + assert_eq!(limit, at_the_read + CAP, "at {gas_limit}"); let db = MemoryDatabase::default() .account_code(CONTRACT, spin(op(BytecodeBuilder::default(), TIMESTAMP))) @@ -986,6 +1111,92 @@ fn test_a_stipend_is_not_compute() { } } +/// The regular charges a contract makes from its first `POP` after a read up to a `CALL` of one wei +/// that forwards no gas to a cold contract: the `POP`, the call's seven pushes, and the call's own +/// charges, the cold access and the transfer. +fn charges_to_a_stipend_call() -> Charges { + Charges::default().then(&[2, 2, 2, 2, 2, 3, 3, 2, cold_access(), value_transfer()]) +} + +/// Appends a `CALL` of one wei to `CHILD` forwarding no gas, so the child runs on its stipend +/// alone, dropping its status. +fn stipend_call(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(CHILD) + .append_many([PUSH0, CALL]) +} + +/// Appends a loop that never ends, twelve gas a round: `JUMPDEST`, a push and `JUMP`. +fn cheap_spin(code: BytecodeBuilder) -> Bytes { + let dest = code.len() as u32; + code.append(JUMPDEST).push_number(dest).append(JUMP).build() +} + +/// What a value call's callee runs on its stipend is compute, whoever funds it: after its caller's +/// read, a callee given the stipend alone, which spins, is stopped at the compute limit once it has +/// run what the limit leaves, though it holds more of the stipend — where it would run out of the +/// stipend if that were not compute. Its caller catches the stop and ends. The regular ledger bills +/// the transaction its compute less the stipend, which is gas the transaction never paid. +#[test] +fn test_stipend_funded_work_is_compute() { + let to_the_call = charges_to_a_stipend_call(); + // A thousand gas past the call, well within the stipend. + let cap = to_the_call.total() + 1_000; + let parent = stipend_call(op(BytecodeBuilder::default(), TIMESTAMP)).stop().build(); + let child = cheap_spin(BytecodeBuilder::default()); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CHILD, child.clone()); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + + // TIMESTAMP was the first opcode. + let limit = run.limit.expect("the read set a limit"); + assert_eq!(limit, 2 + cap, "at {gas_limit}"); + let call = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!(call.result, InstructionResult::Revert, "at {gas_limit}: the stop"); + assert_eq!(call.output, stop_data(limit), "at {gas_limit}"); + assert!(run.outcome.result.is_success(), "at {gas_limit}: {:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None, "at {gas_limit}: the caller caught it"); + let left = to_the_call.clone().cheap_spin().left(cap); + assert_eq!( + run.outcome.gas.regular, + intrinsic(gas_limit) + limit - left - call_stipend(), + "at {gas_limit}: compute up to the crossing, less the stipend nobody paid" + ); + } +} + +/// A value call that returns leaves its caller's compute counting every charge made since the read +/// — the call's own in full, and what the callee ran on its stipend — though the stipend the callee +/// did not spend came back to the caller's gas: the caller, spinning after the call, is stopped +/// where those charges, its own and its callee's in the order they were made, reach the limit. +#[test] +fn test_a_returned_value_call_counts_what_its_callee_ran() { + // The callee runs eighty rounds of a counting loop, 2,085 gas, within the stipend. + let callee = burn(BytecodeBuilder::default(), 80).stop().build(); + let parent = cheap_spin(stipend_call(op(BytecodeBuilder::default(), TIMESTAMP)).append(POP)); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CHILD, callee.clone()); + let cap = 50_000; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let run = run_on( + &mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), + tx(CALLER, CONTRACT, gas_limit), + ); + let charges = charges_to_a_stipend_call().burn(80).then(&[2]).cheap_spin(); + assert_stopped_with_stipends(&run, intrinsic(gas_limit), charges.left(cap), call_stipend()); + } +} + /// A read made by a call is counted from the compute the caller paid at it: its pushes, its /// static and dynamic gas, and the gas it forwards to the callee less a value call's stipend, /// which nobody paid. The limit is exact for a plain call and for one carrying value. @@ -1165,7 +1376,14 @@ fn test_running_out_of_the_frames_own_gas_still_halts() { /// halts. #[test] fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { + // More fresh slots than the 1,000 the spec's state-growth limit lets a transaction keep, so + // the rows run with that limit lifted: under it the 1,001st slot stops the frame first. let slots = CAP / fresh_write() + 1; + assert!(slots > TX_STATE_GROWTH_LIMIT, "{slots} fresh slots"); + let execute = |db: MemoryDatabase, tx| { + let limits = EvmTxRuntimeLimits::default().with_tx_state_growth_limit(u64::MAX); + run_on(&mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), tx) + }; let mut code = op(BytecodeBuilder::default(), TIMESTAMP); for slot in 1..=slots { code = code.sstore(U256::from(slot), U256::from(1)); @@ -1487,7 +1705,7 @@ fn test_the_switch_is_scoped_to_its_subtree() { /// An interceptor's answer carries the forwarded gas back without running a frame: the caller /// is held to the limit as it resumes. The call forwards what it forwards without the read — the -/// withheld part of the caller's gas is part of the 63/64 — and gets all of it back, so the +/// withheld part of the caller's gas is part of the 98/100 — and gets all of it back, so the /// caller holds the same gas after the call with the read and without it. /// /// What `remainingComputeGas()` answers is what the caller could still spend: without the read, @@ -1625,9 +1843,13 @@ fn test_state_and_history_gas_are_not_compute() { // Each slot as (slot, original, present), by slot. let written: Vec<_> = (1..=slots).map(|slot| (U256::from(slot), U256::ZERO, U256::from(1))).collect(); + // At cheaper byte prices the cap's compute pays for more fresh slots than the 1,000 the spec's + // state-growth limit lets a transaction keep, so the rows run with that limit lifted. + let limits = EvmTxRuntimeLimits::default().with_tx_state_growth_limit(u64::MAX); for gas_limit in TIERS { - let run = execute( - MemoryDatabase::default().account_code(CONTRACT, code.clone()), + let db = MemoryDatabase::default().account_code(CONTRACT, code.clone()); + let run = run_on( + &mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), tx(CALLER, CONTRACT, gas_limit), ); assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); @@ -1648,8 +1870,8 @@ fn test_state_and_history_gas_are_not_compute() { assert_eq!(run.limit, Some(2 + CAP), "{case}: TIMESTAMP set the limit, first"); assert_eq!( run.outcome.usage, - LimitUsage { data_size: history_bytes, write_records: slots }, - "{case}: one write record a slot", + LimitUsage { data_size: history_bytes, write_records: slots, state_growth: slots }, + "{case}: one write record and one new slot a slot", ); } } @@ -1694,6 +1916,171 @@ fn test_a_refill_after_the_read_does_not_lift_the_cap() { assert_stopped(&run, intrinsic(BELOW), left); } +/// A slot written away from a non-zero original value and back takes its record back, and the +/// history the record paid with it; there is no state gas to give back, since the write added no +/// state. That history spilled onto regular gas before the read, and its refill — the +/// completed-write hook's own, after revm's state refill — must not give the frame compute past the +/// cap either. +#[test] +fn test_a_history_refill_after_the_read_does_not_lift_the_cap() { + // A record that costs nothing refills nothing. + if crate::common::history_is_free() { + return; + } + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(2)); + let code = op(code, TIMESTAMP).sstore(U256::from(1), U256::from(1)); + let db = MemoryDatabase::default().account_code(CONTRACT, spin(code)).account_storage( + CONTRACT, + U256::from(1), + U256::from(1), + ); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + // The `POP`, then the restoring write — two pushes and `SSTORE`'s static gas, the whole of a + // warm write that restores its slot's original value — then the loop. + let left = Charges::default().then(&[2, 3, 3, 100]).spin(0).left(CAP); + assert_stopped(&run, intrinsic(BELOW), left); + assert_eq!(run.outcome.gas.history, history_gas(TX_BODY_SIZE).unwrap(), "the body's alone"); +} + +/// A frame-starting opcode whose caller cannot pay the history of the records the start makes +/// starts no frame, and halts its caller: what the caller forwarded is burned with the rest of its +/// gas, and none of it is compute, since the frame never ran — nor is a value call's stipend, +/// which the caller never held. So a transaction that read before it called that caller computes +/// the caller's charges up to its forward and no more, and is stopped at the cap exactly where +/// those and its own reach it; its regular ledger bills the burned gas on top. +/// +/// `MIDDLE` starts each kind of frame that makes records, with all but 2 per cent of what it holds, +/// a fiftieth short of the records' price; and a value call with an explicit forward that leaves +/// it one gas short. One gas less forwarded leaves it the price: that frame starts, its callee +/// returns the stipend, and the transaction computes the same. A value `CALLCODE` is not among +/// them: it moves nothing and makes no record, so there is no price to fall short of. +#[test] +fn test_a_start_its_caller_cannot_pay_for_counts_none_of_its_forward() { + // Records that cost nothing leave no price to be short of, and records priced at a fraction of + // a gas may round to nothing. + if crate::common::history_is_free() || crate::common::history_rounds() { + return; + } + const MIDDLE: Address = address!("0000000000000000000000000000000000d00004"); + const OTHER: Address = address!("0000000000000000000000000000000000d00005"); + let price = |records| write_record_history_gas(records).expect("records have a price"); + let create = crate::salt::entry(GasId::create()); + let account = crate::salt::entry(GasId::create_state_gas()); + // `PUSH0` ×4, `PUSH1` of the value, `PUSH20 OTHER`, then `GAS` or a push of the forward. + let value_call = |scheme, forward: Option| { + let code = + BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]).push_number(1_u8); + let code = code.push_address(OTHER); + let code = match forward { + Some(forward) => code.push_number(forward), + None => code.append(GAS), + }; + code.append_many([scheme, STOP]).build() + }; + let value_call_charges = |pushed: bool| { + let push = if pushed { 3 } else { 2 }; + vec![2, 2, 2, 2, 3, 3, push, cold_access(), value_transfer()] + }; + /// A start `MIDDLE` makes: its code, its charges up to its forward, the price of the start's + /// records, the state gas it spills before its forward, and the gas it is given — `None` for + /// 50 times the price less one, which leaves it a fiftieth of what it holds a gas short. + struct Start { + name: &'static str, + code: Bytes, + charges: Vec, + price: u64, + spilled: u64, + given: Option, + } + let creation = |name, code: &[u8], charges| Start { + name, + code: BytecodeBuilder::default().append_many(code.iter().copied()).append(STOP).build(), + charges, + price: price(2), + spilled: account, + given: None, + }; + let mut rows = vec![ + Start { + name: "a value CALL", + code: value_call(CALL, None), + charges: value_call_charges(false), + price: price(2), + spilled: 0, + given: None, + }, + creation("a CREATE", &[PUSH0, PUSH0, PUSH0, CREATE], vec![2, 2, 2, create]), + creation("a CREATE2", &[PUSH0, PUSH0, PUSH0, PUSH0, CREATE2], vec![2, 2, 2, 2, create]), + ]; + // An explicit forward: `MIDDLE`, given its charges and 50 times the price less one, forwards + // all but 2 per cent of it, and keeps the price less one. + let charges = value_call_charges(true); + let given = charges.iter().sum::() + 50 * (price(2) - 1); + let forward = 49 * (price(2) - 1); + rows.push(Start { + name: "a value CALL forwarding one gas too many", + code: value_call(CALL, Some(forward)), + charges: charges.clone(), + price: price(2), + spilled: 0, + given: Some(given), + }); + + let run = |middle: Bytes, given: u64| { + let parent = op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(MIDDLE) + .push_number(given) + .append_many([CALL, POP]); + let db = MemoryDatabase::default() + .account_code(CONTRACT, spin(parent)) + .account_code(MIDDLE, middle) + .account_balance(MIDDLE, U256::from(1)) + .account_balance(OTHER, U256::from(1)); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + let called_other = evm + .inspector() + .calls + .iter() + .find(|call| call.target == OTHER) + .map(|call| (call.result, call.forward)); + (run, called_other) + }; + // After the read: its `POP`; the call to `MIDDLE` — `PUSH0` ×5, `PUSH20`, the push of the gas + // and the cold access; then what `MIDDLE` charged; then the `POP` of the status and the loop. + let left = |middle: &[u64]| { + Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 3, cold_access()]) + .then(middle) + .then(&[2]) + .spin(0) + .left(CAP) + }; + + for Start { name, code: middle, charges, price, spilled, given } in rows { + let spent: u64 = charges.iter().sum(); + let given = given.unwrap_or(50 * price - 1); + if given <= spent + spilled { + note_price_guard("a new account's state gas outweighs 50 times two records' history"); + continue; + } + let (run, called_other) = run(middle, given); + assert_eq!(called_other, None, "{name}: no frame started"); + assert_eq!(run.outcome.usage.write_records, 0, "{name}"); + // `MIDDLE` burned all it was given but its charges; the transaction computed those. + assert_stopped(&run, intrinsic(BELOW) + given - spent, left(&charges)); + } + + let (run, called_other) = run(value_call(CALL, Some(forward - 1)), given); + assert_eq!( + called_other, + Some((InstructionResult::Stop, forward - 1 + call_stipend())), + "one gas less forwarded, the frame starts, with the stipend on top" + ); + assert_stopped_with_stipends(&run, intrinsic(BELOW), left(&charges), call_stipend()); +} + /// A chain's caps must be below [`MAX_TX_COMPUTE_GAS`], the most compute a transaction can /// spend. The transaction that can spend it pays the least a frame that runs code can before its /// first instruction — a call to its own sender, which EIP-2780 charges its base cost alone, whose diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 39e1dc3dc..9ba20e682 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -9,11 +9,12 @@ //! [`test_the_history_ledger_is_what_satin_adds_to_every_transaction`] pins what that ledger is //! made of. One baseline case runs above the execution cap, because a transaction that has an //! EIP-8037 reservoir pays its history out of it, and a charge that is given back behind the -//! ledger's back shows up nowhere else. The six cases at the end are the ones that diverge for a +//! ledger's back shows up nowhere else. The seven cases at the end are the ones that diverge for a //! reason of their own — the //! system contract interceptors, keyless deployment, the system-address transaction, -//! the account a deposit creates for its sender, a crowded SALT bucket and the history ledger — -//! and they pin both sides, so a divergence is never silently absorbed. Later changes (the +//! the account a deposit creates for its sender, a crowded SALT bucket, a creation that destroys +//! itself and the history ledger — and they pin both sides, so a divergence is never silently +//! absorbed. Later changes (the //! limits) add their own. //! //! Every Satin transaction also reads the live system address when it is validated, which leaves @@ -40,39 +41,29 @@ use mega_evm::{ note_price_guard, op_transaction, take_system_address_read, transfer_log, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + MegaContext, MegaEvm, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use op_revm::{constants::BASE_FEE_RECIPIENT, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use op_revm::{constants::BASE_FEE_RECIPIENT, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{CALL, GAS, POP, PUSH0, PUSH1}, - context::{ - result::{ExecResultAndState, ExecutionResult}, - BlockEnv, CfgEnv, Context, ContextTr, TxEnv, - }, + context::{BlockEnv, CfgEnv, ContextTr, TxEnv}, context_interface::cfg::GasId, inspector::NoOpInspector, state::EvmState, - ExecuteEvm, Journal, + ExecuteEvm, }; -use crate::common::{ - account_state_gas, body_history, history, runs_at_measurement_prices, slot_state_gas, +use crate::{ + common::{ + account_state_gas, body_history, history, holding_to_keep, runs_at_measurement_prices, + slot_state_gas, + }, + op_reference::{self, Op, OpContext, Settled}, }; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); -type Outcome = ExecResultAndState, EvmState>; -type OpContext = Context< - BlockEnv, - OpTransaction, - CfgEnv, - MemoryDatabase, - Journal, - L1BlockInfo, ->; - fn block() -> BlockEnv { BlockEnv { number: U256::from(1), @@ -84,17 +75,18 @@ fn block() -> BlockEnv { /// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the /// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes — the `MegaEvm` one with its gas -/// by ledger — and that `CfgEnv`. -fn run_both(db: MemoryDatabase, tx: TxEnv) -> (MegaTransactionOutcome, Outcome, CfgEnv) { +/// by ledger, op-revm's with the reservoir it left ([`op_reference`](crate::op_reference)) — and +/// that `CfgEnv`. +fn run_both(db: MemoryDatabase, tx: TxEnv) -> (MegaTransactionOutcome, Settled, CfgEnv) { run_both_in(db, tx, block()) } /// Runs `tx` on `db` through op-revm's `OpEvm` alone, on the `CfgEnv` a `MegaEvm` context holds: /// for a gas limit that is op-revm's own, which Satin, charging the body's history on top, may /// refuse at validation. -fn run_op_alone(db: MemoryDatabase, tx: TxEnv) -> Outcome { +fn run_op_alone(db: MemoryDatabase, tx: TxEnv) -> Settled { let (_, mut op, _) = both_evms(db, block()); - op.transact(op_transaction(tx)).unwrap() + op_reference::transact(&mut op, op_transaction(tx)).unwrap() } /// [`run_both`] in `block`. @@ -102,10 +94,10 @@ fn run_both_in( db: MemoryDatabase, tx: TxEnv, block: BlockEnv, -) -> (MegaTransactionOutcome, Outcome, CfgEnv) { +) -> (MegaTransactionOutcome, Settled, CfgEnv) { let (mut mega, mut op, cfg) = both_evms(db, block); let mega_outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); - let op_outcome = op.transact(op_transaction(tx)).unwrap(); + let op_outcome = op_reference::transact(&mut op, op_transaction(tx)).unwrap(); (mega_outcome, op_outcome, cfg) } @@ -113,7 +105,7 @@ fn run_both_in( fn both_evms( db: MemoryDatabase, block: BlockEnv, -) -> (MegaEvm, OpEvm, CfgEnv) { +) -> (MegaEvm, Op, CfgEnv) { let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) .with_block(block.clone()) .with_chain(zero_fee_l1_block_info()); @@ -127,8 +119,8 @@ fn both_evms( /// Asserts the two outcomes agree on everything but the history gas Satin charges: `mega` spends /// exactly its history ledger more than `op` and nothing else moves. The whole `ResultGas` is -/// compared against op-revm's with the two fields history touches rebuilt, so a field added later -/// is covered too. +/// compared against op-revm's with the field history touches rebuilt, so a field added later is +/// covered too, and the reservoir each left, which the result does not carry, beside it. /// /// The reservoir pays history first and the regular budget pays what it cannot, which is why the /// reservoir left over saturates at zero rather than going negative. @@ -144,7 +136,7 @@ fn both_evms( /// The state is compared with the read of the live system address taken out, which holds because /// these transactions carry no gas price: a priced transaction pays the extra gas out of the /// sender's balance ([`test_fees_match_op_revm`]). -fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { +fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Settled) { let history = mega.gas.history; assert!(history >= body_history(0), "every Satin transaction pays for its own body"); let (m, o) = (mega.result.gas(), op.result.gas()); @@ -154,16 +146,13 @@ fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { assert!(m.inner_refunded() >= o.inner_refunded(), "refund"); assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); assert_eq!( - m.reservoir_remaining(), - o.reservoir_remaining().saturating_sub(history), + mega.gas.reservoir_remaining, + op.reservoir_remaining.saturating_sub(history), "reservoir remaining" ); assert_eq!( m, - &(*o) - .with_total_gas_spent(o.total_gas_spent() + history) - .with_reservoir_remaining(o.reservoir_remaining().saturating_sub(history)) - .with_refunded(m.inner_refunded()), + &(*o).with_total_gas_spent(o.total_gas_spent() + history).with_refunded(m.inner_refunded()), "ResultGas" ); assert_eq!(mega.result.logs(), op.result.logs(), "logs"); @@ -182,13 +171,13 @@ fn but_the_system_address_read(state: &EvmState) -> EvmState { /// Asserts the two outcomes agree field by field, then as a whole so a field added later is /// covered too. For the paths that charge no history: a system call, which the protocol pays /// nothing for. -fn assert_same(mega: &Outcome, op: &Outcome) { +fn assert_same(mega: &Settled, op: &Settled) { let (m, o) = (mega.result.gas(), op.result.gas()); assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); - assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(mega.reservoir_remaining, op.reservoir_remaining, "reservoir remaining"); assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); assert_eq!(m, o, "ResultGas"); assert_eq!(mega.result.logs(), op.result.logs(), "logs"); @@ -197,10 +186,10 @@ fn assert_same(mega: &Outcome, op: &Outcome) { } /// Both engines run on the Satin configuration: Karst on the Satin gas schedule, EIP-8037, -/// EIP-2780 and EIP-7708 switched on, the 200M execution cap, `MegaETH`'s code-size limits, and a -/// system call's gas above 30M in its reservoir. So op-revm journals the same transfer logs, and -/// the logs of the two are compared as they are, and op-revm splits a system call's gas as Satin -/// does. +/// EIP-2780 and EIP-7708 switched on, the 200M execution cap and `MegaETH`'s code-size limits. So +/// op-revm journals the same transfer logs, and the logs of the two are compared as they are. A +/// system call's split is no configuration: op-revm runs one through the reference handler, which +/// splits its gas as Satin's does ([`op_reference`](crate::op_reference)). fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.spec, OpSpecId::KARST); assert_eq!(cfg.gas_params.table(), satin_gas_params().table()); @@ -211,7 +200,6 @@ fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.limit_contract_initcode_size, Some(MAX_INITCODE_SIZE)); assert!(cfg.enable_amsterdam_eip7708); assert!(!cfg.amsterdam_eip7708_disabled); - assert!(cfg.system_call_state_gas_margin_in_reservoir); } #[test] @@ -230,11 +218,11 @@ fn test_empty_transaction_matches_op_revm() { assert_satin_cfg(&cfg); assert!(mega.result.is_success()); assert_eq!( - mega.result.gas().reservoir_remaining(), + mega.gas.reservoir_remaining, reservoir - mega.gas.history, "the reservoir paid for the body", ); - assert_eq!(op.result.gas().reservoir_remaining(), reservoir, "op-revm has nothing to pay"); + assert_eq!(op.reservoir_remaining, reservoir, "op-revm has nothing to pay"); assert_same_but_history(&mega, &op); } @@ -444,18 +432,27 @@ fn test_refund_matches_op_revm() { /// fresh slot it writes is paid out of the reservoir, and what is left of it is reported. #[test] fn test_system_call_matches_op_revm() { - use revm::handler::{ - system_call::SystemCallEvm, SYSTEM_CALL_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT, - }; + use mega_evm::SYSTEM_CALL_REGULAR_GAS_LIMIT; + use revm::handler::system_call::{SystemCallEvm, SYSTEM_CALL_GAS_LIMIT}; let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(3)).stop().build(); let (mut mega, mut op, cfg) = both_evms(MemoryDatabase::default().account_code(CALLEE, code), block()); assert_satin_cfg(&cfg); - let mega_outcome = mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); - let op_outcome = op.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + let result_and_state = + mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let mega_outcome = Settled { result_and_state, reservoir_remaining }; + let op_outcome = op_reference::system_call( + &mut op, + CALLER, + CALLEE, + Default::default(), + SYSTEM_CALL_GAS_LIMIT, + ) + .unwrap(); assert!(mega_outcome.result.is_success()); assert_eq!( - mega_outcome.result.gas().reservoir_remaining(), + mega_outcome.reservoir_remaining, SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - satin_gas_params().get(GasId::sstore_set_state_gas()), @@ -785,6 +782,47 @@ fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); } +/// A contract whose constructor destroys the account it is creating: Satin's destruction table +/// gives back what the transaction made of an account its first effective destruction removes — +/// here the new account's state gas, and its write record with the record's history — where +/// EIP-8037, which op-revm runs, gives back nothing for this destruction. Everything else the two +/// engines do is the same, so beside the history ledger the whole difference is the account's state +/// gas. +#[test] +fn test_a_creation_that_destroys_itself_diverges_from_op_revm() { + use revm::bytecode::opcode::{ADDRESS, SELFDESTRUCT}; + + let code = + BytecodeBuilder::default().create(U256::ZERO, [ADDRESS, SELFDESTRUCT]).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + // The `CREATE` pays the history of its two records out of the 2 per cent it keeps. + let gas_limit = 1_000_000 + + account_state_gas() + + body_history(0) + + holding_to_keep(history(2 * WRITE_RECORD_SIZE)); + let tx = TxEnv { caller: CALLER, kind: TxKind::Call(CALLEE), gas_limit, ..Default::default() }; + let (mega, op, cfg) = run_both(db, tx); + assert_satin_cfg(&cfg); + assert!(mega.result.is_success() && op.result.is_success(), "{:?}", mega.result); + assert!(but_the_system_address_read(&mega.state)[&CALLEE.create(0)].is_selfdestructed()); + + // The one difference, and its exact size. + let (m, o) = (mega.result.gas(), op.result.gas()); + assert_eq!(o.state_gas_spent_final(), account_state_gas(), "op-revm keeps the account's"); + assert_eq!(m.state_gas_spent_final(), 0, "Satin gives it back"); + assert_eq!( + m.total_gas_spent() + account_state_gas(), + o.total_gas_spent() + mega.gas.history, + "beside the history ledger, the state gas given back is the whole difference", + ); + // The history ledger keeps the body and the creator's record; the created account's record + // went with the account. + assert_eq!(mega.gas.history, body_history(0) + history(WRITE_RECORD_SIZE)); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result.output(), op.result.output(), "output"); + assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); +} + /// A transaction that runs out of gas in the runtime gas phase, before its first frame — here on /// EIP-2780's charge for the account its value creates — burns its whole gas limit on both /// engines and keeps nothing but its sender's nonce: no reservoir comes back from a transaction @@ -823,13 +861,14 @@ fn test_an_out_of_gas_before_the_first_frame_matches_op_revm() { let (mega, _, cfg) = run_both(db(), transfer(mega_limit)); let op = run_op_alone(db(), transfer(op_limit)); assert_satin_cfg(&cfg); - for (engine, result, gas_limit) in - [("Satin", &mega.result, mega_limit), ("op-revm", &op.result, op_limit)] - { + for (engine, result, reservoir, gas_limit) in [ + ("Satin", &mega.result, mega.gas.reservoir_remaining, mega_limit), + ("op-revm", &op.result, op.reservoir_remaining, op_limit), + ] { assert!(result.is_halt(), "{engine}: {result:?}"); let gas = result.gas(); assert_eq!(gas.total_gas_spent(), gas_limit, "{engine}: the whole gas limit burns"); - assert_eq!(gas.reservoir_remaining(), 0, "{engine}: no reservoir comes back"); + assert_eq!(reservoir, 0, "{engine}: no reservoir comes back"); assert_eq!(gas.tx_gas_used(), gas_limit, "{engine}: the receipt bills the gas limit"); } assert_eq!(mega.gas.history, body_history(0), "the history ledger reads the body"); @@ -879,16 +918,17 @@ fn test_an_out_of_gas_creation_before_the_first_frame_matches_op_revm() { let (mega, _, cfg) = run_both(db(), creation(mega_limit)); let op = run_op_alone(db(), creation(op_limit)); assert_satin_cfg(&cfg); - for (engine, result, gas_limit) in - [("Satin", &mega.result, mega_limit), ("op-revm", &op.result, op_limit)] - { + for (engine, result, reservoir, gas_limit) in [ + ("Satin", &mega.result, mega.gas.reservoir_remaining, mega_limit), + ("op-revm", &op.result, op.reservoir_remaining, op_limit), + ] { assert!(result.is_halt(), "{engine}: {result:?}"); assert_eq!( result.gas().total_gas_spent(), gas_limit, "{engine}: the whole gas limit burns" ); - assert_eq!(result.gas().reservoir_remaining(), 0, "{engine}: no reservoir comes back"); + assert_eq!(reservoir, 0, "{engine}: no reservoir comes back"); } assert_eq!(mega.gas.history, body_history(init_code.len() as u64), "the ledger reads the body"); // op-revm reaches the charge for the created account and loads its address; Satin falls short diff --git a/crates/mega-evm/tests/satin/failed_deposit.rs b/crates/mega-evm/tests/satin/failed_deposit.rs index 34fed03a6..c5771e264 100644 --- a/crates/mega-evm/tests/satin/failed_deposit.rs +++ b/crates/mega-evm/tests/satin/failed_deposit.rs @@ -22,7 +22,7 @@ use revm::{ context::{result::ExecutionResult, TxEnv}, }; -use crate::common::{account_state_gas, block, call, context}; +use crate::common::{account_state_gas, block, call, context, grown}; const CALLER: Address = address!("0000000000000000000000000000000000f00000"); const CALLEE: Address = address!("0000000000000000000000000000000000f00001"); @@ -65,7 +65,7 @@ fn test_a_system_deposit_over_the_limit_reports_the_failed_deposit() { ); assert_eq!(outcome.gas.gas_used, 100_000, "a failed deposit bills its gas limit"); assert_eq!(outcome.limit_exceeded, None, "the halt is what the deposit reports"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.state[&CALLER].info.nonce, 1, "a failed deposit bumps its sender's nonce"); } @@ -108,7 +108,11 @@ fn test_a_deposit_whose_body_is_over_the_limit_is_a_failed_deposit() { ); assert_eq!(outcome.gas.gas_used, 100_000, "{case}: a failed deposit bills its gas limit"); assert_eq!(outcome.limit_exceeded, None, "{case}: the failure is what it reports"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{case}" + ); assert_eq!(outcome.state[&CALLER].info.nonce, 1, "{case}: the sender's nonce is bumped"); } } @@ -144,7 +148,7 @@ fn test_a_deposit_over_the_limit_fails_at_every_gas_limit() { const INTRINSIC: u64 = 12_000 + 3_000; const MINT: u64 = 7; let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); - let body = LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }; + let body = LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }; let run = |sender: Address, gas_limit: u64, system: bool| { let mut tx = op_transaction(TxEnv { caller: sender, @@ -193,13 +197,61 @@ fn test_a_deposit_over_the_limit_fails_at_every_gas_limit() { (gas_limit, 0, 0), "{row}: all of it regular gas" ); - assert_eq!(outcome.usage, body, "{row}: the body stays counted"); + let created = u64::from(sender == ABSENT); + assert_eq!( + outcome.usage, + grown(body, created), + "{row}: the body stays counted, and an absent sender's new account is state growth" + ); let sender = &outcome.state[&sender].info; assert_eq!(sender.nonce, 1, "{row}: the sender's nonce is bumped"); assert_eq!(sender.balance, U256::from(balance_before + MINT), "{row}: the mint"); } } +/// A failed deposit whose sender had no account creates it, as its nonce bump and mint stand: one +/// account of state growth, which the transaction reports and its block counts, with no state gas +/// for it on any ledger. The deposit has already failed, so no limit stops it, a state-growth limit +/// of nothing included. A sender that had an account adds nothing. +#[test] +fn test_a_failed_deposit_counts_the_caller_it_creates() { + const INTRINSIC: u64 = 12_000 + 3_000; + let run = |sender: Address, limits: EvmTxRuntimeLimits| { + let mut tx = op_transaction(TxEnv { + caller: sender, + kind: TxKind::Call(CALLEE), + gas_limit: INTRINSIC - 1, + ..Default::default() + }); + tx.deposit.source_hash = B256::repeat_byte(0x22); + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1)); + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(OpTx(tx)) + .expect("the deposit is included") + }; + let unlimited = EvmTxRuntimeLimits::no_limits(); + let none_left = unlimited.with_tx_state_growth_limit(0); + for (case, sender, limits, created) in [ + ("an absent sender", ABSENT, unlimited, 1), + ("an absent sender under a limit of nothing", ABSENT, none_left, 1), + ("a sender with an account", CALLER, unlimited, 0), + ] { + let outcome = run(sender, limits); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{case}: {:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None, "{case}: no stop"); + assert_eq!(outcome.usage.state_growth, created, "{case}"); + assert_eq!(outcome.gas.state, 0, "{case}: no state gas for the account"); + assert_eq!(outcome.state[&sender].info.nonce, 1, "{case}: the account exists"); + } +} + /// Runs `tx` against a callee that sends the Oracle a hint of `payload` and then halts on /// `INVALID`, and returns the outcome with the number of hints the oracle service received. fn run_hint_then_halt(tx: MegaTransaction, payload: &[u8]) -> (MegaTransactionOutcome, usize) { @@ -253,6 +305,7 @@ fn test_a_failed_deposit_keeps_the_hints_it_forwarded() { let kept = LimitUsage { data_size: mega_evm::transaction_body_bytes(&deposit) + payload.len() as u64, write_records: 0, + state_growth: 0, }; let (outcome, hints) = run_hint_then_halt(deposit, &payload); diff --git a/crates/mega-evm/tests/satin/gas_forward.rs b/crates/mega-evm/tests/satin/gas_forward.rs new file mode 100644 index 000000000..11d4f8cfc --- /dev/null +++ b/crates/mega-evm/tests/satin/gas_forward.rs @@ -0,0 +1,276 @@ +//! The regular gas a call or creation forwards: at most +//! `parent_remaining − parent_remaining × 2 / 100` of what its caller has left after the charges +//! the opcode makes before the forward, Rex6's rule in place of EIP-150's 63/64. A value call's +//! 2,300 stipend joins the forward after the cap and is not taken from the caller; a creation +//! forwards the cap and adds none. +//! +//! An inspector reads the caller's regular gas at the end of the opcode that starts a frame — +//! after the forward is taken, before the frame runs — and the forward off the frame's input, so +//! what the caller had at the forward is the two added up. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, POP, PUSH0, PUSH20, STATICCALL, STOP, + }, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{ + account_state_gas, body_history, call, context, forward_cap, history, holding_to_keep, +}; + +const SENDER: Address = address!("0000000000000000000000000000000000730000"); +const A: Address = address!("0000000000000000000000000000000000730001"); +const B: Address = address!("0000000000000000000000000000000000730002"); + +/// The value call's stipend. +const STIPEND: u64 = 2_300; + +/// One frame start seen by [`Forwards`]: the opcode, the caller's regular gas once the opcode took +/// the forward, and the gas limit of the frame it starts. +#[derive(Clone, Copy, Debug)] +struct Start { + opcode: u8, + kept: u64, + gas_limit: u64, +} + +/// Records every frame start of the transaction's own frame: the opcode that made it, the regular +/// gas that frame kept, and the frame's gas limit. +#[derive(Default)] +struct Forwards { + opcode: Option, + kept: u64, + starts: Vec, +} + +impl Inspector, EthInterpreter> for Forwards { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.opcode = Some(interp.bytecode.opcode()); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.kept = interp.gas.remaining(); + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if let Some(opcode) = self.opcode.take() { + self.starts.push(Start { opcode, kept: self.kept, gas_limit: inputs.gas_limit }); + } + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + if let Some(opcode) = self.opcode.take() { + self.starts.push(Start { opcode, kept: self.kept, gas_limit: inputs.gas_limit() }); + } + None + } +} + +/// `A` starts one frame with `opcode`, asking for all its gas, and stops; `B` stops. A call carries +/// `value`, a creation's init code is a `STOP`. +fn starting(opcode: u8, value: u64) -> MemoryDatabase { + let code = match opcode { + CREATE => BytecodeBuilder::default().create(U256::ZERO, [STOP]).append(POP), + CREATE2 => BytecodeBuilder::default().create2(U256::ZERO, [STOP], U256::ZERO).append(POP), + CALL | CALLCODE => { + let code = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + code.push_number(value).append(PUSH20).append_many(B.into_array()).append_many([ + revm::bytecode::opcode::GAS, + opcode, + POP, + ]) + } + _ => BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]) + .append_many(B.into_array()) + .append_many([revm::bytecode::opcode::GAS, opcode, POP]), + }; + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(A, U256::from(1)) + .account_code(A, code.stop().build()) + .account_code(B, Bytes::from_static(&[STOP])) +} + +/// The one start `A` makes with `opcode` at `gas_limit`. +fn start_of(opcode: u8, value: u64, gas_limit: u64) -> Start { + let mut evm = + MegaEvm::new(context(starting(opcode, value))).with_inspector(Forwards::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{opcode:#04x}: {:?}", outcome.result); + let [start] = evm.inspector().starts[..] else { + panic!("{opcode:#04x}: one start: {:?}", evm.inspector().starts) + }; + assert_eq!(start.opcode, opcode); + start +} + +/// Each of the six opcodes, asking for all its gas, forwards all but 2 per cent of what its caller +/// has left, and the caller keeps the 2 per cent; a value call's child gets the stipend on top, +/// which the caller does not pay. Below and above the execution cap alike. A creation's start +/// charges the history of its two records — the created account and the creator's nonce — after +/// the forward, which spills onto the caller's regular gas where there is no reservoir; above the +/// cap the reservoir pays it, as it pays a value call's, so the caller's regular gas is the +/// forward's alone. +#[test] +fn test_a_start_forwards_all_but_two_percent_of_its_callers_regular_gas() { + // The smallest tier holds, below the cap, the body's history and the created account's state + // gas before the forward, and fifty times the records' history after it, which the 2 per cent + // kept must pay, with a million to spare. + let small = account_state_gas() + + body_history(0) + + holding_to_keep(history(2 * WRITE_RECORD_SIZE)) + + 1_000_000; + for gas_limit in [small, 30_000_000.max(small), TX_GAS_LIMIT_CAP + 10_000_000] { + for (opcode, value) in [ + (CALL, 0), + (CALLCODE, 0), + (DELEGATECALL, 0), + (STATICCALL, 0), + (CREATE, 0), + (CREATE2, 0), + ] { + let Start { kept, gas_limit: forwarded, .. } = start_of(opcode, value, gas_limit); + let creation = matches!(opcode, CREATE | CREATE2); + let records = if creation && gas_limit <= TX_GAS_LIMIT_CAP { + history(2 * WRITE_RECORD_SIZE) + } else { + 0 + }; + let had = kept + records + forwarded; + assert_eq!(forwarded, forward_cap(had), "{opcode:#04x} at {gas_limit}"); + assert_eq!( + kept + records, + had * 2 / 100, + "{opcode:#04x} at {gas_limit}: the caller keeps 2%" + ); + } + } + let above = TX_GAS_LIMIT_CAP + 10_000_000; + for opcode in [CALL, CALLCODE] { + let Start { kept, gas_limit, .. } = start_of(opcode, 1, above); + let forwarded = gas_limit - STIPEND; + let had = kept + forwarded; + assert_eq!(forwarded, forward_cap(had), "{opcode:#04x} with value"); + assert_eq!( + kept, + had * 2 / 100, + "{opcode:#04x} with value: the stipend is not the caller's" + ); + } +} + +/// The spec's worked example: a value call whose caller has 10,000 regular gas left after the +/// transfer's charge forwards a cap of 9,800, so its child gets 12,100 and the caller keeps 200; +/// EIP-150 would have forwarded 9,844. +#[test] +fn test_a_value_call_with_ten_thousand_left_forwards_9800_and_its_child_gets_12100() { + assert_eq!(forward_cap(10_000), 9_800); + assert_eq!(forward_cap(10_000) + STIPEND, 12_100); + assert_eq!(10_000 - forward_cap(10_000), 200); + assert_eq!(10_000 - 10_000 / 64, 9_844); + for kept in [0, 1, 7_039] { + let held = holding_to_keep(kept); + assert_eq!(held - forward_cap(held), kept, "{held} keeps {kept}"); + assert_eq!(held + 1 - forward_cap(held + 1), kept + 1, "one gas more keeps one more"); + } +} + +/// The regular gas a frame holds as its call or creation starts, before the opcode's charges, and +/// what it forwards. +#[derive(Default)] +struct Held { + held: Option, + forwarded: Option, +} + +impl Inspector, EthInterpreter> for Held { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if matches!(interp.bytecode.opcode(), CALL | CREATE) { + self.held = Some(interp.gas.remaining()); + } + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if inputs.target_address == B { + self.forwarded = Some(inputs.gas_limit); + } + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.forwarded = Some(inputs.gas_limit()); + None + } +} + +/// Runs `A` holding `code` above the execution cap, where the reservoir pays every state and +/// history charge, and returns the regular gas held at the opcode and the gas forwarded. +fn held_and_forwarded(code: Bytes) -> (u64, u64) { + let db = MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(B, U256::from(1)) + .account_code(A, code); + let mut evm = MegaEvm::new(context(db)).with_inspector(Held::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, 5 * TX_GAS_LIMIT_CAP)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let held = evm.inspector(); + (held.held.expect("the opcode ran"), held.forwarded.expect("a frame started")) +} + +/// A `CALL` given all the gas forwards all but 2 per cent of what its caller holds once the call's +/// own charge — the cold access to its target — is paid. +#[test] +fn test_a_call_forwards_all_but_two_percent_of_what_its_charge_leaves() { + let params = mega_evm::satin_gas_params(); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]) + .append_many(B.into_array()) + .append_many([revm::bytecode::opcode::GAS, CALL, STOP]) + .build(); + let (held, forwarded) = held_and_forwarded(code); + let access = params.get(GasId::warm_storage_read_cost()) + + params.get(GasId::cold_account_additional_cost()); + let left = held - access; + assert_eq!(forwarded, forward_cap(left)); +} + +/// A `CREATE` forwards all but 2 per cent of what its creator holds once the creation's own +/// charges — the `create` entry, EIP-3860's word and the memory the init code occupies — are paid; +/// the created account's state gas comes out of the reservoir. +#[test] +fn test_a_creation_forwards_all_but_two_percent_of_what_its_charges_leave() { + let params = mega_evm::satin_gas_params(); + let code = BytecodeBuilder::default() + .push_number(10_u8) + .append_many([PUSH0, PUSH0, CREATE, STOP]) + .build(); + let (held, forwarded) = held_and_forwarded(code); + let left = held - params.get(GasId::create()) - params.get(GasId::initcode_per_word()) - 3; + assert_eq!(forwarded, forward_cap(left)); +} diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/history_allowance.rs similarity index 87% rename from crates/mega-evm/tests/satin/storage_call_stipend.rs rename to crates/mega-evm/tests/satin/history_allowance.rs index 0629017e7..270d00cbb 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -22,13 +22,14 @@ use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolCall; use mega_evm::{ constants::COST_PER_HISTORY_BYTE, - storage_call_stipend, + history_allowance_gas, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, test_utils::{ is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, }, EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, - STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + HISTORY_ALLOWANCE_BYTES, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use revm::bytecode::opcode::{ ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, @@ -116,8 +117,8 @@ fn test_the_allowance_is_one_three_topic_event_of_history() { if runs_at_measurement_prices() { return; } - assert_eq!(STORAGE_CALL_STIPEND_BYTES, 160); - assert_eq!(storage_call_stipend(), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); + assert_eq!(history_allowance_gas(), 160 * COST_PER_HISTORY_BYTE); } /// The boundary the allowance exists for: a `transfer()` — 2,300 gas and nothing else — reaches a @@ -253,7 +254,7 @@ fn test_the_allowance_cannot_be_spent_on_computation() { if !the_allowance_outweighs_a_record() { return; } - assert_eq!(storage_call_stipend(), allowance(), "the allowance the engine grants"); + assert_eq!(history_allowance_gas(), allowance(), "the allowance the engine grants"); let turns: u16 = 200; let cost = countdown_gas(u64::from(turns)); @@ -275,6 +276,59 @@ fn test_the_allowance_cannot_be_spent_on_computation() { assert_eq!((allowance(), record_history()), (14_080, 3_520), "160 and 40 bytes at 88 gas"); } +/// The hook's three-topic event over `len` bytes of memory: `PUSH1 3; PUSH1 2; PUSH1 1; PUSH2 len; +/// PUSH0; LOG3; STOP`. +fn event_over(len: u16) -> Bytes { + let [high, low] = len.to_be_bytes(); + Bytes::from(vec![PUSH1, 3, PUSH1, 2, PUSH1, 1, PUSH2, high, low, PUSH0, LOG3, STOP]) +} + +/// What [`event_over`] computes, by hand from the opcode prices: the four pushes, 3 each, and +/// `PUSH0`, 2; `LOG3`'s 375, 375 a topic and 8 a byte of data; and the memory it expands, 3 a word +/// and the square of the words over 512. +const fn event_over_gas(len: u64) -> u64 { + let words = len.div_ceil(32); + 4 * 3 + 2 + 375 + 3 * 375 + 8 * len + 3 * words + words * words / 512 +} + +/// An event larger than the allowance draws the whole allowance and pays the rest out of the +/// frame's gas: a hook given its computation and one gas less than that rest runs out of gas on +/// the history charge, after the allowance paid its part, and keeps no event; given the rest in +/// full it keeps the event, and the transaction pays that rest beside the transfer's records. +/// +/// Expected values `independent`: the hook's computation is summed by hand from the opcode prices, +/// and the two runs are the control that the sum is its whole cost; the event's bytes are its +/// address, its three topics and its data, and the rest is their history less the allowance's 160 +/// bytes, at the cost per history byte in effect (`constants`). +#[test] +fn test_an_event_larger_than_the_allowance_pays_the_rest_or_runs_out_of_gas() { + if !the_allowance_outweighs_a_record() { + return; + } + let len = 1_024; + let computation = event_over_gas(u64::from(len)); + let rest = history(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + u64::from(len)) - allowance(); + + let short = run_hook(event_over(len), computation + rest - 1, U256::ZERO); + assert!(!transfer_succeeded(&short), "one gas short of the rest is out of gas"); + assert!(events(&short).is_empty(), "the hook kept no event"); + assert_eq!(short.gas.history, body_history(0), "the failed hook's transfer records came back"); + + let exact = run_hook(event_over(len), computation + rest, U256::ZERO); + assert!(transfer_succeeded(&exact), "the rest in full is enough"); + assert_eq!(events(&exact).len(), 1, "the hook kept its event"); + assert_eq!( + exact.gas.history, + body_history(0) + 2 * record_history() + rest, + "the transfer's two records and the rest of the event; the allowance's part is on no ledger", + ); + + if runs_at_measurement_prices() { + return; + } + assert_eq!((computation, rest), (9_804, (1_152 - 160) * 88)); +} + /// The hook's `SSTORE(0, 2)`: `PUSH1 2; PUSH0; SSTORE; STOP`. fn writes_slot_zero() -> Bytes { Bytes::from(vec![PUSH1, 2, PUSH0, SSTORE, STOP]) @@ -386,7 +440,7 @@ fn test_a_top_level_transfer_gets_no_allowance() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( outcome.gas.history, - body() + record() + STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE, + body() + record() + HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE, "the body, the recipient's record, and the event the transaction paid for itself", ); } @@ -401,7 +455,7 @@ fn test_a_call_without_value_gets_no_allowance() { let receiver = event().append(STOP).build(); let with_value = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); let without = call_with(CALL, RECEIVER, 0, 1_000_000).append(STOP).build(); - let event_history = STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE; + let event_history = HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE; let paid = execute(db(without, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); let granted = execute(db(with_value, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); @@ -412,8 +466,8 @@ fn test_a_call_without_value_gets_no_allowance() { } /// `CALLCODE` transfers value and is granted one; `DELEGATECALL` carries none and is not. -/// `CALLCODE` runs the callee's code in the caller's own account, so its transfer writes one -/// account rather than two. +/// `CALLCODE` runs the callee's code in the caller's own account, so its transfer moves the value +/// from the calling account to itself and writes no account at all. /// /// `STATICCALL` carries no value either, and a static frame may not emit a log at all, so there /// is nothing an allowance could buy it. @@ -423,7 +477,7 @@ fn test_callcode_is_granted_one_and_delegatecall_is_not() { return; } let receiver = event().append(STOP).build(); - let event_history = STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE; + let event_history = HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE; let at = |scheme, value| { let sender = call_with(scheme, RECEIVER, value, 1_000_000).append(STOP).build(); execute(db(sender, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) @@ -431,7 +485,7 @@ fn test_callcode_is_granted_one_and_delegatecall_is_not() { let call_code = at(CALLCODE, 1); assert!(call_code.result.is_success(), "{:?}", call_code.result); - assert_eq!(call_code.gas.history, body() + record(), "one record, and the allowance paid"); + assert_eq!(call_code.gas.history, body(), "no record, and the allowance paid for the event"); let delegate = at(DELEGATECALL, 0); assert!(delegate.result.is_success(), "{:?}", delegate.result); @@ -478,7 +532,7 @@ fn test_an_intercepted_call_neither_takes_nor_adds_an_allowance() { // Enough for the intercepted call and the event's computation, and far below the event's // history, which only the allowance can cover. const FORWARDED: u64 = 8_000; - assert!(FORWARDED < storage_call_stipend(), "the event's history must need the allowance"); + assert!(FORWARDED < history_allowance_gas(), "the event's history must need the allowance"); let sender = call_with(CALL, RECEIVER, 1, FORWARDED).append(STOP).build(); let with_controls = |receiver: Bytes| { db(sender.clone(), receiver) @@ -553,7 +607,7 @@ fn test_a_transaction_level_stop_does_not_hand_the_allowance_back() { ); assert!(spent.gas.gas_used > unspent.gas.gas_used, "the event still costs what it computes"); assert!( - spent.gas.gas_used - unspent.gas.gas_used < storage_call_stipend(), + spent.gas.gas_used - unspent.gas.gas_used < history_allowance_gas(), "and nothing like what its history costs", ); } @@ -584,8 +638,8 @@ fn test_an_unspent_allowance_does_not_return_to_the_caller() { /// A chain of value transfers grants each frame its own allowance, and one frame's spending is /// not another's: three frames each emit their event and the transaction pays for none of them. /// -/// The allowances are on the frames' lanes, which the frame lifecycle keeps aligned with the -/// frames themselves, so a chain cannot draw on an allowance granted further up. +/// An allowance is on the gas tracker of the frame it was granted to, and a child is granted its +/// own rather than handed its caller's, so a chain cannot draw on an allowance granted further up. #[test] fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { if runs_at_measurement_prices() { @@ -612,10 +666,11 @@ fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { assert_eq!(events(&outcome).len(), 2, "both hops emitted their event"); assert_eq!(outcome.result.logs().len(), 4, "beside the two transfers' logs"); // The first transfer writes the sender's account and the middle one's; the second writes the - // receiver's, the middle account being recorded already by the value it received. + // receiver's and returns the middle account to what the transaction loaded, taking its record + // back: the middle hop passed on exactly the wei it received. assert_eq!( outcome.gas.history, - body() + 3 * record(), + body() + 2 * record(), "the transfers' account writes, and no event on any ledger", ); } @@ -656,8 +711,8 @@ fn self_calling_loop() -> Bytes { /// /// The allowance is drawn before the frame's own gas rather than after it, so it is a discount on /// the first 160 bytes of every value-transferring call rather than a fallback for a frame that -/// cannot pay. A contract that calls itself pays its own account's record once and nothing after -/// that, so the grant is repeatable for as long as the transaction's gas lasts: the loop below +/// cannot pay. A contract that calls itself moves nothing and pays for no record at all, so the +/// grant is repeatable for as long as the transaction's gas lasts: the loop below /// costs about 10,000 gas a turn, which is some twenty thousand turns inside one transaction at /// the execution cap — around three megabytes of log bytes, and close to 280,000,000 of history /// gas, on no gas ledger. @@ -679,29 +734,29 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.result.logs().len(), GRANTS as usize, "every frame emitted its event"); - // A self-call writes no recipient, and the caller's own account is written once, so the whole - // loop leaves one record behind. - assert_eq!(outcome.usage.write_records, 1); + // A self-call moves the value from the calling account to itself: no account changes, so the + // whole loop leaves no record behind. + assert_eq!(outcome.usage.write_records, 0); assert_eq!( outcome.usage.data_size, - TX_BODY_SIZE + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, - "the body, the record and every event's bytes are counted", + TX_BODY_SIZE + GRANTS * HISTORY_ALLOWANCE_BYTES, + "the body and every event's bytes are counted", ); assert_eq!( outcome.gas.history, - body() + record(), - "and the history gas is the body and that one record: no event is on it", + body(), + "and the history gas is the body alone: no event is on it", ); assert_eq!( outcome.gas.history_bytes, - TX_BODY_SIZE + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, + TX_BODY_SIZE + GRANTS * HISTORY_ALLOWANCE_BYTES, "the byte column has every event on it", ); let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE; assert_eq!( outcome.gas.history_bytes - bytes_paid_for, - GRANTS * STORAGE_CALL_STIPEND_BYTES, + GRANTS * HISTORY_ALLOWANCE_BYTES, "one allowance per value call, and every one of them off the gas ledger", ); } @@ -721,9 +776,7 @@ fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { let sender = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(500); let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; - assert!( - start + STORAGE_CALL_STIPEND_BYTES <= 490 && start + 2 * STORAGE_CALL_STIPEND_BYTES > 490 - ); + assert!(start + HISTORY_ALLOWANCE_BYTES <= 490 && start + 2 * HISTORY_ALLOWANCE_BYTES > 490); let spent = run_limited( db(sender.clone(), receiver), @@ -744,7 +797,7 @@ fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { // is the whole of the difference: no allowance came back with either. assert!(spent.gas.regular > quiet.gas.regular, "the events still cost what they compute"); assert!( - spent.gas.regular - quiet.gas.regular < storage_call_stipend(), + spent.gas.regular - quiet.gas.regular < history_allowance_gas(), "and the difference is that computation, not an allowance", ); } @@ -774,7 +827,7 @@ fn test_a_drained_allowance_is_not_refunded_by_a_revert() { "the caller pays for the event's computation and gets no allowance back", ); assert!( - drained.gas.gas_used - quiet.gas.gas_used < storage_call_stipend(), + drained.gas.gas_used - quiet.gas.gas_used < history_allowance_gas(), "and the difference is that computation, not an allowance", ); } diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 4bf3bce20..62dc80525 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -21,7 +21,7 @@ use mega_evm::{ test_utils::{is_transfer_log, op_transaction, BytecodeBuilder, MemoryDatabase}, untouched_create_gas, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, - LOG_BASE_SIZE, LOG_TOPIC_SIZE, STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + HISTORY_ALLOWANCE_BYTES, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ @@ -240,9 +240,11 @@ impl Inspector, EthInterpreter> for AnswersCreations } } -/// A creation answered without running deposits nothing, whatever the answer's output: the bytes -/// the transaction reports are what the history ledger charged for, and the charge its caller made -/// for the creation's records comes back with the creation that never made them. +/// A creation answered without running deposits nothing, whatever the answer's output: no byte of +/// code is counted. The answer is taken as given, as revm takes it: no record is counted, the +/// creator's nonce never having been bumped, and what the `CREATE` was charged for the records its +/// start would make stays charged, so the history ledger carries both records beyond the bytes the +/// transaction reports. #[test] fn test_a_creation_answered_without_running_appends_no_code() { if runs_at_measurement_prices() { @@ -256,9 +258,13 @@ fn test_a_creation_answered_without_running_appends_no_code() { .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage.write_records, 0, "the creation that never ran wrote nothing"); - assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "and appended nothing: its body"); - assert_eq!(outcome.gas.history, TX_BODY_SIZE * CPHB); + assert_eq!(outcome.usage.write_records, 0, "no bump, no record"); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "the body alone: no record, no code"); + assert_eq!( + outcome.gas.history, + (TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE) * CPHB, + "the two records' history stays charged" + ); assert_reservoir_paid("a creation answered without running", gas_limit, &outcome); } } @@ -440,7 +446,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { .account_code(RECEIVER, event().stop().build()) }, TX_BODY_SIZE + transfer + log_bytes(3, 32), - STORAGE_CALL_STIPEND_BYTES, + HISTORY_ALLOWANCE_BYTES, ), ( "an event larger than the allowance: the receiver's gas pays the rest", @@ -449,7 +455,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { .account_code(RECEIVER, log(BytecodeBuilder::default(), 3, 64).stop().build()) }, TX_BODY_SIZE + transfer + log_bytes(3, 64), - STORAGE_CALL_STIPEND_BYTES, + HISTORY_ALLOWANCE_BYTES, ), ( "two events: the allowance pays the first", @@ -459,7 +465,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { .account_code(RECEIVER, code) }, TX_BODY_SIZE + transfer + 2 * log_bytes(3, 32), - STORAGE_CALL_STIPEND_BYTES, + HISTORY_ALLOWANCE_BYTES, ), ( "the receiver reverts: the event is not appended, and the transfer's records neither", @@ -485,7 +491,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { }, // The sender's account is written once; each receiver's once. TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE + 2 * log_bytes(3, 32), - 2 * STORAGE_CALL_STIPEND_BYTES, + 2 * HISTORY_ALLOWANCE_BYTES, ), ]; @@ -542,8 +548,6 @@ enum Run { /// Under a transaction data-size limit of this many bytes, which a frame below the /// transaction's own crosses, whose caller catches the stop. Caught(u64), - /// With an inspector that answers every creation without running it. - AnsweringCreations, } /// The history bytes a transaction reports and the data size it kept are counted from one byte @@ -562,7 +566,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { let hint = hint_call().len() as u64; type Case = (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, Run, u64, u64, u64); - let cases: [Case; 35] = [ + let cases: [Case; 34] = [ ( "the body", || callee_running(BytecodeBuilder::default()), @@ -654,11 +658,11 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 1, ), ( - "a SELFDESTRUCT's beneficiary", + "a SELFDESTRUCT's beneficiary, and the account it clears", || funded().account_code(CALLEE, destructs_to(PAYEE)), |gas| call(CALLER, CALLEE, U256::ZERO, gas), Run::Plain, - TX_BODY_SIZE + WRITE_RECORD_SIZE, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, ), @@ -737,15 +741,6 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 0, 0, ), - ( - "a creation an inspector answers without running it", - || callee_running(creating(BytecodeBuilder::default(), &deploying())), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - Run::AnsweringCreations, - TX_BODY_SIZE, - 0, - 0, - ), ( "a first frame answered with the stop", funded, @@ -852,20 +847,21 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 0, ), ( - "a SELFDESTRUCT's beneficiary the destruction creates", + "a SELFDESTRUCT's beneficiary the destruction creates, and the account it clears", || funded().account_code(CALLEE, destructs_to(FRESH)), |gas| call(CALLER, CALLEE, U256::ZERO, gas), Run::Plain, - TX_BODY_SIZE + WRITE_RECORD_SIZE, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, ), ( - "a SELFDESTRUCT to the sender records nothing: the body carries the sender", + "a SELFDESTRUCT to the sender records the account it clears alone: the sender's \ + account the transaction changed already", || funded().account_code(CALLEE, destructs_to(CALLER)), |gas| call(CALLER, CALLEE, U256::ZERO, gas), Run::Plain, - TX_BODY_SIZE, + TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 1, ), @@ -936,21 +932,13 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { for gas_limit in GAS_LIMITS { let limit = match run { Run::Limited(limit) | Run::Caught(limit) => limit, - Run::Plain | Run::AnsweringCreations => u64::MAX, + Run::Plain => u64::MAX, }; // A limit the body alone crosses would stop every case before its first write, and the // case would pin the body's stop rather than its own. assert!(limit > TX_BODY_SIZE, "{name}: the body fits under the limit"); let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limited_to(limit))); - let outcome = match run { - Run::AnsweringCreations => { - evm.with_inspector(AnswersCreations).execute_transaction(tx(gas_limit)) - } - Run::Plain | Run::Limited(_) | Run::Caught(_) => { - evm.execute_transaction(tx(gas_limit)) - } - } - .expect("the transaction is valid"); + let outcome = evm.execute_transaction(tx(gas_limit)).expect("the transaction is valid"); assert_eq!( outcome.limit_exceeded.is_some(), matches!(run, Run::Limited(_)), diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 099c248a1..90da9fe90 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -79,9 +79,9 @@ const DEPLOYED_BYTES: u64 = 32; /// The history bytes a user transaction running the program from [`CALLER`] appends: its body /// with no calldata; the program's four write records — the new slot, then `CONTRACT` (the -/// transfer's sender and the creator, recorded once in its frame), `PAYEE` and the created -/// account; its log of one word with no topic; and the deployed code. The transfer's log is data -/// size and appends no history. +/// transfer's sender and the creator, recorded once: the transfer changed it, and its nonce bump +/// adds nothing), `PAYEE` and the created account; its log of one word with no topic; and the +/// deployed code. The transfer's log is data size and appends no history. const PROGRAM_HISTORY_BYTES: u64 = TX_BODY_SIZE + 4 * WRITE_RECORD_SIZE + (LOG_BASE_SIZE + 32) + DEPLOYED_BYTES; @@ -218,8 +218,10 @@ fn test_a_system_transaction_pays_no_history_gas() { LimitUsage { data_size: transaction_body_bytes(&system_tx()) + WRITE_RECORD_SIZE, write_records: 1, + state_growth: 2, }, - "the body and the slot's record are counted, though neither pays history", + "the body and the slot's record are counted, though neither pays history, and the new slot \ + and the system address's new account are its state growth", ); // The state is charged as usual: the new slot, and the system address's own account, which // the database leaves empty, so the transaction creates it, as it does a deposit's caller. diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 0012dc7aa..37bc7f614 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -3,7 +3,7 @@ //! Every charge is a byte count at the cost per history byte, and every assertion here writes the //! count out, so a repricing moves the numbers without rewriting the test. -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use mega_evm::{ constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, @@ -11,11 +11,17 @@ use mega_evm::{ WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STOP}, + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, RETURN, + REVERT, STATICCALL, STOP, + }, context_interface::cfg::GasId, }; -use crate::common::{call, call_with_data, create, deploying, execute, runs_at_measurement_prices}; +use crate::common::{ + body_history, call, call_with_data, create, deploying, execute, history, history_is_free, + history_rounds, reservoir_share, runs_at_measurement_prices, +}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const CALLEE: Address = address!("0000000000000000000000000000000000200001"); @@ -104,7 +110,7 @@ fn test_calldata_costs_one_history_byte_per_byte() { assert_eq!(longer.gas.history - zeros.gas.history, 100 * CPHB, "a hundred bytes more"); } -/* ---------- the sites the Host stages ---------- */ +/* ---------- the sites of completed writes ---------- */ /// The body of a `LOG` with `topics` topics over `data_len` bytes of memory, without the `STOP` /// that ends a program. @@ -154,7 +160,7 @@ fn test_a_log_pays_history_on_top_of_the_schedules_price() { /* ---------- a frame-start charge the caller cannot pay ---------- */ /// `CALL(GAS, target, 1 wei, [], [])`, discarding the flag, then `STOP`: a value transfer that -/// forwards everything the caller may forward, so the caller keeps a sixty-fourth of what it held. +/// forwards everything the caller may forward, so the caller keeps 2 per cent of what it held. fn transfers_everything_to(target: Address) -> Bytes { BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -185,8 +191,8 @@ fn caller_running(code: Bytes) -> MemoryDatabase { funded().account_balance(CALLEE, U256::from(10_000_000)).account_code(CALLEE, code) } -/// The two records a value call's start makes cost more than a caller under roughly 450,000 gas -/// keeps after the sixty-fourth it may not forward. Such a caller pays for none of them by +/// The two records a value call's start makes cost more than a caller under roughly 352,000 gas +/// at the forward keeps after the 98 per cent it forwards. Such a caller pays for none of them by /// halting: the frame it was starting does not run. #[test] fn test_a_call_whose_caller_cannot_pay_its_records_starts_no_frame() { @@ -194,7 +200,7 @@ fn test_a_call_whose_caller_cannot_pay_its_records_starts_no_frame() { return; } let code = transfers_everything_to(CONTRACT); - let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 600_000)); + let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 560_000)); let ample = execute(caller_running(code), call(CALLER, CALLEE, U256::ZERO, 1_000_000)); assert!(!short.result.is_success(), "the caller halts rather than starting the frame"); @@ -213,7 +219,7 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { return; } let code = creates_everything(); - let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 600_000)); + let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 560_000)); let ample = execute(caller_running(code), call(CALLER, CALLEE, U256::ZERO, 1_000_000)); assert!(!short.result.is_success(), "the creator halts rather than starting the creation"); @@ -225,6 +231,160 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { assert_eq!(ample.gas.history, body(0) + 2 * WRITE_RECORD_SIZE * CPHB); } +/// A creation onto an account the transaction already changed makes no record of the created +/// account — the transaction's earlier write made it — so its creator pays for its own nonce's +/// record alone. `CONTRACT` funds the address `CALLEE`'s `CREATE2` lands on with one wei, a call +/// answered without running, then calls `CALLEE` with the gas each case gives it. `CALLEE` runs +/// `CREATE2` of empty init code, which charges four `PUSH0` and the creation's own gas — no state +/// gas, for an account that exists — and forwards all but 2 per cent of what is left, keeping that +/// fiftieth to pay the start's records with. Given 50 times one record's price on top of its +/// charges, it starts the creation; one gas less, it does not. +#[test] +fn test_a_creation_onto_an_account_the_transaction_changed_charges_its_creator_one_record() { + // Records that cost nothing leave no price to be short of, and records priced at a fraction of + // a gas may round to nothing. + if history_is_free() || history_rounds() { + return; + } + let created = CALLEE.create2(B256::ZERO, keccak256([])); + let price = history(WRITE_RECORD_SIZE); + let charges = 4 * 2 + mega_evm::satin_gas_params().get(GasId::create()); + let run = |given: u64| { + let funds_then_calls = BytecodeBuilder::default() + .call(created, U256::from(1)) + .append_many([POP, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CALLEE) + .push_number(given) + .append_many([CALL, POP, STOP]) + .build(); + let creates = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, CREATE2, POP, STOP]) + .build(); + let db = funded() + .account_code(CONTRACT, funds_then_calls) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CALLEE, creates); + let outcome = execute(db, call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome + }; + + let short = run(charges + 50 * price - 1); + assert_eq!(short.state[&created].info.nonce, 0, "a gas short, the creation never started"); + assert_eq!(short.usage.write_records, 2, "the funding call's: CONTRACT's and the address's"); + assert_eq!(short.gas.history, body_history(0) + 2 * price); + + let exact = run(charges + 50 * price); + assert_eq!(exact.state[&created].info.nonce, 1, "the creation ran"); + assert_eq!(exact.usage.write_records, 3, "and added its creator's record alone"); + assert_eq!(exact.gas.history, body_history(0) + 3 * price); +} + +/// Every call kind reaches the start's charge after its forward. A caller given its charges, an +/// explicit forward and one gas less than what the reservoir leaves of its records' price keeps too +/// little once it forwarded, and starts no frame; given that gas in full it starts the frame and +/// pays the price, the reservoir first and then its own gas. Below the execution cap there is no +/// reservoir; above it the reservoir holds half the price. A `DELEGATECALL` or a `STATICCALL` +/// moves no value, and a `CALLCODE` moves it from the calling account to itself: none makes a +/// record, so from the same gas each starts, and pays no history. +/// +/// `CALLEE` calls `CONTRACT` with the gas each case gives it and returns the call's flag, so the +/// flag says whether `CONTRACT`'s own start happened. `TARGET` holds a balance and no code, so the +/// start is answered without running, and no account is created. +#[test] +fn test_every_call_kind_charges_its_records_after_its_forward() { + if runs_at_measurement_prices() { + return; + } + const TARGET: Address = address!("0000000000000000000000000000000000200003"); + let params = mega_evm::satin_gas_params(); + let cold_access = params.get(GasId::warm_storage_read_cost()) + + params.get(GasId::cold_account_additional_cost()); + let transfer = params.get(GasId::transfer_value_cost()); + // `scheme(forward, TARGET, value, [], [])` and its charges before the forward: four `PUSH0`, a + // `PUSH1` of the value where the scheme carries one, the `PUSH20` and the `PUSH8` of the + // forward, then the cold access and the transfer. + let start = |scheme: u8, forward: u64| { + let code = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + let (code, charges) = if matches!(scheme, CALL | CALLCODE) { + (code.push_number(1_u8), 8 + 3 + 3 + 3 + cold_access + transfer) + } else { + (code, 8 + 3 + 3 + cold_access) + }; + ( + code.push_address(TARGET).push_number(forward).append_many([scheme, STOP]).build(), + charges, + ) + }; + let run = |code: Bytes, given: u64, reservoir: Option| { + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .push_number(given) + .append(CALL) + .return_top() + .build(); + let db = funded() + .account_code(CALLEE, caller) + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(1)) + .account_balance(TARGET, U256::from(1)); + let gas_limit = + reservoir.map_or(GAS_LIMIT, |reservoir| TX_GAS_LIMIT_CAP + body(0) + reservoir); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let started = U256::from_be_slice(outcome.result.output().unwrap()) == U256::from(1); + (started, outcome) + }; + + for (scheme, records) in [(CALL, 2)] { + let price = records * WRITE_RECORD_SIZE * CPHB; + for reservoir in [None, Some(price / 2)] { + let case = format!("scheme {scheme:#04x}, reservoir {reservoir:?}"); + // What the caller's own gas pays once the reservoir it was given is spent — its + // caller's share of the transaction's — and a forward that leaves it one gas less than + // that, the most the 98/100 rule lets it forward. + let given = reservoir.map_or(0, reservoir_share); + let spill = price - given; + let forward = 49 * (spill - 1); + let (code, charges) = start(scheme, forward); + + let (started, short) = run(code.clone(), charges + forward + spill - 1, reservoir); + assert!(!started, "{case}: one gas short, no frame"); + assert_eq!(short.usage.write_records, 0, "{case}"); + assert_eq!(short.gas.history, body(0), "{case}: the body alone"); + if let Some(reservoir) = reservoir { + assert_eq!(short.gas.reservoir_remaining, reservoir, "{case}: the reservoir too"); + } + + let (started, exact) = run(code, charges + forward + spill, reservoir); + assert!(started, "{case}: the gas in full, the frame starts"); + assert_eq!(exact.usage.write_records, records, "{case}"); + assert_eq!(exact.gas.history, body(0) + price, "{case}: the body and the records"); + // The share paid first. The part of the reservoir its caller kept comes back with the + // transaction's own frame, which merged the spill: it unwinds that spill onto regular + // gas before any of it joins the reservoir, so none is left. + if reservoir.is_some() { + assert_eq!( + exact.gas.reservoir_remaining, 0, + "{case}: the spill took what was kept" + ); + } + + // A value `CALLCODE` moves the value from the calling account to itself and makes + // no record, as the two schemes that carry no value make none. + for scheme in [CALLCODE, DELEGATECALL, STATICCALL] { + let case = format!("{case}, then scheme {scheme:#04x} from the same gas"); + let (code, _) = start(scheme, forward); + let (started, outcome) = run(code, charges + forward + spill - 1, reservoir); + assert!(started, "{case}: no records, no charge to fall short of"); + assert_eq!(outcome.usage.write_records, 0, "{case}"); + assert_eq!(outcome.gas.history, body(0), "{case}"); + } + } + } +} + /// Whether a write record is paid for may not depend on how much gas its frame's caller had /// left. Across the gas limits that straddle the point where a caller can no longer pay for the /// records of the frame it starts, the history a transaction pays beyond its body is exactly the @@ -343,3 +503,43 @@ fn test_a_beneficiary_that_is_a_fee_vault_changes_nothing() { assert_eq!(a_vault.gas.history, distinct.gas.history); assert_eq!(a_vault.usage.write_records, 0); } + +/// The record the transaction's own frame makes — its value's recipient — is charged before the +/// frame and given back once: by the frame itself, when the recipient sends the value back and its +/// account returns to what the transaction loaded, so a frame that then succeeds keeps none of it +/// and the settlement gives nothing back again; by the settlement, when the frame fails, its own +/// give-back discarded with it. A recipient that keeps the value keeps the record and its history. +/// +/// Independence: constants — the body and the record are the byte table's, at the price in effect. +#[test] +fn test_the_first_frames_record_is_given_back_once() { + let one = U256::from(1); + let returning = |end: u8| { + BytecodeBuilder::default() + .call(CALLER, one) + .append(POP) + .append_many([PUSH0, PUSH0, end]) + .build() + }; + let cases = [ + ("returns the value and succeeds", returning(RETURN), true, 0), + ("keeps the value", BytecodeBuilder::default().stop().build(), true, 1), + ("returns the value and reverts", returning(REVERT), false, 0), + ]; + for (name, code, succeeds, records) in cases { + let outcome = + execute(funded().account_code(CONTRACT, code), call(CALLER, CONTRACT, one, GAS_LIMIT)); + assert_eq!(outcome.result.is_success(), succeeds, "{name}: {:?}", outcome.result); + assert_eq!( + outcome.gas.history, + body_history(0) + history(WRITE_RECORD_SIZE * records), + "{name}: the body, and the recipient's record where it is kept" + ); + assert_eq!(outcome.usage.write_records, records, "{name}"); + assert_eq!( + outcome.gas.history_bytes, + TX_BODY_SIZE + WRITE_RECORD_SIZE * records, + "{name}: the history bytes follow" + ); + } +} diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 9de582130..7b8af71f5 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -5,7 +5,7 @@ //! gas. Below the cap the reservoir is empty, every charge spills straight onto regular gas, and //! a charge that is silently given back looks exactly like a charge that was made and kept. //! -//! So the rule this lane carries, and the next mechanism inherits: **every ledger invariant gets +//! So the rule these tests carry, and the next mechanism inherits: **every ledger invariant gets //! at least one case above the cap**. Each holds its transaction to //! //! ```text @@ -30,8 +30,12 @@ use mega_evm::{ }; use revm::bytecode::opcode::{CALL, CREATE, GAS, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}; -use crate::common::{ - body_history, call, execute, history_is_free, history_rounds, runs_at_measurement_prices, +use crate::{ + common::{ + body_history, call, execute, history_is_free, history_rounds, runs_at_measurement_prices, + state_is_free, + }, + salt::{crowded_account, minimal_envs, salt_context}, }; const CALLER: Address = address!("0000000000000000000000000000000000700000"); @@ -184,7 +188,7 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { assert!(outcome.result.is_success(), "the caller survives its child's revert"); assert_eq!( outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "the reverted transfer kept nothing but the body" ); assert_eq!(outcome.gas.history, BODY, "the body alone"); @@ -195,10 +199,10 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { ); } -/// A value call a system contract's interceptor refuses never starts a frame: its lane is empty -/// and the whole charge comes back. It is the path where the caller is paid back twice if the -/// frame inherited the caller's reservoir from before the charge, because the empty lane refills -/// what the adoption already restored. +/// A value call a system contract's interceptor refuses never starts a frame: its start counts +/// nothing and the whole charge comes back. It is the path where the caller is paid back twice if +/// the frame inherited the caller's reservoir from before the charge, because the refund of the +/// start charge refills what the adoption already restored. #[test] fn test_an_intercepted_value_call_gives_its_records_back_once() { if runs_at_measurement_prices() { @@ -218,7 +222,7 @@ fn test_an_intercepted_value_call_gives_its_records_back_once() { assert!(outcome.result.is_success(), "the caller survives the refusal"); assert_eq!( outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "the refused call wrote nothing but the body" ); assert_eq!(outcome.gas.history, BODY, "the body alone"); @@ -306,3 +310,39 @@ fn test_the_body_draws_the_reservoir_first_and_only_its_excess_from_regular_gas( assert_eq!(body, 310 * 88, "the body at the spec's price"); assert_eq!(INTRINSIC + ANSWERING + body, 42_295, "the empty call's 42,280 and the program"); } + +/// A transaction above the execution cap that runs out of gas in the runtime gas phase, before its +/// first frame, keeps its body's history charged, and what the reservoir paid of it with it: +/// revm rebuilds the transaction's gas from its intrinsic cost on that path, and the body is +/// intrinsic [S5]. The rest of the regular budget is consumed, and what is left of the reservoir +/// returns to the sender. +/// +/// The phase runs out here on EIP-2780's charge for the account a value call creates, in a bucket +/// crowded past what the regular budget and the reservoir together can pay. A body charged where +/// the rebuild drops it would leave the reservoir whole and the history ledger empty. +#[test] +fn test_an_out_of_gas_before_the_first_frame_keeps_the_body_the_reservoir_paid() { + if history_is_free() || history_rounds() || state_is_free() { + return; + } + const EMPTY: Address = address!("0000000000000000000000000000000000700e00"); + let body = body_history(0); + let reservoir = body + 1_000; + let account = mega_evm::satin_gas_params() + .get(revm::context_interface::cfg::GasId::new_account_state_gas()); + let m = (TX_GAS_LIMIT_CAP + reservoir) / account + 2; + let envs = crowded_account(minimal_envs(), EMPTY, m); + let tx = call(CALLER, EMPTY, U256::from(1), TX_GAS_LIMIT_CAP + reservoir); + let outcome = mega_evm::MegaEvm::new(salt_context(funded(), envs)) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.gas.history, body, "the body stays charged"); + assert_eq!(outcome.gas.state, 0, "the account was not created"); + assert_eq!(outcome.gas.reservoir_remaining, reservoir - body, "the reservoir paid the body"); + assert_eq!(outcome.gas.gas_used, TX_GAS_LIMIT_CAP + body, "the regular budget is consumed"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); +} diff --git a/crates/mega-evm/tests/satin/inherited_costs.rs b/crates/mega-evm/tests/satin/inherited_costs.rs index 7a3ff1e39..a9da22840 100644 --- a/crates/mega-evm/tests/satin/inherited_costs.rs +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -1,39 +1,29 @@ -//! Two costs Satin inherits from Ethereum where the legacy engine departed from it. +//! A cost Satin inherits from Ethereum where the legacy engine departed from it: **a preload-warm +//! address is charged warm.** The precompiles, the block beneficiary and an access-list address +//! are warm from the transaction's start, and the first call to one costs what the second does. +//! The legacy engine's pricing inspected the callee's account before the opcode's own access and +//! charged that first touch cold; Satin's pricing hook inspects no account, so the warmth revm +//! preloads is what the opcode sees. //! -//! - **A preload-warm address is charged warm.** The precompiles, the block beneficiary and an -//! access-list address are warm from the transaction's start, and the first call to one costs -//! what the second does. The legacy engine's pricing inspected the callee's account before the -//! opcode's own access and charged that first touch cold; Satin's pricing hook inspects no -//! account, so the warmth revm preloads is what the opcode sees. -//! - **A call or creation forwards all but a 64th of its gas**, as EIP-150 has it, where the legacy -//! engine forwarded 98/100. The 98% share lives on in the data-size and KV frame budgets, which -//! are not gas. -//! -//! Both are read off the regular ledger, which is the gas the opcodes charge. +//! It is read off the regular ledger, which is the gas the opcodes charge. use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, + MegaTransaction, }; use revm::{ - bytecode::opcode::{CALL, CALLCODE, CREATE, GAS, POP, PUSH0, STATICCALL, STOP}, + bytecode::opcode::{CALL, CALLCODE, POP, PUSH0, STATICCALL, STOP}, context::{ transaction::{AccessList, AccessListItem, TransactionType}, TxEnv, }, context_interface::cfg::GasId, - interpreter::{ - interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, - CreateInputs, CreateOutcome, Interpreter, - }, - Database, Inspector, }; use crate::{ - common::{block, call, context, execute}, + common::{block, call, execute}, salt::entry, }; @@ -155,86 +145,3 @@ fn test_the_first_call_to_the_beneficiary_is_charged_warm() { let beneficiary = block().beneficiary; assert_eq!(first_call_over_second(CALL, beneficiary, plain), 0); } - -/* ---------- forwarding ---------- */ - -/// The regular gas a frame holds as its call or creation starts, and what it forwards. -#[derive(Default)] -struct Forward { - opcode: u8, - held: Option, - forwarded: Option, -} - -impl Inspector, EthInterpreter> for Forward { - fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { - self.opcode = interp.bytecode.opcode(); - if matches!(self.opcode, CALL | CREATE) { - self.held = Some(interp.gas.remaining()); - } - } - - fn call( - &mut self, - _context: &mut MegaContext, - inputs: &mut CallInputs, - ) -> Option { - if inputs.target_address == EXISTING { - self.forwarded = Some(inputs.gas_limit); - } - None - } - - fn create( - &mut self, - _context: &mut MegaContext, - inputs: &mut CreateInputs, - ) -> Option { - self.forwarded = Some(inputs.gas_limit()); - None - } -} - -/// Runs `CONTRACT` holding `code` above the execution cap, where the reservoir pays every state -/// and history charge, and returns the regular gas held at the opcode and the gas forwarded. -fn forward_of(code: Bytes) -> (u64, u64, MegaTransactionOutcome) { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(CONTRACT, code); - let mut evm = MegaEvm::new(context(db)).with_inspector(Forward::default()); - let outcome = evm - .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 5 * TX_GAS_LIMIT_CAP)) - .expect("the transaction is valid"); - let forward = evm.inspector(); - (forward.held.expect("the opcode ran"), forward.forwarded.expect("a frame started"), outcome) -} - -/// A `CALL` given all the gas forwards all but a 64th of what its caller holds once the call's own -/// charge — the cold access to its target — is paid. -#[test] -fn test_a_call_forwards_all_but_a_64th_of_its_gas() { - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(EXISTING) - .append_many([GAS, CALL, STOP]) - .build(); - let (held, forwarded, outcome) = forward_of(code); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let left = held - entry(GasId::warm_storage_read_cost()) - cold_over_warm(); - assert_eq!(forwarded, left - left / 64); -} - -/// A `CREATE` forwards all but a 64th of what its creator holds once the creation's own charges — -/// the `create` entry, EIP-3860's word and the memory the init code occupies — are paid; the -/// created account's state gas comes out of the reservoir. -#[test] -fn test_a_creation_forwards_all_but_a_64th_of_its_gas() { - let code = BytecodeBuilder::default() - .push_number(10_u8) - .append_many([PUSH0, PUSH0, CREATE, STOP]) - .build(); - let (held, forwarded, outcome) = forward_of(code); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let left = held - entry(GasId::create()) - entry(GasId::initcode_per_word()) - 3; - assert_eq!(forwarded, left - left / 64); -} diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index bfe002245..ebb89e325 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -1,18 +1,16 @@ -//! Inspectors on Satin: what a rewriting inspector gets, the one rewrite refused, and the -//! admission gate block execution keys on. +//! Inspectors on Satin: what a rewriting inspector gets and what its rewrites do not change. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ - test_utils::{transfer_log, BytecodeBuilder, GasInspector, MemoryDatabase}, - DeclaredObserver, MegaContext, MegaEvm, TX_BODY_SIZE, WRITE_RECORD_SIZE, + test_utils::{transfer_log, BytecodeBuilder, GasInspector, MemoryDatabase, ReadOnlyObserver}, + MegaContext, MegaEvm, LOG_BASE_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, + bytecode::opcode::{CALL, CREATE, GAS, INVALID, LOG0, PUSH0, REVERT, SSTORE}, context::result::EVMError, - inspector::NoOpInspector, interpreter::{ - interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, }, Database, Inspector, @@ -20,7 +18,7 @@ use revm::{ use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; use crate::common::{ - account_state_gas, body_history, call, context, execute_under, history, slot_state_gas, + account_state_gas, body_history, call, context, execute_under, history, share, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000400000"); @@ -29,16 +27,16 @@ const B: Address = address!("00000000000000000000000000000000000000B1"); const FAKE: Address = address!("00000000000000000000000000000000000FA4E0"); /// 1,000,000 of regular gas on top of what these scenarios add at the byte prices in effect: two -/// fresh slots and a new account, the body and four records, and 64 times the history of two -/// records, which a call or a creation that forwards all but a 64th of its gas pays for the frame -/// it starts from the 64th it keeps. +/// fresh slots and a new account, the body and four records, and 50 times the history of two +/// records, which a call or a creation that forwards all but 2 per cent of its gas pays for the +/// frame it starts from the fiftieth it keeps. fn gas_limit() -> u64 { 1_000_000 + 2 * slot_state_gas() + account_state_gas() + body_history(0) + history(4 * WRITE_RECORD_SIZE) + - 64 * history(2 * WRITE_RECORD_SIZE) + 50 * history(2 * WRITE_RECORD_SIZE) } /// Calls `B` with `value` and stores the call's success flag in slot 0. @@ -220,7 +218,7 @@ fn test_short_circuited_value_call_moves_no_value() { ); assert_eq!(result.state[&A].info.balance, U256::from(100), "no value left A"); assert!(result.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value reached B"); - assert_eq!(evm.ctx().additional_limit().usage().write_records, 1, "only A's slot 0"); + assert_eq!(evm.ctx().limit_usage().write_records, 1, "only A's slot 0"); } /// An address rewritten in `create_end` is what the caller sees, but the code is where the @@ -241,48 +239,53 @@ fn test_create_end_address_rewrite_reaches_the_caller_not_the_code() { } /// A creation its own frame budget stops, revived by an inspector: the stop is the creation's alone -/// and no stop of the transaction, so the creation failed as any failed creation does and its -/// revival settles as the failure — the transaction is not refused. Under a data-size limit of the -/// body and 122 bytes, the creator may keep 122 and the creation 98% of them, 119: the creation's -/// start makes two records, 80 bytes, and the write in its init code is a third, 40 more, over its -/// budget, which the transaction's limit still holds. Under the body and 160 bytes the budget holds -/// it, and so does the transaction's limit once the creator stores the address, a fourth record: -/// the same creation succeeds. +/// and no stop of the transaction, so the creation failed as any failed creation does, and its +/// revival settles as the success the inspector made of it — the transaction is not refused. Under +/// a data-size limit of the body and 4,000 bytes the creation gets 98% of them, 3,920: its start +/// makes the created account's record, 40 bytes, and the log in its init code 3,881 more, one byte +/// over its budget, which the transaction's limit still holds. Revived, it hands its creator the +/// record it counted, and the creator keeps that, its nonce record and the address it stores. Under +/// the body and 4,100 bytes the budget, 4,018, holds the log, and the creator keeps its two records +/// on top: the same creation succeeds. #[test] fn test_a_creation_its_frame_budget_stops_may_be_revived() { - // A write of 1 to slot 1, short enough for `create_and_store_address`. + // A log one byte past the creation's share once the created account's record is counted. + const LOGGED: u64 = 3_849; + assert_eq!(WRITE_RECORD_SIZE + LOG_BASE_SIZE + LOGGED, share(4_000) + 1); let init_code = BytecodeBuilder::default() - .push_number(1_u8) - .push_number(1_u8) - .append(SSTORE) + .push_number(LOGGED) + .push_number(0_u8) + .append(LOG0) .stop() .build(); + // What `gas_limit` covers, and the log the creation keeps when its budget holds it. + let gas_limit = gas_limit() + history(LOG_BASE_SIZE + LOGGED) + 100_000; let db = || MemoryDatabase::default().account_code(A, create_and_store_address(&init_code)); let under = |bytes: u64| { mega_evm::EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + bytes) }; let plain = - |bytes: u64| execute_under(db(), call(CALLER, A, U256::ZERO, gas_limit()), under(bytes)); + |bytes: u64| execute_under(db(), call(CALLER, A, U256::ZERO, gas_limit), under(bytes)); let created = |outcome: &mega_evm::MegaTransactionOutcome| { outcome.state[&A] .storage .get(&U256::ZERO) .is_some_and(|slot| !slot.present_value().is_zero()) }; - let roomy = plain(160); + let roomy = plain(4_100); assert!(roomy.result.is_success() && created(&roomy), "{:?}", roomy.result); // Without the inspector the creation fails alone: its creator stores no address and succeeds, // and the transaction is not stopped. - let stopped = plain(122); + let stopped = plain(4_000); assert!(stopped.result.is_success(), "{:?}", stopped.result); assert_eq!(stopped.limit_exceeded, None, "a frame budget below is no stop"); assert!(!created(&stopped), "the creation failed"); - let limits = under(122); + let limits = under(4_000); let revived = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) .with_inspector(Rewriter { create_succeeds: true, ..Default::default() }) - .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)) .unwrap(); assert!(revived.result.is_success(), "{:?}", revived.result); assert_eq!(revived.limit_exceeded, None, "and the revival is no stop either"); @@ -299,33 +302,33 @@ fn test_a_creation_its_frame_budget_stops_may_be_revived() { ); } -/// A declared observer that writes back fails its declaration in a debug build. +/// A read-only observer that writes back fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer wrote to the interpreter in `step_end`")] -fn test_false_declaration_fails_in_debug() { +#[should_panic(expected = "a read-only observer wrote to the interpreter in `step_end`")] +fn test_false_read_only_claim_fails_in_debug() { let rewriter = Rewriter { charge_after_sstore: 1, ..Default::default() }; - let mut evm = MegaEvm::new(context(writes_two_slots())) - .with_trusted_inspector(DeclaredObserver(rewriter)); + let mut evm = + MegaEvm::new(context(writes_two_slots())).with_inspector(ReadOnlyObserver(rewriter)); let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } -/// A declared call rewrite fails too. +/// A read-only observer's call rewrite fails too. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer rewrote a call result")] -fn test_false_declaration_of_a_call_rewrite_fails_in_debug() { +#[should_panic(expected = "a read-only observer rewrote a call result")] +fn test_false_read_only_claim_of_a_call_rewrite_fails_in_debug() { let db = MemoryDatabase::default() .account_code(A, call_b_and_store_flag(0)) .account_code(B, Bytes::from_static(&[INVALID])); let rewriter = Rewriter { call_succeeds: true, ..Default::default() }; - let mut evm = MegaEvm::new(context(db)).with_trusted_inspector(DeclaredObserver(rewriter)); + let mut evm = MegaEvm::new(context(db)).with_inspector(ReadOnlyObserver(rewriter)); let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } -/// A declared observer that only reads produces the transaction no inspector produces. +/// A read-only observer that only reads produces the transaction no inspector produces. #[test] -fn test_declared_tracer_changes_nothing() { +fn test_read_only_tracer_changes_nothing() { let db = || { MemoryDatabase::default() .account_code(A, call_b_and_store_flag(0)) @@ -334,7 +337,7 @@ fn test_declared_tracer_changes_nothing() { let plain = MegaEvm::new(context(db())).transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); - let mut evm = MegaEvm::new(context(db())).with_trusted_inspector(DeclaredObserver(tracer)); + let mut evm = MegaEvm::new(context(db())).with_inspector(ReadOnlyObserver(tracer)); let traced = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); assert_eq!(plain.result, traced.result); assert_eq!(plain.state, traced.state); @@ -367,27 +370,6 @@ fn test_the_gas_inspector_keeps_the_byte_of_an_undefined_opcode() { } } -/// The admission gate: only an enabled inspector that did not arrive declared is a rewriting one. -#[test] -fn test_has_rewriting_inspector_truth_table() { - let evm = || MegaEvm::new(context(MemoryDatabase::default())); - assert!(!evm().has_rewriting_inspector(), "no inspector"); - assert!(evm().with_inspector(NoOpInspector).has_rewriting_inspector(), "a tool's inspector"); - assert!( - evm().with_inspector(GasInspector::new()).has_rewriting_inspector(), - "test utilities are tools" - ); - assert!(!evm().with_trusted_inspector(NoOpInspector).has_rewriting_inspector()); - let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); - assert!(!evm().with_trusted_inspector(DeclaredObserver(tracer)).has_rewriting_inspector()); - - let mut disabled = evm().with_inspector(Rewriter::default()); - disabled.set_inspector_enabled(false); - assert!(!disabled.has_rewriting_inspector(), "a disabled inspector does not run"); - disabled.set_inspector_enabled(true); - assert!(disabled.has_rewriting_inspector()); -} - /// Counts frame starts and ends. #[derive(Default)] struct Pairs { @@ -530,13 +512,13 @@ fn busy_contract() -> MemoryDatabase { MemoryDatabase::default().account_code(A, code).account_code(B, Bytes::from_static(&[0x00])) } -/// A declared observer forwards every callback to the inspector inside. +/// A read-only observer forwards every callback to the inspector inside. #[test] -fn test_declared_observer_forwards_every_callback() { +fn test_read_only_observer_forwards_every_callback() { let mut plain = MegaEvm::new(context(busy_contract())).with_inspector(Recorder::default()); plain.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let mut declared = MegaEvm::new(context(busy_contract())) - .with_trusted_inspector(DeclaredObserver::new(Recorder::default())); + .with_inspector(ReadOnlyObserver::new(Recorder::default())); declared.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let seen = plain.inspector().clone(); @@ -555,7 +537,7 @@ fn test_declared_observer_forwards_every_callback() { seen.selfdestruct > 0, "every callback ran: {seen:?}" ); - assert_eq!(DeclaredObserver::new(Recorder::default()).into_inner(), Recorder::default()); + assert_eq!(ReadOnlyObserver::new(Recorder::default()).into_inner(), Recorder::default()); } /// Keeps every log handed to `Inspector::log`, the callback for a log journaled outside an @@ -569,16 +551,16 @@ impl Inspector, EthInterpreter> for FrameStartLogs } } -/// A declared observer forwards the EIP-7708 transfer logs a frame's start journals: the +/// A read-only observer forwards the EIP-7708 transfer logs a frame's start journals: the /// transaction's value into `A`, whose frame runs, and `A`'s value into `B`, an account with no /// code, whose frame is answered without running. #[test] -fn test_declared_observer_forwards_the_transfer_logs_of_frame_starts() { +fn test_read_only_observer_forwards_the_transfer_logs_of_frame_starts() { let db = MemoryDatabase::default() .account_balance(CALLER, U256::from(5)) .account_code(A, call_b_and_store_flag(2)); - let mut evm = MegaEvm::new(context(db)) - .with_trusted_inspector(DeclaredObserver::new(FrameStartLogs::default())); + let mut evm = + MegaEvm::new(context(db)).with_inspector(ReadOnlyObserver::new(FrameStartLogs::default())); let outcome = evm.transact_raw(call(CALLER, A, U256::from(5), gas_limit())).unwrap(); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( @@ -634,32 +616,32 @@ impl Inspector, EthInterpreter> for Writer { #[cfg(debug_assertions)] fn run_declared(writer: Writer) { let mut evm = - MegaEvm::new(context(writes_two_slots())).with_trusted_inspector(DeclaredObserver(writer)); + MegaEvm::new(context(writes_two_slots())).with_inspector(ReadOnlyObserver(writer)); let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } -/// A declared observer that edits a frame's inputs fails its declaration in a debug build. +/// A read-only observer that edits a frame's inputs fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer rewrote a frame's inputs")] -fn test_false_declaration_of_an_input_edit_fails_in_debug() { +#[should_panic(expected = "a read-only observer rewrote a frame's inputs")] +fn test_false_read_only_claim_of_an_input_edit_fails_in_debug() { run_declared(Writer { edit_inputs: true, ..Default::default() }); } -/// A declared observer that writes to the journal fails its declaration in a debug build. +/// A read-only observer that writes to the journal fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer wrote to the journal in `step`")] -fn test_false_declaration_of_a_journal_write_fails_in_debug() { +#[should_panic(expected = "a read-only observer wrote to the journal in `step`")] +fn test_false_read_only_claim_of_a_journal_write_fails_in_debug() { run_declared(Writer { log_in_step: true, ..Default::default() }); } -/// A declared observer that rewrites a frame result in `frame_end` fails its declaration in a +/// A read-only observer that rewrites a frame result in `frame_end` fails its declaration in a /// debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer rewrote a frame result in `frame_end`")] -fn test_false_declaration_of_a_frame_end_rewrite_fails_in_debug() { +#[should_panic(expected = "a read-only observer rewrote a frame result in `frame_end`")] +fn test_false_read_only_claim_of_a_frame_end_rewrite_fails_in_debug() { run_declared(Writer { rewrite_frame_end: true, ..Default::default() }); } @@ -686,10 +668,11 @@ impl Inspector for Seen { } /// A system call runs on the handler's plain system-call path wherever the engine and alloy-evm -/// make one — the pre-block calls' entry point, alloy-evm's and revm's — so the EVM's inspector -/// sees nothing of it, as alloy-evm's own EVMs have it. revm's inspecting entry point is the one -/// that hands it to the inspector, and there the call keeps every exemption a system call has: a -/// data-size limit of zero, which would stop a transaction before its first frame, stops nothing. +/// make one — alloy-evm's and revm's entry points here, the block's pre-block calls in the block +/// tests — so the EVM's inspector sees nothing of it, as alloy-evm's own EVMs have it. revm's +/// inspecting entry point is the one that hands it to the inspector, and there the call keeps every +/// exemption a system call has: a data-size limit of zero, which would stop a transaction before +/// its first frame, stops nothing. #[test] fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { use revm::{InspectSystemCallEvm, SystemCallEvm}; @@ -699,8 +682,6 @@ fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(Seen::default()); - let result = evm.transact_system_call_with_gas_limit(CALLER, A, Bytes::new(), 30_000_000); - assert!(result.unwrap().result.is_success()); assert!(Evm::transact_system_call(&mut evm, CALLER, A, Bytes::new()) .unwrap() .result @@ -771,3 +752,34 @@ fn test_intrinsic_data_size_overflow_with_inspector_early_return() { assert_eq!(format!("{inspected:?}"), format!("{plain:?}")); assert!(format!("{plain:?}").contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{plain:?}"); } + +/// Turns every call into a transfer of one wei, whatever value its opcode or the transaction gave +/// it. +struct AddsValue; + +impl Inspector for AddsValue { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + inputs.value = CallValue::Transfer(U256::from(1)); + None + } +} + +/// A rewriting inspector may change what a start writes after its history was charged: the +/// transaction's own call and `A`'s call to `B` carry no value when they are charged — before +/// execution and at `A`'s `CALL` — and one wei each once the inspector rewrote them. The checks +/// that the records counted are the ones charged, which a debug build makes on every other path, +/// are not made under such an inspector, and the rewritten starts run: both transfers move their +/// wei. +#[test] +fn test_a_rewriting_inspector_may_change_what_a_start_writes() { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(A, U256::from(1)) + .account_code(A, call_b_and_store_flag(0)); + let mut evm = MegaEvm::new(context(db)).with_inspector(AddsValue); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.state[&A].storage[&U256::ZERO].present_value, U256::from(1), "B ran"); + assert_eq!(outcome.state[&B].info.balance, U256::from(1), "A's rewritten call moved its wei"); + assert_eq!(outcome.state[&A].info.balance, U256::from(1), "and the transaction's moved A's"); +} diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 7bec7ef3a..697fbf8a7 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -13,10 +13,11 @@ //! //! What each does to Satin's ledgers follows from the inspector contract: a journal write from a //! callback is on no gas ledger and in no count, a paused region spends no gas of any kind while -//! what it writes is still counted, a failed call `expectRevert` turns into a success settles as -//! the failure on every ledger, and a success it turns into a failure keeps none of its writes. -//! `expectRevert` is honored on a result revm answers without running a frame — a precompile's, a -//! call to an account with no code — as on a frame's. +//! what it writes is still counted, and a result `expectRevert` rewrites is taken as given, as revm +//! takes it — a failed call turned into a success keeps its writes reverted and settles as a +//! success. `expectRevert` is honored on a result revm answers without running a frame — a +//! precompile's, a call to an account with no code — as on a frame's. A cheatcode answered on +//! `Gas::new`, as Foundry answers it, carries no reservoir, and its caller is left none. use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::{sol, SolCall}; @@ -38,7 +39,7 @@ use revm::{ }; use crate::{ - common::{call, context}, + common::{body_history, call, context, reservoir_share}, salt::entry, }; @@ -317,8 +318,9 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { LimitUsage { data_size: idle.usage.data_size + WRITE_RECORD_SIZE, write_records: idle.usage.write_records + 1, + state_growth: idle.usage.state_growth + 1, }, - "the record is counted" + "the record is counted, and the slot is new" ); assert_eq!(worked.gas.history_bytes, idle.gas.history_bytes + WRITE_RECORD_SIZE); @@ -334,8 +336,9 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { /// `expectRevert` turns the next call's revert into a success that keeps the revert data. `TARGET` /// fills a fresh slot and reverts with a word; the program notes the flag and the word. The -/// failed call settles as the failure it was on every ledger — the transaction is billed and -/// counted as it is without the cheatcode — and only the flag the program noted differs. +/// failed call's journal was reverted, so the slot is not kept, and the call settles as the +/// success the cheatcode made of it: the transaction is billed and counted as it is where `TARGET` +/// fills the slot and returns the word, with no cheatcode. #[test] fn test_expect_revert_turns_a_revert_into_a_success_that_keeps_its_reason() { let reason = keccak256(b"reason"); @@ -364,8 +367,20 @@ fn test_expect_revert_turns_a_revert_into_a_success_that_keeps_its_reason() { let (reverted, _) = run(db(true), false); assert_eq!(slot(&reverted, TEST, 0), U256::from(1), "the caller saw the revert"); assert_eq!(slot(&reverted, TEST, 1), U256::from_be_bytes(reason.0)); - assert_eq!(expected.gas, reverted.gas, "every ledger"); - assert_eq!(expected.usage, reverted.usage, "every count"); + + // Where `TARGET` returns the word in place of reverting with it, the call succeeds and keeps + // the slot: that is what the rewritten call is billed and counted as. + let returning = BytecodeBuilder::default() + .sstore(U256::from(3), U256::from(1)) + .return_with_data(reason) + .build(); + let db = + MemoryDatabase::default().account_code(TEST, program(true)).account_code(TARGET, returning); + let (returned, _) = run(db, false); + assert_eq!(slot(&returned, TEST, 0), U256::from(2), "the caller saw the success"); + assert!(returned.state[&TARGET].storage[&U256::from(3)].is_changed(), "and the slot is kept"); + assert_eq!(expected.gas, returned.gas, "every ledger"); + assert_eq!(expected.usage, returned.usage, "every count"); } /// `expectRevert` is honored on a result revm answers without running a frame. A point off the @@ -396,13 +411,15 @@ fn test_expect_revert_is_honored_on_a_result_no_frame_ran_to_produce() { } /// At Foundry's default gas limit a test transaction runs above the execution cap, with a -/// reservoir, and Foundry answers every cheatcode call on `Gas::new`, which carries none. The -/// answered frame never ran, so its caller merges back the reservoir it forwarded: a program that -/// calls `deal`, fills a fresh slot and notes `GAS` costs, on every ledger, what it costs where the -/// cheatcode's call reaches an account with no code — its state gas drawn from the reservoir rather -/// than spilled onto regular gas — reads the same `GAS`, and ends with the same reservoir. +/// reservoir, and Foundry answers every cheatcode call on `Gas::new`, which carries none. Its +/// caller adds the answer's reservoir to what it kept of its own when it handed the call its +/// share, as revm settles an answer: a program that calls `deal`, fills a fresh slot and notes +/// `GAS` in another is left only the 2 per cent it kept, which pays for both slots, so `GAS` reads +/// what it reads where the cheatcode's call reaches an account with no code, which carries the +/// whole share back. The state and history it is billed, and what it counts, are the same either +/// way. #[test] -fn test_a_cheatcode_keeps_the_reservoir_at_foundrys_default_gas_limit() { +fn test_a_cheatcode_at_foundrys_default_gas_limit_leaves_its_caller_what_it_kept() { let code = cheat(BytecodeBuilder::default(), Vm::dealCall { who: TARGET, newBalance: U256::ONE }) .sstore(U256::ZERO, U256::ONE) @@ -416,8 +433,16 @@ fn test_a_cheatcode_keeps_the_reservoir_at_foundrys_default_gas_limit() { assert_eq!(answered, 1); assert_eq!(cheated.state[&TARGET].info.balance, U256::ONE, "the cheatcode ran"); let (plain, _) = run_with_gas_limit(db(), false, FOUNDRY_GAS_LIMIT); - assert!(plain.gas.reservoir_remaining > 0, "the transaction runs with a reservoir"); - assert_eq!(cheated.gas, plain.gas, "every ledger, the reservoir included"); + // `TEST` holds the whole reservoir when it calls the cheatcode, and the two fresh slots draw + // it. + let whole = FOUNDRY_GAS_LIMIT - mega_evm::constants::TX_GAS_LIMIT_CAP - body_history(0); + let record = mega_evm::history_gas(WRITE_RECORD_SIZE).expect("a record has a price"); + let slots = 2 * (entry(GasId::sstore_set_state_gas()) + record); + assert_eq!(plain.gas.reservoir_remaining, whole - slots, "the slots drew the reservoir"); + let kept = whole - reservoir_share(whole); + assert!(kept > slots, "what `TEST` kept pays for both slots"); + assert_eq!(cheated.gas.reservoir_remaining, kept - slots, "the answer's reservoir: none"); + assert_eq!((cheated.gas.state, cheated.gas.history), (plain.gas.state, plain.gas.history)); assert_eq!(cheated.usage, plain.usage, "every count"); - assert_eq!(slot(&cheated, TEST, 1), slot(&plain, TEST, 1), "the same `GAS`"); + assert_eq!(slot(&cheated, TEST, 1), slot(&plain, TEST, 1), "nothing spilled"); } diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index 86c7d8fef..23a77a7aa 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -4,32 +4,38 @@ //! frame's gas into the result it returns, so what `step_end` writes to the interpreter's gas //! after it reaches nobody. What a frame returns is changed on its result, in `call_end`. //! - An inspector cannot overdraw a frame: a charge the frame's spendable gas cannot pay is refused -//! and takes nothing, the frame runs on, and nothing is left behind to classify its end — not -//! even under gas detention, where the same refusal of an opcode's charge is the crossing. -//! - An answer carries only the regular gas its inspector chose: the frame never ran, so its caller -//! merges back the reservoir it forwarded, whatever `Gas` the answer was built on. +//! and takes nothing, and the frame runs on. Under gas detention the refusal of an opcode's +//! charge is the crossing; an inspector's leaves the same record on the frame's gas, as revm +//! leaves it, which stops nothing in a frame that ends without an out-of-gas, and which a later +//! halt that records nothing of its own is read off. +//! - An answer settles on the gas its inspector built it on, as revm settles it: its caller takes +//! the answer's reservoir as its own, and the charges the answer carries as a success's. use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, test_utils::{BytecodeBuilder, MemoryDatabase}, - untouched_call_gas, with_pools_of, EvmTxRuntimeLimits, MegaContext, MegaEvm, + untouched_call_gas, EvmTxRuntimeLimits, LimitCheck, MegaContext, MegaEvm, MegaTransactionOutcome, }; use revm::{ - bytecode::opcode::{LOG0, POP, PUSH0, TIMESTAMP}, + bytecode::opcode::{BALANCE, CALL, JUMP, JUMPDEST, LOG0, POP, PUSH0, PUSH20, TIMESTAMP}, interpreter::{ - interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, Gas, - InstructionResult, Interpreter, InterpreterAction, InterpreterResult, + instructions::gas_table_spec, interpreter::EthInterpreter, interpreter_types::LoopControl, + CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, InterpreterAction, + InterpreterResult, PoolId, }, + primitives::hardfork::SpecId, Database, Inspector, }; -use crate::common::{call, context}; +use crate::common::{body_history, call, context, reservoir_share}; const CALLER: Address = address!("0000000000000000000000000000000000e00000"); const A: Address = address!("0000000000000000000000000000000000e00001"); const B: Address = address!("0000000000000000000000000000000000e00002"); +/// An account no transaction here touches before `B` reads its balance. +const COLD: Address = address!("0000000000000000000000000000000000e00003"); const GAS_LIMIT: u64 = 1_000_000; /// `A` calls `B` and stops; `B` pushes and pops a word and stops. @@ -140,32 +146,45 @@ fn test_gas_changed_at_a_frames_end_has_no_effect() { /// The callbacks holding the interpreter that [`Overdraws`] charges from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Callback { + InitializeInterp, Step, StepEnd, LogFull, } +/// The frames [`Overdraws`] charges in. +#[derive(Clone, Copy, Debug)] +enum Frames { + /// Any frame. + Any, + /// A frame part of whose gas is withheld. + Detained, + /// A frame running `B`'s code. + B, +} + /// Charges, once, one more gas than the running frame's spendable gas from the callback `from`, -/// the first time it runs while part of the frame's gas is withheld — or at all, when -/// `detained_only` is off — and records whether the charge was refused. +/// the first time it runs in one of `frames`, and records whether the charge was refused. #[derive(Clone)] struct Overdraws { from: Callback, - detained_only: bool, + frames: Frames, refused: Option, } impl Overdraws { - const fn new(from: Callback, detained_only: bool) -> Self { - Self { from, detained_only, refused: None } + const fn new(from: Callback, frames: Frames) -> Self { + Self { from, frames, refused: None } } fn charge(&mut self, from: Callback, interp: &mut Interpreter) { let gas = interp.gas.tracker(); - if from != self.from || - self.refused.is_some() || - (self.detained_only && gas.withheld() == 0) - { + let in_frames = match self.frames { + Frames::Any => true, + Frames::Detained => gas.withheld() > 0, + Frames::B => interp.input.target_address == B, + }; + if from != self.from || self.refused.is_some() || !in_frames { return; } let over = gas.spendable() + 1; @@ -174,6 +193,14 @@ impl Overdraws { } impl Inspector, EthInterpreter> for Overdraws { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + ) { + self.charge(Callback::InitializeInterp, interp); + } + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { self.charge(Callback::Step, interp); } @@ -204,7 +231,7 @@ impl Inspector, EthInterpreter> for Overdraws { fn test_an_inspector_cannot_overdraw_a_frame() { let limits = EvmTxRuntimeLimits::no_limits(); let (plain, _) = run::(a_calls_b(), limits, GAS_LIMIT, None); - let overdraws = Overdraws::new(Callback::StepEnd, false); + let overdraws = Overdraws::new(Callback::StepEnd, Frames::Any); let (overdrawn, inspector) = run(a_calls_b(), limits, GAS_LIMIT, Some(overdraws)); assert_eq!(inspector.unwrap().refused, Some(true), "the charge was refused"); assert_eq!(overdrawn.result, plain.result, "nothing was taken, and nothing halted"); @@ -224,7 +251,7 @@ fn test_an_inspector_cannot_overdraw_a_frame() { assert!(plain.result.is_success(), "{:?}", plain.result); for from in [Callback::Step, Callback::StepEnd, Callback::LogFull] { let (overdrawn, inspector) = - run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, true))); + run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, Frames::Detained))); assert_eq!(inspector.unwrap().refused, Some(true), "{from:?}: the withheld part"); assert_eq!(overdrawn.limit_exceeded, None, "{from:?}: no crossing"); assert_eq!(overdrawn.result, plain.result, "{from:?}"); @@ -232,6 +259,65 @@ fn test_an_inspector_cannot_overdraw_a_frame() { } } +/// A charge an inspector's callback could not pay is refused and leaves its record of what the +/// frame had, as revm leaves it: revm does not guard what a callback writes to the interpreter's +/// gas, and neither does the engine. `A` reads the block's timestamp, calls `B` with 2,000 gas, +/// then loops until the compute limit stops it. `B`'s callback charge is refused; `B` then pushes +/// and pops a hundred words and halts on a cold `BALANCE` it cannot pay, which the interpreter +/// refuses before any charge, so no failed deduction of its own records what `B` had. What `B` +/// burns is read off the refused charge's record: what `B` had at the callback, not at its halt. +/// The gas `B` ran in between counts as burned rather than as compute, so `A` runs that much longer +/// to the limit, and is billed that much more, than in the transaction no inspector runs. +#[test] +fn test_a_refused_charge_is_read_as_what_a_later_halt_burns() { + let b = BytecodeBuilder::default() + .append_many([PUSH0, POP].repeat(100)) + .push_address(COLD) + .append(BALANCE) + .stop() + .build(); + let a = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(2_000_u16) + .append_many([CALL, POP]); + let lap = a.len() as u8; + let a = a.append(JUMPDEST).push_number(lap).append(JUMP).build(); + let db = || MemoryDatabase::default().account_code(A, a.clone()).account_code(B, b.clone()); + let detained = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(20_000); + let (plain, _) = run::(db(), detained, GAS_LIMIT, None); + assert!(plain.limit_exceeded.is_some(), "the loop runs to the limit: {:?}", plain.result); + // What `B` runs before its halt: the pushes and pops, the address and `BALANCE`'s static gas. + let static_gas = gas_table_spec(SpecId::AMSTERDAM); + let to_the_halt = 100 * u64::from(static_gas[PUSH0 as usize] + static_gas[POP as usize]) + + u64::from(static_gas[PUSH20 as usize] + static_gas[BALANCE as usize]); + // What `B` ran before the callback: nothing before its first step, its first `PUSH0` before + // the step's end. + for (from, before) in [ + (Callback::InitializeInterp, 0), + (Callback::Step, 0), + (Callback::StepEnd, u64::from(static_gas[PUSH0 as usize])), + ] { + let (overdrawn, inspector) = + run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, Frames::B))); + assert_eq!(inspector.unwrap().refused, Some(true), "{from:?}: the charge was refused"); + let stop = |outcome: &MegaTransactionOutcome| match outcome.limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind, limit, .. }) => Some((kind, limit)), + _ => None, + }; + assert_eq!(stop(&overdrawn), stop(&plain), "{from:?}: the same limit stops it"); + // The stop lands on the first of `A`'s loop charges the limit leaves no room for, so the + // bill grows by the extra room to within the loop's dearest charge, its `JUMP`. + let grown = overdrawn.gas.regular - plain.gas.regular; + assert!( + grown.abs_diff(to_the_halt - before) < u64::from(static_gas[JUMP as usize]), + "{from:?}: what B ran after the callback is burned, and A runs that much longer: \ + {grown} for {}", + to_the_halt - before + ); + } +} + /// How [`AnswersB`] builds the gas of its answer. #[derive(Clone, Copy, Debug)] enum AnswerGas { @@ -240,7 +326,7 @@ enum AnswerGas { /// `Gas::new` of the call's gas limit, as Foundry answers a cheatcode: no reservoir. Fresh, /// Fresh regular gas carrying the pools of the untouched gas after a state and a history - /// charge ([`with_pools_of`]): charges the frame, which never ran, did not make. + /// charge: charges the frame, which never ran, did not make. Charged, } @@ -262,7 +348,16 @@ impl Inspector, EthInterpreter> for AnswersB { assert!( charged.record_state_cost(40_000) && charged.record_history_cost(3_000) ); - with_pools_of(inputs.gas_limit, &charged) + let mut gas = Gas::new(inputs.gas_limit); + gas.set_reservoir(charged.reservoir()); + gas.set_state_gas_spent(charged.state_gas_spent()); + gas.set_state_gas_spilled(charged.state_gas_spilled()); + gas.set_history_gas_spent(charged.history_gas_spent()); + for pool in PoolId::ALL { + gas.set_pool_remaining(pool, charged.pool_remaining(pool)); + gas.set_pool_spent(pool, charged.pool_spent(pool)); + } + gas } }; CallOutcome::new( @@ -273,19 +368,23 @@ impl Inspector, EthInterpreter> for AnswersB { } } -/// An answered frame never ran, so its gas carries nothing but the regular gas its inspector -/// chose: its caller merges back the reservoir it forwarded, whatever `Gas` the answer was built -/// on. Above the execution cap, an answer on the frame's untouched gas, one on `Gas::new` — which -/// carries no reservoir — and one carrying charges the frame never made settle alike, a success, a -/// revert and a halt each, and the transaction keeps the reservoir it keeps when `B` runs. The -/// charges are rolled back against the answer's own reservoir before the inherited one replaces -/// it, so neither the reservoir nor a ledger counts them. +/// An answered frame never ran, and its caller settles the answer on the gas its inspector built +/// it on, as revm does. Above the execution cap, an answer on the frame's untouched gas carries the +/// reservoir share it inherited, and the transaction keeps the reservoir it keeps when `B` runs; +/// one on `Gas::new`, which carries none, leaves its caller only the part of its reservoir it kept +/// from the share, a success, a revert and a halt alike. +/// One carrying charges the frame never made merges them as a success's — the state and history +/// gas on their ledgers, drawn from the reservoir — and a revert or a halt rolls them back. #[test] -fn test_an_answer_carries_the_reservoir_its_caller_merges() { +fn test_an_answer_settles_on_the_gas_it_is_built_on() { let gas_limit = TX_GAS_LIMIT_CAP + 100_000_000; let limits = EvmTxRuntimeLimits::no_limits(); let (plain, _) = run::(a_calls_b(), limits, gas_limit, None); - assert!(plain.gas.reservoir_remaining > 0, "the reservoir comes back"); + // Nothing draws the reservoir: `A` holds all of it when it calls `B`, which takes its share. + let whole = gas_limit - TX_GAS_LIMIT_CAP - body_history(0); + assert_eq!(plain.gas.reservoir_remaining, whole, "the reservoir comes back"); + let kept = whole - reservoir_share(whole); + assert_ne!(kept, 0); for result in [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] { @@ -294,12 +393,27 @@ fn test_an_answer_carries_the_reservoir_its_caller_merges() { run(a_calls_b(), limits, gas_limit, Some(inspector)).0 }; let untouched = answer(AnswerGas::Untouched); + assert!(untouched.result.is_success(), "{result:?}: `A` ignores the answer"); assert_eq!(untouched.gas.reservoir_remaining, plain.gas.reservoir_remaining, "{result:?}"); - for gas in [AnswerGas::Fresh, AnswerGas::Charged] { - let answered = answer(gas); - assert!(answered.result.is_success(), "{result:?}, {gas:?}: `A` ignores the answer"); - assert_eq!(answered.gas, untouched.gas, "{result:?}, {gas:?}: every ledger"); - assert_eq!(answered.usage, untouched.usage, "{result:?}, {gas:?}: every count"); + + let fresh = answer(AnswerGas::Fresh); + assert!(fresh.result.is_success(), "{result:?}, fresh: `A` ignores the answer"); + assert_eq!(fresh.gas.reservoir_remaining, kept, "{result:?}: `Gas::new` carries none"); + assert_eq!(fresh.usage, untouched.usage, "{result:?}, fresh: every count"); + + let charged = answer(AnswerGas::Charged); + assert!(charged.result.is_success(), "{result:?}, charged: `A` ignores the answer"); + assert_eq!(charged.usage, untouched.usage, "{result:?}, charged: every count"); + if result.is_ok() { + assert_eq!(charged.gas.state, untouched.gas.state + 40_000, "{result:?}: merged"); + assert_eq!(charged.gas.history, untouched.gas.history + 3_000, "{result:?}: merged"); + assert_eq!( + charged.gas.reservoir_remaining, + untouched.gas.reservoir_remaining - 43_000, + "{result:?}: drawn from the reservoir" + ); + } else { + assert_eq!(charged.gas, untouched.gas, "{result:?}: rolled back, on every ledger"); } } } diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 0464dce67..bd0d6ddbb 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -1,44 +1,40 @@ -//! What a frame that kept nothing settles into its caller, whatever an inspector made of its -//! result, and what a success an inspector rewrites into a failure keeps: nothing, the journal -//! following the result as it follows a frame that fails. +//! What a frame's result an inspector rewrites settles into: the result as given, as revm takes it. //! -//! Two frames keep nothing in the journal: one that failed, whose checkpoint was reverted before -//! the inspector saw its result, and one the inspector answered in place of running, which never -//! started. An inspector may still hand the caller a success for either — Foundry's `expectRevert` -//! turns a failed call into a success, and a mocked call is answered without running — and the -//! caller sees the success, the output and the regular gas the inspector left. Nothing else of the -//! frame reaches it: no state gas or history gas for writes the journal does not hold, no refund, -//! no write record, and no upfront charge for an account that was never added. +//! revm commits or reverts a frame's journal checkpoint before the inspector sees the frame's +//! result, and the result the inspector hands back is the one its caller settles. So a failed frame +//! an inspector revives into a success — Foundry's `expectRevert` — keeps its journal reverted and +//! settles as a success: its state gas, history, refund and the records it counted merge into its +//! caller. A success it rewrites into a failure keeps its journal and settles as a failure: its +//! charges are rolled back, its counts restored and its start charge refunded. A frame it answers +//! in place of running never started: the charges its caller's opcode made for it stay charged, +//! since the answer carries no upfront-charge flag and no start charge for revm to give back, and +//! it counts nothing of its own. //! -//! Every expectation here is the rule's: a caller that drops the flag cannot tell a rewritten -//! failure from the failure, and a frame answered without running adds no account and writes -//! nothing, so the transaction's state gas is zero and its history is its body's. An answer -//! carries nothing but the regular gas the inspector chose, so every answer is given twice — on -//! the gas the frame was forwarded, untouched, and on `Gas::new` of it, as Foundry answers, which -//! carries no reservoir — and the two settle alike. Where a new -//! account is charged, its bucket is crowded (`m = 3`), so the charge that comes back is the one -//! that was made, priced at the account it was made for. +//! Every expectation is read off a twin no inspector touches: the same frame succeeding, or +//! failing, or the call running. Where a new account is charged, its bucket is crowded (`m = 3`), +//! so the charge is the one that was made, priced at the account it was made for. use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, history_gas, + op_revm::OpHaltReason, test_utils::{BytecodeBuilder, MemoryDatabase}, - transaction_body_bytes, untouched_call_gas, untouched_create_gas, LimitUsage, MegaContext, - MegaEvm, MegaTransaction, MegaTransactionOutcome, WRITE_RECORD_SIZE, + transaction_body_bytes, untouched_call_gas, untouched_create_gas, EvmTxRuntimeLimits, + LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, }; use revm::{ bytecode::{ opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, Bytecode, }, - context::{ContextTr, JournalTr}, + context::{result::ExecutionResult, ContextTr, JournalTr}, context_interface::{cfg::GasId, journaled_state::account::JournaledAccountTr, Transaction}, + handler::SYSTEM_ADDRESS, interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, + interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue, CreateInputs, + CreateOutcome, InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, }, - state::{AccountStatus, EvmStorageSlot}, Inspector, }; @@ -72,40 +68,31 @@ impl Inspector for Revives { } } -/// Answers every call to `target`, and every creation, itself with `result`, on the gas the frame -/// was forwarded, untouched, or, when `fresh`, on `Gas::new` of it: the frame never starts. An -/// answered creation reports `address`. +/// Answers every call to `target`, and every creation when `target` is zero, itself with `result`, +/// on the gas the frame was forwarded, untouched: the frame never starts. An answered creation +/// reports `address`. #[derive(Clone, Copy, Debug)] struct Answers { target: Address, result: InstructionResult, address: Option
, - fresh: bool, } impl Answers { const fn call(target: Address, result: InstructionResult) -> Self { - Self { target, result, address: None, fresh: false } + Self { target, result, address: None } } const fn creation(result: InstructionResult, address: Option
) -> Self { - Self { target: Address::ZERO, result, address, fresh: false } - } - - /// The same answers, built on `Gas::new` of the gas the frame was forwarded, as Foundry - /// answers a cheatcode: gas that carries no reservoir. - const fn on_fresh_gas(self) -> Self { - Self { fresh: true, ..self } + Self { target: Address::ZERO, result, address } } } impl Inspector for Answers { fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { (inputs.target_address == self.target).then(|| { - let gas = - if self.fresh { Gas::new(inputs.gas_limit) } else { untouched_call_gas(inputs) }; CallOutcome::new( - InterpreterResult::new(self.result, Bytes::new(), gas), + InterpreterResult::new(self.result, Bytes::new(), untouched_call_gas(inputs)), inputs.return_memory_offset.clone(), ) }) @@ -113,11 +100,7 @@ impl Inspector for Answers { fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { (self.target == Address::ZERO).then(|| { - let gas = if self.fresh { - Gas::new(inputs.gas_limit()) - } else { - untouched_create_gas(inputs) - }; + let gas = untouched_create_gas(inputs); CreateOutcome::new(InterpreterResult::new(self.result, Bytes::new(), gas), self.address) }) } @@ -144,31 +127,16 @@ where .expect("a valid transaction") } -/// Runs `tx` over `db()` reading `envs()` under `answers`, on the gas the answered frame was -/// forwarded, untouched, and again on `Gas::new` of it; hands back the first once the second -/// settled alike. The frame never ran, so its answer carries nothing but the regular gas the -/// inspector chose, and its caller merges back the reservoir it forwarded whatever the answer was -/// built on. -fn answered( - db: impl Fn() -> MemoryDatabase, - envs: impl Fn() -> SaltEnvs, - tx: &MegaTransaction, - answers: Answers, -) -> MegaTransactionOutcome { - let untouched = inspected(db(), envs(), tx.clone(), answers); - let fresh = inspected(db(), envs(), tx.clone(), answers.on_fresh_gas()); - assert_eq!(fresh.result, untouched.result, "{answers:?}: on fresh gas"); - assert_eq!(fresh.gas, untouched.gas, "{answers:?}: every ledger, on fresh gas"); - assert_eq!(fresh.usage, untouched.usage, "{answers:?}: every count, on fresh gas"); - assert_eq!(fresh.state, untouched.state, "{answers:?}: the state, on fresh gas"); - untouched -} - /// A call from `CALLER` to `to` carrying `value` and `data`, at `gas_limit`. fn to(to: Address, value: u64, data: Bytes, gas_limit: u64) -> MegaTransaction { tx_with_gas(TxKind::Call(to), data, U256::from(value), gas_limit) } +/// What `tx` counts before any frame: its body's bytes, and no write record. +fn body_usage(tx: &MegaTransaction) -> LimitUsage { + LimitUsage { data_size: transaction_body_bytes(tx), write_records: 0, state_growth: 0 } +} + /// A transaction that keeps nothing but its body: no state gas, its body's history alone, and its /// body's bytes alone on the data size. Above the execution cap the reservoir paid for the body and /// nothing else, so what is left of it comes back. @@ -182,7 +150,14 @@ fn assert_keeps_only_its_body(case: &str, tx: &MegaTransaction, outcome: &MegaTr "{case}: the reservoir less the body's history" ); assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!(outcome.usage, body_usage(tx), "{case}"); +} + +/// Requires `outcome` to bill the state gas and the history `charged` bills: the charges the run +/// made and kept, which a result an inspector rewrote kept too. +fn assert_bills_as(case: &str, outcome: &MegaTransactionOutcome, charged: &MegaTransactionOutcome) { + assert_eq!(outcome.gas.state, charged.gas.state, "{case}: the state gas"); + assert_eq!(outcome.gas.history, charged.gas.history, "{case}: the history gas"); } /// Whether `account` holds anything in `outcome`'s state. @@ -190,13 +165,15 @@ fn holds_something(outcome: &MegaTransactionOutcome, account: Address) -> bool { outcome.state.get(&account).is_some_and(|account| !account.info.is_empty()) } +/* ---------- a failure revived into a success ---------- */ + /// `CALLEE` fills a fresh slot, clears a slot it held (a refund), logs a word, then reverts; -/// `CONTRACT` calls it and drops the flag. Rewritten into a success, the call is the revert it was -/// to everything but the flag `CONTRACT` drops: the transaction is the one no inspector runs, on -/// every ledger. Kept, the same writes cost state gas, history and a refund — what the rewrite -/// would otherwise have merged. +/// `CONTRACT` calls it and drops the flag. Revived into a success, the call keeps the state of the +/// revert — its journal was reverted before the inspector saw it, so no slot and no log — and +/// settles as the success: its caller merges the state gas, the history, the refund and the +/// records of the same writes kept, on every ledger. #[test] -fn test_a_failed_call_rewritten_into_a_success_settles_as_the_failure() { +fn test_a_failed_call_revived_into_a_success_settles_as_a_success() { let writes = || { BytecodeBuilder::default() .sstore(U256::from(1), U256::from(1)) @@ -212,36 +189,43 @@ fn test_a_failed_call_rewritten_into_a_success_settles_as_the_failure() { ) }; let reverting = setup(writes().revert().build()); - let stopping = setup(writes().stop().build()); + // Returning nothing costs what reverting with nothing does, so the two spend the same and the + // refund's cap is the same for both. + let stopping = setup(writes().return_empty().build()); for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); let kept = plain(stopping.clone(), minimal_envs(), tx.clone()); assert!(kept.result.is_success(), "{:?}", kept.result); - assert_eq!( - kept.gas.state, - entry(GasId::sstore_set_state_gas()), - "kept, the fresh slot costs state gas" - ); + assert_eq!(kept.gas.state, entry(GasId::sstore_set_state_gas()), "the fresh slot"); assert_eq!(kept.usage.write_records, 2, "and both slots are records"); - let failed = plain(reverting.clone(), minimal_envs(), tx.clone()); - let rewritten = inspected(reverting.clone(), minimal_envs(), tx.clone(), Revives); - assert!(failed.result.is_success(), "CONTRACT drops the flag: {:?}", failed.result); assert_keeps_only_its_body("the failed call", &tx, &failed); - assert_eq!(rewritten.result, failed.result, "no log, and the same bill"); - assert_eq!(rewritten.gas, failed.gas, "gas limit {gas_limit}: every ledger"); - assert_eq!(rewritten.usage, failed.usage, "gas limit {gas_limit}: the counts"); - assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + + let revived = inspected(reverting.clone(), minimal_envs(), tx.clone(), Revives); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert!(revived.result.logs().is_empty(), "{case}: the log went with the journal"); + assert_eq!(revived.state, failed.state, "{case}: the state is the revert's"); + assert_bills_as(&case, &revived, &kept); + assert_eq!(revived.gas.history_bytes, kept.gas.history_bytes, "{case}"); + assert_eq!(revived.usage, kept.usage, "{case}: the counts are the success's"); + assert_eq!( + revived.result.gas().inner_refunded(), + kept.result.gas().inner_refunded(), + "{case}: and so is the refund" + ); + assert_eq!(revived.gas, kept.gas, "{case}: every ledger is the success's"); } } /// `CONTRACT` sends a wei to the BN254 pairing precompile with no gas of its own: the stipend is -/// short of the pairing's price, so the call runs out of gas, and the account its value would add -/// — the upfront new-account charge its `CALL` made — goes with it. Rewritten into a success, the -/// call gives that charge back all the same: the transaction is the one no inspector runs. With the -/// gas to run, the same call adds the account and keeps the charge. +/// short of the pairing's price, so the call runs out of gas, and the account its value would add — +/// the upfront new-account charge its `CALL` made — and its start's records go with it. Revived +/// into a success, no wei moved, and the call keeps both charges, as the call that runs keeps them: +/// a success gives back neither. revm decided the start as a failure, which counted nothing, so the +/// transaction counts its body alone. #[test] -fn test_a_failed_value_call_rewritten_into_a_success_gives_the_new_account_charge_back() { +fn test_a_failed_value_call_revived_into_a_success_keeps_its_charges() { let caller = |gas: u64| { BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -255,28 +239,28 @@ fn test_a_failed_value_call_rewritten_into_a_success_gives_the_new_account_charg }; let envs = || crowded_account(minimal_envs(), PAIRING, 3); for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); let ran = plain(db(caller(1_000_000)), envs(), tx.clone()); assert!(holds_something(&ran, PAIRING), "the pairing ran and kept the wei"); assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); - let failed = plain(db(caller(0)), envs(), tx.clone()); - let rewritten = inspected(db(caller(0)), envs(), tx.clone(), Revives); assert_keeps_only_its_body("the failed call", &tx, &failed); - assert!(!holds_something(&rewritten, PAIRING), "no wei moved"); - assert_eq!(rewritten.gas, failed.gas, "gas limit {gas_limit}: every ledger"); - assert_eq!(rewritten.usage, failed.usage, "gas limit {gas_limit}: the counts"); - assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + + let revived = inspected(db(caller(0)), envs(), tx.clone(), Revives); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert!(!holds_something(&revived, PAIRING), "{case}: no wei moved"); + assert_bills_as(&case, &revived, &ran); + assert_eq!(revived.usage, body_usage(&tx), "{case}: nothing counted"); } } /// The transaction's own frame: a wei sent to the BN254 addition precompile with a point off the /// curve fails, and takes back the account EIP-2780 charged its start for and the write record -/// charged before execution. Rewritten into a success, the transaction reports the success and -/// keeps only its body, as the failure does. With a point on the curve, the same transaction adds -/// the account and keeps both charges. +/// charged before execution. Revived into a success, no wei moved, and the transaction keeps both +/// charges, as the transaction with a point on the curve keeps them; its start counted nothing. #[test] -fn test_the_transactions_own_failed_frame_rewritten_into_a_success_keeps_nothing() { +fn test_the_transactions_own_failed_frame_revived_into_a_success_keeps_its_charges() { let point_off_the_curve = { let mut input = [0_u8; 128]; input[31] = 1; @@ -285,32 +269,102 @@ fn test_the_transactions_own_failed_frame_rewritten_into_a_success_keeps_nothing }; let envs = || crowded_account(minimal_envs(), ADDITION, 3); for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); let valid = to(ADDITION, 1, Bytes::from(vec![0_u8; 128]), gas_limit); - let ran = plain(db(Bytes::new()), envs(), valid.clone()); + let ran = plain(db(Bytes::new()), envs(), valid); assert!(ran.result.is_success(), "{:?}", ran.result); assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); - let body = transaction_body_bytes(&valid); - assert_eq!(ran.gas.history_bytes, body + WRITE_RECORD_SIZE, "the body and the record"); let tx = to(ADDITION, 1, point_off_the_curve.clone(), gas_limit); let failed = plain(db(Bytes::new()), envs(), tx.clone()); assert!(failed.result.is_halt(), "{:?}", failed.result); assert_keeps_only_its_body("the failed transaction", &tx, &failed); - let rewritten = inspected(db(Bytes::new()), envs(), tx.clone(), Revives); - assert!(rewritten.result.is_success(), "the inspector's: {:?}", rewritten.result); - assert_keeps_only_its_body("the rewritten transaction", &tx, &rewritten); - assert!(!holds_something(&rewritten, ADDITION), "no wei moved"); - assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + let revived = inspected(db(Bytes::new()), envs(), tx.clone(), Revives); + assert!(revived.result.is_success(), "{case}: the inspector's: {:?}", revived.result); + assert!(!holds_something(&revived, ADDITION), "{case}: no wei moved"); + assert_eq!(revived.state, failed.state, "{case}: the state is the failure's"); + assert_bills_as(&case, &revived, &ran); + assert_eq!(revived.usage, body_usage(&tx), "{case}: nothing counted"); + } +} + +/// Turns every failed creation result into a success at `0x…01`, as Foundry's `expectRevert` on a +/// creation does: the revert's output and gas stay as they are, and the address is one the +/// creation never made. +struct RevivesCreations; + +impl Inspector for RevivesCreations { + fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) { + if !outcome.result.result.is_ok() { + outcome.result.result = InstructionResult::Return; + outcome.address = Some(Address::with_last_byte(1)); + } + } +} + +/// Where a creation case runs one init code: the code of `CONTRACT` and the transaction. +type CreationSetup<'a> = &'a dyn Fn(&[u8]) -> (Bytes, MegaTransaction); + +/// A creation whose init code fills a fresh slot, logs a word and reverts, revived into a success, +/// keeps the state of the revert — no account, no slot, no log — and settles as the creation that +/// returns no code does: the upfront charge for the account, priced at its bucket (`m = 3`), the +/// slot, the records and the log's bytes, all kept. At the transaction's own frame and one call +/// down, carrying no value and one wei, below and above the execution cap. +#[test] +fn test_a_failed_creation_revived_into_a_success_settles_as_a_success() { + let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); + // Returning no code, as long as reverting, so the transaction's own creation carries a body of + // the same size either way. + let stopping = writes().append_many([PUSH0, PUSH0, RETURN]).build(); + let reverting = writes().revert().build(); + for (gas_limit, value) in GAS_LIMITS.into_iter().flat_map(|limit| [(limit, 0), (limit, 1)]) { + let creates = |init: &[u8]| { + BytecodeBuilder::default().create(U256::from(value), init).append(POP).stop().build() + }; + let own = |init: &[u8]| { + let data = Bytes::copy_from_slice(init); + (Bytes::new(), tx_with_gas(TxKind::Create, data, U256::from(value), gas_limit)) + }; + let down = |init: &[u8]| (creates(init), to(CONTRACT, 0, Bytes::new(), gas_limit)); + let cases: [(&str, Address, CreationSetup<'_>); 2] = [ + ("the transaction's own", CALLER.create(0), &own), + ("one call down", CONTRACT.create(0), &down), + ]; + for (at, created, setup) in cases { + let envs = || crowded_account(minimal_envs(), created, 3); + let case = format!("{at}, value {value}, gas limit {gas_limit}"); + let (code, tx) = setup(&stopping[..]); + let ran = plain(db(code), envs(), tx); + assert!(holds_something(&ran, created), "{case}: run, the creation adds its account"); + assert_eq!( + ran.gas.state, + 3 * entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()), + "{case}: the account in its bucket and the slot" + ); + + let (code, tx) = setup(&reverting[..]); + let failed = plain(db(code.clone()), envs(), tx.clone()); + assert!(!holds_something(&failed, created), "{case}: reverting, it adds none"); + let revived = inspected(db(code), envs(), tx.clone(), RevivesCreations); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert!(!holds_something(&revived, created), "{case}: no account"); + assert!(revived.result.logs().is_empty(), "{case}: no log"); + assert_bills_as(&case, &revived, &ran); + assert_eq!(revived.usage, ran.usage, "{case}: the counts are the success's"); + } } } +/* ---------- a frame an inspector answers ---------- */ + /// A value call to an account that does not exist, answered by an inspector with a success, a -/// revert or a halt: the frame never started, so no wei moved and no account was added, and the -/// new-account charge its `CALL` made comes back whatever the answer. The three answers cost the -/// same, and the transaction keeps only its body. Run, the call adds the account in its bucket. +/// revert or a halt: the frame never started, so no wei moved and no account was added, and nothing +/// of the start is counted. The charges the `CALL` made for it — the account, at its bucket, and +/// the history of the records its start would make — stay charged, as for the call that runs: the +/// answer carries no flag and no start charge for revm to give back. #[test] -fn test_a_value_call_an_inspector_answers_gives_its_new_account_charge_back() { +fn test_a_value_call_an_inspector_answers_keeps_what_its_opcode_was_charged() { let caller = || value_call(EMPTY).append(POP).stop().build(); let envs = || crowded_account(minimal_envs(), EMPTY, 3); for gas_limit in GAS_LIMITS { @@ -319,27 +373,26 @@ fn test_a_value_call_an_inspector_answers_gives_its_new_account_charge_back() { assert!(holds_something(&ran, EMPTY), "the call added the account"); assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); - let answers = - [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas].map( - |result| { - let answered = - answered(|| db(caller()), envs, &tx, Answers::call(EMPTY, result)); - let case = format!("answered with {result:?}, gas limit {gas_limit}"); - assert!(answered.result.is_success(), "{case}: {:?}", answered.result); - assert_keeps_only_its_body(&case, &tx, &answered); - assert!(!holds_something(&answered, EMPTY), "{case}: no account"); - (answered.gas, answered.state.clone()) - }, - ); - assert_eq!(answers[0], answers[1], "gas limit {gas_limit}: a success costs a revert's"); + for result in + [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] + { + let case = format!("answered with {result:?}, gas limit {gas_limit}"); + let answered = + inspected(db(caller()), envs(), tx.clone(), Answers::call(EMPTY, result)); + assert!(answered.result.is_success(), "{case}: {:?}", answered.result); + assert!(!holds_something(&answered, EMPTY), "{case}: no account"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage, body_usage(&tx), "{case}: nothing counted"); + } } } /// The transaction's own value transfer to an account that does not exist, answered by an -/// inspector: the account EIP-2780 charged the frame's start for is not added, and neither is the -/// write record charged before execution, whatever the answer. +/// inspector: the account is not added and nothing is counted, and what the transaction was charged +/// before its frame ran — the account EIP-2780 charged its start for, the write record — stays +/// charged, as for the transfer that runs. #[test] -fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_nothing() { +fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_its_charges() { let envs = || crowded_account(minimal_envs(), EMPTY, 3); for gas_limit in GAS_LIMITS { let tx = to(EMPTY, 1, Bytes::new(), gas_limit); @@ -348,19 +401,23 @@ fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_nothing() for result in [InstructionResult::Stop, InstructionResult::Revert] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); - let answered = answered(|| db(Bytes::new()), envs, &tx, Answers::call(EMPTY, result)); + let answered = + inspected(db(Bytes::new()), envs(), tx.clone(), Answers::call(EMPTY, result)); assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); - assert_keeps_only_its_body(&case, &tx, &answered); assert!(!holds_something(&answered, EMPTY), "{case}: no account"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage, body_usage(&tx), "{case}: nothing counted"); } } } -/// A creation an inspector answers adds no account, whatever the answer — a success with an -/// address, a success with none, a revert — so the creation's upfront charge comes back once, and -/// the three answers cost the same. Run, the creation adds its account in its bucket. +/// A creation an inspector answers adds no account and bumps no nonce, whatever the answer — a +/// success with an address, a success with none, a revert — and the charges its `CREATE` made stay +/// charged, as for the creation that runs: the account at its bucket, the history of its records. +/// It counts no record: the creator's nonce was not bumped, so no record of it stands. The three +/// answers cost the same. #[test] -fn test_a_creation_an_inspector_answers_gives_its_charge_back() { +fn test_a_creation_an_inspector_answers_keeps_what_its_opcode_was_charged() { let caller = || create_with(&[STOP]).append(POP).stop().build(); let created = CONTRACT.create(0); let envs = || crowded_account(minimal_envs(), created, 3); @@ -369,6 +426,7 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { let ran = plain(db(caller()), envs(), tx.clone()); assert!(ran.result.is_success(), "{:?}", ran.result); assert_eq!(ran.gas.state, 3 * entry(GasId::create_state_gas()), "in its bucket"); + let nonce = ran.state[&CONTRACT].info.nonce; let answers = [ (InstructionResult::Return, Some(ANSWERED)), @@ -376,11 +434,14 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { (InstructionResult::Revert, None), ] .map(|(result, address)| { - let answered = answered(|| db(caller()), envs, &tx, Answers::creation(result, address)); let case = format!("answered with {result:?}, gas limit {gas_limit}"); + let answers = Answers::creation(result, address); + let answered = inspected(db(caller()), envs(), tx.clone(), answers); assert!(answered.result.is_success(), "{case}: {:?}", answered.result); - assert_keeps_only_its_body(&case, &tx, &answered); assert!(!holds_something(&answered, created), "{case}: no account"); + assert_eq!(answered.state[&CONTRACT].info.nonce, nonce - 1, "{case}: no bump"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage.write_records, 0, "{case}: no bump, no record"); answered.gas }); assert_eq!(answers[0], answers[1], "gas limit {gas_limit}: with an address or without"); @@ -388,11 +449,11 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { } } -/// The transaction's own creation, answered by an inspector: the account EIP-2780 charged the -/// frame's start for is not added, and neither is the write record charged before execution, -/// whatever the answer. Run, the creation adds its account in its bucket. +/// The transaction's own creation, answered by an inspector: the account is not added and nothing +/// is counted, and what the transaction was charged before its frame ran — the account EIP-2780 +/// charged its start for, the write record — stays charged, as for the creation that runs. #[test] -fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { +fn test_the_transactions_own_creation_an_inspector_answers_keeps_its_charges() { let created = CALLER.create(0); let envs = || crowded_account(minimal_envs(), created, 3); for gas_limit in GAS_LIMITS { @@ -407,42 +468,16 @@ fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { (InstructionResult::Revert, None), ] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); - let answered = - answered(|| db(Bytes::new()), envs, &tx, Answers::creation(result, address)); + let answers = Answers::creation(result, address); + let answered = inspected(db(Bytes::new()), envs(), tx.clone(), answers); assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); - assert_keeps_only_its_body(&case, &tx, &answered); assert!(!holds_something(&answered, created), "{case}: no account"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage, body_usage(&tx), "{case}: nothing counted"); } } } -/// A value call an inspector answers leaves its caller holding none of the state gas its `CALL` -/// was charged for the account: the charge came back. The caller then fills a slot, and holds the -/// slot alone, where the caller whose call ran holds the slot and the account. -#[test] -fn test_an_answered_call_leaves_its_caller_none_of_the_accounts_state_gas() { - let caller = - || value_call(EMPTY).append(POP).sstore(U256::from(1), U256::from(1)).stop().build(); - let slot = entry(GasId::sstore_set_state_gas()); - let tx = to(CONTRACT, 0, Bytes::new(), GAS_LIMITS[0]); - let context = || salt_context(db(caller()), minimal_envs()); - - let ran = MegaEvm::new(context()).execute_transaction(tx.clone()).unwrap(); - assert!(ran.result.is_success(), "{:?}", ran.result); - assert_eq!( - ran.gas.state, - slot + entry(GasId::new_account_state_gas()), - "the slot and the account" - ); - - let answered = MegaEvm::new(context()) - .with_inspector(Answers::call(EMPTY, InstructionResult::Stop)) - .execute_transaction(tx) - .unwrap(); - assert!(answered.result.is_success(), "{:?}", answered.result); - assert_eq!(answered.gas.state, slot, "the slot alone"); -} - /* ---------- a call an inspector retargets ---------- */ /// The address `Retargets` sends a call to. @@ -477,18 +512,18 @@ impl Inspector for Retargets } /// A value call to an account that does not exist charges that account's state gas upfront, in its -/// SALT bucket. An inspector that redirects the call to another account, whose bucket is priced -/// otherwise, changes which account the charge comes back for: it comes back at the price it was -/// made at, the original account's, whatever the new target costs. Both ways — the account dearer -/// than the new target (`m` = 8 and 1) and cheaper (1 and 8) — the call answered in place of -/// running, and the call that runs and reverts, keep nothing: no state gas, the body's history -/// alone, and the reservoir back where it started. A refund at the new target's price would leave -/// state gas behind in one direction and drive the state ledger negative, growing the reservoir, -/// in the other. +/// SALT bucket. An inspector that redirects the call to another account rewrites the inputs revm +/// reads the charge's account off when the frame fails: the call that runs at the new target and +/// reverts gives the charge back at the new target's price. Where the account is dearer (`m` = 8 +/// and 1) the transaction keeps the difference as state gas; where it is cheaper (1 and 8) more +/// comes back than was charged, which revm credits to the reservoir, so the state ledger reads +/// nothing and the sender gets the excess back with the reservoir. The call answered in place of +/// running gives back nothing, as every answer does. #[test] -fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_price_it_was_made_at() { +fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_new_targets_price() { let caller = || value_call(EMPTY).append(POP).stop().build(); let reverts = Bytecode::new_raw(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let account = entry(GasId::new_account_state_gas()); for (account_m, retarget_m) in [(8, 1), (1, 8)] { let envs = || { crowded_account(crowded_account(minimal_envs(), EMPTY, account_m), RETARGET, retarget_m) @@ -499,85 +534,32 @@ fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_price_it_was_m let ran = plain(db(), envs(), tx.clone()); assert_eq!( ran.gas.state, - account_m * entry(GasId::new_account_state_gas()), + account_m * account, "{account_m}/{retarget_m}: run, the call adds the account in its bucket" ); - for (name, answer) in - [("answered", Some(InstructionResult::Stop)), ("running and reverting", None)] - { - let case = format!("{name}, m {account_m}/{retarget_m}, gas limit {gas_limit}"); - let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer }; - let outcome = inspected(db(), envs(), tx.clone(), inspector); - assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); - assert_keeps_only_its_body(&case, &tx, &outcome); - assert!(!holds_something(&outcome, EMPTY), "{case}: no account"); - } - } - } -} - -/* ---------- a failed creation rewritten into a success ---------- */ - -/// Turns every failed creation result into a success at `0x…01`, as Foundry's `expectRevert` on a -/// creation does: the revert's output and gas stay as they are, and the address is one the -/// creation never made. -struct RevivesCreations; - -impl Inspector for RevivesCreations { - fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) { - if !outcome.result.result.is_ok() { - outcome.result.result = InstructionResult::Return; - outcome.address = Some(Address::with_last_byte(1)); - } - } -} - -/// A creation whose init code fills a fresh slot, logs a word and reverts, rewritten into a -/// success, is the failure it was to everything but the address its creator is handed: every -/// ledger, the counts and the state are those of the run no inspector touches. The upfront charge -/// the `CREATE` made for the account comes back, priced at the account it was made for — its bucket -/// is crowded (`m = 3`) — and the slot, the log and the account are not kept. At the transaction's -/// own frame and one call down, carrying no value and one wei, below and above the execution cap; -/// run, the creation adds its account. -#[test] -fn test_a_failed_creation_rewritten_into_a_success_settles_as_the_failure() { - let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); - let (reverting, stopping) = (writes().revert().build(), writes().stop().build()); - for (gas_limit, value) in GAS_LIMITS.into_iter().flat_map(|limit| [(limit, 0), (limit, 1)]) { - let creates = |init: &[u8]| { - BytecodeBuilder::default().create(U256::from(value), init).append(POP).stop().build() - }; - let own = |init: &[u8]| { - let data = Bytes::copy_from_slice(init); - (Bytes::new(), tx_with_gas(TxKind::Create, data, U256::from(value), gas_limit)) - }; - let down = |init: &[u8]| (creates(init), to(CONTRACT, 0, Bytes::new(), gas_limit)); - let cases: [(&str, Address, CreationSetup<'_>); 2] = [ - ("the transaction's own", CALLER.create(0), &own), - ("one call down", CONTRACT.create(0), &down), - ]; - for (at, created, setup) in cases { - let envs = || crowded_account(minimal_envs(), created, 3); - let case = format!("{at}, value {value}, gas limit {gas_limit}"); - let (code, tx) = setup(&stopping[..]); - let ran = plain(db(code), envs(), tx); - assert!(holds_something(&ran, created), "{case}: run, the creation adds its account"); + let case = format!("m {account_m}/{retarget_m}, gas limit {gas_limit}"); + let answer = Some(InstructionResult::Stop); + let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer }; + let answered = inspected(db(), envs(), tx.clone(), inspector); + assert!(answered.result.is_success(), "{case}: {:?}", answered.result); + assert_eq!(answered.gas.state, account_m * account, "{case}: answered, kept whole"); + + let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer: None }; + let reverted = inspected(db(), envs(), tx.clone(), inspector); + assert!(reverted.result.is_success(), "{case}: {:?}", reverted.result); + assert!(!holds_something(&reverted, EMPTY), "{case}: no account"); + let body = history_gas(transaction_body_bytes(&tx)).unwrap(); + assert_eq!(reverted.gas.history, body, "{case}: the start's records given back"); + let kept = i128::from(account_m * account) - i128::from(retarget_m * account); + let reservoir = + i128::from(gas_limit.saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(body)); + let reservoir = if reservoir == 0 { (-kept).max(0) } else { reservoir - kept }; assert_eq!( - ran.gas.state, - 3 * entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()), - "{case}: the account in its bucket and the slot" + i128::from(reverted.gas.state), + kept.max(0), + "{case}: reverting, given back at the new target's price" ); - - let (code, tx) = setup(&reverting[..]); - let failed = plain(db(code.clone()), envs(), tx.clone()); - assert!(!holds_something(&failed, created), "{case}: reverting, it adds none"); - let rewritten = inspected(db(code), envs(), tx.clone(), RevivesCreations); - assert!(rewritten.result.is_success(), "{case}: {:?}", rewritten.result); - assert!(!holds_something(&rewritten, created), "{case}: no account"); - assert!(rewritten.result.logs().is_empty(), "{case}: no log"); - assert_eq!(rewritten.gas, failed.gas, "{case}: every ledger"); - assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); - assert_eq!(rewritten.state, failed.state, "{case}: the state"); + assert_eq!(i128::from(reverted.gas.reservoir_remaining), reservoir, "{case}"); } } } @@ -640,7 +622,7 @@ impl Inspector for Fails { /// Runs `tx` over `db()` reading `envs()` under `fails`, and again under the same inspector /// rewriting nothing; hands back the first once the journal's depth was the same at every -/// instruction of both: taking a frame's journal back leaves the depth as it was. +/// instruction of both: a rewrite leaves the depth as it was. fn rewritten( db: impl Fn() -> MemoryDatabase, envs: impl Fn() -> SaltEnvs, @@ -661,35 +643,15 @@ fn rewritten( /// The failures a success is rewritten into: Foundry's revert, and a halt. const FAILURES: [InstructionResult; 2] = [InstructionResult::Revert, InstructionResult::OutOfGas]; -/// An account as a state is compared on without its code: status, balance, nonce and storage. -type AccountBesideCode = (Address, AccountStatus, U256, u64, Vec<(U256, EvmStorageSlot)>); - -/// `outcome`'s state without the code of its accounts, in address order: what two runs whose -/// programs differ in their last opcodes are compared on. -fn state_without_code(outcome: &MegaTransactionOutcome) -> Vec { - let mut accounts: Vec<_> = outcome - .state - .iter() - .map(|(address, account)| { - let mut storage: Vec<_> = - account.storage.iter().map(|(key, slot)| (*key, slot.clone())).collect(); - storage.sort_by_key(|(key, _)| *key); - (*address, account.status, account.info.balance, account.info.nonce, storage) - }) - .collect(); - accounts.sort_by_key(|(address, ..)| *address); - accounts -} - -/// A value call that adds an account, rewritten into a failure, keeps nothing. `EMPTY` has no code, -/// so revm answers the call without building a frame, and what its start journaled — the value's -/// move, the account it touched, the transfer log — is taken back to where the start began: the -/// value stays with its sender and no account is added. The failure then settles as the same -/// failure an inspector answers in place of the call does, on every ledger and in the state: no -/// state gas, the body's history alone. At the transaction's own frame and one call down, below -/// and above the execution cap; run, the call adds the account and logs the transfer. +/// A value call that adds an account, rewritten into a failure, settles as a failure and keeps the +/// state of its success. `EMPTY` has no code, so revm answers the call without building a frame and +/// commits what its start journaled — the value's move, the account it adds, the transfer log — +/// before the inspector sees the result: the wei stays with `EMPTY`. The failure gives back the +/// upfront charge for the account, the history of the start's records and the records themselves, +/// so the transaction bills its body alone. At the transaction's own frame and one call down, +/// below and above the execution cap. #[test] -fn test_a_value_call_rewritten_into_a_failure_keeps_nothing() { +fn test_a_value_call_rewritten_into_a_failure_keeps_its_state_and_bills_its_body() { let envs = || crowded_account(minimal_envs(), EMPTY, 3); let caller = value_call(EMPTY).append(POP).stop().build(); for gas_limit in GAS_LIMITS { @@ -701,33 +663,27 @@ fn test_a_value_call_rewritten_into_a_failure_keeps_nothing() { let db = || db(code.clone()); let ran = plain(db(), envs(), tx.clone()); assert!(holds_something(&ran, EMPTY), "{at}: run, the call adds the account"); - assert_eq!(ran.result.logs().len(), 1, "{at}: and logs the transfer"); for result in FAILURES { let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); let rewritten = rewritten(db, envs, &tx, Fails::call(EMPTY, result)); - let answered = inspected(db(), envs(), tx.clone(), Answers::call(EMPTY, result)); + assert!(holds_something(&rewritten, EMPTY), "{case}: the wei moved"); + assert_eq!( + rewritten.state[&EMPTY].info, ran.state[&EMPTY].info, + "{case}: the account the success added" + ); assert_keeps_only_its_body(&case, &tx, &rewritten); - assert!(!holds_something(&rewritten, EMPTY), "{case}: no account"); - assert!(rewritten.result.logs().is_empty(), "{case}: no transfer log"); - assert_eq!(rewritten.gas, answered.gas, "{case}: every ledger"); - assert_eq!(rewritten.usage, answered.usage, "{case}: every count"); - assert_eq!(rewritten.state, answered.state, "{case}: the state"); } } } } -/// Where a creation case runs one init code: the code of `CONTRACT` and the transaction. -type CreationSetup<'a> = &'a dyn Fn(&[u8]) -> (Bytes, MegaTransaction); - -/// A creation rewritten into a failure keeps what a creation that fails keeps: its creator's nonce -/// bump, which revm makes before the creation's checkpoint, and its record — nothing after the -/// checkpoint: no account, no code, no endowment. It settles as a creation whose init code reverts -/// in place of returning does, on the state beside the code, state and history gas and the counts; -/// a revert keeps the regular gas the run spent. At the transaction's own frame and one call down, -/// below and above the execution cap; run, the creation adds its account. +/// A creation rewritten into a failure keeps the state of its success — its account, its code and +/// its endowment — and settles as the creation whose init code reverts in place of returning does: +/// its creator's nonce record, which outlives the creation, and nothing of the creation's own — no +/// state gas, no history and no record of the account. At the transaction's own frame and one call +/// down, below and above the execution cap. #[test] -fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() { +fn test_a_creation_rewritten_into_a_failure_keeps_its_state_and_settles_as_a_failure() { let (deploys, reverts) = (&[PUSH0, PUSH0, RETURN][..], &[PUSH0, PUSH0, REVERT][..]); let creates = |init: &[u8]| { BytecodeBuilder::default().create(U256::from(1), init).append(POP).stop().build() @@ -753,16 +709,13 @@ fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); let rewritten = rewritten(|| db(deploying.clone()), envs, &tx, Fails::creation(result)); - assert!(!holds_something(&rewritten, created), "{case}: no account"); - let state = state_without_code(&rewritten); - assert_eq!(state, state_without_code(&failed), "{case}: the state"); + assert_eq!( + rewritten.state[&created].info.balance, ran.state[&created].info.balance, + "{case}: the account and its endowment" + ); assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); - assert_eq!(rewritten.gas.state, failed.gas.state, "{case}: state gas"); - assert_eq!(rewritten.gas.history, failed.gas.history, "{case}: history gas"); + assert_bills_as(&case, &rewritten, &failed); assert_eq!(rewritten.gas.history_bytes, failed.gas.history_bytes, "{case}"); - if result == InstructionResult::Revert { - assert_eq!(rewritten.gas.regular, ran.gas.regular, "{case}: regular gas"); - } } } } @@ -772,13 +725,12 @@ fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() type CallSetup<'a> = &'a dyn Fn(&Bytes) -> MemoryDatabase; /// A call whose frame ran and wrote — a fresh slot filled and a word logged — rewritten into a -/// failure keeps none of it: the frame's journal is taken back to its checkpoint, so the slot is -/// not in the state and the log is not in the receipt. It settles as the same writes reverting do, -/// on the state beside the code, state and history gas and the counts; a revert keeps the regular -/// gas the run spent. At the transaction's own frame and one call down, below and above the -/// execution cap; run, the slot and the log are kept. +/// failure keeps its writes: revm committed the frame's checkpoint before the inspector saw the +/// result, so the slot is in the state, and one call down the log is in the receipt. It settles as +/// the same writes reverting do: their state gas, history and records given back. At the +/// transaction's own frame and one call down, below and above the execution cap. #[test] -fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_none_of_it() { +fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_its_writes_and_settles_as_a_failure() { let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); let (stopping, reverting) = (writes().stop().build(), writes().revert().build()); let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); @@ -792,23 +744,18 @@ fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_none_of_it() { let slot = |outcome: &MegaTransactionOutcome| { outcome.state[&writer].storage.get(&U256::from(1)).is_some_and(|s| s.is_changed()) }; - let ran = plain(setup(&stopping), minimal_envs(), tx.clone()); - assert!(slot(&ran) && !ran.result.logs().is_empty(), "{at}: run, the writes are kept"); let failed = plain(setup(&reverting), minimal_envs(), tx.clone()); + assert!(!slot(&failed), "{at}: reverting, the slot is not kept"); for result in FAILURES { let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); let fails = Fails::call(writer, result); let rewritten = rewritten(|| setup(&stopping), minimal_envs, &tx, fails); - assert!(!slot(&rewritten), "{case}: no slot"); - assert!(rewritten.result.logs().is_empty(), "{case}: no log"); - let state = state_without_code(&rewritten); - assert_eq!(state, state_without_code(&failed), "{case}: the state"); - assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); - assert_eq!(rewritten.gas.state, failed.gas.state, "{case}: state gas"); - assert_eq!(rewritten.gas.history, failed.gas.history, "{case}: history gas"); - if result == InstructionResult::Revert { - assert_eq!(rewritten.gas.regular, ran.gas.regular, "{case}: regular gas"); + assert!(slot(&rewritten), "{case}: the slot stays"); + if writer == CALLEE { + assert_eq!(rewritten.result.logs().len(), 1, "{case}: and the log"); } + assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); + assert_bills_as(&case, &rewritten, &failed); } } } @@ -841,13 +788,11 @@ impl Inspector, EthInterpreter> for Writes } } -/// What an inspector writes to the journal in the callback that turns a success into a failure is -/// journaled after the frame's checkpoint, and goes with the frame's writes; written in a callback -/// that leaves the success alone, it stays. Where revm fails the frame itself, the checkpoint is -/// gone before `call_end`, so a write made there stays: the one place the rewrite and a real -/// failure part. +/// What an inspector writes to the journal in `call_end` comes after the frame's checkpoint was +/// committed or reverted, so it stays whatever the frame's result says: left a success, turned into +/// a failure, or failed by revm itself. #[test] -fn test_a_write_an_inspector_makes_as_it_fails_a_frame_goes_with_the_frame() { +fn test_a_write_an_inspector_makes_at_a_frames_end_stays() { let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); let db = |callee: Bytes| db(caller.clone()).account_code(CALLEE, callee); let stopping = BytecodeBuilder::default().stop().build(); @@ -857,6 +802,313 @@ fn test_a_write_an_inspector_makes_as_it_fails_a_frame_goes_with_the_frame() { inspected(db(callee.clone()), minimal_envs(), tx.clone(), WritesAtTheEnd { fails }) }; assert!(holds_something(&run(&stopping, false), NOTE), "left a success, the write stays"); - assert!(!holds_something(&run(&stopping, true), NOTE), "failing it, the write goes"); + assert!(holds_something(&run(&stopping, true), NOTE), "failing it, the write stays"); assert!(holds_something(&run(&reverting, false), NOTE), "revm failed it: the write stays"); } + +/// Rewrites the creator of every creation to `creator`: Foundry's `vm.prank` before `new C()`. +struct Pranks { + creator: Address, +} + +impl Inspector for Pranks { + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + inputs.set_call(self.creator); + None + } +} + +/// A creation whose creator an inspector rewrites to an account the transaction already changed +/// (the sender, whose validation changed it) runs, and counts the records of what revm did: the +/// account it created, and no record of the rewritten creator, whose bump changed an account +/// changed already. The opcode's creator was never bumped and has no record either; what its +/// opcode was charged for one stays charged. +#[test] +fn test_a_creation_whose_creator_an_inspector_rewrites_to_a_changed_account_runs() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let outcome = inspected(db(caller()), minimal_envs(), tx, Pranks { creator: CALLER }); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 1, "the created account alone"); +} + +/// A creation whose creator an inspector rewrites to an account the transaction has not changed +/// counts that account's nonce record, the record of the account revm bumped, and, the account +/// being empty, one account of state growth for the account the bump made, with the created +/// account's record and growth. +#[test] +fn test_a_creation_whose_creator_an_inspector_rewrites_to_an_empty_account_counts_its_record() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let outcome = inspected(db(caller()), minimal_envs(), tx, Pranks { creator: EMPTY }); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.state[&EMPTY].info.nonce, 1, "revm bumped the rewritten creator"); + assert_eq!(outcome.usage.write_records, 2, "its nonce record and the created account's"); + assert_eq!(outcome.usage.state_growth, 2, "its account, which the bump made, and the created"); +} + +/// A contract `CONTRACT` calls to send a wei to `CALLEE`, which changes `CALLEE` and leaves +/// `CONTRACT` unchanged. +const SENDER: Address = address!("0000000000000000000000000000000000c00011"); + +/// A rewrite of a frame's start, made in the inspector's `call` or `create` after the start's hook +/// charged for the records the start would make. +#[derive(Clone, Copy, Debug)] +enum Rewrite { + /// A zero-value call to `CALLEE` carries a wei: the start moves value between two accounts + /// it left unchanged, two records. + Value, + /// A creation's creator becomes `CALLEE`, which `SENDER` changed: the creator's nonce bump + /// makes no record of its own. + Creator, +} + +impl Rewrite { + /// `CONTRACT`'s code, which makes the start the rewrite is for. + fn code(self) -> Bytes { + match self { + Self::Value => BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP), + Self::Creator => BytecodeBuilder::default() + .call(SENDER, U256::ZERO) + .append(POP) + .append_many(create_with(&[STOP]).build_vec()) + .append(POP), + } + .stop() + .build() + } + + /// The state the rewritten run reads: `CONTRACT` and `SENDER` funded, `SENDER` sending a wei. + fn db(self) -> MemoryDatabase { + db(self.code()) + .account_balance(SENDER, U256::from(10u64.pow(9))) + .account_code(SENDER, value_call(CALLEE).append(POP).stop().build()) + } +} + +impl Inspector for Rewrite { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + if matches!(self, Self::Value) && inputs.target_address == CALLEE { + inputs.value = CallValue::Transfer(U256::from(1)); + } + None + } + + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + if matches!(self, Self::Creator) { + inputs.set_call(CALLEE); + } + None + } +} + +/// Every way a tool runs an inspector: alloy-evm's `transact` with the inspector enabled, and +/// revm's `InspectEvm`, `InspectCommitEvm` and `InspectSystemCallEvm` called directly, with +/// alloy-evm's switch off. +#[derive(Clone, Copy, Debug)] +enum Entry { + AlloyTransact, + InspectOneTx, + InspectTx, + InspectOne, + Inspect, + InspectTxCommit, + InspectCommit, + InspectOneSystemCall, + InspectOneSystemCallWithCaller, + InspectSystemCall, + InspectSystemCallWithCaller, + InspectOneSystemCallWithInspector, + InspectSystemCallWithInspector, + InspectOneSystemCallWithInspectorAndCaller, + InspectSystemCallWithInspectorAndCaller, +} + +impl Entry { + const ALL: [Self; 15] = [ + Self::AlloyTransact, + Self::InspectOneTx, + Self::InspectTx, + Self::InspectOne, + Self::Inspect, + Self::InspectTxCommit, + Self::InspectCommit, + Self::InspectOneSystemCall, + Self::InspectOneSystemCallWithCaller, + Self::InspectSystemCall, + Self::InspectSystemCallWithCaller, + Self::InspectOneSystemCallWithInspector, + Self::InspectSystemCallWithInspector, + Self::InspectOneSystemCallWithInspectorAndCaller, + Self::InspectSystemCallWithInspectorAndCaller, + ]; + + /// Runs a zero-value call to `CONTRACT` under `rewrite` through this entry point: a transaction + /// from `CALLER`, or a system call. + fn run(self, rewrite: Rewrite) -> ExecutionResult { + use mega_evm::alloy_evm::Evm as _; + use revm::{InspectCommitEvm, InspectEvm, InspectSystemCallEvm}; + let mut evm = + MegaEvm::new(salt_context(rewrite.db(), minimal_envs())).with_inspector(rewrite); + if !matches!(self, Self::AlloyTransact) { + evm.set_inspector_enabled(false); + } + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let (caller, data) = (SYSTEM_ADDRESS, Bytes::new()); + let result = match self { + Self::AlloyTransact => { + return evm.execute_transaction(tx).expect("valid").result_and_state.result + } + Self::InspectOneTx => evm.inspect_one_tx(tx), + Self::InspectTx => evm.inspect_tx(tx).map(|done| done.result), + Self::InspectOne => evm.inspect_one(tx, rewrite), + Self::Inspect => evm.inspect(tx, rewrite).map(|done| done.result), + Self::InspectTxCommit => evm.inspect_tx_commit(tx), + Self::InspectCommit => evm.inspect_commit(tx, rewrite), + Self::InspectOneSystemCall => evm.inspect_one_system_call(CONTRACT, data), + Self::InspectOneSystemCallWithCaller => { + evm.inspect_one_system_call_with_caller(caller, CONTRACT, data) + } + Self::InspectSystemCall => evm.inspect_system_call(CONTRACT, data).map(|r| r.result), + Self::InspectSystemCallWithCaller => { + evm.inspect_system_call_with_caller(caller, CONTRACT, data).map(|r| r.result) + } + Self::InspectOneSystemCallWithInspector => { + evm.inspect_one_system_call_with_inspector(CONTRACT, data, rewrite) + } + Self::InspectSystemCallWithInspector => { + evm.inspect_system_call_with_inspector(CONTRACT, data, rewrite).map(|r| r.result) + } + Self::InspectOneSystemCallWithInspectorAndCaller => evm + .inspect_one_system_call_with_inspector_and_caller(caller, CONTRACT, data, rewrite), + Self::InspectSystemCallWithInspectorAndCaller => evm + .inspect_system_call_with_inspector_and_caller(caller, CONTRACT, data, rewrite) + .map(|r| r.result), + }; + result.expect("valid") + } +} + +/// An inspector may rewrite a frame's start after the start's hook charged for its records — a +/// call's value, a creation's creator — whichever entry point runs it: the run settles the start +/// revm made. +#[test] +fn test_every_inspected_entry_point_runs_a_start_an_inspector_rewrote() { + for entry in Entry::ALL { + for rewrite in [Rewrite::Value, Rewrite::Creator] { + let result = entry.run(rewrite); + assert!(result.is_success(), "{entry:?}, {rewrite:?}: {result:?}"); + } + } +} + +/// The records a rewritten start counts are those revm made. A zero-value call rewritten to carry +/// a wei moves it between `CONTRACT` and `CALLEE`, two accounts the transaction left unchanged +/// until then: two records and the transfer log. A creation whose creator is rewritten to `CALLEE`, +/// which `SENDER`'s wei changed, bumps an account changed already, which makes no record: the +/// transaction keeps `SENDER`'s transfer, two records and its log, and the created account. +#[test] +fn test_a_rewritten_start_counts_the_records_revm_made() { + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + for (rewrite, records, logs) in [(Rewrite::Value, 2, 1), (Rewrite::Creator, 3, 1)] { + let outcome = inspected(rewrite.db(), minimal_envs(), tx.clone(), rewrite); + assert!(outcome.result.is_success(), "{rewrite:?}: {:?}", outcome.result); + assert_eq!(outcome.usage.write_records, records, "{rewrite:?}"); + assert_eq!(outcome.result.logs().len(), logs, "{rewrite:?}: the transfer log"); + } +} + +/// Raises the endowment of every creation to `value`. +struct Endows { + value: U256, +} + +impl Inspector for Endows { + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + inputs.set_value(self.value); + None + } +} + +/// A creation revm refuses on its creator's account — an inspector raised the endowment past the +/// creator's balance — bumps no nonce and makes no frame, so it counts no record: the transaction +/// keeps its body alone, at either gas limit. What the `CREATE` was charged at its opcode stays +/// charged, as for a start an inspector answers: the history of the created account's record, +/// which the start declared, comes back with the refusal, and that of the creator's record, which +/// it did not declare, stays. +#[test] +fn test_a_creation_refused_on_its_creators_account_counts_no_record() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(caller()), minimal_envs(), tx.clone()); + let nonce = ran.state[&CONTRACT].info.nonce; + let refused = + inspected(db(caller()), minimal_envs(), tx.clone(), Endows { value: U256::MAX }); + assert!(refused.result.is_success(), "{case}: {:?}", refused.result); + assert_eq!(refused.state[&CONTRACT].info.nonce, nonce - 1, "{case}: no bump"); + assert_keeps_only_its_body_and_the_opcodes_charge(&case, &tx, &refused); + } +} + +/// [`assert_keeps_only_its_body`], for a creation an inspector made revm refuse: the history of +/// the record of its creator's nonce, which its `CREATE` was charged and its start did not declare, +/// is on the history ledger beyond the body's bytes. +fn assert_keeps_only_its_body_and_the_opcodes_charge( + case: &str, + tx: &MegaTransaction, + outcome: &MegaTransactionOutcome, +) { + let body = transaction_body_bytes(tx); + let charged = history_gas(body + mega_evm::WRITE_RECORD_SIZE).unwrap(); + assert_eq!(outcome.gas.state, 0, "{case}: no state gas"); + assert_eq!(outcome.gas.history, charged, "{case}: the body's history and the opcode's charge"); + assert_eq!( + outcome.gas.reservoir_remaining, + tx.gas_limit().saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(charged), + "{case}: the reservoir less what the history ledger bills" + ); + assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); + assert_eq!(outcome.usage, body_usage(tx), "{case}"); +} + +/// A refused creation draws nothing on its creator's pool: the creator writes one fresh slot after +/// it, and that write's record fits a data-size limit of the body and 40 bytes, and no tighter +/// one. +#[test] +fn test_a_refused_creation_leaves_its_creators_pool_whole() { + let code = || create_with(&[STOP]).append(POP).sstore(U256::ZERO, U256::from(1)).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let run = |limit: u64| { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + MegaEvm::new(salt_context(db(code()), minimal_envs()).with_tx_runtime_limits(limits)) + .with_inspector(Endows { value: U256::MAX }) + .execute_transaction(tx.clone()) + .expect("a valid transaction") + }; + let fits = transaction_body_bytes(&tx) + 40; + let kept = run(fits); + assert!(kept.result.is_success(), "{:?}", kept.result); + assert_eq!(kept.limit_exceeded, None, "the one slot's record fits"); + assert_eq!(kept.usage.write_records, 1, "the slot's record, and not the creator's"); + assert!(run(fits - 1).limit_exceeded.is_some(), "one byte less does not"); +} + +/// A creator with nothing left in its pool, whose creation revm refuses, is held to nothing: no +/// record was counted, and it resumes within its budget. +#[test] +fn test_a_refused_creation_holds_an_empty_pool_to_nothing() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(transaction_body_bytes(&tx)); + let refused = + MegaEvm::new(salt_context(db(caller()), minimal_envs()).with_tx_runtime_limits(limits)) + .with_inspector(Endows { value: U256::MAX }) + .execute_transaction(tx.clone()) + .expect("a valid transaction"); + assert!(refused.result.is_success(), "{:?}", refused.result); + assert_eq!(refused.limit_exceeded, None, "no stop"); + assert_keeps_only_its_body_and_the_opcodes_charge("empty pool", &tx, &refused); +} diff --git a/crates/mega-evm/tests/satin/kv_updates.rs b/crates/mega-evm/tests/satin/kv_updates.rs new file mode 100644 index 000000000..dfb1af658 --- /dev/null +++ b/crates/mega-evm/tests/satin/kv_updates.rs @@ -0,0 +1,285 @@ +//! The KV-update limit: the write records a transaction keeps, held per transaction at +//! `TX_KV_UPDATE_LIMIT` and per frame at 98/100 of what the parent has left, rounded down. A record +//! that crosses either stops the frame that makes it with `MegaLimitExceeded(1, limit)`, naming the +//! frame's budget when the record crosses it, and its caller resumes. +//! +//! Every figure is hand arithmetic from the record rules: a fresh slot's first write is one record, +//! a write back to its original takes it back. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::{TX_DATA_LIMIT, TX_KV_UPDATE_LIMIT}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaLimitExceeded, MegaSpecId, + MegaTransactionOutcome, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE}, + context::result::ExecutionResult, +}; + +use crate::common::{call, execute_under, share}; + +const CALLER: Address = address!("0000000000000000000000000000000000740000"); +const A: Address = address!("0000000000000000000000000000000000740001"); +const B: Address = address!("0000000000000000000000000000000000740002"); +const C: Address = address!("0000000000000000000000000000000000740003"); +const D: Address = address!("0000000000000000000000000000000000740004"); + +/// Room for a few hundred fresh slots and the calls around them, at any byte price the grid runs. +const GAS_LIMIT: u64 = 2_000_000_000; + +/// Writes the fresh slots `from..from + count`. +fn writes(code: BytecodeBuilder, from: u64, count: u64) -> BytecodeBuilder { + (from..from + count).fold(code, |code, slot| code.sstore(U256::from(slot), U256::from(1))) +} + +/// Calls `to` with all its gas, then returns what the call returned or reverted with. +fn then_call_returning(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(to) + .append_many([GAS, CALL, POP, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([RETURNDATASIZE, PUSH0, RETURN]) +} + +/// The revert data of a KV stop naming `limit`. +fn kv_stop(limit: u64) -> Bytes { + MegaLimitExceeded { kind: LimitKind::KvUpdate.as_u8(), limit }.abi_encode().into() +} + +/// Runs a call to `A` over `db` under `limits`. +fn run(db: MemoryDatabase, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + execute_under(db, call(CALLER, A, U256::ZERO, GAS_LIMIT), limits) +} + +/// Limits holding the transaction to `records` write records, and nothing else. +fn kv(records: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(records) +} + +/// The spec's numbers: 500,000 records per transaction, more than the data size can hold at 40 +/// bytes each, which is why the data size binds first at the protocol's values. +#[test] +fn test_the_kv_limit_is_the_specs() { + assert_eq!(TX_KV_UPDATE_LIMIT, 500_000); + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + assert_eq!(limits.tx_kv_update_limit, TX_KV_UPDATE_LIMIT); + const { + assert!( + TX_KV_UPDATE_LIMIT * WRITE_RECORD_SIZE > TX_DATA_LIMIT, + "data size is the tighter cap" + ) + }; + assert_eq!(EvmTxRuntimeLimits::no_limits().tx_kv_update_limit, u64::MAX); +} + +/// The transaction's own frame gets what the transaction has left — all ten records of a limit of +/// ten when nothing was counted before it — and the eleventh record stops it, kind 1, naming that +/// budget. The stop settles as a revert and keeps nothing the frame wrote; ten records fit. +#[test] +fn test_the_eleventh_record_stops_the_transactions_own_frame() { + let db = |count| { + MemoryDatabase::default() + .account_code(A, writes(BytecodeBuilder::default(), 1, count).stop().build()) + }; + let fits = run(db(10), kv(10)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 10); + + let stopped = run(db(11), kv(10)); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::KvUpdate, + limit: 10, + used: 11, + frame_local: true + }) + ); + match &stopped.result { + ExecutionResult::Revert { output, .. } => assert_eq!(output, &kv_stop(10)), + other => panic!("expected the stop, got {other:?}"), + } + assert_eq!( + stopped.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); +} + +/// A child gets 98/100 of what its caller has left, rounded down: under a limit of ten, a caller +/// that kept two records gives its child seven, and the child's eighth record stops it, kind 1, +/// naming seven. The caller catches the stop with its eight records left, and keeps writing within +/// them: eight more fit, which a ninth would not. +#[test] +fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { + assert_eq!(share(10 - 2), 7); + let child = writes(BytecodeBuilder::default(), 1, 8).stop().build(); + let caller = |after: u64| { + let code = writes(BytecodeBuilder::default(), 1, 2) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append_many([GAS, CALL, POP]); + let code = writes(code, 3, after); + code.append_many([ + RETURNDATASIZE, + PUSH0, + PUSH0, + RETURNDATACOPY, + RETURNDATASIZE, + PUSH0, + RETURN, + ]) + .build() + }; + let db = |after| { + MemoryDatabase::default().account_code(A, caller(after)).account_code(B, child.clone()) + }; + + let caught = run(db(8), kv(10)); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&kv_stop(7)), "the child's stop names its budget"); + assert_eq!(caught.limit_exceeded, None, "a stop below the transaction's own frame"); + assert_eq!(caught.usage.write_records, 10, "the caller's ten records, none of the child's"); + + let stopped = run(db(9), kv(10)); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::KvUpdate, + limit: 10, + used: 11, + frame_local: true + }), + "the caller's own eleventh record stops it in turn, naming its budget" + ); +} + +/// The budgets at depth, under a limit of 100: the transaction's own frame gets 100, a child 98, +/// a grandchild 96, the next frame 94, each the share of what the frame above has left; the 95th +/// record of the frame three calls down stops it, kind 1, naming 94, and every caller resumes. +#[test] +fn test_the_kv_budgets_at_depth() { + assert_eq!((share(100), share(share(100)), share(share(share(100)))), (98, 96, 94)); + let db = |records: u64| { + MemoryDatabase::default() + .account_code(A, then_call_returning(BytecodeBuilder::default(), B).build()) + .account_code(B, then_call_returning(BytecodeBuilder::default(), C).build()) + .account_code(C, then_call_returning(BytecodeBuilder::default(), D).build()) + .account_code(D, writes(BytecodeBuilder::default(), 1, records).stop().build()) + }; + let fits = run(db(94), kv(100)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 94); + + let caught = run(db(95), kv(100)); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&kv_stop(94)), "D's stop, returned up the chain"); + assert_eq!(caught.usage.write_records, 0, "D's records went with its revert"); +} + +/// One record that crosses the data-size frame budget and the KV frame budget at once stops on +/// data size, the first of the counted dimensions: kind 0, naming the data-size budget. +#[test] +fn test_a_record_crossing_data_size_and_kv_stops_on_data_size() { + let db = MemoryDatabase::default() + .account_code(A, writes(BytecodeBuilder::default(), 1, 2).stop().build()); + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_kv_update_limit(1) + .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE); + let stopped = run(db, limits); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: WRITE_RECORD_SIZE, + used: 2 * WRITE_RECORD_SIZE, + frame_local: true + }) + ); +} + +/// A frame's remaining is its budget less its net, never more than the budget: a child that takes +/// back a record its caller made has a net of minus one, and the frame it starts still gets 98% of +/// the child's budget, not of the budget and the record it took back. +/// +/// `A` writes its slot 1 and `DELEGATECALL`s `B`, which runs on `A`'s storage: under a limit of +/// 100, `A` has 99 left and `B` gets 97. `B` writes slot 1 back to its original, which takes `A`'s +/// record back, and calls `C`, which gets 98% of `B`'s 97, 95 — not of the 98 `B`'s pool holds — +/// and writes slots of its own: the 96th stops it, naming 95. +#[test] +fn test_a_negative_net_does_not_enlarge_the_next_childs_budget() { + use revm::bytecode::opcode::DELEGATECALL; + assert_eq!((share(99), share(97), share(98)), (97, 95, 96)); + let a = writes(BytecodeBuilder::default(), 1, 1) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append_many([GAS, DELEGATECALL, POP, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([RETURNDATASIZE, PUSH0, RETURN]) + .build(); + let b = then_call_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::ZERO), C) + .build(); + let db = |records: u64| { + MemoryDatabase::default() + .account_code(A, a.clone()) + .account_code(B, b.clone()) + .account_code(C, writes(BytecodeBuilder::default(), 100, records).stop().build()) + }; + let fits = run(db(95), kv(100)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 95, "C's 95; A's record went back with B's write"); + + let caught = run(db(96), kv(100)); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&kv_stop(95)), "C's budget is the share of 97, not 98"); +} + +/// An EIP-7702 list that would keep more records than the transaction's limit allows is not +/// applied: none of its authorities is bumped, delegated or counted, and the transaction's own +/// frame returns the stop before it runs, kind 1, naming the transaction's limit, since no frame +/// budget exists yet. A list within the limit is applied. +#[test] +fn test_an_authorization_list_over_the_kv_limit_is_skipped_and_stops_the_first_frame() { + use crate::common::authorizing_call; + const DELEGATE: Address = address!("0000000000000000000000000000000000740005"); + const AUTHORITIES: [Address; 2] = [ + address!("0000000000000000000000000000000000740006"), + address!("0000000000000000000000000000000000740007"), + ]; + let db = || { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_u64.pow(18))) + .account_code(A, writes(BytecodeBuilder::default(), 1, 1).stop().build()) + }; + let keys = AUTHORITIES; + let list = [(keys[0], 0), (keys[1], 0)]; + let tx = authorizing_call(CALLER, A, U256::ZERO, GAS_LIMIT, DELEGATE, &list); + + let applied = execute_under(db(), tx.clone(), kv(3)); + assert!(applied.result.is_success(), "{:?}", applied.result); + assert_eq!(applied.usage.write_records, 3, "two authorities and A's slot"); + + let skipped = execute_under(db(), tx, kv(1)); + assert_eq!( + skipped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::KvUpdate, + limit: 1, + used: 2, + frame_local: false + }) + ); + match &skipped.result { + ExecutionResult::Revert { output, .. } => assert_eq!(output, &kv_stop(1)), + other => panic!("expected the stop, got {other:?}"), + } + assert_eq!(skipped.usage.write_records, 0, "nothing of the list is kept"); + for authority in &keys { + let account = skipped.state.get(authority); + assert!(account.is_none_or(|account| account.info.nonce == 0), "{authority}: not bumped"); + assert!( + account.is_none_or(|account| account.info.is_empty_code_hash()), + "{authority}: not delegated" + ); + } +} diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index efe41c39e..ed4e5fc30 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -1,10 +1,10 @@ //! Who is held to no per-transaction limit: a transaction the protocol itself sent, and a system //! call. //! -//! The data-size limit and its frame budgets hold what users do. The protocol's own work — the -//! maintenance a system transaction performs, the calls the protocol makes before a block's -//! transactions — must not fail on them, as it pays no history gas for the same reason. What it -//! uses is counted all the same, and reported. +//! The data-size, KV-update and state-growth limits and their frame budgets hold what users do. The +//! protocol's own work — the maintenance a system transaction performs, the calls the protocol +//! makes before a block's transactions — must not fail on them, as it pays no history gas for the +//! same reason. What it uses is counted all the same, and reported. //! //! A user's deposit is not the protocol's work: it is held to every limit, and so is a user's //! transaction that calls a system contract. @@ -77,12 +77,20 @@ fn call_from(caller: Address, to: Address) -> MegaTransaction { } /// Every per-transaction limit the program crosses, one at a time, and all of them together. -fn limits() -> [(&'static str, EvmTxRuntimeLimits); 3] { +fn limits() -> [(&'static str, EvmTxRuntimeLimits); 5] { let none = EvmTxRuntimeLimits::no_limits(); [ ("the transaction's data size", none.with_tx_data_size_limit(TX_BODY_SIZE)), ("a frame's data size", none.with_frame_data_size_limit(WRITE_RECORD_SIZE)), - ("every limit at zero", none.with_tx_data_size_limit(0).with_frame_data_size_limit(0)), + ("the transaction's KV updates", none.with_tx_kv_update_limit(0)), + ("the transaction's state growth", none.with_tx_state_growth_limit(0)), + ( + "every limit at zero", + none.with_tx_data_size_limit(0) + .with_frame_data_size_limit(0) + .with_tx_kv_update_limit(0) + .with_tx_state_growth_limit(0), + ), ] } @@ -95,6 +103,10 @@ fn test_a_system_transaction_is_held_to_no_limit() { assert!(free.result.is_success(), "{:?}", free.result); assert_eq!(free.usage.write_records, 3, "three slots"); assert_eq!(free.usage.data_size, TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE + 32 + 64); + assert_eq!( + free.usage.state_growth, 4, + "three new slots, and the system address's account, which the transaction creates" + ); assert!(free.gas.state >= 3 * slot_state_gas(), "at least its three slots' state gas"); for (name, limits) in limits() { @@ -119,16 +131,13 @@ fn test_a_system_call_is_held_to_no_limit() { let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)); let result = Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()) .expect("the system call runs"); - ( - result, - evm.ctx().additional_limit().usage(), - evm.ctx().additional_limit().limit_exceeded().copied(), - ) + (result, evm.ctx().limit_usage(), evm.ctx().additional_limit().limit_exceeded().copied()) }; let (free, free_usage, _) = run(EvmTxRuntimeLimits::no_limits()); assert!(free.result.is_success(), "{:?}", free.result); assert_eq!(free_usage.write_records, 3); assert_eq!(free_usage.data_size, 310 + 3 * 40 + 32 + 64, "its body, records and log"); + assert_eq!(free_usage.state_growth, 3, "three new slots"); for (name, limits) in limits() { let (result, usage, stop) = run(limits); @@ -139,26 +148,53 @@ fn test_a_system_call_is_held_to_no_limit() { } } -/// A user's deposit is held to the limits: over the data size, it is stopped. So is a user's -/// transaction to the contract a system transaction may call. +/// A user's deposit is held to the limits: over the data size, the KV count or the state growth, +/// it is stopped on that dimension. So is a user's transaction to the contract a system +/// transaction may call. #[test] fn test_a_deposit_and_a_user_call_to_a_system_contract_are_held_to_the_limits() { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE); - let cases = [ - ("a deposit", deposit(call_from(CALLER, CONTRACT))), - ("a user's call to a system contract", call_from(CALLER, ORACLE_CONTRACT_ADDRESS)), + let none = EvmTxRuntimeLimits::no_limits(); + let dimensions = [ + (none.with_tx_data_size_limit(TX_BODY_SIZE), LimitKind::DataSize), + (none.with_tx_kv_update_limit(0), LimitKind::KvUpdate), + (none.with_tx_state_growth_limit(0), LimitKind::StateGrowth), ]; - for (name, tx) in cases { - let outcome = execute_under(db(), tx, limits); - let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}: stopped")); - assert!( - matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }), - "{name}: {stop:?}" - ); - assert!( - !outcome.result.is_success() && !outcome.result.is_halt(), - "{name}: {:?}", - outcome.result - ); + for (limits, kind) in dimensions { + let cases = [ + ("a deposit", deposit(call_from(CALLER, CONTRACT))), + ("a user's call to a system contract", call_from(CALLER, ORACLE_CONTRACT_ADDRESS)), + ]; + for (name, tx) in cases { + let outcome = execute_under(db(), tx, limits); + let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}: stopped")); + assert!( + matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: crossed, .. } if crossed == kind), + "{name}, {kind:?}: {stop:?}" + ); + assert!( + !outcome.result.is_success() && !outcome.result.is_halt(), + "{name}, {kind:?}: {:?}", + outcome.result + ); + } } } + +/// Under the spec's own limits a system transaction keeps more than the 1,000 new slots a user's +/// transaction may: 1,001 fresh slots are not stopped, and their count is reported, with the +/// system address's new account, for the block to count. +#[test] +fn test_a_system_transaction_keeps_more_state_growth_than_the_limit() { + use mega_evm::constants::{TX_GAS_LIMIT_CAP, TX_STATE_GROWTH_LIMIT}; + let slots = TX_STATE_GROWTH_LIMIT + 1; + let code = (1..=slots).fold(BytecodeBuilder::default(), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)) + }); + let db = db().account_code(ORACLE_CONTRACT_ADDRESS, code.stop().build()); + let mut tx = call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + tx.0.base.gas_limit = TX_GAS_LIMIT_CAP + slots * slot_state_gas() + 100_000_000; + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::default()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.usage.state_growth, slots + 1, "the slots and the system address"); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/block.rs b/crates/mega-evm/tests/satin/limit_matrix/block.rs new file mode 100644 index 000000000..d92e4fdaf --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/block.rs @@ -0,0 +1,334 @@ +//! What a block skips, and what it still counts. +//! +//! The block's gas limit is the page's bound: the fixture block's 10 billion, not a 30 million +//! stand-in. Per-transaction limits stay the protocol's. The executor installs them itself. + +use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxLegacy}; +use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{MemoryDatabase, SequencerRegistryRoles}, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, + MegaSpecId, MegaTxEnvelope, ProtocolLimits, +}; +use op_alloy_consensus::TxDeposit; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::State, + Database, +}; + +use super::{slots_gas, store_n_slots, CALLER, CONTRACT, TX_STATE_GROWTH_LIMIT}; + +const CHAIN_ID: u64 = 4_326; +const BLOCK_GAS: u64 = 10_000_000_000; + +/// A second sender, so the transaction the block should skip is not the one that filled it. +const OTHER: Address = alloy_primitives::address!("0000000000000000000000000000000000ab1008"); +/// The deposit's sender. +const DEPOSITOR: Address = alloy_primitives::address!("0000000000000000000000000000000000ab1009"); + +/// The database a block runs on: Rex6 predeploys, the registry naming the system address, and +/// every sender funded. `CONTRACT` runs `code`. +pub(super) fn database(code: Bytes) -> MemoryDatabase { + let mut db = MemoryDatabase::default() + .rex6_predeploys(SequencerRegistryRoles::from(MEGA_SYSTEM_ADDRESS)) + .account_code(CONTRACT, code) + .account_balance(CALLER, U256::from(10u128.pow(24))) + .account_balance(OTHER, U256::from(10u128.pow(24))) + .account_balance(DEPOSITOR, U256::from(10u128.pow(24))) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(10u128.pow(24))); + db.set_account_code(DEPOSITOR, Bytes::new()); + db +} + +fn env() -> EvmEnv { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + let block = BlockEnv { number: U256::from(1), gas_limit: BLOCK_GAS, ..Default::default() }; + EvmEnv::new(cfg, block) +} + +/// A legacy call. Gas price 0, chain id [`CHAIN_ID`]. +pub(super) fn legacy( + from: Address, + nonce: u64, + to: Address, + gas_limit: u64, +) -> Recovered { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 0, + gas_limit, + to: TxKind::Call(to), + value: U256::ZERO, + input: Bytes::new(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO)), + from, + ) +} + +/// A user deposit to `to`. +pub(super) fn deposit( + from: Address, + to: Address, + gas_limit: u64, + system: bool, +) -> Recovered { + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0x11), + from, + to: TxKind::Call(to), + mint: 0, + value: U256::ZERO, + gas_limit, + is_system_transaction: system, + input: Bytes::new(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, B256::repeat_byte(0xde))), + from, + ) +} + +/// Runs `txs` in order on a fresh block over `db`. Each entry is `Ok` when the transaction was +/// included, including one whose receipt failed. +pub(super) fn drive( + db: MemoryDatabase, + txs: Vec>, +) -> (Vec>, State) { + drive_with(db, txs, BlockLimits::no_limits(), None) +} + +/// [`drive`] under a builder's `policy`, and under `protocol` in place of the spec's limits when +/// it is given. +pub(super) fn drive_with( + db: MemoryDatabase, + txs: Vec>, + policy: BlockLimits, + protocol: Option, +) -> (Vec>, State) { + let mut state = State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, env()); + let ctx = MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), policy); + let mut executor = MegaBlockExecutor::new( + evm, + ctx, + MegaHardforkConfig::default().with_all_activated(), + OpAlloyReceiptBuilder::default(), + ); + if let Some(protocol) = protocol { + executor = executor.with_protocol_limits(protocol); + } + executor.apply_pre_execution_changes().expect("the block starts"); + let results = txs + .iter() + .map(|tx| executor.execute_transaction(tx).map(|_| ()).map_err(|err| err.to_string())) + .collect(); + drop(executor); + (results, state) +} + +pub(super) fn slot(state: &mut State, address: Address, index: u64) -> U256 { + state.storage(address, U256::from(index)).expect("the slot is readable") +} + +/// The block's state growth is already 1,000. The next ordinary transaction is skipped before it +/// runs. A deposit is not skipped. +#[test] +fn test_an_ordinary_transaction_is_skipped_at_the_block_state_growth_limit() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + let (results, mut state) = drive( + db, + vec![ + legacy(CALLER, 0, CONTRACT, gas), + deposit(DEPOSITOR, CONTRACT, gas, false), + legacy(OTHER, 0, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "the filling transaction is included: {:?}", results[0]); + assert_eq!(slot(&mut state, CONTRACT, 1), U256::from(1)); + assert!(results[1].is_ok(), "a deposit is not skipped: {:?}", results[1]); + assert!( + results[2].is_err(), + "the next ordinary transaction is skipped before it runs: {:?}", + results[2] + ); +} + +/// A block KV limit reduced to 10, so the case is reachable before data size. The transaction +/// whose 10 records reach it is included. A deposit after it is not skipped and counts; the next +/// ordinary transaction is skipped before it runs. +#[test] +fn test_a_reduced_block_kv_limit_skips_the_next_ordinary_transaction() { + let Some(gas) = slots_gas(10) else { return }; + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN).with_block_kv_update_limit(10); + let db = database(store_n_slots(10)); + let (results, mut state) = drive_with( + db, + vec![ + legacy(CALLER, 0, CONTRACT, gas), + deposit(DEPOSITOR, CONTRACT, gas, false), + legacy(OTHER, 0, CONTRACT, gas), + ], + BlockLimits::no_limits(), + Some(protocol), + ); + assert!(results[0].is_ok(), "the transaction that reaches the limit is included"); + assert_eq!(slot(&mut state, CONTRACT, 10), U256::from(1)); + assert!(results[1].is_ok(), "a deposit is not skipped: {:?}", results[1]); + assert!(results[2].is_err(), "the next ordinary transaction is skipped: {:?}", results[2]); +} + +/// The block's data size, KV and state growth are all reached by one transaction under reduced +/// block limits. The next ordinary transaction is skipped. A node may name any of the three, so +/// the test asserts the skip and no dimension. +/// Filling only data size would not hold the other two budgets to the rule. +#[test] +fn test_a_skip_with_every_block_dimension_reached_records_no_dimension() { + let Some(gas) = slots_gas(2) else { return }; + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN) + .with_block_txs_data_limit(1) + .with_block_kv_update_limit(1) + .with_block_state_growth_limit(1); + let db = database(store_n_slots(2)); + let (results, _) = drive_with( + db, + vec![legacy(CALLER, 0, CONTRACT, gas), legacy(OTHER, 0, CONTRACT, gas)], + BlockLimits::no_limits(), + Some(protocol), + ); + assert!(results[0].is_ok(), "the transaction that reaches the limits is included"); + assert!(results[1].is_err(), "the next ordinary transaction is skipped: {:?}", results[1]); +} + +/// A system-originated transaction creates 1,001 new slots. It is not stopped: the slots are +/// kept. Its usage is counted and moves the block's state-growth counter past 1,000, so the +/// ordinary transaction after it is skipped. +#[test] +fn test_a_system_transaction_of_1001_slots_is_not_stopped() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let mut db = database(store_n_slots(1)); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16)); + let (results, mut state) = drive( + db, + vec![ + legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + legacy(CALLER, 0, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "the system transaction is included: {:?}", results[0]); + assert_eq!( + slot(&mut state, ORACLE_CONTRACT_ADDRESS, TX_STATE_GROWTH_LIMIT + 1), + U256::from(1), + "1,001 slots are kept" + ); + assert!(results[1].is_err(), "the system transaction counted: {:?}", results[1]); +} + +/// A pre-block call creates 1,001 new slots. It is not stopped, and the block counters do not +/// move: the ordinary transaction after it that fills 1,000 slots is included, and only the one +/// after that is skipped. +/// +/// The pre-block calls' gas is fixed at 31,566,720, which at the spec's byte prices cannot pay +/// 1,001 fresh slots, so the test is built with the `satin-price-override` feature and returns +/// early unless the prices in effect fit them. The pre-block call runs no inspector, so the whole +/// reservoir its outermost frame receives is not observed here. +#[cfg(feature = "satin-price-override")] +#[test] +fn test_a_pre_block_call_of_1001_slots_is_not_stopped_and_does_not_move_the_block() { + use alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS; + use revm::context_interface::cfg::GasId; + // A fresh slot's regular gas is the store's own, from the schedule, and the loop's opcodes + // around it, which take less than 100. Its state gas draws the reservoir first and then + // spills onto the regular budget, so the two together must fit the call's whole gas. + let params = mega_evm::satin_gas_params(); + let store_regular = params.get(GasId::sstore_static()) + + params.get(GasId::cold_storage_cost()) + + params.get(GasId::sstore_set_without_load_cost()); + let slots = TX_STATE_GROWTH_LIMIT + 1; + let needed = slots * (crate::common::slot_state_gas() + store_regular + 100); + if needed > mega_evm::constants::PRE_BLOCK_CALL_GAS_LIMIT { + mega_evm::test_utils::note_price_guard("1,001 slots do not fit a pre-block call"); + return; + } + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let mut db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + db.set_account_code(HISTORY_STORAGE_ADDRESS, store_n_slots(slots as u16)); + let (results, mut state) = + drive(db, vec![legacy(CALLER, 0, CONTRACT, gas), legacy(OTHER, 0, CONTRACT, gas)]); + assert_eq!(slot(&mut state, HISTORY_STORAGE_ADDRESS, slots), U256::from(1), "not stopped"); + assert!(results[0].is_ok(), "the pre-block call moved no counter: {:?}", results[0]); + assert!(results[1].is_err(), "the block is now at 1,000: {:?}", results[1]); +} + +/// The block is already at 1,000 state growth: the ordinary transaction that comes later is +/// skipped. A Mega System Transaction at that point is not skipped, and not stopped by the +/// per-transaction limit: its 1,001 slots are kept. It counts. +#[test] +fn test_a_system_transaction_after_1000_slots_is_not_skipped() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let mut db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16)); + let (results, mut state) = drive( + db, + vec![ + legacy(CALLER, 0, CONTRACT, gas), + legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + legacy(OTHER, 0, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "{:?}", results[0]); + assert!(results[1].is_ok(), "a system transaction is not skipped: {:?}", results[1]); + assert_eq!( + slot(&mut state, ORACLE_CONTRACT_ADDRESS, TX_STATE_GROWTH_LIMIT + 1), + U256::from(1), + "it is not stopped" + ); + assert!(results[2].is_err(), "the block is at its limit: {:?}", results[2]); +} + +/// A builder's policy holds the block's KV packing budget at 10 and its state-growth packing +/// budget at 2. The ordinary transaction that fills two slots reaches the state-growth budget, +/// so the next ordinary one is not packed; a deposit and a Mega System Transaction are not +/// refused and still count. A validator applies no policy and includes the next one too, and the +/// transactions both packed compute the same. The protocol values stay 500,000 and 1,000. +#[test] +fn test_a_builders_kv_and_state_growth_policy_does_not_bind_a_validator() { + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN); + assert_eq!(protocol.block_kv_update_limit, super::TX_KV_UPDATE_LIMIT); + assert_eq!(protocol.block_state_growth_limit, TX_STATE_GROWTH_LIMIT); + let Some(gas) = slots_gas(4) else { return }; + let txs = || { + vec![ + legacy(CALLER, 0, CONTRACT, gas), + deposit(DEPOSITOR, CONTRACT, gas, false), + legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + legacy(OTHER, 0, CONTRACT, gas), + ] + }; + let db = || { + let mut db = database(store_n_slots(2)); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, store_n_slots(2)); + db + }; + let policy = + BlockLimits::no_limits().with_block_kv_update_limit(10).with_block_state_growth_limit(2); + let (built, mut built_state) = drive_with(db(), txs(), policy, None); + assert!(built[0].is_ok() && built[1].is_ok() && built[2].is_ok(), "{built:?}"); + assert!(built[3].is_err(), "the builder does not pack it: {:?}", built[3]); + let (validated, mut validated_state) = drive(db(), txs()); + assert!(validated.iter().all(Result::is_ok), "a validator applies no policy: {validated:?}"); + for (address, index) in [(CONTRACT, 2), (ORACLE_CONTRACT_ADDRESS, 2)] { + assert_eq!( + slot(&mut built_state, address, index), + slot(&mut validated_state, address, index) + ); + } +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/deposits.rs b/crates/mega-evm/tests/satin/limit_matrix/deposits.rs new file mode 100644 index 000000000..ca4ce9e23 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/deposits.rs @@ -0,0 +1,130 @@ +//! A user's deposit, and a deposit that has already failed. +//! +//! The created caller of a user deposit is state growth before the first frame. A failed deposit +//! reports `FailedDeposit` and is not stopped. + +use alloy_primitives::{address, Address, U256}; +use mega_evm::{MegaHaltReason, MegaTransaction}; +use revm::context::result::ExecutionResult; + +use super::{ + block, execute, nonce_of, reverted_stop, slot_value, slots_gas, store_n_slots, world, CALLER, + CONTRACT, TX_STATE_GROWTH_LIMIT, +}; +use crate::common; + +const FRESH: Address = address!("0000000000000000000000000000000000ab100a"); +/// A second contract, so a deposit's slots are not the slots an earlier transaction filled. +const OTHER_CONTRACT: Address = address!("0000000000000000000000000000000000ab100c"); + +fn user_deposit(caller: Address, gas_limit: u64, system: bool) -> MegaTransaction { + let mut tx = common::deposit(common::call(caller, CONTRACT, U256::ZERO, gas_limit)); + tx.0.deposit.is_system_transaction = system; + tx +} + +/// A user deposit whose sender had no account, then fresh slots. The created caller is +1 before +/// the first frame. The first frame's budget is 999. The 1,000th slot stops that frame, kind 3, +/// `limit` 999. The caller account stays. +#[test] +fn test_a_new_depositors_1000th_slot_stops_at_999() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let db = world(&[(CONTRACT, store_n_slots(TX_STATE_GROWTH_LIMIT as u16))]); + let outcome = execute(db, user_deposit(FRESH, gas, false)); + assert_eq!( + reverted_stop(&outcome), + mega_evm::MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT - 1 } + ); + assert!(outcome.limit_exceeded.is_some(), "the deposit's own frame stopped"); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO, "the stopped frame keeps no slot"); + assert!(nonce_of(&outcome, FRESH) >= 1, "the created caller stays"); + assert_eq!( + outcome.gas.state, + common::account_state_gas(), + "the created caller keeps its state gas; the stopped slots keep none" + ); +} + +/// A user deposit whose sender already had an account. No pre-frame growth. The 1,001st fresh +/// slot stops the first frame, kind 3, `limit` 1,000. +#[test] +fn test_an_existing_depositors_1001st_slot_stops_at_1000() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let db = world(&[(CONTRACT, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16))]) + .account_balance(FRESH, U256::from(1)); + let outcome = execute(db, user_deposit(FRESH, gas, false)); + assert_eq!( + reverted_stop(&outcome), + mega_evm::MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT } + ); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); +} + +/// The block is already at 1,000 state growth: the ordinary transaction after the deposit is +/// skipped. The deposit, a user's, is not skipped. It runs under the per-transaction limit: the +/// 1,001 slots it tries are stopped, and none is kept. +#[test] +fn test_a_user_deposit_after_1000_slots_is_not_skipped() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let mut db = block::database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + db.set_account_code(OTHER_CONTRACT, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16)); + let (results, mut state) = block::drive( + db, + vec![ + block::legacy(CALLER, 0, CONTRACT, gas), + block::deposit(FRESH, OTHER_CONTRACT, gas, false), + block::legacy(CALLER, 1, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "{:?}", results[0]); + assert!(results[1].is_ok(), "a user deposit is not skipped: {:?}", results[1]); + assert_eq!( + block::slot(&mut state, OTHER_CONTRACT, 1), + U256::ZERO, + "the deposit is held to the per-transaction limit" + ); + assert!(results[2].is_err(), "the block is at its limit: {:?}", results[2]); +} + +/// A failed deposit whose sender had no account: no state gas for that account, and the limit +/// does not stop it. Its account counts one toward the block's state growth: after an ordinary +/// transaction of 999 slots, one such deposit takes the block to 1,000, so the next ordinary +/// transaction is skipped, and a second such deposit after it is not, taking the counter past +/// 1,000. +#[test] +fn test_a_failed_deposit_from_a_new_sender_is_not_stopped() { + let db = world(&[(CONTRACT, store_n_slots(1))]); + let outcome = execute(db, user_deposit(FRESH, 100_000, true)); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.gas.state, 0, "a failed deposit charges no state gas"); + assert!(outcome.limit_exceeded.is_none(), "the halt is not a limit stop"); + assert_eq!(nonce_of(&outcome, FRESH), 1, "the sender account is created"); + + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let db = block::database(store_n_slots((TX_STATE_GROWTH_LIMIT - 1) as u16)); + let (results, _) = block::drive( + db, + vec![ + block::legacy(CALLER, 0, CONTRACT, gas), + block::deposit(FRESH, CONTRACT, 100_000, true), + block::legacy(CALLER, 1, CONTRACT, gas), + block::deposit( + address!("0000000000000000000000000000000000ab100b"), + CONTRACT, + 100_000, + true, + ), + ], + ); + assert!(results[0].is_ok(), "{:?}", results[0]); + assert!(results[1].is_ok(), "a failed deposit is not skipped: {:?}", results[1]); + assert!(results[2].is_err(), "the failed deposit's account counted: {:?}", results[2]); + assert!(results[3].is_ok(), "the counter may pass 1,000: {:?}", results[3]); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs new file mode 100644 index 000000000..cd9d7d23e --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs @@ -0,0 +1,1365 @@ +//! The same-transaction destruction table, and the state growth a `SELFDESTRUCT` adds. +//! +//! A scenario run through [`plain_and_probed`] reads its figures off a plain run and the +//! state-growth net it kept off the probe's budget. The figures are the page's at `m` = 1 and the +//! spec's byte prices: a test that pins them returns early at other prices. Kind 1 runs under a +//! reduced transaction KV limit. + +use alloy_op_evm::OpTx; +use alloy_primitives::{keccak256, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + satin_gas_params, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{ + ADDRESS, CALL, CALLDATALOAD, CALLDATASIZE, CALLVALUE, GAS, JUMPDEST, JUMPI, LT, MLOAD, POP, + PUSH0, SELFDESTRUCT, SLOAD, SSTORE, STOP, + }, + context::{result::ExecutionResult, TxEnv}, + interpreter::{ + interpreter::EthInterpreter, + interpreter_types::{InputsTr, Jumps}, + Interpreter, + }, + Database, Inspector, +}; + +use super::{ + assert_growth, at_spec_prices, balance_of, call_tx, call_with_gas, create_tx, delegatecall, + execute, has_code, is_destroyed, plain_and_probed, probe_gas, returned_stop, slot_value, + slots_gas, store_n_prefix, store_n_prefix_at, warm_call, world, ACCOUNT_LEAF_STATE_GAS_M1, + BENEFICIARY, BODY_BYTES, BODY_HISTORY, CALLER, CHILD, CODE_DEPOSIT_STATE_PER_BYTE, CONTRACT, + EXECUTION_CAP, EXISTING, GRAND, HISTORY_GAS_PER_BYTE, NEXT, RECORD_HISTORY, SLOT_STATE_GAS_M1, + TRANSFER_LOG_SIZE, TX_STATE_GROWTH_LIMIT, WRITE_RECORD_SIZE, +}; +use crate::common::{self, context, state_is_free}; + +/// Whether the page's state and history figures hold at the prices in effect. +fn pins_state() -> bool { + at_spec_prices() && !state_is_free() && !common::history_is_free() +} + +/// History gas of `bytes` at the spec's byte price. +const fn history(bytes: u64) -> u64 { + bytes * HISTORY_GAS_PER_BYTE +} + +/// State gas of deploying `code` at `m` = 1. +fn code_state(code: &[u8]) -> u64 { + code.len() as u64 * CODE_DEPOSIT_STATE_PER_BYTE +} + +fn runtime_to(beneficiary: Address) -> Bytes { + BytecodeBuilder::default().selfdestruct(beneficiary).build() +} + +fn init_returning(prefix: BytecodeBuilder, runtime: &[u8]) -> Bytes { + prefix.return_with_data(runtime).build() +} + +fn created_at(init: &[u8]) -> Address { + CONTRACT.create2(B256::ZERO, keccak256(init)) +} + +/// `CREATE2` of `init` with salt 0 carrying `endowment`, its address popped, then `tail`. The tail +/// has no absolute jump: a loop in it is placed with `store_n_prefix_at`. +fn after_create(init: Bytes, endowment: U256, tail: BytecodeBuilder) -> Vec { + let mut code = BytecodeBuilder::default() + .create2(endowment, init, U256::ZERO) + .append(POP) + .build() + .to_vec(); + code.extend_from_slice(&tail.build()); + code +} + +fn funded_contract(code: impl Into) -> MemoryDatabase { + let mut db = world(&[(CONTRACT, code.into()), (EXISTING, Bytes::from_static(&[STOP]))]); + db.set_account_balance(CONTRACT, U256::from(10u128.pow(24))); + db +} + +/// [`plain_and_probed`] on a funded contract. `setup` adds accounts to both databases. +fn both( + scenario: Vec, + setup: impl Fn(&mut MemoryDatabase), +) -> Option<(MegaTransactionOutcome, MegaTransactionOutcome)> { + plain_and_probed(&scenario, |code| { + let mut db = funded_contract(code); + setup(&mut db); + db + }) +} + +/// Runtime that stores its 32-byte calldata into slot 1, or with no calldata self-destructs to +/// `beneficiary`. +fn store_or_destroy(beneficiary: Address) -> Bytes { + let destroy = BytecodeBuilder::default().selfdestruct(beneficiary).build(); + // `CALLDATASIZE`, `PUSH1 store`, `JUMPI` come first. + let store = 4 + destroy.len(); + let mut code = BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(store as u8) + .append(JUMPI) + .build() + .to_vec(); + code.extend_from_slice(&destroy); + code.extend_from_slice( + &BytecodeBuilder::default() + .append_many([JUMPDEST, PUSH0, CALLDATALOAD]) + .push_number(1_u8) + .append_many([SSTORE, STOP]) + .build(), + ); + Bytes::from(code) +} + +/// `CALL` of `target` with all the gas left and one 32-byte word of calldata, `word`. +fn call_with_word(code: BytecodeBuilder, target: Address, word: u64) -> BytecodeBuilder { + code.mstore(0x200, U256::from(word).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .push_number(0x200_u16) + .append(PUSH0) + .push_address(target) + .append_many([GAS, CALL]) +} + +/// Create an account that did not exist, deposit its code, store one fresh slot, and +/// `SELFDESTRUCT` it to a new beneficiary, moving a non-zero balance. The leaf, the code and the +/// slot are given back at the prices charged, and their records and the code's data size and +/// history go with them. The logs, here the two transfer logs, stay counted. The beneficiary is +/// +1 and its leaf, 183,600 at `m` = 1, stays charged: the kept net is 1. +/// +/// The beneficiary is held after the give-back: a destroying frame exactly at its budget, here 0, +/// subtracts the absent leaf and its new slot, `1 + N` = 2, and the beneficiary fits. +#[test] +fn test_a_kept_destruction_gives_back_the_leaf_the_code_and_the_slot() { + if !pins_state() { + return; + } + let runtime = runtime_to(BENEFICIARY); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init.clone(), + U256::from(1), + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "the account is removed"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1)); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "only the new beneficiary stays"); + // Kept: the creator's record and the beneficiary's. The endowment's and the move's transfer + // logs stay counted and pay no history. + assert_eq!(outcome.usage.write_records, 2); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE); + assert_eq!(outcome.gas.history, history(BODY_BYTES + 2 * WRITE_RECORD_SIZE)); + assert_eq!(outcome.gas.history_bytes, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_eq!(outcome.result.logs().len(), 2, "the two transfer logs stay"); + assert_growth(&probed, 1); + + // At the budget: the creation is +2 on the creator, which then stores 998 slots, so the + // destroying frame's budget is `floor(0 × 98 / 100)` = 0. + let mut code = after_create(init, U256::from(1), BytecodeBuilder::default()); + code.extend_from_slice(&store_n_prefix_at(code.len(), 998, 1, false)); + code.extend_from_slice(&BytecodeBuilder::default().call(created, U256::ZERO).stop().build()); + let Some(gas) = slots_gas(1_010) else { return }; + let outcome = execute(funded_contract(code), call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "the destruction at the budget fits"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1), "the beneficiary fits"); + assert_eq!(slot_value(&outcome, CONTRACT, 998), U256::from(1)); +} + +/// The top frame creates the account. An inner frame calls it, it self-destructs, and the inner +/// frame then reverts. The creation sits outside that revert: the mark, the falls, the give-back +/// and the record takeback are discarded, so the leaf and the code stay charged, the creator's +/// and the created account's records stand, and the kept net is the creation's +1. +#[test] +fn test_a_reverted_inner_frame_discards_the_destruction() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP), + ); + let child = BytecodeBuilder::default().call(created, U256::ZERO).revert().build(); + let Some((outcome, probed)) = both(parent, |db| db.set_account_code(CHILD, child.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(!is_destroyed(&outcome, created), "the revert discards the destruction"); + assert!(has_code(&outcome, created)); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + code_state(&runtime)); + assert_eq!(outcome.usage.write_records, 2, "the records stand again"); + assert_growth(&probed, 1); +} + +/// A pre-existing contract, a child of the top frame with a state-growth budget of 980, stores +/// 980 slots and self-destructs to a new beneficiary. It was not created in the transaction, so +/// there is no fall and no give-back. The beneficiary's +1 crosses: the stop names the frame +/// budget, kind 3, `limit` 980, and the operation keeps nothing. +#[test] +fn test_a_new_beneficiary_at_a_full_budget_stops_the_frame() { + let mut pre = store_n_prefix(980, 1, false); + pre.extend_from_slice(&runtime_to(BENEFICIARY)); + let mut db = world(&[(CONTRACT, super::forward_to(CHILD)), (CHILD, Bytes::from(pre))]); + db.set_account_balance(CHILD, U256::from(10)); + let Some(gas) = slots_gas(1_000) else { return }; + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 980 }); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::ZERO, "the operation keeps nothing"); + assert_eq!(balance_of(&outcome, CHILD), U256::from(10)); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); +} + +/// Create an account with one fresh slot outside an enclosing frame. The enclosing frame destroys +/// it, stores the slot to another non-zero value, stores it to zero, and destroys it again. +/// +/// When the enclosing frame is kept, the first destruction gives the leaf, the code and the slot +/// back and takes their records back; the later stores do not rise, fall, charge, refill or make +/// a record; the second destruction does nothing. When it reverts, all of that is discarded: the +/// creation's charges and its three records stand, and the kept net is 2. +#[test] +fn test_stores_after_the_mark_and_a_reverted_enclosing_frame() { + if !pins_state() { + return; + } + let runtime = store_or_destroy(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP), + ); + for kept in [true, false] { + let enclosing = BytecodeBuilder::default().call(created, U256::ZERO).append(POP); + let enclosing = call_with_word(enclosing, created, 2).append(POP); + let enclosing = call_with_word(enclosing, created, 0).append(POP); + let enclosing = enclosing.call(created, U256::ZERO).append(POP); + let enclosing = if kept { enclosing.stop() } else { enclosing.revert() }; + let enclosing = enclosing.build(); + assert_eq!( + sstore_state_gas(&parent, |db| db.set_account_code(CHILD, enclosing.clone()), created), + [SLOT_STATE_GAS_M1 as i64, 0, 0], + "kept {kept}: the stores after the mark move no state gas" + ); + let Some((outcome, probed)) = + both(parent.clone(), |db| db.set_account_code(CHILD, enclosing.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "kept {kept}: {:?}", outcome.result); + if kept { + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "given back once, and nothing after the mark"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); + } else { + assert!(!is_destroyed(&outcome, created)); + assert_eq!(slot_value(&outcome, created, 1), U256::from(1)); + assert_eq!( + outcome.gas.state, + ACCOUNT_LEAF_STATE_GAS_M1 + SLOT_STATE_GAS_M1 + code_state(&runtime) + ); + assert_eq!(outcome.usage.write_records, 3, "the records stand again"); + assert_eq!( + outcome.usage.data_size, + BODY_BYTES + 3 * WRITE_RECORD_SIZE + runtime.len() as u64 + ); + assert_growth(&probed, 2); + } + } +} + +/// Runtime that accepts value and stops, or with no value emits one `LOG3` of a word and +/// self-destructs to `beneficiary`. +fn log_and_destroy(beneficiary: Address) -> Bytes { + let body = BytecodeBuilder::default().log3_word().selfdestruct(beneficiary).build(); + let accept = 4 + body.len(); + let mut code = BytecodeBuilder::default() + .append(CALLVALUE) + .push_number(accept as u8) + .append(JUMPI) + .build() + .to_vec(); + code.extend_from_slice(&body); + code.extend_from_slice(&[JUMPDEST, STOP]); + Bytes::from(code) +} + +/// A kept same-transaction destruction of an account absent at the start, with one fresh slot, +/// deposited code, one `LOG3` of a word and a non-zero balance moved to an existing account. The +/// account's and the slot's records are taken back, and the code's data size and history with +/// them; state gas comes back whole. The `LOG3` stays counted, 160 bytes, and its history stays +/// charged; the transfer logs stay counted and pay none. A later value transfer to the marked +/// account makes no record and is not a rise. +#[test] +fn test_a_destruction_gives_back_record_history_and_keeps_the_logs() { + if !pins_state() { + return; + } + let runtime = log_and_destroy(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::from(1), + BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(created, U256::from(1)) + .append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the leaf, the slot and the code come back"); + // Kept records: the creator and the existing beneficiary. Transfer logs: the endowment, the + // move, and the later value. + const LOG3_WORD: u64 = 32 + 3 * 32 + 32; + assert_eq!(outcome.usage.write_records, 2); + assert_eq!( + outcome.usage.data_size, + BODY_BYTES + 2 * WRITE_RECORD_SIZE + LOG3_WORD + 3 * TRANSFER_LOG_SIZE + ); + assert_eq!(outcome.gas.history, history(BODY_BYTES + 2 * WRITE_RECORD_SIZE + LOG3_WORD)); + assert_eq!(outcome.gas.history_bytes, BODY_BYTES + 2 * WRITE_RECORD_SIZE + LOG3_WORD); + assert_eq!(outcome.result.logs().len(), 4, "the LOG3 and the three transfer logs"); + assert_growth(&probed, 0); +} + +/// The creation is +2 on the top frame, whose remaining becomes 998, so the enclosing frame it +/// calls gets `floor(998 × 98 / 100)` = 978. The enclosing frame calls the account, which +/// destroys itself and returns a net of −2. The enclosing frame's remaining stays at its budget, +/// 978, not 980, so the child it then starts gets `floor(978 × 98 / 100)` = 958. +#[test] +fn test_a_destroying_childs_negative_net_does_not_raise_the_parents_budget() { + assert_eq!(super::frame_share(998), 978); + assert_eq!(super::frame_share(978), 958); + let runtime = runtime_to(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(CHILD, U256::ZERO).return_returndata(), + ); + let enclosing = BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(NEXT, U256::ZERO) + .return_returndata() + .build(); + let mut db = funded_contract(parent); + db.set_account_code(CHILD, enclosing); + db.set_account_code(NEXT, super::probe_code()); + let Some(gas) = probe_gas(2) else { return }; + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 958 }); + assert_eq!(slot_value(&outcome, NEXT, 1), U256::ZERO); +} + +/// The enclosing frame, given 2,000,000 gas, halts out of gas after a successful destroying +/// child. The mark, the falls, the give-back and the record takeback are discarded: the leaf, the +/// slot and the code stay charged, the three records stand, and the kept net is 2. +#[test] +fn test_a_halt_after_a_destroying_child_discards_the_mark() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + call_with_gas(BytecodeBuilder::default(), CHILD, U256::ZERO, 2_000_000).append(POP), + ); + // A load at offset 2^32 − 1 cannot pay its memory: an out-of-gas halt. + let enclosing = BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .push_number(u32::MAX) + .append_many([MLOAD, STOP]) + .build(); + let Some((outcome, probed)) = both(parent, |db| db.set_account_code(CHILD, enclosing.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(!is_destroyed(&outcome, created), "the halt discards the destruction"); + assert_eq!(slot_value(&outcome, created, 1), U256::from(1)); + assert_eq!( + outcome.gas.state, + ACCOUNT_LEAF_STATE_GAS_M1 + SLOT_STATE_GAS_M1 + code_state(&runtime) + ); + assert_eq!(outcome.usage.write_records, 3, "the records stand again"); + assert_growth(&probed, 2); +} + +/// A second `SELFDESTRUCT` of an account created in the transaction, with no balance moved and no +/// funding between, subtracts nothing, gives nothing back, takes no record back and creates no +/// beneficiary: the beneficiary does not exist and a zero balance does not create it. +#[test] +fn test_a_second_destruction_with_no_balance_subtracts_nothing() { + if !pins_state() { + return; + } + let runtime = runtime_to(BENEFICIARY); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(created, U256::ZERO) + .append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the first destruction gives the leaf and the code back once"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::ZERO, "no beneficiary"); + assert_growth(&probed, 0); +} + +/// The same repeated destruction after the account was funded again, moving that non-zero +/// balance to an account that does not exist. The second destruction still subtracts nothing and +/// gives nothing back; the value sent to the marked account makes no record. The beneficiary is a +/// rise, 183,600 at `m` = 1, and its record is kept. +#[test] +fn test_a_second_destruction_after_refunding_charges_only_the_beneficiary() { + if !pins_state() { + return; + } + let runtime = runtime_to(BENEFICIARY); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(created, U256::from(1)) + .append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, + "the second destruction only adds the beneficiary" + ); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1)); + assert_eq!(outcome.usage.write_records, 2, "the creator and the beneficiary"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE); + assert_growth(&probed, 1); +} + +/// Value to the counterfactual address A, then `CREATE2` onto A, then A self-destructs to an +/// existing account. The value call is the rise and the leaf's charge; the creation onto a +/// funded address adds neither. A did not exist at the start, so the destruction is the absent +/// row: it gives back the value call's leaf charge and the code, and takes A's record back. +#[test] +fn test_value_then_create2_then_destruct_gives_the_value_calls_leaf_back() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = BytecodeBuilder::default() + .call(created, U256::from(1)) + .append(POP) + .create2(U256::ZERO, init, U256::ZERO) + .append(POP) + .call(created, U256::ZERO) + .append(POP) + .build() + .to_vec(); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the value call's leaf is given back to the destroying frame"); + // Kept: the creator's record and the existing beneficiary's. Transfer logs: the value call and + // the move. + assert_eq!(outcome.usage.write_records, 2); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE); + assert_growth(&probed, 0); +} + +/// The reservoir is empty. A constructor stores three fresh slots, burns its gas down to about +/// 100,000 left after `SELFDESTRUCT`'s static and cold costs, and self-destructs to a new +/// beneficiary, moving its endowment. The destruction would give back 477,360 at `m` = 1, the +/// leaf's 183,600 and three slots of 97,920, but the beneficiary's new-account charge, 183,600, +/// is made first and cannot be paid: the constructor halts out of gas, the give-back is not +/// credited, and the creation fails with no beneficiary. +#[test] +fn test_a_beneficiary_charge_the_frame_cannot_pay_halts_before_the_give_back() { + if !pins_state() { + return; + } + assert_eq!(ACCOUNT_LEAF_STATE_GAS_M1 + 3 * SLOT_STATE_GAS_M1, 477_360); + // `GAS`, `PUSH3`, `LT`, `PUSH1`, `JUMPI`, `JUMPDEST`: 22 gas a turn, 19 after the last `GAS`. + // Then `PUSH20` and `SELFDESTRUCT`'s static 5,000 and the cold beneficiary. + let after_loop = 19 + 3 + 5_000 + satin_gas_params().selfdestruct_cold_cost(); + let target = u32::try_from(100_000 + 22 + after_loop).expect("fits a PUSH3"); + let slots = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(3), U256::from(1)) + .build(); + let entry = slots.len(); + let mut init = slots.to_vec(); + init.extend_from_slice( + &BytecodeBuilder::default() + .append_many([JUMPDEST, GAS]) + .push_bytes(&target.to_be_bytes()[1..]) + .append(LT) + .push_number(entry as u8) + .append(JUMPI) + .selfdestruct(BENEFICIARY) + .build(), + ); + let code = BytecodeBuilder::default().create(U256::from(1), init).return_top().build(); + let outcome = execute(funded_contract(code), call_tx(5_000_000)); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the creator runs on: {:?}", outcome.result); + }; + assert_eq!(output.data().as_ref(), &[0_u8; 32], "the creation failed"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::ZERO, "no beneficiary is kept"); + assert_eq!(outcome.gas.state, 0, "nothing of the failed creation stays charged"); + assert_eq!(outcome.gas.reservoir_remaining, 0); +} + +/// After the mark, an `SSTORE` of the destroyed account's own slot, `(original 0, present +/// non-zero, new 0)`, on the slot the destruction already gave back. No rise, no fall, no +/// fresh-slot charge and no refill: the state gas is still given back exactly once, and the store +/// makes no record. The EIP-3529 refund counter is not pinned here. +#[test] +fn test_a_cleared_slot_after_the_mark_does_not_refill_again() { + if !pins_state() { + return; + } + let runtime = store_or_destroy(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + call_with_word( + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + created, + 0, + ) + .append(POP), + ); + let fresh = SLOT_STATE_GAS_M1 as i64; + assert_eq!( + sstore_state_gas(&code, |_| {}, created), + [fresh, 0], + "the constructor's store is charged; the clear after the mark moves no state gas" + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "given back once by the table and not refilled again"); + assert_eq!(outcome.usage.write_records, 1, "the store after the mark makes no record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// A pre-existing contract, unchanged so far and holding a balance, self-destructs to an account +/// the transaction already changed. Under a transaction KV limit of 3, the top frame's two records +/// for the earlier transfer leave it 1, so the destroying frame's KV budget is +/// `floor(1 × 98 / 100)` = 0. The cleared account's one record crosses it, kind 1, `limit` 0; the +/// beneficiary adds no record; the operation keeps nothing. Under a limit of 4 the budget is 1 +/// and the same operation fits. +#[test] +fn test_a_cleared_account_with_no_kv_room_stops_at_the_frame_budget() { + let code = BytecodeBuilder::default() + .call(EXISTING, U256::from(1)) + .append(POP) + .call(CHILD, U256::ZERO) + .return_returndata() + .build(); + let Some(gas) = slots_gas(2) else { return }; + for (limit, fits) in [(3, false), (4, true)] { + let mut db = funded_contract(code.clone()); + db.set_account_code(CHILD, runtime_to(EXISTING)); + db.set_account_balance(CHILD, U256::from(10)); + let limits = mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(limit); + let outcome = super::execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + if fits { + assert_eq!(balance_of(&outcome, CHILD), U256::ZERO); + assert_eq!(balance_of(&outcome, EXISTING), U256::from(12)); + } else { + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 0 }); + assert_eq!(balance_of(&outcome, CHILD), U256::from(10), "the operation keeps nothing"); + assert_eq!(balance_of(&outcome, EXISTING), U256::from(2)); + } + } +} + +/// A destruction inside a frame that reverts, then a later destruction of the same account in a +/// frame that is kept. The first mark does not stand, so the later destruction is the first +/// effective one: it gives the leaf, the slot and the code back once and takes their records back +/// once. +#[test] +fn test_only_the_kept_destruction_gives_the_charges_back() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .call(created, U256::ZERO) + .append(POP), + ); + let child = BytecodeBuilder::default().call(created, U256::ZERO).revert().build(); + let Some((outcome, probed)) = both(parent, |db| db.set_account_code(CHILD, child.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the leaf, the code and the slot come back once"); + assert_eq!(outcome.usage.write_records, 1, "their records are taken back once"); + assert_eq!(outcome.gas.history, history(BODY_BYTES + WRITE_RECORD_SIZE)); + assert_growth(&probed, 0); +} + +/// A new account destroyed by its constructor, before any code is deposited and before any slot +/// is written. The leaf is refilled and falls, and the account's record is taken back. Nothing +/// else was charged. +#[test] +fn test_a_new_account_destroyed_before_code_or_slots_refills_the_leaf() { + if !pins_state() { + return; + } + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default()); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the leaf is refilled and nothing else was charged"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// A pre-funded address is created onto, and its constructor destroys it to itself, so no balance +/// moves to another account. The leaf was present: no charge, no refill, no fall, and the record +/// the nonce bump made stands. No beneficiary and no transfer log. +#[test] +fn test_a_prefunded_destruction_that_moves_no_balance_keeps_the_nonce_record() { + if !pins_state() { + return; + } + let init = BytecodeBuilder::default().append_many([ADDRESS, SELFDESTRUCT]).build(); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default()); + let Some((outcome, probed)) = both(code, |db| db.set_account_balance(created, U256::from(1))) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "a present leaf is neither charged nor refilled"); + assert_eq!(outcome.usage.write_records, 2, "the creator's and the nonce bump's records"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// Code deposited, then the account is destroyed in a later call. The account was absent at the +/// start. The code deposit's state gas is refilled, and the code's data size and history are taken +/// back; the code is no record and no unit of state growth. +#[test] +fn test_destroyed_code_refills_its_deposit_and_its_history() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert!(code_state(&runtime) > 0, "the runtime deposits code"); + assert_eq!(outcome.gas.state, 0, "the code deposit and the leaf are refilled"); + // The call carries no calldata: the body is 310 bytes, and the creator's record is kept. + assert_eq!(outcome.gas.history, history(BODY_BYTES + WRITE_RECORD_SIZE)); + assert_eq!(outcome.gas.history_bytes, BODY_BYTES + WRITE_RECORD_SIZE); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_eq!(outcome.usage.write_records, 1); + assert_growth(&probed, 0); +} + +/// Two slots, each original zero and present non-zero, one of them restored to zero before the +/// destruction. The non-zero slot is the zero, non-zero, deleted row: refilled, −1, record back. +/// The restored slot is the zero, zero, deleted row and is not counted again. +#[test] +fn test_slots_deleted_with_the_account_refill_once() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning( + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(1), U256::ZERO), + &runtime, + ); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "each slot refills once"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_growth(&probed, 0); +} + +/// A creation onto an address that held nonce 0, balance 0, empty code and slot 1 = 5 at the +/// transaction's start. `CREATE2` does not collide on storage. The address is empty under +/// EIP-161, so the creation charges a new account, 183,600 at `m` = 1, and counts a rise; the leaf +/// is the present row, so the destruction neither refills that charge nor subtracts the rise, and +/// the account's record stands. The code was absent and is given back. +/// +/// The runtime's `SLOAD` of slot 1 reads zero, not the 5 the database holds: a slot of an account +/// created in the transaction that the transaction first accesses after the creation reads zero, +/// so its original is zero, and it is the zero, zero, deleted row, which makes no record. Only a +/// slot accessed before the creation keeps the value the database holds (the record unit test). +#[test] +fn test_a_creation_onto_an_empty_address_with_storage_keeps_the_leaf_charge() { + if !pins_state() { + return; + } + let runtime = BytecodeBuilder::default() + .push_number(1_u8) + .append_many([SLOAD, POP]) + .selfdestruct(EXISTING) + .build(); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = + both(code, |db| db.set_account_storage(created, U256::from(1), U256::from(5))) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "the creation did not collide"); + let slot = &outcome.state[&created].storage[&U256::from(1)]; + assert_eq!( + (slot.original_value, slot.present_value), + (U256::ZERO, U256::ZERO), + "the slot loads as zero for an account created in the transaction" + ); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "the leaf's charge stands"); + // The creator's record and the created account's, which the present leaf keeps. + assert_eq!(outcome.usage.write_records, 2); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_growth(&probed, 1); +} + +/// Runs `txs` in order over `db` twice — each committed before the next runs, and all on one +/// journal that runs them without finalizing — and returns the last one's outcome on the committed +/// path, having held the other path's to it: the same result, gas, usage and limit stop. +fn the_same_on_one_journal( + db: MemoryDatabase, + txs: &[MegaTransaction], + what: &str, +) -> MegaTransactionOutcome { + use revm::{DatabaseCommit, ExecuteEvm}; + let (last, earlier) = txs.split_last().expect("a transaction"); + let mut committed = db.clone(); + for tx in earlier { + let outcome = execute(committed.clone(), tx.clone()); + assert!(outcome.result.is_success(), "{what}: {:?}", outcome.result); + committed.commit(outcome.result_and_state.state); + } + let control = execute(committed, last.clone()); + + let mut evm = mega_evm::MegaEvm::new(context(db)); + for tx in earlier { + let result = ExecuteEvm::transact_one(&mut evm, tx.clone()).expect("valid"); + assert!(result.is_success(), "{what}: {result:?}"); + } + let outcome = evm.execute_transaction(last.clone()).expect("valid"); + assert_eq!(outcome.result_and_state.result, control.result_and_state.result, "{what}"); + assert_eq!(outcome.gas, control.gas, "{what}"); + assert_eq!(outcome.usage, control.usage, "{what}"); + assert_eq!(outcome.limit_exceeded, control.limit_exceeded, "{what}"); + control +} + +/// A leaf an earlier transaction destroyed is absent at the next transaction's start, whether the +/// two run on one journal, as a block builder runs them, or the first is committed before the +/// second runs. The address held an account the first transaction found: a balance, or nothing but +/// storage. The first transaction creates there and destroys the account, the present row, which +/// gives no leaf back; the second does the same onto an address that now holds nothing, the absent +/// row, whose leaf comes back with its state gas, its unit of state growth and its record. The +/// second transaction's outcome is the same on either path, at any byte price. +#[test] +fn test_a_leaf_an_earlier_transaction_destroyed_is_absent_at_the_next_start() { + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default().append(STOP)); + let tx = |nonce| { + let mut tx = call_tx(BELOW_THE_CAP); + tx.0.base.nonce = nonce; + tx + }; + for (held, what) in [(true, "a balance"), (false, "storage alone")] { + let mut db = funded_contract(code.clone()); + if held { + db.set_account_balance(created, U256::from(1)); + } else { + db.set_account_storage(created, U256::from(1), U256::from(5)); + } + + let first = execute(db.clone(), tx(0)); + assert!(first.result.is_success(), "{what}: {:?}", first.result); + assert!(is_destroyed(&first, created), "{what}: the first transaction destroyed it"); + let charged = if held { 0 } else { common::account_state_gas() }; + assert_eq!(first.gas.state, charged, "{what}: the present row gives no leaf back"); + + let second = the_same_on_one_journal(db, &[tx(0), tx(1)], what); + assert!(second.result.is_success(), "{what}: {:?}", second.result); + assert_eq!(second.gas.state, 0, "{what}: the absent row gives the leaf back"); + assert_eq!(second.usage.state_growth, 0, "{what}"); + assert_eq!(second.usage.write_records, 1, "{what}: the factory's nonce alone"); + assert_eq!(second.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE, "{what}"); + } +} + +/// A creation at the address an earlier transaction funded, destroyed to an existing account, +/// whose leaf the transaction found present: the creation charged no account, so the destruction +/// gives no leaf back, and the created account's record stands beside the factory's and the +/// beneficiary's, with the transfer log of the balance it moved. +fn assert_the_present_row(outcome: &MegaTransactionOutcome, created: Address, what: &str) { + assert!(outcome.result.is_success(), "{what}: {:?}", outcome.result); + assert!(is_destroyed(outcome, created), "{what}: the creation did not collide"); + assert_eq!(outcome.gas.state, 0, "{what}: no leaf was charged or given back"); + assert_eq!(outcome.usage.state_growth, 0, "{what}"); + assert_eq!(outcome.usage.write_records, 3, "{what}: the factory, the account, the beneficiary"); + assert_eq!( + outcome.usage.data_size, + BODY_BYTES + 3 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + "{what}" + ); +} + +/// A leaf an earlier transaction funded is present at the next transaction's start, whether the +/// two run on one journal or the first is committed before the second runs. The address held no +/// account until the first transaction moved 1 wei to it; the second creates there and destroys +/// the account to an existing one. On one journal revm's flag of the account the database answered +/// none for still stands from the first transaction's load, but the leaf held a balance when the +/// second started, so it is the present row, as on the committed path. +#[test] +fn test_a_leaf_an_earlier_transaction_funded_is_present_at_the_next_start() { + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default().append(STOP)); + let mut create = call_tx(BELOW_THE_CAP); + create.0.base.nonce = 1; + let fund = common::call(CALLER, created, U256::from(1), BELOW_THE_CAP); + let outcome = the_same_on_one_journal(funded_contract(code), &[fund, create], "funded"); + assert_the_present_row(&outcome, created, "funded"); +} + +/// A leaf funded after an earlier transaction destroyed the account there is present at the next +/// transaction's start, on one journal as on the committed path. The first transaction creates at +/// the address and destroys the account; the second moves 1 wei to it; the third creates there +/// again and destroys the account to an existing one. On one journal revm's entry names the third +/// destruction a first one in its transaction of an account an earlier transaction destroyed, but +/// the leaf held a balance when the third started, so it is the present row. The address held no +/// account at first, or a balance the database answered. +#[test] +fn test_a_leaf_funded_after_its_destruction_is_present_at_the_next_start() { + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default().append(STOP)); + let create = |nonce| { + let mut tx = call_tx(BELOW_THE_CAP); + tx.0.base.nonce = nonce; + tx + }; + let mut fund = common::call(CALLER, created, U256::from(1), BELOW_THE_CAP); + fund.0.base.nonce = 1; + for (held, what) in [(false, "no account"), (true, "a balance")] { + let mut db = funded_contract(code.clone()); + if held { + db.set_account_balance(created, U256::from(1)); + } + let outcome = the_same_on_one_journal(db, &[create(0), fund.clone(), create(2)], what); + assert_the_present_row(&outcome, created, what); + } +} + +/// After the mark, an `SSTORE` of a slot the destroyed account never wrote, `(original 0, present +/// 0, new non-zero)`: the write happens, but it does not rise, keeps no fresh-slot state gas — the +/// pricing hook prices it at nothing, so the store neither charges nor refills it — and makes no +/// record. +#[test] +fn test_a_fresh_slot_written_after_the_mark_is_neither_charged_nor_counted() { + if !pins_state() { + return; + } + let runtime = store_or_destroy(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + call_with_word( + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + created, + 7, + ) + .append(POP), + ); + assert_eq!(sstore_state_gas(&code, |_| {}, created), [0], "the store moves no state gas"); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(slot_value(&outcome, created, 1), U256::from(7), "the store after the mark ran"); + assert_eq!(outcome.gas.state, 0, "the slot keeps no state gas"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// A created account whose runtime reads the block's timestamp and then self-destructs, under a +/// compute cap its `SELFDESTRUCT` crosses: at the opcode's own gas, before the destruction is +/// written, or at its cold access to the beneficiary, after it. Either way the crossing stops the +/// destroying frame before the opcode completes, so the operation applies none of the table: the +/// account is not destroyed, its leaf, code and slot stay charged and recorded, and its caller +/// resumes and returns the stop. Under a cap that also leaves the caller's own work after the call +/// its room, the destruction completes and gives them back. +#[test] +fn test_a_detention_crossing_at_the_destruction_applies_none_of_the_table() { + use revm::bytecode::opcode::TIMESTAMP; + if !pins_state() { + return; + } + let mut runtime = vec![TIMESTAMP, POP]; + runtime.extend_from_slice(&runtime_to(EXISTING)); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP).return_returndata(), + ); + // After the read: `POP`, `PUSH20`, then the opcode's 5,000 and its cold access. + let cold = satin_gas_params().selfdestruct_cold_cost(); + for cap in [2 + 3 + 5_000 - 1, 2 + 3 + 5_000 + cold - 1] { + let limits = + mega_evm::EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let outcome = + super::execute_under(funded_contract(code.clone()), call_tx(BELOW_THE_CAP), limits); + assert!(outcome.result.is_success(), "cap {cap}: {:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2, "cap {cap}: the destroying frame is stopped"); + assert!(!is_destroyed(&outcome, created), "cap {cap}"); + assert_eq!( + outcome.gas.state, + ACCOUNT_LEAF_STATE_GAS_M1 + SLOT_STATE_GAS_M1 + code_state(&runtime), + "cap {cap}: nothing is given back" + ); + assert_eq!(outcome.usage.write_records, 3, "cap {cap}: the records stand"); + } + let limits = mega_evm::EvmTxRuntimeLimits::default() + .with_block_env_access_compute_gas_limit(2 + 3 + 5_000 + cold + 100); + let outcome = super::execute_under(funded_contract(code), call_tx(BELOW_THE_CAP), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "within the cap the destruction completes"); + assert_eq!(outcome.gas.state, 0, "and gives the account's state gas back"); +} + +/// A transaction gas limit below the execution cap: no reservoir, so state gas spills onto +/// regular gas and a frame's regular gas is all that pays it. +const BELOW_THE_CAP: u64 = 50_000_000; + +/// `CALL` of `target` with `gas` and one 32-byte word of calldata, `word`. +fn call_with_word_and_gas( + code: BytecodeBuilder, + target: Address, + word: u64, + gas: u32, +) -> BytecodeBuilder { + code.mstore(0x200, U256::from(word).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .push_number(0x200_u16) + .append(PUSH0) + .push_address(target) + .push_number(gas) + .append(CALL) +} + +/// After the mark, a fresh `SSTORE` on 60,000 gas, below the transaction's execution cap where +/// no reservoir pays: the store is charged no state gas, so it completes, where the same store of +/// the account before any destruction needs the slot's 97,920 of state gas and runs out of gas. +#[test] +fn test_a_store_after_the_mark_is_not_charged_what_its_frame_cannot_pay() { + if !pins_state() { + return; + } + const GAS: u32 = 60_000; + assert!(u64::from(GAS) < SLOT_STATE_GAS_M1); + let runtime = store_or_destroy(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + for destroyed in [true, false] { + let first = if destroyed { + BytecodeBuilder::default().call(created, U256::ZERO).append(POP) + } else { + BytecodeBuilder::default() + }; + let tail = call_with_word_and_gas(first, created, 7, GAS).append(POP).stop(); + let code = after_create(init.clone(), U256::ZERO, tail); + let outcome = execute(funded_contract(code), call_tx(BELOW_THE_CAP)); + assert!(outcome.result.is_success(), "destroyed {destroyed}: {:?}", outcome.result); + let stored = if destroyed { U256::from(7) } else { U256::ZERO }; + assert_eq!(slot_value(&outcome, created, 1), stored, "destroyed {destroyed}"); + } +} + +/// Code deposited after its constructor destroyed the account, on gas that cannot pay the +/// deposit's state gas: the address held a balance before the transaction, so its leaf was +/// present and the destruction refills nothing that could pay for the deposit. The deposit is +/// charged no state gas, so the creation succeeds; the same constructor without the destruction +/// runs out of gas on the deposit, and the creation fails. +/// +/// The transaction carries a reservoir of 10,000 above the cap and the body: the creating frame's +/// share of it pays the history of the `CREATE2`'s two records, 7,040, which the 2 per cent of its +/// regular gas it keeps could not, and leaves the constructor a share of about 2,700. The creating +/// frame is called with 40,000 of regular gas: once the `CREATE2` took its own, the constructor's +/// share covers the destruction and the deposit's hash, and falls short of the deposit's state gas. +/// The destroying constructor deploys from 30,000 up, and the other fails up to 45,000. +#[test] +fn test_a_deposit_after_the_mark_is_not_charged_what_its_frame_cannot_pay() { + if !pins_state() { + return; + } + const CREATOR_GAS: u32 = 40_000; + let runtime = runtime_to(EXISTING); + assert!(code_state(&runtime) > 30_000); + let gas = EXECUTION_CAP + BODY_HISTORY + 10_000; + for destroyed in [true, false] { + let mut init = + if destroyed { delegatecall(GRAND).append(POP).build().to_vec() } else { vec![] }; + init.extend_from_slice(&BytecodeBuilder::default().return_with_data(&runtime).build()); + let init = Bytes::from(init); + let created = CHILD.create2(B256::ZERO, keccak256(&init)); + let creator = + BytecodeBuilder::default().create2(U256::ZERO, &init, U256::ZERO).return_top().build(); + let code = call_with_gas(BytecodeBuilder::default(), CHILD, U256::ZERO, CREATOR_GAS) + .append(POP) + .return_returndata() + .build() + .to_vec(); + let mut db = funded_contract(code); + db.set_account_code(CHILD, creator); + db.set_account_code(GRAND, runtime.clone()); + db.set_account_balance(created, U256::from(1)); + let outcome = execute(db, call_tx(gas)); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("destroyed {destroyed}: {:?}", outcome.result); + }; + let deployed = + U256::from_be_slice(output.data()) == U256::from_be_slice(created.as_slice()); + assert_eq!(deployed, destroyed, "destroyed {destroyed}: the creation succeeds"); + if destroyed { + assert!(is_destroyed(&outcome, created)); + assert!(has_code(&outcome, created), "the code was deposited"); + assert_eq!(outcome.gas.state, 0, "and charged no state gas"); + } + } +} + +/// A constructor that destroys its own account through a `DELEGATECALL` to code that +/// self-destructs, and then returns its runtime. The destruction gives the leaf back; the code is +/// deposited after the mark, so its state gas is not kept, while its data size and history are +/// charged as any deposited code's. A later call that runs the runtime, which self-destructs +/// again, takes nothing back. +#[test] +fn test_code_deposited_after_its_constructor_destroyed_the_account_keeps_no_state_gas() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let mut prefix = delegatecall(CHILD).append(POP).build().to_vec(); + prefix.extend_from_slice(&BytecodeBuilder::default().return_with_data(&runtime).build()); + let init = Bytes::from(prefix); + let created = created_at(&init); + for again in [false, true] { + let tail = if again { + BytecodeBuilder::default().call(created, U256::ZERO).append(POP) + } else { + BytecodeBuilder::default() + }; + let code = after_create(init.clone(), U256::ZERO, tail); + let Some((outcome, probed)) = both(code, |db| db.set_account_code(CHILD, runtime.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "again {again}: {:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "again {again}"); + assert!(has_code(&outcome, created), "again {again}: the code was deposited"); + assert_eq!(outcome.gas.state, 0, "again {again}: the leaf came back, the code kept none"); + let kept = BODY_BYTES + WRITE_RECORD_SIZE + runtime.len() as u64; + assert_eq!(outcome.usage.data_size, kept, "again {again}: the code's bytes stay"); + assert_eq!(outcome.gas.history, history(kept), "again {again}: and their history"); + assert_eq!(outcome.usage.write_records, 1, "again {again}: only the creator's record"); + assert_growth(&probed, 0); + } +} + +/// A creation transaction carrying 1 wei whose constructor writes 999 fresh slots and then +/// self-destructs to an account that does not exist. The created account and its slots use the +/// whole state-growth limit of 1,000, which is the transaction's own frame's budget, and the +/// beneficiary would be a 1,001st unit: the destruction takes back the absent leaf and the 999 +/// slots before the beneficiary is held, so the beneficiary fits and the transaction keeps one new +/// account. Under a limit one unit higher the transaction keeps the same: the limit stops nothing. +#[test] +fn test_a_creation_at_its_growth_limit_that_destroys_itself_to_a_new_account_succeeds() { + let mut init = store_n_prefix(999, 1, false); + init.extend_from_slice(&runtime_to(BENEFICIARY)); + let Some(gas) = slots_gas(1_000) else { return }; + let tx = || { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + data: Bytes::from(init.clone()), + value: U256::from(1), + gas_limit: gas, + ..Default::default() + })) + }; + let created = CALLER.create(0); + for limit in [TX_STATE_GROWTH_LIMIT, TX_STATE_GROWTH_LIMIT + 1] { + let limits = mega_evm::EvmTxRuntimeLimits::default().with_tx_state_growth_limit(limit); + let outcome = super::execute_under(world(&[]), tx(), limits); + assert!(outcome.result.is_success(), "limit {limit}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "limit {limit}"); + assert!(is_destroyed(&outcome, created), "limit {limit}"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1), "limit {limit}"); + assert_eq!(outcome.usage.state_growth, 1, "limit {limit}: the beneficiary alone"); + // The beneficiary's record; the created account's and its slots' went with it. + assert_eq!(outcome.usage.write_records, 1, "limit {limit}"); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "limit {limit}"); + } + } +} + +/// The state gas each `SSTORE` an account ran moved on its frame's net, in execution order. +#[derive(Clone, Debug, Default)] +struct SstoreStateGas { + armed: Option<(Address, i64)>, + seen: Vec<(Address, i64)>, +} + +impl Inspector, EthInterpreter> for SstoreStateGas { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + if interp.bytecode.opcode() == SSTORE { + self.armed = Some((interp.input.target_address(), interp.gas.state_gas_spent())); + } + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if let Some((account, before)) = self.armed.take() { + self.seen.push((account, interp.gas.state_gas_spent() - before)); + } + } +} + +/// What each `SSTORE` that ran in `account` moved its frame's state gas by, in order, in the +/// plain run [`both`] makes of `scenario`. +fn sstore_state_gas( + scenario: &[u8], + setup: impl Fn(&mut MemoryDatabase), + account: Address, +) -> Vec { + let mut code = scenario.to_vec(); + code.push(STOP); + let mut db = funded_contract(code); + setup(&mut db); + let gas = probe_gas(10).expect("the scenario fits a gas limit"); + let mut evm = mega_evm::MegaEvm::new(context(db)).with_inspector(SstoreStateGas::default()); + let outcome = evm.execute_transaction(call_tx(gas)).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + evm.inspector().seen.iter().filter(|(at, _)| *at == account).map(|(_, moved)| *moved).collect() +} + +/// What a frame's gas held just before and just after its `SELFDESTRUCT`. +#[derive(Clone, Debug, Default)] +struct DestructionGas { + armed: bool, + /// `(regular remaining, reservoir)` at the opcode, before its static gas. + before: Option<(u64, u64)>, + /// `(regular remaining, reservoir)` once the opcode completed. + after: Option<(u64, u64)>, +} + +impl Inspector, EthInterpreter> for DestructionGas { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + if interp.bytecode.opcode() == SELFDESTRUCT { + self.armed = true; + self.before = Some((interp.gas.remaining(), interp.gas.reservoir())); + } + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.armed { + self.armed = false; + self.after = Some((interp.gas.remaining(), interp.gas.reservoir())); + } + } +} + +/// The transaction is below the execution cap, so the reservoir is empty. The destroying frame +/// stores two fresh slots of its own, which spill 195,840 of state gas and 7,040 of history onto +/// its regular gas, and self-destructs to a warm existing account. The table gives back the leaf +/// and its record, slot 1 and its record from the constructor, the code's state gas and history, +/// and the frame's own two slots and records. The frame's regular gas is credited first, up to +/// the 202,880 still spilled, and the rest goes to its reservoir. Read at the opcode with an +/// inspector. At the transaction's end nothing is left in the reservoir and no state gas stays. +#[test] +fn test_a_give_back_onto_an_empty_reservoir_credits_the_spill_first() { + if !pins_state() { + return; + } + let runtime = BytecodeBuilder::default() + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(3), U256::from(1)) + .selfdestruct(EXISTING) + .build(); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP).stop(), + ); + let spilled = 2 * (SLOT_STATE_GAS_M1 + RECORD_HISTORY); + assert_eq!(spilled, 202_880); + let rest = ACCOUNT_LEAF_STATE_GAS_M1 + + RECORD_HISTORY + + SLOT_STATE_GAS_M1 + + RECORD_HISTORY + + code_state(&runtime) + + history(runtime.len() as u64); + let mut evm = mega_evm::MegaEvm::new(context(funded_contract(code))) + .with_inspector(DestructionGas::default()); + let outcome = evm + .execute_transaction(warm_call(50_000_000, &[EXISTING])) + .expect("the transaction is valid"); + let probe = evm.inspector().clone(); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (before, reservoir_before) = probe.before.expect("the account self-destructed"); + let (after, reservoir_after) = probe.after.expect("the opcode completed"); + assert_eq!(reservoir_before, 0, "the reservoir is empty"); + assert_eq!(after + 5_000, before + spilled, "regular gas is credited up to the spill"); + assert_eq!(reservoir_after, rest, "the rest goes to the reservoir"); + assert_eq!(outcome.gas.state, 0); + assert_eq!(outcome.gas.reservoir_remaining, 0, "the credit meets the callers' spill too"); +} + +/// A creation transaction whose constructor destroys its own account. On success the created +/// account's record is given back once, 3,520 at the spec's byte price, and not a second time. +/// When that first frame fails, the table's give-back is discarded and the settlement gives the +/// charge back once. +#[test] +fn test_a_creation_that_destroys_itself_refunds_its_record_once() { + if !pins_state() { + return; + } + let mut prefix = delegatecall(CHILD).append(POP).build().to_vec(); + prefix.extend_from_slice(&BytecodeBuilder::default().revert().build()); + let init = Bytes::from(prefix); + let db = world(&[(CHILD, runtime_to(EXISTING))]); + let Some(gas) = slots_gas(1) else { return }; + let outcome = execute(db, create_tx(init.clone(), gas)); + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "a failing constructor reverts the creation: {:?}", + outcome.result + ); + let body = (BODY_BYTES + init.len() as u64) * HISTORY_GAS_PER_BYTE; + assert_eq!(outcome.gas.history, body, "a failed first frame gives the record back once"); + assert_eq!(outcome.gas.state, 0); + + let init = runtime_to(EXISTING); + let Some(gas) = slots_gas(1) else { return }; + let db = world(&[(EXISTING, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, create_tx(init.clone(), gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let body = (BODY_BYTES + init.len() as u64) * HISTORY_GAS_PER_BYTE; + assert_eq!( + outcome.gas.history, body, + "giving the created record back removes {RECORD_HISTORY}, once" + ); + assert_eq!(outcome.gas.history, outcome.gas.history_bytes * HISTORY_GAS_PER_BYTE); + assert_eq!(outcome.gas.state, 0, "the leaf is given back and the beneficiary already exists"); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs b/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs new file mode 100644 index 000000000..be1b98ecf --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs @@ -0,0 +1,438 @@ +//! The gas cap and the reservoir share. +//! +//! A child frame is started with an explicit gas below the caller's cap, so the gas it holds at +//! `CALL` is the number the test names. The opcode's static warm read is not yet charged when the +//! inspector reads `remaining`. + +use alloy_primitives::{Bytes, U256}; +use mega_evm::{ + test_utils::{neutral_cfg, neutralize_evm, note_price_guard, BytecodeBuilder}, + EthSpecId, EvmTxRuntimeLimits, MegaEvm, MegaLimitExceeded, +}; +use revm::bytecode::opcode::{ + CALL, CALLDATALOAD, GAS, MSTORE8, POP, PUSH0, SHR, SSTORE, STOP, TIMESTAMP, +}; + +use super::{ + at_spec_prices, call_tx, call_with_reservoir, execute, execute_forward, execute_forward_under, + forward_to, gas_cap, returned_stop, slot_value, warm_call, world, CALL_STIPEND, CHILD, + CONTRACT, EXECUTION_CAP, EXISTING, GRAND, HISTORY_ALLOWANCE_BYTES, HISTORY_ALLOWANCE_GAS, + HISTORY_GAS_PER_BYTE, RESERVOIR_KEPT_PERCENT, SLOT_STATE_GAS_M1, VALUE_TRANSFER_GAS, WARM_READ, +}; +use crate::common::{self, context}; + +/// Gas the non-value inner frame spends before `CALL`'s static warm read. +/// +/// Five `PUSH0`, one `PUSH20` and `GAS`: `5 × 2 + 3 + 2`. +const NON_VALUE_PREFIX: u64 = 15; + +/// Gas the value inner frame spends before `CALL`'s static warm read. +/// +/// Four `PUSH0`, one `PUSH1`, one `PUSH20` and `GAS`: `4 × 2 + 3 + 3 + 2`. +const VALUE_PREFIX: u64 = 16; + +/// Inner code that calls [`EXISTING`] with all the gas it has. +fn measuring_call(value: bool) -> Bytes { + let mut code = BytecodeBuilder::default(); + if value { + code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).push_number(1_u8); + } else { + code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]); + } + code.push_address(EXISTING).append_many([GAS, CALL, STOP]).build() +} + +/// Outer code that gives [`CHILD`] exactly `frame_gas`, carrying no value, so no stipend is added +/// to it. +fn grant(frame_gas: u16) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(frame_gas) + .append_many([CALL, STOP]) + .build() +} + +/// A warm call above the execution cap. The reservoir pays the history of the inner value call's +/// two records, which the caller could not pay from the 2% of its regular gas it keeps. +fn measuring_tx() -> super::MegaTransaction { + warm_call(EXECUTION_CAP + common::value_call_room(), &[CHILD, EXISTING]) +} + +/// `(gas held at the inner CALL, gas the inner CALL forwarded)`. +fn measure(frame_gas: u16, value: bool) -> (u64, u64) { + let db = world(&[ + (CONTRACT, grant(frame_gas)), + (CHILD, measuring_call(value)), + (EXISTING, Bytes::from_static(&[STOP])), + ]); + let (outcome, probe) = execute_forward(db, measuring_tx(), super::Forward::targeting(EXISTING)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let held = probe.held.unwrap_or_else(|| { + panic!("the inner CALL was reached; calls {:?}", probe.calls); + }); + let forwarded = probe.gas_limit.expect("the inner CALL forwarded gas"); + (held, forwarded) +} + +/// What EIP-150's 63/64 rule would forward of `remaining`, for contrast. +const fn eip150(remaining: u64) -> u64 { + remaining - remaining / 64 +} + +/// Regular gas left after the warm read, which is the cap's input. +fn left_after_warm(held: u64) -> u64 { + held - WARM_READ +} + +/// Parent reservoir `R = 50 × 97,920`. The child receives `R − R × 2 / 100`. The grandchild +/// receives that share of what the child has left. +#[test] +fn test_a_child_receives_the_reservoir_share() { + const R: u64 = 50 * SLOT_STATE_GAS_M1; + let db = world(&[ + (CONTRACT, forward_to(CHILD)), + (CHILD, forward_to(GRAND)), + (GRAND, Bytes::from_static(&[STOP])), + ]); + let (outcome, probe) = execute_forward(db, call_with_reservoir(R), super::Forward::any()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(probe.calls.len() >= 2, "child and grandchild: {:?}", probe.calls); + assert_eq!(probe.reservoir_given(CONTRACT), R, "the transaction's own frame takes the whole"); + let child = probe.reservoir_given(CHILD); + let grandchild = probe.reservoir_given(GRAND); + assert_eq!(child, R - R * RESERVOIR_KEPT_PERCENT / 100, "child reservoir {child}"); + assert_eq!( + grandchild, + child - child * RESERVOIR_KEPT_PERCENT / 100, + "grandchild reservoir {grandchild}" + ); +} + +/// The child spends one fresh slot from its reservoir share and reverts. The caller had no +/// outstanding spill, so it holds the reservoir it had after the body's charge. The slot is not +/// kept and the state ledger is zero. +#[test] +fn test_a_reverted_child_returns_its_reservoir_share() { + const R: u64 = 50 * SLOT_STATE_GAS_M1; + if common::slot_state_gas() > R { + note_price_guard("one fresh slot costs more than the reservoir this row forwards"); + return; + } + let mut child = super::store_n_prefix(1, 1, false); + child.extend_from_slice(&[PUSH0, PUSH0, 0xfd]); + let db = world(&[(CONTRACT, forward_to(CHILD)), (CHILD, Bytes::from(child))]); + let outcome = execute(db, call_with_reservoir(R)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + assert_eq!(outcome.gas.state, 0, "the child's state charge came back"); + assert_eq!(outcome.gas.reservoir_remaining, R); +} + +/// The share a failed child returns when its caller has an outstanding spill. +/// +/// The caller holds `R` and keeps `k = R × 2 / 100` when its first child takes the share. That +/// child fills 50 fresh slots, more than its share pays, and succeeds, so its spill joins the +/// caller's and the caller's kept `k` is not drawn. The second child is given `k − k × 2 / 100` +/// and reverts at once. The share it returns unwinds the caller's spill first, so the caller ends +/// with `k × 2 / 100`, not the `k` it held after the start's charges. At `m` = 1, `R` = +/// 4,896,000, `k` = 97,920 and the reservoir left is 1,958. +/// +/// The caller is the transaction's own frame, so its reservoir is read where its frame ends: +/// the transaction then settles that frame as a caller settles a child, and the 1,958 unwinds +/// the frame's own outstanding spill there, coming back to the sender as regular gas. +#[test] +fn test_a_reverted_childs_share_unwinds_the_callers_spill_first() { + if common::state_is_free() { + return; + } + let r = 50 * common::slot_state_gas(); + let kept = r * RESERVOIR_KEPT_PERCENT / 100; + let left = kept * RESERVOIR_KEPT_PERCENT / 100; + if left == 0 { + note_price_guard("the caller's second keep rounds to nothing"); + return; + } + let parent = BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .call(GRAND, U256::ZERO) + .append(POP) + .stop() + .build(); + let db = world(&[ + (CONTRACT, parent), + (CHILD, super::store_n_slots(50)), + (GRAND, BytecodeBuilder::default().revert().build()), + ]); + let (outcome, probe) = execute_forward(db, call_with_reservoir(r), super::Forward::any()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(slot_value(&outcome, CHILD, 50), U256::from(1), "the first child succeeded"); + assert_eq!(probe.reservoir_given(GRAND), kept - left, "the second child's share"); + let ended = probe.call_ends.last().expect("the transaction's own frame ended"); + assert_eq!(ended.0, CONTRACT); + assert_eq!( + ended.1, left, + "the returned share unwound the spill; k = {kept}, k × 2 / 100 = {left}" + ); + assert_eq!(outcome.gas.reservoir_remaining, 0, "the transaction's settlement unwound the rest"); +} + +/// `CALL` with gas argument 1 still forwards the reservoir share, `R − R × 2 / 100` of the +/// reservoir `R` the caller holds. The gas argument bounds the regular gas only. +#[test] +fn test_a_one_gas_call_still_forwards_the_reservoir() { + const R: u64 = SLOT_STATE_GAS_M1; + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(1_u8) + .append_many([CALL, STOP]) + .build(); + let db = world(&[(CONTRACT, parent), (CHILD, super::store_n_slots(1))]); + let (outcome, probe) = + execute_forward(db, call_with_reservoir(R), super::Forward::targeting(CHILD)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(probe.gas_limit, Some(1), "the gas argument bounds regular gas"); + assert_eq!(probe.reservoir, Some(super::reservoir_share(R)), "the share, not 1 and not R"); +} + +/// With 1,000 regular gas left, the cap is 980. EIP-150 would forward 985. +#[test] +fn test_a_call_with_1000_gas_left_forwards_980() { + let (held, forwarded) = measure((1_000 + NON_VALUE_PREFIX + WARM_READ) as u16, false); + assert_eq!(left_after_warm(held), 1_000, "held {held}"); + assert_eq!(forwarded, gas_cap(1_000)); + assert_ne!(forwarded, eip150(1_000), "EIP-150's 985 is not the cap"); +} + +/// With 99 left, the subtraction forwards 98. The frame-budget product would forward 97. +/// EIP-150 also forwards 98, so a pass here does not decide the quotient. +#[test] +fn test_a_call_with_99_gas_left_forwards_98() { + let (held, forwarded) = measure((99 + NON_VALUE_PREFIX + WARM_READ) as u16, false); + assert_eq!(left_after_warm(held), 99, "held {held}"); + assert_eq!(forwarded, 99 - 99 * RESERVOIR_KEPT_PERCENT / 100); + assert_ne!(forwarded, super::frame_share(99), "the product would forward 97"); +} + +/// With 50 left, the subtraction forwards 49. EIP-150 forwards 50, because `floor(50 / 64)` is 0. +#[test] +fn test_a_call_with_50_gas_left_forwards_49() { + let (held, forwarded) = measure((50 + NON_VALUE_PREFIX + WARM_READ) as u16, false); + assert_eq!(left_after_warm(held), 50, "held {held}"); + assert_eq!(forwarded, 49); + assert_ne!(forwarded, eip150(50), "EIP-150 forwards the whole 50"); +} + +/// After the 11,300 value-transfer charge the caller has 10,000 left and requests all. The cap +/// on 10,000 is 9,800. The child receives 12,100. The caller keeps 200. The 2,300 stipend is +/// already inside the 11,300 and is added after the cap, not taken from the caller. The caller +/// is granted its gas without value, so its own gas has no stipend in it, and the transaction's +/// reservoir pays the history of the value call's records. +#[test] +fn test_a_value_call_with_10000_left_forwards_12100() { + let frame = VALUE_PREFIX + WARM_READ + VALUE_TRANSFER_GAS + 10_000; + let (held, forwarded) = measure(frame as u16, true); + let after_value = held - WARM_READ - VALUE_TRANSFER_GAS; + assert_eq!(after_value, 10_000, "held {held}"); + assert_eq!(forwarded, gas_cap(10_000) + CALL_STIPEND); + assert_eq!(10_000 - gas_cap(10_000), 200, "the caller keeps 200 of the 10,000"); +} + +/// A value `CALL` below the top frame grants 160 history bytes (14,080 gas). The allowance is +/// outside the child's gas limit and outside the reservoir share: the child's gas is the 98/100 +/// cap plus the 2,300 stipend, and its reservoir is the share of what the caller has left after +/// the history of the start's two records. +#[test] +fn test_a_value_call_grants_a_history_allowance_outside_gas() { + if !at_spec_prices() || common::history_is_free() || common::history_rounds() { + return; + } + const R: u64 = 50 * SLOT_STATE_GAS_M1; + let parent = BytecodeBuilder::default().call(CHILD, U256::from(1)).stop().build(); + let db = world(&[ + (CONTRACT, parent), + (CHILD, BytecodeBuilder::default().log3_word().stop().build()), + ]) + .account_balance(CONTRACT, U256::from(10u128.pow(18))); + // The access list adds one 20-byte address to the body. + let gas = EXECUTION_CAP + common::history(super::BODY_BYTES + 20) + R; + let (outcome, probe) = + execute_forward(db, warm_call(gas, &[CHILD]), super::Forward::targeting(CHILD)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let gap = outcome.gas.history_bytes * HISTORY_GAS_PER_BYTE - outcome.gas.history; + assert_eq!( + gap, + HISTORY_ALLOWANCE_BYTES * HISTORY_GAS_PER_BYTE, + "history bytes {} gas {}", + outcome.gas.history_bytes, + outcome.gas.history + ); + assert_eq!(gap, HISTORY_ALLOWANCE_GAS); + let held = probe.held.expect("the value call was reached"); + let forwarded = probe.gas_limit.expect("the value call forwarded gas"); + let left = held - WARM_READ - VALUE_TRANSFER_GAS; + assert_eq!(forwarded, gas_cap(left) + CALL_STIPEND, "the cap plus the stipend, no allowance"); + // The caller's and the child's balances change: two records, paid from the reservoir first. + let after_records = R - 2 * super::RECORD_HISTORY; + assert_eq!(probe.reservoir, Some(super::reservoir_share(after_records))); +} + +/// Reservoir remaining 1 gives the child 1 and the caller 0. A frame whose data-size remaining is +/// 1 gives its child `floor(1 × 98 / 100)` = 0, so one 40-byte record stops that child, kind 0, +/// `limit` 0. +/// +/// A transaction data-size limit of the body plus 2,002 gives the top frame 2,002 and its child +/// `floor(2,002 × 98 / 100)` = 1,961. That child keeps 49 records, 1,960 bytes, and has 1 left. +/// The transaction still has 42, so the grandchild's record crosses its own budget alone. +#[test] +fn test_a_reservoir_of_1_and_a_frame_budget_of_1() { + const TOP: u64 = 2_002; + assert_eq!(super::frame_share(TOP), 1_961); + assert_eq!(super::frame_share(TOP) - 49 * super::WRITE_RECORD_SIZE, 1); + let mut child = super::store_n_prefix(49, 1, false); + child.extend_from_slice( + &BytecodeBuilder::default().call(GRAND, U256::ZERO).return_returndata().build(), + ); + let db = world(&[ + (CONTRACT, forward_to(CHILD)), + (CHILD, Bytes::from(child)), + (GRAND, super::store_n_slots(1)), + ]); + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(super::BODY_BYTES + TOP); + let (outcome, probe) = + execute_forward_under(db, call_with_reservoir(1), limits, super::Forward::targeting(CHILD)); + assert_eq!(probe.reservoir, Some(1), "a remaining 1 forwards the whole reservoir"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the child caught the stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 0 }); + assert_eq!(slot_value(&outcome, GRAND, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CHILD, 49), U256::from(1), "the child kept its records"); +} + +/// A detained frame forwards with the 98/100 cap computed on spendable plus withheld. The child +/// then makes a regular charge past the compute cap, and that charge stops it, kind 2. +#[test] +fn test_a_detained_frame_forwards_on_spendable_plus_withheld() { + const CAP: u64 = 50_000; + let parent = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .call(CHILD, U256::ZERO) + .return_returndata() + .build(); + // One byte at offset 200_000 expands 6,251 words: about 95,000 gas, past the cap. + let child = BytecodeBuilder::default() + .push_number(1_u8) + .push_number(200_000_u32) + .append_many([MSTORE8, STOP]) + .build(); + let db = world(&[(CONTRACT, parent), (CHILD, child)]); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(CAP); + let (outcome, probe) = execute_forward_under( + db, + warm_call(5_000_000, &[CHILD]), + limits, + super::Forward::targeting(CHILD), + ); + let held = probe.held.expect("the call after TIMESTAMP was reached"); + let forwarded = probe.gas_limit.expect("the call forwarded gas"); + let left = held - WARM_READ; + assert!(left > CAP, "remaining() includes the withheld part: left {left}, cap {CAP}"); + assert_eq!(forwarded, gas_cap(left), "held {held}, forwarded {forwarded}"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2); +} + +/// The equivalence-mode contrast to Satin's forward, of which the page pins no figure. +/// +/// Neutral Amsterdam forwards EIP-150's 985 and passes each child the whole reservoir its caller +/// holds. `no_limits()` on Satin does not change the forward: 980 of regular gas, and at each of +/// the two calls the reservoir share, so the measured grandchild call gets the share of the share. +#[test] +fn test_neutral_forwards_eip150_and_satin_keeps_its_cap_without_limits() { + const R: u64 = 50 * SLOT_STATE_GAS_M1; + let frame = (1_000 + NON_VALUE_PREFIX + WARM_READ) as u16; + let code = [ + (CONTRACT, grant(frame)), + (CHILD, measuring_call(false)), + (EXISTING, Bytes::from_static(&[STOP])), + ]; + // The access list adds two 20-byte addresses to the body. + let gas = EXECUTION_CAP + common::history(super::BODY_BYTES + 40) + R; + let tx = warm_call(gas, &[CHILD, EXISTING]); + + let cfg = neutral_cfg(EthSpecId::AMSTERDAM).expect("Amsterdam has a neutral configuration"); + let mut neutral = MegaEvm::new(context(world(&code)).with_neutral_cfg(cfg)) + .with_inspector(super::Forward::targeting(EXISTING)); + neutralize_evm(&mut neutral, EthSpecId::AMSTERDAM).expect("Amsterdam neutralizes"); + let neutral_outcome = + neutral.execute_transaction(tx.clone()).expect("the transaction is valid"); + let neutral_probe = neutral.inspector().clone(); + assert!(neutral_outcome.result.is_success(), "{:?}", neutral_outcome.result); + let neutral_held = neutral_probe.held.expect("neutral reached the call"); + let neutral_forwarded = neutral_probe.gas_limit.expect("neutral forwarded"); + assert_eq!(neutral_held - WARM_READ, 1_000); + assert_eq!(neutral_forwarded, eip150(1_000), "EIP-150 forwards 985"); + assert_eq!( + neutral_probe.calls[1].2, neutral_probe.calls[0].2, + "neutral passes the whole reservoir: {:?}", + neutral_probe.calls + ); + + let limits = EvmTxRuntimeLimits::no_limits(); + let (outcome, probe) = + execute_forward_under(world(&code), tx, limits, super::Forward::targeting(EXISTING)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let held = probe.held.expect("satin reached the call"); + let forwarded = probe.gas_limit.expect("satin forwarded"); + assert_eq!(held - WARM_READ, 1_000); + assert_eq!(forwarded, gas_cap(1_000)); + let child = R - R * RESERVOIR_KEPT_PERCENT / 100; + assert_eq!(probe.reservoir_given(CONTRACT), R, "the transaction's own frame takes the whole"); + assert_eq!(probe.reservoir_given(CHILD), child, "the child's share"); + assert_eq!(probe.reservoir, Some(child - child * RESERVOIR_KEPT_PERCENT / 100)); +} + +/// Below the execution cap the reservoir starts at 0. The callee fills a fresh slot, so 97,920 of +/// state gas spills onto its regular gas and, on return, onto the caller. The callee then clears +/// the slot. The refill lands in the callee's reservoir and the returned reservoir unwinds the +/// caller's spill, so the caller's reservoir stays 0. A settlement that left the 97,920 in the +/// reservoir would report at least that much still remaining. +#[test] +fn test_a_returned_reservoir_unwinds_the_callers_spill() { + if !at_spec_prices() || common::state_is_free() { + return; + } + // Calldata byte 0 selects the value stored into slot 1. + let child = BytecodeBuilder::default() + .append(PUSH0) + .append(CALLDATALOAD) + .push_number(248_u8) + .append(SHR) + .push_number(1_u8) + .append(SSTORE) + .stop() + .build(); + let call_one_byte = |code: BytecodeBuilder| { + code.append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append_many([PUSH0, PUSH0]) + .push_address(CHILD) + .append_many([GAS, CALL]) + }; + let parent = call_one_byte( + call_one_byte(BytecodeBuilder::default().mstore(0, [1_u8])).append(POP).mstore(0, [0_u8]), + ) + .stop() + .build(); + let db = world(&[(CONTRACT, parent), (CHILD, child)]); + let outcome = execute(db, call_tx(10_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + assert_eq!(outcome.gas.state, 0, "the clear refilled the fresh-slot charge"); + assert_eq!( + outcome.gas.reservoir_remaining, 0, + "the returned refill unwinds the caller's spill instead of staying in the reservoir" + ); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs new file mode 100644 index 000000000..8459f2cc8 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs @@ -0,0 +1,682 @@ +//! Authorization totals and a keyless creation's forward, from the page. Kind 1 on the +//! authorization list runs under reduced transaction limits. A fatal database error is a +//! block verdict; the injected error here is not fatal, so the test checks that the transaction +//! has no outcome. + +use alloy_primitives::{hex, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + alloy_consensus::{Signed, TxLegacy}, + system::keyless::{ + decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + }, + test_utils::{ + note_price_guard, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, + SequencerRegistryRoles, + }, + MegaEvm, MegaLimitExceeded, MegaTransaction, +}; +use revm::{ + context::{result::ExecutionResult, transaction::TransactionType}, + context_interface::{ + cfg::GasId, + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, +}; + +use super::{ + at_spec_prices, call_tx, delegatecall, execute, execute_forward, frame_share, + halted_out_of_gas, nonce_of, reservoir_share, reverted_stop, store_n_slots, world, Forward, + ACCOUNT_LEAF_STATE_GAS_M1, BODY_BYTES, CALLER, CHILD, CONTRACT, EXECUTION_CAP, EXISTING, + INDICATOR_STATE_GAS, TX_STATE_GROWTH_LIMIT, +}; +use crate::common::{self, context}; + +/// Above any forward a `keylessDeploy` call here can make. +const LARGE_OVERRIDE: u64 = 10_000_000_000; +/// Signed gas of a creation that only stops. Below what the call has left. +const SIGNED_STOP_GAS: u64 = 1_000_000; +/// Signed gas of a creation that fills hundreds of slots. Below the call's regular gas, above the +/// state gas of 980 slots at the spec's byte price. +const SIGNED_SLOT_GAS: u64 = 150_000_000; +/// The gas price Nick's Method signs. The outer transaction's gas price stays zero. +const SIGNED_GAS_PRICE: u128 = 100_000_000_000; + +/// One authorization the list simulates. +struct Auth { + /// `None` is an unrecoverable signature. + authority: Option
, + chain_id: u64, + nonce: u64, + delegate: Address, +} + +/// A pre-EIP-155 creation, signed with Nick's Method's fixed signature. +struct Deployment { + tx: Bytes, + signer: Address, + address: Address, +} + +impl Deployment { + fn signed(gas_limit: u64, init_code: Bytes) -> Self { + let tx = TxLegacy { + nonce: 0, + gas_price: SIGNED_GAS_PRICE, + gas_limit, + to: TxKind::Create, + value: U256::ZERO, + input: init_code, + chain_id: None, + }; + let word = U256::from_be_bytes(hex!( + "2222222222222222222222222222222222222222222222222222222222222222" + )); + let signed = Signed::new_unchecked(tx, Signature::new(word, word, false), B256::ZERO); + let mut encoded = Vec::new(); + signed.rlp_encode(&mut encoded); + let signer = signed.recover_signer().expect("a Nick's-Method signature recovers"); + Self { tx: encoded.into(), signer, address: signer.create(0) } + } + + fn call_data(&self, gas_limit_override: u64) -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: self.tx.clone(), + gasLimitOverride: U256::from(gas_limit_override), + } + .abi_encode() + .into() + } +} + +fn keyless_db() -> MemoryDatabase { + // The relayer is [`CALLER`]. The registry's system address is a different account, so this + // call is not a system-address transaction. + MemoryDatabase::default() + .rex6_predeploys(SequencerRegistryRoles::from(mega_evm::system::MEGA_SYSTEM_ADDRESS)) + .account_balance(CALLER, U256::from(10u128.pow(24))) +} + +fn keyless_tx(data: Bytes, gas_limit: u64) -> MegaTransaction { + common::call_with_data(CALLER, KEYLESS_DEPLOY_ADDRESS, data, gas_limit) +} + +/// Gas above the execution cap that can pay `count` new authorities from the reservoir. +fn gas_above(count: u64) -> Option { + let history = common::history(BODY_BYTES + count.saturating_mul(101)); + let per = common::account_state_gas().saturating_add(indicator_at_schedule()); + let state = count.checked_mul(per)?.checked_add(common::account_state_gas())?; + let Some(gas) = history + .checked_add(state) + .and_then(|gas| gas.checked_add(5_000_000)) + .and_then(|gas| gas.checked_add(EXECUTION_CAP)) + else { + note_price_guard("the authorization list does not fit above the execution cap"); + return None; + }; + Some(gas) +} + +/// Gas below the execution cap. A list of 1,001 authorities cannot pay its state gas from it. +fn gas_below(count: u64) -> Option { + let history = common::history(BODY_BYTES + count.saturating_mul(101)); + let floor = history.saturating_add(21_000).saturating_add(count.saturating_mul(25_000)); + if floor >= EXECUTION_CAP { + note_price_guard("the authorization list's history does not fit below the execution cap"); + return None; + } + Some(EXECUTION_CAP - 1) +} + +/// Gas that covers one authority's intrinsic cost and cannot pay its leaf and indicator. +fn gas_under_one_authority() -> Option { + let floor = common::history(BODY_BYTES + 101).saturating_add(80_000); + let bill = common::account_state_gas().saturating_add(indicator_at_schedule()); + if bill <= floor || floor >= EXECUTION_CAP { + note_price_guard("one authority's state gas fits in the gas under test"); + return None; + } + Some(floor) +} + +fn indicator_at_schedule() -> u64 { + mega_evm::satin_gas_params().get(GasId::tx_eip7702_state_gas_bytecode()) +} + +fn pins_state() -> bool { + at_spec_prices() && !common::state_is_free() +} + +fn authority(n: u16) -> Address { + let mut raw = [0u8; 20]; + raw[0] = 0xa1; + raw[18] = (n >> 8) as u8; + raw[19] = n as u8; + Address::from(raw) +} + +fn auth_tx(gas_limit: u64, value: U256, to: Address, auths: &[Auth]) -> MegaTransaction { + let authorization_list = auths + .iter() + .map(|auth| { + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: U256::from(auth.chain_id), + address: auth.delegate, + nonce: auth.nonce, + }, + auth.authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), + )) + }) + .collect(); + let mut tx = call_tx(gas_limit); + tx.0.base.tx_type = TransactionType::Eip7702 as u8; + tx.0.base.kind = TxKind::Call(to); + tx.0.base.value = value; + tx.0.base.gas_priority_fee = Some(0); + tx.0.base.authorization_list = authorization_list; + tx +} + +/// Code that returns what one `BALANCE` of `address` cost: `GAS`, `PUSH20`, `BALANCE`, `POP`, +/// `GAS`, and the difference, which is the access plus 7. +fn balance_cost(address: Address) -> Bytes { + use revm::bytecode::opcode::{BALANCE, GAS, POP, SUB, SWAP1}; + BytecodeBuilder::default() + .append(GAS) + .push_address(address) + .append_many([BALANCE, POP, GAS, SWAP1, SUB]) + .return_top() + .build() +} + +/// The cost of the `BALANCE` [`balance_cost`] measured. +fn access_cost(outcome: &mega_evm::MegaTransactionOutcome) -> u64 { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the measuring call did not succeed: {:?}", outcome.result); + }; + U256::from_be_slice(output.data()).to::() - 7 +} + +fn new_auth(n: u16, nonce: u64) -> Auth { + Auth { authority: Some(authority(n)), chain_id: 0, nonce, delegate: CHILD } +} + +fn many(count: u16) -> Vec { + (1..=count).map(|n| new_auth(n, 0)).collect() +} + +fn keyless_failure(outcome: &mega_evm::MegaTransactionOutcome) -> KeylessDeployError { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the keyless call did not succeed: {:?}", outcome.result); + }; + let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + .expect("a keylessDeploy return"); + decode_error_result(&ret.errorData).expect("errorData is a keyless error") +} + +/// The creation's state-gas and history charges the call makes before it forwards the reservoir: +/// the signer's leaf, the deploy address's leaf, and one record for each. +fn start_charges() -> u64 { + 2 * common::account_state_gas() + 2 * common::history(super::WRITE_RECORD_SIZE) +} + +/// 1,001 distinct new authorities, below the execution cap. Apply none. The transaction's own +/// frame stops before it runs, kind 3, `limit` 1,000. No authority is created. +#[test] +fn test_an_authorization_list_of_1001_new_authorities_stops_before_the_first_frame() { + let Some(gas) = gas_below(1_001) else { return }; + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_001))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert!(outcome.limit_exceeded.is_some()); + assert_eq!(nonce_of(&outcome, authority(1)), 0, "no authority account is kept"); + assert_eq!(nonce_of(&outcome, CALLER), 1, "the sender's nonce stands"); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0, "no authority state gas is charged"); + } +} + +/// 1,000 new authorities fit and are applied. The transaction's value would create one more +/// account. That recipient stops the first frame, kind 3, `limit` 0, and is not kept. The +/// authorities stay. +#[test] +fn test_a_fitting_list_keeps_the_authorities_when_the_recipient_stops() { + let Some(gas) = gas_above(1_000) else { return }; + let recipient = Address::from_word(B256::repeat_byte(0x27)); + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::from(1), recipient, &many(1_000))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: 0 }); + assert_eq!(super::balance_of(&outcome, recipient), U256::ZERO, "the recipient is not kept"); + assert_eq!(nonce_of(&outcome, authority(1)), 1, "an applied authority stays"); + assert_eq!(nonce_of(&outcome, authority(1_000)), 1); +} + +/// Signer absent, deploy address empty, a creation that deploys one byte. The call is the top +/// frame. The creation's regular gas is `min(gasLimitOverride, remaining)`, which at this gas +/// limit is above the 98/100 cap of the execution cap. After the call's start charges, the two +/// leaves and the two records, the creation receives the reservoir share. Its state-growth budget +/// is the share of the call's whole 1,000, `floor(1,000 × 98 / 100)` = 980, the signer's rise +/// being counted on the call once the creation returned, and the empty deploy address is +1 +/// against it: 980 fresh slots take it to 981 and stop it at 980. +#[test] +fn test_a_keyless_creation_receives_the_reservoir_share_and_a_980_budget() { + let one_byte = BytecodeBuilder::default().return_with_data([0x00]).build(); + let deployment = Deployment::signed(SIGNED_STOP_GAS, one_byte); + let data = deployment.call_data(LARGE_OVERRIDE); + let reservoir_after_body = 50 * super::SLOT_STATE_GAS_M1; + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + reservoir_after_body; + let (outcome, probe) = execute_forward(keyless_db(), keyless_tx(data, gas), Forward::any()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(super::has_code(&outcome, deployment.address), "the creation succeeds"); + let (forwarded, reservoir) = probe.created.expect("the creation started"); + assert!( + forwarded > super::gas_cap(EXECUTION_CAP), + "regular gas {forwarded} is min(override, remaining), above the 98/100 cap {}", + super::gas_cap(EXECUTION_CAP) + ); + let charges = start_charges(); + assert!(reservoir_after_body > charges, "the reservoir covers the start charges"); + let remainder = reservoir_after_body - charges; + assert_eq!( + reservoir, + reservoir_share(remainder), + "creation reservoir {reservoir}; remainder after the start charges {remainder}; share {}", + reservoir_share(remainder) + ); + + if 980 * common::slot_state_gas() > SIGNED_SLOT_GAS { + note_price_guard("980 slots of state gas do not fit the keyless forward"); + return; + } + let filling = Deployment::signed(SIGNED_SLOT_GAS, store_n_slots(980)); + let data = filling.call_data(LARGE_OVERRIDE); + let state = 980 * common::slot_state_gas() + 2 * common::account_state_gas(); + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + state + 5_000_000; + let outcome = execute(keyless_db(), keyless_tx(data, gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + let stop = MegaLimitExceeded::abi_decode(&output).expect("the creation's revert is a stop"); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: frame_share(1_000) }); + assert_eq!(nonce_of(&outcome, filling.signer), 1, "the signer's bump stands"); + assert!(!super::has_code(&outcome, filling.address)); +} + +/// The clauses EIP-7702 already decides come first: one rise, one record and one indicator for two +/// acceptances of one new authority; nothing loaded or counted for a wrong chain id, a nonce of +/// 2^64 − 1 or an unrecoverable signature, and no warm access for the first; a zero delegation +/// target that creates its authority without an indicator; an authorization signed for the +/// sender's pre-transaction nonce, skipped; no rise for an existing authority; no indicator for one +/// that holds one at the start, a clear and a later non-zero authorization included; one indicator +/// for a clear and a later non-zero authorization of an authority that holds none; a database +/// error on a consulted authority, after an overflowing prefix too, gives no outcome. Then the +/// 999 / 1,000 / 1,001 boundaries of the state-growth stop. +/// +/// Where the list would cross both KV and state growth, the kind is 1. Whether a database error is +/// fatal is the node's database's to say, a block verdict this EVM call does not report; the +/// witness of every loaded authority is the block witness harness's, not this outcome's. +#[test] +fn test_authorization_list_boundaries() { + let stop_code = Bytes::from_static(&[0x00]); + let db = world(&[(CONTRACT, stop_code.clone())]); + let Some(gas) = gas_above(2) else { return }; + + // Two acceptances of one new authority: one rise, one record, one indicator. + let twice = [new_auth(1, 0), new_auth(1, 1)]; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &twice)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(1)), 2); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + INDICATOR_STATE_GAS); + } + + // Wrong chain id, nonce 2^64 − 1, unrecoverable signature: not loaded, not created. + for auth in [ + Auth { authority: Some(authority(2)), chain_id: 7, nonce: 0, delegate: CHILD }, + Auth { authority: Some(authority(3)), chain_id: 0, nonce: u64::MAX, delegate: CHILD }, + Auth { authority: None, chain_id: 0, nonce: 0, delegate: CHILD }, + ] { + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[auth])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } + } + assert_eq!( + nonce_of( + &execute( + db.clone(), + auth_tx( + gas, + U256::ZERO, + CONTRACT, + &[Auth { + authority: Some(authority(2)), + chain_id: 7, + nonce: 0, + delegate: CHILD + },] + ) + ), + authority(2) + ), + 0 + ); + + // A zero delegation target creates the account and charges no indicator. + let zero = + Auth { authority: Some(authority(4)), chain_id: 0, nonce: 0, delegate: Address::ZERO }; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[zero])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(4)), 1); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1); + } + + // Signed for the sender's pre-transaction nonce: skipped, and the sender adds no record. + let sender = Auth { authority: Some(CALLER), chain_id: 0, nonce: 0, delegate: CHILD }; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[sender])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } + + // An existing authority adds no state growth. The indicator is charged once. + let mut existing = db.clone(); + existing.set_account_balance(authority(5), U256::from(1)); + let outcome = execute(existing, auth_tx(gas, U256::ZERO, CONTRACT, &[new_auth(5, 0)])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, INDICATOR_STATE_GAS); + } + + // An authority that already holds an indicator is charged none, a clear and a later + // non-zero authorization included. + let mut delegated = crate::detention::with_delegation(db.clone(), authority(6), CHILD); + delegated.set_account_nonce(authority(6), 1); + delegated.set_account_balance(authority(6), U256::from(1)); + let outcome = execute(delegated.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[new_auth(6, 1)])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } + let clear_and_set = [ + Auth { authority: Some(authority(6)), chain_id: 0, nonce: 1, delegate: Address::ZERO }, + new_auth(6, 2), + ]; + let outcome = execute(delegated, auth_tx(gas, U256::ZERO, CONTRACT, &clear_and_set)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(6)), 3); + if pins_state() { + assert_eq!(outcome.gas.state, 0, "an indicator held at the start is never charged"); + } + + // An entry skipped for its chain id is not loaded, so it is not warmed. + let measuring = world(&[(CONTRACT, balance_cost(authority(2)))]); + let wrong_chain = + Auth { authority: Some(authority(2)), chain_id: 7, nonce: 0, delegate: CHILD }; + let outcome = execute(measuring, auth_tx(gas, U256::ZERO, CONTRACT, &[wrong_chain])); + assert!(access_cost(&outcome) > super::WARM_READ, "the skipped authority is cold"); + + // A clear of an authority that holds none, then the first non-zero designator: one indicator. + let clear_then = [ + Auth { authority: Some(authority(7)), chain_id: 0, nonce: 0, delegate: Address::ZERO }, + new_auth(7, 1), + ]; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &clear_then)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(7)), 2); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + INDICATOR_STATE_GAS); + } + + // A database error on a consulted authority gives the transaction no outcome. + let mut failing = ErrorInjectingDatabase::new(db.clone()); + failing.fail_on_account = Some(authority(8)); + let err = MegaEvm::new(context(failing)).execute_transaction(auth_tx( + gas, + U256::ZERO, + CONTRACT, + &[new_auth(8, 0)], + )); + assert!(err.is_err(), "a database error is not a limit stop: {err:?}"); + + // Both totals crossed: the kind is 1 and `limit` the KV transaction limit. + { + let limits = mega_evm::EvmTxRuntimeLimits::default() + .with_tx_kv_update_limit(3) + .with_tx_state_growth_limit(3); + let outcome = + super::execute_under(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &many(4)), limits); + assert_eq!(reverted_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 3 }); + assert_eq!(nonce_of(&outcome, authority(1)), 0); + } + + // The same, after a prefix of 1,001 new authorities that would already cross the limit. + if let Some(gas) = gas_above(1_002) { + let mut failing = ErrorInjectingDatabase::new(db); + failing.fail_on_account = Some(authority(1_002)); + let mut list = many(1_001); + list.push(new_auth(1_002, 0)); + let err = MegaEvm::new(context(failing)).execute_transaction(auth_tx( + gas, + U256::ZERO, + CONTRACT, + &list, + )); + assert!(err.is_err(), "an overflowing prefix does not hide the fault: {err:?}"); + } + + // 999 applied: the first frame's budget is 1. The second fresh slot stops it, `limit` 1. + let Some(gas) = gas_above(999) else { return }; + let db = world(&[(CONTRACT, store_n_slots(2))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(999))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: 1 }); + assert!(super::slot_value(&outcome, CONTRACT, 1).is_zero()); + + // 1,000 applied: the budget is 0. One slot stops it, `limit` 0. The authorities stay. + let Some(gas) = gas_above(1_000) else { return }; + let db = world(&[(CONTRACT, store_n_slots(1))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_000))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: 0 }); + assert_eq!(nonce_of(&outcome, authority(1)), 1); + + // 1,001 skip the list. Above the cap, so a success here is the missing stop. + let Some(gas) = gas_above(1_001) else { return }; + let db = world(&[(CONTRACT, stop_code)]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_001))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert_eq!(nonce_of(&outcome, authority(1)), 0); + assert_eq!(outcome.usage.write_records, 0); +} + +/// Signer nonce 0, signer absent. With the deploy address's +1, the init code's 980th fresh slot +/// crosses the creation's budget of 980, the share of the call's 1,000; the signer's rise is the +/// call's, counted once the creation returned. The call answers `ExecutionReverted` with that stop. +/// The deploy account and its record are taken back. The signer's bump stands, and its record with +/// it, while the account still differs. +#[test] +fn test_a_keyless_creation_from_nonce_0_stopped_in_its_initcode() { + if 980 * common::slot_state_gas() > SIGNED_SLOT_GAS { + note_price_guard("980 slots of state gas do not fit the keyless forward"); + return; + } + let deployment = Deployment::signed(SIGNED_SLOT_GAS, store_n_slots(980)); + let data = deployment.call_data(LARGE_OVERRIDE); + let data_len = data.len() as u64; + let state = 980 * common::slot_state_gas() + 2 * common::account_state_gas(); + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + state + 5_000_000; + let outcome = execute(keyless_db(), keyless_tx(data, gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + let stop = MegaLimitExceeded::abi_decode(&output).expect("the revert data is a stop"); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: frame_share(1_000) }); + assert_eq!(nonce_of(&outcome, deployment.signer), 1); + assert!(!super::has_code(&outcome, deployment.address)); + assert!(outcome.limit_exceeded.is_none(), "the call caught the creation's stop"); + // The signer's record stands, the deploy address's goes with the creation. + assert_eq!(outcome.usage.write_records, 1); + assert_eq!(outcome.usage.data_size, BODY_BYTES + data_len + super::WRITE_RECORD_SIZE); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "only the signer's leaf"); + } +} + +/// The same creation from signer nonce 1. The bump does not create the signer, so the creation's +/// budget is `floor(1,000 × 98 / 100)` = 980, and the deploy address's rise is inside it. 980 +/// fresh slots cross that budget. The bump is the last nonce change the deployment made and is +/// taken back, with its record and that record's history. +#[test] +fn test_a_keyless_creation_from_nonce_1_takes_the_bump_back() { + if 980 * common::slot_state_gas() > SIGNED_SLOT_GAS { + note_price_guard("980 slots of state gas do not fit the keyless forward"); + return; + } + let deployment = Deployment::signed(SIGNED_SLOT_GAS, store_n_slots(980)); + let mut db = keyless_db(); + db.set_account_nonce(deployment.signer, 1); + db.set_account_balance(deployment.signer, U256::from(1)); + let data = deployment.call_data(LARGE_OVERRIDE); + let data_len = data.len() as u64; + let state = 980 * common::slot_state_gas() + common::account_state_gas(); + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + state + 5_000_000; + let outcome = execute(db, keyless_tx(data, gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + let stop = MegaLimitExceeded::abi_decode(&output).expect("the revert data is a stop"); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: frame_share(TX_STATE_GROWTH_LIMIT) }); + assert_eq!(nonce_of(&outcome, deployment.signer), 1, "the bump is taken back"); + assert!(!super::has_code(&outcome, deployment.address)); + // The signer is again as the transaction loaded it: its record and the record's history go. + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.usage.data_size, BODY_BYTES + data_len); + assert_eq!(outcome.gas.history, common::body_history(data_len)); + if pins_state() { + assert_eq!(outcome.gas.state, 0, "the deploy address's leaf goes with the creation"); + } +} + +/// The constructor `DELEGATECALL`s a library that self-destructs the account, then returns one +/// byte of runtime. The creation's EVM result succeeds, and the call answers `EmptyCodeDeployed` +/// with the zero address. The destruction gives the deploy address's leaf and its record back to +/// the destroying frame, inside the creation, so what the creation spent from both pools net of +/// that give-back is below its regular gas, and `gasUsed` is the regular gas it spent. The code is +/// deposited after the mark: no state gas, and its data size and history stay charged. The +/// account is removed at the end of the transaction. +#[test] +fn test_a_keyless_constructor_that_self_destructs_answers_empty_code() { + if !pins_state() { + return; + } + let library = BytecodeBuilder::default().selfdestruct(EXISTING).build(); + let mut prefix = delegatecall(CHILD).append(revm::bytecode::opcode::POP).build().to_vec(); + prefix.extend_from_slice(&BytecodeBuilder::default().return_with_data([0x00]).build()); + let deployment = Deployment::signed(SIGNED_STOP_GAS, Bytes::from(prefix)); + let mut db = keyless_db(); + db.set_account_code(CHILD, library); + db.set_account_balance(EXISTING, U256::from(1)); + db.set_account_code(EXISTING, Bytes::from_static(&[0x00])); + let data = deployment.call_data(LARGE_OVERRIDE); + let data_len = data.len() as u64; + let gas = EXECUTION_CAP + + common::body_history(data.len() as u64) + + 2 * common::account_state_gas() + + 5_000_000; + let (outcome, probe) = execute_forward(db, keyless_tx(data, gas), Forward::any()); + let KeylessDeployError::EmptyCodeDeployed { gas_used } = keyless_failure(&outcome) else { + panic!("expected EmptyCodeDeployed: {:?}", outcome.result); + }; + let (forwarded, _) = probe.created.expect("the creation started"); + let left = probe.create_end_remaining.expect("the creation ended"); + assert_eq!(gas_used, forwarded - left, "gasUsed is the creation's regular gas"); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "only the signer's leaf stands"); + // The signer's record and the deposited byte stay; the deploy address's record goes. + assert_eq!( + outcome.gas.history, + (BODY_BYTES + data_len + super::WRITE_RECORD_SIZE + 1) * super::HISTORY_GAS_PER_BYTE + ); + assert!(super::is_destroyed(&outcome, deployment.address)); +} + +/// The list fits. The authority's state gas cannot be paid. Out of gas, and the authorization is +/// taken back. This is not the limit stop. +#[test] +fn test_an_authority_whose_state_gas_cannot_be_paid_is_taken_back() { + let Some(gas) = gas_under_one_authority() else { return }; + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &[new_auth(1, 0)])); + assert!(halted_out_of_gas(&outcome), "out of gas, not a limit stop: {:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none()); + assert_eq!(nonce_of(&outcome, authority(1)), 0, "the authorization is taken back"); + assert_eq!(outcome.usage.write_records, 0); +} + +/// The list does not fit, and the state gas it would have charged also cannot be paid. The list is +/// skipped and the first frame stops with the limit. The out-of-gas path is not taken. +#[test] +fn test_a_list_that_does_not_fit_is_not_the_out_of_gas_path() { + let Some(gas) = gas_below(1_001) else { return }; + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_001))); + assert!(!halted_out_of_gas(&outcome), "the out-of-gas path is not taken: {:?}", outcome.result); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } +} + +/// The list fits. One authority holds code that is not a delegation. The entry is skipped and its +/// nonce is not bumped; a later entry for it is compared with that unbumped nonce. The authority +/// was loaded before the code check, so it is warm. +#[test] +fn test_an_authority_with_non_delegation_code_is_skipped() { + let Some(gas) = gas_above(1) else { return }; + let mut db = world(&[(CONTRACT, balance_cost(authority(1)))]); + db.set_account_code(authority(1), Bytes::from_static(&[0x00])); + db.set_account_balance(authority(1), U256::from(1)); + let auths = [new_auth(1, 0), new_auth(1, 0)]; + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &auths)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(access_cost(&outcome), super::WARM_READ, "the authority is warm"); + assert_eq!(nonce_of(&outcome, authority(1)), 0, "the simulated nonce is not bumped"); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } +} + +/// Two entries for one new authority, both signed for nonce 0. The first is accepted, the +/// simulated nonce becomes 1, and the authority is created once, with one record and one +/// indicator. The second does not match that nonce and is skipped. The authority is warm. +#[test] +fn test_two_entries_for_one_new_authority_accept_the_first() { + let Some(gas) = gas_above(1) else { return }; + let db = world(&[(CONTRACT, balance_cost(authority(1)))]); + let auths = [new_auth(1, 0), new_auth(1, 0)]; + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &auths)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(access_cost(&outcome), super::WARM_READ, "the authority is warm"); + assert_eq!(nonce_of(&outcome, authority(1)), 1); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + INDICATOR_STATE_GAS); + } +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/limits.rs b/crates/mega-evm/tests/satin/limit_matrix/limits.rs new file mode 100644 index 000000000..d9d4a5a3f --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/limits.rs @@ -0,0 +1,418 @@ +//! Frame budgets and the transaction limits. +//! +//! Expected stops use the page's kind and `limit`. Gas room follows the schedule at the prices +//! in effect, so a measurement build can still reach the stop. + +use alloy_primitives::{keccak256, Bytes, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, ORACLE_CONTRACT_ADDRESS}, + test_utils::BytecodeBuilder, + EvmTxRuntimeLimits, MegaLimitExceeded, +}; +use revm::bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0}; + +use super::{ + balance_of, call_tx, delegatecall, execute, execute_under, forward_to, frame_share, + gas_for_slots, keep_returndata, nonce_of, return_kept, returned_stop, returned_stops, + reverted_stop, slot_value, slots_gas, store_n_prefix, store_n_prefix_at, store_n_slots, world, + BENEFICIARY, BODY_BYTES, CHILD, CONTRACT, GRAND, NEXT, TRANSFER_LOG_SIZE, TX_DATA_LIMIT, + TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, WRITE_RECORD_SIZE, +}; + +fn join(prefix: Vec, rest: BytecodeBuilder) -> Bytes { + let mut code = prefix; + code.extend_from_slice(&rest.build()); + Bytes::from(code) +} + +/// The transaction's own frame has a state-growth budget of 1,000. The 1,001st fresh slot stops +/// that frame, kind 3, `limit` 1,000. The slot is not kept. The receipt fails and the transaction +/// is included. +#[test] +fn test_the_1001st_fresh_slot_stops_the_transaction() { + let Some(gas) = slots_gas(1_001) else { return }; + let db = world(&[(CONTRACT, store_n_slots(1_001))]); + let outcome = execute(db, call_tx(gas)); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert!(outcome.limit_exceeded.is_some(), "the transaction's own frame stopped"); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CONTRACT, 1_001), U256::ZERO); +} + +/// The caller has kept 20 of a 1,000 budget. The child budget is `floor(980 × 98 / 100)` = 960. +/// Those 960 slots succeed. The caller net becomes 980 and its remaining becomes 20, so a later +/// child receives `floor(20 × 98 / 100)` = 19. +#[test] +fn test_a_child_budget_of_960_then_a_later_child_of_19() { + let Some(gas) = slots_gas(1_000) else { return }; + let parent = join( + store_n_prefix(20, 1, false), + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .call(NEXT, U256::ZERO) + .return_returndata(), + ); + let db = world(&[(CONTRACT, parent), (CHILD, store_n_slots(960)), (NEXT, store_n_slots(20))]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the caller caught the later child's stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 19 }); + assert_eq!(slot_value(&outcome, CONTRACT, 20), U256::from(1)); + assert_eq!(slot_value(&outcome, CHILD, 960), U256::from(1)); + assert_eq!( + slot_value(&outcome, NEXT, 1), + U256::ZERO, + "the later child's 20 slots are discarded" + ); +} + +/// The same caller. The child's 961st slot stops the child, kind 3, `limit` 960. The child's net +/// is discarded, so the caller net stays 20 and its remaining stays 980: a later child receives +/// `floor(980 × 98 / 100)` = 960 again, and its own 961st slot stops it at 960. +#[test] +fn test_a_childs_961st_slot_stops_at_960() { + let Some(gas) = slots_gas(2_000) else { return }; + let rest = BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP); + let rest = keep_returndata(rest, 0x100).call(NEXT, U256::ZERO).append(POP); + let parent = join(store_n_prefix(20, 1, false), return_kept(keep_returndata(rest, 0x180))); + let db = world(&[(CONTRACT, parent), (CHILD, store_n_slots(961)), (NEXT, store_n_slots(961))]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (child, next) = returned_stops(&outcome); + assert_eq!(child, MegaLimitExceeded { kind: 3, limit: 960 }); + assert_eq!(next, MegaLimitExceeded { kind: 3, limit: 960 }, "the caller still had 980 left"); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO, "the child's net is discarded"); + assert_eq!(slot_value(&outcome, NEXT, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CONTRACT, 20), U256::from(1)); +} + +/// Transaction KV limit 10, caller has used 2. The child budget is `floor(8 × 98 / 100)` = 7. +/// The 8th new record stops the child, kind 1, `limit` 7. On that stop the caller still has 8 +/// left, and its own 8 further records fit. At the protocol value 500,000 this shape hits data +/// size first ([`test_kv_weighs_more_than_the_data_size_cap`]). +#[test] +fn test_a_child_kv_budget_of_7_stops_the_eighth_record() { + assert_eq!(frame_share(8), 7); + let Some(gas) = slots_gas(20) else { return }; + let mut parent = store_n_prefix(2, 1, false); + parent + .extend_from_slice(&BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP).build()); + // Slots 10 down to 1: slots 1 and 2 are already set, so this adds 8 records. + parent.extend_from_slice(&store_n_prefix_at(parent.len(), 10, 1, false)); + // A store leaves the return data alone: the parent returns the child's stop. + parent.extend_from_slice(&BytecodeBuilder::default().return_returndata().build()); + let db = world(&[(CONTRACT, Bytes::from(parent)), (CHILD, store_n_slots(8))]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 7 }); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CONTRACT, 10), U256::from(1), "the caller had 8 left"); + assert_eq!(outcome.usage.write_records, 10); +} + +/// Not a protocol-gas execution. 500,000 records weigh 20,000,000 bytes, above `TX_DATA_LIMIT` +/// 13,107,200. After a 310-byte body the top frame's data-size budget is 13,106,890. 327,672 +/// records fit. A 327,673rd record would cross that frame budget, kind 0, `limit` 13,106,890. +/// The KV check itself is pinned under reduced KV limits +/// ([`test_a_child_kv_budget_of_7_stops_the_eighth_record`], +/// [`test_the_transactions_own_frame_stops_at_a_reduced_kv_limit`]). +#[test] +fn test_kv_weighs_more_than_the_data_size_cap() { + let weight = TX_KV_UPDATE_LIMIT * WRITE_RECORD_SIZE; + assert_eq!(weight, 20_000_000); + assert!(weight > TX_DATA_LIMIT); + let budget = TX_DATA_LIMIT - BODY_BYTES; + assert_eq!(budget, 13_106_890); + assert_eq!(327_672 * WRITE_RECORD_SIZE, 13_106_880); + assert!(327_672 * WRITE_RECORD_SIZE <= budget); + assert_eq!(327_673 * WRITE_RECORD_SIZE, 13_106_920); + assert!(327_673 * WRITE_RECORD_SIZE > budget); + let _ = MegaLimitExceeded { kind: 0, limit: budget }; +} + +/// A reduced KV transaction limit of 10, with nothing counted before the frame, so the +/// transaction's own frame has a KV budget of 10. Its 11th record stops it, kind 1, `limit` 10. +/// The data size does not bind. +#[test] +fn test_the_transactions_own_frame_stops_at_a_reduced_kv_limit() { + let Some(gas) = slots_gas(11) else { return }; + let db = world(&[(CONTRACT, store_n_slots(11))]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let outcome = execute_under(db, call_tx(gas), limits); + assert_eq!(reverted_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 10 }); + assert!(outcome.limit_exceeded.is_some()); + assert_eq!(slot_value(&outcome, CONTRACT, 11), U256::ZERO); +} + +/// One fresh `SSTORE` whose record crosses the data-size frame budget and the state-growth frame +/// budget names data size, kind 0, and `limit` is the data-size frame budget. +/// +/// A transaction data-size limit of the body plus 40,000 gives the top frame 40,000 bytes and a +/// child `floor(40,000 × 98 / 100)` = 39,200, 980 records. The child's state-growth budget is 980 +/// too. Its 981st slot crosses both, and not the transaction limit. When the top frame itself +/// makes the 1,001st record, that record crosses the data-size frame budget, 40,000, the +/// data-size transaction limit and the state-growth budget, 1,000, and the stop still names the +/// frame budget, 40,000. +#[test] +fn test_a_record_that_crosses_data_size_and_state_growth_names_data_size() { + let Some(gas) = slots_gas(1_001) else { return }; + let budget = frame_share(40_000); + assert_eq!(budget, 39_200); + assert!(981 * WRITE_RECORD_SIZE > budget); + assert!(980 * WRITE_RECORD_SIZE <= budget); + assert_eq!(frame_share(TX_STATE_GROWTH_LIMIT), 980); + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(BODY_BYTES + 40_000); + let db = world(&[(CONTRACT, forward_to(CHILD)), (CHILD, store_n_slots(981))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the caller caught the child's stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: budget }); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + + let db = world(&[(CONTRACT, store_n_slots(1_001))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert_eq!( + reverted_stop(&outcome), + MegaLimitExceeded { kind: 0, limit: 40_000 }, + "the frame budget, not the transaction limit {}", + BODY_BYTES + 40_000 + ); +} + +/// State growth at depth 2 and 3, top remaining 1,000. Child 980, grandchild 960, the next frame +/// `floor(960 × 98 / 100)` = 940. The 941st slot there stops that frame, kind 3, `limit` 940. +#[test] +fn test_state_growth_at_depth_2_and_3_stops_at_940() { + let Some(gas) = slots_gas(941) else { return }; + assert_eq!(frame_share(1_000), 980); + assert_eq!(frame_share(980), 960); + assert_eq!(frame_share(960), 940); + let db = world(&[ + (CONTRACT, forward_to(CHILD)), + (CHILD, forward_to(GRAND)), + (GRAND, forward_to(NEXT)), + (NEXT, store_n_slots(941)), + ]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 940 }); + assert_eq!(slot_value(&outcome, NEXT, 1), U256::ZERO); +} + +/// Parent budget 1,000, net 100. The child, a `DELEGATECALL` in the parent's storage, clears +/// those 100: its net is −100 and its remaining stays 882, so the frame it starts receives 864, +/// and that frame's 865th slot stops it at 864. When the child succeeds, the parent's net is 0 +/// and its remaining is 1,000 again, so a later child receives 980. When the child reverts, the +/// parent's net stays 100 and its remaining 900, so a later child receives 882. +#[test] +fn test_a_cleared_net_does_not_raise_the_childs_remaining() { + let Some(gas) = slots_gas(2_000) else { return }; + assert_eq!(frame_share(900), 882); + assert_eq!(frame_share(882), 864); + let parent = { + let rest = keep_returndata(delegatecall(CHILD).append(POP), 0x100); + let rest = keep_returndata(rest.call(NEXT, U256::ZERO).append(POP), 0x180); + join(store_n_prefix(100, 1, false), return_kept(rest)) + }; + for (kept, next) in [(true, 980), (false, 882)] { + let tail = BytecodeBuilder::default().call(GRAND, U256::ZERO); + let tail = if kept { tail.return_returndata() } else { tail.revert_with_returndata() }; + let child = join(store_n_prefix(100, 0, false), tail); + let db = world(&[ + (CONTRACT, parent.clone()), + (CHILD, child), + (GRAND, store_n_slots(865)), + (NEXT, store_n_slots(TX_STATE_GROWTH_LIMIT as u16)), + ]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (grand, later) = returned_stops(&outcome); + assert_eq!(grand, MegaLimitExceeded { kind: 3, limit: 864 }, "kept {kept}"); + assert_eq!(later, MegaLimitExceeded { kind: 3, limit: next }, "kept {kept}"); + assert_eq!(slot_value(&outcome, GRAND, 1), U256::ZERO); + let slot = if kept { U256::ZERO } else { U256::from(1) }; + assert_eq!(slot_value(&outcome, CONTRACT, 1), slot, "kept {kept}"); + } +} + +/// Plants `sendHint`'s selector at memory 0 and calls the Oracle with `len` bytes of calldata. +fn hint_call(len: u32) -> BytecodeBuilder { + BytecodeBuilder::default() + .mstore(0, IOracle::sendHintCall::SELECTOR) + .append_many([ + PUSH0, // retSize + PUSH0, // retOffset + ]) + .push_number(len) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL]) +} + +/// Body 310 plus twelve admitted hints of 1,048,576 bytes is 12,583,222. A child `LOG0` of +/// 524,288 data bytes is 524,320 bytes and crosses the transaction limit. The child's frame +/// budget is not crossed. Kind 0, `limit` 13,107,200. The hints stay counted. The log does not. +#[test] +fn test_hints_then_a_child_log_names_the_transaction_data_limit() { + const HINT: u32 = 1_048_576; + const LOG_DATA: u64 = 524_288; + const BEFORE: u64 = BODY_BYTES + 12 * HINT as u64; + assert_eq!(BEFORE, 12_583_222); + assert_eq!(32 + LOG_DATA, 524_320); + const { assert!(BEFORE + 32 + LOG_DATA > TX_DATA_LIMIT) }; + let mut code = Vec::new(); + for _ in 0..12 { + code.extend_from_slice(&hint_call(HINT).build()); + code.push(POP); + } + code.extend_from_slice( + &BytecodeBuilder::default().call(CHILD, U256::ZERO).return_returndata().build(), + ); + let child = BytecodeBuilder::default() + .push_number(LOG_DATA as u32) + .append_many([PUSH0, LOG0]) + .stop() + .build(); + let db = world(&[ + (CONTRACT, Bytes::from(code)), + (CHILD, child), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(40_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the caller caught the log's stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: TX_DATA_LIMIT }); + assert_eq!(outcome.usage.data_size, BEFORE); +} + +/// The same log in the transaction's own frame stops that frame, kind 0, `limit` 13,107,200. +/// Failed receipt, included. The admitted hint bytes stay counted. +#[test] +fn test_hints_then_a_top_frame_log_stops_the_transaction() { + const HINT: u32 = 1_048_576; + const LOG_DATA: u64 = 524_288; + const BEFORE: u64 = BODY_BYTES + 12 * HINT as u64; + let mut code = Vec::new(); + for _ in 0..12 { + code.extend_from_slice(&hint_call(HINT).build()); + code.push(POP); + } + code.extend_from_slice( + &BytecodeBuilder::default().push_number(LOG_DATA as u32).append_many([PUSH0, LOG0]).build(), + ); + let db = world(&[ + (CONTRACT, Bytes::from(code)), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(40_000_000)); + assert_eq!(reverted_stop(&outcome), MegaLimitExceeded { kind: 0, limit: TX_DATA_LIMIT }); + assert!(outcome.limit_exceeded.is_some(), "the transaction's own frame stopped"); + assert_eq!(outcome.usage.data_size, BEFORE); +} + +/// One admitted hint whose calldata is exactly 100 bytes: the selector and 96 zero bytes. +fn hint_100() -> BytecodeBuilder { + hint_call(100) +} + +/// Body 310, one admitted hint of 100 bytes, a top-frame record of 40, and a successful child +/// whose net is −40. The transaction's net is 410. The same child reverting keeps the 40, so the +/// net is 450. +#[test] +fn test_a_successful_childs_negative_net_leaves_the_transaction_at_410() { + let success_child = join(store_n_prefix(1, 0, false), BytecodeBuilder::default().stop()); + let db = world(&[ + (CONTRACT, hint_and_store()), + (CHILD, success_child), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(5_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 100); + + let failing = join(store_n_prefix(1, 0, false), BytecodeBuilder::default().revert()); + let db = world(&[ + (CONTRACT, hint_and_store()), + (CHILD, failing), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(5_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 100 + WRITE_RECORD_SIZE); +} + +fn hint_and_store() -> Bytes { + let mut code = hint_100().append(POP).sstore(U256::from(1), U256::from(1)).build().to_vec(); + code.extend_from_slice(&delegatecall(CHILD).stop().build()); + Bytes::from(code) +} + +/// A transaction data-size limit of the body plus 81 gives the top frame 81 bytes. The parent +/// writes one 40-byte record, so 41 remain and the child receives 40. The child returns that record +/// and its remaining stays 40. The frame it starts receives `floor(40 × 98 / 100)` = 39, and one +/// 40-byte record there stops it, kind 0, `limit` 39. +#[test] +fn test_a_negative_data_size_net_does_not_raise_what_a_frame_forwards() { + assert_eq!(frame_share(41), 40); + assert_eq!(frame_share(40), 39); + let child = join( + store_n_prefix(1, 0, false), + BytecodeBuilder::default().call(GRAND, U256::ZERO).return_returndata(), + ); + let parent = join( + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).build().to_vec(), + delegatecall(CHILD).return_returndata(), + ); + let db = world(&[ + (CONTRACT, parent), + (CHILD, child), + (GRAND, BytecodeBuilder::default().sstore(U256::from(2), U256::from(1)).stop().build()), + ]); + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(BODY_BYTES + 81); + let outcome = execute_under(db, call_tx(5_000_000), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 39 }); +} + +/// A pre-funded address, balance, nonce 0, no code, is created onto and destroyed. The leaf was +/// present. No refill and no fall, and the net stays 0. 1,000 further slot rises fit. The 1,001st +/// stops the frame, kind 3, `limit` 1,000. +#[test] +fn test_a_prefunded_creation_keeps_a_zero_net_until_the_1001st_slot() { + let init = BytecodeBuilder::default().selfdestruct(BENEFICIARY).build(); + let created = CONTRACT.create2(B256::ZERO, keccak256(init.as_ref())); + let only = + BytecodeBuilder::default().create2(U256::ZERO, init.clone(), U256::ZERO).stop().build(); + let mut db = world(&[(CONTRACT, only), (BENEFICIARY, Bytes::from_static(&[0x00]))]); + db = db.account_balance(created, U256::from(1)); + let Some(gas) = gas_for_slots(1) else { return }; + let settled = execute(db, call_tx(gas)); + assert!(settled.result.is_success(), "{:?}", settled.result); + assert_eq!(settled.gas.state, 0, "a present leaf is not charged and not refilled"); + assert!(nonce_of(&settled, CONTRACT) >= 1, "the creator nonce bump stands"); + // The creator's nonce, the created account's nonce, and the beneficiary's balance: the + // created account's record stands. One transfer log for the balance the destruction moved. + assert_eq!(settled.usage.write_records, 3, "the nonce bump's record stands"); + assert_eq!(settled.usage.data_size, BODY_BYTES + 3 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); + assert_eq!(balance_of(&settled, created), U256::ZERO); + + // The loop's jumps are absolute. It has to start at its own pc, after the `CREATE2`. + let prefix = + BytecodeBuilder::default().create2(U256::ZERO, init, U256::ZERO).append(POP).build(); + let mut code = prefix.to_vec(); + code.extend_from_slice(&store_n_prefix_at(prefix.len(), 1_001, 1, true)); + let mut db = + world(&[(CONTRACT, Bytes::from(code)), (BENEFICIARY, Bytes::from_static(&[0x00]))]); + db = db.account_balance(created, U256::from(1)); + let Some(gas) = slots_gas(1_001) else { return }; + let outcome = execute(db, call_tx(gas)); + assert_eq!( + reverted_stop(&outcome), + MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT } + ); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/mod.rs b/crates/mega-evm/tests/satin/limit_matrix/mod.rs new file mode 100644 index 000000000..bdc2c1a34 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/mod.rs @@ -0,0 +1,587 @@ +//! The resource-limit matrix of the specification: one test per case of its rules, written from +//! `docs/spec/upgrades/satin.md` alone, independently of the engine — the KV-update and +//! state-growth limits, the reservoir and pool shares, the stop, the block budgets, deposits, +//! keyless deployment and the same-transaction destruction table. A test's doc states the rule it +//! pins. +//! +//! The numbers below are the page's. A test does not import an engine constant for a figure the +//! page states. Gas room around a scenario may follow the schedule at the prices in effect, so +//! the same test still runs when a measurement build changes a byte price. + +pub(super) mod block; +pub(super) mod deposits; +pub(super) mod destruction; +pub(super) mod forwarding; +pub(super) mod keyless; +pub(super) mod limits; +pub(super) mod records; +pub(super) mod stop; + +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + test_utils::{note_price_guard, op_transaction, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransaction, + MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{ + CALL, CREATE, CREATE2, DELEGATECALL, GAS, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, + }, + context::{ + result::{ExecutionResult, HaltReason}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, + primitives::KECCAK_EMPTY, + Database, Inspector, +}; + +use crate::common::{self, context}; + +/// `TX_DATA_LIMIT` and `BLOCK_DATA_LIMIT` on the page. +pub(super) const TX_DATA_LIMIT: u64 = 13_107_200; +/// `TX_KV_UPDATE_LIMIT` and `BLOCK_KV_UPDATE_LIMIT` on the page. +pub(super) const TX_KV_UPDATE_LIMIT: u64 = 500_000; +/// `TX_STATE_GROWTH_LIMIT` and `BLOCK_STATE_GROWTH_LIMIT` on the page. +pub(super) const TX_STATE_GROWTH_LIMIT: u64 = 1_000; +/// History gas per byte. SALT does not scale it. +pub(super) const HISTORY_GAS_PER_BYTE: u64 = 88; +/// One write record, in bytes. Also its history bytes. +pub(super) const WRITE_RECORD_SIZE: u64 = 40; +/// Data size of one EIP-7708 transfer log, which pays no history. +pub(super) const TRANSFER_LOG_SIZE: u64 = 160; +/// History gas of one write record at the spec's byte price: `40 × 88`. +pub(super) const RECORD_HISTORY: u64 = 3_520; +/// The body's fixed bytes: the envelope and five records. +pub(super) const BODY_BYTES: u64 = 310; +/// History gas of an empty-calldata body at the spec's byte price: `310 × 88`. +pub(super) const BODY_HISTORY: u64 = 27_280; +/// State gas of one fresh slot at the minimum bucket: `64 × 1,530`. +pub(super) const SLOT_STATE_GAS_M1: u64 = 97_920; +/// State gas of one new account leaf at the minimum bucket: `120 × 1,530`. +pub(super) const ACCOUNT_LEAF_STATE_GAS_M1: u64 = 183_600; +/// State gas of one deployed code byte at the minimum bucket. +pub(super) const CODE_DEPOSIT_STATE_PER_BYTE: u64 = 1_530; +/// State gas of one delegation indicator, charged at most once per authority. +pub(super) const INDICATOR_STATE_GAS: u64 = 35_190; +/// Regular gas of a value-transferring `CALL`. The 2,300 stipend is already inside it. +pub(super) const VALUE_TRANSFER_GAS: u64 = 11_300; +/// Stipend added to a value-transferring `CALL` or `CALLCODE` after the cap. +pub(super) const CALL_STIPEND: u64 = 2_300; +/// Warm account access, charged as the `CALL` opcode's static gas. +pub(super) const WARM_READ: u64 = 100; +/// History allowance of a value `CALL` below the transaction's own frame, in bytes. +pub(super) const HISTORY_ALLOWANCE_BYTES: u64 = 160; +/// Gas of that allowance: `160 × 88`. It is not gas and not reservoir. +pub(super) const HISTORY_ALLOWANCE_GAS: u64 = 14_080; +/// The execution cap. Gas above it is the reservoir. Not a transaction-size cap. +pub(super) const EXECUTION_CAP: u64 = 200_000_000; +/// Percent of reservoir a caller keeps. The division truncates toward zero. +pub(super) const RESERVOIR_KEPT_PERCENT: u64 = 2; + +/// The caller every transaction is sent from. +pub(super) const CALLER: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1000"); +/// The contract a transaction calls. +pub(super) const CONTRACT: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1001"); +/// A callee. +pub(super) const CHILD: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1002"); +/// A callee of [`CHILD`]. +pub(super) const GRAND: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1003"); +/// A frame started after another child returned. +pub(super) const NEXT: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1004"); +/// Where a `SELFDESTRUCT` sends the balance. +pub(super) const BENEFICIARY: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1005"); +/// An account that already exists and holds no code worth running. +pub(super) const EXISTING: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1006"); +/// The state-growth probe: a callee that fills fresh slots until its frame budget stops it. +pub(super) const PROBE: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab100f"); + +/// Reservoir a child receives: `remaining − remaining × 2 / 100`. +pub(super) const fn reservoir_share(remaining: u64) -> u64 { + remaining - remaining * RESERVOIR_KEPT_PERCENT / 100 +} + +/// Frame budget a child receives: `remaining × 98 / 100`, rounded down. +pub(super) const fn frame_share(remaining: u64) -> u64 { + remaining * 98 / 100 +} + +/// Regular-gas cap: the same subtraction as [`reservoir_share`]. +pub(super) const fn gas_cap(remaining: u64) -> u64 { + reservoir_share(remaining) +} + +/// Bytecode that stores `1` into slots `1..=n` and stops. +/// +/// The loop is `PUSH2 n`, a `JUMPDEST` at pc 3, and a back-edge to it. The exit `JUMPDEST` is pc +/// 20 (`PUSH1 0x14`). Slot 0 is left untouched. +pub(super) fn store_n_slots(n: u16) -> Bytes { + Bytes::from(store_n_prefix(n, 1, true)) +} + +/// The loop of [`store_n_slots`] storing `value`, without the trailing `STOP` when `stop` is false, +/// so a caller can append another opcode. +pub(super) fn store_n_prefix(n: u16, value: u8, stop: bool) -> Vec { + let mut code = vec![ + 0x61, + (n >> 8) as u8, + (n & 0xff) as u8, + 0x5b, // JUMPDEST at pc 3 + 0x80, // DUP1 + 0x15, // ISZERO + 0x60, + 0x14, // PUSH1 20, the exit JUMPDEST + 0x57, // JUMPI + 0x60, + value, + 0x81, // DUP2 + 0x55, // SSTORE + 0x60, + 0x01, // PUSH1 1 + 0x90, // SWAP1 + 0x03, // SUB + 0x60, + 0x03, // PUSH1 3 + 0x56, // JUMP + 0x5b, // JUMPDEST at pc 20 + 0x50, // POP + ]; + if stop { + code.push(0x00); + } + code +} + +/// [`store_n_prefix`] placed at `origin`, so a loop appended after other code jumps to its own +/// `JUMPDEST`s. The jump targets are `PUSH2`. `PUSH2` costs the same static gas as the `PUSH1` +/// the origin-zero loop uses. +pub(super) fn store_n_prefix_at(origin: usize, n: u16, value: u8, stop: bool) -> Vec { + let entry = u16::try_from(origin + 3).expect("the loop's entry fits a PUSH2"); + let exit = u16::try_from(origin + 22).expect("the loop's exit fits a PUSH2"); + let mut code = vec![ + 0x61, + (n >> 8) as u8, + n as u8, + 0x5b, // JUMPDEST at origin + 3 + 0x80, // DUP1 + 0x15, // ISZERO + 0x61, + (exit >> 8) as u8, + exit as u8, + 0x57, // JUMPI + 0x60, + value, + 0x81, // DUP2 + 0x55, // SSTORE + 0x60, + 0x01, // PUSH1 1 + 0x90, // SWAP1 + 0x03, // SUB + 0x61, + (entry >> 8) as u8, + entry as u8, + 0x56, // JUMP + 0x5b, // JUMPDEST at origin + 22 + 0x50, // POP + ]; + if stop { + code.push(0x00); + } + code +} + +/// Code that ends a scenario by calling [`PROBE`] with all its gas and returning what the probe +/// returned. +/// +/// The probe tries to fill [`TX_STATE_GROWTH_LIMIT`] fresh slots of its own, more than any child +/// budget, so it always stops, kind 3, at its budget: `floor((1,000 − g) × 98 / 100)` when the +/// scenario before it kept a state-growth net of `g`. For `g` up to 49 the budget pins `g`. +pub(super) fn then_probe(scenario: impl AsRef<[u8]>) -> Bytes { + let mut code = scenario.as_ref().to_vec(); + code.extend_from_slice( + &BytecodeBuilder::default().call(PROBE, U256::ZERO).return_returndata().build(), + ); + Bytes::from(code) +} + +/// The probe's code: [`TX_STATE_GROWTH_LIMIT`] fresh slots. +pub(super) fn probe_code() -> Bytes { + store_n_slots(TX_STATE_GROWTH_LIMIT as u16) +} + +/// Asserts that the scenario before [`then_probe`] kept a state-growth net of `kept`: the probe +/// stopped at `floor((1,000 − kept) × 98 / 100)`. +pub(super) fn assert_growth(outcome: &MegaTransactionOutcome, kept: u64) { + assert!(kept < 50, "the probe pins a net below 50"); + assert_eq!( + returned_stop(outcome), + MegaLimitExceeded { kind: 3, limit: frame_share(TX_STATE_GROWTH_LIMIT - kept) }, + "the probe's budget is the share of what a kept net of {kept} leaves" + ); +} + +/// Runs `scenario` twice: ending in `STOP`, for its figures, and ending in [`then_probe`], for +/// the state-growth net it kept. `db` builds the database around the code [`CONTRACT`] runs. +/// Under the state-growth limit the probe is stopped and keeps nothing; an engine without one +/// keeps its slots and their charges, so the scenario's figures are read off the plain run. +pub(super) fn plain_and_probed( + scenario: &[u8], + db: impl Fn(Bytes) -> MemoryDatabase, +) -> Option<(MegaTransactionOutcome, MegaTransactionOutcome)> { + let gas = probe_gas(10)?; + let mut plain = scenario.to_vec(); + plain.push(0x00); + let outcome = execute(db(Bytes::from(plain)), call_tx(gas)); + let probed = execute(db(then_probe(scenario)), call_tx(gas)); + assert!(probed.result.is_success(), "the probed run: {:?}", probed.result); + Some((outcome, probed)) +} + +/// Gas for a scenario of `slots` fresh slots followed by the probe. +pub(super) fn probe_gas(slots: u64) -> Option { + slots_gas(slots + TX_STATE_GROWTH_LIMIT) +} + +/// `CALL` of `target` carrying `value`, forwarding exactly `gas`, with no calldata. Leaves the +/// success flag. +pub(super) fn call_with_gas( + code: BytecodeBuilder, + target: Address, + value: U256, + gas: u32, +) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_u256(value) + .push_address(target) + .push_number(gas) + .append(CALL) +} + +/// Copies the last call's return data to memory at `offset`. +pub(super) fn keep_returndata(code: BytecodeBuilder, offset: u16) -> BytecodeBuilder { + code.append_many([RETURNDATASIZE, PUSH0]).push_number(offset).append(RETURNDATACOPY) +} + +/// `RETURN` of the 256 bytes from `0x100`, where [`keep_returndata`] kept two return datas, at +/// `0x100` and `0x180`. +pub(super) fn return_kept(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(0x100_u16).push_number(0x100_u16).append(RETURN) +} + +/// The two stops a successful transaction returned through [`return_kept`]. +pub(super) fn returned_stops( + outcome: &MegaTransactionOutcome, +) -> (MegaLimitExceeded, MegaLimitExceeded) { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("expected a success that returns two stops, got {:?}", outcome.result); + }; + let data = output.data(); + let decode = |at: usize| { + MegaLimitExceeded::abi_decode(&data[at..at + 68]).unwrap_or_else(|err| { + panic!("return data at {at} is not MegaLimitExceeded ({err}); output {data:?}"); + }) + }; + (decode(0), decode(0x80)) +} + +/// `CALL` of `target` with all remaining gas, then `RETURN` of its return data. +pub(super) fn forward_to(target: Address) -> Bytes { + BytecodeBuilder::default().call(target, U256::ZERO).return_returndata().build() +} + +/// `DELEGATECALL` of `target` with all remaining gas. Leaves the success flag. +pub(super) fn delegatecall(target: Address) -> BytecodeBuilder { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(target) + .append_many([GAS, DELEGATECALL]) +} + +/// A database with [`CALLER`] funded and [`PROBE`] installed. Each `(address, code)` exists with +/// balance 1, so a call to it is not an account-creation. +pub(super) fn world(code: &[(Address, Bytes)]) -> MemoryDatabase { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u128.pow(24))) + .account_code(PROBE, probe_code()) + .account_balance(PROBE, U256::from(1)); + for (address, bytecode) in code { + db = db.account_code(*address, bytecode.clone()).account_balance(*address, U256::from(1)); + } + db +} + +/// A call from [`CALLER`] to [`CONTRACT`]. +pub(super) fn call_tx(gas_limit: u64) -> MegaTransaction { + common::call(CALLER, CONTRACT, U256::ZERO, gas_limit) +} + +/// A creation from [`CALLER`]. +pub(super) fn create_tx(init_code: Bytes, gas_limit: u64) -> MegaTransaction { + common::create(CALLER, init_code, gas_limit) +} + +/// An EIP-2930 call that warms `warm` from the start, so the measured `CALL` pays no cold access. +pub(super) fn warm_call(gas_limit: u64, warm: &[Address]) -> MegaTransaction { + let access_list = AccessList::from( + warm.iter() + .map(|address| AccessListItem { address: *address, storage_keys: vec![] }) + .collect::>(), + ); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit, + access_list, + ..Default::default() + })) +} + +/// Gas that covers `slots` fresh slots above the execution cap at the prices in effect: the +/// slots' state gas, the history of the body and one record each, and regular gas for the loop. +/// +/// `None` when that sum does not fit a `u64`. The caller leaves a price-guard note and returns. +pub(super) fn gas_for_slots(slots: u64) -> Option { + let state = slots.checked_mul(common::slot_state_gas())?; + let bytes = BODY_BYTES.checked_add(slots.checked_mul(WRITE_RECORD_SIZE)?)?; + let history = common::history(bytes); + let regular = slots.checked_mul(40_000)?.checked_add(8_000_000)?; + state.checked_add(history)?.checked_add(regular)?.checked_add(EXECUTION_CAP) +} + +/// [`gas_for_slots`], or a note and `None` when the scenario does not fit. +pub(super) fn slots_gas(slots: u64) -> Option { + match gas_for_slots(slots) { + Some(gas) => Some(gas), + None => { + note_price_guard("the fresh-slot scenario does not fit one gas limit"); + None + } + } +} + +/// Whether this process prices bytes at the spec's constants. +/// +/// A test that pins a spec gas figure returns early otherwise. +/// [`common::runs_at_measurement_prices`] leaves the grid's note. +pub(super) fn at_spec_prices() -> bool { + !common::runs_at_measurement_prices() +} + +/// Runs `tx` and returns its outcome. +pub(super) fn execute(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + common::execute(db, tx) +} + +/// Runs `tx` under `limits`. +pub(super) fn execute_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + common::execute_under(db, tx, limits) +} + +/// The stop a reverted transaction carries. +pub(super) fn reverted_stop(outcome: &MegaTransactionOutcome) -> MegaLimitExceeded { + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("expected a revert, got {:?}", outcome.result); + }; + MegaLimitExceeded::abi_decode(output).unwrap_or_else(|err| { + panic!("revert data is not MegaLimitExceeded ({err}); output {output:?}"); + }) +} + +/// The stop a successful transaction returned from a frame it caught. +pub(super) fn returned_stop(outcome: &MegaTransactionOutcome) -> MegaLimitExceeded { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("expected a success that returns the stop, got {:?}", outcome.result); + }; + MegaLimitExceeded::abi_decode(output.data()).unwrap_or_else(|err| { + panic!("return data is not MegaLimitExceeded ({err}); output {output:?}"); + }) +} + +/// The value of `slot` after `outcome`, or zero when the account has no entry for it. +pub(super) fn slot_value(outcome: &MegaTransactionOutcome, address: Address, slot: u64) -> U256 { + outcome + .state + .get(&address) + .and_then(|account| account.storage.get(&U256::from(slot))) + .map(|entry| entry.present_value()) + .unwrap_or(U256::ZERO) +} + +/// Whether `outcome` destroyed `address`: an account created in the transaction that a +/// `SELFDESTRUCT` deleted. Its code can still be in the state entry, so code is not the test. +pub(super) fn is_destroyed(outcome: &MegaTransactionOutcome, address: Address) -> bool { + outcome.state.get(&address).is_some_and(|account| account.is_selfdestructed()) +} + +/// Whether `address` has code that is not empty. +pub(super) fn has_code(outcome: &MegaTransactionOutcome, address: Address) -> bool { + outcome.state.get(&address).is_some_and(|account| { + account.info.code.as_ref().is_some_and(|code| !code.is_empty()) || + (account.info.code_hash != alloy_primitives::B256::ZERO && + account.info.code_hash != KECCAK_EMPTY) + }) +} + +/// The nonce `outcome` leaves `address`, or zero when the account was not loaded. +pub(super) fn nonce_of(outcome: &MegaTransactionOutcome, address: Address) -> u64 { + outcome.state.get(&address).map(|account| account.info.nonce).unwrap_or(0) +} + +/// The balance `outcome` leaves `address`, or zero when the account was not loaded. +pub(super) fn balance_of(outcome: &MegaTransactionOutcome, address: Address) -> U256 { + outcome.state.get(&address).map(|account| account.info.balance).unwrap_or(U256::ZERO) +} + +/// Whether `outcome` halted because a frame ran out of gas. +pub(super) fn halted_out_of_gas(outcome: &MegaTransactionOutcome) -> bool { + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } + ) +} + +/// One forwarded call: the gas the caller held at the opcode, the gas the child was given, and +/// the reservoir the child was given. +#[derive(Clone, Debug, Default)] +pub(super) struct Forward { + want: Option
, + pending: Option, + /// Regular gas the caller held at the opcode, before its static gas. + pub(super) held: Option, + /// Regular gas the child was given. + pub(super) gas_limit: Option, + /// Reservoir the child was given. + pub(super) reservoir: Option, + /// Every call, in order: target, gas limit, reservoir. The first is the transaction's own + /// frame. + pub(super) calls: Vec<(Address, u64, u64)>, + /// Every call's end, in order: target, and the reservoir its frame ended with, before its + /// caller (or, for the transaction's own frame, the transaction) settles it. + pub(super) call_ends: Vec<(Address, u64)>, + /// The creation's gas limit and reservoir, when one started. + pub(super) created: Option<(u64, u64)>, + /// The regular gas the creation returned with, when one ended. + pub(super) create_end_remaining: Option, +} + +impl Forward { + /// Records the call whose target is `want`, and every call besides. + pub(super) fn targeting(want: Address) -> Self { + Self { want: Some(want), ..Self::default() } + } + + /// Records every call and the creation. + pub(super) fn any() -> Self { + Self::default() + } + + /// The reservoir the first call to `target` was given. + pub(super) fn reservoir_given(&self, target: Address) -> u64 { + let call = self.calls.iter().find(|(to, ..)| *to == target); + call.unwrap_or_else(|| panic!("no call to {target}: {:?}", self.calls)).2 + } +} + +impl Inspector, EthInterpreter> for Forward { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + let opcode = interp.bytecode.opcode(); + if matches!(opcode, CALL | DELEGATECALL | CREATE | CREATE2) { + self.pending = Some(interp.gas.remaining()); + } + } + + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + self.calls.push((inputs.target_address, inputs.gas_limit, inputs.reservoir)); + if self.want.is_none_or(|want| inputs.target_address == want) { + self.held = self.pending; + self.gas_limit = Some(inputs.gas_limit); + self.reservoir = Some(inputs.reservoir); + } + None + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + self.call_ends.push((inputs.target_address, outcome.result.gas.reservoir())); + } + + fn create( + &mut self, + _context: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.created = Some((inputs.gas_limit(), inputs.reservoir())); + self.held = self.pending; + self.gas_limit = Some(inputs.gas_limit()); + self.reservoir = Some(inputs.reservoir()); + None + } + + fn create_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.create_end_remaining = Some(outcome.result.gas.remaining()); + } +} + +/// Runs `tx` over `db` and returns the outcome together with what [`Forward`] recorded. +pub(super) fn execute_forward( + db: MemoryDatabase, + tx: MegaTransaction, + probe: Forward, +) -> (MegaTransactionOutcome, Forward) { + let mut evm = MegaEvm::new(context(db)).with_inspector(probe); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let probe = evm.inspector().clone(); + (outcome, probe) +} + +/// Same as [`execute_forward`], under `limits`. +pub(super) fn execute_forward_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, + probe: Forward, +) -> (MegaTransactionOutcome, Forward) { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(probe); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let probe = evm.inspector().clone(); + (outcome, probe) +} + +/// A call from [`CALLER`] to [`CONTRACT`] whose gas limit is the execution cap plus `reservoir` +/// plus the body's history, so the reservoir left after the body is `reservoir`. +pub(super) fn call_with_reservoir(reservoir: u64) -> MegaTransaction { + let gas = EXECUTION_CAP + common::body_history(0) + reservoir; + call_tx(gas) +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/records.rs b/crates/mega-evm/tests/satin/limit_matrix/records.rs new file mode 100644 index 000000000..923dc4003 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/records.rs @@ -0,0 +1,266 @@ +//! What one slot or one account keeps. +//! +//! A figure pinned below is the page's, at the minimum bucket. Each scenario runs through +//! [`plain_and_probed`]: its figures come from the plain run, and the state-growth net it kept +//! from the probe's budget, which is how a row about the state-growth count observes it. + +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; +use mega_evm::{test_utils::BytecodeBuilder, MegaTransactionOutcome}; +use revm::bytecode::opcode::POP; + +use super::{ + assert_growth, at_spec_prices, balance_of, call_with_gas, has_code, nonce_of, plain_and_probed, + slot_value, world, ACCOUNT_LEAF_STATE_GAS_M1, BODY_BYTES, BODY_HISTORY, CHILD, CONTRACT, + EXISTING, SLOT_STATE_GAS_M1, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, +}; +use crate::common::state_is_free; + +/// An address no test funds. +const NOBODY: Address = address!("0000000000000000000000000000000000ab102b"); + +/// Whether a test that pins a spec state-gas figure can run. +fn pins_state() -> bool { + at_spec_prices() && !state_is_free() +} + +/// [`plain_and_probed`] on `world`, with [`CONTRACT`] running `scenario` and `setup` applied. +fn run( + scenario: Bytes, + setup: impl Fn(&mut mega_evm::test_utils::MemoryDatabase), +) -> Option<(MegaTransactionOutcome, MegaTransactionOutcome)> { + plain_and_probed(&scenario, |code| { + let mut db = world(&[(CONTRACT, code), (EXISTING, Bytes::from_static(&[0x00]))]); + setup(&mut db); + db + }) +} + +/// Slot `0 → x → 0` in one frame. The second `SSTORE` is the fall row: state gas is refilled, +/// the record is taken back, and the slot's net state growth is 0. +#[test] +fn test_a_slot_set_and_cleared_refills_its_state_gas() { + if !pins_state() { + return; + } + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::ZERO) + .build(); + let Some((outcome, probed)) = run(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "the fall refills the fresh-slot charge"); + assert_eq!( + outcome.gas.history, BODY_HISTORY, + "the taken-back record leaves the body's history" + ); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); + assert_eq!(outcome.usage.write_records, 0, "the record is taken back with the value"); + assert_growth(&probed, 0); +} + +/// `CREATE2` onto an address that held a balance before the transaction, nonce 0, no code, and +/// that this transaction has not changed. The creation is valid and the nonce becomes 1. No +/// state-growth rise and no new-account charge. One record for the target, because its nonce +/// differs from what the transaction loaded, and the creator's nonce record apart from it. +/// +/// Under a transaction KV limit of 1 the creation's KV budget is `floor(1 × 98 / 100)` = 0 and the +/// target's record stops it, kind 1, `limit` 0, while the creator's bump stands, and the creator +/// keeps its record in the 1 it has once the creation returned. +#[test] +fn test_create2_onto_a_prefunded_address_is_not_a_rise() { + let init = BytecodeBuilder::default().stop().build(); + let created = CONTRACT.create2(B256::ZERO, keccak256(init.as_ref())); + let code = || { + BytecodeBuilder::default().create2(U256::ZERO, init.clone(), U256::ZERO).append(POP).build() + }; + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_balance(created, U256::from(1)); + }; + let Some((outcome, probed)) = run(code(), setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, created), 1, "the creation bumps the nonce"); + assert_eq!(outcome.gas.state, 0, "a funded address is not empty: no new-account charge"); + assert_eq!(outcome.usage.write_records, 2, "the target's record and the creator's"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_growth(&probed, 0); + + { + let mut code = code().to_vec(); + code.extend_from_slice(&BytecodeBuilder::default().return_returndata().build()); + let mut db = world(&[(CONTRACT, Bytes::from(code))]); + setup(&mut db); + let limits = mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(1); + let Some(gas) = super::slots_gas(2) else { return }; + let outcome = super::execute_under(db, super::call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + super::returned_stop(&outcome), + mega_evm::MegaLimitExceeded { kind: 1, limit: 0 } + ); + assert_eq!(nonce_of(&outcome, created), 0, "the stopped creation is taken back"); + assert_eq!(nonce_of(&outcome, CONTRACT), 1, "the creator's bump stands"); + assert_eq!(outcome.usage.write_records, 1, "the creator's record"); + } +} + +/// `CREATE2` onto an address this transaction funded earlier. The value call created the leaf: +/// +1 and 183,600 at `m` = 1. The address already has its write record, so the creation adds no +/// record, no rise and no second account charge. +#[test] +fn test_create2_onto_an_address_funded_in_this_transaction_charges_one_leaf() { + if !pins_state() { + return; + } + let init = BytecodeBuilder::default().stop().build(); + let funded = CONTRACT.create2(B256::ZERO, keccak256(init.as_ref())); + let code = BytecodeBuilder::default() + .call(funded, U256::from(1)) + .append(POP) + .create2(U256::ZERO, init, U256::ZERO) + .append(POP) + .build(); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_balance(CONTRACT, U256::from(10u64.pow(18))); + }; + let Some((outcome, probed)) = run(code, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, + "the value call is the one leaf; the creation adds none" + ); + assert_eq!(nonce_of(&outcome, funded), 1); + assert_eq!(outcome.usage.write_records, 2, "the creator's record and the funded address's"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); + assert_growth(&probed, 1); +} + +/// `CREATE2` onto an address that holds code: a collision. No target-side start is kept: the +/// target account, the endowment and its transfer log are not kept. The creator's nonce bump +/// and its record are retained. The collision adds no state growth. +/// +/// A collision consumes the regular gas it was forwarded, all but 2 per cent of its creator's, +/// so the creator is a child given [`CREATOR_GAS`]: the transaction's own frame keeps the gas the +/// probe after it runs on. +#[test] +fn test_create2_onto_code_keeps_the_creator_nonce_and_not_the_target() { + /// Regular gas for the creator: the `CREATE2` and what it forwards to the collision. The + /// history of the start's records draws the reservoir the creator is given. + const CREATOR_GAS: u32 = 200_000; + let init = BytecodeBuilder::default().stop().build(); + let target = CHILD.create2(B256::ZERO, keccak256(init.as_ref())); + let creator = + BytecodeBuilder::default().create2(U256::from(1), init, U256::ZERO).append(POP).build(); + let code = call_with_gas(BytecodeBuilder::default(), CHILD, U256::ZERO, CREATOR_GAS) + .append(POP) + .build(); + let before = U256::from(7); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_code(CHILD, creator.clone()); + db.set_account_balance(CHILD, U256::from(10u64.pow(18))); + db.set_account_code(target, Bytes::from_static(&[0x00])); + db.set_account_balance(target, before); + }; + let Some((outcome, probed)) = run(code, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, CHILD), 1, "the creator nonce bump stands"); + assert_eq!(balance_of(&outcome, target), before, "the target and its endowment are not kept"); + assert!(has_code(&outcome, target), "the target code stays"); + assert_eq!(outcome.gas.state, 0, "a collision is not a rise"); + assert_eq!(outcome.usage.write_records, 1, "the creator's nonce record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE, "no transfer log"); + assert!(outcome.result.logs().is_empty()); + assert_growth(&probed, 0); +} + +/// A value `CALL` the caller cannot fund, to an account that does not exist, counts nothing: no +/// record, no rise, no charge. A creation whose creator nonce cannot be bumped counts nothing +/// either, though the address it would create is empty. No limit stops either. +#[test] +fn test_an_unfunded_value_call_and_a_stuck_nonce_count_nothing() { + let call = BytecodeBuilder::default().call(NOBODY, U256::from(5)).append(POP).build(); + let Some((outcome, probed)) = run(call, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0, "an unfunded value call writes nothing"); + assert_eq!(outcome.usage.data_size, BODY_BYTES); + assert_eq!(outcome.gas.state, 0, "and is charged nothing"); + assert_eq!(balance_of(&outcome, NOBODY), U256::ZERO); + assert!(outcome.limit_exceeded.is_none()); + assert_growth(&probed, 0); + + let init = BytecodeBuilder::default().stop().build(); + let create = BytecodeBuilder::default().create(U256::ZERO, init).append(POP).build(); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_nonce(CONTRACT, u64::MAX); + }; + let Some((outcome, probed)) = run(create, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0, "a nonce that cannot move writes nothing"); + assert_eq!(outcome.usage.data_size, BODY_BYTES); + assert_eq!(outcome.gas.state, 0); + assert_eq!(nonce_of(&outcome, CONTRACT), u64::MAX); + assert!(outcome.limit_exceeded.is_none()); + assert_growth(&probed, 0); +} + +/// `(original 0, present non-zero, new non-zero)` neither rises nor falls: the slot rose once, at +/// its first write. `(original non-zero, present 0, new non-zero)` neither rises nor falls, and +/// charges no fresh-slot state gas and refills none. +#[test] +fn test_a_second_nonzero_write_neither_rises_nor_falls() { + if !pins_state() { + return; + } + let twice = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::from(2)) + .build(); + let Some((outcome, probed)) = run(twice, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, SLOT_STATE_GAS_M1, "0 → x → y rose once"); + assert_growth(&probed, 1); + + let restored = BytecodeBuilder::default() + .sstore(U256::from(1), U256::ZERO) + .sstore(U256::from(1), U256::from(1)) + .build(); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_storage(CONTRACT, U256::from(1), U256::from(9)); + }; + let Some((outcome, probed)) = run(restored, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "a slot that started non-zero charges and refills nothing"); + assert_growth(&probed, 0); +} + +/// `0 → 0` changes nothing. `0 → x → x` and `0 → x → y` rose once. `0 → x → 0 → y` rose, fell, +/// and rose again, net +1. A slot whose original value is non-zero changes nothing on every write. +#[test] +fn test_slot_sequences_in_one_frame_rise_once() { + if !pins_state() { + return; + } + let writes = |values: &[u64]| { + values + .iter() + .fold(BytecodeBuilder::default(), |code, value| { + code.sstore(U256::from(1), U256::from(*value)) + }) + .build() + }; + for (values, rises) in [(&[0][..], 0), (&[1, 1][..], 1), (&[1, 2][..], 1), (&[1, 0, 3][..], 1)] + { + let Some((outcome, probed)) = run(writes(values), |_| {}) else { return }; + assert!(outcome.result.is_success(), "{values:?}: {:?}", outcome.result); + assert_eq!(outcome.gas.state, rises * SLOT_STATE_GAS_M1, "{values:?}"); + assert_eq!(outcome.usage.write_records, rises, "{values:?}"); + assert_growth(&probed, rises); + } + + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_storage(CONTRACT, U256::from(1), U256::from(8)); + }; + let Some((outcome, probed)) = run(writes(&[4, 0, 5]), setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "an originally non-zero slot changes nothing"); + assert_growth(&probed, 0); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/stop.rs b/crates/mega-evm/tests/satin/limit_matrix/stop.rs new file mode 100644 index 000000000..d25f62590 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/stop.rs @@ -0,0 +1,306 @@ +//! Which dimension a crossing names, and a caller that catches it. +//! +//! Every kind is observed through the revert data. + +use alloy_primitives::{Bytes, U256}; +use mega_evm::{test_utils::BytecodeBuilder, EvmTxRuntimeLimits, MegaLimitExceeded}; +use revm::{ + bytecode::opcode::{POP, TIMESTAMP}, + context::result::ExecutionResult, +}; + +use super::{ + call_tx, execute_under, returned_stop, slot_value, slots_gas, store_n_prefix, world, CHILD, + CONTRACT, TX_STATE_GROWTH_LIMIT, +}; + +fn extend(prefix: Vec, rest: BytecodeBuilder) -> Bytes { + let mut code = prefix; + code.extend_from_slice(&rest.build()); + Bytes::from(code) +} + +/// Under a transaction KV limit of 10, an applied authorization is one record before the first +/// frame, on no frame, so the transaction's own frame has a KV budget of 9. That frame's 10th +/// record crosses its budget and the transaction limit. Kind 1. `limit` is the frame budget, 9. +#[test] +fn test_a_record_that_crosses_kv_names_the_frame_budget() { + let Some(gas) = slots_gas(12) else { return }; + let authority = alloy_primitives::address!("0000000000000000000000000000000000ab1018"); + let db = world(&[(CONTRACT, super::store_n_slots(10))]); + let tx = crate::common::authorizing_call( + super::CALLER, + CONTRACT, + U256::ZERO, + gas, + CHILD, + &[(authority, 0)], + ); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let outcome = execute_under(db, tx, limits); + assert_eq!(super::reverted_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 9 }); + assert_eq!(super::nonce_of(&outcome, authority), 1, "the admitted authorization stays"); +} + +/// A fresh `SSTORE` whose regular charge crosses detention, and whose completed write would have +/// crossed the state-growth frame budget. The charge is made before the write is counted. Kind +/// 2. The crossing slot is not kept. The parent's earlier slots stay: the stop is the child's. +#[test] +fn test_a_charge_that_crosses_detention_stops_before_the_write_is_counted() { + let child = BytecodeBuilder::default() + .append(TIMESTAMP) + .append(POP) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(); + let parent = extend( + store_n_prefix(TX_STATE_GROWTH_LIMIT as u16, 1, false), + BytecodeBuilder::default().call(CHILD, U256::ZERO).return_returndata(), + ); + let db = world(&[(CONTRACT, parent), (CHILD, child)]); + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + // 50 leaves the opcodes between the read and `SSTORE` inside the cap, and `SSTORE`'s charge + // past it. Zero would be a real cap the read itself could not move past. + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(50); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let stop = returned_stop(&outcome); + assert_eq!(stop.kind, 2, "the regular charge stops the opcode before the write is counted"); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO, "the crossing slot is not kept"); + assert_eq!( + slot_value(&outcome, CONTRACT, 1), + U256::from(1), + "the parent frame is outside the stop" + ); +} + +/// KV at depth 2 and 3 under a transaction limit of 100: the child's budget is 98, the +/// grandchild's 96 and the next frame's `floor(96 × 98 / 100)` = 94. The 95th new record there +/// stops that frame, kind 1, `limit` 94. +#[test] +fn test_kv_at_depth_2_and_3_stops_at_94() { + assert_eq!(super::frame_share(100), 98); + assert_eq!(super::frame_share(98), 96); + assert_eq!(super::frame_share(96), 94); + let Some(gas) = slots_gas(95) else { return }; + let db = world(&[ + (CONTRACT, super::forward_to(CHILD)), + (CHILD, super::forward_to(super::GRAND)), + (super::GRAND, super::forward_to(super::NEXT)), + (super::NEXT, super::store_n_slots(95)), + ]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(100); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 94 }); + assert_eq!(slot_value(&outcome, super::NEXT, 1), U256::ZERO); +} + +/// The caller catches a kind-3 stop, continues, and is stopped in turn. The child's stop is not +/// the transaction's result. `limit` is the caller's frame budget. The top frame catches that +/// stop in turn and the transaction succeeds. +/// +/// The same shape for kind 1, under a transaction KV limit of 100. +#[test] +fn test_a_caller_that_catches_a_stop_is_stopped_by_its_own_next_record() { + let child = super::store_n_slots(1); + let mid = extend( + store_n_prefix(980, 1, false), + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .sstore(U256::from(981), U256::from(1)), + ); + let parent = + BytecodeBuilder::default().call(super::GRAND, U256::ZERO).return_returndata().build(); + // GRAND is the frame whose budget is 980. CHILD is the frame whose budget is 0. + let db = world(&[(CONTRACT, parent.clone()), (super::GRAND, mid), (CHILD, child)]); + let Some(gas) = slots_gas(1_000) else { return }; + let outcome = execute_under(db, call_tx(gas), EvmTxRuntimeLimits::default()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the top frame caught the stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 980 }); + assert_eq!( + slot_value(&outcome, super::GRAND, 1), + U256::ZERO, + "the stopped caller keeps nothing" + ); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + + { + // The caller's KV budget is `floor(100 × 98 / 100)` = 98, its child's 0. + let mid = extend( + store_n_prefix(98, 1, false), + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .sstore(U256::from(99), U256::from(1)), + ); + let db = + world(&[(CONTRACT, parent), (super::GRAND, mid), (CHILD, super::store_n_slots(1))]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(100); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the top frame caught the stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 98 }); + assert_eq!(slot_value(&outcome, super::GRAND, 1), U256::ZERO); + } +} + +/// Under a transaction KV limit of 10 the creator, a child of the top frame, has a KV budget of +/// 9. It keeps 9 records and then creates: the creation's budget is the share of the nothing the +/// creator has left, 0, and its own record stops it at its start. The start bumped the creator's +/// nonce, whose record is counted on the creator when the creation returns, before it runs on: +/// the creator stops, kind 1, `limit` 9, its frame budget. +/// +/// With one record of room the creation's budget is still `floor(1 × 98 / 100)` = 0, so the +/// creation is stopped at its start, kind 1, `limit` 0, and the creator keeps the bump and its +/// record in the one it has: its nonce is 1. +#[test] +fn test_a_creator_nonce_record_stops_the_creator_at_its_kv_budget() { + let Some(gas) = slots_gas(12) else { return }; + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let creator = |records: u16| { + let mut code = store_n_prefix(records, 1, false); + let init = BytecodeBuilder::default().return_with_data([0x00]).build(); + code.extend_from_slice( + &BytecodeBuilder::default() + .create(U256::ZERO, init) + .append(POP) + .return_returndata() + .build(), + ); + Bytes::from(code) + }; + + let db = world(&[(CONTRACT, super::forward_to(CHILD)), (CHILD, creator(9))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 9 }); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO, "the stopped creator keeps nothing"); + + let db = world(&[(CONTRACT, super::forward_to(CHILD)), (CHILD, creator(8))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 0 }); + assert_eq!(super::nonce_of(&outcome, CHILD), 1, "a stopped creation keeps the creator's bump"); + assert_eq!(slot_value(&outcome, CHILD, 8), U256::from(1)); +} + +/// A value `CALL` to the BN254 pairing precompile with no input, whose price, 45,000, is past +/// what a read of the block environment under a cap of 20,000 leaves once the caller's own +/// `CALL` is paid, and within the forward. The start's two records, the caller's +/// balance and the precompile's, are inside every budget, so the price is the stop, kind 2, and +/// the value, the transfer log and the records are taken back with it, the new account's state +/// gas included. A value the caller cannot fund runs no precompile, counts nothing and is stopped +/// by no limit. +/// +/// Under a transaction KV limit of 2 the started frame's KV share is `floor(2 × 98 / 100)` = 1, +/// the two records cross it, and the stop is kind 1, `limit` 1, not the price. A precompile the +/// node cannot price needs a node precompile and is not run. +#[test] +fn test_precompile_records_stop_at_the_kv_share_before_the_price() { + const PAIRING: alloy_primitives::Address = + alloy_primitives::address!("0000000000000000000000000000000000000008"); + let paying = |value: u64| { + BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .call(PAIRING, U256::from(value)) + .append(POP) + .return_returndata() + .build() + }; + let gas = super::EXECUTION_CAP + crate::common::value_call_room(); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(20_000); + + let outcome = execute_under(world(&[(CONTRACT, paying(1))]), call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2, "the records fit: the price is the stop"); + assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO, "the value is taken back"); + assert!(outcome.result.logs().is_empty(), "the transfer log is taken back"); + assert_eq!(outcome.usage.write_records, 0, "the records are taken back"); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); + assert_eq!(outcome.gas.state, 0, "the new account's charge comes back"); + + let outcome = execute_under(world(&[(CONTRACT, paying(5))]), call_tx(gas), limits); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("an unfunded value call fails and its caller runs on: {:?}", outcome.result); + }; + assert!(output.data().is_empty(), "no precompile ran and no stop was returned"); + assert!(outcome.limit_exceeded.is_none()); + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); + assert_eq!(outcome.gas.state, 0, "the unfunded start is charged nothing"); + + { + let limits = limits.with_tx_kv_update_limit(2); + let outcome = execute_under(world(&[(CONTRACT, paying(1))]), call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO); + assert_eq!(outcome.usage.write_records, 0); + } +} + +/// A precompile the node installed, whose start's records are held before its answer. +/// +/// A precompile the engine cannot price runs on what the compute limit leaves its frame, and the +/// start's records are held to the limits before its answer is: a value `CALL` to a node's own +/// precompile, installed through `with_dyn_precompiles`, whose price, 100,000, is past what a read +/// of the block environment under a cap of 30,000 leaves once the caller's own `CALL` is paid, and +/// within the forward. With the records inside every budget it runs out of that allowance, and +/// that is the stop, kind 2, which takes the value and the records back. Under a transaction KV +/// limit of 2 the started frame's KV share is `floor(2 × 98 / 100)` = 1, the two records cross it, +/// and the stop is kind 1, `limit` 1: the same order as for a precompile the engine prices. +#[test] +fn test_an_unpriced_precompile_records_stop_at_the_kv_share_before_its_allowance() { + use alloy_primitives::map::HashMap; + use mega_evm::MegaEvm; + use revm::bytecode::opcode::{CALL, GAS, PUSH0}; + + use crate::withheld_gas::{priced, Runs, PRICED}; + + const PRICE: u64 = 100_000; + let code = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .mstore(0, U256::from(PRICE).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .append(PUSH0) + .push_u256(U256::from(1)) + .push_address(PRICED) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build(); + let gas = super::EXECUTION_CAP + crate::common::value_call_room(); + let run = |limits: EvmTxRuntimeLimits| { + let runs = Runs::default(); + let context = crate::common::context(world(&[(CONTRACT, code.clone())])) + .with_tx_runtime_limits(limits); + let outcome = MegaEvm::new(context) + .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])) + .execute_transaction(call_tx(gas)) + .expect("the transaction is valid"); + let ran = runs.lock().unwrap().clone(); + (outcome, ran) + }; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(30_000); + + let (outcome, ran) = run(limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2, "the records fit: the allowance is the stop"); + assert!( + matches!(ran.as_slice(), [(allowance, false)] if *allowance < 30_000), + "it ran once, on the allowance, short of its price: {ran:?}" + ); + assert_eq!(super::balance_of(&outcome, PRICED), U256::ZERO, "the value is taken back"); + assert_eq!(outcome.usage.write_records, 0, "the records are taken back"); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); + + let (outcome, _) = run(limits.with_tx_kv_update_limit(2)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + assert_eq!(super::balance_of(&outcome, PRICED), U256::ZERO); + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index dd2ee96c2..dca186240 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,8 @@ mod detention; mod equivalence; mod failed_deposit; mod floor_exempt; +mod gas_forward; +mod history_allowance; mod history_bytes; mod history_exemption; mod history_gas; @@ -25,13 +27,19 @@ mod inspector_cheatcodes; mod inspector_limits; mod inspector_settlement; mod intrinsic; +mod kv_updates; mod limit_exemption; +mod limit_matrix; mod limit_stop; mod neutral; +#[path = "../shared/op_reference.rs"] +mod op_reference; mod outcome; mod pool_validation; mod precompile_gas; mod pricing_table; +mod reservoir_drain; +mod reservoir_share; mod salt; mod salt_delegation; mod salt_deposit; @@ -45,10 +53,10 @@ mod state; mod state_growth; mod static_callee; mod stops; -mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; mod system_call; +mod tool_writes; mod transfer_logs; mod volatile_access; mod withheld_gas; diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index da8f4d79b..657c565d1 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -30,8 +30,8 @@ use op_revm::{ }; use revm::{ bytecode::opcode::{ - ADDRESS, BALANCE, CALL, EXTCODESIZE, GAS, LOG1, LOG3, NUMBER, POP, PUSH0, PUSH1, SSTORE, - TIMESTAMP, + ADDRESS, BALANCE, CALL, DELEGATECALL, EXTCODESIZE, GAS, LOG1, LOG3, NUMBER, POP, PUSH0, + PUSH1, SELFDESTRUCT, SSTORE, STOP, TIMESTAMP, }, context::{ result::{ExecResultAndState, ExecutionResult}, @@ -188,6 +188,56 @@ fn test_neutral_creation_matches_op_revm() { } } +/// A `CREATE` from a contract whose nonce is at its maximum. On Osaka, where EIP-8037 is off, the +/// opcode starts the creation without the address it would take, and revm refuses it before the +/// bump; on Amsterdam the opcode refuses it itself. Either way nothing is created and nothing is +/// counted, and the run is op-revm's. +#[test] +fn test_neutral_creation_from_a_nonce_at_its_maximum_matches_op_revm() { + let code = BytecodeBuilder::default().create(U256::ZERO, [STOP]).return_top().build(); + for fork in FORKS { + let db = funded().account_code(CALLEE, code.clone()).account_nonce(CALLEE, u64::MAX); + let outcome = run_both(fork, db, call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success(), "{fork:?}: {:?}", outcome.0.result); + assert_eq!(outcome.0.result.output(), Some(&Bytes::from(vec![0; 32])), "{fork:?}"); + assert_eq!(outcome.0.state[&CALLEE].info.nonce, u64::MAX, "{fork:?}: not bumped"); + assert_same(fork, outcome); + } +} + +/// A creation whose constructor writes a fresh slot, destroys its own account through a +/// `DELEGATECALL`, writes another fresh slot and returns code. On Satin's configuration the +/// destruction gives back the leaf and the slot's state gas, the slot written after it keeps none, +/// and the code deposited after it keeps none; EIP-8037 gives back nothing for this destruction, +/// and the neutral configuration prices as the fork does, so the run is op-revm's on both forks, +/// Amsterdam's state gas included. +#[test] +fn test_neutral_creation_that_destroys_itself_matches_op_revm() { + const DESTROYER: Address = address!("0x5000000000000000000000000000000000000003"); + let destroyer = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); + let init = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(DESTROYER) + .append_many([GAS, DELEGATECALL, POP]) + .sstore(U256::from(2), U256::from(1)) + .return_with_data([STOP, STOP]) + .build(); + let code = BytecodeBuilder::default().create(U256::ZERO, &init).append(POP).stop().build(); + for fork in FORKS { + let db = + funded().account_code(CALLEE, code.clone()).account_code(DESTROYER, destroyer.clone()); + let outcome = run_both(fork, db, call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success(), "{fork:?}: {:?}", outcome.0.result); + let created = CALLEE.create(0); + assert!( + outcome.0.state[&created].is_selfdestructed(), + "{fork:?}: the account is destroyed" + ); + assert_same(fork, outcome); + } +} + /// A nested value call: on Satin's configuration its caller pays for the two write records the /// callee's frame makes, and the callee gets a history allowance. Neither shows here. #[test] @@ -372,3 +422,38 @@ fn test_neutral_kzg_call_matches_ethereum() { assert_same(fork, outcome); } } + +/// A creation onto an address an earlier transaction run on the same journal loaded — two +/// transactions in a row, without the journal finalized between them, as a block builder runs one +/// after another — makes a new account, and counts its unit of state growth, as on a fresh +/// journal. On Osaka the `CREATE2` opcode does not load the address itself, EIP-8037 being off, so +/// what the earlier transaction left of the account in the journal is all the start finds. +#[test] +fn test_neutral_creation_onto_an_address_an_earlier_transaction_loaded_counts_its_account() { + const READER: Address = address!("0x5000000000000000000000000000000000000002"); + let init = Bytes::from_static(&[STOP]); + let created = CALLEE.create2(alloy_primitives::B256::ZERO, alloy_primitives::keccak256(&init)); + let factory = BytecodeBuilder::default().create2(U256::ZERO, &init, U256::ZERO).stop().build(); + let reader = + BytecodeBuilder::default().push_address(created).append_many([BALANCE, POP]).stop().build(); + for fork in FORKS { + let db = + funded().account_code(CALLEE, factory.clone()).account_code(READER, reader.clone()); + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + neutralize_evm(&mut evm, fork).expect("a neutral fork"); + let read = TxEnv { kind: TxKind::Call(READER), ..call(Bytes::new(), U256::ZERO) }; + let read = ExecuteEvm::transact_one(&mut evm, OpTx(op_transaction(read))).unwrap(); + assert!(read.is_success(), "{fork:?}: {read:?}"); + let create = TxEnv { nonce: 1, ..call(Bytes::new(), U256::ZERO) }; + let create = ExecuteEvm::transact_one(&mut evm, OpTx(op_transaction(create))).unwrap(); + assert!(create.is_success(), "{fork:?}: {create:?}"); + let state = ExecuteEvm::finalize(&mut evm); + assert_eq!(state[&created].info.nonce, 1, "{fork:?}: the account was created"); + assert_eq!(evm.ctx().limit_usage().state_growth, 1, "{fork:?}: its unit of growth"); + } +} diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index d65b69196..d5d9fbf85 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -67,7 +67,12 @@ fn test_outcome_reports_the_ledgers() { ); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 } + LimitUsage { + data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, + write_records: 2, + state_growth: 2 + }, + "the two write records; both slots are new" ); assert_eq!(outcome.limit_exceeded, None); @@ -92,14 +97,15 @@ fn test_outcome_reports_the_stop() { outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: TX_BODY_SIZE + 40, - used: TX_BODY_SIZE + 80, - frame_local: false - }) + limit: 40, + used: 80, + frame_local: true + }), + "the transaction's own frame crossed its budget, what the body leaves of the limit" ); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "the stop drops the writes and keeps the body" ); } diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index a73acf4fa..7405a9559 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -4,7 +4,7 @@ Generated by `cargo test -p mega-evm --test satin`; the test compares this file ## Schedule entries -Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte and deposited code priced at `MegaETH`'s cost per history byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those two applies. +Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte, deposited code and a value call's history allowance priced at `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller has left of its regular gas, of its reservoir and of its data-size, KV-update and state-growth budgets; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those applies. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -19,7 +19,7 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | memory_quadratic_reduction | 512 | 512 | 512 | | initcode_per_word | 2 | 2 | 2 | | create | 32000 | 12000 | 12000 | -| call_stipend_reduction | 64 | 64 | 64 | +| call_stipend_reduction | 64 | 64 | 50 | | transfer_value_cost | 9000 | 11300 | 11300 | | cold_account_additional_cost | 2500 | 2900 | 2900 | | new_account_cost | 25000 | 0 | 0 | @@ -57,6 +57,11 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | max_refund_quotient | 5 | 5 | 5 | | tx_account_write_cost | 0 | 9000 | 9000 | | tx_create_access_cost | 0 | 12000 | 12000 | +| pool2_kept_percent | 0 | 0 | 2 | +| pool1_kept_percent | 0 | 0 | 2 | +| pool0_kept_percent | 0 | 0 | 2 | +| reservoir_kept_percent | 0 | 0 | 2 | +| call_history_allowance | 0 | 0 | 14080 | | code_deposit_history_gas | 0 | 0 | 88 | ## Measured transactions diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 83a524df5..f5dd920d2 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -141,9 +141,11 @@ fn render() -> String { out.push_str( "Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam \ devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state \ - entries rebuilt at `MegaETH`'s cost per state byte and deposited code priced at \ - `MegaETH`'s cost per history byte; the `Satin` column differs from `Amsterdam` in \ - exactly the entries where one of those two applies.\n\n", + entries rebuilt at `MegaETH`'s cost per state byte, deposited code and a value call's \ + history allowance priced at `MegaETH`'s cost per history byte, and a frame forwarded \ + 98 per cent of what its caller has left of its regular gas, of its reservoir and of its \ + data-size, KV-update and state-growth budgets; the `Satin` column differs from \ + `Amsterdam` in exactly the entries where one of those applies.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { @@ -307,11 +309,21 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { // Every regular entry is Amsterdam's. The state entries are rebuilt rather than copied, and // land on Amsterdam's numbers because the provisional cost per state byte is the one - // Glamsterdam uses. The history entry is the one Satin adds: upstream prices no history byte - // at all. + // Glamsterdam uses. The history entries are the ones Satin adds — upstream prices no history + // byte at all — and so are the parts of the data-size, KV-update and state-growth pools and of + // the reservoir a caller keeps from the frame it starts, which upstream forwards whole, and the + // quotient of the regular gas a call forwards, Rex6's 98/100 in place of EIP-150's 63/64. assert_eq!( differing, - ["code_deposit_history_gas"], + [ + "call_stipend_reduction", + "pool2_kept_percent", + "pool1_kept_percent", + "pool0_kept_percent", + "reservoir_kept_percent", + "call_history_allowance", + "code_deposit_history_gas" + ], "the entries Satin prices differently from Amsterdam" ); } diff --git a/crates/mega-evm/tests/satin/reservoir_drain.rs b/crates/mega-evm/tests/satin/reservoir_drain.rs new file mode 100644 index 000000000..6ec0a0550 --- /dev/null +++ b/crates/mega-evm/tests/satin/reservoir_drain.rs @@ -0,0 +1,1751 @@ +//! How a callee's charges draw on the EIP-8037 reservoir it inherits from its caller. +//! +//! Under one gas pool, the forward bounds everything a callee spends. Under Satin a call forwards +//! regular gas, at most `remaining − remaining × 2 / 100` of what its caller has left, and hands +//! the callee the same share of its caller's reservoir whatever regular gas it asks for; the +//! callee's state and history charges draw that share before its regular gas. These tests measure +//! how far a callee's charges reach past the forward, and what that leaves its caller. +//! +//! The contracts: +//! - `A`, the transaction's target, reads `GAS`, calls `C` with an explicit forward (or all it may, +//! asking for its `GAS`), reads `GAS` again, then writes `K` fresh slots of its own and returns. +//! - `C` is `STOP`; `INVALID`, which burns its forward and charges nothing else; or a loop of one +//! charging opcode — `LOG0` with data, `LOG4` without data, or a fresh `SSTORE` — that reads +//! `GAS` around the opcode and returns once an iteration's drop exceeds the opcode's regular cost +//! (the reservoir no longer paid the whole charge), or once its regular gas is below what one +//! more iteration costs with the whole charge spilled onto regular gas. The greedy variant never +//! stops on the drop. One more `C` `CREATE`s a contract of zero bytes and stops. +//! +//! `K` is the work a single pool's forward rule would guarantee `A`: the most fresh slots `A` +//! completes after a callee that spent exactly its forward of regular gas and charged the +//! reservoir nothing, which is what the `INVALID` callee does: its halt hands its share of the +//! reservoir back whole. Each slot is a new slot, so the state-growth limit holds `K` to the 1,000 +//! the transaction may add, and the slots `C` keeps come out of them; below that `A`'s gas binds +//! `K`, and the work fails once `C`'s charges, from both pools together, take more than the room +//! the work leaves. +//! +//! Every figure is predicted by a model of the two pools ([`Pools`]) and the three counted budgets +//! ([`Budget`]) built from the spec's rules and the static opcode costs — a regular charge draws +//! regular gas only, a state or history charge draws the reservoir first and spills onto regular +//! gas, `GAS` reads regular gas; a call forwards at most all but 2 per cent of its caller's regular +//! gas and hands the child all but 2 per cent of its caller's reservoir; the child hands back what +//! it leaves, its reservoir unwinding the caller's spill before the rest joins what the caller +//! kept, and a frame that reverts or halts gives its charges back, its share of the reservoir +//! with them; a child's data-size, KV and state-growth budgets are 98/100 of what its caller has +//! left, and a charge that crosses one reverts the frame with the stop — and each run is held to +//! it: the forward, the share, the charges `C` made, the pools it left, `A`'s `GAS` around the +//! call, whether `A`'s work completed, and the receipt with its ledgers and counts. The figures are +//! read by an inspector, and the same run without one settles the same. The tests print their +//! tables (`--nocapture`); a frame's end shows its gas before its caller settles it, so a reverted +//! `C`'s history column is what it charged before the revert gave it back. +//! +//! They pin the spec's numbers, and return early at other byte prices. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{ + COST_PER_STATE_BYTE, MAX_CONTRACT_SIZE, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, + TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, + }, + decode_mega_limit_exceeded, + test_utils::MemoryDatabase, + LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaTransaction, + MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + ADD, CALL, CREATE, DUP1, DUP2, DUP3, GAS, GT, INVALID, ISZERO, JUMP, JUMPDEST, JUMPI, LOG0, + LOG4, LT, MSTORE, POP, PUSH0, PUSH1, PUSH2, PUSH20, PUSH3, PUSH4, PUSH6, RETURN, SSTORE, + STOP, SUB, SWAP1, + }, + context::result::ExecutionResult, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{ + account_state_gas, body_history, call, context, execute, forward_cap, history, + reservoir_giving, reservoir_share, runs_at_measurement_prices, share, slot_state_gas, +}; + +const SENDER: Address = address!("0000000000000000000000000000000000710000"); +const A: Address = address!("0000000000000000000000000000000000710001"); +const C: Address = address!("0000000000000000000000000000000000710002"); + +/// The bytes of data each `LOG0` of the log-heavy callee carries. +const LOG_DATA: u64 = 512; + +/* ---------- static costs ---------- */ + +// revm's Amsterdam table, which Satin keeps. + +/// `GAS`, `PUSH0`, `POP`. +const G_BASE: u64 = 2; +/// `PUSHn`, `DUPn`, `SWAPn`, `ADD`, `SUB`, `LT`, `GT`, `ISZERO`, `MSTORE`. +const G_VERYLOW: u64 = 3; +/// `JUMPDEST`. +const G_JUMPDEST: u64 = 1; +/// `JUMP`. +const G_JUMP: u64 = 8; +/// `JUMPI`. +const G_JUMPI: u64 = 10; +/// A `LOG`'s base cost. +const G_LOG: u64 = 375; +/// A `LOG`'s cost per topic. +const G_LOG_TOPIC: u64 = 375; +/// A `LOG`'s cost per byte of data. +const G_LOG_DATA: u64 = 8; +/// A fresh `SSTORE` to a cold slot: `sstore_static` 100, `cold_storage_additional_cost` 2,000 +/// and `sstore_set_without_load_cost` 10,000. +const G_SSTORE_SET_COLD: u64 = 100 + 2_000 + 10_000; +/// EIP-2200's sentry: an `SSTORE` needs more regular gas than the call stipend. +const SSTORE_SENTRY: u64 = 2_300; +/// A `CALL` without value to a cold account: the warm access 100 and the cold surcharge 2,900. +const G_CALL_COLD: u64 = 100 + 2_900; +/// The intrinsic regular gas of a call with no calldata: `TX_BASE_COST` 12,000 and 3,000 for the +/// recipient's access. +const INTRINSIC: u64 = 12_000 + 3_000; + +/// The gas limits of the sweep. +const SWEEP: [u64; 5] = [400_000_000, 800_000_000, 1_200_000_000, 1_600_000_000, 2_000_000_000]; + +/* ---------- the pool model ---------- */ + +/// A frame ran out of gas. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Halt; + +/// A frame's two pools — its regular gas and the EIP-8037 reservoir — and the state and history +/// gas its charges spilled onto its regular gas, which a returning child's reservoir unwinds +/// first. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Pools { + regular: u64, + reservoir: u64, + spill: u64, +} + +impl Pools { + const fn new(regular: u64, reservoir: u64) -> Self { + Self { regular, reservoir, spill: 0 } + } + + /// A regular charge draws regular gas only. + fn regular(&mut self, cost: u64) -> Result<(), Halt> { + self.regular = self.regular.checked_sub(cost).ok_or(Halt)?; + Ok(()) + } + + /// A state or history charge draws the reservoir first and spills the rest onto regular gas. + fn draw(&mut self, cost: u64) -> Result<(), Halt> { + let from_reservoir = cost.min(self.reservoir); + let spill = cost - from_reservoir; + if spill > self.regular { + return Err(Halt); + } + self.reservoir -= from_reservoir; + self.regular -= spill; + self.spill += spill; + Ok(()) + } + + /// A call's start forwarding `gas` of regular gas: the child gets it and the reservoir's + /// share, all but this frame's 2 per cent, whatever `gas` is, and starts with no spill. + fn forward(&mut self, gas: u64) -> Self { + let reservoir = reservoir_share(self.reservoir); + self.regular -= gas; + self.reservoir -= reservoir; + Self::new(gas, reservoir) + } + + /// A child's return, handing back `child`: its regular gas comes back, a kept child's spill + /// joins this frame's, and the reservoir it hands back unwinds this frame's spill onto its + /// regular gas before the rest joins what this frame kept. + fn absorb(&mut self, child: Self, kept: bool) { + self.regular += child.regular; + if kept { + self.spill += child.spill; + } + let unwound = child.reservoir.min(self.spill); + self.regular += unwound; + self.spill -= unwound; + self.reservoir += child.reservoir - unwound; + } +} + +/// The pools the transaction's own frame starts with: the regular gas the execution cap leaves +/// once the intrinsic gas is paid, and the gas limit above the cap. The body's history is paid +/// before the frame, from the reservoir first, so none of it is a spill of the frame's. +fn first_frame(gas_limit: u64) -> Pools { + let mut pools = Pools::new( + gas_limit.min(TX_GAS_LIMIT_CAP) - INTRINSIC, + gas_limit.saturating_sub(TX_GAS_LIMIT_CAP), + ); + pools.draw(body_history(0)).expect("the body fits"); + Pools { spill: 0, ..pools } +} + +/// A limit's stop: the dimension crossed, the budget the frame was given, which the stop names, +/// and the frame's count with the crossing charge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Stop { + kind: LimitKind, + limit: u64, + used: u64, +} + +/// A frame's data-size, KV and state-growth budgets: what it was given and what it has left. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Budget { + given: LimitUsage, + left: LimitUsage, +} + +impl Budget { + /// The transaction's own frame's: what the transaction's limits leave once its body is + /// counted. + const fn first_frame() -> Self { + let given = LimitUsage { + data_size: TX_DATA_LIMIT - TX_BODY_SIZE, + write_records: TX_KV_UPDATE_LIMIT, + state_growth: TX_STATE_GROWTH_LIMIT, + }; + Self { given, left: given } + } + + /// No budget at all. + const fn unlimited() -> Self { + let given = + LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: u64::MAX }; + Self { given, left: given } + } + + /// A child's: 98/100 of what this frame has left in each dimension, rounded down. + fn child(&self) -> Self { + let given = LimitUsage { + data_size: share(self.left.data_size), + write_records: share(self.left.write_records), + state_growth: share(self.left.state_growth), + }; + Self { given, left: given } + } + + /// Counts `counted`, or stops on the first dimension it crosses, in the order data size, KV + /// updates, state growth, counting nothing. + fn count(&mut self, counted: LimitUsage) -> Result<(), Stop> { + let dimensions = [ + (LimitKind::DataSize, counted.data_size, self.left.data_size, self.given.data_size), + ( + LimitKind::KvUpdate, + counted.write_records, + self.left.write_records, + self.given.write_records, + ), + ( + LimitKind::StateGrowth, + counted.state_growth, + self.left.state_growth, + self.given.state_growth, + ), + ]; + for (kind, add, left, limit) in dimensions { + if add > left { + return Err(Stop { kind, limit, used: limit - left + add }); + } + } + self.merge(counted); + Ok(()) + } + + /// Takes `kept` out of what this frame has left: what it counted, or what a child that + /// returned kept. + fn merge(&mut self, kept: LimitUsage) { + self.left.data_size -= kept.data_size; + self.left.write_records -= kept.write_records; + self.left.state_growth -= kept.state_growth; + } +} + +/// The sum of two counts. +const fn plus(a: LimitUsage, b: LimitUsage) -> LimitUsage { + LimitUsage { + data_size: a.data_size + b.data_size, + write_records: a.write_records + b.write_records, + state_growth: a.state_growth + b.state_growth, + } +} + +/// `a` less `b`: what a frame counted of a budget `a` when it has `b` left. +const fn minus(a: LimitUsage, b: LimitUsage) -> LimitUsage { + LimitUsage { + data_size: a.data_size - b.data_size, + write_records: a.write_records - b.write_records, + state_growth: a.state_growth - b.state_growth, + } +} + +/// What a fresh slot counts: its write record's bytes, the record, and the new slot. +const SLOT_COUNTS: LimitUsage = + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1, state_growth: 1 }; + +/// What the transaction counts before its frame: its body. +const BODY_COUNTS: LimitUsage = + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }; + +/* ---------- the callee ---------- */ + +/// The charging opcode the callee's loop repeats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Charge { + /// `LOG0` of [`LOG_DATA`] bytes: history only. + Log0Data, + /// `LOG4` of no data: history only. + Log4, + /// A fresh `SSTORE`: state and history. + FreshSlot, +} + +impl Charge { + fn name(self) -> &'static str { + match self { + Self::Log0Data => "LOG0 512 B", + Self::Log4 => "LOG4 0 B", + Self::FreshSlot => "fresh SSTORE", + } + } + + fn opcode(self) -> u8 { + match self { + Self::Log0Data => LOG0, + Self::Log4 => LOG4, + Self::FreshSlot => SSTORE, + } + } + + /// Code that runs once before the loop: `LOG0` reads its data from memory expanded here, so + /// no iteration pays an expansion. + fn prologue(self) -> Vec { + match self { + Self::Log0Data => { + let [hi, lo] = ((LOG_DATA - 32) as u16).to_be_bytes(); + vec![PUSH0, PUSH2, hi, lo, MSTORE] + } + Self::Log4 | Self::FreshSlot => vec![], + } + } + + fn prologue_regular(self) -> u64 { + match self { + Self::Log0Data => { + let words = LOG_DATA / 32; + G_BASE + 2 * G_VERYLOW + 3 * words + words * words / 512 + } + Self::Log4 | Self::FreshSlot => 0, + } + } + + /// The opcodes that push the charging opcode's operands, run with the loop's `[i, g0]` on the + /// stack; the opcode follows and leaves the stack so. + fn operands(self) -> Vec { + match self { + Self::Log0Data => { + let [hi, lo] = (LOG_DATA as u16).to_be_bytes(); + vec![PUSH2, hi, lo, PUSH0] + } + Self::Log4 => vec![PUSH0; 6], + // `SSTORE(key = i, value = 1)`: the counter is a fresh slot each iteration. + Self::FreshSlot => vec![PUSH1, 1, DUP3], + } + } + + fn operands_regular(self) -> u64 { + match self { + Self::Log0Data => G_VERYLOW + G_BASE, + Self::Log4 => 6 * G_BASE, + Self::FreshSlot => 2 * G_VERYLOW, + } + } + + /// The charging opcode's regular gas. + fn opcode_regular(self) -> u64 { + match self { + Self::Log0Data => G_LOG + G_LOG_DATA * LOG_DATA, + Self::Log4 => G_LOG + 4 * G_LOG_TOPIC, + Self::FreshSlot => G_SSTORE_SET_COLD, + } + } + + /// The regular gas of one charge, operands included: what an iteration's `GAS` drop is when + /// the reservoir paid the whole charge, less the closing `GAS`. + fn body_regular(self) -> u64 { + self.operands_regular() + self.opcode_regular() + } + + /// The bytes one charge appends: a log's 32 for its address and 32 per topic plus its data, + /// a write record's 40. + fn bytes(self) -> u64 { + match self { + Self::Log0Data => 32 + LOG_DATA, + Self::Log4 => 32 + 4 * 32, + Self::FreshSlot => WRITE_RECORD_SIZE, + } + } + + /// What one charge counts against the frame's budgets: a log its bytes, a fresh slot its + /// record's bytes, the record and the new slot. + fn counts(self) -> LimitUsage { + match self { + Self::Log0Data | Self::Log4 => { + LimitUsage { data_size: self.bytes(), write_records: 0, state_growth: 0 } + } + Self::FreshSlot => SLOT_COUNTS, + } + } + + /// The state gas of one charge. + fn state(self) -> u64 { + match self { + Self::Log0Data | Self::Log4 => 0, + Self::FreshSlot => slot_state_gas(), + } + } + + /// The history gas of one charge. + fn history(self) -> u64 { + history(self.bytes()) + } + + /// The regular gas the callee keeps before another iteration: that iteration with its whole + /// charge spilled onto regular gas, and the way out. + fn reserve(self) -> u64 { + self.body_regular() + LOOP_REGULAR + self.state() + self.history() + 64 + } +} + +// The callee's loop: its regular gas outside the charge. + +/// `JUMPDEST GAS`, which opens an iteration. +const LOOP_ENTRY: u64 = G_JUMPDEST + G_BASE; +/// `DUP1 PUSH4 GT PUSH2 JUMPI`: out when the regular gas left is below the reserve. +const RESERVE_CHECK: u64 = 4 * G_VERYLOW + G_JUMPI; +/// `SWAP1 SUB PUSH4 LT PUSH2 JUMPI`: out when the drop exceeds the charge's regular gas. +const DROP_CHECK: u64 = 5 * G_VERYLOW + G_JUMPI; +/// `PUSH1 ADD PUSH2 JUMP`: the counter, and back to the top. +const LOOP_NEXT: u64 = 3 * G_VERYLOW + G_JUMP; +/// One iteration's regular gas outside the charge, the closing `GAS` included. +const LOOP_REGULAR: u64 = LOOP_ENTRY + G_BASE + RESERVE_CHECK + DROP_CHECK + LOOP_NEXT; + +/// What `C` runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Callee { + /// `STOP`: returns at once, charging nothing. + Stop, + /// `INVALID`: halts, burning its whole forward and charging nothing else. It spends what a + /// single pool's forward rule lets a callee spend, and no more. + Burn, + /// The loop of `charge`; `stop_on_spill` stops it on the first iteration the reservoir did + /// not pay in full. + Loop { charge: Charge, stop_on_spill: bool }, +} + +impl Callee { + const fn stops_on_spill(charge: Charge) -> Self { + Self::Loop { charge, stop_on_spill: true } + } + + const fn greedy(charge: Charge) -> Self { + Self::Loop { charge, stop_on_spill: false } + } + + fn name(self) -> String { + match self { + Self::Stop => "STOP".into(), + Self::Burn => "INVALID".into(), + Self::Loop { charge, stop_on_spill: true } => charge.name().into(), + Self::Loop { charge, stop_on_spill: false } => format!("{}, greedy", charge.name()), + } + } + + fn charge(self) -> Option { + match self { + Self::Stop | Self::Burn => None, + Self::Loop { charge, .. } => Some(charge), + } + } + + fn code(self) -> Bytes { + let (charge, stop_on_spill) = match self { + Self::Stop => return Bytes::from_static(&[STOP]), + Self::Burn => return Bytes::from_static(&[INVALID]), + Self::Loop { charge, stop_on_spill } => (charge, stop_on_spill), + }; + // The drop that stops the loop: the charge's regular gas and the closing `GAS`. + let stop_above = + if stop_on_spill { charge.body_regular() + G_BASE } else { u64::from(u32::MAX) }; + let u32_bytes = |value: u64| u32::try_from(value).expect("fits a PUSH4").to_be_bytes(); + + let mut code = charge.prologue(); + code.push(PUSH0); + let top = code.len(); + code.extend([JUMPDEST, GAS]); + code.extend(charge.operands()); + code.push(charge.opcode()); + // [i, g0, g1]: out when g1 < reserve. + code.extend([GAS, DUP1, PUSH4]); + code.extend(u32_bytes(charge.reserve())); + code.extend([GT, PUSH2, 0, 0, JUMPI]); + let out_on_reserve = code.len() - 3; + // [i, g0 - g1]: out when the drop exceeds the charge's regular gas. + code.extend([SWAP1, SUB, PUSH4]); + code.extend(u32_bytes(stop_above)); + 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() + } +} + +/// How `C` ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CalleeEnd { + Returned, + /// A charge crossed one of `C`'s budgets: `C` reverts with the stop. + Crossed(Stop), + Halted, +} + +/// What the model says `C` does. +#[derive(Clone, Copy, Debug)] +struct CalleeModel { + end: CalleeEnd, + /// Charging opcodes started, the one that crossed or halted included. + charges: u64, + /// `C`'s pools at its end, before the revert of a crossing gives its charges back. + at_end: Pools, + /// The pools `C` hands back to `A`. + handed_back: Pools, + /// The state and history gas of the charges `C` kept. + state: u64, + history: u64, + /// What `C` kept of its budgets. + kept: LimitUsage, +} + +/// `C` run on the pools `start` and the budgets `budget` its start handed it. +fn model_callee(callee: Callee, start: Pools, budget: Budget) -> CalleeModel { + let (charge, stop_on_spill) = match callee { + Callee::Stop | Callee::Burn => { + // `INVALID` charged nothing, so its halt hands the share back whole. + let (end, handed_back) = match callee { + Callee::Stop => (CalleeEnd::Returned, start), + _ => (CalleeEnd::Halted, Pools::new(0, start.reservoir)), + }; + return CalleeModel { + end, + charges: 0, + at_end: handed_back, + handed_back, + state: 0, + history: 0, + kept: LimitUsage::ZERO, + }; + } + Callee::Loop { charge, stop_on_spill } => (charge, stop_on_spill), + }; + let mut pools = start; + let mut budget = budget; + let mut charges = 0; + let (mut state, mut history) = (0, 0); + let end = (|| -> Result { + pools.regular(charge.prologue_regular() + G_BASE)?; + loop { + pools.regular(LOOP_ENTRY)?; + let g0 = pools.regular; + pools.regular(charge.operands_regular())?; + charges += 1; + if charge == Charge::FreshSlot && pools.regular <= SSTORE_SENTRY { + return Err(Halt); + } + pools.regular(charge.opcode_regular())?; + pools.draw(charge.state())?; + // The completed-write hook counts the write before it charges its history. + if let Err(stop) = budget.count(charge.counts()) { + return Ok(CalleeEnd::Crossed(stop)); + } + pools.draw(charge.history())?; + state += charge.state(); + history += charge.history(); + pools.regular(G_BASE)?; + let g1 = pools.regular; + pools.regular(RESERVE_CHECK)?; + if g1 < charge.reserve() { + pools.regular(G_JUMPDEST)?; + return Ok(CalleeEnd::Returned); + } + pools.regular(DROP_CHECK)?; + if stop_on_spill && g0 - g1 > charge.body_regular() + G_BASE { + pools.regular(G_JUMPDEST)?; + return Ok(CalleeEnd::Returned); + } + pools.regular(LOOP_NEXT)?; + } + })() + .unwrap_or(CalleeEnd::Halted); + let (handed_back, kept) = match end { + CalleeEnd::Returned => (pools, minus(budget.given, budget.left)), + // The revert gives the charges back: what the reservoir paid to the share, what spilled + // to the regular gas it hands back. + CalleeEnd::Crossed(_) => { + (Pools::new(pools.regular + pools.spill, start.reservoir), LimitUsage::ZERO) + } + CalleeEnd::Halted => (Pools::new(0, start.reservoir), LimitUsage::ZERO), + }; + let (state, history) = if end == CalleeEnd::Returned { (state, history) } else { (0, 0) }; + CalleeModel { end, charges, at_end: pools, handed_back, state, history, kept } +} + +/* ---------- the caller ---------- */ + +/// The gas `A` forwards. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Forward { + Explicit(u64), + /// `GAS` as the call's gas, more than the cap: all but 2 per cent of what is left after the + /// call's cost. + All, +} + +impl Forward { + fn name(self) -> String { + match self { + Self::Explicit(gas) => gas.to_string(), + Self::All => "all but 2/100".into(), + } + } +} + +/// `A`'s code, writing `work` fresh slots after the call. +fn caller_code(forward: Forward, work: u64) -> Bytes { + let mut code = vec![GAS, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + code.extend(C); + match forward { + Forward::Explicit(gas) => { + code.push(PUSH4); + code.extend(u32::try_from(gas).expect("fits a PUSH4").to_be_bytes()); + } + Forward::All => code.push(GAS), + } + code.extend([CALL, GAS, PUSH4]); + code.extend(u32::try_from(work).expect("fits a PUSH4").to_be_bytes()); + // [gas0, ok, gas1, k]: while k != 0, `SSTORE(k, 1)` and k -= 1. + 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); + // Returns `gas0`, `ok` and `gas1`, a word each. + code.extend([JUMPDEST, POP, PUSH1, 0x40, MSTORE, PUSH1, 0x20, MSTORE, PUSH0, MSTORE]); + code.extend([PUSH1, 0x60, PUSH0, RETURN]); + code.into() +} + +/// `A`'s regular gas before the `SSTORE` of one fresh slot of its work: `JUMPDEST DUP1 ISZERO +/// PUSH2 JUMPI PUSH1 DUP2`. +const WORK_BEFORE: u64 = G_JUMPDEST + 5 * G_VERYLOW + G_JUMPI; +/// `A`'s regular gas after the `SSTORE`: `PUSH1 SWAP1 SUB PUSH2 JUMP`. +const WORK_AFTER: u64 = 4 * G_VERYLOW + G_JUMP; +/// The way out: the last `JUMPDEST DUP1 ISZERO PUSH2 JUMPI`, `JUMPDEST POP`, three `MSTORE`s with +/// their pushes and the expansion to three words, and `PUSH1 PUSH0 RETURN`. +const WORK_OUT: u64 = (G_JUMPDEST + 3 * G_VERYLOW + G_JUMPI) + + (G_JUMPDEST + G_BASE) + + (2 * (G_VERYLOW + G_VERYLOW) + G_BASE + G_VERYLOW + 3 * 3) + + (G_VERYLOW + G_BASE); + +/// How `A`'s work ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WorkEnd { + /// `A` returns, on these pools. + Completed(Pools), + /// A charge ran out of gas: the transaction halts. + OutOfGas, + /// A slot crossed one of `A`'s budgets: `A` reverts with the stop, on these pools. + Stopped(Stop, Pools), +} + +impl WorkEnd { + const fn completed(self) -> bool { + matches!(self, Self::Completed(_)) + } +} + +/// How `A`'s work of `slots` fresh slots, run on `pools` and `budget` after its second `GAS`, +/// ends. +fn model_work(slots: u64, mut pools: Pools, mut budget: Budget) -> WorkEnd { + let mut work = || -> Result { + pools.regular(G_VERYLOW)?; + for _ in 0..slots { + pools.regular(WORK_BEFORE)?; + if pools.regular <= SSTORE_SENTRY { + return Err(Halt); + } + pools.regular(G_SSTORE_SET_COLD)?; + pools.draw(slot_state_gas())?; + if let Err(stop) = budget.count(SLOT_COUNTS) { + return Ok(WorkEnd::Stopped(stop, pools)); + } + pools.draw(history(WRITE_RECORD_SIZE))?; + pools.regular(WORK_AFTER)?; + } + pools.regular(WORK_OUT)?; + Ok(WorkEnd::Completed(pools)) + }; + work().unwrap_or(WorkEnd::OutOfGas) +} + +/// The most fresh slots `A` completes on `pools` and `budget`. +fn capacity(pools: Pools, budget: Budget) -> u64 { + let bound = (pools.regular / G_SSTORE_SET_COLD).min(budget.left.state_growth); + let (mut fits, mut fails) = (0, bound + 1); + while fails - fits > 1 { + let mid = (fits + fails) / 2; + if model_work(mid, pools, budget).completed() { + fits = mid; + } else { + fails = mid; + } + } + fits +} + +/// One run: a gas limit, the gas `A` forwards and what `C` runs. +#[derive(Clone, Copy, Debug)] +struct Scenario { + gas_limit: u64, + forward: Forward, + callee: Callee, +} + +/// What the model says the run does. +#[derive(Clone, Copy, Debug)] +struct Prediction { + /// The reservoir once the body is paid: what `A` holds at its call. + reservoir_at_call: u64, + gas_before_call: u64, + regular_at_call: u64, + /// The regular gas and the reservoir the call hands `C`. + handed: Pools, + /// `C`'s budgets: 98/100 of what `A` has left, which is the transaction's limits less the + /// body. + budget: Budget, + callee: CalleeModel, + /// `A`'s pools once `C` returned, before its second `GAS`. + pools_after_return: Pools, + gas_after_call: u64, + pools_after_call: Pools, + /// `A`'s budgets once `C` returned. + budget_after_call: Budget, + /// `A`'s work: unless a run names it, the most fresh slots `A` completes after a callee that + /// spent exactly its forward of regular gas and charged the reservoir nothing. + work: u64, + /// The most fresh slots `A` could complete after the call as it happened. + capacity_after_call: u64, + /// How `A`'s work ends. + end: WorkEnd, +} + +fn predict(scenario: Scenario, work: Option) -> Prediction { + let Scenario { gas_limit, forward, callee } = scenario; + let mut pools = first_frame(gas_limit); + let reservoir_at_call = pools.reservoir; + pools.regular(G_BASE).unwrap(); + let gas_before_call = pools.regular; + let gas_operand = match forward { + Forward::Explicit(_) => G_VERYLOW, + Forward::All => G_BASE, + }; + pools.regular(5 * G_BASE + G_VERYLOW + gas_operand).unwrap(); + let regular_at_call = pools.regular; + pools.regular(G_CALL_COLD).unwrap(); + let cap = forward_cap(pools.regular); + let forward = match forward { + Forward::Explicit(gas) => gas.min(cap), + Forward::All => cap, + }; + let handed = pools.forward(forward); + let mut budget_after_call = Budget::first_frame(); + let budget = budget_after_call.child(); + let callee = model_callee(callee, handed, budget); + + // After a callee that burns its forward and charges the reservoir nothing. + let mut kept_by_a_single_pool = pools; + kept_by_a_single_pool.absorb(Pools::new(0, handed.reservoir), false); + kept_by_a_single_pool.regular(G_BASE).unwrap(); + let work = work.unwrap_or_else(|| capacity(kept_by_a_single_pool, budget_after_call)); + + pools.absorb(callee.handed_back, callee.end == CalleeEnd::Returned); + budget_after_call.merge(callee.kept); + let pools_after_return = pools; + pools.regular(G_BASE).unwrap(); + Prediction { + reservoir_at_call, + gas_before_call, + regular_at_call, + handed, + budget, + callee, + pools_after_return, + gas_after_call: pools.regular, + pools_after_call: pools, + budget_after_call, + work, + capacity_after_call: capacity(pools, budget_after_call), + end: model_work(work, pools, budget_after_call), + } +} + +/* ---------- the meter ---------- */ + +/// What `C`'s frame held when it returned to `A`. +#[derive(Clone, Debug)] +struct Returned { + result: InstructionResult, + output: Bytes, + pools: Pools, + history: i64, + state: i64, +} + +/// A frame's pools as an inspector reads them. +fn pools_of(gas: &revm::interpreter::Gas) -> Pools { + Pools { regular: gas.remaining(), reservoir: gas.reservoir(), spill: gas.state_gas_spilled() } +} + +/// Reads `A`'s `GAS` around the call, its pools at the call and after it, what the call hands +/// `C`, what a creation `C` makes is handed, the charges `C` starts and what its frame holds at +/// its return. +#[derive(Clone, Debug, Default)] +struct Meter { + charge: Option, + frames: usize, + gas_pending: bool, + gas_before_call: Option, + gas_after_call: Option, + at_call: Option, + handed: Option, + created_with: Option, + returned: Option, + after_return: Option, + charges: u64, +} + +impl Inspector, EthInterpreter> for Meter { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + let opcode = interp.bytecode.opcode(); + match self.frames { + 1 => { + if self.returned.is_some() && self.after_return.is_none() { + self.after_return = Some(pools_of(&interp.gas)); + } + if opcode == CALL && self.at_call.is_none() { + self.at_call = Some(pools_of(&interp.gas)); + } + self.gas_pending = opcode == GAS; + } + 2 if Some(opcode) == self.charge => self.charges += 1, + _ => {} + } + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if !core::mem::take(&mut self.gas_pending) { + return; + } + let gas = interp.stack.peek(0).expect("GAS pushed its answer").to::(); + if self.returned.is_some() { + self.gas_after_call.get_or_insert(gas); + } else { + self.gas_before_call.get_or_insert(gas); + } + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.frames += 1; + if inputs.target_address == C { + self.handed = Some(Pools::new(inputs.gas_limit, inputs.reservoir)); + } + None + } + + fn call_end( + &mut self, + _: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == C { + let gas = &outcome.result.gas; + self.returned = Some(Returned { + result: outcome.result.result, + output: outcome.result.output.clone(), + pools: pools_of(gas), + history: gas.history_gas_spent(), + state: gas.state_gas_spent(), + }); + } + self.frames -= 1; + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.frames += 1; + self.created_with = Some(Pools::new(inputs.gas_limit(), inputs.reservoir())); + None + } + + fn create_end(&mut self, _: &mut MegaContext, _: &CreateInputs, _: &mut CreateOutcome) { + self.frames -= 1; + } +} + +/* ---------- the run ---------- */ + +/// One run's measured figures. +#[derive(Clone, Debug)] +struct Measured { + scenario: Scenario, + prediction: Prediction, + gas_before_call: u64, + gas_after_call: u64, + reservoir_at_call: u64, + handed: Pools, + reservoir_after_call: u64, + callee: Returned, + charges: u64, + outcome: MegaTransactionOutcome, +} + +impl Measured { + fn forward(&self) -> u64 { + self.prediction.handed.regular + } + + /// The regular gas `C` spent of its forward, spills included: all of it when `C` halted. + fn callee_regular(&self) -> u64 { + if self.callee.result.is_halt() { + return self.forward(); + } + self.forward() - self.callee.pools.regular + } + + /// The reservoir `C` consumed: what `A` held at the call less what it holds after it. + fn consumed(&self) -> u64 { + self.reservoir_at_call - self.reservoir_after_call + } + + fn completed(&self) -> bool { + self.outcome.result.is_success() + } + + fn callee_end(&self) -> String { + match self.callee.result { + InstructionResult::Stop => "returned".into(), + InstructionResult::Revert => match decode_mega_limit_exceeded(&self.callee.output) { + Some((kind, limit)) => format!("reverted: {kind:?} stop at {limit}"), + None => "reverted".into(), + }, + other => format!("{other:?}"), + } + } + + fn status(&self) -> String { + status(&self.outcome) + } + + /// Whether `A`'s work needs the reservoir: it does not fit in `A`'s regular gas after the + /// call alone. + fn work_needs_reservoir(&self) -> bool { + needs_reservoir(self.prediction.work, self.gas_after_call) + } +} + +/// Whether `slots` fresh slots of `A`'s work run out of gas on `regular` gas alone, whatever the +/// budgets. +fn needs_reservoir(slots: u64, regular: u64) -> bool { + model_work(slots, Pools::new(regular, 0), Budget::unlimited()) == WorkEnd::OutOfGas +} + +fn status(outcome: &MegaTransactionOutcome) -> String { + match &outcome.result { + ExecutionResult::Success { .. } => "success".into(), + ExecutionResult::Revert { output, .. } => match decode_mega_limit_exceeded(output) { + Some((kind, limit)) => format!("revert: {kind:?} stop at {limit}"), + None => "revert".into(), + }, + ExecutionResult::Halt { reason, .. } => format!("halt: {reason:?}"), + } +} + +/// Runs `tx` on `db` under the meter, and again without it, and holds the two to the same +/// settlement. +#[track_caller] +fn execute_metered( + db: impl Fn() -> MemoryDatabase, + tx: impl Fn() -> MegaTransaction, + meter: Meter, + name: &str, +) -> (MegaTransactionOutcome, Meter) { + let mut evm = MegaEvm::new(context(db())).with_inspector(meter); + let outcome = evm.execute_transaction(tx()).expect("the transaction is valid"); + let meter = evm.inspector().clone(); + let plain = execute(db(), tx()); + assert_eq!(plain.result.is_success(), outcome.result.is_success(), "{name}: the inspector"); + assert_eq!(plain.gas, outcome.gas, "{name}: the ledgers under the inspector"); + assert_eq!(plain.usage, outcome.usage, "{name}: the usage under the inspector"); + (outcome, meter) +} + +/// Holds `outcome` to how the model says `A`'s work ends: `C` kept `callee`'s charges and counts +/// and `A`'s work its slots, or the transaction ended in a halt or a stop that kept neither. +#[track_caller] +fn assert_settled( + name: &str, + outcome: &MegaTransactionOutcome, + scenario: Scenario, + p: &Prediction, + callee: (u64, u64, LimitUsage), +) { + let (callee_state, callee_history, callee_kept) = callee; + let body = body_history(0); + let nothing_kept = |what: &str| { + assert_eq!( + outcome.gas.reservoir_remaining, p.reservoir_at_call, + "{name}: the reservoir comes back whole on {what}" + ); + assert_eq!(outcome.gas.history, body, "{name}: the body alone on {what}"); + assert_eq!(outcome.gas.state, 0, "{name}: no state on {what}"); + assert_eq!(outcome.usage, BODY_COUNTS, "{name}: the body's counts alone on {what}"); + }; + match p.end { + WorkEnd::Completed(left) => { + assert!( + outcome.result.is_success(), + "{name}: A's work completes: {:?}", + outcome.result + ); + assert_eq!( + outcome.gas.history, + body + callee_history + p.work * history(WRITE_RECORD_SIZE), + "{name}: the history ledger" + ); + assert_eq!( + outcome.gas.state, + callee_state + p.work * slot_state_gas(), + "{name}: the state ledger" + ); + assert_eq!( + outcome.gas.reservoir_remaining, left.reservoir, + "{name}: the reservoir left" + ); + assert_eq!( + outcome.gas.gas_used, + scenario.gas_limit - left.regular - left.reservoir, + "{name}: the receipt" + ); + let work_counts = LimitUsage { + data_size: p.work * WRITE_RECORD_SIZE, + write_records: p.work, + state_growth: p.work, + }; + assert_eq!( + outcome.usage, + plus(plus(BODY_COUNTS, callee_kept), work_counts), + "{name}: the counts" + ); + assert_eq!(outcome.limit_exceeded, None, "{name}: no stop"); + } + WorkEnd::OutOfGas => { + assert!( + matches!(outcome.result, ExecutionResult::Halt { .. }), + "{name}: A's work runs out of gas: {:?}", + outcome.result + ); + // The halt gives A's state and history back, C's merged charges included, and burns + // the regular gas: the receipt is the execution cap and the body. + nothing_kept("a halt"); + assert_eq!( + outcome.gas.gas_used, + scenario.gas_limit - p.reservoir_at_call, + "{name}: the receipt" + ); + } + WorkEnd::Stopped(stop, at) => { + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "{name}: A's work is stopped: {:?}", + outcome.result + ); + assert_eq!( + decode_mega_limit_exceeded(outcome.result.output().unwrap()), + Some((stop.kind, stop.limit)), + "{name}: the stop A reverts with" + ); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: stop.kind, + limit: stop.limit, + used: stop.used, + frame_local: true + }), + "{name}: the stop the outcome names" + ); + // The revert gives A's state and history back, C's merged charges included, the + // spill to the regular gas, which comes back to the sender with the reservoir. + nothing_kept("a stop"); + assert_eq!( + outcome.gas.gas_used, + scenario.gas_limit - p.reservoir_at_call - at.regular - at.spill, + "{name}: the receipt" + ); + } + } +} + +/// Runs `scenario` with and without the meter, holds both runs to the model, and returns what +/// the meter read. +#[track_caller] +fn run(scenario: Scenario) -> Measured { + run_with(scenario, None) +} + +/// [`run`], with `A` writing `work` fresh slots when it is named. +#[track_caller] +fn run_with(scenario: Scenario, work: Option) -> Measured { + let prediction = predict(scenario, work); + let name = format!( + "{} at a {} gas limit, forwarding {}", + scenario.callee.name(), + scenario.gas_limit, + scenario.forward.name() + ); + let db = || { + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10u64.pow(18))) + .account_code(A, caller_code(scenario.forward, prediction.work)) + .account_code(C, scenario.callee.code()) + }; + let tx = || call(SENDER, A, U256::ZERO, scenario.gas_limit); + + let meter = + Meter { charge: scenario.callee.charge().map(Charge::opcode), ..Default::default() }; + let (outcome, meter) = execute_metered(db, tx, meter, &name); + + let after_return = meter.after_return.expect("A resumed"); + let measured = Measured { + scenario, + prediction, + gas_before_call: meter.gas_before_call.expect("A read GAS before the call"), + gas_after_call: meter.gas_after_call.expect("A read GAS after the call"), + reservoir_at_call: meter.at_call.expect("A called").reservoir, + handed: meter.handed.expect("A called C"), + reservoir_after_call: after_return.reservoir, + callee: meter.returned.clone().expect("C returned"), + charges: meter.charges, + outcome, + }; + let p = &prediction; + + // The reservoir is the gas limit above the execution cap, less the body [S4.4]. + assert_eq!( + meter.at_call, + Some(Pools::new(p.regular_at_call, p.reservoir_at_call)), + "{name}: A's pools at the call" + ); + // `GAS` reads the regular budget, not the reservoir. + assert_eq!(measured.gas_before_call, p.gas_before_call, "{name}: A's GAS before the call"); + // A call forwards at most all but 2 per cent of the regular gas, and the child gets all but + // 2 per cent of the reservoir whatever the call asks for. + assert_eq!(measured.handed, p.handed, "{name}: what the call hands C"); + assert_eq!(measured.charges, p.callee.charges, "{name}: the charges C started"); + match p.callee.end { + CalleeEnd::Returned => { + assert_eq!(measured.callee.result, InstructionResult::Stop, "{name}: C returns"); + assert_eq!( + measured.callee.history, p.callee.history as i64, + "{name}: the history C charged" + ); + assert_eq!(measured.callee.state, p.callee.state as i64, "{name}: the state C charged"); + assert_eq!( + measured.callee.pools, p.callee.handed_back, + "{name}: the pools C hands back" + ); + } + CalleeEnd::Crossed(stop) => { + assert_eq!(measured.callee.result, InstructionResult::Revert, "{name}: C reverts"); + assert_eq!( + decode_mega_limit_exceeded(&measured.callee.output), + Some((stop.kind, stop.limit)), + "{name}: C's budget stopped it" + ); + // A frame's end shows its gas before the settlement: the history of every charge + // before the crossing one, which the caller's merge then gives back to the reservoir. + let charge = scenario.callee.charge().unwrap(); + let charged = (p.callee.charges - 1) * charge.history(); + assert_eq!(measured.callee.history, charged as i64, "{name}: the history C charged"); + assert_eq!(measured.callee.pools, p.callee.at_end, "{name}: C's pools at its end"); + } + CalleeEnd::Halted => { + assert_eq!(scenario.callee, Callee::Burn, "{name}: only INVALID halts C"); + assert_eq!( + measured.callee.result, + InstructionResult::InvalidFEOpcode, + "{name}: C halts" + ); + } + } + // What C hands back, its reservoir unwinding A's spill first, is what A holds after the call. + assert_eq!(after_return, p.pools_after_return, "{name}: A's pools after the call"); + assert_eq!(measured.gas_after_call, p.gas_after_call, "{name}: A's GAS after the call"); + + let callee = (p.callee.state, p.callee.history, p.callee.kept); + assert_settled(&name, &measured.outcome, scenario, p, callee); + if p.end.completed() { + let words: Vec = measured + .outcome + .result + .output() + .expect("A returns") + .chunks(32) + .map(U256::from_be_slice) + .collect(); + assert_eq!( + words, + [ + U256::from(p.gas_before_call), + U256::from(u64::from(p.callee.end == CalleeEnd::Returned)), + U256::from(p.gas_after_call) + ], + "{name}: A's GAS around the call and the call's flag, as A read them" + ); + } + measured +} + +/* ---------- the tables ---------- */ + +fn ratio(numerator: u64, denominator: u64) -> String { + format!("{:.2}", numerator as f64 / denominator as f64) +} + +fn print_table(title: &str, rows: &[Measured]) { + println!("\n### {title}\n"); + println!( + "| gas limit | C | forward | charges | C regular spent | C history charged | \ + C state charged | reservoir at call | reservoir to C | reservoir at return | consumed | \ + consumed / forward | (regular + consumed) / forward | A GAS before | A GAS after | \ + A work (slots) | work needs reservoir | A capacity after | C end | status | gas used |" + ); + println!("|{}", "---:|".repeat(21)); + for row in rows { + println!( + "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | \ + {} | {} | {} | {} | {} |", + row.scenario.gas_limit, + row.scenario.callee.name(), + row.forward(), + row.charges, + row.callee_regular(), + row.callee.history, + row.callee.state, + row.reservoir_at_call, + row.handed.reservoir, + row.reservoir_after_call, + row.consumed(), + ratio(row.consumed(), row.forward()), + ratio(row.callee_regular() + row.consumed(), row.forward()), + row.gas_before_call, + row.gas_after_call, + row.prediction.work, + if row.work_needs_reservoir() { "yes" } else { "no" }, + row.prediction.capacity_after_call, + row.callee_end(), + row.status(), + row.outcome.gas.gas_used, + ); + } +} + +/* ---------- the measurements ---------- */ + +/// One slot of `A`'s work, from both pools: its regular gas and its state and history. +fn slot_cost() -> u64 { + WORK_BEFORE + G_SSTORE_SET_COLD + WORK_AFTER + slot_state_gas() + history(WRITE_RECORD_SIZE) +} + +/// With a 400M gas limit and a forward of 1M, a callee that returns at once leaves `A` the whole +/// reservoir, and a callee that logs until its regular gas runs low charges ten times its forward +/// to its share of it. +/// +/// `A`'s work is the 1,000 slots the state-growth limit lets the transaction add, which `A`'s +/// regular gas pays for alone, so it completes after the log-heavy callee as after one that returns +/// at once, and the slot past it is the stop, kind 3, not an out-of-gas. A callee's charges still +/// reach `A`'s work where the callee spends both its shares: forwarding all, the greedy callee +/// leaves `A` the 2 per cent of its regular gas and of its reservoir that `A` kept, and the 329 +/// slots `A` completes after a callee that burns all it was forwarded run out of gas. +#[test] +fn test_a_log_heavy_callee_charges_past_its_forward_and_leaves_two_percent_of_each_pool() { + if runs_at_measurement_prices() { + return; + } + let scenario = + |callee| Scenario { gas_limit: 400_000_000, forward: Forward::Explicit(1_000_000), callee }; + let baseline = run(scenario(Callee::Stop)); + let heavy = run(scenario(Callee::stops_on_spill(Charge::Log0Data))); + // The work is what a callee that spends exactly its forward leaves room for, and no more. + let burns = run(scenario(Callee::Burn)); + let one_more = run_with(scenario(Callee::Burn), Some(burns.prediction.work + 1)); + print_table( + "1a. Baseline vs. a log-heavy callee (400M, forward 1M)", + &[baseline.clone(), heavy.clone(), burns.clone(), one_more.clone()], + ); + assert!(burns.completed(), "A's work completes after a callee that burns its forward"); + assert_eq!(burns.prediction.work, TX_STATE_GROWTH_LIMIT, "the state-growth limit binds it"); + assert_eq!( + decode_mega_limit_exceeded(one_more.outcome.result.output().unwrap()), + Some((LimitKind::StateGrowth, TX_STATE_GROWTH_LIMIT)), + "one slot more is the stop" + ); + + assert_eq!(baseline.consumed(), 0); + assert!(baseline.completed(), "A's work completes after a callee that charged nothing"); + // The Rex6 comparison in `mega-evme`'s tests runs this callee's bytes on the released + // engine, with these two numbers written out. + assert_eq!(Charge::Log0Data.body_regular() + G_BASE, 4_478, "the drop that stops C"); + assert_eq!(Charge::Log0Data.reserve(), 52_481, "the reserve C keeps"); + + assert!(heavy.callee_regular() <= heavy.forward(), "regular gas stays within the forward"); + assert!(heavy.reservoir_after_call > 0, "the forward ran out before the share"); + assert_eq!(heavy.consumed(), heavy.charges * Charge::Log0Data.history()); + assert!( + heavy.consumed() > 10 * heavy.forward(), + "the share pays ten times the forward: {}", + heavy.consumed() + ); + assert!( + heavy.callee_regular() + heavy.consumed() > heavy.forward() + slot_cost(), + "C charged more than its forward and one slot" + ); + assert!(!heavy.work_needs_reservoir(), "A's regular gas pays for the work alone"); + assert!(heavy.completed(), "so C's charges do not reach it"); + + // Forwarding all, after a callee that burns its forward and after one that spends both + // shares. + let all = |callee| Scenario { gas_limit: 400_000_000, forward: Forward::All, callee }; + let burns_all = run(all(Callee::Burn)); + let work = burns_all.prediction.work; + let greedy = run_with(all(Callee::greedy(Charge::Log0Data)), Some(work)); + print_table("1b. Forwarding all but 2/100 (400M)", &[burns_all.clone(), greedy.clone()]); + assert!(burns_all.completed()); + assert!(work < TX_STATE_GROWTH_LIMIT, "A's regular gas binds it: {work}"); + assert_eq!(greedy.callee.result, InstructionResult::Stop, "C returns"); + assert_eq!(greedy.callee.pools.reservoir, 0, "C spent its whole share"); + assert!(greedy.callee.pools.regular < Charge::Log0Data.reserve(), "and its forward"); + assert_eq!( + greedy.reservoir_after_call, + greedy.reservoir_at_call * 2 / 100, + "A keeps its 2 per cent of the reservoir" + ); + assert!( + greedy.callee_regular() + greedy.consumed() > greedy.forward() + slot_cost(), + "C charged more than its forward and one slot" + ); + assert!(!greedy.completed(), "the work A completes after a burned forward fails"); + assert_eq!(greedy.prediction.end, WorkEnd::OutOfGas, "out of gas"); +} + +/// The log-heavy callee at gas limits from 400M to 2B. A forward of 1M bounds it by its regular gas +/// at every limit: it consumes the same reservoir everywhere. Forwarding all but 2 per cent, it +/// consumes its whole share of the reservoir until the share outgrows what its 98/100 data-size +/// budget lets it log; from there its budget stops it first, it reverts, and its history comes back +/// to `A`. The threshold is exact: one gas less of reservoir and the share runs out first. +/// +/// The threshold is the gas limit whose share pays for the logs the budget holds, 1,353,400,537; +/// below it the callee leaves `A` its 2 per cent, and at 400M its share is just below its forward. +/// Either side of the threshold the 2 per cent `A` kept and the regular gas the callee left pay for +/// more than the 1,000 slots the state-growth limit lets `A` add, so that work, which needs the +/// reservoir, completes on both sides. +#[test] +fn test_the_frame_budget_binds_a_callee_once_the_reservoir_outgrows_it() { + if runs_at_measurement_prices() { + return; + } + let callee = Callee::stops_on_spill(Charge::Log0Data); + let at = |gas_limit, forward| run(Scenario { gas_limit, forward, callee }); + + let bounded: Vec<_> = + SWEEP.iter().map(|&limit| at(limit, Forward::Explicit(1_000_000))).collect(); + for row in &bounded { + assert_eq!(row.consumed(), bounded[0].consumed(), "the forward bounds what C logs"); + assert_eq!(row.callee.result, InstructionResult::Stop); + } + + // The budget stops the log that takes C past it, before its history is charged. The share + // pays every earlier log in full once it holds their history. + let budget = share(TX_DATA_LIMIT - TX_BODY_SIZE); + let kept = budget / Charge::Log0Data.bytes(); + let threshold = + TX_GAS_LIMIT_CAP + body_history(0) + reservoir_giving(kept * Charge::Log0Data.history()); + + let mut all: Vec<_> = SWEEP.iter().map(|&limit| at(limit, Forward::All)).collect(); + all.push(at(threshold - 1, Forward::All)); + all.push(at(threshold, Forward::All)); + all.sort_by_key(|row| row.scenario.gas_limit); + for row in &all { + assert_eq!(row.prediction.budget.given.data_size, budget, "C's data-size budget"); + if row.scenario.gas_limit < threshold { + assert_eq!(row.callee.result, InstructionResult::Stop, "C returns"); + assert_eq!(row.consumed(), row.handed.reservoir, "C consumed its whole share"); + assert_eq!( + row.reservoir_after_call, + row.reservoir_at_call * 2 / 100, + "A keeps its 2 per cent" + ); + assert_eq!( + row.consumed() > row.forward(), + row.scenario.gas_limit > 400_000_000, + "more than its forward, once its share outgrows A's regular gas" + ); + } else { + assert_eq!(row.charges, kept + 1, "the crossing log is the one past the budget"); + assert_eq!( + decode_mega_limit_exceeded(&row.callee.output), + Some((LimitKind::DataSize, budget)), + "C's budget stops it" + ); + assert_eq!(row.consumed(), 0, "C's history comes back to the reservoir"); + assert!(row.completed(), "A's work completes"); + } + } + assert!(1_200_000_000 < threshold && threshold <= 1_600_000_000, "{threshold}"); + + // `A`'s own work in those rows is bound by its regular gas, so it completes on either side. + // The most `A` may add needs the reservoir on both sides, and the reservoir `A` kept below the + // threshold pays for it. + let below = all.iter().find(|row| row.scenario.gas_limit == threshold - 1).unwrap(); + assert_eq!(below.prediction.capacity_after_call, TX_STATE_GROWTH_LIMIT); + let gas_alone = capacity(below.prediction.pools_after_call, Budget::unlimited()); + assert!(gas_alone > TX_STATE_GROWTH_LIMIT, "A's gas pays for more: {gas_alone}"); + let at_work = |gas_limit| { + run_with(Scenario { gas_limit, forward: Forward::All, callee }, Some(TX_STATE_GROWTH_LIMIT)) + }; + let below = at_work(threshold - 1); + let at_threshold = at_work(threshold); + assert!(below.work_needs_reservoir() && at_threshold.work_needs_reservoir()); + assert!(below.completed(), "the 2 per cent A kept pays for what its regular gas does not"); + assert!(at_threshold.completed(), "C's crossing gave the share back"); + + print_table("2a. Gas-limit sweep, forward 1M", &bounded); + print_table("2b. Gas-limit sweep, forward all but 2/100 (threshold rows included)", &all); + print_table( + "2c. Either side of the threshold, A's work needing the reservoir", + &[below, at_threshold], + ); + println!( + "\nC's data-size budget: {budget} bytes, {kept} logs; threshold gas limit {threshold}; \ + A's capacity below it on gas alone: {gas_alone} slots" + ); +} + +/// Without a reservoir every charge spills onto the callee's regular gas, so the forward bounds all +/// of it: the callee that stops on a spill logs once, the greedy one logs until its forward runs +/// low, and `A`'s work completes after either. At the execution cap that work is the 1,000 slots +/// the state-growth limit allows. +#[test] +fn test_without_a_reservoir_the_forward_bounds_every_charge() { + if runs_at_measurement_prices() { + return; + } + let mut rows = Vec::new(); + for gas_limit in [TX_GAS_LIMIT_CAP, 100_000_000] { + for callee in [Callee::stops_on_spill(Charge::Log0Data), Callee::greedy(Charge::Log0Data)] { + let row = run(Scenario { gas_limit, forward: Forward::Explicit(1_000_000), callee }); + assert_eq!(row.reservoir_at_call, 0); + assert_eq!(row.handed.reservoir, 0); + assert_eq!(row.consumed(), 0); + assert_eq!(row.callee.history, (row.charges * Charge::Log0Data.history()) as i64); + assert!( + row.callee.history as u64 <= row.callee_regular() && + row.callee_regular() + row.consumed() <= row.forward(), + "every charge C made, its history included, came out of its forward" + ); + assert!(row.completed(), "A's work completes"); + rows.push(row); + } + } + assert_eq!(rows[0].charges, 1, "the first log spills"); + assert!(rows[1].charges > 1, "the greedy callee logs until its forward runs low"); + assert_eq!(rows[0].prediction.work, TX_STATE_GROWTH_LIMIT, "the state-growth limit binds"); + assert!(rows[2].prediction.work < TX_STATE_GROWTH_LIMIT, "the gas binds"); + print_table("3. No reservoir (forward 1M)", &rows); +} + +/// The forwards of the forward-size tables. +fn forwards() -> [Forward; 4] { + [ + Forward::Explicit(100_000), + Forward::Explicit(1_000_000), + Forward::Explicit(10_000_000), + Forward::All, + ] +} + +/// One charge's callee, on the forwards from 100k to all but 2 per cent, at 400M. +#[track_caller] +fn forward_sizes(charge: Charge) -> Vec { + forwards() + .into_iter() + .map(|forward| { + run(Scenario { + gas_limit: 400_000_000, + forward, + callee: Callee::stops_on_spill(charge), + }) + }) + .collect() +} + +/// Holds the explicit forwards' rows: regular gas within the forward, and a reservoir consumed +/// past it that grows with it. +#[track_caller] +fn assert_past_the_forward(explicit: &[Measured]) { + for row in explicit { + assert!(row.callee_regular() <= row.forward(), "regular gas stays within the forward"); + assert!(row.consumed() > row.forward(), "the share pays more than the forward"); + } + assert!( + explicit.windows(2).all(|pair| pair[0].consumed() < pair[1].consumed()), + "the reservoir consumed grows with the forward" + ); +} + +/// The reservoir a log-heavy callee consumes against its forward, for `LOG0` with data and `LOG4` +/// without: past the forward at every explicit size, growing with it, and its whole share +/// forwarding all. +/// +/// Forwarding all, the callee consumes its share, which at 400M is 98/100 of a reservoir just below +/// `A`'s regular gas, so just under the forward, and `A` keeps its 2 per cent. +#[test] +fn test_the_reservoir_a_logging_callee_consumes_grows_with_its_forward() { + if runs_at_measurement_prices() { + return; + } + let log0 = forward_sizes(Charge::Log0Data); + let log4 = forward_sizes(Charge::Log4); + for rows in [&log0, &log4] { + let (all, explicit) = rows.split_last().unwrap(); + assert_past_the_forward(explicit); + assert!(all.consumed() > explicit.last().unwrap().consumed()); + assert_eq!(all.callee.result, InstructionResult::Stop, "C returns"); + assert_eq!(all.consumed(), all.handed.reservoir, "C consumes its whole share"); + assert_eq!(all.reservoir_after_call, all.reservoir_at_call * 2 / 100, "A keeps 2 per cent"); + assert!(all.consumed() < all.forward(), "just under the forward at 400M"); + } + print_table("4a. Forward sizes, LOG0 with 512 bytes of data (400M)", &log0); + print_table("4b. Forward sizes, LOG4 with no data (400M)", &log4); +} + +/// The same with fresh `SSTORE`s, whose state and history both draw the reservoir: past the forward +/// at every explicit size and growing with it, until the callee's state-growth budget, 98/100 of +/// the 1,000 new slots the transaction may add, stops it. +/// +/// Forwarding all, the callee's 981st slot crosses its budget of 980 before the share runs out: it +/// reverts, and its charges and the share come back to `A`, which consumes nothing of the +/// reservoir. The slots the callee keeps at an explicit forward come out of the 1,000 too, so `A`'s +/// 1,000 are stopped by the limit after them. +#[test] +fn test_a_writing_callees_state_growth_budget_stops_it_before_its_share_runs_out() { + if runs_at_measurement_prices() { + return; + } + let rows = forward_sizes(Charge::FreshSlot); + let (all, explicit) = rows.split_last().unwrap(); + assert_past_the_forward(explicit); + for row in explicit { + assert_eq!( + row.consumed(), + row.charges * (Charge::FreshSlot.state() + Charge::FreshSlot.history()) + ); + assert_eq!( + row.prediction.budget_after_call.left.state_growth, + TX_STATE_GROWTH_LIMIT - row.charges, + "C's slots come out of A's" + ); + } + let growth = share(TX_STATE_GROWTH_LIMIT); + assert_eq!(all.prediction.budget.given.state_growth, growth); + assert!( + all.handed.reservoir > (growth + 1) * (slot_state_gas() + history(WRITE_RECORD_SIZE)), + "the share would pay for the slot past the budget" + ); + assert_eq!(all.charges, growth + 1, "the crossing slot is the one past the budget"); + assert_eq!( + decode_mega_limit_exceeded(&all.callee.output), + Some((LimitKind::StateGrowth, growth)), + "C's state-growth budget stops it" + ); + assert_eq!(all.consumed(), 0, "C's charges and its share come back to A"); + assert!(all.completed(), "A's work completes"); + print_table("5. Forward sizes, fresh SSTOREs (400M)", &rows); +} + +/* ---------- a callee that deploys code ---------- */ + +/// A callee that `CREATE`s a contract of `size` zero bytes, from the init code +/// `PUSH3 size PUSH0 RETURN`, then stops. +fn deploying(size: u64) -> Bytes { + assert!(size < 1 << 24, "{size} fits a PUSH3"); + let [_, high, middle, low] = (size as u32).to_be_bytes(); + let mut code = vec![PUSH6, PUSH3, high, middle, low, PUSH0, RETURN]; + // The init code lands right-aligned in the first word: bytes 26 to 31. + code.extend([PUSH0, MSTORE, PUSH1, 6, PUSH1, 26, PUSH0, CREATE, POP, STOP]); + code.into() +} + +/// The history of a creation's two write records: the created account and the creator's nonce. +fn creation_records_history() -> u64 { + history(2 * WRITE_RECORD_SIZE) +} + +/// What the creation pays for depositing `size` bytes: each byte's state and history gas. +fn deposit_charges(size: u64) -> u64 { + size * COST_PER_STATE_BYTE + history(size) +} + +/// What the reservoir pays for a creation that deposits `size` bytes: the created account's +/// state gas and the history of its two write records, which its creator pays at the start, and +/// the deposit. +fn deployment_charges(size: u64) -> u64 { + account_state_gas() + creation_records_history() + deposit_charges(size) +} + +/// What a creation that deposits `size` bytes counts: its two records with their bytes, the +/// created account, and the code's bytes. +const fn deployment_counts(size: u64) -> LimitUsage { + LimitUsage { data_size: 2 * WRITE_RECORD_SIZE + size, write_records: 2, state_growth: 1 } +} + +/// A code deposit charges each byte 1,530 state gas and 88 history gas against a few regular gas of +/// memory and hashing, so a callee that deploys code draws hundreds to thousands of times its +/// forward from the reservoir: 96 KiB on a forward of 100,000 and on one of 1,000,000, which +/// consume the same, and the largest contract on a forward of 1,000,000. +/// +/// `C`'s regular gas is not modelled here: the reservoir it consumes is held to the schedule, its +/// regular gas to its forward, and `A`'s work, sized as in the other measurements, to the pools and +/// the budgets the call left it. +/// +/// The creation's start charges `C` the account and the records and hands the creation all but 2 +/// per cent of what that leaves of `C`'s share, which pays the deposit. `A`'s work is the 1,000 +/// slots the state-growth limit allows, and it fails on that limit, the created account having +/// taken one of them, not on gas: the 999 slots the limit leaves `A` fit in its regular gas alone. +#[test] +fn test_a_deploying_callee_charges_the_reservoir_hundreds_of_times_its_forward() { + if runs_at_measurement_prices() { + return; + } + println!("\n### 7. A callee that deploys code\n"); + println!( + "| gas limit | forward | code size | C regular spent | reservoir at call | \ + reservoir to C | reservoir to the creation | reservoir at return | consumed | \ + consumed / forward | A GAS after | A work (slots) | A capacity after | \ + work needs reservoir | status | gas used |" + ); + println!("|{}", "---:|".repeat(16)); + for (gas_limit, forward, size) in [ + (400_000_000, 100_000, 96 * 1024), + (400_000_000, 1_000_000, 96 * 1024), + (1_200_000_000, 1_000_000, MAX_CONTRACT_SIZE as u64), + ] { + let name = format!("{size} bytes at a {gas_limit} gas limit, forwarding {forward}"); + // `A` runs as it does before a callee that returns at once. + let scenario = + Scenario { gas_limit, forward: Forward::Explicit(forward), callee: Callee::Stop }; + let p = predict(scenario, None); + let db = || { + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10u64.pow(18))) + .account_code(A, caller_code(Forward::Explicit(forward), p.work)) + .account_code(C, deploying(size)) + }; + let tx = || call(SENDER, A, U256::ZERO, gas_limit); + let (outcome, meter) = execute_metered(db, tx, Meter::default(), &name); + + assert_eq!(meter.gas_before_call, Some(p.gas_before_call), "{name}: A's GAS before"); + assert_eq!(meter.handed, Some(p.handed), "{name}: what the call hands C"); + let created_with = meter.created_with.expect("C created"); + assert_eq!( + created_with.reservoir, + reservoir_share(p.handed.reservoir - account_state_gas() - creation_records_history()), + "{name}: the creation's share" + ); + assert!(deposit_charges(size) <= created_with.reservoir, "{name}: the share pays it"); + let returned = meter.returned.clone().expect("C returned"); + assert_eq!(returned.result, InstructionResult::Stop, "{name}: C returns"); + let callee_regular = forward - returned.pools.regular; + assert!(callee_regular <= forward, "{name}: regular gas stays within the forward"); + let after = meter.after_return.expect("A resumed"); + let consumed = p.reservoir_at_call - after.reservoir; + assert_eq!(consumed, deployment_charges(size), "{name}: the reservoir paid the deployment"); + assert!(consumed > 100 * forward, "{name}: a hundred times the forward: {consumed}"); + + let mut after_gas = after; + after_gas.regular(G_BASE).unwrap(); + assert_eq!(meter.gas_after_call, Some(after_gas.regular), "{name}: A's GAS after"); + let mut budget = Budget::first_frame(); + budget.merge(deployment_counts(size)); + let left = capacity(after_gas, budget); + assert_eq!(p.work, TX_STATE_GROWTH_LIMIT, "{name}: the state-growth limit binds the work"); + assert_eq!(left, TX_STATE_GROWTH_LIMIT - 1, "{name}: the created account took one"); + assert!(!needs_reservoir(left, after_gas.regular), "{name}: A's regular gas pays for it"); + let end = model_work(p.work, after_gas, budget); + assert!( + matches!(end, WorkEnd::Stopped(Stop { kind: LimitKind::StateGrowth, .. }, _)), + "{name}: A's work is stopped on the state-growth limit: {end:?}" + ); + let callee = ( + account_state_gas() + size * COST_PER_STATE_BYTE, + creation_records_history() + history(size), + deployment_counts(size), + ); + assert_settled(&name, &outcome, scenario, &Prediction { end, ..p }, callee); + + let status = status(&outcome); + println!( + "| {gas_limit} | {forward} | {size} | {callee_regular} | {} | {} | {} | {} | \ + {consumed} | {} | {} | {} | {left} | {} | {status} | {} |", + p.reservoir_at_call, + p.handed.reservoir, + created_with.reservoir, + after.reservoir, + ratio(consumed, forward), + after_gas.regular, + p.work, + if needs_reservoir(p.work, after_gas.regular) { "yes" } else { "no" }, + outcome.gas.gas_used, + ); + } +} diff --git a/crates/mega-evm/tests/satin/reservoir_share.rs b/crates/mega-evm/tests/satin/reservoir_share.rs new file mode 100644 index 000000000..0ebf30c3d --- /dev/null +++ b/crates/mega-evm/tests/satin/reservoir_share.rs @@ -0,0 +1,200 @@ +//! The reservoir a frame starts with: the transaction's own frame and a system call's outermost +//! frame take the whole of it, and every child of `CALL`, `CALLCODE`, `DELEGATECALL`, +//! `STATICCALL`, `CREATE` or `CREATE2` takes `remaining − remaining × 2 / 100` of what its caller +//! has left after every charge it made for the start, the history of the start's records +//! included, whatever regular gas the caller asks to forward. The caller keeps the rest while the +//! child runs, and the child's return adds what it left back. +//! +//! An inspector reads the reservoir each start hands its frame off the frame's input, which is +//! where revm puts the share it took out of the caller. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, PUSH0, PUSH1, PUSH20, STOP}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + }, + Database, Inspector, +}; + +use crate::common::{ + body_history, call, context, history, reservoir_share, runs_at_measurement_prices, +}; + +const SENDER: Address = address!("0000000000000000000000000000000000720000"); +const A: Address = address!("0000000000000000000000000000000000720001"); +const B: Address = address!("0000000000000000000000000000000000720002"); +const C: Address = address!("0000000000000000000000000000000000720003"); + +/// The gas a transaction carries above the execution cap: its reservoir before the body is paid. +const ABOVE_THE_CAP: u64 = 10_000_000; + +/// Records the reservoir every frame start hands its frame, in the order the starts are made. +#[derive(Default)] +struct Shares { + reservoirs: Vec, + gas_limits: Vec, +} + +impl Inspector, EthInterpreter> for Shares { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.reservoirs.push(inputs.reservoir); + self.gas_limits.push(inputs.gas_limit); + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.reservoirs.push(inputs.reservoir()); + self.gas_limits.push(inputs.gas_limit()); + None + } +} + +/// `A` calls `B`, which calls `C`, each with all its gas and no value. +fn chain() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_code(A, BytecodeBuilder::default().call(B, U256::ZERO).stop().build()) + .account_code(B, BytecodeBuilder::default().call(C, U256::ZERO).stop().build()) + .account_code(C, Bytes::from_static(&[STOP])) +} + +/// The reservoir the transaction's own frame starts with: what the gas limit carries above the +/// execution cap, less the history of the body, which the reservoir pays first. +fn first_frame_reservoir() -> u64 { + ABOVE_THE_CAP - body_history(0) +} + +/// The transaction's own frame takes the whole reservoir; a child takes all but its caller's 2 per +/// cent, and a grandchild all but 2 per cent of what the child has left. Nothing spends any of it, +/// so it all comes back, and the transaction is reimbursed the whole. +#[test] +fn test_a_child_takes_the_reservoir_less_its_callers_two_percent_at_every_depth() { + let mut evm = MegaEvm::new(context(chain())).with_inspector(Shares::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, TX_GAS_LIMIT_CAP + ABOVE_THE_CAP)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + let whole = first_frame_reservoir(); + let child = reservoir_share(whole); + let grandchild = reservoir_share(child); + assert_eq!(evm.inspector().reservoirs, [whole, child, grandchild]); + assert!(whole * 2 / 100 > 0, "the caller keeps a part of this reservoir"); + assert_eq!(outcome.gas.reservoir_remaining, whole, "every share came back"); +} + +/// `A` calls `B` asking for one unit of regular gas, carrying `value`. +fn asking_for_one(value: u8) -> MemoryDatabase { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, PUSH20]) + .append_many(B.into_array()) + .append_many([PUSH1, 1, CALL]) + .stop() + .build(); + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(A, U256::from(1)) + .account_code(A, code) + .account_code(B, Bytes::from_static(&[STOP])) +} + +/// The regular gas a call asks to forward does not bound the reservoir it hands its frame: a call +/// asking for one unit of gas still hands it the share. A call that moves value hands it the +/// share of what the history of the start's records left the caller — the two accounts the +/// transfer changes — and the stipend joins the forward. +#[test] +fn test_the_regular_gas_a_call_asks_for_does_not_bound_the_reservoir_it_forwards() { + let whole = first_frame_reservoir(); + for (value, gas_limit, records) in [(0, 1, 0), (1, 1 + 2_300, 2)] { + let mut evm = + MegaEvm::new(context(asking_for_one(value))).with_inspector(Shares::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, TX_GAS_LIMIT_CAP + ABOVE_THE_CAP)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "value {value}: {:?}", outcome.result); + let left = whole - history(WRITE_RECORD_SIZE * records); + let shares = evm.inspector(); + assert_eq!(shares.reservoirs, [whole, reservoir_share(left)], "value {value}"); + assert_eq!(shares.gas_limits[1], gas_limit, "value {value}"); + } +} + +/// A system call's outermost frame takes the whole reservoir the split leaves it, and the frame it +/// starts takes the share of it: the protocol's own work is exempt from the limits, not from the +/// split. +#[test] +fn test_a_system_calls_outermost_frame_takes_the_whole_reservoir_and_its_child_the_share() { + use revm::{handler::system_call::SYSTEM_CALL_GAS_LIMIT, InspectSystemCallEvm}; + let mut evm = MegaEvm::new(context(chain())).with_inspector(Shares::default()); + let result = InspectSystemCallEvm::inspect_one_system_call_with_caller( + &mut evm, + SENDER, + A, + Bytes::new(), + ) + .expect("the system call runs"); + assert!(result.is_success(), "{result:?}"); + let whole = SYSTEM_CALL_GAS_LIMIT - mega_evm::SYSTEM_CALL_REGULAR_GAS_LIMIT; + let child = reservoir_share(whole); + assert_eq!(evm.inspector().reservoirs, [whole, child, reservoir_share(child)]); + assert_eq!(evm.ctx().additional_limit().reservoir_remaining(), whole, "it all came back"); +} + +/// The figures above at the spec's numbers: a 10,000,000 margin pays the body's 27,280 of history, +/// and the frames take 9,972,720, 9,773,266 and 9,577,801. +#[test] +fn test_the_shares_at_the_specs_numbers() { + if runs_at_measurement_prices() { + return; + } + let whole = first_frame_reservoir(); + assert_eq!(whole, 9_972_720); + assert_eq!(reservoir_share(whole), 9_773_266); + assert_eq!(reservoir_share(reservoir_share(whole)), 9_577_801); +} + +/// The neutral configuration runs the fixture fork's schedule, which forwards the whole reservoir +/// to every child, as Ethereum's Amsterdam does; `no_limits()` on Satin's own configuration takes +/// out the limits and leaves the share as it is. +#[test] +fn test_the_neutral_configuration_forwards_the_whole_reservoir_and_no_limits_keeps_the_share() { + use mega_evm::{ + test_utils::{neutral_cfg, neutralize_evm, zero_fee_l1_block_info}, + EthSpecId, EvmTxRuntimeLimits, MegaSpecId, + }; + let gas_limit = TX_GAS_LIMIT_CAP + ABOVE_THE_CAP; + + let ctx = MegaContext::new(chain(), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(EthSpecId::AMSTERDAM).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(crate::common::block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx).with_inspector(Shares::default()); + neutralize_evm(&mut evm, EthSpecId::AMSTERDAM).expect("a neutral fork"); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let [first, child, grandchild] = evm.inspector().reservoirs[..] else { + panic!("three frames: {:?}", evm.inspector().reservoirs) + }; + assert_eq!((child, grandchild), (first, first), "the whole reservoir, at every depth"); + + let ctx = context(chain()).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(ctx).with_inspector(Shares::default()); + evm.execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + let whole = first_frame_reservoir(); + let child = reservoir_share(whole); + assert_eq!(evm.inspector().reservoirs, [whole, child, reservoir_share(child)]); +} diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index f7e3511d0..690414e18 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -323,7 +323,8 @@ fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { /// A `SELFDESTRUCT` moving a balance to an account that does not exist adds that account's leaf, /// and the beneficiary's own bucket prices it — the same entry and the same site a value `CALL` /// pays, reached from the opcode that empties an account rather than the one that funds it. The -/// history is the body and the beneficiary's record. +/// history is the body and the destruction's two records, the beneficiary's and that of the +/// account it clears. /// /// Rules: [S6.4], [S6.5], [S7.2]. #[test] @@ -331,7 +332,7 @@ fn test_the_selfdestruct_beneficiary_charge_scales_with_the_beneficiary_s_bucket assert_scales( "SELFDESTRUCT to a new account", entry(GasId::new_account_state_gas()), - TX_BODY_SIZE + WRITE_RECORD_SIZE, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, |envs, m| crowded_account(envs, EMPTY, m), || (db(selfdestruct_to(EMPTY).build()), call_contract()), ); diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 0d6bad039..4eadc4e9a 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -4,7 +4,7 @@ //! //! One shape names the charge and asks the hook for its price again: the same opcode taking its //! own write back (`SSTORE` 0 -> x -> 0), the upfront charge a caller made for a call or a -//! creation that did not add the leaf after all, the transaction-level refund, and the +//! creation that did not add the leaf after all, the transaction-level refund, and revm's //! settlement of a frame result built without running a frame. Because the site is re-priced //! through the one hook, and because the multiplier of a bucket is read once per transaction, //! the refill is the charge — a bucket cannot be read at one capacity for the charge and another @@ -23,19 +23,21 @@ use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ - settle_frame_result, synthetic_frame_result, + synthetic_frame_result, test_utils::{BytecodeBuilder, MemoryDatabase}, MegaTransaction, }; use revm::{ bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, + context::result::EVMError, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, Host, }, + handler::EthFrame, interpreter::{ - CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - InstructionResult, + interpreter::EthInterpreter, CallInput, CallInputs, CallScheme, CallValue, CreateInputs, + CreateScheme, FrameInput, InstructionResult, }, }; @@ -389,8 +391,9 @@ struct Settled { } /// Charges `charge` through the pricing hook of a context reading `envs`, hands the frame the -/// reservoir the caller has left, and settles a synthetic failure for it through the public -/// helper — the route a mechanism takes when it answers a frame rather than running it. +/// reservoir the caller has left, and settles a synthetic failure for it into the caller through +/// revm's own frame return — the route a result takes when a mechanism answers a frame rather +/// than running it. fn settle_a_synthetic_failure( envs: &SaltEnvs, reservoir: u64, @@ -404,16 +407,18 @@ fn settle_a_synthetic_failure( assert!(caller.record_state_cost(price), "the caller can pay the crowded charge"); let spilled = caller.state_gas_spilled(); - let mut result = - synthetic_frame_result(&input(caller.reservoir()), InstructionResult::Revert, Bytes::new()); - settle_frame_result::<_, revm::context::result::EVMError>( - &mut ctx, - &mut caller, - &mut result, - ) - .expect("the refund is priced through the same hook"); - - Settled { caller, price, spilled } + // The calling opcode hands the frame the reservoir its charge left, taken out of the caller, + // whose return adds what the frame gives back to what the caller kept. + let share = caller.reservoir(); + caller.forward_reservoir(share); + let result = synthetic_frame_result(&input(share), InstructionResult::Revert, Bytes::new()); + let mut frame = EthFrame::::default(); + *frame.interpreter.gas.tracker_mut() = caller; + frame + .return_result::<_, EVMError>(&mut ctx, result) + .expect("the refund is priced through the same hook"); + + Settled { caller: *frame.interpreter.gas.tracker(), price, spilled } } /// The inputs of a `CALL` whose calling opcode charged the caller for the account it would add. @@ -431,6 +436,9 @@ fn charged_call_input(reservoir: u64) -> FrameInput { is_static: false, reservoir, charged_new_account_state_gas: true, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, })) } @@ -467,7 +475,7 @@ fn assert_restores_both_pools(site: &str, envs: &SaltEnvs, reservoir: u64, settl ); } -/// A synthetic `CALL` failure settled through the public helper gives back a SALT-priced upfront +/// A synthetic `CALL` failure settled into its caller gives back a SALT-priced upfront /// charge, both when the reservoir paid for it and when it spilled onto regular gas. #[test] fn test_a_synthetic_call_failure_refunds_the_crowded_upfront_charge() { @@ -573,7 +581,7 @@ fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { return; } // The deposit's price on top of the rest, below the execution cap as every probe here runs: - // forwarded 63/64 of it, the creation runs its init code and falls short of the deposit. + // forwarded 98/100 of it, the creation runs its init code and falls short of the deposit. let gas_limit = (without_the_deposit + deposit).min(GAS_LIMIT); let envs = crowd(minimal_envs()); @@ -611,11 +619,13 @@ fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { /// A `CREATE` whose init code `SELFDESTRUCT`s the account it is creating, in the same transaction. /// /// EIP-8037's gas refills for `SELFDESTRUCT` say that destruction leaves the account, its code -/// and its storage out of the trie, and still produces no state-gas refill and no change to the -/// state gas the transaction has spent. The created-account charge therefore stands, priced in -/// the created address's bucket, at the minimum multiplier and above it. +/// and its storage out of the trie, and produces no state-gas refill. Satin's destruction table +/// gives back the parts the transaction made: the account was absent at the transaction's start, +/// so its leaf's state gas comes back to the destroying frame at the price it was charged, priced +/// in the created address's bucket, and the transaction keeps none, at the minimum multiplier and +/// above it. #[test] -fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state_gas() { +fn test_a_created_account_selfdestructed_in_the_same_transaction_gives_its_state_gas_back() { // A charge that costs nothing is the same number whether or not it is given back. if state_is_free() { return; @@ -624,7 +634,6 @@ fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state // is that account, which the creation itself just added, so no second account is charged. let init = selfdestruct_to_self(); let created = CONTRACT.create(0); - let account = entry(GasId::create_state_gas()); assert_eq!( net_state_at( @@ -632,14 +641,17 @@ fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state move |envs, m| crowded_account(envs, created, m), || (db(create_with(&init).stop().build()), call_contract()), ), - [account, account * 2, account * 8], - "the created account's state gas is not refilled", + [0, 0, 0], + "the created account's state gas comes back at the price it was charged", ); - let outcome = run( - db(create_with(&init).stop().build()), - crowded_account(minimal_envs(), created, 8), - call_contract(), + let envs = crowded_account(minimal_envs(), created, 8); + let outcome = run(db(create_with(&init).stop().build()), envs.clone(), call_contract()); + assert_eq!(outcome.gas.state, 0); + assert_eq!( + envs.bucket_queries(account_bucket(created)), + 1, + "one capacity read priced both the charge and the give-back", ); assert!( outcome.state.get(&created).is_some_and(|account| account.is_selfdestructed()), @@ -647,6 +659,64 @@ fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state ); } +/// A contract created in the transaction and destroyed by a later call gives back every state +/// charge the transaction made for it, each at the price it was charged in its own bucket: the +/// account leaf, the slot its init code wrote and the code it deposited, the leaf and the code in +/// the account's bucket and the slot in the slot's. The transaction keeps none of them, at the +/// minimum multiplier and above it, with either bucket crowded, and each bucket is read once. +#[test] +fn test_a_contract_destroyed_after_its_creation_gives_back_its_leaf_slot_and_code() { + use revm::bytecode::opcode::{ADDRESS, DUP6, GAS, POP, SELFDESTRUCT}; + if state_is_free() { + return; + } + let init = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .return_with_data([ADDRESS, SELFDESTRUCT]) + .build(); + let created = CONTRACT.create(0); + // The creation leaves the created address on the stack, and a call to it destroys it. + let code = || { + create_with(&init) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, DUP6, GAS, CALL, POP, POP]) + .stop() + .build() + }; + type Crowd = fn(SaltEnvs, Address, u64) -> SaltEnvs; + let crowds: [(&str, Crowd); 2] = [ + ("the account's bucket", crowded_account), + ("the slot's bucket", |envs, address, m| crowded_slot(envs, address, U256::from(SLOT), m)), + ]; + for (crowded, crowd) in crowds { + assert_eq!( + net_state_at( + [1, 2, 8], + move |envs, m| crowd(envs, created, m), + || { (db(code()), call_contract()) } + ), + [0, 0, 0], + "{crowded}: every part comes back at the price it was charged", + ); + } + + let envs = + crowded_slot(crowded_account(minimal_envs(), created, 8), created, U256::from(SLOT), 8); + let outcome = run(db(code()), envs.clone(), call_contract()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.state[&created].is_selfdestructed(), "the call destroyed the contract"); + assert_eq!(outcome.gas.state, 0); + for (bucket, read) in [ + (account_bucket(created), "the account's"), + (slot_bucket(created, U256::from(SLOT)), "the slot's"), + ] { + assert_eq!( + envs.bucket_queries(bucket), + 1, + "{read} bucket priced its charges and give-backs" + ); + } +} + /// Init code that self-destructs the account being created: `ADDRESS SELFDESTRUCT`. fn selfdestruct_to_self() -> Vec { use revm::bytecode::opcode::{ADDRESS, SELFDESTRUCT}; diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 9f5dd5078..4f1bf0d6f 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -29,15 +29,15 @@ const CALLER: Address = address!("0000000000000000000000000000000000900000"); const CALLEE: Address = address!("0000000000000000000000000000000000900001"); /// 1,000,000 of regular gas on top of what the transactions here add at the byte prices in effect: -/// a new account and a fresh slot, a kilobyte of history, and 64 times the history of two records, -/// which a `CREATE` that forwards all but a 64th of its gas pays for the frame it starts from the -/// 64th it keeps. +/// a new account and a fresh slot, a kilobyte of history, and 50 times the history of two records, +/// which a `CREATE` that forwards all but 2 per cent of its gas pays for the frame it starts from +/// the fiftieth it keeps. fn gas_limit() -> u64 { 1_000_000 + account_state_gas() + slot_state_gas() + history(1_000) + - 64 * history(2 * mega_evm::WRITE_RECORD_SIZE) + 50 * history(2 * mega_evm::WRITE_RECORD_SIZE) } /// The gas a transaction used, the state gas inside it, the history gas the schedule does not diff --git a/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap b/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap index 6c7df5b53..9cc802228 100644 --- a/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap +++ b/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap @@ -56,7 +56,7 @@ expression: gas "selfdestruct_created_in_same_tx_to_existing_account": [ { "outcome": "success", - "gas_used": 372085 + "gas_used": 184965 } ], "sstore_set_spills": [ diff --git a/crates/mega-evm/tests/satin/spec_numbers.rs b/crates/mega-evm/tests/satin/spec_numbers.rs index 38551315b..774c3bf30 100644 --- a/crates/mega-evm/tests/satin/spec_numbers.rs +++ b/crates/mega-evm/tests/satin/spec_numbers.rs @@ -10,7 +10,8 @@ use mega_evm::{ constants::{ ACCOUNT_STATE_GAS, BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, MAX_TX_COMPUTE_GAS, - ORACLE_ACCESS_COMPUTE_GAS, SLOT_STATE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, + ORACLE_ACCESS_COMPUTE_GAS, PRE_BLOCK_CALL_GAS_LIMIT, SLOT_STATE_GAS, TX_DATA_LIMIT, + TX_GAS_LIMIT_CAP, TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, }, kzg_point_evaluation, op_revm::precompiles::{ @@ -23,7 +24,6 @@ use mega_evm::{ revm::{ bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}, context_interface::cfg::{gas::WARM_STORAGE_READ_COST, GasId, GasParams}, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, interpreter::instructions::gas_table_spec, precompile::secp256r1::{P256VERIFY_BASE_GAS_FEE_OSAKA, P256VERIFY_OSAKA}, primitives::{ @@ -44,10 +44,10 @@ use mega_evm::{ }, LimitKind, MegaSpecId, ProtocolLimits, SatinPrices, VolatileDataAccess, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, - FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, HISTORY_GAS_PRICED, LOG_BASE_SIZE, - LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, - SYSTEM_ADDRESS, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, - WRITE_RECORD_SIZE, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, HISTORY_ALLOWANCE_BYTES, + HISTORY_GAS_PRICED, LOG_BASE_SIZE, LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, STATE_GAS_REPRICED, + SYSTEM_ADDRESS, SYSTEM_CALL_REGULAR_GAS_LIMIT, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, + TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, }; const SATIN_MD: &str = include_str!("../../../../docs/spec/upgrades/satin.md"); @@ -80,7 +80,7 @@ fn named_constants(doc: &str) { require_eq(doc, "AUTHORIZATION_SIZE", AUTHORIZATION_SIZE); require_eq(doc, "WRITE_RECORD_SIZE", WRITE_RECORD_SIZE); require_eq(doc, "TRANSFER_LOG_SIZE", TRANSFER_LOG_SIZE); - require_eq(doc, "HISTORY_ALLOWANCE_BYTES", STORAGE_CALL_STIPEND_BYTES); + require_eq(doc, "HISTORY_ALLOWANCE_BYTES", HISTORY_ALLOWANCE_BYTES); require_eq(doc, "MIN_BUCKET_SIZE", MIN_BUCKET_SIZE as u64); require_eq(doc, "KEYLESS_DEPLOY_OVERHEAD_GAS", KEYLESS_DEPLOY_OVERHEAD_GAS); require_eq(doc, "BLOCK_ENV_ACCESS_COMPUTE_GAS", BLOCK_ENV_ACCESS_COMPUTE_GAS); @@ -96,29 +96,21 @@ fn named_constants(doc: &str) { grouped(LOG_TOPIC_SIZE) ), ); - require(doc, &format!("({} gas)", grouped(STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE))); + require(doc, &format!("({} gas)", grouped(HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE))); require(doc, &format!("capped at {} per transaction", grouped(TX_GAS_LIMIT_CAP))); require(doc, &format!("at most {} of regular gas", grouped(SYSTEM_CALL_REGULAR_GAS_LIMIT))); - require(doc, &format!("max(block_gas_limit, {})", grouped(SYSTEM_CALL_REGULAR_GAS_LIMIT))); - require(doc, &format!("A {}-byte allowance", STORAGE_CALL_STIPEND_BYTES)); + require_eq(doc, "PRE_BLOCK_CALL_GAS_LIMIT", PRE_BLOCK_CALL_GAS_LIMIT); require( doc, &format!( - "`FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR` = {}/{}", - FRAME_DATA_SHARE_NUMERATOR, FRAME_DATA_SHARE_DENOMINATOR + "a reservoir of {}, the state gas of sixteen fresh storage slots", + grouped(PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT) ), ); + require(doc, &format!("A {}-byte allowance", HISTORY_ALLOWANCE_BYTES)); + require_eq(doc, "FRAME_DATA_SHARE_NUMERATOR", FRAME_DATA_SHARE_NUMERATOR); + require_eq(doc, "FRAME_DATA_SHARE_DENOMINATOR", FRAME_DATA_SHARE_DENOMINATOR); require(doc, &format!("KV × {WRITE_RECORD_SIZE} ≤ data size")); - let records = TX_DATA_LIMIT / WRITE_RECORD_SIZE; - require( - doc, - &format!( - "fewer than {} write records ({} / {})", - grouped(records), - grouped(TX_DATA_LIMIT), - WRITE_RECORD_SIZE - ), - ); } fn schedule(doc: &str) { @@ -249,21 +241,34 @@ fn limits(doc: &str) { "the page states one detention cap for both" ); - // Data size is the one dimension limited per transaction and per block: no table row names a - // limit on KV updates, state gas or execution gas. + // No table row names a block limit on state gas or execution gas. let resources = section(doc, "### 10. Resource Limits", "### 11. The Revert-Class"); assert!( table_row(resources, "Data size")[2].contains(&grouped(TX_DATA_LIMIT)), "the transaction's data-size limit" ); + assert_eq!( + table_row(resources, "KV updates")[2], + format!("`TX_KV_UPDATE_LIMIT` = {}", grouped(TX_KV_UPDATE_LIMIT)), + "the transaction's KV-update limit" + ); + assert_eq!(defaults.tx_runtime_limits.tx_kv_update_limit, TX_KV_UPDATE_LIMIT); + assert_eq!( + table_row(resources, "State growth")[2], + format!("`TX_STATE_GROWTH_LIMIT` = {}", grouped(TX_STATE_GROWTH_LIMIT)), + "the transaction's state-growth limit" + ); + assert_eq!(defaults.tx_runtime_limits.tx_state_growth_limit, TX_STATE_GROWTH_LIMIT); + require( + resources, + &format!( + "{} records weigh {} bytes", + grouped(TX_KV_UPDATE_LIMIT), + grouped(TX_KV_UPDATE_LIMIT * WRITE_RECORD_SIZE) + ), + ); let blocks = section(doc, "### 20. Block Limits", "### 21. Transaction and Block"); - for (page, removed) in [ - (resources, "KV updates"), - (resources, "State growth"), - (blocks, "Execution gas"), - (blocks, "State gas"), - (blocks, "KV updates"), - ] { + for (page, removed) in [(blocks, "Execution gas"), (blocks, "State gas")] { assert!( !page.lines().any(|line| line.contains(removed) && line.contains('|')), "no table row limits {removed}" @@ -271,17 +276,16 @@ fn limits(doc: &str) { } assert_eq!( *table_row(blocks, "Data size").last().unwrap(), - format!("{} bytes", grouped(BLOCK_DATA_LIMIT)) + format!("`BLOCK_DATA_LIMIT` = {}", grouped(BLOCK_DATA_LIMIT)) ); let safety = section(doc, "## Safety and Compatibility", "## References"); + require(safety, &format!("data size at {} bytes", grouped(TX_DATA_LIMIT))); + require(safety, &format!("KV updates at {}", grouped(TX_KV_UPDATE_LIMIT))); + require(safety, &format!("state growth at {}", grouped(TX_STATE_GROWTH_LIMIT))); require( safety, - &format!( - "the data-size limits at {} bytes and the detention caps at {} each", - grouped(TX_DATA_LIMIT), - grouped(BLOCK_ENV_ACCESS_COMPUTE_GAS) - ), + &format!("the detention caps at {} each", grouped(BLOCK_ENV_ACCESS_COMPUTE_GAS)), ); } @@ -371,20 +375,16 @@ fn detention_and_stops(doc: &str) { ); let stops = section(doc, "### 11. The Revert-Class", "### 12. Gas Detention"); - let kinds = - [(LimitKind::DataSize, "Data size"), (LimitKind::ComputeGas, "Compute (gas detention)")]; + let kinds = [ + (LimitKind::DataSize, "Data size"), + (LimitKind::KvUpdate, "KV updates"), + (LimitKind::ComputeGas, "Compute (gas detention)"), + (LimitKind::StateGrowth, "State growth"), + ]; for (kind, name) in kinds { let cells = row_with_first(stops, &kind.as_u8().to_string()); assert_eq!(cells[1], name, "kind {}", kind.as_u8()); } - for retired in [1_u8, 3] { - assert_eq!(LimitKind::from_u8(retired), None, "kind {retired} names no dimension"); - let first = retired.to_string(); - assert!( - stops.lines().map(cells).all(|cells| cells.first() != Some(&first.as_str())), - "the page lists no kind {retired}" - ); - } let access = section(doc, "### 13. Volatile-Data", "### 14. EIP-7708"); let reads = [ diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 2c4439f10..f237adb5c 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -1,5 +1,6 @@ -//! The state a transaction adds, which no limit holds: EIP-8037 charges state gas for exactly that -//! state, and the transaction's own gas pays for it. +//! The state a transaction adds: EIP-8037 charges state gas for exactly that state, which the +//! transaction's own gas pays for, and the state-growth limit holds its count — the new accounts +//! and new slots it keeps, net — per transaction and per frame. //! //! What each site charges — a fresh slot, an account a value transfer, a creation or a destruction //! adds, an applied EIP-7702 authority — is the schedule's state-gas entry, at the minimum bucket, @@ -14,18 +15,20 @@ use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ + constants::{TX_GAS_LIMIT_CAP, TX_STATE_GROWTH_LIMIT}, test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, - AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, ProtocolLimits, AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, + TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, INVALID, POP, PUSH0, SELFDESTRUCT, STOP, +use revm::{ + bytecode::opcode::{CALL, CREATE, DELEGATECALL, GAS, INVALID, POP, PUSH0, SELFDESTRUCT, STOP}, + context::result::ExecutionResult, }; use crate::common::{ account_state_gas, authorizing_call, body_history, call, context, execute_under, history, - slot_state_gas, state_is_free, + share, slot_state_gas, state_is_free, }; const CALLER: Address = address!("0000000000000000000000000000000000600000"); @@ -62,16 +65,28 @@ fn run_under_data_size( execute_under(db, tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)) } -/// The outcome was stopped by the transaction's data-size limit `limit`, crossed at `used`: a -/// revert carrying `MegaLimitExceeded(0, limit)`, never a halt. -fn assert_data_size_stopped(what: &str, outcome: &MegaTransactionOutcome, limit: u64, used: u64) { +/// The transaction's own frame was stopped crossing the transaction's data-size limit `limit` at +/// `used`, the transaction having counted `before` before the frame: the frame's budget is what the +/// limit leaves, which the crossing crosses too, so the outcome is a revert carrying +/// `MegaLimitExceeded(0, budget)`, never a halt. +fn assert_data_size_stopped( + what: &str, + outcome: &MegaTransactionOutcome, + before: u64, + limit: u64, + used: u64, +) { assert!( !outcome.result.is_success() && !outcome.result.is_halt(), "{what}: {:?}", outcome.result ); - let stop = - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local: false }; + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: limit - before, + used: used - before, + frame_local: true, + }; assert_eq!(outcome.limit_exceeded, Some(stop), "{what}"); assert_eq!(outcome.result.output().unwrap(), &stop.revert_data(), "{what}"); } @@ -255,6 +270,77 @@ fn test_an_authorization_adds_state_only_when_it_applies() { } } +/// An authority an earlier transaction funded is no new account, whether the two transactions run +/// on one journal, as a block builder runs them, or the first is committed before the second runs: +/// the application charges it no account, and the transaction counts no rise for it. +#[test] +fn test_an_authority_an_earlier_transaction_funded_is_no_new_account() { + use revm::{DatabaseCommit, ExecuteEvm}; + let fund = call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP); + let mut apply = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); + apply.0.base.nonce = 1; + let db = funded().account_code(A, Bytes::from_static(&[STOP])); + let first = run(db.clone(), fund.clone()); + assert!(first.result.is_success(), "{:?}", first.result); + + let mut committed = db.clone(); + committed.commit(first.result_and_state.state); + let control = run(committed, apply.clone()); + assert!(control.result.is_success(), "{:?}", control.result); + let (_, delegation) = account_and_delegation(); + assert_eq!(control.gas.state, delegation, "the delegation's bytes alone"); + assert_eq!(control.usage.state_growth, 0, "the authority existed"); + assert_eq!(control.usage.write_records, 1, "the authority's record"); + + let context = + crate::common::context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(context); + assert!(ExecuteEvm::transact_one(&mut evm, fund).expect("valid").is_success()); + let second = evm.execute_transaction(apply).expect("valid"); + assert_eq!(second.result_and_state.result, control.result_and_state.result); + assert_eq!(second.gas, control.gas); + assert_eq!(second.usage, control.usage); + assert_eq!(second.limit_exceeded, control.limit_exceeded); +} + +/// An authority an earlier transaction called without value, which the database holds no account +/// for, is counted as the application charges it, whether the two transactions run on one journal +/// or the first is committed before the second runs: the transaction counts a rise for it exactly +/// when the application charged it a new account beside the delegation's bytes. On one journal the +/// call touched the empty account, and revm's flag of the touch outlives the call's transaction, so +/// the application finds the authority touched and charges it no account. +#[test] +fn test_an_authority_an_earlier_transaction_touched_is_counted_as_it_is_charged() { + use revm::{DatabaseCommit, ExecuteEvm}; + if state_is_free() { + return; + } + let (account, delegation) = account_and_delegation(); + let counted_as_charged = |outcome: &MegaTransactionOutcome, path: &str| { + assert!(outcome.result.is_success(), "{path}: {:?}", outcome.result); + let charged = outcome.gas.state == account + delegation; + assert!(charged || outcome.gas.state == delegation, "{path}: {}", outcome.gas.state); + assert_eq!(outcome.usage.state_growth, u64::from(charged), "{path}: the rise"); + assert_eq!(outcome.usage.write_records, 1, "{path}: the authority's record"); + }; + let touch = call(CALLER, AUTHORITY_1, U256::ZERO, BELOW_CAP); + let mut apply = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); + apply.0.base.nonce = 1; + let db = funded().account_code(A, Bytes::from_static(&[STOP])); + let first = run(db.clone(), touch.clone()); + assert!(first.result.is_success(), "{:?}", first.result); + + let mut committed = db.clone(); + committed.commit(first.result_and_state.state); + counted_as_charged(&run(committed, apply.clone()), "committed"); + + let context = + crate::common::context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(context); + assert!(ExecuteEvm::transact_one(&mut evm, touch).expect("valid").is_success()); + counted_as_charged(&evm.execute_transaction(apply).expect("valid"), "one journal"); +} + /// The state gas an authority costs is charged before the first frame, from the transaction's /// gas. A gas limit that covers it in a minimal bucket but not in a crowded one is not refused at /// validation: the transaction runs out of gas before its first frame, and the out-of-gas takes @@ -361,7 +447,8 @@ fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { let start = if value.is_zero() { 0 } else { WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE }; let limit = TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE + start; let stopped = run_under_data_size(writes, tx.clone(), limit); - assert_data_size_stopped("the slot", &stopped, limit, limit + WRITE_RECORD_SIZE); + let before = TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE; + assert_data_size_stopped("the slot", &stopped, before, limit, limit + WRITE_RECORD_SIZE); let applied = run(idle, tx); assert!(applied.result.is_success(), "{:?}", applied.result); @@ -407,7 +494,8 @@ fn test_a_stopped_deposit_keeps_the_caller_it_created() { }; let (writes, tx) = deposit(write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); let stopped = run_under_data_size(writes, tx, TX_BODY_SIZE); - assert_data_size_stopped("the slot", &stopped, TX_BODY_SIZE, TX_BODY_SIZE + WRITE_RECORD_SIZE); + let (body, used) = (TX_BODY_SIZE, TX_BODY_SIZE + WRITE_RECORD_SIZE); + assert_data_size_stopped("the slot", &stopped, body, body, used); let (idle, tx) = deposit(BytecodeBuilder::default().stop().build()); let created = run(idle, tx); assert!(created.result.is_success(), "{:?}", created.result); @@ -444,10 +532,10 @@ fn test_a_destruction_to_itself_grows_no_state() { /// Once the state charge is paid, a frame start still charges the caller the history of the two /// records the frame makes, after the gas it forwards is computed [S7.23]; one gas short of what /// the start costs in all is an out-of-gas too, and the frame does not start [S7.24]. A `CREATE` -/// charges the created account before its 63/64 split, as EIP-8037 has it, so the records come out -/// of the 64th the creator keeps, and the creator must hold 64 times their price after the state -/// charge. EIP-8037 states that order for a creation alone — of a value `CALL` it says only that -/// the charge comes right before the child frame is entered — so, though the engine charges a +/// charges the created account before its 98/100 split, as EIP-8037 has it, so the records come +/// out of the fiftieth the creator keeps, and the creator must hold 50 times their price after the +/// state charge. EIP-8037 states that order for a creation alone — of a value `CALL` it says only +/// that the charge comes right before the child frame is entered — so, though the engine charges a /// `CALL`'s new account before its split too, that order is not pinned here: the `CALL` forwards /// an explicit nothing — the same forward in any order — and its rows hold whatever the order: a /// gas limit short of the state charge, and one gas short of the whole start, runs out of gas. @@ -522,7 +610,7 @@ fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() entry(GasId::cold_account_additional_cost()) + entry(GasId::warm_storage_read_cost()), account_state_gas(), - // The beneficiary's record is held before its history is charged. + // The destruction's records are held before their history is charged. 0, false, ), @@ -581,8 +669,8 @@ fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() // Three `PUSH0` for an empty init code carrying no value, then the creation's 32,000. call_intrinsic + 3 * 2 + entry(GasId::create()), created_account_state_gas(), - // The two records, out of the 64th the creator keeps after its forward. - 64 * start_records, + // The two records, out of the fiftieth the creator keeps after its forward. + 50 * start_records, false, ), ]; @@ -626,13 +714,701 @@ fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() paid.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: TX_BODY_SIZE, - frame_local: false, + limit: 0, + frame_local: true, .. }) ), - "{name}, everything paid: the record after the charge is the stop, {:?}", + "{name}, everything paid: the record after the charge crosses the frame's budget of \ + nothing the body leaves, {:?}", paid.limit_exceeded ); } } + +/* ---------- the state-growth limit ---------- */ + +// State growth is the count of the new accounts and new slots a transaction keeps, net, held per +// transaction at `TX_STATE_GROWTH_LIMIT` and per frame at 98/100 of what its parent has left, +// rounded down. A rise that crosses either stops the frame that makes it with +// `MegaLimitExceeded(3, limit)`, naming the frame's budget when the rise crosses it, and its caller +// resumes. Every figure below is hand arithmetic from the rises and falls the spec lists. + +const C: Address = address!("0000000000000000000000000000000000600009"); +const D: Address = address!("000000000000000000000000000000000060000a"); + +/// Gas for `slots` fresh slots and the calls around them at the prices in effect: the execution +/// cap's regular gas, and a reservoir paying every slot's state gas and its record's history, with +/// room for a few new accounts on top. +fn room(slots: u64) -> u64 { + TX_GAS_LIMIT_CAP + + slots * (slot_state_gas() + history(WRITE_RECORD_SIZE)) + + 16 * (account_state_gas() + history(WRITE_RECORD_SIZE)) + + 100_000_000 +} + +/// Limits holding the transaction to `units` of state growth, and nothing else. +fn growth(units: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(units) +} + +/// The revert data of a state-growth stop naming `limit`. +fn growth_stop(limit: u64) -> Bytes { + LimitCheck::ExceedsLimit { kind: LimitKind::StateGrowth, limit, used: 0, frame_local: true } + .revert_data() +} + +/// The stop of a state-growth crossing of the budget `limit` at `used`, by the frame that made it. +const fn budget_crossed(limit: u64, used: u64) -> Option { + Some(LimitCheck::ExceedsLimit { kind: LimitKind::StateGrowth, limit, used, frame_local: true }) +} + +/// A call to `A` with gas for `slots` fresh slots, run over `db` under `limits`. +fn run_a(db: MemoryDatabase, slots: u64, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + execute_under(db, call(CALLER, A, U256::ZERO, room(slots)), limits) +} + +/// Appends a `CALL` of `to` with all the gas and no value, dropping its status. +fn call_dropping(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.call(to, U256::ZERO).append(POP) +} + +/// Appends a `CALL` of `to` with all the gas and no value, then returns what it returned or +/// reverted with: a frame that ends with its child's answer as its own output. +fn call_answering(code: BytecodeBuilder, to: Address, value: U256) -> Bytes { + code.call(to, value).append(POP).return_returndata().build() +} + +/// Appends a `DELEGATECALL` of `to` with all the gas, dropping its status: `to`'s code on the +/// caller's own storage. +fn delegatecall_dropping(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).push_address(to).append_many([ + GAS, + DELEGATECALL, + POP, + ]) +} + +/// Appends writes of zero to the slots `from..to`: a fall of each slot an earlier write in the +/// transaction made non-zero from an original of zero. +fn clear_slots(mut builder: BytecodeBuilder, from: u64, to: u64) -> BytecodeBuilder { + for slot in from..to { + builder = builder.sstore(U256::from(slot), U256::ZERO); + } + builder +} + +/// The output of `outcome`'s transaction, the revert data of a stop a frame answered with. +fn output(outcome: &MegaTransactionOutcome) -> Bytes { + outcome.result.output().cloned().unwrap_or_default() +} + +/// The spec's numbers: 1,000 new accounts and slots per transaction, kind 3, every frame budgeted +/// at the same 98/100 share as the data size and the KV count; no limit at all leaves it unlimited. +#[test] +fn test_the_state_growth_limit_is_the_specs() { + assert_eq!(TX_STATE_GROWTH_LIMIT, 1_000); + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + assert_eq!(limits.tx_state_growth_limit, TX_STATE_GROWTH_LIMIT); + assert_eq!(EvmTxRuntimeLimits::no_limits().tx_state_growth_limit, u64::MAX); + assert_eq!(LimitKind::StateGrowth.as_u8(), 3); + assert_eq!(LimitKind::from_u8(3), Some(LimitKind::StateGrowth)); +} + +/// The transaction's own frame gets what the transaction has left, the whole 1,000 under the spec's +/// limits, and the 1,001st fresh slot stops it, kind 3, naming that budget: the stop settles as a +/// revert, and the slot, like every slot the frame wrote, is not kept. The gas pays for every slot, +/// so the count is what stops it, not the price. 1,000 fresh slots fit. +#[test] +fn test_the_1001st_fresh_slot_stops_the_transactions_own_frame() { + let db = |count: u64| { + funded() + .account_code(A, write_slots(BytecodeBuilder::default(), 1, count + 1).stop().build()) + }; + let limits = EvmTxRuntimeLimits::default(); + let fits = run_a(db(1_000), 1_001, limits); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 1_000); + + let stopped = run_a(db(1_001), 1_001, limits); + assert_eq!(stopped.limit_exceeded, budget_crossed(1_000, 1_001)); + assert!(matches!(&stopped.result, ExecutionResult::Revert { .. }), "{:?}", stopped.result); + assert_eq!(output(&stopped), growth_stop(1_000)); + assert_eq!( + stopped.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, + "nothing the frame wrote is kept" + ); + assert!(stopped.state[&A].storage.values().all(|slot| slot.present_value.is_zero())); +} + +/// A child gets 98/100 of what its caller has left: a caller that kept 20 of the 1,000 gives its +/// child `980 × 98 / 100` = 960, the product rounded down rather than the subtraction's 961. The +/// 960th slot fits and the 961st stops the child, naming 960; the caller catches the stop and runs +/// on within what it has left. After a child that kept 960, the caller has the 20 the transaction +/// has left: 20 more fit, and the 21st stops the caller itself, naming its own budget, 1,000. +#[test] +fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { + assert_eq!(share(1_000 - 20), 960); + let db = |child: u64, after: u64| { + let caller = write_slots(BytecodeBuilder::default(), 1, 21); + let caller = write_slots(call_dropping(caller, B), 21, 21 + after).stop().build(); + funded() + .account_code(A, caller) + .account_code(B, write_slots(BytecodeBuilder::default(), 1, child + 1).stop().build()) + }; + let limits = EvmTxRuntimeLimits::default(); + + let full = run_a(db(960, 20), 1_000, limits); + assert!(full.result.is_success(), "{:?}", full.result); + assert_eq!(full.usage.state_growth, 1_000, "20, the child's 960, and 20"); + + let over = run_a(db(960, 21), 1_001, limits); + assert_eq!(over.limit_exceeded, budget_crossed(1_000, 1_001), "the caller's own budget"); + + let child_over = run_a(db(961, 20), 1_001, limits); + assert!(child_over.result.is_success(), "{:?}", child_over.result); + assert_eq!(child_over.limit_exceeded, None, "a stop below is no stop"); + assert_eq!(child_over.usage.state_growth, 40, "the caller's 40; none of the child's"); + assert!( + child_over + .state + .get(&B) + .is_none_or(|b| b.storage.values().all(|s| s.present_value.is_zero())), + "the child's slots went with its stop" + ); +} + +/// Under the spec's 1,000 a frame two calls down gets 960 and one three calls down 940 +/// (`960 × 98 / 100` rounded down), when nothing above it kept anything: the 940th slot there fits +/// and the 941st stops that frame, naming 940; every caller catches the stop and ends. +#[test] +fn test_the_state_growth_budgets_at_depth() { + assert_eq!(share(share(share(1_000))), 940); + let db = |slots: u64| { + let d = BytecodeBuilder::default(); + funded() + .account_code(A, call_answering(BytecodeBuilder::default(), B, U256::ZERO)) + .account_code(B, call_answering(BytecodeBuilder::default(), C, U256::ZERO)) + .account_code(C, call_answering(BytecodeBuilder::default(), D, U256::ZERO)) + .account_code(D, write_slots(d, 1, slots + 1).stop().build()) + }; + let fits = run_a(db(940), 941, EvmTxRuntimeLimits::default()); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 940); + + let stopped = run_a(db(941), 941, EvmTxRuntimeLimits::default()); + assert!(stopped.result.is_success(), "{:?}", stopped.result); + assert_eq!(stopped.limit_exceeded, None, "the callers caught it"); + assert_eq!(output(&stopped), growth_stop(940), "D's stop, handed up as each caller's answer"); + assert_eq!(stopped.usage.state_growth, 0); +} + +/// A frame's net is signed, and its remaining is clamped to the budget it was given: a caller that +/// added 100 of its 1,000 gives its child 882; the child clears those 100 slots — it runs on the +/// caller's storage — so its net is −100, yet what it forwards is still 98/100 of its 882, 864, and +/// the 865th slot of its own child stops that frame. When the child succeeds its net merges, the +/// caller's net is 0, and a later child gets 980; when it reverts, its net is discarded with its +/// writes, the caller keeps its 100, and a later child gets 882. +#[test] +fn test_a_negative_net_does_not_enlarge_the_next_childs_budget() { + assert_eq!((share(900), share(882), share(1_000)), (882, 864, 980)); + let writer = |slots: u64| write_slots(BytecodeBuilder::default(), 1, slots + 1).stop().build(); + let caller = |then: Option
| { + let code = delegatecall_dropping(write_slots(BytecodeBuilder::default(), 1, 101), B); + match then { + Some(child) => call_answering(code, child, U256::ZERO), + None => code.stop().build(), + } + }; + let clearer = |then: Option
, reverts: bool| { + let code = clear_slots(BytecodeBuilder::default(), 1, 101); + let code = match then { + Some(child) => call_dropping(code, child), + None => code, + }; + if reverts { + code.revert().build() + } else { + code.stop().build() + } + }; + let limits = EvmTxRuntimeLimits::default(); + + // The clamp: the clearing child's own child gets 864. + for (slots, fits) in [(864, true), (865, false)] { + let db = funded() + .account_code(A, caller(None)) + .account_code(B, clearer(Some(C), false)) + .account_code(C, writer(slots)); + let outcome = run_a(db, 1_100, limits); + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + let kept = if fits { slots } else { 0 }; + assert_eq!(outcome.usage.state_growth, kept, "{slots}: the 100 cleared, and C's slots"); + } + + // The merge, and the revert: the next child gets 980, or 882. + for (reverts, budget) in [(false, 980), (true, 882)] { + for slots in [budget, budget + 1] { + let db = funded() + .account_code(A, caller(Some(D))) + .account_code(B, clearer(None, reverts)) + .account_code(D, writer(slots)); + let outcome = run_a(db, 1_100, limits); + let case = format!("child reverts {reverts}, {slots} slots"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let caller_kept = if reverts { 100 } else { 0 }; + if slots == budget { + assert_eq!(outcome.usage.state_growth, caller_kept + slots, "{case}"); + assert!(output(&outcome).is_empty(), "{case}"); + } else { + assert_eq!(output(&outcome), growth_stop(budget), "{case}: D's budget"); + assert_eq!(outcome.usage.state_growth, caller_kept, "{case}"); + } + } + } +} + +/// An `SSTORE` falls on the slot it writes back to zero from an original of zero, and the fall +/// makes room: under a limit of one, a slot written `0 → 1 → 0` nets nothing, so another fresh +/// slot fits after it, and a third crosses. A fall with no earlier rise in the frame — a child +/// clearing a slot its caller made — leaves the child's remaining at its budget, and later rises +/// consume the fall: the child keeps a net of its budget and no more. +#[test] +fn test_a_slot_written_back_to_zero_falls_and_makes_room() { + let code = |extra: u64| { + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::ZERO); + write_slots(code, 2, 3 + extra).stop().build() + }; + let fits = run_a(funded().account_code(A, code(0)), 4, growth(1)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 1, "slot 1 rose and fell; slot 2 rose"); + let crosses = run_a(funded().account_code(A, code(1)), 4, growth(1)); + assert_eq!(crosses.limit_exceeded, budget_crossed(1, 2)); + + // Under ten, the caller keeps one slot and gives its child 8; the child clears the caller's + // slot and writes nine of its own on the caller's storage, a net of 8. + assert_eq!(share(10 - 1), 8); + let child = |slots: u64| { + write_slots(clear_slots(BytecodeBuilder::default(), 1, 2), 100, 100 + slots).stop().build() + }; + for (slots, fits) in [(9, true), (10, false)] { + let caller = delegatecall_dropping(write_slots(BytecodeBuilder::default(), 1, 2), B); + let db = funded().account_code(A, caller.stop().build()).account_code(B, child(slots)); + let outcome = run_a(db, 12, growth(10)); + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + assert_eq!(outcome.usage.state_growth, if fits { slots } else { 1 }, "{slots}"); + } +} + +/// Each site the spec lists adds one new account or slot, and nothing else does: a transaction's +/// value to an account that does not exist, a value `CALL` to one, a creation at an empty address — +/// whatever code it deploys — a creation transaction, a `SELFDESTRUCT` moving a balance to one, an +/// authorization creating its authority, and a deposit creating its caller. An account that exists, +/// a `CALLCODE`, a value call to the calling account itself, a destruction moving nothing, and an +/// authorization of an account that exists add none. +#[test] +fn test_each_site_adds_one_new_account_or_slot() { + let one = U256::from(1); + let contract = |code: Bytes| funded().account_code(A, code); + let value_call = + |to| contract(BytecodeBuilder::default().call(to, one).append(POP).stop().build()); + let fresh_caller = address!("00000000000000000000000000000000006000fe"); + let cases: Vec<(&str, MegaTransactionOutcome, u64)> = vec![ + ( + "the transaction's value to a new account", + run(funded(), call(CALLER, EMPTY, one, BELOW_CAP)), + 1, + ), + ( + "the transaction's value to an account that exists", + run(funded(), call(CALLER, A, one, BELOW_CAP)), + 0, + ), + ( + "a value CALL to a new account", + run(value_call(EMPTY), call(CALLER, A, U256::ZERO, BELOW_CAP)), + 1, + ), + ( + "a value CALL to an account that exists", + run(value_call(CALLER), call(CALLER, A, U256::ZERO, BELOW_CAP)), + 0, + ), + ( + "a value CALL to the calling account itself", + run(value_call(A), call(CALLER, A, U256::ZERO, BELOW_CAP)), + 0, + ), + ( + "a value CALLCODE", + run( + contract( + BytecodeBuilder::default().callcode(EMPTY, one).append(POP).stop().build(), + ), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 0, + ), + ( + "a CREATE deploying 32 bytes", + run( + contract( + BytecodeBuilder::default() + .create(U256::ZERO, crate::common::deploying(32)) + .append(POP) + .stop() + .build(), + ), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 1, + ), + ( + "a creation transaction", + run(funded(), crate::common::create(CALLER, crate::common::deploying(32), BELOW_CAP)), + 1, + ), + ( + "a SELFDESTRUCT moving a balance to a new account", + run( + contract(BytecodeBuilder::default().selfdestruct(EMPTY).build()), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 1, + ), + ( + "a SELFDESTRUCT moving nothing", + run( + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, BytecodeBuilder::default().selfdestruct(EMPTY).build()), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 0, + ), + ( + "an authorization creating its authority", + run( + funded().account_code(A, BytecodeBuilder::default().stop().build()), + authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]), + ), + 1, + ), + ( + "an authorization of an account that exists", + run( + funded() + .account_balance(AUTHORITY_1, one) + .account_code(A, BytecodeBuilder::default().stop().build()), + authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]), + ), + 0, + ), + ( + "a deposit creating its caller", + run( + funded().account_code(A, BytecodeBuilder::default().stop().build()), + crate::common::deposit(call(fresh_caller, A, U256::ZERO, BELOW_CAP)), + ), + 1, + ), + ]; + for (site, outcome, expected) in cases { + assert!(outcome.result.is_success(), "{site}: {:?}", outcome.result); + assert_eq!(outcome.usage.state_growth, expected, "{site}"); + } +} + +/// A start its caller's account refuses counts nothing and is stopped by no limit, even with no +/// state growth left: a value call the caller cannot fund, a creation it cannot endow. A creation +/// onto an occupied address fails on the collision, after the creator's nonce bump, and adds no +/// state growth, the address being no new account; nor does a `CREATE2` onto an address that holds +/// a balance, which succeeds under a limit of nothing, keeping the creator's nonce record and the +/// created account's. +#[test] +fn test_a_start_that_makes_no_new_account_is_held_to_nothing() { + let one = U256::from(1); + let poor = |code: Bytes| { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, code) + }; + let refused_call = poor(BytecodeBuilder::default().call(EMPTY, one).append(POP).stop().build()); + let refused_creation = poor( + BytecodeBuilder::default() + .create(one, crate::common::deploying(0)) + .append(POP) + .stop() + .build(), + ); + let init = crate::common::deploying(0); + let target = A.create2(B256::ZERO, alloy_primitives::keccak256(&init)); + let creation = BytecodeBuilder::default() + .create2(U256::ZERO, &init, U256::ZERO) + .append(POP) + .stop() + .build(); + let collision = funded() + .account_code(A, creation.clone()) + .account_code(target, Bytes::from_static(&[STOP])); + let funded_target = funded().account_code(A, creation).account_balance(target, one); + for (case, db) in [ + ("a value call the caller cannot fund", refused_call), + ("a creation the caller cannot endow", refused_creation), + ("a creation onto an address with code", collision), + ("a creation onto an address that holds a balance", funded_target), + ] { + let outcome = run_a(db, 1, growth(0)); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}"); + assert_eq!(outcome.usage.state_growth, 0, "{case}"); + assert!(output(&outcome).is_empty(), "{case}"); + } + let onto_funded = run_a( + funded() + .account_code( + A, + BytecodeBuilder::default() + .create2(U256::ZERO, &init, U256::ZERO) + .append(POP) + .stop() + .build(), + ) + .account_balance(target, one), + 1, + growth(0), + ); + assert_eq!(onto_funded.usage.write_records, 2, "the creator's nonce and the created account"); + assert_eq!(onto_funded.state[&target].info.nonce, 1, "created"); +} + +/// A creation's budget is 98/100 of what its creator has left at its `CREATE`, the creator's nonce +/// record being counted on the creator once the creation returned: a creator with the whole 1,000 +/// left, whose nonce bump creates nothing, gives its creation 980, +/// against which the created account is the creation's first rise — its init code fits 979 fresh +/// slots, and the 980th stops it, naming 980, which the creator catches. A creation transaction's +/// own frame is no such child: it gets the whole 1,000, the account and 999 slots. +#[test] +fn test_a_creation_is_budgeted_after_its_creators_counts() { + assert_eq!(share(1_000), 980); + let init = |slots: u64| write_slots(BytecodeBuilder::default(), 1, slots + 1).stop().build(); + for (slots, fits) in [(979, true), (980, false)] { + let creator = + BytecodeBuilder::default().create(U256::ZERO, init(slots)).append(POP).stop().build(); + let outcome = + run_a(funded().account_code(A, creator), 1_000, EvmTxRuntimeLimits::default()); + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{slots}"); + let created = if fits { 1 + slots } else { 0 }; + assert_eq!(outcome.usage.state_growth, created, "{slots}: the account and its slots"); + assert_eq!(outcome.state[&A].info.nonce, 1, "{slots}: the creator's bump stands"); + } + for (slots, fits) in [(999, true), (1_000, false)] { + let tx = crate::common::create(CALLER, init(slots), room(1_001)); + let outcome = execute_under(funded(), tx, EvmTxRuntimeLimits::default()); + if fits { + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + assert_eq!(outcome.usage.state_growth, 1_000, "the account and 999 slots"); + } else { + assert_eq!(outcome.limit_exceeded, budget_crossed(1_000, 1_001), "{slots}"); + } + } +} + +/// A write that crosses more than one counted dimension stops on the first of data size, KV +/// updates and state growth: a fresh slot's record over the data size and its slot over the state +/// growth is kind 0; its record over the KV count and its slot over the state growth, kind 1. +/// Compute is decided at the charge, before the write is counted: a fresh `SSTORE` whose regular +/// charge crosses gas detention stops with kind 2, though its slot would have crossed the state +/// growth. +#[test] +fn test_a_slot_crossing_several_limits_stops_on_the_first_in_order() { + use revm::bytecode::opcode::TIMESTAMP; + let writes = + || funded().account_code(A, write_slots(BytecodeBuilder::default(), 1, 2).stop().build()); + let kind_of = |outcome: &MegaTransactionOutcome| match outcome.limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind, .. }) => kind, + other => panic!("expected a stop: {other:?}"), + }; + let data = growth(0).with_tx_data_size_limit(TX_BODY_SIZE); + assert_eq!(kind_of(&run_a(writes(), 1, data)), LimitKind::DataSize); + let kv = growth(0).with_tx_kv_update_limit(0); + assert_eq!(kind_of(&run_a(writes(), 1, kv)), LimitKind::KvUpdate); + assert_eq!(kind_of(&run_a(writes(), 1, growth(0))), LimitKind::StateGrowth); + + let detained = funded().account_code( + A, + write_slots(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), 1, 2).stop().build(), + ); + let capped = growth(0).with_block_env_access_compute_gas_limit(100); + assert_eq!(kind_of(&run_a(detained.clone(), 1, capped)), LimitKind::ComputeGas); + assert_eq!(kind_of(&run_a(detained, 1, growth(0))), LimitKind::StateGrowth, "undetained"); +} + +/// An authorization list is decided before it is applied, on the accounts it would create: a list +/// whose new authorities would cross the transaction's state growth is skipped whole — no authority +/// is bumped, delegated or counted — and the transaction's own frame returns the stop before it +/// runs, kind 3, naming the transaction's limit, since no frame budget exists yet. A list crossing +/// both counts is the KV count's, kind 1. Repeated acceptances of one new authority create it once. +/// A list that fits is applied, and its accounts are counted on the transaction, so the first +/// frame's budget is what they leave: with none left, the transaction's value to a new account +/// stops that frame at its start, naming a budget of nothing, and the authorities stay applied. +#[test] +fn test_an_authorization_list_is_held_to_the_state_growth_it_would_add() { + let db = || funded().account_code(A, BytecodeBuilder::default().stop().build()); + let both = [(AUTHORITY_1, 0), (AUTHORITY_2, 0)]; + let tx = |value: U256, list: &[(Address, u64)]| { + authorizing_call(CALLER, A, value, room(0), DELEGATE, list) + }; + let untouched = |outcome: &MegaTransactionOutcome| { + for authority in [AUTHORITY_1, AUTHORITY_2] { + let account = outcome.state.get(&authority); + assert!( + account.is_none_or(|account| account.info.nonce == 0), + "{authority}: not bumped" + ); + assert!( + account.is_none_or(|account| account.info.is_empty_code_hash()), + "{authority}: not delegated" + ); + } + }; + + let skipped = execute_under(db(), tx(U256::ZERO, &both), growth(1)); + assert_eq!( + skipped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 1, + used: 2, + frame_local: false + }) + ); + assert!(matches!(&skipped.result, ExecutionResult::Revert { .. }), "{:?}", skipped.result); + assert_eq!( + skipped.usage, + LimitUsage { data_size: skipped.usage.data_size, write_records: 0, state_growth: 0 } + ); + assert_eq!(skipped.gas.state, 0, "no authority's state gas"); + untouched(&skipped); + + let both_counts = + execute_under(db(), tx(U256::ZERO, &both), growth(1).with_tx_kv_update_limit(1)); + assert!( + matches!( + both_counts.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::KvUpdate, limit: 1, .. }) + ), + "{:?}", + both_counts.limit_exceeded + ); + + let repeated = + execute_under(db(), tx(U256::ZERO, &[(AUTHORITY_1, 0), (AUTHORITY_1, 1)]), growth(1)); + assert!(repeated.result.is_success(), "{:?}", repeated.result); + assert_eq!((repeated.usage.write_records, repeated.usage.state_growth), (1, 1)); + assert_eq!(repeated.state[&AUTHORITY_1].info.nonce, 2, "both applied"); + + let fits = execute_under(db(), tx(U256::ZERO, &both), growth(2)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 2); + + let recipient_stopped = execute_under( + funded(), + authorizing_call(CALLER, EMPTY, U256::from(1), room(0), DELEGATE, &both), + growth(2), + ); + assert_eq!(recipient_stopped.limit_exceeded, budget_crossed(0, 1), "the recipient"); + assert_eq!(recipient_stopped.usage.state_growth, 2, "the authorities stay"); + for authority in [AUTHORITY_1, AUTHORITY_2] { + assert_eq!(recipient_stopped.state[&authority].info.nonce, 1, "{authority}: applied"); + } + assert!( + recipient_stopped.state.get(&EMPTY).is_none_or(|account| account.info.is_empty()), + "the recipient was not created" + ); +} + +/// A deposit's caller, created before its first frame, is one account of state growth on the +/// transaction: it outlives a stop of the first frame, and the first frame's budget is what it +/// leaves — under a limit of two, one fresh slot fits and the second stops the frame. +#[test] +fn test_a_deposits_new_caller_is_counted_before_its_first_frame() { + let fresh = address!("00000000000000000000000000000000006000fd"); + let db = |slots: u64| { + funded() + .account_code(A, write_slots(BytecodeBuilder::default(), 1, slots + 1).stop().build()) + }; + let tx = || crate::common::deposit(call(fresh, A, U256::ZERO, room(2))); + let fits = execute_under(db(1), tx(), growth(2)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 2, "the caller and the slot"); + let stopped = execute_under(db(2), tx(), growth(2)); + assert_eq!( + stopped.limit_exceeded, + budget_crossed(1, 2), + "the frame's budget: what the caller left" + ); + assert_eq!(stopped.usage.state_growth, 1, "the caller stays"); + assert_eq!(stopped.state[&fresh].info.nonce, 1, "and exists"); + // Under a limit of nothing, which the spec's 1,000 never is, the caller alone is over it, and + // it is counted all the same: the first frame's start, held to the transaction's limit, is the + // stop, naming that limit, before the frame writes anything. + let none_left = execute_under(db(1), tx(), growth(0)); + assert_eq!( + none_left.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 0, + used: 1, + frame_local: false + }) + ); + assert_eq!(none_left.usage.state_growth, 1, "the caller, over the limit, stays"); + assert!(none_left.state[&A].storage.values().all(|slot| slot.present_value.is_zero())); +} + +/// A frame whose start adds a new account it has no budget for is stopped before it runs, and what +/// its start moved goes back: a value call to a new account under a budget of nothing is answered +/// with the stop, its value not moved, and its caller catches it. A creation's start alike: its +/// init code never runs, and its creator keeps the nonce bump revm made before the creation's +/// checkpoint. A call to a precompile whose start adds an account crosses the state growth before +/// gas detention prices it: the records' stop is the answer, though the price crosses the compute +/// limit too. +#[test] +fn test_a_start_over_the_state_growth_is_stopped_before_it_runs() { + use revm::bytecode::opcode::TIMESTAMP; + let one = U256::from(1); + let value_call = + funded().account_code(A, call_answering(BytecodeBuilder::default(), EMPTY, one)); + let answered = run_a(value_call, 1, growth(0)); + assert!(answered.result.is_success(), "{:?}", answered.result); + assert_eq!(output(&answered), growth_stop(0), "the value call's answer is the stop"); + assert!(answered.state.get(&EMPTY).is_none_or(|account| account.info.is_empty()), "not moved"); + assert_eq!(answered.state[&A].info.balance, U256::from(1_000), "the value came back"); + + let marker = BytecodeBuilder::default().sstore(U256::from(1), one).stop().build(); + let creator = BytecodeBuilder::default().create(U256::ZERO, marker).append(POP).stop().build(); + let created = run_a(funded().account_code(A, creator), 1, growth(0)); + assert!(created.result.is_success(), "{:?}", created.result); + assert_eq!(created.usage.state_growth, 0, "the init code never ran"); + assert_eq!(created.state[&A].info.nonce, 1, "the creator's bump stands"); + assert!(created.state.get(&A.create(0)).is_none_or(|account| account.info.is_empty())); + + // The KZG point evaluation, priced 100,000, past a compute limit of 50,000 after the read, + // which the call's own charges stay within. + let kzg = address!("000000000000000000000000000000000000000a"); + let precompile = funded().account_code( + A, + call_answering(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), kzg, one), + ); + let cap = EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(50_000); + let both = run_a(precompile.clone(), 1, cap.with_tx_state_growth_limit(0)); + assert_eq!(output(&both), growth_stop(0), "the records first"); + let priced = run_a(precompile, 1, cap); + let (kind, _) = mega_evm::decode_mega_limit_exceeded(&output(&priced)).expect("a stop"); + assert_eq!(kind, LimitKind::ComputeGas, "without the state growth, the price"); +} diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 781397192..8ece1bcd5 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1,12 +1,12 @@ //! The revert-class stop, pinned as a matrix. //! -//! A limit — data size or gas detention's compute limit — stops the frame that crosses it with a -//! revert: the frame reverts with `MegaLimitExceeded(kind, limit)` and keeps nothing it did, and -//! its caller resumes as after any revert. A crossing the transaction's own frame makes is the -//! transaction's result, which settles like an EIP-8037 revert: the sender pays for what ran, and -//! its unspent regular gas and the reservoir come back. A frame budget stops its frame the same -//! way. A real out-of-gas and a precompile given less than its price still halt, and burn what -//! their frame was given. +//! A limit — data size, KV updates, state growth or gas detention's compute limit — stops the +//! frame that crosses it with a revert: the frame reverts with `MegaLimitExceeded(kind, limit)` and +//! keeps nothing it did, and its caller resumes as after any revert. A crossing the transaction's +//! own frame makes is the transaction's result, which settles like an EIP-8037 revert: the sender +//! pays for what ran, and its unspent regular gas and the reservoir come back. A frame budget stops +//! its frame the same way. A real out-of-gas and a precompile given less than its price still halt, +//! and burn what their frame was given. //! //! The matrix crosses each limit in the transaction's own frame and in a frame three calls below //! it, below the execution cap and above it, where a reservoir pays the body first, without an @@ -19,12 +19,13 @@ //! stopped transaction keeps. //! //! A column of creations revived by an inspector that rewrites every frame result into a success -//! shows that a revived stop settles as a frame that kept nothing, and is no stop. +//! shows that a revived stop is taken as given — a success that keeps what it counted before the +//! stop — and is no stop. //! -//! The last cells cross a limit three calls down with a frame answered without running — an -//! answer past what the compute limit leaves it, a precompile run on that allowance, and a start -//! whose records cross the data-size limit before the frame is built — and the callers catch the -//! stop the same way. +//! The last cells cross a limit three calls down with a frame answered without running — a +//! precompile run on what the compute limit leaves it, and a start whose records cross the +//! data-size limit before the frame is built — and the callers catch the stop the same way. An +//! inspector's answer past that allowance is taken as given, and is no stop. use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ @@ -92,18 +93,27 @@ const TWIN_REVERT: u64 = 4; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Limit { DataSize, + KvUpdate, + StateGrowth, Compute, } impl Limit { - const ALL: [Self; 2] = [Self::DataSize, Self::Compute]; + const ALL: [Self; 4] = [Self::DataSize, Self::KvUpdate, Self::StateGrowth, Self::Compute]; const fn kind(self) -> LimitKind { match self { Self::DataSize => LimitKind::DataSize, + Self::KvUpdate => LimitKind::KvUpdate, + Self::StateGrowth => LimitKind::StateGrowth, Self::Compute => LimitKind::ComputeGas, } } + + /// Whether the limit is one the layer counts, crossed by a write, rather than gas detention's. + const fn is_counted(self) -> bool { + !matches!(self, Self::Compute) + } } /// Appends a log with no topic and no data: 32 bytes of data size, and a log a stop must not keep. @@ -142,7 +152,9 @@ fn frame_code(limit: Limit, depth: usize, crossing: usize, twin: bool) -> Bytes let code = match limit { Limit::Compute if twin => code.append(TIMESTAMP), Limit::Compute => work(code.append_many([TIMESTAMP, POP]), ROUNDS), - Limit::DataSize => code.sstore(CROSSING_SLOT, U256::from(1)), + Limit::DataSize | Limit::KvUpdate | Limit::StateGrowth => { + code.sstore(CROSSING_SLOT, U256::from(1)) + } }; if twin { revert(code).build() @@ -297,19 +309,21 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { // The regular gas the frames spent up to the crossing: for the compute limit, up to the read. let before_crossing = twin.gas.regular - intrinsic.gas.regular - TWIN_REVERT; - // The limit crossed, and the usage that crossed it: one more byte than the limit. The compute - // limit is set by the read, at the compute it ran to plus the cap, and the stop reports the - // compute up to the charge that crosses it: after the read's `POP`, one of the work's. - let (configured, value) = limits_of(limit, crossing); - let (value, used) = match value { - Some(value) => (value, value + 1), + // The limit crossed, and the usage that crossed it. A counted limit is crossed by the crossing + // frame's write, which takes the transaction one over its limit and the frame over its own + // budget, which the stop names. The compute limit is set by the read, at the compute it ran + // to plus the cap, and the stop reports the compute up to the charge that crosses it: after + // the read's `POP`, one of the work's. + let (configured, crossing_of) = limits_of(limit, crossing); + let (value, used, frame_local, tx_limit) = match crossing_of { + Some(Crossing { tx_limit, budget, used }) => (budget, used, true, tx_limit), None => { let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); - (before_crossing + CAP, before_crossing + CAP - left) + let value = before_crossing + CAP; + (value, value - left, false, value) } }; - let stop = - LimitCheck::ExceedsLimit { kind: limit.kind(), limit: value, used, frame_local: false }; + let stop = LimitCheck::ExceedsLimit { kind: limit.kind(), limit: value, used, frame_local }; // What ran: up to the crossing, and for the compute limit up to the charge that crosses it. // The callers that catch the stop end at no cost. let ran = if limit == Limit::Compute { used } else { before_crossing }; @@ -372,7 +386,13 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { } assert_eq!(outcome.usage, twin.usage, "{cell}: what is kept"); match limit { - Limit::DataSize => assert!(outcome.usage.data_size <= value, "{cell}: within it"), + Limit::DataSize => assert!(outcome.usage.data_size <= tx_limit, "{cell}: within it"), + Limit::KvUpdate => { + assert!(outcome.usage.write_records <= tx_limit, "{cell}: within it") + } + Limit::StateGrowth => { + assert!(outcome.usage.state_growth <= tx_limit, "{cell}: within it") + } Limit::Compute => { let compute = outcome.gas.regular - intrinsic.gas.regular; assert!(compute <= value, "{cell}: within the limit, {compute} of {value}"); @@ -381,7 +401,7 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { if !caught { assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{cell}: the body stays" ); } @@ -390,7 +410,7 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { // crossed, and every caller resumed and ended. assert_eq!(recorded.gas, plain.gas, "{row}"); assert_eq!(recorder.marker_writes(), 0, "{row}: no frame ran on after the crossing"); - if limit == Limit::DataSize { + if limit.is_counted() { assert_eq!( recorder.last_in(CHAIN[crossing]), Some((SSTORE, Some(CROSSING_SLOT))), @@ -451,9 +471,11 @@ impl Inspector, EthInterpreter> for Halter { /// An inspector that rewrites every frame result into a halt gets the halt: a stop is a revert of /// the frame that crossed, which the rewrite turns into a halt like any other result, so the -/// transaction halts, keeps nothing but its body, and reports no stop, whether the frame that +/// transaction halts, counts nothing but its body, and reports no stop, whether the frame that /// crossed was its own or three calls below, under every limit and at either tier. The stop is -/// in the inspector's hands as every result is. +/// in the inspector's hands as every result is. Each frame above the one that crossed succeeded, +/// and revm committed its journal before the inspector rewrote its result, so the log it made is +/// in the receipt, as revm leaves it. /// /// Rules: [S11.1], [S11.6]. Independence: constants — the body is `TX_BODY_SIZE`. #[test] @@ -478,10 +500,14 @@ fn test_an_inspector_that_rewrites_a_stop_into_a_halt_gets_the_halt() { evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); assert_eq!(halted.limit_exceeded, None, "{case}: the result is no stop"); - assert!(halted.result.logs().is_empty(), "{case}"); + assert_eq!( + halted.result.logs().len(), + crossing, + "{case}: the logs of the frames above the one that crossed" + ); assert_eq!( halted.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{case}: the body alone" ); } @@ -490,18 +516,54 @@ fn test_an_inspector_that_rewrites_a_stop_into_a_halt_gets_the_halt() { } } -/// The limits a cell runs under, and the stop's limit where it is known before the run: every -/// dimension but the compute limit, which the read sets. -fn limits_of(limit: Limit, crossing: usize) -> (EvmTxRuntimeLimits, Option) { +/// Where a counted limit is crossed: the transaction's limit, the budget of the frame that crosses +/// it, which the stop names, and what that frame used of it with the write that crossed. +#[derive(Clone, Copy, Debug)] +struct Crossing { + tx_limit: u64, + budget: u64, + used: u64, +} + +/// The limits a cell runs under, and where a counted limit is crossed, which is known before the +/// run: every dimension but the compute limit, which the read sets. +/// +/// The transaction's limit is one short of what the chain keeps with the crossing write. The +/// transaction's own frame gets what the body leaves of it, and each frame below 98% of what its +/// caller has left at its call: `A` has logged and written its [`OWN_SLOTS`] by then, `B` and `C` +/// have logged. The crossing frame's write crosses its budget, the transaction's limit with it. +fn limits_of(limit: Limit, crossing: usize) -> (EvmTxRuntimeLimits, Option) { let frames = crossing as u64 + 1; - match limit { + // What the transaction's own frame keeps before it calls or crosses, what a frame below keeps + // before it calls or crosses, and what the crossing write adds, in the limit's unit. + let (own, below, write) = match limit { + Limit::DataSize => (LOG_BASE_SIZE + OWN_SLOTS * WRITE_RECORD_SIZE, LOG_BASE_SIZE, 40), + // The fresh slots are new slots, one each, as they are write records. + Limit::KvUpdate | Limit::StateGrowth => (OWN_SLOTS, 0, 1), + Limit::Compute => return (EvmTxRuntimeLimits::default(), None), + }; + let (limits, tx_limit, outside) = match limit { Limit::DataSize => { - let value = - TX_BODY_SIZE + frames * LOG_BASE_SIZE + (OWN_SLOTS + 1) * WRITE_RECORD_SIZE - 1; - (EvmTxRuntimeLimits::default().with_tx_data_size_limit(value), Some(value)) + let value = TX_BODY_SIZE + own + (frames - 1) * below + write - 1; + (EvmTxRuntimeLimits::default().with_tx_data_size_limit(value), value, TX_BODY_SIZE) + } + Limit::KvUpdate => { + let value = own + (frames - 1) * below + write - 1; + (EvmTxRuntimeLimits::default().with_tx_kv_update_limit(value), value, 0) } - Limit::Compute => (EvmTxRuntimeLimits::default(), None), + _ => { + let value = own + (frames - 1) * below + write - 1; + (EvmTxRuntimeLimits::default().with_tx_state_growth_limit(value), value, 0) + } + }; + let share = |left: u64| left * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let mut budget = tx_limit - outside; + let mut kept = own; + for _ in 0..crossing { + budget = share(budget - kept); + kept = below; } + (limits, Some(Crossing { tx_limit, budget, used: kept + write })) } /* ---------- creations under an inspector that revives them ---------- */ @@ -514,7 +576,7 @@ enum Creation { /// The transaction's own frame creates a contract whose init code crosses the limit. Nested, /// The transaction's own frame creates a contract whose start crosses the limit — its write - /// records, or the account it adds — so its init code never runs. + /// records, or the new account it adds — so its init code never runs. NestedStart, } @@ -548,44 +610,77 @@ fn creation_run( } } +/// `creation` for `limit` run without limits, where it succeeds. +fn unlimited_creation_run( + creation: Creation, + limit: Limit, + gas_limit: u64, +) -> MegaTransactionOutcome { + let (db, tx) = creation_run(creation, limit, gas_limit); + let unlimited = + MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(unlimited.result.is_success(), "{creation:?}, {limit:?}: {:?}", unlimited.result); + unlimited +} + /// The limits under which `creation` crosses `limit` by one unit at the place it names. /// /// Where the init code crosses, the limit is one unit below what the whole transaction uses without -/// limits, whose last write is the init code's; the compute limit is the spec's cap. Where the -/// start crosses, the limit is what the transaction used before it. +/// limits, whose last write is the init code's; the compute limit is the spec's cap. For a nested +/// creation's data size it is one record below: a byte below, the creation's share would hold all +/// it writes, and the stop would be its creator's once its nonce record is counted; a record below, +/// the share falls short of the creation's last write by the part its creator keeps. Where the +/// start crosses, the limit is what the transaction used before it and the creator's nonce record: +/// the creation's share of that falls short of its start, and the creator keeps its record once +/// the creation returned. fn creation_limits(creation: Creation, limit: Limit, gas_limit: u64) -> EvmTxRuntimeLimits { let limits = EvmTxRuntimeLimits::default(); if matches!(creation, Creation::NestedStart) { return match limit { - Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE), + Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE), + Limit::KvUpdate => limits.with_tx_kv_update_limit(1), + // `A` exists, so its nonce record is no new account. + Limit::StateGrowth => limits.with_tx_state_growth_limit(0), Limit::Compute => unreachable!("a start charges no compute past the cap"), }; } - let (db, tx) = creation_run(creation, limit, gas_limit); - let unlimited = - MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) - .execute_transaction(tx) - .expect("the transaction is valid"); - assert!(unlimited.result.is_success(), "{creation:?}, {limit:?}: {:?}", unlimited.result); - match limit { - Limit::DataSize => limits.with_tx_data_size_limit(unlimited.usage.data_size - 1), - Limit::Compute => limits, + let unlimited = unlimited_creation_run(creation, limit, gas_limit); + match (creation, limit) { + (Creation::Nested, Limit::DataSize) => { + limits.with_tx_data_size_limit(unlimited.usage.data_size - WRITE_RECORD_SIZE) + } + (_, Limit::DataSize) => limits.with_tx_data_size_limit(unlimited.usage.data_size - 1), + (_, Limit::KvUpdate) => limits.with_tx_kv_update_limit(unlimited.usage.write_records - 1), + // The created account and the init code's slot are the creation's new state, two of it: + // a nested creation's budget, 98% of the whole count, is one short of them. + (Creation::Nested, Limit::StateGrowth) => { + limits.with_tx_state_growth_limit(unlimited.usage.state_growth) + } + (_, Limit::StateGrowth) => { + limits.with_tx_state_growth_limit(unlimited.usage.state_growth - 1) + } + (_, Limit::Compute) => limits, } } /// A creation the limit stopped, revived by an inspector that rewrites every frame result into a -/// success, settles as a frame that kept nothing, as a revived call does, and is no stop: the -/// result of the transaction's own frame is the inspector's success, so the outcome names no stop. -/// A creation transaction whose init code crosses a limit, a nested creation whose init code -/// crosses one, and a nested creation whose start crosses one each end with the stop before their -/// revival, deploy nothing, keep what the run without the inspector keeps, and bill what it bills, -/// below the execution cap and above it. +/// success, is taken as given, as a revived call is, and is no stop: the result of the +/// transaction's own frame is the inspector's success, so the outcome names no stop. A creation +/// transaction whose init code crosses a limit, a nested creation whose init code crosses one, and +/// a nested creation whose start crosses one each end with the stop before their revival and deploy +/// nothing: the stop reverted the creation's journal. The revival settles as a success, so what the +/// creation counted before it crossed is kept — all the creation counts without limits but the +/// write that crossed. Where its start crossed, it counted nothing of the start: its creator keeps +/// its own nonce record, counted on it once the creation returned, and catches the start's stop, +/// so the revival changes the creation's result alone. Below the execution cap and above it. #[test] -fn test_a_revived_creation_settles_as_a_frame_that_kept_nothing() { +fn test_a_revived_creation_keeps_what_it_counted_before_its_stop() { let cases = [ (Creation::Transaction, Limit::ALL.as_slice()), (Creation::Nested, Limit::ALL.as_slice()), - (Creation::NestedStart, [Limit::DataSize].as_slice()), + (Creation::NestedStart, [Limit::DataSize, Limit::KvUpdate, Limit::StateGrowth].as_slice()), ]; for (creation, limits) in cases { for &limit in limits { @@ -626,8 +721,30 @@ fn test_a_revived_creation_settles_as_a_frame_that_kept_nothing() { revived.state.get(&created).is_none_or(|account| account.info.is_empty()), "{case}: nothing deployed" ); - assert_eq!(revived.usage, plain.usage, "{case}: what the plain run keeps"); - assert_eq!(revived.gas, plain.gas, "{case}: what the plain run bills"); + let unlimited = unlimited_creation_run(creation, limit, gas_limit); + let counted = match (creation, limit) { + // `A` exists, so its nonce record is no new account. + (Creation::NestedStart, _) => LimitUsage { + data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 0, + }, + // The crossing write, a fresh slot, is one record and one new slot. + (_, Limit::DataSize | Limit::KvUpdate | Limit::StateGrowth) => LimitUsage { + data_size: unlimited.usage.data_size - WRITE_RECORD_SIZE, + write_records: unlimited.usage.write_records - 1, + state_growth: unlimited.usage.state_growth - 1, + }, + (_, Limit::Compute) => unlimited.usage, + }; + assert_eq!(revived.usage, counted, "{case}: what it counted before its stop"); + if matches!(creation, Creation::NestedStart) { + // `A` catches the start's stop and keeps the same. + assert!(plain.result.is_success(), "{case}: {:?}", plain.result); + assert_eq!(plain.usage, counted, "{case}: the stop kept nothing of the start"); + } else { + assert_ne!(revived.usage, plain.usage, "{case}: which the stop takes back"); + } } } } @@ -919,6 +1036,14 @@ fn slots_past_the_cap() -> u64 { CAP / fresh_write() + 1 } +/// The spec's limits with the state-growth limit lifted, which these rows run under: their writes +/// are [`slots_past_the_cap`] fresh slots, more than the 1,000 new slots the spec's limit lets a +/// transaction keep, so under it the 1,001st slot would stop the frame before its compute reached +/// the cap. +fn detention_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::default().with_tx_state_growth_limit(u64::MAX) +} + /// Appends writes of the fresh slots `1..=`[`slots_past_the_cap`]: 20,011,218 of compute at the /// schedule's prices, past the cap. fn writes_past_the_cap(code: BytecodeBuilder) -> BytecodeBuilder { @@ -1007,7 +1132,7 @@ fn test_volatile_data_access_oog_does_not_consume_all_gas() { let code = writes_past_the_cap(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); let db = MemoryDatabase::default().account_code(A, code.stop().build()); let left = pop_then_writes().left(CAP); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, accessed) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); assert_eq!(accessed, mega_evm::VolatileDataAccess::TIMESTAMP); } @@ -1026,7 +1151,7 @@ fn test_nested_call_block_env_access_child_oog() { // charge was not made from. let left = pop_then_writes().left(CAP); let left = Charges::default().then(&[2]).fresh_writes(1).left(left); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 10_000, "the child read near the start: {}", limit - CAP); } @@ -1046,7 +1171,7 @@ fn test_parent_block_env_access_oog_after_nested_call() { .then(&[2, 2, 2, 2, 2, 2, 3, 2, cold_access(), 3, 3, 3, 2, 2]) .fresh_writes(slots_past_the_cap()) .left(CAP); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); } @@ -1058,7 +1183,7 @@ fn test_an_oracle_read_holds_the_transaction_to_its_cap() { let code = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), None)); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, accessed) = assert_detention_stop(db, detention_limits(), left); assert!(limit - ORACLE_ACCESS_COMPUTE_GAS < 10_000, "{}", limit - ORACLE_ACCESS_COMPUTE_GAS); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1069,7 +1194,7 @@ fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { let code = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), Some(0xffff))); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); - assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert_detention_stop(db, detention_limits(), left); } /// A contract that calls one that reads the Oracle's storage and then writes the fresh slots: the @@ -1096,8 +1221,7 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { 2, ]; let left = Charges::default().then(&sload).left(left); - let (_, accessed) = - assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), left); + let (_, accessed) = assert_detention_stop(with_oracle_read(db), detention_limits(), left); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1109,7 +1233,7 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { const ORACLE_CAP: u64 = 1_000_000; let code = call_oracle(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), Some(0xffff)); let db = MemoryDatabase::default().account_code(A, writes_past_the_cap(code).stop().build()); - let limits = EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(ORACLE_CAP); + let limits = detention_limits().with_oracle_access_compute_gas_limit(ORACLE_CAP); let left = oracle_pops_then_writes().left(ORACLE_CAP); let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, left); assert!(limit - ORACLE_CAP < 10_000, "the Oracle's read binds: {limit}"); @@ -1126,7 +1250,7 @@ fn test_volatile_access_post_access_cap_enforced() { let code = work(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), ROUNDS); let db = MemoryDatabase::default().account_code(A, code.stop().build()); let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 1_000, "{}", limit - CAP); } @@ -1227,7 +1351,10 @@ fn test_data_limit_exceed_in_nested_call() { let outcome = execute(db, EvmTxRuntimeLimits::default().with_tx_data_size_limit(limit), BELOW); assert!(outcome.result.is_success(), "the caller caught the stop: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None); - assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); let ran = 15_000 + 15 + 3_000 + 5 + 2_100 + 10_100 + 2; assert_eq!(outcome.gas.regular, ran, "what ran, on the regular ledger"); assert_eq!(outcome.gas.history, body_history(0), "the body's history alone"); @@ -1236,7 +1363,8 @@ fn test_data_limit_exceed_in_nested_call() { } /// A value transfer to a contract that writes a slot, under a limit one byte above the body: the -/// first frame's start crosses it, so the value never moves and the contract never runs. +/// first frame's start crosses it — its own budget of one byte, and the transaction's limit — so +/// the value never moves and the contract never runs. #[test] fn test_state_revert_when_exceeding_limit() { let db = MemoryDatabase::default() @@ -1251,9 +1379,12 @@ fn test_state_revert_when_exceeding_limit() { assert!( matches!( stop, - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, frame_local: false, .. } - if limit == TX_BODY_SIZE + 1 + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: 1, frame_local: true, .. } ), + "the frame's budget, the byte the body leaves: {stop:?}" + ); + assert!( + matches!(stop, LimitCheck::ExceedsLimit { used, .. } if used == WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE), "{stop:?}" ); assert!( @@ -1262,7 +1393,10 @@ fn test_state_revert_when_exceeding_limit() { "{:?}", outcome.result ); - assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); assert!(outcome.state.get(&A).is_none_or(|a| a.storage.is_empty() && a.info.balance.is_zero())); assert_eq!(outcome.state[&CALLER].info.balance, U256::from(10_000), "the value did not move"); } @@ -1295,15 +1429,15 @@ fn test_detention_plus_intrinsic_data_size_overflow() { } /// A call a data-size limit stopped — its own frame budget, or the transaction's limit — revived -/// into a success by an inspector, hands its caller nothing it counted: its checkpoint was reverted -/// before the inspector saw its result, so its log is not kept, and its lane goes the way its log -/// did. Its caller runs on within the limits, and the transaction is the one no inspector runs: the -/// rewrite changed only the flag `A` drops. +/// into a success by an inspector, hands its caller nothing to count: its checkpoint was reverted +/// before the inspector saw its result, so its log is not kept, and the log was its one write, +/// which the crossing counted nothing of. Its caller runs on within the limits, and the transaction +/// is the one no inspector runs: the rewrite changed only the flag `A` drops. /// /// Under a frame cap of 1,000 bytes `A` gives `B` 98% of it, and `B`'s log of 1,000 bytes counts /// 1,032, which crosses `B`'s budget, and would cross `A`'s were it handed on. Under a transaction -/// limit of the body and 1,000 bytes the same log crosses the transaction's limit, which is checked -/// first. +/// limit of the body and 1,000 bytes the same log crosses the transaction's limit and `B`'s budget, +/// 98% of the 1,000 `A` is given, which is checked first and named. #[test] fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { const CAP: u64 = 1_000; @@ -1321,9 +1455,7 @@ fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { let unlimited = EvmTxRuntimeLimits::no_limits(); let rows = [ ("its frame budget", unlimited.with_frame_data_size_limit(CAP), share), - ("the transaction's limit", unlimited.with_tx_data_size_limit(TX_BODY_SIZE + CAP), { - TX_BODY_SIZE + CAP - }), + ("the transaction's limit", unlimited.with_tx_data_size_limit(TX_BODY_SIZE + CAP), share), ]; for (row, limits, crossed) in rows { let plain = execute(db.clone(), limits, BELOW); @@ -1352,8 +1484,12 @@ fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { assert_eq!(outcome.limit_exceeded, None, "{row}: a stop below is no stop"); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, - "{row}: the body and A's marker: none of B's log" + LimitUsage { + data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 1 + }, + "{row}: the body and A's marker, a new slot: none of B's log" ); assert!(outcome.result.logs().is_empty(), "{row}: B's log was reverted with B"); assert!(plain.result.is_success(), "{row}: {:?}", plain.result); @@ -1371,14 +1507,14 @@ const EMPTY: Address = address!("0000000000000000000000000000000000500005"); #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Answered { /// An inspector answers the call to `D` having spent all it was forwarded, past what the - /// compute limit leaves the frame. An interceptor's answer is settled the same way; none of - /// this engine's interceptors spends gas. + /// compute limit leaves the frame. An inspector's answer is taken as given: it is no stop + /// (see [`test_an_inspectors_answer_past_the_allowance_is_taken_as_given`]). PastTheAllowance, /// `C` calls a precompile priced past the cap, which revm runs on the allowance: it runs out /// of it without computing. Precompile, /// `C` sends a wei to [`EMPTY`], whose start's records and transfer log cross the data-size - /// limit, before revm builds the frame. + /// limit once revm answered the call. StartRecords, } @@ -1446,27 +1582,41 @@ fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { stop(LimitKind::ComputeGas, 2 + CAP, 2 + to_the_answer(answered)), ), Answered::StartRecords => { - // The body, and one byte short of the start's two records and its transfer log. - let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; + // The body, and one byte short of the start's two records and its transfer log. The + // start three calls down crosses the budget it would start with too, 98% of 98% of + // 98% of what the body leaves, which the stop names. + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let limit = TX_BODY_SIZE + start - 1; + let share = + |left: u64| left * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let budget = share(share(share(start - 1))); ( EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), - stop(LimitKind::DataSize, limit, limit + 1), + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: budget, + used: start, + frame_local: true, + }, ) } } } /// Answers every call to `D` itself, having spent all the gas it was forwarded, and records every -/// frame it sees end, deepest first, with the result and output it had; with `rewrite`, it then -/// rewrites that result into a success, as [`FrameRecorder`] does. +/// frame it sees end, deepest first, with the result and output it had, and the gas the call to `D` +/// was forwarded; with `rewrite`, it then rewrites that result into a success, as +/// [`FrameRecorder`] does. struct AnswersD { rewrite: bool, ended: Vec<(Address, InstructionResult, Bytes)>, + forward: Option, } impl Inspector, EthInterpreter> for AnswersD { fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { (inputs.target_address == D).then(|| { + self.forward = Some(inputs.gas_limit); let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); gas.spend_all(); @@ -1492,12 +1642,14 @@ impl Inspector, EthInterpreter> for AnswersD { } } -/// A run of an answered chain: its outcome, the frames an inspector saw end, and what the -/// precompile at [`PRICED`] ran on, each with whether its price was within it. +/// A run of an answered chain: its outcome, the frames an inspector saw end, what the precompile +/// at [`PRICED`] ran on, each with whether its price was within it, and the gas an inspector's +/// answer to `D` was forwarded. struct AnsweredRun { outcome: MegaTransactionOutcome, ended: Vec<(Address, InstructionResult, Bytes)>, ran_on: Vec<(u64, bool)>, + forward: Option, } /// Runs the stopped chain of `answered` under `limits` at `gas_limit`, with the precompile at @@ -1514,20 +1666,20 @@ fn run_answered( let evm = MegaEvm::new(context(answered_chain(answered)).with_tx_runtime_limits(limits)) .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])); let tx = call(CALLER, A, U256::ZERO, gas_limit); - let (outcome, ended) = if answered == Answered::PastTheAllowance { - let mut evm = evm.with_inspector(AnswersD { rewrite, ended: Vec::new() }); + let (outcome, ended, forward) = if answered == Answered::PastTheAllowance { + let mut evm = evm.with_inspector(AnswersD { rewrite, ended: Vec::new(), forward: None }); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); - (outcome, evm.inspector().ended.clone()) + (outcome, evm.inspector().ended.clone(), evm.inspector().forward) } else if rewrite { let mut evm = evm.with_inspector(FrameRecorder::rewriting()); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); - (outcome, evm.inspector().ended.clone()) + (outcome, evm.inspector().ended.clone(), None) } else { let mut evm = evm; - (evm.execute_transaction(tx).expect("the transaction is valid"), Vec::new()) + (evm.execute_transaction(tx).expect("the transaction is valid"), Vec::new(), None) }; let ran_on = runs.lock().unwrap().clone(); - AnsweredRun { outcome, ended, ran_on } + AnsweredRun { outcome, ended, ran_on, forward } } /// One answered cell, both columns: `answered`'s chain at `gas_limit`, without the rewrite and @@ -1541,40 +1693,50 @@ fn run_answered( /// back. That run is on the same engine, so its bill pins that a stop bills what ran and no more; /// it pins no price, and a charge both runs make, such as `C`'s own `CALL`, would be wrong in both /// alike. +/// +/// A start's stop the inspector rewrites into a success is taken as given: the success gives back +/// neither the account the start's `CALL` was charged for nor the history of the start's records, +/// so that column bills the state and history gas of the run without limits, where the start is +/// kept, while it counts nothing and moves nothing, as the stop left it. fn assert_answered_cell(answered: Answered, gas_limit: u64) { let row = format!("{answered:?}, gas limit {gas_limit}"); let intrinsic = intrinsic(gas_limit); let (limits, stop) = answered_limits(answered); let LimitCheck::ExceedsLimit { kind, used, .. } = stop else { unreachable!() }; - let ran = if kind == LimitKind::ComputeGas { - used + 3 * 2 - } else { + let free = (kind != LimitKind::ComputeGas).then(|| { let free = execute(answered_chain(answered), EvmTxRuntimeLimits::no_limits(), gas_limit); assert!(free.result.is_success(), "{row}: without limits: {:?}", free.result); assert_eq!(balance_of(&free, EMPTY), U256::from(1), "{row}: the start moves its wei"); - free.gas.regular - intrinsic.gas.regular - }; + free + }); + let ran = free.as_ref().map_or(used + 3 * 2, |free| free.gas.regular - intrinsic.gas.regular); let plain = run_answered(answered, limits, gas_limit, false); let rewritten = run_answered(answered, limits, gas_limit, true); for (column, run) in [("not rewritten", &plain), ("rewritten", &rewritten)] { let cell = format!("{row}, {column}"); let outcome = &run.outcome; + let (state, history) = match (&free, column) { + (Some(free), "rewritten") => (free.gas.state, free.gas.history), + _ => (0, intrinsic.gas.history), + }; + let kept = state + history - intrinsic.gas.history; assert!(outcome.result.is_success(), "{cell}: the callers caught the stop"); assert_eq!(outcome.limit_exceeded, None, "{cell}: a stop below is no stop of it"); assert_eq!(outcome.gas.regular, intrinsic.gas.regular + ran, "{cell}: regular"); - assert_eq!(outcome.gas.state, 0, "{cell}: the stop keeps no state gas"); - assert_eq!(outcome.gas.history, intrinsic.gas.history, "{cell}: the body's history alone"); + assert_eq!(outcome.gas.state, state, "{cell}: the state gas"); + assert_eq!(outcome.gas.history, history, "{cell}: the history gas"); assert_eq!(outcome.gas.history_bytes, intrinsic.gas.history_bytes, "{cell}"); assert_eq!( - outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining, - "{cell}: the reservoir comes back, less the body it paid" + outcome.gas.reservoir_remaining, + intrinsic.gas.reservoir_remaining.saturating_sub(kept), + "{cell}: the reservoir comes back, less the body it paid and what is kept" ); - assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + ran, "{cell}: gas used"); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + ran + kept, "{cell}: gas used"); assert!(outcome.result.logs().is_empty(), "{cell}: no log is kept"); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{cell}: the body stays" ); assert_eq!(balance_of(outcome, EMPTY), U256::ZERO, "{cell}: no value moved"); @@ -1583,8 +1745,10 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { assert_eq!(run.ran_on, [(allowance, false)], "{cell}: run on the allowance"); } } - assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); - assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); + if free.is_none() { + assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); + assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); + } let ended = vec![ (answered.target(), InstructionResult::Revert, stop.revert_data()), (C, InstructionResult::Stop, Bytes::new()), @@ -1595,13 +1759,6 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { rewritten.ended, ended, "{row}: the answered frame ended stopped, then every caller ended" ); - if answered == Answered::PastTheAllowance { - // Its answer is an inspector's, which in this column rewrites nothing. - assert_eq!( - plain.ended, ended, - "{row}, not rewritten: the answered frame ended stopped, then every caller ended" - ); - } } /// The balance `address` holds after `outcome`: zero for an account it did not touch. @@ -1610,27 +1767,137 @@ fn balance_of(outcome: &MegaTransactionOutcome, address: Address) -> U256 { } /// A frame three calls down that is answered without running, and whose answer crosses a limit, is -/// the stop as a frame that ran there would be: an answer past what the compute limit leaves the -/// frame, and a precompile run on that allowance and priced past it. Below the execution cap and -/// above it, with and without an inspector that rewrites every frame result into a success, the -/// answer is the stop, its caller catches it, every frame ends, and the transaction bills what -/// ran, keeps the body's history and nothing else, and gets its reservoir back. +/// the stop as a frame that ran there would be: a precompile run on what the compute limit leaves +/// the frame and priced past it. Below the execution cap and above it, with and without an +/// inspector that rewrites every frame result into a success, the answer is the stop, its caller +/// catches it, every frame ends, and the transaction bills what ran, keeps the body's history and +/// nothing else, and gets its reservoir back. #[test] fn test_an_answer_three_calls_down_is_the_stop_its_caller_catches_at_either_tier() { - for answered in [Answered::PastTheAllowance, Answered::Precompile] { - for gas_limit in TIERS { - assert_answered_cell(answered, gas_limit); + for gas_limit in TIERS { + assert_answered_cell(Answered::Precompile, gas_limit); + } +} + +/// An inspector's answer is taken as given, as revm's inspected frame start takes it: gas detention +/// holds the engine's answers to the compute limit, and a frame the inspector answers never +/// reaches the engine's frame start. An inspector's answer to `D`, three calls down, that spent all +/// it was forwarded, past what the compute limit leaves the frame, is no stop: `D` ends as the +/// inspector answered it, and what it spent is `C`'s compute. Every caller then resumes on what the +/// limit leaves the transaction, nothing, and crosses it at its next charge, its `POP`: the +/// inspector sees each end with the stop, and the stop of the transaction's own frame is the +/// transaction's result, which reports the compute at that crossing — the read, the calls down and +/// the answer's forward, past the limit — and bills it. +#[test] +fn test_an_inspectors_answer_past_the_allowance_is_taken_as_given() { + for gas_limit in TIERS { + let row = format!("gas limit {gas_limit}"); + let intrinsic = intrinsic(gas_limit); + let (limits, _) = answered_limits(Answered::PastTheAllowance); + let run = run_answered(Answered::PastTheAllowance, limits, gas_limit, false); + let forward = run.forward.expect("the inspector answered the call to D"); + let used = 2 + to_the_answer(Answered::PastTheAllowance) + forward; + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: 2 + CAP, + used, + frame_local: false, + }; + assert_eq!(run.outcome.limit_exceeded, Some(stop), "{row}: the transaction's own stop"); + match &run.outcome.result { + ExecutionResult::Revert { output, .. } => { + assert_eq!(output, &stop.revert_data(), "{row}: the stop's revert data") + } + other => panic!("{row}: expected the stop, got {other:?}"), } + assert_eq!(run.outcome.gas.regular, intrinsic.gas.regular + used, "{row}: regular"); + let stopped = |frame| (frame, InstructionResult::Revert, stop.revert_data()); + assert_eq!( + run.ended, + [(D, InstructionResult::Stop, Bytes::new()), stopped(C), stopped(B), stopped(A)], + "{row}: D ended as answered, then every caller returned the stop" + ); } } /// A frame three calls down whose start's records and transfer log cross the data-size limit is -/// answered with the stop before revm builds it: no value moves and no account is added. Its -/// caller catches the stop, below the execution cap and above it, with and without the rewriting -/// inspector. +/// answered with the stop once revm answered it, and what its start moved goes back with it: no +/// value stays moved and no account is added. Its caller catches the stop, below the execution +/// cap and above it, with and without the rewriting inspector, whose success keeps what the start +/// was charged at its caller's opcode. #[test] -fn test_a_start_three_calls_down_crossing_the_limit_is_stopped_before_it_is_built() { +fn test_a_start_three_calls_down_crossing_the_limit_is_stopped_at_its_start() { for gas_limit in TIERS { assert_answered_cell(Answered::StartRecords, gas_limit); } } + +/* ---------- a stopped answer gives its caller back its share ---------- */ + +/// A start revm answers without building a frame — a value call to an account with no code — and +/// whose records cross a budget gives way to the stop on the pools the frame would have started +/// with, which go back to its caller as a failed frame's do: the caller then holds what it held +/// before the call, and a write of its own past its budget is stopped by that budget. +/// +/// `B`, given a budget of nine slots, records or growth units by `A`, fills it, sends one wei to an +/// account that does not exist, whose start's records and new account cross the share of nothing +/// it gets, and catches that stop; its next fresh slot crosses its own budget of nine, and `A` +/// returns that stop. In each of the three counted dimensions, below the execution cap and above +/// it. +#[test] +fn test_a_stopped_answer_gives_its_caller_back_its_share() { + const OWN: u64 = 9; + // The call from `CALLER` to `A` carries no value and no calldata: the transaction's own frame + // gets what the limit leaves of the body, and `B` the share of that. The smallest data-size + // limit that leaves `B` nine records is the body and nine records' bytes scaled back up by the + // share, rounded up. + let records = OWN * WRITE_RECORD_SIZE; + let data_size_limit = TX_BODY_SIZE + + (records * FRAME_DATA_SHARE_DENOMINATOR).div_ceil(FRAME_DATA_SHARE_NUMERATOR); + let limits = [ + (LimitKind::DataSize, records, data_size_limit), + (LimitKind::KvUpdate, OWN, 10), + (LimitKind::StateGrowth, OWN, 10), + ]; + let mut b = BytecodeBuilder::default(); + for slot in 1..=OWN { + b = b.sstore(U256::from(slot), U256::from(1)); + } + let b = b + .call(C, U256::from(1)) + .append(POP) + .sstore(U256::from(OWN + 1), U256::from(1)) + .stop() + .build(); + let a = BytecodeBuilder::default().call(B, U256::ZERO).append(POP).return_returndata().build(); + for (kind, budget, limit) in limits { + let mut under = EvmTxRuntimeLimits::default(); + under = match kind { + LimitKind::DataSize => under.with_tx_data_size_limit(limit), + LimitKind::KvUpdate => under.with_tx_kv_update_limit(limit), + LimitKind::StateGrowth => under.with_tx_state_growth_limit(limit), + LimitKind::ComputeGas => unreachable!(), + }; + let held = + |remaining: u64| remaining * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let own_frame = if kind == LimitKind::DataSize { limit - TX_BODY_SIZE } else { limit }; + assert_eq!(held(own_frame), budget, "{kind:?}: B's budget"); + for gas_limit in TIERS { + let row = format!("{kind:?}, gas limit {gas_limit}"); + let db = MemoryDatabase::default() + .account_code(A, a.clone()) + .account_code(B, b.clone()) + .account_balance(B, U256::from(1)); + let outcome = execute(db, under, gas_limit); + assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); + let stop = LimitCheck::ExceedsLimit { kind, limit: budget, used: 0, frame_local: true }; + assert_eq!( + outcome.result.output(), + Some(&stop.revert_data()), + "{row}: B's own slot crossed its budget, not a pool the answer lifted" + ); + assert_eq!(outcome.limit_exceeded, None, "{row}: A caught B's stop"); + assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, ..LimitUsage::ZERO }); + } + } +} diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index c33ef7f6d..c7d45c169 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -6,7 +6,9 @@ //! crosses again stops it in turn. A transaction whose own frame is stopped settles like an //! EIP-8037 revert: the sender gets the unspent regular gas and the whole reservoir back. A real //! out-of-gas still halts and burns. The limit here is the configurable data-size cap of -//! `EvmTxRuntimeLimits`; a write record is 40 bytes. +//! `EvmTxRuntimeLimits`; a write record is 40 bytes. A frame that crosses the transaction's limit +//! crosses its own budget too — the budgets of the frames on the stack add up to what the +//! transaction has left — and the stop names the budget, which is tested first. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; @@ -150,16 +152,19 @@ impl Inspector, EthInterpreter> for Probe { /// Crossing the cap at depth 3 reverts `D` alone, and every caller resumes, held to what the /// transaction has left: `C`'s log after its second write crosses the cap again and stops `C`, /// `B` writes and logs within it, and `A`'s second write crosses it once more and stops the -/// transaction's own frame, which takes back everything below it. Each stop names the cap, and -/// at no point does the transaction keep more than it. +/// transaction's own frame, which takes back everything below it. At no point does the +/// transaction keep more than the cap. /// /// What each crossing reached, above the body: `A`, `B`, `C` and `D`'s first writes are four /// records (160 bytes), and `D`'s second makes 200; `C`'s second write makes 160 again, and its -/// log 192; `B`'s second write and log make 152; `A`'s second write 192. +/// log 192; `B`'s second write and log make 152; `A`'s second write 192. Each crossing crosses the +/// frame's own budget too, so each stop names that budget: `A`'s is the 180 the transaction has +/// left; `B` gets 98% of the 140 `A` has after its write, 137; `C` 98% of `B`'s 97, 95; `D` 98% of +/// `C`'s 55, 53. #[test] fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { let limit = mega_evm::TX_BODY_SIZE + 180; - let stop = limit_exceeded(LimitKind::DataSize, limit); + let stop = |budget| limit_exceeded(LimitKind::DataSize, budget); for inspect in [false, true] { let mut evm = evm_with( chain(), @@ -169,16 +174,16 @@ fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&outcome.result, LimitKind::DataSize, limit); + assert_stopped(&outcome.result, LimitKind::DataSize, 180); assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit, - used: mega_evm::TX_BODY_SIZE + 192, - frame_local: false + limit: 180, + used: 192, + frame_local: true }), - "A's own crossing produced its result" + "A's own crossing of its budget produced its result" ); assert!(outcome.result.logs().is_empty()); for account in [A, B, C, D] { @@ -196,10 +201,10 @@ fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { assert_eq!( probe.call_results, vec![ - (D, InstructionResult::Revert, stop.clone()), - (C, InstructionResult::Revert, stop.clone()), + (D, InstructionResult::Revert, stop(53)), + (C, InstructionResult::Revert, stop(95)), (B, InstructionResult::Stop, Bytes::new()), - (A, InstructionResult::Revert, stop.clone()), + (A, InstructionResult::Revert, stop(180)), ], "each frame that crossed returned the stop, the deepest first" ); @@ -213,19 +218,19 @@ fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { fn test_stop_refills_the_reservoir_at_any_gas_limit() { let at = |gas_limit: u64| { let result = run(chain(), cap(180), call(CALLER, A, U256::ZERO, gas_limit)); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); - *result.result.gas() + assert_stopped(&result.result, LimitKind::DataSize, 180); + result }; let small = at(100_000_000); let large = at(1_000_000_000); - assert_eq!(small.reservoir_remaining(), 0, "a limit under the cap has no reservoir"); + assert_eq!(small.gas.reservoir_remaining, 0, "a limit under the cap has no reservoir"); assert_eq!( - large.reservoir_remaining(), + large.gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(), "all of it back but the body's history, which the stop does not take back", ); - assert_eq!(small.tx_gas_used(), large.tx_gas_used()); - assert_eq!(small.total_gas_spent(), large.total_gas_spent()); + assert_eq!(small.result.gas().tx_gas_used(), large.result.gas().tx_gas_used()); + assert_eq!(small.result.gas().total_gas_spent(), large.result.gas().total_gas_spent()); } /// An `SSTORE` that runs out of gas after its Host call records nothing, so a cap of zero does @@ -275,9 +280,10 @@ fn test_child_out_of_gas_under_a_cap_is_no_stop() { result.usage, mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE + mega_evm::WRITE_RECORD_SIZE, - write_records: 1 + write_records: 1, + state_growth: 1, }, - "A's record alone, which meets the cap and does not cross it" + "A's record alone, which meets the cap and does not cross it, and its fresh slot" ); } @@ -293,13 +299,17 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); let mut evm = evm_with(funded().account_code(B, writer()), cap(39), Probe::default()); let result = evm.transact_raw(call(CALLER, B, U256::from(5), GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 39); + assert_stopped(&result.result, LimitKind::DataSize, 39); assert!(evm.inspector().steps.is_empty(), "the recipient's code never ran"); assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); assert_eq!( - evm.ctx().additional_limit().usage(), - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + evm.ctx().limit_usage(), + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE, + write_records: 0, + state_growth: 0 + }, "the body stays; the recipient record does not" ); @@ -372,7 +382,11 @@ fn test_frame_budget_of_the_outermost_frame_reverts_the_transaction() { ); assert_eq!( result.usage, - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE, + write_records: 0, + state_growth: 0 + }, "the body is all the transaction keeps" ); } @@ -400,8 +414,12 @@ fn test_the_stop_does_not_outlive_its_transaction() { .is_success()); assert!(!stopped(&evm)); assert_eq!( - evm.ctx().additional_limit().usage(), - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + evm.ctx().limit_usage(), + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE, + write_records: 0, + state_growth: 0 + }, "an empty call keeps its body" ); @@ -430,7 +448,7 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { let room = init_code.len() as u64 + mega_evm::WRITE_RECORD_SIZE - 1; let tx = crate::common::create(CALLER, init_code.clone(), GAS_LIMIT); let result = run(MemoryDatabase::default(), cap(room), tx); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + room); + assert_stopped(&result.result, LimitKind::DataSize, room - init_code.len() as u64); assert!(result.limit_exceeded.is_some()); assert_eq!(result.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); assert!(result.state.get(&CALLER.create(0)).is_none_or(|a| a.info.is_empty_code_hash())); @@ -440,7 +458,7 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { let tx = crate::common::create(CALLER, init_code.clone(), 1_000_000_000); let result = run(MemoryDatabase::default(), cap(room), tx); assert_eq!( - result.result.gas().reservoir_remaining(), + result.gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - create_body_history(init_code.len() as u64), ); } @@ -458,7 +476,7 @@ fn test_usage_equal_to_the_limit_does_not_stop() { let result = run(db(), budget, call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert!(result.result.is_success(), "{:?}", result.result); let result = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 119); + assert_stopped(&result.result, LimitKind::DataSize, 119); } /// A tool's inspector that writes to the running frame's gas. @@ -525,7 +543,7 @@ fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { assert_eq!(plain.gas.state, 9 * slot_state_gas(), "the chain's nine slots are state gas"); let stopped = execute_with(chain(), cap(180), charger(), gas_limit); - assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); assert_eq!(stopped.gas.reservoir_remaining, reservoir, "refilled by the stop"); assert_eq!(stopped.gas.state, 0); } @@ -553,6 +571,6 @@ fn test_outcome_reports_history_gas() { // The body is charged before the first frame, so the stop keeps it and takes back every // charge the frames made, the inspector's included. let stopped = execute_with(chain(), cap(180), charger(), GAS_LIMIT); - assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); assert_eq!(stopped.gas.history, body_history()); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index cfcbec37c..ac222def3 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -70,6 +70,9 @@ fn call_frame_init(depth: usize) -> FrameInit { is_static: false, reservoir: RESERVOIR, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, })), } } @@ -152,7 +155,7 @@ fn test_depth_guard_answers_a_creation_and_every_call_scheme() { if let FrameResult::Create(outcome) = &result { assert_eq!(outcome.address, None, "{what}"); } - assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO, "{what}: counted"); + assert_eq!(evm.ctx().limit_usage(), LimitUsage::ZERO, "{what}: counted"); assert!(!evm.ctx().journal_ref().state.contains_key(&CALLER), "{what}: no nonce bumped"); } } @@ -198,10 +201,12 @@ impl Inspector for AlwaysAnsw } } -/// An inspector's answer to a call past the limit gives way to `CallTooDeep`, and the inspector -/// still sees the call end. +/// An inspector's answer to a call past the limit is taken as given, as revm's inspected frame +/// start takes it: the depth guard is the engine's frame start, which a frame the inspector +/// answers never reaches, so the answer is the inspector's `Stop` on the gas it built, and the +/// inspector sees the call end. #[test] -fn test_inspect_frame_init_depth_guard_overrides_inspector() { +fn test_an_inspectors_answer_past_the_depth_limit_is_taken_as_given() { let mut evm = MegaEvm::new(context(MemoryDatabase::default())).with_inspector(AlwaysAnswers::default()); let result = InspectorEvmTr::inspect_frame_init( @@ -209,8 +214,12 @@ fn test_inspect_frame_init_depth_guard_overrides_inspector() { call_frame_init(CALL_STACK_LIMIT as usize + 1), ) .expect("inspect_frame_init does not fail"); - let ItemOrResult::Result(result) = result else { panic!("the frame was answered") }; - assert_call_too_deep(&result); + let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { + panic!("the frame was answered") + }; + assert_eq!(outcome.result.result, InstructionResult::Stop, "the inspector's answer"); + assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT, "on the gas the inspector built"); + assert_eq!(outcome.result.gas.reservoir(), 0, "which carries no reservoir"); assert_eq!( (evm.inspector().calls, evm.inspector().call_ends), (1, 1), @@ -232,71 +241,15 @@ fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, TARGET, U256::from(1), gas_limit)) .unwrap(); assert!(!result.result.is_success() && !result.result.is_halt(), "{:?}", result.result); - *result.result.gas() + (*result.result.gas(), evm.ctx().additional_limit().reservoir_remaining()) }; - let (small, large) = (at(100_000_000), at(1_000_000_000)); - assert_eq!(small.reservoir_remaining(), 0); - assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(0)); + let ((small, small_reservoir), (large, large_reservoir)) = (at(100_000_000), at(1_000_000_000)); + assert_eq!(small_reservoir, 0); + assert_eq!(large_reservoir, 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(0)); assert_eq!(small.tx_gas_used(), large.tx_gas_used()); assert_eq!(small.state_gas_spent_final(), large.state_gas_spent_final()); } -/// `settle_frame_result` settles a result into its caller's gas exactly as revm's frame return -/// does, for a success, a revert and a halt, with state gas drawn from the reservoir and spilled -/// onto regular gas. -#[test] -fn test_settle_frame_result_matches_revms_frame_return() { - use mega_evm::{settle_frame_result, synthetic_frame_result}; - use revm::context::result::EVMError; - - for result_kind in - [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] - { - let code = Bytes::from_static(&[revm::bytecode::opcode::STOP]); - let mut evm = - MegaEvm::new(context(MemoryDatabase::default().account_code(TARGET, code.clone()))); - let journal = evm.ctx_mut().journal_mut(); - journal.load_account(CALLER).unwrap(); - journal.load_account(TARGET).unwrap(); - let mut caller_init = call_frame_init(1); - if let FrameInput::Call(inputs) = &mut caller_init.frame_input { - let bytecode = revm::state::Bytecode::new_raw(code.clone()); - inputs.known_bytecode = (bytecode.hash_slow(), bytecode); - } - let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, caller_init).unwrap() else { - panic!("the caller frame is built"); - }; - - // The child the caller starts: 30,000 gas of the caller's, and its reservoir. - let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); - let caller_frame = frames.get(); - assert!(caller_frame.interpreter.gas.record_regular_cost(30_000)); - let child_input = { - let FrameInput::Call(mut inputs) = call_frame_init(2).frame_input else { - unreachable!() - }; - inputs.gas_limit = 30_000; - inputs.reservoir = caller_frame.interpreter.gas.reservoir(); - FrameInput::Call(inputs) - }; - let mut result = synthetic_frame_result(&child_input, result_kind, Bytes::new()); - // The child spent regular gas, and state gas beyond the reservoir that spilled. - let child_gas = result.gas_mut(); - assert!(child_gas.record_regular_cost(1_000)); - assert!(child_gas.record_state_cost(RESERVOIR + 500)); - - let mut expected = *caller_frame.interpreter.gas.tracker(); - settle_frame_result::<_, EVMError>( - ctx, - &mut expected, - &mut result.clone(), - ) - .unwrap(); - caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); - assert_eq!(caller_frame.interpreter.gas.tracker(), &expected, "{result_kind:?}"); - } -} - /// A gas limit below the execution cap: the transaction has no state-gas reservoir. const NARROW: u64 = 100_000_000; @@ -330,7 +283,7 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected let at = |gas_limit: u64| { let mut tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); tx.0.base.value = value; - let (result, _) = crate::common::run(system_db(), tx); + let result = crate::common::execute(system_db(), tx); let output = result.result.output().cloned().unwrap_or_default(); match &expected { Expected::Answer(answer) => { @@ -349,7 +302,7 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected assert!(result.result.is_success(), "at {gas_limit}: {:?}", result.result); } } - (*result.result.gas(), output) + (result, output) }; let ((narrow, narrow_answer), (wide, wide_answer)) = (at(NARROW), at(WIDE)); @@ -365,15 +318,15 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected narrow limit has no reservoir, so its body's history comes off that budget too", ); } - assert_eq!(narrow.reservoir_remaining(), 0, "there is no pool below the cap"); + assert_eq!(narrow.gas.reservoir_remaining, 0, "there is no pool below the cap"); assert_eq!( - wide.reservoir_remaining(), + wide.gas.reservoir_remaining, WIDE - TX_GAS_LIMIT_CAP - body_history(data.len() as u64), "the call spends no state gas, so the whole pool but the body's history comes back", ); assert_eq!( - narrow.tx_gas_used(), - wide.tx_gas_used(), + narrow.result.gas().tx_gas_used(), + wide.result.gas().tx_gas_used(), "the call costs the same with a pool and without one", ); } @@ -521,13 +474,14 @@ fn test_the_keyless_value_refusal_keeps_the_reservoir() { } /// A `keylessDeploy` call forwarded less regular gas than the overhead runs out of gas on its -/// first run, with the reservoir it inherited carried, and that result settles into a caller -/// exactly as revm's own frame return settles a frame that ran out. +/// first action, with the reservoir it inherited carried: the frame revm built for it ends before +/// it runs, and its frame start returns the out-of-gas as an answer is returned. revm's frame +/// return hands its caller none of the call's regular gas back and the reservoir whole, as for +/// any frame that ran out. #[test] fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { use core::convert::Infallible; - use mega_evm::settle_frame_result; use revm::context::result::EVMError; let forwarded = KEYLESS_DEPLOY_OVERHEAD_GAS - 1; @@ -537,15 +491,12 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { journal.load_account(CALLER).unwrap(); journal.load_account_with_code(KEYLESS_DEPLOY_ADDRESS).unwrap(); let init = call_frame_init_to(0, KEYLESS_DEPLOY_ADDRESS, keyless_deploy_call(), forwarded); - let ItemOrResult::Item(_) = + let ItemOrResult::Result(result) = EvmTr::frame_init(&mut evm, init).expect("frame_init does not fail") - else { - panic!("the call's frame is built"); - }; - let ItemOrResult::Result(result) = EvmTr::frame_run(&mut evm).expect("frame_run does not fail") else { panic!("a call that cannot pay the overhead starts no creation"); }; + assert_eq!(EvmTr::all(&evm).3.index(), None, "the call's frame is off the stack"); let FrameResult::Call(outcome) = &result else { panic!("expected a call result: {result:?}") }; assert_eq!(outcome.result.result, InstructionResult::OutOfGas); assert!(outcome.result.output.is_empty()); @@ -569,9 +520,13 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); let caller_frame = frames.get(); - let mut expected = *caller_frame.interpreter.gas.tracker(); - settle_frame_result::<_, EVMError>(ctx, &mut expected, &mut result.clone()) - .unwrap(); + let before = *caller_frame.interpreter.gas.tracker(); + // The call's opcode took the reservoir the answer carries out of the caller, which the answer's + // return adds back to what the caller kept. + caller_frame.interpreter.gas.tracker_mut().forward_reservoir(result.gas().reservoir()); caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); - assert_eq!(caller_frame.interpreter.gas.tracker(), &expected); + let after = caller_frame.interpreter.gas.tracker(); + assert_eq!(after.remaining(), before.remaining(), "a halt hands none of its gas back"); + assert_eq!(after.reservoir(), RESERVOIR, "and the inherited reservoir comes back whole"); + assert_eq!(after.state_gas_spent(), before.state_gas_spent()); } diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 5a077f0a1..0ca8dc5f3 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -1,59 +1,53 @@ //! How a system call's gas is settled: at most 30M of it regular gas, the rest its state-gas -//! reservoir. +//! reservoir. A system call runs on one of two gas limits: revm's default, which alloy-evm's and +//! revm's entry points use, or the pre-block budget, which the block's pre-block calls use. //! //! Every case runs the same system call through `MegaEvm` and through op-revm's `OpEvm` on the -//! `CfgEnv` the `MegaEvm` context holds — so on the fork with the same switch on — and compares -//! the two field by field: the gas, the reservoir left, the result and the state. A system call is -//! the protocol's own work: it pays no history gas, prices its state at the minimum SALT bucket and -//! is held to no per-transaction limit, so nothing Satin adds to a transaction separates the two. +//! `CfgEnv` the `MegaEvm` context holds — op-revm's handler with EIP-8037's split of a system +//! call's gas, which op-revm leaves to its consumer ([`op_reference`](crate::op_reference)) — and +//! compares the two field by field: the gas, the reservoir left, the result and the state. A +//! system call is the protocol's own work: it pays no history gas, prices its state at the minimum +//! SALT bucket and is held to no per-transaction limit, so nothing Satin adds to a transaction +//! separates the two. //! //! A transaction is not a system call. The last cases hold a system-address transaction, which is //! promoted to a deposit, to the deposit op-revm runs for it, below and above the execution cap: //! its gas is split by the cap, as every transaction's is, and not by the system-call budget. -use std::convert::Infallible; - use alloy_evm::Evm; use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ - constants::{SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + constants::{PRE_BLOCK_CALL_GAS_LIMIT, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, satin_gas_params, system::{ storage_slots::{ CURRENT_SYSTEM_ADDRESS, PENDING_SYSTEM_ADDRESS, SYSTEM_ADDRESS_ACTIVATION_BLOCK, }, - IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_REGISTRY_CODE, + transact_apply_pending_changes, IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, + MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, }, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use op_revm::{ - handler::OpHandler, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpEvm, - OpSpecId, OpTransaction, OpTransactionError, + test_utils::{ + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, + EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, + MIN_BUCKET_SIZE, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; +use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{GAS, INVALID, NUMBER, POP, PUSH0, SSTORE, STOP}, - context::{ - result::{EVMError, ExecResultAndState, ExecutionResult}, - BlockEnv, CfgEnv, Context, ContextSetters, ContextTr, Transaction, TxEnv, - }, + context::{result::ExecutionResult, BlockEnv, CfgEnv, ContextTr, Transaction, TxEnv}, context_interface::cfg::GasId, - handler::{ - EthFrame, ExecuteEvm, Handler, SystemCallTx, SYSTEM_CALL_GAS_LIMIT, - SYSTEM_CALL_REGULAR_GAS_LIMIT, - }, + handler::system_call::SYSTEM_CALL_GAS_LIMIT, inspector::NoOpInspector, - interpreter::interpreter::EthInterpreter, - state::EvmState, - Journal, }; -use crate::common::{runs_at_measurement_prices, state_is_free}; +use crate::{ + common::{runs_at_measurement_prices, state_is_free}, + op_reference::{self, Op, OpContext, Settled}, +}; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CONTRACT: Address = address!("0x5000000000000000000000000000000000000001"); @@ -70,17 +64,6 @@ fn slot() -> u64 { satin_gas_params().get(GasId::sstore_set_state_gas()) } -type Outcome = ExecResultAndState, EvmState>; -type OpContext = Context< - BlockEnv, - OpTransaction, - CfgEnv, - MemoryDatabase, - Journal, - L1BlockInfo, ->; -type Op = OpEvm; - fn block() -> BlockEnv { BlockEnv { number: U256::from(1_000), @@ -113,8 +96,7 @@ fn both_evms_with( .with_block(block()) .with_chain(zero_fee_l1_block_info()); let cfg = ctx.cfg().clone(); - assert!(cfg.system_call_state_gas_margin_in_reservoir, "both run with the split"); - assert!(cfg.enable_amsterdam_eip8037, "which needs EIP-8037"); + assert!(cfg.enable_amsterdam_eip8037, "both run EIP-8037's two pools"); (MegaEvm::new(ctx), op_evm(db, cfg)) } @@ -123,45 +105,31 @@ fn both_evms(db: MemoryDatabase) -> (MegaEvm Outcome { - let mut tx = OpTransaction::::new_system_tx_with_caller(caller, contract, data); - tx.base.gas_limit = gas_limit; - op.0.ctx.set_tx(tx); - let result: Result<_, EVMError> = - OpHandler::<_, _, EthFrame>::new().run_system_call(op); - ExecResultAndState::new(result.expect("the system call runs"), op.finalize()) -} - -/// Runs the system call from `caller` to `contract` on `gas_limit` through both engines. +/// Runs the system call from `caller` to `contract` through both engines, on revm's default gas +/// limit. fn run_both( (mut mega, mut op): (MegaEvm, Op), caller: Address, contract: Address, data: Bytes, - gas_limit: u64, -) -> (Outcome, Outcome) { - let mega_outcome = mega - .transact_system_call_with_gas_limit(caller, contract, data.clone(), gas_limit) +) -> (Settled, Settled) { + let result_and_state = Evm::transact_system_call(&mut mega, caller, contract, data.clone()) .expect("the system call runs"); - let op_outcome = op_system_call(&mut op, caller, contract, data, gas_limit); - (mega_outcome, op_outcome) + assert_eq!(mega.ctx().tx().gas_limit(), SYSTEM_CALL_GAS_LIMIT); + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let op_outcome = + op_reference::system_call(&mut op, caller, contract, data, SYSTEM_CALL_GAS_LIMIT) + .expect("the system call runs"); + (Settled { result_and_state, reservoir_remaining }, op_outcome) } /// Asserts the two outcomes agree field by field, then as a whole, so a field added later is /// covered too. -fn assert_same(mega: &Outcome, op: &Outcome) { +fn assert_same(mega: &Settled, op: &Settled) { let (m, o) = (mega.result.gas(), op.result.gas()); assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); - assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(mega.reservoir_remaining, op.reservoir_remaining, "reservoir remaining"); assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); @@ -178,7 +146,7 @@ fn gas_to_slot() -> Bytes { } /// What [`gas_to_slot`] stored. -fn stored_gas(outcome: &Outcome) -> u64 { +fn stored_gas(outcome: &Settled) -> u64 { let slot = outcome.state[&CONTRACT].storage[&U256::ZERO].present_value(); slot.to::() } @@ -194,40 +162,21 @@ fn db_with(code: Bytes) -> MemoryDatabase { MemoryDatabase::default().account_code(CONTRACT, code) } -/// A system call whose gas limit is at most 30M is regular gas alone: there is no reservoir, and -/// the fresh slot's state gas is paid out of the regular budget. -#[test] -fn test_a_system_call_within_30m_has_no_reservoir() { - for gas_limit in [1_000_000, SYSTEM_CALL_REGULAR_GAS_LIMIT] { - let (mega, op) = - run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new(), gas_limit); - assert!(mega.result.is_success(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), 0); - assert_eq!(mega.result.gas().state_gas_spent_final(), slot()); - assert!(stored_gas(&mega) > gas_limit - 10, "all {gas_limit} of it is regular gas"); - assert_same(&mega, &op); - } -} - -/// A system call whose gas limit is above 30M runs on 30M of regular gas, which is what `GAS` -/// reads, and carries the rest as its reservoir: the fresh slot is paid out of it, and what is -/// left is reported. So on revm's default limit and on a far larger one. +/// A system call runs on 30M of regular gas, which is what `GAS` reads, and carries the rest of +/// its gas limit as its reservoir: the fresh slot is paid out of it, and what is left is reported. #[test] fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { - for gas_limit in [SYSTEM_CALL_GAS_LIMIT, 250_000_000] { - let (mega, op) = - run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new(), gas_limit); - assert!(mega.result.is_success(), "{:?}", mega.result); - let gas = stored_gas(&mega); - assert!(gas < SYSTEM_CALL_REGULAR_GAS_LIMIT, "GAS reads the regular budget: {gas}"); - assert!(gas > SYSTEM_CALL_REGULAR_GAS_LIMIT - 10, "all of it: {gas}"); - assert_eq!( - mega.result.gas().reservoir_remaining(), - gas_limit - SYSTEM_CALL_REGULAR_GAS_LIMIT - slot(), - "the excess, less the one slot it paid for", - ); - assert_same(&mega, &op); - } + let (mega, op) = run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new()); + assert!(mega.result.is_success(), "{:?}", mega.result); + let gas = stored_gas(&mega); + assert!(gas < SYSTEM_CALL_REGULAR_GAS_LIMIT, "GAS reads the regular budget: {gas}"); + assert!(gas > SYSTEM_CALL_REGULAR_GAS_LIMIT - 10, "all of it: {gas}"); + assert_eq!( + mega.reservoir_remaining, + DEFAULT_RESERVOIR.saturating_sub(slot()), + "the excess, less the one slot it paid for", + ); + assert_same(&mega, &op); } /// The default reservoir holds sixteen fresh slots at Satin's price. That many writes empty it and @@ -236,8 +185,8 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { /// took is its own regular cost, which the writes before it show, plus the part of its slot the /// reservoir did not hold. /// -/// Where a slot is cheaper, the default reservoir holds more fresh slots than the regular budget -/// can write, so the call is given a reservoir of sixteen. +/// Where a slot is far cheaper, the default reservoir holds more fresh slots than the regular +/// budget can write, and there is no spill to reach. #[test] fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { // Slots that cost nothing never empty the reservoir, and there is nothing to spill. @@ -248,21 +197,25 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { assert_eq!(SLOT_STATE_GAS, slot()); assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); } - let reservoir = DEFAULT_RESERVOIR.min(16 * slot()); + let reservoir = DEFAULT_RESERVOIR; + // A fresh write's regular gas does not move with the byte prices, and 30M of it writes well + // over a thousand slots, so a reservoir that holds no more than that can be emptied. + if reservoir / slot() > 1_000 { + note_price_guard("the default reservoir holds more fresh slots than 30M can write"); + return; + } // The reading is stored into a slot that already holds a value, which writes no new state. - const READING: u64 = 0xff; + // The fresh writes take the slots from zero up, so the reading's key is one none of them reach. + let reading_slot = U256::MAX; let run = |writes| { - let code = - fresh_writes(writes).append(GAS).push_number(READING as u8).append(SSTORE).stop(); - let db = - db_with(code.build()).account_storage(CONTRACT, U256::from(READING), U256::from(1)); - let gas_limit = SYSTEM_CALL_REGULAR_GAS_LIMIT + reservoir; - let (mega, op) = run_both(both_evms(db), CALLER, CONTRACT, Bytes::new(), gas_limit); + let code = fresh_writes(writes).append(GAS).push_u256(reading_slot).append(SSTORE).stop(); + let db = db_with(code.build()).account_storage(CONTRACT, reading_slot, U256::from(1)); + let (mega, op) = run_both(both_evms(db), CALLER, CONTRACT, Bytes::new()); assert!(mega.result.is_success(), "{:?}", mega.result); assert_eq!(mega.result.gas().state_gas_spent_final(), writes * slot()); assert_same(&mega, &op); - let reading = mega.state[&CONTRACT].storage[&U256::from(READING)].present_value(); - (reading.to::(), mega.result.gas().reservoir_remaining()) + let reading = mega.state[&CONTRACT].storage[&reading_slot].present_value(); + (reading.to::(), mega.reservoir_remaining) }; // The most slots the reservoir holds, and what the one after them spills. @@ -289,15 +242,9 @@ fn test_reservoir_remaining_is_what_the_writes_left() { let most = DEFAULT_RESERVOIR.checked_div(slot()).map_or(5, |held| held.min(5)); for writes in [0, 1, most] { let code = fresh_writes(writes).stop().build(); - let (mega, op) = run_both( - both_evms(db_with(code)), - CALLER, - CONTRACT, - Bytes::new(), - SYSTEM_CALL_GAS_LIMIT, - ); + let (mega, op) = run_both(both_evms(db_with(code)), CALLER, CONTRACT, Bytes::new()); assert_eq!( - mega.result.gas().reservoir_remaining(), + mega.reservoir_remaining, DEFAULT_RESERVOIR - writes * slot(), "{writes} writes", ); @@ -311,28 +258,16 @@ fn test_reservoir_remaining_is_what_the_writes_left() { #[test] fn test_a_failing_system_call_settles_like_op_revm() { let reverting = fresh_writes(3).revert().build(); - let (mega, op) = run_both( - both_evms(db_with(reverting)), - CALLER, - CONTRACT, - Bytes::new(), - SYSTEM_CALL_GAS_LIMIT, - ); + let (mega, op) = run_both(both_evms(db_with(reverting)), CALLER, CONTRACT, Bytes::new()); assert!(matches!(mega.result, ExecutionResult::Revert { .. }), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), DEFAULT_RESERVOIR, "nothing kept"); + assert_eq!(mega.reservoir_remaining, DEFAULT_RESERVOIR, "nothing kept"); assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); let halting = fresh_writes(3).append(INVALID).build(); - let (mega, op) = run_both( - both_evms(db_with(halting)), - CALLER, - CONTRACT, - Bytes::new(), - SYSTEM_CALL_GAS_LIMIT, - ); + let (mega, op) = run_both(both_evms(db_with(halting)), CALLER, CONTRACT, Bytes::new()); assert!(mega.result.is_halt(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), DEFAULT_RESERVOIR); + assert_eq!(mega.reservoir_remaining, DEFAULT_RESERVOIR); assert_eq!( mega.result.gas().total_gas_spent(), SYSTEM_CALL_REGULAR_GAS_LIMIT, @@ -359,8 +294,7 @@ fn test_a_system_call_with_a_reservoir_stays_exempt() { .with_block_env_access_compute_gas_limit(0), ); - let (mega_outcome, op_outcome) = - run_both((mega, op), SYSTEM_ADDRESS, CONTRACT, Bytes::new(), 250_000_000); + let (mega_outcome, op_outcome) = run_both((mega, op), SYSTEM_ADDRESS, CONTRACT, Bytes::new()); assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega_outcome.result.gas().state_gas_spent_final(), 20 * slot(), "m = 1"); assert_eq!(crowded.total_bucket_queries(), 0, "no capacity was read"); @@ -386,29 +320,43 @@ fn registry_with_a_due_change() -> MemoryDatabase { ) } -/// `applyPendingChanges()` on 30M in a crowded SALT region applies the change at the minimum -/// bucket's price: with no reservoir its state gas is paid out of the 30M, which holds it many -/// times over, and it is what op-revm charges, which has no SALT. +/// The pre-block `applyPendingChanges()` call in a crowded SALT region runs on the pre-block +/// budget and applies the change at the minimum bucket's price: its fresh slots are paid out of +/// the reservoir, which holds them, and it is what op-revm charges on the same budget, which has no +/// SALT. #[test] -fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { +fn test_the_pre_block_apply_pending_changes_is_priced_at_the_minimum_bucket() { let crowded = TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 2_000); + let (mut mega, mut op) = both_evms_with(registry_with_a_due_change(), crowded.clone()); + let result_and_state = + transact_apply_pending_changes(&mut mega).expect("the pre-block call succeeds"); + assert_eq!(mega.ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT, "not the block's 10B"); + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let mega = Settled { result_and_state, reservoir_remaining }; let data = Bytes::from(ISequencerRegistry::applyPendingChangesCall {}.abi_encode()); - let (mega, op) = run_both( - both_evms_with(registry_with_a_due_change(), crowded.clone()), + let op = op_reference::system_call( + &mut op, SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, data, - SYSTEM_CALL_REGULAR_GAS_LIMIT, - ); + PRE_BLOCK_CALL_GAS_LIMIT, + ) + .expect("the system call runs"); assert!(mega.result.is_success(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), 0); + let state = mega.result.gas().state_gas_spent_final(); // Where a state byte is free the slots cost nothing, at any bucket. if !state_is_free() { - let state = mega.result.gas().state_gas_spent_final(); assert!(state > 0, "the change wrote fresh slots"); assert_eq!(state % slot(), 0, "at m = 1"); } + if !runs_at_measurement_prices() { + assert_eq!( + mega.reservoir_remaining, + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - state, + "the reservoir paid for every slot", + ); + } assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega, &op); } @@ -416,7 +364,7 @@ fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { /// The default system-call entry point runs on revm's default gas limit however large the block, /// in a crowded region too: 30M of regular gas and the margin as reservoir, the EIP-2935 and /// EIP-4788 contracts' writes paid out of it at the minimum bucket. The block's own pre-block -/// calls widen the reservoir with the block (see the block tests); this entry point does not. +/// calls run on the pre-block budget, also whatever the block (see the block tests). #[test] fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_region() { use alloy_eips::{ @@ -432,23 +380,23 @@ fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_reg TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 2_000); let (mut mega, mut op) = both_evms_with(db, crowded.clone()); let data = Bytes::from(B256::repeat_byte(0x29).0); - let mega_outcome = + let result_and_state = Evm::transact_system_call(&mut mega, SYSTEM_ADDRESS, contract, data.clone()) .expect("the system call runs"); - let op_outcome = revm::handler::SystemCallEvm::system_call_with_caller( + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let mega_outcome = Settled { result_and_state, reservoir_remaining }; + let op_outcome = op_reference::system_call( &mut op, SYSTEM_ADDRESS, contract, data, + SYSTEM_CALL_GAS_LIMIT, ) .expect("the system call runs"); assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega.ctx().tx().gas_limit(), SYSTEM_CALL_GAS_LIMIT, "not the block's 10B"); - assert_eq!( - mega_outcome.result.gas().reservoir_remaining(), - DEFAULT_RESERVOIR - slots * slot(), - ); + assert_eq!(mega_outcome.reservoir_remaining, DEFAULT_RESERVOIR - slots * slot()); assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega_outcome, &op_outcome); } @@ -495,13 +443,17 @@ fn test_a_system_address_transaction_is_split_by_the_execution_cap() { let mega_outcome = mega.execute_transaction(OpTx(op_transaction(tx))).expect("accepted"); assert!(mega.ctx().is_system_originated(), "it is the protocol's own transaction"); - let op_outcome = op.transact(deposit).expect("accepted"); + let op_outcome = op_reference::transact(&mut op, deposit).expect("accepted"); assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega_outcome.gas.history, 0); - assert_eq!(mega_outcome.result.gas().reservoir_remaining(), reservoir, "{gas_limit}"); - let mut satin = mega_outcome.result_and_state; - let registry = satin.state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("the read"); + assert_eq!(mega_outcome.gas.reservoir_remaining, reservoir, "{gas_limit}"); + let mut satin = Settled { + result_and_state: mega_outcome.result_and_state, + reservoir_remaining: mega_outcome.gas.reservoir_remaining, + }; + let registry = + satin.result_and_state.state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("the read"); assert!(!registry.is_touched(), "a read-only entry"); assert_eq!(registry.storage.keys().collect::>(), [&CURRENT_SYSTEM_ADDRESS]); assert_same(&satin, &op_outcome); diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs new file mode 100644 index 000000000..6a50c6e83 --- /dev/null +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -0,0 +1,154 @@ +//! The data size of the writes made by anything but the transaction's own execution. +//! +//! What a transaction keeps is counted where its own execution writes: at the completed-write and +//! frame-start hooks, and where revm decides a start. A precompile's writes through +//! `EvmInternals` and an inspector's are not the transaction's own execution, and neither is +//! counted; neither is a start an inspector answers before revm decides it. + +use alloy_evm::precompiles::DynPrecompile; +use alloy_primitives::{address, map::HashMap, Address, Bytes, Log, LogData, B256, U256}; +use mega_evm::{ + test_utils::{transfer_log, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, +}; +use revm::{ + bytecode::opcode::STOP, + handler::FrameResult, + interpreter::{ + interpreter::EthInterpreter, CallOutcome, FrameInput, Gas, InstructionResult, + InterpreterResult, + }, + precompile::{PrecompileId, PrecompileOutput}, + Inspector, +}; + +use crate::common::{call, context, grown, records_and_moves, value_call_room}; + +const CALLER: Address = address!("0000000000000000000000000000000000e10000"); +/// The transaction's own frame. +const CONTRACT: Address = address!("0000000000000000000000000000000000e10001"); +/// A contract whose code stops. +const RECEIVER: Address = address!("0000000000000000000000000000000000e10002"); +/// An account with no code. +const PAYEE: Address = address!("0000000000000000000000000000000000e10003"); +/// A node's own precompile, which writes through `EvmInternals`. +const STATEFUL: Address = address!("0000000000000000000000000000000000e10100"); + +/// What every value call moves. +const VALUE: u64 = 1_000; + +/// A log of `address`'s with one topic and no data. +fn marker(address: Address, topic: u8) -> Log { + Log { address, data: LogData::new_unchecked(vec![B256::repeat_byte(topic)], Bytes::new()) } +} + +/// A precompile that writes through `EvmInternals` everything the API lets it: two slots, one of +/// them inside a checkpoint it commits, a log, a value transfer to [`PAYEE`], and, inside a +/// checkpoint it reverts, a third slot and a second log. +fn stateful() -> DynPrecompile { + DynPrecompile::new(PrecompileId::Custom("stateful".into()), |mut input| { + let internals = &mut input.internals; + internals.sstore(STATEFUL, U256::from(1), U256::from(7)).unwrap(); + internals.log(marker(STATEFUL, 1)); + assert_eq!(internals.transfer(STATEFUL, PAYEE, U256::from(1)).unwrap(), None); + let _ = internals.checkpoint(); + internals.sstore(STATEFUL, U256::from(2), U256::from(7)).unwrap(); + internals.checkpoint_commit(); + let checkpoint = internals.checkpoint(); + internals.sstore(STATEFUL, U256::from(3), U256::from(7)).unwrap(); + internals.log(marker(STATEFUL, 2)); + internals.checkpoint_revert(checkpoint); + Ok(PrecompileOutput::new(0, Bytes::new(), input.reservoir)) + }) +} + +/// A node's own precompile that writes through `EvmInternals` — storage, a log, a value transfer, +/// a checkpoint it commits and one it reverts — keeps its writes in the state and the receipt, and +/// counts none of them: the transaction's data size is its body and the start of the value call +/// that reached the precompile, the precompile's record and its caller's and the call's transfer +/// log, as for a precompile that writes nothing. +#[test] +fn test_a_precompiles_writes_through_evm_internals_count_nothing() { + let code = BytecodeBuilder::default().call(STATEFUL, U256::from(VALUE)).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(VALUE)); + let tx = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); + let mut evm = MegaEvm::new(context(db)) + .with_dyn_precompiles(HashMap::from_iter([(STATEFUL, stateful())])); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let storage = |slot: u64| { + outcome.state[&STATEFUL].storage.get(&U256::from(slot)).map(|slot| slot.present_value) + }; + assert_eq!(storage(1), Some(U256::from(7)), "the precompile's write is kept"); + assert_eq!(storage(2), Some(U256::from(7)), "and the one it committed"); + assert_ne!(storage(3), Some(U256::from(7)), "the one it reverted is not"); + assert_eq!(outcome.state[&PAYEE].info.balance, U256::from(1), "its transfer moved"); + assert_eq!( + outcome.result.logs(), + [ + transfer_log(CONTRACT, STATEFUL, U256::from(VALUE)), + marker(STATEFUL, 1), + transfer_log(STATEFUL, PAYEE, U256::from(1)), + ], + "the receipt carries the call's transfer log, then the precompile's log and transfer log", + ); + assert_eq!( + outcome.usage, + grown(records_and_moves(2, 1), 1), + "the call's start alone is counted, whose value creates STATEFUL" + ); +} + +/// An inspector that answers, in `frame_start`, the call to `target` with a success on the gas +/// the call was given. +struct AnswersAtFrameStart { + target: Address, +} + +impl Inspector, EthInterpreter> for AnswersAtFrameStart { + fn frame_start( + &mut self, + _context: &mut MegaContext, + frame_input: &mut FrameInput, + ) -> Option { + let FrameInput::Call(inputs) = frame_input else { return None }; + (inputs.target_address == self.target).then(|| { + FrameResult::Call(CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + )) + }) + } +} + +/// A value call an inspector answers in `frame_start`, before revm decides it, starts nothing: +/// the transaction keeps its body alone, whether the answered call is the transaction's own frame +/// or one a contract makes. +#[test] +fn test_a_value_call_answered_at_frame_start_counts_nothing() { + let code = BytecodeBuilder::default().call(RECEIVER, U256::from(VALUE)).stop().build(); + for (case, to, target) in [ + ("below the transaction's frame", CONTRACT, RECEIVER), + ("the transaction's frame", RECEIVER, RECEIVER), + ] { + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.clone()) + .account_balance(CONTRACT, U256::from(VALUE)) + .account_balance(CALLER, U256::from(VALUE)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])); + let value = if to == RECEIVER { VALUE } else { 0 }; + let tx = call(CALLER, to, U256::from(value), value_call_room()); + let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersAtFrameStart { target }); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert!(outcome.result.logs().is_empty(), "{case}: nothing moved"); + assert_eq!(outcome.usage, records_and_moves(0, 0), "{case}"); + } +} diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index fd026b07a..bd954cf08 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -2,26 +2,30 @@ //! //! Every value movement emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm //! journals itself — no `LOG` opcode runs — and the receipt carries. Satin counts it by the rule a -//! `LOG3` carrying one word is counted, 160 bytes, on the lane of the frame whose journal +//! `LOG3` carrying one word is counted, 160 bytes, on the byte pool of the frame whose journal //! checkpoint holds the move, and charges it nothing: //! //! - a frame start that moves value — the transaction's own value, a value `CALL`, a creation's -//! endowment — counts its log with the frame's records, before revm builds the frame, so a -//! crossing answers the frame with the stop before any value moves; -//! - a `SELFDESTRUCT` that moves a balance counts its log with the beneficiary's record, once the -//! opcode completed, and a crossing stops the destructing frame, which takes the move back. +//! endowment — counts its log with the frame's records, held to the limits once revm decided the +//! start, so a crossing stops the frame before it runs and takes the move back; +//! - a `SELFDESTRUCT` that moves a balance counts its log with its records, once the opcode +//! completed, and a crossing stops the destructing frame, which takes the move back. //! //! Every site runs below the execution cap and above it, and is pinned four ways: the exact bytes //! it adds and the log the receipt carries; a frame budget one byte short of them, which stops the //! frame that moves the value and lets its caller resume; the transaction's limit one byte short, //! which does the same, and stops the transaction when the frame is its own; and a failure above //! the move, which takes the log and its bytes back. Each stop is the one a `LOG3` of one word -//! makes in the same place, where the same bytes are counted: its twin below. +//! makes in the same place, where the same bytes are counted: its twin below. A creation's bytes +//! are held to its creator's budget: the creation's share of it holds the created account's record +//! and the log, and the creator's nonce record is counted on the creator once the creation +//! returned, so it is the creator that is one byte short, and its stop takes the move back. //! -//! A frame start is counted before revm decides it. A 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, and runs under a limit as it does without one; a creation onto an occupied address is -//! counted, and revm refuses it after the count. +//! A frame start is held to the limits once revm decided it. A 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, and runs under a limit as it does without one; a value call revm answers +//! without building a frame has its move taken back with the stop; a creation onto an occupied +//! address fails on the collision, its start held to nothing. use alloy_op_evm::OpTx; use alloy_primitives::{address, keccak256, Address, Bytes, Log, TxKind, B256, U256}; @@ -40,8 +44,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATASIZE, DELEGATECALL, GAS, JUMPDEST, JUMPI, LOG1, POP, PUSH0, PUSH1, - REVERT, SELFDESTRUCT, STOP, + ADD, ADDRESS, CALL, CALLDATASIZE, GAS, JUMPDEST, JUMPI, LOG1, MSTORE, POP, PUSH0, PUSH1, + RETURN, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFBALANCE, SELFDESTRUCT, STOP, }, context::{ result::{ExecutionResult, Output}, @@ -51,7 +55,9 @@ use revm::{ Database, Inspector, }; -use crate::common::{account_state_gas, context, execute_under, history_rounds, share}; +use crate::common::{ + account_state_gas, context, execute_under, history_rounds, share, value_call_room, +}; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); /// The contract a nested site's transaction calls: it calls [`ACTOR`] and returns what that @@ -105,7 +111,7 @@ enum Site { enum Variant { /// The move, as it is. Plain, - /// The same bytes on the same lane with no value moved, the last of them a `LOG3` of one word + /// The same bytes on the same pool with no value moved, the last of them a `LOG3` of one word /// where the transfer log is. Twin, /// The move, then a failure above it that takes it back. @@ -124,7 +130,7 @@ impl Site { Self::SelfDestruct, ]; - /// The depth of the frame whose lane holds the log: the transaction's own, or the one the + /// The depth of the frame whose pool holds the log: the transaction's own, or the one the /// actor starts. const fn depth(self) -> u32 { match self { @@ -133,29 +139,52 @@ impl Site { } } + /// The depth of the frame whose budget holds all the bytes the move counts: the frame whose + /// pool holds the log, but for a creation its creator, the actor. The creation's share of the + /// actor's budget holds the created account's record and the log, 200 bytes, whenever the + /// actor's holds those and its own nonce record, 240, which it counts once the creation + /// returned: `share(240)` is 235. + const fn holding_depth(self) -> u32 { + match self { + Self::Create | Self::Create2 => 1, + _ => self.depth(), + } + } + /// The write records the move makes: the recipient's or the created account's, and the - /// caller's own below the transaction's frame; a destruction's beneficiary alone. + /// caller's own below the transaction's frame; a destruction's beneficiary and the account it + /// clears. const fn records(self) -> u64 { match self { - Self::TxValue | Self::TxEndowment | Self::SelfDestruct => 1, + Self::TxValue | Self::TxEndowment => 1, _ => 2, } } - /// The bytes the move counts on its frame's lane: its records and its transfer log. + /// The new accounts and slots `variant` keeps once it ran to its end: the account the move + /// creates — the created account, or [`PAYEE`]'s and the identity precompile's, which hold + /// nothing before the value reaches them — and for the twin, the account it creates or the + /// fresh slots it writes for the records. A move taken back keeps none. + const fn growth(self, variant: Variant) -> u64 { + match (self, variant) { + (_, Variant::TakenBack) => 0, + (Self::TxEndowment | Self::Create | Self::Create2, _) | + (Self::CallWithoutCode | Self::CallToPrecompile, Variant::Plain) => 1, + (_, Variant::Plain) => 0, + (_, Variant::Twin) => self.records(), + } + } + + /// The bytes the move counts: its records and its transfer log. const fn bytes(self) -> u64 { self.records() * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE } - /// What a stop at the move leaves counted beside the body: the nonce record a creation - /// stopped at its start leaves its creator; nothing otherwise. - const fn left_by_a_stop(self) -> LimitUsage { - match self { - Self::Create | Self::Create2 => { - LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 } - } - _ => LimitUsage::ZERO, - } + /// The budget of the frame that holds the move, when the transaction's own frame starts with + /// `first`: that frame itself at the transaction's own frame; below it, 98% of `first` for the + /// actor, and 98% of what the actor has left for the frame it starts. + fn holding_budget(self, first: u64) -> u64 { + budget(self.holding_depth(), first) } /// The account the value moves to. The sender and the actor start at nonce zero. @@ -356,7 +385,11 @@ fn assert_completed( assert_eq!(balance(outcome, site.recipient()), moved, "{case}: the value at the recipient"); assert_eq!( outcome.usage, - LimitUsage { data_size: body + site.bytes(), write_records: site.records() }, + LimitUsage { + data_size: body + site.bytes(), + write_records: site.records(), + state_growth: site.growth(variant) + }, "{case}: the body, the records and one log", ); let history_bytes = body + site.records() * WRITE_RECORD_SIZE + log_history; @@ -373,7 +406,7 @@ fn assert_completed( } /// Asserts `outcome` is `site` stopped at its move by `stop`, with nothing of the move left: no -/// transfer log, no value moved, and only what a stop leaves beside the body counted. +/// transfer log, no value moved, and nothing but the body counted. fn assert_stopped_at_the_move( case: &str, site: Site, @@ -389,10 +422,9 @@ fn assert_stopped_at_the_move( ); assert!(transfer_logs(outcome).is_empty(), "{case}: no transfer log"); assert_eq!(balance(outcome, site.recipient()), U256::ZERO, "{case}: no value moved"); - let left = site.left_by_a_stop(); assert_eq!( outcome.usage, - LimitUsage { data_size: body + left.data_size, write_records: left.write_records }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "{case}: the move's bytes are not counted", ); } @@ -415,18 +447,20 @@ fn test_each_site_counts_its_transfer_log() { } } -/// A frame budget holds the move at exactly its bytes, and one byte short of them stops the frame -/// that moves the value before anything moves, frame-locally: the caller resumes — the relay and -/// the actor return the stop as their output — and the transaction reports no stop. The -/// transaction's own frame has no caller, so its stop reverts the transaction, and the outcome -/// names it, the crossing that produced that frame's result. +/// A frame budget holds the move at exactly the bytes it counts, and one byte short of them stops +/// the frame that holds the move, which keeps nothing of it, frame-locally: the caller resumes — +/// the relay and the actor return the stop as their output — and the transaction reports no stop. +/// The transaction's own frame has no caller, so its stop reverts the transaction, and the outcome +/// names it, the crossing that produced that frame's result. A creation's bytes are held to its +/// creator's budget, whose nonce record is counted on it once the creation returned: one byte +/// short, the creation runs and returns, and the creator is stopped before it runs on. /// /// A `LOG3` of one word where the transfer log is, after the same bytes of records, stops the /// same frame at the same budget with the same revert. #[test] fn test_each_site_stops_one_byte_short_of_its_frame_budget() { for site in Site::ALL { - let cap = cap_for(site.depth(), site.bytes()); + let cap = cap_for(site.holding_depth(), site.bytes()); for gas_limit in GAS_LIMITS { for variant in [Variant::Plain, Variant::Twin] { let case = format!("{site:?} {variant:?} at {gas_limit}"); @@ -470,8 +504,7 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { Some(&Bytes::from(stop.abi_encode())), "{case}: the same stop", ); - let left = site.left_by_a_stop(); - assert_eq!(over.usage.data_size - body, left.data_size, "{case}"); + assert_eq!(over.usage.data_size, body, "{case}: the body alone"); assert!(over.result.logs().is_empty(), "{case}: the log went"); } Variant::TakenBack => unreachable!(), @@ -482,10 +515,11 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { } } -/// The transaction's limit one byte short of the move stops the frame that moves the value there, -/// as its budget does: the stop names the data size and the transaction's limit, the caller -/// resumes — the relay and the actor return the stop as their output — and the move's bytes go -/// with the frame. At the transaction's own frame the stop is the transaction's result, the +/// The transaction's limit one byte short of the move stops the frame that holds the move there, +/// as its budget does: the stop names the data size and the frame's budget, which the limit leaves +/// it, the caller resumes — the relay and the actor return the stop as their output — and the +/// move's bytes go with the frame. For a creation that frame is its creator, stopped once the +/// creation returned. At the transaction's own frame the stop is the transaction's result, the /// outcome names it with the move's bytes in the figure that crossed, and a limit of exactly the /// bytes holds. A `LOG3` of one word where the transfer log is, after the same bytes of records, /// crosses the same way. @@ -504,11 +538,17 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { }; let (outcome, body, limit) = run(1); + // The frame that holds the move crosses its own budget with the transaction's + // limit, and the stop names the budget: at the transaction's own + // frame what the body leaves of the limit; below it, 98% of that + // for the actor, and 98% of what the actor has left for the frame + // it starts. + let budget = site.holding_budget(limit - body); let own_frames = (site.depth() == 0).then_some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit, - used: body + site.bytes(), - frame_local: false, + limit: budget, + used: site.bytes(), + frame_local: true, }); assert_eq!( outcome.limit_exceeded, own_frames, @@ -520,7 +560,7 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { "{case}: the caller resumes: {:?}", outcome.result ); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; match variant { Variant::Plain => { assert_stopped_at_the_move(&case, site, &outcome, body, stop); @@ -531,8 +571,7 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { Some(&Bytes::from(stop.abi_encode())), "{case}: the same stop", ); - let left = site.left_by_a_stop(); - assert_eq!(outcome.usage.data_size - body, left.data_size, "{case}"); + assert_eq!(outcome.usage.data_size, body, "{case}: the body alone"); assert!(outcome.result.logs().is_empty(), "{case}: the log went"); } Variant::TakenBack => unreachable!(), @@ -549,6 +588,64 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { } } +/// A value call revm answers without building a frame — to an account with no code, to a +/// precompile — whose start crosses the transaction's limit is answered with the stop once revm +/// moved the value, and what the start moved is taken back before its caller resumes: the caller, +/// which wrote a slot before the call and reads its own balance before and after it, finds its +/// balance as it was, keeps its slot, and returns the stop it caught. +#[test] +fn test_an_answered_value_call_whose_start_crosses_is_taken_back_before_its_caller_resumes() { + for site in [Site::CallWithoutCode, Site::CallToPrecompile] { + let held = U256::from(10 * VALUE); + let actor = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([SELFBALANCE, PUSH0, MSTORE]) + .call(site.recipient(), U256::from(VALUE)) + .append_many([POP, SELFBALANCE]) + .push_number(0x20_u8) + .append_many([MSTORE, RETURNDATASIZE, PUSH0]) + .push_number(0x40_u8) + .append_many([RETURNDATACOPY, RETURNDATASIZE]) + .push_number(0x40_u8) + .append_many([ADD, PUSH0, RETURN]) + .build(); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, held) + .account_code(ACTOR, actor); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + // The body, the slot's record, then the call's two records and its transfer log, but one. + let limit = transaction_body_bytes(&tx) + WRITE_RECORD_SIZE + site.bytes() - 1; + let outcome = + execute_under(db, tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + + assert!(outcome.result.is_success(), "{site:?}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{site:?}: the caller caught the stop"); + let output = outcome.result.output().expect("the caller returns").clone(); + let (before, after) = + (U256::from_be_slice(&output[..32]), U256::from_be_slice(&output[32..64])); + assert_eq!( + (before, after), + (held, held), + "{site:?}: the move is taken back before it reads" + ); + // The actor's budget is what the body leaves; once its slot is kept, the call's start gets + // 98% of what is left, which the move crosses with the transaction's limit. + let budget = crate::common::share(site.bytes() - 1); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; + assert_eq!(&output[64..], stop.abi_encode().as_slice(), "{site:?}: the call is the stop"); + assert_eq!(balance(&outcome, site.recipient()), U256::ZERO, "{site:?}: nothing moved"); + assert!(transfer_logs(&outcome).is_empty(), "{site:?}: no transfer log"); + let slot = outcome.state[&ACTOR].storage[&U256::from(1)].present_value; + assert_eq!(slot, U256::from(1), "{site:?}: the caller keeps its own write"); + } +} + /// A failure above the move takes the transfer log back with the move, and its bytes with them: /// the actor reverting after it, or the transaction's own frame failing. What is left counted is /// the body. @@ -565,7 +662,11 @@ fn test_a_failure_takes_each_sites_transfer_log_back() { assert!(!outcome.result.is_halt(), "{case}: {:?}", outcome.result); assert_eq!(outcome.result.is_success(), site.depth() > 0, "{case}: the relay resumes"); assert!(outcome.result.logs().is_empty(), "{case}: the log went with the move"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{case}" + ); if site == Site::SelfDestruct { assert_eq!(balance(&outcome, DESTRUCTOR), U256::from(VALUE), "{case}"); } @@ -627,23 +728,26 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { .append_many([PUSH0, CALLDATASIZE, PUSH1, end, JUMPI, POP]) .append_many(self_call.build_vec()) .append(JUMPDEST); - let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize); 7] = [ - ("a CALLCODE", db(actor().callcode(RECEIVER, value)), call(ACTOR, 0), 1, 0), - // The move's sender and recipient are one account, recorded once. - ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 1, 0), - ("a zero-value CALL", db(actor().call(RECEIVER, U256::ZERO)), call(ACTOR, 0), 0, 0), - ("a transaction's value to its sender", db(actor()), call(CALLER, VALUE), 0, 0), + // (case, database, transaction, write records, logs, new accounts and slots) + let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize, u64); 7] = [ + // The move's sender and recipient are one account, which it leaves as it was: no record. + ("a CALLCODE", db(actor().callcode(RECEIVER, value)), call(ACTOR, 0), 0, 0, 0), + ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 0, 0, 0), + ("a zero-value CALL", db(actor().call(RECEIVER, U256::ZERO)), call(ACTOR, 0), 0, 0, 0), + ("a transaction's value to its sender", db(actor()), call(CALLER, VALUE), 0, 0, 0), ( - "a creation that destructs to itself: its endowment's log alone", + "a creation that destructs to itself: its endowment's log alone; the destruction takes \ + back the new account's record and its growth, and the creator's record stands", db(actor().create(value, &burner)), call(ACTOR, 0), - 2, 1, + 1, + 0, ), - ("an older account destructing to itself", db(actor()), call(DESTRUCTOR, 0), 0, 0), - ("a value call a system contract refuses", db(refused), call(ACTOR, 0), 0, 0), + ("an older account destructing to itself", db(actor()), call(DESTRUCTOR, 0), 0, 0, 0), + ("a value call a system contract refuses", db(refused), call(ACTOR, 0), 0, 0, 0), ]; - for (name, db, tx, records, logs) in cases { + for (name, db, tx, records, logs, growth) in cases { let body = transaction_body_bytes(&tx); let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); @@ -654,6 +758,7 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { LimitUsage { data_size: body + records * WRITE_RECORD_SIZE + logs as u64 * TRANSFER_LOG_SIZE, write_records: records, + state_growth: growth, }, "{name}", ); @@ -673,10 +778,11 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { /// A start revm refuses on its caller's account moves nothing and writes nothing, so nothing is /// counted for it, and no limit stops it for what it would have counted: it runs as it does with /// no limit. Here, a value call its caller cannot fund, which revm answers with `OutOfFunds` and no -/// data, which the actor returns: a `CALL`, whose move would count two records and a transfer log, -/// and a `CALLCODE`, whose move to its own account would count the caller's record alone. Neither -/// the transaction's limit nor the frame's budget one byte short of those bytes changes anything. -/// The same call funded to the last wei is made, and both stop it there. +/// data, which the actor returns: a `CALL`, whose move would count two records and a transfer log. +/// Neither the transaction's limit nor the frame's budget one byte short of those bytes changes +/// anything. The same call funded to the last wei is made, and both stop it there. A `CALLCODE` +/// is not among the cases: its move is to the calling account itself, which counts nothing funded +/// or not, so no limit can stop it. #[test] fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { let value = U256::from(VALUE); @@ -695,18 +801,11 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { })); let body = transaction_body_bytes(&tx); let actor = |call: BytecodeBuilder| call.append(POP).return_returndata().build(); - let cases = [ - ( - "a CALL", - actor(BytecodeBuilder::default().call(RECEIVER, value)), - 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - ), - ( - "a CALLCODE", - actor(BytecodeBuilder::default().callcode(RECEIVER, value)), - WRITE_RECORD_SIZE, - ), - ]; + let cases = [( + "a CALL", + actor(BytecodeBuilder::default().call(RECEIVER, value)), + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + )]; for (name, actor, bytes) in cases { let tx_limit = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + bytes - 1); let frame_budget = @@ -717,7 +816,11 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { assert!(free.result.is_success(), "{name}: {:?}", free.result); assert_eq!(free.result.output(), Some(&Bytes::new()), "{name}: the refusal's empty data"); assert!(free.result.logs().is_empty(), "{name}"); - assert_eq!(free.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + assert_eq!( + free.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{name}" + ); assert_eq!(balance(&free, ACTOR), U256::from(VALUE - 1), "{name}: nothing moved"); for limits in [tx_limit, frame_budget] { let limited = execute_under(db(VALUE - 1, &actor), tx.clone(), limits); @@ -728,7 +831,9 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { } let stopped = execute_under(db(VALUE, &actor), tx.clone(), tx_limit); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: body + bytes - 1 }; + // The call's start gets 98% of the actor's budget, which the move crosses first. + let budget = crate::common::share(bytes - 1); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; assert_eq!( stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), @@ -745,10 +850,16 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { } } -/// A value call its caller cannot fund is charged nothing for the records it would make, as it -/// counts none: a caller that keeps less gas, once it has forwarded all it can, than those records' -/// history carries on past the refused call. Funded, the same call runs it out of gas at its -/// opcode, which shows the caller does keep less than that. +/// A value call its caller cannot fund is charged nothing at its opcode: the frame-start hook, +/// which charges a start's records from the journal's state, sees the caller cannot fund the value +/// revm then refuses, and the refused call makes no record. So the caller runs on past the refused +/// call, billed its body's history alone and counting nothing more, even where it keeps less than +/// the records would have cost once it has forwarded all it can; the same caller, able to fund the +/// value, runs out of gas at the opcode on the records' history. +/// +/// Before the net-change rule the opcode charged the records whether or not the caller could fund +/// the value, and the charge came back when the refused start returned; a caller that could not +/// pay it halted at the opcode though the start would have been refused. #[test] fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { let actor = @@ -768,26 +879,13 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { ..Default::default() })) }; - // About 150,000 gas for the actor, of which it keeps a sixty-fourth at its `CALL`: less than - // the history of the two records the move would make. Where 64 times that history is not - // above the 20,000 the actor needs to reach its `CALL`, as where a history byte costs - // nothing, no actor both reaches the call and keeps less than the records cost. - let records = history_gas(2 * WRITE_RECORD_SIZE).unwrap(); - let actor_gas = (64 * records).saturating_sub(1).min(150_000); - if actor_gas < 20_000 { - return; - } - assert!(actor_gas / 64 < records, "the actor keeps less than the records cost"); - let gas_limit = 21_000 + history_gas(transaction_body_bytes(&tx(0))).unwrap() + actor_gas; + let body = transaction_body_bytes(&tx(0)); - let refused = execute_under(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + let refused = execute_under(db(VALUE - 1), tx(20_000_000), EvmTxRuntimeLimits::no_limits()); assert!(refused.result.is_success(), "{:?}", refused.result); - let funded = execute_under(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); - assert!(funded.result.is_halt(), "{:?}", funded.result); - let body = transaction_body_bytes(&tx(gas_limit)); assert_eq!( refused.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "the refused call counted nothing", ); assert_eq!( @@ -795,128 +893,28 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { history_gas(body).unwrap(), "and paid the body's history alone" ); - assert_eq!(funded.gas.gas_used, gas_limit, "the funded call's halt used the whole gas limit"); -} - -/// Appends a call carrying [`VALUE`] to `MegaAccessControl`, which answers it with -/// `NonZeroTransfer()` before revm looks at the caller's balance, leaving the call's status on the -/// stack. From a caller that holds less, it is a start revm would refuse, answered before its -/// init. -fn call_the_system_contract_answers(code: BytecodeBuilder) -> BytecodeBuilder { - code.mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) - .append_many([PUSH0, PUSH0]) - .push_number(4u64) - .append(PUSH0) - .push_u256(U256::from(VALUE)) - .push_address(ACCESS_CONTROL_ADDRESS) - .append_many([GAS, CALL]) -} -/// Whether revm refuses a start on its caller's account is found once, by the opcode starting it, -/// and taken by the frame's init. A start answered before its init leaves that answer behind: -/// here a value call its caller cannot fund, which the system contract answers with -/// `NonZeroTransfer()` before revm could refuse it. The frame the caller starts next takes none -/// of it: a `DELEGATECALL` whose two fresh slots cross its budget by a byte reverts on that -/// budget, as it does with no call before it, and keeps nothing. -#[test] -fn test_a_start_answered_before_its_init_leaves_no_refusal_for_the_next() { - const WRITER: Address = address!("0000000000000000000000000000000000d00008"); - let writer = BytecodeBuilder::default() - .sstore(U256::from(1), U256::from(1)) - .sstore(U256::from(2), U256::from(1)) - .stop() - .build(); - // The `ACTOR` holds nothing, so revm would refuse the value; the system contract answers first. - let answered_call = call_the_system_contract_answers; - let delegate_to_writer = |code: BytecodeBuilder| { - code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(WRITER) - .append_many([GAS, DELEGATECALL]) - .return_top() - }; - let db = |actor: BytecodeBuilder| { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) - .account_code(WRITER, writer.clone()) - .account_code(ACTOR, actor.build()) - }; - let tx = OpTx(op_transaction(TxEnv { - caller: CALLER, - kind: TxKind::Call(ACTOR), - gas_limit: 20_000_000, - ..Default::default() - })); - let body = transaction_body_bytes(&tx); - let limits = EvmTxRuntimeLimits::no_limits() - .with_frame_data_size_limit(cap_for(1, 2 * WRITE_RECORD_SIZE - 1)); - - let answer = execute_under( - db(answered_call(BytecodeBuilder::default()).append(POP).return_returndata()), - tx.clone(), - limits, - ); - assert_eq!( - answer.result.output(), - Some(&Bytes::from(IMegaAccessControl::NonZeroTransfer::SELECTOR.to_vec())), - "the system contract answers the call, not revm" - ); - - let cases = [ - ("alone", delegate_to_writer(BytecodeBuilder::default())), - ( - "after the answered call", - delegate_to_writer(answered_call(BytecodeBuilder::default()).append(POP)), - ), - ]; - for (name, actor) in cases { - let outcome = execute_under(db(actor), tx.clone(), limits); - assert_eq!( - outcome.result.output(), - Some(&Bytes::from(U256::ZERO.to_be_bytes::<32>())), - "{name}: the DELEGATECALL reverted on its budget", + // About 150,000 gas for the actor, of which it keeps a fiftieth at its `CALL`: less than the + // history of the two records the move would make. Where 50 times that history is not above + // the 20,000 the actor needs to reach its `CALL`, as where a history byte costs nothing, no + // actor both reaches the call and keeps less than the records cost. + let records = history_gas(2 * WRITE_RECORD_SIZE).unwrap(); + let actor_gas = (50 * records).saturating_sub(1).min(150_000); + if actor_gas < 20_000 { + mega_evm::test_utils::note_price_guard( + "two write records' history is too cheap for a caller to keep less than it", ); - assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget below is no stop"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + return; } -} - -/// The answer a transaction's last start left behind is not taken by the next transaction's first -/// frame, whose own answer nothing staged: a deposit pays no history, so no record of its is -/// charged before execution and nothing asks its sender's account before the frame's init. Its -/// value to `RECEIVER` is counted — the recipient's record and the transfer log — as on an EVM -/// that ran nothing before it. -#[test] -fn test_an_answer_a_transaction_leaves_is_not_taken_by_the_next() { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) - .account_code(RECEIVER, Bytes::from_static(&[STOP])) - .account_code( - ACTOR, - call_the_system_contract_answers(BytecodeBuilder::default()).stop().build(), - ); - let answered = OpTx(op_transaction(TxEnv { - caller: CALLER, - kind: TxKind::Call(ACTOR), - gas_limit: 20_000_000, - ..Default::default() - })); - let user_deposit = || deposit(TxKind::Call(RECEIVER), 1_000, 400); - let body = transaction_body_bytes(&user_deposit()); - - let alone = execute_under(db.clone(), user_deposit(), EvmTxRuntimeLimits::no_limits()); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())); - let first = evm.execute_transaction(answered).expect("the transaction is valid"); - assert!(first.result.is_success(), "{:?}", first.result); - let next = evm.execute_transaction(user_deposit()).expect("the transaction is valid"); - - assert_eq!( - next.usage, - LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, - ); - assert_eq!(next.usage, alone.usage); - assert_eq!(next.result, alone.result); + assert!(actor_gas / 50 < records, "the actor keeps less than the records cost"); + let gas_limit = 21_000 + history_gas(body).unwrap() + actor_gas; + let unfunded = execute_under(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(unfunded.result.is_success(), "unfunded: charged nothing: {:?}", unfunded.result); + assert_eq!(unfunded.usage, refused.usage, "unfunded: nothing counted"); + assert_eq!(unfunded.gas.history, refused.gas.history, "unfunded: the body's history alone"); + let funded = execute_under(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(funded.result.is_halt(), "funded: out of gas on the records: {:?}", funded.result); + assert_eq!(funded.gas.gas_used, gas_limit, "funded: the halt used the gas limit"); } /// Raises the value of every call to [`RECEIVER`] by one wei as the call starts: an inspector's @@ -936,12 +934,12 @@ impl Inspector, EthInterpreter> for RaisesValue { } } -/// An inspector may rewrite a frame's input after the opcode that starts it found whether revm -/// refuses it, so the inspected start asks again on the input the inspector leaves. The `ACTOR` -/// can fund the value its `CALL` carries and not the one the inspector raises it to: revm refuses -/// the start with `OutOfFunds` and no data, which the actor returns, and nothing is counted for -/// it — under a frame budget one byte short of the records and the transfer log the start would -/// count, which would stop it with the limit's revert data otherwise. +/// An inspector may rewrite a frame's input after the opcode that starts it charged its records, +/// and revm decides the start on the input the inspector leaves. The `ACTOR` can fund the value +/// its `CALL` carries and not the one the inspector raises it to: revm refuses the start with +/// `OutOfFunds` and no data, which the actor returns, and nothing is counted for it — under a +/// frame budget one byte short of the records and the transfer log the start would count, which +/// would stop it with the limit's revert data otherwise. #[test] fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { let actor = BytecodeBuilder::default() @@ -972,20 +970,19 @@ fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { assert_eq!(outcome.result.output(), Some(&Bytes::new()), "the refusal's empty data"); assert!(transfer_logs(&outcome).is_empty(), "nothing moved"); assert_eq!(balance(&outcome, ACTOR), U256::from(VALUE)); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.limit_exceeded, None); } -/// A creation onto an occupied address is the one refusal decided after its start is counted: -/// revm reads the created address's account only once it builds the frame, and reading it any -/// earlier would load it. Without a limit, the creation fails on the collision after it bumped its -/// creator's nonce, so the creator's record is kept, and the created account's record and the -/// transfer log are not. Under the transaction's limit one byte short of what the start counts, -/// the start's records and transfer log cross it, and the stop comes first: the creation returns -/// the stop rather than the collision's empty data, which the creator returns, and the creator -/// keeps its nonce record either way. +/// A creation onto an occupied address fails on the collision once revm bumped its creator's +/// nonce, and its start is held to nothing: under the transaction's limit one byte short of what +/// its start would count — the created account's record, its creator's nonce and the transfer log +/// — it fails as without a limit, with the collision's empty data, which the creator returns. The +/// created account's record and the transfer log go with the failure; the creator keeps its nonce +/// record, held to its own limits with it, so a limit one byte short of the body and that record +/// stops the creator. #[test] -fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() { +fn test_a_creation_onto_an_occupied_address_fails_on_the_collision() { let occupied = Site::Create2.recipient(); let actor = BytecodeBuilder::default() .create2(U256::from(VALUE), [], U256::ZERO) @@ -1006,6 +1003,13 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() ..Default::default() })); let body = transaction_body_bytes(&tx); + let under = |limit| { + execute_under( + db(), + tx.clone(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ) + }; let free = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); assert!(free.result.is_success(), "{:?}", free.result); @@ -1015,19 +1019,24 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() assert_eq!(balance(&free, occupied), U256::ZERO, "no value moved"); assert_eq!( free.usage, - LimitUsage { data_size: body + WRITE_RECORD_SIZE, write_records: 1 }, + LimitUsage { data_size: body + WRITE_RECORD_SIZE, write_records: 1, state_growth: 0 }, "the creator's nonce alone", ); - let limit = body + Site::Create2.bytes() - 1; - let stopped = - execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); - assert!(stopped.result.is_success(), "the creator catches the stop: {:?}", stopped.result); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; - assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the stop first"); - assert_eq!(stopped.limit_exceeded, None); - assert_eq!(stopped.usage, free.usage, "the creator's nonce alone"); - assert_eq!(stopped.state[&ACTOR].info.nonce, 1, "the stopped creation bumped it too"); + let limited = under(body + Site::Create2.bytes() - 1); + assert_eq!(limited.limit_exceeded, None); + assert_eq!(limited.result, free.result, "the collision, as without a limit"); + assert_eq!(limited.usage, free.usage, "the creator's nonce alone"); + assert_eq!(limited.gas, free.gas); + + let limit = body + WRITE_RECORD_SIZE - 1; + let stopped = under(limit); + // The creator's nonce record overdraws the actor's budget, which is held first and named. + let stop = + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: WRITE_RECORD_SIZE - 1 }; + assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the creator's"); + assert!(stopped.limit_exceeded.is_some(), "the transaction's own frame is the creator"); + assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); } /// A deposit's value moves in its first frame and is logged there, from the depositor to the @@ -1050,7 +1059,12 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { assert_eq!(balance(&outcome, DEPOSITOR), U256::from(600)); assert_eq!( outcome.usage, - LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + LimitUsage { + data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + write_records: 1, + state_growth: 1 + }, + "the recipient's record and the log; the deposit creates its depositor", ); assert_eq!((outcome.gas.history, outcome.gas.history_bytes), (0, 0), "a deposit pays none"); @@ -1071,8 +1085,8 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { ); assert_eq!( stopped.limit_exceeded.map(|stop| (stop.exceeded_limit(), stop.is_frame_local())), - Some((true, false)), - "a user's deposit is stopped at its transfer log", + Some((true, true)), + "a user's deposit is stopped at its transfer log, on its frame's budget", ); assert!(stopped.result.logs().is_empty()); assert_eq!(balance(&stopped, DEPOSITOR), U256::from(1_000), "the mint stays, the value not"); @@ -1107,6 +1121,135 @@ fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { } } +/// A value call whose recipient cannot hold the value — its balance would overflow — is refused by +/// revm with `OverflowPayment` before it journals the move: no transfer log, no record, and the +/// history the actor paid for the records at its opcode comes back with the refusal. A limit one +/// byte short of the start's bytes changes nothing: nothing was counted. +#[test] +fn test_a_value_call_its_recipient_cannot_hold_keeps_nothing() { + let actor = BytecodeBuilder::default().call(PAYEE, U256::from(VALUE)).return_top().build(); + let db = || { + MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_balance(PAYEE, U256::MAX) + .account_code(ACTOR, actor.clone()) + }; + for gas_limit in GAS_LIMITS { + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + for limits in [ + EvmTxRuntimeLimits::no_limits(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + start - 1), + ] { + let outcome = execute_under(db(), tx.clone(), limits); + assert!(outcome.result.is_success(), "{limits:?}: {:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::from(vec![0; 32])), "the call failed"); + assert!(outcome.result.logs().is_empty(), "{limits:?}: no transfer log"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); + assert_eq!( + outcome.gas.history, + history_gas(body).unwrap(), + "the records' charge came back" + ); + } + } +} + +/// A value call to a precompile that fails after its gas check — the BN254 pairing given an input +/// of the wrong length — moved its value and journaled its transfer log before the precompile ran, +/// and revm takes both back with the failure. The start is held to the limits as revm made it, on +/// the records and the log it counted before the failure took them back: under a limit one byte +/// short of them the call is answered with the stop rather than the failure, and either way the +/// transaction keeps its body alone. +#[test] +fn test_a_failed_precompiles_start_is_held_to_the_limits_it_counted_against() { + const EC_PAIRING: Address = address!("0000000000000000000000000000000000000008"); + let actor = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append(PUSH0) + .push_number(VALUE) + .push_address(EC_PAIRING) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build(); + let db = || { + MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_code(ACTOR, actor.clone()) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: value_call_room(), + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + + let failed = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(failed.result.is_success(), "{:?}", failed.result); + assert_eq!(failed.result.output(), Some(&Bytes::new()), "the precompile's failure"); + assert!(failed.result.logs().is_empty(), "the failure took the transfer log back"); + assert_eq!(failed.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); + + let limit = body + start - 1; + let stopped = + execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + let budget = crate::common::share(start - 1); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; + assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the stop"); + assert!(stopped.result.logs().is_empty()); + assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); +} + +/// A `CREATE` from a contract whose nonce cannot be bumped is refused by the opcode itself, which +/// pushes zero before its start's hook: no account, no record, no log, and no history charged for +/// the two records the start would have made. A limit one byte short of the start's bytes changes +/// nothing. +#[test] +fn test_a_nested_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { + let actor = BytecodeBuilder::default().create(U256::from(1), [STOP]).return_top().build(); + let db = || { + MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_nonce(ACTOR, u64::MAX) + .account_code(ACTOR, actor.clone()) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: value_call_room(), + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + for limits in [ + EvmTxRuntimeLimits::no_limits(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + start - 1), + ] { + let outcome = execute_under(db(), tx.clone(), limits); + assert!(outcome.result.is_success(), "{limits:?}: {:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::from(vec![0; 32])), "no address"); + assert!(outcome.result.logs().is_empty(), "{limits:?}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); + assert_eq!(outcome.state[&ACTOR].info.nonce, u64::MAX, "{limits:?}: not bumped"); + assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "no charge for the records"); + } +} + /// A creation from an account whose nonce cannot be bumped is answered by revm with a success /// that creates nothing and moves nothing: a `Return` with no address, and no log. It keeps /// nothing either, and no limit stops it for what it did not do. @@ -1134,7 +1277,11 @@ fn test_a_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { let outcome = execute_under(db, tx.clone(), limits); assert!(created_nothing(&outcome), "{limits:?}: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "{limits:?}"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{limits:?}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{limits:?}" + ); } let db = MemoryDatabase::default() @@ -1155,7 +1302,7 @@ fn test_a_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { .execute_transaction(tx) .expect("the transaction is valid with the nonce check off"); assert!(created_nothing(&outcome), "{:?}", outcome.result); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.gas.history_bytes, body, "its body alone"); assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "and the history of its body"); } @@ -1202,7 +1349,8 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { outcome.usage, LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - write_records: 1 + write_records: 1, + state_growth: 0, }, "counted all the same", ); @@ -1224,8 +1372,8 @@ fn test_transfer_logs_keep_execution_order() { const MOVED: u64 = 7; let marker = B256::repeat_byte(0x4d); // Regular room, the new account a creation adds, and sixty-four times the history of a few - // records: the creation is forwarded all but a 64th of the gas, and the caller pays the - // records from the 64th it keeps, at whatever a byte costs. + // records: the creation is forwarded all but 2 per cent of the gas, and the caller pays the + // records from the fiftieth it keeps, at whatever a byte costs. let gas_limit = 2_000_000 + 2 * account_state_gas() + crate::common::body_history(0) + diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index d50e617d9..4c9070ec1 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1,7 +1,7 @@ //! Gas detention against every other reader of a frame's gas, and against every out-of-gas. //! //! A detained frame's spendable gas is held at what the limit leaves the transaction, and the rest -//! is withheld: only a regular charge sees the difference. `GAS`, the 63/64 forward, the `SSTORE` +//! is withheld: only a regular charge sees the difference. `GAS`, the 98/100 forward, the `SSTORE` //! sentry, the skip-cold checks and a callee's inheritance see the whole regular gas. So a //! transaction that reads volatile data runs as it does without the read — the same result and the //! same bill on every ledger — unless its compute crosses the limit, which is a regular charge the @@ -426,8 +426,8 @@ fn test_a_callees_out_of_gas_is_caught_as_without_the_read() { /// /// The callee's charge fails on an operand, a memory expansion, a hash, four copies, a log and an /// invalid opcode, all on all the gas; and on the history of the write records a value call makes, -/// after the call forwarded 63/64 of its gas to a frame that never starts. That callee is given -/// 400,000, or less where it would pay that history out of the 64th it keeps, and its caller +/// after the call forwarded 98/100 of its gas to a frame that never starts. That callee is given +/// 400,000, or less where it would pay that history out of the fiftieth it keeps, and its caller /// computes twenty rounds further, so the limit is left less than the callee forwards. Above the /// execution cap the reservoir pays that history, so that case runs below it. A precompile that /// rejects its input halts without running a frame, and burns all it was forwarded too. @@ -456,12 +456,13 @@ fn test_what_a_halting_callee_burns_is_not_compute() { ]; // 6,396 rounds: 19,878,768 of compute before the call. let rounds = 6_396; - // The value call's callee keeps a 64th of what it has at its `CALL`, which has to be less than - // the history of the records the call makes. It spends at most 40,000 before the forward — the - // value transfer, the new account and the cold access. Where 64 times that history is under - // 100,000, as where a history byte costs nothing, the callee cannot also forward past the - // margin its caller leaves, and the case has nothing to show. - let middle_gas = (64 * history(2 * WRITE_RECORD_SIZE)).saturating_sub(1).min(400_000); + // The value call's callee keeps a fiftieth of what it has at its `CALL` once the forward is + // taken, which has to be less than the history of the records the call makes: given less than + // 50 times that history, it keeps less whatever it spends before the forward — the value + // transfer, the new account and the cold access. Where 50 times that history is under 100,000, + // as where a history byte costs nothing, the callee cannot also forward past the margin its + // caller leaves, and the case has nothing to show. + let middle_gas = (50 * history(2 * WRITE_RECORD_SIZE)).saturating_sub(1).min(400_000); for gas_limit in TIERS { for (name, callee) in &cases { let records = name.starts_with("a value call"); @@ -486,11 +487,11 @@ fn test_what_a_halting_callee_burns_is_not_compute() { assert_eq!(slot(&detained, 0), Some(U256::ZERO), "{name}: the call failed"); if records { // `MIDDLE` halted on all it was given; the rest of the regular ledger is compute, - // and it leaves the limit less than the 63/64 `MIDDLE` forwarded, so counting that + // and it leaves the limit less than the 98/100 `MIDDLE` forwarded, so counting that // forward as compute would have stopped the transaction. let compute = plain.outcome.gas.regular - intrinsic(gas_limit) - middle_gas; let margin = detained.limit.unwrap() - compute; - let forwarded = (middle_gas - 40_000) * 63 / 64; + let forwarded = (middle_gas - 40_000) * 98 / 100; assert!(margin < forwarded, "{name}: {margin} short of the limit"); } } @@ -610,73 +611,41 @@ fn test_a_returndatacopy_that_cannot_pay_its_words_burns_what_its_frame_had() { /// for the recipient. The body's history is on the history ledger, whichever pool paid it. const CALL_INTRINSIC: u64 = 12_000 + 3_000; -/// A charge the interpreter's step loop makes before the opcode runs — its static gas — is seen by -/// no wrapper, so what a frame had when it fails counts as compute: burned gas counted as compute, -/// which brings the stop earlier, never later, and by less than the failed charge's price per -/// halting frame. +/// A charge the interpreter's step loop makes before the opcode runs — its static gas — records +/// what the frame had when it fails, as every failed charge does, so a halt on it burns that, and +/// what it burns is not compute. /// /// Fifty children forwarded 5,002 gas each run a `PUSH20` and a `SELFDESTRUCT`, whose static -/// charge of 5,000 fails with 4,999 left. Under a cap of 200,000 the caller stops, though about -/// 8,500 gas of instructions ran after its read. The child that took the compute past the limit -/// did so without a charge crossing it, so the stop is its caller's next charge, and the stop's -/// compute, which the regular ledger bills, is the limit and that child's overshoot, under the -/// 5,000 it failed to pay. Under a cap of 300,000, above fifty times the forward and the caller's -/// own work, the caller completes as without the read. +/// charge of 5,000 fails with 4,999 left. Each burns those, and the caller completes under a cap of +/// 200,000 as without the read: counted as compute, the fifty burns would pass the cap. /// -/// Rules: [S12.18], [S12]. Independence: independent — the limit, the walk of the charges to the -/// crossing and the intrinsic gas are hand arithmetic from the opcode prices and EIP-2780. +/// Rules: [S12.18], [S12]. Independence: independent — every charge is the opcode's price, the +/// burns are the forward less the `PUSH20`, and the intrinsic gas is EIP-2780's. #[test] -fn test_a_halt_on_a_static_charge_counts_what_its_frame_had_as_compute() { +fn test_a_halt_on_a_static_charge_burns_what_its_frame_had() { let child = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); + // The read and its `POP`, then fifty calls: five pushes, the address, the forward, the access + // (cold the first time), the child's `PUSH20`, and the `POP` of the status. + let warm = crate::salt::entry(GasId::warm_storage_read_cost()); + let compute = 2 + 2 + 50 * (10 + 3 + 3 + 3 + 2) + cold_access() + 49 * warm; + let burned = 50 * (5_002 - 3); + let limit = 2 + 200_000; + assert!(compute <= limit && compute + burned > limit, "only the burns would pass the limit"); for gas_limit in TIERS { - let build = |first| { + let (detained, plain) = with_and_without_read_under(200_000, |first| { let code = calls_to_child(op(BytecodeBuilder::default(), first), 50, 5_002); let db = MemoryDatabase::default() .account_code(CONTRACT, code.stop().build()) .account_code(CHILD, child.clone()); (db, gas_limit) - }; - let (detained, plain) = with_and_without_read_under(200_000, build); - let limit = detained.limit.unwrap(); - assert_eq!(limit, 2 + 200_000); - assert_eq!(detained.outcome.result.output(), Some(&stop_data(limit))); - // The compute after the read: its `POP`, then each call — five pushes, the address, the - // forward's push, the access, cold the first time — and the child's whole forward, which - // it computes with or burns counted as compute, and the caller's `POP`. The caller's first - // charge the limit leaves no room for is the stop. - let mut since_read = 2; - let crossing = 'calls: { - for call in 0..50 { - let access = if call == 0 { cold_access() } else { 100 }; - for charge in [2, 2, 2, 2, 2, 3, 3, access] { - if since_read + charge > 200_000 { - break 'calls since_read; - } - since_read += charge; - } - since_read += 5_002; - if since_read + 2 > 200_000 { - break 'calls since_read; - } - since_read += 2; - } - panic!("the calls fit the cap"); - }; - assert!(crossing > 200_000 && crossing - 200_000 < 5_000, "an overshoot: {crossing}"); - let used = 2 + crossing; + }); + assert_eq!(detained.limit, Some(limit), "the read's compute plus the cap"); + assert_as_without_read(&detained, &plain, "fifty halts on a static charge"); assert_eq!( - detained.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit, - used, - frame_local: false - }) + plain.outcome.gas.regular, + intrinsic(gas_limit) + compute + burned, + "the bill is the intrinsic gas, the compute and the burns" ); - assert_eq!(detained.outcome.gas.regular, CALL_INTRINSIC + used); - assert!(plain.outcome.result.is_success()); - let (detained, plain) = with_and_without_read_under(300_000, build); - assert_as_without_read(&detained, &plain, "fifty halts on a static charge"); } } @@ -692,92 +661,77 @@ fn call_forwarding(code: BytecodeBuilder, to: Address, gas: u32) -> BytecodeBuil .append(CALL) } -/// One case of [`test_a_static_gas_halt_takes_the_compute_past_the_limit`]: the transaction's -/// code after its read, the cap, and the bill worked out by hand. -struct Overshoot { +/// One case of [`test_static_gas_halts_leave_the_compute_where_it_was`]: the transaction's code +/// after its read, the cap, and the bill worked out by hand. +struct StaticHalts { name: &'static str, /// [`CONTRACT`]'s code after its read: the read's `POP`, a call, and what follows it. after_read: fn(BytecodeBuilder) -> BytecodeBuilder, /// The block-environment cap. cap: u64, - /// The transaction's compute, the read's own two gas included, up to the end of the run or - /// to the charge that crossed. + /// The transaction's compute, the read's own two gas included: every charge its frames made. compute: u64, - /// Whether that compute ends on a stop. - stopped: bool, - /// The compute of the same program without the read, which completes. - plain_compute: u64, -} - -/// A frame that halts because it cannot pay an opcode's static gas counts what it had left as -/// compute, and that can take the transaction's compute past the limit without a crossing: no -/// regular charge crossed the limit, so nothing stopped it. The overshoot is less than the static -/// gas the frame failed to pay. Its caller then resumes with no spendable gas, so its next non-zero -/// regular charge is the crossing; a caller whose whole gas cannot pay its own next static gas -/// halts the same way first and adds what it had left, so the overshoots of a chain of halting -/// frames add up. A transaction that makes no non-zero regular charge after the overshoot is not -/// stopped at all, and ends with its compute past the limit. + /// What the halting frames burned: what each had when its static charge failed. + burned: u64, +} + +/// A frame that halts because it cannot pay an opcode's static gas burns what it had left, so a +/// halt adds nothing to the transaction's compute, along a chain of such frames too: the compute +/// stays within the limit where the burns counted as compute would take it past. /// /// Every halt here is a `SELFDESTRUCT`, whose static gas of 5,000 is the largest. The charges, /// from the read on: `TIMESTAMP` 2, which is the compute at the read, then `POP` 2; a call is five /// `PUSH0` at 2, a `PUSH20` and a `PUSH4` at 3, and its cold access of 3,000; a callee forwarded -/// 5,002 runs a `PUSH20` of 3 and halts on its `SELFDESTRUCT` with 4,999 left, all of which is -/// compute. So a call to a halting callee is 3,016 of compute in its caller and the 5,002 it -/// forwarded. +/// 5,002 runs a `PUSH20` of 3 and halts on its `SELFDESTRUCT` with 4,999 left, which it burns. /// -/// - **One frame.** The callee's halt brings the compute from 3,023 to 8,022; under a cap of 3,400 -/// the limit is 3,402, so the halt overshoots it by 4,620, less than 5,000. The caller's `POP` is -/// its next charge and the crossing: the stop reports 8,022, and the bill is the intrinsic gas -/// and that compute, without the `POP`. +/// - **One frame.** The callee's halt leaves the compute at 3,023; under a cap of 3,400 the limit +/// is 3,402, which the caller's `POP` stays within: 3,025, and 4,999 burned. /// - **A chain of two.** [`HALTING_MIDDLE`] is forwarded 12,000, calls [`CHILD`] with 5,002 — /// compute 6,036 at its `CALL`, 6,039 after the child's `PUSH20` — and keeps 12,000 − 3,016 − -/// 5,002 = 3,982. The child's halt brings the compute to 11,038, 4,996 past a limit of 6,042 (a -/// cap of 6,040); the middle frame's next opcode is a `SELFDESTRUCT` its 3,982 cannot pay, so it -/// halts too and adds them: 15,020, 8,978 past the limit, more than either halt could add alone. -/// The caller's `POP` is the crossing. -/// - **No charge after.** The one-frame case ending on `STOP`, which charges nothing, after the -/// call: the transaction succeeds, its compute 8,022, past the limit of 3,402. +/// 5,002 = 3,982. The child's halt burns 4,999, and the middle frame's next opcode is a +/// `SELFDESTRUCT` its 3,982 cannot pay, so it halts too and burns them. The caller's `POP` brings +/// the compute to 6,041, within a limit of 6,042 (a cap of 6,040). +/// - **No charge after.** The one-frame case ending on `STOP` after the call: 3,023. /// -/// Each case runs below the execution cap and above it, and is billed the same in both; without -/// the read the program completes and is billed its whole compute. +/// Each case runs below the execution cap and above it, completes as without the read, and is +/// billed its compute and its burns. /// /// Rules: [S12.18], [S12.24], [S12.38], [S11], [S12]. Independence: independent — every charge is /// the opcode's price, the limit is the read's compute plus the cap, and the intrinsic gas is /// EIP-2780's. #[test] -fn test_a_static_gas_halt_takes_the_compute_past_the_limit() { +fn test_static_gas_halts_leave_the_compute_where_it_was() { let child = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); // The middle frame's `SELFDESTRUCT` names the status its call left as the beneficiary. let middle = call_forwarding(BytecodeBuilder::default(), CHILD, 5_002).append(SELFDESTRUCT).build(); - // The cold access the call to the first callee pays, which every case's caps are set above. - let call = 2 + 2 + 10 + 3 + 3 + cold_access(); + // A call to a cold callee: five pushes, the address, the forward and the cold access. + let call = 10 + 3 + 3 + cold_access(); + // The read and its `POP`, then the call to the first callee. + let to_callee = 2 + 2 + call; let cases = [ - Overshoot { + StaticHalts { name: "one frame", after_read: |code| call_forwarding(code.append(POP), CHILD, 5_002).append(POP).stop(), cap: 3_400, - compute: call + 5_002, - stopped: true, - plain_compute: call + 5_002 + 2, + compute: to_callee + 3 + 2, + burned: 5_002 - 3, }, - Overshoot { + StaticHalts { name: "a chain of two", after_read: |code| { call_forwarding(code.append(POP), HALTING_MIDDLE, 12_000).append(POP).stop() }, cap: 6_040, - compute: call + 12_000, - stopped: true, - plain_compute: call + 12_000 + 2, + compute: to_callee + call + 3 + 2, + burned: (5_002 - 3) + (12_000 - call - 5_002), }, - Overshoot { + StaticHalts { name: "no charge after", after_read: |code| call_forwarding(code.append(POP), CHILD, 5_002).stop(), cap: 3_400, - compute: call + 5_002, - stopped: false, - plain_compute: call + 5_002, + compute: to_callee + 3, + burned: 5_002 - 3, }, ]; for gas_limit in TIERS { @@ -793,41 +747,16 @@ fn test_a_static_gas_halt_takes_the_compute_past_the_limit() { }); let limit = 2 + case.cap; assert_eq!(detained.limit, Some(limit), "{name}: the read's compute plus the cap"); - assert!(case.compute > limit, "{name}: the halts took the compute past the limit"); - if case.stopped { - assert_eq!( - detained.outcome.result.output(), - Some(&stop_data(limit)), - "{name}: the stop" - ); - assert_eq!( - detained.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit, - used: case.compute, - frame_local: false - }), - "{name}: the stop reports the compute past the limit" - ); - } else { - assert!( - detained.outcome.result.is_success(), - "{name}: {:?}", - detained.outcome.result - ); - assert_eq!(detained.outcome.limit_exceeded, None, "{name}: no stop"); - } - assert_eq!( - detained.outcome.gas.regular, - CALL_INTRINSIC + case.compute, - "{name}: the bill is the intrinsic gas and the compute" + assert!(case.compute <= limit, "{name}: the compute stays within the limit"); + assert!( + case.compute + case.burned > limit, + "{name}: the burns counted as compute would pass it" ); - assert!(plain.outcome.result.is_success(), "{name}: {:?}", plain.outcome.result); + assert_as_without_read(&detained, &plain, name); assert_eq!( plain.outcome.gas.regular, - CALL_INTRINSIC + case.plain_compute, - "{name}: without the read" + CALL_INTRINSIC + case.compute + case.burned, + "{name}: the bill is the intrinsic gas, the compute and the burns" ); } } @@ -1538,6 +1467,69 @@ fn test_the_kzg_point_evaluation_is_priced_and_keeps_no_clamp() { } } +/// Upstream's KZG point evaluation, which costs 50,000, put at the KZG address in place of the +/// Satin entry, which costs 100,000, and called as above, after a read with 80,000 under a cap of +/// 50,000, whose allowance pays neither price. Gas detention decides the same call two ways, +/// priced and unpriced — a failed call against a crossing — and which way follows the route that +/// installed the precompile, not the precompile: +/// +/// - installed through `with_dyn_precompiles`, the route a node changes its set by, it is not +/// priced: it is run on the allowance, runs out of it, and is the stop, which gives its forward +/// back and which its caller catches before it stores the failure; +/// - put in the map around the engine, through the mutable reference `EvmTr::all_mut` hands out, +/// under the Satin entry's id, it is still priced from the Satin table: priced past its forward, +/// it runs on the forward, as the Satin entry does, and fails — on its input, past its own gas +/// check — a failed call that burns its forward, which its caller survives to store. A valid +/// input would compute there, past the cap: the boundary a node keeps to by changing its set +/// through the engine. +#[test] +fn test_a_priced_and_an_unpriced_precompile_part_as_a_failed_call_and_a_crossing() { + let kzg = vec![0_u8; 192]; + let kzg_address = mega_evm::kzg_point_evaluation::ADDRESS; + let upstream = || { + DynPrecompile::new(PrecompileId::KzgPointEvaluation, |input| { + let result = revm::precompile::kzg_point_evaluation::run(input.data, input.gas); + Ok(PrecompileOutput::from_eth_result(result, input.reservoir)) + }) + }; + let cap = 50_000; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let allowance = cap - charges_to_the_precompile(kzg.len(), Some(80_000)).total(); + assert!(allowance < 50_000, "the allowance pays neither price"); + for gas_limit in TIERS { + let evm = || { + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(TIMESTAMP, kzg_address, Some(80_000))); + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + }; + let ended = |evm: &MegaEvm| { + let call = evm.inspector().calls.iter().find(|call| call.target == kzg_address); + let call = call.expect("the call ended"); + assert_eq!(call.forward, 80_000); + (call.result, call.precompile_ran) + }; + + let mut unpriced = evm() + .with_dyn_precompiles(HashMap::from_iter([(kzg_address, upstream())])) + .with_inspector(Calls::default()); + let run = run_on(&mut unpriced, tx_with(&kzg, gas_limit)); + let intrinsic = intrinsic_with(&kzg, gas_limit); + assert_caught(&run, intrinsic, allowance, &failed_status_store()); + assert_eq!(ended(&unpriced), (InstructionResult::Revert, true), "the stop, run on the cap"); + + let mut priced = evm().with_inspector(Calls::default()); + revm::handler::EvmTr::all_mut(&mut priced) + .2 + .apply_precompile(&kzg_address, |_| Some(upstream())); + let run = run_on(&mut priced, tx_with(&kzg, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None, "a failed call, no stop"); + let ran_and_failed = (InstructionResult::PrecompileError, true); + assert_eq!(ended(&priced), ran_and_failed, "run on its forward, failed on its input"); + assert_eq!(slot(&run, 0), Some(U256::ZERO), "the call fails and its caller goes on"); + } +} + /// A precompile priced between the allowance and its forward whose input fails a check made after /// its gas check: the BN254 pairing of three pairs and a stray byte, priced 147,000 for its three /// whole pairs, which checks the input's length after its gas. Under a cap of 100,000 it is @@ -1811,38 +1803,34 @@ impl Inspector, EthInterpreter> for AnswersPastThe } } -/// An answer past the allowance is the stop, billed the intrinsic gas alone, whatever state or -/// history gas the answer charged: the answer's spending is the charge that crossed, so none of it -/// is made, and the frame, detained from its start, computed nothing before it. Below the -/// execution cap the state or history gas spills onto regular gas and the stop's revert gives it -/// back; above the cap the reservoir pays it and nothing spills. +/// An inspector's answer is taken as given, as revm's inspected frame start takes it: gas +/// detention holds the engine's answers to the compute limit, and an inspector's answer never +/// reaches the engine's frame start. An answer to a frame detained from its start that spent past +/// the cap, with state or history gas on top, is no stop: the transaction succeeds and is billed +/// what the answer spent, the regular gas on the regular ledger and the state or history gas on +/// its own, below the execution cap where it spills onto regular gas and above it where the +/// reservoir pays it. #[test] -fn test_an_answer_past_the_allowance_with_a_spill_is_billed_nothing_of_it() { +fn test_an_inspectors_answer_to_the_transactions_frame_past_the_cap_is_taken_as_given() { for gas_limit in TIERS { for history in [false, true] { + let case = format!("{gas_limit}, history {history}"); let db = MemoryDatabase::default().account_code(CONTRACT, Bytes::from_static(&[STOP])); - let intrinsic = run_on( + let plain = run_on( &mut MegaEvm::new(context(db.clone())), tx(BENEFICIARY, CONTRACT, gas_limit), ) .outcome - .gas - .regular; + .gas; let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersPastTheCapWithASpill { history }); let run = run_on(&mut evm, tx(BENEFICIARY, CONTRACT, gas_limit)); - assert_eq!(run.outcome.result.output(), Some(&stop_data(CAP)), "{gas_limit} {history}"); - assert_eq!( - run.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit: CAP, - used: 0, - frame_local: false - }), - "{gas_limit}, history {history}" - ); - assert_eq!(run.outcome.gas.regular, intrinsic, "{gas_limit}, history {history}"); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None, "{case}: no stop"); + assert_eq!(run.outcome.gas.regular, plain.regular + CAP + 1, "{case}: regular"); + let (state, kept_history) = if history { (0, 1_000) } else { (1_000, 0) }; + assert_eq!(run.outcome.gas.state, plain.state + state, "{case}: state"); + assert_eq!(run.outcome.gas.history, plain.history + kept_history, "{case}: history"); } } } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index f2aac4aba..1489ee4c9 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1,17 +1,24 @@ -//! The observe-stage-commit layer and the write records it counts. +//! The write records the common execution layer counts, and when it counts them. //! //! A write record is one account or storage write, 40 bytes of data size. The sites: the first //! change of a slot in the transaction (taken back when the slot is written back), a value //! transfer's sender and recipient, a creation's creator nonce and created account, a -//! `SELFDESTRUCT` that moves value to another account, an applied EIP-7702 authority, and the -//! transaction's own value recipient or created account. The sender's own account is part of the -//! transaction body and is not a record. Records are deduplicated per frame and discarded with the -//! frame that fails. +//! `SELFDESTRUCT` that moves value to another account (the account it clears and its beneficiary), +//! an applied EIP-7702 authority, and the transaction's own value recipient or created account. +//! The sender's own account is part of the transaction body and is not a record. +//! +//! An account's record follows the net change of its info within the transaction: a write that +//! makes an unchanged account's nonce, balance or code differ from what the transaction loaded +//! creates the record, a write that returns it to that takes the record back, and a write to an +//! account that already differs adds nothing. A creation's created account follows the same rule: +//! the creation records it when the address was unchanged, and an address the transaction changed +//! before keeps the one record it has. The records a frame made are discarded with the frame that +//! fails; a creator's nonce record is the creating frame's, and survives the creation's failure. //! //! Every value movement also leaves an EIP-7708 transfer log, which is data size and not a record: //! the figures below carry [`TRANSFER_LOG_SIZE`] for each one a transaction keeps. -use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, Log, LogData, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{ @@ -19,44 +26,47 @@ use mega_evm::{ ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, test_utils::{is_transfer_log, BytecodeBuilder, MemoryDatabase}, - LimitUsage, MegaContext, MegaEvm, StagedRecord, TRANSFER_LOG_SIZE, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + LimitUsage, MegaContext, MegaEvm, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, - REVERT, SELFDESTRUCT, SSTORE, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, + JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STOP, + }, + context::ContextTr, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, }, - interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Database, Inspector, }; -use crate::common::{account_state_gas, call, call_with_data, context, create, history, run}; +use crate::common::{ + account_state_gas, call, call_with_data, context, create, deposit, grown, history, run, + value_call_room, +}; const CALLER: Address = address!("0000000000000000000000000000000000100000"); const CALLEE: Address = address!("0000000000000000000000000000000000100001"); const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); -/// Room for the state gas of several new accounts, including in a frame that resumes after a -/// child burned the 63/64 it was forwarded: at least 50,000,000, and 64 times what a value call to -/// a new account costs its caller at the byte prices in effect. -fn gas_limit() -> u64 { - (64 * (account_state_gas() + history(4 * WRITE_RECORD_SIZE) + 50_000)).max(50_000_000) -} - /// The transaction body and nothing else. const fn body_only() -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 } + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } } /// `n` write records on top of the transaction body. const fn records(n: u64) -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, write_records: n } + LimitUsage { + data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, + write_records: n, + state_growth: 0, + } } /// `n` write records and no body: the difference between two transactions that carry the same one. const fn records_only(n: u64) -> LimitUsage { - LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n } + LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n, state_growth: 0 } } fn with_extra(usage: LimitUsage, bytes: u64) -> LimitUsage { @@ -85,21 +95,483 @@ fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) } -/* ---------- value transfers and creations, deduplicated per frame ---------- */ +/* ---------- value transfers and creations: a record per account that changed ---------- */ -/// Two value transfers from one frame record the sender once and each recipient. +/// Two value transfers from one frame record the sender once and each recipient: the first +/// transfer changes the sender's balance, and the second finds it changed already. #[test] fn test_two_value_calls_record_the_sender_once() { let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); - let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run( + funded().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE once, CONTRACT, CONTRACT2, and a transfer log for each transfer" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2), + "CALLEE once, CONTRACT, CONTRACT2, and a transfer log for each transfer; CONTRACT and \ + CONTRACT2 are new" + ); +} + +/// Value transfers to one recipient record it once, and the sender once: the first transfer +/// changes both accounts, and the later ones find them changed. Each transfer still logs. +/// +/// Before the net-change rule a recipient was recorded by every transfer to it — N transfers to +/// one recipient kept N records — and only the sender's record was deduplicated, per frame. +#[test] +fn test_value_calls_to_one_recipient_record_it_once() { + let code = (0..3).fold(BytecodeBuilder::default(), |code, _| { + append_value_call(code, CONTRACT, 1).append(POP) + }); + let (result, usage) = run( + funded().account_code(CALLEE, code.append(STOP).build()), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); + assert!(result.result.is_success()); + assert_eq!( + usage, + grown(with_extra(records(2), 3 * TRANSFER_LOG_SIZE), 1), + "CALLEE once, CONTRACT once, and a transfer log for each transfer; the first transfer \ + creates CONTRACT" + ); +} + +/* ---------- a record follows the net change of its account ---------- */ + +/// `CALLDATASIZE; JUMPI` over `body`, so that a call with empty calldata stops at once: the +/// transaction calls the code with a byte of calldata, and a call back into it carries none. +fn guarded_code(body: BytecodeBuilder) -> Bytes { + BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(5_u8) + .append(JUMPI) + .append(STOP) + .append(JUMPDEST) + .append_many(body.build_vec()) + .build() +} + +/// `CALL(gas=GAS, CALLER, value, [], [])`, leaving the success flag: a transfer of `value` back +/// to whoever called the frame. +fn append_return_to_caller(builder: BytecodeBuilder, value: u8) -> BytecodeBuilder { + builder.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).append(PUSH1).append(value).append_many([ + CALLER_OPCODE, + GAS, + CALL, + ]) +} + +/// Runs the transaction that calls `CALLEE`, holding `callee`, with a byte of calldata, and +/// reports its outcome. +fn run_guarded(callee: Bytes, contract: Bytes) -> mega_evm::MegaTransactionOutcome { + let db = funded().account_code(CALLEE, callee).account_code(CONTRACT, contract); + crate::common::execute( + db, + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), value_call_room()), + ) +} + +/// What a transaction [`run_guarded`] runs keeps beside `usage`: the byte of calldata it carries. +fn guarded(usage: LimitUsage) -> LimitUsage { + with_extra(usage, 1) +} + +/// The history a transaction [`run_guarded`] runs pays for its body, its byte of calldata and +/// `records` records, at the prices in effect. +fn body_and_records(records: u64) -> u64 { + history(TX_BODY_SIZE + 1 + records * WRITE_RECORD_SIZE) +} + +/// One transfer records its sender and its recipient, and logs. +#[test] +fn test_one_transfer_records_its_sender_and_its_recipient() { + let outcome = run_guarded( + guarded_code(append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop()), + Bytes::new(), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.usage, + guarded(grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), + "CALLEE, CONTRACT, a log; CONTRACT, which holds no code, is new" + ); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(2)); + } +} + +/// A transfer and its exact return take both records back: the recipient hands the value back to +/// its caller, so both balances are what the transaction loaded, and neither account keeps a +/// record. The two transfer logs stay, and the history the caller paid for the two records comes +/// back to it once the return that took them back is kept. +#[test] +fn test_a_transfer_and_its_exact_return_take_both_records_back() { + let outcome = run_guarded( + guarded_code(append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop()), + // Returns what it was sent, `CALLVALUE`, to `CALLER`. + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, CALLVALUE, CALLER_OPCODE, GAS, CALL, POP]) + .stop() + .build(), ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.usage, + guarded(with_extra(body_only(), 2 * TRANSFER_LOG_SIZE)), + "no record stands; the two transfer logs do" + ); + assert_eq!(outcome.state[&CALLEE].info.balance, U256::from(10_000_000), "back to its balance"); + assert_eq!(outcome.state[&CONTRACT].info.balance, U256::ZERO); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(0), "the records' history came back"); + } +} + +/// A partial return leaves both accounts changed, so both records stand. +#[test] +fn test_a_partial_return_keeps_both_records() { + let outcome = run_guarded( + guarded_code(append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop()), + append_return_to_caller(BytecodeBuilder::default(), 3).append(POP).stop().build(), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.usage, + guarded(with_extra(records(2), 2 * TRANSFER_LOG_SIZE)), + "CALLEE and CONTRACT still differ from what the transaction loaded" + ); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(2)); + } +} + +/// A child that reverts after writing keeps nothing: a slot it wrote, a transfer it made and +/// the transfer it received go with it, and so does a return of the value it received, which its +/// revert undoes with the receipt. A child whose return alone fails — the call that hands the +/// value back reverts, and the child then succeeds — undoes the take-back and keeps the receipt: +/// both records stand, with the history the caller paid for them, and the child earned no refund +/// for a take-back that did not stand. +#[test] +fn test_a_child_that_reverts_after_writing_keeps_nothing() { + let callee = |returns: u8| { + BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(7_u8) + .append(JUMPI) + // A call back into it, carrying no calldata: refuses or accepts the return. + .append_many(if returns == STOP { + [PUSH0, PUSH0, STOP] + } else { + [PUSH0, PUSH0, REVERT] + }) + .append(JUMPDEST) + .append_many( + append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).build_vec(), + ) + .stop() + .build() + }; + let writes_then_reverts = append_value_call( + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), + CONTRACT2, + 1, + ) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let returns_then_reverts = append_return_to_caller(BytecodeBuilder::default(), 5) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let returns_then_stops = + append_return_to_caller(BytecodeBuilder::default(), 5).append(POP).stop().build(); + for (case, callee, contract, expected, records) in [ + ( + "a slot and a transfer, then a revert", + callee(STOP), + writes_then_reverts, + guarded(body_only()), + 0, + ), + ( + "the value handed back, then a revert", + callee(STOP), + returns_then_reverts, + guarded(body_only()), + 0, + ), + ( + "the value handed back into a call that reverts", + callee(REVERT), + returns_then_stops, + guarded(with_extra(records(2), TRANSFER_LOG_SIZE)), + 2, + ), + ] { + let outcome = run_guarded(callee, contract); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{case}"); + let kept = U256::from(5 * records / 2); + assert_eq!(outcome.state[&CONTRACT].info.balance, kept, "{case}: what CONTRACT keeps"); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(records), "{case}"); + } + } +} + +/// A creation that fails leaves its creator's nonce record on the caller: the bump stands, and +/// the creator's account differs by it. A second failing creation adds nothing, the creator being +/// changed already. +#[test] +fn test_a_creation_that_fails_leaves_the_creators_record_on_the_caller() { + for (creations, case) in [(1, "one failed creation"), (2, "two failed creations")] { + let db = funded().account_code(OUTER_CREATOR, reverting_creations(creations)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, value_call_room())); + assert!(result.result.is_success(), "{case}"); + assert_eq!(usage, records(1), "{case}: the creator's nonce record alone"); + assert_eq!(result.state[&OUTER_CREATOR].info.nonce, creations as u64, "{case}"); + } +} + +/// Nested creations record each account once: the outer creator, the account it creates — whose +/// own creation bumps a nonce the creation already changed — and the account that one creates. +#[test] +fn test_nested_creations_record_each_account_once() { + // Init code that creates an account with empty init code and returns no code. + let inner: Vec = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, CREATE, POP]) + .stop() + .build_vec(); + let len = inner.len() as u64; + let outer = BytecodeBuilder::default() + .mstore(0, &inner) + .push_number(len) + .push_number(0_u64) + .push_number(0_u64) + .append_many([CREATE, POP]) + .stop() + .build(); + let (result, usage) = run( + funded().account_code(CALLEE, outer), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + usage, + grown(records(3), 2), + "CALLEE, the account it created, and the one that created; both created accounts are new" + ); + let created = CALLEE.create(0); + assert_eq!(result.state[&created].info.nonce, 2, "it created one account of its own"); + assert!(result.state.contains_key(&created.create(1))); +} + +/// A value call to the frame's own account moves nothing and records nothing, and neither does a +/// value `CALLCODE`, which moves the value from the calling account to that same account. +/// +/// Before the net-change rule either recorded the calling account once, as the transfer's sender. +#[test] +fn test_a_value_call_to_self_records_nothing() { + assert_eq!(nested_delta(&[SELF_CALLER]), LimitUsage::ZERO, "a CALL to itself"); + + let code = BytecodeBuilder::default().callcode(CONTRACT, U256::from(1)).append(POP).stop(); + let (result, usage) = run( + funded().account_code(CALLEE, code.build()), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(usage, body_only(), "a value CALLCODE"); +} + +/// A transfer to the transaction's sender records nothing for it — validation changed its account +/// already, by its fee and its nonce — and one to a fee account records it, unchanged until +/// execution writes it. The sender of the transfer is recorded either way. +#[test] +fn test_a_transfer_to_the_sender_and_to_a_fee_account() { + for (case, target, expected) in [ + ("the sender", CALLER, with_extra(records(1), TRANSFER_LOG_SIZE)), + ("the block beneficiary", COINBASE, with_extra(records(2), TRANSFER_LOG_SIZE)), + ] { + let code = append_value_call(BytecodeBuilder::default(), target, 1).append(POP).stop(); + let db = funded().account_code(CALLEE, code.build()).account_balance(COINBASE, U256::ONE); + let block = revm::context::BlockEnv { beneficiary: COINBASE, ..crate::common::block() }; + let outcome = MegaEvm::new(context(db).with_block(block)) + .execute_transaction(call(CALLER, CALLEE, U256::ZERO, value_call_room())) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{case}"); + } +} + +/// A `SELFDESTRUCT` that moves value writes two accounts: the beneficiary, recorded when the +/// move changes it, and the destructed account, whose balance the move clears. A fresh +/// beneficiary is recorded; one a transfer already changed is not; and a destructed account whose +/// whole balance the transaction gave it goes back to what was loaded, taking its record back — +/// as does the caller the value goes back to. +#[test] +fn test_a_destruction_to_a_fresh_and_to_a_changed_beneficiary() { + let destruct_to = |code: BytecodeBuilder, beneficiary: Address| { + code.push_address(beneficiary).append(SELFDESTRUCT) + }; + let sends_then_destructs = destruct_to( + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP), + CONTRACT, + ); + for (case, callee, contract, balance, expected) in [ + ( + "to a fresh beneficiary, which the destruction creates", + destruct_to(BytecodeBuilder::default(), CONTRACT).build(), + Bytes::new(), + 5, + guarded(grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), + ), + ( + "to a beneficiary a transfer changed, which the transfer creates", + sends_then_destructs.build(), + Bytes::new(), + 5, + guarded(grown(with_extra(records(2), 2 * TRANSFER_LOG_SIZE), 1)), + ), + ( + "of an account whose balance the transaction gave it, back to the giver", + guarded_code( + append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop(), + ), + BytecodeBuilder::default().append_many([CALLER_OPCODE, SELFDESTRUCT]).build(), + 10_000_000, + guarded(with_extra(body_only(), 2 * TRANSFER_LOG_SIZE)), + ), + ] { + let db = funded() + .account_code(CALLEE, callee) + .account_code(CONTRACT, contract) + .account_balance(CALLEE, U256::from(balance)); + let outcome = crate::common::execute( + db, + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), value_call_room()), + ); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{case}"); + } +} + +/// A creation by `CALLEE`, whose nonce is zero: a `CREATE2` with salt zero, or a `CREATE`. +#[derive(Clone, Copy, Debug)] +enum Creation { + Create2, + Create, +} + +impl Creation { + /// The address a creation of `init_code` lands on. + fn address(self, init_code: &[u8]) -> Address { + match self { + Self::Create2 => CALLEE.create2(B256::ZERO, keccak256(init_code)), + Self::Create => CALLEE.create(0), + } + } + + /// Appends the creation of `init_code`, endowed with `value` wei, and drops its address. + fn append(self, code: BytecodeBuilder, init_code: &[u8], value: u8) -> BytecodeBuilder { + let value = U256::from(value); + match self { + Self::Create2 => code.create2(value, init_code, U256::ZERO), + Self::Create => code.create(value, init_code), + } + .append(POP) + } +} + +/// A creation records the account it creates by the rule every account write follows: when the +/// creation changes an account the transaction had not changed. An address the transaction funded, +/// or a `SELFDESTRUCT` paid, before a creation lands on it is changed already and keeps the one +/// record its first change made, whatever the creation then writes to it, an endowment included. +/// The creator's nonce adds no record either where the transfer that funded the address changed +/// the creator already. +/// +/// The creating opcode charges its caller the created account's history only when the transaction +/// had not changed the address, a `CREATE2`'s as a `CREATE`'s, and the creation's failure gives it +/// back with everything else the creation made: the history the transaction pays is its body's and +/// the records it keeps, at the prices in effect. +/// +/// Before, a creation recorded the account it creates whatever the address held: an address +/// funded then created kept two records, and one paid by a destruction then created kept them with +/// the destructed account's and the creator's. +#[test] +fn test_a_creation_records_its_account_only_when_it_changes_it() { + const DESTRUCTOR: Address = address!("000000000000000000000000000000000000DE57"); + const SUCCEEDS: &[u8] = &[]; + const FAILS: &[u8] = &[PUSH0, PUSH0, REVERT]; + /// What `CALLEE` runs before the creation, given the address X the creation lands on. + type Prelude = fn(BytecodeBuilder, Address) -> BytecodeBuilder; + /// The creation's init code and endowment, if one runs. + type Created = Option<(&'static [u8], u8)>; + let nothing: Prelude = |code, _| code; + let fund: Prelude = |code, x| code.call(x, U256::from(5)).append(POP); + let destruct: Prelude = |code, _| code.call(DESTRUCTOR, U256::ZERO).append(POP); + // (case, what runs before the creation, the creation, the records kept, the transfer logs + // kept, the new accounts kept: X, by the first write that reaches it — a creation onto an + // address the transaction funded adds none) + let rows: [(&str, Prelude, Created, u64, u64, u64); 6] = [ + ("fund X only: CALLEE and X", fund, None, 2, 1, 1), + ("create X only: CALLEE's nonce and X", nothing, Some((SUCCEEDS, 0)), 2, 0, 1), + ("fund X, then create X: CALLEE and X", fund, Some((SUCCEEDS, 0)), 2, 1, 1), + ( + "fund X, then create X with an endowment: CALLEE and X", + fund, + Some((SUCCEEDS, 1)), + 2, + 2, + 1, + ), + ( + "a destruction pays X, then create X: DESTRUCTOR, X and CALLEE's nonce", + destruct, + Some((SUCCEEDS, 0)), + 3, + 1, + 1, + ), + ("fund X, then a creation at X that fails: CALLEE and X", fund, Some((FAILS, 0)), 2, 1, 1), + ]; + for creation in [Creation::Create2, Creation::Create] { + for (case, prelude, created, records_kept, logs, growth) in rows { + let case = format!("{creation:?}, {case}"); + let x = creation.address(created.map_or(SUCCEEDS, |(init, _)| init)); + let mut code = prelude(BytecodeBuilder::default(), x); + if let Some((init, value)) = created { + code = creation.append(code, init, value); + } + let db = funded() + .account_code(CALLEE, code.stop().build()) + .account_code(DESTRUCTOR, BytecodeBuilder::default().selfdestruct(x).build()) + .account_balance(DESTRUCTOR, U256::from(7)); + let outcome = + crate::common::execute(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let deployed = created.is_some_and(|(init, _)| init == SUCCEEDS); + assert_eq!( + outcome.state.get(&x).map(|account| account.info.nonce), + Some(u64::from(deployed)), + "{case}: X is created where the creation succeeds" + ); + assert_eq!( + outcome.usage, + grown(with_extra(records(records_kept), logs * TRANSFER_LOG_SIZE), growth), + "{case}" + ); + if !crate::common::history_rounds() { + assert_eq!( + outcome.gas.history, + history(TX_BODY_SIZE + records_kept * WRITE_RECORD_SIZE), + "{case}: the body and the records kept, and nothing for a record not made" + ); + } + } + } } /// A creation and a value transfer from one frame record the frame's account once. @@ -107,13 +579,16 @@ fn test_two_value_calls_record_the_sender_once() { fn test_create_then_call_record_the_frame_account_once() { let code = append_value_create(BytecodeBuilder::default()).append(POP); let code = append_value_call(code, CONTRACT, 1).append(POP).append(STOP).build(); - let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run( + funded().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE once, the created account, CONTRACT, and a transfer log for each endowment" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2), + "CALLEE once, the created account, CONTRACT, and a transfer log for each endowment; the \ + created account and CONTRACT are new" ); } @@ -122,13 +597,16 @@ fn test_create_then_call_record_the_frame_account_once() { fn test_two_creates_record_the_creator_once() { let code = append_value_create(BytecodeBuilder::default()).append(POP); let code = append_value_create(code).append(POP).append(STOP).build(); - let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run( + funded().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE once, two created accounts, and a transfer log for each endowment" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2), + "CALLEE once, two created accounts, and a transfer log for each endowment; both created \ + accounts are new" ); } @@ -139,7 +617,7 @@ fn test_failed_child_discards_its_transfer_records() { append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); let db = funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success(), "the outer call succeeds although the child halts"); assert_eq!(usage, body_only()); } @@ -164,15 +642,56 @@ fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { .build(); let db = funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(2), TRANSFER_LOG_SIZE), - "CALLEE and CONTRACT2 and the transfer log, from the second transfer" + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "CALLEE and CONTRACT2 and the transfer log, from the second transfer, which creates \ + CONTRACT2" ); } +/// A library a `DELEGATECALL` runs as its caller: a value transfer to [`CONTRACT`], then a revert +/// when `fails`. +fn library_transferring(fails: bool) -> Bytes { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + if fails { + code.append_many([PUSH0, PUSH0, REVERT]).build() + } else { + code.append(STOP).build() + } +} + +/// A `DELEGATECALL` runs as its caller, so a value transfer it makes records its caller's account, +/// and that record follows the delegate's frame: kept and handed to the caller when the delegate +/// succeeds, so a later transfer from the caller does not record it again; taken back with the +/// delegate's failure, so the later transfer records it. +#[test] +fn test_a_delegates_record_of_its_callers_account_follows_the_delegate() { + const LIBRARY: Address = address!("0000000000000000000000000000000000100004"); + for fails in [false, true] { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(LIBRARY) + .append_many([GAS, DELEGATECALL, POP]); + let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let db = + funded().account_code(CALLEE, code).account_code(LIBRARY, library_transferring(fails)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(result.result.is_success(), "the caller succeeds"); + let expected = if fails { + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1) + } else { + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2) + }; + assert_eq!( + usage, expected, + "CALLEE once, then CONTRACT2, and CONTRACT unless it failed; each recipient is new" + ); + } +} + const OUTER_CREATOR: Address = address!("000000000000000000000000000000000000C0FF"); /// `PUSH5 ; PUSH1 0; MSTORE; (PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP) x @@ -191,7 +710,7 @@ fn reverting_creations(n: usize) -> Bytes { #[test] fn test_reverted_then_retried_create_records_the_creator_once() { let db = funded().account_code(OUTER_CREATOR, reverting_creations(2)); - let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, records(1)); } @@ -208,7 +727,7 @@ fn test_creation_without_funds_records_nothing() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, body_only()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); @@ -220,8 +739,8 @@ const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004" fn value_delta(to: Address) -> LimitUsage { let db = || MemoryDatabase::default().account_balance(A, U256::from(1_000_000)); - let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), gas_limit())); - let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, gas_limit())); + let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), value_call_room())); + let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, value_call_room())); assert!(with_value.result.is_success() && zero_value.result.is_success()); usage_value.saturating_sub(usage_zero) } @@ -235,7 +754,11 @@ fn test_top_level_self_transfer_no_double_count() { /// A top-level transfer to another account records the recipient. #[test] fn test_top_level_transfer_counts_the_recipient() { - assert_eq!(value_delta(B), with_extra(records_only(1), TRANSFER_LOG_SIZE), "and its log"); + assert_eq!( + value_delta(B), + grown(with_extra(records_only(1), TRANSFER_LOG_SIZE), 1), + "and its log; the value creates B" + ); } /// `CALLDATASIZE; JUMPI` to a body that calls `targets` with `value`, so an inner call with empty @@ -266,27 +789,21 @@ fn nested_delta(targets: &[Address]) -> LimitUsage { .account_balance(SELF_CALLER, U256::from(1_000_000)) .account_code(SELF_CALLER, self_calling_code(targets, value)); let (result, usage) = - run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), gas_limit())); + run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), value_call_room())); assert!(result.result.is_success()); usage }; usage(1).saturating_sub(usage(0)) } -/// A nested transfer to the frame's own account is one account write. -#[test] -fn test_nested_self_call_with_value_counts_once() { - assert_eq!(nested_delta(&[SELF_CALLER]), records_only(1)); -} - /// After a transfer to another account recorded the frame's account, a transfer to itself adds /// nothing. #[test] fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { assert_eq!( nested_delta(&[B, SELF_CALLER]), - with_extra(records_only(2), TRANSFER_LOG_SIZE), - "the transfer to B and its log" + grown(with_extra(records_only(2), TRANSFER_LOG_SIZE), 1), + "the transfer to B and its log; the transfer creates B" ); } @@ -296,9 +813,10 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { #[test] fn test_sstore_first_change_records_and_write_back_refunds() { type Writes = &'static [(u64, u64)]; + // (writes, the slot's original value, what is kept: a slot written from zero is new) let cases: [(Writes, u64, LimitUsage); 4] = [ - (&[(0, 1)], 0, records(1)), - (&[(0, 1), (0, 2)], 0, records(1)), + (&[(0, 1)], 0, grown(records(1), 1)), + (&[(0, 1), (0, 2)], 0, grown(records(1), 1)), (&[(0, 1), (0, 0)], 0, body_only()), (&[(0, 0)], 5, records(1)), ]; @@ -310,7 +828,7 @@ fn test_sstore_first_change_records_and_write_back_refunds() { let db = MemoryDatabase::default() .account_code(CALLEE, code.stop().build()) .account_storage(CALLEE, U256::ZERO, U256::from(original)); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, expected, "writes {writes:?} over original {original}"); } @@ -323,7 +841,8 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); let failing_child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).append(INVALID).build(); - for (code, expected) in [(child, body_only()), (failing_child, records(1))] { + // The write-back takes back the caller's new slot with its record, and dies with the child. + for (code, expected) in [(child, body_only()), (failing_child, grown(records(1), 1))] { // CALLEE writes slot 0, then DELEGATECALLs CONTRACT, which writes it back in CALLEE's // storage. let parent = BytecodeBuilder::default() @@ -337,31 +856,36 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { .build(); let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, expected); } } -/// `SELFDESTRUCT` records the beneficiary only when value moves to another account than the -/// destructed one and the sender, whose account the transaction body counts. A move to the sender -/// still leaves its transfer log; a destruction to itself burns the balance and leaves none. +/// `SELFDESTRUCT` records the accounts the move changes: the destructed account, whose balance it +/// clears, and the beneficiary, unless that is the sender, whose account validation changed. A +/// move to the sender still leaves its transfer log; a destruction to itself, of an account the +/// transaction did not create, moves nothing and leaves none, and so does one of an account with +/// no balance. +/// +/// Before the net-change rule the destructed account was never recorded, only the beneficiary. #[test] fn test_selfdestruct_records_the_beneficiary_when_value_moves() { let destruct_to = |beneficiary: Address| { BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() }; let cases = [ - (U256::from(5), CONTRACT, with_extra(records(1), TRANSFER_LOG_SIZE)), + // CONTRACT does not exist: the move creates it. + (U256::from(5), CONTRACT, grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), (U256::from(5), CALLEE, body_only()), - (U256::from(5), CALLER, with_extra(body_only(), TRANSFER_LOG_SIZE)), + (U256::from(5), CALLER, with_extra(records(1), TRANSFER_LOG_SIZE)), (U256::ZERO, CONTRACT, body_only()), ]; for (balance, beneficiary, expected) in cases { let db = MemoryDatabase::default() .account_code(CALLEE, destruct_to(beneficiary)) .account_balance(CALLEE, balance); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, expected, "balance {balance}, beneficiary {beneficiary}"); } @@ -371,13 +895,17 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { #[test] fn test_top_level_create_records_the_created_account() { // `STOP` is one byte of init code and deposits nothing. - let (result, usage) = - run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[STOP]), gas_limit())); + let (result, usage) = run( + MemoryDatabase::default(), + create(CALLER, Bytes::from_static(&[STOP]), value_call_room()), + ); assert!(result.result.is_success()); - assert_eq!(usage, with_extra(records(1), 1)); + assert_eq!(usage, grown(with_extra(records(1), 1), 1), "the created account is new"); - let (result, usage) = - run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[INVALID]), gas_limit())); + let (result, usage) = run( + MemoryDatabase::default(), + create(CALLER, Bytes::from_static(&[INVALID]), value_call_room()), + ); assert!(!result.result.is_success()); assert_eq!(usage, with_extra(body_only(), 1)); } @@ -405,7 +933,8 @@ enum FeeRowPath { /// /// Every row runs from a contract frame, `CALLEE`, which the transaction calls without value and /// which holds ten million wei. A value transfer records its sender, `CALLEE`, and its recipient; -/// a `SELFDESTRUCT` of an account the transaction did not create records its beneficiary alone. +/// a `SELFDESTRUCT` of an account the transaction did not create records the account it clears, +/// `CALLEE`, and its beneficiary. /// Each row moves value to another account, so each keeps one EIP-7708 transfer log, which is /// data size and neither a record nor history. The fee accounts exist before the transaction, so /// no row adds state; the transaction pays a fee at a gas price of ten over a base fee of one, so @@ -426,11 +955,11 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { // (row, the transaction's sender, the account execution writes, the path, the records kept) let rows: [(&str, Address, Address, FeeRowPath, u64); 12] = [ ("the block beneficiary, by a value transfer", CALLER, COINBASE, ValueTransfer, 2), - ("the block beneficiary, by a SELFDESTRUCT", CALLER, COINBASE, SelfDestruct, 1), + ("the block beneficiary, by a SELFDESTRUCT", CALLER, COINBASE, SelfDestruct, 2), ("the L1 fee vault, by a value transfer", CALLER, L1_FEE_RECIPIENT, ValueTransfer, 2), - ("the L1 fee vault, by a SELFDESTRUCT", CALLER, L1_FEE_RECIPIENT, SelfDestruct, 1), + ("the L1 fee vault, by a SELFDESTRUCT", CALLER, L1_FEE_RECIPIENT, SelfDestruct, 2), ("the base fee vault, by a value transfer", CALLER, BASE_FEE_RECIPIENT, ValueTransfer, 2), - ("the base fee vault, by a SELFDESTRUCT", CALLER, BASE_FEE_RECIPIENT, SelfDestruct, 1), + ("the base fee vault, by a SELFDESTRUCT", CALLER, BASE_FEE_RECIPIENT, SelfDestruct, 2), ( "the operator fee vault, by a value transfer", CALLER, @@ -443,10 +972,10 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { CALLER, OPERATOR_FEE_RECIPIENT, SelfDestruct, - 1, + 2, ), ("the sender, by a value transfer", CALLER, CALLER, ValueTransfer, 1), - ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 0), + ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 1), ( "the block beneficiary that is the sender, by a value transfer", COINBASE, @@ -459,7 +988,7 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { COINBASE, COINBASE, SelfDestruct, - 0, + 1, ), ]; for (row, sender, target, path, records) in rows { @@ -478,7 +1007,7 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { db = db.account_balance(account, U256::from(1)); } } - let mut tx = call(sender, CALLEE, U256::ZERO, gas_limit()); + let mut tx = call(sender, CALLEE, U256::ZERO, value_call_room()); tx.0.base.gas_price = 10; let block = revm::context::BlockEnv { beneficiary: COINBASE, basefee: 1, ..crate::common::block() }; @@ -528,26 +1057,24 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { /// Records, after each opcode, what the layer holds. #[derive(Default)] struct LayerProbe { - /// `(opcode, staged record left, usage)` after each opcode. - steps: Vec<(u8, bool, LimitUsage)>, + /// `(opcode, usage)` after each opcode. + steps: Vec<(u8, LimitUsage)>, opcode: u8, - /// Stages a log through the Host before every `SSTORE`, as a stale record. - stage_before_sstore: bool, + /// Appends a log through the Host before every `SSTORE`, as a tool's write. + log_before_sstore: bool, } impl Inspector, EthInterpreter> for LayerProbe { fn step(&mut self, interp: &mut Interpreter, context: &mut MegaContext) { self.opcode = interp.bytecode.opcode(); - if self.stage_before_sstore && self.opcode == SSTORE { + if self.log_before_sstore && self.opcode == SSTORE { + let before = context.limit_usage(); let log = Log { address: CALLEE, data: LogData::new(vec![B256::ZERO], Bytes::new()).unwrap(), }; revm::context_interface::Host::log(context, log); - assert!(matches!( - context.additional_limit().staged_record(), - Some(StagedRecord::Log { .. }) - )); + assert_eq!(context.limit_usage(), before, "a tool's log counts nothing"); } } @@ -556,42 +1083,34 @@ impl Inspector, EthInterpreter> for LayerProbe { _interp: &mut Interpreter, context: &mut MegaContext, ) { - let layer = context.additional_limit(); - self.steps.push((self.opcode, layer.staged_record().is_some(), layer.usage())); + self.steps.push((self.opcode, context.limit_usage())); } } -fn probe( - db: MemoryDatabase, - gas_limit: u64, - stage_before_sstore: bool, -) -> Vec<(u8, bool, LimitUsage)> { +fn probe(db: MemoryDatabase, gas_limit: u64, log_before_sstore: bool) -> Vec<(u8, LimitUsage)> { let mut evm = MegaEvm::new(context(db)) - .with_inspector(LayerProbe { stage_before_sstore, ..Default::default() }); + .with_inspector(LayerProbe { log_before_sstore, ..Default::default() }); alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); evm.inspector().steps.clone() } -fn after_sstore(steps: &[(u8, bool, LimitUsage)]) -> (bool, LimitUsage) { - let (_, staged, usage) = steps.iter().find(|(op, ..)| *op == SSTORE).copied().unwrap(); - (staged, usage) +fn after_sstore(steps: &[(u8, LimitUsage)]) -> LimitUsage { + steps.iter().find(|(op, _)| *op == SSTORE).map(|(_, usage)| *usage).unwrap() } -/// A completed `SSTORE` commits its record: nothing is left staged and the record is counted by -/// the time the opcode ends. +/// A completed `SSTORE` commits its record by the time the opcode ends. #[test] fn test_completed_sstore_commits_its_record() { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), gas_limit(), false); - let (staged, usage) = after_sstore(&steps); - assert!(!staged); - assert_eq!(usage, records(1)); + let steps = + probe(MemoryDatabase::default().account_code(CALLEE, code), value_call_room(), false); + assert_eq!(after_sstore(&steps), grown(records(1), 1), "a new slot"); } -/// An `SSTORE` that runs out of gas after its Host call wrote the slot discards the staged -/// record: the Host observed the write, the failure takes it back, and nothing is counted. +/// An `SSTORE` that runs out of gas after its Host call wrote the slot counts nothing: the +/// failure takes the write back, and revm offers the completed-write hook nothing. #[test] -fn test_sstore_out_of_gas_after_the_write_discards_the_record() { +fn test_sstore_out_of_gas_after_the_write_counts_nothing() { // CALLEE calls CONTRACT with 5,000 gas: past the EIP-2200 stipend check, so the Host call // writes the slot, but short of the 22,100 a cold first write charges after it. let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); @@ -603,21 +1122,22 @@ fn test_sstore_out_of_gas_after_the_write_discards_the_record() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, child); - let steps = probe(db, gas_limit(), false); - let (staged, usage) = after_sstore(&steps); - assert!(!staged, "the record is discarded, not left for the next opcode"); - assert_eq!(usage, body_only(), "a failed opcode's write is not counted"); + let steps = probe(db, value_call_room(), false); + assert_eq!(after_sstore(&steps), body_only(), "a failed opcode's write is not counted"); } -/// A record staged outside an opcode's wrapper is discarded when the next wrapper starts, so it -/// is never committed for that opcode. +/// A log a tool appends through the Host, outside an opcode — here an inspector's, in its `step` +/// before an `SSTORE` — counts nothing, and the `SSTORE` that follows counts its own record alone. #[test] -fn test_wrapper_discards_a_stale_record_on_entry() { +fn test_a_tools_log_in_step_counts_nothing() { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), gas_limit(), true); - let (staged, usage) = after_sstore(&steps); - assert!(!staged); - assert_eq!(usage, records(1), "the SSTORE's record, and not the stale log's bytes"); + let steps = + probe(MemoryDatabase::default().account_code(CALLEE, code), value_call_room(), true); + assert_eq!( + after_sstore(&steps), + grown(records(1), 1), + "the SSTORE's record and its new slot, and not the tool's log" + ); } /* ---------- applied EIP-7702 authorities ---------- */ @@ -637,7 +1157,7 @@ fn authorizing_call( CALLER, to, U256::from(value), - gas_limit(), + value_call_room(), DELEGATE, authorizations, ) @@ -653,8 +1173,9 @@ fn test_applied_authorities_record_once_each() { authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0), (AUTHORITY_2, 0), (AUTHORITY_1, 1)]), ); assert!(result.result.is_success(), "{:?}", result.result); - // Three authorization tuples travel in the body; two distinct authorities are applied. - assert_eq!(usage, with_extra(records(2), 3 * mega_evm::AUTHORIZATION_SIZE)); + // Three authorization tuples travel in the body; two distinct authorities are applied, and + // the first authorization of each creates it. + assert_eq!(usage, grown(with_extra(records(2), 3 * mega_evm::AUTHORIZATION_SIZE), 2)); let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 7)])); assert!(result.result.is_success()); @@ -674,8 +1195,9 @@ fn test_value_to_an_applied_authority_records_it_once() { assert!(result.result.is_success(), "{:?}", result.result); assert_eq!( usage, - with_extra(records(1), mega_evm::AUTHORIZATION_SIZE + TRANSFER_LOG_SIZE), - "the authority, its authorization and the transfer log" + grown(with_extra(records(1), mega_evm::AUTHORIZATION_SIZE + TRANSFER_LOG_SIZE), 1), + "the authority, its authorization and the transfer log; the authorization creates the \ + authority, and the value finds it" ); // And is charged for once: the transaction's own frame writes no recipient, because the @@ -726,13 +1248,13 @@ fn test_frames_running_as_the_sender_do_not_record_it() { let account = db.load_account(CALLER).unwrap(); account.info.code_hash = delegation.hash_slow(); account.info.code = Some(delegation); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "the transfer happened"); assert_eq!( usage, - with_extra(records(1), TRANSFER_LOG_SIZE), - "CONTRACT2 and the transfer log only; the sender is part of the body" + grown(with_extra(records(1), TRANSFER_LOG_SIZE), 1), + "CONTRACT2 and the transfer log only; the sender is part of the body; CONTRACT2 is new" ); } @@ -751,18 +1273,19 @@ impl Inspector, EthInterpreter> for OverfundCreati } /// A creation that fails before bumping the creator's nonce (here, an endowment an inspector -/// raised past the creator's balance) takes its creator record back with it. +/// raised past the creator's balance) records nothing: the creator's record is counted from the +/// bump, and there is none. #[test] fn test_creation_failing_before_the_nonce_bump_records_nothing() { let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, code))) .with_inspector(OverfundCreations); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, value_call_room())) .unwrap(); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); - assert_eq!(evm.ctx().additional_limit().usage(), body_only()); + assert_eq!(evm.ctx().limit_usage(), body_only()); } /// A creation that collides with an existing account fails after bumping the creator's nonce, so @@ -771,7 +1294,7 @@ fn test_creation_failing_before_the_nonce_bump_records_nothing() { fn test_colliding_creation_keeps_the_creator_record() { let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); let db = funded().account_code(CALLEE, code).account_nonce(CALLEE.create(0), 1); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 1, "the collision comes after the bump"); assert_eq!(usage, records(1), "the creator's nonce only"); @@ -781,8 +1304,9 @@ fn test_colliding_creation_keeps_the_creator_record() { /// is bumped and its record kept, the created account's record goes. #[test] fn test_creation_stopped_at_init_bumps_the_creator_nonce() { - // CALLEE writes a slot (40 bytes of its 100-byte budget), then creates: the creation's two - // records (80 bytes) exceed the 60 bytes left to it. CALLEE stores the created address. + // CALLEE writes a slot (40 bytes of its 80-byte budget), then creates: the creation's share + // of the 40 bytes left, 39, is one short of the created account's record. CALLEE keeps its + // nonce record in those 40 once the creation returned, and stores the created address. let code = BytecodeBuilder::default() .sstore(U256::from(1), U256::from(1)) .append_many([PUSH0, PUSH0, PUSH0]) @@ -792,15 +1316,20 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, code); - let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(80); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, value_call_room())) .unwrap(); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CALLEE].info.nonce, 1, "the stopped creation bumped the nonce"); assert_eq!(result.state[&CALLEE].storage[&U256::ZERO].present_value(), U256::ZERO, "it failed"); - assert_eq!(evm.ctx().additional_limit().usage(), records(2), "slot 1 and the creator's nonce"); + assert_eq!( + evm.ctx().limit_usage(), + grown(records(2), 1), + "slot 1 and the creator's nonce; slot 1 is new, and the failed creation's zero address \ + leaves slot 0 empty" + ); } /// A transaction is held at validation to its body and a record for every entry of its @@ -826,7 +1355,11 @@ fn test_authority_records_are_held_to_the_limit_at_validation() { let largest = TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE; let at_the_cap = with_cap(largest, &once).expect("a transaction at the limit is valid"); assert!(at_the_cap.result.is_success(), "{:?}", at_the_cap.result); - assert_eq!(at_the_cap.usage, with_extra(records(1), tuple)); + assert_eq!( + at_the_cap.usage, + grown(with_extra(records(1), tuple), 1), + "the authority, which the authorization creates" + ); let code = at_the_cap.state[&AUTHORITY_1].info.code.as_ref(); assert_eq!(code.and_then(|code| code.eip7702_address()), Some(DELEGATE), "it is applied"); assert!(refused(largest - 1, &once), "one byte of limit less rejects it"); @@ -836,7 +1369,11 @@ fn test_authority_records_are_held_to_the_limit_at_validation() { assert!(refused(bound - 1, &twice), "two entries are held to two records"); let ran = with_cap(bound, &twice).expect("valid at two records"); assert!(ran.result.is_success(), "{:?}", ran.result); - assert_eq!(ran.usage, with_extra(records(1), 2 * tuple), "the one authority makes one record"); + assert_eq!( + ran.usage, + grown(with_extra(records(1), 2 * tuple), 1), + "the one authority makes one record, and is new once" + ); } /// A funded caller's database, for the runtime out-of-gas tests. @@ -924,12 +1461,137 @@ fn test_an_inspected_runtime_out_of_gas_unwinds_as_a_plain_one() { assert_eq!(inspected.state, plain.state); } -/* ---------- which frame's account counts as recorded ---------- */ +/* ---------- what a transaction changed before its own frame ---------- */ + +/// The accounts the transaction changed from what it loaded as its own frame starts, each with +/// whether its nonce is among what changed: what the journal holds at the first frame's `call` or +/// `create` hook. +#[derive(Default)] +struct ChangedBeforeTheFirstFrame(Option>); + +impl ChangedBeforeTheFirstFrame { + fn note(&mut self, context: &MegaContext) { + if self.0.is_some() { + return; + } + let journal = context.journal_ref(); + let mut changed: Vec<(Address, bool)> = journal + .state + .iter() + .filter(|(_, account)| account.transaction_id == journal.transaction_id) + .filter_map(|(address, account)| { + let (now, loaded) = (&account.info, account.original_info()); + let nonce = now.nonce != loaded.nonce; + (nonce || now.balance != loaded.balance || now.code_hash != loaded.code_hash) + .then_some((*address, nonce)) + }) + .collect(); + changed.sort_unstable(); + self.0 = Some(changed); + } +} + +impl Inspector, EthInterpreter> for ChangedBeforeTheFirstFrame { + fn call(&mut self, context: &mut MegaContext, _: &mut CallInputs) -> Option { + self.note(context); + None + } + + fn create( + &mut self, + context: &mut MegaContext, + _: &mut CreateInputs, + ) -> Option { + self.note(context); + None + } +} + +/// Before its own frame a transaction has changed no account but its sender and the EIP-7702 +/// authorities it applied, whose records the body and the authorities' count hold, and an account +/// it changed there differs by its nonce — but for a creation's sender, whose own creation bumps +/// it later, and which no value goes to. So the transaction's own value, which the history charged +/// before execution prices as the records it makes, takes no record back: its recipient is an +/// account the transaction had not changed, an authority whose nonce no transfer returns, or the +/// sender itself, to which nothing moves. The first frame's start builds on that: it carries no +/// credit for a record taken back; this holds it for every transaction shape, in the release build +/// too. +#[test] +fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authorities() { + let sender_funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let mut minted = deposit(call(CALLER, CONTRACT, U256::from(1), value_call_room())); + minted.0.deposit.mint = Some(5); + let one = U256::from(1); + for (case, db, tx, authorities, records_kept) in [ + ( + "a value call", + sender_funded(), + call(CALLER, CONTRACT, one, value_call_room()), + vec![], + 1, + ), + ( + "a value call to the sender", + sender_funded(), + call(CALLER, CALLER, one, value_call_room()), + vec![], + 0, + ), + ( + "a creation", + sender_funded(), + create(CALLER, Bytes::from_static(&[STOP]), value_call_room()), + vec![], + 1, + ), + ("a deposit that mints and moves value", MemoryDatabase::default(), minted, vec![], 1), + ( + "a value call to the authority it applies", + sender_funded(), + authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)]), + vec![AUTHORITY_1], + 1, + ), + ( + "a value call past the authority it applies", + sender_funded(), + authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)]), + vec![AUTHORITY_1], + 2, + ), + ] { + let recipient = tx.0.base.kind.to().copied(); + let mut evm = + MegaEvm::new(context(db)).with_inspector(ChangedBeforeTheFirstFrame::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage.write_records, records_kept, "{case}"); + let changed = evm.inspector().0.clone().expect("the first frame started"); + for (account, by_nonce) in &changed { + assert!( + *account == CALLER || authorities.contains(account), + "{case}: {account} changed before the first frame: {changed:?}" + ); + if Some(*account) == recipient && *account != CALLER { + assert!(by_nonce, "{case}: the recipient {account} differs by its nonce"); + } + } + assert!( + authorities.iter().all(|authority| changed.contains(&(*authority, true))), + "{case}: every applied authority is changed, by its nonce: {changed:?}" + ); + } +} + +/* ---------- whose account a frame's writes find changed ---------- */ const D: Address = address!("00000000000000000000000000000000000000D1"); -/// A child that received value records its own account then: its own value transfers do not -/// record it again. +/// A child that received value had its own account recorded by the transfer; passing all of it +/// on returns the account to what the transaction loaded and takes that record back, so what +/// stands is the sender's and the last recipient's. +/// +/// Before the net-change rule the child's account stayed recorded once it was. #[test] fn test_value_receiving_child_records_itself_once() { let a = @@ -939,18 +1601,20 @@ fn test_value_receiving_child_records_itself_once() { .append(STOP) .build(); let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(result.state[&CONTRACT].info.balance, U256::ZERO, "as it was loaded"); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE, CONTRACT once, CONTRACT2, and two transfer logs" + grown(with_extra(records(2), 2 * TRANSFER_LOG_SIZE), 1), + "CALLEE, CONTRACT2, and two transfer logs: CONTRACT passed on what it received; CONTRACT2 \ + is new" ); } -/// A child that received nothing starts with its own account unrecorded, whatever its caller's -/// state. +/// A child that received nothing has its own account unchanged, whatever its caller's state: its +/// first value transfer records it. #[test] fn test_zero_value_child_starts_unrecorded() { let a = BytecodeBuilder::default() @@ -969,12 +1633,12 @@ fn test_zero_value_child_starts_unrecorded() { .account_code(CALLEE, a) .account_code(CONTRACT, b) .account_balance(CONTRACT, U256::from(5)); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), value_call_room())); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE as the recipient, CONTRACT, CONTRACT2, and two transfer logs" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 1), + "CALLEE as the recipient, CONTRACT, CONTRACT2, and two transfer logs; CONTRACT2 is new" ); } @@ -990,7 +1654,11 @@ fn delegate_to_d() -> Bytes { .build() } -/// A `DELEGATECALL` runs as its caller's account, and inherits whether that account is recorded. +/// A `DELEGATECALL` runs as its caller's account, so a transfer it makes writes that account as +/// the caller left it: changed by the value it received, and returned to what the transaction +/// loaded when the delegate passes that value on, which takes the caller's record back. +/// +/// Before the net-change rule the caller's account stayed recorded once it was. #[test] fn test_delegatecall_child_inherits_the_frame_account_record() { let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) @@ -998,18 +1666,18 @@ fn test_delegatecall_child_inherits_the_frame_account_record() { .append(STOP) .build(); let db = funded().account_code(CALLEE, delegate_to_d()).account_code(D, d); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), value_call_room())); assert!(result.result.is_success()); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "CALLEE's value moved"); assert_eq!( usage, - with_extra(records(2), 2 * TRANSFER_LOG_SIZE), - "CALLEE as the recipient, CONTRACT2, and two transfer logs" + grown(with_extra(records(1), 2 * TRANSFER_LOG_SIZE), 1), + "CONTRACT2 and two transfer logs: CALLEE passed on the value it received; CONTRACT2 is new" ); } -/// A created frame's account is recorded by the creation; a `DELEGATECALL` from its init code -/// inherits that. +/// A created frame's account is recorded by the creation; a transfer a `DELEGATECALL` from its +/// init code makes finds it changed. #[test] fn test_created_frame_delegatecall_inherits_the_created_account_record() { let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) @@ -1018,7 +1686,7 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { .build(); let db = funded().account_code(D, d); let tx = { - let mut tx = create(CALLER, delegate_to_d(), gas_limit()); + let mut tx = create(CALLER, delegate_to_d(), value_call_room()); tx.0.base.value = U256::from(5); tx }; @@ -1028,12 +1696,13 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { // The init code travels in the body. `STOP` deploys nothing. assert_eq!( usage, - with_extra(records(2), delegate_to_d().len() as u64 + 2 * TRANSFER_LOG_SIZE), - "the created account, CONTRACT2, and two transfer logs" + grown(with_extra(records(2), delegate_to_d().len() as u64 + 2 * TRANSFER_LOG_SIZE), 2), + "the created account, CONTRACT2, and two transfer logs; both are new" ); } -/// A transaction calling its own sender (delegated) counts the sender as recorded from the start. +/// A transaction calling its own sender (delegated) finds the sender's account changed from the +/// start, by its fee and its nonce: a transfer from it records the recipient alone. #[test] fn test_top_level_self_call_counts_the_sender_as_recorded() { let sender_code = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) @@ -1045,10 +1714,14 @@ fn test_top_level_self_call_counts_the_sender_as_recorded() { let account = db.load_account(CALLER).unwrap(); account.info.code_hash = delegation.hash_slow(); account.info.code = Some(delegation); - let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, value_call_room())); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - assert_eq!(usage, with_extra(records(1), TRANSFER_LOG_SIZE), "CONTRACT2 and its log only"); + assert_eq!( + usage, + grown(with_extra(records(1), TRANSFER_LOG_SIZE), 1), + "CONTRACT2 and its log only; CONTRACT2 is new" + ); } /// Answers every call to `CONTRACT` itself. @@ -1073,10 +1746,10 @@ impl Inspector, EthInterpreter> for AnswerContract } } -/// A call an inspector answers gets an empty lane of its own, so its caller's lane is intact for -/// what the caller does next. +/// A call an inspector answers counts nothing of its own, so what its caller does next is counted +/// as it is without the call. #[test] -fn test_inspector_answered_call_keeps_the_caller_lane() { +fn test_inspector_answered_call_counts_nothing_of_its_own() { let a = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(CONTRACT) @@ -1087,13 +1760,13 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, a))).with_inspector(AnswerContract); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, value_call_room())) .unwrap(); assert!(result.result.is_success()); assert_eq!( - evm.ctx().additional_limit().usage(), - with_extra(records(2), TRANSFER_LOG_SIZE), - "CALLEE and CONTRACT2, and the transfer log" + evm.ctx().limit_usage(), + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "CALLEE and CONTRACT2, and the transfer log; CONTRACT2 is new" ); } @@ -1160,7 +1833,7 @@ fn paired_corpus() -> Vec { beneficiary: Address::ZERO, }; let to_callee = |code: Bytes| funded().account_code(CALLEE, code); - let plain = || call(CALLER, CALLEE, U256::ZERO, gas_limit()); + let plain = || call(CALLER, CALLEE, U256::ZERO, value_call_room()); let calling = |target, value| { append_value_call(BytecodeBuilder::default(), target, value) .append(POP) @@ -1198,13 +1871,13 @@ fn paired_corpus() -> Vec { 0, 0, ), - // Its sender is its recipient: one account, one record, and no transfer log. + // Its sender is its recipient: nothing moves, no record, and no transfer log. case( "a value call to the calling account itself", to_callee(self_calling_code(&[CALLEE], 1)), - call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), gas_limit()), + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), value_call_room()), + 0, 0, - 1, ), case( "a log over one word", @@ -1240,10 +1913,11 @@ fn paired_corpus() -> Vec { case( "a creation whose init code reverts", funded().account_code(OUTER_CREATOR, reverting_creations(1)), - call(CALLER, OUTER_CREATOR, U256::ZERO, gas_limit()), + call(CALLER, OUTER_CREATOR, U256::ZERO, value_call_room()), 0, 1, ), + // The account it clears and its beneficiary. Paired { transfer_logs: 1, ..case( @@ -1254,7 +1928,7 @@ fn paired_corpus() -> Vec { .account_balance(CALLEE, U256::from(1)), plain(), 0, - 1, + 2, ) }, case( @@ -1269,7 +1943,7 @@ fn paired_corpus() -> Vec { case( "a transaction carrying calldata", to_callee(Bytes::new()), - call_with_data(CALLER, CALLEE, Bytes::from(vec![7u8; 100]), gas_limit()), + call_with_data(CALLER, CALLEE, Bytes::from(vec![7u8; 100]), value_call_room()), 0, 0, ), @@ -1278,7 +1952,7 @@ fn paired_corpus() -> Vec { ..case( "a value transaction", funded(), - call(CALLER, CONTRACT, U256::from(1), gas_limit()), + call(CALLER, CONTRACT, U256::from(1), value_call_room()), 0, 1, ) @@ -1286,22 +1960,28 @@ fn paired_corpus() -> Vec { case( "a value transaction the recipient reverts", funded().account_code(CONTRACT, reverting), - call(CALLER, CONTRACT, U256::from(1), gas_limit()), + call(CALLER, CONTRACT, U256::from(1), value_call_room()), + 0, 0, + ), + case( + "a creation transaction", + funded(), + create(CALLER, Bytes::new(), value_call_room()), 0, + 1, ), - case("a creation transaction", funded(), create(CALLER, Bytes::new(), gas_limit()), 0, 1), case( "a creation that deploys code", funded(), - create(CALLER, constructor_returning(32), gas_limit()), + create(CALLER, constructor_returning(32), value_call_room()), 32, 1, ), case( "a creation whose revert data is not deployed code", funded(), - create(CALLER, reverting_with(10), gas_limit()), + create(CALLER, reverting_with(10), value_call_room()), 0, 0, ), @@ -1317,7 +1997,7 @@ fn paired_corpus() -> Vec { CALLER, ORACLE_CONTRACT_ADDRESS, send_hint(b"a hint the transaction pays data size for"), - gas_limit(), + value_call_room(), ), 0, 0, @@ -1332,7 +2012,7 @@ fn paired_corpus() -> Vec { { // A fee the beneficiary is actually credited, so the account the transfer // records is one the body's five already bound. - let mut tx = call(CALLER, CONTRACT, U256::from(1), gas_limit()); + let mut tx = call(CALLER, CONTRACT, U256::from(1), value_call_room()); tx.0.base.gas_price = 10; tx }, @@ -1409,14 +2089,12 @@ fn test_every_kept_write_pays_one_record_of_history() { } } -/// A value call an inspector answers makes none of the writes its caller paid for, so all of that -/// history comes back — whatever the inspector answered with. -/// -/// A frame answered without running is the one case where a *successful* result must still give -/// the caller its charge back: the records were never made. An interceptor's refusal and the -/// depth guard both fail, so only an inspector reaches this. +/// A value call an inspector answers makes none of the writes its caller paid for, and counts none. +/// The answer is taken as given, as revm takes it: it carries no start charge for revm to give +/// back, so the history its caller paid at its `CALL` for the records the start would make stays +/// paid, as for the call that runs, while the transaction counts its body alone. #[test] -fn test_an_inspector_answered_value_call_gives_its_history_back() { +fn test_an_inspector_answered_value_call_keeps_its_history_charged() { if crate::common::runs_at_measurement_prices() { return; } @@ -1424,16 +2102,13 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); let run_with = |inspector: Option| { let db = funded().account_code(CALLEE, code.clone()); - let tx = call(CALLER, CALLEE, U256::ZERO, gas_limit()); + let tx = call(CALLER, CALLEE, U256::ZERO, value_call_room()); match inspector { Some(inspector) => { let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); assert!(result.result.is_success(), "{:?}", result.result); - ( - evm.ctx().additional_limit().usage(), - evm.ctx().additional_limit().history_gas_spent(), - ) + (evm.ctx().limit_usage(), evm.ctx().additional_limit().history_gas_spent()) } None => { let outcome = crate::common::execute(db, tx); @@ -1446,17 +2121,17 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { let (ran_usage, ran_history) = run_with(None); let body = mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE; - assert_eq!(answered_usage, body_only(), "the answered call wrote nothing"); - assert_eq!(answered_history, body, "so its caller pays for nothing beyond its body"); assert_eq!( ran_usage, - with_extra(records(2), TRANSFER_LOG_SIZE), - "the transfer that ran wrote two accounts and left its log" + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "the transfer that ran wrote two accounts and left its log, and created CONTRACT" ); assert_eq!( ran_history, body + 2 * WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE ); + assert_eq!(answered_usage, body_only(), "the answered call wrote nothing"); + assert_eq!(answered_history, ran_history, "and its caller's charge for the records stays"); } /* ---------- the KV count and the data size ---------- */ @@ -1472,7 +2147,7 @@ struct KvWeighsNoMore { impl Inspector, EthInterpreter> for KvWeighsNoMore { fn step_end(&mut self, _: &mut Interpreter, context: &mut MegaContext) { self.steps += 1; - let usage = context.additional_limit().usage(); + let usage = context.limit_usage(); if usage.write_records * WRITE_RECORD_SIZE > usage.data_size { self.over.get_or_insert(usage); } @@ -1481,10 +2156,11 @@ impl Inspector, EthInterpreter> for KvWeighsNoMore /// The KV count a node reads is the write-record count, and it never weighs more than the data /// size: every record is forty bytes of it, counted with it and taken back with it. Across the -/// corpus — slots written back, a slot rewritten, accounts recorded once per frame, failed -/// children, a hint — `KV × 40 ≤ data size` holds after every instruction a transaction runs, and -/// what it keeps parts from the records by exactly the bytes that are not records: the body, the -/// logs — the transfer logs among them — the deployed code and the hint's payload. +/// corpus — slots written back, a slot rewritten, accounts written again while they differ from +/// what was loaded, failed children, a hint — `KV × 40 ≤ data size` holds after every instruction +/// a transaction runs, and what it keeps parts from the records by exactly the bytes that are not +/// records: the body, the logs — the transfer logs among them — the deployed code and the hint's +/// payload. /// /// So the data-size limit bounds the records: at the production data-size caps a transaction keeps /// at most 327,680 of them. diff --git a/crates/mega-evm/tests/shared/op_reference.rs b/crates/mega-evm/tests/shared/op_reference.rs new file mode 100644 index 000000000..7f902424d --- /dev/null +++ b/crates/mega-evm/tests/shared/op_reference.rs @@ -0,0 +1,221 @@ +//! op-revm as the reference the comparisons hold Satin to. +//! +//! A target includes this file once, from its `main.rs`: +//! +//! ```ignore +//! #[path = "../shared/op_reference.rs"] +//! mod op_reference; +//! ``` +//! +//! op-revm's handler leaves two things to its consumer that Satin's handler does itself: EIP-8037's +//! split of a system call's gas — at most [`SYSTEM_CALL_REGULAR_GAS`] of it regular gas, the rest +//! its state-gas reservoir — and the reservoir a result settled with, which revm's result does not +//! carry. [`OpReference`] is op-revm's handler with both, so a comparison runs op-revm on the gas +//! Satin runs on, and reads op-revm's reservoir beside its result. +//! +//! The reference overrides every phase op-revm's handler overrides, each forwarded to it, and +//! nothing else: a phase op-revm comes to override must be forwarded here too. + +use std::{cell::Cell, convert::Infallible, ops::Deref}; + +use alloy_primitives::{Address, Bytes}; +use mega_evm::{test_utils::MemoryDatabase, MegaHaltReason}; +use op_revm::{ + handler::OpHandler, L1BlockInfo, OpEvm, OpSpecId, OpTransaction, OpTransactionError, +}; +use revm::{ + context::{ + result::{EVMError, ExecResultAndState, ExecutionResult, ResultGas}, + BlockEnv, CfgEnv, Context, ContextSetters, TxEnv, + }, + context_interface::cfg::gas::GasTracker, + handler::{EthFrame, ExecuteEvm, FrameResult, Handler, SystemCallTx}, + inspector::NoOpInspector, + interpreter::{interpreter::EthInterpreter, InitialAndFloorGas}, + state::EvmState, + Journal, +}; + +/// op-revm's context over a [`MemoryDatabase`]. +pub(crate) type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +/// op-revm's EVM over [`OpContext`]. +pub(crate) type Op = OpEvm; + +type OpError = EVMError; + +/// The regular gas EIP-8037 runs a system call on, at most: the system-call gas limit before +/// EIP-8037. Written out rather than taken from the engine, so the comparison holds the engine's +/// own number to it. +const SYSTEM_CALL_REGULAR_GAS: u64 = 30_000_000; + +/// A result and its state, and the reservoir the result settled with: what a transaction or a +/// system call left of its reservoir, which its sender gets back. +/// +/// Derefs to the result and state, so `outcome.result` and `outcome.state` read through. +#[derive(Debug)] +pub(crate) struct Settled { + pub(crate) result_and_state: ExecResultAndState, EvmState>, + pub(crate) reservoir_remaining: u64, +} + +impl Deref for Settled { + type Target = ExecResultAndState, EvmState>; + + fn deref(&self) -> &Self::Target { + &self.result_and_state + } +} + +/// Runs `tx` on `op` through [`OpReference`], as op-revm's own `transact` runs it. +pub(crate) fn transact(op: &mut Op, tx: OpTransaction) -> Result { + op.0.ctx.set_tx(tx); + let mut handler = OpReference::new(false); + let result = handler.run(op)?; + Ok(Settled { + result_and_state: ExecResultAndState::new(result, op.finalize()), + reservoir_remaining: handler.reservoir.get(), + }) +} + +/// Runs op-revm's system call from `caller` to `contract` with `data` on `gas_limit` through +/// [`OpReference`]: its system-call transaction with the gas limit replaced, run through its +/// handler's system-call path. +pub(crate) fn system_call( + op: &mut Op, + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, +) -> Result { + let mut tx = OpTransaction::::new_system_tx_with_caller(caller, contract, data); + tx.base.gas_limit = gas_limit; + op.0.ctx.set_tx(tx); + let mut handler = OpReference::new(true); + let result = handler.run_system_call(op)?; + Ok(Settled { + result_and_state: ExecResultAndState::new(result, op.finalize()), + reservoir_remaining: handler.reservoir.get(), + }) +} + +/// op-revm's handler, splitting a system call's gas as EIP-8037 has it and keeping the reservoir +/// its result settled with. Every phase op-revm's handler overrides is its own. +struct OpReference { + op: OpHandler>, + /// Whether the handler runs a system call, whose gas it splits. + system_call: bool, + /// The reservoir read where revm builds the result's gas of a transaction. + settled: Cell>, + /// The reservoir the result settled with; none for a failed deposit. + reservoir: Cell, +} + +impl OpReference { + fn new(system_call: bool) -> Self { + Self { + op: OpHandler::new(), + system_call, + settled: Cell::new(None), + reservoir: Cell::new(0), + } + } +} + +impl Handler for OpReference { + type Evm = Op; + type Error = OpError; + type HaltReason = MegaHaltReason; + + fn validate_env(&self, evm: &mut Op) -> Result<(), OpError> { + self.op.validate_env(evm) + } + + fn validate_against_state_and_deduct_caller( + &self, + evm: &mut Op, + init_and_floor_gas: &mut InitialAndFloorGas, + ) -> Result<(), OpError> { + self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) + } + + fn tx_gas(&self, evm: &mut Op, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + let mut gas = self.op.tx_gas(evm, init_and_floor_gas); + if self.system_call { + let margin = gas.remaining().saturating_sub(SYSTEM_CALL_REGULAR_GAS); + gas.set_remaining(gas.remaining() - margin); + gas.set_reservoir(gas.reservoir() + margin); + } + gas + } + + fn last_frame_result( + &mut self, + evm: &mut Op, + frame_result: &mut FrameResult, + parent_gas: &mut GasTracker, + ) -> Result<(), OpError> { + self.op.last_frame_result(evm, frame_result, parent_gas) + } + + fn post_execution( + &self, + evm: &mut Op, + exec_result: &mut FrameResult, + init_and_floor_gas: InitialAndFloorGas, + eip7702_gas_refund: i64, + ) -> Result { + self.settled.set(Some(exec_result.gas().reservoir())); + self.op.post_execution(evm, exec_result, init_and_floor_gas, eip7702_gas_refund) + } + + fn reimburse_caller(&self, evm: &mut Op, exec_result: &mut FrameResult) -> Result<(), OpError> { + self.op.reimburse_caller(evm, exec_result) + } + + fn refund( + &self, + evm: &mut Op, + exec_result: &mut FrameResult, + eip7702_refund: i64, + ) -> Result<(), OpError> { + self.op.refund(evm, exec_result, eip7702_refund) + } + + fn reward_beneficiary( + &self, + evm: &mut Op, + exec_result: &mut FrameResult, + ) -> Result<(), OpError> { + self.op.reward_beneficiary(evm, exec_result) + } + + /// revm's system-call path settles without `post_execution`: the result it hands over here is + /// the settled one. + fn execution_result( + &mut self, + evm: &mut Op, + result: FrameResult, + result_gas: ResultGas, + ) -> Result, OpError> { + let reservoir = self.settled.get().unwrap_or_else(|| result.gas().reservoir()); + let result = self.op.execution_result(evm, result, result_gas)?; + self.reservoir.set(reservoir); + Ok(result) + } + + fn catch_error( + &self, + evm: &mut Op, + error: OpError, + ) -> Result, OpError> { + self.op.catch_error(evm, error) + } +} diff --git a/crates/mega-evm/tests/system/access_control.rs b/crates/mega-evm/tests/system/access_control.rs index e1eec4ce0..98cd1f140 100644 --- a/crates/mega-evm/tests/system/access_control.rs +++ b/crates/mega-evm/tests/system/access_control.rs @@ -7,7 +7,7 @@ //! The legacy engine's rows, on Satin's switch. The beneficiary is the block's, `Address::ZERO` in //! these tests. -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, @@ -19,7 +19,7 @@ use mega_evm::{ volatile_data_access_disabled_revert_data, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, VolatileDataAccess, }; -use revm::bytecode::opcode::*; +use revm::{bytecode::opcode::*, context::BlockEnv}; use crate::common::{block, call_tx_with_gas, steer, system_db, Run, GAS_LIMIT}; @@ -40,10 +40,15 @@ const DISABLED_BY_PARENT: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECT /// Runs `tx` over `db`, with an oracle service that holds slot 0 of the Oracle. fn execute(db: MemoryDatabase, tx: MegaTransaction) -> Run { + execute_in(db, tx, block()) +} + +/// [`execute`] in `block`. +fn execute_in(db: MemoryDatabase, tx: MegaTransaction, block: BlockEnv) -> Run { let envs = TestExternalEnvs::::new() .with_oracle_storage(U256::ZERO, U256::from(0x1234)); let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, ExternalEnvs::from(envs)) - .with_block(block()) + .with_block(block) .with_chain(zero_fee_l1_block_info()); let mut evm = MegaEvm::new(ctx); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); @@ -329,6 +334,126 @@ fn test_selfdestruct_beneficiary_not_restricted_without_disable() { assert!(run.logged_status(0)); } +/* ---------- 4b. a creation's own loads ---------- */ + +/// Appends a creation through `scheme` of empty init code carrying `value`, salt zero for a +/// `CREATE2`, leaving the created address on the stack. +fn create_empty(code: BytecodeBuilder, scheme: u8, value: u8) -> BytecodeBuilder { + let code = if scheme == CREATE2 { code.append(PUSH0) } else { code }; + code.append_many([PUSH0, PUSH0]).push_number(value).append(scheme) +} + +/// Where a creation of empty init code by `creator`, whose nonce is `nonce`, lands through +/// `scheme`. +fn created_address(creator: Address, scheme: u8, nonce: u64) -> Address { + if scheme == CREATE2 { + creator.create2(B256::ZERO, keccak256([])) + } else { + creator.create(nonce) + } +} + +/// Asserts that the account at `address` was created, holding `balance`. +fn assert_created(run: &Run, address: Address, balance: u64, case: &str) { + let account = run.outcome.state.get(&address).unwrap_or_else(|| panic!("{case}: not created")); + assert_eq!(account.info.nonce, 1, "{case}: a created account's nonce"); + assert_eq!(account.info.balance, U256::from(balance), "{case}"); +} + +/// The status of the call the parent logged last, after the logs its callee left. +fn last_logged_status(run: &Run) -> bool { + run.logged_status(run.outcome.result.logs().len() - 1) +} + +/// A frame running as the beneficiary that switched access off creates: a `CREATE` carrying value +/// and a `CREATE2` load the creator's account, which is the beneficiary's, for its balance and +/// nonce, and neither load is a volatile read, so neither is refused. The beneficiary's frame +/// succeeds and both accounts are created, the first holding the value. +#[test] +fn test_a_beneficiary_frame_with_access_off_creates() { + let beneficiary = + create_empty(create_empty(disable(BytecodeBuilder::default()), CREATE, 1), CREATE2, 0); + let parent = + log_status(call(BytecodeBuilder::default(), CALL, BENEFICIARY, 50_000_000)).stop().build(); + let db = system_db() + .account_code(PARENT, parent) + .account_code(BENEFICIARY, beneficiary.stop().build()) + .account_balance(BENEFICIARY, U256::from(10)); + let run = execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)); + assert!(last_logged_status(&run), "the beneficiary's frame succeeded"); + assert_created(&run, created_address(BENEFICIARY, CREATE, 0), 1, "CREATE"); + assert_created(&run, created_address(BENEFICIARY, CREATE2, 1), 0, "CREATE2"); + assert_eq!(run.accessed, VolatileDataAccess::BENEFICIARY_BALANCE, "the parent's call of it"); +} + +/// A value `CALL` from a frame running as the beneficiary that switched access off moves the +/// value: the check of the caller's balance is no volatile read, as a creation's is not. +#[test] +fn test_a_value_call_from_a_beneficiary_frame_with_access_off_moves_the_value() { + let beneficiary = disable(BytecodeBuilder::default()) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(SIBLING) + .push_number(100_000_u32) + .append_many([CALL, STOP]); + let parent = + log_status(call(BytecodeBuilder::default(), CALL, BENEFICIARY, 50_000_000)).stop().build(); + let db = system_db() + .account_code(PARENT, parent) + .account_code(BENEFICIARY, beneficiary.build()) + .account_balance(BENEFICIARY, U256::from(10)); + let run = execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)); + assert!(last_logged_status(&run), "the beneficiary's frame succeeded"); + assert_eq!(run.outcome.state[&SIBLING].info.balance, U256::ONE, "the value moved"); +} + +/// A frame running as the beneficiary that switched access off is still refused its explicit reads +/// of its own account: `SELFBALANCE`, and `BALANCE` and `EXTCODESIZE` of `ADDRESS`. +#[test] +fn test_a_beneficiary_frame_with_access_off_is_refused_its_own_account() { + for (name, read) in [ + ("SELFBALANCE", &[SELFBALANCE][..]), + ("BALANCE", &[ADDRESS, BALANCE][..]), + ("EXTCODESIZE", &[ADDRESS, EXTCODESIZE][..]), + ] { + let beneficiary = disable(BytecodeBuilder::default()) + .append_many(read.iter().copied()) + .append_many([POP, STOP]) + .build(); + let parent = call_and_return_data(BytecodeBuilder::default(), BENEFICIARY); + let run = run(&[(PARENT, parent), (BENEFICIARY, beneficiary)]); + assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Beneficiary, "{name}"); + } +} + +/// A `CREATE` or `CREATE2` whose created address is the block beneficiary loads that address's +/// account to decide the created account's state gas, and the load is no volatile read: it marks +/// nothing and sets no compute limit with access on, and is not refused with access off. The +/// creating frame then runs a wrapped read of non-volatile data, `SLOAD` of its own slot, which +/// commits nothing either. +#[test] +fn test_a_creation_at_the_beneficiary_is_no_read() { + const NONCE: u64 = 1; + for scheme in [CREATE, CREATE2] { + for switched_off in [false, true] { + let case = format!("{scheme:#04x}, access off: {switched_off}"); + let code = BytecodeBuilder::default(); + let code = if switched_off { disable(code) } else { code }; + let parent = log_status(create_empty(code, scheme, 0).append_many([PUSH0, SLOAD, POP])) + .stop() + .build(); + let created = created_address(PARENT, scheme, NONCE); + let db = system_db().account_code(PARENT, parent).account_nonce(PARENT, NONCE); + let block = BlockEnv { beneficiary: created, ..block() }; + let run = execute_in(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT), block); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + assert_created(&run, created, 0, &case); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{case}"); + assert_eq!(run.limit, None, "{case}"); + } + } +} + /* ---------- 5. a refused read reads nothing ---------- */ /// A refused read records nothing and sets no compute limit: the block environment, the diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 0817418b4..61c17f2d1 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -345,3 +345,53 @@ fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { "sent by a relayer: the signer's nonce record too", ); } + +/// Records the reservoir each frame start hands its frame: the call's, then the creation's. +#[derive(Default)] +struct Reservoirs(Vec); + +impl + revm::Inspector, revm::interpreter::interpreter::EthInterpreter> + for Reservoirs +{ + fn call( + &mut self, + _: &mut MegaContext, + inputs: &mut revm::interpreter::CallInputs, + ) -> Option { + self.0.push(inputs.reservoir); + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut revm::interpreter::CreateInputs, + ) -> Option { + self.0.push(inputs.reservoir()); + None + } +} + +/// The call, the transaction's own frame, takes the whole reservoir; the creation it starts takes +/// all but the call's 2 per cent of what the call has left once it paid for the creation's start — +/// the signer's account, the created account and the two records — as a `CREATE` opcode's child +/// does. +#[test] +fn test_the_creation_takes_the_reservoir_share_of_what_the_call_has_left() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + let data = deployment.call_data(LARGE_OVERRIDE); + let gas_limit = TX_GAS_LIMIT_CAP * 2; + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let mut evm = MegaEvm::new(context(system_db())).with_inspector(Reservoirs::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + + let whole = gas_limit - TX_GAS_LIMIT_CAP - history(mega_evm::TX_BODY_SIZE + data.len() as u64); + let left = whole - + entry(GasId::new_account_state_gas()) - + entry(GasId::create_state_gas()) - + 2 * record(); + assert_eq!(evm.inspector().0, [whole, left - left * 2 / 100]); +} diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 2fd93df66..9144638a0 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -884,20 +884,20 @@ fn test_a_deployment_carrying_value_logs_the_move() { } } -/// The transfer log is counted with the creation's start, before revm builds the creation and -/// moves the value: a creation whose budget holds its two records and not the log is stopped at -/// its start, alone, with the value unmoved and no log journaled — the debug build's check of -/// every frame start holds it to exactly that. The same deployment without value deploys under -/// the same limit. +/// The transfer log is counted with the creation's start: a creation whose budget holds its +/// record and not the log is stopped at its start, alone, before it runs, and its revert takes +/// back the value revm moved and the log it journaled. The same deployment without value deploys +/// under the same limit. #[test] fn test_a_creation_is_stopped_on_its_transfer_log_before_the_value_moves() { let with_value = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); let without = Deployment::new(deploying(&runtime(1))); - // The creation gets 98% of what the call leaves: 235 bytes, room for its records' 80 and - // its byte of code, not for the log's 160 on top of the records. + // The creation gets 98% of the 200 bytes the call has: 196, room for the created account's + // record and its byte of code, not for the log's 160 on top of the record. The call keeps the + // signer's nonce record in what the creation leaves it. let limits = |deployment: &Deployment, gas_limit| { let body = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit).usage.data_size; - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 240) + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 200) }; for gas_limit in GAS_LIMITS { let stopped = run_with( @@ -926,3 +926,77 @@ fn test_a_creation_is_stopped_on_its_transfer_log_before_the_value_moves() { assert_eq!(returned(&deployed).deployedAddress, without.address, "at {gas_limit}"); } } + +/// A constructor that returns empty code for the deploy address is refused, unless it destroyed +/// the address in this transaction, and code a constructor returns is kept unless it destroyed the +/// address in this transaction: a destruction an earlier transaction on the same journal made — +/// two transactions run one after another without the journal finalized between them, as a block +/// builder runs them — is not this one. The constructor destroys its account while a probe address +/// is empty, and returns empty code, or one byte, otherwise. The first deployment destroys it; a +/// transfer then funds the probe; the same deployment again returns code for an account it did not +/// destroy: empty code is refused, so the deploy address is not created, and one byte is deployed. +#[test] +fn test_a_destruction_an_earlier_transaction_made_is_not_the_deployments() { + use revm::{ + bytecode::opcode::{BALANCE, ISZERO, JUMPDEST, JUMPI, SELFDESTRUCT}, + context::ContextTr, + ExecuteEvm, + }; + const PROBE: Address = address!("0x00000000000000000000000000000000000ba1a0"); + for returned in [0_u8, 1] { + // `PUSH20 probe; BALANCE; ISZERO; PUSH1 destroy; JUMPI; PUSH1 returned; PUSH0; RETURN; + // JUMPDEST` at 30, then the destruction. + let init = BytecodeBuilder::default() + .push_address(PROBE) + .append_many([BALANCE, ISZERO]) + .push_number(30_u8) + .append(JUMPI) + .push_number(returned) + .append_many([PUSH0, RETURN, JUMPDEST]) + .push_address(NOBODY) + .append(SELFDESTRUCT) + .build(); + assert_eq!(init[30], JUMPDEST); + let deployment = Deployment::new(init); + let mut evm = MegaEvm::new( + context(db_for(&deployment, U256::ZERO)) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()), + ); + let deploy = |nonce| { + let data = deployment.call_data(LARGE_OVERRIDE); + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); + tx.0.base.nonce = nonce; + tx + }; + let first = ExecuteEvm::transact_one(&mut evm, deploy(0)).expect("valid"); + assert!(first.is_success(), "returning {returned}: {first:?}"); + assert!( + evm.ctx().journal_ref().state[&deployment.address].is_selfdestructed(), + "returning {returned}: the first deployment destroyed the account" + ); + let mut fund = call_tx(PROBE, Bytes::new(), U256::from(1)); + fund.0.base.nonce = 1; + assert!(ExecuteEvm::transact_one(&mut evm, fund).expect("valid").is_success()); + + let second = ExecuteEvm::transact_one(&mut evm, deploy(2)).expect("valid"); + let ExecutionResult::Success { output, .. } = &second else { panic!("{second:?}") }; + let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + .expect("a keylessDeploy return"); + let state = ExecuteEvm::finalize(&mut evm); + let deployed = state.get(&deployment.address); + if returned == 0 { + assert_eq!( + decode_error_result(&ret.errorData), + Some(KeylessDeployError::EmptyCodeDeployed { gas_used: ret.gasUsed }), + "the empty code is refused" + ); + assert!( + deployed.is_none_or(|account| account.info.nonce == 0), + "the refused creation leaves the deploy address uncreated" + ); + } else { + assert_eq!(ret.deployedAddress, deployment.address, "the byte is deployed"); + assert!(deployed.is_some_and(|account| account.info.code_hash != KECCAK_EMPTY)); + } + } +} diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index f6afb2d1f..9ad75cd0e 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -667,17 +667,21 @@ fn test_a_deployment_another_limit_stops_keeps_the_reads_its_creation_made() { let prefix = BytecodeBuilder::default().append_many([TIMESTAMP, POP]).sstore(U256::ZERO, U256::ONE); let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); - // The body, the creation's two start records and the slot's record, one byte short. + // The body, the signer's nonce record, the created account's record and one byte: the + // creation's share of the 81 bytes the call has, 79, holds its start's record and not the + // slot's, and the call keeps the signer's record once the creation returned. let body = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; - let limit = body + 3 * mega_evm::WRITE_RECORD_SIZE - 1; + let limit = body + 2 * mega_evm::WRITE_RECORD_SIZE + 1; for gas_limit in GAS_LIMITS { let run = run_both(&deployment, gas_limit, capped(CAP).with_tx_data_size_limit(limit)); let KeylessDeployError::ExecutionReverted { output, .. } = failure(&run.outcome) else { panic!("expected the creation's data-size stop, got {:?}", run.outcome.result); }; + // The creation's budget is 98% of what the call has, which the slot's record crosses. + let budget = (limit - body) * 98 / 100; assert_eq!( MegaLimitExceeded::abi_decode(&output).unwrap(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }, ); assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); assert!(run.limit.is_some()); diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index a0fff80aa..066a53282 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -215,7 +215,7 @@ impl Scenario { self.to, self.data.clone(), ); - render_system_call(result.map(|r| (r.result, r.state))) + render_system_call(result.map(|r| (r.result, r.state)), evm.ctx()) } else { render_outcome(evm.execute_transaction(self.tx())) }; @@ -230,7 +230,7 @@ impl Scenario { self.to, self.data.clone(), ); - render_system_call(result.map(|r| (r.result, r.state))) + render_system_call(result.map(|r| (r.result, r.state)), evm.ctx()) } else { render_outcome(evm.execute_transaction(self.tx())) }; @@ -540,6 +540,9 @@ fn scenarios() -> Vec { /* Limits. */ let data_size = Deployment::new(logging(2_000)); let body = reference(data_size.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; + // The call keeps 40 bytes for the signer's record, and the creation's share of them, 39, + // is one short of its start. + let small_body = reference(small.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; let compute = Deployment::new(reads_then_burns(TIMESTAMP, 1_000)); for nonce in [0, 1] { let db = |d: &Deployment| system_db().account_nonce(d.signer, nonce); @@ -588,7 +591,7 @@ fn scenarios() -> Vec { &small, gas_limit, ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 40)), + .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(small_body + 40)), ); } all.push( @@ -956,6 +959,7 @@ impl Inspector, EthInterpreter> for Recorder { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: Default::default(), }) } @@ -1031,11 +1035,17 @@ fn render_outcome(outcome: Result( +/// A system call's result and state, and the reservoir it left, which its result does not carry. +fn render_system_call( result: Result<(R, EvmState), E>, + ctx: &MegaContext, ) -> String { match result { - Ok((result, state)) => format!("result: {result:?}\nstate:\n{}", render_state(&state)), + Ok((result, state)) => format!( + "result: {result:?}\nreservoir_remaining: {}\nstate:\n{}", + ctx.additional_limit().reservoir_remaining(), + render_state(&state) + ), Err(error) => format!("error: {error:?}\n"), } } diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 780cdbfc2..88db12ced 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -47,14 +47,18 @@ fn call_frame(code: revm::state::Bytecode, data: Bytes, gas_limit: u64) -> Frame scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, })), } } -/// The call is a frame on revm's stack, driven through revm's frame lifecycle by hand: revm builds -/// it at depth 0; its first run starts the creation as its child, at depth 1, which revm builds -/// above it on the stack; the creation returns into it; and on its resume it answers in the ABI, -/// as the outermost frame. +/// The call is a frame on revm's stack, driven through revm's frame lifecycle by hand, as revm's +/// loop drives it, a frame's run result handed over before it returns: revm builds it at depth 0; +/// its first run starts the creation as its child, at depth 1, which revm builds above it on the +/// stack; the creation returns into it; and on its resume it answers in the ABI, as the outermost +/// frame. #[test] fn test_the_call_is_a_frame_on_revms_stack() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -85,17 +89,19 @@ fn test_the_call_is_a_frame_on_revms_stack() { }; assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(1), "above the call on the stack"); - let ItemOrResult::Result(created) = EvmTr::frame_run(&mut evm).unwrap() else { + let ItemOrResult::Result(mut created) = EvmTr::frame_run(&mut evm).unwrap() else { panic!("the creation runs to its end"); }; + EvmTr::frame_run_result(&mut evm, &mut created).unwrap(); assert!(matches!(&created, FrameResult::Create(outcome) if outcome.result.is_ok())); let returned = EvmTr::frame_return_result(&mut evm, created).unwrap(); assert!(returned.is_none(), "the creation returns into the call"); assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(0)); - let ItemOrResult::Result(answer) = EvmTr::frame_run(&mut evm).unwrap() else { + let ItemOrResult::Result(mut answer) = EvmTr::frame_run(&mut evm).unwrap() else { panic!("the call answers on its resume"); }; + EvmTr::frame_run_result(&mut evm, &mut answer).unwrap(); let answer = EvmTr::frame_return_result(&mut evm, answer).unwrap(); let Some(FrameResult::Call(outcome)) = answer else { panic!("the call is the outermost frame: {answer:?}"); diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 554ac26eb..6e2a3a0ed 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -5,8 +5,8 @@ use alloy_sol_types::SolError; use mega_evm::{ - system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, LimitKind, - MegaLimitExceeded, WRITE_RECORD_SIZE, + system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, EvmTxRuntimeLimits, + LimitKind, MegaLimitExceeded, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{LOG0, PUSH0, REVERT}, @@ -75,6 +75,7 @@ impl Inspector, EthInterpreter> for Recorder { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: Default::default(), }) } @@ -182,12 +183,14 @@ fn test_a_failed_deployment_ends_as_a_revert_in_the_trace() { } /// An inspector that answers the creation itself — a tool's rewrite — starts no creation: the -/// signer's nonce is not spent, so neither its account nor the created one is charged, and the -/// call reports what the inspector answered. The transaction spends the overhead, the regular gas -/// the `CREATE` opcode charges whatever its frame does, and the reference's gas, and nothing -/// else. +/// signer's nonce is not spent, and the call reports what the inspector answered. The answer is +/// taken as given, as revm takes it: what the call was charged for the creation's start stays +/// charged — the history of the signer's nonce record and of the created account's record — and +/// no record is counted, the signer's nonce never having been bumped. The transaction spends the +/// overhead, the regular gas the `CREATE` opcode charges whatever its frame does, those two +/// records' history, and the reference's gas. #[test] -fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { +fn test_a_creation_an_inspector_answers_keeps_what_its_start_was_charged() { let deployment = Deployment::new(deploying(&runtime(1))); let opcode = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(deploying(&runtime(1)).len()); for gas_limit in GAS_LIMITS { @@ -199,7 +202,7 @@ fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); assert_eq!( [total, regular, state, history_gas, history_bytes], - [opcode, opcode, 0, 0, 0], + [opcode + 2 * record(), opcode, 0, 2 * record(), 0], "at {gas_limit}", ); assert_eq!( @@ -385,10 +388,13 @@ fn test_a_revived_keyless_creation_a_limit_stopped_answers_address_mismatch() { let KeylessDeployError::ExecutionReverted { output, .. } = failure(&plain) else { panic!("the creation did not revert: {:?}", plain.result); }; + // The creation's budget: 98% of what the call has left, which the log crosses with the + // transaction's limit. + let budget = (limit - body) * 98 / 100; assert_eq!( MegaLimitExceeded::abi_decode(&output).expect("a limit stop"), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, - "at {gas_limit}: the constructor's log crossed the transaction's limit" + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }, + "at {gas_limit}: the constructor's log crossed the creation's budget" ); assert_eq!(nonce(&plain, deployment.signer), 1, "the plain run spends the nonce"); @@ -418,3 +424,76 @@ fn test_an_inspector_sees_an_empty_code_deployment_end_as_a_revert() { assert_eq!(ends, [&end], "at {gas_limit}"); } } + +/// Halts the `keylessDeploy` call's frame whenever it is handed to the inspector, in +/// `initialize_interp` or in a `step`, and counts the times it was. +#[derive(Default)] +struct HaltsTheCall { + handed: usize, +} + +impl HaltsTheCall { + fn halt(&mut self, interp: &mut Interpreter) { + if interp.input.target_address == KEYLESS_DEPLOY_ADDRESS { + self.handed += 1; + interp.halt(InstructionResult::OutOfGas); + } + } +} + +impl Inspector, EthInterpreter> for HaltsTheCall { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + ) { + self.halt(interp); + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.halt(interp); + } +} + +/// The actions the engine sets on the call's frame — the creation it starts, the answer once the +/// creation returned, and the stop of a call its creation's nonce record left over the frame's +/// budget — are the frame's own: revm hands a frame built with an action to no +/// `initialize_interp`, and returns an action set before a run without a `step`. So an inspector +/// that would halt the call's frame there is never handed it, and the run is the plain run, in a +/// debug build and a release build alike. +#[test] +fn test_an_inspector_that_would_halt_the_calls_frame_is_never_handed_it() { + let deployment = Deployment::new(deploying(&runtime(1))); + let over_the_budget = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39); + for gas_limit in GAS_LIMITS { + for limits in [None, Some(over_the_budget)] { + let case = format!("{limits:?} at {gas_limit}"); + let context = || match limits { + Some(limits) => context(system_db()).with_tx_runtime_limits(limits), + None => context(system_db()), + }; + let tx = keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let plain = MegaEvm::new(context()).execute_transaction(tx.clone()).expect("valid"); + if limits.is_none() { + assert_eq!(returned(&plain).deployedAddress, deployment.address, "{case}"); + } else { + // The call's first action started its creation, which returned into it, leaving + // the call over its budget: the call returns the stop on its resume. + assert!(plain.limit_exceeded.is_some(), "{case}: the call returns the stop"); + let mut evm = MegaEvm::new(context()).with_inspector(Recorder::default()); + evm.execute_transaction(tx.clone()).expect("valid"); + let events = &evm.inspector().events; + let started = events.iter().any(|event| matches!(event, Event::Create(..))); + let returned = events.iter().any(|event| matches!(event, Event::CreateEnd(..))); + assert!(started && returned, "{case}: the creation started and returned"); + } + let mut evm = MegaEvm::new(context()).with_inspector(HaltsTheCall::default()); + let halted = evm.execute_transaction(tx).expect("valid"); + assert_eq!(evm.inspector().handed, 0, "{case}: the call's frame is never handed over"); + assert_eq!(halted.result_and_state, plain.result_and_state, "{case}"); + assert_eq!(halted.gas, plain.gas, "{case}"); + assert_eq!(halted.usage, plain.usage, "{case}"); + assert_eq!(halted.limit_exceeded, plain.limit_exceeded, "{case}"); + } + } +} diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 90a8b9a40..8915a05ac 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -4,10 +4,10 @@ //! an ordinary creation is: its share of the data-size budget, the transaction's limits. A limit //! the creation crosses, its budget or the transaction's, reverts the creation alone, and the call //! answers `ExecutionReverted` with the stop's revert data, keeping what the creation's start -//! wrote. A limit the call itself crosses — its budget, crossed by the nonce record a failed -//! creation leaves it — reverts the call with the stop, which takes back everything the deployment -//! wrote, the signer's nonce included, and the sender pays for what ran and gets the rest of its -//! gas and its reservoir back. +//! wrote. A limit the call itself crosses — its budget, or the transaction's limit, crossed by the +//! signer's nonce record, counted on the call once the creation returned — reverts the call with +//! the stop, which takes back everything the deployment wrote, the signer's nonce included, and the +//! sender pays for what ran and gets the rest of its gas and its reservoir back. //! //! The creation's stop is pinned as a column of the matrix: every limit a creation can cross, //! from a signer at nonce 0 and at nonce 1, below the execution cap and above it, with and without @@ -17,13 +17,14 @@ //! caller or to the sender: an answer built without a frame, the settlement of a stopped //! transaction, and the return of the frame's unspent gas. -use alloy_sol_types::SolError; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, LimitCheck, - LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, + constants::TX_GAS_LIMIT_CAP, + system::{keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, IOracle, ORACLE_CONTRACT_ADDRESS}, + LimitCheck, LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{PUSH0, REVERT, TIMESTAMP}, + bytecode::opcode::{CALL, GAS, POP, PUSH0, REVERT, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, InstructionResult, @@ -105,8 +106,7 @@ fn assert_nothing_kept( assert_eq!(outcome.usage.write_records, 0, "{case}: no record is kept"); if gas_limit > TX_GAS_LIMIT_CAP { assert_eq!( - outcome.result.gas().reservoir_remaining(), - reference.result.gas().reservoir_remaining(), + outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining, "{case}: the reservoir comes back", ); } @@ -124,7 +124,8 @@ fn test_a_deployment_crossing_its_data_size_budget_reverts_alone() { gas_limit, EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(1_000), ); - // The call's own lane gets the frame cap, and its creation 98% of that. + // The call's own pool gets the frame cap, and the creation 98% of it; the signer's nonce + // record is counted on the call once the creation returned. assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 980 }); assert_eq!(outcome.limit_exceeded, None); assert_eq!(nonce(&outcome, deployment.signer), 1); @@ -134,8 +135,8 @@ fn test_a_deployment_crossing_its_data_size_budget_reverts_alone() { /// The records the creation's start makes are held before the creation is built: a transaction /// limit that holds one record but not two stops the creation before its init code runs. The -/// start still bumps the signer's nonce, whose record the call keeps within the limit, and the -/// call answers the stop. +/// start still bumps the signer's nonce, whose record the call keeps within the limit once the +/// creation returned, and the call answers the stop. #[test] fn test_the_creations_start_crossing_the_limit_stops_the_creation() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -146,7 +147,9 @@ fn test_the_creations_start_crossing_the_limit_stops_the_creation() { gas_limit, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit }); + // The call has the one record's room, and the creation 98% of it, which its own record + // crosses. + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 39 }); assert_eq!(outcome.limit_exceeded, None, "at {gas_limit}"); assert_eq!(nonce(&outcome, deployment.signer), 1, "at {gas_limit}"); assert_eq!( @@ -160,10 +163,10 @@ fn test_the_creations_start_crossing_the_limit_stops_the_creation() { } } -/// A failed creation leaves its creator's nonce record on the call's lane, which no check held it -/// to: a call whose budget cannot hold that record reverts alone with its own stop, and takes the -/// nonce back with it. The outcome names the call's budget, whose crossing produced the result of -/// the transaction's own frame. +/// A failed creation leaves its creator's nonce record to the call, counted on the call's pool +/// once the creation returned and held to the call's budget: a call whose budget cannot hold that +/// record reverts alone with its own stop, and takes the nonce back with it. The outcome names the +/// call's budget, whose crossing produced the result of the transaction's own frame. #[test] fn test_the_signers_record_can_put_the_call_over_its_budget() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -188,6 +191,57 @@ fn test_the_signers_record_can_put_the_call_over_its_budget() { } } +/// The signer's nonce record is counted on the call once the creation returned, after the hint +/// the creation's constructor sent to the Oracle: the hint used what the transaction had left, and +/// the record crosses the transaction's limit, with room to spare in the call's budget. The call +/// reverts with that stop, which takes the whole deployment back; the hint stays counted. +#[test] +fn test_a_hint_the_creation_sent_leaves_the_signers_record_over_the_transaction_limit() { + let hint = Bytes::from( + IOracle::sendHintCall { topic: B256::repeat_byte(0x7a), data: Bytes::from(vec![0x5a; 64]) } + .abi_encode(), + ); + let hint_bytes = hint.len() as u64; + let prefix = mega_evm::test_utils::BytecodeBuilder::default() + .mstore(0, &hint) + .append_many([PUSH0, PUSH0]) + .push_number(hint_bytes) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]) + .build_vec(); + let deployment = Deployment::new(constructor(&prefix, &runtime(1))); + let body = body_bytes(&deployment); + // The created account's record, the hint and the deployed byte, and one byte short of the + // signer's record. + let limit = body + WRITE_RECORD_SIZE + hint_bytes + 1 + WRITE_RECORD_SIZE - 1; + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit }, "at {gas_limit}"); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + 1, + frame_local: false, + }), + "at {gas_limit}: the transaction's limit, not the call's budget" + ); + assert_eq!(nonce(&outcome, deployment.signer), 0, "at {gas_limit}: the bump goes back"); + assert!( + code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY), + "at {gas_limit}: no code is deployed" + ); + assert_eq!(outcome.usage.data_size, body + hint_bytes, "at {gas_limit}: the hint stays"); + assert_eq!(outcome.usage.write_records, 0, "at {gas_limit}"); + } +} + /// A failed creation by a signer at nonce 1 leaves no record on the call: its nonce bump is taken /// back, and the record with it. The same budget then holds the call, which answers with the /// creation's own stop, and the signer stays at 1. @@ -201,7 +255,8 @@ fn test_a_failure_from_nonce_one_leaves_the_call_within_its_budget() { gas_limit, EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39), ); - // The call's lane gets the frame cap, and its creation 98% of that. + // The call's pool gets the frame cap, and the creation 98% of it, 38, which its own + // record crosses. assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 38 }); assert_eq!(outcome.limit_exceeded, None); assert_eq!(nonce(&outcome, deployment.signer), 1, "at {gas_limit}"); @@ -209,6 +264,50 @@ fn test_a_failure_from_nonce_one_leaves_the_call_within_its_budget() { } } +/// Init code that fills the fresh slots `1..=slots` and deploys a one-byte runtime. +fn filling(slots: u64) -> Bytes { + let prefix = (1..=slots) + .fold(mega_evm::test_utils::BytecodeBuilder::default(), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)) + }); + constructor(&prefix.build_vec(), &runtime(1)) +} + +/// A signer the creation's nonce bump creates is one account of state growth on the call, counted +/// with the signer's record once the creation returned, and the empty deploy address is the +/// creation's first rise against its share of what the call has left: under the spec's 1,000 the +/// creation gets `1,000 × 98 / 100` = 980. Under a limit of ten the creation gets 9, of which the +/// deploy address takes one: init code filling eight fresh slots deploys, the call keeping the +/// signer's account in the one it kept, and a ninth slot stops the creation, naming 9, which the +/// call answers, the signer's bump and its new account kept. A signer that exists adds nothing, +/// and its creation gets the same 9: the address and eight slots. +#[test] +fn test_a_new_signer_and_its_deploy_address_are_state_growth() { + assert_eq!(1_000 * 98 / 100, 980); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(10); + let (fits, over) = (Deployment::new(filling(8)), Deployment::new(filling(9))); + for gas_limit in GAS_LIMITS { + let deployed = limited(&fits, gas_limit, limits); + assert_eq!(returned(&deployed).deployedAddress, fits.address, "at {gas_limit}"); + assert_eq!(deployed.usage.state_growth, 10, "at {gas_limit}: the signer, the address, 8"); + + let stopped = limited(&over, gas_limit, limits); + assert_eq!(creation_stop(&stopped), MegaLimitExceeded { kind: 3, limit: 9 }); + assert_eq!(stopped.limit_exceeded, None, "at {gas_limit}: the call answered"); + assert_eq!(nonce(&stopped, over.signer), 1, "at {gas_limit}"); + assert_eq!(stopped.usage.state_growth, 1, "at {gas_limit}: the signer's new account"); + + let existing = run_with( + system_db().account_balance(fits.signer, U256::from(1)), + fits.call_data(LARGE_OVERRIDE), + gas_limit, + limits, + ); + assert_eq!(returned(&existing).deployedAddress, fits.address, "at {gas_limit}"); + assert_eq!(existing.usage.state_growth, 9, "at {gas_limit}: the address and eight slots"); + } +} + /// A limit that holds the whole deployment lets it through. #[test] fn test_a_deployment_within_every_limit_deploys() { @@ -240,10 +339,7 @@ fn test_a_refusal_after_the_charges_gives_the_reservoir_back() { [total, regular, state, history_gas], [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0] ); - assert_eq!( - outcome.result.gas().reservoir_remaining(), - reference.result.gas().reservoir_remaining(), - ); + assert_eq!(outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining,); } /// And a call refused after the charges of the creation's start — the forward the `CREATE` @@ -281,10 +377,7 @@ fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { let [total, regular, state, history_gas, _] = beyond(&outcome, &reference); let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + opcode; assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); - assert_eq!( - outcome.result.gas().reservoir_remaining(), - reference.result.gas().reservoir_remaining(), - ); + assert_eq!(outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining,); } /// The call gets back what its creation did not spend, the same way whether the creation @@ -358,14 +451,17 @@ impl Crossing { let limits = EvmTxRuntimeLimits::no_limits(); match self { Self::DataSize => { - // The body, the two records of the creation's start and 100 bytes more; the - // constructor's log crosses with all its bytes. + // The body, the two records of the deployment's start and 100 bytes more; the + // constructor's log crosses with all its bytes the transaction's limit and the + // creation's budget, which the stop names: 98% of what the call has left, the + // signer's nonce record being counted on the call once the creation returned. let start = body_bytes(deployment) + 2 * WRITE_RECORD_SIZE; let limit = start + 100; - let used = start + LOG_BASE_SIZE + 2_000; + let budget = (limit - body_bytes(deployment)) * 98 / 100; + let used = WRITE_RECORD_SIZE + LOG_BASE_SIZE + 2_000; ( limits.with_tx_data_size_limit(limit), - Crossed::new(LimitKind::DataSize, limit, used), + Crossed::new(LimitKind::DataSize, budget, used), ) } Self::Compute => { @@ -487,7 +583,8 @@ fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { let [_, regular, ..] = beyond(outcome, &reference); assert_eq!(regular, used, "{cell}: computed up to the charge that crossed"); } else { - assert!(outcome.usage.data_size <= limit, "{cell}: within the limit"); + let tx_limit = limits.tx_data_size_limit; + assert!(outcome.usage.data_size <= tx_limit, "{cell}: within the limit"); } } assert_eq!( diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 52a5b414a..95e82d629 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -586,7 +586,7 @@ fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { #[test] fn test_every_way_a_deployment_from_nonce_one_fails_leaves_the_nonce_at_one() { let one = U256::ONE; - // The call's lane gets 39 bytes, and its creation 98% of that: less than its start's two + // The call's pool gets 39 bytes, and its creation 98% of that: less than its start's two // records. let a_share_short_of_the_start = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39); let cases = [ diff --git a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap index d9448bd75..644a3fff0 100644 --- a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap +++ b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap @@ -4,150 +4,150 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xb5a5ac86d1fae7f5e736ca81732ad3c9d376a7bbac67681509c8c11cad0fe21e", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x8cb374010ef32a5b928292a27304c9ff3df52dc6e29bb7dc3378cbea850ae292", - "rule: arguments that do not decode @ 50000000 | keccak256=0x4873273b34dd03636298cf421a82fa400e22c641ca56fea88d493e6d759c138c", - "rule: malformed transaction @ 50000000 | keccak256=0x8736f4dcd9908c3bd36c0b87bebef88fc498fb79c412e8710b84f624f5ef2304", - "rule: a trailing byte @ 50000000 | keccak256=0x6d63b733472ee70ca12153d130895554e40d3576812f5be0e881c43c152cd093", - "rule: not a creation @ 50000000 | keccak256=0x11925b46a5532a3c576d8a095b29b86cd873a33bbd523481641138a9296cd2c7", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0x65165db7ef0c4d75c7d0db224328b34b50bdeb792624bf21212e55f4cd95dfe9", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x8b7363b60e2b5e351baa81fca15777fb579647fa7754835a4f776da548966267", - "rule: override below the signed gas limit @ 50000000 | keccak256=0x4c688e0f80991bb11360110133e41549a0dedfafc587ab1b3b2646c1032fce5f", - "rule: invalid signature @ 50000000 | keccak256=0x336f5ea6b4275fc3d79318d8eb9a6d5f53efbb87115c458282fb25e34b8d7688", - "rule: signer nonce 2 @ 50000000 | keccak256=0x784863cbfebafe7f52b34279b301fefd3fe22a1d3a40d20a12f669a36efecc8f", - "rule: signer with code @ 50000000 | keccak256=0xdf3bde8c053f4f048fc1d3a40ed8c1700e056bc631adc33bf36a95663534f997", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xc990151441bd899dd9a9c441f70e395ae898e580c2d23dc162b10f4da2e2ba21", - "rule: occupied address @ 50000000 | keccak256=0xfe77891e1596dfc0e17c6aa4b342d2d4e20ae2c8d7f30162ec01134fb186a432", - "rule: value the signer cannot fund @ 50000000 | keccak256=0xbdf2d161642260839f7abd86b915c550fb7981b53605cbc47de42824a8632915", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x854194a30e818cbc3e9e62adbcd5e9e6a0892b7ff6f9cf8fc94496388e20f705", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xaa0b7d00ffbb61a885bed9e69808248023f4d9cf6a527f94591e79ae8391f6ea", - "deploys from nonce 1 @ 50000000 | keccak256=0x1e38b97533ce81f692e2447bf2cc32a6469210d30e0a6ba5a04e2c81663ffb11", - "the address already has a balance @ 50000000 | keccak256=0x1c0f949828b4bc72f1baf27f0b744b9f15ccbe227fcce4ea5c59bbdcc3b827f4", - "moves value @ 50000000 | keccak256=0xd2beb5e62d347eba371882f82a4e30318fbbc9d43b0e57df063b9049f53bebf7", - "moves value from nonce 1 @ 50000000 | keccak256=0x0bdc41e79d10e1e4ea7b68f35e5556790d45cda9551f6761707bef4496d94e59", - "the CREATE2 factory @ 50000000 | keccak256=0xb2ecb5cf3ea5d5fbaaf3fce280431d390fe86795538c8ad1fff617dde998e5b4", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x3ad22e63f14ded44a13f1e15bab3451f03d9c6fc4e33ade9a66d08626f29b75e", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x8909f08d1f86bb0af70c417b964ba8d79ff369bcb3558c6a84f232989e64fd46", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xdd4a8355d943e2f22af2fdec3c38e37c5dd7ddc63613c0d9e72b500b61136807", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x1df27a735363f4758e4bd567ffd2cde36f7f9f7f88b088a763f2dea01d3985f2", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xb80e17a2e7939e95262c7efb0f7809a708c46f9ffbacc61bb7012b9228e06cba", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x25606317ab5eba31abfcbc5f24421a37e94aed0e04e53ed4edda18bfb18d2df7", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x27077cb99c3f49dcf9c6f9041fe2ffb1b26437a31a32b82807c9a3411c9c2efe", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x17c7152fe5947693070eb1627f4f858975b5403cce1e0ae07ba25e3a292f6475", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x265bc4dd1e96384237e9b90cebd4be1d68f3a8f7b6a6607804bebca25894f552", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x751a90caf62483d4706d2367d403f1c9d793cc3d12ed41ab96f2098459986690", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x9c37a4c741b5dbecdec991084171b2f36a07aa8dd1ebea9f6568a0359c927917", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x2ec59b5a0ebe01e93f5d791d951f2cf0149ca9fbfa30aa14534ce3a2226117f7", - "a constructor out of gas @ 50000000 | keccak256=0xbbeb48fca5fe19e74924ea6bfd705899920f01410ebb67f8ce64cd0c0baae4a7", - "the signer sends it @ 50000000 | keccak256=0xf4e163092bc6483934a37e6069b79be53cba1090721dfa1c4b783db7c8f78a9d", - "the signer sends it, and it reverts @ 50000000 | keccak256=0x57ef3326c672cfbe88fc9e7828a9e7d8deba35e2876b18153b2f6429ff165660", - "a delegated signer @ 50000000 | keccak256=0x0064a10239803109ee59bd0d16911f7decf55a346d05d57e18dce03e84fa99d0", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xcd8b9ea08cc5d3e4877320057b96181c0483eaa28d99f08469468b15ea5d3d59", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x7c33d51d018dd7be35a4727c89a401d5d07ee0ff1712cf4a04fe3a660d95d800", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x55a77222c7212b63b30697325a075db2bcb1e0d3a290678eeaa96927a5422db3", - "limit: compute, nonce 0 @ 50000000 | keccak256=0xb60e1f212cff27717b50251f22920f60a266d67387cffb4886d9bf1097bdadff", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x9e2e2b613e18eabd9a69df5ddd3204e0f8d663621abcedef4e8367f0db09baa9", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x6c591038e8021803ab4a3f338e45878adf3917f1345899376d715e746d8d2f64", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x92c4b677efbf06476c5b9c9aa7e85e4cf3923af232d571eb6664ecd6fb7476a6", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x4286eada20e5f558e7c2ed6c826d15fdb4d3d50186e43da02a4d77655b7a4cd1", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x2d65b3a7fdb37ae17b12ab3c9b9dec67fd93bf92b365d1b86b26a3bebff461ea", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xf7a1feafa45b6895ff67602578ba339bf8e037bade29b6271e67d2e1797e3782", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x8800b8030288909004fea33f41c96fc7c97e77342c75d3c1b51dcae69390d796", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xdf3dbf511f3df59eaa39d299e5d2cb0a80712cbf8ab0ad577f4dffe6f1cea31d", + "rule: value @ 50000000 | keccak256=0xbbb1a321fa8fabf8d27760616c768bf9f2a0d5649438373c76fc4348d88cfb8a", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0xc3ab1c1af149f2cbe5733aeac1c9cdb42eadc2b47e270a5b721b14eed20c410a", + "rule: arguments that do not decode @ 50000000 | keccak256=0xb0db489839a78c2e662f000d2220ddeef36e06c5a473eceaaccf3e0866dc53d8", + "rule: malformed transaction @ 50000000 | keccak256=0xba96cfe68c780d656f805049a752b68a4049a7c1ef502eccefb3f6c6ca81e8f8", + "rule: a trailing byte @ 50000000 | keccak256=0x5c624cfbbeb559e89cd58716f98111cb2d4f07902c8e71d9df478997c0a84619", + "rule: not a creation @ 50000000 | keccak256=0x0386ff909ab7ea665c8b7c11d8181445da53b91efdc2c2941b6533036e92dc3b", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0xc9a0492b8f7f17629e2ebd8bebf7acff541dbf9458a9e262e147cfdaad714b52", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x84315464c623f5cbc5ee897e2bc8bfd119ad900e123143ac721555e0c2e3a3e1", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xc00f787f6cae8873132a89f2038212b36ee02270d3410df38338adcfad75f6ee", + "rule: invalid signature @ 50000000 | keccak256=0x0123d8ec66253bfee2c311b216a5d9f19cb3c15457dd4b99aba8678431cb3303", + "rule: signer nonce 2 @ 50000000 | keccak256=0x74f3e6b4e5ffc6831d4f2322f91a596707fd1887699f43e9f811f2645a0ba3da", + "rule: signer with code @ 50000000 | keccak256=0xc43364d930583df0460bc9dd42d3cc23386abba568218a3b5db7a8d530bf78bd", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x7e885926e896aac59f698ae640a0a2e6777938661d0f2a7cf7e12d3b1e3ecf00", + "rule: occupied address @ 50000000 | keccak256=0x34719a7157d75c75a400db9d1dde3c03682120e583f3392ec8b1ee36be0613ec", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x199eb3f0514dc7eb89d00b814e9be6ec96147ceb2614753a0e25b762024434be", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xa1fcdd4a0bbf7c9c08985315582f9c4c31a37525c5e6f08e2bb045066c2d16b3", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x0bf902ac6bebbd9e81996c57e45f893937320dcfb1fa92223d246e9cacae047f", + "deploys from nonce 1 @ 50000000 | keccak256=0xa520227afa0779933441e9c8d0a81b82d5d4796763a0deaec2db7543baf413d4", + "the address already has a balance @ 50000000 | keccak256=0x854e5d67d0b3ae6d8eb7cd5e516475df2baf36301993404093da7e2c78e2aea4", + "moves value @ 50000000 | keccak256=0xe68adf4ea6323e5e85daf9baa8f674dd6780d7c5e09aeea5f6aa950f25135522", + "moves value from nonce 1 @ 50000000 | keccak256=0xbd4dd91295040091c9daa24f413d6c9dac7987ab302fb756f51523feed7c0f69", + "the CREATE2 factory @ 50000000 | keccak256=0xa4eb75201156746b64933d762f2578d85eec1b973fd8f44a27f1a9b82b1fac56", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x814369e9694895a04efcdf10e46d291f77debf3360a7da90f162fbd8ff8b3f81", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x04c1ef35d5661cd9e663bfef971e77257290c620ff0b02ec2a7240ecda007306", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xbb72f34db268a2e3887ed09e962acd0594acbdaaa38c886d46fa16b4a9f5a24c", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x26959ab40d300c7c80e74399f2cd52a8104f2c8d2df3f2187868e28318a425c9", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xc4b37379e510c216a96aaf24979d06e3be3a2fc3a03d6538bf9253fb8e452639", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x064dd785d29f0bc752281e4bbce7c180d4d7914bde6eee54f59deac6d4839b91", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x5708cede78495e8a958a94377f3e5fbdb437a9a36b5e5b2572cfc3c2a619f1c1", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x74c1faf2ea41ef8023efd520ef2a149617e919657d26a3a67f866bf2e99a40d4", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x2ed3583f5a9b25f68e6a68771ed8715b836135a3ce6e7351c0031adbd43ddd46", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x1ddb229bdc98071111d5a644e98a5e3402c89e440056044b50e42d5bb1c98546", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x6abf2671730921222c7e0486fc58421a29c3b286f2075c6312bbca64a352a656", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x54c19083cb9b9253786f583e80007a9c467a2e1783e3e4dd4aabfb7f456b0829", + "a constructor out of gas @ 50000000 | keccak256=0xed4e182648a6a0eeb5f61018a3eaca23a60974f3a6167f31218ac538280726bf", + "the signer sends it @ 50000000 | keccak256=0x0ced203a45283f8624433c0835beec78f12792ddf7e92d2f12fea1cddea5560a", + "the signer sends it, and it reverts @ 50000000 | keccak256=0xe5713953532d5bc302ea6160476e728624ca3af937bd6e89fc8553f89f9ff2dd", + "a delegated signer @ 50000000 | keccak256=0x38d2ce3b0bb3da4d31d02be4e87013cf7daf22ffc487562e464dc7d41256dcd7", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xf4d03fbc577835fcd11e7288e0cc4d2ed642d48738d44ff0c8280e768598c35d", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x35e254125b51703420e8deb970c97aa8074627918996d8e97bc5671b524e674f", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0xbe19e2acd0ee697fc43ab05cd0cc9ecada8e8d700b158fda10ec6f6bc5c1e53c", + "limit: compute, nonce 0 @ 50000000 | keccak256=0x2944b7d9bf52ea422166c67d00937280a9ee1c88958fdb4b119298455cc6e82f", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x797de99052c6684ca98831510e1746166d2a9dfc6939e65a04d79705c6fac121", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x5451cb823c7026bf7cd782549d118c84c8fadc0b2b0791aad17ea04640b873c2", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x4e3a6609240565a3b8f9ec0278c29e08a15dac083bc70c93cec71dc5b2d4a284", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xb4a3e25c6b0253329363c075ad24f7810fa574d9c6b4abf47cfedcd463aa7df8", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x45b1d087eaecc7df26d766ec791eef23560c46269e58faeaf131758e7af705a7", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x5845d201af918e1750abfcd4332f0dccae77c77944db18976357cbd43029fffd", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x4ca715d952d52d966160cd70482e6dec9d55396b808afecf01b76f7bb9e6815c", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x769a1fa287ccaebe0944d36d9405909abf987c3260d54922249afb4684096b41", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0x401e8a4d34c0a257a9f6d5eb3c191ef9e04259932d15df8f69ef9d284c44597d", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x67d17bdcceef5522f067097fb8b5bb9535b7e3c50edfc735b7a17281baa83a79", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0xee5119ad3ae3a1ed755fa53d53e1dce456fb500e2142cb3ab4cddbc6c5ef2a93", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xd36808e24a3e4424b5c1983330c2b072a37aadd913bb8f7bfc6f40a93c7aa762", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xee6c92b0634bb05ad67f16e49fbee64807792ed5210108bb7227a6e0a44c52ea", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0xda6467b28250e76945cd72fb1c61e87e4ff082c572e77c699398a8986702ecb1", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x476ebf8d0d9b175a438951231459d7eff3e3d4cff678fdf874926c58c66e1103", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x30e7f681371492a39eb7b8cce401b2d3305ac108573b9b31904caf0d84c45172", - "not dispatched: version() @ 50000000 | keccak256=0x1bcdfb0c443aedd9aa2dc040e14363bb98e50e81a143c794ed140aa08997127a", - "not dispatched: no selector @ 50000000 | keccak256=0x472f5c2dcd74cee319c67289882d7ae5de0827e9ab51e3189cc994f9030a8c41", - "not dispatched: from a contract @ 50000000 | keccak256=0x1c294e98bc947c88900950d97d417766b82b79a0730db66c83325f049a72e59c", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x82ece1017f1c33999f1543b189848287c03fafd8abab52e663bde37910d48caf", - "no contract code @ 50000000 | keccak256=0x61a84ade88a26edc2149aadbdff8cf04d12724cff24b5177848f93ef00e41e53", - "a system call @ 50000000 | keccak256=0xa0f9654dc5d720d585bd5262f59c3eb57dfc5e0a2e2cfbb4a4d4195d1bb8e582", - "rule: value @ 400000000 | keccak256=0xd303c37d1d7da78c74d1a96a932bcb273b9fdc308308f4006413974f816f1061", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x90ac683d459875174607b7de159993d754ffbfff2d1bde2f45327e31eff58a30", - "rule: arguments that do not decode @ 400000000 | keccak256=0xc2291f0a80a04b8650aee76c9bd25d4efb87a1197f98e511fb254121d900eb1a", - "rule: malformed transaction @ 400000000 | keccak256=0x483bd928fe503c1c518a50616f83f71abf2e5cb62bfde657f3bb76f422c690c1", - "rule: a trailing byte @ 400000000 | keccak256=0xf2f566ffc210e9e80e3d61f995cb7fbe4aeb13753a717e637754e5f586dd28e7", - "rule: not a creation @ 400000000 | keccak256=0x51107b2d6b41035c93f36a9473aaf257606f435d3e4309f399308a140654e8a5", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x4ebf62eef276a4b331f8a06f51dea3fd8498df29aa0f4601e45378917ac30b4e", - "rule: signed at nonce 1 @ 400000000 | keccak256=0xe52fdae23846ea20448d0f1718077ac94f32b9974fd0a7715a19bde74255eeae", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x90e4f5261d501523f740ccc40dd40eb30e9e5b7f89cc7e14e9f27cba2f1b9a37", - "rule: invalid signature @ 400000000 | keccak256=0x520a8ea364be745edac070d2b7647b72009651c15cc92c89f31e7275d92b5890", - "rule: signer nonce 2 @ 400000000 | keccak256=0xbd17b75de1e42505f2ee5082ccc16a3311baa780b8692a84d77ceec24b4b893e", - "rule: signer with code @ 400000000 | keccak256=0xec1da80a88bfab4fd9508199c44446a7a2712b502e2e01c249836b10e5d0c7e4", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xf194b8d24aff31661c0ab3bd59a18f006b92ce704683ad7237294a2bd7c7e423", - "rule: occupied address @ 400000000 | keccak256=0xbdc9f465f12c2e0f064ee17721cb8b7124e5bd348daf8ff08488ea72aee8df01", - "rule: value the signer cannot fund @ 400000000 | keccak256=0x1e190910f68843e409de4da0c031f3c1e29b9bbb9310b781891c55b1cad48b6a", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x404d2ce242ff28ee98306359e5ad4b216e74387e803f08a5803d3c47aa0ae764", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0xaa02134b6ab8240d6425e5e3ee34b4d035790c4d78995cc721001941564afcb5", - "deploys from nonce 1 @ 400000000 | keccak256=0x8b1ccbd6d099d0e1b1371aec903a117c33a2a3b398a355098ab4a37e239d2102", - "the address already has a balance @ 400000000 | keccak256=0x23b1e10d7f6d8135f85779bdaa1ee01943b79b711810cbcf2355dce52626cfb8", - "moves value @ 400000000 | keccak256=0x92c5f7758579e2ea93bd39c77e516e03476c6c66eb65aac6c31ccc79bf0d5881", - "moves value from nonce 1 @ 400000000 | keccak256=0x8d87dc75052ef30e13e395be1b673b7a874f843c85bfd0bf8c33ebc09188827c", - "the CREATE2 factory @ 400000000 | keccak256=0xddc26d1ec888e72def99e14f179859577a6d5c263db65710414136b00f784636", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xcbf6d3addfc90a9b82ef149891785585747b23b84e6e6feea48408c0927b05fb", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x4e8ae911031010a24c172fd27a23a45e572301e31d8e3942c9b78958fc1c812b", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x11d6d8106eec4144fb4b27aa8048e61ebd3e28ff5e34a3ab258e58870c2029be", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x58da2c85e1b4aed114d883890f022c19bc6ab5306bf321d91499d43bc74fe1ee", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xe0964b9f5609b93ab45e0fb18d0d641dc29de37d524eb743b5010334d5789fce", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0xf652556af0037df5691da20eda38055aed1ab41a0ad98fae98979bbe4e1c165c", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x6c0ecb273aac09d6ad165e7b627ef64bd9df6fc70e6e82c353dc440d5c96b8f7", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x7a3b943b6d397f733c8cbf3f4434feae3b84079f10aa6fd9ee7b2873aad76b19", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x95d24bcd22a84c68dffab292724f1e7c796a6b75c3df83e538bf81323747ef75", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x433ce029fff43e9d2a3293c22c889d4f1daff43d301460404e24bd71f846cba9", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0xf873d861f34095986d68362bd6931829e01d2ec3ce8e4db6fdb888ad786ddd64", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0xe982dd88cd68a044a422609dc8934c114c048189a82860d730ac0334256c82cd", - "a constructor out of gas @ 400000000 | keccak256=0x27652b56760f6fcf1213bc170730a622ecb6c8c7fcc4269ee80d62304eb79f4a", - "the signer sends it @ 400000000 | keccak256=0xd78efd6fd17a7921cee7edcefbf4049630fc2fe902c65969f3e2e1d10db65c10", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xfadd6b105b17e3e8173859cc7ea6e21f3058d66859c3f772e8b993e6022f035c", - "a delegated signer @ 400000000 | keccak256=0x75dcb0c5b12fcfdc2ec9d5fb412f2a356d2b6b4c08498f592cb77d695f24fade", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x912a471ac573f1137c7ff715bbd4c716d896290ea34c38918f341dd5bd4fcd7c", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xd7cb0a921f3295e113674bc4766d4d1c846e169fe1aeb479f30060b613904a68", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x34226a40534a6d1a5db718843ddf4ed03dd8e88c2dc532a9d1277a908efbaf17", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x220083af3453245d7157fce25daf5ae7b146135fe68a4e67fb957b3081ae5f1f", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xfe881a80d9f1ea7971209d7555df06b46c5657581f03b17ba771a2c62a2c0875", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x1b9c5fa7ce5f8c7720eb855681d2ce4c242161487366162aa11f92a0fe795f0f", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x5ae6445d4fc7034526b72b03f278548083826e5f864ea499fca9a38c8fba127c", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x5adb3dfbb10b12745e6ae864bd4b245ba9a18b438615f6d5f3caa277aeb78f99", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x1730186a0ab9121039c156b8c1aaa81326de8a4169a409783d8960467ca16a6f", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x713d112b4aac78b020780ba0f2d604f45ea2e2f35eccb200ff28cedca809939c", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xae24e0359fe82a35095090953c820f194176cb9312f8f0c76d0a3e9b2d310747", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x9891361cdbebda97af570c4a61f0857a55e8696f1707c5a7df546895ab4a0476", + "limit: the default limits @ 50000000 | keccak256=0xb9b6a4f4f4da4ff07d70af782977146943836dd091c23bbe9c4ed7a9e4bb9f27", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x23ee0068e75b5a67d97e1a45bc5f5b66e34c2dc8798fa9e752a11080bee93dc1", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0xdd925caae45fadd96556e1d7f018b1d83045ad2734d2f4f525a5f911a00975e0", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x40a829bd5cb26d43f18f3b177e051c1387857cd7265a7440e5a4fae346a31cc8", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x56f60b8f8bc96d3815e7a120f09fe74d1cbc3c85cb4d80a5886b98f4a6158122", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x2abbe75645d93afdbcc7687b6c0afc479613f57afbe28463f223273e683bbee5", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xf279c5307fac715d603ebbe9b8c74aa223c5594b798abb3de195e0cb23ae6bd5", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x92e09638ad6a4e0af87f695337f3aafd6fa9196da822f38cdfbbebc7e0a0c39c", + "not dispatched: version() @ 50000000 | keccak256=0x7c5ee96f08957b0fd43ec3609c12cef5bd0074792d595a9f1ea971ca31fd7875", + "not dispatched: no selector @ 50000000 | keccak256=0xc0be8244d5572b8b9fb9ad4d4c4e0db85d8ffca5002f37279b9c52ddc3fa5b02", + "not dispatched: from a contract @ 50000000 | keccak256=0xa0f75061e50b6327aaadf92e71f9af22665b274ea379aa98bf396b8e08071d20", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x268116d81aba3d36b1bfd0f3473a60adf58644ac1dfc8886a2fb0224bd4aa82b", + "no contract code @ 50000000 | keccak256=0x253953af0211838296cd30ba77a533ea7798a45b1c5accd1a2b739e290605d47", + "a system call @ 50000000 | keccak256=0x4ff198380163db3fd96b41cac5955f3c4723a559398265bfb2b32405dd00edc2", + "rule: value @ 400000000 | keccak256=0xa18ebeca543b35b95bcd4fd93a0679cdd9486f1d1c8d0feef804ffc1b9ad4d0f", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0xf986d1cac4109cbb2466259d2110ea80ce1f4de09f3fa2038a51d0f81b4384ae", + "rule: arguments that do not decode @ 400000000 | keccak256=0xeba2668832f3afd0ee12d3a70f506e50ff8c491017c079245bde2181c8c8ba98", + "rule: malformed transaction @ 400000000 | keccak256=0x287361e49cc3a3985b31a7c25a558074861a227e9bbe7643190c426e20720289", + "rule: a trailing byte @ 400000000 | keccak256=0x77cf0ce7ea670c10f24127fc9549928877d70bff052f8b82cdb36829865a65cb", + "rule: not a creation @ 400000000 | keccak256=0x41e892cdfdf1964cfe253027160234eafc5cd532e42ac66d851015a220436675", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0xb8772e8dabb39783785b7999e3c138ead3904b9f5efffe173c44a809b34ccc40", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x302873560dce8cb91d53397f6189cc657823d918512e98c299fdb45b3a9327d3", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x2fd5a2d895fd1dbbf20d73eee0c2e29eebaec2e6476f5d9bc4b614e4f9b3137c", + "rule: invalid signature @ 400000000 | keccak256=0x491f9c8eb64f398c3399171c286cd7db7d01c23e0f256dba72dc36d7b91cfc4f", + "rule: signer nonce 2 @ 400000000 | keccak256=0x91cd17bd5232587c10bc61fec1446a8058a5399723976f4b0af1745ddffd22b1", + "rule: signer with code @ 400000000 | keccak256=0x1a75998f8e5a2654da4b90af611fdc21e4a0b21b3bb7ccec1c3c41066b180eb9", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x282c1e56d00c8e98ddf030dee7c443ed146bd37bd1950b38fc37a9925eea5a7f", + "rule: occupied address @ 400000000 | keccak256=0x173768aec05d99a3b4f2f8a514bc8189f1f0d699d6ccda32e8ea14238c3228b6", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x496e2dc7b600882979349caf494d574a55f4ca03435079b95e932d84006116b3", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x3e2c83f410dee0ba6ba3907641250811618c539150ff18370b00c084bbd718a3", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x5008280aa7bf2ecdbcf76ed8d79a74798b58628b93a03683b15979440fd953fc", + "deploys from nonce 1 @ 400000000 | keccak256=0x62aa872f3858800f4ea40b9d1a956f89c3cf8bd3ad7fc22f872c823e8a3c0cfb", + "the address already has a balance @ 400000000 | keccak256=0x3b5b6e733d25fae001d95c053553c30a3e557099851432da7f24b5d9dcc98fa2", + "moves value @ 400000000 | keccak256=0xccd0aaf8e8333f0651d6846a9caff6d2a7561e9545d7db98afe7fb41b162fc85", + "moves value from nonce 1 @ 400000000 | keccak256=0x97de89df5cb3776fab2e0dbc5c8ac479326d7b0413780c9650a9583d376b6b71", + "the CREATE2 factory @ 400000000 | keccak256=0xf2a19245595181d80dc2652cedcd2b6bc2e56a2aa6e0374b8f03490012b0d723", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x4d0e173f5592e65112162b83dd01c4bed23f58304b289aeb7f0a6f0ab86e795d", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x1ec883ee368ed36093aba984eac350045b962d2e6ee6b4b635e0a901f79426c0", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x1e3d2de4feb46b93cb142d18a19732fa0f82c41ad5d7e313b76eabcbc5eca33d", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x94e3351af11a471277dd64ad107ca6afe43192ed20a0bdfb4a226dbb673cf37a", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xf070389fce7571465c57ab2c64a99bf68a33c60afd6cb1f80229e1b07495193d", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x690f7ae1f153f7b29374fee5e68181039f1372b68fa9df80931a17dc28e6cef3", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x3817844eb1ece2cbc97c7b6b7ecbdb1e543ce3bbc098431dbd45db3682c70f82", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xecc6b6a5fd7719e95d1a5775558038aef9d7855b41980a9dd9d203040ab45aa4", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x48df122101a9b81d974c3237bebc381d79551cae986badab597bb412d7dcb6b8", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xe457f48c9514540b08c08824e66ef7ea82cf99fdb4c640aece47340eb0d26a31", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x1deb9dc2b89d6ee0d0b3f112b9b7d57f64e9b982cc40c271dacc9794dbae5355", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x74086a0c3fa9ed53cc49bc1df8c405d0d2624ba5b99ffaebe58dc52d2066edf1", + "a constructor out of gas @ 400000000 | keccak256=0x6f036558fefbd5f702390c01155793948729106ff9273141de789c93eb9fc6e9", + "the signer sends it @ 400000000 | keccak256=0xfe626210c579451c32e2f626c26834b42d17cddaf18882e101beb02014bdf06c", + "the signer sends it, and it reverts @ 400000000 | keccak256=0x491266db1558879e50eebae46bb33d9d5ea0f16a34ee3b13c7ac2e263036ee93", + "a delegated signer @ 400000000 | keccak256=0x8f487f733dbfbaa181fb520e69d984a19deec1caca1d050c0f3b166a049b6a27", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xa107860c667709332d37c4ec41fdfd0cceeaab19ef93b2e55c679184bc76ac7b", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x2b21304f22f83d0bbb83974ab351c33b78ad2fcd8d052fa838bbe3bad39ecba9", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xa10400d847c8bb7dff794681de273610f0abcbb592d60e221e015880dce5904d", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x164eb97b6134fc61fe58d2803253adfad06b514a1443bf12e5b7c23e56b996d8", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xfda55f9a2100228c51c54da623f5a69891fa02f564887f61646a2a44ab0e45a7", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xaa6722d542bda19e9050f94e4b82676d3630f6f09be8eecbf67e43da6ef90cc3", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x5ad715ed7e110f818526030bb5f13738d4b7dc330118c23e9a331ae3526c7a05", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x6494bb9f4cd13f0f60b1b2d162386905a3fe97299b7f42d844fec3e4863ecefa", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x50426648fa3561c26af727374ede6f44be7f33fef83fd732679ae9b48fc7bfd3", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x5fcc23bc18404f8b3325b694cb671119236f914248b22f9508c7f3fdfcaf3d93", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xb549fca44063b07fbb35746c9a92776bf53c9b2eb63557034f99cba42aadd658", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xa84f7ecc5a86208551f0527940f6288e998f795e6621a6c9f67305eb49bf0eb8", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0x53c838e3841fda75efc979f830a995785fd6053d207e339657d4326c087b15c6", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x6b31a69eab1eea9f014065acfc3616431a7153c9a951dbbfbb8dc4c02c496d10", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x70c93c1e49bb3f82ee27b6df2e74542f134daf45511344c7b06af84148b15c01", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xa41b5f6fd60a0a7154a11d40792fb6c273c69b21e49c5e4e4500c48a7c74ad95", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x767616227fc4acae739ee2d88a2d706b4dd8506312cad721ca51dd8f3e46e5ff", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x422863b3415771d5169477ca5fc7f3c49012fce27dd20287dcb57129ead7977f", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x02747b270c6ef30361086a8b120b3a9a3b7368ffc212402eadf2ea09833dc6e9", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0xfc8b374ddae00ab903e7c7eb7e61a3b6b327365514d104289baca17db3c63289", - "not dispatched: version() @ 400000000 | keccak256=0x21d0fa310f4524f0b6e8506cf6ba99eb84418b6e3f0ddcb2e0deb6003b207fd0", - "not dispatched: no selector @ 400000000 | keccak256=0x68cfd5c7dbdde76046afb03872c58b7c798d53eaea467a999c9f7b3635da9eed", - "not dispatched: from a contract @ 400000000 | keccak256=0x60fbdbf02f2571dd99675222f8697d42508b159a9d424852f19aa3a1f2148c51", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x906b081db7ac18f4d82e58ea150ff78a00919fd4d4234d2b0f9f5ac93a541cbc", - "no contract code @ 400000000 | keccak256=0xafac51c3747f80833d5f3296750254d077e3bf6c2d6cec6c36cd8555993ac0dc", - "a system call @ 400000000 | keccak256=0xff3ddad83eca747c58bae960be9ebdba8ab07a3794a8014a8b1721ea8778a416", - "out of gas: the overhead @ 161535 | keccak256=0xe2b170867ee82b5c184c55d46183a6b0f757d90341f439ef72e7a43f2b775a85", - "out of gas: the signer's account @ 162536 | keccak256=0xdfe860c27a35a9c33d54e3e47c64c4afc141c4bb6cabfc87f45cf12df47c8052", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x07b0e90b13e66371d8d7abb066a23367672a4bc8899b77d381aac2b0e84f53e4", - "out of gas: the creation's charges @ 163024 | keccak256=0x589fee35bc1e64ba2ee3e7a6c5ad7e9eb8f84f54c82657a285cfb10f31823b50", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x1c92a67f868f90f76bb5072ab6e2dbe42a4a60d64d31e739dafd3f5dd1b53178", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0xfc312c015b3d41364fc2ad03a1b68ab5e28f1d8b2b6cb360058df6360212c280", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x0f84ba12e978600a79b6d268f088a54cd2a15d063ce1f8ebe91dce8e99f7d828", - "rule: init code over the limit @ 150000000 | keccak256=0xa2498a026c354cd59572ab576b85a982356e60b06704fb79a8a6fe21717a91d3", - "rule: init code over the limit @ 2000000000 | keccak256=0x8e0e07266b270414f4eb958872388f1a26baf80ff2262daba5da7553b7435e8e" + "limit: the default limits @ 400000000 | keccak256=0xf2871d0172174549bbfc91d7cf684dfeddc058a330911913403976c47f656c8a", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x055cf0c41d75363ebbb2ce416ddd379b3f8f6f931acd8c2852bfbe27da79dfdb", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x1c13190dfd8c7ba6f1d4e4b257ba9c4236acd01636e6a5655053b7aa7884925d", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x343cce5a7e77fff5350bcc29ab8a34044f599cb1bf018cc46624dcf3026c45cd", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x1f08a9c99ca1d6c759b171eccb25d3e6820cb40c38bda50976c993b5b2686f5b", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x366811708e9a1b60152807d8c5dd3984ed1b88a0016c86ab2f0aa4d763b09ae2", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x43602609a20ae5de69612764d022fd449af3d17c1b8cb39698c9cdcb16dd34c4", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x539be37bb5236f91463bf14405e2d8fbecc38ca8d6913c376af276b39258cce0", + "not dispatched: version() @ 400000000 | keccak256=0xf21dab241d0565c2393c9e0c37035f6be5de3b03a33921186dc6044f506775bc", + "not dispatched: no selector @ 400000000 | keccak256=0xec805be7015aa71877a9df3bea1213c555c71c0b8607af8d6044f45fee86f790", + "not dispatched: from a contract @ 400000000 | keccak256=0x77bca1e5ada4917e8ff0dd9e9d481e75f3df2de516327c1ffc50926730d6bf5e", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x2a9952071b259bebd707febdf9f9569b4a6401dfef933777e104c432daf84942", + "no contract code @ 400000000 | keccak256=0xfce752eedcc5e1032c0c2d2da6c959bdc5bc642bed36645a002b1f00af0266f7", + "a system call @ 400000000 | keccak256=0x2753d26c7e11d1b72c62b08fdc4f837edc93238506589ed4137a1ae5aac6c656", + "out of gas: the overhead @ 161535 | keccak256=0x46d0e2acc5da4810497ed4749f8176deeeac29fc6325babd64a609f4e02d369f", + "out of gas: the signer's account @ 162536 | keccak256=0x22574237323abc6ea7696732db91b88baf87ae39d55aa4fe95e599e215091c66", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x003485722c66eff085661021f5f19626c15898fc5bf93a8beddc1cd2c59d9456", + "out of gas: the creation's charges @ 163024 | keccak256=0xa576d982542405802977013b3806c9bd522dcbaae1ee07fb81b6122b57e032c7", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x5de05094feaf6cf89a99eb14871f718dcde64a0b52deb7feb6fa6e9de8db0bd0", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x37fe0d37c5b7662773341c622b439cfd9cb8159e103834bf92a11032cd307dd3", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x445fccc13f9822d385a925895a79bf1a230fad9dd1e4001d222c4009cbf88046", + "rule: init code over the limit @ 150000000 | keccak256=0x7ec570ba276f8b3c81c80cb731e98c1482d7a42cc327ed79e606851b608a30d1", + "rule: init code over the limit @ 2000000000 | keccak256=0xa1e17bd2b8390974bab623c8d659da58eae6ac84ef35102103a07b429f5d705b" ], "summary": { - "bytes": 2392466, + "bytes": 2577938, "cases": 139, - "lines": 11444, + "lines": 11452, "runs": 556 } } diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 26fb4b91d..79bb3ca60 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -319,7 +319,7 @@ fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); assert_eq!( outcome.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "a hint that was not forwarded is not counted: the body is what the transaction keeps", ); assert_eq!( @@ -515,7 +515,7 @@ fn test_consecutive_hints_add_up_on_the_transaction() { assert_eq!(outcome.limit_exceeded, None); assert_eq!( outcome.usage, - LimitUsage { data_size: nested_hint(len), write_records: 0 }, + LimitUsage { data_size: nested_hint(len), write_records: 0, state_growth: 0 }, "the forwarded hint stays counted and the one that crossed is not", ); } @@ -541,7 +541,7 @@ fn test_data_size_overflow_blocks_forwarding_and_stops_the_call() { assert_eq!(outcome.limit_exceeded, None, "a stop below is no stop of the transaction"); assert_eq!( outcome.usage, - LimitUsage { data_size: nested_hint(0), write_records: 0 }, + LimitUsage { data_size: nested_hint(0), write_records: 0, state_growth: 0 }, "the transaction keeps its body: the hint never left the machine", ); diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs index f20ffb471..5a4b4a7af 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -521,10 +521,11 @@ fn test_the_answer_is_what_the_caller_resumes_with() { } } -/// A callee a value call started hears the stipend counted, whether or not the transaction is -/// detained: detention counts the stipend outside compute, so its allowance carries it as the -/// callee's own gas does, and the callee hears the stipend more than the same callee a call -/// without value started. +/// A callee a value call started hears the stipend with its own gas, whether or not the +/// transaction is detained, and so the stipend more than the same callee a call without value +/// started: its own gas binds, the cap leaving far more than the call forwarded. What the callee +/// runs on the stipend is compute like the rest, so once the cap binds the stipend adds nothing +/// to what the limit leaves. #[test] fn test_a_value_called_callee_hears_its_stipend_whether_or_not_detained() { let stipend = 2_300; diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 84ab99255..71f9ac166 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -740,8 +740,8 @@ fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_is_a_f assert_eq!(outcome.limit_exceeded, None, "the failure is not a data-size stop"); assert_eq!( outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, - "the body stays counted", + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 1 }, + "the body stays counted, and the sender's account, which the failed deposit created", ); } @@ -802,7 +802,8 @@ fn test_the_callee_sees_the_system_address_as_its_caller() { } /// The account a deposit-like transaction creates for its caller is the transaction's own -/// account: it is part of the transaction body, so it is not a write record of its own. +/// account: it is part of the transaction body, so it is not a write record of its own. It is a +/// new account all the same, one of state growth on the transaction. #[test] fn test_the_created_caller_is_not_a_write_record() { let fresh = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x99))); @@ -812,10 +813,13 @@ fn test_the_created_caller_is_not_a_write_record() { ); assert!(fresh.result.is_success() && existing.result.is_success()); assert_eq!( - fresh.usage, existing.usage, + (fresh.usage.data_size, fresh.usage.write_records), + (existing.usage.data_size, existing.usage.write_records), "creating the sender's own account records nothing a transaction with an existing sender \ does not record", ); + assert_eq!(existing.usage.state_growth, 1, "the Oracle's slot, set from zero"); + assert_eq!(fresh.usage.state_growth, 2, "and the sender's new account"); } /// A deposit-like transaction that creates a contract pays for the account it creates for its diff --git a/crates/mega-evm/tests/tracers/harness.rs b/crates/mega-evm/tests/tracers/harness.rs index 528a056e2..289518da9 100644 --- a/crates/mega-evm/tests/tracers/harness.rs +++ b/crates/mega-evm/tests/tracers/harness.rs @@ -644,7 +644,13 @@ pub(crate) fn assert_every_frame_stops( panic!("the transaction is not stopped: {:?}", traced.outcome.result); }; assert_eq!((stopped, stopped_at), (kind, limit), "the limit that stopped the transaction"); - assert!(!frame_local, "a transaction-level limit"); + // A counted limit the transaction's own frame crosses is that frame's budget too, which the + // stop names; the compute limit is the transaction's. + assert_eq!( + frame_local, + kind != LimitKind::ComputeGas, + "the frame's budget or the compute limit" + ); let ExecutionResult::Revert { output, .. } = &traced.outcome.result else { panic!("a stop settles as a revert: {:?}", traced.outcome.result); }; diff --git a/crates/mega-evm/tests/tracers/scenarios.rs b/crates/mega-evm/tests/tracers/scenarios.rs index 1f1935d75..d15cbe83c 100644 --- a/crates/mega-evm/tests/tracers/scenarios.rs +++ b/crates/mega-evm/tests/tracers/scenarios.rs @@ -91,16 +91,16 @@ const ROOM: u64 = 1_000_000; /// /// The bill is the receipt, the EIP-7623 floor included: a gas limit below the floor is refused. /// What a scenario holds in passing is gas it is not billed: what it is charged and given back, -/// the 64th a call keeps back from its forward ([`kept_back`]), and what a rule, a limit or an +/// the fiftieth a call keeps back from its forward ([`kept_back`]), and what a rule, a limit or an /// assertion needs it to hold without spending it. fn gas_limit(expected: Ledgers, held: u64) -> u64 { ROOM + expected.receipt() + held } -/// What a caller holds beyond `forwarded` for a forward of all but a 64th of its gas to still -/// cover `forwarded`: a 63rd of it, rounded up. +/// What a caller holds beyond `forwarded` for a forward of all but 2 per cent of its gas to still +/// cover `forwarded`: a 49th of it, rounded up. const fn kept_back(forwarded: u64) -> u64 { - forwarded.div_ceil(63) + forwarded.div_ceil(49) } /// The gas limit the keyless deployments are signed with, which the call's forward must cover. @@ -264,12 +264,12 @@ fn test_nested_call_inner_reverts() { history: gas::body(0) + gas::history(LOG_BASE_SIZE), floor: gas::call_floor(&[], false), }; - // Held in passing: the value call forwards all but a 64th of what the caller has and pays its - // two records' history out of that 64th, so the caller holds 64 times that history; the - // callee pays its slot and the slot's record before its revert gives them back; and the - // forward must cover all the callee spends, which the 64th kept back does not reach. + // Held in passing: the value call forwards all but 2 per cent of what the caller has and pays + // its two records' history out of the fiftieth it keeps, so the caller holds 50 times that + // history; the callee pays its slot and the slot's record before its revert gives them back; + // and the forward must cover all the callee spends, which the part kept back does not reach. let spilled = gas::slot_state() + gas::records(1); - let held = 64 * gas::records(2) + spilled + kept_back(callee_regular + spilled); + let held = 50 * gas::records(2) + spilled + kept_back(callee_regular + spilled); let traced = Traced::run( funded() .account_code(CONTRACT, parent) @@ -549,9 +549,9 @@ fn log0_size(data_len: u8) -> u64 { /// A first frame whose start crosses the transaction's data-size limit, at the smallest limit /// validation admits the transaction under: its body fits, and the record and the transfer log of -/// its value do not. The frame is answered with the stop before it runs, so it runs no instruction -/// and its value never moves. A body over the limit is no scenario: validation rejects it, and a -/// rejected transaction has no trace. +/// its value do not. The frame returns the stop before it runs an instruction, and its revert takes +/// back the value revm moved for it. A body over the limit is no scenario: validation rejects it, +/// and a rejected transaction has no trace. #[test] fn test_data_size_limit_stops_the_first_frame_at_its_start() { let limit = TX_BODY_SIZE; @@ -570,7 +570,8 @@ fn test_data_size_limit_stops_the_first_frame_at_its_start() { call_tx(CALLER, CONTRACT, Bytes::new(), U256::from(1), gas_limit(expected, held)), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); - assert_every_frame_stops(&traced, LimitKind::DataSize, limit, 1); + // The frame's budget is what the body leaves of the limit: nothing, which its start crosses. + assert_every_frame_stops(&traced, LimitKind::DataSize, limit - TX_BODY_SIZE, 1); assert!(traced.inspector.traces().nodes()[0].trace.steps.is_empty(), "no instruction ran"); // The record's history was charged on the transaction's gas before the frame and comes back // after the tracer read the frame, as a failed frame's spill does. @@ -578,8 +579,8 @@ fn test_data_size_limit_stops_the_first_frame_at_its_start() { } /// A child's `LOG0` that crosses the transaction's data-size limit and, with it, its own frame -/// budget. The transaction limit is the one the child's stop names, and only the child reverts: -/// the parent resumes, writes a slot within what the transaction has left, and succeeds. +/// budget. The budget, tested first, is the one the child's stop names, and only the child +/// reverts: the parent resumes, writes a slot within what the transaction has left, and succeeds. #[test] fn test_data_size_limit_stop_is_caught_by_the_parent() { // What the transaction may produce besides its body; the child's log is larger, the parent's @@ -601,7 +602,7 @@ fn test_data_size_limit_stop_is_caught_by_the_parent() { history: gas::body(0) + gas::records(1), floor: gas::call_floor(&[], false), }; - // Held in passing: the 64th the parent keeps back from a forward that must cover what the + // Held in passing: the fiftieth the parent keeps back from a forward that must cover what the // child spends. let held = kept_back(logging_regular(data_len)); let traced = Traced::run( @@ -617,8 +618,8 @@ fn test_data_size_limit_stop_is_caught_by_the_parent() { assert_eq!(child.error.as_deref(), Some("execution reverted")); assert_eq!( decode_stop(child.output.as_ref().expect("the child's revert data")), - (LimitKind::DataSize, limit), - "the child reverts with the transaction's limit" + (LimitKind::DataSize, room * 98 / 100), + "the child reverts with its budget, 98% of what the body leaves the parent" ); assert!(child.logs.is_empty(), "the child's log was never made"); assert_parent_resumed(&traced, "STOP"); @@ -652,7 +653,7 @@ fn test_frame_budget_reverts_the_child_alone() { history: gas::body(0) + gas::history(LOG_BASE_SIZE), floor: gas::call_floor(&[], false), }; - // Held in passing: the 64th the parent keeps back from a forward that must cover what the + // Held in passing: the fiftieth the parent keeps back from a forward that must cover what the // child spends. let held = kept_back(logging_regular(data_len)); let traced = Traced::run( @@ -758,8 +759,8 @@ fn test_detention_stop_crosses_again_in_the_parent() { // Held in passing: what the child holds when it crosses. The charge that crosses, the child's // `JUMP`: detention stops a charge the frame's whole gas covers, and one beyond it is an // out-of-gas. On top of it the receipt, so the crossing step, which reads as spending the - // child's whole gas, shows a cost the receipt cannot have billed. And the 64th the parent keeps - // back from a forward that must cover the child's loop and all that. + // child's whole gas, shows a cost the receipt cannot have billed. And the 2 per cent the parent + // keeps back from a forward that must cover the child's loop and all that. let at_crossing = expected.receipt() + MID; let held = at_crossing + kept_back(compute - before_loop + at_crossing); let traced = Traced::run( @@ -889,7 +890,7 @@ fn test_precompile_child_frame() { history: gas::body(0), floor: gas::call_floor(&[], false), }; - // Held in passing: the 64th the contract keeps back from a forward that must cover the + // Held in passing: the 2 per cent the contract keeps back from a forward that must cover the // precompile's price. let traced = Traced::run( funded().account_code(CONTRACT, code), diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap index a205dd458..6e59f94ce 100644 --- a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap @@ -8,7 +8,7 @@ expression: "&redacted(&traced.call_frame(true))" "gas": "[gas]", "gasUsed": "[gas]", "input": "0x", - "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000136", + "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "to": "0x0000000000000000000000000000000000400002", "type": "CALL", "value": "0x1" diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap index 6d31977f5..1288ccf71 100644 --- a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap @@ -10,7 +10,7 @@ expression: "&redacted(&traced.call_frame(true))" "gas": "[gas]", "gasUsed": "[gas]", "input": "0x", - "output": "0x84b902670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000019a", + "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000062", "to": "0x0000000000000000000000000000000000400003", "type": "CALL", "value": "0x0" diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index a1c80cc18..fd9b08fad 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -38,6 +38,8 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty ## WHERE TO LOOK - Add or move a deviation: `src/deviations.rs`, its entries taken from a `--json-outcome` run, then `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. +- Change what the outcome digest records, or how it is encoded: `src/digest.rs`; every change moves the digest of every transaction it touches, so it is made on its own, with the base's digest taken by the same code. +- Tighten the limits a run is held to: `Config::limits`, from `state-test`'s `--limit-*` options. - Change what a mode configures: `src/mode.rs`, and `mega-evm`'s `src/test_utils/neutral.rs`. - Change how a test is judged: `src/runner.rs::check`, `src/exceptions.rs`. - Change how a blockchain test is judged: `src/blockchain/mod.rs`; its skips: `src/blockchain/skips.rs`; what is taken out of its state root: `src/blockchain/chain.rs`. diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index 18bc0aa3f..9dffdb534 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -58,6 +58,31 @@ cargo run --release -p state-test -- --mode satin --fork Osaka
/state_test `--expect-executed`, `--expect-skipped` and `--expect-deviations` turn a full run into the pinned gate CI runs (`.github/workflows/exec-spec-satin.yml`). `--json-outcome` prints one JSON line per test, a failure's produced hashes included, and `--trace` runs each test under an EIP-3155 tracer. +## The outcome digest + +A verdict is the post-state root and the logs hash, so a change that moves gas between ledgers and keeps the receipt's total, or changes the bytes a limit counted, leaves every verdict as it was. +The digest (`src/digest.rs`) is the record such a change cannot leave alone: the whole `MegaTransactionOutcome` of every transaction that ran, whatever its fixture's verdict. +`--json-digest` prints, per executed transaction, one JSON line on standard error with the test's identity (`mode`, `fork`, `path`, `test`, `d`, `g`, `v`), the Keccak-256 of the canonical record (`digest`) and `row`, `outcome` for a transaction that ended and `panic` for a test that panicked; `--json-digest-full` adds the record (`record`). +A transaction the engine rejects has a record of its own, the error; a test skipped before it ran has none. + +The record holds the status with its halt or revert reason, the output, the created address and the logs in order; `ResultGas` and every field of `MegaGasUsage`; `usage`; `limit_exceeded`; `oracle_reads`; and the post-state, each account with its status flags, balance, nonce, code hash and every storage slot's original and present values. +It is canonical: JSON with every object's keys sorted, 256-bit numbers as lowercase hex without leading zeros, hashes and addresses at full width, maps sorted by key, so it depends on neither a thread count nor a hash map's order. +It is taken from the outcome as the engine produced it, before the runner takes the base-fee vault the fee routing created back out of the state. + +## Tightened limits + +Satin mode holds each transaction to the spec's limits, which the corpus rarely reaches. +`--limit-data-size BYTES` replaces the transaction data-size limit, and with it the frame data-size cap, which follows it unless `--limit-frame-data-size BYTES` names another; `--limit-kv-updates RECORDS` and `--limit-state-growth UNITS` replace the transaction's KV and state-growth limits, every frame's budget following each as its share; `--limit-compute-gas GAS` replaces gas detention's two caps. +A run so limited stops transactions the spec's run lets through, so its verdicts fail; it is read through its digest, whose `limit_exceeded` and `usage` then cover the stop paths of the whole corpus. +The options need `--mode satin`: equivalence mode installs no limit, and refuses them. +There is no write-record limit to tighten: a record is forty bytes of data size and is held by the data-size limit. + +To compare two revisions, run the same command at both, keep the lines that start with `{`, sort them, and compare the files; a line that differs is found by its `path` and `test`, and its full form shows the fields. + +```bash +state-test --mode satin --fork Osaka
/state_tests --json-digest 2>&1 >/dev/null | grep '^{' | sort > head.digest +``` + ## Blockchain tests `state-test btest` imports the execution-spec blockchain tests through Satin's block executor (`src/blockchain/`): the tests of the main release's `blockchain_tests` filled for Osaka, the release and the network the state-test gate's Osaka run uses. diff --git a/crates/mega-state-test/src/digest.rs b/crates/mega-state-test/src/digest.rs new file mode 100644 index 000000000..252c54f25 --- /dev/null +++ b/crates/mega-state-test/src/digest.rs @@ -0,0 +1,358 @@ +//! The canonical record of a transaction's whole outcome, and its hash. +//! +//! A fixture's verdict says whether the post-state root and the logs hash match the fixture's; it +//! says nothing of the gas a transaction spent on each ledger, of the bytes its limits counted, of +//! how it stopped or of the state beneath the root. A change that moves gas between ledgers and +//! keeps the receipt's total, or changes `usage` alone, leaves every verdict as it was. The digest +//! is the record such a change cannot leave alone: everything [`MegaTransactionOutcome`] holds, +//! rendered in one fixed encoding, so two runs of the same fixtures at two revisions can be +//! compared line by line, and a mismatch shows which field differs. +//! +//! The encoding is canonical: a JSON value whose objects list their keys in sorted order, whose +//! 256-bit numbers are `0x`-prefixed lowercase hex without leading zeros, and whose hashes, +//! addresses and byte strings are full-width lowercase hex. Maps are sorted by key before they +//! are written, so nothing in it depends on a hash map's iteration order or on a memory address. +//! The one place that renders a type through `Debug` is a halt or success reason and a rejected +//! transaction's error, whose names are the types' own; a dependency changing those names moves +//! the digest of the transactions that end that way, and the full form shows it. + +use std::collections::BTreeMap; + +use mega_evm::{ + revm::{ + context::result::{ExecutionResult, ResultGas}, + primitives::{keccak256, Address, Log, B256, U256}, + state::{Account, EvmState}, + }, + LimitCheck, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome, OracleRead, +}; +use serde_json::{Map, Value}; + +/// What a transaction ended in: its outcome, or the error it was rejected with. +pub type Executed<'a> = Result<&'a MegaTransactionOutcome, &'a str>; + +/// A JSON object whose keys are listed in sorted order, whichever order the map keeps. +fn object(entries: impl IntoIterator) -> Value { + let sorted: BTreeMap = entries.into_iter().collect(); + let mut map = Map::new(); + for (key, value) in sorted { + map.insert(key, value); + } + Value::Object(map) +} + +fn fields(entries: [(&str, Value); N]) -> Value { + object(entries.into_iter().map(|(key, value)| (key.to_string(), value))) +} + +/// A 256-bit number as `0x`-prefixed lowercase hex without leading zeros. +fn number(value: U256) -> Value { + Value::String(format!("{value:#x}")) +} + +fn hex(bytes: impl AsRef<[u8]>) -> Value { + Value::String(format!("0x{}", to_hex(bytes.as_ref()))) +} + +fn to_hex(bytes: &[u8]) -> String { + use core::fmt::Write; + bytes.iter().fold(String::with_capacity(bytes.len() * 2), |mut out, byte| { + write!(out, "{byte:02x}").expect("writing to a string cannot fail"); + out + }) +} + +fn address(address: &Address) -> String { + format!("0x{}", to_hex(address.as_slice())) +} + +/// A result's gas, with the reservoir the transaction left beside its other fields: revm's +/// [`ResultGas`] does not carry it, the outcome does ([`MegaGasUsage::reservoir_remaining`]). +fn result_gas(gas: &ResultGas, reservoir_remaining: u64) -> Value { + fields([ + ("block_regular_gas_used", gas.block_regular_gas_used().into()), + ("block_state_gas_used", gas.block_state_gas_used().into()), + ("final_refunded", gas.final_refunded().into()), + ("floor_gas", gas.floor_gas().into()), + ("inner_refunded", gas.inner_refunded().into()), + ("reservoir_remaining", reservoir_remaining.into()), + ("state_gas_spent_final", gas.state_gas_spent_final().into()), + ("total_gas_spent", gas.total_gas_spent().into()), + ("tx_gas_used", gas.tx_gas_used().into()), + ]) +} + +fn gas_usage(gas: &MegaGasUsage) -> Value { + let MegaGasUsage { + regular, + state, + history, + history_bytes, + reservoir_remaining, + floor, + gas_used, + } = *gas; + fields([ + ("floor", floor.into()), + ("gas_used", gas_used.into()), + ("history", history.into()), + ("history_bytes", history_bytes.into()), + ("regular", regular.into()), + ("reservoir_remaining", reservoir_remaining.into()), + ("state", state.into()), + ]) +} + +fn usage(usage: &LimitUsage) -> Value { + let LimitUsage { data_size, write_records, state_growth } = *usage; + fields([ + ("data_size", data_size.into()), + ("state_growth", state_growth.into()), + ("write_records", write_records.into()), + ]) +} + +fn log(log: &Log) -> Value { + fields([ + ("address", address(&log.address).into()), + ("data", hex(&log.data.data)), + ("topics", Value::Array(log.data.topics().iter().map(hex).collect())), + ]) +} + +fn logs(logs: &[Log]) -> Value { + Value::Array(logs.iter().map(log).collect()) +} + +fn limit_check(check: &LimitCheck) -> Value { + match check { + LimitCheck::WithinLimit => fields([("check", "within-limit".into())]), + LimitCheck::ExceedsLimit { kind, limit, used, frame_local } => fields([ + ("check", "exceeds-limit".into()), + ("frame_local", (*frame_local).into()), + ("kind", format!("{kind:?}").into()), + ("limit", (*limit).into()), + ("used", (*used).into()), + ]), + } +} + +fn oracle_read(read: &OracleRead) -> Value { + fields([("answer", read.answer.map_or(Value::Null, number)), ("slot", number(read.slot))]) +} + +fn account(account: &Account) -> Value { + let storage = object(account.storage.iter().map(|(key, slot)| { + ( + format!("{key:#066x}"), + fields([ + ("original", number(slot.original_value)), + ("present", number(slot.present_value)), + ]), + ) + })); + fields([ + ("balance", number(account.info.balance)), + ("code_hash", hex(account.info.code_hash)), + ("nonce", account.info.nonce.into()), + ("status", account.status.bits().into()), + ( + "status_flags", + Value::Array(account.status.iter_names().map(|(name, _)| name.into()).collect()), + ), + ("storage", storage), + ]) +} + +fn state(state: &EvmState) -> Value { + object(state.iter().map(|(addr, account_)| (address(addr), account(account_)))) +} + +fn result(result: &ExecutionResult, reservoir_remaining: u64) -> Value { + match result { + ExecutionResult::Success { reason, gas, logs: l, output } => fields([ + ("created", output.address().map_or(Value::Null, |a| address(a).into())), + ("gas", result_gas(gas, reservoir_remaining)), + ("logs", logs(l)), + ("output", hex(output.data())), + ("reason", format!("{reason:?}").into()), + ("status", "success".into()), + ]), + ExecutionResult::Revert { gas, logs: l, output } => fields([ + ("gas", result_gas(gas, reservoir_remaining)), + ("logs", logs(l)), + ("output", hex(output)), + ("status", "revert".into()), + ]), + ExecutionResult::Halt { reason, gas, logs: l } => fields([ + ("gas", result_gas(gas, reservoir_remaining)), + ("logs", logs(l)), + ("reason", format!("{reason:?}").into()), + ("status", "halt".into()), + ]), + } +} + +/// The canonical record of an executed transaction. +pub fn canonical(executed: Executed<'_>) -> Value { + match executed { + Ok(outcome) => fields([ + ("gas", gas_usage(&outcome.gas)), + ("limit_exceeded", outcome.limit_exceeded.as_ref().map_or(Value::Null, limit_check)), + ("oracle_reads", Value::Array(outcome.oracle_reads.iter().map(oracle_read).collect())), + ("result", result(&outcome.result, outcome.gas.reservoir_remaining)), + ("state", state(&outcome.state)), + ("usage", usage(&outcome.usage)), + ]), + Err(error) => fields([("rejected", error.into())]), + } +} + +/// The record of a test that panicked. +pub fn panicked(message: &str) -> Value { + fields([("panic", message.into())]) +} + +/// The digest of a canonical record: the Keccak-256 of its JSON text. +pub fn hash(canonical: &Value) -> B256 { + keccak256(text(canonical)) +} + +/// A canonical record's JSON text, on one line. +pub fn text(canonical: &Value) -> String { + serde_json::to_string(canonical).expect("a JSON value serializes") +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::revm::{ + context::result::{Output, ResultAndState, SuccessReason}, + primitives::Bytes, + state::{AccountInfo, EvmStorageSlot}, + }; + + fn gas() -> ResultGas { + ResultGas::default() + .with_total_gas_spent(100_000) + .with_state_gas_spent(30_000) + .with_refunded(4_000) + .with_floor_gas(21_000) + } + + fn outcome() -> MegaTransactionOutcome { + let mut state = EvmState::default(); + let mut account = Account::from(AccountInfo { nonce: 3, ..Default::default() }); + account.storage.insert( + U256::from(1), + EvmStorageSlot::new_changed(U256::from(7), U256::from(9), Default::default()), + ); + account.mark_touch(); + state.insert(Address::repeat_byte(0xaa), account); + state.insert(Address::repeat_byte(0x11), Account::default()); + MegaTransactionOutcome { + result_and_state: ResultAndState::new( + ExecutionResult::Success { + reason: SuccessReason::Stop, + gas: gas(), + logs: Vec::new(), + output: Output::Call(Bytes::from_static(&[1, 2])), + }, + state, + ), + gas: MegaGasUsage::new(&gas(), 10_000, 125, 5_000), + usage: LimitUsage { data_size: 500, write_records: 3, state_growth: 0 }, + limit_exceeded: None, + oracle_reads: vec![OracleRead { slot: U256::from(4), answer: Some(U256::from(5)) }], + } + } + + fn digest(outcome: &MegaTransactionOutcome) -> B256 { + hash(&canonical(Ok(outcome))) + } + + /// The same outcome, built twice, has the same text and the same hash, whatever order its + /// maps were filled in. + #[test] + fn test_the_digest_is_stable() { + let (a, b) = (outcome(), outcome()); + assert_eq!(text(&canonical(Ok(&a))), text(&canonical(Ok(&b)))); + assert_eq!(digest(&a), digest(&b)); + + let mut reordered = outcome(); + let accounts: Vec<_> = reordered.state.drain().collect(); + for (addr, account) in accounts.into_iter().rev() { + reordered.state.insert(addr, account); + } + assert_eq!(digest(&a), digest(&reordered)); + } + + /// The text names its keys in sorted order, whichever order the JSON map keeps. + #[test] + fn test_the_text_lists_keys_in_sorted_order() { + let text = text(&canonical(Ok(&outcome()))); + assert!(text.starts_with("{\"gas\":{\"floor\":"), "{text}"); + let markers = [ + ",\"limit_exceeded\":", + ",\"oracle_reads\":", + ",\"result\":{", + ",\"state\":{\"0x11", + ",\"usage\":", + ]; + let positions: Vec<_> = markers.iter().map(|m| text.find(m).expect(m)).collect(); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{text}"); + } + + /// Moving history gas to regular gas with the total kept changes the digest, though the + /// receipt's figures stay the same. + #[test] + fn test_one_gas_field_moves_the_digest() { + let base = outcome(); + let mut moved = outcome(); + moved.gas.history -= 100; + moved.gas.regular += 100; + assert_eq!(base.gas.regular + base.gas.history, moved.gas.regular + moved.gas.history); + assert_eq!(base.gas.gas_used, moved.gas.gas_used); + assert_ne!(digest(&base), digest(&moved)); + } + + /// Each of `usage`'s counts moves the digest on its own. + #[test] + fn test_usage_alone_moves_the_digest() { + let base = outcome(); + let mut data = outcome(); + data.usage.data_size += 1; + let mut records = outcome(); + records.usage.write_records += 1; + let mut growth = outcome(); + growth.usage.state_growth += 1; + assert_ne!(digest(&base), digest(&data)); + assert_ne!(digest(&base), digest(&records)); + assert_ne!(digest(&base), digest(&growth)); + } + + /// A slot's original value alone, its present value kept, moves the digest. + #[test] + fn test_an_original_storage_value_alone_moves_the_digest() { + let base = outcome(); + let mut moved = outcome(); + moved + .state + .get_mut(&Address::repeat_byte(0xaa)) + .unwrap() + .storage + .get_mut(&U256::from(1)) + .unwrap() + .original_value = U256::from(8); + assert_ne!(digest(&base), digest(&moved)); + } + + /// A rejection and a panic are records of their own, which differ from an outcome's and from + /// each other. + #[test] + fn test_a_rejection_and_a_panic_have_their_own_records() { + let rejected = hash(&canonical(Err("nonce too low"))); + assert_ne!(rejected, digest(&outcome())); + assert_ne!(rejected, hash(&panicked("nonce too low"))); + } +} diff --git a/crates/mega-state-test/src/lib.rs b/crates/mega-state-test/src/lib.rs index 0f65f5c73..d25456f3d 100644 --- a/crates/mega-state-test/src/lib.rs +++ b/crates/mega-state-test/src/lib.rs @@ -25,6 +25,7 @@ pub mod blockchain; pub mod deviations; +pub mod digest; pub mod exceptions; mod fork; mod mode; @@ -34,6 +35,8 @@ pub mod skips; pub mod witness; pub use fork::*; +/// The per-transaction limits a run can be held to, for [`runner::Config::limits`]. +pub use mega_evm::EvmTxRuntimeLimits; pub use mode::*; /// The execution-spec state-test fixture types, as the revm fork's reference runner reads diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index f8966439d..2dadd11af 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -38,18 +38,21 @@ use std::{ }; use mega_evm::{ + alloy_evm::Database, alloy_op_evm::OpTx, op_revm::{constants::BASE_FEE_RECIPIENT, OpHaltReason, OpTransaction, OpTransactionError}, revm::{ context::{ - result::{EVMError, ExecutionResult}, + result::{EVMError, ExecutionResult, ResultAndState}, BlockEnv, CfgEnv, }, database::{EmptyDB, State}, - inspector::{inspectors::TracerEip3155, InspectCommitEvm}, + inspector::{inspectors::TracerEip3155, Inspector}, + interpreter::interpreter::EthInterpreter, primitives::{Bytes, B256, KECCAK_EMPTY, U256}, - ExecuteCommitEvm, + DatabaseCommit, ExecuteCommitEvm, }, + EvmTxRuntimeLimits, MegaContext, MegaEvm, }; use serde::{ de::{Error as _, MapAccess, Visitor}, @@ -59,6 +62,7 @@ use walkdir::WalkDir; use crate::{ deviations::{self, Deviation}, + digest, exceptions::{self, Mismatch}, mode::MAX_BLOBS_PER_TX, roots::{logs_hash, state_root}, @@ -80,11 +84,25 @@ pub struct Config { pub json_outcome: bool, /// Run each test under an EIP-3155 tracer writing to standard error. pub trace: bool, + /// Print the digest of every transaction's whole outcome to standard error, in this form. + pub digest: Option, + /// Satin mode: the per-transaction limits the tests run under instead of the spec's, to reach + /// the limit-stop paths. Equivalence mode installs no limit and refuses these. + pub limits: Option, /// The registry equivalence mode attributes failures to: [`deviations::DEVIATIONS`] for the /// gate. pub deviations: &'static [Deviation], } +/// How much of a transaction's digest a run prints. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DigestForm { + /// The test's identity and the hash of the canonical record. + Compact, + /// The same, with the canonical record itself. + Full, +} + /// Which test a result is about. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] pub struct TestId { @@ -226,6 +244,11 @@ pub struct TestResult { pub id: TestId, /// What happened to it. pub outcome: Outcome, + /// The canonical record of what its transaction ended in ([`digest::canonical`]), for a test + /// whose transaction ran, whatever the verdict: a test that did not run, or panicked before + /// its transaction ended, has none. + #[serde(skip)] + pub record: Option, } /// Every test a run was given, and what happened to each. @@ -493,18 +516,28 @@ pub fn run_file(path: &Path, config: Config) -> Result, Failure> entry, indexes: (test.indexes.data, test.indexes.gas, test.indexes.value), }; + let mut executed = None; let outcome = match skip { Some(reason) => Outcome::Skipped { reason }, - None => catch_unwind(AssertUnwindSafe(|| run_test(config, unit, test))) - .unwrap_or_else(|panic| { - Outcome::Failed(Failure::new(FailureKind::Panic, panic_message(&panic))) - }), + None => catch_unwind(AssertUnwindSafe(|| { + run_test(config, unit, test, &mut executed) + })) + .unwrap_or_else(|panic| { + let message = panic_message(&panic); + if let Some(form) = config.digest { + print_digest(config, form, &id, "panic", &digest::panicked(&message)); + } + Outcome::Failed(Failure::new(FailureKind::Panic, message)) + }), }; + if let (Some(form), Some(executed)) = (config.digest, &executed) { + print_digest(config, form, &id, "outcome", executed); + } let outcome = attribute(config, &id, outcome); if config.json_outcome { print_outcome(config, &id, &outcome); } - results.push(TestResult { id, outcome }); + results.push(TestResult { id, outcome, record: executed }); } } } @@ -561,6 +594,34 @@ fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { .unwrap_or_else(|| "a panic without a message".into()) } +/// Prints the digest line of a test to standard error: the compact form names the test and the +/// hash of its canonical record, the full form carries the record too. `row` is `outcome` for a +/// transaction that ended and `panic` for a test that panicked, which a run compared by digest +/// must not have. +fn print_digest( + config: Config, + form: DigestForm, + id: &TestId, + row: &str, + record: &serde_json::Value, +) { + let mut line = serde_json::json!({ + "mode": config.mode, + "fork": config.fork, + "path": id.path, + "test": id.name, + "d": id.indexes.0, + "g": id.indexes.1, + "v": id.indexes.2, + "digest": digest::hash(record), + "row": row, + }); + if form == DigestForm::Full { + line["record"] = record.clone(); + } + eprintln!("{line}"); +} + fn print_outcome(config: Config, id: &TestId, outcome: &Outcome) { let line = serde_json::json!({ "mode": config.mode, @@ -585,8 +646,16 @@ pub(crate) fn chain_id(unit: &TestUnit) -> Result { } /// Executes one entry and judges it against its fixture. -fn run_test(config: Config, unit: &TestUnit, test: &Test) -> Outcome { - match execute_and_check(config, unit, test) { +/// +/// `executed` receives the canonical record of what the transaction ended in as soon as it has +/// ended, so a test that then fails its fixture, or panics while it is judged, still has one. +fn run_test( + config: Config, + unit: &TestUnit, + test: &Test, + executed: &mut Option, +) -> Outcome { + match execute_and_check(config, unit, test, executed) { Ok(None) => Outcome::Passed, Ok(Some(reason)) => Outcome::Skipped { reason }, Err(failure) => Outcome::Failed(failure), @@ -597,6 +666,7 @@ fn execute_and_check( config: Config, unit: &TestUnit, test: &Test, + executed: &mut Option, ) -> Result, Failure> { let Ready { chain_id, block, tx } = match prepare(config.fork, unit, test)? { Ok(ready) => ready, @@ -606,13 +676,15 @@ fn execute_and_check( let basefee = block.basefee; let mut state = State::builder().with_cached_prestate(unit.state()).with_bundle_update().build(); - let evm = config.mode.evm(config.fork, &mut state, block, chain_id); + let mut evm = config.mode.evm(config.fork, &mut state, block, chain_id); + if let Some(limits) = config.limits { + evm.set_tx_runtime_limits(limits); + } let result = if config.trace { let mut evm = evm.with_inspector(TracerEip3155::buffered(stderr()).without_summary()); - evm.inspect_tx_commit(tx) + execute_and_commit(&mut evm, tx, executed) } else { - let mut evm = evm; - evm.transact_commit(tx) + execute_and_commit(&mut evm, tx, executed) }; if let Ok(result) = &result { undo_fee_vault_credit(unit, &mut state, basefee, result.tx_gas_used()); @@ -621,6 +693,38 @@ fn execute_and_check( Ok(None) } +/// Executes `tx` on `evm` and commits what it produced, as `transact_commit` does, keeping the +/// transaction's whole outcome: its canonical record goes to `executed`, and the result is what +/// the fixture is judged on. +fn execute_and_commit( + evm: &mut MegaEvm, + tx: OpTx, + executed: &mut Option, +) -> Result, EVMError> +where + DB: Database + DatabaseCommit, + INSP: Inspector, EthInterpreter>, +{ + match evm.execute_transaction(tx) { + Ok(outcome) => { + *executed = Some(digest::canonical(Ok(&outcome))); + let ResultAndState { result, state } = outcome.result_and_state; + evm.commit(state); + Ok(result) + } + Err(error) => { + *executed = Some(digest::canonical(Err(&format!("{error:?}")))); + Err(match error { + EVMError::Transaction(error) => EVMError::Transaction(error.0), + EVMError::Header(error) => EVMError::Header(error), + EVMError::Database(error) => EVMError::Database(error), + EVMError::Custom(error) => EVMError::Custom(error), + EVMError::CustomAny(error) => EVMError::CustomAny(error), + }) + } + } +} + /// An entry ready to run: its chain id, block and transaction. pub(crate) struct Ready { /// The chain id the entry runs on. diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index 3f71fc110..f94235984 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -18,7 +18,7 @@ use state_test::{ runner::{run, Config, FailureKind, Outcome, Report}, skips::SkipReason, types::TestSuite, - Fork, Mode, + EvmTxRuntimeLimits, Fork, Mode, }; const SENDER: &str = "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"; @@ -31,7 +31,16 @@ const BASE_FEE_VAULT: &str = "0x4200000000000000000000000000000000000019"; const STORE_AND_LOG: &str = "0x602a5f5560075f5260205fa000"; fn config(mode: Mode, fork: Fork) -> Config { - Config { mode, fork, threads: 2, json_outcome: false, trace: false, deviations: DEVIATIONS } + Config { + mode, + fork, + threads: 2, + json_outcome: false, + trace: false, + digest: None, + limits: None, + deviations: DEVIATIONS, + } } /// A unit calling `CONTRACT` with `transaction` fields over the defaults, and one entry per fork @@ -499,3 +508,105 @@ fn test_the_registry_does_not_absorb_another_failure_of_its_entries() { )); assert_eq!(report.summary().unattributed, 1); } + +/// The records of a run's tests, in test order: none for a test whose transaction did not run. +fn records(report: &Report) -> Vec> { + report.results.iter().map(|result| result.record.as_ref()).collect() +} + +/// A run's digest does not depend on the thread count or on the run: the records of a file of +/// several tests are the same on one thread and on several, twice over, whatever the verdicts. +#[test] +fn test_the_digest_is_stable_across_runs_and_thread_counts() { + let dir = tempfile::tempdir().unwrap(); + let units: serde_json::Map<_, _> = (0..6) + .map(|n| { + let unit = unit( + &[Fork::Osaka], + json!({ "gasLimit": ["0x0f4240"], "value": [format!("0x{n:02x}")] }), + ); + (format!("call_{n}"), fill_from_ethereum(unit)) + }) + .collect(); + let paths = [write(dir.path(), "a.json", units.clone().into()), { + write(dir.path(), "b.json", units.into()) + }]; + let run_with = |threads| { + let report = run(&paths, Config { threads, ..config(Mode::Satin, Fork::Osaka) }); + records(&report).into_iter().map(|r| r.cloned()).collect::>() + }; + let one = run_with(1); + assert_eq!(one.len(), 12); + assert!(one.iter().all(Option::is_some), "every transaction ran"); + assert_eq!(one, run_with(1)); + assert_eq!(one, run_with(4)); + assert_eq!(one, run_with(4)); + let hashes: std::collections::BTreeSet<_> = + one.iter().flatten().map(state_test::digest::hash).collect(); + assert_eq!(hashes.len(), 6, "six distinct values, two files of each"); +} + +/// A test that fails its fixture still has the record of what ran, and a transaction the engine +/// rejects has one that says so; a test skipped by its fixture has none. +#[test] +fn test_the_digest_covers_failed_and_rejected_tests() { + let dir = tempfile::tempdir().unwrap(); + let filled = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + let mut wrong_root = filled.clone(); + wrong_root["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); + let mut rejected = fill_from_ethereum(unit( + &[Fork::Osaka], + json!({ "gasLimit": ["0x5208"], "data": ["0x00"] }), + )); + rejected["post"]["Osaka"][0]["expectException"] = + json!("TransactionException.INTRINSIC_GAS_TOO_LOW"); + let path = write( + dir.path(), + "a.json", + json!({ "a_passes": filled, "b_wrong_root": wrong_root, "c_rejected": rejected }), + ); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + let kinds: Vec<_> = outcomes(&report).into_iter().map(failure_kind).collect(); + assert_eq!(kinds, [None, Some(FailureKind::StateRootMismatch), None]); + let records = records(&report); + assert!(records.iter().all(Option::is_some)); + assert!(records[0].unwrap()["result"]["status"] == "success"); + assert_eq!( + records[0], records[1], + "the same transaction, the same record, whatever the verdict" + ); + assert!(records[2].unwrap()["rejected"] + .as_str() + .unwrap() + .contains("CallGasCostMoreThanGasLimit")); +} + +/// Running under tighter limits stops the transaction a limit holds: its record names the stop, +/// where the same fixture under the spec's limits has none. +#[test] +fn test_tightened_limits_reach_the_limit_stop_paths() { + let dir = tempfile::tempdir().unwrap(); + let path = write( + dir.path(), + "a.json", + json!({ "call": fill_from_ethereum(unit(&[Fork::Osaka], json!({ "gasLimit": ["0x0f4240"] }))) }), + ); + let spec = run(std::slice::from_ref(&path), config(Mode::Satin, Fork::Osaka)); + let tight = run( + &[path], + Config { + limits: Some( + EvmTxRuntimeLimits::default() + .with_tx_data_size_limit(400) + .with_frame_data_size_limit(400), + ), + ..config(Mode::Satin, Fork::Osaka) + }, + ); + let (spec, tight) = (records(&spec)[0].unwrap(), records(&tight)[0].unwrap()); + assert!(spec["limit_exceeded"].is_null()); + assert_eq!(tight["limit_exceeded"]["kind"], "DataSize"); + // The transaction's own frame crosses its budget, what the body leaves of the 400 bytes. + assert_eq!(tight["limit_exceeded"]["limit"], 400 - mega_evm::TX_BODY_SIZE); + assert_ne!(state_test::digest::hash(spec), state_test::digest::hash(tight)); +} diff --git a/crates/state-test/README.md b/crates/state-test/README.md index 7f573970d..b461230f3 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -10,6 +10,11 @@ state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] .. - `--mode satin` is the report: it runs the same entries under Satin's own configuration, prints the counts by outcome, and exits zero unless a fixture file cannot be read. - `--fork` names the fork whose fixture entries run. - `--expect-executed N`, `--expect-skipped N` and `--expect-deviations` pin the counts of a full run; CI passes all three. +- `--json-digest` prints one JSON line per executed transaction on standard error: the test's identity and the hash of the canonical record of the transaction's whole Mega outcome. + `--json-digest-full` adds the record itself to each line. + The two make a whole-outcome differential: run both at two revisions, sort and compare (`sort | cmp`), and read the full lines of the ids that differ. +- `--limit-data-size BYTES`, `--limit-frame-data-size BYTES`, `--limit-kv-updates RECORDS`, `--limit-state-growth UNITS` and `--limit-compute-gas GAS` (Satin mode only) hold every transaction to tighter per-transaction limits than the spec's, so the limit-stop paths run across the corpus; the frame budget follows `--limit-data-size`. + The verdicts of such a run are expected to fail; it is for comparing digests. - `--summary-json FILE` writes the counts as JSON, `--json-outcome` prints one JSON line per test on standard error, `--trace` runs every test under an EIP-3155 tracer and `--threads` sets the worker count. ```bash diff --git a/crates/state-test/src/main.rs b/crates/state-test/src/main.rs index 7c24e0cdd..a95facd70 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -17,8 +17,8 @@ use std::{path::PathBuf, process::ExitCode}; use clap::Parser; use state_test::{ deviations, - runner::{find_json_files, run, Config, Outcome, Report, Summary, TestResult}, - Fork, Mode, + runner::{find_json_files, run, Config, DigestForm, Outcome, Report, Summary, TestResult}, + EvmTxRuntimeLimits, Fork, Mode, }; /// How many unattributed failures, and how many unreproduced entries, the summary lists. @@ -47,6 +47,34 @@ struct Cmd { /// Print one JSON line per test to standard error. #[arg(long)] json_outcome: bool, + /// Print one JSON line per executed transaction on standard error: the test's identity and the + /// hash of the canonical record of the transaction's whole outcome (result, state, gas by + /// ledger, usage, logs, oracle reads), whatever the fixture's verdict. + #[arg(long)] + json_digest: bool, + /// As `--json-digest`, with the canonical record in each line, to see which field differs. + #[arg(long)] + json_digest_full: bool, + /// Satin mode: hold every transaction to this data-size limit, in bytes, instead of the + /// spec's; the frame budget follows it unless `--limit-frame-data-size` names one. + #[arg(long, value_name = "BYTES")] + limit_data_size: Option, + /// Satin mode: cap every frame's data-size budget at this many bytes. + #[arg(long, value_name = "BYTES")] + limit_frame_data_size: Option, + /// Satin mode: gas detention's two caps, the compute a transaction may still spend once it + /// read volatile data, instead of the spec's. + #[arg(long, value_name = "GAS")] + limit_compute_gas: Option, + /// Satin mode: hold every transaction to this many write records, its KV count, instead of + /// the spec's; every frame's budget is its share of what its parent has left. + #[arg(long, value_name = "RECORDS")] + limit_kv_updates: Option, + /// Satin mode: hold every transaction to this many new accounts and new slots, its state + /// growth, instead of the spec's; every frame's budget is its share of what its parent has + /// left. + #[arg(long, value_name = "UNITS")] + limit_state_growth: Option, /// Trace every test with an EIP-3155 tracer on standard error; runs on one thread. #[arg(long)] trace: bool, @@ -92,12 +120,26 @@ fn main() -> ExitCode { } else { cmd.threads.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())) }; + let limits = match tightened_limits(&cmd) { + Ok(limits) => limits, + Err(error) => { + eprintln!("error: {error}"); + return ExitCode::FAILURE; + } + }; + let digest = match (cmd.json_digest, cmd.json_digest_full) { + (_, true) => Some(DigestForm::Full), + (true, false) => Some(DigestForm::Compact), + (false, false) => None, + }; let config = Config { mode: cmd.mode, fork: cmd.fork, threads, json_outcome: cmd.json_outcome, trace: cmd.trace, + digest, + limits, deviations: deviations::DEVIATIONS, }; let report = run(&files, config); @@ -135,6 +177,42 @@ fn main() -> ExitCode { } } +/// The limits the `--limit-*` options name, over the spec's own, or none when no option is given. +fn tightened_limits(cmd: &Cmd) -> Result, String> { + if cmd.limit_data_size.is_none() && + cmd.limit_frame_data_size.is_none() && + cmd.limit_compute_gas.is_none() && + cmd.limit_kv_updates.is_none() && + cmd.limit_state_growth.is_none() + { + return Ok(None); + } + if cmd.mode == Mode::Equivalence { + return Err( + "the --limit-* options need --mode satin: equivalence mode holds no limit".into() + ); + } + let mut limits = EvmTxRuntimeLimits::default(); + if let Some(bytes) = cmd.limit_data_size { + limits = limits.with_tx_data_size_limit(bytes).with_frame_data_size_limit(bytes); + } + if let Some(bytes) = cmd.limit_frame_data_size { + limits = limits.with_frame_data_size_limit(bytes); + } + if let Some(gas) = cmd.limit_compute_gas { + limits = limits + .with_block_env_access_compute_gas_limit(gas) + .with_oracle_access_compute_gas_limit(gas); + } + if let Some(records) = cmd.limit_kv_updates { + limits = limits.with_tx_kv_update_limit(records); + } + if let Some(units) = cmd.limit_state_growth { + limits = limits.with_tx_state_growth_limit(units); + } + Ok(Some(limits)) +} + fn print_summary(report: &Report, summary: &Summary) { println!("{} mode, {} fixtures: {} files", report.mode, report.fork, summary.files); println!( diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index d9d3348d9..9d6fc4eab 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -159,6 +159,57 @@ fn test_bad_arguments_exit_non_zero() { } } +/// The digest options print one line per executed transaction on standard error: the compact form +/// the test and the hash of its record, the full form the record too, and the same line twice. +#[test] +fn test_the_digest_options_print_a_line_per_transaction() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + let lines = |flag: &str| -> Vec { + let output = state_test(&[flag, "--fork", "Osaka"], &path); + assert!(output.status.success(), "{}", stdout(&output)); + String::from_utf8_lossy(&output.stderr) + .lines() + .filter(|line| line.starts_with('{')) + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + }; + let compact = lines("--json-digest"); + assert_eq!(compact.len(), 1); + assert_eq!(compact[0]["row"], "outcome"); + assert!(compact[0]["digest"].as_str().unwrap().starts_with("0x")); + assert!(compact[0].get("record").is_none()); + assert_eq!(compact, lines("--json-digest")); + + let full = lines("--json-digest-full"); + assert_eq!(full.len(), 1); + assert_eq!(full[0]["digest"], compact[0]["digest"]); + assert!(full[0]["record"]["rejected"].is_string(), "the transaction is rejected"); +} + +/// The limit options tighten Satin mode's limits; equivalence mode holds none, so it refuses them. +#[test] +fn test_the_limit_options_need_satin_mode() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + for option in [ + ["--limit-data-size", "1024"], + ["--limit-frame-data-size", "1024"], + ["--limit-compute-gas", "30000"], + ["--limit-kv-updates", "10"], + ["--limit-state-growth", "10"], + ] { + let mut args = vec!["--fork", "Osaka"]; + args.extend(option); + let output = state_test(&args, &path); + assert_eq!(output.status.code(), Some(1), "{option:?} in equivalence mode"); + assert!(String::from_utf8_lossy(&output.stderr).contains("--mode satin")); + + args.extend(["--mode", "satin"]); + assert!(state_test(&args, &path).status.success(), "{option:?} in Satin mode"); + } +} + /// A blockchain fixture of one empty block on a pre-state of one funded account, with /// `edit` applied to the block's header. With no pre-block contract and no transaction the block /// changes nothing on Ethereum, so its expected roots are the pre-state's and the empty trie's, diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index d7ae2e73a..e1a82cb37 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -63,7 +63,8 @@ On Satin, every output field keeps its legacy name and meaning, and one field is | `floor_gas` | The EIP-7623 floor the receipt's gas used cannot fall below | | `data_size` | Data-size bytes the transaction kept | | `write_records` | Account and storage write records it kept: its KV count | -| `limit_exceeded` | `null`, or the limit that stopped it: `kind` (`data_size`, `compute_gas`), `limit`, `used` | +| `state_growth` | New accounts and new storage slots it kept, net: its state growth | +| `limit_exceeded` | `null`, or the limit that stopped it: `kind` (`data_size`, `kv_updates`, `state_growth`, `compute_gas`), `limit`, `used` | | `limits_override` | Present only under `--override.limits`: the protocol limits the run was held to, in the shape the flag takes | In text mode the same numbers follow the summary under `=== Satin Gas ===`. @@ -76,7 +77,11 @@ A Satin run is held to Satin's protocol limits, which the spec fixes and no chai | Limit | Value | | ------------------------------------------------------------------------ | ---------- | | A transaction's data size (`txDataSizeLimit`) | 13,107,200 | +| A transaction's KV updates (`txKvUpdateLimit`) | 500,000 | +| A transaction's state growth (`txStateGrowthLimit`) | 1,000 | | A block's data size (`blockTxsDataLimit`) | 13,107,200 | +| A block's KV updates (`blockKvUpdateLimit`) | 500,000 | +| A block's state growth (`blockStateGrowthLimit`) | 1,000 | | Compute after a block-environment read (`blockEnvAccessComputeGasLimit`) | 20,000,000 | | Compute after an Oracle read (`oracleAccessComputeGasLimit`) | 20,000,000 | | A frame's data size beyond its share (`frameDataSizeLimit`) | unlimited | @@ -87,17 +92,22 @@ The values are provisional, as Satin is. `--override.limits` runs under other limits, a counterfactual. It takes a JSON object in the limits' shape, inline or as the path of a file. The fields it names replace Satin's, and every other stays. +A file written for the shape's first published version, without the KV-update and state-growth limits, runs with Satin's values for them. The whole shape, at Satin's values: ```json { "txRuntimeLimits": { "txDataSizeLimit": 13107200, + "txKvUpdateLimit": 500000, + "txStateGrowthLimit": 1000, "frameDataSizeLimit": 18446744073709551615, "blockEnvAccessComputeGasLimit": 20000000, "oracleAccessComputeGasLimit": 20000000 }, - "blockTxsDataLimit": 13107200 + "blockTxsDataLimit": 13107200, + "blockKvUpdateLimit": 500000, + "blockStateGrowthLimit": 1000 } ``` diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index 359d3df64..836fd79fd 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -64,6 +64,14 @@ _(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) gas Drawn from the [reservoir](#reservoir) first, then from regular gas. +The accounts and fresh slots this gas prices are what Satin counts as state growth, limited per transaction, per frame and per block. + +The first effective `SELFDESTRUCT` of an account created in the same transaction refills this gas only for a part that was absent at the transaction's start: the account leaf, the code deposit and each new slot. +That refill goes to the destroying frame, including when another frame paid it. +A part that existed at the start is not refilled, and state growth does not fall for it. + +A failed deposit's created caller is counted as state growth and pays no state gas, and the limit does not stop that deposit. + See the [Satin](upgrades/satin.md) network upgrade. ## History gas @@ -72,6 +80,10 @@ _(Satin, unstable)_ Gas a transaction pays for the bytes it appends to the chain Drawn from the [reservoir](#reservoir) first, then from regular gas, and never scaled by SALT. +The first effective `SELFDESTRUCT` of an account created in the same transaction gives this gas back for each [write record](#write-record) it takes back, and for deployed code that was absent at the transaction's start and is deleted with the account. +That give-back goes to the destroying frame, including when another frame paid it. +Every other give-back of this gas goes to whoever paid it. + See the [Satin](upgrades/satin.md) network upgrade. ## Execution cap @@ -83,10 +95,28 @@ Gas limit above the cap goes to the [reservoir](#reservoir). _(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) state-gas reservoir: the part of a transaction's gas limit above the [execution cap](#execution-cap), which pays [state gas](#state-gas) and [history gas](#history-gas) before they spill onto regular gas. +The transaction's own frame, and a system call's outermost frame, receive the whole reservoir. + +A child frame of `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or `CREATE2`, and the creation a keyless deployment starts, receives `remaining − remaining × 2 / 100` of the caller's remaining reservoir, taken after every charge the caller makes for that start. + +The explicit gas argument does not bound that share. + +What the child does not spend returns to the caller, and a failed child's charges roll back as EIP-8037 specifies. +On every such return, whether the start was answered without building a frame or a built frame returns, the reservoir the child returns first unwinds the caller's outstanding spill, and the rest joins the reservoir the caller kept. +The part the caller kept is not drawn. +State gas and history gas share that spill. +The caller's own charge for a leaf the child did not add is given back after that. + ## Write record -_(Satin, unstable)_ One account or storage write a transaction keeps, 40 bytes of data size and of [history gas](#history-gas). +_(Satin, unstable)_ One account or storage write a transaction keeps, 40 bytes of data size and of [history gas](#history-gas): an account's record exists while the account's nonce, balance or code differs from what the transaction loaded, whichever writes changed it — a creation's created account included — and a slot's while its value differs from its original value in the transaction. The KV-update count is the number of write records. +The first effective `SELFDESTRUCT` of an account created in the same transaction takes back the write record of each part that was absent at the transaction's start — the account leaf and each new slot — with that record's data size and history gas. +A part that existed at the start keeps its record, because the account or the slot now differs from its original. +Deployed code is not a write record; the same destruction gives back the data size and history gas of code that was absent at the start. +A write to the account or to one of its slots after that mark makes no record. + +Satin limits that count per transaction, per frame and per block: `TX_KV_UPDATE_LIMIT` and `BLOCK_KV_UPDATE_LIMIT` are 500,000. ## History allowance @@ -180,6 +210,8 @@ One of four independent limits enforced per transaction: compute gas, data size, See [resource limits](evm/resource-limits.md). +_(Satin, unstable)_ Satin keeps data size, KV updates and state growth as limited dimensions, each per transaction, per frame and per block, and enforces compute through gas detention on regular gas, with no separate compute-gas limit. + ## Call frame A single execution context within a transaction, corresponding to a message call (CALL, STATICCALL, DELEGATECALL, CALLCODE) or a contract creation (CREATE, CREATE2) as defined in the [Ethereum Yellow Paper](https://ethereum.github.io/yellowpaper/paper.pdf). @@ -190,6 +222,8 @@ Call frames nest: each CALL or CREATE within a transaction creates a child call Resource trackers (data size, KV updates, state growth) are call-frame-aware — usage within a child call frame is discarded if the child reverts. +_(Satin, unstable)_ A child frame's budget in each of data size, KV updates and state growth is `parent_remaining × 98 / 100`, rounded down. + ## Call-frame-local exceed When a call frame exceeds its per-call-frame resource budget, the call frame **reverts** with `MegaLimitExceeded(uint8 kind, uint64 limit)`. @@ -200,6 +234,10 @@ Distinct from a transaction-level exceed, which **halts** the entire transaction Per-call-frame resource budgets are introduced in Rex4. +_(Satin, unstable)_ Satin stops the frame that crosses a limit with that same revert, the transaction's own frame included, and the caller continues. + +The `kind` values are 0 for data size, 1 for KV updates, 2 for detention's compute limit and 3 for state growth. + ## Spec (`MegaSpecId`) A set of MegaETH verifiable behaviors: the complete definition of what a correct node does at a given stage. diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index 3c1e25f79..c507445d9 100644 --- a/docs/spec/hardfork-spec.md +++ b/docs/spec/hardfork-spec.md @@ -193,12 +193,12 @@ It restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka) rather - **Two-pool gas** — [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 per-transaction execution cap, with the rest of the gas limit as a state-gas reservoir, replacing the [dual gas model](evm/dual-gas-model.md). - **State gas** — EIP-8037's byte counts at MegaETH's cost per state byte, scaled by the [SALT bucket](glossary.md#salt-bucket) the state lands in. - **History gas** — a price per byte on the transaction body, logs, write records and deployed code, replacing the storage gas on logs and calldata, the intrinsic storage gas, and the [storage gas stipend](glossary.md#storage-gas-stipend). -- **Resource limits** — data size per transaction, with no KV-update, state-growth or separate compute-gas limit; every limit stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, which its caller can catch. +- **Resource limits** — data size, KV updates (500,000) and state growth (1,000), each per transaction, per frame at 98/100 of what the parent has left, and per block, with no separate compute-gas limit; every limit stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, which its caller can catch. - **[Gas detention](evm/gas-detention.md)** — enforced on the gas a frame is allowed to spend, withholding the rest inside the frame's own gas. -- **[EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs**, the `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` opcodes, and 63/64 gas forwarding. +- **[EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs**, the `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` opcodes, and 98/100 forwarding of regular gas and of the reservoir. - **[KeylessDeploy](system-contracts/keyless-deploy.md)** — the deployment runs as a native creation frame instead of a sandbox. - **System calls** — at most 30,000,000 of a system call's gas is regular gas, and the pre-block calls run before every block; the block in which Satin activates checks that the system contracts and the EIP-7997 factory hold the code Satin runs, and Satin deploys none of them. - **Live system address** — every transaction reads the [SequencerRegistry](system-contracts/sequencer-registry.md) itself, and a system-address transaction without the system shape is invalid. -- **Block limits** — data size is a packing budget that never refuses a deposit or a Mega System Transaction. +- **Block limits** — data size, KV updates and state growth are packing budgets that never refuse a deposit or a Mega System Transaction. _See [Satin Network Upgrade](upgrades/satin.md) for the current state._ diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 3854c1540..acd4cbc4a 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -51,7 +51,7 @@ For the current stable behavior as a single reference, see the [MegaEVM Overview Satin (unstable): base layer and reference implementation Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction but a deposit or one of the protocol's own pays history gas, so no transaction that pays it behaves identically to Optimism under Satin. -Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 (`v40.0.3-mega.4`), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 (`v20.0.0-mega.3`), and alloy-evm 0.36. +Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `2fc8edf33b2ffddb195cebc17be9adabfd95417c` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `f599efdabc3e5b36a280f1aa72978751bd64c160` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. See the [Satin Network Upgrade](upgrades/satin.md). @@ -83,7 +83,7 @@ Contracts deployed under a given spec will continue to behave identically, regar - **REX4** — Per-call-frame resource budgets, relative gas detention, [storage gas stipend](glossary.md#storage-gas-stipend), MegaAccessControl and MegaLimitControl system contracts. - **REX5** — SequencerRegistry system contract, Oracle v2.0.0 with dynamic system address, caller-account update deduplication, storage-gas-stipend separated-allowance model, value-transfer CALL/CALLCODE parent compute-gas attribution, CREATE code-deposit compute-gas atomicity, EIP-2935/EIP-4788 pre-block gas floor with fail-closed block rejection, CREATE2 empty-initcode short-circuit, KeylessDeploy trailing-bytes rejection and empty-code log forwarding. - **REX6** — Unified per-opcode gas metering order, consolidated EIP-7702 authorization accounting, CREATE-frame accounting corrections, KeylessDeploy sandbox hardening, post-execution fee-reward accounting, system-originated transaction metering exemption, extended beneficiary detention coverage, and SequencerRegistry v2.0.0 rotation hardening. -- **SATIN** — The **unstable** spec, not scheduled on any network. Restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka): EIP-8037 regular gas under a 200,000,000 execution cap with a state-gas reservoir, SALT-scaled state gas, history gas, revert-class limit stops, gas detention on withheld gas, EIP-7708 transfer logs, native KeylessDeploy creation, and block limits as packing budgets. +- **SATIN** — The **unstable** spec, not scheduled on any network. Restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka): EIP-8037 regular gas under a 200,000,000 execution cap with a state-gas reservoir, 98/100 forwarding of regular gas and of that reservoir, SALT-scaled state gas, history gas, data-size, KV-update (500,000) and state-growth (1,000) limits per transaction, per frame and per block, revert-class limit stops, gas detention on withheld gas, EIP-7708 transfer logs, native KeylessDeploy creation, and data-size, KV and state-growth block limits as packing budgets. See [Hardforks and Specs](hardfork-spec.md) for full details. diff --git a/docs/spec/upgrades/overview.md b/docs/spec/upgrades/overview.md index 588768154..3b05e9229 100644 --- a/docs/spec/upgrades/overview.md +++ b/docs/spec/upgrades/overview.md @@ -153,7 +153,7 @@ Not yet scheduled {% endtabs %} Unstable; under active development. -Optimism Karst (Ethereum Osaka) base, [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 execution cap with a state-gas reservoir, SALT-scaled state gas, history gas per byte appended, limits that stop the frame that crosses them with a revert, gas detention on withheld gas, [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs, native [KeylessDeploy](../system-contracts/keyless-deploy.md) creation, system calls on 30,000,000 regular gas plus reservoir, the live system address read by the transaction, the block's data-size limit as a packing budget, and the EIP-7997 factory. +Optimism Karst (Ethereum Osaka) base, [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 execution cap with a state-gas reservoir, 98/100 forwarding of regular gas and of that reservoir to a child frame, SALT-scaled state gas, history gas per byte appended, data-size, KV-update (500,000) and state-growth (1,000) limits per transaction, per frame at 98/100 and per block, each stopping the frame that crosses it with a revert, gas detention on withheld gas, [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs, native [KeylessDeploy](../system-contracts/keyless-deploy.md) creation, system calls on 30,000,000 regular gas plus reservoir, the live system address read by the transaction, the block's data-size, KV and state-growth limits as packing budgets that never refuse a deposit or a Mega System Transaction, and the EIP-7997 factory. ## How to Read These Pages diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 43fb960ee..c58567a6c 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1,5 +1,5 @@ --- -description: Satin network upgrade (unstable) — MegaETH's execution rules restated on Optimism Karst (Ethereum Osaka) — EIP-8037 regular and state gas under a 200,000,000 execution cap with a state-gas reservoir, a history-gas ledger for the bytes a transaction appends, SALT-scaled state gas, limits that stop the frame that crosses them with a revert, gas detention on withheld gas, EIP-7708 transfer logs, keyless deployment as a native creation, system calls on a split budget, the live system address read by the transaction itself, the block's data-size limit as a packing budget, and the witness a stateless validator re-executes a block from. +description: Satin network upgrade (unstable). MegaETH's execution rules restated on Optimism Karst (Ethereum Osaka): EIP-8037 regular and state gas under a 200,000,000 execution cap with a state-gas reservoir, a history-gas ledger for the bytes a transaction appends, SALT-scaled state gas, data-size, KV and state-growth limits that stop the frame that crosses them with a revert, 98/100 forwarding of regular gas and of the reservoir, gas detention on withheld gas, EIP-7708 transfer logs, keyless deployment as a native creation, system calls on a split budget, the live system address read by the transaction itself, block data-size, KV and state-growth limits as packing budgets, and the witness a stateless validator re-executes a block from. --- # Satin Network Upgrade @@ -19,27 +19,30 @@ A transaction's gas is split into regular gas, which pays for computation and is State growth is paid in [state gas](../glossary.md#state-gas) — EIP-8037's byte counts at MegaETH's own cost per state byte, scaled by the [SALT bucket](../glossary.md#salt-bucket) the state lands in — and the bytes a transaction appends to the chain's history (its body, its logs, its [write records](../glossary.md#write-record), its deployed code) are paid in a third ledger, [history gas](../glossary.md#history-gas). Together they replace [storage gas](../glossary.md#storage-gas), the 39,000 intrinsic storage gas, the 10× multiplier on logs and calldata, and the 23,000-gas [storage gas stipend](../glossary.md#storage-gas-stipend). -The per-transaction resource limits keep data size and drop the KV-update, state-growth and compute-gas limits: write records are bounded by the data size they weigh and priced in history gas, state growth is priced in state gas, and compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md). -Every limit — data size and detention's compute limit — now stops the frame that crosses it with a revert carrying `MegaLimitExceeded(kind, limit)` instead of a halt: the frame's caller can catch the stop and carry on within what the limits leave, and a transaction whose own frame is stopped pays only for what ran. +The per-transaction resource limits are data size, KV updates and state growth, each also limited per frame and per block. +Write records are the KV count, weighed as data size and priced in history gas. +State growth is the net count of new accounts and new slots, and it is priced in state gas. +Compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md), and Satin keeps no separate compute-gas limit. +Every limit, data size, KV updates, state growth and detention's compute limit, stops the frame that crosses it with a revert carrying `MegaLimitExceeded(kind, limit)`: the frame's caller can catch the stop and carry on within what the limits leave, and a transaction whose own frame is stopped pays only for what ran. Detention holds each frame's spendable regular gas inside the frame's own gas, so a transaction that read volatile data runs exactly as it would have without the read until a regular charge needs the gas it is not allowed to spend. -Satin also brings EIP-7708 transfer logs, deploys a `keylessDeploy` transaction as a native creation instead of in a sandbox, runs system calls on at most 30,000,000 of regular gas with the rest as reservoir, has a system-address transaction read the live system address itself, and makes the block's data-size limit, its one block-level execution limit, a packing budget that never refuses a deposit or a Mega System Transaction. +Satin also brings EIP-7708 transfer logs, deploys a `keylessDeploy` transaction as a native creation instead of in a sandbox, runs system calls on at most 30,000,000 of regular gas with the rest as reservoir, has a system-address transaction read the live system address itself, and makes the block's data-size, KV and state-growth limits packing budgets that never refuse a deposit or a Mega System Transaction. Satin follows [Rex6](rex6.md) on the spec ladder, so every **Previous behavior** below is Rex6's. Satin does not add to the Rex6 rules one by one: it restates the execution layer, and a Rex6 rule this page does not carry over does not apply under Satin. The changes, in the order this page records them: -1. **Base layer.** Optimism Karst (Ethereum Osaka), four Amsterdam opcodes, and no EIP-7825 transaction gas cap. +1. **Base layer.** Optimism Karst (Ethereum Osaka), four Amsterdam opcodes, and no EIP-7825 or EIP-8037 transaction gas cap. 2. **Precompiles.** Karst's set, with KZG point evaluation still at 100,000. 3. **Contract size limits.** 512 KiB of code and 1 MiB of initcode. -4. **Two-pool gas.** EIP-8037 regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. +4. **Two-pool gas.** EIP-8037, as of 4 September 2026, regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. 5. **Gas schedule and intrinsic gas.** Amsterdam's schedule, EIP-8038's state-access prices included, and EIP-2780 intrinsic cost. 6. **State gas and SALT pricing.** `entry × multiplier` on EIP-8037's byte counts, replacing `base × (multiplier − 1)`. 7. **History gas.** A price per byte on everything a transaction appends to history. 8. **History allowance.** A 160-byte allowance for value calls, replacing the 23,000-gas storage gas stipend. -9. **Gas forwarding.** The standard 63/64 rule, replacing 98/100. -10. **Resource limits.** Data size over a byte table and write records, and no KV-update, state-growth or compute-gas limit. +9. **Gas forwarding.** 98/100 of regular gas, as in Rex6, in place of 63/64, and 98/100 of the caller's remaining reservoir to a child frame. +10. **Resource limits.** Data size, KV updates and state growth, per transaction, per frame at 98/100, and per block, with no separate compute-gas limit. 11. **The revert-class stop.** Every limit stops the frame that crosses it with a revert, which its caller can catch. 12. **Gas detention on withheld gas.** 13. **Volatile-data access control and `remainingComputeGas()`.** @@ -67,7 +70,9 @@ The changes, in the order this page records them: - Satin builds on Optimism Karst, whose Ethereum base is Osaka. Every standard EVM, transaction and block rule this page does not override MUST be Karst's, including the Optimism changes of Jovian and Karst and the Ethereum changes of Osaka (for example `CLZ`, [EIP-7939](https://eips.ethereum.org/EIPS/eip-7939)). - The per-transaction gas limit cap of [EIP-7825](https://eips.ethereum.org/EIPS/eip-7825) MUST NOT be applied. - The execution cap of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model) bounds a transaction's regular gas instead, and a transaction's gas limit is bounded by the block's gas limit; a block builder MAY refuse a larger declared gas limit as building policy, which a node validating a block does not apply (see [Block Limits](#20-block-limits)). + The execution cap of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model) bounds a transaction's regular gas instead, and a transaction's gas limit is bounded by the block's gas limit. + The EIP-8037 cap `TX_MAX_TOTAL_GAS_LIMIT` = 2^32 − 1 MUST NOT be applied either. + A block builder MAY refuse a larger declared gas limit as building policy, which a node validating a block does not apply (see [Block Limits](#20-block-limits)). - A node MUST enable four opcodes that Osaka does not have: `DUPN` (`0xE6`), `SWAPN` (`0xE7`) and `EXCHANGE` (`0xE8`) from [EIP-8024](https://eips.ethereum.org/EIPS/eip-8024), and `SLOTNUM` (`0x4B`) from [EIP-7843](https://eips.ethereum.org/EIPS/eip-7843). `SLOTNUM` MUST push the block's slot number, an unsigned 64-bit integer the node supplies with the block. The slot number has no absent value: a block for which the node supplies no other number runs with slot number zero, which `SLOTNUM` pushes like any other. @@ -121,6 +126,8 @@ A KZG call given at least 100,000 gas that fails otherwise — an input of the w - Deployed code MUST be at most `MAX_CONTRACT_SIZE` = 524,288 bytes. - Initcode MUST be at most `MAX_INITCODE_SIZE` = 1,048,576 bytes, twice the code limit, the ratio [EIP-3860](https://eips.ethereum.org/EIPS/eip-3860) sets between the two. +- These are Ethereum's size checks at MegaETH's sizes, not resource limits: initcode over `MAX_INITCODE_SIZE` MUST halt the creating frame at the creation opcode, and deployed code over `MAX_CONTRACT_SIZE` MUST halt the creation, each consuming the halting frame's gas as Ethereum does. + Neither is the [revert-class stop](#11-the-revert-class-stop) a resource limit makes. - The creation opcodes MUST make their checks and charges in this order: the static context; the value, offset and size operands, and the size's range; the initcode size; EIP-3860's initcode cost; the offset's range and the memory the initcode is read from (neither checked for empty initcode); for `CREATE2`, the salt operand, then the 12,000 and the hashing cost of the initcode, and for `CREATE` the 12,000. Satin adds no charge ahead of these. So a creation in a static frame fails before its operands are read, and a `CREATE2` short of its salt pays the initcode cost and the memory first: the halt consumes the frame's gas either way, but under [gas detention](#12-gas-detention-on-withheld-gas) those charges can be the crossing, which stops the frame with a revert where the stack underflow would have halted it. @@ -136,7 +143,24 @@ A KZG call given at least 100,000 gas that fails otherwise — an input of the w #### New behavior -A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amsterdam applies it, with the parameters below. +A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) (4 September 2026), with the parameters below, and with the later changes this section names. +Satin adopts the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef) (4 September 2026) as the reference implementation performs it, and does not adopt the transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950) (14 September 2026). +On the return of every start, whether the start is answered without building a frame (a precompile, a call to an account with no code, an interceptor's answer) or a built frame returns, the reservoir the child returns MUST first unwind the caller's outstanding spill, and the rest MUST join the reservoir the caller kept. +`d = min(returned reservoir, the caller's outstanding spill)`. +The caller's regular gas increases by `d`, its spill decreases by `d`, and its reservoir increases by the returned reservoir less `d`. +The reservoir the caller kept MUST NOT be drawn. +State charges and history charges share that spill (see [History Gas](#7-history-gas)). +A successful child's own spill MUST be added to the caller's spill before this unwind. +A revert or a halt MUST NOT add the child's spill: the child's rollback already credited that spill to the gas the child returns, and a halt then consumes it. +A node MUST NOT cap a transaction's gas limit at `TX_MAX_TOTAL_GAS_LIMIT` = 2^32 − 1. +The gas limit stays bounded by the block's gas limit. +That cap stays open until EIP-8037 is final. +An authority charge made before the first frame is not committed out of the outstanding spill when that frame starts. +The reservoir the first frame returns unwinds that spill by the same rule, together with any other spill still outstanding. +A failure of the first frame returns no reservoir that charge had already drawn, so the charge stays (see [The Revert-Class Stop](#11-the-revert-class-stop)). +That is the failure outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) (14 September 2026), and not its commit of the pre-execution spill, which would keep a later return from unwinding it. +A creation does not collide on storage (see [Resource Limits](#10-resource-limits)), which is the collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) (18 September 2026). +The removal of an unused counter ([commit `052029f362`](https://github.com/ethereum/EIPs/commit/052029f3625328d6f51dec8e62a7090201e66f17)), the co-author lines and the move to Last Call change no rule a transaction executes, and Satin does not track them. - **The execution cap.** `EXECUTION_CAP` = 200,000,000. @@ -157,11 +181,21 @@ A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amster A state charge (see [State Gas](#6-state-gas-and-salt-pricing)) and a history charge (see [History Gas](#7-history-gas)) MUST draw the reservoir first and spill onto the regular budget only past it. `GAS` MUST return the regular budget the frame has left, not the reservoir. - **Frames.** - A call or creation MUST forward regular gas as the inherited rules have it (see [Gas Forwarding](#9-gas-forwarding)), and the child MUST inherit the caller's whole reservoir; what the child leaves of the reservoir returns to the caller. - When a frame reverts or halts, the state and history gas it charged MUST be given back: the part the reservoir paid returns to the reservoir, and the part that spilled returns to the frame's regular budget. + A call or creation MUST forward regular gas as [Gas Forwarding](#9-gas-forwarding) specifies. + The transaction's own frame, and a system call's outermost frame, MUST receive the whole reservoir: there is no caller to retain a share from. + A child frame of `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or `CREATE2`, and the creation a keyless deployment starts, MUST receive `reservoir_share = remaining − remaining × 2 / 100` of the reservoir its caller has left after every charge the caller makes for that start, and the caller MUST keep the rest. + `remaining` is that reservoir, and the division is integer division, truncating toward zero. + The regular gas the caller asks to forward MUST NOT bound `reservoir_share`. + What the child leaves of its share MUST return to the caller by the child-merge rule above. + When a frame reverts or halts, the state and history gas it charged MUST be given back as [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) specifies: the part the reservoir paid returns to the reservoir, and the part that spilled returns to the frame's regular budget. A revert then returns the frame's unspent regular gas to its caller; an exceptional halt consumes it, the returned spill included. + A failed child therefore returns the share it was given, whether the start was answered without building a frame (a precompile, a call to an account with no code, an interceptor's answer) or a built frame returns. + That share unwinds the caller's outstanding spill before the rest joins the reservoir the caller kept. + When the caller has no outstanding spill, the caller holds the reservoir it had after the charges it made for the start. + The caller's own charge for a leaf the child did not add is given back after that. - **The transaction.** When the transaction ends, the reservoir left MUST return to the sender, and so MUST the unspent regular gas unless the transaction's own frame halted; this holds when the transaction reverts or is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). + A failed deposit is the exception: it MUST use its whole gas limit, the reservoir included, and nothing returns (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)); a deposit that succeeds, reverts or is stopped by a limit is not a failed deposit and settles as above. The receipt's gas used is what the transaction spent from both pools — regular, state and history gas together — after the inherited refund and floor rules. When that spend less the refund is below the floor, the gas used MUST be the floor and no refund is made: the sender gets back its gas limit less the floor, the floor's excess over the spend coming out of the unspent regular gas and the reservoir alike. - **Three ledgers.** @@ -257,8 +291,10 @@ The EIP-2780 intrinsic regular gas of a transaction MUST be `TX_BASE_COST` = 12, A transfer to the sender itself pays the base alone. The 7,816 per authorization MUST be charged as every intrinsic entry is, by the transaction's validation; an authority that already exists is refunded nothing when its authorization is applied. The state-dependent parts — a recipient or created account that does not exist, an authority that does not exist, a delegation indicator, an authority's first write — MUST be charged at the start of execution, as EIP-2780 and EIP-8037 specify, with every state charge priced as [State Gas](#6-state-gas-and-salt-pricing) says. +The delegation-indicator charge is at most once per authority, and only when the authority holds no indicator at the start of the transaction and no earlier authorization in the list set one (see [Resource Limits](#10-resource-limits)). A deposit-like transaction whose caller account does not exist MUST be charged the new-account state gas for it exactly once. A transaction that cannot pay a charge made before its first frame — the account a deposit-like transaction creates for its caller, an authorization's charges, the history of the write records made outside a frame (see [History Gas](#7-history-gas)), or a charge for the first frame's start — MUST run out of gas without running a frame. +A list that the KV or state-growth limit skips is not charged, and this out-of-gas path does not apply to it (see [Resource Limits](#10-resource-limits)). Everything applied before the first frame, other than what validation did to the sender's account (its fee and a call's nonce) and the account a deposit-like transaction creates for its caller, is then taken back: the applied EIP-7702 authorizations with their nonce and delegation writes, the sender's own authorization included, their state gas and their write records. The intrinsic gas and the body's history gas stay charged, the rest of the regular budget is consumed, and what is left of the reservoir returns to the sender; the sender of a creation keeps the nonce bump the creation would have made. A deposit that runs out of gas this way is instead a failed deposit, which uses its whole gas limit, reservoir included (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). @@ -268,6 +304,7 @@ A creation that cannot pay any of the four runs out of gas and leaves no code. A node MUST charge account access to the addresses the inherited rules treat as warm from the start of a transaction — precompiles, the block beneficiary and access-list addresses listed without storage keys — as warm, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) has it: Rex6's cold charge on the first `CALL`-family or `SELFDESTRUCT`-beneficiary touch of such an address does not apply. The `SequencerRegistry`'s account and its `_currentSystemAddress` slot MUST be warm from the start of every transaction as well, the slot as an access-list storage key is: validation reads both for every transaction (see [The Live System Address](#17-the-live-system-address)). +The sender, and the recipient of a call, are warm from the start as well, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) leaves them. ### 6. State Gas and SALT Pricing @@ -283,19 +320,24 @@ Every EIP-8037 state charge MUST be `entry × m`: - `entry` — the schedule's state-gas entry: EIP-8037's byte count of the state times `COST_PER_STATE_BYTE` = 1,530. - `m` — the multiplier of the [SALT bucket](../glossary.md#salt-bucket) the state lands in, `floor(bucket_capacity / MIN_BUCKET_SIZE)` with `MIN_BUCKET_SIZE` = 256. -| State | Bytes | `entry` at `m = 1` | Bucket | -| --------------------------------------- | ----- | ------------------ | --------------------- | -| Fresh storage slot (`SSTORE` 0 → non-0) | 64 | 97,920 | The slot's | -| New account | 120 | 183,600 | The account's | -| Created contract account | 120 | 183,600 | The created account's | -| Deployed code, per byte | 1 | 1,530 | The created account's | -| EIP-7702 delegation indicator | 23 | 35,190 | The authority's | +| State | Bytes | `entry` at `m = 1` | Bucket | +| ---------------------------------------------------------------------- | ----- | ------------------ | --------------------- | +| Fresh storage slot (`SSTORE`, original and present zero, new non-zero) | 64 | 97,920 | The slot's | +| New account | 120 | 183,600 | The account's | +| Created contract account | 120 | 183,600 | The created account's | +| Deployed code, per byte | 1 | 1,530 | The created account's | +| EIP-7702 delegation indicator | 23 | 35,190 | The authority's | - A state charge MUST be made where the state is added: a fresh slot by the `SSTORE` that fills it; a new account by the `CALL` that moves value to it, by a `SELFDESTRUCT` that moves a balance to it, by the transaction whose value creates it, and by an applied EIP-7702 authorization that creates it; a created account by `CREATE`, `CREATE2` or a creation transaction. - `m` scales state gas and nothing else: regular gas never scales. - A bucket's multiplier MUST be read at most once per transaction: every later charge, and every give-back, in that bucket MUST use the same `m`, so a give-back cancels its charge exactly. - A bucket capacity below `MIN_BUCKET_SIZE`, or a capacity the node cannot read, is a fault of the node, including for a deposit: the transaction MUST NOT be priced at any multiplier or settled, and the node MUST report an internal error (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). -- A slot restored to its original zero value in the same transaction MUST give its state gas back at the price it was charged, as EIP-8037 specifies: first to the frame's regular gas, up to what the frame's state charges spilled onto it, and the rest to the reservoir. +- The only `SSTORE` that charges fresh-slot state gas is one whose original value is zero, whose present value is zero, and whose new value is not. + The only `SSTORE` that refills it is one whose original value is zero, whose present value is not, and whose new value is zero, except on an account marked for deletion (see [Resource Limits](#10-resource-limits)), and that refill MUST be the price the slot was charged, in the refill order of [History Gas](#7-history-gas). + Every other `SSTORE` transition charges no fresh-slot state gas and refills none. + That is the same transition table as the state-growth change of an `SSTORE` (see [Resource Limits](#10-resource-limits)). +- The first effective `SELFDESTRUCT` of an account created in the same transaction refills state gas for each part the [destruction table](#the-destruction-table) names. + EIP-8037 specifies that this destruction produces no state-gas refills. - The protocol's own transactions MUST be priced at `m = 1` whatever their buckets hold (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). A deposit that is not system-originated is not one of them and MUST be priced by bucket, although it pays no history gas (see [History Gas](#7-history-gas)). @@ -335,20 +377,37 @@ When each charge is made: A gas limit that cannot cover it MUST make the transaction invalid (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). The body's history gas MUST NOT be reported on the state ledger. - The records of the applied EIP-7702 authorities, and the record the transaction's own frame makes (its value's recipient or its created account), MUST be charged before the first frame. - The authorities' records are the transaction's own and MUST be kept when the first frame fails or is stopped; the first frame's record is that frame's, and comes back with it. + A list the KV or state-growth limit skips has no authority records, and that history is not charged. + The authorities' records are the transaction's own and MUST be kept when the first frame fails or is stopped. + The first frame's record is that frame's. + Its history gas comes back with that frame when the frame fails or is stopped. + When the destruction table takes that record back inside a first frame that then succeeds, the charge has already come back with the table, and the settlement MUST NOT give that history gas back a second time. + When that first frame then fails, the table's give-back is discarded with the table, and the settlement MUST give the charge back once. A transaction that runs out of gas before its first frame keeps neither: the out-of-gas takes the authorizations back with their records (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). -- A log, a storage write's record and the record of a `SELFDESTRUCT`'s beneficiary MUST be charged by the opcode, once it completed. +- A log, a storage write's record and the records of a `SELFDESTRUCT` — the account it clears and its beneficiary — MUST be charged by the opcode, once it completed, and a record the opcode takes back — a slot written back to its original value, an account a `SELFDESTRUCT` returns to what the transaction loaded, and each part the [destruction table](#the-destruction-table) takes back — MUST be given back by it then, before what it makes is charged. + A part the table takes back is given back to the destroying frame, including when another frame paid it. + Every other record is given back to whoever paid it. An opcode that fails after its write was observed — an `SSTORE` or a `SELFDESTRUCT` that cannot pay the gas it charges after its load — keeps nothing and is charged no history; a `LOG` observes its write after every charge of the inherited opcode, so only the limits and its history charge, below, can fail it after its write was observed. -- A `CALL`, `CALLCODE`, `CREATE` or `CREATE2` MUST charge its own frame for the records the frame it starts makes (a value transfer's sender and recipient; a creation's creator nonce and created account), after the gas it forwards is computed, so the forward is not reduced by them. +- A `CALL`, `CALLCODE`, `CREATE` or `CREATE2` MUST charge its own frame for the records the frame it starts makes (the accounts a value transfer changes from what the transaction loaded; a creation's created account, unless the transaction changed it already, and, when the bump changes the creator's account from what the transaction loaded, its creator nonce — see [Resource Limits](#10-resource-limits)), after the gas it forwards is computed, so the forward is not reduced by them. A caller that cannot pay MUST halt with out-of-gas, and the frame MUST NOT start. - A value `CALL` to an empty account (EIP-161) MUST charge its caller in this order: its regular gas — the access's static 100, memory, the value transfer, then the cold surcharge with the new account's regular gas, which is zero — then the new account's state gas, reservoir first, then the 63/64 forward of the regular gas left, then the history of the start's records; a state charge that spills onto the regular budget so shrinks the forward, and the records' history does not. - A `CREATE` or `CREATE2` likewise charges the created account's state gas, when the account at the created address is empty, before it computes the forward. + The price of a record the start takes back — an account the transfer returns to what the transaction loaded — MUST be given back to the caller once the frame returned with its start kept. + A value `CALL` to an empty account (EIP-161) MUST charge its caller in this order: its regular gas — the access's static 100, memory, the value transfer, then the cold surcharge with the new account's regular gas, which is zero — then the new account's state gas, reservoir first, then the 98/100 forward of the regular gas left (see [Gas Forwarding](#9-gas-forwarding)), then the history of the start's records; a state charge that spills onto the regular budget so shrinks the forward, and the records' history does not. + That forward is regular gas only. + The child is given its reservoir share after the history charge, from the reservoir the charge left the caller, and the gas the caller asks to forward does not bound the share. + A `CREATE` or `CREATE2` likewise charges the created account's state gas, when the account at the created address is empty, before it computes the forward, and gives the creation its reservoir share at the same point a call does, after the history of the start's records. - Deployed code MUST be charged at the deposit (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). -- What a frame does not keep — a failed frame's records and logs, a slot written back to its original value — MUST be given back at the price it was charged, to whoever paid it. +- What a frame does not keep — a failed frame's records and logs, a slot written back to its original value, an account returned to what the transaction loaded — MUST be given back at the price it was charged, to whoever paid it. + A part the [destruction table](#the-destruction-table) takes back is the exception: it is given back to the destroying frame, including when another frame paid it, and a failure of that frame discards the give-back. -A record an opcode commits — a storage write, a log, a `SELFDESTRUCT`'s beneficiary — MUST be checked against the limits before its history is charged, so a record a limit refuses is not charged. +Every give-back of state gas or of history gas MUST follow one refill order. +The frame's regular gas is credited first, up to the spill still outstanding on that frame, and the rest goes to its reservoir. +State charges and history charges share that spill. +A give-back inside a frame uses this order, as the rollback of a failed frame does (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + +A record an opcode commits — a storage write, a log, a `SELFDESTRUCT`'s records — MUST be checked against the limits before its history is charged, so a record a limit refuses is not charged. A frame that cannot pay that history charge MUST halt with out-of-gas, keeping neither the record nor its bytes. At a frame start the order is the reverse: the calling opcode pays for the records before the frame starts and they are counted, so a caller that cannot pay runs out of gas first, and the charge for a start a limit stops is given back when the stopped frame returns. +The opcode charges the records the start makes as the state stands when it runs: a value the caller cannot fund, which revm refuses on the caller's account, makes no record and is charged nothing, the opcode seeing the caller's balance; a creation whose creator's nonce cannot be bumped starts no frame and is charged nothing, since the creation opcode refuses it before it charges for the start, as it refuses an endowment the creator cannot fund and a call depth past the limit: revm's creation opcode makes these three checks first under EIP-8037, before it reads the created address. These MUST NOT pay history gas: @@ -385,8 +444,49 @@ Where it binds, the gas used is the floor, drawn from the whole gas limit, the r #### New behavior -- A call or creation MUST forward regular gas under the inherited [EIP-150](https://eips.ethereum.org/EIPS/eip-150) rule: at most all but one 64th of the caller's remaining regular gas. -- The child inherits the caller's reservoir whole (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +- A `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or `CREATE2` MUST cap the regular gas it forwards by Rex6's rule, in place of the [EIP-150](https://eips.ethereum.org/EIPS/eip-150) 63/64 rule: + + `forwarded_gas_cap = parent_remaining_gas − parent_remaining_gas × 2 / 100` + + `parent_remaining_gas` is the caller's remaining regular gas after the charges the opcode makes before the forward. + For a value-transferring `CALL` or `CALLCODE` those charges include the value-transfer cost of 11,300, which already contains the 2,300 stipend, so the stipend is not taken from `parent_remaining_gas` again. + The division is integer division, truncating toward zero. + The child's regular gas MUST be `min(requested_gas, forwarded_gas_cap)`, plus the 2,300 stipend for a value-transferring `CALL` or `CALLCODE` and for no other opcode. + The stipend is added to the child after the cap, and it is not taken from the caller's remaining gas. + The stipend is outside the cap, as Rex6 specifies: the cap applies to the forwarded portion, not to the stipend. + `requested_gas` MUST NOT raise the forwarded portion above `forwarded_gas_cap`. + `CREATE` and `CREATE2` have no gas operand, so each forwards `forwarded_gas_cap` and adds no stipend. + A value-transferring `CALL` whose caller has 10,000 regular gas left after the value-transfer charge forwards a cap of 9,800: the child receives 12,100 and the caller keeps 200. + The history allowance (see [History Allowance](#8-history-allowance-replaces-the-storage-gas-stipend)) stays outside the child's gas limit, as the storage-gas stipend did under Rex6. + +- The reservoir is not part of that cap. + The transaction's own frame, and a system call's outermost frame, MUST receive the whole reservoir. + A child frame MUST receive `reservoir_share = remaining − remaining × 2 / 100` of the reservoir its caller has left after every charge the caller makes for the start, the history of the start's records included, and the caller MUST keep the rest (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + `remaining` is that reservoir, under the same integer division. + The regular gas the caller asks to forward MUST NOT bound `reservoir_share`: a call that forwards no regular gas still forwards the share. + A keyless deployment's creation receives this share of the reservoir the call has left after the call's start charges (see [Native Keyless Deployment](#15-native-keyless-deployment)). + That creation's regular-gas forward is `min(gasLimitOverride, remaining gas)`, and the 98/100 cap does not apply to it, as Rex6's sandbox envelope was that minimum and the call charges nothing after the creation returns. + What the child leaves of its share MUST return to the caller by the child-merge rule of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model). + A frame that reverts or halts gives its state and history charges back as EIP-8037 specifies. + A failed child therefore returns the share it was given, whether the start was answered without building a frame (a precompile, a call to an account with no code, an interceptor's answer) or a built frame returns. + That share unwinds the caller's outstanding spill before the rest joins the reservoir the caller kept. + When the caller has no outstanding spill, the caller holds the reservoir it had after the charges it made for the start. + The caller's own charge for a leaf the child did not add is given back after that. + The reservoir share uses this gas-forwarding formula. + A frame budget under [Resource Limits](#10-resource-limits) uses `remaining × 98 / 100`, rounded down. + The two 98/100 rules are different integers. + The subtraction gives the child 98 of a remaining 99, and the whole remaining value whenever that value is below 50, so a remaining 1 gives the child 1 and the caller 0. + The frame-budget multiplication gives the child 97 of 99 and 0 of 1. +- The fraction is Rex6's. + Rex6 replaced 63/64 because MegaETH's block gas limits run up to 10 billion, and 63/64 leaves enough gas at depth 1,024 to repeat the call-depth attack 63/64 was meant to stop. + The reservoir uses the same fraction for a second reason. + Satin's state-gas prices are far above Rex6's storage-gas prices, so a hard-coded gas argument that also bounded the reservoir would fail calls Rex6's single gas pool could pay, which is why EIP-8037 passes the reservoir whole. + Satin keeps the gas argument off the reservoir. + The caller keeps `remaining × 2 / 100`, and the child receives the share. + When `remaining` is below 50 that product is 0, so the child receives the whole reservoir and the caller keeps none of it. + A reservoir of 1 is that case. + A child that spends its whole share leaves the caller what the caller kept, which a gas argument of zero would not. + A system-originated transaction and a system call are exempt from the per-transaction limits (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)) and are not exempt from this split: the split is how the reservoir is handed to a child, not a limit. ### 10. Resource Limits @@ -399,41 +499,325 @@ Where it binds, the gas used is the floor, drawn from the whole gas limit, the r #### New behavior -One dimension is limited per transaction, data size; compute is not one (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)), and neither are KV updates or state growth. +Data size, KV updates and state growth are limited per transaction. +Compute is not a fourth limit (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)): it is regular gas, bounded by the execution cap and by gas detention. + +| Dimension | Counted in | Transaction limit | Frame budget | +| ------------ | -------------------------- | ------------------------------- | ------------ | +| Data size | Bytes of the byte table | `TX_DATA_LIMIT` = 13,107,200 | Yes | +| KV updates | Write records | `TX_KV_UPDATE_LIMIT` = 500,000 | Yes | +| State growth | New accounts and new slots | `TX_STATE_GROWTH_LIMIT` = 1,000 | Yes | -| Dimension | Counted in | Transaction limit | Frame budget | -| --------- | ----------------------- | ---------------------------- | ------------ | -| Data size | Bytes of the byte table | `TX_DATA_LIMIT` = 13,107,200 | Yes | +The same KV and state-growth numbers limit a block: `BLOCK_KV_UPDATE_LIMIT` = 500,000 and `BLOCK_STATE_GROWTH_LIMIT` = 1,000 (see [Block Limits](#20-block-limits)). - **Data size** counts the byte table of [History Gas](#7-history-gas), plus two items that pay no history: an EIP-7708 transfer log, counted as `TRANSFER_LOG_SIZE` = 160 bytes (a `LOG3` of one word), and an Oracle hint's payload, counted by its length before it is forwarded. - It counts the body before any frame; the applied authorities' records before the first frame; a frame start's records and transfer log when the frame starts; a storage write's record, a log, and a `SELFDESTRUCT`'s beneficiary record and transfer log once the opcode completed; deployed code once every deposit charge is made and before the creation commits; a hint before it is forwarded, on the transaction and on no frame's budget, unless it would cross the transaction's limit, in which case it is neither counted nor forwarded (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). + It counts the body before any frame; the applied authorities' records before the first frame; a frame start's records and transfer log when the frame starts; a storage write's record, a log, and a `SELFDESTRUCT`'s records (the account it clears and its beneficiary) and transfer log once the opcode completed; deployed code once every deposit charge is made and before the creation commits; a hint before it is forwarded, on the transaction and on no frame's budget, unless it would cross the transaction's limit, in which case it is neither counted nor forwarded (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). A deposit's data size is counted like any transaction's, and a deposit that fails keeps what it counted: its body and the hints it admitted. - **Write records.** - One record per account or storage write the transaction keeps: a slot's first change in the transaction (taken back when the slot is written back to its original value); a value transfer's sender and recipient; a creation's creator nonce and created account; a `SELFDESTRUCT` that moves a balance to another account (its beneficiary); an applied EIP-7702 authority; the transaction's value recipient or created account. - The sender's account is one of the body's five fixed records and MUST NOT be counted as a record again, whatever writes it: a frame running as the sender, a value transfer or a `SELFDESTRUCT` that moves value to the sender, an applied EIP-7702 authority that is the sender, and a keyless deployment whose signer is the sender record nothing for it. - The four fee accounts are in the body only for the fee credits the transaction's settlement makes: a write execution makes to a fee account that is not the sender — for example a value transfer to it, a `SELFDESTRUCT` that moves a balance to it, or an applied EIP-7702 authority that is one of them — MUST be recorded like a write to any other account. - Records MUST be deduplicated per frame, not per transaction: a frame records an account once, and each value-transferring call records its target on the lane of the frame it starts, which merges into the caller's when the call succeeds. - N value transfers from one frame to the same recipient keep N records and pay N records' history gas, so a transaction's record count is an upper bound on the accounts it wrote, like the body's fixed fee-account records. - A value-transferring `CALLCODE` moves the value from the calling account to that same account: it MUST record that account once, as the transfer's sender, with no recipient record beside it, and pay one record's history gas — or nothing, if the calling frame has already recorded its account. - A value-transferring `CALL` to the calling account itself MUST likewise record that account once, its recipient being its sender, and pay one record's history gas — or nothing, if the calling frame has already recorded its account. - A successful frame's records and bytes MUST merge into its caller's; a failed frame's MUST be discarded, except that a creator's nonce record survives its creation's failure once the nonce was bumped, and lands on the creator. - The KV count is the write-record count; every record weighs `WRITE_RECORD_SIZE` bytes of data size, counted and taken back with it, so `KV × 40 ≤ data size` at every point. - No limit holds the KV count: the data-size limit bounds it — a transaction keeps fewer than 327,680 write records (13,107,200 / 40) — and history gas prices every record (see [History Gas](#7-history-gas)). + One record per account or storage write the transaction keeps. + A storage slot's record exists while the slot's value differs from its original value in the transaction: the slot's first change makes it, and writing the slot back to its original value takes it back. + An account's record exists while the account's nonce, balance or code differs from what the transaction loaded — the account's original info, which revm sets at the account's first load in the transaction: a write that changes an unchanged account makes the record, a write that returns a changed account to what was loaded takes it back, and a write to an account that already differs adds nothing. + The writes: a value transfer's sender and recipient, on the balances the transfer leaves them; a creation's created account, which the creation leaves changed by its nonce, and the creator's nonce it bumps; a `SELFDESTRUCT`'s beneficiary and the account it clears; an applied EIP-7702 authority; the transaction's value recipient or created account. + A created account is no exception: an address the transaction changed before a creation lands on it — a value transfer funded it, or a `SELFDESTRUCT` paid it — differs already, and the creation adds no record for it. + A record is made where the write is and taken back where a write returns the account: a value transfer that returns an account to what the transaction loaded takes the record back in the frame the transfer starts, with its data size, and the history gas the record cost comes back to the caller once that frame returned with its start kept (see [History Gas](#7-history-gas)), as a storage slot written back gives its record back; a `SELFDESTRUCT` whose move returns an account takes the record back where the opcode completed. + The first effective `SELFDESTRUCT` of an account created in the transaction takes back, where the opcode completed, each write record the [destruction table](#the-destruction-table) names, and it leaves the record of a part that existed at the transaction's start. + Deployed code the table takes back returns its data size and its history gas there, and code is not a write record. + From that mark the account and its slots keep no further record, the account's logs stay charged, and a failure of the destroying frame discards the takeback, as the destruction table specifies. + So N value transfers from one frame to the same recipient keep one record for it and one for the sender, the first transfer having changed both; a transfer and its exact return keep none; a recipient that passes on exactly what it received keeps none of its own; a frame that funds an address and then creates at it keeps two records, its own and the address's: the transfer changed both, so neither the creator's nonce bump nor the creation adds one. + A value-transferring `CALLCODE` moves the value from the calling account to that same account, and a value-transferring `CALL` to the calling account itself likewise: neither changes an account, and neither records one. + The sender's account is one of the body's five fixed records and is never recorded again: validation changes it before execution, by its fee and a call's nonce, and a creation transaction's first frame by its nonce, so no write execution makes to it — a frame running as the sender, a value transfer or a `SELFDESTRUCT` that moves value to the sender, a keyless deployment whose signer is the sender — changes it from what the transaction loaded. + An applied EIP-7702 authority is changed by its nonce and its delegation when it is applied: a write to it afterwards adds nothing, the transaction's own value to it included. + The four fee accounts are in the body only for the fee credits the transaction's settlement makes, and are unchanged until execution writes them: a write execution makes to a fee account that is not the sender — for example a value transfer to it, a `SELFDESTRUCT` that moves a balance to it, or an applied EIP-7702 authority that is one of them — is recorded like a write to any other account. + A successful frame's records and bytes MUST merge into its caller's; a failed frame's MUST be discarded, the records it took back standing again, except that a creator's nonce record is the creating frame's: it MUST be counted on the creator once the creation returned with the nonce bumped, held to the creator's budget and not the creation's, and it survives the creation's failure. + The creation's budget MUST be the share taken at the opcode, before that record. + The KV count is the write-record count. + Every record weighs `WRITE_RECORD_SIZE` bytes of data size, counted and taken back with it, so `KV × 40 ≤ data size` at every point. + History gas prices every record (see [History Gas](#7-history-gas)). + `TX_KV_UPDATE_LIMIT` = 500,000, and the limit is enforced on that count. + A write record taken back cannot cross it. + At these constants 500,000 records weigh 20,000,000 bytes, more than `TX_DATA_LIMIT`, so the data-size cap is the tighter of the two. + That comparison is of the caps. + Under the execution cap a transaction cannot pay the regular gas of enough writes to reach either number, and the KV check is still made. + A later change to the byte weight or to the data-size cap does not retire it. + The count differs from Rex6's KV count where the write record differs, and each difference is that record: + - The sender and the four fee credits are the body's fixed records and are not KV. + Rex6 counts the caller as one KV update that cannot be discarded, and counts each distinct fee recipient after the result, where the count cannot change the outcome. + The body already bounds those writes, and a transaction that writes nothing keeps no record. + - Deduplication is the transaction-wide net change, not once per frame. + The record is the account or slot the transaction keeps changed, which is what history gas prices. + - A creation refused before the creator's nonce is bumped counts nothing, because nothing was written. + Rex6 records the creator even when no bump follows. + - Each applied authority is one record while the account differs from what the transaction loaded, not one record per authorization. + One account was changed once. + - Logs, deployed code, EIP-7708 transfer logs and Oracle hint payloads are not records, as they are not KV updates under Rex6 either. - **Frame budgets.** - The transaction's own frame MUST get what the transaction has left once its body and pre-frame records are counted; every child MUST get `FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR` = 98/100 of what its parent has left, rounded down. + Data size, KV updates and state growth each have a frame budget. + The transaction's own frame MUST get what the transaction has left in that dimension once the body and the pre-frame counts are counted. + Every child MUST get `parent_remaining × FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR`, where `FRAME_DATA_SHARE_NUMERATOR` = 98 and `FRAME_DATA_SHARE_DENOMINATOR` = 100, rounded down. + `parent_remaining` is what the parent has left in that dimension, and the three dimensions share one definition of it. + A frame's net in a dimension is signed: what it added, minus what it gave back, plus the nets its successful children merged in. + A fall, a write record taken back, or data size given back can make that net negative. + The frame's remaining is `min(budget, max(0, budget − net))`. + It stays inside the budget the frame was given, including when the net is negative, so a negative net does not raise what the frame forwards. + The transaction's net is what sits on no frame — the body, the applied authorities' records, a deposit's caller and every admitted hint — plus the net of every frame on the stack. + A frame's net includes a child's only after that child succeeded and the net merged, so a failed frame's net is not part of the transaction's net. + The transaction's remaining is the same clamp of that net against the transaction limit, and it never exceeds that limit. + A child that receives this share therefore receives at most 98/100 of the budget its parent was given. + A frame with a state-growth budget of 1,000 that has added 100 has 900 left, and the child it starts receives 882. + If that child removes those 100, its net is −100 and its remaining stays 882, so the frame it starts receives 864. + When a frame succeeds, its signed net merges into its caller and the caller's remaining is computed again from the caller's own budget. + The merge can raise the caller's remaining up to that budget. + After the child above succeeds, the caller's net is 0 and its remaining is again 1,000, so a later child receives 980. + When a frame fails, its net is discarded, its caller's net is unchanged, and the credits inside the failed frame are discarded with it, the state-gas refill, the write-record takeback and the code data size and history gas of a same-transaction destruction included. + A fall with no earlier rise leaves the frame's remaining at its budget. + Later rises may consume that fall, and the kept net still cannot pass the budget. + The count a transaction reports for KV updates and for state growth is `max(net, 0)`. + The fraction is the data-size share, and KV and state growth use the same one. + A `CREATE` or `CREATE2` MUST take the child's share of what the creator has left: the creation receives `parent_remaining × 98 / 100`, rounded down. + The creator's nonce record, and the creator's state growth when the bump creates the creator, MUST be counted on the creator when the creation returns. + The created account's write record and its state growth are the creation's own rise, checked against that budget. + A creation transaction's own frame is not that child. + It receives the whole of what the transaction has left after the body and the pre-frame counts, as every transaction's own frame does. + A creator that has 1,000 of state growth left, and whose nonce bump adds none, gives the creation a state-growth budget of 980. Satin sets no further per-frame cap. + This multiplication is the frame-budget rule. + The gas-forwarding rule is the subtraction in [Gas Forwarding](#9-gas-forwarding), and the two integers differ at some remaining values. A frame that crosses its budget MUST revert with `MegaLimitExceeded(kind, budget)` and its caller continues. - The budget keeps a caller's own work within reach of what it calls: a child inherits its caller's whole reservoir and history gas draws the reservoir first, so EIP-150's 63/64 forwarding does not bound the bytes a child can append, and without a budget a callee could take the transaction to its limit and leave its caller, which can catch the stop (see [The Revert-Class Stop](#11-the-revert-class-stop)), nothing to carry on with. -- **State growth** is not limited. - EIP-8037 charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), so what bounds state growth is what it costs: the transaction's gas limit and the block's. - That the bound stays within the state growth the chain's storage sustains is a property of the state-gas prices, not of a limit. + The budget keeps a caller's own work within reach of what it calls. + A child receives 98/100 of its caller's remaining regular gas and 98/100 of its caller's remaining reservoir, and state gas and history gas draw the reservoir first, so the gas forward alone does not bound what a child can append. + Without a frame budget, and without the reservoir share the caller keeps, a callee could take the transaction to a limit and leave its caller, which can catch the stop (see [The Revert-Class Stop](#11-the-revert-class-stop)), nothing to carry on with. + The retained fraction is a share the caller keeps, not a gas argument: the gas the caller asks to forward does not bound the reservoir (see [Gas Forwarding](#9-gas-forwarding)). +- **State growth** is the net count of new accounts and new storage slots the transaction keeps. + Each rise is one unit, at an EIP-8037 account-leaf or fresh-slot charge site (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), and not one unit per byte of deployed code or of a delegation indicator. + State gas still prices those bytes. + The count is what `TX_STATE_GROWTH_LIMIT` holds. + The rises are: + - a fresh slot, and only the `SSTORE` transition named below; + - a value `CALL` to an account that is empty under EIP-161; + - a `SELFDESTRUCT` that moves a non-zero balance to an account that does not exist; + - the recipient a transaction's value creates; + - an applied EIP-7702 authorization that creates its authority; + - a `CREATE`, a `CREATE2`, a creation transaction, or a keyless creation, when the created address is empty; + - the keyless signer's account, when the creation's nonce bump creates it, counted on the keyless call; + - the caller account a deposit-like transaction creates, charged once (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + An account that already exists is not a rise, and neither is a `CALLCODE`, a value call to the calling account itself, deployed code, or the 23-byte delegation indicator. + An `SSTORE` changes state growth only by the table below. + The columns are the slot's original value in the transaction, its present value, and the value written. + The state-growth change is the same transition as the fresh-slot state-gas charge or refill (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)). + +| Original | Present | New | State growth | +| -------- | -------- | -------- | ------------ | +| zero | zero | zero | none | +| zero | zero | non-zero | +1 | +| zero | non-zero | zero | −1 | +| zero | non-zero | non-zero | none | +| non-zero | zero | zero | none | +| non-zero | zero | non-zero | none | +| non-zero | non-zero | zero | none | +| non-zero | non-zero | non-zero | none | + +A no-op writes the present value and is one of the rows that change nothing, including original zero, present zero, and new zero. +A rewrite of a slot that is already non-zero, and whose original value is zero, changes nothing: the rise was the write that first made it non-zero. +A slot whose original value is not zero changes nothing on every transition, including present zero and new non-zero. +A slot written from zero to a non-zero value and then to another non-zero value rose once. +A slot written from zero to a non-zero value and then back to zero has a net of zero. +A slot written from zero to a non-zero value, back to zero, and then to a non-zero value again rose on the first write, fell on the second, and rose on the third. +The fee credits the settlement writes are not rises. +They are not EIP-8037 charge sites. +Rex6 recorded each distinct fee recipient after the result, where the count could not change the outcome. +Satin does not: the body's five fixed records already bound those accounts for data size, and a count taken after the result cannot stop the frame that wrote them. +The falls happen at the opcode that restores the state. +A fall cannot cross a limit. +The only slot fall is the table's row of original zero, present non-zero, and new zero, and its state gas is given back as [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing) specifies. + +##### The destruction table + +The first effective `SELFDESTRUCT` of an account created in the same transaction applies the table below to every part of that account. +The columns are the part's value at the transaction's start, its value before the destruction, and deleted. +A slot's value at the transaction's start is its original value in the transaction: the value it held when the transaction first accessed it. +A slot of the created account that the transaction first accesses after the creation reads zero, whatever the state held there, and so has an original of zero. +A slot the transaction accessed before the creation keeps the value it held then as its original, and holds that value, or what the transaction writes to it, afterwards. +A part the transaction made, absent at the start, is refilled and taken back. +A part that existed at the start is an ordinary deletion. + +| Part | At the transaction's start | Before | After | Effect | +| ------------- | -------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Account leaf | absent | present | deleted | refill the leaf's state gas; state growth −1; take the account's write record back | +| Account leaf | present | present | deleted | nothing: the leaf existed before the transaction, and its write record stands | +| Deployed code | absent | present | deleted | refill the code deposit's state gas; take back its data size and its history gas | +| Deployed code | absent | absent | deleted | nothing | +| Deployed code | present | present | deleted | not reached: non-empty code at the start collides with the creation | +| Slot | zero | non-zero | deleted | refill the slot's state gas; state growth −1; take the slot's write record back | +| Slot | zero | zero | deleted | nothing: the slot is already clear | +| Slot | non-zero | any | deleted | nothing of the refill or the fall. The write record of a slot the transaction loaded stands, and the deletion makes it when that loaded slot still holds its original value. A slot the transaction did not load has no record | + +A refill MUST be the price that part was charged, the schedule entry times the bucket multiplier of that charge, and it MUST go to the destroying frame, including when another frame paid it. +On the absent row, the account leaf's charge is the one this transaction made for that leaf: at the value transfer that funded the address, at a `SELFDESTRUCT` that paid it, at the transaction's own value, or at the creation when the created address was empty. +State growth falls for the absent leaf and for each slot on the zero, non-zero, deleted row, and for nothing else in the table. +The fall of the absent leaf stands even when the creation itself added no rise, as when the transaction funded the address and then created onto it. +An address that held a balance before the transaction is the present row: the creation adds no rise for that leaf, the destruction subtracts none, and the write record the nonce bump made stands. +The write record taken back returns its data size to the destroying frame's budget and its history gas to that frame, and the KV count falls by that record. +When the destroying frame is the transaction's own frame and that frame succeeds, this return is the record's history gas, once. +The settlement of that frame MUST NOT give the same charge back again (see [History Gas](#7-history-gas)). +Deployed code is not a write record and not a unit of state growth. +Code on the absent, present, deleted row returns its data size and its history gas the same way. +The give-back MUST follow the refill order of [History Gas](#7-history-gas). +It is a give-back of state gas or of history gas, as a slot written back to zero is, and not an EIP-3529 refund. +EIP-8037 specifies that this destruction produces no state-gas refills, and Rex6 refunded none of the storage gas. +Satin refills the state gas because a part the transaction made does not remain for a node to store, so the count and the charge stay aligned. +It MUST be credited with the completed write, after every charge the opcode makes: a charge the frame cannot pay halts the opcode first, and the give-back is not credited. +The give-back MUST NOT raise that frame's remaining above the budget it was given. +When the destroying frame succeeds, the give-back is unspent gas of that frame and returns up the chain. +When the destroying frame fails, or a frame that contains it fails, the mark and every effect of the table are discarded. +The charges then stand, or come back by the ordinary rule for that failure, and a record the table took back stands again. +The discarded give-back is not a further one. +A later `SELFDESTRUCT` of the same account, while the mark stands, applies the table again for nothing: it subtracts nothing, refills nothing and takes nothing back. +A `SELFDESTRUCT` of an account that was not created in the transaction does not apply the table. +It subtracts nothing, refills nothing, and does not mark the account. +EIP-6780 does not delete that account. +From the first effective destruction until the end of the transaction, while the mark stands, the account adds nothing further to state growth and keeps no further state gas. +An `SSTORE` of one of its slots in that span does not rise, does not fall, and neither charges nor refills fresh-slot state gas. +The `SSTORE`'s regular gas is unchanged. +A slot the table already refilled therefore cannot be charged or refilled again. +Code on the absent, absent, deleted row was not deposited when the account was destroyed: a constructor can destroy the account before its code is deposited. +That later deposit's state gas MUST NOT be charged. +Its data size and history gas MUST be charged as any deposited code, and no later destruction takes them back. +Value sent to the marked account afterwards is not a rise, and it makes no write record. +The account still exists until the transaction ends, and it is removed then with the balance it holds (see [EIP-7708 Transfer Logs](#14-eip-7708-transfer-logs)). +From the mark until the transaction ends, a write to the account or to one of its slots makes no record. +The account's logs, and the transfer log of the balance moved, stay counted and stay charged: a log is history the transaction appended, and the transfer log is data size the move made. +Removing the account at the end of the transaction does not take a record back again, and it does not take the code's data size or history gas back again. +A creation collides when the address holds non-empty code or a nonce other than zero, and it does not collide on storage. +EIP-7610 would refuse a creation onto non-empty storage, and it says that rule applies retroactively. +Ethereum's clients apply it, and so do the execution-spec fixtures, including the Osaka files under `paris/eip7610_create_collision`. +Satin does not apply it: the engine reads storage slot by slot and cannot see storage it has not loaded, so it cannot see a collision with storage alone. +The execution-spec gate skips those fixtures for that reason. +A creation can therefore land on an address with nonce zero, empty code and storage. +Execution that has always applied EIP-161 and EIP-6780 does not produce that address: a creation sets the nonce to one, and a same-transaction destruction deletes the account. +The address can still be in the state a block is given. +A slot of it that the transaction first accesses once the account is created reads zero and is on a zero row, and a slot the state held that the transaction never accessed makes no record when the account is destroyed. +The non-zero slot row is a slot of that address the transaction accessed before the creation: it keeps the value it held, and the destruction deletes it with the account as an ordinary deletion, which makes its write record while it still holds that value. +An account that is empty under EIP-161 while its leaf is already in the state the transaction loaded — nonce zero, balance zero, empty code, and storage that is not empty — is the present-leaf row. +The creation may still charge new-account state gas and count a rise, because the address is empty under EIP-161. +That row does not refill the charge and does not subtract the rise. +A `SELFDESTRUCT` that moves a non-zero balance to a distinct account that does not exist is still a rise, a repeated destruction included. +A zero balance creates no account and is not a rise, on a first destruction or a repeated one. +That rise is held to the limits only after the operation's give-back. +The give-back cannot cross a limit. +A frame that is exactly at its state-growth budget, and that destroys an account created in the transaction while moving a non-zero balance to a new beneficiary, subtracts the leaf only when the leaf was absent at the transaction's start, and subtracts one for each of the account's new slots, before it adds the beneficiary. +When the leaf was absent and the account has N new slots, the subtraction is `1 + N` and the beneficiary fits. +When the leaf was present, the subtraction is N, and the beneficiary fits when N is at least one. +Compute is decided before the opcode completes. +A regular charge that crosses gas detention stops the frame at that charge, and the operation applies none of the table and no beneficiary. +The operation first gives back what the table takes back: the state-growth falls, the state-gas refills, the write records, and the deployed code's data size and history gas. +That give-back is part of the completed write, after every charge the opcode makes. +A part taken back is given back before the positive effects are held, as [History Gas](#7-history-gas) requires. +The operation's positive effects are then held, in the dimension order data size, KV updates, then state growth: the records the operation makes — the account it clears, when that account was not created in the transaction and this write makes its record; a loaded pre-existing slot of an account the table covers, when the deletion is what makes that slot's record; and its beneficiary — and its transfer log, then the beneficiary's state growth. +Within each dimension they use the rule in **Order at one site** below. +When a positive effect crosses, the frame stops and the operation keeps nothing: the table's effects, the beneficiary and the transfer log are discarded with it. +The rises and falls are the frame's, as its write records are. +A successful frame's net MUST merge into its caller. +A failed frame's net MUST be discarded. +A child's net is negative when it removes more state growth than it added. +That negative contribution lets a child undo state its caller added, and the remaining that sizes the next frame is the clamp in **Frame budgets** above, so the negative net does not enlarge the child's budget. +The state growth a transaction reports is `max(net, 0)`. +A rise that would make the signed net exceed the transaction limit or the frame budget is the crossing, and that rise MUST NOT be kept. +`TX_STATE_GROWTH_LIMIT` = 1,000. +At `m = 1` a fresh slot costs 97,920 state gas, so 1,000 fresh slots cost 97,920,000, which a transaction's gas limit can cover. +The count is what stops the 1,001st slot. +The gas price does not stand in for the count. +A failed deposit that creates its caller, when that account did not exist, counts that account as one toward the transaction's reported state growth and toward the block counter. +It pays no state gas for the account (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and the limit does not stop the deposit, which has already failed. +The account is state the block keeps, so a block of such deposits cannot pass the cap while reporting no state growth. +A deposit that runs to a success or a revert and creates its caller is the ordinary charged rise of one, and a stop of its first frame keeps that account (see [The Revert-Class Stop](#11-the-revert-class-stop)). + - **Order at one site.** - A record that crosses the transaction's data-size limit and its frame's budget at once MUST stop its frame with the transaction's limit in the revert data: the transaction limit is checked before the frame budget. -- **A frame start** is counted before the frame is built. - A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing, be charged nothing, and be stopped by no limit. - A creation onto an occupied address is counted, and a crossing it causes stops it where it would otherwise have failed on the collision. + At a completed write or a decided frame start, an operation that crosses more than one of data size (kind 0), KV updates (kind 1) and state growth (kind 3) MUST stop on the first of those three, in that order. + The order is Rex6's order across dimensions. + Compute (kind 2) is decided at the regular charge, before the write is counted. + A regular charge that crosses gas detention means the opcode does not complete, so the operation's data size, KV updates and state growth are not counted, and kind 2 is the stop because the write did not happen. + A call to a precompile is the exception: the value has already moved when the price is consulted, so the start's records are decided before the price. + Those records MUST be held to these limits first, in the order of this section. + The price is kind 2 only when the start kept within them. + A value the caller cannot fund runs no precompile, counts nothing and is stopped by no limit. + The same order applies when a precompile the node cannot price runs out of the allowance: the start's records are held first, and running out of the allowance is kind 2 only when the start kept within them. + The exception begins at the price: the call's own regular charges — its static 100, its memory, the 11,300 value transfer and a cold access — MUST be decided first, as any opcode's, and one that crosses MUST stop the calling frame before anything moves, whether or not the caller can fund the value. + Inside data size, KV updates and state growth, the frame budget MUST be tested before the transaction limit. + When the frame budget is crossed, the stop MUST name that budget, and `limit` is that budget, including when the transaction limit of the same dimension is crossed too. + When the frame budget is not crossed, a crossing of the transaction limit MUST name that limit, and `limit` is the transaction limit. + The frame budget is not crossed when none applies, and also when the frame's own budget still holds the write. + No frame budget applies to an Oracle hint's bytes, which are counted on the transaction and on no frame, or to the authorization list, which is decided before the first frame (see above). + A framed write can cross the transaction's data-size limit alone after hints have used what the transaction had left, while the frame's own budget still holds the write, and the stop then names the transaction limit. + The admitted hint bytes stay counted. + A framed write of KV updates or of state growth cannot cross the transaction limit without crossing its frame budget: once a frame is running, those dimensions have no usage that sits on the transaction and on no frame, and a child's budget is a share of what its parent has left. + The body is refused at validation, so it does not cross at runtime. + Gas detention remains kind 2 (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). +- **A frame start** is held to the limits once it is decided: once the value moved and, for a creation, the creator's nonce was bumped and the created account made. + A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing, be stopped by no limit, and be charged nothing at its opcode (see [History Gas](#7-history-gas)). + A creation onto an occupied address fails on the collision after its creator's nonce was bumped, and MUST NOT be stopped for what its start would count: its failure discards the created account's record and its transfer log, and the creator's nonce record, which survives it, MUST be counted on the creator when the creation returns, the creator held to its limits with it. + The created account was not new, so the collision adds no state growth. + The creator's nonce record is KV on the creator, and state growth only when the bump creates the creator's account, as a keyless signer's bump can. +- **Authorizations before the first frame.** + Before the first frame, a node MUST decide the list by simulating [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) application in list order. + The simulation writes nothing and warms nothing. + An entry whose chain id is neither zero nor this chain's, whose nonce is 2^64 − 1, or whose signature does not recover an authority, is skipped, and its authority account is not read. + Every other entry loads the authority's account, with its code. + An authority account that holds code other than a delegation is skipped, and its simulated nonce is not bumped. + The authorization's nonce is then compared with the authority's effective nonce. + When an earlier entry for the same authority was accepted in this list, the effective nonce is the simulated nonce after those acceptances. + When the authority is the sender and no earlier entry for it was accepted, the effective nonce is the sender's nonce after validation's bump: an authorization signed for the sender's nonce before the transaction does not match. + Otherwise the effective nonce is the account's current nonce. + A nonce that differs skips the entry. + A nonce that matches would apply. + The simulated nonce then becomes one higher. + The simulation MUST walk the whole list, and it MUST NOT stop at the first entry that would cross a limit. + Each distinct authority whose entry passed the chain-id, nonce and signature gates is loaded once. + A later entry for that authority uses the simulated nonce and the code already loaded. + A failure to read an authority the simulation consults is a database fault: the transaction has no outcome. + When the node's database declares that error fatal, the node reports an internal error; any other database error makes the block invalid. + The block is not refused for the limit (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + This holds when an earlier prefix of the list would already have crossed. + The simulation charges no cold-access gas. + The intrinsic 7,816 per entry is already charged at validation, for every entry, applied or not. + The totals the list would keep, were it applied, are one KV write record for each distinct authority it would change, other than the sender, whose account is the body's record; one state-growth unit for each distinct authority it would create, however many of its entries are accepted; and account-creation state gas once for each such new authority. + Delegation-indicator state gas is charged at most once per authority. + It is charged only when an accepted authorization writes a non-zero delegation designator, the authority holds no delegation indicator at the start of the transaction, and no earlier authorization in the list set one for that authority. + An authority that holds an indicator at the start of the transaction is charged none for it, a clear and a later non-zero authorization included. + A clear charges none. + Two accepted non-zero authorizations for one authority that holds none at the start charge the indicator once. + A zero delegation target still bumps the nonce and can create the account, and it charges no indicator. + The indicator is not a unit of state growth. + Repeated acceptances of one new authority create it once and keep one KV record. + 1,000 new authorities fit `TX_STATE_GROWTH_LIMIT`, and 1,001 do not. + If those KV or state-growth totals would exceed the transaction's limit, the node MUST apply none of the list, charge none of the authority state gas or record history, and MUST stop the transaction's own frame before it runs, with `MegaLimitExceeded` of the crossed kind and that transaction limit. + No frame budget exists yet, so the stop names the transaction limit. + When both KV and state growth would be crossed, the kind is 1. + Data size cannot be crossed here, and compute does not apply. + The body's data size, with a record for each authorization entry, is already refused at validation when it exceeds `TX_DATA_LIMIT` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)), so a transaction that passes validation is not over the data-size limit before its authorizations are applied. + A skipped list keeps no authority account, no authority write record, no authority state gas and no authority history. + The intrinsic regular gas, the body's history gas and the body's data size stay. + No delegation is written, and no authority nonce is bumped beyond the sender's validation bump. + The consulted authorities are not made warm, except an authority that was already warm from the start of the transaction: the sender, the recipient of a call, the block beneficiary, an access-list address, a precompile, or the `SequencerRegistry`'s account (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + The witness MUST hold every authority account the simulation loaded, with the code the chain held, whether or not the list is applied (see [The Stateless Witness](#22-the-stateless-witness)). + The skip is all or nothing, including an authority that would have fitted by itself. + That all-or-nothing skip is Rex6's rule for this list. + Satin settles it as this revert-class stop rather than Rex6's halt: a stop of the first frame does not revert pre-frame writes (see [The Revert-Class Stop](#11-the-revert-class-stop)), so applying the list would keep more than the limit allows. + When the list fits, it is applied, and EIP-7702 warms every authority whose account the application loads. + An entry skipped for its chain id, for a nonce of 2^64 − 1, or for a signature that does not recover an authority is not loaded, and it is not warmed. + An entry skipped because the authority's code is not a delegation, or because the nonce does not match, is loaded by the application before that check, and that authority is warmed. + The state gas and the history of the authority records are charged then. + Those counts reduce what the first frame is given. + If one of those charges cannot be paid, the transaction takes the out-of-gas path of [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas): the authorizations are taken back, and for a non-deposit this is an out-of-gas halt, not the limit stop. + The limit is decided before those charges, so a list that does not fit never takes that path. + When the list fits, a later stop of the first frame keeps the authorizations. + The caller account a deposit creates is not an authorization. + It is always created and kept, and it is one account, so it cannot by itself cross `TX_STATE_GROWTH_LIMIT`. + The check is made where the accounts are read, during execution. + Validation that does not read state cannot tell which authorities are new, so the skip is not a pool rejection. + At the spec's gas numbers the execution cap admits at most 25,587 authorizations, so the KV form of the skip is not reached. + The state-growth form is: the state gas of 1,001 new authorities fits in a gas limit above the execution cap. - **The limits are fixed per spec.** - The transaction's data-size limit, the per-frame share, the detention caps (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) and the block's data-size limit (see [Block Limits](#20-block-limits)) are protocol values of the Satin spec, the same on every chain. + The transaction's data-size, KV and state-growth limits, the per-frame share, the detention caps (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)), and the block's data-size, KV and state-growth limits (see [Block Limits](#20-block-limits)) are protocol values of the Satin spec, the same on every chain. They are not chain configuration: no chain configuration carries them, and a node MUST hold every Satin transaction and block to them, never to values a configuration names or a node is handed with a block. A later spec that changes one states its own value. A node MUST hold the transactions of block execution and validation, the executions whose result the chain agrees on, to these values. @@ -450,7 +834,15 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw #### New behavior -Every limit — the transaction's data-size limit, a frame's data-size budget, and gas detention's compute limit — MUST stop the frame that crosses it with a revert, never a halt. +Every limit, the transaction's data-size, KV and state-growth limits, a frame's budget in those dimensions, and gas detention's compute limit, MUST stop the frame that crosses it with a revert, never a halt. +A _limit stop_ is that revert, in exactly the four dimensions the revert data below enumerates: data size (kind 0), KV updates (kind 1), compute under gas detention (kind 2) and state growth (kind 3). +Nothing else is a limit stop, and in particular these inherited endings, each of which enforces a size or a payment, are not: + +- initcode over `MAX_INITCODE_SIZE`, for which a non-deposit creation transaction is rejected at validation, a creation opcode halts the creating frame and a keyless deployment is refused with `InitCodeTooLarge` (see [Native Keyless Deployment](#15-native-keyless-deployment)), and deployed code over `MAX_CONTRACT_SIZE`, which halts the creation (see [Contract Size Limits](#3-contract-size-limits)); +- an input over an OP precompile's size limit — the BN254 pairing's and the BLS12-381 MSMs' and pairing's — which the precompile refuses before any gas check, halting the call and consuming its forward (see [Precompiles](#2-precompiles)); +- a failed deposit, which uses its whole gas limit and reports no stop (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)); +- a charge made before the first frame that the transaction cannot pay, which runs out of gas without running a frame (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + The stop applies to a transaction that passes validation and pays every charge made before its first frame. A transaction that fails validation, or that cannot pay a charge made before its first frame (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)), MUST report no stop: a non-deposit transaction that fails validation is rejected, and a deposit that fails validation — a system deposit, which the inherited rules refuse under Regolith, and a deposit whose body is over the data-size limit included — or that cannot pay a charge made before its first frame is included as a failed deposit, whatever kind of deposit it is (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). The body of such a deposit MUST stay counted as data size. @@ -459,28 +851,35 @@ For a transaction the stop applies to: 1. The frame that crosses a limit MUST revert with `MegaLimitExceeded(uint8 kind, uint64 limit)` as its output. The write or the charge that crossed MUST NOT be kept or made, and every write and log the frame made MUST be reverted, as a `REVERT` reverts them. 2. Its caller MUST resume as after any revert: the call fails, its return data is the stop's revert data, and the gas the frame had — before the charge that crossed, for gas detention's limit — returns to the caller, its reservoir included. -3. What the frame counted MUST be discarded with it, so the caller resumes within every limit. - A caller that carries on is held to what the transaction has left: a write or a charge of its own that crosses a limit again MUST stop the caller's frame in turn. - A transaction therefore never keeps more data size than its limit, and never computes past gas detention's limit but by what [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas) allows. -4. A caller that catches the stop MUST run on as after any failed call: a transaction whose frames catch every stop below its own frame MAY succeed, keeping what its frames did and nothing of a frame that was stopped. +3. What the frame counted MUST be discarded with it, so the caller resumes within every limit, but in one case. + A failed frame's discard puts back what the frames above it kept when it started, a record of theirs it took back included, while an Oracle hint it admitted stays counted (below); a hint sent into the room such a take-back freed leaves the transaction over its data-size limit once the frame fails. + The frame it returns into MUST then return the stop of the transaction's data-size limit before it runs another instruction, whether the frame below reverted, halted or was itself stopped. + Otherwise a caller that carries on is held to what the transaction has left: a write or a charge of its own that crosses a limit again MUST stop the caller's frame in turn. + A transaction therefore never keeps more data size, KV updates or state growth than its limits, and never computes past gas detention's limit but by what [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas) allows. +4. A caller that catches the stop MUST run on as after any failed call, unless the item above stops it as it resumes: a transaction whose frames catch every stop below its own frame MAY succeed, keeping what its frames did and nothing of a frame that was stopped. 5. A stop of the transaction's own frame is the transaction's result. The transaction MUST settle like an EIP-8037 revert: every write and log its frames made MUST be reverted, the value its first frame carried and that frame's write record included; the sender pays the intrinsic gas, the body's history gas, the charges of what it keeps from before the first frame (below), and what ran; the unspent regular gas and the reservoir return to the sender. The transaction is included with a failed receipt, and its usage counts towards the block's counters. + A deposit whose own frame is stopped settles this way too, as a revert: it is not a failed deposit, which only a deposit that fails validation, cannot pay a charge made before its first frame, or whose own frame halts becomes, and which uses its whole gas limit, the reservoir included (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). What was applied before the first frame is not the frames' doing, and a stop of the transaction's own frame MUST NOT revert it, as a revert of the first frame does not: - the sender's nonce and the fees it pays; for a deposit, its mint and the caller account it created, with that account's state gas; -- the EIP-7702 authorizations admitted before the first frame: their authorities' nonce and delegation writes, their state gas, their write records, and the history gas those records cost. +- the EIP-7702 authorizations admitted before the first frame, which are those the list rule of [Resource Limits](#10-resource-limits) let through: their authorities' nonce and delegation writes, their state gas, their write records, and the history gas those records cost. + A list that rule skipped was not admitted, and the stop keeps nothing of it. An Oracle hint a frame admitted is not the frames' state either: it MUST stay counted as data size through any stop, whether its payload reached the oracle service or failed to decode (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). A hint that would itself cross the data-size limit is neither forwarded nor counted. -A limit is enforced before the writes it guards: +A limit is enforced on the writes it guards before anything runs on them: -- A frame whose start would cross a limit MUST be answered with the stop before it is built, so no value moves. - A stopped creation still bumps its creator's nonce, and that write's record lands on the creator, which MUST be held to its limits with it before it runs on and be stopped if it crosses one. +- A frame whose start crosses a limit MUST be stopped before it runs an instruction, and what its start moved MUST be reverted with it: the value, the transfer log, a created account. + A frame answered without running — a call to an account with no code, a precompile, whatever it answered — MUST have its answer replaced by the stop, on the gas its caller forwarded, untouched. + When that answer is a precompile whose price crosses gas detention and whose start's records also cross a data-size, KV or state-growth budget, the records' stop is the result, as [Resource Limits](#10-resource-limits) orders the two. + A stopped creation keeps its creator's nonce bump, and that write's record MUST be counted on the creator when the creation returns: the creator MUST be held to its limits with it before it runs on, and be stopped if it crosses one. - A frame answered without running whose answer is then rewritten to the stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST have what its start moved reverted with it, as a frame that fails has. -- Nothing counted before the first frame — the body, and the records of the EIP-7702 authorities applied — crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +- Nothing counted before the first frame crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + KV updates and state growth can cross before the first frame, on that authorization list, and the list is then skipped (see [Resource Limits](#10-resource-limits)). A real out-of-gas, a precompile given less than its price, and an invalid opcode still halt and consume the frame's gas. @@ -489,11 +888,15 @@ The revert data: | `kind` | Dimension | `limit` | | ------ | ----------------------- | -------------------------------------------------------------------------------------------------- | | 0 | Data size | The limit or frame budget crossed, in bytes | +| 1 | KV updates | The limit or frame budget crossed, as a count of write records | | 2 | Compute (gas detention) | The compute limit of the binding read: the transaction's compute at that read plus the cap, in gas | +| 3 | State growth | The limit or frame budget crossed, as a count of new accounts and new slots | The discriminants are Rex6's, so a decoder of the Rex6 revert data decodes Satin's. -Kinds 1 and 3, Rex6's KV updates and state growth, are not reported: no limit holds either dimension. -Kind 2 names the limit; the compute the transaction is billed can exceed it when frames halt because they cannot pay an opcode's static gas — the first of them taking the compute past the limit, each later one holding it there — by less than that static gas per halting frame, added over those frames (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). +Every limit stop carries `MegaLimitExceeded`, in every dimension, and a refusal the protocol makes that is not a limit stop MUST NOT carry it: a refused volatile read reverts with `VolatileDataAccessDisabled(uint8)` (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)), the system contracts' and a keyless deployment's refusals carry their own errors (see [Native Keyless Deployment](#15-native-keyless-deployment)), a call past the call-depth limit or with a value its caller cannot fund fails with empty return data, and a halt has no return data. +Kind 0, kind 1 and kind 3 name the frame budget when that budget is crossed, including when the transaction limit of the same dimension is crossed too. +They name the transaction limit when the frame budget is not crossed, whether or not a frame budget applies to the operation (see [Resource Limits](#10-resource-limits)). +Kind 2 names the compute limit, which the transaction's compute does not exceed (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). A contract can revert with the same bytes, and so can a caller that re-raises the stop a frame below it returned, so the revert data alone does not identify a stop: the stop of a transaction is the crossing that produced the result of its own frame (see [Developer Impact](#developer-impact)). ### 12. Gas Detention on Withheld Gas @@ -511,11 +914,16 @@ A contract can revert with the same bytes, and so can a caller that re-raises th `BLOBHASH` MUST NOT be volatile: it reads the transaction's own blob hashes. A read MUST be marked where the value is loaded, and only once the opcode completed; a load that fails, and a read whose opcode then fails, mark nothing. `BLOCKHASH` loads the block number before it decides whether its operand is in range, so every `BLOCKHASH` is a read of the block environment, one of the current block, a future block or a block outside the last 256 included, and one in range reads the hash as well. - A `CREATE` or `CREATE2` MUST NOT be marked as a read, even when its creator or its created address is the block beneficiary: the loads it makes of them — the creator's, to check its balance and nonce, and the created address's, to decide the created account's state gas — mark nothing, and a frame then running as the beneficiary marks the beneficiary's account by its own `SELFBALANCE`, `SELFDESTRUCT` and the other reads above (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas) for what those loads do with access off). + A call to the EIP-2935 history contract is a read of the block environment because the contract's `get` path executes `NUMBER` before it loads the slot; the storage the EIP-2935 and EIP-4788 pre-block calls write is state committed before the block's first transaction, and an `SLOAD` of it MUST NOT be a volatile read. + A `CREATE` or `CREATE2` MUST NOT be marked as a read, nor refused in a frame whose access is off (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)), even when its creator or its created address is the block beneficiary: the loads it makes of them — the creator's, to check its balance and nonce, and the created address's, to decide the created account's state gas — are the creation's own checks, which revm's creation opcode makes under EIP-8037, and not volatile reads, as a value call's check of its caller's balance is not one, and as Rex6 neither marked nor refused a creation. + A frame then running as the beneficiary marks the beneficiary's account by its own `SELFBALANCE`, `SELFDESTRUCT` and the other reads above, and with access off is refused them. - **Compute.** - A transaction's compute is its regular ledger — the running frame's regular gas spent, plus every suspended caller's, each less its child's whole gas limit — less the state and history gas that spilled onto regular gas, and less what halting frames burned. - A child's gas limit includes a value call's 2,300 stipend, which its caller did not spend: what the callee spends of it is not compute, and what the callee leaves of it lowers the caller's spent regular gas when it returns. - What a halting frame burns is not compute, with one exception: when an opcode's static gas cannot be paid, what the halting frame had left counts as compute. + A transaction's compute is every regular charge its frames make, whoever funds it: the running frame's regular gas spent, plus every suspended caller's, each less the gas it forwarded its child, less the state and history gas that spilled onto regular gas, and less what halting frames burned. + A value call's 2,300 stipend is not forwarded gas: what the callee runs on it MUST count as compute, as the rest of what it runs does. + The stipend MUST NOT lower compute either: when a value call returns, what the callee left of the stipend comes back to its caller with the rest of the callee's gas, and compute MUST NOT fall with the caller's spent regular gas. + So compute exceeds the transaction's regular ledger by the stipends of its value calls, gas no pool of the transaction paid. + What a halting frame burns — the regular gas it had left when it halted — MUST NOT count as compute, whatever it could not pay: a dynamic charge, an opcode's static gas, a cold access, or state or history gas that spilled past the reservoir. + A precompile that runs out of gas counts nothing of its forward as compute: it burns the forward, a value call's stipend included, as a halting frame burns what it had left, unless it is the crossing (see Precompiles, below), and then the forward returns to its caller. - **The limit.** A read MUST set `limit = compute_at_read + cap`, with `cap` = `BLOCK_ENV_ACCESS_COMPUTE_GAS` = 20,000,000 for the block environment and the beneficiary and `ORACLE_ACCESS_COMPUTE_GAS` = 20,000,000 for the Oracle; the limit only goes down, so the most restrictive read binds. The caps are protocol values fixed per spec with the other limits (see [Resource Limits](#10-resource-limits)). @@ -524,22 +932,22 @@ A contract can revert with the same bytes, and so can a caller that re-raises th Once a limit is set, every frame's regular gas MUST be split into a spendable part, held at what the limit leaves the transaction (`limit − compute`, or zero once the compute is past the limit), and a withheld part, the rest. The split MUST be applied when the read's opcode completes, when a frame starts or resumes, and after an `SSTORE` (whose restore of a slot can refill regular gas). Only a regular charge MUST be limited to the spendable part. - Every other reader of the frame's gas MUST see both parts: `GAS`, the 63/64 forward and the clamp of an explicit call gas, the `SSTORE` minimum-gas check, the checks that decide whether a cold load is attempted, the gas a child returns, and the settlement at the end of the transaction. + Every other reader of the frame's gas MUST see both parts: `GAS`, the 98/100 forward and the clamp of an explicit call gas, the `SSTORE` minimum-gas check, the checks that decide whether a cold load is attempted, the gas a child returns, and the settlement at the end of the transaction. At the settlement the withheld part MUST be unspent gas: it returns to the sender with the rest of the unspent gas, and it is not part of the gas used that caps the EIP-3529 refund at a fifth. + A failed deposit MUST return none of it, as it returns no unspent gas and no reservoir (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). A forward and a spill of state or history gas MUST draw the withheld part first. So a transaction that read volatile data runs exactly as it would without the read until a regular charge needs the withheld part. - **The crossing.** A regular charge that the spendable part cannot pay but the frame's whole regular gas can is the crossing: the charge MUST NOT be made, the frame's gas MUST be put back to what it was before the charge, and the frame MUST be stopped with `MegaLimitExceeded(2, limit)` (see [The Revert-Class Stop](#11-the-revert-class-stop)). What the frame spent before the crossing charge stays spent, and its caller MUST get back everything the frame had, the withheld part included. - The transaction's compute at the crossing is then at most the limit and less than the crossing charge short of it, with one exception. + The transaction's compute at the crossing is then at most the limit and less than the crossing charge short of it. A caller the stop returns into resumes held to what the limit leaves the transaction, which is less than the charge that crossed, so any regular charge of its own past that is a crossing too. - A frame that halts because it cannot pay an opcode's static gas counts what it had left as compute (see Compute, above), and that can take the transaction's compute past the limit without a crossing, by less than the static charge the frame failed to pay: at most 4,999 gas per such frame, `SELFDESTRUCT`'s static gas of 5,000 being the largest. - Its caller then resumes with no spendable gas; a caller whose whole regular gas cannot pay its next opcode's static gas either halts the same way and adds what it had left, so the overshoots accumulate along such a chain of frames, each adding less than its own static charge, with no fixed total. - From then on the spendable part is zero, so the next non-zero regular charge that a frame's whole regular gas can pay MUST be the crossing, and the compute stays past the limit by the overshoots together. - A transaction whose frames make no such charge after the overshoot ends as it would without the read, its compute past the limit. + What a halting frame burns adds nothing to the compute (see Compute, above), while the frame's paid work before the halt still counts, so no halt takes the transaction's compute past the limit: the compute since a read is at most its cap. A regular charge beyond the frame's whole regular gas, and every other out-of-gas, MUST halt as it would without the read. - **Precompiles.** + The call's own regular charges come first, as any opcode's: one that crosses MUST stop the calling frame before the price is consulted (see Order at one site in [Resource Limits](#10-resource-limits)). A call to a precompile forwarded more regular gas than the frame's allowance MUST be decided from the precompile's price before it runs: priced within the allowance, it runs on its whole forward; priced past the allowance but within the forward, it MUST NOT run and is the crossing; priced past its whole forward, it runs on the forward and fails, as without the read. + When the value has already moved, the start's records are held to the data-size, KV and state-growth limits before that crossing is the stop, and the price is kind 2 only when the start kept within them (see [Resource Limits](#10-resource-limits)). Every precompile of the Satin set has a price; an input over a size limit is priced at zero, since it is refused before any gas check. An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. @@ -573,7 +981,6 @@ The reference implementation has no price for one, so it runs such a precompile - A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` on the gas it had after the opcode's static gas: the refused read pays its static gas and nothing else — not a cold access, not a copy's memory, not a call's value transfer. The static gas is the opcode's base cost: 2 for `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE` and `SLOTNUM`; 5 for `SELFBALANCE`; 20 for `BLOCKHASH`; 100 for `BALANCE`, `EXTCODEHASH`, the four call opcodes and an `SLOAD` of the Oracle's storage (whose cold surcharge is not paid); 200 for `EXTCODESIZE` and `EXTCODECOPY`, EIP-8038's base of two warm accesses (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)); and 5,000 for `SELFDESTRUCT`. What the opcode charged after its static gas and before the load — the memory and the copy cost of `EXTCODECOPY`, a call's memory and value-transfer cost — MUST be given back. -- A `CREATE` or `CREATE2` in a frame whose access is off is outside this rule when it loads the block beneficiary's account: the creator's, which it loads first for its balance and nonce, or the created address's, which it loads to decide the created account's state gas once the endowment, nonce and depth checks passed; that load is refused as a load the frame cannot make, and the creating frame MUST halt with an out-of-gas, consuming its gas, instead of reverting with the error. - The error's argument MUST be ABI-encoded as a `uint8`: | `accessType` | Read | @@ -614,10 +1021,10 @@ A node MUST apply [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708): - A deposit's value is logged; its mint is not. - Satin applies the `Transfer` log of EIP-7708 and nothing else of any revision of that EIP: [EIP-8246](https://eips.ethereum.org/EIPS/eip-8246), which EIP-7708 lists among its requirements, MUST NOT be applied, so a balance can still be burned, and a burn MUST NOT log — no `Burn` log is ever emitted, whatever revision of EIP-7708 defines one. Two burns remain, both silent: a `SELFDESTRUCT` to itself of an account created in the same transaction burns the balance at once, and an account destroyed in the transaction is removed at its end with whatever balance it then holds, a value it received after its destruction included (the `CALL` that sent it logged the transfer). -- A transfer log is data size (`TRANSFER_LOG_SIZE` = 160 bytes), counted where the value moves: with the start of the frame that moves it, before any value moves, or with the `SELFDESTRUCT` that moves it. +- A transfer log is data size (`TRANSFER_LOG_SIZE` = 160 bytes), counted where the value moves: with the start of the frame that moves it, held to the limits with the start's records, or with the `SELFDESTRUCT` that moves it. It is not a write record, pays no history gas, and does not draw on a history allowance. - A frame start that the caller's account refuses moves nothing and logs nothing. -- A creation with an endowment onto an occupied address counts its transfer log with its start, as any creation with an endowment does, though the collision then moves nothing and logs nothing: a crossing the count causes stops it first (see [Resource Limits](#10-resource-limits)), and otherwise the count is discarded with the failed creation. +- A creation with an endowment onto an occupied address moves nothing and logs nothing: the collision fails it before the endowment moves, and nothing of the log is counted or held to a limit (see [Resource Limits](#10-resource-limits)). ### 15. Native Keyless Deployment @@ -638,23 +1045,23 @@ The call MUST make these charges and checks, in this order. A rule's refusal reverts the call with the error named: the state and history gas the call was charged are given back, and the regular gas it spent stays spent. An out-of-gas step halts the call, consuming its regular gas. -| Step | Check or charge | Refusal | -| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -| 1 | Charge `KEYLESS_DEPLOY_OVERHEAD_GAS` = 100,000 regular gas | Out-of-gas | -| 2 | The call carries no value | `NoEtherTransfer()`, before the frame is built: no value moves | -| 3 | The arguments and the carried transaction decode: a signed legacy creation, no chain id, no trailing bytes | `MalformedEncoding()`, `NotContractCreation()`, `NotPreEIP155()` | -| 4 | The carried transaction's nonce is 0 | `NonZeroTxNonce(uint64)` | -| 5 | The initcode is within `MAX_INITCODE_SIZE` | `InitCodeTooLarge(uint64,uint64)` | -| 6 | `gasLimitOverride` covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | -| 7 | The signer can be recovered, from a signature with a low or a high `s` value: EIP-2's bound on `s` does not apply | `InvalidSignature()` | -| 8 | The signer's nonce is at most 1 | `SignerNonceTooHigh(uint64)` | -| 9 | Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation | `SignerHasCode()` | -| 10 | If the signer's account is empty (EIP-161), charge its new-account state gas (`183,600 × m`) | Out-of-gas | -| 11 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | -| 12 | The deploy address `keccak256(rlp([signer, 0]))[12:]` holds no code | `ContractAlreadyExists()` | -| 13 | The signer's balance covers the carried value | `InsufficientBalance()` | -| 14 | Charge what a `CREATE` charges its frame: 12,000 plus EIP-3860's initcode cost, the created account's state gas if the deploy address is empty, and the history gas of the created account's record and, unless the signer is the transaction's sender, the signer's nonce record | Out-of-gas | -| 15 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| Step | Check or charge | Refusal | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 1 | Charge `KEYLESS_DEPLOY_OVERHEAD_GAS` = 100,000 regular gas | Out-of-gas | +| 2 | The call carries no value | `NoEtherTransfer()`, before the frame is built: no value moves | +| 3 | The arguments and the carried transaction decode: a signed legacy creation, no chain id, no trailing bytes | `MalformedEncoding()`, `NotContractCreation()`, `NotPreEIP155()` | +| 4 | The carried transaction's nonce is 0 | `NonZeroTxNonce(uint64)` | +| 5 | The initcode is within `MAX_INITCODE_SIZE` | `InitCodeTooLarge(uint64,uint64)` | +| 6 | `gasLimitOverride` covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| 7 | The signer can be recovered, from a signature with a low or a high `s` value: EIP-2's bound on `s` does not apply | `InvalidSignature()` | +| 8 | The signer's nonce is at most 1 | `SignerNonceTooHigh(uint64)` | +| 9 | Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation | `SignerHasCode()` | +| 10 | If the signer's account is empty (EIP-161), charge its new-account state gas (`183,600 × m`) | Out-of-gas | +| 11 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| 12 | The deploy address `keccak256(rlp([signer, 0]))[12:]` holds no code | `ContractAlreadyExists()` | +| 13 | The signer's balance covers the carried value | `InsufficientBalance()` | +| 14 | Charge what a `CREATE` charges its frame: 12,000 plus EIP-3860's initcode cost, the created account's state gas if the deploy address is empty, and the history gas of the created account's record, unless the transaction changed the deploy address already, and, unless it changed the signer's account already — the transaction's sender among them — the signer's nonce record | Out-of-gas | +| 15 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | - Steps 1 to 13 keep Rex6's order, so a call several rules refuse reports the Rex6 error. - The read of the signer's account that steps 8 to 10 and 13 check, and the deploy-address read of step 12, MUST load the account into the transaction's state as an account access loads it, warm, the deploy address without its code. @@ -668,22 +1075,33 @@ An out-of-gas step halts the call, consuming its regular gas. An initcode that branches on any of them can be made to return empty code, and the deployment then answers `EmptyCodeDeployed`, but it occupies nothing: the same signed bytes can be submitted again. - A signer that is the block beneficiary MUST be detained as a read of the beneficiary's account, made when the signer's account is read, once step 7 recovered it and before step 8's check: the read's compute is the call's 100,000 of step 1, so the limit is 100,000 plus the cap, unless an earlier read set a lower limit. - The creation MUST then start as a creation by the signer at the deploy address, one level below the call, forwarding `min(gasLimitOverride, remaining gas)`; the forward draws the call's withheld gas first (see [Gas Detention](#12-gas-detention-on-withheld-gas)). + That forward is regular gas, and the 98/100 cap does not apply to it, as Rex6's sandbox envelope was that minimum and the call charges nothing after the creation returns. + The creation MUST receive the reservoir share of [Gas Forwarding](#9-gas-forwarding) from the reservoir the call has left after step 14, and the call keeps the rest. + In data size, KV updates and state growth the creation MUST receive the child share of what the call has left. + The signer's nonce record, and the signer's state growth when the bump creates the signer, MUST be counted on the call at its settlement, once the creation returned. From there it is an ordinary creation frame: priced, limited, detained and logged as one. `ORIGIN` and `GASPRICE` in the initcode are the transaction's own. - **The signer's nonce.** The creation bumps the signer's nonce as any creation bumps its creator's. A deployment from nonce 0 MUST keep the bump. From nonce 1, when the creation's bump is the last nonce change the deployment made, the node MUST take the bump back, whether the deployment succeeded or failed. - The bump's write record and that record's history gas go back with it, unless the creation returned without a revert or a halt — a constructor that destroyed its own account included, and a creation refused its empty deposit not — and moved value out of the signer, whose account then keeps a write of its own. + The signer's write record MUST be counted after that: when the nonce set back leaves the signer's account as the transaction loaded it, no record stands, and the history gas charged for it MUST be given back; a signer's account another write changed — the value a creation that returned without a revert or a halt moved out of it, or into it — keeps its record (see [Resource Limits](#10-resource-limits)). A signer whose own code spent a nonce during the creation that survives it keeps every bump. - **The answer.** The call MUST succeed with `(gasUsed, deployedAddress, errorData)`: the deploy address and empty `errorData` when the deploy address holds code afterwards; otherwise the zero address and `ExecutionReverted(uint64 gasUsed, bytes output)`, `ExecutionHalted(uint64 gasUsed)` or `EmptyCodeDeployed(uint64 gasUsed)` — the last for a creation that returned empty code for the deploy address, which is refused and reverts, and also for a constructor that destroyed its own account. - `gasUsed` MUST be what the creation spent from both pools, with no intrinsic gas and before the EIP-3529 refund: the regular gas it spent and the state and history gas it kept, net of every give-back within the creation — a slot written back to its original value, a record taken back, the upfront state gas of a frame it started that failed; the call's own charges of steps 1 and 14 are not in it, and a give-back is not a refund. + `gasUsed` MUST be what the creation spent from both pools, with no intrinsic gas and before the EIP-3529 refund: the regular gas it spent and the state and history gas it kept, net of every give-back within the creation — a slot written back to its original value, a record taken back, the upfront state gas of a frame it started that failed, and the state gas and the history gas a same-transaction destruction gives back, the deployed code's history gas included; the call's own charges of steps 1 and 14 are not in it, and a give-back is not an EIP-3529 refund. It is never less than the regular gas the creation spent. - **Limits.** - A limit the creation crosses — its frame budget, the transaction's data-size limit or gas detention's compute limit, at its start or in its initcode — stops the creation, and the call answers `ExecutionReverted` with the stop's revert data, keeping what the creation's start wrote. - A limit the call's own charges cross — gas detention's compute limit — stops the call: it reverts with the stop, and the deployment, the signer's nonce included, is taken back. - When the signer's nonce record, which survives a failed creation, takes the call over a limit — its own frame budget or the transaction's data-size limit — the call reverts with that stop and the deployment, the nonce included, is taken back; since the call is the transaction's own frame, the stop reported for the transaction is that one. + A limit the creation crosses stops the creation, and the call answers `ExecutionReverted` with the stop's revert data. + The creation keeps only the creator-side effects an ordinary failed creation keeps, under the nonce rule above. + The deploy address's account, the endowment, the transfer log and the deploy address's write record are taken back. + The signer's nonce bump stands when a deployment from nonce 0 fails, and from nonce 1 it is taken back when it is the last nonce change the deployment made. + That limit may be the creation's frame budget in data size, KV updates or state growth, the transaction's limit in one of those dimensions, or gas detention's compute limit, at the creation's start or in its initcode. + A limit the call's own charges cross stops the call: it reverts with the stop, and the deployment, the signer's nonce included, is taken back. + Those charges can cross gas detention's compute limit. + The signer's nonce record, counted on the call at its settlement, can cross the call's frame budget, in data size, in KV updates, and in state growth when the bump creates the signer, and the transaction's data-size limit once Oracle hints the creation sent used what the transaction had left. + When that record, which survives a failed creation, takes the call over either, the call MUST revert with that stop, and the deployment, the nonce included, is taken back. + The call is the transaction's own frame, so the stop reported for the transaction is that one. - The contract's interface no longer declares the four errors only Rex6 and earlier produced: `ParentBudgetExceeded(uint8,uint64,uint64)`, `InvalidTransaction()`, `InsufficientComputeGas(uint64,uint64)` and `InternalError()`. A node MUST NOT produce them: a failed database read or SALT lookup gives the transaction no outcome, as [Transaction and Block Refusals](#21-transaction-and-block-refusals) says. `AddressMismatch()` and `NoContractCreated()` remain as answers to a creation reported at another address or at none, which no deployment reaches. @@ -763,8 +1181,10 @@ An out-of-gas step halts the call, consuming its regular gas. `GAS` inside a system call reads at most 30,000,000. A transaction is not a system call: every transaction's gas is split by the execution cap, a Mega System Transaction's included. - **The pre-block budget.** - Each pre-block call MUST run from `0xfffffffffffffffffffffffffffffffffffffffe` on `max(block_gas_limit, 30,000,000)`; what the budget adds above 30,000,000 is reservoir. - In a block whose gas limit is at most 30,000,000 the call MUST have no reservoir, and its state gas MUST spill onto its regular gas (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + Each pre-block call MUST run from `0xfffffffffffffffffffffffffffffffffffffffe` on `PRE_BLOCK_CALL_GAS_LIMIT` = 31,566,720 gas, whatever the block's gas limit: 30,000,000 of regular gas, and a reservoir of 1,566,720, the state gas of sixteen fresh storage slots at the minimum bucket. + State gas the reservoir cannot pay spills onto the regular gas (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + On MegaETH's chains, whose EIP-2935 and EIP-4788 addresses hold those EIPs' own code, a pre-block call writes at most six fresh slots — an `applyPendingChanges()` that applies both roles — so at Satin's state-gas price the reservoir pays all of it; other code at those addresses runs on the same budget, and what its state gas the reservoir cannot pay spills. + The block's gas limit, which a pre-block call does not draw on, does not set the budget; on MegaETH's chains neither EIP-2935's nor EIP-4788's code nor `applyPendingChanges()` reads `GAS`, so how much of the budget is reservoir changes no call's result. - **The pre-block sequence.** Before its transactions, a block MUST, in order: 1. make the EIP-2935 call; @@ -806,7 +1226,7 @@ A system-originated transaction and every system call: - MUST be priced at `m = 1` and MUST NOT read a bucket capacity; - MUST pay no history gas, the body and deposited code included; -- MUST NOT be stopped by any per-transaction limit or frame budget; +- MUST NOT be stopped by any per-transaction limit or frame budget, data size, KV updates and state growth included; - MUST NOT be detained; - still have their usage counted. @@ -823,30 +1243,48 @@ A deposit pays no history gas either (see [History Gas](#7-history-gas)), but a #### New behavior -A block MUST count, per transaction, its regular (as `max(regular, floor)`), state and history gas, its history bytes, its data size and its write records. -One of those counts is limited: +A block MUST count, per transaction, its regular (as `max(regular, floor)`), state and history gas, its history bytes, its data size, its KV updates and its state growth. +Three of those counts are limited. +The transaction that reaches a limit MUST be included, and a later ordinary transaction MUST be skipped before it runs. + +| Block limit | Counted | Checked | Limit | +| ------------ | ------------------------------------------ | -------------------------------- | ---------------------------------- | +| Data size | Data-size bytes per transaction | Before the next transaction runs | `BLOCK_DATA_LIMIT` = 13,107,200 | +| KV updates | Write records per transaction | Before the next transaction runs | `BLOCK_KV_UPDATE_LIMIT` = 500,000 | +| State growth | New accounts and new slots per transaction | Before the next transaction runs | `BLOCK_STATE_GROWTH_LIMIT` = 1,000 | -| Block limit | Counted | Checked | Limit | -| ----------- | ------------------------------- | -------------------------------- | ---------------- | -| Data size | Data-size bytes per transaction | Before the next transaction runs | 13,107,200 bytes | +Reaching a limit means the block's counter is at or above it. +The transaction that moves a counter from below the limit to the limit, or past it, is the one included. +When more than one of these limits is already reached, a node MAY report the skip in the order data size, then KV updates, then state growth, which is the order Rex6 checks. +A skip leaves no field in the block. +Two nodes need not name the same dimension. +The transaction is skipped in any case. -- It is a packing budget: the transaction that reaches the limit MUST be included, and later transactions MUST be skipped. - A builder that executes several candidates before it commits one MUST hold each to the block's counters again when it commits it, together with the block gas limit and the data-availability footprint; a validator commits every transaction before it executes the next, so for it the second check finds what the first found. +- A builder that executes several candidates before it commits one MUST hold each to the block's counters again when it commits it, together with the block gas limit and the data-availability footprint; a validator commits every transaction before it executes the next, so for it the second check finds what the first found. Such a builder MUST NOT commit a candidate whose sender's nonce or balance — the system address's, for a Mega System Transaction — another commit moved since the candidate executed: committing it would write the sender's account over what that commit did. Any other state a candidate read and a commit since changed is the builder's to account for, by executing the candidate again; a candidate that read the Oracle executed before a Mega System Transaction that writes it, committed after that transaction, commits the value it read. -- A deposit — a transaction whose envelope is a deposit — MUST NOT be refused by it, and MUST count towards it. - A Mega System Transaction MUST NOT be refused by it either, nor by a building policy, and MUST count towards it, so the oracle update the sequencer must be able to include is never skipped for a budget the block's other transactions used up. +- A deposit, a transaction whose envelope is a deposit, MUST NOT be refused by any of the three, and MUST count towards each. + A Mega System Transaction MUST NOT be refused by any of the three either, nor by a building policy, and MUST count towards each, so the oracle update the sequencer must be able to include is never skipped for a budget the block's other transactions used up. + The exemption covers KV and state growth for the same reason it covers data size: a deposit is derived from L1 and must be included, and a Mega System Transaction is the sequencer's own update. + Refusing either for KV or state growth alone would make the same transaction valid on the data-size budget and skippable on another block limit. + Rex6 skipped every later candidate, deposits included, once any of these counters was at or above its limit. + Satin does not. The block decides that before the transaction runs, from its envelope and the live system address (see [The Live System Address](#17-the-live-system-address)): a legacy transaction of the system shape sent from that address. A transaction from that address of another shape is no Mega System Transaction here; the block treats it as any other transaction, and it is invalid as [The Live System Address](#17-the-live-system-address) states. - A Mega System Transaction is still held to the block gas limit, and, its envelope being legacy, to the block's data-availability footprint, which it counts towards with its data-availability size; the exemption is from the data-size budget and from building policy alone. -- Execution, state and history gas have no block limit beyond the block gas limit; state gas prices the state a block adds, so the block gas limit bounds it. - The block's history bytes and write records are reported, not limited. + A Mega System Transaction is still held to the block gas limit, and, its envelope being legacy, to the block's data-availability footprint, which it counts towards with its data-availability size. + The exemption is from the three packing budgets and from building policy. +- Execution gas, state gas and history gas have no block limit beyond the block gas limit. + State gas prices the state a block adds, and `BLOCK_STATE_GROWTH_LIMIT` counts it. + The block gas limit does not stand in for that count: at `m = 1`, 1,000 fresh slots cost 97,920,000 state gas, and a block gas limit above that does not stop the 1,001st. + History bytes are reported and are not limited. + KV updates are the write-record count, and `BLOCK_KV_UPDATE_LIMIT` limits them. - The block gas limit is unchanged: a transaction's declared gas limit MUST fit in what the block has left. -- The limit is a protocol value fixed per spec with the per-transaction limits (see [Resource Limits](#10-resource-limits)), the same on every chain; no chain configuration carries it. - A node validating a block MUST hold it to that value, as the rules above state them, and to no other value. -- A block builder MAY pack tighter, as building policy: it MAY refuse a transaction for its declared gas limit, its encoded size or its data-availability size, hold the block to an encoded-size or data-availability budget, and hold the data-size limit below the protocol's value, never above it. +- The three packing budgets are protocol values fixed per spec with the per-transaction limits (see [Resource Limits](#10-resource-limits)), the same on every chain; no chain configuration carries them. + A node validating a block MUST hold the block to those values, as the rules above state them, and to no other value. +- A block builder MAY pack tighter, as building policy: it MAY refuse a transaction for its declared gas limit, its encoded size or its data-availability size, hold the block to an encoded-size or data-availability budget, and hold any of the three packing budgets below the protocol's value, never above it. + A builder MAY still pack fewer transactions than the protocol budgets allow, by not selecting them. A building policy MUST NOT refuse a deposit, which the block derived from L1 must include: none of those per-transaction limits and budgets applies to one. - It MUST NOT refuse a Mega System Transaction either: none of them applies to one, and the policy's cap on the data-size budget does not. + It MUST NOT refuse a Mega System Transaction either: none of them applies to one, and a policy's cap on a packing budget does not. A deposit counts towards the block's encoded size and not towards its data-availability size; a Mega System Transaction counts towards both; the block gas limit holds either as it holds every transaction. A node validating a block MUST NOT apply a building policy, and a policy never changes what a packed block computes: it only decides which transactions the builder packs. - Satin sets no limit on a transaction's or a block's encoded size; a block-size rule of the base layer, where a chain adopts one, is the node's to apply and is not one of these limits. @@ -874,18 +1312,19 @@ A transaction MUST be rejected before inclusion when: A deposit MUST NOT be rejected for failing a validation check: a deposit that fails any of these checks MUST be included as a failed deposit instead, which bumps its sender's nonce, credits its mint, uses its whole gas limit and applies nothing else. A read the node fails to make is not a validation check, for a deposit as for any transaction (below). A Mega System Transaction is a legacy transaction until it passes its own chain-id, nonce and EIP-3607 checks, so failing one of those is a rejection; once it passes them it runs as a deposit, and a check it fails after that includes it as a failed deposit. -A failed deposit — one that fails a check, or whose execution halts — reports its whole gas limit as regular gas, and no state gas and no history gas on any ledger, the transaction's or the block's: the caller account it creates for a sender that did not exist carries no state gas, unlike the one a deposit that runs to a success or a revert creates (see [The Revert-Class Stop](#11-the-revert-class-stop)). +A failed deposit, one that fails a check, or whose execution halts, reports its whole gas limit as regular gas, and no state gas and no history gas on any ledger, the transaction's or the block's: the caller account it creates for a sender that did not exist carries no state gas, unlike the one a deposit that runs to a success or a revert creates (see [The Revert-Class Stop](#11-the-revert-class-stop)). +That created account still counts as one of state growth, on the transaction's reported usage and on the block counter (see [Resource Limits](#10-resource-limits)). A transaction MUST be skipped for the current block, and MAY be included in a later one, when: - its declared gas limit does not fit in the block's remaining gas; - its data-availability footprint does not fit in what the block's gas limit has left for footprints; -- it is neither a deposit nor a Mega System Transaction and the block has reached its data-size limit; +- it is neither a deposit nor a Mega System Transaction and the block has reached its data-size limit, its KV-update limit, or its state-growth limit (see [Block Limits](#20-block-limits)); - it is not a deposit and the block activates Satin or an Optimism fork at or after Jovian in the Optimism fork order, as the chain configuration schedules it (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)). A block that contains a transaction it should have skipped is invalid. -A block builder MAY also skip a transaction other than a deposit or a Mega System Transaction under its own building policy (see [Block Limits](#20-block-limits)): a per-transaction declared-gas, encoded-size or data-availability limit, a block encoded-size or data-availability budget, or the block's data-size limit held below the protocol's value. +A block builder MAY also skip a transaction other than a deposit or a Mega System Transaction under its own building policy (see [Block Limits](#20-block-limits)): a per-transaction declared-gas, encoded-size or data-availability limit, a block encoded-size or data-availability budget, or any of the three packing budgets held below the protocol's value. A transaction over a builder's per-transaction limit never fits that builder's blocks, and the builder MAY drop it. A block is not invalid for a transaction a building policy would have skipped. @@ -923,14 +1362,14 @@ The witness is defined by what the block's execution returns and exports, and a A transaction loads every account and slot its execution reads from the state: in its validation (the registry's account and system-address slot every transaction reads included), in its fee settlement, and in any of its frames, a frame that reverted or halted included, and a frame of a deposit that failed. A failed frame's writes are taken back, not its reads; a failed deposit takes back everything but its sender's nonce bump and mint, not its reads; and a validator re-executing the transaction makes the same reads in the same frames. The one exception is the L1 block info the transaction is priced against, which the pre-block phase loads for the whole block (see the L1 block info, below). - A read that gas or a limit skipped loads nothing (see the reads a validator makes again, below). + A read that gas or a limit skipped loads nothing (see the reads a validator makes again, below), except an authority account the authorization preflight consulted: that account is loaded whether or not the list is applied (see [Resource Limits](#10-resource-limits)). Execution reports what it loaded in the states the block commits: a pre-block step in the state it commits on its own, and a transaction in its returned state, which the block commits and which names every account and slot the transaction loaded, whether it wrote it or not, whether the frame that loaded it succeeded or not, and, for a deposit, whether the deposit failed or not. The set is a function of those states and the exports alone, not of how the node caches state: a node that serves a block's execution from a state cache another block filled builds the same witness, because the states name what was loaded whether or not a database was asked for it. A state names the keys; the values are the chain's. A slot of an account the chain does not hold before the block is not recorded: such an account has no storage, and a validator MUST answer every slot of it with zero without looking it up. The code in particular is not the code a returned state carries: a transaction that replaces an account's code — an EIP-7702 authority delegated anew — is admitted against the code the chain held, and its returned state carries the code it wrote. - **What the block reads, and where it lands.** - A transaction's loads are in its returned state: its sender, its recipient or created address, every account and every slot any of its frames loads, the fee recipients, the registry's account and system-address slot every transaction reads, and a keyless deployment's signer and deploy address; the state names an account whether or not the load brought its code. + A transaction's loads are in its returned state: its sender, its recipient or created address, every account and every slot any of its frames loads, the fee recipients, the registry's account and system-address slot every transaction reads, every authority account the authorization preflight consulted, and a keyless deployment's signer and deploy address; the state names an account whether or not the load brought its code. The pre-block phase's reads land in the states it commits, one per step, in order: the two EIP calls' states, in Satin's activation block each predeploy's read-only entry, the registry's pending slots the due-change decision read, the `applyPendingChanges()` call's state, and last the L1 block info. Each state is committed whole, read-only entries included, and a node MUST collect the states as they are committed: what a commit keeps of a state is only what it changed, which holds none of the read-only entries. `BLOCKHASH` reads the chain's history outside the journal and its reads are exported; a SALT bucket's capacity and the oracle service's answer are read outside the database and are exported or recorded. @@ -972,7 +1411,8 @@ The witness is defined by what the block's execution returns and exports, and a A validator without a service that finds another value in the slot computes another block; a transaction that wrote the value but was dropped by the builder wrote nothing the chain holds. Hints reach the service alone: they are not in the witness, and change nothing a validator computes except through the answers the service then gives, which the records carry. - **The check.** - A block replayed on exactly its witness MUST produce the same receipts, state changes, gas ledgers, logs, block counters and exports as the block's execution, and MUST read nothing the witness does not hold. + A block replayed on exactly its witness MUST produce the same receipts, state changes, gas ledgers, logs and block counters as the block's execution, and MUST read nothing the witness does not hold. + Its exports MUST be a subset of the building node's and MAY be a proper one: the building node's also hold the buckets and block hashes that candidates it executed and dropped asked for, which the replay, running the included transactions alone, never asks for. ## Developer Impact @@ -985,7 +1425,17 @@ A contract that checks `gasleft()` against a large constant sees at most the reg A frame stopped by a resource limit or by gas detention now reverts rather than halting the transaction, with `MegaLimitExceeded(kind, limit)` as its output: its caller sees a failed call whose return data is the stop, and can catch it and carry on within what the limits leave. A transaction whose own frame is stopped reverts with the stop, and its sender pays only for what ran. -No KV-update or state-growth limit stops a transaction, so kinds 1 and 3 are never reported. +A KV crossing reverts with kind 1 and a state-growth crossing with kind 3. +`limit` is the count. +At the protocol caps the data-size cap is tighter than the KV cap, because each record weighs 40 bytes and 500,000 records weigh more than 13,107,200 bytes. +Under the execution cap a transaction cannot pay the regular gas of enough writes to reach either number, and the KV check is still made. +The state-growth limit is reachable at the minimum bucket: 1,000 fresh slots cost 97,920,000 state gas. +Destroying a contract created in the same transaction refills, at the price charged, the state gas of each part that was absent at the transaction's start: the account leaf, the deposited code and each new slot. +State growth falls for that leaf and for those slots. +The write records of those parts are taken back, and so are the deposited code's data size and history gas. +A part that existed at the start, such as the leaf of an address funded before the transaction, is an ordinary deletion: no refill, no fall, and its write record stands. +A destruction that moves no balance creates no beneficiary. +EIP-8037 leaves that state gas charged, and Rex6 refunded none of the storage gas and took none of those records back. A transaction that reads volatile data is still held to its compute at the read plus the cap (20,000,000), but until a regular charge needs gas past that limit, `GAS`, call forwarding and state or history charges see its whole gas, and the stop is a revert of the frame that makes that charge. `VolatileDataAccessDisabled` can carry the value 12 (`SLOTNUM`), which a Solidity handler must decode as a `uint8`. @@ -1019,7 +1469,7 @@ A node, a stateless validator and a replay tool must agree on everything below, The reference implementation reports the body-size refusal (`TX_BODY_OVER_DATA_SIZE_LIMIT`) and the system-shape refusal as invalid-transaction errors with fixed messages, which a pool maps to its own error. The rest of the stateless validation is the base layer's. Whether a recipient, a created account or an authority is new is the state's to say: EIP-2780 charges it when the transaction runs, and a gas limit that cannot pay it runs out of gas rather than being refused. - The history of the write records a transaction's start makes is charged when it runs too: one record for the recipient of its value (none for value sent to the sender itself or to an authority it applied) or the account it creates, and one for each authority that applies other than the sender. + The history of the write records a transaction's start makes is charged when it runs too: one record for the recipient of its value (none for a recipient the transaction has changed already: the sender itself, or an authority it applied) or the account it creates, and one for each authority that applies other than the sender. So the least gas limit validation admits is not what a transaction needs: at that gas limit a transfer of value to another account runs out of gas on its recipient's record, and one to a new account needs that account's state gas as well. A deposit and a Mega System Transaction pay no history gas; a pool that recognizes the latter, and refuses a transaction from the live system address without the system shape, needs the live system address from the state. That address changes only in a block's pre-block step and then holds for the whole block, so a pool reads it again for every block, from the state after that block's pre-block changes. @@ -1039,6 +1489,10 @@ A node, a stateless validator and a replay tool must agree on everything below, A node builds a block's witness from the states the block commits, in order: each pre-block step's state, committed on its own, read-only entries included, then each included transaction's returned state (see [The Stateless Witness](#22-the-stateless-witness)). The reference implementation commits them through the database's commit, so a hook on that commit — revm's `State::set_state_hook` — receives each state whole; the block's transitions and bundle keep only what a state changed, and a witness taken from them misses the activation block's predeploys, the registry's pending slots and the L1 block info. Block execution hands the pre-block states to nothing else. +- **An account the state does not hold.** + The destruction table gives an account's leaf back only when no account stood at the address at the transaction's start (see [The destruction table](#the-destruction-table)), and the node's state says which. + An address the state holds no account for must be answered as no account — `None` from revm's `Database::basic` in the reference implementation — never as an empty account, which is a leaf the state holds. + A state that answers an empty account for an address it does not hold gives that leaf back to no destruction, and executes a different chain. - **The predeploys.** Satin runs on a chain that ran the legacy forks: Rex5 deployed the SequencerRegistry and upgraded the Oracle to 2.0.0, and Rex6 upgraded the SequencerRegistry to 2.0.0, so the chain holds the six system contracts at the versions Satin runs, and OP's genesis tooling gave it the EIP-7997 factory. Satin's activation block checks that they are there and is invalid otherwise (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); it deploys, upgrades and seeds nothing, so a chain must have run a Rex6 block before `satinTime`. @@ -1047,11 +1501,13 @@ A node, a stateless validator and a replay tool must agree on everything below, A builder that executes a transaction and commits it after other commits MUST commit through the checked commit (`commit_transaction_outcome`), which refuses an outcome whose sender's nonce or balance another commit moved (see [Block Limits](#20-block-limits)). The refusal is an internal error of the node (`MegaBlockExecutionError::StaleOutcome`), not a verdict on the block or the transaction: the builder executes the transaction again. - **Packing a Mega System Transaction.** - A block's data-size budget and a builder's policy never refuse one (see [Block Limits](#20-block-limits)), so a builder has no reason to skip it for either and requeue the transaction that triggered it; the block gas limit and the data-availability footprint still hold it, and a builder keeps room for both. + A block's data-size, KV and state-growth budgets, and a builder's policy, never refuse one (see [Block Limits](#20-block-limits)), so a builder has no reason to skip it for any of them and requeue the transaction that triggered it; the block gas limit and the data-availability footprint still hold it, and a builder keeps room for both. The execution result tells a node which transactions the block treated so: `MegaBlockTxResult::is_system_transaction`, beside `is_deposit`, which stays the envelope's. - **Reporting a limit stop.** A stop is a revert whose output is `MegaLimitExceeded(kind, limit)`, and a contract can revert with the same bytes, as can a caller that re-raises the stop a frame below it returned. - Execution reports the crossing that produced the result of the transaction's own frame — the transaction's data-size limit, gas detention's compute limit, or that frame's own data-size budget — and none when that result is not the stop's revert; a node must read that report, and must not infer a stop from the output alone. + Execution reports the crossing that produced the result of the transaction's own frame: the transaction's data-size, KV or state-growth limit, gas detention's compute limit, or that frame's own budget in data size, KV or state growth. + It reports none when that result is not the stop's revert. + A node must read that report, and must not infer a stop from the output alone. A stop a caller caught produced no result of the transaction's own frame: the transaction reports none, and it can succeed, so a node maps an RPC error or a builder's handling of a stopped transaction from that report alone (`LimitStop::from_result`, or `MegaTransactionOutcome::limit_stop`), never from the output bytes. - **The chain configuration.** A genesis file's `config` object carries Satin as one key beside the other forks'. @@ -1064,8 +1520,9 @@ A node, a stateless validator and a replay tool must agree on everything below, No key names a limit: the limits are the spec's (see [Resource Limits](#10-resource-limits)). No key names the `SequencerRegistry`'s roles either: the registry is the one the legacy forks left (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). A key that starts with `satin`, in any ASCII letter case, and is not `satinTime` exactly is refused, so a file written against an earlier version of the format, which named the registry's roles (`satinInitialSystemAddress`, `satinInitialSequencer`, `satinInitialAdmin`, `satinMinRotationDelay`), `satinInitialFromBlock` or the limits, does not load, whether or not it carries `satinTime`. - A key given twice is refused only where the reader still sees both copies, as a parser handed the object's text does; a reader that first parses the file into a JSON value, as the reference CLI and a node do, sees only the last copy and reads it. + A key given twice is read as its last copy by every reader, whether it is handed the object's text or first parses the file into a JSON value, as the reference CLI and a node do, which keeps the last copy alone. `satinTime` is a JSON number up to 2^64 − 1. + It may also be given as the object `{"$serde_json::private::Number": ""}`, read as the number its decimal digits write, with the same range: that is the form `serde_json` hands a number over in when its `arbitrary_precision` feature is on, and a reader cannot tell it from the same object written in the file. The key format is provisional until a network publishes a genesis file carrying it. The Satin key does not time the forks Satin runs on: Optimism Karst and the Ethereum forks it includes, Osaka among them, are timed by the configuration's own keys for them, and a node must check their timing against `satinTime` both ways when it loads the configuration. @@ -1077,12 +1534,14 @@ A node, a stateless validator and a replay tool must agree on everything below, ## Safety and Compatibility Satin changes nothing about blocks under earlier specs: a node replaying history resolves each block's spec from its timestamp and applies that spec's rules. -Satin is a restatement rather than a delta, so a Rex6 rule this page does not carry over — the compute-gas limit, the storage-gas formulas, the sandbox, the 98/100 forwarding, the cold first touch of preload-warm addresses — does not apply to Satin blocks. +Satin is a restatement rather than a delta, so a Rex6 rule this page does not carry over (the compute-gas limit, the storage-gas formulas, the sandbox, the cold first touch of preload-warm addresses) does not apply to Satin blocks. The six system contracts keep their Rex6 bytecode and ABI, but for the four errors `IKeylessDeploy` no longer declares; Satin deploys and upgrades none of them, and its activation block refuses a chain that does not hold them, and the EIP-7997 factory, at the versions Rex6 left. A transaction from the live system address without the system shape is refused, as in Rex6, now as an invalid transaction: a deposit from the system address, which Rex6 refused with an error that left its block unexecutable, is a failed deposit, so the engine no longer depends on the L1 portal refusing deposits from each system address a rotation installs. -The per-transaction and block limits and the detention caps are protocol values fixed by the spec, not chain configuration, so every node executing any chain holds its Satin blocks to the same ones: the data-size limits at 13,107,200 bytes and the detention caps at 20,000,000 each. +The per-transaction and block limits and the detention caps are protocol values fixed by the spec, not chain configuration, so every node executing any chain holds its Satin blocks to the same ones: data size at 13,107,200 bytes, KV updates at 500,000, state growth at 1,000, and the detention caps at 20,000,000 each. +The KV check is enforced even where the data-size cap binds first. +Dropping it because 40 bytes times 500,000 exceeds 13,107,200 would retire the cap the moment the byte weight or the data-size cap changed. No chain can set a limit that stops the block's L1 attributes deposit, whose data size is its body, its calldata and a write record for each slot of the L1 block contract it changes: 526 bytes on recorded mainnet blocks within one L1 origin. The per-transaction gas-limit, encoded-size and data-availability limits are a block builder's policy, not the chain's: a node validating a block does not apply them. @@ -1090,7 +1549,9 @@ Satin is unstable and not scheduled on any network: its prices, limits and rules ## References -- [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) — state gas and the reservoir. +- [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) — state gas and the reservoir. + Satin adopts the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef), drawing only the reservoir the child returns, and does not adopt the transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950). + The creation-collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) and the first-frame authority outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) are this page's own rules, stated in [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model). - [EIP-2780](https://eips.ethereum.org/EIPS/eip-2780) — the decomposed intrinsic cost. - [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038) — the state-access prices. - [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) — transfer logs.