From 617d0caa4c4f8d93eaca5186ec11e67fc8f2cfb5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:29:10 +0800 Subject: [PATCH 001/190] feat(evm): SLOTNUM pushes zero whatever slot number the block carries --- crates/mega-evm/src/evm/host.rs | 8 ++++---- crates/mega-evm/tests/satin/detention.rs | 6 ++++-- crates/mega-evm/tests/satin/schedule.rs | 9 ++++----- docs/spec/upgrades/satin.md | 8 ++++---- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index b0e8ce209..dc51ad4fa 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -198,10 +198,10 @@ impl revm::context_interface::Host #[inline] fn slot_num(&self) -> U256 { - if !self.read_block_env(VolatileDataAccess::SLOT_NUM) { - return Default::default(); - } - self.inner.slot_num() + // The read is volatile (marked, refusable) but its value is the engine's own: zero, + // whatever slot number the block environment carries. + self.read_block_env(VolatileDataAccess::SLOT_NUM); + U256::ZERO } /// Loads the slot; a slot of the Oracle's storage is read through the oracle environment diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 7cafb61d9..4295f48fc 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -837,7 +837,8 @@ fn test_the_history_contract_reads_the_block_number_and_the_beacon_roots_contrac } /// 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. +/// loaded, whether or not the read caps anything. `SLOTNUM` is the exception: it is marked like the +/// others but pushes zero, whatever slot number the block carries. #[test] fn test_a_read_answers_with_the_blocks_field() { let reads = [ @@ -848,7 +849,8 @@ fn test_a_read_answers_with_the_blocks_field() { (GASLIMIT, U256::from(10_000_000_000_u64)), (BASEFEE, U256::from(1)), (BLOBBASEFEE, U256::from(3)), - (SLOTNUM, U256::from(9)), + // The block carries a slot number of 9; the engine pushes zero whatever it is. + (SLOTNUM, U256::ZERO), ]; let mut code = BytecodeBuilder::default(); for (slot, (opcode, _)) in reads.iter().enumerate() { diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 4f1bf0d6f..22ebeb063 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -246,10 +246,10 @@ fn test_clz_runs_on_the_base_spec() { assert!(result.is_success(), "{result:?}"); } -/// `SLOTNUM` pushes the block's slot number, `BlockEnv::slot_num`, which the node supplies, and -/// zero for a block that does not set it. +/// `SLOTNUM` pushes zero, whatever slot number the block environment carries: the value is the +/// engine's own and depends on no field the node supplies. #[test] -fn test_slotnum_pushes_the_blocks_slot_number() { +fn test_slotnum_pushes_zero_whatever_the_block_carries() { let code = BytecodeBuilder::default().append(SLOTNUM).return_top().build(); for (slot_num, name) in [(0x0123_4567_89ab_u64, "a slot the node set"), (0, "no slot set")] { let block = revm::context::BlockEnv { slot_num, ..crate::common::block() }; @@ -261,9 +261,8 @@ fn test_slotnum_pushes_the_blocks_slot_number() { assert!(result.is_success(), "{name}: {result:?}"); assert_eq!( result.output().map(|output| U256::from_be_slice(output)), - Some(U256::from(slot_num)), + Some(U256::ZERO), "{name}", ); } - assert_eq!(crate::common::block().slot_num, 0, "the tests' block leaves it unset"); } diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 0218aad37..832da7fe6 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -74,8 +74,8 @@ The changes, in the order this page records them: 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. + `SLOTNUM` MUST push zero, whatever slot number the block environment carries: the value is the engine's own and depends on no field the node supplies. + The read is still a read of volatile data: it is marked, detention applies after it, and it is refused when volatile-data access is disabled. - The Karst block rules apply to MegaETH blocks: - A block in which Satin activates, or in which an Optimism fork at or after Jovian in the Optimism fork order activates, MUST contain only deposit transactions; a non-deposit transaction in it makes the block invalid. A fork activates in a block when it is active at the block's timestamp and not at the parent block's, as the chain configuration schedules it; a fork the configuration does not schedule never activates. @@ -1399,8 +1399,8 @@ The witness is defined by what the block's execution returns and exports, and a 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. - The header, the chain configuration — the schedule — the parent hash, the parent beacon block root, the extra data, whether the block admits only deposits (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)), whether Satin activates in it, and the block's slot number are inputs a validator is given beside the witness. - `SLOTNUM` pushes the slot number the node supplies, so a validator MUST be given the number the building node supplied, zero included. + The header, the chain configuration — the schedule — the parent hash, the parent beacon block root, the extra data, whether the block admits only deposits (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)), and whether Satin activates in it are inputs a validator is given beside the witness. + `SLOTNUM` pushes zero, so a validator needs no slot number. - **The L1 block info.** A non-deposit transaction is priced against the L1 block contract (`0x4200000000000000000000000000000000000015`): its L1 base fee slot (1), its Ecotone fee scalars slot (3), its Ecotone blob base fee slot (7), its operator fee scalars slot (8), which also holds the DA footprint gas scalar, and, only when the Ecotone scalars are empty (the blob base fee scalar and the eight bytes of the two scalars zero), its L1 fee overhead slot (5). These reads are made on the block's state, not through a transaction's journal, so they land in no transaction's returned state. From f4c5bbd3449de4987a67c9352eb40372a11ed863 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:30:31 +0800 Subject: [PATCH 002/190] feat(system): a value-bearing sendHint is admitted --- crates/mega-evm/src/system/AGENTS.md | 2 +- crates/mega-evm/src/system/oracle.rs | 14 +-- crates/mega-evm/tests/system/oracle.rs | 117 +++++++++++++++++++--- crates/mega-evm/tests/system/system_tx.rs | 7 +- docs/spec/upgrades/satin.md | 5 +- 5 files changed, 122 insertions(+), 23 deletions(-) diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index cf25b0016..b8846c8b3 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -25,7 +25,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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 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. +- 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 — some gas (a value call's stipend included; the value itself does not matter, the bytecode refuses it after the hint was sent), 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). - `remainingComputeGas()` is read when the call reaches the dispatch, after the calling opcode charged its own costs: the lesser of the caller's regular gas with the forward counted back (`MegaEvm::intercept` passes what the caller has left; the answer returns the forward untouched) and gas detention's allowance at the call. That is the caller's spendable regular gas before the forward, which detention caps. This departs from the legacy engine's figure, 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 limit, so it could exceed the caller's gas; here compute is regular gas, and the answer is at most the caller's own. The one property carried over is that forwarded gas is not counted. - `VolatileDataAccessDisabled`'s argument is a `uint8` on the wire. A refused `SLOTNUM` names 12 (`SLOT_NUM_ACCESS_TYPE`), past the contract's enum, so Solidity handlers decode the argument as `uint8`; the contracts are not changed for it, and their code hashes stay. diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index 6028b9461..f2cb3f844 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -43,20 +43,21 @@ pub use mega_system_contracts::oracle::IOracle; /// effect rather than an answer. The Oracle's storage methods are ordinary code, and reading /// its storage through the node's oracle service is the Host's business. /// -/// Three conditions admit a hint, and none is a statement about the frame that runs afterwards: +/// Two conditions admit a hint, and none is a statement about the frame that runs afterwards: /// /// - the call was forwarded gas. A call with none cannot run the dispatcher of the bytecode at all, -/// so its hint would be a free message to the service; -/// - the call carries no value. `sendHint` is not payable, so a value-bearing call reverts in the -/// bytecode and its hint would be one the caller never sent; +/// so its hint would be a free message to the service. The gas is the message's whole gas limit, +/// the stipend of a value-transferring call included, which the call helper has added by then; a +/// transaction's own call has no stipend and is judged on its first frame's whole gas. The value +/// itself does not matter: `sendHint` is not payable, so the bytecode refuses a value-bearing +/// call, but the hint is a message to the service and has been sent; /// - the calling frame may read volatile data. A hint is how a contract asks the oracle service for /// what it will read from the Oracle's storage, and a frame whose volatile-data access /// `MegaAccessControl` switched off — its own switch, or one a frame above it set — cannot read /// it. Its hint is dropped, not refused: the call runs the bytecode as any other, because a hint /// is a message to the service, not state, and dropping it changes nothing the call returns. /// -/// The gas and switch conditions are the legacy engine's, carried over; the value condition is -/// new. A hint that fails any of them is neither forwarded nor counted. +/// A hint that fails either condition is neither forwarded nor counted. /// /// Gas above zero does not promise that the bytecode succeeds: a hint forwarded with one gas /// reaches the service and the frame it was sent from then runs out of gas. A forwarded hint is a @@ -84,7 +85,6 @@ pub(crate) fn intercept( ) -> Option { let selector = peek_selector(&inputs.input, ctx)?; if selector != IOracle::sendHintCall::SELECTOR || - inputs.transfers_value() || inputs.gas_limit == 0 || depth.checked_sub(1).is_some_and(|caller| ctx.detention.is_access_disabled(caller)) { diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 79bb3ca60..db015e574 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -15,10 +15,12 @@ use mega_evm::{ use revm::{ bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, context::result::ResultAndState, + primitives::TxKind, }; use crate::common::{ - block, call_tx, calls_with, run, steer, system_db, with_contract, CALLER, CONTRACT, + block, call_tx, call_tx_with_gas, calls_with, run, steer, system_db, with_contract, CALLER, + CONTRACT, }; /// A topic and payload the tests send. @@ -61,6 +63,15 @@ fn run_with_oracle_under( tx: MegaTransaction, limits: EvmTxRuntimeLimits, ) -> (MegaTransactionOutcome, Vec) { + try_run_with_oracle_under(db, tx, limits).expect("the transaction is valid") +} + +/// [`run_with_oracle_under`] for a transaction that may be refused: `None` when it is. +fn try_run_with_oracle_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> Option<(MegaTransactionOutcome, Vec)> { let envs = TestExternalEnvs::::new(); let ctx = MegaContext::new_with_external_envs( db, @@ -70,8 +81,8 @@ fn run_with_oracle_under( .with_block(block()) .with_chain(zero_fee_l1_block_info()) .with_tx_runtime_limits(limits); - let outcome = MegaEvm::new(ctx).execute_transaction(tx).expect("the transaction is valid"); - (outcome, envs.recorded_hints()) + let outcome = MegaEvm::new(ctx).execute_transaction(tx).ok()?; + Some((outcome, envs.recorded_hints())) } /// A `sendHint` transaction reaches the oracle service with the caller, the topic and the @@ -132,11 +143,42 @@ fn test_a_static_call_forwards_the_hint() { assert_eq!(hints[0].from, CONTRACT, "the frame that called is the sender of the hint"); } -/// A call that carries value forwards nothing: `sendHint` is not payable, so the call reverts -/// in the bytecode and the hint would be one the caller never sent. +/// A call that carries value is judged on its gas like any other, and a call that requests none +/// still holds the value call's stipend, so its hint is admitted. `sendHint` is not payable, so +/// the bytecode refuses the value; the hint is a message to the service and was already sent, and +/// its bytes stay counted. #[test] -fn test_a_value_bearing_call_forwards_nothing() { +fn test_a_value_bearing_call_forwards_its_hint() { + use revm::bytecode::opcode::{POP, PUSH0, REVERT}; + let data = send_hint(b"paid"); + let code = BytecodeBuilder::default() + .mstore(0x0, &data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(1_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(0_u64) // gas: none requested, the stipend is all the call holds + .append(CALL) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(!result.result.is_success(), "the frame that sent the hint reverted"); + assert_eq!(hints.len(), 1, "the hint reached the service"); + assert_eq!(hints[0].from, CONTRACT); + assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); +} + +/// The bytecode refuses the value of a value-bearing call that holds gas, as before: the hint is +/// forwarded and the call reports failure. +#[test] +fn test_a_value_bearing_call_with_gas_forwards_its_hint_and_the_bytecode_refuses() { + let data = send_hint(b"paid with gas"); let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &data, 1); let (result, hints, usage) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); @@ -144,12 +186,63 @@ fn test_a_value_bearing_call_forwards_nothing() { let outcome = result.result.output().cloned().unwrap_or_default(); let (status, _) = crate::common::split_outcome(&outcome); assert!(!status, "the bytecode refuses the value"); - assert!(hints.is_empty()); - assert_eq!( - usage.data_size, - nested_hint(0), - "nothing was materialised for a hint that is not forwarded" - ); + assert_eq!(hints.len(), 1); + assert_eq!(usage.data_size, nested_hint(data.len() as u64)); +} + +/// A transaction's own value call has no stipend and is judged on its first frame's whole gas: +/// one gas admits the hint, and so do the stipend's 2,300 and 2,301. The smallest gas limit that +/// does is found by search, since the first frame's gas is what the limit leaves after the +/// intrinsic and start charges, which depend on the byte prices; a legacy transaction and a +/// deposit alike. +#[test] +fn test_a_transactions_own_value_hint_is_admitted_on_one_gas_and_more() { + let data = send_hint(b"own"); + let funded = || system_db().account_balance(ORACLE_CONTRACT_ADDRESS, U256::from(1)); + let legacy = |gas: u64| call_tx_with_gas(ORACLE_CONTRACT_ADDRESS, &data, U256::from(1), gas); + let deposit = |gas: u64| { + let mut tx = crate::system_tx::deposit_tx( + CALLER, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + U256::from(1), + 1, + ); + tx.0.base.data = data.clone(); + tx.0.base.gas_limit = gas; + tx + }; + type Build<'a> = &'a dyn Fn(u64) -> MegaTransaction; + let forwarded = |build: Build<'_>, gas: u64| { + // A gas limit the transaction is refused at runs nothing. + try_run_with_oracle_under(funded(), build(gas), EvmTxRuntimeLimits::no_limits()) + .is_some_and(|(_, hints)| !hints.is_empty()) + }; + for (name, build) in [("legacy", &legacy as Build<'_>), ("deposit", &deposit as Build<'_>)] { + // The smallest gas limit whose first frame holds any gas at all. + let (mut low, mut high) = (21_000_u64, 30_000_000_u64); + assert!(forwarded(build, high), "{name}: a large limit forwards"); + while low < high { + let mid = low + (high - low) / 2; + if forwarded(build, mid) { + high = mid; + } else { + low = mid + 1; + } + } + let one_gas = high; + assert!(!forwarded(build, one_gas - 1), "{name}: no gas in the first frame, no hint"); + for frame_gas in [1_u64, 2_300, 2_301] { + let (outcome, hints) = run_with_oracle_under( + funded(), + build(one_gas + frame_gas - 1), + EvmTxRuntimeLimits::no_limits(), + ); + let case = format!("{name}: {frame_gas} gas"); + assert_eq!(hints.len(), 1, "{case}: the hint reached the service"); + assert_eq!(hints[0].from, CALLER, "{case}"); + assert!(outcome.usage.data_size >= data.len() as u64, "{case}: and it is counted"); + } + } } /// A call forwarded no gas forwards nothing: it cannot run the contract either, so its hint diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 71f9ac166..d4559c160 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -75,7 +75,12 @@ fn legacy_tx_with_chain_id( } /// A deposit transaction from `caller`, which pays no fee, minting `mint` to its caller. -fn deposit_tx(caller: Address, kind: TxKind, value: U256, mint: u128) -> MegaTransaction { +pub(crate) fn deposit_tx( + caller: Address, + kind: TxKind, + value: U256, + mint: u128, +) -> MegaTransaction { let mut tx = legacy_tx(caller, kind, Bytes::new(), 0); tx.0.base.gas_price = 0; tx.0.base.value = value; diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 832da7fe6..988130282 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1148,9 +1148,10 @@ An out-of-gas step halts the call, consuming its regular gas. - Every such read MUST be charged as a cold access (2,100 gas), however often the slot was read, and the slot MUST be loaded whichever source answers, so a later write finds it warm and a stateless witness carries it. - A frame whose regular gas, its withheld part included, cannot pay the cold access MUST read nothing and ask nothing; a refused read asks nothing. - A system call MUST NOT ask the service at all: its read answers the chain's value (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). -- A `sendHint` MUST reach the service synchronously, when it is called, and only when the call is forwarded gas, carries no value, and comes from a frame whose volatile-data access is on. +- A `sendHint` MUST reach the service synchronously, when it is called, and only when the call is forwarded gas and comes from a frame whose volatile-data access is on. A hint that fails any of those conditions is dropped and counts nothing; the call runs the Oracle's bytecode either way. - The value condition is new. + A call that carries value is judged on its gas like any other: the gas of a value-transferring call includes its stipend, and a transaction's own call is judged on its first frame's whole gas. + The Oracle's bytecode refuses the value, which changes nothing about a hint already sent. The service MUST be handed the hint's topic, its data, and the address of the frame that made the call: the transaction's sender for a `sendHint` that is the transaction's own call. Only a `CALL` or a `STATICCALL` to the Oracle is a `sendHint`: a `CALLCODE` or `DELEGATECALL` of the method runs the Oracle's bytecode in a frame of the caller's own context, reaches no service and counts nothing. - An admitted hint MUST count the call's whole input length as data size on the transaction, before the input is decoded, and pays no history gas. From 773d12b13962b468b35ac741201e29bb8c7dc3e3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:30:44 +0800 Subject: [PATCH 003/190] feat(keyless): recognize a keylessDeploy call only once its arguments decode --- AGENTS.md | 2 +- crates/mega-evm/src/evm/execution.rs | 10 +-- .../mega-evm/src/system/keyless/dispatch.rs | 59 +++++++++------- crates/mega-evm/src/system/keyless/mod.rs | 6 +- .../mega-evm/tests/block/witness/keyless.rs | 8 ++- .../mega-evm/tests/system/keyless/dispatch.rs | 70 ++++++++++++++++--- crates/mega-evm/tests/system/keyless/frame.rs | 5 +- .../tests/system/keyless/precedence.rs | 53 ++++++++------ ...erential__keyless_differential_record.snap | 12 ++-- docs/spec/upgrades/satin.md | 6 +- 10 files changed, 154 insertions(+), 77 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8a60340d2..d7e168288 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -307,7 +307,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. - The dispatch is by address and selector, whatever the address holds: where the state holds no contract code, the frame is built on the contract's own, which never runs. + The dispatch is by address, selector and arguments that decode as `(bytes, uint256)` (a call whose arguments do not decode is not dispatched, is charged nothing and runs the bytecode), whatever the address holds: where the state holds no contract code, the frame is built on the contract's own, which never runs. A stop of the call itself — its own charges past detention's limit, or a limit the creator's nonce record crosses on it — reverts it with the stop and takes the deployment back, the signer's nonce included; otherwise the call succeeds with the deployed address or the error the creation failed with, a limit's stop the creation crossed included. `ORIGIN` and `GASPRICE` in the init code are the transaction's, and `gasUsed` is what the creation spent from either pool, the same below and above the execution cap. Rule 4 (signer nonce at most 1) counts real nonces: the creation's bump stands from 0 to 1, which is the replay barrier. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 533cb5c6e..242a50be5 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -632,8 +632,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm( ctx: &MegaContext, frame_init: &FrameInit, -) -> bool { - let FrameInput::Call(inputs) = &frame_init.frame_input else { return false }; - frame_init.depth == 0 && - inputs.target_address == KEYLESS_DEPLOY_ADDRESS && - inputs.scheme == CallScheme::Call && - peek_selector(&inputs.input, ctx) == Some(IKeylessDeploy::keylessDeployCall::SELECTOR) +) -> Option { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; + if frame_init.depth != 0 || + inputs.target_address != KEYLESS_DEPLOY_ADDRESS || + inputs.scheme != CallScheme::Call || + peek_selector(&inputs.input, ctx) != Some(IKeylessDeploy::keylessDeployCall::SELECTOR) + { + return None; + } + IKeylessDeploy::keylessDeployCall::abi_decode(&inputs.input.bytes(ctx)).ok() } /// Readies the frame of a call [`is_dispatched`] took for revm to build, or answers it. @@ -85,14 +92,15 @@ 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 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. +/// made by hand, its first by [`start`]. The dispatch is by address, selector and decoded +/// arguments, 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, frame_init: &mut FrameInit, + call: &IKeylessDeploy::keylessDeployCall, ) -> Result, ContextError> { let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return Ok(None) }; if inputs.call_value().is_zero() { @@ -104,7 +112,7 @@ pub(crate) fn ready( } let mut gas = untouched_call_gas(inputs); ctx.detention.hold(gas.tracker_mut()); - let Err(refusal) = prepare(ctx, inputs, &mut gas)? else { + let Err(refusal) = prepare(ctx, inputs, call, &mut gas)? else { unreachable!("a call carrying value is refused at rule 2") }; Ok(Some(refusal.answer(inputs, gas))) @@ -125,9 +133,10 @@ pub(crate) fn ready( /// transaction and recovering its signer. A call that cannot pay it runs out of gas. /// 2. The call carries no value (`NoEtherTransfer()`). A call carrying value is refused before revm /// builds its frame ([`ready`]). -/// 3. Its arguments decode, and so does the transaction they carry: a signed legacy creation, no -/// chain id, no trailing bytes (`MalformedEncoding()`, `NotContractCreation()`, -/// `NotPreEIP155()`), signed at nonce 0 (`NonZeroTxNonce`). +/// 3. The transaction the arguments carry decodes (the arguments themselves decoded when the call +/// was recognized): a signed legacy creation, no chain id, no trailing bytes +/// (`MalformedEncoding()`, `NotContractCreation()`, `NotPreEIP155()`), signed at nonce 0 +/// (`NonZeroTxNonce`). /// 4. The init code is within the configured initcode size limit (`InitCodeTooLarge`). /// 5. `gasLimitOverride` covers the signed gas limit (`GasLimitTooLow`). /// 6. The signer can be recovered (`InvalidSignature()`). @@ -173,12 +182,13 @@ pub(crate) fn ready( pub(crate) fn start( ctx: &mut MegaContext, frame: &mut EthFrame, + call: &IKeylessDeploy::keylessDeployCall, ) -> Result> { let FrameInput::Call(inputs) = &frame.input else { unreachable!("a keylessDeploy call's frame is a call") }; let gas = &mut frame.interpreter.gas; - let deployment = match prepare(ctx, inputs, gas)? { + let deployment = match prepare(ctx, inputs, call, gas)? { Ok(deployment) => deployment, Err(refusal) => { let (result, output) = refusal.result(gas); @@ -265,6 +275,7 @@ impl Refusal { fn prepare( ctx: &mut MegaContext, inputs: &CallInputs, + call: &IKeylessDeploy::keylessDeployCall, gas: &mut Gas, ) -> Result, ContextError> { macro_rules! refuse { @@ -278,10 +289,6 @@ fn prepare( if !inputs.call_value().is_zero() { refuse!(KeylessDeployError::NoEtherTransfer); } - let input = inputs.input.bytes(ctx); - let Ok(call) = IKeylessDeploy::keylessDeployCall::abi_decode(&input) else { - refuse!(KeylessDeployError::MalformedEncoding); - }; let signed = match decode_keyless_tx(&call.keylessDeploymentTransaction) { Ok(signed) => signed, Err(error) => refuse!(error), diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index a6f041077..5c3283d14 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -29,9 +29,9 @@ //! 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 -//! 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. +//! - The dispatch is by address, selector and arguments that decode, whatever the address holds: +//! 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. //! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. //! - The creation runs at depth 1, as the call's child: one level below the same init code sent as //! a creation transaction, which runs at depth 0. Its frames reach the call-stack limit one frame diff --git a/crates/mega-evm/tests/block/witness/keyless.rs b/crates/mega-evm/tests/block/witness/keyless.rs index 01bf9a873..f1449ee7c 100644 --- a/crates/mega-evm/tests/block/witness/keyless.rs +++ b/crates/mega-evm/tests/block/witness/keyless.rs @@ -220,7 +220,8 @@ fn test_a_resubmission_in_the_same_block_is_refused() { assert_eq!(refused(run, 1), KeylessDeployError::ContractAlreadyExists); } -/// A malformed call is refused before any read. +/// A call whose arguments do not decode is not a deployment: the bytecode runs, and nothing is +/// read. #[test] fn test_a_malformed_keyless_call_reads_nothing() { let data: Bytes = @@ -228,6 +229,9 @@ fn test_a_malformed_keyless_call_reads_nothing() { let replay = Case::new("keyless malformed", db()).tx(call(0, KEYLESS_DEPLOY_ADDRESS, data, GAS)).run(); let run = &replay.recorded; - assert_eq!(refused(run, 0), KeylessDeployError::MalformedEncoding); + let ExecutionResult::Revert { output, .. } = &run.tx(0).result else { + panic!("the call did not revert: {:?}", run.tx(0).result); + }; + assert!(output.is_empty()); assert!(run.bucket_ids.is_empty()); } diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index e877fe363..a45921370 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -174,15 +174,69 @@ fn test_the_overhead_does_not_depend_on_the_payload() { } } -/// Admission is the selector alone here too: a payload too short to hold the arguments the ABI -/// names is still dispatched and charged, and the deployment rejects what it cannot decode with -/// `MalformedEncoding()`. +/// A call is recognised only once its arguments decode as `(bytes, uint256)`: a payload too short +/// to hold them, an offset that points past the data, and a length that runs past it are not +/// dispatched. The deployed bytecode runs and its decoder reverts with empty data, and the +/// overhead is not charged. #[test] -fn test_a_truncated_payload_is_still_dispatched() { - let truncated: Bytes = - KEYLESS_DEPLOY.iter().copied().chain([0_u8; 16]).collect::>().into(); - let dispatched = run_with(system_db(), truncated.clone(), GAS_LIMIT, no_limits()); +fn test_arguments_that_do_not_decode_are_not_dispatched() { + let selector = KEYLESS_DEPLOY.to_vec(); + let word = |value: u64| U256::from(value).to_be_bytes::<32>().to_vec(); + let well_formed = keyless_deploy(b"a transaction").to_vec(); + + let mut offset_past_the_data = selector.clone(); + offset_past_the_data.extend(word(0x1000)); + offset_past_the_data.extend(word(1_000_000)); + let mut length_past_the_data = selector.clone(); + length_past_the_data.extend(word(0x40)); + length_past_the_data.extend(word(1_000_000)); + length_past_the_data.extend(word(32)); + let cases = [ + ("short", [selector.clone(), vec![0_u8; 16]].concat()), + ("selector alone", selector.clone()), + ("offset past the data", offset_past_the_data), + ("length past the data", length_past_the_data), + ("cut inside the bytes", well_formed[..well_formed.len() - 40].to_vec()), + ]; + for (name, input) in cases { + let data = Bytes::from(input); + for gas_limit in GAS_LIMITS { + let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("{name}: the bytecode did not revert: {:?}", outcome.result); + }; + assert!(output.is_empty(), "{name}: the bytecode's decoder reverts with empty data"); + let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); + assert!( + total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, + "{name} at {gas_limit}: paid {total} beyond a plain call, an overhead it does not \ + owe", + ); + } + } +} + +/// Bytes after a valid encoding do not prevent the recognition: the call is dispatched and pays +/// the overhead, and the deployment rejects what the first argument carries. +#[test] +fn test_bytes_after_a_valid_encoding_are_still_dispatched() { + let mut data = keyless_deploy(b"a transaction").to_vec(); + data.extend([0xab; 5]); + let data = Bytes::from(data); + let dispatched = run_with(system_db(), data.clone(), GAS_LIMIT, no_limits()); assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); - let [total, ..] = beyond(&dispatched, &reference(truncated, GAS_LIMIT)); + let [total, ..] = beyond(&dispatched, &reference(data, GAS_LIMIT)); assert_eq!(total, KEYLESS_DEPLOY_OVERHEAD_GAS); } + +/// A call that carries value and whose arguments do not decode is not dispatched either: the +/// bytecode runs and refuses the value itself, with the empty revert data of a non-payable +/// method, and no overhead is charged. +#[test] +fn test_a_value_call_whose_arguments_do_not_decode_runs_the_bytecode() { + let truncated: Bytes = KEYLESS_DEPLOY.iter().copied().chain([0_u8; 16]).collect(); + let result = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, truncated, U256::from(1))); + assert!(!result.result.is_success()); + assert!(revert_data(&result).is_empty()); + assert!(result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS); +} diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 07f2362bd..8867210dd 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -274,8 +274,9 @@ fn test_the_contracts_bytecode_never_runs_for_a_dispatched_call() { } } -/// The dispatch is by address and selector, whatever the address holds: where the state holds no -/// contract code, the call's frame is built on the contract's own, and the call deploys. +/// The dispatch is by address, selector and decodable arguments, whatever the address holds: where +/// the state holds no contract code, the call's frame is built on the contract's own, and the call +/// deploys. #[test] fn test_a_call_is_dispatched_where_the_state_holds_no_contract_code() { let deployment = Deployment::new(deploying(&runtime(1))); diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 46db0ffa9..3e39599bd 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -10,8 +10,9 @@ //! charges refuse on their own, where the legacy engine charged nothing. //! //! One pair reports an error the legacy engine never reported: a call carrying value whose -//! arguments do not decode is refused for the value, where the legacy engine ran the bytecode and -//! reverted with empty data. +//! carried transaction does not decode is refused for the value, where the legacy engine ran the +//! bytecode and reverted with empty data. A call whose arguments do not decode is no deployment +//! at all, with or without value, and runs the bytecode as the legacy engine did. use mega_evm::{ system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, @@ -144,32 +145,40 @@ fn test_a_call_two_rules_refuse_reports_the_first_the_legacy_engine_checked() { } } -/// A call that carries value and whose arguments do not decode, or carry a transaction that does -/// not, is refused for the value: the value rule comes before decoding. The same call without -/// value is refused `MalformedEncoding()`. The legacy engine let both fall through to the -/// bytecode, which reverted with empty data. +/// A call that carries value and a transaction that does not decode is refused for the value: the +/// value rule comes before decoding the transaction. The same call without value is refused +/// `MalformedEncoding()`. Arguments that do not decode as `(bytes, uint256)` are no deployment at +/// all and reach neither rule: they run the bytecode, which reverts with empty data. #[test] fn test_a_value_bearing_call_that_does_not_decode_is_refused_for_the_value() { let truncated: Bytes = IKeylessDeploy::keylessDeployCall::SELECTOR.iter().copied().chain([0; 16]).collect(); let undecodable_tx = keyless_deploy_call(b"a transaction", U256::from(LARGE_OVERRIDE)); for gas_limit in GAS_LIMITS { - for (payload, data) in [("arguments", &truncated), ("transaction", &undecodable_tx)] { - for (value, answer) in [ - (0, KeylessDeployError::MalformedEncoding), - (1, KeylessDeployError::NoEtherTransfer), - ] { - let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::from(value)); - tx.0.base.gas_limit = gas_limit; - let outcome = MegaEvm::new(context(system_db())) - .execute_transaction(tx) - .expect("a valid transaction"); - assert_eq!( - refusal(&outcome), - answer, - "undecodable {payload}, value {value}, at {gas_limit}", - ); - } + for value in [0, 1] { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, truncated.clone(), U256::from(value)); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(tx) + .expect("a valid transaction"); + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("the bytecode did not revert: {:?}", outcome.result); + }; + assert!(output.is_empty(), "undecodable arguments, value {value}, at {gas_limit}"); + } + for (value, answer) in + [(0, KeylessDeployError::MalformedEncoding), (1, KeylessDeployError::NoEtherTransfer)] + { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, undecodable_tx.clone(), U256::from(value)); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(tx) + .expect("a valid transaction"); + assert_eq!( + refusal(&outcome), + answer, + "undecodable transaction, value {value}, at {gas_limit}", + ); } } } 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 f0a43b50f..b57d440a4 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 @@ -5,8 +5,8 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca { "cases": [ "rule: value @ 50000000 | keccak256=0x70efa1acc6606a24ed2001d41f9e6ac401ef411f46c929dee5043aa06be58810", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x67d4381e1b358e4694b07b0a18728c4e6e3f1c91077391acab6ceed782e46d29", - "rule: arguments that do not decode @ 50000000 | keccak256=0xd2827c7aec63978452165c7595a034877c8771d7e504b7dea3f3fbc0aa15b5db", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x6401f75c56ae5ba4720369e22bb4fae524a0d92109200d1b814890f050b4deb7", + "rule: arguments that do not decode @ 50000000 | keccak256=0xf200f388d13c3181bef7bd920c142d7682efb6a66a337cd89380d9c322b302e4", "rule: malformed transaction @ 50000000 | keccak256=0x53e169618aad04c59acaa0e61bf9a259e42b3994e3df64ec789329dd04a03472", "rule: a trailing byte @ 50000000 | keccak256=0x562d6c884cab4c6ca986bead04dc90661c3dd59026842d504f1a785f109ebde9", "rule: not a creation @ 50000000 | keccak256=0x3931ffdc0411acf5f321a32fd6fbd0c8b9cd6fc15367d7c222838b2fc4ea9543", @@ -70,8 +70,8 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "no contract code @ 50000000 | keccak256=0xd070c6166a53661bc3203f16a69707d9e8846b3c1737d22cbfff5a7a5f6f67c8", "a system call @ 50000000 | keccak256=0x23867bfad6c1f95ee8422b2c15dfb47ab157163fecdb69f6e142f50971b86ea2", "rule: value @ 400000000 | keccak256=0xb00b12499990c15c1599808de7903b34b5ed9beb8673675a5a9aa77fafa9015b", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0xab45a43f5e1a4faa1af944c4016c3dce4436e6ec00814fc78ad3897c791321f2", - "rule: arguments that do not decode @ 400000000 | keccak256=0xdc686f081e53b20b0eb44e645c0efc0a34c584ebccc694f6ba79c6f9a0cedcdf", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0x3dcf58fea56c393d9432b8d0ddb70ab27c94f1f397297097116ab93d288638d9", + "rule: arguments that do not decode @ 400000000 | keccak256=0x1e85d077ef72d33c8bedeef7ab6a25396d2045a316422c35a003947d831b924a", "rule: malformed transaction @ 400000000 | keccak256=0xa14ab3686735b259326aeefd8ffde19e7d03ca5f6710a8278d3c20b3588941c7", "rule: a trailing byte @ 400000000 | keccak256=0xe3dd6f5f1d180e13aa45ac712b48ae4124f1f24283214c1aa69d30174cb444e1", "rule: not a creation @ 400000000 | keccak256=0x228398e161b11148e9c04b5732a72a116f61e8682066063a104ac1065d76ba47", @@ -145,9 +145,9 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "rule: init code over the limit @ 2000000000 | keccak256=0xf7949b8ae857d9eb689ab1a96b0795d150698f13795c880b330fe388ca949434" ], "summary": { - "bytes": 2443212, + "bytes": 2451324, "cases": 139, - "lines": 11452, + "lines": 11482, "runs": 556 } } diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 0218aad37..01a21a8fd 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1064,7 +1064,9 @@ A node MUST apply [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708): #### New behavior A `keylessDeploy(bytes,uint256)` call that is the transaction's own frame (depth 0, to `KEYLESS_DEPLOY_ADDRESS` = `0x6342000000000000000000000000000000000003`) MUST deploy the carried creation as an ordinary creation frame, a child of the call; no code runs in the call's frame itself. -The call is recognized by its depth, its scheme (`CALL`), its target and its selector alone, whatever code the state holds at the address. +The call is recognized by its depth, its scheme (`CALL`), its target, its selector and its arguments, which MUST decode under the Solidity ABI as `(bytes, uint256)` (bytes after a valid encoding do not prevent it), whatever code the state holds at the address. +A call with the selector whose arguments do not decode is not recognized: it is charged nothing and runs the contract's bytecode, as every other call to the contract does, and the bytecode reverts with empty data. +This holds with or without value. A `keylessDeploy` call a contract makes MUST run the contract's bytecode: without value it reverts with `NotIntercepted()`, and with value it reverts with empty data, the method not being payable. The call MUST make these charges and checks, in this order. @@ -1075,7 +1077,7 @@ An out-of-gas step halts the call, consuming its regular gas. | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | 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()` | +| 3 | The carried transaction decodes (the arguments decoded when the call was recognized): 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)` | From 8611c5faa2bf306a2d66d3548ab4b1995ff1b102 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:35:35 +0800 Subject: [PATCH 004/190] test(keyless): a stop test's keylessDeploy call carries well-formed arguments --- crates/mega-evm/tests/block/witness/stops.rs | 11 ++++++++--- crates/mega-evm/tests/system/keyless/dispatch.rs | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs index 00f5d952d..0bec7f281 100644 --- a/crates/mega-evm/tests/block/witness/stops.rs +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -71,10 +71,15 @@ fn read_then_ecrecover() -> Bytes { .build() } -/// The calldata of a `keylessDeploy` call the dispatch takes: its selector and bytes the value -/// rule refuses before they are decoded. +/// The calldata of a `keylessDeploy` call the dispatch takes: a well-formed encoding of its +/// arguments, carrying bytes the value rule refuses before they are decoded as a transaction. fn keyless_call() -> Bytes { - IKeylessDeploy::keylessDeployCall::SELECTOR.iter().copied().chain([0_u8; 8]).collect() + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(&[0_u8; 8]), + gasLimitOverride: U256::ZERO, + } + .abi_encode() + .into() } /// The stop `kind` reports. diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index a45921370..7e1f25913 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -193,7 +193,7 @@ fn test_arguments_that_do_not_decode_are_not_dispatched() { length_past_the_data.extend(word(32)); let cases = [ ("short", [selector.clone(), vec![0_u8; 16]].concat()), - ("selector alone", selector.clone()), + ("selector alone", selector), ("offset past the data", offset_past_the_data), ("length past the data", length_past_the_data), ("cut inside the bytes", well_formed[..well_formed.len() - 40].to_vec()), From 0d9752d03295d28d544d9bd73da5217f05990d92 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:37:57 +0800 Subject: [PATCH 005/190] test(utils): MemoryDatabase commit applies EIP-161 clearing, and the authority growth test pins the node's answer --- crates/mega-evm/src/test_utils/database.rs | 76 +++++++++++++++++++-- crates/mega-evm/tests/satin/state_growth.rs | 52 +++++++++----- 2 files changed, 106 insertions(+), 22 deletions(-) diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs index aeda79c25..376af8efa 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -234,10 +234,28 @@ impl revm::Database for MemoryDatabase { } impl revm::DatabaseCommit for MemoryDatabase { - delegate! { - to self.db { - fn commit(&mut self, changes: EvmState); - } + /// Commits a transaction's state with EIP-161 state clearing, as a node's database does. + /// + /// revm leaves the removal of a touched empty account to the database at commit, and + /// `CacheDB` keeps such an account as an existing empty one. A node's state removes it, so + /// a later transaction finds it absent and charges it as a new account. An account created in + /// the transaction stays, as under revm's own `State`, and a self-destructed account is + /// handled by `CacheDB` as before. + fn commit(&mut self, mut changes: EvmState) { + changes.retain(|address, account| { + let cleared = account.is_touched() && + account.is_empty() && + !account.is_selfdestructed() && + !account.is_created(); + if cleared { + let cached = self.db.cache.accounts.entry(*address).or_default(); + cached.storage.clear(); + cached.account_state = AccountState::NotExisting; + cached.info = AccountInfo::default(); + } + !cleared + }); + self.db.commit(changes); } } @@ -355,4 +373,54 @@ mod tests { assert!(err.to_string().contains("injected block_hash() error for 7"), "{err}"); assert_eq!(db.block_hash(1).unwrap(), served); } + + fn touched(info: AccountInfo) -> revm::state::Account { + let mut account = revm::state::Account::from(info); + account.mark_touch(); + account + } + + #[test] + fn test_commit_removes_a_touched_empty_account_and_keeps_the_rest() { + use revm::DatabaseCommit; + let empty = address!("00000000000000000000000000000000000000e1"); + let funded = address!("00000000000000000000000000000000000000e2"); + let destroyed = address!("00000000000000000000000000000000000000e3"); + let mut db = MemoryDatabase::default() + .account_balance(funded, U256::from(5)) + .account_balance(destroyed, U256::from(7)); + // An empty account the database holds, and one it holds none for, both touched. + db.insert_account_info(empty, AccountInfo::default()); + db.insert_account_storage(empty, U256::from(1), U256::from(2)).unwrap(); + let absent = address!("00000000000000000000000000000000000000e4"); + + let mut selfdestructed = touched(AccountInfo::from_balance(U256::from(7))); + selfdestructed.mark_selfdestruct(); + let changes: EvmState = [ + (empty, touched(AccountInfo::default())), + (absent, touched(AccountInfo::default())), + (funded, touched(AccountInfo::from_balance(U256::from(5)))), + (destroyed, selfdestructed), + ] + .into_iter() + .collect(); + db.commit(changes); + + assert_eq!(db.basic(empty).unwrap(), None, "a touched empty account is removed"); + assert_eq!(db.storage(empty, U256::from(1)).unwrap(), U256::ZERO, "its storage with it"); + assert_eq!(db.basic(absent).unwrap(), None, "and one the database held none for"); + assert_eq!(db.basic(funded).unwrap().expect("kept").balance, U256::from(5)); + assert_eq!(db.basic(destroyed).unwrap(), None, "a self-destructed account is removed"); + } + + #[test] + fn test_commit_keeps_an_empty_account_created_in_the_transaction() { + use revm::DatabaseCommit; + let created = address!("00000000000000000000000000000000000000e5"); + let mut account = touched(AccountInfo::default()); + account.mark_created(); + let mut db = MemoryDatabase::default(); + db.commit([(created, account)].into_iter().collect()); + assert!(db.basic(created).unwrap().is_some(), "a created account is not cleared"); + } } diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index fd461d08c..6623ec61c 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -304,41 +304,57 @@ fn test_an_authority_an_earlier_transaction_funded_is_no_new_account() { } /// 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. +/// for, is charged as a new account when the earlier transaction is committed: the call touched the +/// empty account, and a node's database removes a touched empty account (EIP-161), so the +/// application finds it absent. The transaction counts the rise for it, and one write record. #[test] -fn test_an_authority_an_earlier_transaction_touched_is_counted_as_it_is_charged() { - use revm::{DatabaseCommit, ExecuteEvm}; +fn test_an_authority_an_earlier_transaction_touched_is_charged_as_new_when_committed() { + use revm::DatabaseCommit; 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()); + let first = run(db.clone(), touch); assert!(first.result.is_success(), "{:?}", first.result); - let mut committed = db.clone(); + let mut committed = db; committed.commit(first.result_and_state.state); - counted_as_charged(&run(committed, apply.clone()), "committed"); + let outcome = run(committed, apply); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, account + delegation); + assert_eq!(outcome.usage.state_growth, 1); + assert_eq!(outcome.usage.write_records, 1); +} +/// The same two transactions on one journal that is not finalized in between differ from the +/// committed path, in simulation only: revm's flag of the call's touch outlives the call's +/// transaction, so the application finds the authority touched, not new, and charges the +/// delegation alone, counts no rise, and still one write record. A node commits between +/// transactions, so this is not the chain's answer. +#[test] +fn test_an_authority_touched_on_one_unfinalized_journal_is_charged_the_delegation_only() { + use revm::ExecuteEvm; + if state_is_free() { + return; + } + let (_, delegation) = account_and_delegation(); + 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 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"); + let outcome = evm.execute_transaction(apply).expect("valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, delegation); + assert_eq!(outcome.usage.state_growth, 0); + assert_eq!(outcome.usage.write_records, 1); } /// The state gas an authority costs is charged before the first frame, from the transaction's From 8d7bb05b03e02b3856dd05cda2f57f2436562233 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:39:05 +0800 Subject: [PATCH 006/190] feat(block): the executor works out the two activation-block rules from the parent timestamp --- bin/mega-evme/src/block/satin.rs | 19 ++-- bin/mega-evme/src/replay/cmd.rs | 9 +- crates/mega-evm/src/block/executor.rs | 91 +++++++++++-------- crates/mega-evm/tests/block/activation.rs | 65 +++++++++---- crates/mega-evm/tests/block/common.rs | 19 +++- crates/mega-evm/tests/block/predeploys.rs | 19 ++-- crates/mega-evm/tests/block/rules.rs | 7 +- crates/mega-evm/tests/block/sequences.rs | 10 +- .../tests/block/witness/predeploys.rs | 26 +++--- .../mega-state-test/src/blockchain/chain.rs | 10 +- 10 files changed, 159 insertions(+), 116 deletions(-) diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 9917d2a9d..dd128f549 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -68,20 +68,19 @@ pub(super) fn execute( envs = envs.with_bucket_capacity(bucket, capacity); } 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 - // schedule activates after genesis is active at it, so Satin does not activate in it either. - let activates_satin = parent_timestamp - .is_some_and(|parent| hardforks.is_satin_activation_block(parent, header.timestamp)); - let block_ctx = MegaBlockExecutionCtx::new( + // The executor works out which rules the block's activations bring from the schedule and the + // parent's timestamp. Without the timestamp it applies none, which is right only where no + // fork activates in the block, so any other block is refused here. + admits_only_deposits(&hardforks, header.number, parent_timestamp, header.timestamp)?; + let mut block_ctx = MegaBlockExecutionCtx::new( header.parent_hash, header.parent_beacon_block_root, header.extra_data.clone(), BlockLimits::default(), - ) - .with_no_user_tx_activation_block(only_deposits) - .with_satin_activation_block(activates_satin); + ); + if let Some(parent_timestamp) = parent_timestamp { + block_ctx = block_ctx.with_parent_timestamp(parent_timestamp); + } let result = { let mut db = State::builder().with_database(SatinDb(state)).with_bundle_update().build(); diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index b2256685e..719d51f34 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -19,8 +19,7 @@ use mega_evm::{ primitives::{eip4844, Address, Log}, DatabaseRef, Inspector, }, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforks, - MegaSpecId, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaSpecId, }; use tracing::{debug, info, trace, warn}; @@ -447,17 +446,13 @@ impl Cmd { // 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 // node works it out. - let parent_timestamp = ctx.parent_block.header.timestamp(); - let only_deposits = hardforks.admits_only_deposits(parent_timestamp, timestamp); - let activates_satin = hardforks.is_satin_activation_block(parent_timestamp, timestamp); let block_ctx = MegaBlockExecutionCtx::new( ctx.parent_block.hash(), ctx.block.header.parent_beacon_block_root(), ctx.block.header.extra_data().clone(), BlockLimits::default(), ) - .with_no_user_tx_activation_block(only_deposits) - .with_satin_activation_block(activates_satin); + .with_parent_timestamp(ctx.parent_block.header.timestamp()); let start = Instant::now(); // The tracer is attached only for `--trace`: otherwise preceding transactions would be diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 92e174a38..39a2d305d 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -14,10 +14,11 @@ //! //! # The block rules of the Karst base //! -//! - **An activation block admits only deposits.** The caller sets -//! [`no_user_tx_activation_block`](MegaBlockExecutionCtx::no_user_tx_activation_block) from the -//! chain's schedule ([`MegaHardforks::admits_only_deposits`]), and a user transaction in such a -//! block is refused before it executes. This mirrors alloy-op-evm's flag of the same name. +//! - **An activation block admits only deposits.** The executor works out whether a fork activates +//! in the block from the chain's schedule ([`MegaHardforks::admits_only_deposits`]), the block's +//! own timestamp and the parent's, which the caller supplies with +//! [`MegaBlockExecutionCtx::with_parent_timestamp`]. A user transaction in such a block is +//! refused before it executes. This mirrors alloy-op-evm's rule of the same name. //! - **The data-availability footprint is a block limit.** Each non-deposit transaction's footprint //! is its compressed size times the footprint gas scalar the L1 block contract holds, accumulated //! against the block's gas limit and reported as the block's blob gas used. With no scalar in @@ -138,7 +139,7 @@ use crate::{ /// What the node hands block execution beside the EVM. /// /// It carries what the pre-block calls need (the parent hash and the parent beacon block root, as -/// alloy-op-evm does), the block's own extra data, the two activation-block flags and the +/// alloy-op-evm does), the block's own extra data, the parent block's timestamp and the /// builder's packing policy. #[derive(Clone, Debug, Default)] pub struct MegaBlockExecutionCtx { @@ -148,21 +149,16 @@ pub struct MegaBlockExecutionCtx { pub parent_beacon_block_root: Option, /// The block's extra data. pub extra_data: Bytes, - /// Whether this block admits only deposit transactions because a fork activates in it. + /// The parent block's timestamp. /// - /// The caller sets it from the chain's schedule with - /// [`MegaHardforks::admits_only_deposits`], which needs the parent block's timestamp; `false` - /// skips the rule. - pub no_user_tx_activation_block: bool, - /// Whether Satin activates in this block, which makes the pre-block step check the system - /// contracts and the EIP-7997 factory. + /// With the chain's schedule and the block's own timestamp it decides whether a fork + /// activates in this block, which makes the block admit only deposits, and whether Satin + /// does, which makes the pre-block step check the system contracts and the EIP-7997 factory. + /// The executor works both out itself. /// - /// The caller sets it from the chain's schedule with - /// [`MegaHardforks::is_satin_activation_block`], which needs the parent block's timestamp, as - /// it sets [`no_user_tx_activation_block`](Self::no_user_tx_activation_block); `false` - /// skips the check. The two differ: an Optimism fork at or after Jovian also makes a block - /// deposit-only. - pub satin_activation_block: bool, + /// `None` is a block with no parent to compare against, such as a genesis block: neither + /// rule applies to it. A caller that executes a block with a parent must supply it. + pub parent_timestamp: Option, /// The builder's packing policy: the limits only a builder applies, and a cap on the block's /// data-size budget below the protocol's ([`BlockLimits`]). /// @@ -172,7 +168,8 @@ pub struct MegaBlockExecutionCtx { } impl MegaBlockExecutionCtx { - /// A context for a block that activates no fork. + /// A context for a block with no known parent timestamp; supply it with + /// [`with_parent_timestamp`](Self::with_parent_timestamp). pub const fn new( parent_hash: B256, parent_beacon_block_root: Option, @@ -183,21 +180,15 @@ impl MegaBlockExecutionCtx { parent_hash, parent_beacon_block_root, extra_data, - no_user_tx_activation_block: false, - satin_activation_block: false, + parent_timestamp: None, block_limits, } } - /// Marks this block one that admits only deposit transactions. - pub const fn with_no_user_tx_activation_block(mut self, activation_block: bool) -> Self { - self.no_user_tx_activation_block = activation_block; - self - } - - /// Marks this block the one in which Satin activates. - pub const fn with_satin_activation_block(mut self, activation_block: bool) -> Self { - self.satin_activation_block = activation_block; + /// Sets the parent block's timestamp, from which the executor works out whether a fork + /// activates in this block. + pub const fn with_parent_timestamp(mut self, parent_timestamp: u64) -> Self { + self.parent_timestamp = Some(parent_timestamp); self } } @@ -381,6 +372,32 @@ where &self.protocol_limits } + /// Whether this block admits only deposit transactions because a fork activates in it: a + /// fork of the schedule is active at the block's timestamp and not at its parent's. + /// + /// `false` when the context carries no parent timestamp. + pub fn admits_only_deposits(&self) -> bool { + self.ctx + .parent_timestamp + .is_some_and(|parent| self.spec.admits_only_deposits(parent, self.block_timestamp())) + } + + /// Whether Satin activates in this block, which makes the pre-block step check the system + /// contracts and the EIP-7997 factory. + /// + /// The two answers differ: an Optimism fork at or after Jovian also makes a block + /// deposit-only. `false` when the context carries no parent timestamp. + pub fn is_satin_activation_block(&self) -> bool { + self.ctx.parent_timestamp.is_some_and(|parent| { + self.spec.is_satin_activation_block(parent, self.block_timestamp()) + }) + } + + /// The block's own timestamp, from its environment. + fn block_timestamp(&self) -> u64 { + self.evm.ctx().block().timestamp().saturating_to() + } + /// Holds this block to `limits` in place of the spec's: a counterfactual of a tool's or a /// test's, which a node executing the chain never runs. /// @@ -616,11 +633,11 @@ where /// 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 - /// the code Satin expects, and its account is committed as a read-only entry; any other block - /// reads none of them. Satin deploys and upgrades nothing: a chain reaches it through the - /// legacy forks, which leave the six system contracts at the versions Satin runs, and the - /// EIP-7997 factory is OP's predeploy. + /// (see [`MegaBlockExecutor::is_satin_activation_block`]): each of the seven predeploys must + /// hold the code Satin expects, and its account is committed as a read-only entry; any + /// other block reads none of them. Satin deploys and upgrades nothing: a chain reaches it + /// through the legacy forks, which leave the six system contracts at the versions Satin + /// runs, and the EIP-7997 factory is OP's predeploy. /// /// The registry's role changes come after. Its pending slots are read and committed as a /// read-only state whatever they say, and when a change is due in this block the @@ -655,7 +672,7 @@ where // The EIP-2935 / EIP-4788 calls above do not depend on these predeploys: they target // their own contracts, not the MegaETH system addresses or the factory. - if self.ctx.satin_activation_block { + if self.is_satin_activation_block() { for spec in system_contract_specs() { let state = check_system_contract(self.evm.db_mut(), &spec).map_err( @@ -899,7 +916,7 @@ where // A block that activates a fork carries the chain's own transactions only, so a user // transaction in it is refused before anything runs. - if self.ctx.no_user_tx_activation_block && !is_deposit { + if self.admits_only_deposits() && !is_deposit { return Err(MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock.into()); } diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs index d3ddf5e54..7c56207e7 100644 --- a/crates/mega-evm/tests/block/activation.rs +++ b/crates/mega-evm/tests/block/activation.rs @@ -1,11 +1,11 @@ //! The activation-block rule as a node applies it. //! -//! Block execution does not work out whether a block admits only deposits: it is told, through -//! [`MegaBlockExecutionCtx::no_user_tx_activation_block`]. A node works it out from its schedule -//! and the parent block's timestamp ([`MegaHardforks::admits_only_deposits`]) for every block it -//! builds or validates. The tests here build each block's context that way, from a schedule, and -//! run the block: a user transaction is refused exactly in the blocks the rule names, and a -//! deposit runs in every block. +//! Block execution works out for itself whether a block admits only deposits and whether it is +//! Satin's activation block, from its chain schedule, the block's own timestamp and the parent +//! block's timestamp ([`MegaBlockExecutionCtx::with_parent_timestamp`]), which is all a node +//! supplies. The tests here build each block's context from the parent's timestamp alone and run +//! the block: a user transaction is refused exactly in the blocks the rule names, and a deposit +//! runs in every block. use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; use alloy_hardforks::{EthereumHardfork, ForkCondition}; @@ -13,7 +13,7 @@ use alloy_op_hardforks::OpHardfork; use alloy_primitives::{Bytes, U256}; use mega_evm::{ system::SYSTEM_CONTRACT_COUNT, test_utils::CommittedStates, BlockLimits, MegaBlockExecutionCtx, - MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, MegaHardforks, + MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, }; use crate::common::{ @@ -32,16 +32,11 @@ fn schedule(satin: u64) -> MegaHardforkConfig { MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(satin)) } -/// The context of the block at `timestamp`, whose parent is at `parent_timestamp`, as a node -/// builds it: both switches come from the schedule and the parent's timestamp. -fn node_ctx( - spec: &MegaHardforkConfig, - parent_timestamp: u64, - timestamp: u64, -) -> MegaBlockExecutionCtx { - block_ctx(BlockLimits::no_limits()) - .with_no_user_tx_activation_block(spec.admits_only_deposits(parent_timestamp, timestamp)) - .with_satin_activation_block(spec.is_satin_activation_block(parent_timestamp, timestamp)) +/// The context of a block whose parent is at `parent_timestamp`. Nothing else is said: the +/// executor works out from its schedule and the block's own timestamp whether a fork activates +/// in the block. +fn node_ctx(parent_timestamp: u64) -> MegaBlockExecutionCtx { + block_ctx(BlockLimits::no_limits()).with_parent_timestamp(parent_timestamp) } /// Whether `error` is the activation-block refusal. @@ -66,7 +61,7 @@ fn refuses_a_user_transaction( ) -> bool { let mut env = common::evm_env(); env.block_env.timestamp = U256::from(timestamp); - let ctx = node_ctx(&spec, parent_timestamp, timestamp); + let ctx = node_ctx(parent_timestamp); let mut state = common::state(); let mut executor = executor_with_env_and_spec(&mut state, ctx, env, spec); executor.apply_pre_execution_changes().unwrap_or_else(|e| panic!("{name}: starts: {e}")); @@ -191,7 +186,7 @@ fn test_the_activation_rule_follows_the_optimism_fork_order() { fn predeploys_checked(spec: MegaHardforkConfig, parent_timestamp: u64, timestamp: u64) -> usize { let mut env = common::evm_env(); env.block_env.timestamp = U256::from(timestamp); - let ctx = node_ctx(&spec, parent_timestamp, timestamp); + let ctx = node_ctx(parent_timestamp); let mut state = common::state(); let committed = CommittedStates::install(&mut state); let mut executor = executor_with_env_and_spec(&mut state, ctx, env, spec); @@ -227,3 +222,35 @@ fn test_a_node_context_checks_the_predeploys_where_satin_activates() { assert_eq!(predeploys_checked(spec, parent, timestamp), expected, "{name}"); } } + +/// [S1] [S18] A context that names no parent timestamp is a block with no parent to compare +/// against, such as a genesis block: neither rule applies to it, however the schedule places the +/// block's own timestamp. The same block with the parent named is the activation block, so the +/// absence is the context's own answer and not an effect of the schedule. +/// +/// Expected values: independent (the schedule's own timestamps and the documented default). +#[test] +fn test_an_absent_parent_timestamp_applies_neither_activation_rule() { + let at = ACTIVATION; + let mut env = common::evm_env(); + env.block_env.timestamp = U256::from(at); + let run = |ctx: MegaBlockExecutionCtx| { + let mut state = common::state(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env_and_spec(&mut state, ctx, env.clone(), schedule(at)); + let (only_deposits, satin) = + (executor.admits_only_deposits(), executor.is_satin_activation_block()); + executor.apply_pre_execution_changes().expect("the block starts"); + let checked = committed.states().iter().filter(|s| common::is_predeploy_check(s)).count(); + (only_deposits, satin, checked) + }; + + let absent = block_ctx(BlockLimits::no_limits()); + assert_eq!(absent.parent_timestamp, None, "a context starts with no parent timestamp"); + assert_eq!(run(absent), (false, false, 0), "no parent: neither rule"); + assert_eq!( + run(node_ctx(at - 1)), + (true, true, SYSTEM_CONTRACT_COUNT), + "the same block with its parent named is the activation block" + ); +} diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index f4358c7a2..b924c380d 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -18,8 +18,8 @@ use mega_evm::{ }, test_utils::{BytecodeBuilder, MemoryDatabase, SequencerRegistryRoles}, BlockLimits, EmptyExternalEnv, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, - MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, - MegaTxEnvelope, ProtocolLimits, + MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardfork, MegaHardforkConfig, + MegaSpecId, MegaTxEnvelope, ProtocolLimits, }; use op_alloy_consensus::TxDeposit; use revm::{ @@ -117,6 +117,21 @@ pub(crate) fn chain_spec() -> MegaHardforkConfig { MegaHardforkConfig::default().with_all_activated() } +/// A schedule in which Satin activates at [`BLOCK_TIMESTAMP`], the timestamp of the block +/// [`evm_env`] describes, so that block is Satin's activation block when its context names a +/// parent before it ([`activation_ctx`]). +pub(crate) fn activation_spec() -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(BLOCK_TIMESTAMP)) +} + +/// The context of the block [`evm_env`] describes as Satin's activation block under +/// [`activation_spec`]: its parent came one second before the activation, so the block admits +/// only deposits and checks the predeploys. +pub(crate) fn activation_ctx() -> MegaBlockExecutionCtx { + unlimited_ctx().with_parent_timestamp(BLOCK_TIMESTAMP - 1) +} + /// The loosest limits a block could be held to while a read of volatile data still detains: /// every limit unlimited, and gas detention's caps one below the most compute a transaction can /// spend, which no transaction of a block this size reaches. For a test that holds a block to diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 1a893f0f4..4675448f2 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -22,13 +22,10 @@ use revm::{ context::result::ExecutionResult, database::State, primitives::KECCAK_EMPTY, state::EvmState, }; -use crate::common::{self, executor, named_accounts, recovered, tx, unlimited_ctx}; - -/// The context of the block in which Satin activates, as a node sets it from the schedule and -/// the parent's timestamp: deposit-only, and the check of the predeploys. -fn activation_ctx() -> MegaBlockExecutionCtx { - unlimited_ctx().with_no_user_tx_activation_block(true).with_satin_activation_block(true) -} +use crate::common::{ + self, activation_ctx, activation_spec, executor_with_spec, named_accounts, recovered, tx, + unlimited_ctx, +}; /// The states the pre-block steps of a block over `state` held to `ctx` committed, in order, as a /// commit hook on `state` receives them. @@ -37,7 +34,7 @@ fn start( ctx: MegaBlockExecutionCtx, ) -> Result, BlockExecutionError> { let committed = CommittedStates::install(state); - let mut executor = executor(state, ctx); + let mut executor = executor_with_spec(state, ctx, activation_spec()); executor.apply_pre_execution_changes()?; assert_eq!(executor.gas().execution, 0); assert_eq!(executor.gas().state, 0); @@ -122,7 +119,7 @@ fn test_no_other_block_reads_a_predeploy() { mega_evm::MegaBlockExecutor::new( evm, ctx, - common::chain_spec(), + common::activation_spec(), alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), ) .apply_pre_execution_changes() @@ -138,7 +135,7 @@ fn test_no_other_block_reads_a_predeploy() { fn refused(db: MemoryDatabase, at: Address) -> MegaBlockExecutionError { let mut state = State::builder().with_database(db).build(); let committed = CommittedStates::install(&mut state); - let mut executor = executor(&mut state, activation_ctx()); + let mut executor = executor_with_spec(&mut state, activation_ctx(), activation_spec()); let error = executor.apply_pre_execution_changes().expect_err("the block is refused"); let delivered = named_accounts(&committed.states()); let position = system_contract_specs().iter().position(|spec| spec.address == at).unwrap(); @@ -237,7 +234,7 @@ fn test_an_activation_block_without_the_expected_code_is_refused() { #[test] fn test_a_create2_round_trip_through_the_factory() { let mut state = common::state(); - let mut executor = executor(&mut state, unlimited_ctx()); + let mut executor = common::executor(&mut state, unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); let salt = B256::repeat_byte(0x11); diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index fcadeae17..3a4521165 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -18,8 +18,8 @@ use revm::{ }; use crate::common::{ - self, deposit_tx, empty_call_gas, executor, system_tx, unlimited_ctx, user_tx, TestExecutor, - BLOCK_GAS_LIMIT, BLOCK_NUMBER, + self, deposit_tx, empty_call_gas, executor, executor_with_spec, system_tx, unlimited_ctx, + user_tx, TestExecutor, BLOCK_GAS_LIMIT, BLOCK_NUMBER, }; /// The word the L1 block contract holds at its scalars slot: the data-availability footprint @@ -90,7 +90,8 @@ fn operator_fee_paid(executor: TestExecutor<'_>) -> U256 { #[test] fn test_activation_block_rejects_a_mega_system_transaction() { let mut state = common::state(); - let mut executor = executor(&mut state, unlimited_ctx().with_no_user_tx_activation_block(true)); + let mut executor = + executor_with_spec(&mut state, common::activation_ctx(), common::activation_spec()); executor.apply_pre_execution_changes().expect("the block starts"); let err = executor diff --git a/crates/mega-evm/tests/block/sequences.rs b/crates/mega-evm/tests/block/sequences.rs index 96252e500..58c53d38b 100644 --- a/crates/mega-evm/tests/block/sequences.rs +++ b/crates/mega-evm/tests/block/sequences.rs @@ -11,8 +11,8 @@ use mega_evm::{test_utils::rex6_predeploys, BlockLimits, MegaBlockExecutionCtx, use revm::{database::State, Database}; use crate::common::{ - self, deposit_tx, empty_call_gas, executor, executor_with_env, unlimited_ctx, user_tx, - BLOCK_NUMBER, CALLER, + self, deposit_tx, empty_call_gas, executor_with_env, executor_with_spec, unlimited_ctx, + user_tx, BLOCK_NUMBER, CALLER, }; /// The seven predeploys are as the state held them before the blocks: the code and the nonce. @@ -104,10 +104,8 @@ fn next_block_env() -> EvmEnv { fn test_the_block_after_an_activation_block_packs_a_user_transaction() { let mut state = common::state(); let nonce = { - let ctx = unlimited_ctx() - .with_no_user_tx_activation_block(true) - .with_satin_activation_block(true); - let mut executor = executor(&mut state, ctx); + let mut executor = + executor_with_spec(&mut state, common::activation_ctx(), common::activation_spec()); executor.apply_pre_execution_changes().expect("the activation block starts"); executor .execute_transaction(&deposit_tx(Bytes::new(), empty_call_gas())) diff --git a/crates/mega-evm/tests/block/witness/predeploys.rs b/crates/mega-evm/tests/block/witness/predeploys.rs index d56fb77cc..133ab19a2 100644 --- a/crates/mega-evm/tests/block/witness/predeploys.rs +++ b/crates/mega-evm/tests/block/witness/predeploys.rs @@ -71,21 +71,17 @@ fn test_an_activation_block_replays() { let mut db = common::database(); db.set_account_code(CONTRACT, slot_writer()); let activation = || { - Case::new("activation block", db.clone()) - .ctx( - common::unlimited_ctx() - .with_no_user_tx_activation_block(true) - .with_satin_activation_block(true), - ) - .tx(deposit( - CALLER, - alloy_primitives::TxKind::Call(CONTRACT), - 0, - U256::ZERO, - slot(1), - write_gas(), - )) - .tx(call(0, CONTRACT, slot(2), write_gas())) + let mut case = Case::new("activation block", db.clone()).ctx(common::activation_ctx()); + case.spec = common::activation_spec(); + case.tx(deposit( + CALLER, + alloy_primitives::TxKind::Call(CONTRACT), + 0, + U256::ZERO, + slot(1), + write_gas(), + )) + .tx(call(0, CONTRACT, slot(2), write_gas())) }; let replay = activation().run(); let run = &replay.recorded; diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs index 2ab2410d1..561b8f85e 100644 --- a/crates/mega-state-test/src/blockchain/chain.rs +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -52,7 +52,7 @@ use mega_evm::{ SharedWitnessRecord, }, BlockLimits, EmptyExternalEnv, ExternalEnvFactory, ExternalEnvTypes, MegaBlockExecutionCtx, - MegaBlockExecutor, MegaEvm, MegaHardforkConfig, MegaHardforks, ProtocolLimits, + MegaBlockExecutor, MegaEvm, MegaHardforkConfig, ProtocolLimits, }; use super::fixture::DecodedBlock; @@ -434,17 +434,13 @@ impl Chain { E: ExternalEnvTypes, { let header = &block.header; - let only_deposits = self.spec.admits_only_deposits(self.head_timestamp, header.timestamp); - let activates_satin = - self.spec.is_satin_activation_block(self.head_timestamp, header.timestamp); let ctx = MegaBlockExecutionCtx::new( header.parent_hash, header.parent_beacon_block_root, header.extra_data.clone(), BlockLimits::no_limits(), ) - .with_no_user_tx_activation_block(only_deposits) - .with_satin_activation_block(activates_satin); + .with_parent_timestamp(self.head_timestamp); let mut executor = MegaBlockExecutor::new(evm, ctx, self.spec.clone(), OpAlloyReceiptBuilder::default()) .with_protocol_limits(limits()); @@ -477,6 +473,8 @@ fn refusal(error: BlockExecutionError) -> Refusal { #[cfg(test)] mod tests { + use mega_evm::MegaHardforks; + use super::*; /// The removal list names every predeploy the pre-state holds and the three fee vaults, each From 484b3059aad48d987901b56e99df69d06e76c9f4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:39:51 +0800 Subject: [PATCH 007/190] docs: the executor derives the activation-block rules from the parent timestamp --- .claude/skills/satin-review/SKILL.md | 4 ++-- AGENTS.md | 4 ++-- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/system/AGENTS.md | 2 +- docs/mega-evme/commands/replay.md | 2 +- docs/spec/upgrades/satin.md | 14 ++++++++------ 6 files changed, 15 insertions(+), 13 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 61d685c74..90e6d3542 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -310,7 +310,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **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. + - The activation-block rules are derived by the executor (`admits_only_deposits`, `is_satin_activation_block`) from the schedule, the block's timestamp and `MegaBlockExecutionCtx::parent_timestamp`; an absent parent timestamp applies neither. - 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. - 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. @@ -335,7 +335,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. 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. + The block in which Satin activates (`MegaBlockExecutor::is_satin_activation_block`, derived from the schedule, the block's timestamp and the parent's) 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. diff --git a/AGENTS.md b/AGENTS.md index 8a60340d2..9ac443396 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,7 +141,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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`) | +| `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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`); `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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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`) | @@ -280,7 +280,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. The block in which Satin activates reads the seven in order, and each must hold exactly Satin's code, whatever its nonce, balance and storage (`check_system_contract`, `system/predeploys.rs`); anything else — no account, no code, an older version, other code — refuses the block with one error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and each read is a read-only pre-block state. - The node says which block that is (`MegaBlockExecutionCtx::satin_activation_block`, off by default), from its schedule and the parent's timestamp as it sets `no_user_tx_activation_block`; no other block reads the seven. + The executor works out which block that is (`MegaBlockExecutor::is_satin_activation_block`) from its schedule, the block's timestamp and the parent's, which the node supplies (`MegaBlockExecutionCtx::with_parent_timestamp`; with none, the block is no activation block); no other block reads the seven. A test or a tool that runs a Satin block on a state of its own puts them there in the shape Rex6 left them (`test_utils::rex6_predeploys`, `MemoryDatabase::rex6_predeploys`, `SequencerRegistryRoles`). Three of the six system contracts have interceptors (`system/`) — `MegaAccessControl` and `MegaLimitControl` answer, the Oracle's forwards a hint and lets its bytecode run, or answers a hint that would cross the data-size limit with the stop — and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless dispatch before interception. A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input; an unknown selector is not intercepted and runs the contract's own bytecode. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 29ff43c68..a70f0a241 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -59,7 +59,7 @@ The block context a node passes carries only building policy (`BlockLimits`): a 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 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. +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, in the block in which Satin activates — which the executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::with_parent_timestamp`) — 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`). A database that cannot serve one of those L1 reads fails the block before its first transaction, as an internal error, whatever the block holds. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index cf25b0016..5383f7894 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -73,6 +73,6 @@ The executor commits it on its own, in the order the steps run: a commit hook on - 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. -- Change how the activation block checks the predeploys: `block/executor.rs::apply_pre_execution_changes` iterates the spec list when `MegaBlockExecutionCtx::satin_activation_block` is set, commits each read as a state of its own, and refuses the block on the first unexpected code. +- Change how the activation block checks the predeploys: `block/executor.rs::apply_pre_execution_changes` iterates the spec list when `MegaBlockExecutor::is_satin_activation_block` holds, commits each read as a state of its own, and refuses the block on the first unexpected code. - Change when a role change is applied: `sequencer_registry.rs`, whose two pre-block helpers `block/executor.rs::apply_pre_execution_changes` calls after the predeploy check, in that order. - Change how the live system address is read: `sequencer_registry.rs::load_system_address`, which `MegaHandler::validate_env` calls, and `MegaHandler::validate_env_as`, which decides from the address whether the transaction is a system-address transaction; the answer lives on the context as the transaction's system-originated flag (`MegaContext::is_system_originated`). `sequencer_registry.rs::live_system_address` makes the same read off a database, for a pool. diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index cf7682795..918090af8 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -200,7 +200,7 @@ A block's inputs are the block with its transactions, the chain's receipts, and A read the trace does not cover (what only a pre-block system call reads, or a path a counterfactual takes that the chain did not) is read from the parent block over RPC. On Satin a block in which a fork activates admits only deposits, as the [Satin upgrade](../../spec/upgrades/satin.md#1-base-layer-optimism-karst-ethereum-osaka) states: Satin itself, or an Optimism fork at or after Jovian. -The replay works this out as a node does, from the schedule the block runs under and the parent block's timestamp, and tells block execution; every transaction of such a block but its deposits is reported `refused`. +The replay works this out as a node does, from the schedule the block runs under and the parent block's timestamp, and gives block execution the parent's timestamp, from which it decides; every transaction of such a block but its deposits is reported `refused`. A transaction replay works it out the same way, from the parent block it forks, and refuses a non-deposit transaction of such a block with an error. The parent's timestamp decides the answer only for a Satin block at which a fork its schedule activates after genesis is active; for such a block alone the replay fetches the parent's header over `--rpc` and keeps its timestamp in the cache. Every other block, a legacy one or one whose schedule activates every fork it runs at genesis as the Satin counterfactual's does, replays from what the cache holds and never asks for the parent. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 0218aad37..ef0ecfa04 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1504,12 +1504,14 @@ A node, a stateless validator and a replay tool must agree on everything below, A bucket or database read the node fails to make is not a validation failure, for a deposit either: the transaction gets no outcome; a failed bucket read, a database error the database declares fatal, or any database error on a read block execution makes around the transaction is an internal error of the node, while any other database error the transaction's execution meets makes the block invalid; a builder, which has no outcome to include for that transaction, may then leave a non-deposit transaction out, but cannot build a block that must hold the deposit while the read fails. The reference implementation keeps nothing that changes a later execution of a transaction that got no outcome: the transactions executed after it, and the same transaction executed again once the read succeeds, execute as they would on a fresh execution environment over the same state. - **Activation blocks.** - Block execution does not work out whether a block admits only deposits: it is told, and refuses a non-deposit transaction only when told so. - The chain's rule is therefore enforced by the nodes that derive and build the chain, not by the executor alone: MegaETH's op-node MUST enforce deposit-only activation blocks for Satin and for every later MegaETH fork, and a block builder MUST compute the flag from the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates. - A node works it out from its configuration and the parent block's timestamp — whether a MegaETH fork, Satin itself, or an Optimism fork at or after Jovian in the Optimism fork order, is active at the block's timestamp and not at the parent's (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)) — for every block it builds and every block it validates, and a stateless validator is given it beside the witness. - An execution that is not told runs the block as one that admits non-deposit transactions, and accepts one in an activation block, which makes the block invalid. - It is told separately whether Satin activates in the block (`MegaBlockExecutionCtx::satin_activation_block`, from `MegaHardforks::is_satin_activation_block` and the parent's timestamp), which has it check the predeploys (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)): the two flags differ, since an Optimism fork's activation block admits only deposits too. - An execution that is not told checks no predeploy, and runs on a state that may lack them. + Block execution works out for itself whether a block admits only deposits and whether Satin activates in it, from the chain configuration, the block's own timestamp and the parent block's timestamp. + Neither is an input a caller can omit or set: the caller supplies the parent block's timestamp, and nothing else. + A block admits only deposits when a MegaETH fork, Satin itself, or an Optimism fork at or after Jovian in the Optimism fork order, is active at the block's timestamp and not at the parent's (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)); a user transaction in such a block is refused before it runs. + A block builder and a validator MUST give block execution the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates, and a stateless validator is given the parent block's timestamp beside the witness. + A block with no parent timestamp, such as a genesis block, is one with no parent to compare against: block execution applies neither rule to it. + A block that has a parent and is executed without its timestamp therefore runs as one that admits non-deposit transactions, so an implementation MUST supply it for every block but the first. + Satin's activation block is told apart from the other deposit-only blocks, since an Optimism fork's activation block admits only deposits too: only Satin's makes the pre-block step check the predeploys (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). + A block that is not Satin's activation block checks no predeploy, and runs on a state that may lack them. - **The L1 block information.** Block execution reads the L1 block contract at the block's first non-deposit transaction other than a Mega System Transaction, after the block's L1 attributes deposit wrote it, unless the node handed it the information for this block beforehand, which it then prices with, the footprint gas scalar aside; a node that hands it over must hand over what that deposit writes, so that the block's transactions are priced as [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka) requires. - **The witness.** From a22611a6beec8838c23093c6e5c12a2d9c0da5bc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:40:01 +0800 Subject: [PATCH 008/190] feat(evm): a deposit and a Mega System Transaction ask the oracle service nothing --- crates/mega-evm/src/evm/context.rs | 70 ++++++- crates/mega-evm/src/evm/host.rs | 20 +- crates/mega-evm/src/external/oracle.rs | 5 + crates/mega-evm/tests/block/witness/oracle.rs | 112 ++++++++--- .../mega-evm/tests/system/oracle_storage.rs | 185 +++++++++++++++++- 5 files changed, 350 insertions(+), 42 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 551fa2c22..a1739447d 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -65,6 +65,9 @@ pub struct MegaContext, @@ -106,6 +109,7 @@ impl MegaContext { bucket_record: BucketRecord::default(), oracle_reads: OracleReadRecord::default(), system_call: false, + oracle_service: true, keyless_creation: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, @@ -464,6 +468,10 @@ impl MegaContext { pub(crate) fn on_new_tx(&mut self, system_transaction: bool) { self.prepare(system::originates_from_the_protocol(&self.inner.tx, system_transaction)); self.system_call = false; + // Decided before a system-address transaction is promoted to a deposit, so it is told + // apart by `system_transaction`, and any other deposit by its type. + self.oracle_service = + !system_transaction && self.inner.tx.tx_type() != DEPOSIT_TRANSACTION_TYPE; } /// Prepares the context for a system call. Every system-call entry point of @@ -475,20 +483,40 @@ impl MegaContext { pub(crate) fn on_new_system_call(&mut self) { self.prepare(true); self.system_call = true; + self.oracle_service = false; } /// Whether the running execution is a system call: the protocol's own call, such as a - /// pre-block call, rather than a transaction of the block. - /// - /// A system call is a function of the chain's state alone, so it never asks the oracle - /// service: the service's answers reach a stateless validator through the included - /// transactions' records, and a system call has none. Set when the call is prepared and + /// pre-block call, rather than a transaction of the block. Set when the call is prepared and /// cleared when the next transaction is, so it cannot outlive the call. #[inline] pub(crate) const fn is_system_call(&self) -> bool { self.system_call } + /// Whether the running execution asks the oracle service for the Oracle's storage: a + /// transaction that is neither a deposit nor a Mega System Transaction does. A system call, a + /// deposit and a Mega System Transaction do not: an Oracle read they make pushes the slot's + /// value on the chain, and records no answer. + /// + /// A node that replays a block runs no oracle service, so a value the service gives a read + /// must be on the chain before the transaction that read it, written by a Mega System + /// Transaction the block orders first; none of the three can have one before it. A system + /// call precedes the block's transactions and is a function of the state a stateless + /// validator is given. Every deposit of a block precedes its other transactions, and a deposit + /// cannot be left out of the block instead. A Mega System Transaction is the sequencer's write + /// of the values the service gave, so a value served to its own read would need another one + /// before it. The block in which Satin activates admits only deposits, so none of its reads + /// asks the service. + /// + /// Decided when the execution is prepared, from what the transaction is then: a system-address + /// transaction before the engine promotes it to a deposit, and any other deposit by its type. + /// It cannot outlive the execution: the next one decides again. + #[inline] + pub(crate) const fn asks_oracle_service(&self) -> bool { + self.oracle_service + } + /// 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 @@ -496,7 +524,7 @@ impl MegaContext { /// 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) const fn splits_system_call_gas(&self) -> bool { - !self.runs_neutral() && self.system_call + !self.runs_neutral() && self.is_system_call() } /// The part of its pools and of its EIP-8037 reservoir, in per cent, a caller keeps when it @@ -776,7 +804,7 @@ mod tests { use super::*; use crate::{limit::emits_transfer_logs, EthSpecId, SaltEnv, TestExternalEnvs}; use alloy_eips::eip4788::SYSTEM_ADDRESS; - use alloy_primitives::U256; + use alloy_primitives::{B256, U256}; use core::convert::Infallible; use revm::{context_interface::cfg::GasParams, database::EmptyDB}; @@ -1054,6 +1082,34 @@ mod tests { assert!(!ctx.is_system_call(), "nor is a system transaction, which the protocol sends"); } + /// Only a transaction that is neither a deposit nor a system-address transaction asks the + /// oracle service; a deposit, a system-address transaction, which the engine promotes to a + /// deposit after this decision, and a system call do not. The decision is each execution's + /// own: the next one decides again. + #[test] + fn test_only_a_transaction_that_is_no_deposit_asks_the_oracle_service() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + ctx.on_new_tx(false); + assert!(ctx.asks_oracle_service(), "an ordinary transaction asks"); + + ctx.on_new_tx(true); + assert!(!ctx.asks_oracle_service(), "a system-address transaction does not"); + + ctx.inner.tx.deposit.source_hash = B256::repeat_byte(0x22); + ctx.on_new_tx(false); + assert!(!ctx.asks_oracle_service(), "nor does a deposit"); + + ctx.inner.tx.deposit.source_hash = B256::ZERO; + ctx.on_new_tx(false); + assert!(ctx.asks_oracle_service(), "the deposit's decision does not outlive it"); + + ctx.on_new_system_call(); + assert!(!ctx.asks_oracle_service(), "nor does a system call"); + + ctx.on_new_tx(false); + assert!(ctx.asks_oracle_service(), "and the call's does not outlive it"); + } + /// 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] diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index b0e8ce209..1deb392ba 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -641,9 +641,10 @@ impl MegaContext { /// and it is in the transaction's state, which a stateless witness is built from, even when /// the environment's value was the one used. /// - /// A system call does not ask the environment, whatever it holds: its read answers the chain's - /// slot, so the call is a function of the state a stateless validator is given (see - /// [`MegaContext::is_system_call`]). + /// A system call, a deposit and a Mega System Transaction do not ask the environment, whatever + /// it holds: their reads answer the chain's slot, its present value, a write the Oracle's own + /// frame made earlier included, and are loaded, priced and marked as any other read (see + /// [`MegaContext::asks_oracle_service`]). /// /// A frame whose regular gas, the part detention withholds included, cannot pay the cold /// access reads nothing and asks nothing, as revm's own skipped cold load does. A detained @@ -653,7 +654,7 @@ impl MegaContext { /// It is a read of volatile data: it is refused while the frame's volatile-data access is off, /// and marked for gas detention, under the Oracle's cap, once it succeeded. /// - /// The read and the answer are recorded on the context for the transaction's outcome + /// A read that asks is recorded, with the answer, on the context for the transaction's outcome /// ([`OracleReadRecord`](crate::OracleReadRecord)): the answer is in no database, so a /// stateless validator is given the included transactions' reads in place of the service. fn oracle_sload( @@ -671,14 +672,15 @@ impl MegaContext { false, )? .data; - // A system call reads the chain: it asks the service nothing and records no answer, and - // the read is priced and loaded as any other. - let answer = if self.is_system_call() { - None - } else { + // A system call, a deposit and a Mega System Transaction read the chain: they ask the + // service nothing and record no answer, and the read is priced, loaded and marked as any + // other. + let answer = if self.asks_oracle_service() { let answer = self.external_envs().oracle_env.get_oracle_storage(key); self.oracle_reads.record(key, answer); answer + } else { + None }; self.detention.observe(VolatileDataAccess::ORACLE); Ok(StateLoad::new(answer.unwrap_or(loaded), true)) diff --git a/crates/mega-evm/src/external/oracle.rs b/crates/mega-evm/src/external/oracle.rs index f1c7505e0..7350af153 100644 --- a/crates/mega-evm/src/external/oracle.rs +++ b/crates/mega-evm/src/external/oracle.rs @@ -31,6 +31,11 @@ pub trait OracleEnv: Debug + Unpin { /// earlier in the transaction. The slot is loaded whatever the answer, so a node that replays /// a block without the service prices and witnesses it as the node that built the block did. /// + /// Only a transaction that is neither a deposit nor a Mega System Transaction asks. A system + /// call, a deposit and a Mega System Transaction never do, and their reads use the loaded + /// value: none of them can have a value the service gave written on the chain before it, as a + /// node that replays the block without the service needs. + /// /// A frame whose regular gas, the part gas detention withholds included, cannot pay the read's /// cold access, and a frame whose volatile-data access is switched off, read nothing and do not /// ask. A detained frame that holds the gas but may not spend it does ask, and the read's diff --git a/crates/mega-evm/tests/block/witness/oracle.rs b/crates/mega-evm/tests/block/witness/oracle.rs index e782230fc..717a2e45d 100644 --- a/crates/mega-evm/tests/block/witness/oracle.rs +++ b/crates/mega-evm/tests/block/witness/oracle.rs @@ -1,6 +1,8 @@ //! Oracle reads, hints and the high-precision timestamp through the harness. //! -//! An oracle read loads the chain's slot, then takes the service's answer over it. The chain's +//! An oracle read loads the chain's slot, then, in a transaction that is neither a deposit nor a +//! Mega System Transaction, takes the service's answer over it; a deposit, a Mega System +//! Transaction and a system call ask the service nothing and take the chain's slot. The chain's //! slot is in the record like any slot; the service's answer is not in any database, so a replay //! matches only when it is given the answer — the included transactions' own records, in block //! order — or when the chain holds it at the read, which is what a node must arrange for a @@ -71,10 +73,15 @@ fn get_slot_of(slot: U256) -> Bytes { } /// A system transaction writing `value` into `slot` of the Oracle: a legacy call from the live -/// system address to `setSlot`, which the engine promotes to a deposit. Its gas is regular room -/// on top of the account the engine creates for its caller and the history its body would pay. +/// system address to `setSlot`, which the engine promotes to a deposit. fn oracle_update(slot: U256, value: U256) -> super::harness::Tx { - let input = IOracle::setSlotCall { slot, value: B256::from(value) }.abi_encode(); + system_transaction(IOracle::setSlotCall { slot, value: B256::from(value) }.abi_encode().into()) +} + +/// The system address's first system transaction, calling the Oracle with `input`: a legacy call +/// from the live system address, which the engine promotes to a deposit. Its gas is regular room +/// on top of the account the engine creates for its caller and the history its body would pay. +fn system_transaction(input: Bytes) -> super::harness::Tx { let gas = 1_000_000 + common::new_account_state_gas() + common::body_history(input.len() as u64); legacy_from( @@ -82,7 +89,7 @@ fn oracle_update(slot: U256, value: U256) -> super::harness::Tx { 0, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, - input.into(), + input, gas, ) } @@ -147,14 +154,14 @@ fn test_an_unanswered_oracle_read_replays() { assert_eq!(replay.recorded.record.oracle_reads, vec![OracleRead { slot: SLOT, answer: None }]); } -/// A deposit that failed keeps on its outcome the oracle reads its frames made: the failure takes -/// back everything but the sender's nonce bump and mint, not what the service answered, and a -/// validator re-executing the deposit makes the same reads. A deposit into a contract that reads -/// [`SLOT`] through the Oracle and then halts is included as a failed deposit that recorded the -/// read and its answer; the chain's slot is a key, and the channel replay is answered exactly -/// from the record. +/// A deposit asks the oracle service nothing, one that fails included: a deposit into a contract +/// that reads [`SLOT`] through the Oracle and then halts is included as a failed deposit that +/// recorded no read, and the service never saw one. The failure takes back everything but the +/// sender's nonce bump and mint, not what the deposit loaded: the chain's slot is a key, and a +/// validator re-executing the deposit makes the same read of it, served nothing, with a service +/// or without one. #[test] -fn test_a_failed_deposits_oracle_read_is_recorded_and_replayed() { +fn test_a_failed_deposits_oracle_read_asks_nothing_and_replays_without_a_service() { let depositor = address!("0x4000000000000000000000000000000000000009"); let read = get_slot(); let read_then_halt = BytecodeBuilder::default() @@ -170,17 +177,19 @@ fn test_a_failed_deposits_oracle_read_is_recorded_and_replayed() { SLOT, STATE_VALUE, ); - let replay = Case::new("a failed deposit that read the oracle", db) - .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) - .tx(deposit( - depositor, - TxKind::Call(CONTRACT), - 1_000_000_000, - U256::ZERO, - Bytes::new(), - 1_000_000 + common::new_account_state_gas(), - )) - .run(); + let case = || { + Case::new("a failed deposit that read the oracle", db.clone()) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(deposit( + depositor, + TxKind::Call(CONTRACT), + 1_000_000_000, + U256::ZERO, + Bytes::new(), + 1_000_000 + common::new_account_state_gas(), + )) + }; + let replay = case().run(); let run = &replay.recorded; assert!( matches!( @@ -190,9 +199,62 @@ fn test_a_failed_deposits_oracle_read_is_recorded_and_replayed() { "{:?}", run.tx(0).result ); - assert_eq!(run.tx(0).oracle_reads, vec![SLOT_READ], "the read is on the failed deposit"); + assert!(run.tx(0).oracle_reads.is_empty(), "the failed deposit recorded no read"); + assert!(run.executed_oracle_reads.is_empty(), "the service saw none"); assert!(run.keys.slots.contains(&(ORACLE_CONTRACT_ADDRESS, SLOT)), "the chain's slot is a key"); - assert!(replay.channel.oracle_replayed_exactly, "the replay was answered from the record"); + assert!(replay.channel.oracle_replayed_exactly, "the replay was served nothing"); + + let without = case().replay_channels(run, Oracle::Absent); + assert_same_run("a failed deposit's oracle read, no service", run, &without); +} + +/// A deposit and a Mega System Transaction ask the oracle service nothing: each reads [`SLOT`] +/// through the Oracle and takes the chain's value, over the one the service holds, and records +/// no read, so the block's only recorded answer is the user transaction's after them. A validator +/// given that record answers the user's read alone: were the deposit or the system transaction +/// asked, the first would take the user's answer and the user's read would find none. Without a +/// service the two take the chain's value as they did, and only the user's read comes out +/// differently. +#[test] +fn test_a_deposit_and_a_system_transaction_leave_the_recorded_answers_to_the_users() { + let depositor = address!("0x4000000000000000000000000000000000000009"); + let case = || { + Case::new( + "a deposit's, a system transaction's and a user's oracle reads", + db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE), + ) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(deposit( + depositor, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + 1_000_000_000, + U256::ZERO, + get_slot(), + gas(36) + common::new_account_state_gas(), + )) + .tx(system_transaction(get_slot())) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))) + }; + let replay = case().run(); + let run = &replay.recorded; + for index in 0..3 { + assert!(run.tx(index).result.is_success(), "{index}: {:?}", run.tx(index).result); + } + assert_eq!(returned(run, 0), STATE_VALUE, "the deposit took the chain's value"); + assert_eq!(returned(run, 1), STATE_VALUE, "so did the system transaction"); + assert_eq!(returned(run, 2), SERVICE_VALUE, "the user's transaction was answered"); + assert!(run.tx(0).oracle_reads.is_empty(), "the deposit recorded no read"); + assert!(run.tx(1).oracle_reads.is_empty(), "nor did the system transaction"); + assert_eq!(run.tx(2).oracle_reads, vec![SLOT_READ]); + assert_eq!(run.executed_oracle_reads, vec![SLOT_READ], "the only read the service saw"); + assert_eq!(run.included_oracle_reads(), vec![SLOT_READ]); + assert!(replay.channel.oracle_replayed_exactly, "the user's answer went to the user's read"); + + let without = case().replay_channels(run, Oracle::Absent); + assert_eq!(returned(&without, 0), STATE_VALUE); + assert_eq!(returned(&without, 1), STATE_VALUE); + assert_eq!(returned(&without, 2), STATE_VALUE, "the chain's value stands in for the user's"); + assert_differs("no service, the user's read", run, &without); } /// The answers a validator replays are the included transactions' own, in block order, not the diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs index 728123a12..4b9e0f4ae 100644 --- a/crates/mega-evm/tests/system/oracle_storage.rs +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -10,7 +10,9 @@ use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ constants::{ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, - system::{IOracle, ORACLE_CONTRACT_ADDRESS}, + system::{ + IOracle, MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, + }, test_utils::{ op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, ReplayingOracleEnv, }, @@ -829,3 +831,184 @@ fn test_reads_in_a_nested_oracle_frame_are_cold_and_ask() { assert_eq!(service.seen(), vec![Seen::Read(SLOT); 3]); } } + +/* ---------- which executions ask the service ---------- */ + +/// Code for the Oracle's own frame that reads [`SLOT`] once and returns the word it read and what +/// the read cost: the push of the slot, the `SLOAD` and the `GAS` after it. +fn read_and_price() -> Bytes { + BytecodeBuilder::default() + .append(GAS) + .push_u256(SLOT) + // [g0, value, g1]: the value at 0, g0 - g1 at 0x20. + .append_many([SLOAD, GAS, SWAP1, PUSH0, MSTORE, SWAP1, SUB]) + .push_number(0x20_u8) + .append(MSTORE) + .push_number(0x40_u8) + .append_many([PUSH0, RETURN]) + .build() +} + +/// What [`read_and_price`] reports for a read charged as a cold access. +fn cold_read() -> u64 { + let params = mega_evm::satin_gas_params(); + 3 + params.warm_storage_read_cost() + params.cold_storage_additional_cost() + 2 +} + +/// A database whose Oracle runs [`read_and_price`] on [`SLOT`] holding [`STATE_VALUE`], whose +/// [`CONTRACT`] calls the Oracle and returns what it answered, and whose registry names +/// [`MEGA_SYSTEM_ADDRESS`] the system address. +fn reading_db() -> MemoryDatabase { + db_with_state() + .account_code(ORACLE_CONTRACT_ADDRESS, read_and_price()) + .account_code(CONTRACT, calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &[], 0)) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) +} + +/// The word [`read_and_price`] read and what the read cost, out of a successful transaction to +/// the Oracle, or, `through_contract`, to [`CONTRACT`], which returns the call's status first. +fn read_of(run: &Run, through_contract: bool) -> (U256, u64) { + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let output = run.outcome.result.output().cloned().unwrap_or_default(); + let words = if through_contract { + let (status, data) = split_outcome(&output); + assert!(status, "the call to the Oracle failed"); + data.to_vec() + } else { + output.to_vec() + }; + (U256::from_be_slice(&words[..32]), U256::from_be_slice(&words[32..64]).to::()) +} + +/// `tx` as a deposit carrying `source_hash`: no fee. +fn as_deposit(mut tx: MegaTransaction, source_hash: B256) -> MegaTransaction { + tx.0.deposit.source_hash = source_hash; + tx.0.base.gas_price = 0; + tx +} + +/// A legacy call of the Oracle from `caller`, with the chain id the default configuration runs. +fn legacy_call_of_the_oracle(caller: Address) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + gas_limit: GAS_LIMIT, + chain_id: Some(1), + ..Default::default() + })) +} + +/// A deposit asks the oracle service nothing: an `SLOAD` in the Oracle's own frame pushes the +/// slot's value on the chain, over the value the service would give, and the deposit records no +/// answer. Every deposit of a block precedes the block's other transactions, so no Mega System +/// Transaction could put a value the service gave on the chain before the deposit reads it. +/// +/// The rule covers the deposit's every frame, a nested Oracle frame as much as its own call, and +/// every deposit: a user's, and one handed to the engine carrying the source hash the engine +/// stamps on a promoted Mega System Transaction. Only the question and the record go: the read +/// is loaded, priced and marked as the same read by a user's transaction is — the slot is in the +/// state, the read pays the cold access, and gas detention holds a user's deposit under the +/// Oracle's cap at the same limit. A deposit carrying the promotion's source hash is the +/// protocol's own, which is not detained, whatever it reads. +#[test] +fn test_a_deposit_asks_the_oracle_service_nothing() { + let user_deposit = B256::repeat_byte(0x22); + for (source_hash, through_contract) in + [(user_deposit, false), (user_deposit, true), (MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, false)] + { + let detained = source_hash == user_deposit; + let case = format!("source hash {source_hash}, through a contract: {through_contract}"); + let to = if through_contract { CONTRACT } else { ORACLE_CONTRACT_ADDRESS }; + let service = Service::holding(SLOT, SERVICE_VALUE); + let deposit = + run(reading_db(), &service, as_deposit(call_tx(to, [], U256::ZERO), source_hash)); + + assert_eq!( + read_of(&deposit, through_contract), + (STATE_VALUE, cold_read()), + "{case}: the chain's value, priced cold" + ); + assert!(service.seen().is_empty(), "{case}: the service was not asked"); + assert!(deposit.outcome.oracle_reads.is_empty(), "{case}: and no answer is recorded"); + assert!(deposit.evm_reads.is_empty(), "{case}"); + let slot = &deposit.outcome.state[&ORACLE_CONTRACT_ADDRESS].storage[&SLOT]; + assert_eq!(slot.original_value, STATE_VALUE, "{case}: the slot was loaded"); + + // The same read by a user's transaction, which the service answers. + let served = Service::holding(SLOT, SERVICE_VALUE); + let user = run(reading_db(), &served, call_tx(to, [], U256::ZERO)); + assert_eq!(read_of(&user, through_contract), (SERVICE_VALUE, cold_read()), "{case}"); + assert_eq!(user.accessed, VolatileDataAccess::ORACLE, "{case}: the user's read is marked"); + if detained { + assert_eq!((deposit.accessed, deposit.limit), (user.accessed, user.limit), "{case}"); + } else { + assert_eq!((deposit.accessed, deposit.limit), (VolatileDataAccess::empty(), None)); + } + } +} + +/// A Mega System Transaction asks the oracle service nothing: it is the sequencer's write of the +/// values the service gave, and a value served to its own read would need another one before it. +/// The engine promotes the legacy transaction the sequencer sends to a deposit; its read in the +/// Oracle's own frame pushes the slot's value on the chain, is priced as a cold access and loads +/// the slot, and no answer is recorded. +#[test] +fn test_a_mega_system_transaction_asks_the_oracle_service_nothing() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let run = run(reading_db(), &service, legacy_call_of_the_oracle(MEGA_SYSTEM_ADDRESS)); + + assert_eq!(read_of(&run, false), (STATE_VALUE, cold_read()), "the chain's value, priced cold"); + assert!(service.seen().is_empty(), "the service was not asked"); + assert!(run.outcome.oracle_reads.is_empty(), "and no answer is recorded"); + assert!(run.evm_reads.is_empty()); + let slot = &run.outcome.state[&ORACLE_CONTRACT_ADDRESS].storage[&SLOT]; + assert_eq!(slot.original_value, STATE_VALUE, "the slot was loaded"); +} + +/// A transaction that is neither a deposit nor a Mega System Transaction is still answered by +/// the oracle service, and its answer recorded: a user's, and one the pre-block calls' caller +/// sends, which is the protocol's own for every other rule but not one of the two the service +/// must not answer. +#[test] +fn test_a_transaction_that_is_no_deposit_is_still_answered_by_the_oracle_service() { + for caller in [CALLER, alloy_eips::eip4788::SYSTEM_ADDRESS] { + let service = Service::holding(SLOT, SERVICE_VALUE); + let run = run(reading_db(), &service, legacy_call_of_the_oracle(caller)); + + assert_eq!(read_of(&run, false), (SERVICE_VALUE, cold_read()), "{caller}"); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)], "{caller}: the service was asked"); + let read = OracleRead { slot: SLOT, answer: Some(SERVICE_VALUE) }; + assert_eq!(run.outcome.oracle_reads, [read], "{caller}: and its answer recorded"); + assert_eq!(run.evm_reads, [read], "{caller}"); + } +} + +/// A system call asks the oracle service nothing: its read in the Oracle's own frame pushes the +/// slot's value on the chain, is priced as a cold access, and records no answer, so the call is +/// a function of the state a stateless validator is given. +#[test] +fn test_a_system_call_asks_the_oracle_service_nothing() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let envs: ExternalEnvs = + ExternalEnvs { salt_env: EmptyExternalEnv, oracle_env: service.clone() }; + let ctx = MegaContext::new_with_external_envs(reading_db(), MegaSpecId::SATIN, envs) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + let result = alloy_evm::Evm::transact_system_call( + &mut evm, + alloy_eips::eip4788::SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, + Bytes::new(), + ) + .expect("the system call runs"); + + assert!(result.result.is_success(), "{:?}", result.result); + let output = result.result.output().cloned().unwrap_or_default(); + let read = (U256::from_be_slice(&output[..32]), U256::from_be_slice(&output[32..64])); + assert_eq!(read, (STATE_VALUE, U256::from(cold_read())), "the chain's value, priced cold"); + assert!(service.seen().is_empty(), "the service was not asked"); + assert!(evm.oracle_reads().is_empty(), "and no answer is recorded"); + let slot = &result.state[&ORACLE_CONTRACT_ADDRESS].storage[&SLOT]; + assert_eq!(slot.original_value, STATE_VALUE, "the slot was loaded"); +} From dc84311a03e0afa07c66444857645060f14e7ef1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:40:01 +0800 Subject: [PATCH 009/190] docs: a deposit and a Mega System Transaction ask the oracle service nothing --- AGENTS.md | 4 ++-- docs/spec/upgrades/satin.md | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8a60340d2..a24c4474a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -294,8 +294,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A node that replays a block without the service must price and witness it as the node that built it did, and it cannot tell which source the building node read, so nothing may depend on the source: every such read is priced as a cold access, however often the slot was read, and the slot is loaded on both paths, so afterwards it is warm for the frame's `SSTORE` and it is in the transaction's state, which a stateless witness is built from. A frame whose regular gas, the part detention withholds included, cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either; a detained frame that holds the gas but may not spend it does ask, and the charge then stops that frame at the compute limit. It is a volatile read for detention, under the Oracle's cap, and a hint reaches the service synchronously as `sendHint` is called, so a read after a hint finds the service told. - A system call, a pre-block call among them, asks no service: its Oracle read answers the chain's slot and records nothing (`MegaContext::is_system_call`, set in `on_new_system_call` and cleared by the next transaction), so a chain whose EIP-2935 or EIP-4788 code reads the Oracle still replays from its witness. - 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 system call, a pre-block call among them, a deposit and a Mega System Transaction ask no service: their Oracle reads answer the chain's slot, are loaded, priced and marked as any other, and record nothing (`MegaContext::asks_oracle_service`, decided in `on_new_tx` — a system-address transaction by the verdict validation hands it, before its promotion, any other deposit by its type — and in `on_new_system_call`), because a value the service gives must be on the chain before its reader, written by a Mega System Transaction the block orders first, and none of the three can have one; so a chain whose EIP-2935 or EIP-4788 code reads the Oracle still replays from its witness, and the deposit-only block in which Satin activates asks the service nothing. + Every read by a transaction that asks 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: 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. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 0218aad37..49900109f 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -81,6 +81,7 @@ The changes, in the order this page records them: A fork activates in a block when it is active at the block's timestamp and not at the parent block's, as the chain configuration schedules it; a fork the configuration does not schedule never activates. The rule covers Jovian, Karst and every later Optimism fork the chain configuration schedules. A Mega System Transaction is a legacy transaction, so it is refused in such a block too, and the Satin activation block owes none: nothing writes the [Oracle](#16-oracle-storage-reads-and-hints) in it, because the only transactions the block admits are deposits, and a deposit from the system address is a failed deposit that runs no call (see [The Live System Address](#17-the-live-system-address)). + Nor does any Oracle read in that block ask the oracle service, since a deposit asks it nothing: every read pushes the slot's value on the chain. - Each non-deposit transaction's data-availability footprint — its compressed size times the footprint gas scalar held by the L1 block contract — MUST accumulate against the block's gas limit, and the block MUST report the sum as its blob gas used. A transaction whose footprint does not fit in what the block has left MUST NOT be included. With no scalar in state the scalar is zero, and the rule costs nothing. @@ -1143,11 +1144,18 @@ An out-of-gas step halts the call, consuming its regular gas. #### New behavior -- An `SLOAD` in the Oracle's own frame MUST load the slot from state, then ask the oracle service, and answer the service's value when it gives one and the loaded value otherwise. +- An `SLOAD` in the Oracle's own frame MUST load the slot from state, then, unless the read is made during a system call, a deposit or a Mega System Transaction, ask the oracle service, and answer the service's value when it gives one and the loaded value otherwise. The service's value MUST win over whatever the slot holds at the read, a value the Oracle's own frame wrote earlier in the transaction included; with no value from the service the read answers the slot's present value, that write included. - Every such read MUST be charged as a cold access (2,100 gas), however often the slot was read, and the slot MUST be loaded whichever source answers, so a later write finds it warm and a stateless witness carries it. - A frame whose regular gas, its withheld part included, cannot pay the cold access MUST read nothing and ask nothing; a refused read asks nothing. -- A system call MUST NOT ask the service at all: its read answers the chain's value (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). +- A system call, a deposit and a Mega System Transaction MUST NOT ask the service for a value: their reads answer the slot's value on the chain, its present value, a write made earlier in the same call or transaction included, are loaded, priced and marked as any Oracle read is, and record no answer. + Only a transaction that is neither a deposit nor a Mega System Transaction asks the service, and the rule holds for the whole of the call or transaction it covers. + A node that replays a block runs no service, so a value the service gives a read must be on the chain before the transaction that read it, written by a Mega System Transaction the block orders first, and none of the three can have one before it. + A system call precedes the block's transactions and is a function of the state a stateless validator is given (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). + Every deposit of a block precedes its other transactions, and a deposit cannot be left out of the block instead. + A Mega System Transaction is the sequencer's write of the values the service gave, so a value served to its own read would need another one before it. + This is the practice of the node Rex6 runs on, which opens its oracle service only around each user transaction it executes; the block in which Satin activates admits only deposits, so none of its reads asks the service. + A `sendHint` made in such a call or transaction is admitted, forwarded and counted as in any other. - A `sendHint` MUST reach the service synchronously, when it is called, and only when the call is forwarded gas, carries no value, and comes from a frame whose volatile-data access is on. A hint that fails any of those conditions is dropped and counts nothing; the call runs the Oracle's bytecode either way. The value condition is new. @@ -1229,7 +1237,7 @@ An out-of-gas step halts the call, consuming its regular gas. - **Oracle reads in a system call.** A system call MUST NOT ask the oracle service: an `SLOAD` in the Oracle's own frame during one reads the slot's value on the chain, which is loaded and priced as an Oracle read is (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), and records no answer. The pre-block calls run whatever code sits at the EIP-2935 and EIP-4788 addresses: on MegaETH's chains that is EIP-2935's and EIP-4788's own code, which reads no Oracle, and the rule keeps a system call a function of the state a stateless validator is given, which carries no service answer, whatever that code is. - The rule ends with the call: the transactions of the block are answered by the service as they are outside it. + The rule ends with the call: the transactions of the block are answered by the service as they are outside it, a deposit and a Mega System Transaction excepted, which ask it nothing either (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). - **Failure.** A pre-block call that does not succeed MUST make the block invalid, before its state is used. A database error the node's database declares fatal is an internal error of the node, not a verdict on the block; any other failure of a call — a non-fatal database error, another EVM error, an outcome that is not a success — makes the block invalid. @@ -1423,9 +1431,10 @@ The witness is defined by what the block's execution returns and exports, and a Block execution exports every hash `BLOCKHASH` was served, emptied when the block starts. It is not what a node's state cache holds, which may carry hashes an earlier block read. - **The oracle.** - An `SLOAD` in the Oracle's own frame loads the chain's slot, which is in the transaction's returned state and so in the witness, then takes the service's answer over it. + An `SLOAD` in the Oracle's own frame loads the chain's slot, which is in the transaction's returned state and so in the witness, then, in a transaction that is neither a deposit nor a Mega System Transaction, takes the service's answer over it. The answer is in no database. The engine records every read a transaction makes through the service, with the answer, in order, on the transaction's outcome; an answer can be none, where the service had no value and the slot's loaded value stood. + A deposit and a Mega System Transaction ask the service nothing and record no read: each of their reads takes the slot's value on the chain, which the witness carries, and a validator re-executing them is served nothing. A node MUST take the oracle reads of the transactions it includes from their outcomes, in block order, and nothing of a candidate it executed and dropped. A validator MUST do one of the following: - be given those records, and answer each read its own execution makes from them, in order; or From 7ca1114d39afe8f3526df973472c10fe12a189ed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:42:42 +0800 Subject: [PATCH 010/190] test(utils): build the single-entry state without into_iter --- crates/mega-evm/src/test_utils/database.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs index 376af8efa..254aafe84 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -420,7 +420,9 @@ mod tests { let mut account = touched(AccountInfo::default()); account.mark_created(); let mut db = MemoryDatabase::default(); - db.commit([(created, account)].into_iter().collect()); + let mut changes = EvmState::default(); + changes.insert(created, account); + db.commit(changes); assert!(db.basic(created).unwrap().is_some(), "a created account is not cleared"); } } From 4b51f929518bbda41bc6bc1ecd58eddc62c09dcc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:47:05 +0800 Subject: [PATCH 011/190] refactor(block): the parent timestamp is a required argument of the execution context --- AGENTS.md | 2 +- bin/mega-evme/src/block/satin.rs | 6 +-- bin/mega-evme/src/replay/cmd.rs | 4 +- crates/mega-evm/README.md | 4 +- crates/mega-evm/benches/block.rs | 1 + crates/mega-evm/src/block/executor.rs | 40 +++++++++---------- crates/mega-evm/tests/block/activation.rs | 14 +++++-- crates/mega-evm/tests/block/bucket_ids.rs | 1 + crates/mega-evm/tests/block/common.rs | 10 ++++- crates/mega-evm/tests/block/counters.rs | 1 + crates/mega-evm/tests/block/eips.rs | 13 ++++-- crates/mega-evm/tests/block/inspector.rs | 1 + crates/mega-evm/tests/block/salt.rs | 1 + .../tests/block/sequencer_registry.rs | 2 + crates/mega-evm/tests/block/sequences.rs | 1 + .../mega-evm/tests/block/witness/history.rs | 1 + crates/mega-evm/tests/fuzz/blocks.rs | 3 +- .../tests/satin/limit_matrix/block.rs | 2 +- .../mega-state-test/src/blockchain/chain.rs | 4 +- docs/spec/upgrades/satin.md | 2 +- 20 files changed, 69 insertions(+), 44 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9ac443396..b1d768a19 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -280,7 +280,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. The block in which Satin activates reads the seven in order, and each must hold exactly Satin's code, whatever its nonce, balance and storage (`check_system_contract`, `system/predeploys.rs`); anything else — no account, no code, an older version, other code — refuses the block with one error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and each read is a read-only pre-block state. - The executor works out which block that is (`MegaBlockExecutor::is_satin_activation_block`) from its schedule, the block's timestamp and the parent's, which the node supplies (`MegaBlockExecutionCtx::with_parent_timestamp`; with none, the block is no activation block); no other block reads the seven. + The executor works out which block that is (`MegaBlockExecutor::is_satin_activation_block`) from its schedule, the block's timestamp and the parent's, which the node passes to `MegaBlockExecutionCtx::new` (`None` for a block with no parent, which is no activation block); no other block reads the seven. A test or a tool that runs a Satin block on a state of its own puts them there in the shape Rex6 left them (`test_utils::rex6_predeploys`, `MemoryDatabase::rex6_predeploys`, `SequencerRegistryRoles`). Three of the six system contracts have interceptors (`system/`) — `MegaAccessControl` and `MegaLimitControl` answer, the Oracle's forwards a hint and lets its bytecode run, or answers a hint that would cross the data-size limit with the stop — and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless dispatch before interception. A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input; an unknown selector is not intercepted and runs the contract's own bytecode. diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index dd128f549..b3d07bcb5 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -72,15 +72,13 @@ pub(super) fn execute( // parent's timestamp. Without the timestamp it applies none, which is right only where no // fork activates in the block, so any other block is refused here. admits_only_deposits(&hardforks, header.number, parent_timestamp, header.timestamp)?; - let mut block_ctx = MegaBlockExecutionCtx::new( + let block_ctx = MegaBlockExecutionCtx::new( header.parent_hash, header.parent_beacon_block_root, header.extra_data.clone(), BlockLimits::default(), + parent_timestamp, ); - if let Some(parent_timestamp) = parent_timestamp { - block_ctx = block_ctx.with_parent_timestamp(parent_timestamp); - } let result = { let mut db = State::builder().with_database(SatinDb(state)).with_bundle_update().build(); diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index 719d51f34..d3ed7f1f4 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -451,8 +451,8 @@ impl Cmd { ctx.block.header.parent_beacon_block_root(), ctx.block.header.extra_data().clone(), BlockLimits::default(), - ) - .with_parent_timestamp(ctx.parent_block.header.timestamp()); + Some(ctx.parent_block.header.timestamp()), + ); let start = Instant::now(); // The tracer is attached only for `--trace`: otherwise preceding transactions would be diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index a70f0a241..72c0251e4 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -59,7 +59,7 @@ The block context a node passes carries only building policy (`BlockLimits`): a 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 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 executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::with_parent_timestamp`) — 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. +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, in the block in which Satin activates — which the executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`) — 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`). A database that cannot serve one of those L1 reads fails the block before its first transaction, as an internal error, whatever the block holds. @@ -197,7 +197,7 @@ use alloy_evm::block::{BlockExecutor as _, BlockExecutorFactory as _}; use mega_evm::{BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory}; let factory = MegaBlockExecutorFactory::new(receipt_builder, chain_spec, MegaEvmFactory::new()); -let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_block_root, extra_data, BlockLimits::no_limits()); +let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_block_root, extra_data, BlockLimits::no_limits(), Some(parent_timestamp)); let mut executor = factory.create_executor(evm, ctx); executor.apply_pre_execution_changes()?; diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 4e45afffa..6f40bbd4b 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -182,6 +182,7 @@ fn block_ctx() -> MegaBlockExecutionCtx { Some(PARENT_BEACON_ROOT), Bytes::new(), BlockLimits::default(), + None, ) } diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 39a2d305d..d2669565c 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -17,8 +17,8 @@ //! - **An activation block admits only deposits.** The executor works out whether a fork activates //! in the block from the chain's schedule ([`MegaHardforks::admits_only_deposits`]), the block's //! own timestamp and the parent's, which the caller supplies with -//! [`MegaBlockExecutionCtx::with_parent_timestamp`]. A user transaction in such a block is -//! refused before it executes. This mirrors alloy-op-evm's rule of the same name. +//! [`MegaBlockExecutionCtx::parent_timestamp`]. A user transaction in such a block is refused +//! before it executes. This mirrors alloy-op-evm's rule of the same name. //! - **The data-availability footprint is a block limit.** Each non-deposit transaction's footprint //! is its compressed size times the footprint gas scalar the L1 block contract holds, accumulated //! against the block's gas limit and reported as the block's blob gas used. With no scalar in @@ -141,7 +141,7 @@ use crate::{ /// It carries what the pre-block calls need (the parent hash and the parent beacon block root, as /// alloy-op-evm does), the block's own extra data, the parent block's timestamp and the /// builder's packing policy. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] pub struct MegaBlockExecutionCtx { /// The parent block's hash, which the EIP-2935 pre-block call records. pub parent_hash: B256, @@ -168,28 +168,19 @@ pub struct MegaBlockExecutionCtx { } impl MegaBlockExecutionCtx { - /// A context for a block with no known parent timestamp; supply it with - /// [`with_parent_timestamp`](Self::with_parent_timestamp). + /// A context for a block whose parent block is at `parent_timestamp`. + /// + /// `None` is a block with no parent to compare against, such as a genesis block: neither + /// activation-block rule applies to it. A block that has a parent must pass its timestamp, + /// since a block executed without it silently skips both rules. pub const fn new( parent_hash: B256, parent_beacon_block_root: Option, extra_data: Bytes, block_limits: BlockLimits, + parent_timestamp: Option, ) -> Self { - Self { - parent_hash, - parent_beacon_block_root, - extra_data, - parent_timestamp: None, - block_limits, - } - } - - /// Sets the parent block's timestamp, from which the executor works out whether a fork - /// activates in this block. - pub const fn with_parent_timestamp(mut self, parent_timestamp: u64) -> Self { - self.parent_timestamp = Some(parent_timestamp); - self + Self { parent_hash, parent_beacon_block_root, extra_data, parent_timestamp, block_limits } } } @@ -1054,7 +1045,13 @@ mod tests { .with_block(BlockEnv { gas_limit: 30_000_000, ..Default::default() }); let mut executor = MegaBlockExecutor::new( MegaEvm::new(ctx), - MegaBlockExecutionCtx::default(), + MegaBlockExecutionCtx::new( + B256::ZERO, + None, + Bytes::new(), + BlockLimits::default(), + None, + ), MegaHardforkConfig::default().with_all_activated(), alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), ); @@ -1096,7 +1093,7 @@ mod tests { let policy = BlockLimits::no_limits().with_block_txs_data_limit(u64::MAX); let executor = MegaBlockExecutor::new( MegaEvm::new(ctx), - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), policy), + MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), policy, None), MegaHardforkConfig::default().with_all_activated(), alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), ); @@ -1122,6 +1119,7 @@ mod tests { None, Bytes::new(), BlockLimits::no_limits().with_block_txs_data_limit(5), + None, ), MegaHardforkConfig::default().with_all_activated(), alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs index 7c56207e7..ff908c000 100644 --- a/crates/mega-evm/tests/block/activation.rs +++ b/crates/mega-evm/tests/block/activation.rs @@ -2,7 +2,7 @@ //! //! Block execution works out for itself whether a block admits only deposits and whether it is //! Satin's activation block, from its chain schedule, the block's own timestamp and the parent -//! block's timestamp ([`MegaBlockExecutionCtx::with_parent_timestamp`]), which is all a node +//! block's timestamp ([`MegaBlockExecutionCtx::new`]), which is all a node //! supplies. The tests here build each block's context from the parent's timestamp alone and run //! the block: a user transaction is refused exactly in the blocks the rule names, and a deposit //! runs in every block. @@ -10,7 +10,7 @@ use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; use alloy_hardforks::{EthereumHardfork, ForkCondition}; use alloy_op_hardforks::OpHardfork; -use alloy_primitives::{Bytes, U256}; +use alloy_primitives::{Bytes, B256, U256}; use mega_evm::{ system::SYSTEM_CONTRACT_COUNT, test_utils::CommittedStates, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, @@ -36,7 +36,13 @@ fn schedule(satin: u64) -> MegaHardforkConfig { /// executor works out from its schedule and the block's own timestamp whether a fork activates /// in the block. fn node_ctx(parent_timestamp: u64) -> MegaBlockExecutionCtx { - block_ctx(BlockLimits::no_limits()).with_parent_timestamp(parent_timestamp) + MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + Some(parent_timestamp), + ) } /// Whether `error` is the activation-block refusal. @@ -246,7 +252,7 @@ fn test_an_absent_parent_timestamp_applies_neither_activation_rule() { }; let absent = block_ctx(BlockLimits::no_limits()); - assert_eq!(absent.parent_timestamp, None, "a context starts with no parent timestamp"); + assert_eq!(absent.parent_timestamp, None, "the helper names no parent"); assert_eq!(run(absent), (false, false, 0), "no parent: neither rule"); assert_eq!( run(node_ctx(at - 1)), diff --git a/crates/mega-evm/tests/block/bucket_ids.rs b/crates/mega-evm/tests/block/bucket_ids.rs index 6e671a910..fdca164ca 100644 --- a/crates/mega-evm/tests/block/bucket_ids.rs +++ b/crates/mega-evm/tests/block/bucket_ids.rs @@ -177,6 +177,7 @@ fn test_the_pre_block_calls_and_a_system_transaction_add_no_bucket() { Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits(), + None, ); let mut executor = MegaBlockExecutor::new(evm, ctx, common::chain_spec(), OpAlloyReceiptBuilder::default()); diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index b924c380d..ddc54a912 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -129,7 +129,13 @@ pub(crate) fn activation_spec() -> MegaHardforkConfig { /// [`activation_spec`]: its parent came one second before the activation, so the block admits /// only deposits and checks the predeploys. pub(crate) fn activation_ctx() -> MegaBlockExecutionCtx { - unlimited_ctx().with_parent_timestamp(BLOCK_TIMESTAMP - 1) + MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + Some(BLOCK_TIMESTAMP - 1), + ) } /// The loosest limits a block could be held to while a read of volatile data still detains: @@ -153,7 +159,7 @@ pub(crate) const fn loosest_tx() -> EvmTxRuntimeLimits { /// Cancun is active, so the block carries a parent beacon block root; without one the EIP-4788 /// pre-block call refuses the block. pub(crate) fn block_ctx(policy: BlockLimits) -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), policy) + MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), policy, None) } /// The context of a block packed under no building policy, as a validator executes one. diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 3ccd8f89d..60f2818c4 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -352,6 +352,7 @@ fn test_the_pre_block_calls_count_towards_no_block_budget() { Some(root), Bytes::new(), mega_evm::BlockLimits::no_limits(), + None, ); let mut executor = executor(&mut state, ctx); executor.apply_pre_execution_changes().expect("the block starts"); diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 89a9cd9c3..e441069ef 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -81,12 +81,13 @@ fn ctx() -> MegaBlockExecutionCtx { Some(PARENT_BEACON_ROOT), Bytes::new(), BlockLimits::no_limits(), + None, ) } /// The context of a block that carries no parent beacon block root. fn ctx_without_beacon_root() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new(PARENT_HASH, None, Bytes::new(), BlockLimits::no_limits()) + MegaBlockExecutionCtx::new(PARENT_HASH, None, Bytes::new(), BlockLimits::no_limits(), None) } /// The environment of a block at `number`. @@ -237,8 +238,13 @@ fn test_the_pre_block_calls_are_held_to_no_limit() { #[test] fn test_the_pre_block_calls_count_towards_no_counter_or_budget() { let policy = BlockLimits::no_limits().with_block_txs_data_limit(1); - let ctx = - MegaBlockExecutionCtx::new(PARENT_HASH, Some(PARENT_BEACON_ROOT), Bytes::new(), policy); + let ctx = MegaBlockExecutionCtx::new( + PARENT_HASH, + Some(PARENT_BEACON_ROOT), + Bytes::new(), + policy, + None, + ); 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()); @@ -314,6 +320,7 @@ fn test_the_genesis_block_makes_no_pre_block_call() { Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits(), + None, ); assert_eq!( diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index f34dd1331..b8ce155bf 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -95,6 +95,7 @@ fn recording_ctx() -> MegaBlockExecutionCtx { Some(B256::repeat_byte(0xcd)), Bytes::new(), BlockLimits::no_limits(), + None, ) } diff --git a/crates/mega-evm/tests/block/salt.rs b/crates/mega-evm/tests/block/salt.rs index 03d9508fa..8df1c056a 100644 --- a/crates/mega-evm/tests/block/salt.rs +++ b/crates/mega-evm/tests/block/salt.rs @@ -84,6 +84,7 @@ fn ctx() -> MegaBlockExecutionCtx { Some(PARENT_BEACON_ROOT), Bytes::new(), BlockLimits::no_limits(), + None, ) } diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index a21e470ee..b1617982c 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -115,6 +115,7 @@ fn executor_on( Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits(), + None, ); MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } @@ -632,6 +633,7 @@ fn started_block_at(state: &mut State, number: u64) -> Executor< Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits(), + None, ); let mut executor = MegaBlockExecutor::new(evm, ctx, common::chain_spec(), OpAlloyReceiptBuilder::default()); diff --git a/crates/mega-evm/tests/block/sequences.rs b/crates/mega-evm/tests/block/sequences.rs index 58c53d38b..573574b7d 100644 --- a/crates/mega-evm/tests/block/sequences.rs +++ b/crates/mega-evm/tests/block/sequences.rs @@ -47,6 +47,7 @@ fn record_parent( Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits(), + None, ); let mut executor = executor_with_env(state, ctx, env); executor.apply_pre_execution_changes().expect("the block starts"); diff --git a/crates/mega-evm/tests/block/witness/history.rs b/crates/mega-evm/tests/block/witness/history.rs index 0e1874600..a186e9ef1 100644 --- a/crates/mega-evm/tests/block/witness/history.rs +++ b/crates/mega-evm/tests/block/witness/history.rs @@ -37,6 +37,7 @@ fn test_block_hash_reads_replay() { Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits(), + None, )) .tx(call(0, CONTRACT, Bytes::new(), common::empty_call_gas())) .run(); diff --git a/crates/mega-evm/tests/fuzz/blocks.rs b/crates/mega-evm/tests/fuzz/blocks.rs index 57605f97d..7d549826b 100644 --- a/crates/mega-evm/tests/fuzz/blocks.rs +++ b/crates/mega-evm/tests/fuzz/blocks.rs @@ -394,7 +394,8 @@ fn run_block(case: &BlockCase) -> Result (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 ctx = MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), policy, None); let mut executor = MegaBlockExecutor::new( evm, ctx, diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs index 561b8f85e..fcda7990e 100644 --- a/crates/mega-state-test/src/blockchain/chain.rs +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -439,8 +439,8 @@ impl Chain { header.parent_beacon_block_root, header.extra_data.clone(), BlockLimits::no_limits(), - ) - .with_parent_timestamp(self.head_timestamp); + Some(self.head_timestamp), + ); let mut executor = MegaBlockExecutor::new(evm, ctx, self.spec.clone(), OpAlloyReceiptBuilder::default()) .with_protocol_limits(limits()); diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index ef0ecfa04..39d4621c2 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1508,7 +1508,7 @@ A node, a stateless validator and a replay tool must agree on everything below, Neither is an input a caller can omit or set: the caller supplies the parent block's timestamp, and nothing else. A block admits only deposits when a MegaETH fork, Satin itself, or an Optimism fork at or after Jovian in the Optimism fork order, is active at the block's timestamp and not at the parent's (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)); a user transaction in such a block is refused before it runs. A block builder and a validator MUST give block execution the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates, and a stateless validator is given the parent block's timestamp beside the witness. - A block with no parent timestamp, such as a genesis block, is one with no parent to compare against: block execution applies neither rule to it. + A block with no parent, such as a genesis block, is executed with an explicit absence of the parent timestamp: block execution applies neither rule to it. A block that has a parent and is executed without its timestamp therefore runs as one that admits non-deposit transactions, so an implementation MUST supply it for every block but the first. Satin's activation block is told apart from the other deposit-only blocks, since an Optimism fork's activation block admits only deposits too: only Satin's makes the pre-block step check the predeploys (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). A block that is not Satin's activation block checks no predeploy, and runs on a state that may lack them. From fa0a73becd45850775d4e5f5254b347397e02f28 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 10:56:06 +0800 Subject: [PATCH 012/190] test(state-test): register SLOTNUM pushing zero as a deviation --- crates/mega-state-test/DEVIATIONS.md | 33 +++++++ crates/mega-state-test/src/deviations.rs | 117 ++++++++++++++++++++++- 2 files changed, 149 insertions(+), 1 deletion(-) diff --git a/crates/mega-state-test/DEVIATIONS.md b/crates/mega-state-test/DEVIATIONS.md index aff8790d1..d977fc4f6 100644 --- a/crates/mega-state-test/DEVIATIONS.md +++ b/crates/mega-state-test/DEVIATIONS.md @@ -138,3 +138,36 @@ Whether Satin takes EIP-8246 is a decision for its specification, not for this g - `tests/ported_static/stCreate2/test_create2_suicide.py::test_create2_suicide[fork_Amsterdam-state_test-d7]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x087df75fad91a65e75b9373ad835882429c431166f9a3e6d086206cd39e2f662` - `for_amsterdam/ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json` - `tests/ported_static/stInitCodeTest/test_transaction_create_suicide_in_initcode.py::test_transaction_create_suicide_in_initcode[fork_Amsterdam-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xf6456935a8fdccc4fa60c10233d27e602088fdfbce68c9db41363767cffd367d` + +## `slotnum-pushes-zero` + +12 failed entries of the pinned Amsterdam fixtures. + +**Rule.** +SLOTNUM pushes zero whatever slot number the block environment carries: the value is the engine's own and depends on no field the node supplies. + +**Reason.** +EIP-7843 has SLOTNUM push the slot number of the block, which a node supplies. +Satin fixes the value instead, so that a stateless validator needs no slot number as an input. +The fixtures set a non-zero slot number in the block environment and expect it on the stack, or in the state and the gas that follow from it, so each fixture that executes the opcode with a slot number other than zero fails on the state root. +The read stays a volatile read of the block environment, so the opcode's price and its marking are Amsterdam's. + +**Failures.** Each entry with its data, gas and value indices, how it fails and the hashes Satin produces; paths are relative to the release's `state_tests` directory. + +- `for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_call_contexts.json` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_CALL-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x9844550375d5580d1c236fdb59423d5f5c271c18440f4f7eb00d4ab1a289ee8e` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_CALLCODE-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xb227ac98fb5ebb4b89cc8e829a1fbd9271f38e92b9f97647e4dcfb9224c6730d` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_DELEGATECALL-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x026cf9c2e991acb1be1a28b072563a5bcd18f117291dc90f0a85e0f4ce3fe19a` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_STATICCALL-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x86c4b58c8b6c4e5354d9c7e0f7d73d4687085df933246408dd507107ed4f7cf4` +- `for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_initcode_create.json` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_initcode_create[fork_Amsterdam-state_test-opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x40d0b7ae59cf8b28c14aeb856399b90846fdf1e591043556df14c3d90349504f` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_initcode_create[fork_Amsterdam-state_test-opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x9da4f5c40a1b386fbd0ca103b74cccca0d8eb15cef887bea3e3aa17049523934` +- `for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_initcode_tx.json` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_initcode_tx[fork_Amsterdam-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xefee50e6818a814993fd8754c49822d9663aabd235e54b6a91ff8a02f143bec4` +- `for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_set_code.json` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_set_code[fork_Amsterdam-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x0f50f514d60dd84274327a597b7d8bf19a12c45b13e6771d9081f163b8c4811c` +- `for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_value.json` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_4096]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_large]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_max_u64]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77` + - `tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_one]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77` diff --git a/crates/mega-state-test/src/deviations.rs b/crates/mega-state-test/src/deviations.rs index 0310ba950..c3f90aa5e 100644 --- a/crates/mega-state-test/src/deviations.rs +++ b/crates/mega-state-test/src/deviations.rs @@ -187,7 +187,8 @@ impl fmt::Display for Entry { } /// Every registered deviation. -pub const DEVIATIONS: &[Deviation] = &[AMSTERDAM_OPCODES_ON_OSAKA, SELFDESTRUCT_BURNS_ON_OSAKA]; +pub const DEVIATIONS: &[Deviation] = + &[AMSTERDAM_OPCODES_ON_OSAKA, SELFDESTRUCT_BURNS_ON_OSAKA, SLOTNUM_PUSHES_ZERO]; /// Satin's instruction table carries four Amsterdam opcodes on its Osaka base. pub const AMSTERDAM_OPCODES_ON_OSAKA: Deviation = Deviation { @@ -1201,6 +1202,120 @@ pub const SELFDESTRUCT_BURNS_ON_OSAKA: Deviation = Deviation { ], }; +/// `SLOTNUM` pushes zero, where Amsterdam pushes the block's slot number. +pub const SLOTNUM_PUSHES_ZERO: Deviation = Deviation { + id: "slotnum-pushes-zero", + rule: "SLOTNUM pushes zero whatever slot number the block environment carries: the value is \ + the engine's own and depends on no field the node supplies.", + reason: "EIP-7843 has SLOTNUM push the slot number of the block, which a node supplies. Satin \ + fixes the value instead, so that a stateless validator needs no slot number as an \ + input. The fixtures set a non-zero slot number in the block environment and expect \ + it on the stack, or in the state and the gas that follow from it, so each fixture \ + that executes the opcode with a slot number other than zero fails on the state \ + root. The read stays a volatile read of the block environment, so the opcode's \ + price and its marking are Amsterdam's.", + fork: Fork::Amsterdam, + blockchain_entries: &[], + entries: &[ + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_call_contexts.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_CALL-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x9844550375d5580d1c236fdb59423d5f5c271c18440f4f7eb00d4ab1a289ee8e" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_call_contexts.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_CALLCODE-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xb227ac98fb5ebb4b89cc8e829a1fbd9271f38e92b9f97647e4dcfb9224c6730d" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_call_contexts.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_DELEGATECALL-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x026cf9c2e991acb1be1a28b072563a5bcd18f117291dc90f0a85e0f4ce3fe19a" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_call_contexts.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_call_contexts[fork_Amsterdam-call_opcode_STATICCALL-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x86c4b58c8b6c4e5354d9c7e0f7d73d4687085df933246408dd507107ed4f7cf4" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_initcode_create.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_initcode_create[fork_Amsterdam-state_test-opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x40d0b7ae59cf8b28c14aeb856399b90846fdf1e591043556df14c3d90349504f" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_initcode_create.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_initcode_create[fork_Amsterdam-state_test-opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x9da4f5c40a1b386fbd0ca103b74cccca0d8eb15cef887bea3e3aa17049523934" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_initcode_tx.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_initcode_tx[fork_Amsterdam-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xefee50e6818a814993fd8754c49822d9663aabd235e54b6a91ff8a02f143bec4" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_set_code.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_set_code[fork_Amsterdam-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x0f50f514d60dd84274327a597b7d8bf19a12c45b13e6771d9081f163b8c4811c" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_value.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_4096]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_value.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_large]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_value.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_max_u64]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip7843_slotnum/slotnum/slotnum_value.json", + name: "tests/amsterdam/eip7843_slotnum/test_slotnum.py::test_slotnum_value[fork_Amsterdam-state_test-slot_one]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x67b89cfc59cd0d25225e304db8b5d0bf9ec2dad6aebd62374a37f4f14ea78d77" + )), + }, + ], +}; + /// The deviation in `registry` that explains a failure of the entry `id` of `fork`, which /// produced `produced`, if one does. /// From 0aa6b7e3371fe41a6733e90a5b5ef8ed82df5017 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 12:00:01 +0800 Subject: [PATCH 013/190] test: hold the keyless value-call and intrinsic-history checks at any byte price --- crates/mega-evm/tests/satin/intrinsic.rs | 5 +++++ crates/mega-evm/tests/system/keyless/dispatch.rs | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 2a2f2ca53..18db95d58 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -450,8 +450,13 @@ fn test_the_bodys_history_is_reported_once_validation_admits_it() { let minimum = EMPTY_CALL + body_history(0); evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, minimum)).expect("the minimum is admitted"); assert_eq!(evm.ctx().intrinsic_history_gas(), body_history(0), "admitted"); + // At a byte price so small that the body's history rounds to nothing, the minimum is the + // intrinsic charge alone, and a gas limit equal to it is admitted: only a limit below the + // charge it is compared with is refused. for (gas_limit, initial_gas) in [(EMPTY_CALL - 1, EMPTY_CALL), (EMPTY_CALL, minimum), (minimum - 1, minimum)] + .into_iter() + .filter(|(gas_limit, initial_gas)| gas_limit < initial_gas) { let refused = evm .transact_raw(call(CALLER, CALLEE, U256::ZERO, gas_limit)) diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index 7e1f25913..7ee7537cb 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -235,8 +235,18 @@ fn test_bytes_after_a_valid_encoding_are_still_dispatched() { #[test] fn test_a_value_call_whose_arguments_do_not_decode_runs_the_bytecode() { let truncated: Bytes = KEYLESS_DEPLOY.iter().copied().chain([0_u8; 16]).collect(); - let result = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, truncated, U256::from(1))); + let result = + run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, truncated.clone(), U256::from(1))); assert!(!result.result.is_success()); assert!(revert_data(&result).is_empty()); - assert!(result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS); + // The same input without value is not dispatched either, so it pays no overhead; the value + // call must spend within an overhead of it, whatever the calldata costs at the byte prices in + // effect. + let without_value = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, truncated, U256::ZERO)); + let (with, without) = + (result.result.gas().total_gas_spent(), without_value.result.gas().total_gas_spent()); + assert!( + with.abs_diff(without) < KEYLESS_DEPLOY_OVERHEAD_GAS, + "the value call spent {with} against {without} without value: an overhead it does not owe", + ); } From 33ef1fb8eedd3eaac6eba96138aa4ad38c3d6df8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 12:40:00 +0800 Subject: [PATCH 014/190] ci: run the whole byte-price grid on every pull request --- .github/workflows/price-grid.yml | 25 ++++++++----------------- AGENTS.md | 6 +++--- REVIEW.md | 9 ++++----- 3 files changed, 15 insertions(+), 25 deletions(-) diff --git a/.github/workflows/price-grid.yml b/.github/workflows/price-grid.yml index 2abdcc19d..8ac0656d5 100644 --- a/.github/workflows/price-grid.yml +++ b/.github/workflows/price-grid.yml @@ -5,20 +5,17 @@ name: Byte-price grid # (scripts/price_grid.sh). Both prices are provisional until the economics sign-off, so the suite # must hold at any price it may end at, and a test that only holds at the constants shows here: # -# - on a pull request, five points: both bytes free, both at one gas (1 / 1), the cheapest and the -# dearest pair under consideration (312.5 / 20 and 5000 / 300), and a point past every candidate -# (10000 / 1000); -# - nightly and on dispatch, the whole grid: a cost per state byte of 0, 1, 312.5, 700, 1530, 2000, -# 5000 and 10000 by a cost per history byte of 0, 1, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 -# on both. +# Every pull request and every dispatch runs the whole grid: a cost per state byte of 0, 1, 312.5, +# 700, 1530, 2000, 5000 and 10000 by a cost per history byte of 0, 1, 20, 50, 88, 100, 200, 300 and +# 1000, and 0.001 on both. There is no schedule: GitHub fires a scheduled workflow only from the +# default branch, which has no such workflow, so a nightly full grid ran nowhere and points outside +# the five of the quick mode (scripts/price_grid.sh --pr, kept for local use) went unchecked. # # The run at the constants is the `test` job of build-and-test.yml. on: workflow_dispatch: pull_request: - schedule: - - cron: "0 4 * * *" permissions: contents: read @@ -31,7 +28,8 @@ jobs: price-grid: name: byte-price grid runs-on: ubuntu-24.04 - # The pull-request points take minutes; the nightly grid runs the suite 73 times. + # The full grid runs the suite 73 times: about 16 minutes on a warm local machine, so the build + # and a slower runner fit well within the limit. timeout-minutes: 90 steps: - uses: actions/checkout@v4 @@ -45,14 +43,7 @@ jobs: uses: foundry-rs/foundry-toolchain@v1 - name: Run the suite at each point - env: - EVENT: ${{ github.event_name }} - run: | - if [ "$EVENT" = "pull_request" ]; then - scripts/price_grid.sh --pr - else - scripts/price_grid.sh --full - fi + run: scripts/price_grid.sh --full - name: Upload the logs of a failing run if: failure() diff --git a/AGENTS.md b/AGENTS.md index fb29aedbc..af0986616 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ cargo test -p mega-evm --features satin-price-override,test-utils # that assert the spec's own byte prices skip, and the suite checks less than it looks like it does # The suite at other byte prices, as the byte-price grid job runs it (logs under target/price-grid) -scripts/price_grid.sh --pr # five points; --full for the whole grid, or name points: 312.5/20 +scripts/price_grid.sh --full # the whole grid, as CI runs it; --pr is five points; or name points: 312.5/20 # Regenerate the checked-in pricing table after an intentional schedule or engine change UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin @@ -626,7 +626,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te A fixture entry the engine rejects has no returned state to build the channel witness from, and replays on the record alone. The block tests cover each mechanism that reads, in the `test` job; `exec-spec-satin.yml` replays every Osaka and Amsterdam entry of the fixture releases in both modes and fails on any entry that does not replay, counting the entries replayed on both witnesses apart from the rejected ones. The fixture test is always ignored by default: it runs only with `-- --ignored` (or `--include-ignored`) and `MEGA_STATE_TEST_FIXTURES` set to the fixtures, and setting the variable alone runs nothing. -- **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, five points on a pull request and the whole grid nightly. +- **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, the whole grid on every pull request and on dispatch (`--pr`, five points, is the quick local mode). The prices are provisional, so a test holds at any of them — a byte price of nothing, or one gas per byte up to the grid's dearest point: it sizes its gas from the schedule at the prices in effect, and a case whose scenario is state or history gas returns early where that byte costs nothing (`state_is_free`, `history_is_free`). Below one gas per byte the schedule's entries round to nothing one at a time, and no test is held there. Each guard leaves a note (`test_utils::note_price_guard`), and the grid reports per point how many tests were guarded beside how many passed. @@ -707,7 +707,7 @@ When the agent is requested to implement a new feature or bug fix, it should con - **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 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. + 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, and `--full` before a pull request. - **Pin only outputs with no computable expectation.** A snapshot or a golden is the owner of an output no test can compute an expectation for, and of nothing else. Those outputs are the tracers' formats (`tests/tracers/`, the call-with-logs and prestate-diff views per scenario with the gas figures redacted, and the opcode view of two), recorded traces, such as the keyless differential's record pinned by one digest per case (`tests/system/keyless/differential.rs`), and the receipt bytes a node hashes, hand-pinned in `tests/block/receipt_goldens.rs`. diff --git a/REVIEW.md b/REVIEW.md index f0bc1333b..346a34b8a 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -145,13 +145,12 @@ These checks guard every change to the Satin engine. ### Byte-price grid - `.github/workflows/price-grid.yml` runs the `mega-evm` suite at byte prices other than the constants, through `scripts/price_grid.sh`: a cost per state byte and a cost per history byte per point, each run with `--no-fail-fast`. -- On a pull request it runs five points: both bytes free (0 / 0), both at one gas (1 / 1), the cheapest and the dearest pair under consideration (312.5 / 20 and 5000 / 300), and a point past every candidate (10000 / 1000). - Between them they have failed every test the whole grid failed; 1 / 1 is where a premise that a charge cannot be paid, true only while a byte is dear, breaks. -- Nightly and on dispatch it runs the whole grid: CPSB 0, 1, 312.5, 700, 1530, 2000, 5000 and 10000 by CPHB 0, 1, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 on both. +- On a pull request and on dispatch it runs the whole grid: CPSB 0, 1, 312.5, 700, 1530, 2000, 5000 and 10000 by CPHB 0, 1, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 on both. + It has no schedule, because a scheduled run would fire only from the default branch. - It is not a required check. A failure is a test that assumes a price, a scenario that does not scale with it, or an engine defect; the first two are fixed in the test, the third is not hidden behind a guard. - Each point reports how many tests a price guard held back (`guarded`, from `note_price_guard`; the tests are listed in the point's `.guards` file beside its log): every point passes the same number of tests, and this column tells a point at which tests returned early from one at which they ran. -- Locally, `scripts/price_grid.sh --pr`, `--full`, or the points named (`scripts/price_grid.sh 312.5/20 5000/300`); each point's log is under `target/price-grid/`. +- Locally, `scripts/price_grid.sh --full`, `--pr` (five points: 0 / 0, 1 / 1, 312.5 / 20, 5000 / 300 and 10000 / 1000, a quick local check), or the points named (`scripts/price_grid.sh 312.5/20 5000/300`); each point's log is under `target/price-grid/`. ### Instruction counts (CodSpeed) @@ -185,7 +184,7 @@ These checks guard every change to the Satin engine. ### Scheduled workflows -- GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, doc-audit, the weekly execution-spec run, the nightly byte-price grid) stay inert until `satin` is the default branch. +- GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, doc-audit, the weekly execution-spec run) stay inert until `satin` is the default branch. - Run them on `satin` by hand: `gh workflow run .yml --ref satin` runs `satin`'s copy of the workflow on `satin`'s head, so none of them needs a `ref` input. - `mutation.yml`: the whole-crate cargo-mutants run and suppression hygiene. - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. From e1c1025f4e9cdbf029066c34222cfd7b43bc9835 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 12:40:14 +0800 Subject: [PATCH 015/190] ci: describe the quick mode as local --- scripts/price_grid.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh index c1df50c0f..a9f754aae 100755 --- a/scripts/price_grid.sh +++ b/scripts/price_grid.sh @@ -2,7 +2,7 @@ # Runs the mega-evm test suite at state and history byte prices other than the constants. # # Usage: -# scripts/price_grid.sh --pr the pull-request points (PR_POINTS below) +# scripts/price_grid.sh --pr five quick points (PR_POINTS below) # scripts/price_grid.sh --full the whole grid (CPSB_AXIS x CPHB_AXIS, and EXTRA_POINTS) # scripts/price_grid.sh CPSB/CPHB ... the points named, e.g. 312.5/20 5000/300 # From b2f35567bf3d4e7bc3f67eac4be270feacf3f8a2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 13:35:27 +0800 Subject: [PATCH 016/190] test: size the reservoir scenarios from the schedule so they hold at any byte price --- .../tests/satin/reservoir_settlement.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/reservoir_settlement.rs b/crates/mega-evm/tests/satin/reservoir_settlement.rs index 56e593999..78dd0c0b7 100644 --- a/crates/mega-evm/tests/satin/reservoir_settlement.rs +++ b/crates/mega-evm/tests/satin/reservoir_settlement.rs @@ -28,7 +28,9 @@ use revm::{ Database, Inspector, }; -use crate::common::{body_history, call, context, history_is_free, slot_state_gas, state_is_free}; +use crate::common::{ + body_history, call, context, history, history_is_free, slot_state_gas, state_is_free, +}; const SENDER: Address = address!("0000000000000000000000000000000000740000"); const A: Address = address!("0000000000000000000000000000000000740001"); @@ -170,6 +172,15 @@ struct Run { read: Settlements, } +/// The reservoir the scenarios run with: four new slots' state gas and, beside each, the history of +/// one write record that the slot's write is charged on top. Sized from the schedule, so it covers +/// the transaction's start charge and every child's records at any byte price; a reservoir of the +/// state gas alone is smaller than one record's history where a history byte is dear, and the +/// children's shares then round to nothing. +fn scenario_reservoir() -> u64 { + 4 * (slot_state_gas() + history(mega_evm::WRITE_RECORD_SIZE)) +} + /// The gas limit that leaves `reservoir` once the body is paid. fn leaving(reservoir: u64) -> u64 { TX_GAS_LIMIT_CAP + body_history(0) + reservoir @@ -218,7 +229,7 @@ fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_ha } let children = [OK, REVERTER, HALTER, SPENDER, IDLE]; let Run { reservoir_remaining, read, .. } = - run(calling(&children, revm::bytecode::opcode::STOP), leaving(4 * slot_state_gas()), 0); + run(calling(&children, revm::bytecode::opcode::STOP), leaving(scenario_reservoir()), 0); assert_eq!(read.children.len(), children.len()); for (child, settled) in children.iter().zip(&read.children) { @@ -257,7 +268,7 @@ fn test_the_transactions_gas_holds_what_its_frame_hands_back_and_nothing_more() if state_is_free() { return; } - let above = leaving(4 * slot_state_gas()); + let above = leaving(scenario_reservoir()); for (end, ok, value, gas_limit) in [ (revm::bytecode::opcode::STOP, true, 0, above), (revm::bytecode::opcode::REVERT, false, 0, above), From 457db9b45ca8628dda9b7e8cc9c1945d399c75f4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 14:04:09 +0800 Subject: [PATCH 017/190] docs: format AGENTS.md --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index af0986616..db636ef1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,7 +141,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`); `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`) | +| `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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`); `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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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`) | From 32596388c37b49678d483d607f6eef9e4604051b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 14:53:36 +0800 Subject: [PATCH 018/190] test(fuzz): decide an applied authority's state growth by existence --- crates/mega-evm/tests/fuzz/gen/case.rs | 10 ++-- crates/mega-evm/tests/fuzz/properties.rs | 18 ++++++- crates/mega-evm/tests/fuzz/regressions.rs | 65 ++++++++++++++++++++++- 3 files changed, 86 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/tests/fuzz/gen/case.rs b/crates/mega-evm/tests/fuzz/gen/case.rs index 2fa6b6911..8eeb23c55 100644 --- a/crates/mega-evm/tests/fuzz/gen/case.rs +++ b/crates/mega-evm/tests/fuzz/gen/case.rs @@ -61,10 +61,12 @@ impl Case { /// system address, the fixed accounts with their programs, the delegation, and, for a keyless /// deployment, its signer's account and what its deploy address holds. /// - /// An account that would hold nothing — no balance, nonce, code or slot — is left out, as no - /// chain past EIP-161 holds one: revm's EIP-7702 application counts an account its database - /// holds as existing, empty or not, where a value transfer counts an empty one as new, so an - /// empty account in the pre-state would make the two disagree on a state no chain reaches. + /// An account that would hold nothing — no balance, nonce, code or slot — is left out. One that + /// holds slots and nothing else is installed, its slots holding zero or not: an account empty + /// under EIP-161 whose leaf the state holds, as a genesis allocation can leave one. The sites + /// that add an account decide it by two rules: an applied EIP-7702 authority is new only where + /// the state holds no account, so this one exists, and every other site counts an account + /// empty under EIP-161 as new. pub(crate) fn database(&self) -> MemoryDatabase { let mut db = MemoryDatabase::default().rex6_predeploys(SYSTEM_ADDRESS); let world = &self.world; diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index a1181029a..6d56d8aef 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -4,7 +4,10 @@ //! states what the spec says of the outcome. A property that does not hold by design is stated //! as what does hold, and says so. -use std::{collections::BTreeMap, sync::Mutex}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Mutex, +}; use alloy_primitives::{Address, U256}; use mega_evm::{ @@ -436,6 +439,10 @@ fn fee_credits( /// 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 applied EIP-7702 authority is decided by existence instead: it is a rise only where the +/// world held no account at its address, and one the world held empty under EIP-161 is no new +/// account. Every other site that adds an account counts an empty one as new. +/// /// 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 @@ -453,6 +460,8 @@ pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runne let deposit_like = tx.0.deposit.source_hash != alloy_primitives::B256::ZERO || tx.caller() == SYSTEM_ADDRESS; let mut pre = case.database(); + let authorities: BTreeSet
= + applied_authorizations(case).into_iter().map(|(authority, _)| authority).collect(); let mut expected = 0; for (address, account) in &outcome.state { if destroyed_in_the_transaction(account) { @@ -469,6 +478,13 @@ pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runne if *address == tx.caller() && !deposit_like { continue; } + // An authority is decided by existence: one whose account the world held, empty or not, is + // no new account, and its application leaves it with a nonce, so no later site in the + // transaction adds it either. Where the list was skipped or taken back, the account stands + // as the world held it, which is no rise whichever test decides it. + if authorities.contains(address) && leaf_at_start(&mut pre, *address).is_some() { + continue; + } if pre_account(&mut pre, *address).is_some() { continue; } diff --git a/crates/mega-evm/tests/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 8c5ff81ae..a9000ffda 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -28,11 +28,11 @@ use crate::{ gen::{ case::Case, program::{End, Forward, InitCode, Op, Program, Scheme, Target}, - tx::{GasTier, Price, Shape, Tx}, + tx::{Auth, Delegate, GasTier, Price, Shape, Tx}, world::{ AccountShape, Balance, BeneficiaryIs, BlockShape, Delegation, Limits, Salt, World, }, - Value, Who, + Value, Who, Word, }, harness::{history_rounds, runs_at_measurement_prices}, render::render, @@ -206,6 +206,67 @@ fn test_a_delegated_sender_that_funds_then_creates_reports_the_net_change() { ); } +/// An EIP-7702 authority whose account the pre-state holds empty — nonce zero, no balance, no +/// code, and one slot that holds zero — is no new account: an authority is new only where the state +/// holds no account at its address, an account empty under EIP-161 included, while the other sites +/// that add an account count an empty one as new. Applying the authorization charges the +/// delegation's bytes alone and counts no state growth. +/// +/// The state-growth property's oracle decided every account by EIP-161 emptiness and counted the +/// authority as a rise the engine, by the existence rule, does not make. +#[test] +fn test_an_authority_whose_empty_account_the_state_holds_is_no_new_state() { + let mut world = plain_world(); + world.a.slots = vec![(0, Word::Zero)]; + let case = Case { + world, + tx: Tx { + shape: Shape::Eip7702 { + to: Who::Caller, + auths: vec![Auth { + authority: Who::A, + nonce_ok: true, + chain_ok: true, + recovers: true, + delegate: Delegate::Contract, + }], + }, + value: Value::Zero, + gas: GasTier::Small, + price: Price::Free, + nonce_ok: true, + }, + main: stop(), + a: Program { ops: vec![], end: End::Fallthrough }, + b: stop(), + }; + let execution = case.execute(); + let rendered = render(&execution); + if let Err(error) = crate::properties::check_state_growth(&case) { + panic!("{error}\n{rendered}"); + } + // The figures below need the authorization applied, which the case's gas limit pays for at the + // spec's byte prices, where the case was found; at the dearest prices it runs out of gas before + // the first frame, which takes the authorization back. + if runs_at_measurement_prices() { + return; + } + use revm::context_interface::cfg::GasId; + let outcome = execution.as_ref().expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{rendered}"); + let authority = &outcome.state[&Who::A.address()]; + assert!( + authority.info.nonce == 1 && authority.info.code.as_ref().is_some_and(|c| c.is_eip7702()), + "the authorization applied\n{rendered}" + ); + assert_eq!(outcome.usage.state_growth, 0, "the authority existed\n{rendered}"); + assert_eq!( + outcome.gas.state, + mega_evm::satin_gas_params().get(GasId::tx_eip7702_state_gas_bytecode()), + "the delegation's bytes, and no new account\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 From 71d720c7907e9503fdfceca86f7c1d3a9ebc5080 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 14:53:37 +0800 Subject: [PATCH 019/190] test(satin): pin an empty account as existing for an authority and new for a value transfer --- crates/mega-evm/tests/satin/state_growth.rs | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 6623ec61c..2307ab6df 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -330,6 +330,44 @@ fn test_an_authority_an_earlier_transaction_touched_is_charged_as_new_when_commi assert_eq!(outcome.usage.write_records, 1); } +/// An account the database holds empty under EIP-161 — nonce zero, no balance, no code, and +/// storage holding nothing — exists for an authorization and is new for a value transfer: an +/// authority is new only where the state holds no account at its address, while a transaction's +/// value counts an empty recipient as new as it counts an absent one. The authorization charges the +/// delegation's bytes alone and counts no rise, and still writes the account, one record; the +/// value charges the new account and counts the rise. +#[test] +fn test_an_account_the_database_holds_empty_is_new_to_a_value_transfer_and_not_to_an_authority() { + if state_is_free() { + return; + } + let (account, delegation) = account_and_delegation(); + let held_empty = || { + funded().account_code(A, Bytes::from_static(&[STOP])).account_storage( + AUTHORITY_1, + U256::ZERO, + U256::ZERO, + ) + }; + let held = revm::Database::basic(&mut held_empty(), AUTHORITY_1).expect("in memory"); + assert!( + held.is_some_and(|info| info.is_empty()), + "the database holds the authority's account, empty" + ); + + let authorized = run(held_empty(), authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)])); + assert!(authorized.result.is_success(), "{:?}", authorized.result); + assert_eq!(authorized.state[&AUTHORITY_1].info.nonce, 1, "the authorization applied"); + assert_eq!(authorized.gas.state, delegation, "the delegation's bytes, and no new account"); + assert_eq!(authorized.usage.state_growth, 0, "the authority existed"); + assert_eq!(authorized.usage.write_records, 1, "the authority's record"); + + let paid = run(held_empty(), call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP)); + assert!(paid.result.is_success(), "{:?}", paid.result); + assert_eq!(paid.gas.state, account, "the new account"); + assert_eq!(paid.usage.state_growth, 1, "the empty recipient is a new account"); +} + /// The same two transactions on one journal that is not finalized in between differ from the /// committed path, in simulation only: revm's flag of the call's touch outlives the call's /// transaction, so the application finds the authority touched, not new, and charges the From 4d7fac826d03fc3c741707e45ee92c3659879064 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 14:54:40 +0800 Subject: [PATCH 020/190] docs: state the existence rule for an authority's state growth --- docs/spec/upgrades/satin.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 574006a1f..74099f13e 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -628,6 +628,7 @@ The same KV and state-growth numbers limit a block: `BLOCK_KV_UPDATE_LIMIT` = 50 - 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 authority is new only where the state holds no account at its address, so an authority whose account the state holds is not a rise, an account empty under EIP-161 included; every other site counts an account empty under EIP-161 as new, as it counts an absent one. 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)). From bedbbfb6e73fac5100ae125ba9c079fc0c1bcc9e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 16:43:57 +0800 Subject: [PATCH 021/190] test(fuzz): require the cases to reach empty-but-present accounts --- crates/mega-evm/tests/fuzz/gen/case.rs | 26 +++++- crates/mega-evm/tests/fuzz/gen/program.rs | 11 ++- crates/mega-evm/tests/fuzz/gen/tx.rs | 2 +- crates/mega-evm/tests/fuzz/gen/world.rs | 34 +++++++ crates/mega-evm/tests/fuzz/properties.rs | 109 +++++++++++++++++++++- crates/mega-evm/tests/fuzz/regressions.rs | 4 +- 6 files changed, 177 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/tests/fuzz/gen/case.rs b/crates/mega-evm/tests/fuzz/gen/case.rs index 8eeb23c55..a28c35b0e 100644 --- a/crates/mega-evm/tests/fuzz/gen/case.rs +++ b/crates/mega-evm/tests/fuzz/gen/case.rs @@ -66,7 +66,9 @@ impl Case { /// under EIP-161 whose leaf the state holds, as a genesis allocation can leave one. The sites /// that add an account decide it by two rules: an applied EIP-7702 authority is new only where /// the state holds no account, so this one exists, and every other site counts an account - /// empty under EIP-161 as new. + /// empty under EIP-161 as new. The world's `empty_leaves` install more such accounts, with + /// nothing in them: the fresh address, the distinct beneficiary and the addresses the + /// programs' `CREATE2` ops land on, and the address a creation transaction deploys at. pub(crate) fn database(&self) -> MemoryDatabase { let mut db = MemoryDatabase::default().rex6_predeploys(SYSTEM_ADDRESS); let world = &self.world; @@ -77,6 +79,28 @@ impl Case { let beneficiary_balance = world.beneficiary_balance.wei(); if !beneficiary_balance.is_zero() { db.set_account_balance(Who::Beneficiary.address(), beneficiary_balance); + } else if world.empty_leaves.beneficiary { + db.insert_account_info(Who::Beneficiary.address(), AccountInfo::default()); + } + if world.empty_leaves.fresh { + db.insert_account_info(Who::Fresh.address(), AccountInfo::default()); + } + if world.empty_leaves.created { + // The address a creation transaction deploys at, whose init code is the main program. + if matches!(self.tx.shape, Shape::Create | Shape::Deposit { create: true, .. }) { + let caller = Who::Caller.address(); + db.insert_account_info( + caller.create(world.nonce_of(caller)), + AccountInfo::default(), + ); + } + for (deployer, program) in + [(Who::Contract, &self.main), (Who::A, &self.a), (Who::B, &self.b)] + { + for address in program.create2_addresses(deployer.address()) { + db.insert_account_info(address, AccountInfo::default()); + } + } } if let Some(delegation) = world.delegation { let address = delegation.delegator.address(); diff --git a/crates/mega-evm/tests/fuzz/gen/program.rs b/crates/mega-evm/tests/fuzz/gen/program.rs index 79cec5908..26c9af2d3 100644 --- a/crates/mega-evm/tests/fuzz/gen/program.rs +++ b/crates/mega-evm/tests/fuzz/gen/program.rs @@ -667,7 +667,7 @@ fn end() -> impl Strategy { 3 => (0u16..=100).prop_map(|len| End::Return { len }), 3 => (0u16..=100).prop_map(|len| End::Revert { len }), 1 => Just(End::Invalid), - 2 => target().prop_map(|to| End::Selfdestruct { to }), + 3 => target().prop_map(|to| End::Selfdestruct { to }), 1 => Just(End::Spin), 1 => Just(End::Fallthrough), ] @@ -681,6 +681,15 @@ pub(crate) struct Program { } impl Program { + /// The addresses the program's `CREATE2` ops land on when `deployer` runs it. + pub(crate) fn create2_addresses(&self, deployer: Address) -> Vec
{ + Creations::of(&self.ops) + .0 + .into_iter() + .map(|(salt, init_hash)| deployer.create2(B256::left_padding_from(&[salt]), init_hash)) + .collect() + } + /// The program's bytecode. pub(crate) fn assemble(&self) -> Vec { let creations = Creations::of(&self.ops); diff --git a/crates/mega-evm/tests/fuzz/gen/tx.rs b/crates/mega-evm/tests/fuzz/gen/tx.rs index 89c6ca99d..8c74cd078 100644 --- a/crates/mega-evm/tests/fuzz/gen/tx.rs +++ b/crates/mega-evm/tests/fuzz/gen/tx.rs @@ -472,7 +472,7 @@ fn shape(flavor: Flavor) -> impl Strategy { let shapes = prop_oneof![ 10 => (who(), 0u16..=200, access_list()) .prop_map(|(to, data_len, access_list)| Shape::Call { to, data_len, access_list }), - 3 => Just(Shape::Create), + 5 => Just(Shape::Create), // An empty authorization list refuses the transaction: one in sixteen covers it. 3 => ( who(), diff --git a/crates/mega-evm/tests/fuzz/gen/world.rs b/crates/mega-evm/tests/fuzz/gen/world.rs index 4e807c46d..215ec26a7 100644 --- a/crates/mega-evm/tests/fuzz/gen/world.rs +++ b/crates/mega-evm/tests/fuzz/gen/world.rs @@ -317,6 +317,35 @@ fn block() -> impl Strategy { .prop_map(|(basefee, slot_num, blob)| BlockShape { basefee, slot_num, blob }) } +/// Which addresses that would hold nothing are still in the state, each as an account empty under +/// EIP-161 (no balance, nonce, code or storage) whose leaf the state holds, as a genesis +/// allocation can leave one. Existence and emptiness give different answers at several sites, so +/// the cases must reach both an absent address and an empty one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct EmptyLeaves { + /// The `Fresh` address. + pub(crate) fresh: bool, + /// The distinct beneficiary, where its balance is zero. + pub(crate) beneficiary: bool, + /// The address each `CREATE2` of the three programs lands on, and the one a creation + /// transaction deploys at. + pub(crate) created: bool, +} + +fn empty_leaves() -> impl Strategy { + // A third of the worlds for the fixed addresses, which the rest keep absent. The landings of + // creations are empty in two worlds of three: a creation over an empty leaf that its init code + // then destroys needs a creation, an init code that destroys and a landing the world holds, + // and is otherwise too rare for a bounded run to reach. + let third = || prop_oneof![1 => Just(true), 2 => Just(false)]; + let two_thirds = || prop_oneof![2 => Just(true), 1 => Just(false)]; + (third(), third(), two_thirds()).prop_map(|(fresh, beneficiary, created)| EmptyLeaves { + fresh, + beneficiary, + created, + }) +} + /// The world a case runs in. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct World { @@ -335,6 +364,8 @@ pub(crate) struct World { pub(crate) block: BlockShape, /// The system address's nonce. pub(crate) system_nonce: u8, + /// The addresses held as empty accounts rather than absent. + pub(crate) empty_leaves: EmptyLeaves, } impl World { @@ -378,6 +409,7 @@ pub(crate) fn world() -> impl Strategy { limits(), block(), 0u8..2, + empty_leaves(), ) .prop_map( |( @@ -390,6 +422,7 @@ pub(crate) fn world() -> impl Strategy { limits, block, system_nonce, + empty_leaves, )| World { caller, contract, @@ -403,6 +436,7 @@ pub(crate) fn world() -> impl Strategy { limits, block, system_nonce, + empty_leaves, }, ) } diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index 6d56d8aef..b80765b73 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -32,7 +32,7 @@ use crate::{ tx::{tx, Delegate, Shape}, Flavor, Who, SYSTEM_ADDRESS, }, - harness::{check, print_tally, prop_check, prop_eq}, + harness::{check, print_tally, prop_check, prop_eq, require_coverage}, render::{render, render_outcome}, }; @@ -141,6 +141,35 @@ fn leaf_at_start(db: &mut MemoryDatabase, address: Address) -> Option, + classes: &[&str], +) { + let missing: Vec = classes + .iter() + .filter(|class| tally.get(**class).copied().unwrap_or(0) == 0) + .map(|class| (*class).to_string()) + .collect(); + require_coverage(name, bounded_cases, &missing); +} + /// 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 @@ -367,13 +396,38 @@ fn test_property_kv_weighs_no_more_than_data_size() { /// 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. +/// +/// The destruction rule branches on whether the world held the account's leaf, so the case must +/// reach an account created and destroyed over a leaf that existed empty (a class this property +/// claims, see [`EMPTY_LEAF_DESTROYED`]). #[test] fn test_property_the_record_count_is_the_net_change() { - check("record_count", CASES, || case(Flavor::Satin), check_record_count); + let tally: Mutex> = Mutex::new(BTreeMap::new()); + check( + "record_count", + CASES, + || case(Flavor::Satin), + |case| { + check_record_count_observed(case, &|class| { + *tally.lock().unwrap().entry(class).or_default() += 1; + }) + }, + ); + let tally = tally.into_inner().unwrap(); + print_tally("record_count", tally.iter().map(|(class, n)| (class, *n))); + require_classes("record_count", CASES, &tally, &[EMPTY_LEAF_DESTROYED]); } /// 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> { + check_record_count_observed(case, &|_| {}) +} + +/// [`check_record_count`], reporting the classes the case reached to `observe`. +fn check_record_count_observed( + case: &Case, + observe: &dyn Fn(&'static str), +) -> Result<(), proptest::test_runner::TestCaseError> { let tx = case.transaction(); let Ok(outcome) = case.execute() else { return Ok(()) }; let credit = fee_credits(case, &tx, &outcome); @@ -381,7 +435,11 @@ pub(crate) fn check_record_count(case: &Case) -> Result<(), proptest::test_runne 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()); + let leaf = leaf_at_start(&mut pre, *address); + if leaf.as_ref().is_some_and(|info| info.is_empty()) { + observe(EMPTY_LEAF_DESTROYED); + } + expected += u64::from(leaf.is_some()); continue; } let slots = account.storage.values().filter(|slot| slot.is_changed()).count(); @@ -447,13 +505,44 @@ fn fee_credits( /// 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. +/// +/// Existence and emptiness give different answers at three sites, and the property claims a case +/// at each: an applied authority the world holds as an empty account (no new account), an empty +/// account a value transfer or a creation fills (a new account), and an account created and +/// destroyed over an empty leaf (a leaf the destruction does not take back). #[test] fn test_property_state_growth_is_the_net_count_of_new_state() { - check("state_growth", CASES, || case(Flavor::Satin), check_state_growth); + let tally: Mutex> = Mutex::new(BTreeMap::new()); + check( + "state_growth", + CASES, + || case(Flavor::Satin), + |case| { + check_state_growth_observed(case, &|class| { + *tally.lock().unwrap().entry(class).or_default() += 1; + }) + }, + ); + let tally = tally.into_inner().unwrap(); + print_tally("state_growth", tally.iter().map(|(class, n)| (class, *n))); + require_classes( + "state_growth", + CASES, + &tally, + &[EMPTY_AUTHORITY, EMPTY_LEAF_FILLED, EMPTY_LEAF_DESTROYED], + ); } /// 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> { + check_state_growth_observed(case, &|_| {}) +} + +/// [`check_state_growth`], reporting the classes the case reached to `observe`. +fn check_state_growth_observed( + case: &Case, + observe: &dyn Fn(&'static str), +) -> Result<(), proptest::test_runner::TestCaseError> { let tx = case.transaction(); let Ok(outcome) = case.execute() else { return Ok(()) }; let credit = fee_credits(case, &tx, &outcome); @@ -466,6 +555,9 @@ pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runne 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()); + if empty_leaf { + observe(EMPTY_LEAF_DESTROYED); + } expected += u64::from(empty_leaf); continue; } @@ -482,7 +574,11 @@ pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runne // no new account, and its application leaves it with a nonce, so no later site in the // transaction adds it either. Where the list was skipped or taken back, the account stands // as the world held it, which is no rise whichever test decides it. - if authorities.contains(address) && leaf_at_start(&mut pre, *address).is_some() { + let leaf = leaf_at_start(&mut pre, *address); + if authorities.contains(address) && leaf.is_some() { + if leaf.as_ref().is_some_and(|info| info.is_empty()) { + observe(EMPTY_AUTHORITY); + } continue; } if pre_account(&mut pre, *address).is_some() { @@ -494,6 +590,9 @@ pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runne let exists = account.info.nonce != 0 || !balance.is_zero() || account.info.code_hash != revm::primitives::KECCAK_EMPTY; + if exists && leaf.is_some() { + observe(EMPTY_LEAF_FILLED); + } expected += u64::from(exists); } prop_eq!( diff --git a/crates/mega-evm/tests/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index a9000ffda..9befbe4da 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -30,7 +30,8 @@ use crate::{ program::{End, Forward, InitCode, Op, Program, Scheme, Target}, tx::{Auth, Delegate, GasTier, Price, Shape, Tx}, world::{ - AccountShape, Balance, BeneficiaryIs, BlockShape, Delegation, Limits, Salt, World, + AccountShape, Balance, BeneficiaryIs, BlockShape, Delegation, EmptyLeaves, Limits, + Salt, World, }, Value, Who, Word, }, @@ -59,6 +60,7 @@ fn plain_world() -> World { limits: Limits::Default, block: BlockShape { basefee: 0, slot_num: 0, blob: true }, system_nonce: 0, + empty_leaves: EmptyLeaves::default(), } } From 5fb9d564cf3798625910b2740a3db1a8e6ce8514 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 16:44:08 +0800 Subject: [PATCH 022/190] docs(mega-evme): state why an all-zero RPC account reads as absent --- bin/mega-evme/src/block/state.rs | 15 +++++++++++---- bin/mega-evme/src/common/state.rs | 18 +++++++++++++----- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/bin/mega-evme/src/block/state.rs b/bin/mega-evme/src/block/state.rs index 09db3782f..9d0bacaaa 100644 --- a/bin/mega-evme/src/block/state.rs +++ b/bin/mega-evme/src/block/state.rs @@ -54,10 +54,17 @@ const fn is_zero(n: &u64) -> bool { impl PreAccount { /// Whether the account does not exist. /// - /// Neither a trace nor an RPC endpoint can say "no such account": they report zeros for it. - /// A node's database answers `None`, and the difference is observable (EIP-7702 refunds an - /// authorization whose authority already exists), so an all-zero account is absent. An - /// existing empty account cannot occur on a chain that has had EIP-161 from genesis. + /// Neither a trace nor an RPC endpoint can say "no such account": they report zeros for it, so + /// reading the report as it stands would make every absent account an existing empty one. A + /// node's database answers `None`, and the difference is observable (EIP-7702 refunds an + /// authorization whose authority already exists, 12,500 gas each), so an all-zero account is + /// absent. + /// + /// That is safe because an existing-but-empty account cannot occur on a chain that has had + /// EIP-161 from genesis, as every `MegaETH` chain has: EIP-161 removes empty accounts on touch + /// and forbids creating them, and the genesis allocations carry a balance or code. An account + /// with no balance, nonce or code that still holds storage cannot exist either, since storage + /// is reachable only through code and a contract has code or a nonce. pub fn is_absent(&self) -> bool { self.balance.is_zero() && self.nonce == 0 && self.code_hash.is_none() } diff --git a/bin/mega-evme/src/common/state.rs b/bin/mega-evme/src/common/state.rs index cf2f88035..f87f3782c 100644 --- a/bin/mega-evme/src/common/state.rs +++ b/bin/mega-evme/src/common/state.rs @@ -604,11 +604,19 @@ pub(crate) fn materialize_dumped_code( /// Whether an account an RPC endpoint reported is one that does not exist. /// -/// JSON-RPC cannot say "no such account": `eth_getBalance`, `eth_getTransactionCount` and -/// `eth_getCode` answer zeros for it. A node's database answers `None`, and the difference is -/// observable (EIP-7702 refunds an authorization whose authority already exists), so an all-zero -/// answer is read as absent. An existing account that is empty cannot occur on a chain that has -/// had EIP-161 from genesis, as every `MegaETH` chain has. +/// JSON-RPC cannot express account non-existence: `eth_getBalance`, `eth_getTransactionCount` and +/// `eth_getCode` all answer zeros for an account that was never created, so reading the answer as +/// it stands materializes an *existing* empty account. That flips every consumer of existence, +/// most visibly the EIP-7702 refund per authorization: a brand-new authority would be judged +/// already in the trie and the replay would refund 12,500 gas per authorization that the chain did +/// not. +/// +/// Reading an all-zero answer as absent is safe because an existing-but-empty account cannot occur +/// on `MegaETH`: EIP-161 removes empty accounts on touch and forbids creating them, every chain +/// this tool replays has had it from genesis, and the genesis allocations carry a balance or code. +/// The one shape this cannot tell apart, an account with zero balance, nonce and code that still +/// holds storage, cannot exist after EIP-161 either, since storage is reachable only through code +/// and a contract has code or a nonce. fn rpc_reads_as_absent(info: &AccountInfo) -> bool { info.balance.is_zero() && info.nonce == 0 && info.code_hash == revm::primitives::KECCAK_EMPTY } From 0de45a253698994dd3e13f42c77c01e10e983c8c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 16:53:40 +0800 Subject: [PATCH 023/190] ci: run the long fuzz and the price record on every pull request --- .github/workflows/fuzz.yml | 42 ++++++++++++++++++++++++-------------- AGENTS.md | 7 +++++-- REVIEW.md | 9 ++++++++ 3 files changed, 41 insertions(+), 17 deletions(-) diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index fa1492af1..afe35f6d6 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -1,30 +1,33 @@ name: Randomized tests, long mode # Runs the randomized tests of the Satin engine (crates/mega-evm/tests/fuzz) in their long mode: -# many more cases per property than the bounded run every pull request makes, drawn from a seed -# this run chooses (or the one given), in a debug build, where every debug assertion runs, and in -# a release build, where none does. A failure prints the seed and the case count that reproduce it -# and the minimal case it shrank to; the job's log is the record. +# many more cases per property than the bounded run every pull request makes in the `test` checks, +# drawn from a seed this run chooses (or the one given), in a debug build, where every debug +# assertion runs, and in a release build, where none does. A failure prints the seed and the case +# count that reproduce it and the minimal case it shrank to; the job's log is the record. # # It also runs the byte-price record at two prices and compares them: where a case followed the # same path at both, its state gas must not fall as the cost per state byte rises, nor its history # gas as the cost per history byte rises (scripts/fuzz_price_monotonic.py). # -# Dispatch only: a scheduled trigger fires on the default branch alone, which the Satin -# integration branch is not. Dispatch it from the branch to test, with a seed to reproduce a run -# or none to draw a new one. +# Every pull request runs all of it, and so does a dispatch. There is no schedule and no dispatch +# alone: GitHub fires a scheduled workflow only from the default branch, and accepts a dispatch +# only for a workflow the default branch has, which has no such workflow, so a run triggered either +# way ran nowhere on the Satin integration branch. There is no path filter either, so a change to +# the engine, a generator or a property all run it. # -# The two inputs, and how they meet the long mode: +# The two inputs of a dispatch, and how they meet the long mode: # -# - `cases` empty (the default): each property runs fifty times its own bounded count, 6,400 to -# 38,400 cases, which is what `MEGA_FUZZ_LONG=1` means on its own. +# - `cases` empty (the default, and always on a pull request): each property runs fifty times its +# own bounded count, 6,400 to 38,400 cases, which is what `MEGA_FUZZ_LONG=1` means on its own. # - `cases` set: every property runs exactly that many cases. The count replaces the bounded count # and the multiplier alike; it is not multiplied by fifty. -# - `seed` empty: the run draws one seed from the clock, prints it, and uses it for every property -# and both profiles, so one number reproduces the run. +# - `seed` empty (the default, and always on a pull request): the run draws one seed from the +# clock, prints it in the step summary, and uses it for every property and every job, so one +# number reproduces the run. The price comparison needs both of its records from one seed. # # The runner itself reads an empty `MEGA_FUZZ_CASES` or `MEGA_FUZZ_SEED` as unset, so an input left -# empty cannot fail the run. +# empty (or absent, as on a pull request) cannot fail the run. on: workflow_dispatch: @@ -37,10 +40,15 @@ on: description: "The seed to draw the cases from; empty draws one from the clock" required: false default: "" + pull_request: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: seed: name: the run's seed @@ -63,7 +71,10 @@ jobs: name: long mode (${{ matrix.profile }}) needs: seed runs-on: ubuntu-24.04 - timeout-minutes: 120 + # Measured locally at one seed on a warm machine: the release run takes 2 minutes and the debug + # run 7 (400 s), each after a build of a minute or less. A runner three times slower with a cold + # build (about 15 minutes) still finishes within 40 minutes. + timeout-minutes: 60 strategy: fail-fast: false matrix: @@ -96,7 +107,8 @@ jobs: name: state and history gas along the byte prices needs: seed runs-on: ubuntu-24.04 - timeout-minutes: 60 + # Measured locally: the three runs take under a minute after the build, which is the cost. + timeout-minutes: 45 steps: - uses: actions/checkout@v4 with: diff --git a/AGENTS.md b/AGENTS.md index db636ef1b..135d30992 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -577,10 +577,13 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te - **Two modes.** The bounded mode is deterministic: seed 0, a fixed case count per property (128 to 768), under ten seconds in debug. It is part of `cargo test --workspace`, which `build-and-test.yml` runs in debug (`test`), where every debug assertion runs, and in release (`test-release`), where none does. - The long mode (`MEGA_FUZZ_LONG=1`) multiplies each property's count by fifty and draws a seed from the clock unless `MEGA_FUZZ_SEED` names one; `fuzz.yml` runs it on `workflow_dispatch`, in debug and in release, since a schedule fires only on the default branch. + The long mode (`MEGA_FUZZ_LONG=1`) multiplies each property's count by fifty and draws a seed from the clock unless `MEGA_FUZZ_SEED` names one; `fuzz.yml` runs it on every pull request and on dispatch, in debug and in release, from one seed drawn per run; a schedule or a dispatch alone would never run it, because GitHub accepts a dispatch only for a workflow the default branch has and fires a schedule only from the default branch. `MEGA_FUZZ_SEED` names the seed in either mode. `MEGA_FUZZ_CASES` names the case count in either mode, and it is the count: every property runs exactly that many cases, and the long mode's multiplier does not apply to it. Either variable set to the empty string counts as unset, which is how `fuzz.yml` passes an input left empty. +- **Coverage claims.** + A property lists the classes its default run (seed 0, the bounded count) must reach and fails if one is missed (`harness::require_coverage`); on any other run a missed class is a printed note. + Existence and emptiness give different answers at several sites, so the world holds some addresses as accounts empty under EIP-161 rather than absent (`EmptyLeaves`), and the state-growth and record-count properties claim the cases where that decides the answer: an applied authority, an account a value transfer or a creation fills, and an account created and destroyed over an empty leaf. - **The properties hold for any seed.** Seed 0 is what CI runs, not what the properties are true of: a change to a generator redraws every case, so a property that held on one seed by luck fails on the pull request that touches a weight. Before changing a generator or a property, run the bounded mode on a few dozen seeds and the long mode on a few; a failure there is a bug to fix or a property to correct, never a seed to avoid. @@ -601,7 +604,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te An expected value is computed from the case or from what the transactions themselves report, never read back from the thing under test: an assertion that restates a definition, or compares a counter with itself, cannot fail. To add an op or a transaction shape, extend the enum and its strategy in `gen/`, its assembly, and, if op-revm cannot express it, its `neutralized` counterpart. - **The byte prices** are a process-wide constant, so a case cannot run at two prices in one test. - `prices.rs` checks the schedule builder's monotonicity in-process, and under `satin-price-override` records what every case spent (`MEGA_FUZZ_PRICE_RECORD`) for `scripts/fuzz_price_monotonic.py` to compare two runs at two prices, which `fuzz.yml` does. + `prices.rs` checks the schedule builder's monotonicity in-process, and under `satin-price-override` records what every case spent (`MEGA_FUZZ_PRICE_RECORD`) for `scripts/fuzz_price_monotonic.py` to compare two runs at two prices, which `fuzz.yml` does on every pull request. The properties themselves hold at any byte price and run in the byte-price grid; the regression tests that fall short of a charge pin a minimal case at the spec's prices and return early at others. ## Test Gates diff --git a/REVIEW.md b/REVIEW.md index 346a34b8a..1aa185486 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -152,6 +152,15 @@ These checks guard every change to the Satin engine. - Each point reports how many tests a price guard held back (`guarded`, from `note_price_guard`; the tests are listed in the point's `.guards` file beside its log): every point passes the same number of tests, and this column tells a point at which tests returned early from one at which they ran. - Locally, `scripts/price_grid.sh --full`, `--pr` (five points: 0 / 0, 1 / 1, 312.5 / 20, 5000 / 300 and 10000 / 1000, a quick local check), or the points named (`scripts/price_grid.sh 312.5/20 5000/300`); each point's log is under `target/price-grid/`. +### Randomized tests, long mode + +- The bounded fuzz run is part of the `test` and `test-release` checks. +- `.github/workflows/fuzz.yml` runs the long mode on every pull request and on dispatch: every property at fifty times its bounded count, in debug and in release, and the byte-price record at two prices compared by `scripts/fuzz_price_monotonic.py`, all from one seed the run draws and prints in the step summary. + It has no schedule and no path filter, because a scheduled or dispatch-only workflow would never run on this line (GitHub needs the workflow on the default branch for either). +- It is not a required check. + A failure prints the seed and the case count that reproduce it and the minimal case; it is a defect in the engine or a property to correct, never a seed to avoid. +- Locally, `MEGA_FUZZ_LONG=1 MEGA_FUZZ_SEED= cargo test [--release] -p mega-evm --test fuzz -- --nocapture`. + ### Instruction counts (CodSpeed) - The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (the JSON scenarios under `benches/scenarios` through `MegaEvm`, a bench input rather than a conformance suite), `factory` (EVM construction through `MegaEvmFactory`) and `block` (a block through `MegaBlockExecutor`), all in `crates/mega-evm/benches`. From cadc95b750328a42071d46a65f86c6444c027e50 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:08:34 +0800 Subject: [PATCH 024/190] test(system): pin an unfunded value-bearing sendHint, under and over the data-size limit --- crates/mega-evm/tests/system/oracle.rs | 92 ++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index db015e574..870fc4e70 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -174,6 +174,98 @@ fn test_a_value_bearing_call_forwards_its_hint() { assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); } +/// Code that calls the Oracle with `data`, one unit of value and no requested gas, and returns +/// the call's status followed by its return data. The contract holds no balance, so the call +/// cannot be funded. +fn unfunded_value_hint_call(data: &[u8]) -> Bytes { + use revm::bytecode::opcode::{ADD, MSTORE, RETURN, RETURNDATACOPY, RETURNDATASIZE}; + + BytecodeBuilder::default() + .mstore(0x0, data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(1_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(0_u64) // gas: none requested, the stipend is all the call holds + .append(CALL) + // memory[0..32] = the call's status + .push_number(0_u64) + .append(MSTORE) + // memory[32..] = the return data + .append(RETURNDATASIZE) + .push_number(0_u64) + .push_number(32_u64) + .append(RETURNDATACOPY) + .append(RETURNDATASIZE) + .push_number(32_u64) + .append(ADD) + .push_number(0_u64) + .append(RETURN) + .build() +} + +/// The database of the unfunded value-hint cases: a contract with the code of +/// [`unfunded_value_hint_call`] and no balance. +fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { + system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) +} + +/// A value-bearing `sendHint` whose caller cannot fund the value is intercepted before revm +/// starts the call and checks the funds: the hint is forwarded and its input counted, then the +/// call fails for the funds with empty return data and moves no value, and the Oracle's bytecode +/// never runs. +#[test] +fn test_an_unfunded_value_hint_is_forwarded_and_then_fails_for_funds() { + let data = send_hint(b"unfunded"); + let (result, hints, usage) = + run_with_oracle(unfunded_contract_db(&data), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(result.result.is_success(), "the contract survives the failed call"); + let returned = result.result.output().cloned().unwrap_or_default(); + let (status, return_data) = crate::common::split_outcome(&returned); + assert!(!status, "the call fails for funds"); + assert!(return_data.is_empty(), "with empty return data"); + assert_eq!( + hints, + vec![RecordedHint { from: CONTRACT, topic: TOPIC, data: Bytes::from_static(b"unfunded") }], + "the hint reached the service", + ); + assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its input is counted"); + assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + data.len() as u64); + let balance = + |address| result.state.get(&address).map_or(U256::ZERO, |account| account.info.balance); + assert_eq!(balance(CONTRACT), U256::ZERO, "no value moved from the caller"); + assert_eq!(balance(ORACLE_CONTRACT_ADDRESS), U256::ZERO, "and none reached the Oracle"); +} + +/// The same unfunded call under a data-size limit its input would cross is answered with the +/// stop, not with the funds failure: nothing is forwarded and nothing is counted. +#[test] +fn test_an_unfunded_value_hint_over_the_limit_is_answered_with_the_stop() { + let data = send_hint(b"unfunded"); + let limit = nested_hint(data.len() as u64) - 1; + let (outcome, hints) = run_with_oracle_under( + unfunded_contract_db(&data), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + + assert!(outcome.result.is_success(), "the contract catches the stop: {:?}", outcome.result); + let returned = outcome.result.output().cloned().unwrap_or_default(); + let (status, return_data) = crate::common::split_outcome(&returned); + assert!(!status, "the call was stopped"); + assert_eq!( + return_data, + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }.abi_encode().as_slice(), + "with the stop, not the funds failure's empty data", + ); + assert!(hints.is_empty(), "nothing is forwarded"); + assert_eq!(outcome.usage.data_size, nested_hint(0), "and nothing is counted"); + assert_eq!(outcome.limit_exceeded, None, "a stop below is no stop of the transaction"); +} + /// The bytecode refuses the value of a value-bearing call that holds gas, as before: the hint is /// forwarded and the call reports failure. #[test] From b1dd831bf0bc5dd367c8ecb4c4800076da20e9fc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:08:56 +0800 Subject: [PATCH 025/190] test(keyless): pin the arguments the contract's decoder accepts as dispatched --- .../mega-evm/src/system/keyless/dispatch.rs | 8 ++- .../mega-evm/tests/system/keyless/dispatch.rs | 65 +++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ee844e58d..ed686ab6d 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -63,8 +63,12 @@ pub(crate) struct Started { /// declare, and arguments that do not decode run the deployed bytecode and are charged nothing: a /// `keylessDeploy` call a contract makes reaches the method body and its `NotIntercepted()`, an /// undeclared selector finds no function and no fallback, so it reverts with empty data, and -/// arguments that do not decode revert with empty data in the method's own decoder. Bytes after a -/// valid encoding do not prevent the decoding. +/// arguments that do not decode revert with empty data in the method's own decoder. +/// +/// The arguments are accepted exactly when the contract's own calldata decoder for `(bytes, +/// uint256)` accepts them: a head of at least 64 bytes, an offset and a length below 2^64, and the +/// offset plus 32 plus the length within the input; no padding and no canonical offset is required, +/// and trailing bytes are allowed. /// /// The depth is tested first: every frame below the transaction's own leaves after one /// comparison. The decoded call is handed on, so the rules do not decode the arguments again. diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index 7ee7537cb..40a8eecab 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -229,6 +229,71 @@ fn test_bytes_after_a_valid_encoding_are_still_dispatched() { assert_eq!(total, KEYLESS_DEPLOY_OVERHEAD_GAS); } +/// The calldata of a `keylessDeploy` call: the selector and `words` as 32-byte words, then +/// `tail` as it is. +fn raw_call(words: &[u64], tail: &[u8]) -> Bytes { + let mut data = KEYLESS_DEPLOY.to_vec(); + for word in words { + data.extend(U256::from(*word).to_be_bytes::<32>()); + } + data.extend(tail); + Bytes::from(data) +} + +/// A call is recognised exactly when the contract's own calldata decoder for `(bytes, uint256)` +/// accepts its arguments, and that decoder asks for no padding and no canonical offset: the +/// padding of the bytes' tail cut off, an offset that points at the head's second word, which is +/// then read as the length, and an offset of zero are all recognised. Each pays the overhead and +/// reaches the rule that refuses a payload that is no signed transaction. +#[test] +fn test_arguments_the_contracts_decoder_accepts_are_dispatched() { + let cases = [ + // offset 0x40, gas limit, length 5, five bytes and none of the 27 bytes of padding + ("the tail's padding cut off", raw_call(&[0x40, 1_000_000, 5], &[0xab; 5])), + // offset 0x20 points at the second head word (3), which is read as the length of the + // three bytes after the head + ("an offset at the second head word", raw_call(&[0x20, 3], &[0xab; 3])), + // offset zero points at the first head word (0), read as an empty payload + ("an offset of zero", raw_call(&[0, 1_000_000], &[])), + ]; + for (name, data) in cases { + for gas_limit in GAS_LIMITS { + let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); + assert_eq!( + refusal(&dispatched), + KeylessDeployError::MalformedEncoding, + "{name} at {gas_limit}", + ); + let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); + assert_eq!( + [total, regular], + [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], + "{name} at {gas_limit}: recognised, so the overhead is charged", + ); + } + } +} + +/// The first of those cases one byte short of the declared length is refused by the same +/// decoder: the call is not recognised, pays no overhead, and the bytecode reverts with empty +/// data. +#[test] +fn test_a_payload_one_byte_short_of_its_declared_length_is_not_dispatched() { + let data = raw_call(&[0x40, 1_000_000, 5], &[0xab; 4]); + for gas_limit in GAS_LIMITS { + let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("the bytecode did not revert: {:?}", outcome.result); + }; + assert!(output.is_empty(), "the bytecode's decoder reverts with empty data"); + let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); + assert!( + total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, + "at {gas_limit}: paid {total} beyond a plain call, an overhead it does not owe", + ); + } +} + /// A call that carries value and whose arguments do not decode is not dispatched either: the /// bytecode runs and refuses the value itself, with the empty revert data of a non-payable /// method, and no overhead is charged. From 939d874efdd03e45352a9169942b33acf30913be Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:10:23 +0800 Subject: [PATCH 026/190] test(system): observe the first frame's gas in the value sendHint boundary test --- crates/mega-evm/tests/system/oracle.rs | 106 ++++++++++++++++++------- 1 file changed, 76 insertions(+), 30 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 870fc4e70..3c6ada677 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -14,8 +14,11 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, - context::result::ResultAndState, + context::{result::ResultAndState, CfgEnv}, + context_interface::ContextTr, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome}, primitives::TxKind, + Inspector, }; use crate::common::{ @@ -282,11 +285,59 @@ fn test_a_value_bearing_call_with_gas_forwards_its_hint_and_the_bytecode_refuses assert_eq!(usage.data_size, nested_hint(data.len() as u64)); } +/// Records the gas the first frame of the Oracle call holds: the gas limit of the call as the +/// interceptor sees it, which an inspector's `call` hook is handed before the engine decides the +/// start. +#[derive(Debug, Default)] +struct OracleCallGas { + gas_limits: Vec, +} + +impl Inspector for OracleCallGas { + fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { + if inputs.target_address == ORACLE_CONTRACT_ADDRESS { + self.gas_limits.push(inputs.gas_limit); + } + None + } +} + +/// Runs `tx` against a recording oracle environment with the calldata floor off, and returns the +/// outcome, the hints and the gas the Oracle call's frame held. +/// +/// The floor is off so that the gas limit alone decides how much gas the first frame holds: with +/// it on, a transaction of this calldata must carry a limit that leaves the first frame thousands +/// of gas unless history gas is charged beside it, which neither a deposit nor a zero byte price +/// does, and the boundary below that would be unreachable. +fn run_observing_first_frame( + db: MemoryDatabase, + tx: MegaTransaction, +) -> (MegaTransactionOutcome, Vec, u64) { + let envs = TestExternalEnvs::::new(); + let ctx = MegaContext::new_with_external_envs( + db, + MegaSpecId::SATIN, + ExternalEnvs::from(envs.clone()), + ) + .with_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN).with_disable_eip7623(true)) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(ctx).with_inspector(OracleCallGas::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let [first_frame_gas] = evm.inspector().gas_limits[..] else { + panic!("the Oracle was called once: {:?}", evm.inspector().gas_limits); + }; + (outcome, envs.recorded_hints(), first_frame_gas) +} + /// A transaction's own value call has no stipend and is judged on its first frame's whole gas: -/// one gas admits the hint, and so do the stipend's 2,300 and 2,301. The smallest gas limit that -/// does is found by search, since the first frame's gas is what the limit leaves after the -/// intrinsic and start charges, which depend on the byte prices; a legacy transaction and a -/// deposit alike. +/// none drops the hint, and one gas, the stipend's 2,300 and 2,301 admit it. A legacy transaction +/// and a deposit alike. +/// +/// The first frame's gas is what the transaction's limit leaves after the intrinsic charges, which +/// depend on the byte prices, so the limit is derived from a probe run that observes the gas the +/// frame held, and each run is held to the gas it was meant to hold. #[test] fn test_a_transactions_own_value_hint_is_admitted_on_one_gas_and_more() { let data = send_hint(b"own"); @@ -304,35 +355,30 @@ fn test_a_transactions_own_value_hint_is_admitted_on_one_gas_and_more() { tx }; type Build<'a> = &'a dyn Fn(u64) -> MegaTransaction; - let forwarded = |build: Build<'_>, gas: u64| { - // A gas limit the transaction is refused at runs nothing. - try_run_with_oracle_under(funded(), build(gas), EvmTxRuntimeLimits::no_limits()) - .is_some_and(|(_, hints)| !hints.is_empty()) - }; for (name, build) in [("legacy", &legacy as Build<'_>), ("deposit", &deposit as Build<'_>)] { - // The smallest gas limit whose first frame holds any gas at all. - let (mut low, mut high) = (21_000_u64, 30_000_000_u64); - assert!(forwarded(build, high), "{name}: a large limit forwards"); - while low < high { - let mid = low + (high - low) / 2; - if forwarded(build, mid) { - high = mid; - } else { - low = mid + 1; - } - } - let one_gas = high; - assert!(!forwarded(build, one_gas - 1), "{name}: no gas in the first frame, no hint"); - for frame_gas in [1_u64, 2_300, 2_301] { - let (outcome, hints) = run_with_oracle_under( - funded(), - build(one_gas + frame_gas - 1), - EvmTxRuntimeLimits::no_limits(), - ); + const PROBE: u64 = 1_000_000; + let (_, _, probed) = run_observing_first_frame(funded(), build(PROBE)); + let before_the_frame = PROBE - probed; + + let mut dropped_size = None; + for frame_gas in [0_u64, 1, 2_300, 2_301] { let case = format!("{name}: {frame_gas} gas"); + let (outcome, hints, held) = + run_observing_first_frame(funded(), build(before_the_frame + frame_gas)); + assert_eq!(held, frame_gas, "{case}: the first frame holds the gas it was built for"); + if frame_gas == 0 { + assert!(hints.is_empty(), "{case}: a call without gas drops the hint"); + dropped_size = Some(outcome.usage.data_size); + continue; + } assert_eq!(hints.len(), 1, "{case}: the hint reached the service"); assert_eq!(hints[0].from, CALLER, "{case}"); - assert!(outcome.usage.data_size >= data.len() as u64, "{case}: and it is counted"); + assert_eq!( + outcome.usage.data_size - dropped_size.expect("the zero-gas run came first"), + data.len() as u64, + "{case}: and exactly its input is counted beside what the transaction keeps \ + without the hint", + ); } } } From 095e9e34a118586fc7bc983cc0bb15b53af354b3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:19:19 +0800 Subject: [PATCH 027/190] fix(block): refuse an absent parent timestamp where it decides the activation rules, and decide them once per block --- AGENTS.md | 2 +- bin/mega-evme/src/block/satin.rs | 4 +- crates/mega-evm/benches/block.rs | 2 +- crates/mega-evm/src/block/executor.rs | 125 +++++++++++++++++----- crates/mega-evm/src/block/hardfork.rs | 44 ++++++++ crates/mega-evm/tests/block/activation.rs | 120 ++++++++++++++++----- crates/mega-evm/tests/block/common.rs | 13 +++ crates/mega-evm/tests/block/predeploys.rs | 8 +- docs/spec/upgrades/satin.md | 5 +- 9 files changed, 261 insertions(+), 62 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 135d30992..a292d1550 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,7 +141,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`); `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`) | +| `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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, and refusing an absent parent timestamp where the schedule activates a fork after genesis that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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`) | diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index b3d07bcb5..67fc271dc 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -149,7 +149,7 @@ pub(super) fn execute( /// its parent came ([`admits_only_deposits`]). pub(super) fn needs_parent_timestamp(chain_id: u64, timestamp: u64) -> Result { let hardforks = satin_schedule(chain_id, timestamp)?; - Ok(hardforks.admits_only_deposits(0, timestamp)) + Ok(hardforks.activation_depends_on_parent(timestamp)) } /// Whether block `number`, at `timestamp`, admits only deposits under `hardforks`, as a node works @@ -169,7 +169,7 @@ fn admits_only_deposits( ) -> Result { match parent_timestamp { Some(parent_timestamp) => Ok(hardforks.admits_only_deposits(parent_timestamp, timestamp)), - None if !hardforks.admits_only_deposits(0, timestamp) => Ok(false), + None if !hardforks.activation_depends_on_parent(timestamp) => Ok(false), None => Err(EvmeError::Other(format!( "block {number}: a fork its schedule activates is active at its timestamp, and \ whether the fork activates in this block depends on its parent's timestamp, which \ diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 6f40bbd4b..67e9b24ed 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -182,7 +182,7 @@ fn block_ctx() -> MegaBlockExecutionCtx { Some(PARENT_BEACON_ROOT), Bytes::new(), BlockLimits::default(), - None, + Some(BLOCK_TIMESTAMP - 1), ) } diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index d2669565c..881aff642 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -17,8 +17,10 @@ //! - **An activation block admits only deposits.** The executor works out whether a fork activates //! in the block from the chain's schedule ([`MegaHardforks::admits_only_deposits`]), the block's //! own timestamp and the parent's, which the caller supplies with -//! [`MegaBlockExecutionCtx::parent_timestamp`]. A user transaction in such a block is refused -//! before it executes. This mirrors alloy-op-evm's rule of the same name. +//! [`MegaBlockExecutionCtx::parent_timestamp`]. Both rules are decided once, when the executor is +//! built. A user transaction in such a block is refused before it executes. This mirrors +//! alloy-op-evm's rule of the same name. A block with a parent whose timestamp the caller leaves +//! out is refused where the omission could change the answer. //! - **The data-availability footprint is a block limit.** Each non-deposit transaction's footprint //! is its compressed size times the footprint gas scalar the L1 block contract holds, accumulated //! against the block's gas limit and reported as the block's blob gas used. With no scalar in @@ -156,8 +158,11 @@ pub struct MegaBlockExecutionCtx { /// does, which makes the pre-block step check the system contracts and the EIP-7997 factory. /// The executor works both out itself. /// - /// `None` is a block with no parent to compare against, such as a genesis block: neither - /// rule applies to it. A caller that executes a block with a parent must supply it. + /// `None` is a block with no parent to compare against, such as a genesis block, and neither + /// rule applies to it. It is accepted only where no parent could change that: when every fork + /// the schedule activates is active from genesis. Where one could, executing the block fails + /// with [`MegaBlockExecutionError::MissingParentTimestamp`], since the block would otherwise + /// run as an ordinary one. A caller that executes a block with a parent must supply it. pub parent_timestamp: Option, /// The builder's packing policy: the limits only a builder applies, and a cap on the block's /// data-size budget below the protocol's ([`BlockLimits`]). @@ -171,8 +176,9 @@ impl MegaBlockExecutionCtx { /// A context for a block whose parent block is at `parent_timestamp`. /// /// `None` is a block with no parent to compare against, such as a genesis block: neither - /// activation-block rule applies to it. A block that has a parent must pass its timestamp, - /// since a block executed without it silently skips both rules. + /// activation-block rule applies to it. A block that has a parent must pass its timestamp: + /// where the schedule activates a fork after genesis, executing the block without it fails + /// with [`MegaBlockExecutionError::MissingParentTimestamp`]. pub const fn new( parent_hash: B256, parent_beacon_block_root: Option, @@ -189,6 +195,17 @@ impl MegaBlockExecutionCtx { pub enum MegaBlockExecutionError { /// A block that activates a fork carries a transaction that is not a deposit. UnexpectedNonDepositTxInActivationBlock, + /// The context names no parent timestamp for a block whose activation rules depend on it: a + /// fork the schedule activates after genesis is active at the block, and whether it activates + /// in this block, which makes the block deposit-only and, for Satin, makes the pre-block step + /// check the predeploys, is decided by the parent's timestamp. + /// + /// The caller's omission, not a verdict on the block: an internal error. Executing the block + /// without the timestamp would run it as an ordinary block. + MissingParentTimestamp { + /// The block's own timestamp. + block_timestamp: u64, + }, /// A transaction's data-availability footprint does not fit in what the block has left. TransactionDaFootprintAboveGasLimit { /// The footprint of the transaction that does not fit. @@ -234,6 +251,12 @@ impl fmt::Display for MegaBlockExecutionError { Self::UnexpectedNonDepositTxInActivationBlock => { f.write_str("unexpected non-deposit transaction in fork activation block") } + Self::MissingParentTimestamp { block_timestamp } => write!( + f, + "the parent block's timestamp is missing: a fork the schedule activates after \ + genesis is active at the block's timestamp {block_timestamp}, and whether it \ + activates in this block depends on the parent's timestamp" + ), Self::TransactionDaFootprintAboveGasLimit { transaction_da_footprint, available_block_da_footprint, @@ -262,12 +285,13 @@ impl core::error::Error for MegaBlockExecutionError {} impl From for BlockExecutionError { /// 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. + /// let go stale and a parent timestamp the caller left out say 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::StaleOutcome { .. } => Self::other(error), + MegaBlockExecutionError::StaleOutcome { .. } | + MegaBlockExecutionError::MissingParentTimestamp { .. } => Self::other(error), MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | MegaBlockExecutionError::UnexpectedSystemContractCode { .. } | @@ -296,6 +320,19 @@ pub struct MegaBlockExecutor { limiter: BlockLimiter, /// The limits the protocol holds this block to: the spec's. protocol_limits: ProtocolLimits, + /// Which activation rules apply to this block, decided once when the block starts, or why + /// they cannot be decided. + activation: Result, +} + +/// The two rules a fork's activation puts on a block, decided from the schedule, the block's +/// timestamp and its parent's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct ActivationRules { + /// A fork activates in the block, so it admits only deposits. + admits_only_deposits: bool, + /// Satin activates in the block, so the pre-block step checks the predeploys. + satin_activation_block: bool, } impl MegaBlockExecutor { @@ -351,10 +388,47 @@ where receipt_builder: R, ) -> Self { let block_gas_limit = evm.ctx().block().gas_limit(); + let block_timestamp = evm.ctx().block().timestamp().saturating_to(); let protocol_limits = ProtocolLimits::for_spec(evm.ctx().spec()); evm.set_tx_runtime_limits(protocol_limits.tx_runtime_limits); let limiter = BlockLimiter::new(ctx.block_limits.within(&protocol_limits), block_gas_limit); - Self { spec, receipt_builder, ctx, evm, receipts: Vec::new(), limiter, protocol_limits } + let activation = Self::activation_rules(&spec, ctx.parent_timestamp, block_timestamp); + Self { + spec, + receipt_builder, + ctx, + evm, + receipts: Vec::new(), + limiter, + protocol_limits, + activation, + } + } + + /// The activation rules of the block at `block_timestamp` whose parent is at + /// `parent_timestamp`, decided once for the block. + /// + /// Without the parent's timestamp the rules are known only where no parent could change + /// them: no fork the schedule activates after genesis is active at the block + /// ([`MegaHardforks::activation_depends_on_parent`]), so neither rule applies. That is a block + /// with no parent, such as a genesis block, or a chain whose forks are all active from the + /// start. Any other block is refused with [`MegaBlockExecutionError::MissingParentTimestamp`], + /// since running it as an ordinary block would silently skip both rules. + fn activation_rules( + spec: &Spec, + parent_timestamp: Option, + block_timestamp: u64, + ) -> Result { + match parent_timestamp { + Some(parent) => Ok(ActivationRules { + admits_only_deposits: spec.admits_only_deposits(parent, block_timestamp), + satin_activation_block: spec.is_satin_activation_block(parent, block_timestamp), + }), + None if !spec.activation_depends_on_parent(block_timestamp) => { + Ok(ActivationRules { admits_only_deposits: false, satin_activation_block: false }) + } + None => Err(MegaBlockExecutionError::MissingParentTimestamp { block_timestamp }), + } } /// The limits the protocol holds this block to: the spec's @@ -366,27 +440,19 @@ where /// Whether this block admits only deposit transactions because a fork activates in it: a /// fork of the schedule is active at the block's timestamp and not at its parent's. /// - /// `false` when the context carries no parent timestamp. - pub fn admits_only_deposits(&self) -> bool { - self.ctx - .parent_timestamp - .is_some_and(|parent| self.spec.admits_only_deposits(parent, self.block_timestamp())) + /// `false` when the context carries no parent timestamp and no parent could change the answer, + /// and [`MegaBlockExecutionError::MissingParentTimestamp`] when one could. + pub fn admits_only_deposits(&self) -> Result { + self.activation.clone().map(|rules| rules.admits_only_deposits) } /// Whether Satin activates in this block, which makes the pre-block step check the system /// contracts and the EIP-7997 factory. /// /// The two answers differ: an Optimism fork at or after Jovian also makes a block - /// deposit-only. `false` when the context carries no parent timestamp. - pub fn is_satin_activation_block(&self) -> bool { - self.ctx.parent_timestamp.is_some_and(|parent| { - self.spec.is_satin_activation_block(parent, self.block_timestamp()) - }) - } - - /// The block's own timestamp, from its environment. - fn block_timestamp(&self) -> u64 { - self.evm.ctx().block().timestamp().saturating_to() + /// deposit-only. Decided as [`admits_only_deposits`](Self::admits_only_deposits) is. + pub fn is_satin_activation_block(&self) -> Result { + self.activation.clone().map(|rules| rules.satin_activation_block) } /// Holds this block to `limits` in place of the spec's: a counterfactual of a tool's or a @@ -638,6 +704,9 @@ 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> { + // A block whose activation rules cannot be decided is refused before anything runs. + self.admits_only_deposits()?; + // 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(); @@ -663,7 +732,7 @@ where // The EIP-2935 / EIP-4788 calls above do not depend on these predeploys: they target // their own contracts, not the MegaETH system addresses or the factory. - if self.is_satin_activation_block() { + if self.is_satin_activation_block()? { for spec in system_contract_specs() { let state = check_system_contract(self.evm.db_mut(), &spec).map_err( @@ -907,7 +976,7 @@ where // A block that activates a fork carries the chain's own transactions only, so a user // transaction in it is refused before anything runs. - if self.admits_only_deposits() && !is_deposit { + if self.admits_only_deposits()? && !is_deposit { return Err(MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock.into()); } diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 13dc8cfb7..3e2c10c81 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -124,6 +124,19 @@ pub trait MegaHardforks: OpHardforks { }) || self.is_no_user_tx_activation_block(parent_timestamp, block_timestamp) } + /// Whether the answers of [`admits_only_deposits`](Self::admits_only_deposits) and + /// [`is_satin_activation_block`](Self::is_satin_activation_block) for a block at + /// `block_timestamp` can depend on its parent's timestamp. + /// + /// They cannot when every fork the schedule activates and the block has is active from + /// timestamp 0, or when none is active at the block: a fork activates in a block only if it + /// is active at the block and not at its parent, and activation is monotone in the timestamp, + /// so the answers are `false` for every parent. Otherwise a caller that does not know the + /// parent's timestamp cannot tell whether a fork activates in the block. + fn activation_depends_on_parent(&self, block_timestamp: u64) -> bool { + self.admits_only_deposits(0, block_timestamp) + } + /// Checks that this schedule is one a chain can run, so a configuration mistake is caught /// when the chain configuration is loaded rather than at the fork's first block. /// @@ -497,6 +510,37 @@ mod tests { assert!(!config.admits_only_deposits(100, 101), "and not once the parent had it too"); } + /// The answers depend on the parent's timestamp exactly when a fork the schedule activates + /// after genesis is active at the block; for any parent the answers are then both possible. + /// Otherwise both are `false` whatever the parent. + #[test] + fn test_the_activation_answers_depend_on_the_parent_only_after_a_late_fork() { + let satin_at = |timestamp| { + MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(timestamp)) + }; + let late = satin_at(100); + assert!(late.activation_depends_on_parent(100), "active at the block, not at genesis"); + assert!(late.activation_depends_on_parent(500), "and after a gap"); + assert!(!late.activation_depends_on_parent(99), "not active at the block yet"); + assert!(!satin_at(0).activation_depends_on_parent(500), "Satin from genesis"); + assert!(!MegaHardforkConfig::default().activation_depends_on_parent(500), "no Satin"); + let jovian_late = satin_at(0).with(OpHardfork::Jovian, ForkCondition::Timestamp(100)); + assert!(jovian_late.activation_depends_on_parent(100), "an Optimism fork counts too"); + + // Whatever the parent, a schedule that does not depend on it answers `false`. + for config in [late.clone(), satin_at(0), MegaHardforkConfig::default()] { + for block in [1, 99, 100, 500] { + if !config.activation_depends_on_parent(block) { + for parent in 0..=block { + assert!(!config.admits_only_deposits(parent, block)); + assert!(!config.is_satin_activation_block(parent, block)); + } + } + } + } + } + /// Satin's activation block is the block at which Satin is active and at whose parent it is /// not: the first block at the activation, and the first after a gap over it; not the block /// after it, nor any block of a chain with Satin from genesis or without Satin. An Optimism diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs index ff908c000..6a411630b 100644 --- a/crates/mega-evm/tests/block/activation.rs +++ b/crates/mega-evm/tests/block/activation.rs @@ -12,9 +12,11 @@ use alloy_hardforks::{EthereumHardfork, ForkCondition}; use alloy_op_hardforks::OpHardfork; use alloy_primitives::{Bytes, B256, U256}; use mega_evm::{ - system::SYSTEM_CONTRACT_COUNT, test_utils::CommittedStates, BlockLimits, MegaBlockExecutionCtx, - MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, + system::SYSTEM_CONTRACT_COUNT, + test_utils::{CommittedStates, MemoryDatabase}, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, }; +use revm::{context::ContextSetters, context_interface::ContextTr, database::State}; use crate::common::{ self, block_ctx, deposit_tx, empty_call_gas, executor_with_env_and_spec, user_tx, @@ -229,34 +231,102 @@ fn test_a_node_context_checks_the_predeploys_where_satin_activates() { } } -/// [S1] [S18] A context that names no parent timestamp is a block with no parent to compare -/// against, such as a genesis block: neither rule applies to it, however the schedule places the -/// block's own timestamp. The same block with the parent named is the activation block, so the -/// absence is the context's own answer and not an effect of the schedule. +/// The `MegaBlockExecutionError` an internal error carries. +fn internal(error: &BlockExecutionError) -> Option<&MegaBlockExecutionError> { + error.as_internal().and_then(|error| error.downcast_other::()) +} + +/// An executor for the block at `timestamp` on the chain `spec` describes, whose context names +/// `parent_timestamp`. +fn executor_at<'a>( + state: &'a mut State, + spec: MegaHardforkConfig, + parent_timestamp: Option, + timestamp: u64, +) -> common::TestExecutor<'a> { + let mut env = common::evm_env(); + env.block_env.timestamp = U256::from(timestamp); + let mut ctx = block_ctx(BlockLimits::no_limits()); + ctx.parent_timestamp = parent_timestamp; + executor_with_env_and_spec(state, ctx, env, spec) +} + +/// A context that names no parent timestamp, for a block in which a fork the schedule activates +/// after genesis is active, cannot be told from a block that has a parent: whether the fork +/// activates in it depends on the parent. Executing such a block is refused with a typed error, +/// by the block's start, by every transaction and by both rules, instead of running the block as +/// an ordinary one. The same block with the parent named is the activation block. /// -/// Expected values: independent (the schedule's own timestamps and the documented default). +/// Expected values: independent (the schedule's own timestamps and the documented refusal). #[test] -fn test_an_absent_parent_timestamp_applies_neither_activation_rule() { +fn test_an_absent_parent_timestamp_is_refused_where_it_could_change_the_answer() { let at = ACTIVATION; - let mut env = common::evm_env(); - env.block_env.timestamp = U256::from(at); - let run = |ctx: MegaBlockExecutionCtx| { - let mut state = common::state(); - let committed = CommittedStates::install(&mut state); - let mut executor = executor_with_env_and_spec(&mut state, ctx, env.clone(), schedule(at)); - let (only_deposits, satin) = - (executor.admits_only_deposits(), executor.is_satin_activation_block()); - executor.apply_pre_execution_changes().expect("the block starts"); - let checked = committed.states().iter().filter(|s| common::is_predeploy_check(s)).count(); - (only_deposits, satin, checked) - }; + let missing = MegaBlockExecutionError::MissingParentTimestamp { block_timestamp: at }; + + let mut state = common::state(); + let mut executor = executor_at(&mut state, schedule(at), None, at); + assert_eq!(executor.admits_only_deposits(), Err(missing.clone())); + assert_eq!(executor.is_satin_activation_block(), Err(missing.clone())); + let error = executor.apply_pre_execution_changes().expect_err("the block does not start"); + assert_eq!(internal(&error), Some(&missing), "an internal error: the caller's omission"); + let error = executor + .execute_transaction(&deposit_tx(Bytes::new(), empty_call_gas())) + .expect_err("not even a deposit runs"); + assert_eq!(internal(&error), Some(&missing)); - let absent = block_ctx(BlockLimits::no_limits()); - assert_eq!(absent.parent_timestamp, None, "the helper names no parent"); - assert_eq!(run(absent), (false, false, 0), "no parent: neither rule"); + let mut state = common::state(); + let executor = executor_at(&mut state, schedule(at), Some(at - 1), at); assert_eq!( - run(node_ctx(at - 1)), - (true, true, SYSTEM_CONTRACT_COUNT), + (executor.admits_only_deposits(), executor.is_satin_activation_block()), + (Ok(true), Ok(true)), "the same block with its parent named is the activation block" ); } + +/// A context that names no parent timestamp is accepted where no parent could change the answer, +/// and then neither rule applies: a schedule whose forks are all active from genesis, a schedule +/// with no `MegaETH` fork, and a block before the fork's activation. The block runs a user +/// transaction. +/// +/// Expected values: independent (the schedule's own timestamps and the rule's clauses). +#[test] +fn test_an_absent_parent_timestamp_is_accepted_where_no_parent_could_change_the_answer() { + let at = ACTIVATION; + let cases = [ + ("Satin from genesis", schedule(0), at), + ("no MegaETH fork", MegaHardforkConfig::default(), at), + ("a block before the activation", schedule(at), at - 1), + ]; + for (name, spec, timestamp) in cases { + let mut state = common::state(); + let mut executor = executor_at(&mut state, spec, None, timestamp); + assert_eq!(executor.admits_only_deposits(), Ok(false), "{name}"); + assert_eq!(executor.is_satin_activation_block(), Ok(false), "{name}"); + executor.apply_pre_execution_changes().unwrap_or_else(|e| panic!("{name}: starts: {e}")); + executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .unwrap_or_else(|e| panic!("{name}: a user transaction runs: {e}")); + } +} + +/// Both rules are decided when the block starts and not again for each transaction: moving the +/// block environment's timestamp after the executor was built changes neither answer, and the +/// transactions after it are held to the rule the block began with. +/// +/// Expected values: independent (the schedule's own timestamps). +#[test] +fn test_the_activation_rules_are_decided_once_for_the_block() { + let at = ACTIVATION; + let mut state = common::state(); + let mut executor = executor_at(&mut state, schedule(at), Some(at - 1), at); + let mut block = executor.evm().ctx().block().clone(); + block.timestamp = U256::from(at + 1_000); + executor.evm_mut().ctx_mut().set_block(block); + assert_eq!(executor.admits_only_deposits(), Ok(true), "decided for the timestamp it began at"); + assert_eq!(executor.is_satin_activation_block(), Ok(true)); + executor.apply_pre_execution_changes().expect("the block starts"); + let error = executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("a user transaction is still refused"); + assert!(is_activation_refusal(&error), "{error}"); +} diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index ddc54a912..0a473469f 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -138,6 +138,19 @@ pub(crate) fn activation_ctx() -> MegaBlockExecutionCtx { ) } +/// The context of a block that follows the activation block under [`activation_spec`]: its parent +/// is at [`BLOCK_TIMESTAMP`], where Satin is already active, so the block is an ordinary one that +/// admits user transactions and checks no predeploy. +pub(crate) fn after_activation_ctx() -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + Some(BLOCK_TIMESTAMP), + ) +} + /// The loosest limits a block could be held to while a read of volatile data still detains: /// every limit unlimited, and gas detention's caps one below the most compute a transaction can /// spend, which no transaction of a block this size reaches. For a test that holds a block to diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 4675448f2..0812579e5 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -23,8 +23,8 @@ use revm::{ }; use crate::common::{ - self, activation_ctx, activation_spec, executor_with_spec, named_accounts, recovered, tx, - unlimited_ctx, + self, activation_ctx, activation_spec, after_activation_ctx, executor_with_spec, + named_accounts, recovered, tx, unlimited_ctx, }; /// The states the pre-block steps of a block over `state` held to `ctx` committed, in order, as a @@ -89,7 +89,7 @@ fn test_the_activation_block_reads_the_seven_predeploys_once() { let l1_block = &activation[3 + held.len()][&L1_BLOCK_CONTRACT]; assert!(!l1_block.is_touched() && !l1_block.is_created(), "the L1 block info is read only"); - let next = start(&mut state, unlimited_ctx()).expect("the next block starts"); + let next = start(&mut state, after_activation_ctx()).expect("the next block starts"); assert_eq!(named_accounts(&next), expected_accounts(false), "no other block reads them"); for (address, info, _) in held { let now = revm::Database::basic(&mut state, address).unwrap().expect("still there"); @@ -124,7 +124,7 @@ fn test_no_other_block_reads_a_predeploy() { ) .apply_pre_execution_changes() }; - start_on(unlimited_ctx()).expect("an ordinary block reads no predeploy"); + start_on(after_activation_ctx()).expect("an ordinary block reads no predeploy"); let error = start_on(activation_ctx()).expect_err("the activation block reads the Oracle"); assert!(matches!(error, BlockExecutionError::Internal(_)), "{error:?}"); assert!(error.to_string().contains("injected basic() error"), "{error}"); diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 74099f13e..fd103f647 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1522,8 +1522,11 @@ A node, a stateless validator and a replay tool must agree on everything below, Neither is an input a caller can omit or set: the caller supplies the parent block's timestamp, and nothing else. A block admits only deposits when a MegaETH fork, Satin itself, or an Optimism fork at or after Jovian in the Optimism fork order, is active at the block's timestamp and not at the parent's (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)); a user transaction in such a block is refused before it runs. A block builder and a validator MUST give block execution the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates, and a stateless validator is given the parent block's timestamp beside the witness. + Both are decided once, when the block starts. A block with no parent, such as a genesis block, is executed with an explicit absence of the parent timestamp: block execution applies neither rule to it. - A block that has a parent and is executed without its timestamp therefore runs as one that admits non-deposit transactions, so an implementation MUST supply it for every block but the first. + It accepts the absence only where no parent could change that, which is where every fork the schedule activates is active from genesis, or none is active at the block yet. + Where a fork the schedule activates after genesis is active at the block, whether it activates in the block depends on the parent's timestamp, and block execution refuses the block with an error that names the missing timestamp instead of running it as one that admits non-deposit transactions. + An implementation MUST therefore supply the parent timestamp for every block that has a parent, the block right after genesis included, since that block can be the activation block. Satin's activation block is told apart from the other deposit-only blocks, since an Optimism fork's activation block admits only deposits too: only Satin's makes the pre-block step check the predeploys (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). A block that is not Satin's activation block checks no predeploy, and runs on a state that may lack them. - **The L1 block information.** From 8d82269c950934c2f909bb4620222c062bc5ed46 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:21:50 +0800 Subject: [PATCH 028/190] docs: SLOTNUM pushes zero, and a deposit can write the Oracle in Satin's activation block; the byte-price grid runs as shards --- AGENTS.md | 4 ++-- crates/mega-evm/README.md | 2 +- crates/mega-evm/tests/fuzz/gen/world.rs | 3 ++- docs/spec/upgrades/satin.md | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a292d1550..84cbadb63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,7 +169,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 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. + `SLOTNUM` pushes zero whatever `BlockEnv::slot_num` holds; the read is still a volatile one, marked for detention and refused where volatile access is off. - 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 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. @@ -629,7 +629,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te A fixture entry the engine rejects has no returned state to build the channel witness from, and replays on the record alone. The block tests cover each mechanism that reads, in the `test` job; `exec-spec-satin.yml` replays every Osaka and Amsterdam entry of the fixture releases in both modes and fails on any entry that does not replay, counting the entries replayed on both witnesses apart from the rejected ones. The fixture test is always ignored by default: it runs only with `-- --ignored` (or `--include-ignored`) and `MEGA_STATE_TEST_FIXTURES` set to the fixtures, and setting the variable alone runs nothing. -- **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, the whole grid on every pull request and on dispatch (`--pr`, five points, is the quick local mode). +- **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, the whole grid, as four parallel shards, on every pull request that changes more than documentation and on dispatch (`--pr`, five points, is the quick local mode). The prices are provisional, so a test holds at any of them — a byte price of nothing, or one gas per byte up to the grid's dearest point: it sizes its gas from the schedule at the prices in effect, and a case whose scenario is state or history gas returns early where that byte costs nothing (`state_is_free`, `history_is_free`). Below one gas per byte the schedule's entries round to nothing one at a time, and no test is held there. Each guard leaves a note (`test_utils::note_price_guard`), and the grid reports per point how many tests were guarded beside how many passed. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 72c0251e4..69bf1d6c2 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -30,7 +30,7 @@ A call or creation forwards at most `remaining − remaining × 2 / 100` of its 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. -`SLOTNUM` pushes the slot number the node supplies in `BlockEnv::slot_num`, zero when it leaves it unset. +`SLOTNUM` pushes zero whatever `BlockEnv::slot_num` holds; the read is still a volatile one, marked for detention and refused where volatile access is off. Satin takes EIP-7708 from Amsterdam too: every value movement — a 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` into the receipt, in execution order among the contracts' own logs. A deposit's value is logged and its mint is not, and a destruction to itself burns the balance without a log. Its byte prices are an input: the `satin-price-override` feature, off by default, lets a measurement build install other ones. diff --git a/crates/mega-evm/tests/fuzz/gen/world.rs b/crates/mega-evm/tests/fuzz/gen/world.rs index 215ec26a7..f58426142 100644 --- a/crates/mega-evm/tests/fuzz/gen/world.rs +++ b/crates/mega-evm/tests/fuzz/gen/world.rs @@ -299,7 +299,8 @@ pub(crate) fn limits() -> impl Strategy { pub(crate) struct BlockShape { /// The base fee: zero, or seven, which a free transaction is refused under. pub(crate) basefee: u64, - /// The slot number `SLOTNUM` reads, zero for a block that leaves it unset. + /// The block environment's slot number, which `SLOTNUM` ignores: it pushes zero whatever this + /// holds. pub(crate) slot_num: u64, /// Whether the block carries a blob price; one that does not refuses every transaction but a /// deposit on its header. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index fd103f647..cc04c1609 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -80,7 +80,7 @@ The changes, in the order this page records them: - A block in which Satin activates, or in which an Optimism fork at or after Jovian in the Optimism fork order activates, MUST contain only deposit transactions; a non-deposit transaction in it makes the block invalid. A fork activates in a block when it is active at the block's timestamp and not at the parent block's, as the chain configuration schedules it; a fork the configuration does not schedule never activates. The rule covers Jovian, Karst and every later Optimism fork the chain configuration schedules. - A Mega System Transaction is a legacy transaction, so it is refused in such a block too, and the Satin activation block owes none: nothing writes the [Oracle](#16-oracle-storage-reads-and-hints) in it, because the only transactions the block admits are deposits, and a deposit from the system address is a failed deposit that runs no call (see [The Live System Address](#17-the-live-system-address)). + A Mega System Transaction is a legacy transaction, so it is refused in such a block too, and the Satin activation block owes none. A deposit from the system address is a failed deposit that runs no call (see [The Live System Address](#17-the-live-system-address)), but a deposit can still write the [Oracle](#16-oracle-storage-reads-and-hints) in that block through code running at the live system address, a contract or an EIP-7702 delegator, because the Oracle tests only its immediate caller. Nor does any Oracle read in that block ask the oracle service, since a deposit asks it nothing: every read pushes the slot's value on the chain. - Each non-deposit transaction's data-availability footprint — its compressed size times the footprint gas scalar held by the L1 block contract — MUST accumulate against the block's gas limit, and the block MUST report the sum as its blob gas used. A transaction whose footprint does not fit in what the block has left MUST NOT be included. From c34010a147bebc5087943dddfc0c429915b52257 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:21:50 +0800 Subject: [PATCH 029/190] ci: shard the byte-price grid, skip documentation-only pull requests, report from an always-running job --- .github/workflows/fuzz.yml | 86 ++++++++++++++++++++++++++-- .github/workflows/price-grid.yml | 96 +++++++++++++++++++++++++++++--- REVIEW.md | 7 ++- scripts/price_grid.sh | 62 +++++++++++++++++++-- scripts/pull_request_needs_ci.sh | 45 +++++++++++++++ 5 files changed, 277 insertions(+), 19 deletions(-) create mode 100755 scripts/pull_request_needs_ci.sh diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index afe35f6d6..b52b86666 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -13,8 +13,19 @@ name: Randomized tests, long mode # Every pull request runs all of it, and so does a dispatch. There is no schedule and no dispatch # alone: GitHub fires a scheduled workflow only from the default branch, and accepts a dispatch # only for a workflow the default branch has, which has no such workflow, so a run triggered either -# way ran nowhere on the Satin integration branch. There is no path filter either, so a change to -# the engine, a generator or a property all run it. +# way ran nowhere on the Satin integration branch. There is no path filter on the trigger, which +# would leave a required check pending; a pull request that changes documentation alone is skipped +# by the `changes` job instead (every changed file under docs/ or a Markdown file outside crates/ +# and bin/, scripts/pull_request_needs_ci.sh), and any other change runs everything. The `long +# mode` job always runs and reports: it passes when both jobs below passed, or when the run was +# skipped. +# +# The debug and release runs are separate jobs of a matrix and run in parallel, beside the price +# comparison. Timeouts are projections from local runs scaled by 3.7, the ratio of a GitHub runner +# to the local machine seen on the byte-price grid: the debug run takes 400 s locally, about 25 +# minutes there, plus a cold build; the release run 120 s, about 8 minutes; the price comparison is +# under a minute locally after a release build, a few minutes there. The 60-minute limit on the +# properties is about twice the debug projection; none is measured on a runner at this seed. # # The two inputs of a dispatch, and how they meet the long mode: # @@ -50,8 +61,44 @@ concurrency: cancel-in-progress: true jobs: + changes: + name: changes that need the run + runs-on: ubuntu-24.04 + timeout-minutes: 10 + outputs: + run: ${{ steps.diff.outputs.run }} + steps: + - uses: actions/checkout@v4 + if: github.event_name == 'pull_request' + with: + # The merge commit and its parents; the first parent is the base it merges into. + fetch-depth: 2 + persist-credentials: false + + - name: Skip a pull request that changes documentation alone + id: diff + env: + EVENT: ${{ github.event_name }} + run: | + set -euo pipefail + if [ "$EVENT" != pull_request ]; then + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then + echo "::warning::HEAD is not the pull request's merge commit; running" + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # The allowlist is in the script: only docs/ and Markdown outside crates/ and bin/ skip. + run=$(scripts/pull_request_needs_ci.sh HEAD^1 HEAD) + echo "runs: $run" + echo "run=$run" >> "$GITHUB_OUTPUT" + seed: name: the run's seed + needs: changes + if: needs.changes.outputs.run == 'true' runs-on: ubuntu-24.04 timeout-minutes: 5 outputs: @@ -71,9 +118,7 @@ jobs: name: long mode (${{ matrix.profile }}) needs: seed runs-on: ubuntu-24.04 - # Measured locally at one seed on a warm machine: the release run takes 2 minutes and the debug - # run 7 (400 s), each after a build of a minute or less. A runner three times slower with a cold - # build (about 15 minutes) still finishes within 40 minutes. + # See the header: about 25 minutes projected for debug, 8 for release. timeout-minutes: 60 strategy: fail-fast: false @@ -107,7 +152,7 @@ jobs: name: state and history gas along the byte prices needs: seed runs-on: ubuntu-24.04 - # Measured locally: the three runs take under a minute after the build, which is the cost. + # See the header: the three runs take under a minute locally after the build. timeout-minutes: 45 steps: - uses: actions/checkout@v4 @@ -136,3 +181,32 @@ jobs: - name: Compare the records run: python3 scripts/fuzz_price_monotonic.py target/price-low.txt target/price-high.txt + + gate: + name: long mode + needs: [changes, long, price-monotonicity] + # Always, a cancelled run included: a required check that is skipped counts as passed. + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Report the outcome + env: + CHANGES: ${{ needs.changes.result }} + RUN: ${{ needs.changes.outputs.run }} + LONG: ${{ needs.long.result }} + PRICE: ${{ needs.price-monotonicity.result }} + run: | + if [ "$CHANGES" != success ]; then + echo "::error::could not tell whether the run was needed: the changes job ended $CHANGES" + exit 1 + fi + if [ "$RUN" != true ]; then + echo "only documentation changed; the run was skipped" + exit 0 + fi + if [ "$LONG" != success ] || [ "$PRICE" != success ]; then + echo "::error::the run ended: long mode $LONG, price comparison $PRICE" + exit 1 + fi + echo "passed" diff --git a/.github/workflows/price-grid.yml b/.github/workflows/price-grid.yml index 8ac0656d5..96cb9e4d0 100644 --- a/.github/workflows/price-grid.yml +++ b/.github/workflows/price-grid.yml @@ -11,6 +11,22 @@ name: Byte-price grid # default branch, which has no such workflow, so a nightly full grid ran nowhere and points outside # the five of the quick mode (scripts/price_grid.sh --pr, kept for local use) went unchecked. # +# The grid runs as four parallel shards of `scripts/price_grid.sh --full --shard I/4`, which together +# cover the 73 points exactly once; the point list lives in the script alone. +# +# A pull request that changes documentation alone skips the run: every changed file must be under +# docs/ or be a Markdown file outside crates/ and bin/ (scripts/pull_request_needs_ci.sh), and any +# other change runs it. The `byte-price grid` job always runs and reports: it passes when every +# shard passed, or when the run was skipped, so the check a branch rule can require is never left +# pending by a skipped run. +# +# Timeouts. The one measurement on a GitHub runner is run 40804560952 of the five-point mode on +# ubuntu-24.04: 53 to 57 seconds per point and 2 min 11 s to build with a warm cache. A shard has +# 18 or 19 points, so about 17 minutes of tests at that rate, and a cold build is a few minutes +# more: about 25 to 30 minutes projected. The 60-minute limit is about twice that projection. It +# is a projection, not a measurement of a full shard: a suite that grows by half again, or a +# runner twice as slow as that run, still fits; a suite twice as large does not. +# # The run at the constants is the `test` job of build-and-test.yml. on: @@ -25,12 +41,50 @@ concurrency: cancel-in-progress: true jobs: + changes: + name: changes that need the run + runs-on: ubuntu-24.04 + timeout-minutes: 10 + outputs: + run: ${{ steps.diff.outputs.run }} + steps: + - uses: actions/checkout@v4 + if: github.event_name == 'pull_request' + with: + # The merge commit and its parents; the first parent is the base it merges into. + fetch-depth: 2 + persist-credentials: false + + - name: Skip a pull request that changes documentation alone + id: diff + env: + EVENT: ${{ github.event_name }} + run: | + set -euo pipefail + if [ "$EVENT" != pull_request ]; then + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then + echo "::warning::HEAD is not the pull request's merge commit; running" + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # The allowlist is in the script: only docs/ and Markdown outside crates/ and bin/ skip. + run=$(scripts/pull_request_needs_ci.sh HEAD^1 HEAD) + echo "runs: $run" + echo "run=$run" >> "$GITHUB_OUTPUT" + price-grid: - name: byte-price grid + name: byte-price grid shard ${{ matrix.shard }}/4 + needs: changes + if: needs.changes.outputs.run == 'true' runs-on: ubuntu-24.04 - # The full grid runs the suite 73 times: about 16 minutes on a warm local machine, so the build - # and a slower runner fit well within the limit. - timeout-minutes: 90 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v4 with: @@ -42,13 +96,41 @@ jobs: - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 - - name: Run the suite at each point - run: scripts/price_grid.sh --full + - name: Run the suite at this shard's points + run: scripts/price_grid.sh --full --shard ${{ matrix.shard }}/4 - name: Upload the logs of a failing run if: failure() uses: actions/upload-artifact@v4 with: - name: price-grid-logs + name: price-grid-logs-${{ matrix.shard }} path: target/price-grid/ retention-days: 7 + + gate: + name: byte-price grid + needs: [changes, price-grid] + # Always, a cancelled run included: a required check that is skipped counts as passed. + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Report the outcome + env: + CHANGES: ${{ needs.changes.result }} + RUN: ${{ needs.changes.outputs.run }} + RESULT: ${{ needs.price-grid.result }} + run: | + if [ "$CHANGES" != success ]; then + echo "::error::could not tell whether the run was needed: the changes job ended $CHANGES" + exit 1 + fi + if [ "$RUN" != true ]; then + echo "only documentation changed; the run was skipped" + exit 0 + fi + if [ "$RESULT" != success ]; then + echo "::error::the run ended $RESULT" + exit 1 + fi + echo "passed" diff --git a/REVIEW.md b/REVIEW.md index 1aa185486..fe1d39f5c 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -145,6 +145,7 @@ These checks guard every change to the Satin engine. ### Byte-price grid - `.github/workflows/price-grid.yml` runs the `mega-evm` suite at byte prices other than the constants, through `scripts/price_grid.sh`: a cost per state byte and a cost per history byte per point, each run with `--no-fail-fast`. + The full grid runs as four parallel shards (`--full --shard I/4`) of one point list kept in the script, and a pull request that changes documentation alone skips it under the same allowlist; the `byte-price grid` job always runs and reports. - On a pull request and on dispatch it runs the whole grid: CPSB 0, 1, 312.5, 700, 1530, 2000, 5000 and 10000 by CPHB 0, 1, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 on both. It has no schedule, because a scheduled run would fire only from the default branch. - It is not a required check. @@ -157,6 +158,8 @@ These checks guard every change to the Satin engine. - The bounded fuzz run is part of the `test` and `test-release` checks. - `.github/workflows/fuzz.yml` runs the long mode on every pull request and on dispatch: every property at fifty times its bounded count, in debug and in release, and the byte-price record at two prices compared by `scripts/fuzz_price_monotonic.py`, all from one seed the run draws and prints in the step summary. It has no schedule and no path filter, because a scheduled or dispatch-only workflow would never run on this line (GitHub needs the workflow on the default branch for either). + A pull request that changes documentation alone is skipped, by an allowlist: every changed file must be under `docs/` or be a Markdown file outside `crates/` and `bin/` (`scripts/pull_request_needs_ci.sh`); any other change runs it. + The `long mode` job always runs and reports, so a skipped run does not leave a required check pending. - It is not a required check. A failure prints the seed and the case count that reproduce it and the minimal case; it is a defect in the engine or a property to correct, never a seed to avoid. - Locally, `MEGA_FUZZ_LONG=1 MEGA_FUZZ_SEED= cargo test [--release] -p mega-evm --test fuzz -- --nocapture`. @@ -194,11 +197,11 @@ These checks guard every change to the Satin engine. ### Scheduled workflows - GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, doc-audit, the weekly execution-spec run) stay inert until `satin` is the default branch. -- Run them on `satin` by hand: `gh workflow run .yml --ref satin` runs `satin`'s copy of the workflow on `satin`'s head, so none of them needs a `ref` input. +- `price-grid.yml` and `fuzz.yml` are not in that list: they have no schedule, and a dispatch needs the workflow on the default branch, so neither can be dispatched on `satin` and both run on every pull request instead. +- Run the others on `satin` by hand: `gh workflow run .yml --ref satin` runs `satin`'s copy of the workflow on `satin`'s head, so none of them needs a `ref` input. - `mutation.yml`: the whole-crate cargo-mutants run and suppression hygiene. - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. - `doc-audit.yml`: the documentation audit of `satin`'s docs. - - `price-grid.yml`: the whole byte-price grid. ## Dev tools and test infrastructure diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh index a9f754aae..0ea6f95d5 100755 --- a/scripts/price_grid.sh +++ b/scripts/price_grid.sh @@ -6,6 +6,11 @@ # scripts/price_grid.sh --full the whole grid (CPSB_AXIS x CPHB_AXIS, and EXTRA_POINTS) # scripts/price_grid.sh CPSB/CPHB ... the points named, e.g. 312.5/20 5000/300 # +# Any of them takes `--shard I/N` (1 <= I <= N) to run only every Nth point of the selection, +# starting at the Ith, so N runs with I = 1..N cover the selection exactly once between them: the +# CI job runs the full grid as four such shards in parallel. `--list` prints the selected points, +# one per line, and exits without building or running anything. +# # A point is a cost per state byte and a cost per history byte, as `MEGA_SATIN_CPSB` and # `MEGA_SATIN_CPHB` take them (a decimal with at most three places); `-` on either side leaves that # variable unset, which is the constant. The suite is built once with the `satin-price-override` @@ -43,7 +48,37 @@ SNAPSHOT_SKIPPED="snapshot comparison skipped" cd "$(dirname "$0")/.." || exit 1 OUT_DIR="${OUT_DIR:-target/price-grid}" -case "${1:-}" in +shard="" +list_only=false +selection=() +while [ "$#" -gt 0 ]; do + case "$1" in + --shard) + shard="${2:-}" + [ "$#" -ge 2 ] || { echo "error: --shard takes I/N" >&2; exit 2; } + shift 2 + ;; + --list) + list_only=true + shift + ;; + *) + selection+=("$1") + shift + ;; + esac +done +if [ -n "$shard" ]; then + shard_index="${shard%/*}" + shard_count="${shard#*/}" + if ! [[ "$shard_index" =~ ^[0-9]+$ && "$shard_count" =~ ^[0-9]+$ ]] || + [ "$shard_index" -lt 1 ] || [ "$shard_index" -gt "$shard_count" ]; then + echo "error: --shard takes I/N with 1 <= I <= N, got '$shard'" >&2 + exit 2 + fi +fi + +case "${selection[0]:-}" in --pr) points="$PR_POINTS" ;; @@ -57,14 +92,33 @@ case "${1:-}" in points="$points $EXTRA_POINTS" ;; "" | -h | --help) - sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//' + sed -n '2,32p' "$0" | sed 's/^# \{0,1\}//' exit 2 ;; *) - points="$*" + points="${selection[*]}" ;; esac +if [ -n "$shard" ]; then + kept="" + position=0 + for point in $points; do + if [ $((position % shard_count + 1)) -eq "$shard_index" ]; then + kept="$kept $point" + fi + position=$((position + 1)) + done + points="$kept" +fi + +if $list_only; then + for point in $points; do + echo "$point" + done + exit 0 +fi + rm -rf "$OUT_DIR" mkdir -p "$OUT_DIR" # The tests run in their package's directory, so the guard file is named by its absolute path. @@ -120,7 +174,7 @@ done if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then { - echo "## mega-evm at other byte prices" + echo "## mega-evm at other byte prices${shard:+ (shard $shard)}" echo echo "$summary" } >>"$GITHUB_STEP_SUMMARY" diff --git a/scripts/pull_request_needs_ci.sh b/scripts/pull_request_needs_ci.sh new file mode 100755 index 000000000..0a2f41db9 --- /dev/null +++ b/scripts/pull_request_needs_ci.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Decides whether a pull request needs the heavy workflows (the byte-price grid, the long fuzz). +# +# Usage: scripts/pull_request_needs_ci.sh [BASE [HEAD]] (defaults: HEAD^1 and HEAD, the +# merge commit of a pull request) +# +# Prints `true` unless every changed file is on the allowlist, and then `false`: +# +# - anything under docs/, and +# - a Markdown file (*.md) outside crates/ and bin/. +# +# Any other change runs the workflows, and so does a change with no files. Markdown under crates/ +# and bin/ is not on the list because tests read it: the generated documents there (the pricing +# table, the deviation registry, the mega-evme differences) are rendered by a test and compared to +# the file, and a crate's README is its documentation. +# +# Renames are listed as a deletion and an addition, so a file moved out of the allowlist counts at +# both paths. + +set -euo pipefail + +base="${1:-HEAD^1}" +head="${2:-HEAD}" + +changed=0 +while IFS= read -r -d '' file; do + changed=1 + case "$file" in + crates/* | bin/*) + echo true + exit 0 + ;; + docs/* | *.md) ;; + *) + echo true + exit 0 + ;; + esac +done < <(git diff -z --name-only --no-renames "$base" "$head") + +if [ "$changed" -eq 0 ]; then + echo true +else + echo false +fi From ffe9aa5c4e6fae86f49ddfbfdeb332baa98a1268 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 11 Nov 2026 22:28:04 +0800 Subject: [PATCH 030/190] test(block): drop a redundant clone --- crates/mega-evm/src/block/hardfork.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 3e2c10c81..8b0d730f6 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -529,7 +529,7 @@ mod tests { assert!(jovian_late.activation_depends_on_parent(100), "an Optimism fork counts too"); // Whatever the parent, a schedule that does not depend on it answers `false`. - for config in [late.clone(), satin_at(0), MegaHardforkConfig::default()] { + for config in [late, satin_at(0), MegaHardforkConfig::default()] { for block in [1, 99, 100, 500] { if !config.activation_depends_on_parent(block) { for parent in 0..=block { From 7a8a5fb7307d9951792785dbbc3efc0b3a90509b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 01:36:40 +0800 Subject: [PATCH 031/190] test(keyless): pin the dispatch decision table --- .../mega-evm/src/system/keyless/dispatch.rs | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ed686ab6d..aff567021 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -448,3 +448,97 @@ pub(super) fn state_gas( .err() .unwrap_or_else(|| ContextError::Custom("state gas price lookup failed".into()))) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, MegaSpecId}; + use alloy_primitives::address; + use revm::interpreter::{CallInput, CallValue, SharedMemory}; + + const CALLER: Address = address!("00000000000000000000000000000000000e0001"); + const OTHER: Address = address!("00000000000000000000000000000000000e0002"); + + /// Arguments that decode as `(bytes, uint256)`. + fn decodable() -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(&[1, 2, 3]), + gasLimitOverride: U256::from(7), + } + .abi_encode() + .into() + } + + /// The `keylessDeploy` selector with a head too short to decode. + fn undecodable() -> Bytes { + Bytes::copy_from_slice(&IKeylessDeploy::keylessDeployCall::SELECTOR) + } + + /// A call of `scheme` at `depth` to `target` carrying `input`. + fn frame(depth: usize, target: Address, scheme: CallScheme, input: Bytes) -> FrameInit { + FrameInit { + depth, + memory: SharedMemory::new(), + frame_input: FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(input), + return_memory_offset: 0..0, + gas_limit: 1_000_000, + reservoir: 0, + bytecode_address: target, + known_bytecode: Default::default(), + target_address: target, + caller: CALLER, + value: CallValue::Apparent(U256::ZERO), + scheme, + is_static: scheme == CallScheme::StaticCall, + charged_new_account_state_gas: false, + })), + } + } + + /// Only a `CALL` at depth 0 to the contract, carrying the `keylessDeploy` selector and + /// arguments that decode, is dispatched. Each other row of the table changes exactly one + /// condition, so each guard is pinned alone. + #[test] + fn test_the_dispatch_table_takes_only_the_all_true_row() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let other_selector = Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef, 0, 0, 0, 0]); + let at = KEYLESS_DEPLOY_ADDRESS; + let call = CallScheme::Call; + + let dispatched = is_dispatched(&ctx, &frame(0, at, call, decodable())) + .expect("the all-true row is dispatched"); + assert_eq!(dispatched.keylessDeploymentTransaction, Bytes::from_static(&[1, 2, 3])); + assert_eq!(dispatched.gasLimitOverride, U256::from(7)); + + let rows: [(&str, FrameInit); 8] = [ + ("depth 1", frame(1, at, call, decodable())), + ("another target", frame(0, OTHER, call, decodable())), + ("STATICCALL", frame(0, at, CallScheme::StaticCall, decodable())), + ("DELEGATECALL", frame(0, at, CallScheme::DelegateCall, decodable())), + // The scheme alone refuses these: every other condition holds. + ("CALLCODE", frame(0, at, CallScheme::CallCode, decodable())), + ("another selector", frame(0, at, call, other_selector.clone())), + ("undecodable arguments", frame(0, at, call, undecodable())), + ("no selector", frame(0, at, call, Bytes::from_static(&[0xde, 0xad]))), + ]; + for (name, init) in rows { + assert!(is_dispatched(&ctx, &init).is_none(), "{name} is not dispatched"); + } + + // A non-call frame is never dispatched. + let create = FrameInit { + depth: 0, + memory: SharedMemory::new(), + frame_input: FrameInput::Create(Box::new(CreateInputs::new( + CALLER, + CreateScheme::Create, + U256::ZERO, + decodable(), + 1_000_000, + 0, + ))), + }; + assert!(is_dispatched(&ctx, &create).is_none()); + } +} From 4598ef2f196e84e7d3def824da514ff316b0c654 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 01:40:06 +0800 Subject: [PATCH 032/190] test(keyless): drop a redundant clone --- crates/mega-evm/src/system/keyless/dispatch.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index aff567021..14fc16d94 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -518,7 +518,7 @@ mod tests { ("DELEGATECALL", frame(0, at, CallScheme::DelegateCall, decodable())), // The scheme alone refuses these: every other condition holds. ("CALLCODE", frame(0, at, CallScheme::CallCode, decodable())), - ("another selector", frame(0, at, call, other_selector.clone())), + ("another selector", frame(0, at, call, other_selector)), ("undecodable arguments", frame(0, at, call, undecodable())), ("no selector", frame(0, at, call, Bytes::from_static(&[0xde, 0xad]))), ]; From 99aece58d2c58b25759c3a11a0d703ccaf044292 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:07:13 +0800 Subject: [PATCH 033/190] feat(block): report the L1 block contract's reads with the first transaction that made them The block no longer reads the L1 block contract before its transactions. The footprint read and the fee computation's read are added, once each per block, as read-only entries of the first committed transaction that made them, without replacing that transaction's own entries. A failed fee read is routed as a read of the transaction's execution; a failed footprint read stays an internal error. --- crates/mega-evm/benches/block.rs | 13 +- crates/mega-evm/src/block/executor.rs | 199 +++++--- crates/mega-evm/src/block/l1_block_info.rs | 431 +++++++++++++---- crates/mega-evm/src/lib.rs | 12 +- crates/mega-evm/tests/block/common.rs | 52 +++ crates/mega-evm/tests/block/predeploys.rs | 15 +- .../tests/block/sequencer_registry.rs | 9 +- crates/mega-evm/tests/block/witness/state.rs | 439 +++++++++++++----- crates/mega-evm/tests/tracers/harness.rs | 7 +- 9 files changed, 868 insertions(+), 309 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 67e9b24ed..630b585bd 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -49,7 +49,6 @@ use mega_evm::{ BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTransactionOutcome, MegaTxEnvelope, }; -use op_revm::constants::L1_BLOCK_CONTRACT; use revm::{ bytecode::opcode::{CALLDATALOAD, SSTORE}, context::{BlockEnv, CfgEnv}, @@ -286,9 +285,8 @@ fn steady_database() -> MemoryDatabase { } /// Asserts that the pre-block changes of the bench's block on `db` are a steady block's: the two -/// calls, which write their contracts, then the reads of the registry's pending changes and of the -/// L1 block info, and no read of a predeploy, which only Satin's activation block makes. Each step -/// names one account. +/// calls, which write their contracts, then the read of the registry's pending changes, and no +/// read of a predeploy, which only Satin's activation block makes. Each step names one account. fn assert_steady_pre_block(db: &MemoryDatabase) { let states = pre_block_states(db.clone(), BLOCK_NUMBER); let named: Vec<_> = states @@ -300,12 +298,7 @@ fn assert_steady_pre_block(db: &MemoryDatabase) { .collect(); assert_eq!( named, - [ - HISTORY_STORAGE_ADDRESS, - BEACON_ROOTS_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - L1_BLOCK_CONTRACT - ], + [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS, SEQUENCER_REGISTRY_ADDRESS], "a steady block reads no predeploy" ); // Outside every measured section: both calls wrote the contract the bench seeded. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 881aff642..9c55c5d8f 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -27,11 +27,12 @@ //! state the scalar is zero and the rule costs nothing. This mirrors alloy-op-evm's Jovian DA //! footprint block limit. //! - **The L1 block info is read lazily, by the transaction that prices against it.** Block -//! execution fetches nothing: op-revm's handler reads the L1 block contract when it deducts the -//! caller of the first non-deposit transaction, which is after the block's own L1 info deposit -//! has committed, so every transaction prices against the values that deposit set. An empty L1 -//! 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. +//! execution fetches nothing before the block's transactions: op-revm's handler reads the L1 +//! block contract when it deducts the caller of the first non-deposit transaction, which is after +//! the block's own L1 info deposit has committed, so every transaction prices against the values +//! that deposit set. An empty L1 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. //! //! # Committing an outcome //! @@ -53,27 +54,27 @@ //! # The witness is what the block commits //! //! Each pre-block step — the EIP-2935 call, the EIP-4788 call, the activation block's read of each -//! predeploy, the read of the `SequencerRegistry`'s pending changes, the `applyPendingChanges()` -//! call and the read of the L1 block info the block's transactions are priced against — produces an -//! [`EvmState`], and this executor commits each one on its own, in that order, before the first -//! transaction; every committed transaction's returned state follows. A read is a read-only entry -//! of its step's state: an account neither touched nor created, its slots unchanged. The sequence -//! of committed states, with the exported block hashes and buckets, is the witness a stateless -//! client needs. A node takes it with a commit hook on revm's `State` (`State::set_state_hook`), -//! which `commit` hands every state whole, before the cache drops the accounts the state did not -//! touch. The block's transitions and bundle keep only what a state changed, so a witness taken -//! from them would miss the read-only entries — the activation block's predeploys, the registry's -//! pending slots, the L1 block info. +//! predeploy, the read of the `SequencerRegistry`'s pending changes and the `applyPendingChanges()` +//! call — produces an [`EvmState`], and this executor commits each one on its own, in that order, +//! before the first transaction; every committed transaction's returned state follows. A read is a +//! read-only entry of its step's state: an account neither touched nor created, its slots +//! unchanged. The sequence of committed states, with the exported block hashes and buckets, is the +//! witness a stateless client needs. A node takes it with a commit hook on revm's `State` +//! (`State::set_state_hook`), which `commit` hands every state whole, before the cache drops the +//! accounts the state did not touch. The block's transitions and bundle keep only what a state +//! changed, so a witness taken from them would miss the read-only entries — the activation block's +//! predeploys, the registry's pending slots, the L1 block info. //! -//! The L1 block info is read here because nothing else puts it in a state: op-revm prices the -//! block's first non-deposit transaction against the L1 block contract's slots read on the -//! database itself, and this executor reads the DA footprint gas scalar the same way before every -//! non-deposit transaction, so neither read lands in a transaction's returned state. The -//! pre-block entry carries the account and every slot either read can reach, as the chain held -//! them before the block ([`read_l1_block_info`]) — the L1 fee overhead among them, which -//! op-revm reads only when the scalars the block's deposits left are empty; the block's own L1 -//! attributes deposit, when it has one, carries the values it writes over them in its own -//! returned state. +//! The L1 block info is read outside every transaction's journal: op-revm prices the block's first +//! non-deposit transaction other than a Mega System Transaction against the L1 block contract's +//! slots read on the database itself, and this executor reads the DA footprint gas scalar the same +//! way before every non-deposit transaction, so neither read lands in a transaction's returned +//! state. The executor adds them to it: once each per block, the account and every slot either read +//! reached are read-only entries of the returned state of the first transaction that read them — +//! the L1 fee overhead among them only when the scalars the fee computation found are empty — +//! beside, never in place of, what the transaction's own execution put there. Nothing of the +//! contract is read before the block's transactions, so a block that reads none of it does not +//! fail when the database cannot serve it. //! //! # The pre-block system calls //! @@ -110,11 +111,12 @@ use alloy_evm::{ use alloy_op_evm::block::{receipt_builder::OpReceiptBuilder, OpTxEnv}; use alloy_primitives::{Address, Bytes, TxHash, B256}; use op_alloy_consensus::OpDepositReceipt; -use op_revm::{ - constants::L1_BLOCK_CONTRACT, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, -}; +use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; use revm::{ - context::{result::ResultAndState, Block, ContextTr}, + context::{ + result::{EVMError, ResultAndState}, + Block, ContextTr, + }, database::DatabaseCommitExt, state::{AccountInfo, EvmState}, DatabaseCommit, Inspector, @@ -126,7 +128,10 @@ pub type MegaFinishedBlock = (MegaEvm, MegaBlockExecutionResult<::Receipt>); use crate::{ - block::{eips, read_l1_block_info}, + block::{ + eips, + l1_block_info::{read_fee_info, read_footprint_gas_scalar, L1BlockRead, L1BlockReport}, + }, estimated_da_size, system::{ check_system_contract, classify_system_transaction, is_apply_pending_changes_due, @@ -135,7 +140,7 @@ use crate::{ }, BlockGasCounters, BlockLimiter, BlockLimits, BucketId, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, - MegaTransaction, MegaTransactionExt, ProtocolLimits, + MegaTransaction, MegaTransactionError, MegaTransactionExt, ProtocolLimits, }; /// What the node hands block execution beside the EVM. @@ -323,6 +328,9 @@ pub struct MegaBlockExecutor { /// Which activation rules apply to this block, decided once when the block starts, or why /// they cannot be decided. activation: Result, + /// What the block's committed transactions reported of the L1 block contract, which their + /// fee computation and footprint read outside their journal. + l1_block_report: L1BlockReport, } /// The two rules a fork's activation puts on a block, decided from the schedule, the block's @@ -402,6 +410,7 @@ where limiter, protocol_limits, activation, + l1_block_report: L1BlockReport::default(), } } @@ -487,22 +496,57 @@ where self.evm.inspector() } - /// The data-availability footprint gas scalar the L1 block contract holds. + /// The data-availability footprint gas scalar the L1 block contract holds, and, while no + /// committed transaction reported the read, what it found, for the transaction's report. /// /// Read per transaction, as the fork's rule is stated: the block's own L1 info transaction /// may set it, and the transactions after it are held to the value it set. It is a read of /// the block's state, made between transactions, so it lands in no transaction's returned - /// state; the pre-block phase's read of the same slot ([`read_l1_block_info`]) is what puts - /// it in the pre-block states a witness is built from, and this read finds it in the state - /// cache that read filled, or the value the L1 info transaction committed over it. - fn da_footprint_gas_scalar(&mut self) -> Result { - // Load the L1 block account into the cache first; a database that has never seen it - // cannot serve its storage. - let db = self.evm.ctx_mut().db_mut(); - db.basic(L1_BLOCK_CONTRACT).map_err(BlockExecutionError::other)?; - L1BlockInfo::fetch_da_footprint_gas_scalar(db) - .map(u64::from) - .map_err(BlockExecutionError::other) + /// state: the first transaction that made it reports it + /// ([`report_l1_block_reads`](Self::report_l1_block_reads)). A read that fails is an internal + /// error, whether or not the database declares it fatal: the block makes it for the + /// transaction, outside the transaction's execution. + fn da_footprint_gas_scalar( + &mut self, + ) -> Result<(u64, Option), BlockExecutionError> { + let record = self.l1_block_report.reports_footprint(); + let (scalar, read) = read_footprint_gas_scalar(self.evm.ctx_mut().db_mut(), record) + .map_err(BlockExecutionError::other)?; + Ok((u64::from(scalar), read)) + } + + /// Adds to `state`, the returned state of the non-deposit transaction `tx_hash`, what the + /// transaction read of the L1 block contract outside its journal that no committed + /// transaction reported yet, as read-only entries: `footprint`, the footprint read made before + /// it ran, and, when the fee computation `priced` it, the fee read, made again here, on the + /// state it ran on, which a state cache serves from op-revm's own fetch. + /// + /// A failed fee read is a failed read of the transaction's execution, as op-revm's fetch + /// inside it is: an internal error when the database declares it fatal, an invalid block when + /// it does not. + fn report_l1_block_reads( + &mut self, + state: &mut EvmState, + footprint: Option, + priced: bool, + tx_hash: TxHash, + ) -> Result<(), BlockExecutionError> { + let fee = if priced && self.l1_block_report.reports_fee() { + let number = self.evm.block().number(); + let spec = self.evm.ctx().spec().into_op_spec(); + let read = + read_fee_info(self.evm.ctx_mut().db_mut(), number, spec).map_err(|error| { + BlockExecutionError::evm( + EVMError::::Database(error), + tx_hash, + ) + })?; + Some(read) + } else { + None + }; + self.l1_block_report.add_to(state, footprint.iter().chain(&fee)); + Ok(()) } /// Commits `state` to the database. @@ -668,19 +712,17 @@ where /// Runs what a block does before its transactions. /// - /// 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 - /// than inside its helper, so a commit hook on the database sees every step's read and write - /// set. The sequence of committed states is the witness a stateless client needs. + /// In order: the reset of the block-hash and bucket records and of what the block reported of + /// the L1 block contract, the EIP-2935 and EIP-4788 pre-block calls, in the block in which + /// Satin activates the check of the predeploys, and the `SequencerRegistry`'s due role + /// changes. Each step's state is committed here, on its own and read-only entries included, + /// rather than inside its helper, so a commit hook on the database sees every step's read and + /// write set. The sequence of committed states is the witness a stateless client needs. /// - /// The transactions are not priced against the read made here. op-revm's handler fetches the - /// L1 block info when it deducts the caller of the first non-deposit transaction, which is - /// after the block's own L1 info deposit has committed; pricing from this read would price - /// every transaction of the block against the parent block's values. The read here puts the - /// L1 block contract's account and every slot that fetch can reach in the pre-block states, - /// and nothing else. + /// Nothing reads the L1 block contract here. op-revm's handler fetches the L1 block info when + /// it deducts the caller of the first non-deposit transaction, which is after the block's own + /// L1 info deposit has committed, and the first transaction that reads it reports what it read + /// in its own returned state. /// /// The EIP-2935 and EIP-4788 calls run before the check. They write the parent hash and the /// parent beacon root into their own contracts (`0x0…2935` and `0x0…4788`), which are not @@ -708,9 +750,10 @@ where self.admits_only_deposits()?; // The block starts with empty block-hash and bucket records, so what they hold at the end - // is what this block read. + // is what this block read, and with nothing of the L1 block contract reported. self.evm.clear_accessed_block_hashes(); self.evm.clear_accessed_bucket_ids(); + self.l1_block_report = L1BlockReport::default(); let state = eips::transact_blockhashes_contract_call( &self.spec, @@ -765,16 +808,6 @@ where self.commit(state); } - // The L1 block info the transactions are priced against is read on the database itself, - // by op-revm once per block and by `execute` before every non-deposit transaction, so it - // lands in no transaction's state. Read here, it is in the pre-block states instead: - // every slot those reads can reach, because which ones they reach is decided by the state - // the block's deposits leave, not by this one. The read fills the state cache, and its - // commit changes nothing: a commit hook receives the read-only entry, and the cache keeps - // no transition for it. - let state = read_l1_block_info(self.evm.db_mut()).map_err(BlockExecutionError::other)?; - self.commit(state); - Ok(()) } @@ -839,7 +872,14 @@ where } self.limiter.post_execution_update(&output.block_usage()); - let MegaBlockTxResult { tx_type, is_deposit, depositor_nonce, inner, .. } = output; + let MegaBlockTxResult { + tx_type, + is_deposit, + is_system_transaction, + depositor_nonce, + inner, + .. + } = output; let gas = inner.gas; let cumulative_gas_used = self.limiter.block_gas_used; let ResultAndState { result, state } = inner.result_and_state; @@ -874,6 +914,9 @@ where }, ); + if !is_deposit { + self.l1_block_report.committed(&state, !is_system_transaction); + } self.commit(state); GasOutput::with_state_gas(gas.gas_used, gas.state) @@ -1024,12 +1067,13 @@ where // A deposit is exempt from the data-availability footprint of the block, as it is from // its data-availability size. - let da_footprint = if is_deposit { - 0 + let (da_footprint, footprint_read) = if is_deposit { + (0, None) } else { - let footprint = da_size.saturating_mul(self.da_footprint_gas_scalar()?); + let (scalar, read) = self.da_footprint_gas_scalar()?; + let footprint = da_size.saturating_mul(scalar); self.check_da_footprint(footprint)?; - footprint + (footprint, read) }; // The sender's account as the transaction executes against it, read before execution: a @@ -1044,10 +1088,21 @@ where // The transaction runs under the block's limits, whatever was set on the EVM since the // last one. self.evm.set_tx_runtime_limits(self.protocol_limits.tx_runtime_limits); - let outcome = self + let mut outcome = self .evm .execute_transaction(tx_env) .map_err(|err| BlockExecutionError::evm(err, tx_hash))?; + // What the transaction read of the L1 block contract outside its journal: the footprint + // read, and the fee read of every non-deposit transaction but a Mega System Transaction, + // which pays no L1 fee. + if !is_deposit { + self.report_l1_block_reads( + &mut outcome.result_and_state.state, + footprint_read, + !is_system_transaction, + tx_hash, + )?; + } let result = MegaBlockTxResult { tx_type: inner.tx_type(), diff --git a/crates/mega-evm/src/block/l1_block_info.rs b/crates/mega-evm/src/block/l1_block_info.rs index ed5989468..b216a3ea7 100644 --- a/crates/mega-evm/src/block/l1_block_info.rs +++ b/crates/mega-evm/src/block/l1_block_info.rs @@ -1,49 +1,60 @@ -//! The L1 block info a block's transactions are priced against, read before the block's -//! transactions and committed as a read-only state of its own. +//! The L1 block contract's account and slots a block's transactions read outside their journal, +//! and their report with the first transaction that read them. //! -//! A non-deposit transaction is priced against the L1 block contract: op-revm reads the L1 base -//! fee, the Ecotone blob base fee and fee scalars, the L1 fee overhead when the scalars it finds -//! are empty, and the operator fee scalars, once per block, and block execution reads the DA -//! footprint gas scalar before every non-deposit transaction. Both read the block's state -//! directly, not through a transaction's journal, so the account and the slots they read land in -//! no transaction's returned state. A stateless witness built from the states the block commits -//! would miss them, and a validator re-executing the block from such a witness fails it with an -//! error: a read outside the witness is an error, not a zero to price with. +//! Two reads of the base layer read the L1 block contract on the block's state rather than through +//! a transaction's journal. The fee computation prices a non-deposit transaction that pays an L1 +//! fee: op-revm reads the contract's account, its L1 base fee (slot 1), its Ecotone blob base fee +//! (7) and fee scalars (3), the L1 fee overhead (5) only when those scalars are empty, and its +//! operator fee scalars (8), once per block, at the first transaction it prices, on the state the +//! transactions before it left. The footprint read holds every non-deposit transaction, a Mega +//! System Transaction included, which pays no L1 fee, to the data-availability footprint: block +//! execution reads the contract's account and the footprint gas scalar in slot 8 before each one +//! runs. Neither read lands in a transaction's returned state, so a stateless witness built from +//! the states the block commits would miss them, and a validator re-executing the block from such +//! a witness would fail it on a read the witness does not hold. //! -//! [`read_l1_block_info`] reads the account and the slots before the block's transactions and -//! answers them as read-only entries, as the reads of the `SequencerRegistry`'s pending changes -//! are answered, and block execution commits them as a state of their own, so a witness built -//! from the committed states holds them. Without the read, such a witness holds them only as long -//! as two assumptions no check enforces hold: that the block starts with its L1 attributes -//! deposit, whose returned state names slots 1, 3, 7 and 8 because the deposit writes them, and -//! that the Ecotone scalars the deposit leaves are not both zero, since op-revm then reads the -//! overhead in slot 5, which nothing writes and no other state names. The read takes every slot -//! the pricing can read, whatever the contract holds before the block: op-revm makes its read at -//! the block's first non-deposit transaction, on the state the deposits before it left, so which -//! slots it reads is not decided by the state the block starts from. The entry may therefore -//! carry a slot the block does not read after all. The read loads the account and its slots into -//! the block's state cache and changes nothing: its commit hands a commit hook the read-only -//! entry and keeps no transition, and the transactions' own reads find the same values, or the -//! ones the block's L1 attributes deposit wrote over them. - -use alloy_primitives::U256; -use op_revm::constants::{ - ECOTONE_L1_BLOB_BASE_FEE_SLOT, ECOTONE_L1_FEE_SCALARS_SLOT, L1_BASE_FEE_SLOT, - L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT, OPERATOR_FEE_SCALARS_SLOT, +//! Block execution therefore reports them with the first transaction that read them. Once each per +//! block, the account and every slot either read reached are added to that transaction's returned +//! state as read-only entries — the account neither touched nor created, each slot unchanged — +//! which the block commits with the rest of the state, so a witness built from the committed +//! states holds them; their commit changes nothing. A read-only entry never replaces an entry the +//! transaction's own execution made, so its write to the contract stands. A contract the state +//! does not hold is reported as not existing, with no slot: the slots of an absent account are +//! zero without a read. Nothing is read before the block's transactions, so a block of deposits +//! alone reads nothing of the contract, and a slot neither read reaches — the overhead beside set +//! scalars — is not read at all. +//! +//! What the fee computation read is decided by the block, not by whether this node's op-revm +//! fetched the info for it: the fee read is made again, through op-revm's own fetch, once the +//! transaction ran and before it is committed, on the state it ran on, which a node's state cache +//! serves without a database read once op-revm made its own. A validator that replays the block +//! fetches the info at the same transaction and reads the same keys. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::collections::{BTreeMap, BTreeSet}; + +use alloy_primitives::{Address, B256, U256}; +use op_revm::{ + constants::{ + ECOTONE_L1_BLOB_BASE_FEE_SLOT, ECOTONE_L1_FEE_SCALARS_SLOT, L1_BASE_FEE_SLOT, + L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT, OPERATOR_FEE_SCALARS_SLOT, + }, + L1BlockInfo, OpSpecId, }; use revm::{ - state::{Account, EvmState, EvmStorageSlot, TransactionId}, + bytecode::Bytecode, + state::{Account, AccountInfo, EvmState, EvmStorageSlot, TransactionId}, Database, }; -/// The slots of the L1 block contract a block's transactions can be priced against, in ascending -/// order: the L1 base fee (1), the Ecotone fee scalars (3), the L1 fee overhead (5), the Ecotone -/// blob base fee (7) and the operator fee scalars (8), which is also the slot of the DA footprint -/// gas scalar. +/// The slots of the L1 block contract the fee computation and the footprint read can reach, in +/// ascending order: the L1 base fee (1), the Ecotone fee scalars (3), the L1 fee overhead (5), the +/// Ecotone blob base fee (7) and the operator fee scalars (8), which is also the slot of the DA +/// footprint gas scalar. /// -/// The pricing reads the overhead only when the Ecotone scalars it finds are empty, and the -/// others always. The overhead is in the set all the same: the scalars the pricing finds are the -/// ones the block's deposits left, not the ones the block starts from. +/// The fee computation reads the overhead only when the Ecotone scalars it finds are empty, and +/// the others always; the footprint read reads the operator fee scalars' slot alone. pub const L1_BLOCK_INFO_SLOTS: [U256; 5] = [ L1_BASE_FEE_SLOT, ECOTONE_L1_FEE_SCALARS_SLOT, @@ -52,39 +63,189 @@ pub const L1_BLOCK_INFO_SLOTS: [U256; 5] = [ OPERATOR_FEE_SCALARS_SLOT, ]; -/// Reads the L1 block contract's account and every slot of [`L1_BLOCK_INFO_SLOTS`] from `db` and -/// answers them as a read-only state: the account as loaded, neither touched nor created, with -/// each slot as an unchanged entry; or, for a chain that does not hold the contract, the account -/// recorded as not existing and no slot read, since the slots of an absent account are zero -/// without a read. +/// What one read of the L1 block contract found: the account as the block's state held it, and +/// each slot the read reached, with the value it found. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct L1BlockRead { + /// The account, `None` for a state that holds no contract at the address. + account: Option, + /// The slots read, by key. A slot of an account the state does not hold is never reported. + slots: BTreeMap, +} + +/// A database that answers from the one it wraps and, when it records, keeps what it answered +/// about the L1 block contract. +struct Recording<'a, DB> { + db: &'a mut DB, + read: Option, +} + +impl<'a, DB> Recording<'a, DB> { + /// Answers from `db`, recording when `record` says so. + fn new(db: &'a mut DB, record: bool) -> Self { + Self { db, read: record.then(L1BlockRead::default) } + } +} + +impl Database for Recording<'_, DB> { + type Error = DB::Error; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + let info = self.db.basic(address)?; + if let Some(read) = self.read.as_mut().filter(|_| address == L1_BLOCK_CONTRACT) { + read.account.clone_from(&info); + } + Ok(info) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + self.db.code_by_hash(code_hash) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + let value = self.db.storage(address, index)?; + if let Some(read) = self.read.as_mut().filter(|_| address == L1_BLOCK_CONTRACT) { + read.slots.insert(index, value); + } + Ok(value) + } + + fn block_hash(&mut self, number: u64) -> Result { + self.db.block_hash(number) + } +} + +/// Reads the data-availability footprint gas scalar as block execution reads it before a +/// non-deposit transaction runs: the L1 block contract's account, then the scalar's slot, decoded +/// as op-revm decodes it. With `record`, also what the read found, for the transaction's report. /// -/// Every slot is read whatever the others hold, the overhead beside set scalars included. +/// # Errors /// -/// Nothing is committed here. Block execution commits the state on its own, which changes -/// nothing and hands a commit hook the read-only entry. +/// The database's, when a read fails. +pub(crate) fn read_footprint_gas_scalar( + db: &mut DB, + record: bool, +) -> Result<(u16, Option), DB::Error> { + let mut db = Recording::new(db, record); + // Load the account first: a database that has never seen it cannot serve its storage. + db.basic(L1_BLOCK_CONTRACT)?; + let scalar = L1BlockInfo::fetch_da_footprint_gas_scalar(&mut db)?; + Ok((scalar, db.read)) +} + +/// Reads what the fee computation reads to price a non-deposit transaction of block `number` +/// under `spec`: the L1 block contract's account, and, when the state holds it, every slot +/// op-revm's fetch reads, through that fetch itself ([`L1BlockInfo::try_fetch`]), so the two +/// cannot part. A state that holds no contract reads no slot. /// /// # Errors /// /// The database's, when a read fails. -pub fn read_l1_block_info(db: &mut DB) -> Result { - let Some(info) = db.basic(L1_BLOCK_CONTRACT)? else { - let absent = Account::new_not_existing(TransactionId::ZERO); - return Ok(EvmState::from_iter([(L1_BLOCK_CONTRACT, absent)])); - }; - let mut account = Account::from(info); - for slot in L1_BLOCK_INFO_SLOTS { - let value = db.storage(L1_BLOCK_CONTRACT, slot)?; - account.storage.insert(slot, EvmStorageSlot::new(value, TransactionId::ZERO)); +pub(crate) fn read_fee_info( + db: &mut DB, + number: U256, + spec: OpSpecId, +) -> Result { + let mut db = Recording::new(db, true); + if db.basic(L1_BLOCK_CONTRACT)?.is_some() { + L1BlockInfo::try_fetch(&mut db, number, spec)?; + } + Ok(db.read.unwrap_or_default()) +} + +/// What block execution has reported of the L1 block contract in the states it committed in the +/// block, and so what is left to report. +/// +/// The footprint read is reported with the first non-deposit transaction committed, and the fee +/// read with the first committed transaction the fee computation priced, each without the keys a +/// committed state of a transaction that read the contract named already. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct L1BlockReport { + /// Whether a committed transaction reported the footprint read. + footprint: bool, + /// Whether a committed transaction reported the fee read. + fee: bool, + /// Whether a committed state of a transaction that read the contract named its account. + account: bool, + /// The slots of [`L1_BLOCK_INFO_SLOTS`] such a state named. + slots: BTreeSet, +} + +impl L1BlockReport { + /// Whether the footprint read is still to be reported: no transaction that made it was + /// committed yet. + pub(crate) const fn reports_footprint(&self) -> bool { + !self.footprint + } + + /// Whether the fee read is still to be reported: no transaction the fee computation priced was + /// committed yet. + pub(crate) const fn reports_fee(&self) -> bool { + !self.fee + } + + /// Adds to `state`, a transaction's returned state, what `reads` found that no committed state + /// named yet, as read-only entries: the account as found, and each slot found of an account the + /// state holds. An entry `state` holds already is left as it is, so the transaction's own load + /// of the contract, or its write to it, stands; a slot to report goes under it. + pub(crate) fn add_to<'a>( + &self, + state: &mut EvmState, + reads: impl IntoIterator, + ) { + for read in reads { + let fresh: BTreeMap = match read.account { + Some(_) => read + .slots + .iter() + .filter(|(slot, _)| !self.slots.contains(*slot)) + .map(|(slot, value)| (*slot, *value)) + .collect(), + None => BTreeMap::new(), + }; + if self.account && fresh.is_empty() { + continue; + } + let account = + state.entry(L1_BLOCK_CONTRACT).or_insert_with(|| match read.account.clone() { + Some(info) => Account::from(info), + None => Account::new_not_existing(TransactionId::ZERO), + }); + for (slot, value) in fresh { + account + .storage + .entry(slot) + .or_insert_with(|| EvmStorageSlot::new(value, TransactionId::ZERO)); + } + } + } + + /// Records what the committed `state` of a non-deposit transaction reported: the footprint + /// read, which every non-deposit transaction makes, and, when the fee computation `priced` it, + /// the fee read; and the keys of the contract `state` names, which are in the witness from now + /// on. + pub(crate) fn committed(&mut self, state: &EvmState, priced: bool) { + if self.fee || (self.footprint && !priced) { + return; + } + self.footprint = true; + self.fee |= priced; + if let Some(account) = state.get(&L1_BLOCK_CONTRACT) { + self.account = true; + let named = account.storage.keys().filter(|slot| L1_BLOCK_INFO_SLOTS.contains(slot)); + self.slots.extend(named); + } } - Ok(EvmState::from_iter([(L1_BLOCK_CONTRACT, account)])) } #[cfg(test)] mod tests { use alloy_primitives::Bytes; use op_revm::constants::{ - BASE_FEE_SCALAR_OFFSET, BLOB_BASE_FEE_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, + BASE_FEE_SCALAR_OFFSET, BLOB_BASE_FEE_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_OFFSET, + DA_FOOTPRINT_GAS_SCALAR_SLOT, }; + use revm::state::AccountStatus; use super::*; use crate::test_utils::{ErrorInjectingDatabase, MemoryDatabase}; @@ -98,11 +259,21 @@ mod tests { U256::from_be_bytes(word) } + /// The operator fee scalars word holding a footprint gas scalar of 400. + fn footprint_word() -> U256 { + let mut word = [0_u8; 32]; + word[DA_FOOTPRINT_GAS_SCALAR_OFFSET..DA_FOOTPRINT_GAS_SCALAR_OFFSET + 2] + .copy_from_slice(&400_u16.to_be_bytes()); + U256::from_be_bytes(word) + } + /// The value the chain holds in every slot of the set: a distinct non-zero value, with - /// `scalars` at the scalars slot. - fn values(scalars: U256) -> [(U256, U256); 5] { - let mut values = L1_BLOCK_INFO_SLOTS.map(|slot| (slot, slot + U256::from(1_000))); - values[1] = (ECOTONE_L1_FEE_SCALARS_SLOT, scalars); + /// `scalars` at the scalars slot and [`footprint_word`] at the operator fee scalars slot. + fn values(scalars: U256) -> BTreeMap { + let mut values: BTreeMap<_, _> = + L1_BLOCK_INFO_SLOTS.map(|slot| (slot, slot + U256::from(1_000))).into(); + values.insert(ECOTONE_L1_FEE_SCALARS_SLOT, scalars); + values.insert(OPERATOR_FEE_SCALARS_SLOT, footprint_word()); values } @@ -116,7 +287,7 @@ mod tests { db } - /// The set is the five slots the pricing can read: it names the footprint slot and the + /// The set is the five slots either read can reach: it names the footprint slot and the /// overhead, holds no slot twice and is ascending. #[test] fn test_the_slots_are_distinct_ascending_and_hold_the_footprint_slot_and_the_overhead() { @@ -126,58 +297,118 @@ mod tests { assert!(L1_BLOCK_INFO_SLOTS.windows(2).all(|pair| pair[0] < pair[1])); } - /// A held contract is answered as loaded and unchanged, with every slot of the set as an - /// unchanged entry holding the chain's value — the overhead among them — whether the scalars - /// are set or empty. + /// The fee read is op-revm's fetch on Satin's base: the account and slots 1, 3, 7 and 8 with + /// the chain's values, and the overhead only when the scalars are empty. #[test] - fn test_a_held_contract_is_read_as_unchanged_entries_whatever_the_scalars_hold() { - for scalars in [scalars(), U256::ZERO] { - let mut db = chain(scalars); - let state = read_l1_block_info(&mut db).expect("the reads succeed"); - assert_eq!(state.len(), 1, "the L1 block contract alone"); - let account = &state[&L1_BLOCK_CONTRACT]; - assert!(!account.is_touched(), "read, not written"); - assert!(!account.is_created()); - assert!(!account.is_loaded_as_not_existing()); - assert_eq!(account.info.code_hash, alloy_primitives::keccak256([0x00])); - assert_eq!(account.storage.len(), L1_BLOCK_INFO_SLOTS.len(), "the set, no more"); - for (slot, value) in values(scalars) { - let entry = account.storage.get(&slot).expect("in the set"); - assert_eq!(entry.original_value, value, "{slot}"); - assert!(!entry.is_changed(), "{slot} is unchanged"); + fn test_the_fee_read_reads_the_overhead_only_beside_empty_scalars() { + let spec = crate::MegaSpecId::SATIN.into_op_spec(); + for (scalars, overhead) in [(scalars(), false), (U256::ZERO, true)] { + let read = read_fee_info(&mut chain(scalars), U256::from(9), spec).expect("served"); + let account = read.account.expect("the chain holds the contract"); + assert_eq!(account.code_hash, alloy_primitives::keccak256([0x00])); + let mut expected = values(scalars); + if !overhead { + expected.remove(&L1_OVERHEAD_SLOT); } - let overhead = &account.storage[&L1_OVERHEAD_SLOT]; - assert_eq!(overhead.original_value, U256::from(1_005), "scalars {scalars}"); + assert_eq!(read.slots, expected, "scalars {scalars}"); } } - /// A chain without the contract answers it as not existing and reads no slot: a slot read - /// would fail on this database. + /// A chain without the contract is read as not existing, and no slot is read: a slot read + /// would fail on this database. Reported, it is an account recorded as not existing, with no + /// slot, the footprint read's included. #[test] - fn test_an_absent_contract_is_recorded_absent_and_no_slot_is_read() { + fn test_an_absent_contract_is_read_as_absent_and_no_slot_is_read() { + let spec = crate::MegaSpecId::SATIN.into_op_spec(); for slot in L1_BLOCK_INFO_SLOTS { let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); db.fail_on_storage = Some((L1_BLOCK_CONTRACT, slot)); - let state = read_l1_block_info(&mut db).expect("no slot is read"); - let account = &state[&L1_BLOCK_CONTRACT]; - assert!(account.is_loaded_as_not_existing()); - assert!(!account.is_touched()); - assert!(account.storage.is_empty()); + let read = read_fee_info(&mut db, U256::from(9), spec).expect("no slot is read"); + assert_eq!(read, L1BlockRead::default(), "absent, with no slot"); } + let (scalar, footprint) = read_footprint_gas_scalar(&mut MemoryDatabase::default(), true) + .expect("an absent contract holds a zero scalar"); + assert_eq!(scalar, 0); + let mut state = EvmState::default(); + L1BlockReport::default().add_to(&mut state, footprint.iter()); + let account = &state[&L1_BLOCK_CONTRACT]; + assert!(account.is_loaded_as_not_existing() && !account.is_touched()); + assert!(account.storage.is_empty(), "no slot of an absent account"); + } + + /// The footprint read decodes the scalar as op-revm does, and records what it read only when + /// asked: the account and the scalar's slot. + #[test] + fn test_the_footprint_read_records_only_when_asked() { + let (scalar, read) = read_footprint_gas_scalar(&mut chain(scalars()), false).unwrap(); + assert_eq!((scalar, read), (400, None)); + let (scalar, read) = read_footprint_gas_scalar(&mut chain(scalars()), true).unwrap(); + let read = read.expect("recorded"); + assert_eq!(scalar, 400); + assert!(read.account.is_some()); + assert_eq!(read.slots, BTreeMap::from([(OPERATOR_FEE_SCALARS_SLOT, footprint_word())])); } - /// A read the database cannot serve is the database's error: the account, or any slot of the - /// set — the overhead too, though the scalars are set. + /// A report adds read-only entries — the account neither touched nor created, each slot + /// unchanged at the value read — and leaves what the transaction's own state holds: an account + /// it touched stays touched, and a slot it wrote keeps its write. #[test] - fn test_a_database_error_is_returned() { - let mut db = ErrorInjectingDatabase::new(chain(scalars())); - db.fail_on_account = Some(L1_BLOCK_CONTRACT); - assert!(read_l1_block_info(&mut db).is_err()); + fn test_a_report_never_replaces_the_transactions_own_entries() { + let spec = crate::MegaSpecId::SATIN.into_op_spec(); + let read = read_fee_info(&mut chain(scalars()), U256::from(9), spec).unwrap(); - for slot in L1_BLOCK_INFO_SLOTS { - let mut db = ErrorInjectingDatabase::new(chain(scalars())); - db.fail_on_storage = Some((L1_BLOCK_CONTRACT, slot)); - assert!(read_l1_block_info(&mut db).is_err(), "slot {slot} of the set"); + let mut state = EvmState::default(); + L1BlockReport::default().add_to(&mut state, [&read]); + let account = &state[&L1_BLOCK_CONTRACT]; + assert!(!account.is_touched() && !account.is_created()); + assert_eq!(account.storage.len(), 4); + for (slot, value) in &read.slots { + assert_eq!(account.storage[slot].present_value, *value); + assert!(!account.storage[slot].is_changed()); } + + let mut own = Account::from(read.account.clone().unwrap()); + own.status = AccountStatus::Touched; + let mut written = EvmStorageSlot::new(scalars(), TransactionId::ZERO); + written.present_value = U256::ZERO; + own.storage.insert(ECOTONE_L1_FEE_SCALARS_SLOT, written.clone()); + let mut state = EvmState::from_iter([(L1_BLOCK_CONTRACT, own)]); + L1BlockReport::default().add_to(&mut state, [&read]); + let account = &state[&L1_BLOCK_CONTRACT]; + assert!(account.is_touched(), "the transaction's own entry"); + assert_eq!(account.storage[&ECOTONE_L1_FEE_SCALARS_SLOT], written, "its write stands"); + assert_eq!(account.storage.len(), 4, "the other three slots are added"); + } + + /// Once a committed state reported a read, nothing of it is reported again: after a Mega + /// System Transaction's footprint read, the fee read adds the slots it read beside the scalar's + /// alone, under the account it must name to hold them; after a transaction the fee + /// computation priced, nothing is left to report. + #[test] + fn test_what_a_committed_state_reported_is_not_reported_again() { + let spec = crate::MegaSpecId::SATIN.into_op_spec(); + let (_, footprint) = read_footprint_gas_scalar(&mut chain(scalars()), true).unwrap(); + let fee = read_fee_info(&mut chain(scalars()), U256::from(9), spec).unwrap(); + let mut report = L1BlockReport::default(); + assert!(report.reports_footprint() && report.reports_fee()); + + let mut system = EvmState::default(); + report.add_to(&mut system, footprint.iter()); + report.committed(&system, false); + assert!(!report.reports_footprint() && report.reports_fee()); + + let mut priced = EvmState::default(); + report.add_to(&mut priced, footprint.iter().chain([&fee])); + let slots: BTreeSet<_> = priced[&L1_BLOCK_CONTRACT].storage.keys().copied().collect(); + assert_eq!( + slots, + [L1_BASE_FEE_SLOT, ECOTONE_L1_FEE_SCALARS_SLOT, ECOTONE_L1_BLOB_BASE_FEE_SLOT].into() + ); + report.committed(&priced, true); + assert!(!report.reports_footprint() && !report.reports_fee()); + + let mut later = EvmState::default(); + report.add_to(&mut later, [&fee]); + assert!(later.is_empty(), "nothing is left to report"); } } diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index cf0acf3c5..1ce6ccd3d 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -32,12 +32,12 @@ pub use access::{ VolatileDataAccess, }; pub use block::{ - 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, + chain_activation, estimated_da_size, hardfork_schedule, mainnet_hardforks, 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, diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 0a473469f..88962bd0e 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -468,3 +468,55 @@ pub(crate) fn incompressible(len: usize) -> Bytes { .collect::>(), ) } + +/// A database error that is not fatal, as a read an EIP-7928 block access list does not cover +/// raises: a failed read of a transaction's execution that carries it is a verdict on the block, +/// an invalid block, rather than an internal error. +#[derive(Debug)] +pub(crate) struct NotFatalError(String); + +impl core::fmt::Display for NotFatalError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(&self.0) + } +} + +impl core::error::Error for NotFatalError {} + +impl revm::context::DBErrorMarker for NotFatalError { + fn is_fatal(&self) -> bool { + false + } +} + +/// An [`ErrorInjectingDatabase`](mega_evm::test_utils::ErrorInjectingDatabase) whose refusals are +/// not fatal. A block runs on it directly: revm's `State` declares every error of the database +/// below it fatal, so a not-fatal error reaches block execution only from a database it runs on. +#[derive(Debug)] +pub(crate) struct NotFatal(pub(crate) mega_evm::test_utils::ErrorInjectingDatabase); + +impl revm::Database for NotFatal { + type Error = NotFatalError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + self.0.basic(address).map_err(|error| NotFatalError(error.to_string())) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + self.0.code_by_hash(code_hash).map_err(|error| NotFatalError(error.to_string())) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + self.0.storage(address, index).map_err(|error| NotFatalError(error.to_string())) + } + + fn block_hash(&mut self, number: u64) -> Result { + self.0.block_hash(number).map_err(|error| NotFatalError(error.to_string())) + } +} + +impl revm::DatabaseCommit for NotFatal { + fn commit(&mut self, changes: EvmState) { + self.0.commit(changes); + } +} diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 0812579e5..45a13db47 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -17,7 +17,6 @@ use mega_evm::{ test_utils::{rex6_predeploys, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, MegaBlockExecutionCtx, MegaBlockExecutionError, }; -use op_revm::constants::L1_BLOCK_CONTRACT; use revm::{ context::result::ExecutionResult, database::State, primitives::KECCAK_EMPTY, state::EvmState, }; @@ -43,14 +42,15 @@ fn start( } /// The account each pre-block state of a block names, in commit order: the two EIP calls' targets, -/// in the activation block the seven predeploys in order, the registry, whose pending changes are -/// read and found none due on these blocks, and the L1 block contract, whose info is read. +/// in the activation block the seven predeploys in order, and the registry, whose pending changes +/// are read and found none due on these blocks. Nothing reads the L1 block contract before the +/// block's transactions. fn expected_accounts(activation: bool) -> Vec
{ let mut expected = vec![HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]; if activation { expected.extend(system_contract_specs().map(|spec| spec.address)); } - expected.extend([SEQUENCER_REGISTRY_ADDRESS, L1_BLOCK_CONTRACT]); + expected.push(SEQUENCER_REGISTRY_ADDRESS); expected } @@ -58,9 +58,8 @@ fn expected_accounts(activation: bool) -> Vec
{ /// Satin's code. Each pre-block step commits a state of its own, and a commit hook receives them in /// order, read-only entries included: the two EIP calls, which touch their contracts; the seven /// accounts, each a read-only entry as the chain holds it — no write, no created mark, the six at -/// nonce 0 and the factory at its own; the registry's two pending slots, read only; and the L1 -/// block contract, read only. The block after it, on the committed state, reads none of the -/// predeploys, and neither block changes one. +/// nonce 0 and the factory at its own; and the registry's two pending slots, read only. The block +/// after it, on the committed state, reads none of the predeploys, and neither block changes one. /// /// Expected values: independent (the Rex6-shaped accounts the test puts in the state). #[test] @@ -86,8 +85,6 @@ fn test_the_activation_block_reads_the_seven_predeploys_once() { "the read of its pending changes" ); assert!(registry.storage.values().all(|slot| !slot.is_changed())); - let l1_block = &activation[3 + held.len()][&L1_BLOCK_CONTRACT]; - assert!(!l1_block.is_touched() && !l1_block.is_created(), "the L1 block info is read only"); let next = start(&mut state, after_activation_ctx()).expect("the next block starts"); assert_eq!(named_accounts(&next), expected_accounts(false), "no other block reads them"); diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index b1617982c..965713683 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -29,7 +29,7 @@ use mega_evm::{ MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaTxEnvelope, TestExternalEnvs, MIN_BUCKET_SIZE, }; use op_alloy_consensus::TxDeposit; -use op_revm::OpHaltReason; +use op_revm::{constants::L1_BLOCK_CONTRACT, OpHaltReason}; use revm::{ context::result::ExecutionResult, database::State, inspector::NoOpInspector, state::EvmState, Database, @@ -366,8 +366,13 @@ fn test_an_evm_outside_block_execution_promotes_the_rotated_address() { let mut executor = executor(&mut state, envs.clone(), common::BLOCK_GAS_LIMIT); executor.apply_pre_execution_changes().expect("the block starts"); - let in_block = assert_is_the_system_address(&mut executor, NEXT_SYSTEM_ADDRESS).inner; + let mut in_block = assert_is_the_system_address(&mut executor, NEXT_SYSTEM_ADDRESS).inner; drop(executor); + // Block execution reads the footprint gas scalar before the transaction, outside its journal, + // and reports the read in its state as a read-only entry, the block's first; an EVM outside + // block execution makes no such read. + let report = in_block.state.remove(&L1_BLOCK_CONTRACT).expect("the footprint read"); + assert!(!report.is_touched() && !report.is_created(), "a read-only entry"); // The state now holds the rotation the block applied, as the one a node's EVM runs on does. let assert_as_in_block = |evm: &mut OutsideEvm<'_>| { diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs index f4ad5185a..41eaf4d04 100644 --- a/crates/mega-evm/tests/block/witness/state.rs +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -1,10 +1,11 @@ //! State-changing mechanisms through the harness: an EIP-7702 delegation and its replacement, a //! creation, the two shapes of `SELFDESTRUCT`, a value transfer that creates its recipient, and -//! deposits — with the L1 block info a user transaction is priced against, which the pre-block -//! phase carries, and which a block cannot start without. +//! deposits — with the L1 block info a transaction is priced against and the footprint scalar it +//! is held to, which the first transaction that reads them reports, and which nothing reads +//! before the block's transactions. use alloy_evm::{ - block::{BlockExecutionError, BlockExecutor}, + block::{BlockExecutionError, BlockExecutor, BlockValidationError}, EvmFactory, }; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; @@ -22,14 +23,14 @@ use revm::{ bytecode::opcode::{CODECOPY, PUSH0, RETURN}, context_interface::cfg::GasId, database::State, - state::{Account, AccountInfo, Bytecode}, + state::{Account, AccountInfo, Bytecode, EvmState}, }; use super::{ basics::{slot, slot_writer, write_gas}, harness::{ assert_same_run, authorization, call, call_with_value, create, deposit, eip7702, Case, - Oracle, Run, + Oracle, Run, Tx, TxSnapshot, }, }; use crate::{ @@ -236,7 +237,7 @@ fn l1_info() -> [(U256, U256); 4] { } /// The L1 fee overhead the chain holds, which the pricing reads only when the scalars it finds -/// are empty, and the pre-block entry carries whatever they hold. +/// are empty. const OVERHEAD: U256 = U256::from_limbs([188, 0, 0, 0]); /// A chain holding the L1 block contract with `code`, the info of [`l1_info`] and the overhead, @@ -252,23 +253,45 @@ fn chain_with_l1_info(code: Bytes) -> MemoryDatabase { db } -/// The L1 block info entry of a run's pre-block states: the last state the pre-block steps -/// committed, and the one entry in it. -fn l1_entry(run: &Run) -> &Account { - let state = run.pre_block.last().expect("a pre-block state"); - assert_eq!(state.len(), 1, "the L1 block contract alone"); - state.get(&L1_BLOCK_CONTRACT).expect("the L1 block info is the last state") +/// The L1 block contract's entry in `state`. +fn l1_account(state: &EvmState) -> &Account { + state.get(&L1_BLOCK_CONTRACT).expect("the state names the L1 block contract") } -/// A deposit minting to a fresh depositor: the depositor's absent account is read (for the -/// receipt's nonce and as the caller), created and priced, and the deposit writes its slot. A -/// block of deposits alone prices no transaction against the L1 block info; the pre-block phase -/// reads it all the same, here from a chain that does not hold the contract, which the entry -/// records as not existing without a slot read. +/// Asserts `account` is a read-only entry — neither touched nor created — holding exactly +/// `slots`, each unchanged at its value. +fn assert_read_only(what: &str, account: &Account, slots: &[(U256, U256)]) { + assert!(!account.is_touched() && !account.is_created(), "{what}: a read-only entry"); + let named: Vec<_> = account.storage.keys().copied().collect(); + assert_eq!(account.storage.len(), slots.len(), "{what}: the slots named: {named:?}"); + for (slot, value) in slots { + let entry = account.storage.get(slot).unwrap_or_else(|| panic!("{what}: no slot {slot}")); + assert_eq!(entry.present_value, *value, "{what}: slot {slot}"); + assert!(!entry.is_changed(), "{what}: slot {slot} is unchanged"); + } +} + +/// How many of the states `run` committed name the L1 block contract's `slot`, or its account +/// when `slot` is `None`. +fn times_named(run: &Run, slot: Option) -> usize { + run.committed + .iter() + .filter_map(|state| state.get(&L1_BLOCK_CONTRACT)) + .filter(|account| slot.is_none_or(|slot| account.storage.contains_key(&slot))) + .count() +} + +/// Whether any pre-block state of `run` names the L1 block contract. +fn pre_block_names_l1(run: &Run) -> bool { + run.pre_block.iter().any(|state| state.contains_key(&L1_BLOCK_CONTRACT)) +} + +/// A block of deposits alone prices nothing against the L1 block info and has no footprint, so +/// nothing of the L1 block contract is read: no pre-block state and no transaction's state names +/// it, and the database is asked for neither its account nor a slot. The block replays. #[test] -fn test_a_deposit_only_block_replays_and_reads_no_l1_slot() { - let mut db = common::database(); - db.set_account_code(CONTRACT, slot_writer()); +fn test_a_block_of_deposits_reads_nothing_of_the_l1_block_contract() { + let db = chain_with_l1_info(Bytes::from(vec![0x00])); // The first deposit also pays for the account the engine creates for its caller. let replay = Case::new("deposits", db) .tx(deposit( @@ -286,47 +309,85 @@ fn test_a_deposit_only_block_replays_and_reads_no_l1_slot() { assert_eq!(run.tx(0).depositor_nonce, Some(0)); assert_eq!(run.tx(1).depositor_nonce, Some(1), "the nonce the first deposit left"); assert_eq!(run.record.accounts.get(&DEPOSITOR), Some(&None)); - assert!(l1_entry(run).is_loaded_as_not_existing(), "the chain holds no L1 block contract"); - assert_eq!(run.record.accounts.get(&L1_BLOCK_CONTRACT), Some(&None), "read once, pre-block"); + assert!(!pre_block_names_l1(run), "no pre-block read of the L1 block contract"); + assert_eq!(times_named(run, None), 0, "no state names it"); + assert!(!run.record.accounts.contains_key(&L1_BLOCK_CONTRACT), "its account is not read"); assert!( !run.record.storage.keys().any(|(address, _)| *address == L1_BLOCK_CONTRACT), - "no slot of an absent contract is read" + "nor is a slot of it" ); if !common::state_is_free() { assert!(run.bucket_ids.len() >= 2, "the depositor's bucket and the slots'"); } } -/// A user transaction is priced against the L1 block info, which is read on the database itself -/// and not through the transaction's journal: the L1 block contract is in no transaction's state, -/// and the pre-block phase carries its account and slots as read-only entries with the chain's -/// values, so a witness built from the states holds what the transaction's L1 fee, operator fee -/// and footprint were computed from. The entry holds the overhead beside them, which the pricing -/// does not read while the scalars are set: the pre-block read is the one read of it. +/// Nothing reads the L1 block contract before the block's transactions, so a database that +/// cannot serve its account or one of its slots starts the block and runs a block of deposits, +/// which reads none of them. +#[test] +fn test_a_block_that_reads_no_l1_slot_runs_on_a_database_that_cannot_serve_one() { + let refusals = [ + ("the account", Some(L1_BLOCK_CONTRACT), None), + ("the L1 base fee", None, Some((L1_BLOCK_CONTRACT, L1_BASE_FEE_SLOT))), + ("the overhead", None, Some((L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT))), + ("the footprint scalar", None, Some((L1_BLOCK_CONTRACT, OPERATOR_FEE_SCALARS_SLOT))), + ]; + for (what, account, refused) in refusals { + let mut db = ErrorInjectingDatabase::new(chain_with_l1_info(Bytes::from(vec![0x00]))); + db.fail_on_account = account; + db.fail_on_storage = refused; + let mut state = State::builder().with_database(db).with_bundle_update().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(), + ); + executor.apply_pre_execution_changes().unwrap_or_else(|err| panic!("{what}: {err}")); + let tx = deposit( + DEPOSITOR, + TxKind::Call(CONTRACT), + 1_000_000_000, + U256::ZERO, + slot(9), + write_gas() + common::new_account_state_gas(), + ); + executor.execute_transaction(&tx).unwrap_or_else(|err| panic!("{what}: {err}")); + executor.finish().unwrap_or_else(|err| panic!("{what}: {err}")); + } +} + +/// A user transaction is priced against the L1 block info and held to the footprint by its +/// scalar, both read on the database itself and not through the transaction's journal. The first +/// transaction that reads them reports them, as read-only entries of its own state: the account +/// and the four slots its fee and footprint were computed from, with the chain's values. The +/// overhead, which the pricing does not read while the scalars are set, is not read, and no +/// pre-block state names the contract. The block replays from both witnesses. #[test] -fn test_a_user_transaction_is_priced_against_the_l1_info_the_pre_block_state_carries() { +fn test_the_first_transaction_priced_reports_the_l1_info_it_read() { let db = chain_with_l1_info(Bytes::from(vec![0x00])); let replay = Case::new("l1 info", db).tx(call(0, CONTRACT, slot(1), write_gas())).run(); let run = &replay.recorded; let tx = run.tx(0); assert!(tx.result.is_success(), "{:?}", tx.result); - assert!(!tx.state.contains_key(&L1_BLOCK_CONTRACT), "in no transaction's state"); + assert!(!pre_block_names_l1(run), "no pre-block read of the L1 block contract"); - let account = l1_entry(run); - assert!(!account.is_touched() && !account.is_created(), "a read-only entry"); + let account = l1_account(&tx.state); + assert_read_only("the transaction's report", account, &l1_info()); assert_eq!(account.info.code_hash, alloy_primitives::keccak256([0x00])); - let held = l1_info().into_iter().chain([(L1_OVERHEAD_SLOT, OVERHEAD)]); - assert_eq!(account.storage.len(), held.clone().count(), "the slots the pricing can read"); - for (slot, value) in held { - let entry = account.storage.get(&slot).expect("every slot of the set"); - assert_eq!(entry.present_value, value, "{slot}"); - assert!(!entry.is_changed(), "{slot} is unchanged"); + for (slot, value) in l1_info() { assert_eq!( run.record.storage.get(&(L1_BLOCK_CONTRACT, slot)), Some(&value), - "{slot} was read from the database, before the transactions" + "{slot} was read from the database" ); } + assert_eq!( + run.record.storage.get(&(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT)), + None, + "the overhead the set scalars leave unread is not read" + ); let footprint_scalar = u64::from(PARENT_FOOTPRINT_SCALAR); assert_eq!( @@ -340,27 +401,96 @@ fn test_a_user_transaction_is_priced_against_the_l1_info_the_pre_block_state_car } /// With the Ecotone scalars empty before the block the pricing reads the overhead at the first -/// transaction it prices; the pre-block entry holds the same five slots as with set scalars, the -/// overhead among them, and the block replays. +/// transaction it prices, which reports it beside the other four slots, and the block replays. #[test] -fn test_the_overhead_is_in_the_entry_when_the_scalars_are_empty() { +fn test_the_overhead_is_reported_when_the_scalars_are_empty() { let mut db = chain_with_l1_info(Bytes::from(vec![0x00])); db.set_account_storage(L1_BLOCK_CONTRACT, ECOTONE_L1_FEE_SCALARS_SLOT, U256::ZERO); let replay = Case::new("l1 overhead", db).tx(call(0, CONTRACT, slot(1), write_gas())).run(); let run = &replay.recorded; assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); - let account = l1_entry(run); - assert_eq!(account.storage.len(), l1_info().len() + 1, "the same set as with set scalars"); - let overhead = account.storage.get(&L1_OVERHEAD_SLOT).expect("in the entry"); - assert_eq!(overhead.present_value, OVERHEAD); - assert!(!overhead.is_changed()); + let mut read = l1_info().to_vec(); + read[1].1 = U256::ZERO; + read.push((L1_OVERHEAD_SLOT, OVERHEAD)); + assert_read_only("the transaction's report", l1_account(&run.tx(0).state), &read); assert_eq!(run.record.storage.get(&(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT)), Some(&OVERHEAD)); } +/// Two transactions are priced against the same L1 block info and read the same footprint scalar: +/// the first reports the account and the slots, and the second, whose reads they are too, reports +/// nothing again. The block replays. +#[test] +fn test_only_the_first_transaction_that_reads_the_l1_info_reports_it() { + let db = chain_with_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("two readers", db) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .tx(call(1, CONTRACT, slot(2), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert_read_only("the first reader", l1_account(&run.tx(0).state), &l1_info()); + assert!(!run.tx(1).state.contains_key(&L1_BLOCK_CONTRACT), "the second reports nothing"); + assert_eq!(times_named(run, None), 1, "the account is named once"); + for (slot, _) in l1_info() { + assert_eq!(times_named(run, Some(slot)), 1, "slot {slot} is named once"); + } +} + +/// A candidate the builder executes and drops reports what it read, but its state is not +/// committed: the first transaction of the block reports it in its place. The block replays. +#[test] +fn test_a_dropped_first_reader_leaves_the_report_to_the_next() { + let db = chain_with_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("dropped first reader", db) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .dropped(0) + .tx(call(0, CONTRACT, slot(2), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.refusal(0).contains("dropped"), "{}", run.refusal(0)); + assert!(run.tx(1).result.is_success(), "{:?}", run.tx(1).result); + assert_read_only("the first included reader", l1_account(&run.tx(1).state), &l1_info()); + assert_eq!(times_named(run, None), 1); +} + +/// A Mega System Transaction pays no L1 fee, so no fee computation prices it, but the block +/// reads the footprint scalar before it as before every non-deposit transaction: as the block's +/// first reader it reports the account and the scalar's slot alone. The user transaction after +/// it, the first the fee computation prices, reports the fee's other slots, and not the scalar's +/// again. Alone in its block, the system transaction reports the same. Both blocks replay. +#[test] +fn test_a_mega_system_transaction_reports_the_footprint_scalar_it_reads() { + let footprint = [(OPERATOR_FEE_SCALARS_SLOT, parent_scalars_word())]; + + let db = chain_with_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("system transaction alone", db).tx(common::system_tx()).run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_eq!(run.tx(0).gas.history, 0, "the protocol's own transaction"); + assert_read_only("the system transaction", l1_account(&run.tx(0).state), &footprint); + assert_eq!(run.tx(0).da_footprint, run.tx(0).da_size * u64::from(PARENT_FOOTPRINT_SCALAR)); + + let db = chain_with_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("system transaction first", db) + .tx(common::system_tx()) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert_read_only("the system transaction", l1_account(&run.tx(0).state), &footprint); + let fee: Vec<_> = + l1_info().into_iter().filter(|(slot, _)| *slot != OPERATOR_FEE_SCALARS_SLOT).collect(); + assert_read_only("the first transaction priced", l1_account(&run.tx(1).state), &fee); + for (slot, _) in l1_info() { + assert_eq!(times_named(run, Some(slot)), 1, "slot {slot} is named once"); + } +} + /// The production shape: the L1 attributes deposit comes first and writes the block's info over -/// the parent's. The pre-block entry holds the parent's values, the deposit's own returned state -/// holds the write, and the transaction after the deposit is priced against the write; so -/// everything its footprint was computed from is in one of the block's states. +/// the parent's. The deposit's own returned state holds the write, and reads nothing for a fee or +/// a footprint; the transaction after it is priced against the write and reports what it read, +/// the deposit's values, as read-only entries. Everything its fee and footprint were computed +/// from is in one of the block's states. #[test] fn test_the_l1_attributes_deposit_first_prices_the_transactions_after_it() { let db = chain_with_l1_info(l1_block_setter()); @@ -380,13 +510,17 @@ fn test_the_l1_attributes_deposit_first_prices_the_transactions_after_it() { assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); assert!(run.tx(1).result.is_success(), "{:?}", run.tx(1).result); - let before = l1_entry(run).storage.get(&OPERATOR_FEE_SCALARS_SLOT).expect("in the entry"); - assert_eq!(before.present_value, parent_scalars_word(), "the parent's info, pre-block"); - let written = &run.tx(0).state[&L1_BLOCK_CONTRACT].storage[&OPERATOR_FEE_SCALARS_SLOT]; + let deposit = l1_account(&run.tx(0).state); + assert_eq!(deposit.storage.len(), 1, "the deposit's state names its write alone"); + let written = &deposit.storage[&OPERATOR_FEE_SCALARS_SLOT]; assert_eq!(written.original_value, parent_scalars_word()); assert_eq!(written.present_value, word, "the deposit's state carries the write"); assert_eq!(run.tx(0).da_footprint, 0, "a deposit has no footprint"); + let mut read = l1_info(); + read[3].1 = word; + assert_read_only("the transaction after the deposit", l1_account(&run.tx(1).state), &read); + let tx = run.tx(1); assert_eq!( tx.da_footprint, @@ -420,24 +554,29 @@ fn scalars_emptied_in_the_block(overhead: U256) -> Case { } /// The scalars are set before the block and a deposit empties them, so the L1 info the next -/// transaction is priced against is fetched with empty scalars and reads the overhead. No -/// transaction's state names that slot: the deposit wrote the scalars alone, and the fetch is not -/// in the user transaction's journal. The pre-block entry carries the overhead whatever the -/// scalars hold before the block, so the channel witness holds it and the block replays. +/// transaction is priced against is fetched with empty scalars and reads the overhead. The +/// deposit wrote the scalars alone, and names no overhead: the user transaction reports it, once, +/// as a read-only entry of its own state, with the other slots it read, so the channel witness +/// holds it and the block replays. #[test] -fn test_a_deposit_emptying_the_scalars_leaves_the_overhead_in_the_witness() { +fn test_a_deposit_emptying_the_scalars_has_the_next_transaction_report_the_overhead() { let case = scalars_emptied_in_the_block(OVERHEAD); let recorded = case.record(); assert!(recorded.tx(0).result.is_success(), "{:?}", recorded.tx(0).result); assert!(recorded.tx(1).result.is_success(), "{:?}", recorded.tx(1).result); - let written = &recorded.tx(0).state[&L1_BLOCK_CONTRACT].storage; + let written = &l1_account(&recorded.tx(0).state).storage; let scalars = &written[&ECOTONE_L1_FEE_SCALARS_SLOT]; assert_eq!(scalars.original_value, fee_scalars_word(1_000_000, 1_000_000), "set before"); assert_eq!(scalars.present_value, U256::ZERO, "the deposit emptied the scalars"); assert!(!written.contains_key(&L1_OVERHEAD_SLOT), "the deposit's state names no overhead"); + let tx = recorded.tx(1); - assert!(!tx.state.contains_key(&L1_BLOCK_CONTRACT), "nor does the transaction after it"); + let mut read = l1_info().to_vec(); + read[1].1 = U256::ZERO; + read.push((L1_OVERHEAD_SLOT, OVERHEAD)); + assert_read_only("the transaction after the deposit", l1_account(&tx.state), &read); + assert_eq!(times_named(&recorded, Some(L1_OVERHEAD_SLOT)), 1, "the overhead, once"); assert!( tx.state.get(&L1_FEE_RECIPIENT).is_none_or(|vault| vault.info.balance.is_zero()), "priced against the scalars the deposit left: no L1 fee" @@ -449,43 +588,82 @@ fn test_a_deposit_emptying_the_scalars_leaves_the_overhead_in_the_witness() { ); let witness = case.channel_witness(&recorded); - let channel = case.replay(&witness, &recorded.included(), Oracle::Recorded); - assert!( - channel.txs[1].is_ok(), - "the transaction after the deposit replays from the channel witness: {:?}", - channel.txs[1].as_ref().err() - ); assert_eq!( witness.storage.get(&(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT)), Some(&OVERHEAD), - "which holds the overhead" + "the channel witness holds the overhead" ); - let entry = l1_entry(&recorded).storage.get(&L1_OVERHEAD_SLOT).expect("in the entry"); - assert_eq!(entry.present_value, OVERHEAD, "named by the pre-block entry, with set scalars"); + let channel = case.replay(&witness, &recorded.included(), Oracle::Recorded); + assert_same_run("scalars emptied in the block (channel witness)", &recorded, &channel); case.run(); } +/// The L1 block contract's entry of a transaction's state, taken out, so two runs that read other +/// values there can be compared on everything else. +fn without_l1_entry(run: &Run) -> Vec> { + let mut txs = run.txs.clone(); + for tx in txs.iter_mut().flatten() { + if !tx.is_deposit { + tx.state.remove(&L1_BLOCK_CONTRACT); + } + } + txs +} + /// The overhead is a slot the block must be able to read, and nothing more: the fee of a /// transaction priced with empty scalars does not take it in, so the same block on a chain that -/// holds another overhead produces the same transactions, receipts and state changes. +/// holds another overhead produces the same transactions, receipts and state changes; only the +/// value its report carries differs. #[test] fn test_the_overhead_a_block_reads_decides_no_result() { let held = scalars_emptied_in_the_block(OVERHEAD).run().recorded; let zero = scalars_emptied_in_the_block(U256::ZERO).run().recorded; - assert_eq!(l1_entry(&held).storage[&L1_OVERHEAD_SLOT].present_value, OVERHEAD); - assert_eq!(l1_entry(&zero).storage[&L1_OVERHEAD_SLOT].present_value, U256::ZERO); - assert_eq!(held.txs, zero.txs, "the transactions"); + let overhead = + |run: &Run| l1_account(&run.tx(1).state).storage[&L1_OVERHEAD_SLOT].present_value; + assert_eq!(overhead(&held), OVERHEAD); + assert_eq!(overhead(&zero), U256::ZERO); + assert_eq!(without_l1_entry(&held), without_l1_entry(&zero), "the transactions"); assert_eq!(held.receipts, zero.receipts, "the receipts"); assert_eq!(held.bundle, zero.bundle, "the state changes"); assert_eq!((held.gas_used, held.blob_gas_used), (zero.gas_used, zero.blob_gas_used)); } -/// The entry's other condition: a chain that does not hold the L1 block contract has it recorded -/// as not existing, with no slot. A deposit that creates the account in the block does not turn -/// its slots into database reads: the slots of an account the block created are the block's own, -/// so the transaction priced after the deposit reads none from the chain, and the witness, which -/// holds the account as absent and no slot of it, replays the block. +/// A transaction whose own execution writes the L1 block contract keeps its write: code at the +/// contract that empties the scalars, called by the first transaction the fee computation prices. +/// Its state names the account as the call left it, touched, and the scalars' slot as it wrote it, +/// from the set scalars it was priced with to zero; the report adds the other slots it read as +/// read-only entries and replaces neither. The block replays. +#[test] +fn test_a_transaction_that_writes_the_l1_block_contract_keeps_its_write() { + let db = chain_with_l1_info(scalars_emptier()); + let replay = Case::new("a reader that writes the L1 block contract", db) + .tx(call(0, L1_BLOCK_CONTRACT, Bytes::new(), creation_gas())) + .run(); + let run = &replay.recorded; + let tx = run.tx(0); + assert!(tx.result.is_success(), "{:?}", tx.result); + let account = l1_account(&tx.state); + assert!(account.is_touched(), "the call's own entry, not a read-only one"); + let scalars = &account.storage[&ECOTONE_L1_FEE_SCALARS_SLOT]; + assert_eq!(scalars.original_value, fee_scalars_word(1_000_000, 1_000_000), "priced on it"); + assert_eq!(scalars.present_value, U256::ZERO, "the transaction's write stands"); + for (slot, value) in l1_info() { + if slot == ECOTONE_L1_FEE_SCALARS_SLOT { + continue; + } + let entry = account.storage.get(&slot).unwrap_or_else(|| panic!("slot {slot} reported")); + assert_eq!(entry.present_value, value, "slot {slot}"); + assert!(!entry.is_changed(), "slot {slot} is read only"); + } + assert_eq!(account.storage.len(), l1_info().len(), "no overhead: the scalars were set"); +} + +/// The entry's other condition: a chain that does not hold the L1 block contract. A deposit that +/// creates the account in the block does not turn its slots into database reads: the slots of an +/// account the block created are the block's own, so the transaction priced after the deposit +/// reads none from the chain, and the witness, which holds the account as absent and no slot of +/// it, replays the block. #[test] fn test_a_deposit_creating_the_l1_block_contract_adds_no_slot_read() { let mut db = common::database(); @@ -503,9 +681,12 @@ fn test_a_deposit_creating_the_l1_block_contract_adds_no_slot_read() { let recorded = case.record(); assert!(recorded.tx(0).result.is_success(), "{:?}", recorded.tx(0).result); assert!(recorded.tx(1).result.is_success(), "{:?}", recorded.tx(1).result); - assert!(l1_entry(&recorded).is_loaded_as_not_existing(), "absent before the block"); - let created = &recorded.tx(0).state[&L1_BLOCK_CONTRACT]; + assert!(!pre_block_names_l1(&recorded), "no pre-block read of the L1 block contract"); + let created = l1_account(&recorded.tx(0).state); assert_eq!(created.info.balance, U256::from(1_000), "the deposit created the account"); + let reported = l1_account(&recorded.tx(1).state); + assert!(!reported.is_touched(), "the transaction after it reports the account read-only"); + assert_eq!(recorded.record.accounts.get(&L1_BLOCK_CONTRACT), Some(&None), "absent before"); assert!( !recorded.record.storage.keys().any(|(address, _)| *address == L1_BLOCK_CONTRACT), "no slot of it is read from the database, before the deposit or after" @@ -520,33 +701,77 @@ fn test_a_deposit_creating_the_l1_block_contract_adds_no_slot_read() { case.run(); } -/// The pre-block read of the L1 block info is made for every block, so a database that cannot -/// serve the contract's account, or one of the five slots of a contract the chain holds, cannot -/// start the block: the read fails before the first transaction, whatever the block holds — a -/// block of deposits alone, which prices nothing against the contract, included — and so does a -/// read of the overhead beside set scalars, which no transaction of the block would make. The -/// failure is the node's database's, not a verdict on the block: an internal error. +/// A block on `db` that starts, then executes `tx`. +fn execute_one(db: DB, tx: &Tx) -> Result<(), BlockExecutionError> +where + DB: alloy_evm::Database + revm::DatabaseCommit, +{ + let evm = MegaEvmFactory::new().create_evm(db, common::evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ); + executor.apply_pre_execution_changes().expect("nothing reads the L1 block contract yet"); + executor.execute_transaction(tx).map(drop) +} + +/// A database over the L1 info that cannot serve the L1 block contract's `slot`, or its account +/// when `slot` is `None`. +fn refusing(slot: Option) -> ErrorInjectingDatabase { + let mut db = ErrorInjectingDatabase::new(chain_with_l1_info(Bytes::from(vec![0x00]))); + match slot { + Some(slot) => db.fail_on_storage = Some((L1_BLOCK_CONTRACT, slot)), + None => db.fail_on_account = Some(L1_BLOCK_CONTRACT), + } + db +} + +/// The L1 base fee is read by the fee computation alone, inside the transaction's execution: a +/// database that cannot serve it gives the transaction no outcome, and the failure is reported as +/// any failed read of a transaction's execution is, by whether the database declares it fatal — +/// an internal error when it does, an invalid block when it does not. The block starts all the +/// same: nothing reads the slot before the transaction. #[test] -fn test_a_database_that_cannot_serve_the_l1_entry_fails_the_block_as_internal() { - let refusals = [ - ("the account", Some(L1_BLOCK_CONTRACT), None), - ("the L1 base fee", None, Some((L1_BLOCK_CONTRACT, L1_BASE_FEE_SLOT))), - ("the overhead beside set scalars", None, Some((L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT))), +fn test_a_failed_fee_read_is_routed_as_the_transactions_own() { + let tx = call(0, CONTRACT, slot(1), write_gas()); + + let mut state = State::builder() + .with_database(refusing(Some(L1_BASE_FEE_SLOT))) + .with_bundle_update() + .build(); + let err = execute_one(&mut state, &tx).expect_err("the L1 base fee cannot be read"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "fatal: {err:?}"); + + let err = execute_one(common::NotFatal(refusing(Some(L1_BASE_FEE_SLOT))), &tx) + .expect_err("the L1 base fee cannot be read"); + assert!( + matches!(err, BlockExecutionError::Validation(BlockValidationError::EVM { .. })), + "not fatal: {err:?}" + ); +} + +/// The footprint scalar is read by the block before a non-deposit transaction runs, outside its +/// execution: a database that cannot serve the L1 block contract's account or the scalar's slot +/// fails the block as an internal error, whether or not it declares the error fatal, before an +/// ordinary transaction and before a Mega System Transaction alike. The block starts all the +/// same: nothing reads them before the transaction. +#[test] +fn test_a_failed_footprint_read_is_an_internal_error() { + let txs = [ + ("a user transaction", call(0, CONTRACT, slot(1), write_gas())), + ("a Mega System Transaction", common::system_tx()), ]; - for (what, account, slot) in refusals { - let mut db = ErrorInjectingDatabase::new(chain_with_l1_info(Bytes::from(vec![0x00]))); - db.fail_on_account = account; - db.fail_on_storage = slot; - let mut state = State::builder().with_database(db).with_bundle_update().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(), - ); - let err = executor.apply_pre_execution_changes().expect_err(what); - assert!(matches!(err, BlockExecutionError::Internal(_)), "{what}: {err:?}"); - assert!(err.to_string().contains(&L1_BLOCK_CONTRACT.to_string()), "{what}: {err}"); + for (what, tx) in &txs { + for slot in [None, Some(OPERATOR_FEE_SCALARS_SLOT)] { + let err = execute_one(common::NotFatal(refusing(slot)), tx) + .expect_err("the footprint scalar cannot be read"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{what}, {slot:?}: {err:?}"); + assert!( + err.to_string().contains(&L1_BLOCK_CONTRACT.to_string()), + "{what}, {slot:?}: {err}" + ); + } } } diff --git a/crates/mega-evm/tests/tracers/harness.rs b/crates/mega-evm/tests/tracers/harness.rs index 289518da9..aca19dfca 100644 --- a/crates/mega-evm/tests/tracers/harness.rs +++ b/crates/mega-evm/tests/tracers/harness.rs @@ -571,9 +571,10 @@ pub(crate) fn assert_root_gas_used_is_the_receipt(traced: &Traced) { /// /// One read is outside every transaction's state by design, and is the only one excused: op-revm /// reads the L1 block contract's account and the slots of `L1_BLOCK_INFO_SLOTS` on the database -/// itself, not through the journal, to price a transaction's L1 fee. Block execution hands -/// exactly those keys to the witness as a pre-block read (`read_l1_block_info`). The excuse is -/// those keys, read or not, and nothing else. +/// itself, not through the journal, to price a transaction's L1 fee. A transaction run on its own +/// reports them nowhere; block execution adds the keys its fee computation and footprint read to +/// the state of the first transaction of the block that read them. The excuse is those keys, read +/// or not, and nothing else. /// /// An account the engine read without its code — the `SequencerRegistry`'s, which every /// transaction's validation reads by its code hash — is named with the code the pre-state holds, From e627d2b774ef5916244974faeb864b5faa132855 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:09:12 +0800 Subject: [PATCH 034/190] test(evm): cover modexp pricing before size rejection --- crates/mega-evm/src/evm/precompiles.rs | 52 +++++++++++++++++- crates/mega-evm/tests/satin/withheld_gas.rs | 61 ++++++++++++++++++--- docs/spec/upgrades/satin.md | 5 +- 3 files changed, 107 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index bb0c3d818..77cef5047 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -609,15 +609,61 @@ mod tests { /// A `ModExp` header of `base_len`, `exp_len` and `mod_len`, followed by the operands. fn modexp_input(base: &[u8], exponent: &[u8], modulus: &[u8]) -> Bytes { let mut input = std::vec![0u8; 96]; - input[31] = base.len() as u8; - input[63] = exponent.len() as u8; - input[95] = modulus.len() as u8; + input[..32].copy_from_slice(&U256::from(base.len()).to_be_bytes::<32>()); + input[32..64].copy_from_slice(&U256::from(exponent.len()).to_be_bytes::<32>()); + input[64..96].copy_from_slice(&U256::from(modulus.len()).to_be_bytes::<32>()); input.extend_from_slice(base); input.extend_from_slice(exponent); input.extend_from_slice(modulus); Bytes::from(input) } + #[test] + fn test_modexp_over_bound_input_is_priced_before_its_size_check() { + let address = *revm::precompile::modexp::OSAKA.address(); + let input = modexp_input(&[0; 1_025], &[0], &[0]); + // EIP-7883: 2 * ceil(1025 / 8)^2, with one iteration for a zero exponent. + let price = 2 * 129_u64.pow(2); + let priced = PricedPrecompiles::default(); + assert_eq!(priced.price(&satin_precompiles_map(), &address, &input), Some(price)); + + for (gas, expected) in [ + (499, InstructionResult::PrecompileOOG), + (500, InstructionResult::PrecompileOOG), + (price - 1, InstructionResult::PrecompileOOG), + (price, InstructionResult::PrecompileError), + (price + 1, InstructionResult::PrecompileError), + ] { + let result = run(address, input.clone(), gas); + assert_eq!(result.result, expected, "gas={gas}"); + assert_eq!(result.gas.remaining(), 0, "gas={gas}: a halt burns the forward"); + } + } + + #[test] + fn test_modexp_unpayable_lengths_run_out_of_gas() { + let address = *revm::precompile::modexp::OSAKA.address(); + for position in 0..3 { + let mut input = modexp_input(&[0], &[0], &[0]).to_vec(); + input[position * 32..(position + 1) * 32] + .copy_from_slice(&(U256::from(1) << 64_usize).to_be_bytes::<32>()); + assert_eq!( + PricedPrecompiles::default().price(&satin_precompiles_map(), &address, &input), + Some(u64::MAX), + "position={position}" + ); + for gas in [0, 499, 500, 100_000, u64::MAX - 1, u64::MAX] { + let result = run(address, Bytes::copy_from_slice(&input), gas); + assert_eq!( + result.result, + InstructionResult::PrecompileOOG, + "position={position}, gas={gas}" + ); + assert_eq!(result.gas.remaining(), 0, "position={position}, gas={gas}"); + } + } + } + /// `ModExp` is the Osaka entry: a one-byte exponentiation costs the Osaka 500-gas minimum, /// not the 200 of the Berlin entry Karst removed, and an exponentiation large enough for the /// EIP-7883 formula to bite is priced by the formula rather than by the minimum. diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 4c9070ec1..72c39fceb 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1539,21 +1539,68 @@ fn test_a_priced_and_an_unpriced_precompile_part_as_a_failed_call_and_a_crossing /// default cap the allowance pays the price, and the call fails on its input as without the read. #[test] fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowance() { - let input = vec![0_u8; 3 * 192 + 1]; + assert_invalid_precompile_is_held_from_its_price(EC_PAIRING, &[0_u8; 3 * 192 + 1], 100_000); +} + +#[test] +fn test_modexp_over_bound_input_crosses_at_its_formula_price() { + let input: Vec = [U256::from(1_025), U256::from(1), U256::from(1)] + .into_iter() + .flat_map(|len| len.to_be_bytes::<32>()) + .collect(); + // Its 33,282-gas formula price exceeds this cap; the old 500-gas quote did not. + assert_invalid_precompile_is_held_from_its_price(MODEXP, &input, 16_641); +} + +#[test] +fn test_modexp_over_bound_input_returns_its_forward_at_the_default_compute_cap() { + let input: Vec = [U256::from(1_025), U256::from(80), U256::from(1)] + .into_iter() + .flat_map(|len| len.to_be_bytes::<32>()) + .collect(); + // EIP-7883: 2 * 129^2 * (16 * (80 - 32)) = 25,560,576, above the default cap. + let forward = 30_000_000; + for gas_limit in TIERS { + let run = |first| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, MODEXP, Some(forward))); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx_with(&input, gas_limit)); + let call = evm.inspector().calls.iter().find(|call| call.target == MODEXP).unwrap(); + (run, call.spent, call.precompile_ran) + }; + let ((detained, spent, ran), (plain, plain_spent, plain_ran)) = + (run(TIMESTAMP), run(PUSH0)); + let allowance = CAP - charges_to_the_precompile(input.len(), Some(forward)).total(); + assert_caught( + &detained, + intrinsic_with(&input, gas_limit), + allowance, + &failed_status_store(), + ); + assert_eq!(spent, 0, "the crossing returns the whole forward"); + assert!(!ran && plain_ran); + assert_eq!(plain_spent, u64::from(forward), "the size failure burns the forward"); + assert!(detained.outcome.gas.regular < plain.outcome.gas.regular); + } +} + +/// An input rejected after its gas check crosses when its price lies between allowance and forward. +fn assert_invalid_precompile_is_held_from_its_price(to: Address, input: &[u8], cap: u64) { for gas_limit in TIERS { let run = |first, cap| { let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); - let code = calls_precompile(first, EC_PAIRING, None); + let code = calls_precompile(first, to, None); let db = MemoryDatabase::default().account_code(CONTRACT, code); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) .with_inspector(Calls::default()); - let run = run_on(&mut evm, tx_with(&input, gas_limit)); - let call = evm.inspector().calls.iter().find(|call| call.target == EC_PAIRING).unwrap(); + let run = run_on(&mut evm, tx_with(input, gas_limit)); + let call = evm.inspector().calls.iter().find(|call| call.target == to).unwrap(); (run, call.precompile_ran) }; - let ((detained, ran), (plain, plain_ran)) = (run(TIMESTAMP, 100_000), run(PUSH0, 100_000)); - let allowance = 100_000 - charges_to_the_precompile(input.len(), None).total(); - let intrinsic = intrinsic_with(&input, gas_limit); + let ((detained, ran), (plain, plain_ran)) = (run(TIMESTAMP, cap), run(PUSH0, cap)); + let allowance = cap - charges_to_the_precompile(input.len(), None).total(); + let intrinsic = intrinsic_with(input, gas_limit); assert_caught(&detained, intrinsic, allowance, &failed_status_store()); assert!(!ran && plain_ran, "answered without running"); assert!(plain.outcome.result.is_success()); diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index cc04c1609..9770d317b 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -113,7 +113,10 @@ The precompile set MUST be Karst's, with KZG point evaluation at MegaETH's price | BLS12-381 pairing | `0x0F` | Input of at most 156,672 bytes | | Every other precompile | Any | As Karst defines it | -An input over a size limit fails the call before any gas check, as the Optimism specification of the limit has it, a call forwarded no gas included; like every precompile call that fails, it consumes all the gas forwarded to it. +An input over an Optimism pairing or MSM size limit fails the call before any gas check, a call forwarded no gas included; like every precompile call that fails, it consumes all the gas forwarded to it. +ModExp MUST first charge its 500-gas minimum, then the rest of its Osaka formula price with each length saturated to 64 bits, and only then check EIP-7823's 1,024-byte bound on each length. +A call that cannot pay the minimum MUST fail before reading the lengths; a formula price beyond any representable gas limit MUST fail out of gas even at the maximum gas limit. +Gas detention MUST use that same formula price for an over-bound input, so a price above the allowance but within the forwarded gas stops the call before its size check. KZG point evaluation keeps its Rex6 semantics: a call given less than 100,000 gas fails with an out-of-gas before any verification runs, and a successful call is charged exactly 100,000. A KZG call given at least 100,000 gas that fails otherwise — an input of the wrong length, a versioned hash that does not match the commitment, a proof that does not verify — consumes all the gas forwarded to it, not 100,000. From 4627a85b93201e7e3026089622302900aa3faec9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:09:41 +0800 Subject: [PATCH 035/190] feat(evm): read the Oracle slot before its charge, refuse volatile reads for free An SLOAD in the Oracle's own frame loads the slot, asks the oracle service and marks the read at the compute before the opcode, then charges its 2,100 as one charge. A read refused while volatile-data access is off reverts on the gas the frame held at the opcode: the read wrappers charge their opcode's static gas themselves once the read is not refused, block-environment reads are refused before their operands, account, call and SELFDESTRUCT reads once their operands are present and before their body, a call target's delegate read as a required read that warms nothing. --- crates/mega-evm/src/access/detention.rs | 24 +- crates/mega-evm/src/access/mod.rs | 23 +- crates/mega-evm/src/evm/context.rs | 29 ++ crates/mega-evm/src/evm/host.rs | 89 +++-- crates/mega-evm/src/evm/instructions.rs | 353 ++++++++++++++---- crates/mega-evm/src/evm/mod.rs | 25 ++ crates/mega-evm/src/test_utils/neutral.rs | 26 +- crates/mega-evm/tests/block/witness/skips.rs | 161 +++++--- crates/mega-evm/tests/satin/detention.rs | 217 ++++++++--- crates/mega-evm/tests/satin/stops.rs | 16 +- .../mega-evm/tests/satin/volatile_access.rs | 120 +++++- .../tests/system/keyless/detention.rs | 11 +- .../mega-evm/tests/system/oracle_storage.rs | 165 +++++--- 13 files changed, 947 insertions(+), 312 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 5de739335..923925cea 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -166,10 +166,11 @@ impl FrameFigures { /// # Refused reads /// /// A frame in a subtree where volatile-data access is switched off does not read volatile data: -/// the Host refuses the load and the opcode's wrapper reverts the frame with -/// `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. +/// the opcode's wrapper refuses the read before the opcode runs, and reverts the frame with +/// `VolatileDataAccessDisabled`; the Host refuses a load it would mark all the same, which no +/// opcode reaches. 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 /// @@ -323,15 +324,6 @@ impl Detention { !(self.observed.get() | self.refused.get()).is_empty() } - /// Names a refusal the running opcode's Host calls made `access`, whichever load was refused: - /// the kind the opcode reads, for an opcode that loads another kind first. - #[inline] - pub(crate) fn name_refusal(&self, access: VolatileDataAccess) { - if !self.refused.get().is_empty() { - self.refused.set(access); - } - } - /// Takes what the Host refused for the running opcode, if it refused anything. pub(crate) fn take_refused(&self) -> Option { let refused = self.refused.replace(VolatileDataAccess::empty()); @@ -1237,11 +1229,9 @@ mod tests { 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"); + assert_eq!(detention.take_refused(), Some(VolatileDataAccess::BLOCK_NUMBER)); + assert_eq!(detention.take_refused(), None, "a refusal is taken once"); detention.on_frame_end(InstructionResult::Stop, &mut child, 1); assert!(!detention.is_access_disabled(1), "on again once the frame returned"); diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 613c9161a..306d3166d 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -40,6 +40,12 @@ //! 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. //! +//! The Oracle's read is the exception: an `SLOAD` in the Oracle's own frame reads the slot before +//! it charges any of its gas, and its wrapper commits the read at once, at the transaction's +//! compute before the opcode; then the cold access is charged, its warm base included, as one +//! charge. The mark stands for the rest of the transaction, though the frame then runs out of gas +//! or is stopped at that charge. +//! //! 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 @@ -167,12 +173,17 @@ //! # Refused reads //! //! `MegaAccessControl` can switch volatile-data access off for a frame and every frame below it. -//! The Host then refuses the load and the opcode's wrapper reverts the frame with -//! `VolatileDataAccessDisabled(accessType)`. The refusal comes before the load, so a refused read -//! reads nothing and caps nothing, and the frame keeps the gas it had before the opcode: the -//! opcode's static gas is charged, as for any instruction that ran, and nothing else. A refusal -//! names the kind the opcode reads — `BLOCKHASH`'s names the hash, though the opcode loads the -//! block number first — and a `SLOTNUM` refusal names access type 12 +//! The opcode's wrapper then refuses a volatile read before the opcode charges or checks anything, +//! and reverts the frame with `VolatileDataAccessDisabled(accessType)` on the gas it held when it +//! reached the opcode: a refused read reads nothing, caps nothing and costs nothing, not even the +//! opcode's static gas, which the wrapper charges only once it decided the read is not refused, so +//! a frame short of the static gas is refused rather than run out of gas. An opcode volatile +//! whatever its operands is refused before its operands are read; one volatile for the account or +//! the storage it reads is refused once every operand it takes is on the stack, when its target, +//! its frame or a call target's one-hop EIP-7702 delegate shows it reads the beneficiary's account +//! or the Oracle's storage, the delegate read for the decision without warming anything. A refusal +//! names the kind the opcode reads — `BLOCKHASH`'s names the hash, whatever its operand — and a +//! `SLOTNUM` refusal names access type 12 //! ([`SLOT_NUM_ACCESS_TYPE`](crate::system::SLOT_NUM_ACCESS_TYPE)), which the contract's //! `VolatileDataAccessType` does not declare. The error's argument is encoded as a `uint8`, and //! Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index a1739447d..8f7d3c791 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -74,6 +74,10 @@ pub struct MegaContext, } impl MegaContext { @@ -113,6 +117,8 @@ impl MegaContext { keyless_creation: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, + #[cfg(any(test, feature = "test-utils"))] + read_static_gas: None, } } @@ -199,6 +205,29 @@ impl MegaContext { self.neutral } + /// The static gas of `opcode`, one of the opcodes that can read volatile data, which its read + /// wrapper charges itself once it decided the read is not refused, in place of the + /// interpreter: Satin's, or, once the test tooling installed a fixture fork's static prices on + /// the EVM, the fork's. + #[inline(always)] + pub(crate) fn read_static_gas(&self, opcode: u8) -> u64 { + #[cfg(any(test, feature = "test-utils"))] + if let Some(table) = &self.read_static_gas { + return u64::from(table[opcode as usize]); + } + u64::from(super::instructions::SATIN_GAS_TABLE[opcode as usize]) + } + + /// Has the read wrappers charge `table`'s static prices: test tooling, with which an EVM takes + /// a fixture fork's static prices. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) const fn set_read_static_gas( + &mut self, + table: revm::interpreter::instructions::GasTable, + ) { + self.read_static_gas = Some(table); + } + /// Whether the context runs the neutral configuration: never outside the test tooling, which /// alone can set it. #[inline] diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 88f658c11..c3b82344d 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -22,21 +22,22 @@ //! accessors, the account load when the account is the block beneficiary, the storage load when //! the storage is the Oracle's, and `SELFDESTRUCT` when either end is the beneficiary. A read is //! marked once the load succeeded, and the opcode's wrapper commits it once the opcode completed -//! (see the `access` module). Every account opcode reaches the account load: `balance`, -//! `load_account_delegated`, `load_account_code` and `load_account_code_hash` are the trait's own, -//! built on it. +//! (see the `access` module), but for the Oracle's, which its wrapper commits before it charges +//! the read. Every account opcode reaches the account load: `balance`, `load_account_delegated`, +//! `load_account_code` and `load_account_code_hash` are the trait's own, built on it. //! -//! While volatile-data access is switched off for the running frame, the Host refuses those loads -//! instead: an account or storage load fails as a skipped cold load, and a block-environment -//! accessor answers zero. Nothing is loaded, and the opcode's wrapper turns the refusal into the -//! frame's revert. +//! While volatile-data access is switched off for the running frame, the opcode's wrapper refuses +//! a volatile read before the opcode runs, so the Host loads none. Were one reached, the Host +//! would refuse it: an account or storage load fails as a skipped cold load, and a +//! block-environment accessor answers zero. Nothing is loaded, and the opcode's wrapper turns the +//! refusal into the frame's revert. //! //! # The Oracle's storage //! //! A storage load whose owner is the Oracle reads the slot from the node's oracle service //! ([`OracleEnv`]) and falls back to the database for a slot the service has no value for. Every //! such read is priced as a cold access, because a node replaying a block cannot tell which of the -//! two sources the node that built it read. +//! two sources the node that built it read, and is made before that access is charged. //! //! # One hook prices every state charge //! @@ -84,7 +85,7 @@ use std::format; use delegate::delegate; use revm::{ - context::ContextTr, + context::{ContextTr, JournalTr}, context_interface::{ cfg::{gas::GasTracker, GasId, GasParams, StateGasCharge, StateGasSite}, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, @@ -94,10 +95,13 @@ use revm::{ }, journaled_state::AccountInfoLoad, }, + interpreter::InstructionResult, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, + state::Bytecode, Database, }; +use super::execution::{mark, revert_to}; use crate::{ charge_write_records_history, history_gas, limit::{DestroyedParts, HistoryBytes}, @@ -205,7 +209,7 @@ impl revm::context_interface::Host } /// Loads the slot; a slot of the Oracle's storage is read through the oracle environment - /// ([`oracle_sload`](Self::oracle_sload)). + /// ([`read_oracle_slot`](MegaContext::read_oracle_slot)). #[inline] fn sload_skip_cold_load( &mut self, @@ -214,7 +218,12 @@ impl revm::context_interface::Host skip_cold_load: bool, ) -> Result, LoadError> { if address == ORACLE_CONTRACT_ADDRESS { - return self.oracle_sload(key, skip_cold_load); + // `SLOAD` reads the Oracle's storage through its wrapper, before any of its charge; a + // tool's read of it comes here, and skips the read when it asks to. + if skip_cold_load { + return Err(LoadError::ColdLoadSkipped); + } + return self.read_oracle_slot(key).map(|value| StateLoad::new(value, true)); } self.inner.sload_skip_cold_load(address, key, skip_cold_load) } @@ -405,9 +414,10 @@ impl revm::context_interface::Host /// 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. + /// start revm then refuses 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 value the caller cannot + /// fund makes no record either, and is priced none here, so its charge is nothing: only a + /// value call's history allowance is parked for it, and comes back when it returns. /// /// 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 @@ -646,25 +656,17 @@ impl MegaContext { /// frame made earlier included, and are loaded, priced and marked as any other read (see /// [`MegaContext::asks_oracle_service`]). /// - /// A frame whose regular gas, the part detention withholds included, cannot pay the cold - /// access reads nothing and asks nothing, as revm's own skipped cold load does. A detained - /// frame that holds the gas but may not spend it does read and ask, and the charge then stops - /// the transaction at the compute limit. + /// The read is made before its cold access is charged, whatever gas the frame holds: `SLOAD`'s + /// wrapper reads, then charges, so a frame that cannot pay the access has read the slot and + /// asked the environment all the same, and so has one gas detention then stops. /// - /// It is a read of volatile data: it is refused while the frame's volatile-data access is off, - /// and marked for gas detention, under the Oracle's cap, once it succeeded. + /// It is a read of volatile data: marked for gas detention, under the Oracle's cap, once it + /// succeeded. A frame whose volatile-data access is off is refused it before it is made. /// /// A read that asks is recorded, with the answer, on the context for the transaction's outcome /// ([`OracleReadRecord`](crate::OracleReadRecord)): the answer is in no database, so a /// stateless validator is given the included transactions' reads in place of the service. - fn oracle_sload( - &mut self, - key: StorageKey, - skip_cold_load: bool, - ) -> Result, LoadError> { - if self.detention.refuses(VolatileDataAccess::ORACLE) || skip_cold_load { - return Err(LoadError::ColdLoadSkipped); - } + pub(crate) fn read_oracle_slot(&mut self, key: StorageKey) -> Result { let loaded = revm::context_interface::Host::sload_skip_cold_load( &mut self.inner, ORACLE_CONTRACT_ADDRESS, @@ -683,7 +685,36 @@ impl MegaContext { None }; self.detention.observe(VolatileDataAccess::ORACLE); - Ok(StateLoad::new(answer.unwrap_or(loaded), true)) + Ok(answer.unwrap_or(loaded)) + } + + /// The one-hop EIP-7702 delegate a call of `target` would follow, read for a frame whose + /// volatile-data access is off to decide, before the call charges or checks anything, whether + /// the call reads the block beneficiary's account: the address `target`'s code delegates to, + /// or `None` when its code is not a delegation. + /// + /// The read loads `target`'s account and code, and not the delegate's: it is in the + /// transaction's state, and so in a stateless witness, as the call's own load of its target + /// would be. It warms nothing: the journal is taken back to where it stood, so the account is + /// as warm or as cold as it was, and a call the read does not refuse pays its target's access + /// as it would with access on. + /// + /// The read is required: a database error is recorded as the transaction's, which fails with + /// it, and is never taken for a target without a delegate. + pub(crate) fn call_target_delegate( + &mut self, + target: Address, + ) -> Result, InstructionResult> { + let journal = &mut self.inner.journaled_state; + let start = mark(journal); + let delegate = journal + .load_account_with_code(target) + .map(|account| account.data.info.code.as_ref().and_then(Bytecode::eip7702_address)); + revert_to(journal, start); + delegate.map_err(|error| { + *self.error() = Err(ContextError::Db(error)); + InstructionResult::FatalExternalError + }) } } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 2634d68eb..e2f638e46 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -14,31 +14,56 @@ //! 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): +//! `SLOAD`, the four calls and `SELFDESTRUCT` ([`READ_OPCODES`]) — runs in a wrapper that decides +//! whether the read is refused and settles the reads its Host calls made (see the `access` +//! module): //! -//! 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. +//! 1. in a frame whose volatile-data access is off, refuse the read before the opcode charges or +//! checks anything, when what it would read is volatile: the frame reverts with +//! `VolatileDataAccessDisabled` on the gas it held when it reached the opcode; +//! 2. charge the opcode's static gas, as its own charge; +//! 3. run revm's instruction as a read, whose Host calls mark the reads they load; +//! 4. once the opcode completed, commit the reads, which holds the frame's spendable gas to what +//! the compute limit leaves it. //! -//! 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. +//! The opcode's static gas is the wrapper's to charge, after the refusal is decided, so the +//! instruction table carries none for these opcodes: the interpreter charges an opcode's static +//! gas before it runs the instruction, which would make a frame short of it run out of gas +//! rather than be refused, and would charge a refused read. A frame whose access is on runs every +//! wrapped opcode on the same charges, in the same order, as revm's own: its static gas, then the +//! instruction. The static gas the wrappers charge is Satin's ([`satin_gas_table`]), or the +//! fixture fork's under the test tooling's neutral configuration. +//! +//! An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` among +//! them — is refused before its operands are read. One volatile for the account or the storage it +//! reads is refused only once every operand it takes is on the stack, so one that fails on its +//! operands fails as it would with access on; it is then refused when its target operand, its +//! frame's own address, or a call target's one-hop EIP-7702 delegate is the block beneficiary, and +//! an `SLOAD` when its frame's storage is the Oracle's. The delegate is read for the decision: the +//! call target's account and code are loaded, so the read is in the transaction's state, and left +//! as warm or cold as they were. +//! +//! The Oracle's `SLOAD` is the one read made before any of its gas is charged: the slot is loaded, +//! the oracle service asked and the read marked, at the compute before the opcode, and only then +//! is the cold access charged, its warm base included, as one charge. A frame that cannot pay it +//! runs out of gas, and gas detention's crossing stops it, with the read marked all the same. +//! Every other `SLOAD` is revm's: its static gas, then its cold access, each its own charge. +//! +//! The Host observes 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. 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. +//! every deduction that fails — an opcode's static gas 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`]). +//! The static gas table is Amsterdam's ([`satin_gas_table`]). //! //! The table also carries the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), which //! the base spec gates off: Satin takes the Amsterdam schedule, so it takes the opcodes with it. @@ -56,7 +81,7 @@ use revm::{ handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{block_info, contract, host}, + instructions::{block_info, contract, host, utility::IntoAddress, GasTable}, interpreter::EthInterpreter, interpreter_types::LoopControl, FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, @@ -67,7 +92,8 @@ use revm::{ }; use crate::{ - volatile_data_access_disabled_revert_data, ExternalEnvTypes, MegaContext, VolatileDataAccess, + system::ORACLE_CONTRACT_ADDRESS, volatile_data_access_disabled_revert_data, ExternalEnvTypes, + MegaContext, VolatileDataAccess, }; use super::{input_gas_limit, satin_gas_table, value_call_stipend, MegaInstructions}; @@ -78,8 +104,37 @@ type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, Eth /// An instruction of the Satin engine. type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; +/// The opcodes that can read volatile data, which run in a read wrapper that charges their static +/// gas itself. +pub(crate) const READ_OPCODES: [u8; 20] = [ + SELFDESTRUCT, + CALL, + CALLCODE, + DELEGATECALL, + STATICCALL, + COINBASE, + TIMESTAMP, + NUMBER, + DIFFICULTY, + GASLIMIT, + BASEFEE, + BLOBBASEFEE, + SLOTNUM, + BLOCKHASH, + BALANCE, + SELFBALANCE, + EXTCODESIZE, + EXTCODECOPY, + EXTCODEHASH, + SLOAD, +]; + +/// The Satin static opcode prices, which the read wrappers charge for their opcodes. +pub(crate) const SATIN_GAS_TABLE: GasTable = satin_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. +/// the opcodes that can read volatile data wrapped, on the Satin static gas table, less the static +/// gas of the wrapped opcodes, which their wrappers charge. pub(crate) fn mega_instructions( spec: SpecId, ) -> MegaInstructions { @@ -108,40 +163,58 @@ pub(crate) fn mega_instructions( (EXTCODEHASH, extcodehash::), (SLOAD, sload::), ]; + debug_assert!(wrappers.iter().map(|&(opcode, _)| opcode).eq(READ_OPCODES)); for (opcode, wrapper) in wrappers { - let static_gas = instructions.gas_table()[opcode as usize]; - instructions.insert_instruction(opcode, Instruction::new(wrapper), static_gas); + instructions.insert_instruction(opcode, Instruction::new(wrapper), 0); } instructions } +/// `table` as the interpreter charges it with the read wrappers installed: the static gas of every +/// opcode the wrappers run is theirs to charge, so the interpreter's entry is zero. +pub(crate) fn without_read_static_gas(mut table: GasTable) -> GasTable { + for opcode in READ_OPCODES { + table[opcode as usize] = 0; + } + table +} + /// `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, contract::call::) + read_volatile::(context, contract::call::) } -/// 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. +/// Runs the opcode `OPCODE`, which can read volatile data, as `inner`, and settles the reads of +/// volatile data its Host calls made. /// -/// A refusal hands the frame back the gas it had when the wrapper started, which is after the -/// interpreter charged the opcode's static gas: the Host refuses before it loads anything, but an -/// opcode may charge part of its dynamic gas before its load (a copy's memory, a call's value -/// transfer), and none of that is owed for a read that did not happen. +/// In a frame whose volatile-data access is off, the read is decided first +/// ([`refused_read`]): a refused read reverts the frame with `VolatileDataAccessDisabled` on the +/// gas it held when it reached the opcode, before the opcode charges or checks anything. Otherwise +/// the opcode's static gas is charged, as its own charge, as the interpreter charges every other +/// opcode's, and `inner` runs; a read the opcode completed is committed, capping the frame at what +/// the compute limit leaves it. /// /// A read the opcode did not complete — the opcode failed after the load — is dropped: it reached /// no computation, and the frame is failing anyway. #[inline(always)] -fn read_volatile( +fn read_volatile( context: Ctx<'_, DB, ExtEnvs>, inner: impl FnOnce(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult, ) -> InstructionExecResult { let InstructionContext { interpreter, host } = context; + let gas = if host.detention.is_refusing() { + if let Some(refused) = refused_read::(interpreter, host)? { + return Err(refuse(interpreter, refused)); + } + Some(interpreter.gas) + } else { + None + }; + charge_static_gas(interpreter, host.read_static_gas(OPCODE))?; 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() { @@ -150,7 +223,88 @@ fn read_volatile( settle_reads(interpreter, host, result, gas) } -/// The slow half of [`read_volatile`]: the Host observed or refused a read. +/// Charges an opcode's static gas `gas` as the interpreter charges it before every other +/// instruction: an out-of-gas the frame halts on, whose failure the fork records. +#[inline(always)] +fn charge_static_gas( + interpreter: &mut Interpreter, + gas: u64, +) -> InstructionExecResult { + if interpreter.gas.record_cost_unsafe(gas) { + return Err(InstructionResult::OutOfGas); + } + Ok(()) +} + +/// What the opcode `OPCODE` would read that the running frame, whose volatile-data access is off, +/// is refused, or `None` when it reads nothing volatile; decided from the opcode, its operands and +/// its frame, before the opcode charges or checks anything. +/// +/// - The block-environment opcodes, `BLOCKHASH` included, are volatile whatever their operands: +/// they are refused before their operands are read. +/// - `BALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four calls and `SELFDESTRUCT` are +/// volatile only for the account they read: with fewer operands on the stack than the opcode +/// takes, nothing is refused, and the opcode fails on them as it would with access on. They are +/// refused when their target operand is the block beneficiary, `SELFDESTRUCT` also when its frame +/// runs as the beneficiary, and a call also when its target's one-hop EIP-7702 delegate is the +/// beneficiary. `SELFBALANCE` is refused when its frame runs as the beneficiary. +/// +/// The delegate is read for the decision ([`call_target_delegate`]), and the read is required: a +/// database error fails the transaction with its cause, whatever the call would have done. +/// +/// [`call_target_delegate`]: MegaContext::call_target_delegate +#[cold] +#[inline(never)] +fn refused_read( + interpreter: &Interpreter, + host: &mut MegaContext, +) -> Result, InstructionResult> { + let block_env = match OPCODE { + NUMBER => Some(VolatileDataAccess::BLOCK_NUMBER), + TIMESTAMP => Some(VolatileDataAccess::TIMESTAMP), + COINBASE => Some(VolatileDataAccess::COINBASE), + DIFFICULTY => Some(VolatileDataAccess::PREV_RANDAO), + GASLIMIT => Some(VolatileDataAccess::GAS_LIMIT), + BASEFEE => Some(VolatileDataAccess::BASE_FEE), + BLOBBASEFEE => Some(VolatileDataAccess::BLOB_BASE_FEE), + SLOTNUM => Some(VolatileDataAccess::SLOT_NUM), + BLOCKHASH => Some(VolatileDataAccess::BLOCK_HASH), + _ => None, + }; + if block_env.is_some() { + return Ok(block_env); + } + let beneficiary = host.inner.block.beneficiary; + let stack = &interpreter.stack; + // The `n`th operand from the top, as the address the opcode reads it as. + let address = |n: usize| stack.peek(n).ok().map(IntoAddress::into_address); + let own = interpreter.input.target_address; + let reads_beneficiary = match OPCODE { + SELFBALANCE => own == beneficiary, + BALANCE | EXTCODESIZE | EXTCODEHASH => address(0) == Some(beneficiary), + EXTCODECOPY => stack.len() >= 4 && address(0) == Some(beneficiary), + SELFDESTRUCT => { + address(0).is_some_and(|target| target == beneficiary || own == beneficiary) + } + CALL | CALLCODE | DELEGATECALL | STATICCALL => { + let operands = if matches!(OPCODE, CALL | CALLCODE) { 7 } else { 6 }; + match address(1) { + Some(target) if stack.len() >= operands => { + target == beneficiary || host.call_target_delegate(target)? == Some(beneficiary) + } + _ => false, + } + } + _ => false, + }; + Ok(reads_beneficiary.then_some(VolatileDataAccess::BENEFICIARY_BALANCE)) +} + +/// The slow half of [`read_volatile`]: the Host observed a read. +/// +/// The Host refuses a load only where the wrapper did not refuse the read first, which no opcode +/// reaches: every volatile load an opcode makes is one [`refused_read`] decides. Were one reached, +/// the frame would be refused on the gas it held when it reached the opcode (`gas`). #[inline(never)] fn settle_reads( interpreter: &mut Interpreter, @@ -159,8 +313,14 @@ fn settle_reads( gas: Option, ) -> InstructionExecResult { let observed = host.detention.take_observed(); - if let Some(refused) = host.detention.take_refused() { - return Err(refuse(interpreter, refused, gas)); + let refused = host.detention.take_refused(); + debug_assert!(refused.is_none(), "a read the wrapper did not refuse first: {refused:?}"); + if let Some(refused) = refused { + // The Host refuses a load before the opcode builds a frame, so no action is pending. + if let Some(gas) = gas { + interpreter.gas = gas; + } + return Err(refuse(interpreter, refused)); } let completed = match result { Ok(()) => true, @@ -185,18 +345,13 @@ fn settle_reads( } /// Reverts the running frame with `VolatileDataAccessDisabled` for the read `refused`, on the gas -/// it had before the opcode (`gas`, when the wrapper kept it). +/// it holds. #[cold] #[inline(never)] fn refuse( interpreter: &mut Interpreter, refused: VolatileDataAccess, - gas: Option, ) -> InstructionResult { - // The Host refuses a load before the opcode builds a frame, so no action is pending. - if let Some(gas) = gas { - interpreter.gas = gas; - } let result = InstructionResult::Revert; interpreter.bytecode.set_action(InterpreterAction::new_return( result, @@ -215,46 +370,88 @@ fn forwarded_gas(input: &FrameInput, call_stipend: u64) -> u64 { /// Defines an opcode that reads volatile data — a block-environment field, an account or a slot — /// as revm's instruction in [`read_volatile`]. macro_rules! volatile_read { - ($($name:ident => $inner:path, $opcode:literal, $what:literal;)*) => {$( - #[doc = concat!("`", $opcode, "`, committing the read of ", $what, ".")] + ($($name:ident => $inner:path, $opcode:ident, $what:literal;)*) => {$( + #[doc = concat!("`", stringify!($opcode), "`, committing the read of ", $what, ".")] fn $name( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - read_volatile(context, $inner) + read_volatile::<$opcode, _, _>(context, $inner) } )*}; } volatile_read! { - coinbase => block_info::coinbase, "COINBASE", "the field"; - timestamp => block_info::timestamp, "TIMESTAMP", "the field"; - number => block_info::block_number, "NUMBER", "the field"; - difficulty => block_info::difficulty, "PREVRANDAO", "the field"; - gaslimit => block_info::gaslimit, "GASLIMIT", "the field"; - basefee => block_info::basefee, "BASEFEE", "the field"; - blobbasefee => block_info::blob_basefee, "BLOBBASEFEE", "the field"; - slotnum => block_info::slot_num_enabled, "SLOTNUM", "the field"; - balance => host::balance, "BALANCE", "the block beneficiary's account"; - selfbalance => host::selfbalance, "SELFBALANCE", "the block beneficiary's account"; - extcodesize => host::extcodesize, "EXTCODESIZE", "the block beneficiary's account"; - 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"; + coinbase => block_info::coinbase, COINBASE, "the field"; + timestamp => block_info::timestamp, TIMESTAMP, "the field"; + number => block_info::block_number, NUMBER, "the field"; + difficulty => block_info::difficulty, DIFFICULTY, "the field"; + gaslimit => block_info::gaslimit, GASLIMIT, "the field"; + basefee => block_info::basefee, BASEFEE, "the field"; + blobbasefee => block_info::blob_basefee, BLOBBASEFEE, "the field"; + slotnum => block_info::slot_num_enabled, SLOTNUM, "the field"; + blockhash => host::blockhash, BLOCKHASH, "the block number and of the hash"; + balance => host::balance, BALANCE, "the block beneficiary's account"; + selfbalance => host::selfbalance, SELFBALANCE, "the block beneficiary's account"; + extcodesize => host::extcodesize, EXTCODESIZE, "the block beneficiary's account"; + extcodecopy => host::extcodecopy, EXTCODECOPY, "the block beneficiary's account"; + extcodehash => host::extcodehash, EXTCODEHASH, "the block beneficiary's account"; + selfdestruct => host::selfdestruct, SELFDESTRUCT, "the block beneficiary's account"; } -/// `BLOCKHASH`, committing the read of the block number and of the hash. +/// `SLOAD`: revm's for every storage but the Oracle's, its static gas charged first as its own +/// charge; the Oracle's own frame reads through [`oracle_sload`]. +fn sload( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + if context.interpreter.input.target_address == ORACLE_CONTRACT_ADDRESS { + return oracle_sload(context); + } + let InstructionContext { interpreter, host } = context; + charge_static_gas(interpreter, host.read_static_gas(SLOAD))?; + host::sload(InstructionContext { interpreter, host }) +} + +/// `SLOAD` in the Oracle's own frame — a storage read whose owner is the Oracle — which reads +/// before it charges anything. /// -/// revm's instruction reads the block number before the hash, so a refusal is of the number -/// first; it is named for the hash, the kind `BLOCKHASH` reads, as the legacy engine named it. -fn blockhash( +/// The slot operand must be on the stack, or the opcode fails on it as it would with access on. +/// In a frame whose volatile-data access is off the read is then refused, on the gas the frame +/// holds, asking nothing. Otherwise the slot is read +/// ([`read_oracle_slot`](MegaContext::read_oracle_slot)): loaded, the oracle service asked where +/// the execution asks it, and the read marked; and the read is committed at once, at the +/// transaction's compute before the opcode, so the mark stands whatever the charge then does. +/// Only then is the cold access charged, `COLD_SLOAD_COST` with its warm base, as one charge: +/// a frame whose regular gas cannot pay it runs out of gas at the `SLOAD`, and one whose +/// spendable part cannot pay it while the whole can is gas detention's crossing, judged on the +/// whole charge and stopped with none of it made. +#[inline(never)] +fn oracle_sload( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - read_volatile(context, |InstructionContext { interpreter, host }| { - let result = host::blockhash(InstructionContext { interpreter, host: &mut *host }); - host.detention.name_refusal(VolatileDataAccess::BLOCK_HASH); - result - }) + let InstructionContext { interpreter, host } = context; + let Some(key) = interpreter.stack.top().map(|top| *top) else { + return Err(InstructionResult::StackUnderflow); + }; + if host.detention.is_refusing() { + return Err(refuse(interpreter, VolatileDataAccess::ORACLE)); + } + host.detention.begin_read(); + let read = host.read_oracle_slot(key); + host.detention.end_read(); + let value = read?; + let observed = host.detention.take_observed(); + if !observed.is_empty() { + host.detention.commit_reads(observed, &mut interpreter.gas, 0); + } + let cold_access = + host.read_static_gas(SLOAD) + host.gas_params().cold_storage_additional_cost(); + if !interpreter.gas.record_regular_cost(cold_access) { + return Err(InstructionResult::OutOfGas); + } + if let Some(top) = interpreter.stack.top() { + *top = value; + } + Ok(()) } #[cfg(test)] @@ -263,18 +460,24 @@ mod tests { use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; use revm::bytecode::opcode::{CLZ, DUPN, EXCHANGE, SLOTNUM, SWAPN}; - /// The wrappers keep the static gas the Satin table charges for their opcodes: the whole - /// table is revm's Amsterdam one. + /// The table charges the Satin static gas of every opcode but the ones the read wrappers run, + /// which charge it themselves: the whole table, with their entries, is revm's Amsterdam one. /// /// Activating the Amsterdam opcodes does not touch it either — their static gas is the same /// on every spec, which is why the activation is an instruction-table change alone. #[test] - fn test_wrappers_keep_the_static_gas_table() { + fn test_the_table_and_the_wrappers_charge_the_static_gas_table() { let mega = mega_instructions::(SpecId::OSAKA); - assert_eq!(mega.gas_table(), &satin_gas_table()); + assert_eq!(mega.gas_table(), &without_read_static_gas(satin_gas_table())); + let mut charged = *mega.gas_table(); + for opcode in READ_OPCODES { + assert_eq!(charged[opcode as usize], 0, "opcode {opcode:#04x}: the wrapper's"); + charged[opcode as usize] = SATIN_GAS_TABLE[opcode as usize]; + } + assert_eq!(charged, satin_gas_table()); assert_eq!(mega.spec, SpecId::OSAKA); for (opcode, gas) in [(DUPN, 3), (SWAPN, 3), (EXCHANGE, 3), (SLOTNUM, 2), (CLZ, 5)] { - assert_eq!(mega.gas_table()[opcode as usize], gas, "opcode {opcode:#04x}"); + assert_eq!(charged[opcode as usize], gas, "opcode {opcode:#04x}"); } } } diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 3e6b0e773..7693241de 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -232,6 +232,31 @@ impl MegaEvm { self.priced_precompiles.record_foreign(); } + /// Replaces the static opcode prices the EVM charges with `table`: the test tooling's + /// neutral configuration installs a fixture fork's. The opcodes that can read volatile data + /// charge theirs in their read wrappers, which read them from the context; the instruction + /// table carries the rest. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) fn replace_static_gas_table( + &mut self, + table: revm::interpreter::instructions::GasTable, + ) { + self.inner.ctx.set_read_static_gas(table); + *self.inner.instruction.gas_table_mut() = instructions::without_read_static_gas(table); + } + + /// The static opcode prices the EVM charges: the instruction table's, and for the opcodes + /// that can read volatile data the ones their read wrappers charge. + #[cfg(test)] + pub(crate) fn static_gas_table(&self) -> revm::interpreter::instructions::GasTable { + let mut table = *self.inner.instruction.gas_table(); + for opcode in instructions::READ_OPCODES { + table[opcode as usize] = + u16::try_from(self.inner.ctx.read_static_gas(opcode)).unwrap_or(u16::MAX); + } + table + } + /// Enforces `limits` on every transaction this EVM runs from now on. /// /// Every EVM already runs under its spec's limits diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index 6abeecd7f..f0af57b4c 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -32,7 +32,6 @@ use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ context::CfgEnv, context_interface::cfg::GasParams, - handler::EvmTr, interpreter::instructions::{gas_table_spec, GasTable}, precompile::{PrecompileSpecId, Precompiles}, primitives::eip7954, @@ -117,8 +116,7 @@ pub fn neutralize_evm( ) -> Option<()> { let (precompiles, gas_table) = (neutral_precompiles(fork)?, neutral_gas_table(fork)?); evm.replace_precompile_set(precompiles); - let (_, instructions, _, _) = evm.all_mut(); - *instructions.gas_table_mut() = gas_table; + evm.replace_static_gas_table(gas_table); Some(()) } @@ -151,6 +149,7 @@ mod tests { use revm::{ context::{Cfg, ContextTr}, database::EmptyDB, + handler::EvmTr, precompile::kzg_point_evaluation, primitives::{eip170, eip3860, eip7825}, }; @@ -266,8 +265,8 @@ mod tests { #[test] fn test_neutral_gas_tables() { use revm::bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}; - let mut evm = MegaEvm::new(context(EthSpecId::AMSTERDAM)); - let satin = *evm.all_mut().1.gas_table(); + let evm = MegaEvm::new(context(EthSpecId::AMSTERDAM)); + let satin = evm.static_gas_table(); assert_eq!(neutral_gas_table(EthSpecId::AMSTERDAM), Some(satin)); let osaka = neutral_gas_table(EthSpecId::OSAKA).expect("a neutral fork"); @@ -280,16 +279,23 @@ mod tests { } /// `neutralize_evm` installs the fork's static prices, and changes nothing for a fork - /// without a neutral configuration. That it installs the precompile set is shown by a call - /// (`tests/satin/neutral.rs`). + /// without a neutral configuration. The opcodes that can read volatile data take theirs in + /// their read wrappers, so the instruction table charges none of theirs, before and after. + /// That it installs the precompile set is shown by a call (`tests/satin/neutral.rs`). #[test] fn test_neutralize_evm_installs_the_fork_s_static_prices() { - use revm::bytecode::opcode::EXTCODESIZE; + use revm::bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}; let mut evm = MegaEvm::new(context(EthSpecId::OSAKA)); assert!(neutralize_evm(&mut evm, EthSpecId::PRAGUE).is_none()); - assert_eq!(evm.all_mut().1.gas_table()[EXTCODESIZE as usize], 200); + assert_eq!(evm.static_gas_table()[EXTCODESIZE as usize], 200); assert!(neutralize_evm(&mut evm, EthSpecId::OSAKA).is_some()); - assert_eq!(evm.all_mut().1.gas_table()[EXTCODESIZE as usize], 100); + let osaka = neutral_gas_table(EthSpecId::OSAKA).expect("a neutral fork"); + assert_eq!(evm.static_gas_table(), osaka); + assert_eq!(evm.static_gas_table()[EXTCODESIZE as usize], 100); + for opcode in [EXTCODESIZE, EXTCODECOPY] { + assert_eq!(evm.all_mut().1.gas_table()[opcode as usize], 0, "the wrapper's"); + assert_eq!(evm.ctx().read_static_gas(opcode), 100); + } } } diff --git a/crates/mega-evm/tests/block/witness/skips.rs b/crates/mega-evm/tests/block/witness/skips.rs index 197c8350f..7fe4c2f09 100644 --- a/crates/mega-evm/tests/block/witness/skips.rs +++ b/crates/mega-evm/tests/block/witness/skips.rs @@ -1,19 +1,23 @@ //! Reads that gas or a switch skips, through the harness: a cold `SLOAD` and a cold account load -//! with less gas than the cold surcharge, an oracle read the frame cannot pay, and reads a frame -//! that switched its volatile-data access off is refused. None reaches the database, none is in -//! the record, and the replay skips them the same way. +//! with less gas than the cold surcharge, and reads a frame that switched its volatile-data access +//! off is refused. None reaches the database, none is in the record, and the replay skips them the +//! same way. An Oracle read is not one of them: it is made before its charge, so a frame that +//! cannot pay it reads the slot and asks the service all the same, and the replay does too. use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, test_utils::BytecodeBuilder, - OracleRead, + volatile_data_access_disabled_revert_data, OracleRead, VolatileDataAccess, }; use revm::{ - bytecode::opcode::{BALANCE, BLOCKHASH, CALL, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD}, + bytecode::opcode::{ + BALANCE, BLOCKHASH, CALL, CALLCODE, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD, + }, context::result::ExecutionResult, context_interface::cfg::GasId, + state::{AccountInfo, Bytecode}, }; use super::{ @@ -25,6 +29,9 @@ use crate::common::{self, BLOCK_NUMBER, CONTRACT}; /// An account no transaction here funds or reads unless a cold load is made. const STRANGER: Address = address!("0x5000000000000000000000000000000000000005"); +/// An EIP-7702 delegator of the block beneficiary, the harness's block environment's default. +const DELEGATOR: Address = address!("0x5000000000000000000000000000000000000006"); + /// The regular gas an empty call spends before its first instruction, at the byte prices in /// effect: what a transaction to [`CONTRACT`] with empty code is billed on the regular ledger. fn intrinsic() -> u64 { @@ -72,6 +79,40 @@ fn test_a_cold_sload_with_gas_reads_the_slot() { assert_eq!(run.record.storage.get(&(CONTRACT, U256::from(7))), Some(&U256::ZERO)); } +/// Code that reads slot 7 of its own storage and stops. +fn sload_seven() -> Bytes { + BytecodeBuilder::default().push_number(7_u8).append(SLOAD).stop().build() +} + +/// A cold `SLOAD` of another contract than the Oracle charges its static 100 and then its cold +/// access, each on its own, and is skipped before the database is asked when the gas left after +/// the 100 is short of the cold access: with 50 or 2,099 left at the `SLOAD` the slot is not read +/// and the transaction runs out of gas; with 2,100 or 4,099 it is read and the transaction +/// completes. The replay does the same. +#[test] +fn test_a_cold_sload_reads_its_slot_only_with_the_gas_for_its_cold_access() { + for (left, reads) in [(50, false), (2_099, false), (2_100, true), (4_099, true)] { + let mut db = common::database(); + db.set_account_code(CONTRACT, sload_seven()); + let replay = Case::new("cold sload by gas", db) + .tx(call(0, CONTRACT, Bytes::new(), gas_with_room(3 + left))) + .run(); + let run = &replay.recorded; + let slot = run.record.storage.get(&(CONTRACT, U256::from(7))); + if reads { + assert!(run.tx(0).result.is_success(), "{left}: {:?}", run.tx(0).result); + assert_eq!(slot, Some(&U256::ZERO), "{left}: the slot is read"); + } else { + assert!( + matches!(run.tx(0).result, ExecutionResult::Halt { .. }), + "{left}: {:?}", + run.tx(0).result + ); + assert_eq!(slot, None, "{left}: the slot is not read"); + } + } +} + /// A cold `BALANCE` with less gas than its cold surcharge loads no account. #[test] fn test_a_cold_account_load_short_of_gas_reads_no_account() { @@ -100,15 +141,10 @@ fn test_a_cold_account_load_short_of_gas_reads_no_account() { assert_eq!(replay.recorded.record.accounts.get(&STRANGER), Some(&None)); } -/// Code that calls the Oracle's `getSlot(42)` forwarding `gas` and returns whether the call -/// succeeded, as a word. -fn oracle_read_forwarding(gas: u64) -> Bytes { - let input = IOracle::getSlotCall { slot: U256::from(42) }.abi_encode(); +/// Code that calls the Oracle forwarding `gas` and returns whether the call succeeded, as a word. +fn calls_the_oracle_forwarding(gas: u64) -> Bytes { BytecodeBuilder::default() - .mstore(0, &input) - .append_many([PUSH0, PUSH0]) - .push_number(input.len() as u64) - .append_many([PUSH0, PUSH0]) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(ORACLE_CONTRACT_ADDRESS) .push_number(gas) .append_many([CALL, PUSH0, MSTORE]) @@ -117,45 +153,34 @@ fn oracle_read_forwarding(gas: u64) -> Bytes { .build() } -/// An oracle read the frame cannot pay is neither loaded nor asked: a call into the Oracle -/// forwarded less gas than a cold access fails, leaving the slot out of the record and the -/// service unasked, on a chain that holds the Oracle, so the slot would have been read from the -/// database otherwise. The gas is the call's own, set by its caller, so the frame is short of the -/// cold access whatever a byte costs. +/// An Oracle read is made before any of its 2,100 is charged: whatever its frame holds at the +/// `SLOAD` — 50, 2,099, 2,100 or 4,099 — the slot is read from the database and the service +/// asked, on a chain that holds the Oracle, and the frame then runs out of gas on the first two +/// and completes the other two. The replay reads and asks the same, and replays the recorded +/// answer at each. #[test] -fn test_an_oracle_read_short_of_gas_asks_nothing() { - let case = |forwarded: u64| { +fn test_an_oracle_read_is_read_and_asked_whatever_its_frame_holds() { + let slot = (ORACLE_CONTRACT_ADDRESS, U256::from(42)); + for (left, completes) in [(50, false), (2_099, false), (2_100, true), (4_099, true)] { let mut db = chain_with_oracle(); - db.set_account_code(CONTRACT, oracle_read_forwarding(forwarded)); - Case::new("oracle short of gas", db) + db.set_account_code( + ORACLE_CONTRACT_ADDRESS, + BytecodeBuilder::default().push_number(42_u8).append(SLOAD).stop().build(), + ); + db.set_account_code(CONTRACT, calls_the_oracle_forwarding(3 + left)); + let replay = Case::new("oracle read by gas", db) .envs(super::harness::Envs::new().with_oracle_storage(U256::from(42), U256::from(1))) .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) - }; - let succeeded = |run: &super::harness::Run| { - assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); - U256::from_be_slice(run.tx(0).result.output().expect("the flag")) == U256::from(1) - }; - - let short = case(2_000).run(); - assert!(!succeeded(&short.recorded), "the call into the Oracle ran out of gas"); - assert!(short.recorded.record.oracle_reads.is_empty(), "the service was not asked"); - assert!(short.recorded.tx(0).oracle_reads.is_empty(), "and the transaction recorded no read"); - assert!(!short - .recorded - .record - .storage - .contains_key(&(ORACLE_CONTRACT_ADDRESS, U256::from(42)))); - - let enough = case(50_000).run(); - assert!(succeeded(&enough.recorded)); - assert_eq!( - enough.recorded.record.oracle_reads, - vec![OracleRead { slot: U256::from(42), answer: Some(U256::from(1)) }] - ); - assert!( - enough.recorded.record.storage.contains_key(&(ORACLE_CONTRACT_ADDRESS, U256::from(42))), - "with the gas, the slot is read from the database" - ); + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{left}: {:?}", run.tx(0).result); + let succeeded = U256::from_be_slice(run.tx(0).result.output().expect("the flag")); + assert_eq!(succeeded, U256::from(u8::from(completes)), "{left}: the Oracle's frame"); + let read = OracleRead { slot: U256::from(42), answer: Some(U256::from(1)) }; + assert_eq!(run.record.oracle_reads, vec![read], "{left}: the service was asked"); + assert_eq!(run.tx(0).oracle_reads, vec![read], "{left}: and the read recorded"); + assert!(run.record.storage.contains_key(&slot), "{left}: the slot is read"); + } } /// Code that switches its volatile-data access off, then runs `then`. @@ -231,3 +256,43 @@ fn test_a_refused_oracle_read_reads_nothing() { assert_eq!(run.record.oracle_reads.len(), 1, "with access on, the service is asked"); assert!(run.record.storage.contains_key(&slot), "and the slot is read from the database"); } + +/// With access off, a call opcode reads its target's account and code to find the EIP-7702 +/// delegate it would follow, before it charges or checks anything: a `CALLCODE` of a delegator +/// of the block beneficiary, with an input of 1 MiB its 1,000 gas cannot pay, is refused, and the +/// delegator's account and code are in the record and the witness, which the replay reads alike. +#[test] +fn test_a_refused_call_reads_its_targets_account_and_code() { + let delegation = Bytecode::new_eip7702(Address::ZERO); + let mut db = common::database(); + db.insert_account_info( + DELEGATOR, + AccountInfo { + code_hash: delegation.hash_slow(), + code: Some(delegation.clone()), + ..Default::default() + }, + ); + let then = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(0x10_0000_u32) + .append_many([PUSH0, PUSH0]) + .push_address(DELEGATOR) + .push_number(1_000_u16) + .append(CALLCODE) + .stop(); + db.set_account_code(CONTRACT, disabled_then(then)); + let replay = Case::new("refused call of a delegator", db) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) + .run(); + let run = &replay.recorded; + match &run.tx(0).result { + ExecutionResult::Revert { output, .. } => assert_eq!( + output, + &volatile_data_access_disabled_revert_data(VolatileDataAccess::BENEFICIARY_BALANCE) + ), + other => panic!("expected the refusal, got {other:?}"), + } + assert!(run.record.accounts.contains_key(&DELEGATOR), "the target's account is read"); + assert!(run.record.codes.contains_key(&delegation.hash_slow()), "and its code"); +} diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 4295f48fc..4af4fa1c2 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -610,8 +610,9 @@ fn reads() -> Vec { ) }, access: VolatileDataAccess::ORACLE, - // The Oracle's `POP`, then its caller's. - after: &[2, 2], + // The `SLOAD`'s cold access, which the Oracle's read is committed before, as one + // charge; then the Oracle's `POP`, then its caller's. + after: &[2_100, 2, 2], }, ] } @@ -945,8 +946,9 @@ fn test_the_most_restrictive_limit_binds_whatever_the_order() { 2, ]) } else { - // The Oracle's `POP` and its caller's, the work, then `TIMESTAMP` and its `POP`. - Charges::default().then(&[2, 2]).work(300, 0).then(&[2, 2]) + // The `SLOAD`'s cold access, which the Oracle's read comes before, the Oracle's + // `POP` and its caller's, the work, then `TIMESTAMP` and its `POP`. + Charges::default().then(&[2_100, 2, 2]).work(300, 0).then(&[2, 2]) }; let limit = assert_stopped(&run, intrinsic, charges.spin(1_024).left(CAP)); assert!(limit < CAP + 100_000, "the first read set the limit: {limit}"); @@ -984,8 +986,9 @@ fn test_a_callers_limits_set_the_caps() { limits, spin(call(BytecodeBuilder::default(), CALL, ORACLE_CONTRACT_ADDRESS)), ); - // The Oracle's `POP` and its caller's, then the loop. - let left = Charges::default().then(&[2, 2]).spin(0).left(2_000_000); + // The `SLOAD`'s cold access, which the Oracle's read comes before, the Oracle's `POP` and + // its caller's, then the loop. + let left = Charges::default().then(&[2_100, 2, 2]).spin(0).left(2_000_000); let limit = assert_stopped(&run, intrinsic, left); assert!((2_000_000..2_100_000).contains(&limit), "the Oracle's own cap: {limit}"); assert_eq!(run.accessed, VolatileDataAccess::ORACLE); @@ -1416,17 +1419,13 @@ fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { /* ---------- what is not marked ---------- */ -/// A read that does not happen marks nothing, and neither does one whose opcode fails after it: -/// the frame halts, and the caller it halts back into computes on uncapped. +/// A read whose opcode fails after it marks nothing: the frame halts, and the caller it halts back +/// into computes on uncapped. A value transfer to the empty beneficiary loads it, then cannot pay +/// the transfer, and the `CALL` fails. /// -/// - The Oracle's slot is cold and the frame cannot pay the cold access, so the Host does not load -/// it. (The block beneficiary is always warm, so its load cannot be skipped this way.) -/// - A value transfer to the empty beneficiary loads it, then cannot pay the transfer, and the -/// `CALL` fails. +/// An Oracle read is the exception ([`test_an_unpaid_oracle_read_caps_the_transaction`]). #[test] fn test_a_failed_load_caps_nothing() { - // The push and SLOAD's static 100 leave less than the 2,000 more a cold slot costs. - let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); // The child's pushes and the warm access leave less than the value transfer. let child = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -1435,7 +1434,7 @@ fn test_a_failed_load_caps_nothing() { .append_many([PUSH0, CALL, STOP]) .build(); let transfer = u32::try_from(value_transfer()).expect("the transfer's price fits a PUSH4"); - for (callee, gas) in [(ORACLE_CONTRACT_ADDRESS, 2_000_u32), (CHILD, transfer)] { + for (callee, gas) in [(CHILD, transfer)] { let parent = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(callee) @@ -1449,7 +1448,6 @@ fn test_a_failed_load_caps_nothing() { let db = MemoryDatabase::default() .account_balance(CHILD, U256::from(10)) .account_code(CONTRACT, parent.clone()) - .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()) .account_code(CHILD, child.clone()); let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); assert!(run.outcome.result.is_success(), "{callee}: {:?}", run.outcome.result); @@ -1465,6 +1463,41 @@ fn test_a_failed_load_caps_nothing() { } } +/// An Oracle read is made before its cold access is charged, so a frame that cannot pay the +/// access has read the slot and marked the read all the same: the Oracle's frame, forwarded 2,000 +/// gas, reads and then runs out of gas, and the caller it halts back into is held to the limit +/// the read set, and stopped by the work it does past the cap. +#[test] +fn test_an_unpaid_oracle_read_caps_the_transaction() { + // The push leaves the `SLOAD` 1,998, less than the 2,100 of its cold access. + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(2_000_u16) + .append_many([CALL, POP]); + // More compute than the cap. + let parent = work(parent, 7_000).stop().build(); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE, "the read is marked"); + let limit = run.limit.expect("the read set a limit"); + assert!((CAP..CAP + 10_000).contains(&limit), "set at the read: {limit}"); + assert!( + matches!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ), + "the caller's work is stopped: {:?}", + run.outcome.result + ); + assert_eq!(run.outcome.oracle_reads, [OracleRead { slot: U256::ZERO, answer: None }]); + } +} + /// Reads the block's timestamp through the Host before every step, as a tracer might. struct ReadsTheTimestamp; @@ -1544,52 +1577,82 @@ impl Inspector, EthInterpreter> for Calls { } } -/// While volatile-data access is off, every read is refused: the frame reverts with -/// `VolatileDataAccessDisabled(accessType)`, having paid the static gas of what ran and nothing -/// more — not a cold access, not a copy's memory, not a call's value transfer — and the refused -/// read caps nothing. +/// While volatile-data access is off, every read is refused before it charges anything: the frame +/// reverts with `VolatileDataAccessDisabled(accessType)` on the gas it held when it reached the +/// opcode, having paid the static gas of what ran before it and nothing of the refused opcode — +/// not its static gas, not a cold access, not a copy's memory, not a call's value transfer — and +/// the refused read caps nothing. A frame that reaches the opcode with less gas than its static +/// gas is refused all the same, rather than running out of gas. +/// +/// An opcode volatile whatever its operands is refused before it reads them, so a `BLOCKHASH` on +/// an empty stack is refused rather than halting on the underflow; one volatile for the account +/// or the storage it reads is refused once its operands are on the stack, before its body checks +/// anything — a large copy, a call's memory, a value transfer it could not fund, a call to an +/// EIP-7702 delegator of the beneficiary — and so is an `SLOAD` in the Oracle's own frame. #[test] -fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { - // (code, the static gas of everything in it, the refused kind) - let cases: Vec<(&str, Bytes, u64, VolatileDataAccess)> = vec![ +fn test_a_refused_read_reverts_the_frame_and_charges_nothing() { + // Pushes the operands of a call of `to` through `scheme`, carrying `value` when the scheme + // takes one, with an input of 1 MiB, an output of nothing and 1,000 gas. + let call_with_memory = |scheme: u8, value: u8, to: Address| { + let code = + BytecodeBuilder::default().append_many([PUSH0, PUSH0]).push_number(0x10_0000_u32); + let code = code.append(PUSH0); + let code = if matches!(scheme, CALL | CALLCODE) { code.push_number(value) } else { code }; + code.push_address(to).push_number(1_000_u16).append(scheme).build() + }; + // (name, the frame that reads, its code, the static gas of what runs before the refused + // opcode, the refused kind) + let cases: Vec<(&str, Address, Bytes, u64, VolatileDataAccess)> = vec![ ( "TIMESTAMP", + CHILD, BytecodeBuilder::default().append(TIMESTAMP).build(), - 2, + 0, VolatileDataAccess::TIMESTAMP, ), ( "SLOTNUM", + CHILD, BytecodeBuilder::default().append(SLOTNUM).build(), - 2, + 0, VolatileDataAccess::SLOT_NUM, ), ( "BLOCKHASH", + CHILD, BytecodeBuilder::default().push_number(299_u16).append(BLOCKHASH).build(), - 3 + 20, + 3, + VolatileDataAccess::BLOCK_HASH, + ), + ( + "BLOCKHASH on an empty stack", + CHILD, + BytecodeBuilder::default().append(BLOCKHASH).build(), + 0, VolatileDataAccess::BLOCK_HASH, ), ( "BALANCE", + CHILD, on_beneficiary(BytecodeBuilder::default(), BALANCE).build(), - 3 + 100, + 3, VolatileDataAccess::BENEFICIARY_BALANCE, ), ( - "EXTCODECOPY", + "EXTCODECOPY of 1 MiB", + CHILD, BytecodeBuilder::default() - .push_number(1024_u16) + .push_number(0x10_0000_u32) .append_many([PUSH0, PUSH0]) .push_address(BENEFICIARY) .append(EXTCODECOPY) .build(), - // `EXTCODECOPY`'s static gas is EIP-8038's two warm reads, the account and its code. - 3 + 2 + 2 + 3 + 200, + 3 + 2 + 2 + 3, VolatileDataAccess::BENEFICIARY_BALANCE, ), ( "CALL with value", + CHILD, BytecodeBuilder::default() .push_number(64_u8) .append_many([PUSH0, PUSH0, PUSH0]) @@ -1598,48 +1661,84 @@ fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { .append(GAS) .append(CALL) .build(), - 3 + 2 + 2 + 2 + 3 + 3 + 2 + 100, + 3 + 2 + 2 + 2 + 3 + 3 + 2, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ( + "CALL of a delegator of the beneficiary, with a value it cannot fund", + CHILD, + call_with_memory(CALL, 200, DELEGATOR), + 2 + 2 + 3 + 2 + 3 + 3 + 3, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ( + "STATICCALL of a delegator of the beneficiary", + CHILD, + call_with_memory(STATICCALL, 0, DELEGATOR), + 2 + 2 + 3 + 2 + 3 + 3, VolatileDataAccess::BENEFICIARY_BALANCE, ), ( "SELFDESTRUCT", + CHILD, on_beneficiary(BytecodeBuilder::default(), SELFDESTRUCT).build(), - 3 + 5_000, + 3, VolatileDataAccess::BENEFICIARY_BALANCE, ), ( "SELFBALANCE of the beneficiary's own frame", + BENEFICIARY, BytecodeBuilder::default().append(SELFBALANCE).build(), - 5, + 0, VolatileDataAccess::BENEFICIARY_BALANCE, ), + ( + "SLOAD in the Oracle's own frame", + ORACLE_CONTRACT_ADDRESS, + BytecodeBuilder::default().append_many([PUSH0, SLOAD]).build(), + 2, + VolatileDataAccess::ORACLE, + ), ]; for gas_limit in TIERS { - for (name, code, static_gas, refused) in &cases { - // The beneficiary runs its own SELFBALANCE; every other read runs in the child. - let target = if name.starts_with("SELFBALANCE") { BENEFICIARY } else { CHILD }; - let parent = call(BytecodeBuilder::default(), CALL, target).stop().build(); - let db = MemoryDatabase::default() - .account_balance(CHILD, U256::from(10)) - .account_code(CONTRACT, parent) - .account_code(target, code.clone()); - let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) - .with_inspector(Calls::default()); - let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); - assert!(run.outcome.result.is_success(), "{name}: the caller resumes"); - let record = &evm.inspector().calls[0]; - assert_eq!(record.target, target); - assert_eq!(record.result, InstructionResult::Revert, "{name}"); - assert_eq!( - record.output, - volatile_data_access_disabled_revert_data(*refused), - "{name}" - ); - assert_eq!(record.spent, *static_gas, "{name}: the static gas of what ran"); - // Only the calls a transaction to the beneficiary makes read it; the refusal did not. - if target == CHILD { - assert_eq!(run.accessed, VolatileDataAccess::empty(), "{name}"); - assert_eq!(run.limit, None, "{name}"); + for (name, target, code, before, refused) in &cases { + // The frame gets all the parent has, or one gas more than what runs before the refused + // opcode, which is less than the static gas of every opcode refused here. + for forward in [None, Some(before + 1)] { + let parent = + BytecodeBuilder::default().append_many([PUSH0; 5]).push_address(*target); + let parent = match forward { + Some(gas) => parent.push_number(gas), + None => parent.append(GAS), + }; + let parent = parent.append_many([CALL, POP]).stop().build(); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_balance(CHILD, U256::from(10)) + .account_code(CONTRACT, parent) + .account_code(*target, code.clone()); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + let case = format!("{name}, forwarding {forward:?}"); + assert!(run.outcome.result.is_success(), "{case}: the caller resumes"); + let record = &evm.inspector().calls[0]; + assert_eq!(record.target, *target); + assert_eq!(record.result, InstructionResult::Revert, "{case}"); + assert_eq!( + record.output, + volatile_data_access_disabled_revert_data(*refused), + "{case}" + ); + assert_eq!( + record.spent, *before, + "{case}: only what ran before the refused opcode" + ); + // Only the calls a transaction to the beneficiary makes read it; the refusal did + // not. + if *target != BENEFICIARY { + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{case}"); + assert_eq!(run.limit, None, "{case}"); + } } } } diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index e80ec51be..4b47e490a 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1165,9 +1165,10 @@ fn pop_then_writes() -> Charges { Charges::default().then(&[2]).fresh_writes(slots_past_the_cap()) } -/// After the Oracle's read: its `POP`, its caller's, then the fresh slots. +/// After the Oracle's read: the `SLOAD`'s cold access, which the read is made and committed +/// before, as one charge; the Oracle's `POP`, its caller's, then the fresh slots. fn oracle_pops_then_writes() -> Charges { - Charges::default().then(&[2, 2]).fresh_writes(slots_past_the_cap()) + Charges::default().then(&[2_100, 2, 2]).fresh_writes(slots_past_the_cap()) } /// A frame that reads the block's timestamp and then writes the fresh slots stops at the @@ -1246,18 +1247,19 @@ fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { /// A contract that calls one that reads the Oracle's storage and then writes the fresh slots: the /// middle contract is stopped at the first write past the limit, and the outer contract resumes -/// on what the limit leaves it: its `POP`, then its read of its own slot, whose cold access crosses -/// the limit again and stops the transaction. +/// on what the limit leaves it: its `POP`, then its read of its own slot — its static gas, then +/// its cold surcharge, each its own charge — then a loop, whose charges cross the limit again +/// wherever the middle contract's crossing left the outer one, and stop the transaction. #[test] fn test_parent_runs_out_of_gas_after_oracle_access() { let middle = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), None)); let outer = call_all(BytecodeBuilder::default(), B).append(POP).append_many([PUSH0, SLOAD, POP]); let db = MemoryDatabase::default() - .account_code(A, outer.stop().build()) + .account_code(A, crate::detention::spin(outer)) .account_code(B, middle.stop().build()); // The middle contract's crossing, then the outer one's `POP`, `PUSH0` and cold `SLOAD`: its - // static gas, then the cold surcharge. + // static gas, then the cold surcharge; then its loop, in a memory of nothing. let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); let params = mega_evm::satin_gas_params(); let sload = [ @@ -1267,7 +1269,7 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { params.get(GasId::cold_storage_additional_cost()), 2, ]; - let left = Charges::default().then(&sload).left(left); + let left = Charges::default().then(&sload).spin(0).left(left); let (_, accessed) = assert_detention_stop(with_oracle_read(db), detention_limits(), left); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 39a429a00..2532aafb3 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -215,13 +215,14 @@ fn test_the_oracle_reading_its_own_storage_is_held_to_the_cap() { .account_code(ORACLE_CONTRACT_ADDRESS, oracle_reads_then_spins()) }; - // Whoever calls it, the Oracle's `POP` and loop come after its read. - let left = Charges::default().then(&[2]).spin(0).left(CAP); + // Whoever calls it, the `SLOAD`'s cold access, which the read is made before, and the + // Oracle's `POP` and loop come after its read. + let left = Charges::default().then(&[2_100, 2]).spin(0).left(CAP); let run = execute(db(), tx(CALLER, ORACLE_CONTRACT_ADDRESS, gas_limit)); assert_eq!( assert_stopped(&run, intrinsic, left), - CAP + 2 + 2_100, - "the direct call: PUSH0 and a cold SLOAD" + CAP + 2, + "the direct call: the PUSH0 before the read" ); assert_eq!(run.accessed, VolatileDataAccess::ORACLE); @@ -315,8 +316,9 @@ fn test_the_system_address_is_not_detained() { /// /// independent: the cap, the compute at the read and the bill are the spec's own numbers. /// The cap is 20,000,000. -/// `TIMESTAMP` costs 2, `PUSH0` costs 2 and a cold `SLOAD` costs 2,100, so the compute at the -/// read is that opcode's gas. +/// `TIMESTAMP` costs 2, so the compute at its read is that opcode's gas. An Oracle read is made +/// before its `SLOAD` charges anything, so the compute at it is the `PUSH0`'s 2, and the `SLOAD`'s +/// cold access, 2,100, is the first charge the allowance pays after it. /// The EIP-2780 intrinsic of a call to an existing account, with no value and no calldata, is /// `TX_BASE_COST` (12,000) plus the recipient access (3,000). /// What the loop leaves is the same hand count `Charges` makes: the `POP` after the read, the @@ -351,10 +353,16 @@ fn test_a_users_deposit_is_detained() { assert_ne!(CALLER, MEGA_SYSTEM_ADDRESS); assert_ne!(CALLER, mega_evm::SYSTEM_ADDRESS); - // What a 20,000,000 allowance has left when the copy that crosses it is not made. + // What a 20,000,000 allowance has left when the copy that crosses it is not made: after the + // block environment's read, and after the Oracle's, whose `SLOAD` pays its cold access first. let left = allowance_after_the_read(BLOCK_ENV_CAP); assert_eq!(left, 1_100); assert_eq!(Charges::default().then(&[2]).work(PAST_THE_CAP, 0).left(BLOCK_ENV_CAP), left); + let oracle_left = allowance_after_the_read(ORACLE_CAP - COLD_SLOAD); + assert_eq!( + Charges::default().then(&[COLD_SLOAD, 2]).work(PAST_THE_CAP, 0).left(ORACLE_CAP), + oracle_left + ); let timestamp = work(op(BytecodeBuilder::default(), TIMESTAMP), PAST_THE_CAP).stop().build(); let oracle = work(BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP]), PAST_THE_CAP) @@ -373,11 +381,11 @@ fn test_a_users_deposit_is_detained() { assert_deposit_stopped( "Oracle", oracle.clone(), - PUSH_GAS + COLD_SLOAD, + PUSH_GAS, ORACLE_CAP, VolatileDataAccess::ORACLE, intrinsic, - left, + oracle_left, source, ); assert_system_transaction_is_not_stopped("TIMESTAMP", timestamp, BLOCK_ENV_CAP); @@ -695,6 +703,100 @@ fn test_a_database_failure_surfaces_and_a_stack_underflow_comes_first() { } } +/// The operands of a `CALLCODE` of `to` carrying no value, with an input of 1 MiB, an output of +/// nothing and 1,000 gas: the frame cannot pay the input's memory. +fn callcode_of_a_mebibyte(to: Address) -> BytecodeBuilder { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(0x10_0000_u32) + .append_many([PUSH0, PUSH0]) + .push_address(to) + .push_number(1_000_u16) + .append(CALLCODE) +} + +/// What the pushes of [`callcode_of_a_mebibyte`] cost. +const CALLCODE_PUSHES: u64 = 2 + 2 + 3 + 2 + 2 + 3 + 3; + +/// With access off, a call opcode reads its target's account and code to find the EIP-7702 +/// delegate it would follow, before it charges or checks anything, and the read is required: a +/// `CALLCODE` of a delegator of the beneficiary, with an input of 1 MiB its 1,000 gas cannot pay, +/// is refused for free where the delegator can be read, and gives the transaction no outcome +/// where its account or its code cannot, rather than halting on the memory. +#[test] +fn test_a_call_target_unreadable_for_its_delegate_has_no_outcome() { + let code_hash = Bytecode::new_eip7702(BENEFICIARY).hash_slow(); + let child = callcode_of_a_mebibyte(DELEGATOR).build(); + let parent = BytecodeBuilder::default() + .append_many([PUSH0; 5]) + .push_address(CHILD) + .push_number(CALLCODE_PUSHES + 1_000) + .append_many([CALL, POP]) + .stop() + .build(); + let db = || { + MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child.clone()) + }; + + let readable = with_delegation(db(), DELEGATOR, BENEFICIARY); + let mut evm = MegaEvm::new(context(readable).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let record = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!( + (record.result, record.output.clone()), + refused(VolatileDataAccess::BENEFICIARY_BALANCE), + "a readable delegator" + ); + assert_eq!(record.spent, CALLCODE_PUSHES, "the refusal costs nothing"); + + for fails_on_code in [false, true] { + let mut db = ErrorInjectingDatabase::new(db().account_lazy_code(DELEGATOR, code_hash)); + if fails_on_code { + db.fail_on_code_by_hash = Some(code_hash); + } else { + db.fail_on_account = Some(DELEGATOR); + } + let result = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .execute_transaction(tx(CALLER, CONTRACT, BELOW)); + assert!(result.is_err(), "code {fails_on_code}: {result:?}"); + } +} + +/// The read of a call target's account and code that finds its delegate warms neither: a call the +/// read does not refuse — of a delegator of another account than the beneficiary — pays the cold +/// access to its target with access off as with access on, and spends the same. +#[test] +fn test_the_delegate_read_warms_nothing() { + let child = call(BytecodeBuilder::default(), CALL, DELEGATOR).stop().build(); + let spent = |disabled: bool| { + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, OTHER) + .account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, CHILD).stop().build()) + .account_code(CHILD, child.clone()) + .account_code(OTHER, BytecodeBuilder::default().stop().build()); + let mut ctx = context(db); + if disabled { + ctx = ctx.with_volatile_access_disabled_from(1); + } + let mut evm = MegaEvm::new(ctx).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "disabled {disabled}"); + let child = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!(child.result, InstructionResult::Stop, "disabled {disabled}"); + child.spent + }; + let on = spent(false); + // The five pushes and the address's, the `GAS`, the call's cold target and its delegate's + // cold account, and the `POP`: the callee stops at once and hands back what it was forwarded. + let cold = + entry(GasId::warm_storage_read_cost()) + entry(GasId::cold_account_additional_cost()); + assert_eq!(on, 2 * 5 + 3 + 2 + 2 * cold + 2, "access on"); + assert_eq!(spent(true), on, "access off reads the target first and warms nothing"); +} + /// Calling `MegaAccessControl` costs the caller its call's overhead alone: the answer carries the /// forwarded gas back untouched. #[test] diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index 9ad75cd0e..aa81e5fc4 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -506,10 +506,11 @@ fn reads_the_oracle(rounds: u16) -> Bytes { /// A constructor reads the Oracle's storage as any frame does: it gets the service's value when /// the service answers and the chain's otherwise, at the same price either way, and the read is -/// volatile, under the Oracle's cap. Past a cap of 1,000, the constructor stops at its write of +/// volatile, under the Oracle's cap. Past a cap of 5,000, the constructor stops at its write of /// what it read — a fresh, cold slot, whose dynamic charge of 22,000 no such cap pays — after the -/// Oracle's return and the constructor's `POP`, push, `MLOAD`, `PUSH0` and `SSTORE`'s static gas, -/// and the call answers the creation's stop, deploying nothing. +/// `SLOAD`'s cold access, which the read is made before, the rest of the Oracle's frame, and the +/// constructor's `POP`, push, `MLOAD`, `PUSH0` and `SSTORE`'s static gas, and the call answers the +/// creation's stop, deploying nothing. #[test] fn test_a_constructor_reads_the_oracle_as_any_frame_does() { let deployment = Deployment::new(reads_the_oracle(1_000)); @@ -552,10 +553,10 @@ fn test_a_constructor_reads_the_oracle_as_any_frame_does() { .with_inspector(OracleTail::default()); evm.execute_transaction(tx()).expect("the transaction is valid"); let tail = evm.inspector().tail(); - let left = crossing_left(1_000, &[tail, 2, 3, 3, 2, 100, 22_000], &[]); + let left = crossing_left(5_000, &[2_100, tail, 2, 3, 3, 2, 100, 22_000], &[]); assert!(left > 0, "the write is the charge that crosses: {left}"); - let stopped = run_tx(oracle_context(db(), service.clone(), 1_000), tx(), true); + let stopped = run_tx(oracle_context(db(), service.clone(), 5_000), tx(), true); assert_creation_stopped(&stopped, &deployment, gas_limit, left); assert_eq!(stopped.accessed, VolatileDataAccess::ORACLE); } diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs index 4b9e0f4ae..7fa3a0b46 100644 --- a/crates/mega-evm/tests/system/oracle_storage.rs +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -17,7 +17,7 @@ use mega_evm::{ op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, ReplayingOracleEnv, }, volatile_data_access_disabled_revert_data, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, - LimitCheck, LimitKind, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, OracleEnv, OracleRead, VolatileDataAccess, }; use revm::{ @@ -25,7 +25,10 @@ use revm::{ CALL, CALLDATASIZE, DELEGATECALL, DUP2, GAS, JUMPDEST, JUMPI, MSTORE, POP, PUSH0, PUSH1, RETURN, SLOAD, SSTORE, STOP, SUB, SWAP1, TIMESTAMP, }, - context::TxEnv, + context::{ + result::{ExecutionResult, HaltReason}, + TxEnv, + }, interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Inspector, }; @@ -287,8 +290,9 @@ fn test_every_oracle_read_is_cold() { } /// A read of the Oracle's storage is a read of volatile data under the Oracle's own cap: the -/// limit it sets is the transaction's compute at the read — the push and the `SLOAD`, with its -/// cold access — plus the Oracle's cap, not the block environment's. +/// limit it sets is the transaction's compute at the read — the push before the `SLOAD`, the read +/// being made before any of the `SLOAD`'s gas is charged — plus the Oracle's cap, not the block +/// environment's. #[test] fn test_an_oracle_read_is_detained_under_the_oracles_cap() { let code = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); @@ -305,7 +309,7 @@ fn test_an_oracle_read_is_detained_under_the_oracles_cap() { ); assert!(run.outcome.result.is_success()); assert_eq!(run.accessed, VolatileDataAccess::ORACLE); - assert_eq!(run.limit, Some(2 + 2_100 + 5_000_000)); + assert_eq!(run.limit, Some(2 + 5_000_000)); } // Under the default limits the cap is the spec's. @@ -314,7 +318,7 @@ fn test_an_oracle_read_is_detained_under_the_oracles_cap() { &Service::default(), call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), ); - assert_eq!(run.limit, Some(2 + 2_100 + ORACLE_ACCESS_COMPUTE_GAS)); + assert_eq!(run.limit, Some(2 + ORACLE_ACCESS_COMPUTE_GAS)); } /// A hint reaches the oracle service before a read the transaction makes after it, so the read @@ -401,36 +405,68 @@ fn test_a_read_outside_the_oracles_frame_is_an_ordinary_read() { assert_eq!(run.limit, None); } -/// A frame that cannot pay the cold access reads nothing: it runs out of gas as revm's own -/// skipped cold load does, the service is not asked, and nothing volatile was read. -#[test] -fn test_a_read_the_frame_cannot_pay_for_asks_nothing() { - let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); - // The caller forwards 1,000 gas: enough for the push and the warm part of the `SLOAD`, not - // for its cold access. - let caller = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_000_u16) - .append(CALL) - .append_many([PUSH0, MSTORE]) - .push_number(32_u8) - .append_many([PUSH0, RETURN]) - .build(); - let service = Service::holding(U256::ZERO, SERVICE_VALUE); - let db = - system_db().account_code(ORACLE_CONTRACT_ADDRESS, oracle).account_code(CONTRACT, caller); - let run = run(db, &service, call_tx(CONTRACT, [], U256::ZERO)); +/// The regular gas a call to `to` spends before its first instruction, with `to` running `STOP`: +/// what a transaction to it is billed on the regular ledger, at the byte prices in effect. +fn intrinsic(to: Address) -> u64 { + let db = system_db().account_code(to, BytecodeBuilder::default().stop().build()); + let run = run(db, &Service::default(), call_tx(to, [], U256::ZERO)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + run.outcome.gas.regular +} - assert!(run.outcome.result.is_success()); - assert_eq!( - U256::from_be_slice(run.outcome.result.output().unwrap()), - U256::ZERO, - "the call failed" - ); - assert!(service.seen().is_empty(), "a read the frame cannot pay for asks nothing"); - assert!(run.outcome.oracle_reads.is_empty(), "and records nothing"); - assert_eq!(run.accessed, VolatileDataAccess::empty()); +/// A transaction to `to` whose own frame starts with `frame_gas` of regular gas: the gas limit +/// covers the intrinsic regular gas and the body's history, which a transaction below the +/// execution cap pays from its regular gas. +fn tx_with_frame_gas(to: Address, frame_gas: u64) -> MegaTransaction { + tx_with_gas(to, &[], intrinsic(to) + crate::common::body_history(0) + frame_gas) +} + +/// The Oracle's read is made before any of its gas is charged, the 100 of its warm base included: +/// whatever the frame holds when it reaches the `SLOAD` — fewer than 100, from 100 to 2,099, the +/// 2,100 exactly, or more — the slot is loaded, the service asked, and the read marked at the +/// compute before the `SLOAD`, the push's 2, so its limit is 2 plus the Oracle's cap. Then the +/// 2,100 is charged: a frame short of it runs out of gas at the `SLOAD`, the mark standing for the +/// rest of the transaction, and one that holds it pushes the service's value. +#[test] +fn test_an_oracle_read_is_made_before_its_charge_at_every_gas() { + let code = BytecodeBuilder::default().append_many([PUSH0, SLOAD, PUSH0, MSTORE]); + let code = code.push_number(32_u8).append_many([PUSH0, RETURN]).build(); + // The push, the `SLOAD`, and the `MSTORE` with its push and its memory, and the return's two + // pushes: what a frame that completes the read spends after it. + let after = 2 + 3 + 3 + 3 + 2; + for (left, completes) in [(50, false), (2_099, false), (2_100, true), (4_099, true)] { + let service = Service::holding(U256::ZERO, SERVICE_VALUE); + let db = system_db().account_code(ORACLE_CONTRACT_ADDRESS, code.clone()); + let frame_gas = 2 + left + if completes { after } else { 0 }; + let run = run(db, &service, tx_with_frame_gas(ORACLE_CONTRACT_ADDRESS, frame_gas)); + + assert_eq!(service.seen(), vec![Seen::Read(U256::ZERO)], "{left}: the service was asked"); + assert_eq!( + run.outcome.oracle_reads, + [OracleRead { slot: U256::ZERO, answer: Some(SERVICE_VALUE) }], + "{left}: and the read recorded" + ); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE, "{left}: the read is marked"); + assert_eq!(run.limit, Some(2 + ORACLE_ACCESS_COMPUTE_GAS), "{left}: before the SLOAD"); + let oracle = run.outcome.state.get(&ORACLE_CONTRACT_ADDRESS).expect("the Oracle is read"); + assert!(oracle.storage.contains_key(&U256::ZERO), "{left}: the slot is loaded"); + if completes { + assert!(run.outcome.result.is_success(), "{left}: {:?}", run.outcome.result); + assert_eq!(U256::from_be_slice(run.outcome.result.output().unwrap()), SERVICE_VALUE); + } else { + assert!( + matches!( + run.outcome.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), + .. + } + ), + "{left}: {:?}", + run.outcome.result + ); + } + } } /// A read refused because the frame's volatile-data access is off asks the service nothing: the @@ -577,10 +613,9 @@ fn test_two_answers_for_one_slot_replay_only_from_the_record() { } /// A detained frame whose regular gas holds the cold access, but which may not spend it past the -/// compute limit, reads and asks the service all the same: the read's charge then stops the -/// transaction at the limit, and the Oracle read is not marked. A frame whose regular gas cannot -/// hold the cold access at all asks nothing -/// ([`test_a_read_the_frame_cannot_pay_for_asks_nothing`]). +/// compute limit, reads, asks the service and marks the read all the same: the 2,100 is then one +/// charge, the crossing, and stops the frame with none of it made, so the stop's compute is the +/// compute before the `SLOAD` — the `TIMESTAMP`, its `POP` and the push — and the mark stands. #[test] fn test_a_detained_frame_that_may_not_spend_the_cold_access_asks_and_is_stopped() { let code = BytecodeBuilder::default().append_many([TIMESTAMP, POP, PUSH0, SLOAD, STOP]).build(); @@ -594,18 +629,54 @@ fn test_a_detained_frame_that_may_not_spend_the_cold_access_asks_and_is_stopped( ); assert_eq!(service.seen(), vec![Seen::Read(U256::ZERO)], "the service was asked"); - assert!( - matches!( - run.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) - ), - "{:?}", - run.outcome.limit_exceeded + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: 2 + 1_500, + used: 2 + 2 + 2, + frame_local: false, + }), + ); + assert_eq!( + run.accessed, + VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE, + "the Oracle read is marked" ); - assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP, "the Oracle read is not marked"); assert_eq!(run.limit, Some(2 + 1_500), "the timestamp's limit binds"); } +/// The Oracle's `SLOAD` charges its 2,100 as one charge, after the read; another contract's +/// `SLOAD` charges its static 100 and then its cold access, each its own charge. Under a limit +/// that leaves 1,000 spendable at the `SLOAD`, the Oracle's read is stopped at the compute before +/// it, none of the 2,100 made, and the other contract's at the compute after its 100, which it +/// could spend. +#[test] +fn test_the_oracles_cold_access_is_one_charge_and_another_sload_two() { + let code = BytecodeBuilder::default().append_many([TIMESTAMP, POP, PUSH0, SLOAD, STOP]).build(); + // `TIMESTAMP` sets the limit at its compute, 2, plus the cap; the `POP` and the push leave the + // `SLOAD` 1,000 of it. + let cap = 1_000 + 2 + 2; + let stop = |at: Address| { + let run = run_under( + system_db().account_code(at, code.clone()), + &Service::default(), + EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap), + |ctx| ctx, + call_tx(at, [], U256::ZERO), + ); + match run.outcome.limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, limit, used, .. }) => { + assert_eq!(limit, 2 + cap); + used + } + other => panic!("{at}: expected the compute stop, got {other:?}"), + } + }; + assert_eq!(stop(ORACLE_CONTRACT_ADDRESS), 2 + 2 + 2, "the Oracle: none of the 2,100"); + assert_eq!(stop(OTHER), 2 + 2 + 2 + 100, "another contract: its static 100, then the stop"); +} + /* ---------- which source answered leaves no trace ---------- */ /// Below the execution cap, and above it, where the reservoir pays state and history gas first. From beeb4ac924a437932c244e98d7c4916d87a88bb8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:09:41 +0800 Subject: [PATCH 036/190] docs: the Oracle read order and free refused reads --- AGENTS.md | 16 +++++++++++----- crates/mega-evm/README.md | 3 ++- docs/spec/upgrades/satin.md | 25 +++++++++++++++++++------ 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 84cbadb63..7ad6982a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -292,7 +292,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A `sendHint` from a frame whose volatile-data access is off — its own switch or one above it — is dropped: not forwarded and not counted, while the call runs the bytecode as any other. - The Oracle's storage is read through the oracle environment: an `SLOAD` in the Oracle's own frame (a load whose owner is the Oracle) loads the slot through the journal, then asks `OracleEnv::get_oracle_storage`, and gets the environment's value when it answers — even over a value the Oracle's frame stored earlier in the transaction — and the loaded value when it answers `None`; `EmptyExternalEnv` always answers `None`. A node that replays a block without the service must price and witness it as the node that built it did, and it cannot tell which source the building node read, so nothing may depend on the source: every such read is priced as a cold access, however often the slot was read, and the slot is loaded on both paths, so afterwards it is warm for the frame's `SSTORE` and it is in the transaction's state, which a stateless witness is built from. - A frame whose regular gas, the part detention withholds included, cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either; a detained frame that holds the gas but may not spend it does ask, and the charge then stops that frame at the compute limit. + The read is made before any of its gas is charged (`oracle_sload` in `evm/instructions.rs`, which the table runs for an `SLOAD` in the Oracle's own frame): the slot is loaded, the service asked where it is asked, and the read marked and committed at the compute before the `SLOAD`; only then is the cold access charged, its warm base included, as one charge of 2,100. + So a frame that cannot pay it, whether it holds fewer than 100 or from 100 to 2,099, reads, asks and marks, then runs out of gas, the mark standing; a detained frame that holds the gas but may not spend it reads, asks and marks too, and the charge is the crossing, judged on the whole 2,100 and stopped with none of it made; a refused read asks nothing and marks nothing. + Every other `SLOAD` is revm's, its static 100 then its cold access, each its own charge. It is a volatile read for detention, under the Oracle's cap, and a hint reaches the service synchronously as `sendHint` is called, so a read after a hint finds the service told. A system call, a pre-block call among them, a deposit and a Mega System Transaction ask no service: their Oracle reads answer the chain's slot, are loaded, priced and marked as any other, and record nothing (`MegaContext::asks_oracle_service`, decided in `on_new_tx` — a system-address transaction by the verdict validation hands it, before its promotion, any other deposit by its type — and in `on_new_system_call`), because a value the service gives must be on the chain before its reader, written by a Mega System Transaction the block orders first, and none of the three can have one; so a chain whose EIP-2935 or EIP-4788 code reads the Oracle still replays from its witness, and the deposit-only block in which Satin activates asks the service nothing. Every read by a transaction that asks 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. @@ -365,6 +367,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 Oracle's read is the exception: its wrapper commits it once the slot is read, before the `SLOAD` charges anything, at the compute before the opcode, and the mark stands through the out-of-gas or the stop that follows. 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. @@ -415,7 +418,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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 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. + 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 (a read wrapper charges its opcode's), 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. @@ -423,8 +426,11 @@ Detention caps how much a transaction may still compute once it read such data ( `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 (the interceptor's answer carries the switch-off, `system::Answer`, which the settlement applies), 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`. The state is `Detention`'s, and `MegaContext::with_volatile_access_disabled_from` is the test helper that sets it without a call. - The Host then refuses the load and the wrapper reverts the frame with `VolatileDataAccessDisabled(accessType)` on the gas it had after the opcode's static gas, so a refused read pays its static gas and nothing else. - `BLOCKHASH` names `BlockHash` (7), though revm's instruction loads the block number first; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. + The opcode's wrapper then refuses the read before the opcode charges or checks anything (`refused_read` in `evm/instructions.rs`), and the frame reverts with `VolatileDataAccessDisabled(accessType)` on the gas it held when it reached the opcode: a refused read costs nothing, not its static gas, which the wrapper charges itself and only once the read is not refused, so a frame below the static gas is refused rather than run out of gas. + An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` included — is refused before its operands are read, so a `BLOCKHASH` on an empty stack is refused; an account, call, `SELFDESTRUCT` or Oracle read is refused only once every operand it takes is on the stack (a stack underflow stays one), when its target operand, its frame's own address (`SELFBALANCE`, `SELFDESTRUCT`), its frame's storage (`SLOAD` of the Oracle's) or a call target's one-hop EIP-7702 delegate is volatile, before its body's memory, copy, static-context or value checks. + The delegate is read for the decision (`MegaContext::call_target_delegate`): the target's account and code are loaded inside a journal mark taken back at once, so they are in the transaction's state and witness and warm nothing; the read is required, and a database error fails the transaction with its cause, never taken for a target without a delegate. + The Host's own refusal of a load stays behind it, which no opcode reaches (a debug build asserts so). + `BLOCKHASH` names `BlockHash` (7) whatever its operand; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. The error's argument is encoded as a `uint8`, and Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value out of range, and the Rust `IMegaAccessControl` binding decodes 12 to its `__Invalid` placeholder; `decode_volatile_data_access_disabled` is the Rust side's decoder. The system contracts are not changed for it: their bytecode, and so their code hashes, stay as deployed. @@ -451,7 +457,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer A call that transfers no value, of any scheme, makes no record whatever the journal holds, and the hook charges it nothing without reading the journal (`limit::start_makes_no_records`; a debug build reads it and asserts there is nothing to charge). 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). + The opcodes that can read volatile data run in detention's read wrapper (see Gas detention), which charges the opcode's static gas itself once it decided the read is not refused, so the table carries none for them (`READ_OPCODES`); the wrapper charges Satin's, or the fixture fork's once the test tooling installed it (`MegaContext::read_static_gas`, `MegaEvm::replace_static_gas_table`). 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, 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 what revm did — a value transfer's two sides and a creation's created account, as they stood before revm decided the start and as they stand once it did, a creation's creator once the creation returned (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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 69bf1d6c2..c8625c96c 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -156,7 +156,8 @@ Every precompile of the Satin set is priced, op-revm's size-limited BN254 pairin A precompile the engine cannot price — a node's own, an address a node replaced — is run on what the limit leaves its frame, and one it does not pay is the crossing, whatever its price. A keyless deployment's call is the transaction's own frame, held to the limit as any frame is: the overhead and the `CREATE` opcode's regular gas it charges are compute whether a rule then refuses the call or its creation runs, and the creation runs under what the limit leaves it. Every other out-of-gas halts and burns as it would without the read. -While `MegaAccessControl`'s switch is off for a frame, its volatile reads are refused: the frame reverts with `VolatileDataAccessDisabled`, having paid the opcode's static gas and nothing more. +While `MegaAccessControl`'s switch is off for a frame, its volatile reads are refused before the opcode charges or checks anything: the frame reverts with `VolatileDataAccessDisabled` on the gas it held when it reached the opcode, also when that is below the opcode's static gas. +An Oracle read is made before any of its 2,100 is charged: the slot is loaded, the oracle service asked and the read marked, and a frame that then cannot pay the charge runs out of gas with the mark standing. The error's argument is a `uint8`: a refused `SLOTNUM` names access type 12, which the contract's `VolatileDataAccessType` does not declare, so a Solidity handler must decode it as `uint8`, and `decode_volatile_data_access_disabled` decodes it on the Rust side. 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. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index cc04c1609..a8f2332c8 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -941,6 +941,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th The block environment (`NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH`); the block beneficiary's account, through `BALANCE`, `SELFBALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four call opcodes 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 the beneficiary, and a keyless deployment's signer that is the beneficiary; and the Oracle's storage, through `SLOAD` in the Oracle's own frame. `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. + An Oracle read is the exception: it MUST be marked when it is made, before its cold access is charged, and the mark MUST stand for the rest of the transaction though the `SLOAD` then runs out of gas or is stopped, its `compute_at_read` the compute before that charge (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). `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 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. @@ -972,6 +973,8 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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. 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. + Each part an opcode deducts from regular gas is one charge, held to the spendable part where the opcode deducts it, in the opcode's order: its static gas, then each dynamic part it deducts on its own; the first part the spendable part cannot pay decides, as the crossing when the frame's whole regular gas can pay it and as an out-of-gas when it cannot. + An Oracle read's cold access and an interceptor's answer are each one charge instead (see Interceptor answers, below, and [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)): an `SLOAD` of another contract's storage pays its static 100 and then its cold access as two charges, the Oracle's `SLOAD` its 2,100 as one. - **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. @@ -1003,12 +1006,18 @@ The reference implementation has no price for one, so it runs such a precompile - `MegaAccessControl`'s interface, errors, and the scope of `disableVolatileDataAccess()`, `enableVolatileDataAccess()` and `isVolatileDataAccessDisabled()` are unchanged. - `disableVolatileDataAccess()` switches access off once its answer is settled; an answer gas detention turns into the compute stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST leave the switch as it was. -- A read is refused where the opcode loads the value, after it read its operands: an opcode that fails on its operands (a stack underflow, for example) fails as it would with access on. - The load comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. +- An opcode volatile whatever its operands — `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM` and `BLOCKHASH` — MUST be refused before its operands are checked, so a `BLOCKHASH` on an empty stack is refused rather than halting on the underflow. A `BLOCKHASH` is refused as `BLOCKHASH` (7) whatever its operand. -- 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. +- An opcode volatile only for the account or the storage it reads — `BALANCE`, `SELFBALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four call opcodes, `SELFDESTRUCT` and an `SLOAD` of the Oracle's storage — MUST first have every operand it takes on the stack: one that fails on its operands (a stack underflow, for example) fails as it would with access on. + Once its operands are there, it MUST be refused when what it reads is the beneficiary's account or the Oracle's storage, as its operands and its frame show it: the target operand of `BALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH` or a call opcode, or a call target's one-hop EIP-7702 delegate; the executing frame's own address for `SELFBALANCE`, and for `SELFDESTRUCT`, whose target operand is checked too; the frame's storage for an `SLOAD`. + The refusal comes before the opcode charges anything and before any other check its body makes — a memory expansion, a copy, a static-context check, a value transfer, a state charge — so an `EXTCODECOPY` of the beneficiary with a large length, or a call to it the frame could not fund, is refused rather than running out of gas. + Either refusal comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. +- A call opcode whose target's EIP-7702 delegate is the block beneficiary MUST be refused as the beneficiary's account (10): in a frame whose access is off, the opcode reads its target's account and code — not the delegate's — to find the delegate, one hop, before it charges anything, unless the target is itself the beneficiary. + That read lands in the transaction's read set but makes neither account warm, so a call it does not refuse is priced as it would be with access on. + The read is required: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. +- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. + The frame reverts on the gas it held when it reached the opcode, nothing having been charged, and a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, is refused all the same and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. + A refused read marks nothing for gas detention and asks no oracle service. - The error's argument MUST be ABI-encoded as a `uint8`: | `accessType` | Read | @@ -1150,7 +1159,11 @@ An out-of-gas step halts the call, consuming its regular gas. - An `SLOAD` in the Oracle's own frame MUST load the slot from state, then, unless the read is made during a system call, a deposit or a Mega System Transaction, ask the oracle service, and answer the service's value when it gives one and the loaded value otherwise. The service's value MUST win over whatever the slot holds at the read, a value the Oracle's own frame wrote earlier in the transaction included; with no value from the service the read answers the slot's present value, that write included. - Every such read MUST be charged as a cold access (2,100 gas), however often the slot was read, and the slot MUST be loaded whichever source answers, so a later write finds it warm and a stateless witness carries it. -- A frame whose regular gas, its withheld part included, cannot pay the cold access MUST read nothing and ask nothing; a refused read asks nothing. +- The read MUST be made before the cold access is charged: the slot is loaded, the service asked when the read is one that asks it, and the read marked for gas detention at the compute before the `SLOAD`, and only then is the 2,100 charged, as one charge, its warm base of 100 included: no part of the `SLOAD`'s gas is charged before the read. + A frame whose regular gas, its withheld part included, cannot pay the cold access — whether it holds fewer than the warm base's 100 or from 100 to 2,099 — therefore loads the slot, asks the service where it is asked and marks the read, and then runs out of gas at the `SLOAD`; the mark stands for the rest of the transaction. + When the charge is gas detention's crossing — the spendable part cannot pay the 2,100 while the whole regular gas can — the frame is stopped with none of it made, and the slot stays loaded and the read marked all the same. + A replaying node makes the same read before the same charge, so the slot is in the witness whether or not the frame then paid for it. +- A read refused because the frame's volatile-data access is off asks the service nothing and marks nothing (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)). - A system call, a deposit and a Mega System Transaction MUST NOT ask the service for a value: their reads answer the slot's value on the chain, its present value, a write made earlier in the same call or transaction included, are loaded, priced and marked as any Oracle read is, and record no answer. Only a transaction that is neither a deposit nor a Mega System Transaction asks the service, and the rule holds for the whole of the call or transaction it covers. A node that replays a block runs no service, so a value the service gives a read must be on the chain before the transaction that read it, written by a Mega System Transaction the block orders first, and none of the three can have one before it. From 86e0c4c658bc55dbc448d103e6eea116220f200c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:10:35 +0800 Subject: [PATCH 037/190] test(evme): a Satin replay reads the L1 block contract only where a transaction does Recorded blocks that are not Satin's activation block replay offline from the recording on Satin: no pre-block read of the L1 fee overhead is left to serve. --- bin/mega-evme/tests/block_replay.rs | 75 +++++++++++----------------- bin/mega-evme/tests/common/blocks.rs | 18 ++----- bin/mega-evme/tests/replay_paths.rs | 16 ++---- 3 files changed, 39 insertions(+), 70 deletions(-) diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index ec3a4c4da..001754050 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -6,11 +6,11 @@ mod common; use std::path::Path; -use alloy_primitives::{Address, B256, U256}; +use alloy_primitives::{Address, B256}; use common::blocks::{ block_path, cache_copy, cache_copy_for_satin, code_of, factory_account, fixtures, is_deposit, - overhead_slot, read_block, refused_for_block_gas, run_evme, satin_genesis, set_overhead, - timestamp_of, write_block, BLOCKS, FACTORY, L1_BLOCK, + overhead_slot, read_block, refused_for_block_gas, run_evme, satin_genesis, timestamp_of, + write_block, BLOCKS, FACTORY, L1_BLOCK, }; use mega_evm::{system::MEGA_SYSTEM_ADDRESS, MegaSpecId, ProtocolLimits}; use serde_json::Value; @@ -95,15 +95,16 @@ fn test_the_legacy_leg_replays_recorded_blocks_as_the_chain_did() { assert_eq!(std::fs::read(block_path(cache.path(), BLOCKS[0])).unwrap(), before); } -/// A Satin replay of a recorded block reads what the recording lacks: offline, the block fails -/// and names the first of them it met, and the exit code is 1. A counterfactual block is not -/// Satin's activation block, so it reads no predeploy, and its miss is the L1 fee overhead, which -/// the pre-block read of the L1 block info reads beside the fee scalars the recording holds set. -/// Satin's activation block — under a genesis file that activates Satin at the block, whose -/// parent came a second earlier — checks the predeploys first, and its miss is the EIP-7997 -/// factory. +/// A Satin replay of a recorded block reads what the recording lacks only in Satin's activation +/// block. A counterfactual block is not Satin's activation block, so it reads no predeploy, and it +/// reads the L1 block contract as the legacy engine does, when a transaction is priced against it +/// or held to its footprint: the L1 fee overhead, which the recording lacks, is not read beside +/// the fee scalars the recording holds set, so every recorded block replays offline. Satin's +/// activation block — under a genesis file that activates Satin at the block, whose parent came a +/// second earlier — checks the predeploys first: offline, it fails, names the EIP-7997 factory it +/// met, and the exit code is 1. #[test] -fn test_a_read_the_recording_lacks_fails_the_block_offline() { +fn test_a_satin_replay_reads_beyond_the_recording_only_in_its_activation_block() { let refusal = |dir: &Path, args: &[&str]| { let run = replay(BLOCKS[0], dir, args); assert_eq!(run.code, 1); @@ -113,8 +114,14 @@ fn test_a_read_the_recording_lacks_fails_the_block_offline() { }; let cache = cache_copy(); - let error = refusal(cache.path(), &["--override.spec", "Satin"]); - assert!(error.contains(&format!("storage {L1_BLOCK:#x}[{}]", overhead_slot())), "{error}"); + for number in BLOCKS { + let block = read_block(cache.path(), number); + let l1_block = block.prestate.accounts.get(&L1_BLOCK).expect("every block reads it"); + assert!(!l1_block.storage.contains_key(&overhead_slot()), "no recording holds it"); + let run = replay(number, cache.path(), &["--override.spec", "Satin"]); + assert_eq!(run.code, 0, "block {number}: {}", run.stderr); + assert_eq!(blocks_of(&run.records())[0]["engine"], "satin"); + } let dir = tempfile::tempdir().unwrap(); let mut block = read_block(cache.path(), BLOCKS[0]); @@ -162,36 +169,14 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { } } -/// Whatever the L1 fee overhead holds, the Satin rows of the recorded blocks are the same: the -/// blocks' fee scalars are set, so no transaction is priced with it, and the pre-block read that -/// reads it is no transaction. -#[test] -fn test_the_overhead_does_not_change_the_satin_rows() { - let zero = cache_copy_for_satin(); - let set = cache_copy_for_satin(); - for number in BLOCKS { - let mut block = read_block(set.path(), number); - set_overhead(&mut block, U256::from(188)); - write_block(set.path(), number, &block); - } - for number in BLOCKS { - let rows = |dir: &Path| { - let run = replay(number, dir, &["--override.spec", "Satin"]); - assert_eq!(run.code, 0, "{}", run.stderr); - run.records() - }; - assert_eq!(rows(zero.path()), rows(set.path()), "block {number}"); - } -} - /// [S18] A block fetched over RPC replays as the chain did, is written to the block cache with /// what its replay read beyond the trace, and then replays offline from the cache. The mock /// serves the recorded responses, and the trace is the recorded pre-state as one transaction's -/// sighting. The Satin replay, a counterfactual and so no activation block, reads one slot the -/// recording lacks, the L1 fee overhead its pre-block read of the L1 block info reads, and the -/// cache keeps it; it reads no predeploy, so the cache holds no EIP-7997 factory. +/// sighting. The Satin replay, a counterfactual and so no activation block, reads nothing the +/// trace lacks: no predeploy, so the cache holds no EIP-7997 factory, and no L1 fee overhead, +/// which no transaction of the block is priced with, so the cache holds none. /// -/// Expected values: independent (the chain's own receipts, and the one pre-block read). +/// Expected values: independent (the chain's own receipts, and the trace's reads). #[tokio::test(flavor = "multi_thread")] async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { let number = BLOCKS[2]; @@ -206,9 +191,9 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { let run = replay(number, cache.path(), &["--rpc", &uri, "--override.spec", "Satin"]); assert_eq!(run.code, 0, "{}", run.stderr); - assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 1, "the L1 fee overhead came over RPC"); + assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 0, "nothing beyond the trace"); - // Offline now: the cache holds the block, and the overhead the Satin replay read. + // Offline now: the cache holds the block, and nothing the trace did not hold. drop(server); let run = replay(number, cache.path(), &["--verify"]); assert_eq!(run.code, 0, "{}", run.stderr); @@ -218,7 +203,7 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 0); let cached = read_block(cache.path(), number).prestate; assert!(!cached.accounts.contains_key(&FACTORY), "no predeploy was read"); - assert_eq!(cached.accounts[&L1_BLOCK].storage.get(&overhead_slot()), Some(&U256::ZERO)); + assert_eq!(cached.accounts[&L1_BLOCK].storage.get(&overhead_slot()), None, "nor the overhead"); } /// `--override.limits` replays a Satin block under other protocol limits: the fields it names @@ -487,7 +472,7 @@ enum Parent { } /// A mock of the chain serving the recorded `number` block, its receipts, its pre-state as a -/// trace, and the reads Satin's pre-block changes make beyond it; the parent block's header is +/// trace, and the read Satin's activation block makes beyond it; the parent block's header is /// what `parent` says. async fn recorded_chain(number: u64, parent: Parent) -> wiremock::MockServer { use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; @@ -550,8 +535,8 @@ async fn recorded_chain(number: u64, parent: Parent) -> wiremock::MockServer { respond("eth_getBlockReceipts", recorded.receipts.clone()).mount(&server).await; respond("debug_traceBlockByNumber", trace).mount(&server).await; // The parent state of what the trace does not hold: the factory, as the chain holds it - // ([`factory_account`]), which Satin's activation block checks, and the L1 fee overhead, which - // is zero. + // ([`factory_account`]), which Satin's activation block checks; any other account or slot + // asked for is empty. let factory = factory_account(); let per_account = |method: &'static str, factory_value: Value, other: Value| { Mock::given(matchers::method("POST")) diff --git a/bin/mega-evme/tests/common/blocks.rs b/bin/mega-evme/tests/common/blocks.rs index 666ba0500..443bfec2e 100644 --- a/bin/mega-evme/tests/common/blocks.rs +++ b/bin/mega-evme/tests/common/blocks.rs @@ -12,7 +12,7 @@ use std::{ sync::OnceLock, }; -use alloy_primitives::{address, Address, B256, U256}; +use alloy_primitives::{address, Address, B256}; use mega_evme::block::{CachedBlock, PreAccount}; use serde_json::Value; @@ -32,9 +32,8 @@ pub(crate) fn factory_account() -> PreAccount { } } -/// The L1 block contract, whose L1 fee overhead slot Satin's pre-block changes read with the -/// rest of the L1 block info, whatever the fee scalars hold. The legacy engine reads the slot -/// only when the scalars are empty, which they are not on these blocks, so no recording holds it. +/// The L1 block contract, whose L1 fee overhead slot either engine reads only when the fee +/// scalars are empty, which they are not on these blocks, so no recording holds it. pub(crate) const L1_BLOCK: Address = address!("0x4200000000000000000000000000000000000015"); /// The L1 fee overhead slot of [`L1_BLOCK`]. @@ -90,9 +89,7 @@ pub(crate) fn cache_copy() -> tempfile::TempDir { /// A copy of the recorded block cache in which every block's pre-state holds what a Satin replay /// reads beyond the recording: the factory, as the chain holds it ([`factory_account`], its code -/// in the cache's code store), which only Satin's activation block reads, and the L1 fee overhead, -/// zero, as the chain held it. `block_replay.rs` shows the overhead's value changes no transaction -/// row. +/// in the cache's code store), which only Satin's activation block reads. pub(crate) fn cache_copy_for_satin() -> tempfile::TempDir { let dir = cache_copy(); let factory = factory_account(); @@ -102,18 +99,11 @@ pub(crate) fn cache_copy_for_satin() -> tempfile::TempDir { for number in BLOCKS { let mut block = read_block(dir.path(), number); block.prestate.accounts.insert(FACTORY, factory.clone()); - set_overhead(&mut block, U256::ZERO); write_block(dir.path(), number, &block); } dir } -/// Has `block`'s pre-state hold `value` as the L1 fee overhead. -pub(crate) fn set_overhead(block: &mut CachedBlock, value: U256) { - let l1_block = block.prestate.accounts.get_mut(&L1_BLOCK).expect("every block reads it"); - l1_block.storage.insert(overhead_slot(), value); -} - fn copy_dir(from: &Path, to: &Path) { std::fs::create_dir_all(to).unwrap(); for entry in std::fs::read_dir(from).unwrap() { diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs index 4762cf033..c83b99908 100644 --- a/bin/mega-evme/tests/replay_paths.rs +++ b/bin/mega-evme/tests/replay_paths.rs @@ -7,10 +7,9 @@ //! and on Satin (the in-tree port against the block driver). //! //! The RPC is a mock that answers only from the recorded block: a read the recording does not -//! hold is an error, not a guess. The two exceptions are what Satin's pre-block changes read and -//! no recording holds: the EIP-7997 factory, which Satin's activation block checks, served with -//! its code as the chain holds it, and the L1 block contract's L1 fee overhead, served as zero, as -//! the chain held it. `block_replay.rs` shows the overhead changes no transaction row. +//! hold is an error, not a guess. The one exception is what Satin's pre-block changes read and no +//! recording holds: the EIP-7997 factory, which Satin's activation block checks, served with its +//! code as the chain holds it. #![cfg(feature = "legacy")] mod common; @@ -22,8 +21,8 @@ use std::{ use alloy_primitives::{address, Address, B256, U256}; use common::blocks::{ - cache_copy_for_satin, code_of, factory_account, fixtures, is_deposit, overhead_slot, - read_block, run_evme, satin_genesis, timestamp_of, FACTORY, L1_BLOCK, + cache_copy_for_satin, code_of, factory_account, fixtures, is_deposit, read_block, run_evme, + satin_genesis, timestamp_of, FACTORY, }; use mega_evme::block::{CachedBlock, PreAccount}; use serde_json::{json, Value}; @@ -43,11 +42,6 @@ struct Recording { impl Recording { fn account(&self, address: Address) -> Option { match self.block.prestate.accounts.get(&address) { - Some(account) if address == L1_BLOCK => { - let mut account = account.clone(); - account.storage.entry(overhead_slot()).or_insert(U256::ZERO); - Some(account) - } Some(account) => Some(account.clone()), None if address == FACTORY => Some(factory_account()), None => None, From 5394ff8c461b6759ef8864f00b9dfa870134633d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:10:35 +0800 Subject: [PATCH 038/190] docs: the L1 block contract is reported with the first transaction that reads it --- AGENTS.md | 13 +++++------ REVIEW.md | 2 +- bin/mega-evme/README.md | 4 ++-- docs/mega-evme/commands/replay.md | 2 +- docs/mega-evme/cookbook.md | 2 +- docs/spec/upgrades/satin.md | 36 +++++++++++++++++++------------ 6 files changed, 34 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 84cbadb63..08bfea1f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,7 +141,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, and refusing an absent parent timestamp where the schedule activates a fork after genesis that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `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`) | +| `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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, and refusing an absent parent timestamp where the schedule activates a fork after genesis that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `MegaTransactionExt` (`helpers.rs`); the reads of the L1 block contract the fee computation and the footprint make outside every transaction's journal, reported once each per block as read-only entries of the returned state of the first committed transaction that made them, never in place of that transaction's own entries, so a witness built from the committed states holds what op-revm and the executor read on the database itself, and a block that reads none of the contract reads nothing of it (`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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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`) | @@ -275,8 +275,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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`). - `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`). + `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), and applies a role change the `SequencerRegistry` has due in the block (see the system calls below); it reads nothing of the L1 block contract. + op-revm's fee computation and the executor's footprint read read the L1 block contract on the block's state rather than through a transaction's journal, so their reads land in no transaction's state; the executor adds them, once each per block, to the returned state of the first transaction that made them, as read-only entries that never replace the transaction's own (`l1_block_info.rs`): the footprint read — the account and slot 8 — with the first non-deposit transaction, a Mega System Transaction included, and the fee read — the account and slots 1, 3, 7 and 8, and the overhead (5) only when the Ecotone scalars it finds are empty, which a deposit earlier in the block decides — with the first transaction the fee computation prices, read again through op-revm's own fetch once the transaction ran, on the state it ran on, whether or not this node's op-revm fetched it (`tests/block/witness/state.rs`). + A failed fee read is a failed read of the transaction's execution, routed by whether the database declares it fatal; a failed footprint read is always an internal error. 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. The block in which Satin activates reads the seven in order, and each must hold exactly Satin's code, whatever its nonce, balance and storage (`check_system_contract`, `system/predeploys.rs`); anything else — no account, no code, an older version, other code — refuses the block with one error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and each read is a read-only pre-block state. @@ -752,11 +753,11 @@ When the agent is requested to implement a new feature or bug fix, it should con CI's msrv job checks the workspace on 1.94.0, every feature on, with the lock as it is. A dependency whose newer releases declare a newer compiler (alloy 2.2 and later declare 1.94.1) stays on the newest release the declared version builds: `.cargo/config.toml` sets the resolver's `incompatible-rust-versions = "fallback"`, so a `cargo update` run in the repository picks it. - **Pre-block helpers return their state and never commit.** - A helper that takes part in `apply_pre_execution_changes` (the activation block's check of the predeploys, the pre-block system calls, the registry's due-change read, the L1 block info read) never calls `db.commit(...)`: it returns the prepared state — an `EvmState`, or a `ResultAndState` for a system call — and the executor commits it on its own, in order, so the sequence of committed states is the witness a stateless client needs. - A read that changes nothing (a predeploy holding Satin's code, the L1 block info) returns `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. + A helper that takes part in `apply_pre_execution_changes` (the activation block's check of the predeploys, the pre-block system calls, the registry's due-change read) never calls `db.commit(...)`: it returns the prepared state — an `EvmState`, or a `ResultAndState` for a system call — and the executor commits it on its own, in order, so the sequence of committed states is the witness a stateless client needs. + A read that changes nothing (a predeploy holding Satin's code, the registry's pending slots) returns `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. Returning nothing there is a bug — the account disappears from the stateless witness read set. A step that writes includes every account and storage slot it touched; a predeploy holding other code is an error, never an overwrite. - `system/predeploys.rs` holds the predeploy check, `block/eips.rs` the EIP-2935 and EIP-4788 calls, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, `block/l1_block_info.rs` the L1 block info read, and the block executor is what commits them. + `system/predeploys.rs` holds the predeploy check, `block/eips.rs` the EIP-2935 and EIP-4788 calls, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, and the block executor is what commits them. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. Follow the existing pattern: `#[cfg(not(feature = "std"))] use alloc as std;` then `use std::{vec::Vec, ...};`. diff --git a/REVIEW.md b/REVIEW.md index fe1d39f5c..049281aa4 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -21,7 +21,7 @@ Defer to the baseline for everything not listed here; the rules below take prece ### Consensus-critical execution - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. -- 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(...)`. +- Pre-block helpers (the activation block's predeploy check, pre-block system calls, the registry's due-change 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. - **A write is counted once its opcode completed.** diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index a8510ddf7..e359984dc 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -279,8 +279,8 @@ mega-evme replay 0x1234...txhash --override.input-file calldata.hex # Check 200 blocks against the chain and record them mega-evme replay --block 26400000..26400199 --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify -# The same blocks on Satin, as NDJSON (the first Satin run reads the L1 fee overhead slot over RPC; -# later runs of the same blocks can drop --rpc) +# The same blocks on Satin, as NDJSON (--rpc serves what a Satin run reads beyond the cache, such +# as a path a transaction takes on Satin that it did not take on the chain) mega-evme replay --block 26400000..26400199 --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --override.spec Satin --json > satin.ndjson ``` diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index 918090af8..ac0d9b9a3 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -255,7 +255,7 @@ The exit code is 0, 1 when a block could not be replayed, or 2 when `--verify` i `--override.spec Satin` runs every block as it would run on Satin: every transaction as signed, on the state its parent block left, under Satin's protocol limits, or those `--override.limits` gives, with no building policy of a block builder applied. A transaction the Satin engine refuses (it cannot pay for its gas, or a block budget is full) is reported `refused` and left out, and the block goes on. A transaction signed with a gas limit sized for legacy costs can run out of gas on Satin: that is the counterfactual's answer, not a tool fault. -`--override.spec Satin` runs no block as Satin's activation block, so it checks no predeploy; what it reads beyond the legacy replay is the L1 fee overhead slot, which every Satin block reads with the rest of the L1 block info. +`--override.spec Satin` runs no block as Satin's activation block, so it checks no predeploy, and it reads the L1 block contract as the legacy replay does, when a transaction is priced against it or held to its footprint; what it reads beyond the legacy replay is only what a transaction's Satin run reads on a path the chain's run did not take. ## Transaction Overrides diff --git a/docs/mega-evme/cookbook.md b/docs/mega-evme/cookbook.md index d0c842fe6..97e090ba8 100644 --- a/docs/mega-evme/cookbook.md +++ b/docs/mega-evme/cookbook.md @@ -69,7 +69,7 @@ mega-evme replay --block 26400000..26400099 \ ``` Replay the same blocks on Satin and keep the per-transaction records. -The first Satin run reads over RPC what Satin reads beyond the legacy replay (the L1 fee overhead slot of the L1 block contract, which its pre-block changes read with the rest of the L1 block info) and adds it to the cache; later runs of the same blocks can drop `--rpc`: +A Satin run reads the L1 block contract as the legacy replay does and checks no predeploy, so it needs `--rpc` only for a path a transaction takes on Satin that it did not take on the chain; such a read is made over RPC and added to the cache: ```bash mega-evme replay --block 26400000..26400099 --block-cache ./blocks \ diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index cc04c1609..c2c02369f 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1228,8 +1228,10 @@ An out-of-gas step halts the call, consuming its regular gas. 1. make the EIP-2935 call; 2. make the EIP-4788 call (a block without a parent beacon block root is invalid, as EIP-4788 defines); 3. in the block in which Satin activates, and in no other, check the six MegaETH system contracts in address order — Oracle, High-Precision Timestamp, KeylessDeploy, MegaAccessControl, MegaLimitControl, SequencerRegistry — and then the [EIP-7997](https://eips.ethereum.org/EIPS/eip-7997) `CREATE2` factory at `0x4e59b44847b379578588920ca78fbf26c0b4956c`, as below; - 4. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`; - 5. read the L1 block contract's account and its five fee slots, as [the stateless witness](#22-the-stateless-witness) lays out. + 4. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`. + + The sequence reads nothing of the L1 block contract: a transaction reads it when it needs it, as [the stateless witness](#22-the-stateless-witness) lays out. + - **The activation check.** Satin runs on a chain that ran the legacy forks, which installed the six MegaETH system contracts at the versions Satin runs, and whose genesis OP's tooling gave the EIP-7997 factory: Satin deploys, upgrades and seeds none of them. The block in which Satin activates — Satin active at its timestamp and not at its parent's — MUST read the seven addresses, and each MUST hold exactly the code Satin expects: the Oracle and the SequencerRegistry at version 2.0.0, the other four system contracts at the bytecode Rex6 runs, and the factory's runtime, code hash `0x2fa86add0aed31f33a762c9d88e807c475bd51d0f52bd0955754b2608f7e4989`. @@ -1245,8 +1247,8 @@ An out-of-gas step halts the call, consuming its regular gas. - **Failure.** A pre-block call that does not succeed MUST make the block invalid, before its state is used. A database error the node's database declares fatal is an internal error of the node, not a verdict on the block; any other failure of a call — a non-fatal database error, another EVM error, an outcome that is not a success — makes the block invalid. - A database error in the activation check, in the due-change read or in the read of the L1 block info is always an internal error. - The L1 block info is read for every block, whatever its transactions, so a node whose database cannot serve the L1 block contract's account, or one of the five slots of a contract the chain holds, cannot execute the block: it fails before the block's first transaction, as an internal error, even for a block of deposits alone, which prices nothing against the contract, or a block whose transactions never read the overhead slot (5). + A database error in the activation check or in the due-change read is always an internal error. + No pre-block step reads the L1 block contract, so a node whose database cannot serve a slot of it that no transaction of the block reads executes the block: a block of deposits alone, which reads none, or a block whose transactions never read the overhead slot (5). ### 19. The Protocol's Own Transactions @@ -1368,7 +1370,7 @@ A block is not invalid for a transaction a building policy would have skipped. A transaction MUST be included with a failed receipt when it reverts, halts, or its own frame is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). A failed bucket-capacity read or database read is a fault of the node, never an outcome of the transaction, for a deposit as for any transaction: the transaction gets no outcome and MUST NOT be settled, as a failed deposit or otherwise. -The node MUST report the failure as an internal error with its cause: a failed bucket-capacity read always; a failed database read the transaction's execution makes when the node's database declares the error fatal, and otherwise as an invalid-block verdict, as for a pre-block call (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); and a failed read block execution makes for the transaction outside its execution — the L1 block contract's account and footprint gas scalar before a non-deposit transaction, a transaction's sender's account before the transaction runs — always, as the activation check's is. +The node MUST report the failure as an internal error with its cause: a failed bucket-capacity read always; a failed database read the transaction's execution makes — the L1 block contract's account and slots its fee computation reads among them — when the node's database declares the error fatal, and otherwise as an invalid-block verdict, as for a pre-block call (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); and a failed read block execution makes for the transaction outside its execution — the L1 block contract's account and footprint gas scalar before a non-deposit transaction, a transaction's sender's account before the transaction runs — always, as the activation check's is. A node that meets the failure cannot execute the block past that transaction: it reaches no verdict on the block, except that a non-fatal database error met inside the transaction's execution is reported as an invalid block (above); a builder, which has no outcome to include for that transaction, MAY leave a non-deposit transaction out of the block it builds, but a deposit MUST be included, so the block that must hold it cannot be built while the read fails. A block MUST be invalid when: @@ -1399,7 +1401,7 @@ The witness is defined by what the block's execution returns and exports, and a - the oracle service's answer to every oracle read the block's included transactions recorded, in block order. 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). + The one exception is the L1 block info the transaction is priced against and the footprint gas scalar it is held to, which are read outside its journal and which the block reports with the first transaction that read them (see the L1 block info, 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. @@ -1408,20 +1410,25 @@ The witness is defined by what the block's execution returns and exports, and a 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, 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. + 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, and the `applyPendingChanges()` call's state. 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. The header, the chain configuration — the schedule — the parent hash, the parent beacon block root, the extra data and the parent block's timestamp are inputs a validator is given beside the witness. Whether the block admits only deposits (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)) and whether Satin activates in it are not inputs: block execution works them out from the schedule, the block's timestamp and the parent block's timestamp. `SLOTNUM` pushes zero, so a validator needs no slot number. - **The L1 block info.** - A non-deposit transaction is priced against the L1 block contract (`0x4200000000000000000000000000000000000015`): its L1 base fee slot (1), its Ecotone fee scalars slot (3), its Ecotone blob base fee slot (7), its operator fee scalars slot (8), which also holds the DA footprint gas scalar, and, only when the Ecotone scalars are empty (the blob base fee scalar and the eight bytes of the two scalars zero), its L1 fee overhead slot (5). - These reads are made on the block's state, not through a transaction's journal, so they land in no transaction's returned state. - None is made before the block's first non-deposit transaction other than a Mega System Transaction, and each finds the state the transactions before it left: whether the overhead is read is decided by the scalars they left, not by the scalars the chain held before the block, and a deposit that empties the scalars names no overhead in its returned state. - The pre-block phase MUST therefore read the contract's account and all five slots, whatever the scalars it reads hold, and commit them as a state of their own, of read-only entries, after every other pre-block step. - Every OP chain holds the contract from genesis; a state that does not, such as a test's, records the account as not existing and reads no slot. - A witness so holds the overhead of a block that never reads it again, and a block cannot be executed on a state that cannot serve the contract's account or one of the five slots, whether or not a transaction would have been priced with it: the failure is an internal error of the node, not a verdict on the block, and for a stateless validator a defect of the witness it was given. - The read changes nothing: the entries are not written, and a transaction finds the same values, or the ones the block's L1 attributes deposit wrote over them, which are in that deposit's own returned state. + The L1 block contract (`0x4200000000000000000000000000000000000015`) is read, when it is needed, by two reads of the base layer. + The fee computation prices a non-deposit transaction that pays an L1 fee — every one but a Mega System Transaction — and reads the contract's account, its L1 base fee slot (1), its Ecotone fee scalars slot (3), its Ecotone blob base fee slot (7), its operator fee scalars slot (8), and, only when the Ecotone scalars are empty (the blob base fee scalar and the eight bytes of the two scalars zero), its L1 fee overhead slot (5). + It reads them once per block, at the block's first non-deposit transaction other than a Mega System Transaction, on the state the transactions before it left: whether the overhead is read is decided by the scalars they left, not by the scalars the chain held before the block, and a deposit that empties the scalars names no overhead in its returned state. + The footprint read holds every non-deposit transaction, a Mega System Transaction included, to its data-availability footprint, and reads the contract's account and the footprint gas scalar in slot 8 before the transaction runs. + Both reads are made on the block's state, not through a transaction's journal, so they land in no transaction's returned state. + The node MUST nevertheless report the contract's account and every slot either read reaches, each once per block, as read-only entries of the returned state of the first transaction the block includes that read it, whether for its fee or for its footprint, so that the witness holds them. + A read-only entry MUST NOT replace an entry the transaction's own execution made in its state: a write it made to the contract stands. + A block whose only non-deposit transactions are Mega System Transactions therefore reports the account and slot 8, with the first of them, though none pays an L1 fee. + A state that holds no contract at the address records the account as not existing and reads no slot; every OP chain holds the contract from genesis. + Nothing of the contract is read before the block's transactions, and a slot neither read reaches is not read: a block with no non-deposit transaction reads none of it, and a block whose scalars are set does not read the overhead. + A failed read is reported as [Transaction and Block Refusals](#21-transaction-and-block-refusals) classifies it: the fee computation's as a read of the transaction's own execution, the footprint scalar's as a read block execution makes for the transaction outside its execution, always an internal error. + The reads change nothing: the entries are not written. - **The reads a validator makes again.** A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, a `BLOCKHASH` of the current block or outside the last 256 blocks, an oracle read the frame cannot pay, a read a frame whose volatile-data access is off is refused, a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. - **The SALT buckets.** @@ -1531,6 +1538,7 @@ A node, a stateless validator and a replay tool must agree on everything below, A block that is not Satin's activation block checks no predeploy, and runs on a state that may lack them. - **The L1 block information.** Block execution reads the L1 block contract at the block's first non-deposit transaction other than a Mega System Transaction, after the block's L1 attributes deposit wrote it, unless the node handed it the information for this block beforehand, which it then prices with, the footprint gas scalar aside; a node that hands it over must hand over what that deposit writes, so that the block's transactions are priced as [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka) requires. + What it reports of the contract with the first transaction that read it is what a node that handed nothing over reads, whether or not this node handed the information over, since a validator re-executing the block reads it (see [The Stateless Witness](#22-the-stateless-witness)). - **The witness.** 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. From d219b49b4d6587e17f64e5be4b37507cb0068544 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:13:53 +0800 Subject: [PATCH 039/190] docs(evm): an unfunded value call is charged nothing at its start --- crates/mega-evm/src/evm/host.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index c3b82344d..637d4f99a 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -416,8 +416,9 @@ impl revm::context_interface::Host /// such a creation calls it without the address it would take, which makes none either. A /// start revm then refuses 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 value the caller cannot - /// fund makes no record either, and is priced none here, so its charge is nothing: only a - /// value call's history allowance is parked for it, and comes back when it returns. + /// fund makes no record and is priced none here, so it is charged nothing: only a value + /// call's history allowance, which is no gas, is parked for it, and closes with the start when + /// it returns. /// /// 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 From 5f200b17032f59cda7b84df94315a8318e3424c6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:14:23 +0800 Subject: [PATCH 040/190] fix(evm): build the read wrappers' table helper only for the test tooling --- crates/mega-evm/src/evm/instructions.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index e2f638e46..e9c5f0da5 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -172,6 +172,7 @@ pub(crate) fn mega_instructions( /// `table` as the interpreter charges it with the read wrappers installed: the static gas of every /// opcode the wrappers run is theirs to charge, so the interpreter's entry is zero. +#[cfg(any(test, feature = "test-utils"))] pub(crate) fn without_read_static_gas(mut table: GasTable) -> GasTable { for opcode in READ_OPCODES { table[opcode as usize] = 0; From 97484bb2246b18ff9d505ad47acedb4be4c74600 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:14:30 +0800 Subject: [PATCH 041/190] test(evm): align modexp maximum gas behavior --- crates/mega-evm/src/evm/precompiles.rs | 6 +++++- docs/spec/upgrades/satin.md | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 77cef5047..4ed16df28 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -652,7 +652,7 @@ mod tests { Some(u64::MAX), "position={position}" ); - for gas in [0, 499, 500, 100_000, u64::MAX - 1, u64::MAX] { + for gas in [0, 499, 500, 100_000, u64::MAX - 1] { let result = run(address, Bytes::copy_from_slice(&input), gas); assert_eq!( result.result, @@ -661,6 +661,10 @@ mod tests { ); assert_eq!(result.gas.remaining(), 0, "position={position}, gas={gas}"); } + // Like go-ethereum, a u64::MAX gas limit pays the saturated price before the bound. + let result = run(address, Bytes::copy_from_slice(&input), u64::MAX); + assert_eq!(result.result, InstructionResult::PrecompileError, "position={position}"); + assert_eq!(result.gas.remaining(), 0, "position={position}"); } } diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 9770d317b..381c7fe2e 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -115,7 +115,8 @@ The precompile set MUST be Karst's, with KZG point evaluation at MegaETH's price An input over an Optimism pairing or MSM size limit fails the call before any gas check, a call forwarded no gas included; like every precompile call that fails, it consumes all the gas forwarded to it. ModExp MUST first charge its 500-gas minimum, then the rest of its Osaka formula price with each length saturated to 64 bits, and only then check EIP-7823's 1,024-byte bound on each length. -A call that cannot pay the minimum MUST fail before reading the lengths; a formula price beyond any representable gas limit MUST fail out of gas even at the maximum gas limit. +A call that cannot pay the minimum MUST fail before reading the lengths. +The formula price MUST saturate at 2^64 − 1; a gas limit equal to that saturated price passes the gas check and then fails the size bound. Gas detention MUST use that same formula price for an over-bound input, so a price above the allowance but within the forwarded gas stops the call before its size check. KZG point evaluation keeps its Rex6 semantics: a call given less than 100,000 gas fails with an out-of-gas before any verification runs, and a successful call is charged exactly 100,000. A KZG call given at least 100,000 gas that fails otherwise — an input of the wrong length, a versioned hash that does not match the commitment, a proof that does not verify — consumes all the gas forwarded to it, not 100,000. From 8fc18592f4b710eb751dbe987b6c485f3b7c56f0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:29:39 +0800 Subject: [PATCH 042/190] chore(deps): move the revm fork pin to the ModExp pricing order --- .claude/skills/satin-review/SKILL.md | 2 +- Cargo.lock | 42 ++++++++++++++-------------- Cargo.toml | 24 ++++++++-------- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 90e6d3542..30bad8214 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -32,7 +32,7 @@ The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and 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` fork at `4c8f0d43b70f2175f9ce0132cc343283f9a29548` and the `megaeth-labs/op-revm` fork at `8c0db939291e1c4cbf2375782d1483bc371d6b94`, 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. +- Fork code: the `megaeth-labs/revm` fork at `a125b2c45bef8476e2c1b72dac315c1d05f94f61` and the `megaeth-labs/op-revm` fork at `8c0db939291e1c4cbf2375782d1483bc371d6b94`, 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). diff --git a/Cargo.lock b/Cargo.lock index 61e1dbb7f..3d08fdadd 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.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -2384,7 +2384,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2514,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3316,7 +3316,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.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.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" 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?rev=4c8f0d43b70f2175f9ce0132cc343283f9a29548#4c8f0d43b70f2175f9ce0132cc343283f9a29548" +source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" dependencies = [ "alloy-eip7928 0.4.11", "k256", @@ -5764,7 +5764,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6429,7 +6429,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.52.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.59.0", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d23238546..5c3c023cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,18 +232,18 @@ 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", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "4c8f0d43b70f2175f9ce0132cc343283f9a29548" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } [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 From 48e7451abd8e5ce60bad857d3362bebd31bfae90 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:36:01 +0800 Subject: [PATCH 043/190] fix(evm): apply packing limits to system transactions --- AGENTS.md | 10 +- bin/mega-evme/tests/block_replay.rs | 18 +- bin/mega-evme/tests/legacy_line.rs | 52 +++ crates/mega-evm/README.md | 5 +- crates/mega-evm/benches/block.rs | 29 +- crates/mega-evm/src/block/executor.rs | 10 +- crates/mega-evm/src/block/limit.rs | 36 +- crates/mega-evm/src/block/result.rs | 5 +- .../mega-evm/tests/block/system_tx_budgets.rs | 391 ++++++++++++++---- .../tests/satin/limit_matrix/block.rs | 37 +- docs/spec/hardfork-spec.md | 2 +- docs/spec/upgrades/overview.md | 2 +- docs/spec/upgrades/satin.md | 28 +- 13 files changed, 455 insertions(+), 170 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 84cbadb63..0f4865a8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -260,7 +260,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Switching the context to the neutral configuration decides that an ordinary execution pays no history, until the next preparation decides again: switching back with `with_cfg` alone does not price it, so a system call run straight through the handler, which prepares nothing, pays none (`tests/satin/history_exemption.rs`). 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 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 block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction is held to the block's packing budgets, the builder's policy, the block's gas limit and the data-availability footprint 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. @@ -268,11 +268,11 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to the spec's `ProtocolLimits` and the builder's `BlockLimits`, and fills `BlockGasCounters`. 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. - 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`). + It never refuses a deposit, which L1 derivation requires; the builder's policy never refuses one either. + A Mega System Transaction is held to both, and both transaction classes count towards the budget, so later transactions find the room they used. + 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 non-deposit transaction is refused before it runs, a Mega System Transaction included, and only deposits are exempt, while still counting; 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. + 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 hold it as any other non-deposit transaction; admission and the commit-time check exempt only `is_deposit`. 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`). `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. diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index ec3a4c4da..eda95dd2f 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -279,7 +279,8 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { let kept = unlimited["satin"]["data_size"].as_u64(); if from == MEGA_SYSTEM_ADDRESS { // The protocol's transactions carry gas limits close to the block's, so the gas the - // block has left may refuse one, as it may without the override; no limit does. + // block has left may refuse one, as it may without the override; the transaction's + // data-size limit does not. if tx["status"] == "refused" { let reason = tx["reason"].as_str().unwrap(); assert!(reason.contains("blocks available gas"), "{reason}"); @@ -287,7 +288,7 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { } assert!( tx["satin"]["limit_exceeded"].is_null(), - "the protocol's transaction {} is held to no limit", + "the protocol's transaction {} is held to no per-transaction data-size limit", tx["index"] ); if tx["satin"]["data_size"].as_u64().unwrap() > limit { @@ -311,8 +312,8 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { } assert!(protocols > 0 && others > 0, "{protocols} {others}"); - // The budget refuses every transaction after the one that reaches it but the protocol's own: - // a Mega System Transaction is never refused by it. + // The first deposit fills the budget. Every later non-deposit transaction is refused, + // including the system transactions that the recorded block holds. let (packed, block) = replay_under(Some(r#"{"blockTxsDataLimit":1}"#)); let is_protocols = |index: usize| { let from: Address = sent[index]["from"].as_str().unwrap().parse().unwrap(); @@ -320,13 +321,10 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { }; let protocol_txs = (1..packed.len()).filter(|&index| is_protocols(index)).count(); assert!(protocol_txs > 0, "the block holds Mega System Transactions"); - assert_eq!(block["refused"], block["transactions"].as_u64().unwrap() - 1 - protocol_txs as u64,); + assert!(sent.iter().skip(1).all(|tx| tx["type"] != "0x7e"), "only the first is a deposit"); + assert_eq!(block["refused"], block["transactions"].as_u64().unwrap() - 1); assert_eq!(packed[0], counterfactual[0], "the transaction that reaches the budget is packed"); - for (index, tx) in packed.iter().enumerate().skip(1) { - if is_protocols(index) { - assert_ne!(tx["status"], "refused", "the budget does not refuse the protocol's: {tx}"); - continue; - } + for tx in packed.iter().skip(1) { assert_eq!(tx["status"], "refused", "{tx}"); let reason = tx["reason"].as_str().unwrap(); assert!(reason.contains("Block transactions data limit reached"), "{reason}"); diff --git a/bin/mega-evme/tests/legacy_line.rs b/bin/mega-evme/tests/legacy_line.rs index 4167cd1d4..0499b3eb5 100644 --- a/bin/mega-evme/tests/legacy_line.rs +++ b/bin/mega-evme/tests/legacy_line.rs @@ -179,3 +179,55 @@ fn test_the_lockfile_parser_reads_packages() { assert_eq!(compatibility_line("0.18.14"), "0.18"); assert_eq!(compatibility_line("2.0.0-alpha.1"), "2"); } + +/// The released Rex6 engine applies block admission to a system call's legacy envelope. +/// Its exemption from per-transaction resource metering does not exempt block packing. +#[cfg(feature = "legacy")] +#[test] +fn test_rex6_system_transaction_block_admission_is_unchanged() { + use mega_evm_legacy::{ + alloy_primitives::{TxKind, B256}, + check_if_mega_system_transaction, BlockLimiter, BlockLimits, MegaHardfork, + MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + }; + + assert!(check_if_mega_system_transaction( + MEGA_SYSTEM_ADDRESS, + 0, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + MEGA_SYSTEM_ADDRESS, + )); + let limits = BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::Rex6, 1_000_000_000); + for (name, limits, refusal) in [ + ("data", limits.with_block_txs_data_limit(0), "Block transactions data limit reached"), + ("KV", limits.with_block_kv_update_limit(0), "Block KV update limit reached"), + ("growth", limits.with_block_state_growth_limit(0), "Block state growth limit reached"), + ("gas", limits.with_tx_gas_limit(0), "Transaction gas limit exceeded"), + ( + "encoded tx", + limits.with_tx_encode_size_limit(0), + "Transaction encode size limit exceeded", + ), + ( + "encoded block", + limits.with_block_txs_encode_size_limit(0), + "Block transactions encode size limit exceeded", + ), + ( + "DA tx", + limits.with_tx_da_size_limit(0), + "Transaction data availability size limit exceeded", + ), + ( + "DA block", + limits.with_block_da_size_limit(0), + "Block data availability size limit exceeded", + ), + ] { + let limiter = BlockLimiter::new(limits); + let error = limiter + .pre_execution_check(B256::ZERO, 100_000, 100, 100, false) + .expect_err("the legacy envelope is held to block admission"); + assert!(error.to_string().contains(refusal), "{name}: {error}"); + } +} diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 69bf1d6c2..3011d9f72 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -49,7 +49,7 @@ A frame start revm refuses on its caller's account — a value the caller cannot 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, 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. +The block's data size, write records and state growth are packing budgets: the transaction that reaches one is packed and every later non-deposit transaction 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. @@ -57,7 +57,8 @@ Every transaction is held to the spec's limits, and the block counts what its tr 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 packing budgets never refuse a deposit, which the block must include, or a Mega System Transaction; both still count towards them. +The block's packing budgets and building policy never refuse a deposit, which the block must include. +They hold a Mega System Transaction as any other non-deposit transaction, and both classes count towards the budgets. 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 executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`) — 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`). diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 67e9b24ed..15211d9d4 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -12,7 +12,7 @@ //! detention's caps, with no building policy on top (`BlockLimits::default()`); //! - from a fresh `State` over that database, as a node starts each block. //! -//! Three workloads of `N` transactions each, whose per-transaction work beyond the transaction +//! Four workloads of `N` transactions each, whose per-transaction work beyond the transaction //! itself is the executor's own: the admission checks, the size estimates, the limits, the //! counters, the receipt and the commit. //! @@ -26,6 +26,9 @@ //! contract call there is. Each reads and writes two balances and emits one `Transfer` log, so it //! carries two write records and a log through the counters. //! +//! - `system_updates`: legacy calls from the live system address that write fresh Oracle slots, +//! exercising the same admission and commit checks as user transactions. +//! //! The measurement runs `apply_pre_execution_changes`, the transactions and `finish` — the whole //! block a node executes — and hands the state back, so dropping it is not measured. One more arm, //! `steady_pre_block`, measures `apply_pre_execution_changes` alone on the steady state: the @@ -42,9 +45,10 @@ use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{ address, b256, hex, keccak256, Address, Bytes, Signature, TxKind, B256, U256, }; +use alloy_sol_types::SolCall; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ - system::{MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, test_utils::{BytecodeBuilder, CommittedStates, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTransactionOutcome, MegaTxEnvelope, @@ -329,6 +333,27 @@ fn bench_block(c: &mut Criterion) { ("storage_writes", transactions(WRITER, 0, 300_000, slot_calldata), 1), // The sender's balance and the recipient's. ("erc20_transfers", token_transfers(), 2), + ( + "system_updates", + (0..N) + .map(|nonce| { + transaction( + MEGA_SYSTEM_ADDRESS, + nonce, + ORACLE_CONTRACT_ADDRESS, + 0, + 500_000, + IOracle::setSlotCall { + slot: U256::from(nonce), + value: B256::repeat_byte(1), + } + .abi_encode() + .into(), + ) + }) + .collect(), + 1, + ), ]; let mut group = c.benchmark_group("block"); diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 881aff642..ef85e27c5 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -539,7 +539,7 @@ where output.gas_limit, output.tx_size, output.da_size, - output.is_deposit || output.is_system_transaction, + output.is_deposit, )?; self.check_da_footprint(output.da_footprint) } @@ -1014,13 +1014,7 @@ where // transaction here but refused there. let is_system_transaction = !is_deposit && self.is_system_transaction(&tx_env)?; - self.limiter.pre_execution_check( - tx_hash, - gas_limit, - tx_size, - da_size, - is_deposit || is_system_transaction, - )?; + self.limiter.pre_execution_check(tx_hash, gas_limit, tx_size, da_size, is_deposit)?; // A deposit is exempt from the data-availability footprint of the block, as it is from // its data-availability size. diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 1274ca0ef..094fe795e 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -38,10 +38,9 @@ //! 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 -//! deposit does. Its envelope is legacy, so it also counts towards the block's data-availability -//! size, and the data-availability footprint, which the executor checks, holds it. +//! A Mega System Transaction has a legacy envelope: every packing budget and building-policy +//! check holds it as any other non-deposit transaction. It counts towards every budget, including +//! the block's data-availability size and footprint, which the executor checks. //! //! The per-transaction limits the block installs on the EVM are not block limits: they hold a //! deposit's own execution the way they hold any transaction's, and a deposit that crosses one is @@ -111,17 +110,16 @@ 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 or a Mega System Transaction is. + /// reaches it is packed; after it, only a deposit 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. + /// transaction that reaches it is packed; after it, only a deposit 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. + /// growth. The transaction that reaches it is packed; after it, only a deposit 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, } @@ -227,7 +225,7 @@ impl ProtocolLimits { /// [`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. +/// of them refuses a deposit. /// /// 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`]). @@ -428,9 +426,9 @@ impl BlockLimiter { /// Whether `tx` may execute in this block. /// /// Checks the transaction against its own limits, and against what the block has left; a - /// transaction that is `packing_exempt` — a deposit, or a Mega System Transaction — is held to - /// the block's gas limit alone, to no limit only a builder applies and not to the data-size - /// limit. It reads the counters and changes nothing; + /// deposit is held to the block's gas limit alone, to no building policy or packing budget. + /// Every non-deposit transaction, including a Mega System Transaction, is held to all checks. + /// It reads the counters and changes nothing; /// [`post_execution_update`](Self::post_execution_update) advances the counters once the /// transaction commits. /// @@ -446,11 +444,11 @@ impl BlockLimiter { gas_limit: u64, tx_size: u64, da_size: u64, - packing_exempt: bool, + is_deposit: bool, ) -> Result<(), BlockExecutionError> { - // Of the limits checked here, a packing-exempt transaction is held to the block's gas limit + // Of the limits checked here, a deposit is held to the block's gas limit // alone (see the module's documentation on deposits). - if !packing_exempt && gas_limit > self.limits.tx_gas_limit { + if !is_deposit && gas_limit > self.limits.tx_gas_limit { return Err(invalid_tx( tx_hash, MegaTxLimitExceededError::TransactionGasLimit { @@ -468,9 +466,9 @@ impl BlockLimiter { .into()); } - // Nothing below refuses a packing-exempt transaction; `post_execution_update` still counts + // Nothing below refuses a deposit; `post_execution_update` still counts // it. - if packing_exempt { + if is_deposit { return Ok(()); } diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 786b84620..c8af37f8e 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -269,9 +269,8 @@ pub struct MegaBlockTxResult { pub is_deposit: bool, /// Whether the transaction is a Mega System Transaction: a legacy call from the live system /// address, which the engine runs as the protocol's own. The block decided it before the - /// transaction ran, from the registry's system address, and a delayed commit makes the same - /// decision. Like a deposit it is never refused by the data-size packing budget or by the - /// builder's policy, and counts towards them. + /// transaction ran, from the registry's system address. Its legacy envelope is held to the + /// packing budgets and the builder's policy, at admission and at a delayed commit alike. pub is_system_transaction: bool, /// The nonce the depositor had before execution, which the deposit receipt reports. `Some` /// only for a deposit. diff --git a/crates/mega-evm/tests/block/system_tx_budgets.rs b/crates/mega-evm/tests/block/system_tx_budgets.rs index 46e30fe77..0f7aeefd7 100644 --- a/crates/mega-evm/tests/block/system_tx_budgets.rs +++ b/crates/mega-evm/tests/block/system_tx_budgets.rs @@ -1,15 +1,15 @@ -//! 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. +//! Mega System Transactions obey packing budgets and building policy at admission and commit. +//! Deposits remain exempt; both classes count towards the budgets they consume. -use alloy_consensus::transaction::Recovered; +use alloy_consensus::{transaction::Recovered, Transaction}; use alloy_eips::Encodable2718; use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, Address, Bytes, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, - BlockLimits, MegaTransactionExt, MegaTxEnvelope, + BlockLimits, MegaSpecId, MegaTransactionExt, MegaTxEnvelope, ProtocolLimits, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use op_revm::constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, @@ -32,107 +32,330 @@ fn system_call(input: Bytes, gas_limit: u64) -> Recovered { ) } -/// The whole of the policy a builder could tighten, at its tightest. -fn tightest_policy() -> BlockLimits { - BlockLimits::no_limits() - .with_tx_gas_limit(1) - .with_tx_encode_size_limit(1) - .with_block_txs_encode_size_limit(1) - .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, 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_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"); +/// A full packing budget refuses a system transaction before execution and still admits a +/// deposit. A refusal changes neither counters nor receipts. +fn assert_full_budget_refuses_system(policy: BlockLimits, refusal: &str) { + let mut state = common::state(); + let mut builder = executor(&mut state, common::block_ctx(policy)); + builder.apply_pre_execution_changes().expect("the block starts"); + let before = builder.limiter().usage; + let error = builder.run_transaction(&system_tx()).expect_err("the budget is full"); + assert!(matches!(error, BlockExecutionError::Validation(_)), "{error}"); + assert!(error.to_string().contains(refusal), "{error}"); + assert_eq!(builder.limiter().usage, before); + assert!(builder.receipts().is_empty()); + builder + .execute_transaction(&common::deposit_tx(Bytes::new(), empty_call_gas())) + .expect("the same budget cannot refuse a deposit"); + assert_eq!(builder.receipts().len(), 1); - 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}"); - } + // Apply the same budget as a protocol limit, with no building policy. Whole-block + // validation must reject inclusion, rather than silently omit the transaction. + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN) + .with_block_txs_data_limit(policy.block_txs_data_limit) + .with_block_kv_update_limit(policy.block_kv_update_limit) + .with_block_state_growth_limit(policy.block_state_growth_limit); + let mut state = common::state(); + let validator = common::executor_with_limits(&mut state, limits); + let error = validator.execute_block([&system_tx()]).expect_err("the block is invalid"); + assert!(matches!(error, BlockExecutionError::Validation(_)), "{error}"); + assert!(error.to_string().contains(refusal), "{error}"); + + let mut state = common::state(); + let validator = common::executor_with_limits(&mut state, limits); + let block = validator + .execute_block([&common::deposit_tx(Bytes::new(), empty_call_gas())]) + .expect("a block holding a deposit is valid under the same budget"); + assert_eq!(block.receipts.len(), 1); } -/// A building policy at its tightest refuses an ordinary transaction and no system transaction: -/// the system transaction's size counts towards the block's encoded and data-availability sizes. #[test] -fn test_a_mega_system_transaction_is_admitted_under_a_tightened_building_policy() { - let mut state = common::state(); - let mut executor = executor(&mut state, common::block_ctx(tightest_policy())); - executor.apply_pre_execution_changes().expect("the block starts"); +fn test_a_mega_system_transaction_is_refused_at_a_full_data_budget() { + assert_full_budget_refuses_system( + BlockLimits::no_limits().with_block_txs_data_limit(0), + "Block transactions data limit reached", + ); +} - executor - .execute_transaction(&user_tx(0, empty_call_gas())) - .expect_err("the policy refuses an ordinary transaction"); +#[test] +fn test_a_mega_system_transaction_is_refused_at_a_full_kv_budget() { + assert_full_budget_refuses_system( + BlockLimits::no_limits().with_block_kv_update_limit(0), + "Block KV update limit reached", + ); +} +#[test] +fn test_a_mega_system_transaction_is_refused_at_a_full_state_growth_budget() { + assert_full_budget_refuses_system( + BlockLimits::no_limits().with_block_state_growth_limit(0), + "Block state growth limit reached", + ); +} + +/// Each policy rejects the system transaction one unit below its size or gas and admits it at +/// equality. Deposits ignore it, and validation without that policy includes the system call. +fn assert_system_obeys_policy( + set_limit: fn(BlockLimits, u64) -> BlockLimits, + measured: u64, + refusal: &str, +) { let system = system_tx(); - let outcome = executor.run_transaction(&system).expect("the policy does not refuse it"); - assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); - executor.commit_transaction_outcome(outcome).expect("and it commits"); + let mut state = common::state(); + let mut builder = + executor(&mut state, common::block_ctx(set_limit(BlockLimits::default(), measured - 1))); + builder.apply_pre_execution_changes().expect("the block starts"); + let error = builder.run_transaction(&system).expect_err("the policy refuses the system call"); + assert!(error.to_string().contains(refusal), "{error}"); + assert!(builder.receipts().is_empty()); + assert_eq!(builder.limiter().usage, mega_evm::LimitUsage::ZERO); + builder + .execute_transaction(&common::deposit_tx(system.input().clone(), system.gas_limit())) + .expect("a deposit in the same position is exempt"); + assert_eq!(builder.receipts().len(), 1); - assert_eq!(executor.limiter().block_tx_size_used, system.inner().encode_2718_len() as u64); + let mut state = common::state(); + let mut builder = + executor(&mut state, common::block_ctx(set_limit(BlockLimits::default(), measured))); + builder.apply_pre_execution_changes().expect("the block starts"); + let outcome = builder.run_transaction(&system).expect("equality fits"); + assert!(outcome.is_system_transaction && !outcome.is_deposit); + assert!(outcome.inner.result.is_success()); + builder.commit_transaction_outcome(outcome).expect("the exact fit commits"); + assert_eq!(builder.limiter().block_tx_size_used, system.inner().encode_2718_len() as u64); assert_eq!( - executor.limiter().block_da_size_used, + builder.limiter().block_da_size_used, MegaTransactionExt::estimated_da_size(&system) ); + let (_, built) = builder.finish_with_counters().expect("the block finishes"); + + let mut state = common::state(); + let validator = executor(&mut state, common::unlimited_ctx()); + let validated = validator.execute_block([&system]).expect("policy does not invalidate a block"); + assert_eq!(validated.receipts, built.inner.receipts); + assert_eq!(validated.gas_used, built.inner.gas_used); } -/// The commit-time check reads the same decision: an outcome executed while the budget had room -/// still commits after another commit spent it, where an ordinary transaction's outcome does not. #[test] -fn test_a_delayed_commit_of_a_mega_system_transaction_ignores_the_spent_budget() { - let mut db = common::database(); - db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); - let mut state = State::builder().with_database(db).build(); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(1)), +fn test_a_mega_system_transaction_obeys_the_transaction_gas_policy() { + assert_system_obeys_policy( + BlockLimits::with_tx_gas_limit, + system_tx().gas_limit(), + "Transaction gas limit exceeded", + ); +} + +#[test] +fn test_a_mega_system_transaction_obeys_the_transaction_encoded_size_policy() { + assert_system_obeys_policy( + BlockLimits::with_tx_encode_size_limit, + MegaTransactionExt::tx_size(&system_tx()), + "Transaction encode size limit exceeded", + ); +} + +#[test] +fn test_a_mega_system_transaction_obeys_the_block_encoded_size_policy() { + assert_system_obeys_policy( + BlockLimits::with_block_txs_encode_size_limit, + MegaTransactionExt::tx_size(&system_tx()), + "Block transactions encode size limit exceeded", + ); +} + +#[test] +fn test_a_mega_system_transaction_obeys_the_transaction_da_size_policy() { + assert_system_obeys_policy( + BlockLimits::with_tx_da_size_limit, + MegaTransactionExt::estimated_da_size(&system_tx()), + "Transaction data availability size limit exceeded", + ); +} + +#[test] +fn test_a_mega_system_transaction_obeys_the_block_da_size_policy() { + assert_system_obeys_policy( + BlockLimits::with_block_da_size_limit, + MegaTransactionExt::estimated_da_size(&system_tx()), + "Block data availability size limit exceeded", ); +} + +/// A delayed system outcome and a delayed user outcome both lose their room to another +/// commit. A deposit executed at the same time still commits after the budget is reached. +#[test] +fn test_a_delayed_commit_of_a_mega_system_transaction_is_refused_at_a_spent_budget() { + for (name, policy, refusal) in [ + ( + "data", + BlockLimits::default().with_block_txs_data_limit(1), + "Block transactions data limit reached", + ), + ( + "KV", + BlockLimits::default().with_block_kv_update_limit(1), + "Block KV update limit reached", + ), + ( + "growth", + BlockLimits::default().with_block_state_growth_limit(1), + "Block state growth limit reached", + ), + ] { + let mut db = common::database(); + db.set_account_code(CONTRACT, common::writer()); + db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, common::block_ctx(policy)); + executor.apply_pre_execution_changes().expect("the block starts"); + let gas = empty_call_gas() + + common::slot_state_gas() + + mega_evm::write_record_history_gas(1).expect("the record has a price"); + let first = executor + .run_transaction(&Recovered::new_unchecked( + common::tx(0, CONTRACT, Bytes::new(), gas), + CALLER2, + )) + .expect("room"); + assert!(first.inner.result.is_success()); + let second = executor.run_transaction(&user_tx(0, gas)).expect("room"); + let system = executor.run_transaction(&system_tx()).expect("room"); + let deposit = + executor.run_transaction(&common::deposit_tx(Bytes::new(), gas)).expect("room"); + executor.commit_transaction_outcome(first).expect("the first fills the budget"); + let before = executor.limiter().usage; + let error = executor.commit_transaction_outcome(system).expect_err("the budget is spent"); + assert!(error.to_string().contains(refusal), "{name}: {error}"); + assert_eq!(executor.limiter().usage, before, "{name}"); + assert_eq!(executor.receipts().len(), 1, "{name}"); + executor + .commit_transaction_outcome(second) + .expect_err("an ordinary transaction also needs room"); + executor.commit_transaction_outcome(deposit).expect("a delayed deposit is still exempt"); + assert_eq!(executor.receipts().len(), 2, "{name}"); + } +} + +/// A system write fills or overshoots a budget and is kept; subsequent user and system +/// transactions see the room it used, and are refused without undoing that write. +fn assert_system_fills_budget(policy: BlockLimits, refusal: &str) { + let mut state = common::state(); + let mut executor = executor(&mut state, common::block_ctx(policy)); executor.apply_pre_execution_changes().expect("the block starts"); + let input = + IOracle::setSlotCall { slot: U256::from(7), value: B256::repeat_byte(1) }.abi_encode(); + let gas = 1_000_000 + common::new_account_state_gas() + common::slot_state_gas(); + let system = system_call(input.into(), gas); + let outcome = + executor.run_transaction(&system).expect("a counter below its budget admits the call"); + assert!(outcome.inner.result.is_success()); + let usage = outcome.inner.usage; + assert_eq!(usage.data_size, TX_BODY_SIZE + 68 + WRITE_RECORD_SIZE); + assert_eq!(usage.write_records, 1); + assert_eq!(usage.state_growth, 2, "the system sender and the new Oracle slot"); + executor.commit_transaction_outcome(outcome).expect("the call reaching the budget is included"); + assert_eq!(executor.limiter().usage, usage); + for candidate in [ + user_tx(0, empty_call_gas()), + common::legacy_from( + MEGA_SYSTEM_ADDRESS, + 1, + alloy_primitives::TxKind::Call(ORACLE_CONTRACT_ADDRESS), + U256::ZERO, + system.input().clone(), + gas, + 0, + ), + ] { + let error = + executor.run_transaction(&candidate).expect_err("the committed write used the room"); + assert!(error.to_string().contains(refusal), "{error}"); + assert_eq!(executor.limiter().usage, usage); + assert_eq!(executor.receipts().len(), 1); + } + drop(executor); + assert_eq!( + revm::Database::storage(&mut state, ORACLE_CONTRACT_ADDRESS, U256::from(7)).unwrap(), + U256::from_be_bytes([1; 32]) + ); +} - let first = executor.run_transaction(&user_tx(0, empty_call_gas())).expect("room"); - let second = executor - .run_transaction(&Recovered::new_unchecked( - common::tx(0, CONTRACT, Bytes::new(), empty_call_gas()), - CALLER2, - )) - .expect("room"); - let system = executor.run_transaction(&system_tx()).expect("room"); +#[test] +fn test_a_mega_system_transaction_fills_or_overshoots_the_data_budget() { + for limit in [1, TX_BODY_SIZE + 68 + WRITE_RECORD_SIZE] { + assert_system_fills_budget( + BlockLimits::default().with_block_txs_data_limit(limit), + "Block transactions data limit reached", + ); + } +} + +#[test] +fn test_a_mega_system_transaction_fills_the_kv_budget() { + assert_system_fills_budget( + BlockLimits::default().with_block_kv_update_limit(1), + "Block KV update limit reached", + ); +} - executor.commit_transaction_outcome(first).expect("the first fills the budget"); - executor.commit_transaction_outcome(system).expect("a system transaction does not need room"); - executor.commit_transaction_outcome(second).expect_err("an ordinary transaction does"); +#[test] +fn test_a_mega_system_transaction_fills_or_overshoots_the_state_growth_budget() { + for limit in [1, 2] { + assert_system_fills_budget( + BlockLimits::default().with_block_state_growth_limit(limit), + "Block state growth limit reached", + ); + } +} + +/// A candidate that fits an empty block can lose encoded-size or DA room while waiting to +/// commit. Both a fresh execution and the delayed commit must refuse it on the new counters. +fn assert_system_loses_size_room( + set_limit: fn(BlockLimits, u64) -> BlockLimits, + size: fn(&Recovered) -> u64, + refusal: &str, +) { + let system = system_tx(); + let user = user_tx(0, empty_call_gas()); + let policy = set_limit(BlockLimits::default(), size(&system).max(size(&user))); + let mut state = common::state(); + let mut executor = executor(&mut state, common::block_ctx(policy)); + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = executor.run_transaction(&system).expect("the system call fits by itself"); + executor.execute_transaction(&user).expect("the user's encoding consumes the room"); + let before = executor.limiter().usage; + let error = + executor.commit_transaction_outcome(outcome).expect_err("the encoding no longer fits"); + assert!(error.to_string().contains(refusal), "{error}"); + let error = executor.run_transaction(&system).expect_err("a fresh execution also cannot fit"); + assert!(error.to_string().contains(refusal), "{error}"); + assert_eq!(executor.limiter().usage, before); + assert_eq!(executor.receipts().len(), 1); +} + +#[test] +fn test_a_delayed_system_transaction_obeys_remaining_encoded_size() { + assert_system_loses_size_room( + BlockLimits::with_block_txs_encode_size_limit, + MegaTransactionExt::tx_size, + "Block transactions encode size limit exceeded", + ); +} + +#[test] +fn test_a_delayed_system_transaction_obeys_remaining_da_size() { + assert_system_loses_size_room( + BlockLimits::with_block_da_size_limit, + MegaTransactionExt::estimated_da_size, + "Block data availability size limit exceeded", + ); } /// The header's gas limit still holds a Mega System Transaction. #[test] fn test_a_mega_system_transaction_is_still_refused_by_the_header_gas_limit() { let mut state = common::state(); - let mut executor = executor(&mut state, common::block_ctx(tightest_policy())); + let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); let err = executor @@ -164,7 +387,7 @@ fn test_a_mega_system_transaction_is_still_refused_by_the_da_footprint() { U256::from_be_bytes(word), ); let mut state = State::builder().with_database(db).build(); - let mut executor = executor(&mut state, common::block_ctx(tightest_policy())); + let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); let big = system_call(common::incompressible(100_000), 3_000_000); diff --git a/crates/mega-evm/tests/satin/limit_matrix/block.rs b/crates/mega-evm/tests/satin/limit_matrix/block.rs index 8bbfff4b6..932e99b1c 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/block.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/block.rs @@ -268,11 +268,10 @@ fn test_a_pre_block_call_of_1001_slots_is_not_stopped_and_does_not_move_the_bloc 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. +/// The block is already at 1,000 state growth: both a Mega System Transaction and an ordinary +/// transaction are skipped before execution, leaving the system sender and Oracle unchanged. #[test] -fn test_a_system_transaction_after_1000_slots_is_not_skipped() { +fn test_a_system_transaction_after_1000_slots_is_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)); @@ -285,20 +284,20 @@ fn test_a_system_transaction_after_1000_slots_is_not_skipped() { ], ); 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" - ); + let refusal = results[1].as_ref().expect_err("a system transaction is skipped"); + assert!(refusal.contains("Block state growth limit reached"), "{refusal}"); + assert_eq!(slot(&mut state, ORACLE_CONTRACT_ADDRESS, 1), U256::ZERO); + assert_eq!(slot(&mut state, ORACLE_CONTRACT_ADDRESS, TX_STATE_GROWTH_LIMIT + 1), U256::ZERO); + assert_eq!(state.basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().nonce, 0); 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. +/// so the next ordinary and system transactions are not packed; a deposit is included and +/// still counts. A validator applies no policy and includes all of them. The writes both +/// executions keep agree, and only the validator keeps the system write. 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); @@ -321,14 +320,12 @@ fn test_a_builders_kv_and_state_growth_policy_does_not_bind_a_validator() { 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[0].is_ok() && built[1].is_ok(), "{built:?}"); + assert!(built[2].is_err(), "the policy holds a system transaction too: {:?}", built[2]); 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) - ); - } + assert_eq!(slot(&mut built_state, CONTRACT, 2), slot(&mut validated_state, CONTRACT, 2)); + assert_eq!(slot(&mut built_state, ORACLE_CONTRACT_ADDRESS, 2), U256::ZERO); + assert_eq!(slot(&mut validated_state, ORACLE_CONTRACT_ADDRESS, 2), U256::from(1)); } diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index c507445d9..78f9b96b6 100644 --- a/docs/spec/hardfork-spec.md +++ b/docs/spec/hardfork-spec.md @@ -199,6 +199,6 @@ It restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka) rather - **[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, KV updates and state growth are packing budgets that never refuse a deposit or a Mega System Transaction. +- **Block limits** — data size, KV updates and state growth are packing budgets that exempt only deposits; Mega System Transactions obey those budgets and building policy. _See [Satin Network Upgrade](upgrades/satin.md) for the current state._ diff --git a/docs/spec/upgrades/overview.md b/docs/spec/upgrades/overview.md index 3b05e9229..165245197 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, 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. +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 exempt deposits and hold Mega System Transactions as any other non-deposit 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 cc04c1609..f4947246c 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -26,7 +26,7 @@ Compute is regular gas, bounded by the execution cap and by [gas detention](../e 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, KV and state-growth limits packing budgets that never refuse 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 exempt deposits and hold Mega System Transactions as any other non-deposit 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. @@ -1302,15 +1302,12 @@ The transaction is skipped in any case. 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 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 three packing budgets and from building policy. + The block decides this from the envelope before execution. + A deposit is derived from L1 and must be included even after a packing budget is reached. + Rex6 skipped every later candidate, deposits included, once any of these counters was at or above its limit; Satin exempts deposits. + A Mega System Transaction MUST be held to all three packing budgets and to building policy, and MUST count towards each as any other non-deposit transaction does. + The system transaction that reaches or crosses a budget is included; any later non-deposit transaction MUST be skipped before execution. + A Mega System Transaction is also held to the block gas limit and, its envelope being legacy, to the block's data-availability footprint. - 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. @@ -1322,7 +1319,7 @@ The transaction is skipped in any case. - 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 a policy's cap on a packing budget does not. + Every such policy applies to a Mega System Transaction as to any other non-deposit transaction, including a policy's cap on a packing budget. 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. @@ -1357,12 +1354,12 @@ A transaction MUST be skipped for the current block, and MAY be included in a la - 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, its KV-update limit, or its state-growth limit (see [Block Limits](#20-block-limits)); +- it is not a deposit 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 any of the three packing budgets held below the protocol's value. +A block builder MAY also skip any non-deposit transaction, a Mega System Transaction included, 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. @@ -1547,8 +1544,9 @@ 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, 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. + A block's data-size, KV and state-growth budgets, the builder's policy, the block gas limit and the data-availability footprint all hold it (see [Block Limits](#20-block-limits)). + If the system transaction does not fit, the builder MUST leave it out of this block, together with any reader that needs the values it would persist. + The execution result identifies a Mega System Transaction with `MegaBlockTxResult::is_system_transaction`; `is_deposit` stays the envelope's and alone determines exemption from packing budgets and building policy. - **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, KV or state-growth limit, gas detention's compute limit, or that frame's own budget in data size, KV or state growth. From ddab01680ca8242cf20bd1f6f99a4ad3869affb0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:39:55 +0800 Subject: [PATCH 044/190] test(witness): a short list that runs out of gas part-way loads every authority --- crates/mega-evm/tests/block/witness/stops.rs | 41 ++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs index 0bec7f281..97ac6851a 100644 --- a/crates/mega-evm/tests/block/witness/stops.rs +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -240,3 +240,44 @@ fn test_a_skipped_authorization_list_replays() { case.run(); } + +/// A short authorization list whose transaction runs out of gas before the first frame, part-way +/// through the application of the list: the gas pays the first authority's new account and not +/// the second's. The engine decides the list by simulating it whole, whatever its length, so the +/// witness holds the second authority although the application never reached it. +#[test] +fn test_a_short_list_that_runs_out_of_gas_part_way_loads_every_authority() { + 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 gas = 60_000 + common::body_history(0) + common::new_account_state_gas(); + let case = Case::new("short list out of gas", db).tx(eip7702( + 0, + CONTRACT, + slot(1), + vec![first, second], + gas, + )); + let recorded = case.record(); + let witness = case.channel_witness(&recorded); + assert!( + matches!( + recorded.tx(0).result, + revm::context::result::ExecutionResult::Halt { + reason: op_revm::OpHaltReason::Base( + revm::context::result::HaltReason::OutOfGas(_) + ), + .. + } + ), + "{:?}", + recorded.tx(0).result + ); + 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"); + } + case.run(); +} From 7190344025e46ba3f0af3d216ea45303b1ca2a31 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:40:05 +0800 Subject: [PATCH 045/190] feat(evm): simulate every authorization list before the first frame --- crates/mega-evm/src/evm/execution.rs | 10 +++--- crates/mega-evm/src/limit/limit.rs | 54 ---------------------------- 2 files changed, 4 insertions(+), 60 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 242a50be5..9fb23cb18 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1414,8 +1414,10 @@ fn stop_before_the_first_frame( /// 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. +/// state-growth limits. The stop when they cross one, KV updates first; `None` when they fit. +/// Every list is simulated, whatever its length, so the authorities the witness holds do not +/// depend on whether the list could cross a limit or on where its application would run out of +/// gas. /// /// 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 @@ -1426,10 +1428,6 @@ fn hold_authorization_list( 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)) diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index fb47320e2..e7cee35df 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -436,17 +436,6 @@ impl AdditionalLimit { self.created_caller = true; } - /// 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.is_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. @@ -1191,47 +1180,4 @@ mod tests { limit.begin_transaction(TxClass::Ordinary, crate::TX_BODY_SIZE); limit.count_authorities(2, 0); } - - /// An authorization list may cross exactly when it has more entries than the KV or the - /// state-growth limit leaves the transaction, the limit less what the transaction already - /// counts: a list that fills the room exactly cannot cross, one entry more may. An exempt - /// transaction's list never may, whatever its length. - #[test] - fn test_an_authorization_list_may_cross_only_past_what_both_limits_leave() { - let records = |kv| Counted::records(kv, 0, false); - let growth = |accounts| Counted::NONE.with_growth(accounts, 0); - // (case, KV limit, state-growth limit, counted before the list, entries, may cross) - let cases = [ - ("no entries", 3, 5, Counted::NONE, 0, false), - ("entries fill the KV room", 3, 10, Counted::NONE, 3, false), - ("one entry past the KV room", 3, 10, Counted::NONE, 4, true), - ("entries fill the state-growth room", 10, 3, Counted::NONE, 3, false), - ("one entry past the state-growth room", 10, 3, Counted::NONE, 4, true), - ("entries fill the KV room left after records", 5, 10, records(2), 3, false), - ("one entry past the KV room left after records", 5, 10, records(2), 4, true), - ("entries fill the state-growth room left after growth", 10, 5, growth(2), 3, false), - ("one entry past the state-growth room left after growth", 10, 5, growth(2), 4, true), - ("no KV room", 0, 10, Counted::NONE, 1, true), - ("no state-growth room", 10, 0, Counted::NONE, 1, true), - ("the longest list under no limit", u64::MAX, u64::MAX, Counted::NONE, u64::MAX, false), - ]; - for (case, kv, state_growth, before, entries, may_cross) in cases { - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_kv_update_limit(kv) - .with_tx_state_growth_limit(state_growth); - let mut limit = AdditionalLimit::new(limits); - limit.begin_transaction(TxClass::Ordinary, crate::TX_BODY_SIZE); - limit.count(&before); - assert_eq!(limit.authorization_list_may_cross(entries), may_cross, "{case}"); - } - - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_kv_update_limit(0) - .with_tx_state_growth_limit(0); - let mut limit = AdditionalLimit::new(limits); - limit.begin_transaction(TxClass::ProtocolOwn, crate::TX_BODY_SIZE); - for entries in [1, u64::MAX] { - assert!(!limit.authorization_list_may_cross(entries), "exempt, {entries} entries"); - } - } } From 87585a0cb4713da95e983f56c53a60acaa9b41c7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 16:40:18 +0800 Subject: [PATCH 046/190] docs: every authorization list is simulated; tidy a test doc --- crates/mega-evm/tests/block/limits.rs | 15 +++++++-------- crates/mega-evm/tests/block/witness/stops.rs | 4 +--- docs/spec/upgrades/satin.md | 1 + 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index d3b942e2a..de04ffd4c 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -753,14 +753,13 @@ impl revm::Database for RefusesAnAccount { } } -/// 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. +/// An authorization list is simulated before the first frame, 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 diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs index 97ac6851a..dde476774 100644 --- a/crates/mega-evm/tests/block/witness/stops.rs +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -266,9 +266,7 @@ fn test_a_short_list_that_runs_out_of_gas_part_way_loads_every_authority() { matches!( recorded.tx(0).result, revm::context::result::ExecutionResult::Halt { - reason: op_revm::OpHaltReason::Base( - revm::context::result::HaltReason::OutOfGas(_) - ), + reason: op_revm::OpHaltReason::Base(revm::context::result::HaltReason::OutOfGas(_)), .. } ), diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index cc04c1609..60ae7fbbe 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -787,6 +787,7 @@ A deposit that runs to a success or a revert and creates its caller is the ordin - **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. + It MUST run for every list, whatever its length and whether or not the list could cross a limit, so that every authority whose entry passes the chain id, nonce and signature checks is loaded and a stateless witness holds it even when the transaction runs out of gas before the list is applied. 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. From 8ded5689a8c4dbf640ea8896b01f2027243ffd39 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 17:58:41 +0800 Subject: [PATCH 047/190] test(witness): size the short-list gas from the schedule at the running prices --- crates/mega-evm/tests/block/witness/stops.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs index dde476774..75f6a1984 100644 --- a/crates/mega-evm/tests/block/witness/stops.rs +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -252,7 +252,15 @@ fn test_a_short_list_that_runs_out_of_gas_part_way_loads_every_authority() { assert_ne!(first_authority, second_authority); let mut db = common::database(); db.set_account_code(CONTRACT, slot_writer()); - let gas = 60_000 + common::body_history(0) + common::new_account_state_gas(); + if common::state_is_free() { + // With no price on a new account, the gas that pays the first authority pays the second. + return; + } + // The body's history including the two authorizations, the history of the two authorities' + // write records, and one account's state gas: room for the first authority and not the second. + let gas = 60_000 + + common::body_history(2 * mega_evm::AUTHORIZATION_SIZE + 2 * mega_evm::WRITE_RECORD_SIZE) + + common::new_account_state_gas(); let case = Case::new("short list out of gas", db).tx(eip7702( 0, CONTRACT, From 744b441357f0813c3947d79957fe429d69666b7b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 19:49:37 +0800 Subject: [PATCH 048/190] fix(block): report the L1 block contract's reads where an outcome is committed --- crates/mega-evm/src/block/executor.rs | 169 ++++++--- crates/mega-evm/src/block/l1_block_info.rs | 357 +++++++++++++++--- crates/mega-evm/src/block/result.rs | 17 +- .../mega-evm/tests/block/witness/harness.rs | 255 +++++++++++-- crates/mega-evm/tests/block/witness/state.rs | 173 +++++++++ 5 files changed, 827 insertions(+), 144 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 6d3013844..cb18a0bde 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -8,9 +8,11 @@ //! //! The executor reads the limits every node must agree on from [`ProtocolLimits::for_spec`], for //! the spec the EVM executes, installs their per-transaction half on the EVM before every -//! transaction, and holds the block to their data-size budget. A node passes none of them. The -//! node's context adds only the builder's policy ([`BlockLimits`]), which can tighten the budget -//! and never loosen it; a validator leaves it at its default. +//! transaction, and holds the block to their three packing budgets — data size, KV updates and +//! state growth — which refuse every non-deposit transaction once one is reached, a Mega System +//! Transaction included. A node passes none of them. The node's context adds only the builder's +//! policy ([`BlockLimits`]), which can tighten the budgets and never loosen them, and holds every +//! non-deposit transaction alike; a validator leaves it at its default. //! //! # The block rules of the Karst base //! @@ -70,12 +72,20 @@ //! slots read on the database itself, and this executor reads the DA footprint gas scalar the same //! way before every non-deposit transaction, so neither read lands in a transaction's returned //! state. The executor adds them to it: once each per block, the account and every slot either read -//! reached are read-only entries of the returned state of the first transaction that read them — -//! the L1 fee overhead among them only when the scalars the fee computation found are empty — -//! beside, never in place of, what the transaction's own execution put there. Nothing of the -//! contract is read before the block's transactions, so a block that reads none of it does not +//! reached are read-only entries of the returned state of the first transaction committed that +//! read them — the L1 fee overhead among them only when the scalars the fee computation found are +//! empty — beside, never in place of, what the transaction's own execution put there. Nothing of +//! the contract is read before the block's transactions, so a block that reads none of it does not //! fail when the database cannot serve it. //! +//! Which transaction is first is decided at the commit, by what the committing executor has +//! committed, so it does not depend on which executor executed an outcome or in which order the +//! builder executed its candidates. Every outcome carries its reads of the contract beside its +//! returned state, whatever its executor had reported; its returned state carries what its +//! executor would report if it committed it next, and the commit takes that out and adds what its +//! own report lacks. An outcome committed where it executed, before anything else was committed, +//! is committed as it was returned. +//! //! # The pre-block system calls //! //! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) makes the EIP-2935 @@ -89,14 +99,16 @@ //! 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 //! non-deposit transaction, to decide before the transaction runs whether it is a Mega System -//! Transaction, which the data-size budget and the builder's policy do not refuse. Every -//! transaction, a deposit included, then reads the same slot into its own journal when it is +//! Transaction: one pays no L1 fee, so the fee computation does not price it and it reports the +//! footprint read alone, and a delayed commit checks the system address's account as its sender's. +//! The packing budgets and the builder's policy hold it as any other non-deposit transaction. +//! Every transaction, a deposit included, then reads the same slot into its own journal when it is //! validated. #[cfg(not(feature = "std"))] use alloc as std; use core::fmt; -use std::{boxed::Box, collections::BTreeMap, string::String, vec::Vec}; +use std::{boxed::Box, collections::BTreeMap, string::String, sync::Arc, vec::Vec}; use alloy_consensus::{Eip658Value, Header, Transaction, TransactionEnvelope, TxReceipt}; use alloy_eips::{eip7685::Requests, Encodable2718, Typed2718}; @@ -130,7 +142,9 @@ pub type MegaFinishedBlock = use crate::{ block::{ eips, - l1_block_info::{read_fee_info, read_footprint_gas_scalar, L1BlockRead, L1BlockReport}, + l1_block_info::{ + read_fee_info, read_footprint_gas_scalar, L1BlockRead, L1BlockReads, L1BlockReport, + }, }, estimated_da_size, system::{ @@ -331,6 +345,10 @@ pub struct MegaBlockExecutor { /// What the block's committed transactions reported of the L1 block contract, which their /// fee computation and footprint read outside their journal. l1_block_report: L1BlockReport, + /// What the fee computation read of the L1 block contract in this block, once this executor + /// executed a transaction it prices: what every transaction it prices in the block is priced + /// from. + l1_fee_read: Option>, } /// The two rules a fork's activation puts on a block, decided from the schedule, the block's @@ -411,6 +429,7 @@ where protocol_limits, activation, l1_block_report: L1BlockReport::default(), + l1_fee_read: None, } } @@ -496,57 +515,69 @@ where self.evm.inspector() } - /// The data-availability footprint gas scalar the L1 block contract holds, and, while no - /// committed transaction reported the read, what it found, for the transaction's report. + /// The data-availability footprint gas scalar the L1 block contract holds, and what the read + /// found, for the transaction's report. /// /// Read per transaction, as the fork's rule is stated: the block's own L1 info transaction /// may set it, and the transactions after it are held to the value it set. It is a read of /// the block's state, made between transactions, so it lands in no transaction's returned - /// state: the first transaction that made it reports it + /// state: the first transaction committed that made it reports it /// ([`report_l1_block_reads`](Self::report_l1_block_reads)). A read that fails is an internal /// error, whether or not the database declares it fatal: the block makes it for the /// transaction, outside the transaction's execution. - fn da_footprint_gas_scalar( - &mut self, - ) -> Result<(u64, Option), BlockExecutionError> { - let record = self.l1_block_report.reports_footprint(); - let (scalar, read) = read_footprint_gas_scalar(self.evm.ctx_mut().db_mut(), record) + fn da_footprint_gas_scalar(&mut self) -> Result<(u64, L1BlockRead), BlockExecutionError> { + let (scalar, read) = read_footprint_gas_scalar(self.evm.ctx_mut().db_mut()) .map_err(BlockExecutionError::other)?; Ok((u64::from(scalar), read)) } - /// Adds to `state`, the returned state of the non-deposit transaction `tx_hash`, what the - /// transaction read of the L1 block contract outside its journal that no committed - /// transaction reported yet, as read-only entries: `footprint`, the footprint read made before - /// it ran, and, when the fee computation `priced` it, the fee read, made again here, on the - /// state it ran on, which a state cache serves from op-revm's own fetch. - /// - /// A failed fee read is a failed read of the transaction's execution, as op-revm's fetch - /// inside it is: an internal error when the database declares it fatal, an invalid block when - /// it does not. + /// What the non-deposit transaction `tx_hash` read of the L1 block contract outside its + /// journal, which its outcome carries: `footprint`, the footprint read made before it ran, + /// and, when the fee computation `priced` it, the fee read + /// ([`l1_fee_read`](Self::l1_fee_read)). Adds to `state`, its returned state, what of them + /// no transaction this executor committed reported yet, as read-only entries: what its + /// commit reports when nothing is committed before it, which a commit settles again. fn report_l1_block_reads( &mut self, state: &mut EvmState, - footprint: Option, + footprint: L1BlockRead, priced: bool, tx_hash: TxHash, - ) -> Result<(), BlockExecutionError> { - let fee = if priced && self.l1_block_report.reports_fee() { - let number = self.evm.block().number(); - let spec = self.evm.ctx().spec().into_op_spec(); - let read = - read_fee_info(self.evm.ctx_mut().db_mut(), number, spec).map_err(|error| { - BlockExecutionError::evm( - EVMError::::Database(error), - tx_hash, - ) - })?; - Some(read) - } else { - None - }; - self.l1_block_report.add_to(state, footprint.iter().chain(&fee)); - Ok(()) + ) -> Result { + let fee = if priced { Some(self.l1_fee_read(tx_hash)?) } else { None }; + let mut reads = L1BlockReads::new(footprint, fee); + self.l1_block_report.report(state, &mut reads); + Ok(reads) + } + + /// What the fee computation read of the L1 block contract to price the transaction `tx_hash`. + /// + /// The fee computation reads the contract once per block, at the first transaction it prices, + /// and prices every later one from what it read. So the read is made once, after the first + /// transaction this executor executes that the computation prices ran, on the state it ran on, + /// through op-revm's own fetch, which a state cache serves without a database read once op-revm + /// made its own; every transaction it prices in the block carries that read from then on, so an + /// outcome reports it wherever it is committed, and nothing reads a key the fee computation + /// did not. + /// + /// A failed read is a failed read of the transaction's execution, as op-revm's fetch inside it + /// is: an internal error when the database declares it fatal, an invalid block when it does + /// not. + fn l1_fee_read(&mut self, tx_hash: TxHash) -> Result, BlockExecutionError> { + if let Some(read) = &self.l1_fee_read { + return Ok(Arc::clone(read)); + } + let number = self.evm.block().number(); + let spec = self.evm.ctx().spec().into_op_spec(); + let read = read_fee_info(self.evm.ctx_mut().db_mut(), number, spec).map_err(|error| { + BlockExecutionError::evm( + EVMError::::Database(error), + tx_hash, + ) + })?; + let read = Arc::new(read); + self.l1_fee_read = Some(Arc::clone(&read)); + Ok(read) } /// Commits `state` to the database. @@ -750,10 +781,11 @@ where self.admits_only_deposits()?; // The block starts with empty block-hash and bucket records, so what they hold at the end - // is what this block read, and with nothing of the L1 block contract reported. + // is what this block read, and with nothing of the L1 block contract read or reported. self.evm.clear_accessed_block_hashes(); self.evm.clear_accessed_bucket_ids(); self.l1_block_report = L1BlockReport::default(); + self.l1_fee_read = None; let state = eips::transact_blockhashes_contract_call( &self.spec, @@ -851,6 +883,12 @@ where /// an outcome whose sender's nonce or balance another commit moved since it executed; any /// other state the outcome read is the caller's to keep fresh. /// + /// What the transaction read of the L1 block contract outside its journal is reported here, by + /// what this executor has committed: the state committed is the returned state with the + /// entries its executor's report added taken out and the ones this executor's report lacks + /// added, which is the returned state itself for an outcome executed here and committed + /// before anything else. + /// /// # Panics /// /// In a debug build, when the block no longer has room for `output`, or when its sender's @@ -878,11 +916,24 @@ where is_system_transaction, depositor_nonce, inner, + l1_block_reads, .. } = output; let gas = inner.gas; let cumulative_gas_used = self.limiter.block_gas_used; - let ResultAndState { result, state } = inner.result_and_state; + let ResultAndState { result, mut state } = inner.result_and_state; + + // What the transaction read of the L1 block contract outside its journal is reported by + // what this executor committed, whichever executor executed it and whatever was committed + // since. + let priced = !is_system_transaction; + debug_assert!( + l1_block_reads.are_of(is_deposit, priced), + "the outcome's reads of the L1 block contract are not its transaction's" + ); + if !is_deposit { + self.l1_block_report.commit(&mut state, &l1_block_reads, priced); + } self.receipts.push( match self.receipt_builder.build_receipt(ReceiptBuilderCtx { @@ -914,9 +965,6 @@ where }, ); - if !is_deposit { - self.l1_block_report.committed(&state, !is_system_transaction); - } self.commit(state); GasOutput::with_state_gas(gas.gas_used, gas.state) @@ -994,6 +1042,11 @@ where /// again when another commit moved what it read is the builder's responsibility: a builder /// that executes an Oracle-reading transaction, then executes and commits the system-address /// transaction that writes the Oracle before it, commits both. + /// + /// The outcome may have been executed by another executor of the block, or before another + /// outcome committed here: what it read of the L1 block contract outside its journal, which + /// it carries, is reported by what this executor has committed, once each per block, with the + /// first transaction committed here that read it. pub fn commit_transaction_outcome( &mut self, output: MegaBlockTxResult<::TxType>, @@ -1067,7 +1120,7 @@ where let (scalar, read) = self.da_footprint_gas_scalar()?; let footprint = da_size.saturating_mul(scalar); self.check_da_footprint(footprint)?; - (footprint, read) + (footprint, Some(read)) }; // The sender's account as the transaction executes against it, read before execution: a @@ -1089,14 +1142,15 @@ where // What the transaction read of the L1 block contract outside its journal: the footprint // read, and the fee read of every non-deposit transaction but a Mega System Transaction, // which pays no L1 fee. - if !is_deposit { - self.report_l1_block_reads( + let l1_block_reads = match footprint_read { + Some(footprint) => self.report_l1_block_reads( &mut outcome.result_and_state.state, - footprint_read, + footprint, !is_system_transaction, tx_hash, - )?; - } + )?, + None => L1BlockReads::default(), + }; let result = MegaBlockTxResult { tx_type: inner.tx_type(), @@ -1112,6 +1166,7 @@ where sender_nonce: sender_before.nonce, sender_balance: sender_before.balance, inner: outcome, + l1_block_reads, }; Ok(result) } diff --git a/crates/mega-evm/src/block/l1_block_info.rs b/crates/mega-evm/src/block/l1_block_info.rs index b216a3ea7..f8e8efe45 100644 --- a/crates/mega-evm/src/block/l1_block_info.rs +++ b/crates/mega-evm/src/block/l1_block_info.rs @@ -24,15 +24,30 @@ //! alone reads nothing of the contract, and a slot neither read reaches — the overhead beside set //! scalars — is not read at all. //! +//! Which transaction is the first is the block's order, which the commits make: a builder may +//! execute several candidates before it commits any, or commit an outcome another executor of the +//! block executed. So every outcome carries what it read ([`L1BlockReads`]) beside its returned +//! state, whatever its executor had reported, and the executor that commits it decides, from what +//! it has itself committed ([`L1BlockReport`]), what the committed state reports. The returned +//! state carries the report its executor would make if it committed the outcome next; a commit +//! takes that out again and adds what its own report lacks, so the committed states report each +//! key once, with the first committed transaction that read it. +//! //! What the fee computation read is decided by the block, not by whether this node's op-revm -//! fetched the info for it: the fee read is made again, through op-revm's own fetch, once the -//! transaction ran and before it is committed, on the state it ran on, which a node's state cache -//! serves without a database read once op-revm made its own. A validator that replays the block -//! fetches the info at the same transaction and reads the same keys. +//! fetched the info for it: op-revm fetches it once per block, at the first transaction it prices, +//! and prices every later one from what it fetched, and the fee read is made again, through +//! op-revm's own fetch, once that transaction ran and before it is committed, on the state it ran +//! on, which a node's state cache serves without a database read once op-revm made its own, and +//! carried by every transaction the executor prices in the block. A validator that replays the +//! block fetches the info at its first such transaction and reads the same keys. #[cfg(not(feature = "std"))] use alloc as std; -use std::collections::{BTreeMap, BTreeSet}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, + vec::Vec, +}; use alloy_primitives::{Address, B256, U256}; use op_revm::{ @@ -73,17 +88,17 @@ pub(crate) struct L1BlockRead { slots: BTreeMap, } -/// A database that answers from the one it wraps and, when it records, keeps what it answered -/// about the L1 block contract. +/// A database that answers from the one it wraps and keeps what it answered about the L1 block +/// contract. struct Recording<'a, DB> { db: &'a mut DB, - read: Option, + read: L1BlockRead, } impl<'a, DB> Recording<'a, DB> { - /// Answers from `db`, recording when `record` says so. - fn new(db: &'a mut DB, record: bool) -> Self { - Self { db, read: record.then(L1BlockRead::default) } + /// Answers from `db`. + const fn new(db: &'a mut DB) -> Self { + Self { db, read: L1BlockRead { account: None, slots: BTreeMap::new() } } } } @@ -92,8 +107,8 @@ impl Database for Recording<'_, DB> { fn basic(&mut self, address: Address) -> Result, Self::Error> { let info = self.db.basic(address)?; - if let Some(read) = self.read.as_mut().filter(|_| address == L1_BLOCK_CONTRACT) { - read.account.clone_from(&info); + if address == L1_BLOCK_CONTRACT { + self.read.account.clone_from(&info); } Ok(info) } @@ -104,8 +119,8 @@ impl Database for Recording<'_, DB> { fn storage(&mut self, address: Address, index: U256) -> Result { let value = self.db.storage(address, index)?; - if let Some(read) = self.read.as_mut().filter(|_| address == L1_BLOCK_CONTRACT) { - read.slots.insert(index, value); + if address == L1_BLOCK_CONTRACT { + self.read.slots.insert(index, value); } Ok(value) } @@ -117,16 +132,15 @@ impl Database for Recording<'_, DB> { /// Reads the data-availability footprint gas scalar as block execution reads it before a /// non-deposit transaction runs: the L1 block contract's account, then the scalar's slot, decoded -/// as op-revm decodes it. With `record`, also what the read found, for the transaction's report. +/// as op-revm decodes it; and what the read found, for the transaction's report. /// /// # Errors /// /// The database's, when a read fails. pub(crate) fn read_footprint_gas_scalar( db: &mut DB, - record: bool, -) -> Result<(u16, Option), DB::Error> { - let mut db = Recording::new(db, record); +) -> Result<(u16, L1BlockRead), DB::Error> { + let mut db = Recording::new(db); // Load the account first: a database that has never seen it cannot serve its storage. db.basic(L1_BLOCK_CONTRACT)?; let scalar = L1BlockInfo::fetch_da_footprint_gas_scalar(&mut db)?; @@ -146,11 +160,74 @@ pub(crate) fn read_fee_info( number: U256, spec: OpSpecId, ) -> Result { - let mut db = Recording::new(db, true); + let mut db = Recording::new(db); if db.basic(L1_BLOCK_CONTRACT)?.is_some() { L1BlockInfo::try_fetch(&mut db, number, spec)?; } - Ok(db.read.unwrap_or_default()) + Ok(db.read) +} + +/// What a transaction read of the L1 block contract outside its journal, carried with its outcome +/// until a block executor commits it, and what the report of the executor that executed it added +/// to its returned state. +/// +/// A deposit reads nothing; every other transaction the footprint, made before it ran; and a +/// transaction the fee computation priced the fee read too. Each read is carried whole, whatever +/// its executor had reported, so the executor that commits the outcome can report what it has not. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct L1BlockReads { + /// The footprint read: `Some` for every non-deposit transaction. + footprint: Option, + /// The fee read: `Some` for a transaction the fee computation priced. One read serves every + /// transaction the fee computation prices in the block, so its outcomes share it. + fee: Option>, + /// The entries the report of the executor that executed the transaction added to its returned + /// state. + added: Added, +} + +impl L1BlockReads { + /// The reads of a non-deposit transaction: the `footprint` read, and the `fee` read when the + /// fee computation priced it. + pub(crate) const fn new(footprint: L1BlockRead, fee: Option>) -> Self { + Self { footprint: Some(footprint), fee, added: Added::NONE } + } + + /// Whether these are the reads of a transaction that is a deposit when `is_deposit`, and that + /// the fee computation priced when `priced`: none for a deposit, the footprint read for every + /// other transaction, and the fee read for one the fee computation priced. + pub(crate) const fn are_of(&self, is_deposit: bool, priced: bool) -> bool { + self.footprint.is_some() != is_deposit && self.fee.is_some() == (!is_deposit && priced) + } +} + +/// The entries a report added to a transaction's returned state: the L1 block contract's account, +/// when the state named none, and the slots it added. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Added { + /// Whether the report added the account, and so every slot under it. + account: bool, + /// The slots the report added. + slots: Vec, +} + +impl Added { + /// Nothing added. + const NONE: Self = Self { account: false, slots: Vec::new() }; + + /// Takes these entries out of `state`, which leaves what the transaction's own execution put + /// there. + fn take_out(&self, state: &mut EvmState) { + if self.account { + state.remove(&L1_BLOCK_CONTRACT); + } else if let Some(account) = + state.get_mut(&L1_BLOCK_CONTRACT).filter(|_| !self.slots.is_empty()) + { + for slot in &self.slots { + account.storage.remove(slot); + } + } + } } /// What block execution has reported of the L1 block contract in the states it committed in the @@ -158,7 +235,9 @@ pub(crate) fn read_fee_info( /// /// The footprint read is reported with the first non-deposit transaction committed, and the fee /// read with the first committed transaction the fee computation priced, each without the keys a -/// committed state of a transaction that read the contract named already. +/// committed state of a transaction that read the contract named already. It is the committing +/// executor's: an outcome executed elsewhere, or before another commit, is reported by what the +/// executor that commits it has committed. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct L1BlockReport { /// Whether a committed transaction reported the footprint read. @@ -174,25 +253,57 @@ pub(crate) struct L1BlockReport { impl L1BlockReport { /// Whether the footprint read is still to be reported: no transaction that made it was /// committed yet. - pub(crate) const fn reports_footprint(&self) -> bool { + const fn reports_footprint(&self) -> bool { !self.footprint } /// Whether the fee read is still to be reported: no transaction the fee computation priced was /// committed yet. - pub(crate) const fn reports_fee(&self) -> bool { + const fn reports_fee(&self) -> bool { !self.fee } + /// Adds to `state`, the returned state of the transaction that made `reads`, what this report + /// would add if the transaction were committed next, and keeps on `reads` what it added, which + /// a commit takes out again ([`commit`](Self::commit)). + pub(crate) fn report(&self, state: &mut EvmState, reads: &mut L1BlockReads) { + reads.added = self.add(state, reads); + } + + /// Settles `state`, the returned state of the non-deposit transaction that made `reads`, which + /// this report's executor commits, and records what it reports: it takes out what the report + /// of the executor that executed it added, adds what this report lacks, and marks the reads + /// `state` now reports ([`committed`](Self::committed)), the fee read when the fee computation + /// `priced` the transaction. + /// + /// Committed where it executed and before anything else was committed, the outcome is + /// committed as it was returned: the two reports are one. + pub(crate) fn commit(&mut self, state: &mut EvmState, reads: &L1BlockReads, priced: bool) { + reads.added.take_out(state); + self.add(state, reads); + self.committed(state, priced); + } + + /// Adds to `state` what `reads` found that this report lacks — the footprint read while no + /// committed transaction reported it, the fee read while no committed transaction the fee + /// computation priced did — and answers what it added. + fn add(&self, state: &mut EvmState, reads: &L1BlockReads) -> Added { + let footprint = reads.footprint.as_ref().filter(|_| self.reports_footprint()); + let fee = reads.fee.as_deref().filter(|_| self.reports_fee()); + self.add_to(state, footprint.into_iter().chain(fee)) + } + /// Adds to `state`, a transaction's returned state, what `reads` found that no committed state /// named yet, as read-only entries: the account as found, and each slot found of an account the /// state holds. An entry `state` holds already is left as it is, so the transaction's own load - /// of the contract, or its write to it, stands; a slot to report goes under it. - pub(crate) fn add_to<'a>( + /// of the contract, or its write to it, stands; a slot to report goes under it. Answers what it + /// added. + fn add_to<'a>( &self, state: &mut EvmState, reads: impl IntoIterator, - ) { + ) -> Added { + let mut added = Added::NONE; for read in reads { let fresh: BTreeMap = match read.account { Some(_) => read @@ -206,28 +317,27 @@ impl L1BlockReport { if self.account && fresh.is_empty() { continue; } + added.account |= !state.contains_key(&L1_BLOCK_CONTRACT); let account = state.entry(L1_BLOCK_CONTRACT).or_insert_with(|| match read.account.clone() { Some(info) => Account::from(info), None => Account::new_not_existing(TransactionId::ZERO), }); for (slot, value) in fresh { - account - .storage - .entry(slot) - .or_insert_with(|| EvmStorageSlot::new(value, TransactionId::ZERO)); + if !account.storage.contains_key(&slot) { + account.storage.insert(slot, EvmStorageSlot::new(value, TransactionId::ZERO)); + added.slots.push(slot); + } } } + added } /// Records what the committed `state` of a non-deposit transaction reported: the footprint /// read, which every non-deposit transaction makes, and, when the fee computation `priced` it, - /// the fee read; and the keys of the contract `state` names, which are in the witness from now - /// on. - pub(crate) fn committed(&mut self, state: &EvmState, priced: bool) { - if self.fee || (self.footprint && !priced) { - return; - } + /// the fee read; and the keys of the contract `state` names, its own entries among them, which + /// are in the witness from now on, so no later report names them again. + fn committed(&mut self, state: &EvmState, priced: bool) { self.footprint = true; self.fee |= priced; if let Some(account) = state.get(&L1_BLOCK_CONTRACT) { @@ -326,24 +436,21 @@ mod tests { let read = read_fee_info(&mut db, U256::from(9), spec).expect("no slot is read"); assert_eq!(read, L1BlockRead::default(), "absent, with no slot"); } - let (scalar, footprint) = read_footprint_gas_scalar(&mut MemoryDatabase::default(), true) + let (scalar, footprint) = read_footprint_gas_scalar(&mut MemoryDatabase::default()) .expect("an absent contract holds a zero scalar"); assert_eq!(scalar, 0); let mut state = EvmState::default(); - L1BlockReport::default().add_to(&mut state, footprint.iter()); + L1BlockReport::default().add_to(&mut state, [&footprint]); let account = &state[&L1_BLOCK_CONTRACT]; assert!(account.is_loaded_as_not_existing() && !account.is_touched()); assert!(account.storage.is_empty(), "no slot of an absent account"); } - /// The footprint read decodes the scalar as op-revm does, and records what it read only when - /// asked: the account and the scalar's slot. + /// The footprint read decodes the scalar as op-revm does, and records what it read: the + /// account and the scalar's slot. #[test] - fn test_the_footprint_read_records_only_when_asked() { - let (scalar, read) = read_footprint_gas_scalar(&mut chain(scalars()), false).unwrap(); - assert_eq!((scalar, read), (400, None)); - let (scalar, read) = read_footprint_gas_scalar(&mut chain(scalars()), true).unwrap(); - let read = read.expect("recorded"); + fn test_the_footprint_read_records_the_account_and_the_scalars_slot() { + let (scalar, read) = read_footprint_gas_scalar(&mut chain(scalars())).unwrap(); assert_eq!(scalar, 400); assert!(read.account.is_some()); assert_eq!(read.slots, BTreeMap::from([(OPERATOR_FEE_SCALARS_SLOT, footprint_word())])); @@ -387,18 +494,18 @@ mod tests { #[test] fn test_what_a_committed_state_reported_is_not_reported_again() { let spec = crate::MegaSpecId::SATIN.into_op_spec(); - let (_, footprint) = read_footprint_gas_scalar(&mut chain(scalars()), true).unwrap(); + let (_, footprint) = read_footprint_gas_scalar(&mut chain(scalars())).unwrap(); let fee = read_fee_info(&mut chain(scalars()), U256::from(9), spec).unwrap(); let mut report = L1BlockReport::default(); assert!(report.reports_footprint() && report.reports_fee()); let mut system = EvmState::default(); - report.add_to(&mut system, footprint.iter()); + report.add_to(&mut system, [&footprint]); report.committed(&system, false); assert!(!report.reports_footprint() && report.reports_fee()); let mut priced = EvmState::default(); - report.add_to(&mut priced, footprint.iter().chain([&fee])); + report.add_to(&mut priced, [&footprint, &fee]); let slots: BTreeSet<_> = priced[&L1_BLOCK_CONTRACT].storage.keys().copied().collect(); assert_eq!( slots, @@ -411,4 +518,156 @@ mod tests { report.add_to(&mut later, [&fee]); assert!(later.is_empty(), "nothing is left to report"); } + + /// The reads of a priced transaction on [`chain`]: its footprint read and its fee read. + fn priced_reads() -> L1BlockReads { + let spec = crate::MegaSpecId::SATIN.into_op_spec(); + let (_, footprint) = read_footprint_gas_scalar(&mut chain(scalars())).unwrap(); + let fee = read_fee_info(&mut chain(scalars()), U256::from(9), spec).unwrap(); + L1BlockReads::new(footprint, Some(Arc::new(fee))) + } + + /// A report after a priced transaction's commit: nothing is left to report. + fn reported() -> L1BlockReport { + let mut report = L1BlockReport::default(); + let mut state = EvmState::default(); + report.commit(&mut state, &priced_reads(), true); + assert!(!report.reports_footprint() && !report.reports_fee()); + report + } + + /// A transaction's own entry of the contract: the account touched, and the scalars' slot + /// written from the chain's value to zero. + fn own_entry() -> EvmState { + let mut own = Account::from(chain(scalars()).basic(L1_BLOCK_CONTRACT).unwrap().unwrap()); + own.status = AccountStatus::Touched; + let mut written = EvmStorageSlot::new(scalars(), TransactionId::ZERO); + written.present_value = U256::ZERO; + own.storage.insert(ECOTONE_L1_FEE_SCALARS_SLOT, written); + EvmState::from_iter([(L1_BLOCK_CONTRACT, own)]) + } + + /// A commit by the executor that executed the transaction, with nothing committed in between, + /// leaves the returned state as it was: both reports are one. + #[test] + fn test_a_commit_on_the_report_that_executed_changes_nothing() { + for (report, own) in [ + (L1BlockReport::default(), EvmState::default()), + (L1BlockReport::default(), own_entry()), + (reported(), EvmState::default()), + (reported(), own_entry()), + ] { + let mut reads = priced_reads(); + let mut state = own.clone(); + report.report(&mut state, &mut reads); + let returned = state.clone(); + report.clone().commit(&mut state, &reads, true); + assert_eq!(state, returned); + } + } + + /// An outcome executed on a report that had reported nothing, committed on one that reported + /// everything, loses every entry its executor's report added and keeps its own; one executed on + /// a report that had reported everything, committed on one that reported nothing, gets every + /// read added under its own entry, which it replaces in nothing. + #[test] + fn test_a_commit_takes_out_what_the_executing_report_added_and_adds_what_its_own_lacks() { + for own in [EvmState::default(), own_entry()] { + let mut reads = priced_reads(); + let mut state = own.clone(); + L1BlockReport::default().report(&mut state, &mut reads); + assert_eq!(state[&L1_BLOCK_CONTRACT].storage.len(), 4, "reported where executed"); + reported().commit(&mut state, &reads, true); + assert_eq!(state, own, "nothing reported where committed, the own entry kept"); + + let mut reads = priced_reads(); + let mut state = own.clone(); + reported().report(&mut state, &mut reads); + assert_eq!(state, own, "nothing reported where executed"); + let mut report = L1BlockReport::default(); + report.commit(&mut state, &reads, true); + let mut expected = own.clone(); + L1BlockReport::default().add_to( + &mut expected, + [reads.footprint.as_ref().unwrap(), reads.fee.as_deref().unwrap()], + ); + assert_eq!(state, expected, "reported where committed"); + if !own.is_empty() { + let account = &state[&L1_BLOCK_CONTRACT]; + assert!(account.is_touched(), "the own account stands"); + assert_eq!( + account.storage[&ECOTONE_L1_FEE_SCALARS_SLOT], + own[&L1_BLOCK_CONTRACT].storage[&ECOTONE_L1_FEE_SCALARS_SLOT], + "the own write stands" + ); + } + assert!(!report.reports_footprint() && !report.reports_fee(), "and marked"); + } + } + + /// A deposit reads nothing, every other transaction the footprint, and one the fee + /// computation priced the fee too. + #[test] + fn test_the_reads_are_of_the_transaction_that_made_them() { + let none = L1BlockReads::default(); + let footprint = L1BlockReads::new(L1BlockRead::default(), None); + let priced = priced_reads(); + assert!(none.are_of(true, false) && none.are_of(true, true)); + assert!(!none.are_of(false, false) && !none.are_of(false, true)); + assert!(footprint.are_of(false, false) && !footprint.are_of(false, true)); + assert!(priced.are_of(false, true) && !priced.are_of(false, false)); + assert!(!footprint.are_of(true, false) && !priced.are_of(true, true)); + } + + /// The recording database answers every read as the database it wraps — the code by hash and + /// the block hashes, which no read of the contract asks for, included — and records what it + /// answered about the contract alone. + #[test] + fn test_the_recording_answers_as_the_database_it_wraps() { + let mut db = chain(scalars()); + let mut wrapped = chain(scalars()); + let mut recording = Recording::new(&mut db); + let code_hash = alloy_primitives::keccak256([0x00]); + let code = wrapped.code_by_hash(code_hash).unwrap(); + assert!(!code.is_empty(), "the chain holds the contract's code"); + assert_eq!(recording.code_by_hash(code_hash).unwrap(), code); + let hash = wrapped.block_hash(7).unwrap(); + assert_ne!(hash, B256::ZERO); + assert_eq!(recording.block_hash(7).unwrap(), hash); + let other = Address::with_last_byte(9); + assert_eq!(recording.basic(other).unwrap(), wrapped.basic(other).unwrap()); + assert_eq!(recording.storage(other, U256::from(1)).unwrap(), U256::ZERO); + assert_eq!(recording.read, L1BlockRead::default(), "nothing of the contract was read"); + + let mut db = ErrorInjectingDatabase::new(chain(scalars())); + db.fail_on_code_by_hash = Some(code_hash); + db.fail_on_block_hash = Some(7); + let mut recording = Recording::new(&mut db); + assert!(recording.code_by_hash(code_hash).is_err(), "a failed read stays one"); + assert!(recording.block_hash(7).is_err(), "a failed read stays one"); + } + + /// A committed state's own entries of the contract are in the witness from its commit on, so + /// no later report names them again, whichever read was still to be reported: a Mega System + /// Transaction whose own execution read the L1 base fee leaves the fee read that slot to skip. + #[test] + fn test_a_committed_states_own_entries_are_not_reported_again() { + let reads = priced_reads(); + let mut report = L1BlockReport::default(); + let mut system = EvmState::default(); + report.add_to(&mut system, [reads.footprint.as_ref().unwrap()]); + report.committed(&system, false); + let mut own = system.clone(); + own.get_mut(&L1_BLOCK_CONTRACT) + .unwrap() + .storage + .insert(L1_BASE_FEE_SLOT, EvmStorageSlot::new(U256::from(1_001), TransactionId::ZERO)); + report.committed(&own, false); + assert!(!report.reports_footprint() && report.reports_fee()); + + let mut priced = EvmState::default(); + report.add_to(&mut priced, [reads.fee.as_deref().unwrap()]); + let slots: BTreeSet<_> = priced[&L1_BLOCK_CONTRACT].storage.keys().copied().collect(); + assert_eq!(slots, [ECOTONE_L1_FEE_SCALARS_SLOT, ECOTONE_L1_BLOB_BASE_FEE_SLOT].into()); + } } diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index c8af37f8e..6e4ab6330 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -12,7 +12,10 @@ use alloy_evm::{ use alloy_primitives::{Address, TxHash, U256}; use revm::context::result::{InvalidTransaction, ResultAndState}; -use crate::{BlockUsage, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome}; +use crate::{ + block::l1_block_info::L1BlockReads, BlockUsage, LimitUsage, MegaGasUsage, MegaHaltReason, + MegaTransactionOutcome, +}; /// A block's gas, on the three ledgers its transactions spend on, and the history bytes they /// appended. @@ -251,6 +254,11 @@ impl InvalidTxError for MegaBlockLimitExceededError { /// /// Everything execution itself produced travels as the embedded [`MegaTransactionOutcome`], so a /// dimension added there flows through without being declared again here. +/// +/// It also carries what the transaction read of the L1 block contract outside its journal, which +/// the executor that commits it reports in the committed state, whichever executor executed it. +/// That record is the crate's own, so an outcome is only ever made by a block executor executing +/// its transaction: one cannot be built by hand without the reads its commit must report. #[derive(Clone, Debug)] pub struct MegaBlockTxResult { /// The transaction's type, which is what the receipt builder needs of it. @@ -286,7 +294,14 @@ pub struct MegaBlockTxResult { pub sender_balance: U256, /// The execution result, the post-state and what `MegaETH` counted, as execution produced /// them. + /// + /// The post-state of a non-deposit transaction carries, as read-only entries, what of the L1 + /// block contract its executor would report if it committed it next; the commit settles them + /// against what the committing executor has reported. pub inner: MegaTransactionOutcome, + /// What the transaction read of the L1 block contract outside its journal, for the executor + /// that commits it to report. + pub(crate) l1_block_reads: L1BlockReads, } impl MegaBlockTxResult { diff --git a/crates/mega-evm/tests/block/witness/harness.rs b/crates/mega-evm/tests/block/witness/harness.rs index f368935ac..5559bf8b8 100644 --- a/crates/mega-evm/tests/block/witness/harness.rs +++ b/crates/mega-evm/tests/block/witness/harness.rs @@ -20,7 +20,10 @@ use std::{ use alloy_consensus::{transaction::Recovered, Signed, TxEip7702}; use alloy_eips::eip7702::{Authorization, SignedAuthorization}; -use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; +use alloy_evm::{ + block::{BlockExecutionError, BlockExecutor, GasOutput}, + EvmEnv, EvmFactory, +}; use alloy_op_evm::block::receipt_builder::{OpAlloyReceiptBuilder, OpReceiptBuilder}; use alloy_primitives::{Address, Bytes, Signature, TxKind, B256, U256}; use mega_evm::{ @@ -29,11 +32,11 @@ use mega_evm::{ SharedWitnessRecord, StrictDatabase, StrictEnvFactory, WitnessKeys, WitnessRecord, }, BlockGasCounters, BucketId, ExternalEnvFactory, LimitCheck, LimitUsage, MegaBlockExecutionCtx, - MegaBlockExecutor, MegaEvmFactory, MegaGasUsage, MegaHaltReason, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, OracleRead, ProtocolLimits, SaltEnv, TestExternalEnvs, - MIN_BUCKET_SIZE, + MegaBlockExecutor, MegaBlockTxResult, MegaEvmFactory, MegaGasUsage, MegaHaltReason, + MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, OracleRead, ProtocolLimits, SaltEnv, + TestExternalEnvs, MIN_BUCKET_SIZE, }; -use op_alloy_consensus::TxDeposit; +use op_alloy_consensus::{OpTxType, TxDeposit}; use revm::{ context::result::ExecutionResult, database::{states::bundle_state::BundleRetention, BundleState, CacheState, State}, @@ -76,6 +79,12 @@ pub(crate) struct Case { pub txs: Vec, /// The candidates the builder executes and then does not commit. pub dropped: BTreeSet, + /// The candidates whose outcome the builder holds while it executes the next candidate, and + /// commits once that one executed, before it. + pub held: BTreeSet, + /// The candidates the builder executes on another executor of the same block and commits on + /// this one, each with the transactions that other executor executed and committed first. + pub elsewhere: BTreeMap>, /// The answers the oracle service moves on to while the block is built: `(index, slot, /// value)` has it answer `value` for `slot` once the candidate at `index` was executed. pub service_updates: Vec<(usize, U256, U256)>, @@ -87,6 +96,22 @@ const DROPPED: &str = "executed and dropped by the builder"; /// Why a replay did not run a candidate. const NOT_INCLUDED: &str = "not in the recorded block"; +/// What a held candidate is until the builder commits it. +const HELD: &str = "held by the builder"; + +/// What the builder took from another executor of the block for one candidate: the candidate's +/// outcome there, and what that executor's run asked of the channels — the oracle reads of every +/// transaction it executed, in order, and its exports. +struct Elsewhere { + outcome: Result, + oracle_reads: Vec, + block_hashes: BTreeMap, + bucket_ids: Vec, +} + +/// What executing one candidate produced, before it is committed. +type Outcome = MegaBlockTxResult; + impl Case { /// A block over `db` on the tests' chain, with no building policy and no transactions. pub(crate) fn new(name: &str, db: MemoryDatabase) -> Self { @@ -100,6 +125,8 @@ impl Case { env: common::evm_env(), txs: Vec::new(), dropped: BTreeSet::new(), + held: BTreeSet::new(), + elsewhere: BTreeMap::new(), service_updates: Vec::new(), } } @@ -117,6 +144,22 @@ impl Case { self } + /// Has the builder hold the outcome of the candidate at `index` while it executes the next + /// candidate, and commit it once that one executed, before it: two candidates executed before + /// either is committed. + pub(crate) fn held(mut self, index: usize) -> Self { + self.held.insert(index); + self + } + + /// Has the builder execute the candidate at `index` on another executor of the same block, + /// over the same pre-state and environments, after that executor executed and committed + /// `prior`, which are not in this block, and commit the outcome on this one. + pub(crate) fn executed_elsewhere(mut self, index: usize, prior: Vec) -> Self { + self.elsewhere.insert(index, prior); + self + } + /// Has the oracle service answer `value` for `slot` from the moment the candidate at `index` /// was executed: the service moves on while the builder works, so two executions that read /// one slot may be answered differently. @@ -178,6 +221,12 @@ impl Case { } } }, + &self.held, + |index| { + self.elsewhere + .get(&index) + .map(|prior| self.execute_elsewhere(index, prior, &record)) + }, ); self.envs.clear_oracle_storage(); for (slot, value) in answers { @@ -203,7 +252,8 @@ impl Case { Oracle::Absent => StrictEnvFactory::::without_oracle(witness), }; let factory = RecordingEnvFactory::new(strict.clone(), reads.clone()); - let mut run = self.drive(state, factory, |index| included[index], |_| {}); + let mut run = + self.drive(state, factory, |index| included[index], |_| {}, &BTreeSet::new(), |_| None); run.record = reads.take(); run.oracle_replayed_exactly = strict.oracle().replayed_exactly(); run @@ -296,12 +346,19 @@ impl Case { /// Runs the block on `state` with the environments `factory` makes, executing the candidates /// `include` admits and committing those the builder does not drop; `executed` is told each /// candidate's index once its execution returned, whatever it returned. + /// + /// A candidate in `held` is committed once the next candidate executed, before that one; a + /// candidate `elsewhere` answers for is executed on another executor of the block and its + /// outcome committed here. Every other candidate is committed as soon as it executed, and is + /// committed exactly as its outcome returned it. fn drive( &self, mut state: State, factory: F, include: impl Fn(usize) -> bool, executed: impl Fn(usize), + held: &BTreeSet, + elsewhere: impl Fn(usize) -> Option, ) -> Run where DB: Database + Debug, @@ -324,47 +381,70 @@ impl Case { let pre_block = committed.states(); let mut txs = Vec::new(); let mut executed_oracle_reads = Vec::new(); + let mut other_block_hashes = BTreeMap::new(); + let mut other_bucket_ids = BTreeSet::new(); + let mut from_elsewhere = false; + let mut holding: Option<(usize, Outcome)> = None; for (index, tx) in self.txs.iter().enumerate() { if !include(index) { txs.push(Err(NOT_INCLUDED.into())); continue; } - let outcome = executor.run_transaction(tx); + let (outcome, here) = match elsewhere(index) { + Some(other) => { + from_elsewhere = true; + executed_oracle_reads.extend(other.oracle_reads); + other_block_hashes.extend(other.block_hashes); + other_bucket_ids.extend(other.bucket_ids); + (other.outcome, false) + } + None => { + let outcome = executor.run_transaction(tx).map_err(|error| error.to_string()); + if let Ok(outcome) = &outcome { + executed_oracle_reads.extend(outcome.inner.oracle_reads.iter().copied()); + } + (outcome, true) + } + }; executed(index); + // A held outcome is committed once the candidate after it executed, before it, so the + // candidate after it is not committed as soon as it executed. + let after_another = holding.is_some(); + if let Some((index, outcome)) = holding.take() { + let snapshot = TxSnapshot::of(&outcome); + let commit = executor.commit_transaction_outcome(outcome); + txs[index] = self.committed(index, snapshot, commit, &committed, false); + } let outcome = match outcome { Ok(outcome) => outcome, Err(error) => { - txs.push(Err(error.to_string())); + txs.push(Err(error)); continue; } }; - executed_oracle_reads.extend(outcome.inner.oracle_reads.iter().copied()); if self.dropped.contains(&index) { txs.push(Err(DROPPED.into())); continue; } - let snapshot = TxSnapshot { - tx_hash: outcome.tx_hash, - gas_limit: outcome.gas_limit, - tx_size: outcome.tx_size, - da_size: outcome.da_size, - da_footprint: outcome.da_footprint, - is_deposit: outcome.is_deposit, - depositor_nonce: outcome.depositor_nonce, - result: outcome.inner.result.clone(), - state: outcome.inner.state.clone(), - gas: outcome.inner.gas, - usage: outcome.inner.usage, - limit_exceeded: outcome.inner.limit_exceeded, - oracle_reads: outcome.inner.oracle_reads.clone(), - }; - match executor.commit_transaction_outcome(outcome) { - Ok(_) => txs.push(Ok(snapshot)), - Err(error) => txs.push(Err(error.to_string())), + if held.contains(&index) { + txs.push(Err(HELD.into())); + holding = Some((index, outcome)); + continue; } + let snapshot = TxSnapshot::of(&outcome); + let commit = executor.commit_transaction_outcome(outcome); + let immediately = here && !after_another; + txs.push(self.committed(index, snapshot, commit, &committed, immediately)); + } + if let Some((index, outcome)) = holding.take() { + let snapshot = TxSnapshot::of(&outcome); + let commit = executor.commit_transaction_outcome(outcome); + txs[index] = self.committed(index, snapshot, commit, &committed, false); } - let block_hashes = executor.get_accessed_block_hashes(); - let bucket_ids = executor.get_accessed_bucket_ids(); + let mut block_hashes = executor.get_accessed_block_hashes(); + block_hashes.extend(other_block_hashes); + other_bucket_ids.extend(executor.get_accessed_bucket_ids()); + let bucket_ids = other_bucket_ids.into_iter().collect(); let (evm, result) = executor.finish_with_counters().expect("the block finishes"); drop(evm); state.merge_transitions(BundleRetention::Reverts); @@ -386,12 +466,86 @@ impl Case { cache: state.cache, block_hashes, bucket_ids, + from_elsewhere, keys, executed_oracle_reads, record: WitnessRecord::default(), oracle_replayed_exactly: true, } } + + /// What the block holds of the candidate at `index` once the builder committed it: its + /// `snapshot`, taken before the commit, with the state the block committed for it in place of + /// the one its outcome returned, or why `commit` refused it. + /// + /// An outcome executed here and committed as soon as it executed is committed exactly as it + /// returned: `immediately` asserts so. + fn committed( + &self, + index: usize, + mut snapshot: TxSnapshot, + commit: Result, + committed: &CommittedStates, + immediately: bool, + ) -> Result { + commit.map_err(|error| error.to_string())?; + let state = committed.states().pop().expect("the commit committed a state"); + if immediately { + assert_eq!( + state, snapshot.state, + "{}: transaction {index}, committed as soon as it executed, is committed as it \ + returned", + self.name + ); + } + snapshot.state = state; + Ok(snapshot) + } + + /// Executes the candidate at `index` as the builder does on another executor of the same + /// block: over the case's pre-state and environments, recording into `record` what it reads + /// and asks, once that executor executed and committed `prior`. + fn execute_elsewhere( + &self, + index: usize, + prior: &[Tx], + record: &SharedWitnessRecord, + ) -> Elsewhere { + let mut state = State::builder() + .with_database(RecordingDatabase::new(self.db.clone(), record.clone())) + .with_bundle_update() + .build(); + let factory = RecordingEnvFactory::new(self.envs.clone(), record.clone()); + let evm = MegaEvmFactory::new() + .with_external_env_factory(factory) + .create_evm(&mut state, self.env.clone()); + let mut executor = MegaBlockExecutor::new( + evm, + self.ctx.clone(), + self.spec.clone(), + OpAlloyReceiptBuilder::default(), + ); + if let Some(limits) = self.limits { + executor = executor.with_protocol_limits(limits); + } + executor.apply_pre_execution_changes().expect("the other executor's block starts"); + let mut oracle_reads = Vec::new(); + for tx in prior { + let outcome = executor.run_transaction(tx).expect("the other executor executes it"); + oracle_reads.extend(outcome.inner.oracle_reads.iter().copied()); + executor.commit_transaction_outcome(outcome).expect("and commits it"); + } + let outcome = executor.run_transaction(&self.txs[index]).map_err(|error| error.to_string()); + if let Ok(outcome) = &outcome { + oracle_reads.extend(outcome.inner.oracle_reads.iter().copied()); + } + Elsewhere { + outcome, + oracle_reads, + block_hashes: executor.get_accessed_block_hashes(), + bucket_ids: executor.get_accessed_bucket_ids(), + } + } } /// What one transaction of a run produced. @@ -405,6 +559,7 @@ pub(crate) struct TxSnapshot { pub is_deposit: bool, pub depositor_nonce: Option, pub result: ExecutionResult, + /// The state the block committed for it. pub state: EvmState, pub gas: MegaGasUsage, pub usage: LimitUsage, @@ -413,6 +568,27 @@ pub(crate) struct TxSnapshot { pub oracle_reads: Vec, } +impl TxSnapshot { + /// What `outcome` produced, its returned state included. + fn of(outcome: &Outcome) -> Self { + Self { + tx_hash: outcome.tx_hash, + gas_limit: outcome.gas_limit, + tx_size: outcome.tx_size, + da_size: outcome.da_size, + da_footprint: outcome.da_footprint, + is_deposit: outcome.is_deposit, + depositor_nonce: outcome.depositor_nonce, + result: outcome.inner.result.clone(), + state: outcome.inner.state.clone(), + gas: outcome.inner.gas, + usage: outcome.inner.usage, + limit_exceeded: outcome.inner.limit_exceeded, + oracle_reads: outcome.inner.oracle_reads.clone(), + } + } +} + /// What one run of a block produced, and what it read. #[derive(Clone, Debug)] pub(crate) struct Run { @@ -432,9 +608,13 @@ pub(crate) struct Run { pub bundle: BundleState, /// The state cache after the block: everything loaded and committed. pub cache: CacheState, - /// What the executor exported. + /// What the executor exported, with what the other executors a candidate was taken from + /// exported: the union a node takes. pub block_hashes: BTreeMap, pub bucket_ids: Vec, + /// Whether a candidate's outcome was taken from another executor, so this run's state cache + /// holds nothing of what that candidate's execution loaded. + pub from_elsewhere: bool, /// The keys the committed states name: a node's channel witness, before its values are /// resolved. pub keys: WitnessKeys, @@ -496,9 +676,10 @@ pub(crate) struct Replay { /// A candidate the block did not include was not run by the replay, so the two agree on which /// those are and nothing more is compared for them. The recording's state cache and exports hold /// what every execution loaded and asked about, dropped candidates' included, so they are equal -/// only when the block included every candidate; otherwise the replay's exports must be among -/// the recording's. The oracle reads a transaction recorded are the same reads on both runs, and -/// their answers are the service's, which a replay without a service does not have. +/// only when the block included every candidate and executed each on its own executor; otherwise +/// the replay's exports must be among the recording's. The oracle reads a transaction recorded are +/// the same reads on both runs, and their answers are the service's, which a replay without a +/// service does not have. pub(crate) fn assert_same_run(name: &str, a: &Run, b: &Run) { assert_eq!(a.pre_block, b.pre_block, "{name}: the pre-block states"); assert_eq!(a.txs.len(), b.txs.len(), "{name}: the candidate count"); @@ -531,7 +712,7 @@ pub(crate) fn assert_same_run(name: &str, a: &Run, b: &Run) { assert_eq!(a.gas, b.gas, "{name}: the block's ledgers"); assert_eq!(a.usage, b.usage, "{name}: the block's usage"); assert_eq!(a.bundle, b.bundle, "{name}: the state changes"); - if a.included().iter().all(|included| *included) { + if a.included().iter().all(|included| *included) && !a.from_elsewhere { assert_eq!(a.cache, b.cache, "{name}: the state cache"); assert_eq!(a.block_hashes, b.block_hashes, "{name}: the exported block hashes"); assert_eq!(a.bucket_ids, b.bucket_ids, "{name}: the exported buckets"); @@ -547,9 +728,9 @@ pub(crate) fn assert_same_run(name: &str, a: &Run, b: &Run) { } } -/// Asserts what the run `a` committed, in order, is the block: its pre-block states, then each -/// included transaction's returned state, then the end of the block, whose balance increments -/// name no account on this chain. +/// Asserts what the run `a` committed, in order, is the block: its pre-block states, then one +/// state for each included transaction, the one the run took for it, then the end of the block, +/// whose balance increments name no account on this chain. fn assert_commits_the_block(name: &str, a: &Run) { let mut expected = a.pre_block.clone(); expected.extend(a.included_outcomes().into_iter().map(|tx| tx.state.clone())); diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs index 41eaf4d04..01ebea265 100644 --- a/crates/mega-evm/tests/block/witness/state.rs +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -453,6 +453,105 @@ fn test_a_dropped_first_reader_leaves_the_report_to_the_next() { assert_eq!(times_named(run, None), 1); } +/// A second sender, funded on [`chain_with_free_l1_info`]. +const OTHER: Address = address!("0x4000000000000000000000000000000000000007"); + +/// A chain holding the L1 block contract with `code` and nothing to charge: every slot the fee +/// computation and the footprint read hold zero but the overhead, which the empty scalars have +/// the fee computation read; the slot writer at [`CONTRACT`]; [`CALLER`] and [`OTHER`] funded. +/// +/// A transaction at no gas price pays no fee on it, so an outcome executed on another state of +/// the block — on another executor, or before another commit — credits the fee accounts as +/// that state would: it is not stale for them, and the block it is committed into is the block a +/// validator replays. +fn chain_with_free_l1_info(code: Bytes) -> MemoryDatabase { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + db.set_account_code(L1_BLOCK_CONTRACT, code); + db.set_account_storage(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT, OVERHEAD); + db.set_account_balance(OTHER, U256::from(1_000_000_000_000_000_u64)); + db +} + +/// What the fee computation reads of [`chain_with_free_l1_info`], the footprint scalar's slot +/// among it. +fn free_l1_info() -> [(U256, U256); 5] { + [ + (L1_BASE_FEE_SLOT, U256::ZERO), + (ECOTONE_L1_FEE_SCALARS_SLOT, U256::ZERO), + (L1_OVERHEAD_SLOT, OVERHEAD), + (ECOTONE_L1_BLOB_BASE_FEE_SLOT, U256::ZERO), + (OPERATOR_FEE_SCALARS_SLOT, U256::ZERO), + ] +} + +/// A call from `sender` at `nonce` to `to` carrying `input`, at no gas price. +fn free_call(sender: Address, nonce: u64, to: Address, input: Bytes) -> Tx { + common::legacy_from(sender, nonce, TxKind::Call(to), U256::ZERO, input, write_gas(), 0) +} + +/// Asserts the block `run` committed names the L1 block contract's account and each slot of +/// `read` exactly once, all of it in the state of the transaction at `index`, read only. +fn assert_reported_once_by(run: &Run, index: usize, read: &[(U256, U256)]) { + assert_read_only("the first transaction committed", l1_account(&run.tx(index).state), read); + assert_eq!(times_named(run, None), 1, "the account is named once"); + for (slot, _) in read { + assert_eq!(times_named(run, Some(*slot)), 1, "slot {slot} is named once"); + } +} + +/// A builder that executes on several executors of one block commits on this executor an +/// outcome another executed after it had committed a transaction of its own, which reported the +/// L1 block contract there. This executor has reported nothing: the transaction is the first it +/// commits, so its committed state reports the account and every slot its fee and footprint +/// reads reached, and the block replays from the witness built from what this executor committed. +#[test] +fn test_an_outcome_executed_on_another_executor_is_reported_where_it_is_committed() { + let db = chain_with_free_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("executed on another executor after it reported", db) + .tx(free_call(OTHER, 0, CONTRACT, slot(2))) + .executed_elsewhere(0, vec![free_call(CALLER, 0, CONTRACT, slot(1))]) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_reported_once_by(run, 0, &free_l1_info()); +} + +/// The other way round: an outcome executed on another executor that had reported nothing, so +/// its returned state carries the report there, is committed on this executor after a +/// transaction of its own reported the contract. Its committed state names nothing of the +/// contract, and the block replays. +#[test] +fn test_an_outcome_executed_on_another_executor_reports_nothing_this_one_reported() { + let db = chain_with_free_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("executed on another executor before it reported", db) + .tx(free_call(CALLER, 0, CONTRACT, slot(1))) + .tx(free_call(OTHER, 0, CONTRACT, slot(2))) + .executed_elsewhere(1, Vec::new()) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert!(!run.tx(1).state.contains_key(&L1_BLOCK_CONTRACT), "the second reports nothing"); + assert_reported_once_by(run, 0, &free_l1_info()); +} + +/// Two candidates executed before either is committed both read the L1 block contract while no +/// committed transaction had reported it. The first committed reports it; the second, committed +/// after it, reports nothing again, and the block replays. +#[test] +fn test_two_candidates_executed_before_either_is_committed_report_once() { + let db = chain_with_free_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("two candidates executed before either is committed", db) + .tx(free_call(CALLER, 0, CONTRACT, slot(1))) + .held(0) + .tx(free_call(OTHER, 0, CONTRACT, slot(2))) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert!(!run.tx(1).state.contains_key(&L1_BLOCK_CONTRACT), "the second reports nothing"); + assert_reported_once_by(run, 0, &free_l1_info()); +} + /// A Mega System Transaction pays no L1 fee, so no fee computation prices it, but the block /// reads the footprint scalar before it as before every non-deposit transaction: as the block's /// first reader it reports the account and the scalar's slot alone. The user transaction after @@ -659,6 +758,80 @@ fn test_a_transaction_that_writes_the_l1_block_contract_keeps_its_write() { assert_eq!(account.storage.len(), l1_info().len(), "no overhead: the scalars were set"); } +/// Code at the L1 block contract that sets the Ecotone scalars, which +/// [`chain_with_free_l1_info`] holds empty: a write to a slot the fee computation reads. +fn scalars_setter() -> Bytes { + BytecodeBuilder::default().sstore(ECOTONE_L1_FEE_SCALARS_SLOT, scalars_set()).stop().build() +} + +/// The scalars [`scalars_setter`] writes. +fn scalars_set() -> U256 { + fee_scalars_word(7, 9) +} + +/// A transaction whose own execution writes a slot of the L1 block contract the fee computation +/// reads keeps its write and its account, touched, in whatever order the builder executes and +/// commits it beside another transaction, and on whichever executor it executed: committed before +/// the other, the report adds the slots it does not hold as read-only entries under its own +/// account; committed after it, the other reported every slot, and its state holds its own +/// entries alone. Every ordering's block replays. +#[test] +fn test_a_transaction_that_writes_the_l1_block_contract_keeps_its_write_in_every_ordering() { + let writer = || free_call(CALLER, 0, L1_BLOCK_CONTRACT, Bytes::new()); + let reader = || free_call(OTHER, 0, CONTRACT, slot(2)); + let case = |name: &str, first: Tx, second: Tx| { + Case::new(name, chain_with_free_l1_info(scalars_setter())).tx(first).tx(second) + }; + let orderings = [ + ("writer first", case("writer first", writer(), reader()), 0), + ("reader first", case("reader first", reader(), writer()), 1), + ("writer held", case("writer held", writer(), reader()).held(0), 0), + ("reader held", case("reader held", reader(), writer()).held(0), 1), + ( + "writer elsewhere, after the reader there", + case("writer elsewhere", writer(), reader()).executed_elsewhere(0, vec![reader()]), + 0, + ), + ( + "reader elsewhere, after the writer there", + case("reader elsewhere", reader(), writer()).executed_elsewhere(0, vec![writer()]), + 1, + ), + ]; + for (name, case, at) in orderings { + let run = case.run().recorded; + let reader_at = 1 - at; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success(), "{name}"); + + let own = l1_account(&run.tx(at).state); + assert!(own.is_touched(), "{name}: the writer's own entry"); + let written = &own.storage[&ECOTONE_L1_FEE_SCALARS_SLOT]; + assert_eq!(written.original_value, U256::ZERO, "{name}: written over the empty scalars"); + assert_eq!(written.present_value, scalars_set(), "{name}: the write stands"); + + let reported: Vec<_> = free_l1_info() + .into_iter() + .filter(|(slot, _)| *slot != ECOTONE_L1_FEE_SCALARS_SLOT) + .collect(); + if at < reader_at { + for (slot, value) in &reported { + let entry = own.storage.get(slot).unwrap_or_else(|| panic!("{name}: slot {slot}")); + assert_eq!(entry.present_value, *value, "{name}: slot {slot}"); + assert!(!entry.is_changed(), "{name}: slot {slot} is read only"); + } + assert_eq!(own.storage.len(), free_l1_info().len(), "{name}: the slots named"); + assert!(!run.tx(reader_at).state.contains_key(&L1_BLOCK_CONTRACT), "{name}"); + } else { + assert_eq!(own.storage.len(), 1, "{name}: the writer's own slot alone"); + let first = l1_account(&run.tx(reader_at).state); + assert_read_only(name, first, &free_l1_info()); + } + for (slot, _) in reported { + assert_eq!(times_named(&run, Some(slot)), 1, "{name}: slot {slot} is named once"); + } + } +} + /// The entry's other condition: a chain that does not hold the L1 block contract. A deposit that /// creates the account in the block does not turn its slots into database reads: the slots of an /// account the block created are the block's own, so the transaction priced after the deposit From 69c056315ea8c107571d355b15d92e0cca9862c6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 19:49:37 +0800 Subject: [PATCH 049/190] fix(evm): simulate an authorization list only where a KV-update or state-growth limit holds it --- crates/mega-evm/src/evm/execution.rs | 10 ++- crates/mega-evm/src/limit/limit.rs | 39 ++++++++++++ crates/mega-evm/tests/fuzz/differential.rs | 72 +++++++++++++--------- crates/mega-evm/tests/fuzz/regressions.rs | 38 ++++++++++++ 4 files changed, 128 insertions(+), 31 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 9fb23cb18..af6af0090 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1417,7 +1417,11 @@ fn stop_before_the_first_frame( /// state-growth limits. The stop when they cross one, KV updates first; `None` when they fit. /// Every list is simulated, whatever its length, so the authorities the witness holds do not /// depend on whether the list could cross a limit or on where its application would run out of -/// gas. +/// gas — every list of a transaction held to a KV-update or a state-growth limit, which Satin's +/// own limits always set. Limits that set neither hold the list to nothing, so it is not +/// simulated and loads only what its application loads, as Ethereum's does: the neutral +/// configuration's runner turns every limit off +/// ([`AdditionalLimit::holds_authorization_list`](crate::AdditionalLimit)). /// /// 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 @@ -1425,7 +1429,9 @@ fn stop_before_the_first_frame( fn hold_authorization_list( ctx: &mut MegaContext, ) -> Result, DB::Error> { - if ctx.tx().tx_type() != TransactionType::Eip7702 { + if ctx.tx().tx_type() != TransactionType::Eip7702 || + !ctx.additional_limit.holds_authorization_list() + { return Ok(None); } let (records, created) = simulate_authorization_list(ctx)?; diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index e7cee35df..e7c959013 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -436,6 +436,19 @@ impl AdditionalLimit { self.created_caller = true; } + /// Whether the transaction's authorization list is held to a limit before it is applied: it + /// is when the transaction is held to a KV-update or a state-growth limit, which what the list + /// keeps counts towards ([`hold_authorization_list`](Self::hold_authorization_list)). + /// + /// Satin's own limits set both, so every list is decided before it is applied, whatever its + /// length. Only a configuration that sets neither — the limits a tool turns off, as the + /// execution-spec runner does for its neutral configuration — has nothing to hold the list + /// to, and decides nothing, so it loads nothing beyond what the list's application loads, as + /// Ethereum does. + pub(crate) const fn holds_authorization_list(&self) -> bool { + self.limits.tx_kv_update_limit != u64::MAX || self.limits.tx_state_growth_limit != u64::MAX + } + /// 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. @@ -1180,4 +1193,30 @@ mod tests { limit.begin_transaction(TxClass::Ordinary, crate::TX_BODY_SIZE); limit.count_authorities(2, 0); } + + /// An authorization list is held to a limit before it is applied when the transaction is held + /// to a KV-update or a state-growth limit, and only then: the spec's limits hold it, so does + /// either limit alone, and limits that set neither, the data size and the detention caps aside, + /// do not. + #[test] + fn test_an_authorization_list_is_held_where_a_kv_or_state_growth_limit_is_set() { + let none = EvmTxRuntimeLimits::no_limits(); + let cases = [ + ("the spec's", EvmTxRuntimeLimits::default(), true), + ("KV updates alone", none.with_tx_kv_update_limit(500_000), true), + ("state growth alone", none.with_tx_state_growth_limit(1_000), true), + ("a limit of nothing", none.with_tx_state_growth_limit(0), true), + ("none", none, false), + ( + "data size and detention alone", + none.with_tx_data_size_limit(1_000) + .with_block_env_access_compute_gas_limit(1_000) + .with_oracle_access_compute_gas_limit(1_000), + false, + ), + ]; + for (name, limits, held) in cases { + assert_eq!(AdditionalLimit::new(limits).holds_authorization_list(), held, "{name}"); + } + } } diff --git a/crates/mega-evm/tests/fuzz/differential.rs b/crates/mega-evm/tests/fuzz/differential.rs index 776bef5ff..0b273c7e6 100644 --- a/crates/mega-evm/tests/fuzz/differential.rs +++ b/crates/mega-evm/tests/fuzz/differential.rs @@ -158,6 +158,46 @@ fn run_eth(case: &Case, fork: EthSpecId, block: BlockEnv, tx: TxEnv) -> Result Result<(), proptest::test_runner::TestCaseError> { + for fork in FORKS { + let block = case.block(); + let tx = case.transaction().0; + let (mega, cfg) = run_mega(fork, case, block.clone(), tx.clone()); + let op = run_op(case, fork, cfg, block, tx); + prop_eq!(render(&mega), render(&op), "{fork:?}: MegaEvm and op-revm differ"); + } + Ok(()) +} + +/// Whether `case`, a transaction that is not a deposit, run unpriced under the neutral +/// configuration of each fork, produces on `MegaEvm` what revm's mainnet EVM produces on the fork, +/// but for the three fee vaults op-revm touches; on Amsterdam without the self-destructions its +/// init codes held. +pub(crate) fn matches_ethereum(case: &Case) -> Result<(), proptest::test_runner::TestCaseError> { + let on_amsterdam = case.without_destruction_in_creation(); + for fork in FORKS { + let case = if fork == EthSpecId::AMSTERDAM { &on_amsterdam } else { case }; + let block = BlockEnv { basefee: 0, ..case.block() }; + let mut tx = case.transaction().0; + tx.base.gas_price = 0; + tx.base.gas_priority_fee = tx.base.gas_priority_fee.map(|_| 0); + let (mega, _) = run_mega(fork, case, block.clone(), tx.clone()); + let mega = mega.map(|mut outcome| { + for vault in [BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { + if outcome.state.get(&vault).is_some_and(|account| account.is_empty()) { + outcome.state.remove(&vault); + } + } + outcome + }); + let eth = run_eth(case, fork, block, tx.base); + prop_eq!(render(&mega), render(ð), "{fork:?}: MegaEvm and Ethereum differ"); + } + Ok(()) +} + /// Under the neutral configuration of each fork, `MegaEvm` and op-revm produce byte-identical /// outcomes — the result, its gas, logs and output, and the state — or the same refusal, for /// every transaction but a deposit that creates its caller's account. @@ -177,14 +217,7 @@ fn test_differential_neutral_mega_evm_matches_op_revm() { return Ok(()); } compared.fetch_add(1, Ordering::Relaxed); - for fork in FORKS { - let block = case.block(); - let tx = case.transaction().0; - let (mega, cfg) = run_mega(fork, case, block.clone(), tx.clone()); - let op = run_op(case, fork, cfg, block, tx); - prop_eq!(render(&mega), render(&op), "{fork:?}: MegaEvm and op-revm differ"); - } - Ok(()) + matches_op_revm(case) }, ); let compared = compared.load(Ordering::Relaxed); @@ -211,30 +244,11 @@ fn test_differential_neutral_mega_evm_matches_ethereum() { if case.tx.is_deposit() { return Ok(()); } - let on_amsterdam = case.without_destruction_in_creation(); compared.fetch_add(1, Ordering::Relaxed); - if on_amsterdam != *case { + if case.without_destruction_in_creation() != *case { rewritten.fetch_add(1, Ordering::Relaxed); } - for fork in FORKS { - let case = if fork == EthSpecId::AMSTERDAM { &on_amsterdam } else { case }; - let block = BlockEnv { basefee: 0, ..case.block() }; - let mut tx = case.transaction().0; - tx.base.gas_price = 0; - tx.base.gas_priority_fee = tx.base.gas_priority_fee.map(|_| 0); - let (mega, _) = run_mega(fork, case, block.clone(), tx.clone()); - let mega = mega.map(|mut outcome| { - for vault in [BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { - if outcome.state.get(&vault).is_some_and(|account| account.is_empty()) { - outcome.state.remove(&vault); - } - } - outcome - }); - let eth = run_eth(case, fork, block, tx.base); - prop_eq!(render(&mega), render(ð), "{fork:?}: MegaEvm and Ethereum differ"); - } - Ok(()) + matches_ethereum(case) }, ); let compared = compared.load(Ordering::Relaxed); diff --git a/crates/mega-evm/tests/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 9befbe4da..c7c22e0ab 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -344,3 +344,41 @@ fn test_a_program_that_funds_the_account_it_then_creates_keeps_one_record_for_it ); } } + +/// An EIP-7702 transaction that runs out of gas part-way through its authorization list, under +/// the neutral configuration, loads what Ethereum and op-revm load: the list is held to no limit +/// there, so it is not simulated, and the second authority, which the application never reached, +/// is not in the state. Found by the neutral differential, where the simulation had loaded that +/// authority as a cold, untouched account. +#[test] +fn test_a_neutral_authorization_list_that_runs_out_of_gas_loads_what_ethereum_loads() { + let mut world = plain_world(); + world.caller.balance = Balance::Zero; + world.beneficiary = BeneficiaryIs::Fresh; + world.empty_leaves = EmptyLeaves { fresh: true, beneficiary: true, created: true }; + let auth = |authority| Auth { + authority, + nonce_ok: true, + chain_ok: true, + recovers: true, + delegate: Delegate::Contract, + }; + let case = Case { + world, + tx: Tx { + shape: Shape::Eip7702 { + to: Who::Caller, + auths: vec![auth(Who::Fresh), auth(Who::Contract)], + }, + value: Value::Zero, + gas: GasTier::Tiny, + price: Price::Free, + nonce_ok: true, + }, + main: stop(), + a: stop(), + b: stop(), + }; + crate::differential::matches_ethereum(&case).unwrap_or_else(|error| panic!("{error}")); + crate::differential::matches_op_revm(&case).unwrap_or_else(|error| panic!("{error}")); +} From 3a284d84d3af9a8b1ce365d8a772e2b7704cae24 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 19:49:37 +0800 Subject: [PATCH 050/190] test(evm): pin where an EXTCODECOPY is refused and where it is not --- .../mega-evm/tests/satin/volatile_access.rs | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 2532aafb3..3f462e1bd 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -585,7 +585,7 @@ fn refused(access: VolatileDataAccess) -> (InstructionResult, Bytes) { /// The refusal follows what the Host loads, whichever way the call reaches it: the beneficiary /// behind an EIP-7702 delegation, the beneficiary with a delegation of its own, and the /// beneficiary's own frame destroying itself are refused; a call that loads no volatile data -/// proceeds. +/// proceeds, and so does an `EXTCODECOPY` of another account with every operand on the stack. #[test] fn test_a_refusal_follows_what_the_host_loads() { let beneficiary = refused(VolatileDataAccess::BENEFICIARY_BALANCE); @@ -605,6 +605,19 @@ fn test_a_refusal_follows_what_the_host_loads() { .account_code(OTHER, BytecodeBuilder::default().stop().build()) .account_code(CHILD, call(BytecodeBuilder::default(), CALL, OTHER).stop().build()); assert_eq!(refused_child(db), (InstructionResult::Stop, Bytes::new()), "no volatile load"); + + // A copy of another account's code, its four operands on the stack. + let copy = BytecodeBuilder::default() + .push_number(1_u8) + .append_many([PUSH0, PUSH0]) + .push_address(OTHER) + .append(EXTCODECOPY) + .stop() + .build(); + let db = MemoryDatabase::default() + .account_code(OTHER, BytecodeBuilder::default().stop().build()) + .account_code(CHILD, copy); + assert_eq!(refused_child(db), (InstructionResult::Stop, Bytes::new()), "EXTCODECOPY"); } /// The beneficiary's own frame destroying itself reads and clears the beneficiary's balance: @@ -630,8 +643,8 @@ fn test_the_beneficiary_destroying_itself_is_refused() { } /// An opcode that fails before it loads anything keeps its own failure: a `SELFDESTRUCT` in the -/// beneficiary's own frame or a `CALL` to the beneficiary short of operands halts with a stack -/// underflow, not a refusal. +/// beneficiary's own frame, a `CALL` to the beneficiary or an `EXTCODECOPY` of it short of +/// operands halts with a stack underflow, not a refusal. #[test] fn test_a_stack_underflow_is_not_a_refusal() { let db = MemoryDatabase::default() @@ -651,6 +664,11 @@ fn test_a_stack_underflow_is_not_a_refusal() { .build(); let db = MemoryDatabase::default().account_code(CHILD, partial_call); assert_eq!(refused_child(db).0, InstructionResult::StackUnderflow, "CALL"); + + let partial_copy = + BytecodeBuilder::default().push_address(BENEFICIARY).append(EXTCODECOPY).build(); + let db = MemoryDatabase::default().account_code(CHILD, partial_copy); + assert_eq!(refused_child(db).0, InstructionResult::StackUnderflow, "EXTCODECOPY"); } /// A database failure on an account an opcode loads surfaces as an error of the transaction, with From d1c4eb3a4a8b34f4fb76556676ef05cf9a1ea447 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 19:49:37 +0800 Subject: [PATCH 051/190] test(evme): drive the released Rex6 executor with a Mega System Transaction past a reached budget --- bin/mega-evme/tests/legacy_line.rs | 88 ++++++++++++++++++++++++++---- 1 file changed, 77 insertions(+), 11 deletions(-) diff --git a/bin/mega-evme/tests/legacy_line.rs b/bin/mega-evme/tests/legacy_line.rs index 0499b3eb5..a14eb17f2 100644 --- a/bin/mega-evme/tests/legacy_line.rs +++ b/bin/mega-evme/tests/legacy_line.rs @@ -180,24 +180,93 @@ fn test_the_lockfile_parser_reads_packages() { assert_eq!(compatibility_line("2.0.0-alpha.1"), "2"); } -/// The released Rex6 engine applies block admission to a system call's legacy envelope. -/// Its exemption from per-transaction resource metering does not exempt block packing. +/// The released Rex6 block executor holds a Mega System Transaction to block admission as it +/// holds any legacy envelope: run in a block whose data-size, KV-update or state-growth budget is +/// reached, or whose building policy the envelope exceeds, it is refused before it runs, with the +/// error the reached limit names; in a block whose limits it fits, the same transaction is +/// executed. Its exemption from per-transaction resource metering does not exempt it from block +/// packing. #[cfg(feature = "legacy")] #[test] fn test_rex6_system_transaction_block_admission_is_unchanged() { use mega_evm_legacy::{ - alloy_primitives::{TxKind, B256}, - check_if_mega_system_transaction, BlockLimiter, BlockLimits, MegaHardfork, - MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + alloy_consensus::{transaction::Recovered, Signed, TxLegacy}, + alloy_evm::{block::BlockExecutor, EvmEnv}, + alloy_op_evm::block::OpAlloyReceiptBuilder, + alloy_primitives::{address, Bytes, Signature, TxKind, B256, U256}, + check_if_mega_system_transaction, + revm::{ + context::{BlockEnv, CfgEnv}, + database::State, + }, + test_utils::MemoryDatabase, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, MegaHardfork, + MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, SequencerRegistryConfig, + SequencerRegistryRex6Config, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, }; + const CHAIN_ID: u64 = 4326; + const BLOCK_GAS_LIMIT: u64 = 1_000_000_000; + assert!(check_if_mega_system_transaction( MEGA_SYSTEM_ADDRESS, 0, TxKind::Call(ORACLE_CONTRACT_ADDRESS), MEGA_SYSTEM_ADDRESS, )); - let limits = BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::Rex6, 1_000_000_000); + let system_tx = Recovered::new_unchecked( + MegaTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(CHAIN_ID), + nonce: 0, + gas_price: 0, + gas_limit: 100_000, + to: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + value: U256::ZERO, + input: Bytes::new(), + }, + Signature::test_signature(), + B256::with_last_byte(1), + )), + MEGA_SYSTEM_ADDRESS, + ); + // A Rex6 block, the system transaction its only transaction, under `limits`. + let run = |limits: BlockLimits| { + let chain = MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(SequencerRegistryConfig { + rex5_initial_sequencer: address!("0x4000000000000000000000000000000000000004"), + rex5_initial_admin: address!("0x5000000000000000000000000000000000000005"), + }) + .with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 100 }); + let factory = MegaBlockExecutorFactory::new( + chain, + MegaEvmFactory::new() + .with_external_env_factory(TestExternalEnvs::::new()), + OpAlloyReceiptBuilder::default(), + ); + let mut cfg = CfgEnv::default(); + cfg.spec = MegaSpecId::REX6; + cfg.chain_id = CHAIN_ID; + let block = BlockEnv { + number: U256::from(1_000), + timestamp: U256::from(1_800_000_000), + gas_limit: BLOCK_GAS_LIMIT, + basefee: 0, + ..Default::default() + }; + let mut db = MemoryDatabase::default(); + let mut state = State::builder().with_database(&mut db).build(); + let ctx = MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), limits); + let mut executor = factory.create_executor(&mut state, ctx, EvmEnv::new(cfg, block)); + executor.apply_pre_execution_changes().expect("the Rex6 block starts"); + executor.run_transaction(system_tx.as_recovered_ref()).map(drop).map_err(|e| e.to_string()) + }; + + let limits = + BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::Rex6, BLOCK_GAS_LIMIT); + run(limits).expect("within the block's limits the system transaction is executed"); for (name, limits, refusal) in [ ("data", limits.with_block_txs_data_limit(0), "Block transactions data limit reached"), ("KV", limits.with_block_kv_update_limit(0), "Block KV update limit reached"), @@ -224,10 +293,7 @@ fn test_rex6_system_transaction_block_admission_is_unchanged() { "Block data availability size limit exceeded", ), ] { - let limiter = BlockLimiter::new(limits); - let error = limiter - .pre_execution_check(B256::ZERO, 100_000, 100, 100, false) - .expect_err("the legacy envelope is held to block admission"); - assert!(error.to_string().contains(refusal), "{name}: {error}"); + let error = run(limits).expect_err("the legacy envelope is held to block admission"); + assert!(error.contains(refusal), "{name}: {error}"); } } From 2ec32b7193d29dff80d16ba83a0da7fa55d9b846 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 19:49:37 +0800 Subject: [PATCH 052/190] docs: bring the L1 report, MST packing, Oracle, ModExp and authorization-list statements in line --- .claude/skills/satin-review/SKILL.md | 11 ++++++----- AGENTS.md | 6 ++++-- crates/mega-evm/README.md | 7 ++++--- docs/spec/upgrades/satin.md | 9 +++++---- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 30bad8214..d34d1c0f4 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -263,7 +263,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - `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. + - Every EIP-7702 list, whatever its length, is simulated whole before the first frame, in list order, writing and warming nothing, whenever the transaction is held to a KV-update or state-growth limit, which Satin's own limits always set; limits that set neither (`no_limits()`, the neutral configuration's runner) skip the simulation, so equivalence mode loads what Ethereum loads; one that would cross the KV-update or state-growth limit is skipped whole, and the transaction's own frame is stopped before it runs (`hold_authorization_list` in `src/evm/execution.rs`); every authority the simulation loaded stays in the transaction's state, with its code, whether or not the list is applied. - 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). @@ -313,9 +313,10 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - The activation-block rules are derived by the executor (`admits_only_deposits`, `is_satin_activation_block`) from the schedule, the block's timestamp and `MegaBlockExecutionCtx::parent_timestamp`; an absent parent timestamp applies neither. - 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. - 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. + - A deposit is never refused by the packing budgets or building policy and counts towards them; an MST, a legacy envelope, is held to them as any other non-deposit transaction, at admission and at a delayed commit, and counts towards them too; both are held to the header gas limit (`BlockLimiter::pre_execution_check`), and an MST 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. + - 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; nothing of the L1 block contract is read before the block's transactions. + - The L1 block contract's account and the slots the fee computation and the footprint read reach are reported once each per block, as read-only entries of the first committed transaction that read them, never in place of that transaction's own entries, whichever executor produced the outcome and in whatever order the builder executed its candidates (`l1_block_info.rs`). - 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. @@ -440,7 +441,7 @@ The deliberate exceptions: | 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. | | Changed after #407 merged: 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 when revm built its frame or answered it with a success; a call revm answered with a failure — a precompile that fails after the value moved — kept nothing and halts as revm has it, burning its forward, and a precompile gas detention answers from its price is the compute stop, whatever its records would have crossed. | A limit is enforced at the writes it guards, which are what the journal kept: a success kept the start's writes, so it gives way to the stop; a failure's writes revm took back, and a precompile answered from its price moved nothing, so neither has a write to hold. | | 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. | +| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (nothing paid, not even the opcode's static gas; 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: @@ -472,7 +473,7 @@ Each is a decision with its reason; "in this pull request" means review the code - **`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. +- **An MST is held to the packing budgets and builder policy as any other non-deposit transaction**: only a deposit, which L1 derivation requires, is exempt; a block full on a budget refuses an MST as it refuses any later legacy transaction. - **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. - **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. diff --git a/AGENTS.md b/AGENTS.md index 6192d1777..2d256bfef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,7 +141,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, and refusing an absent parent timestamp where the schedule activates a fork after genesis that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `MegaTransactionExt` (`helpers.rs`); the reads of the L1 block contract the fee computation and the footprint make outside every transaction's journal, reported once each per block as read-only entries of the returned state of the first committed transaction that made them, never in place of that transaction's own entries, so a witness built from the committed states holds what op-revm and the executor read on the database itself, and a block that reads none of the contract reads nothing of it (`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`) | +| `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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, and refusing an absent parent timestamp where the schedule activates a fork after genesis that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `MegaTransactionExt` (`helpers.rs`); the reads of the L1 block contract the fee computation and the footprint make outside every transaction's journal, reported once each per block as read-only entries of the returned state of the first committed transaction that made them, never in place of that transaction's own entries, so a witness built from the committed states holds what op-revm and the executor read on the database itself, and a block that reads none of the contract reads nothing of it; every outcome carries its reads beside its returned state (`L1BlockReads`), and the executor that commits it settles what the committed state reports against what that executor has committed (`L1BlockReport::commit`), whichever executor executed it (`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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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`) | @@ -276,7 +276,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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`). `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), and applies a role change the `SequencerRegistry` has due in the block (see the system calls below); it reads nothing of the L1 block contract. - op-revm's fee computation and the executor's footprint read read the L1 block contract on the block's state rather than through a transaction's journal, so their reads land in no transaction's state; the executor adds them, once each per block, to the returned state of the first transaction that made them, as read-only entries that never replace the transaction's own (`l1_block_info.rs`): the footprint read — the account and slot 8 — with the first non-deposit transaction, a Mega System Transaction included, and the fee read — the account and slots 1, 3, 7 and 8, and the overhead (5) only when the Ecotone scalars it finds are empty, which a deposit earlier in the block decides — with the first transaction the fee computation prices, read again through op-revm's own fetch once the transaction ran, on the state it ran on, whether or not this node's op-revm fetched it (`tests/block/witness/state.rs`). + op-revm's fee computation and the executor's footprint read read the L1 block contract on the block's state rather than through a transaction's journal, so their reads land in no transaction's state; the executor adds them, once each per block, to the returned state of the first transaction that made them, as read-only entries that never replace the transaction's own (`l1_block_info.rs`): the footprint read — the account and slot 8 — with the first non-deposit transaction, a Mega System Transaction included, and the fee read — the account and slots 1, 3, 7 and 8, and the overhead (5) only when the Ecotone scalars it finds are empty, which a deposit earlier in the block decides — with the first transaction the fee computation prices, read again through op-revm's own fetch once the first transaction the executor prices in the block ran, on the state it ran on, whether or not this node's op-revm fetched it, and carried by every transaction it prices in the block, as op-revm prices them all from one fetch. + Which transaction is first is decided at the commit: an outcome carries its reads beside its returned state, which holds what its executor would report if it committed it next, and the commit takes that out and adds what the committing executor has not reported, so an outcome another executor executed, or one executed before another commit, reports each key once, with the first transaction committed; an outcome committed where it executed, before anything else was committed, is committed as it was returned (`tests/block/witness/state.rs`). A failed fee read is a failed read of the transaction's execution, routed by whether the database declares it fatal; a failed footprint read is always an internal error. 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. @@ -623,6 +624,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te - 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. + With neither a KV-update nor a state-growth limit set, nothing holds an EIP-7702 list before it is applied, so the list is not simulated and loads only what its application loads, as Ethereum's does (`AdditionalLimit::holds_authorization_list`); Satin's own limits set both, so every list is simulated there, whatever its length. 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. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 33f69b70c..dcb59b266 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -60,9 +60,10 @@ The execution figure a block counts for a transaction is its regular ledger — The block's packing budgets and building policy never refuse a deposit, which the block must include. They hold a Mega System Transaction as any other non-deposit transaction, and both classes count towards the budgets. 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 executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`) — 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`). -A database that cannot serve one of those L1 reads fails the block before its first transaction, as an internal error, whatever the block holds. +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, in the block in which Satin activates — which the executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`) — 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, and applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call; it reads nothing of the L1 block contract. +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; 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`). +op-revm's fee computation and the executor's footprint read read the L1 block contract on the block's state rather than through a transaction, so the executor reports what they read — the contract's account and every slot either read reaches — once each per block, as read-only entries of the state of the first committed transaction that read them, never in place of that transaction's own entries, whichever executor produced the outcome and in whatever order the builder executed its candidates. +A block that reads none of the contract, such as a block of deposits alone, does not fail on a database that cannot serve it. 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. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 046f60260..1f98384e0 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -85,7 +85,7 @@ The changes, in the order this page records them: - Each non-deposit transaction's data-availability footprint — its compressed size times the footprint gas scalar held by the L1 block contract — MUST accumulate against the block's gas limit, and the block MUST report the sum as its blob gas used. A transaction whose footprint does not fit in what the block has left MUST NOT be included. With no scalar in state the scalar is zero, and the rule costs nothing. - - Every non-deposit transaction MUST be priced against the L1 block information that the block's own L1 attributes deposit wrote. + - Every non-deposit transaction that pays an L1 fee — every non-deposit transaction but a Mega System Transaction, which pays no fee — MUST be priced against the L1 block information that the block's own L1 attributes deposit wrote. The information MUST be what the contract holds on the state the transactions before the block's first non-deposit transaction other than a Mega System Transaction left, and MUST hold for every later transaction of the block; the footprint gas scalar MUST be read from the contract again for each non-deposit transaction, a Mega System Transaction included. - Satin starts from the L1 block contract Rex6 left: OP's L1Block 1.6.0 (Isthmus), whose data-availability footprint gas scalar and operator fee scalars are zero. So at Satin's activation the Karst data-availability footprint limit costs nothing and the Jovian operator fee is zero; both take effect only once the L1 block contract is upgraded and the scalars are set, which Satin itself does not do. @@ -984,8 +984,8 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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. The value has not moved when the price is consulted, so the call MUST be held to the price alone: the crossing is the stop, kind 2, whatever records its value transfer would have made (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. + Every precompile of the Satin set has a price for every input: an input over an Optimism pairing or MSM size limit is priced at zero, since it is refused before any gas check, and a ModExp input is priced by its Osaka formula whatever its lengths, one over EIP-7823's bound included, since ModExp charges that price before it checks the bound. + An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check — a ModExp input over EIP-7823's bound among them — is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. - **Interceptor answers.** A system contract's intercepted answer that spent more regular gas than the frame's allowance, state and history gas that spilled onto its regular gas not counted, MUST be the crossing. @@ -1445,7 +1445,7 @@ The witness is defined by what the block's execution returns and exports, and a A failed read is reported as [Transaction and Block Refusals](#21-transaction-and-block-refusals) classifies it: the fee computation's as a read of the transaction's own execution, the footprint scalar's as a read block execution makes for the transaction outside its execution, always an internal error. The reads change nothing: the entries are not written. - **The reads a validator makes again.** - A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, a `BLOCKHASH` of the current block or outside the last 256 blocks, an oracle read the frame cannot pay, a read a frame whose volatile-data access is off is refused, a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. + A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, other than an Oracle read, which is made before its cold access is charged (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), a `BLOCKHASH` of the current block or outside the last 256 blocks, a read a frame whose volatile-data access is off is refused, a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. - **The SALT buckets.** Block execution exports the set of SALT buckets the SALT environment answered with a valid capacity during the block, emptied when the block starts and accumulated over everything executed for the block. A bucket is in the set once it was answered with a valid capacity, whether or not the transaction that asked is in the block: a candidate the builder executed and dropped leaves its buckets in the set, which a validator does not need. @@ -1554,6 +1554,7 @@ A node, a stateless validator and a replay tool must agree on everything below, - **The L1 block information.** Block execution reads the L1 block contract at the block's first non-deposit transaction other than a Mega System Transaction, after the block's L1 attributes deposit wrote it, unless the node handed it the information for this block beforehand, which it then prices with, the footprint gas scalar aside; a node that hands it over must hand over what that deposit writes, so that the block's transactions are priced as [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka) requires. What it reports of the contract with the first transaction that read it is what a node that handed nothing over reads, whether or not this node handed the information over, since a validator re-executing the block reads it (see [The Stateless Witness](#22-the-stateless-witness)). + The first transaction is the first the block commits, whichever executor executed it and in whatever order the builder executed its candidates: an outcome carries what it read of the contract beside its returned state, and the executor that commits it reports what that executor has not reported yet, and nothing it has. - **The witness.** 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. From ab422247f9130da7f2a120fa72cc72773a66d3e6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 19:54:40 +0800 Subject: [PATCH 053/190] refactor(block): add a report's entries through the entry API --- crates/mega-evm/src/block/l1_block_info.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/block/l1_block_info.rs b/crates/mega-evm/src/block/l1_block_info.rs index f8e8efe45..eb8165d30 100644 --- a/crates/mega-evm/src/block/l1_block_info.rs +++ b/crates/mega-evm/src/block/l1_block_info.rs @@ -317,15 +317,20 @@ impl L1BlockReport { if self.account && fresh.is_empty() { continue; } - added.account |= !state.contains_key(&L1_BLOCK_CONTRACT); - let account = - state.entry(L1_BLOCK_CONTRACT).or_insert_with(|| match read.account.clone() { + let account = state.entry(L1_BLOCK_CONTRACT).or_insert_with(|| { + added.account = true; + match read.account.clone() { Some(info) => Account::from(info), None => Account::new_not_existing(TransactionId::ZERO), - }); + } + }); for (slot, value) in fresh { - if !account.storage.contains_key(&slot) { - account.storage.insert(slot, EvmStorageSlot::new(value, TransactionId::ZERO)); + let mut inserted = false; + account.storage.entry(slot).or_insert_with(|| { + inserted = true; + EvmStorageSlot::new(value, TransactionId::ZERO) + }); + if inserted { added.slots.push(slot); } } From 653d655ffd9094ac5eb3b886ce0fc2a04cdd1900 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 23:42:04 +0800 Subject: [PATCH 054/190] test(evm): cover oracle reads and witness failures --- crates/mega-evm/tests/block/activation.rs | 9 +++ crates/mega-evm/tests/block/witness/state.rs | 44 +++++++++-- .../mega-evm/tests/system/oracle_storage.rs | 77 ++++++++++++++++++- 3 files changed, 122 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs index 6a411630b..0c253e009 100644 --- a/crates/mega-evm/tests/block/activation.rs +++ b/crates/mega-evm/tests/block/activation.rs @@ -269,6 +269,15 @@ fn test_an_absent_parent_timestamp_is_refused_where_it_could_change_the_answer() assert_eq!(executor.is_satin_activation_block(), Err(missing.clone())); let error = executor.apply_pre_execution_changes().expect_err("the block does not start"); assert_eq!(internal(&error), Some(&missing), "an internal error: the caller's omission"); + assert_eq!( + internal(&error).unwrap().to_string(), + format!( + "the parent block's timestamp is missing: a fork the schedule activates after \ + genesis is active at the block's timestamp {at}, and whether it activates in this \ + block depends on the parent's timestamp" + ), + "the diagnostic identifies the missing context and the affected block" + ); let error = executor .execute_transaction(&deposit_tx(Bytes::new(), empty_call_gas())) .expect_err("not even a deposit runs"); diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs index 01ebea265..e7bf169bf 100644 --- a/crates/mega-evm/tests/block/witness/state.rs +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -11,7 +11,7 @@ use alloy_evm::{ use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, MegaBlockExecutor, MegaEvmFactory, }; use op_revm::constants::{ @@ -874,12 +874,19 @@ fn test_a_deposit_creating_the_l1_block_contract_adds_no_slot_read() { case.run(); } -/// A block on `db` that starts, then executes `tx`. -fn execute_one(db: DB, tx: &Tx) -> Result<(), BlockExecutionError> +/// A block on `db` that starts, then executes `tx`, optionally using fee information already +/// cached for this block so the transaction itself needs no fee lookup. +fn execute_one(db: DB, tx: &Tx, cached_fees: bool) -> Result<(), BlockExecutionError> where DB: alloy_evm::Database + revm::DatabaseCommit, { - let evm = MegaEvmFactory::new().create_evm(db, common::evm_env()); + let mut evm = MegaEvmFactory::new().create_evm(db, common::evm_env()); + if cached_fees { + evm.ctx_mut().modify_chain(|chain| { + *chain = zero_fee_l1_block_info(); + chain.l2_block = Some(U256::from(common::BLOCK_NUMBER)); + }); + } let mut executor = MegaBlockExecutor::new( evm, common::unlimited_ctx(), @@ -914,10 +921,10 @@ fn test_a_failed_fee_read_is_routed_as_the_transactions_own() { .with_database(refusing(Some(L1_BASE_FEE_SLOT))) .with_bundle_update() .build(); - let err = execute_one(&mut state, &tx).expect_err("the L1 base fee cannot be read"); + let err = execute_one(&mut state, &tx, false).expect_err("the L1 base fee cannot be read"); assert!(matches!(err, BlockExecutionError::Internal(_)), "fatal: {err:?}"); - let err = execute_one(common::NotFatal(refusing(Some(L1_BASE_FEE_SLOT))), &tx) + let err = execute_one(common::NotFatal(refusing(Some(L1_BASE_FEE_SLOT))), &tx, false) .expect_err("the L1 base fee cannot be read"); assert!( matches!(err, BlockExecutionError::Validation(BlockValidationError::EVM { .. })), @@ -925,6 +932,29 @@ fn test_a_failed_fee_read_is_routed_as_the_transactions_own() { ); } +/// Cached fee information lets execution finish, but the outcome still needs the fee read for +/// its witness. A failure to collect that read has the transaction's fatal/nonfatal routing. +#[test] +fn test_a_failed_fee_witness_read_with_cached_fees_has_no_outcome() { + let tx = call(0, CONTRACT, slot(1), write_gas()); + let mut state = State::builder() + .with_database(refusing(Some(L1_BASE_FEE_SLOT))) + .with_bundle_update() + .build(); + + let fatal = execute_one(&mut state, &tx, true).expect_err("the witness lacks the base fee"); + assert!(matches!(fatal, BlockExecutionError::Internal(_)), "fatal: {fatal:?}"); + assert!(fatal.to_string().contains(&L1_BLOCK_CONTRACT.to_string()), "{fatal}"); + + let not_fatal = execute_one(common::NotFatal(refusing(Some(L1_BASE_FEE_SLOT))), &tx, true) + .expect_err("the witness lacks the base fee"); + assert!( + matches!(not_fatal, BlockExecutionError::Validation(BlockValidationError::EVM { .. })), + "not fatal: {not_fatal:?}" + ); + assert!(not_fatal.to_string().contains(&L1_BLOCK_CONTRACT.to_string()), "{not_fatal}"); +} + /// The footprint scalar is read by the block before a non-deposit transaction runs, outside its /// execution: a database that cannot serve the L1 block contract's account or the scalar's slot /// fails the block as an internal error, whether or not it declares the error fatal, before an @@ -938,7 +968,7 @@ fn test_a_failed_footprint_read_is_an_internal_error() { ]; for (what, tx) in &txs { for slot in [None, Some(OPERATOR_FEE_SCALARS_SLOT)] { - let err = execute_one(common::NotFatal(refusing(slot)), tx) + let err = execute_one(common::NotFatal(refusing(slot)), tx, false) .expect_err("the footprint scalar cannot be read"); assert!(matches!(err, BlockExecutionError::Internal(_)), "{what}, {slot:?}: {err:?}"); assert!( diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs index 7fa3a0b46..fd033ac3b 100644 --- a/crates/mega-evm/tests/system/oracle_storage.rs +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -27,8 +27,9 @@ use revm::{ }, context::{ result::{ExecutionResult, HaltReason}, - TxEnv, + JournalTr, TxEnv, }, + context_interface::{ContextTr, Host}, interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Inspector, }; @@ -150,6 +151,80 @@ fn db_with_state() -> MemoryDatabase { system_db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE) } +/// A tool reading through the Host receives the same service answer as an opcode, with the +/// chain's slot loaded into the journal and every read reported as cold. +#[test] +fn test_host_oracle_reads_use_the_service_and_load_the_chains_value() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let envs = ExternalEnvs:: { salt_env: EmptyExternalEnv, oracle_env: service.clone() }; + let mut ctx = MegaContext::new_with_external_envs(db_with_state(), MegaSpecId::SATIN, envs); + ctx.journal_mut().load_account(ORACLE_CONTRACT_ADDRESS).unwrap(); + + let first = Host::sload_skip_cold_load(&mut ctx, ORACLE_CONTRACT_ADDRESS, SLOT, false) + .expect("the tool requests the read"); + let second = Host::sload_skip_cold_load(&mut ctx, ORACLE_CONTRACT_ADDRESS, SLOT, false) + .expect("a repeated read still asks the service"); + + assert_eq!((first.data, second.data), (SERVICE_VALUE, SERVICE_VALUE)); + assert!(first.is_cold && second.is_cold); + assert_eq!(service.seen(), vec![Seen::Read(SLOT), Seen::Read(SLOT)]); + assert_eq!( + ctx.journal().state[&ORACLE_CONTRACT_ADDRESS].storage[&SLOT].present_value, + STATE_VALUE, + "the service answer does not overwrite the chain's slot" + ); +} + +/// A tool that elects to skip a cold Oracle read asks neither the journal nor the service. +#[test] +fn test_host_skipped_oracle_read_loads_no_slot_and_asks_no_service() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let envs = ExternalEnvs:: { salt_env: EmptyExternalEnv, oracle_env: service.clone() }; + let mut ctx = MegaContext::new_with_external_envs(db_with_state(), MegaSpecId::SATIN, envs); + ctx.journal_mut().load_account(ORACLE_CONTRACT_ADDRESS).unwrap(); + + let result = Host::sload_skip_cold_load(&mut ctx, ORACLE_CONTRACT_ADDRESS, SLOT, true); + + assert!(matches!(result, Err(revm::context_interface::host::LoadError::ColdLoadSkipped))); + assert!(service.seen().is_empty()); + assert!(ctx.journal().state[&ORACLE_CONTRACT_ADDRESS].storage.is_empty()); +} + +/// An Oracle SLOAD with no slot operand halts on its stack before it can ask or be refused. +#[test] +fn test_oracle_sload_without_an_operand_halts_before_reading_or_refusing() { + for disabled in [false, true] { + let service = Service::holding(SLOT, SERVICE_VALUE); + let db = db_with_state().account_code( + ORACLE_CONTRACT_ADDRESS, + BytecodeBuilder::default().append(SLOAD).build(), + ); + let run = run_under( + db, + &service, + EvmTxRuntimeLimits::default(), + |ctx| if disabled { ctx.with_volatile_access_disabled_from(0) } else { ctx }, + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + + assert!( + matches!( + run.outcome.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::StackUnderflow), + .. + } + ), + "access disabled {disabled}: {:?}", + run.outcome.result + ); + assert!(service.seen().is_empty(), "access disabled {disabled}"); + assert!(run.accessed.is_empty(), "access disabled {disabled}"); + assert!(run.evm_reads.is_empty(), "access disabled {disabled}"); + assert!(run.outcome.state[&ORACLE_CONTRACT_ADDRESS].storage.is_empty()); + } +} + /// Code that reads `SLOT` twice and returns what each read cost: the price of `GAS`, of pushing /// the slot, of the `SLOAD` and of popping its value. fn two_reads() -> Bytes { From d14018c9d9f1edfe35e7a94abd915e1c7f953bdd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 23:57:57 +0800 Subject: [PATCH 055/190] feat(evm): refuse a call's beneficiary delegate where the call loads it With volatile-data access off, a call opcode no longer looks up its target's EIP-7702 delegate before it charges anything. A call whose target operand is the beneficiary is still refused up front; any other call runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the load of a delegate that is the beneficiary. The wrapper then reverts the frame on the gas it held at the call, so the refusal still costs nothing, and a target is read only by a frame that holds the gas for its access. The up-front lookup let a frame short of the call's static gas load a cold target's account and code: an access-off loop read about one cold account per 160 gas into the witness, where access on reads none. Tests changed for the new rule: - the refused-read table in detention.rs keeps its large-memory call rows but calls the beneficiary itself: a delegator of it, called with 1 MiB of input on 1,000 gas, now runs out of gas on its memory; - the unreadable-target test now gives the transaction no outcome only for a call that reaches its target's load, and an outcome for one that fails on its memory first; - the witness test of a refused call now reaches the delegate (3,100 gas at the call); one more test shows a call short of its memory reads no target; - the delegate-warms-nothing test now states that a call of a delegator of another account pays as with access on. --- crates/mega-evm/src/access/mod.rs | 13 +- crates/mega-evm/src/evm/host.rs | 42 +- crates/mega-evm/src/evm/instructions.rs | 78 +- crates/mega-evm/tests/block/witness/skips.rs | 95 ++- crates/mega-evm/tests/satin/detention.rs | 16 +- .../mega-evm/tests/satin/volatile_access.rs | 681 ++++++++++++++++-- 6 files changed, 763 insertions(+), 162 deletions(-) diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 306d3166d..edd263170 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -179,9 +179,16 @@ //! opcode's static gas, which the wrapper charges only once it decided the read is not refused, so //! a frame short of the static gas is refused rather than run out of gas. An opcode volatile //! whatever its operands is refused before its operands are read; one volatile for the account or -//! the storage it reads is refused once every operand it takes is on the stack, when its target, -//! its frame or a call target's one-hop EIP-7702 delegate shows it reads the beneficiary's account -//! or the Oracle's storage, the delegate read for the decision without warming anything. A refusal +//! the storage it reads is refused once every operand it takes is on the stack, when its target or +//! its frame shows it reads the beneficiary's account or the Oracle's storage. +//! +//! A call whose target's one-hop EIP-7702 delegate is the beneficiary is refused where it loads +//! that delegate, since only the target's code shows it: the call runs its steps before that load +//! as with access on — its static gas, its memory, its value transfer, the load of its target, +//! which a frame short of the cold access skips as an out-of-gas — and the Host refuses the +//! delegate's load. The frame then reverts on the gas it held when it reached the call, as for any +//! refusal, so the call reads its target only once it holds the gas for it, as with access on, and +//! a frame that cannot reach the delegate fails as it would with access on. A refusal //! names the kind the opcode reads — `BLOCKHASH`'s names the hash, whatever its operand — and a //! `SLOTNUM` refusal names access type 12 //! ([`SLOT_NUM_ACCESS_TYPE`](crate::system::SLOT_NUM_ACCESS_TYPE)), which the contract's diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 637d4f99a..db81261f4 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -27,10 +27,12 @@ //! `load_account_code` and `load_account_code_hash` are the trait's own, built on it. //! //! While volatile-data access is switched off for the running frame, the opcode's wrapper refuses -//! a volatile read before the opcode runs, so the Host loads none. Were one reached, the Host -//! would refuse it: an account or storage load fails as a skipped cold load, and a +//! a read its operands and its frame name before the opcode runs, so the Host loads none of those. +//! The one volatile load a wrapper leaves to the Host is a call's load of its target's EIP-7702 +//! delegate, which only the target's code names: when the delegate is the beneficiary, the Host +//! refuses it. A refused account or storage load fails as a skipped cold load, and a refused //! block-environment accessor answers zero. Nothing is loaded, and the opcode's wrapper turns the -//! refusal into the frame's revert. +//! refusal into the frame's revert, on the gas the frame held when it reached the opcode. //! //! # The Oracle's storage //! @@ -85,7 +87,7 @@ use std::format; use delegate::delegate; use revm::{ - context::{ContextTr, JournalTr}, + context::ContextTr, context_interface::{ cfg::{gas::GasTracker, GasId, GasParams, StateGasCharge, StateGasSite}, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, @@ -95,13 +97,10 @@ use revm::{ }, journaled_state::AccountInfoLoad, }, - interpreter::InstructionResult, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, - state::Bytecode, Database, }; -use super::execution::{mark, revert_to}; use crate::{ charge_write_records_history, history_gas, limit::{DestroyedParts, HistoryBytes}, @@ -688,35 +687,6 @@ impl MegaContext { self.detention.observe(VolatileDataAccess::ORACLE); Ok(answer.unwrap_or(loaded)) } - - /// The one-hop EIP-7702 delegate a call of `target` would follow, read for a frame whose - /// volatile-data access is off to decide, before the call charges or checks anything, whether - /// the call reads the block beneficiary's account: the address `target`'s code delegates to, - /// or `None` when its code is not a delegation. - /// - /// The read loads `target`'s account and code, and not the delegate's: it is in the - /// transaction's state, and so in a stateless witness, as the call's own load of its target - /// would be. It warms nothing: the journal is taken back to where it stood, so the account is - /// as warm or as cold as it was, and a call the read does not refuse pays its target's access - /// as it would with access on. - /// - /// The read is required: a database error is recorded as the transaction's, which fails with - /// it, and is never taken for a target without a delegate. - pub(crate) fn call_target_delegate( - &mut self, - target: Address, - ) -> Result, InstructionResult> { - let journal = &mut self.inner.journaled_state; - let start = mark(journal); - let delegate = journal - .load_account_with_code(target) - .map(|account| account.data.info.code.as_ref().and_then(Bytecode::eip7702_address)); - revert_to(journal, start); - delegate.map_err(|error| { - *self.error() = Err(ContextError::Db(error)); - InstructionResult::FatalExternalError - }) - } } #[cfg(test)] diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index e9c5f0da5..86cea6de5 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -37,11 +37,18 @@ //! An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` among //! them — is refused before its operands are read. One volatile for the account or the storage it //! reads is refused only once every operand it takes is on the stack, so one that fails on its -//! operands fails as it would with access on; it is then refused when its target operand, its -//! frame's own address, or a call target's one-hop EIP-7702 delegate is the block beneficiary, and -//! an `SLOAD` when its frame's storage is the Oracle's. The delegate is read for the decision: the -//! call target's account and code are loaded, so the read is in the transaction's state, and left -//! as warm or cold as they were. +//! operands fails as it would with access on; it is then refused when its target operand or its +//! frame's own address is the block beneficiary, and an `SLOAD` when its frame's storage is the +//! Oracle's. +//! +//! A call whose target operand is not the beneficiary reads nothing volatile unless its target's +//! one-hop EIP-7702 delegate is the beneficiary, which only the target's code shows. The wrapper +//! does not look it up: the call runs its own steps as with access on — its static gas, its +//! memory, its value transfer, the load of its target, which a frame short of the cold access +//! skips as an out-of-gas — and the Host refuses the load of the delegate when it is the +//! beneficiary. The wrapper then puts back the gas the frame held when it reached the call and +//! reverts the frame, so the refusal costs nothing, and the call reads its target only once it +//! holds the gas to, as with access on. //! //! The Oracle's `SLOAD` is the one read made before any of its gas is charged: the slot is loaded, //! the oracle service asked and the read marked, at the compute before the opcode, and only then @@ -181,7 +188,9 @@ pub(crate) fn without_read_static_gas(mut table: GasTable) -> GasTable { } /// `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. +/// beneficiary's account when the callee, or the EIP-7702 delegate it runs, is the beneficiary; +/// with access off, refused for the callee before the call charges anything, and for the delegate +/// where the call loads it. fn call( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { @@ -196,7 +205,9 @@ fn call( /// gas it held when it reached the opcode, before the opcode charges or checks anything. Otherwise /// the opcode's static gas is charged, as its own charge, as the interpreter charges every other /// opcode's, and `inner` runs; a read the opcode completed is committed, capping the frame at what -/// the compute limit leaves it. +/// the compute limit leaves it, and a load the Host refused — a call's EIP-7702 delegate that is +/// the beneficiary — reverts the frame on the gas it held when it reached the opcode +/// ([`settle_reads`]). /// /// A read the opcode did not complete — the opcode failed after the load — is dropped: it reached /// no computation, and the frame is failing anyway. @@ -207,7 +218,7 @@ fn read_volatile( ) -> InstructionExecResult { let InstructionContext { interpreter, host } = context; let gas = if host.detention.is_refusing() { - if let Some(refused) = refused_read::(interpreter, host)? { + if let Some(refused) = refused_read::(interpreter, host) { return Err(refuse(interpreter, refused)); } Some(interpreter.gas) @@ -238,8 +249,8 @@ fn charge_static_gas( } /// What the opcode `OPCODE` would read that the running frame, whose volatile-data access is off, -/// is refused, or `None` when it reads nothing volatile; decided from the opcode, its operands and -/// its frame, before the opcode charges or checks anything. +/// is refused, or `None` when its operands and its frame name nothing volatile; decided from the +/// opcode, its operands and its frame, before the opcode charges or checks anything. /// /// - The block-environment opcodes, `BLOCKHASH` included, are volatile whatever their operands: /// they are refused before their operands are read. @@ -247,19 +258,17 @@ fn charge_static_gas( /// volatile only for the account they read: with fewer operands on the stack than the opcode /// takes, nothing is refused, and the opcode fails on them as it would with access on. They are /// refused when their target operand is the block beneficiary, `SELFDESTRUCT` also when its frame -/// runs as the beneficiary, and a call also when its target's one-hop EIP-7702 delegate is the -/// beneficiary. `SELFBALANCE` is refused when its frame runs as the beneficiary. -/// -/// The delegate is read for the decision ([`call_target_delegate`]), and the read is required: a -/// database error fails the transaction with its cause, whatever the call would have done. +/// runs as the beneficiary. `SELFBALANCE` is refused when its frame runs as the beneficiary. /// -/// [`call_target_delegate`]: MegaContext::call_target_delegate +/// A call whose target's one-hop EIP-7702 delegate is the beneficiary is not decided here: the +/// target's code shows the delegate, and the call loads it only once it paid its own earlier steps +/// and holds the target's access, so the Host refuses the delegate's load there. #[cold] #[inline(never)] fn refused_read( interpreter: &Interpreter, - host: &mut MegaContext, -) -> Result, InstructionResult> { + host: &MegaContext, +) -> Option { let block_env = match OPCODE { NUMBER => Some(VolatileDataAccess::BLOCK_NUMBER), TIMESTAMP => Some(VolatileDataAccess::TIMESTAMP), @@ -273,7 +282,7 @@ fn refused_read( _ => None, }; if block_env.is_some() { - return Ok(block_env); + return block_env; } let beneficiary = host.inner.block.beneficiary; let stack = &interpreter.stack; @@ -289,23 +298,26 @@ fn refused_read( } CALL | CALLCODE | DELEGATECALL | STATICCALL => { let operands = if matches!(OPCODE, CALL | CALLCODE) { 7 } else { 6 }; - match address(1) { - Some(target) if stack.len() >= operands => { - target == beneficiary || host.call_target_delegate(target)? == Some(beneficiary) - } - _ => false, - } + stack.len() >= operands && address(1) == Some(beneficiary) } _ => false, }; - Ok(reads_beneficiary.then_some(VolatileDataAccess::BENEFICIARY_BALANCE)) + reads_beneficiary.then_some(VolatileDataAccess::BENEFICIARY_BALANCE) } -/// The slow half of [`read_volatile`]: the Host observed a read. +/// The slow half of [`read_volatile`]: the Host observed or refused a read. /// -/// The Host refuses a load only where the wrapper did not refuse the read first, which no opcode -/// reaches: every volatile load an opcode makes is one [`refused_read`] decides. Were one reached, -/// the frame would be refused on the gas it held when it reached the opcode (`gas`). +/// The Host refuses a load in a frame whose volatile-data access is off where the wrapper did not +/// refuse the read first: a call's load of its target's EIP-7702 delegate when the delegate is the +/// beneficiary. The call has then run its steps before the load — its static gas, its memory, its +/// value transfer, the load of its target — and fails the load as a skipped cold load, before it +/// charges its target's access, any state gas or its forward, and before the frame-start hook, so +/// what it did is all in the frame's gas and memory. The frame is refused on the gas it held when +/// it reached the opcode (`gas`), the spendable and withheld parts and the reservoir as they were, +/// which takes back every charge; its revert takes back the target's warming, and leaves the +/// target's account and code in the transaction's state. The memory the call expanded stays +/// expanded until the frame's end, which follows at once; the gas's record of it is put back with +/// the rest. #[inline(never)] fn settle_reads( interpreter: &mut Interpreter, @@ -314,9 +326,9 @@ fn settle_reads( gas: Option, ) -> InstructionExecResult { let observed = host.detention.take_observed(); - let refused = host.detention.take_refused(); - debug_assert!(refused.is_none(), "a read the wrapper did not refuse first: {refused:?}"); - if let Some(refused) = refused { + if let Some(refused) = host.detention.take_refused() { + // The Host refuses only while the frame refuses, so the wrapper kept the frame's gas. + debug_assert!(gas.is_some(), "a refusal in a frame whose access is on: {refused:?}"); // The Host refuses a load before the opcode builds a frame, so no action is pending. if let Some(gas) = gas { interpreter.gas = gas; diff --git a/crates/mega-evm/tests/block/witness/skips.rs b/crates/mega-evm/tests/block/witness/skips.rs index 7fe4c2f09..1a6cd601d 100644 --- a/crates/mega-evm/tests/block/witness/skips.rs +++ b/crates/mega-evm/tests/block/witness/skips.rs @@ -2,18 +2,21 @@ //! with less gas than the cold surcharge, and reads a frame that switched its volatile-data access //! off is refused. None reaches the database, none is in the record, and the replay skips them the //! same way. An Oracle read is not one of them: it is made before its charge, so a frame that -//! cannot pay it reads the slot and asks the service all the same, and the replay does too. +//! cannot pay it reads the slot and asks the service all the same, and the replay does too. Nor is +//! the target of a call refused at its EIP-7702 delegate: the call loads its target as it would +//! with access on, and is refused at the delegate's load. use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, - test_utils::BytecodeBuilder, + test_utils::{BytecodeBuilder, MemoryDatabase}, volatile_data_access_disabled_revert_data, OracleRead, VolatileDataAccess, }; use revm::{ bytecode::opcode::{ - BALANCE, BLOCKHASH, CALL, CALLCODE, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD, + BALANCE, BLOCKHASH, CALL, CALLCODE, GAS, MSTORE, POP, PUSH0, RETURN, RETURNDATASIZE, SLOAD, + STATICCALL, }, context::result::ExecutionResult, context_interface::cfg::GasId, @@ -257,12 +260,12 @@ fn test_a_refused_oracle_read_reads_nothing() { assert!(run.record.storage.contains_key(&slot), "and the slot is read from the database"); } -/// With access off, a call opcode reads its target's account and code to find the EIP-7702 -/// delegate it would follow, before it charges or checks anything: a `CALLCODE` of a delegator -/// of the block beneficiary, with an input of 1 MiB its 1,000 gas cannot pay, is refused, and the -/// delegator's account and code are in the record and the witness, which the replay reads alike. -#[test] -fn test_a_refused_call_reads_its_targets_account_and_code() { +/// A child of [`CONTRACT`], which runs the calls whose reads the access-off tests count. +const CHILD: Address = address!("0x5000000000000000000000000000000000000007"); + +/// A database holding [`DELEGATOR`], an EIP-7702 delegator of the block beneficiary, and the +/// delegation its code is. +fn with_the_delegator() -> (MemoryDatabase, Bytecode) { let delegation = Bytecode::new_eip7702(Address::ZERO); let mut db = common::database(); db.insert_account_info( @@ -273,6 +276,16 @@ fn test_a_refused_call_reads_its_targets_account_and_code() { ..Default::default() }, ); + (db, delegation) +} + +/// With access off, a call opcode loads its target as it would with access on, once it paid its +/// static gas and its memory: a `CALLCODE` of a delegator of the block beneficiary with an input +/// of 1 MiB its frame cannot pay runs out of gas on its memory, and the delegator's account is in +/// neither the record nor the witness, which the replay reads alike. +#[test] +fn test_a_call_short_of_its_memory_reads_no_target() { + let (mut db, _) = with_the_delegator(); let then = BytecodeBuilder::default() .append_many([PUSH0, PUSH0]) .push_number(0x10_0000_u32) @@ -282,17 +295,63 @@ fn test_a_refused_call_reads_its_targets_account_and_code() { .append(CALLCODE) .stop(); db.set_account_code(CONTRACT, disabled_then(then)); - let replay = Case::new("refused call of a delegator", db) + let replay = Case::new("call of a delegator short of its memory", db) .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) .run(); let run = &replay.recorded; - match &run.tx(0).result { - ExecutionResult::Revert { output, .. } => assert_eq!( - output, - &volatile_data_access_disabled_revert_data(VolatileDataAccess::BENEFICIARY_BALANCE) - ), - other => panic!("expected the refusal, got {other:?}"), + assert!(matches!(run.tx(0).result, ExecutionResult::Halt { .. }), "{:?}", run.tx(0).result); + assert!(!run.record.accounts.contains_key(&DELEGATOR), "the target is not read"); +} + +/// With access off, a call of a delegator of the block beneficiary is refused where it loads the +/// delegate, its target's account and code read by then: a `STATICCALL` of it from a child holding +/// 2,999 at the call — its static gas and one short of the cold surcharge — runs out of gas without +/// reading the delegator; one holding 3,050 reads it and runs out of gas at the check that it +/// holds the delegate's warm access; one holding 3,100 is refused, and the delegator's account and +/// code are in the record and the witness, which the replay reads alike. +#[test] +fn test_a_refused_call_reads_its_targets_account_and_code() { + let params = mega_evm::satin_gas_params(); + let warm = params.get(GasId::warm_storage_read_cost()); + let surcharge = params.get(GasId::cold_account_additional_cost()); + let child = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(DELEGATOR) + .append_many([PUSH0, STATICCALL]) + .stop() + .build(); + let pushes = 4 * 2 + 3 + 2; + let refused = + volatile_data_access_disabled_revert_data(VolatileDataAccess::BENEFICIARY_BALANCE); + // (what the child holds at the call, whether it is refused, whether it reads the delegator) + for (left, is_refused, reads) in [ + (warm + surcharge - 1, false, false), + (warm + surcharge + warm / 2, false, true), + (warm + surcharge + warm, true, true), + ] { + let (mut db, delegation) = with_the_delegator(); + let then = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(pushes + left) + .append_many([CALL, POP, RETURNDATASIZE, PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]); + db.set_account_code(CONTRACT, disabled_then(then)); + db.set_account_code(CHILD, child.clone()); + let replay = Case::new("call of a delegator of the beneficiary", db) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{left}: {:?}", run.tx(0).result); + let returned = U256::from_be_slice(run.tx(0).result.output().expect("the size")); + let expected = if is_refused { refused.len() } else { 0 }; + assert_eq!(returned, U256::from(expected), "{left}: the child's revert data"); + assert_eq!(run.record.accounts.contains_key(&DELEGATOR), reads, "{left}: the account"); + assert_eq!( + run.record.codes.contains_key(&delegation.hash_slow()), + reads, + "{left}: and its code" + ); } - assert!(run.record.accounts.contains_key(&DELEGATOR), "the target's account is read"); - assert!(run.record.codes.contains_key(&delegation.hash_slow()), "and its code"); } diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 4af4fa1c2..96e416ba8 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -1586,9 +1586,11 @@ impl Inspector, EthInterpreter> for Calls { /// /// An opcode volatile whatever its operands is refused before it reads them, so a `BLOCKHASH` on /// an empty stack is refused rather than halting on the underflow; one volatile for the account -/// or the storage it reads is refused once its operands are on the stack, before its body checks -/// anything — a large copy, a call's memory, a value transfer it could not fund, a call to an -/// EIP-7702 delegator of the beneficiary — and so is an `SLOAD` in the Oracle's own frame. +/// or the storage its operands or its frame name is refused once its operands are on the stack, +/// before its body checks anything — a large copy, a call's memory, a value transfer it could not +/// fund — and so is an `SLOAD` in the Oracle's own frame. A call whose target is an EIP-7702 +/// delegator of the beneficiary is not among them: it is refused where it loads the delegate, +/// after its own steps. #[test] fn test_a_refused_read_reverts_the_frame_and_charges_nothing() { // Pushes the operands of a call of `to` through `scheme`, carrying `value` when the scheme @@ -1665,16 +1667,16 @@ fn test_a_refused_read_reverts_the_frame_and_charges_nothing() { VolatileDataAccess::BENEFICIARY_BALANCE, ), ( - "CALL of a delegator of the beneficiary, with a value it cannot fund", + "CALL of the beneficiary, with a value it cannot fund", CHILD, - call_with_memory(CALL, 200, DELEGATOR), + call_with_memory(CALL, 200, BENEFICIARY), 2 + 2 + 3 + 2 + 3 + 3 + 3, VolatileDataAccess::BENEFICIARY_BALANCE, ), ( - "STATICCALL of a delegator of the beneficiary", + "STATICCALL of the beneficiary", CHILD, - call_with_memory(STATICCALL, 0, DELEGATOR), + call_with_memory(STATICCALL, 0, BENEFICIARY), 2 + 2 + 3 + 2 + 3 + 3, VolatileDataAccess::BENEFICIARY_BALANCE, ), diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 3f462e1bd..22a4f98c4 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -14,26 +14,40 @@ use mega_evm::{ IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, }, - test_utils::{op_transaction, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, - volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, - MegaLimitExceeded, MegaTransaction, VolatileDataAccess, + test_utils::{ + op_transaction, record_start_ledger_settlements, take_start_ledger_settlements, + BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, RecordingDatabase, + SharedWitnessRecord, + }, + volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, + MegaContext, MegaEvm, MegaLimitExceeded, MegaTransaction, VolatileDataAccess, }; use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; use revm::{ bytecode::opcode::*, - context::{result::ExecutionResult, Transaction, TxEnv}, + context::{ + result::ExecutionResult, + transaction::{AccessList, AccessListItem, TransactionType}, + Transaction, TxEnv, + }, context_interface::cfg::GasId, - interpreter::InstructionResult, + interpreter::{ + interpreter::EthInterpreter, + interpreter_types::{Jumps, MemoryTr}, + CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, + }, primitives::{eip2780::TX_BASE_COST, eip8038::COLD_ACCOUNT_ACCESS}, state::Bytecode, + Inspector, }; use crate::{ common::body_history, detention::{ - assert_caught, assert_stopped, burn, call, context, execute, intrinsic, on_beneficiary, op, - run_on, spin, stop_data, tx, with_delegation, work, Calls, Charges, BELOW, BENEFICIARY, - CALLER, CAP, CHILD, CONTRACT, DELEGATOR, TIERS, + assert_caught, assert_stopped, burn, call, cold_access, context, execute, intrinsic, + on_beneficiary, op, run_on, spin, stop_data, tx, value_transfer, with_delegation, work, + Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, DELEGATOR, + TIERS, }, salt::entry, }; @@ -721,74 +735,428 @@ fn test_a_database_failure_surfaces_and_a_stack_underflow_comes_first() { } } -/// The operands of a `CALLCODE` of `to` carrying no value, with an input of 1 MiB, an output of -/// nothing and 1,000 gas: the frame cannot pay the input's memory. -fn callcode_of_a_mebibyte(to: Address) -> BytecodeBuilder { - BytecodeBuilder::default() - .append_many([PUSH0, PUSH0]) - .push_number(0x10_0000_u32) - .append_many([PUSH0, PUSH0]) - .push_address(to) - .push_number(1_000_u16) - .append(CALLCODE) +/* ---------- a call's delegate, refused where the call loads it ---------- */ + +/// An account no transaction here funds, and that nothing loads unless a call reads it. +const UNTOUCHED: Address = address!("0000000000000000000000000000000000d00005"); + +/// A call of `to` through `scheme` forwarding no gas, carrying `value` when the scheme takes one, +/// with an input of `in_len` bytes at offset zero and no output, then a `STOP`; and what the +/// pushes before the call cost. +fn call_of(scheme: u8, to: Address, value: u8, in_len: u32) -> (Bytes, u64) { + let mut code = BytecodeBuilder::default().append_many([PUSH0, PUSH0]); + let mut pushes = 2 + 2; + if in_len == 0 { + code = code.append(PUSH0); + pushes += 2; + } else { + code = code.push_number(in_len); + pushes += 3; + } + code = code.append(PUSH0); + pushes += 2; + if matches!(scheme, CALL | CALLCODE) { + if value == 0 { + code = code.append(PUSH0); + pushes += 2; + } else { + code = code.push_number(value); + pushes += 3; + } + } + let code = code.push_address(to).append(PUSH0).append(scheme).stop(); + (code.build(), pushes + 3 + 2) } -/// What the pushes of [`callcode_of_a_mebibyte`] cost. -const CALLCODE_PUSHES: u64 = 2 + 2 + 3 + 2 + 2 + 3 + 3; - -/// With access off, a call opcode reads its target's account and code to find the EIP-7702 -/// delegate it would follow, before it charges or checks anything, and the read is required: a -/// `CALLCODE` of a delegator of the beneficiary, with an input of 1 MiB its 1,000 gas cannot pay, -/// is refused for free where the delegator can be read, and gives the transaction no outcome -/// where its account or its code cannot, rather than halting on the memory. -#[test] -fn test_a_call_target_unreadable_for_its_delegate_has_no_outcome() { - let code_hash = Bytecode::new_eip7702(BENEFICIARY).hash_slow(); - let child = callcode_of_a_mebibyte(DELEGATOR).build(); - let parent = BytecodeBuilder::default() - .append_many([PUSH0; 5]) - .push_address(CHILD) - .push_number(CALLCODE_PUSHES + 1_000) - .append_many([CALL, POP]) - .stop() - .build(); - let db = || { - MemoryDatabase::default() - .account_code(CONTRACT, parent.clone()) - .account_code(CHILD, child.clone()) +/// A call of `CHILD` forwarding `gas`, or everything when `gas` is `None`, its status dropped. +fn calls_child(code: BytecodeBuilder, gas: Option) -> BytecodeBuilder { + let code = code.append_many([PUSH0; 5]).push_address(CHILD); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), }; + code.append_many([CALL, POP]) +} - let readable = with_delegation(db(), DELEGATOR, BENEFICIARY); - let mut evm = MegaEvm::new(context(readable).with_volatile_access_disabled_from(1)) +/// Appends a `BALANCE` of [`DELEGATOR`] and returns, as a word, what it cost with its push, its +/// `POP` and the `GAS` that reads what is left: [`cold_access`] and seven when the account is cold. +fn then_balance_of_the_delegator(code: BytecodeBuilder) -> Bytes { + code.append(GAS) + .push_address(DELEGATOR) + .append_many([BALANCE, POP, GAS, SWAP1, SUB, PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build() +} + +/// What a [`then_balance_of_the_delegator`] returned. +fn balance_cost(run: &Run) -> u64 { + let output = run.outcome.result.output().expect("the caller returns the cost"); + U256::from_be_slice(output).to::() +} + +/// What a `BALANCE` of a cold account costs the caller in [`then_balance_of_the_delegator`]. +fn cold_balance() -> u64 { + 3 + cold_access() + 2 + 2 +} + +/// Runs `tx` with volatile-data access off from depth 1 down, and returns the run, how `CHILD`'s +/// frame ended and the gas it spent. +fn run_child(db: MemoryDatabase, tx: MegaTransaction) -> (Run, InstructionResult, Bytes, u64) { + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) .with_inspector(Calls::default()); - let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); - assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); - let record = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); - assert_eq!( - (record.result, record.output.clone()), - refused(VolatileDataAccess::BENEFICIARY_BALANCE), - "a readable delegator" - ); - assert_eq!(record.spent, CALLCODE_PUSHES, "the refusal costs nothing"); + let run = run_on(&mut evm, tx); + let child = + evm.inspector().calls.iter().find(|call| call.target == CHILD).expect("the child ran"); + let (result, output, spent) = (child.result, child.output.clone(), child.spent); + (run, result, output, spent) +} - for fails_on_code in [false, true] { - let mut db = ErrorInjectingDatabase::new(db().account_lazy_code(DELEGATOR, code_hash)); - if fails_on_code { - db.fail_on_code_by_hash = Some(code_hash); +/// A call of the beneficiary itself is refused before it charges anything, whatever its frame +/// holds: a value `CALL` of it with an input of 1 MiB, from a frame holding 50 at the call — less +/// than its static gas — reverts with `VolatileDataAccessDisabled(10)` spending nothing of the +/// call, and marks nothing for gas detention. +#[test] +fn test_a_direct_call_of_the_beneficiary_is_refused_below_its_static_gas() { + let (child, pushes) = call_of(CALL, BENEFICIARY, 1, 0x10_0000); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code( + CONTRACT, + calls_child(BytecodeBuilder::default(), Some(pushes + 50)).stop().build(), + ) + .account_code(CHILD, child.clone()); + let (run, result, output, spent) = run_child(db, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!((result, output), refused(VolatileDataAccess::BENEFICIARY_BALANCE)); + assert_eq!(spent, pushes, "the call spends nothing"); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + assert_eq!(run.limit, None); + } +} + +/// With access off, a call of a cold EIP-7702 delegator of the beneficiary runs its own steps as +/// it would with access on, and is refused only when it reaches the load of its delegate: its +/// static gas, then the load of its target, which a frame short of the cold surcharge does not +/// make, then the check that it holds its target's access with the delegate's warm access on top. +/// A frame holding 2,999 at the `STATICCALL` runs out of gas without reading the delegator; one +/// holding 3,050 reads it and runs out of gas at that check; one holding 3,100 reaches the +/// delegate and is refused, spending nothing of the call. Either way the frame's end leaves the +/// delegator cold for its caller, whose `BALANCE` of it pays the cold access, and nothing reads +/// the beneficiary. +#[test] +fn test_a_cold_delegator_of_the_beneficiary_is_refused_at_its_delegate() { + let warm = entry(GasId::warm_storage_read_cost()); + let surcharge = entry(GasId::cold_account_additional_cost()); + let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); + // (what the child holds at the call, whether it is refused, whether it reads the delegator) + for (left, is_refused, reads) in [ + (warm + surcharge - 1, false, false), + (warm + surcharge + warm / 2, false, true), + (warm + surcharge + warm, true, true), + ] { + // The caller stops after the call, so the delegator is in the transaction's state only + // if the call read it; or it reads the delegator's balance, to find it warm or cold. + for balance in [false, true] { + let parent = calls_child(BytecodeBuilder::default(), Some(pushes + left)); + let parent = + if balance { then_balance_of_the_delegator(parent) } else { parent.stop().build() }; + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()); + let (run, result, output, spent) = run_child(db, tx(CALLER, CONTRACT, BELOW)); + let case = format!("{left}, balance {balance}"); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + if is_refused { + let refusal = refused(VolatileDataAccess::BENEFICIARY_BALANCE); + assert_eq!((result, output), refusal, "{case}"); + assert_eq!(spent, pushes, "{case}: the refusal spends nothing of the call"); + } else { + assert_eq!(result, InstructionResult::OutOfGas, "{case}"); + assert_eq!(spent, pushes + left, "{case}: the halt burns what the frame held"); + } + if balance { + assert_eq!(balance_cost(&run), cold_balance(), "{case}: the caller finds it cold"); + } else { + assert_eq!(run.outcome.state.contains_key(&DELEGATOR), reads, "{case}: read"); + } + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{case}"); + assert_eq!(run.limit, None, "{case}"); + } + } +} + +/// A delegator of the beneficiary the transaction's access list warms is loaded with no cold +/// surcharge, so the call reaches its delegate with the static gas and the delegate's warm access: +/// a frame holding 199 at the `STATICCALL` runs out of gas at the check that it holds them, and +/// one holding 200 is refused, spending nothing of the call. +#[test] +fn test_a_warm_delegator_of_the_beneficiary_is_refused_with_the_gas_for_its_delegate() { + let warm = entry(GasId::warm_storage_read_cost()); + let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); + for (left, is_refused) in [(2 * warm - 1, false), (2 * warm, true)] { + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code( + CONTRACT, + calls_child(BytecodeBuilder::default(), Some(pushes + left)).stop().build(), + ) + .account_code(CHILD, child.clone()); + let listed = alloy_op_evm::OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit: BELOW, + access_list: AccessList(vec![AccessListItem { + address: DELEGATOR, + storage_keys: vec![], + }]), + ..Default::default() + })); + let (run, result, output, spent) = run_child(db, listed); + assert!(run.outcome.result.is_success(), "{left}: {:?}", run.outcome.result); + if is_refused { + assert_eq!( + (result, output), + refused(VolatileDataAccess::BENEFICIARY_BALANCE), + "{left}" + ); + assert_eq!(spent, pushes, "{left}"); } else { - db.fail_on_account = Some(DELEGATOR); + assert_eq!(result, InstructionResult::OutOfGas, "{left}"); + assert_eq!(spent, pushes + left, "{left}"); + } + } +} + +/// A call's memory and its value transfer come before its target's load: a `CALLCODE` of a cold +/// delegator of the beneficiary with an input of 1 MiB, from a frame holding 5,000, runs out of +/// gas on its memory without reading the delegator. A value `CALL` of it from a frame that cannot +/// fund the value pays its value transfer, then loads its target: holding 14,400 — the static gas, +/// the transfer, the cold access and the delegate's warm access — it is refused before revm checks +/// the caller's balance, spending nothing of the call; holding one less, it reads the delegator +/// and runs out of gas at the check that it holds the delegate's access. +#[test] +fn test_a_calls_memory_and_value_transfer_come_before_its_target_is_read() { + let (callcode, pushes) = call_of(CALLCODE, DELEGATOR, 0, 0x10_0000); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code( + CONTRACT, + calls_child(BytecodeBuilder::default(), Some(pushes + 5_000)).stop().build(), + ) + .account_code(CHILD, callcode); + let (run, result, _, spent) = run_child(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(result, InstructionResult::MemoryOOG, "the memory"); + assert_eq!(spent, pushes + entry(GasId::warm_storage_read_cost()), "the static gas, paid"); + assert!(!run.outcome.state.contains_key(&DELEGATOR), "the target is not read"); + + let warm = entry(GasId::warm_storage_read_cost()); + let reach = warm + value_transfer() + entry(GasId::cold_account_additional_cost()) + warm; + let (value_call, pushes) = call_of(CALL, DELEGATOR, 1, 0); + for (left, is_refused) in [(reach, true), (reach - 1, false)] { + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code( + CONTRACT, + calls_child(BytecodeBuilder::default(), Some(pushes + left)).stop().build(), + ) + .account_code(CHILD, value_call.clone()); + let (run, result, output, spent) = run_child(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{left}: {:?}", run.outcome.result); + if is_refused { + assert_eq!( + (result, output), + refused(VolatileDataAccess::BENEFICIARY_BALANCE), + "{left}" + ); + assert_eq!(spent, pushes, "{left}: the transfer is not charged"); + } else { + assert_eq!((result, spent), (InstructionResult::OutOfGas, pushes + left), "{left}"); + } + assert!(run.outcome.state.contains_key(&DELEGATOR), "{left}: the target is read"); + } +} + +/// A call whose memory crosses gas detention is stopped before it loads its target: with access +/// off below a frame that read the block's timestamp, a `STATICCALL` of an account nothing loaded, +/// with an input of 0x320000 bytes whose memory costs more than the frame may spend and less than +/// it holds, pays its static gas and is stopped at its memory, its frame reverting with the +/// compute stop on everything but its pushes and that static gas, and the account is not read. +#[test] +fn test_a_detained_memory_crossing_reads_no_call_target() { + let (child, pushes) = call_of(STATICCALL, UNTOUCHED, 0, 0x32_0000); + for gas_limit in TIERS { + let parent = calls_child(op(BytecodeBuilder::default(), TIMESTAMP), None).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()) + .account_balance(UNTOUCHED, U256::from(1)); + let (run, result, output, spent) = run_child(db, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let limit = run.limit.expect("the timestamp detains"); + assert_eq!((result, output), (InstructionResult::Revert, stop_data(limit))); + assert_eq!( + spent, + pushes + entry(GasId::warm_storage_read_cost()), + "the memory is not paid" + ); + assert!(!run.outcome.state.contains_key(&UNTOUCHED), "the target is not read"); + } +} + +/// Records, for the first call opcode `CHILD`'s frame runs, the frame's gas and memory size when +/// it reaches the opcode and once the opcode returned, and how the frame ended. +#[derive(Default)] +struct AtTheCall { + pending: bool, + before: Option<(Gas, usize)>, + after: Option<(Gas, usize)>, + child: Option<(InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for AtTheCall { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + let opcode = interp.bytecode.opcode(); + if interp.input.target_address == CHILD && + self.before.is_none() && + matches!(opcode, CALL | CALLCODE | DELEGATECALL | STATICCALL) + { + self.pending = true; + self.before = Some((interp.gas, interp.memory.size())); + } + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if core::mem::take(&mut self.pending) { + self.after = Some((interp.gas, interp.memory.size())); + } + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == CHILD { + self.child = Some((outcome.result.result, outcome.result.output.clone())); } - let result = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) - .execute_transaction(tx(CALLER, CONTRACT, BELOW)); - assert!(result.is_err(), "code {fails_on_code}: {result:?}"); } } -/// The read of a call target's account and code that finds its delegate warms neither: a call the -/// read does not refuse — of a delegator of another account than the beneficiary — pays the cold -/// access to its target with access off as with access on, and spends the same. +/// A call refused at its delegate takes back everything it did before the load, so its frame +/// reverts on exactly the gas it held when it reached the call. A value `CALL` of a cold delegator +/// of the beneficiary, with an input of 64 KiB, from a frame that cannot fund the value, has paid +/// its static gas, its memory and its value transfer and loaded its target when the load of its +/// delegate is refused: the frame's gas once the opcode returned is its gas before it — the +/// spendable and withheld parts, the reservoir and the memory's price. The frame-start hook has not +/// run, so the transaction keeps no state or history gas but its body's and opens no start beyond +/// its two frames'. The revert leaves the delegator cold for the caller, whose `BALANCE` of it +/// pays the cold access, and the refusal marks nothing for gas detention: in a +/// transaction a read of the timestamp detained first, the refusal leaves its limit and its reads +/// as they were. The same holds above the execution cap, where the frame holds a reservoir. #[test] -fn test_the_delegate_read_warms_nothing() { +fn test_a_refusal_at_the_delegate_takes_back_everything_the_call_did() { + let (child, _) = call_of(CALL, DELEGATOR, 1, 0x1_0000); + for gas_limit in TIERS { + for detained in [false, true] { + let start = || { + if detained { + op(BytecodeBuilder::default(), TIMESTAMP) + } else { + BytecodeBuilder::default() + } + }; + let parent = then_balance_of_the_delegator(calls_child(start(), None)); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(AtTheCall::default()); + record_start_ledger_settlements(evm.ctx_mut()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + let case = format!("{gas_limit}, detained {detained}"); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + let inspector = evm.inspector(); + assert_eq!( + inspector.child.clone(), + Some(refused(VolatileDataAccess::BENEFICIARY_BALANCE)), + "{case}" + ); + let (before, after) = (inspector.before.unwrap(), inspector.after.unwrap()); + assert_eq!(after.0, before.0, "{case}: the frame's gas, as it reached the call"); + if gas_limit == ABOVE { + assert!(before.0.reservoir() > 0, "{case}: the frame holds a reservoir"); + } + if detained { + assert!(before.0.tracker().withheld() > 0, "{case}: part of its gas is withheld"); + } + assert_eq!(take_start_ledger_settlements(evm.ctx_mut()).len(), 2, "{case}: two starts"); + assert_eq!(run.outcome.gas.state, 0, "{case}"); + assert_eq!(run.outcome.gas.history, body_history(0), "{case}"); + assert_eq!(balance_cost(&run), cold_balance(), "{case}: the target is left cold"); + + // The same transaction whose child stops before its call reads what this one read. + let twin = then_balance_of_the_delegator(calls_child(start(), None)); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, twin) + .account_code(CHILD, BytecodeBuilder::default().stop().build()); + let twin = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert_eq!((run.accessed, run.limit), (twin.accessed, twin.limit), "{case}"); + } + } +} + +/// With access off, a call's target is a required read once the call reaches its load, and no +/// read before: a `CALLCODE` of a delegator of the beneficiary that holds the gas to reach its +/// target gives the transaction no outcome when the target's account or code cannot be read, +/// rather than taking it for a target without a delegate; one with an input of 1 MiB its 5,000 +/// gas cannot pay runs out of gas on its memory before its target's load, so the same unreadable +/// target fails nothing, and the transaction has its outcome. +#[test] +fn test_a_call_target_unreadable_where_the_call_loads_it_has_no_outcome() { + let code_hash = Bytecode::new_eip7702(BENEFICIARY).hash_slow(); + for (in_len, left, reaches) in [(0, 100_000, true), (0x10_0000, 5_000, false)] { + let (child, pushes) = call_of(CALLCODE, DELEGATOR, 0, in_len); + for fails_on_code in [false, true] { + let case = format!("input {in_len}, code {fails_on_code}"); + let inner = MemoryDatabase::default() + .account_code( + CONTRACT, + calls_child(BytecodeBuilder::default(), Some(pushes + left)).stop().build(), + ) + .account_code(CHILD, child.clone()) + .account_lazy_code(DELEGATOR, code_hash); + let mut db = ErrorInjectingDatabase::new(inner); + if fails_on_code { + db.fail_on_code_by_hash = Some(code_hash); + } else { + db.fail_on_account = Some(DELEGATOR); + } + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let result = evm.execute_transaction(tx(CALLER, CONTRACT, BELOW)); + if reaches { + assert!(result.is_err(), "{case}: {result:?}"); + continue; + } + let outcome = result.expect("the call reads nothing, so nothing fails"); + assert!(outcome.result.is_success(), "{case}"); + let child = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!(child.result, InstructionResult::MemoryOOG, "{case}: on the memory"); + assert!(!outcome.state.contains_key(&DELEGATOR), "{case}"); + } + } +} + +/// A call whose target delegates to another account than the beneficiary is not refused, and +/// pays with access off what it pays with access on: the cold access to its target and to the +/// target's delegate, whose code runs. +#[test] +fn test_a_call_of_a_delegator_of_another_account_pays_as_with_access_on() { let child = call(BytecodeBuilder::default(), CALL, DELEGATOR).stop().build(); let spent = |disabled: bool| { let db = with_delegation(MemoryDatabase::default(), DELEGATOR, OTHER) @@ -812,7 +1180,190 @@ fn test_the_delegate_read_warms_nothing() { let cold = entry(GasId::warm_storage_read_cost()) + entry(GasId::cold_account_additional_cost()); assert_eq!(on, 2 * 5 + 3 + 2 + 2 * cold + 2, "access on"); - assert_eq!(spent(true), on, "access off reads the target first and warms nothing"); + assert_eq!(spent(true), on, "access off"); +} + +/// The fresh addresses an amplification loop calls, none of which any account holds. +fn fresh_addresses(count: u64) -> Vec
{ + (0..count).map(|i| Address::from_word(B256::from(U256::from(0xa000_0000_u64 + i)))).collect() +} + +/// A contract that calls `helper` once for each of `targets`, by `STATICCALL` with the target's +/// address as its 32 bytes of input and `gas` forwarded, or everything when `gas` is `None`, after +/// running `start`. +fn calls_the_helper_for_each( + start: BytecodeBuilder, + helper: Address, + targets: &[Address], + gas: Option, +) -> Bytes { + let mut code = start; + for target in targets { + code = code + .push_address(*target) + .append_many([PUSH0, MSTORE, PUSH0, PUSH0]) + .push_number(32_u8) + .append(PUSH0) + .push_address(helper); + code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + code = code.append_many([STATICCALL, POP]); + } + code.stop().build() +} + +/// A helper that `STATICCALL`s the address its input holds, forwarding nothing, with an input of +/// `in_len` bytes and no output; and what its pushes cost. +fn calls_its_input(in_len: u32) -> (Bytes, u64) { + let code = BytecodeBuilder::default().append_many([PUSH0, PUSH0]); + let (code, pushes) = if in_len == 0 { + (code.append(PUSH0), 2 + 2 + 2) + } else { + (code.push_number(in_len), 2 + 2 + 3) + }; + let code = code.append_many([PUSH0, PUSH0, CALLDATALOAD, PUSH0, STATICCALL]); + (code.build(), pushes + 2 + 2 + 3 + 2) +} + +/// Appends a call of `disableVolatileDataAccess()`, which switches access off for the running +/// frame and every frame below it until the running frame returns. +fn disables_volatile_access(code: BytecodeBuilder) -> BytecodeBuilder { + let disable = IMegaAccessControl::disableVolatileDataAccessCall {}.abi_encode(); + code.mstore(0, &disable) + .append_many([PUSH0, PUSH0]) + .push_number(disable.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ACCESS_CONTROL_ADDRESS) + .append_many([GAS, CALL, POP]) +} + +/// One run of an amplification loop: the regular gas the transaction spent, and how many of the +/// loop's targets its database was asked for. +struct Amplification { + gas: u64, + reads: usize, +} + +impl Amplification { + fn run(db: MemoryDatabase, targets: &[Address]) -> Self { + let record = SharedWitnessRecord::default(); + let outcome = MegaEvm::new(context(RecordingDatabase::new(db, record.clone()))) + .execute_transaction(tx(CALLER, CONTRACT, BELOW)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let record = record.borrow(); + let reads = targets.iter().filter(|target| record.accounts.contains_key(*target)).count(); + Self { gas: outcome.gas.regular, reads } + } + + /// The regular gas the transaction spent per target read, or `None` when it read none. + fn gas_per_read(&self) -> Option { + (self.reads > 0).then(|| self.gas / self.reads as u64) + } +} + +/// With access off, a frame cannot read an account it does not pay for. A contract switches its +/// access off, then calls a warm helper for each of 1,000 fresh addresses, forwarding the helper +/// exactly the gas of its pushes, so the helper reaches its `STATICCALL` of the address holding +/// nothing: the call halts at its static gas and no address is read, as with access on. +/// Forwarding the helper the static gas and the cold access too, every address is read, at the +/// cold access each, and the transaction spends with access off what it spends with access on. +/// +/// The same holds for a frame gas detention holds: in a contract that read the block's timestamp +/// before it switched its access off, a helper whose call's memory crosses the limit is stopped +/// at its memory, before it reads its target. +/// +/// A delegator of the beneficiary is the one account a frame reads and is refused for nothing: a +/// helper holding the static gas, the cold access and the delegate's warm access reaches the +/// delegate, its target read, and its revert hands every gas back. What it can read so is the +/// accounts that delegate to the beneficiary, each of which an authorization created and paid for. +#[test] +fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { + const HELPER: Address = CHILD; + let targets = fresh_addresses(1_000); + let warm = entry(GasId::warm_storage_read_cost()); + let (helper, pushes) = calls_its_input(0); + let start = |disabled: bool| { + let code = BytecodeBuilder::default(); + if disabled { + disables_volatile_access(code) + } else { + code + } + }; + let loop_db = |disabled: bool, gas: u64| { + MemoryDatabase::default() + .account_code( + CONTRACT, + calls_the_helper_for_each(start(disabled), HELPER, &targets, Some(gas)), + ) + .account_code(HELPER, helper.clone()) + }; + + let starved = Amplification::run(loop_db(true, pushes), &targets); + let starved_on = Amplification::run(loop_db(false, pushes), &targets); + let paying = Amplification::run(loop_db(true, pushes + cold_access()), &targets); + let paying_on = Amplification::run(loop_db(false, pushes + cold_access()), &targets); + + let (crossing, _) = calls_its_input(0x32_0000); + let detained_start = disables_volatile_access(op(BytecodeBuilder::default(), TIMESTAMP)); + let detained_db = MemoryDatabase::default() + .account_code(CONTRACT, calls_the_helper_for_each(detained_start, HELPER, &targets, None)) + .account_code(HELPER, crossing); + let detained = Amplification::run(detained_db, &targets); + + let delegators = fresh_addresses(500); + let mut delegators_db = MemoryDatabase::default() + .account_code( + CONTRACT, + calls_the_helper_for_each( + start(true), + HELPER, + &delegators, + Some(pushes + cold_access() + warm), + ), + ) + .account_code(HELPER, helper.clone()); + for delegator in &delegators { + delegators_db = with_delegation(delegators_db, *delegator, BENEFICIARY); + } + let refused_reads = Amplification::run(delegators_db, &delegators); + + println!( + "amplification over {} fresh addresses: starved helper reads {} at {:?} gas each \ + (access on: {} for {} gas); paying helper reads {} at {:?} gas each (access on: {} at \ + {:?}); detained helper reads {} for {} gas; {} delegators of the beneficiary read and \ + refused at {:?} gas each", + targets.len(), + starved.reads, + starved.gas_per_read(), + starved_on.reads, + starved_on.gas, + paying.reads, + paying.gas_per_read(), + paying_on.reads, + paying_on.gas_per_read(), + detained.reads, + detained.gas, + refused_reads.reads, + refused_reads.gas_per_read(), + ); + + assert_eq!(starved.reads, 0, "a helper short of its static gas reads nothing"); + assert_eq!(starved_on.reads, 0, "with access on either"); + assert_eq!(paying.reads, targets.len(), "a helper with the cold access reads its target"); + assert_eq!(paying.reads, paying_on.reads, "as with access on"); + assert_eq!( + paying.gas - starved.gas, + paying_on.gas - starved_on.gas, + "and the reads cost with access off what they cost with access on" + ); + assert_eq!(paying.gas - starved.gas, targets.len() as u64 * cold_access(), "the cold access"); + assert_eq!(detained.reads, 0, "a helper stopped at its memory reads nothing"); + assert_eq!(refused_reads.reads, delegators.len(), "a delegator of the beneficiary is read"); + assert!(refused_reads.gas_per_read().unwrap() < cold_access(), "and refused for free"); } /// Calling `MegaAccessControl` costs the caller its call's overhead alone: the answer carries the From eb9014496db29d3b5f77fe08e39a3cbc2b161739 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 12 Nov 2026 23:57:59 +0800 Subject: [PATCH 056/190] docs: a call's beneficiary delegate is refused where the call loads it --- .claude/skills/satin-review/SKILL.md | 4 ++++ AGENTS.md | 9 ++++++--- docs/spec/upgrades/satin.md | 17 +++++++++++------ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index d34d1c0f4..bd0167f19 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -174,6 +174,10 @@ Each change is stated here in plain words with its reason; the specification has 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. +- **A call's EIP-7702 delegate is refused where the call loads it.** + With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call and reverts it, which was a debug-asserted backstop before. + A frame that cannot reach the delegate (3,100 for a cold target, 200 for a warm one, with no input and no value) runs out of gas instead of being refused for free. + Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, as with access on. ### The stop and the configuration diff --git a/AGENTS.md b/AGENTS.md index 2d256bfef..c18aeac61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -429,9 +429,12 @@ Detention caps how much a transaction may still compute once it read such data ( 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`. The state is `Detention`'s, and `MegaContext::with_volatile_access_disabled_from` is the test helper that sets it without a call. The opcode's wrapper then refuses the read before the opcode charges or checks anything (`refused_read` in `evm/instructions.rs`), and the frame reverts with `VolatileDataAccessDisabled(accessType)` on the gas it held when it reached the opcode: a refused read costs nothing, not its static gas, which the wrapper charges itself and only once the read is not refused, so a frame below the static gas is refused rather than run out of gas. - An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` included — is refused before its operands are read, so a `BLOCKHASH` on an empty stack is refused; an account, call, `SELFDESTRUCT` or Oracle read is refused only once every operand it takes is on the stack (a stack underflow stays one), when its target operand, its frame's own address (`SELFBALANCE`, `SELFDESTRUCT`), its frame's storage (`SLOAD` of the Oracle's) or a call target's one-hop EIP-7702 delegate is volatile, before its body's memory, copy, static-context or value checks. - The delegate is read for the decision (`MegaContext::call_target_delegate`): the target's account and code are loaded inside a journal mark taken back at once, so they are in the transaction's state and witness and warm nothing; the read is required, and a database error fails the transaction with its cause, never taken for a target without a delegate. - The Host's own refusal of a load stays behind it, which no opcode reaches (a debug build asserts so). + An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` included — is refused before its operands are read, so a `BLOCKHASH` on an empty stack is refused; an account, call, `SELFDESTRUCT` or Oracle read is refused only once every operand it takes is on the stack (a stack underflow stays one), when its target operand, its frame's own address (`SELFBALANCE`, `SELFDESTRUCT`) or its frame's storage (`SLOAD` of the Oracle's) is volatile, before its body's memory, copy, static-context or value checks. + A call whose target operand is not the beneficiary is refused where it loads its target's one-hop EIP-7702 delegate, which only the target's code names: it runs its steps before that load as with access on — its static gas, the static-context check of a value `CALL`, its memory, its value transfer, the load of its target's account and code, which a frame short of the cold surcharge skips as an out-of-gas, and the check that the frame holds the target's access and the delegate's warm access — and the Host refuses the delegate's load when the delegate is the beneficiary (`MegaContext::load_account_info_skip_cold_load`), before the call charges its target's access, any state gas or its forward and before the frame-start hook. + The wrapper (`settle_reads` in `evm/instructions.rs`) then reverts the frame on the gas it held when it reached the call — the spendable and withheld parts and the reservoir — so the refusal costs nothing; the frame's revert takes back the target's warming, and the target's account and code stay in the transaction's state and witness, the beneficiary unloaded and nothing marked. + A call that fails or is stopped before the target's load reads nothing, as with access on; once the load is reached it is required, and a database error fails the transaction with its cause, never taken for a target without a delegate. + So a refused call of a delegator of the beneficiary is free only from a frame that holds the gas to reach the delegate (with no input and no value, 3,100 for a cold target, 200 for a warm one); a frame holding less runs out of gas, as with access on. + The memory a refused call expanded stays expanded in the frame's buffer, its price put back with the gas, until the frame's end, which follows at once. `BLOCKHASH` names `BlockHash` (7) whatever its operand; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. The error's argument is encoded as a `uint8`, and Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value out of range, and the Rust `IMegaAccessControl` binding decodes 12 to its `__Invalid` placeholder; `decode_volatile_data_access_disabled` is the Rust side's decoder. The system contracts are not changed for it: their bytecode, and so their code hashes, stay as deployed. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 1f98384e0..3987ce238 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1005,6 +1005,7 @@ The reference implementation has no price for one, so it runs such a precompile #### Previous behavior - A read refused by `disableVolatileDataAccess()` reverts the frame immediately with `VolatileDataAccessDisabled(VolatileDataAccessType)`; `BLOCKHASH` and `BLOBHASH` are refused before their operands are checked. +- A call opcode in a frame whose access is off looks up its target's one-hop EIP-7702 delegate before it charges anything, and is refused when that delegate is the block beneficiary. - `MegaLimitControl.remainingComputeGas()` answers from a separate compute-gas ledger with per-frame budgets of 98/100 of the caller's remaining compute, and can exceed the caller's gas. #### New behavior @@ -1014,14 +1015,18 @@ The reference implementation has no price for one, so it runs such a precompile - An opcode volatile whatever its operands — `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM` and `BLOCKHASH` — MUST be refused before its operands are checked, so a `BLOCKHASH` on an empty stack is refused rather than halting on the underflow. A `BLOCKHASH` is refused as `BLOCKHASH` (7) whatever its operand. - An opcode volatile only for the account or the storage it reads — `BALANCE`, `SELFBALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four call opcodes, `SELFDESTRUCT` and an `SLOAD` of the Oracle's storage — MUST first have every operand it takes on the stack: one that fails on its operands (a stack underflow, for example) fails as it would with access on. - Once its operands are there, it MUST be refused when what it reads is the beneficiary's account or the Oracle's storage, as its operands and its frame show it: the target operand of `BALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH` or a call opcode, or a call target's one-hop EIP-7702 delegate; the executing frame's own address for `SELFBALANCE`, and for `SELFDESTRUCT`, whose target operand is checked too; the frame's storage for an `SLOAD`. + Once its operands are there, it MUST be refused when what its operands and its frame name is the beneficiary's account or the Oracle's storage: the target operand of `BALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH` or a call opcode; the executing frame's own address for `SELFBALANCE`, and for `SELFDESTRUCT`, whose target operand is checked too; the frame's storage for an `SLOAD`. The refusal comes before the opcode charges anything and before any other check its body makes — a memory expansion, a copy, a static-context check, a value transfer, a state charge — so an `EXTCODECOPY` of the beneficiary with a large length, or a call to it the frame could not fund, is refused rather than running out of gas. Either refusal comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. -- A call opcode whose target's EIP-7702 delegate is the block beneficiary MUST be refused as the beneficiary's account (10): in a frame whose access is off, the opcode reads its target's account and code — not the delegate's — to find the delegate, one hop, before it charges anything, unless the target is itself the beneficiary. - That read lands in the transaction's read set but makes neither account warm, so a call it does not refuse is priced as it would be with access on. - The read is required: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. +- A call opcode whose target operand is not the block beneficiary MUST run, in a frame whose access is off, the steps it runs with access on before it loads its target's one-hop EIP-7702 delegate: its static gas, the static-context check of a value-bearing `CALL`, its input and output memory, its value transfer, the load of its target's account and code — skipped as an out-of-gas when the target is cold and the frame's regular gas, its withheld part included, is below the cold surcharge — and, for a target that holds a delegation, the check that the frame holds the target's access and the delegate's warm access. + A call that fails on one of those steps, or that gas detention stops on one, fails or is stopped as it would be with access on, and reads its target only when it reached the target's load. + When the call reaches the load of the delegate and the delegate is the block beneficiary, the load MUST be refused as the beneficiary's account (10): the beneficiary's account is not loaded, nothing is marked for gas detention, and the frame reverts with `VolatileDataAccessDisabled(10)` on the gas it held when it reached the call, everything the call charged before the load taken back. + The target's account and code stay in the transaction's read set, and the frame's revert leaves the target as warm or as cold as it was for the caller. + The target's load is a required read: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. + So a call of a delegator of the beneficiary with no input and no value is refused for nothing from a frame holding its static gas, the target's cold surcharge when the target is cold, and the delegate's warm access — 3,100 for a cold target, 200 for a warm one — and a frame holding less runs out of gas: holding 2,999 at a call of a cold delegator, before its target is read; holding 3,050, after. - A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. - The frame reverts on the gas it held when it reached the opcode, nothing having been charged, and a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, is refused all the same and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. + The frame reverts on the gas it held when it reached the opcode — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged. + A read refused before the opcode's body, which is every refusal but a call's at its target's delegate, is refused all the same in a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. A refused read marks nothing for gas detention and asks no oracle service. - The error's argument MUST be ABI-encoded as a `uint8`: @@ -1445,7 +1450,7 @@ The witness is defined by what the block's execution returns and exports, and a A failed read is reported as [Transaction and Block Refusals](#21-transaction-and-block-refusals) classifies it: the fee computation's as a read of the transaction's own execution, the footprint scalar's as a read block execution makes for the transaction outside its execution, always an internal error. The reads change nothing: the entries are not written. - **The reads a validator makes again.** - A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, other than an Oracle read, which is made before its cold access is charged (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), a `BLOCKHASH` of the current block or outside the last 256 blocks, a read a frame whose volatile-data access is off is refused, a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. + A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, other than an Oracle read, which is made before its cold access is charged (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), a `BLOCKHASH` of the current block or outside the last 256 blocks, a read a frame whose volatile-data access is off is refused (the target of a call refused at its EIP-7702 delegate is no refused read: the call loads it before the refusal, and the witness carries it), a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. - **The SALT buckets.** Block execution exports the set of SALT buckets the SALT environment answered with a valid capacity during the block, emptied when the block starts and accumulated over everything executed for the block. A bucket is in the set once it was answered with a valid capacity, whether or not the transaction that asked is in the block: a candidate the builder executed and dropped leaves its buckets in the set, which a validator does not need. From 29c58794e61802966bfae307ef108424589da1f4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 09:56:47 +0800 Subject: [PATCH 057/190] feat(evm): a call refused at its beneficiary delegate pays its target's access With volatile-data access off, a call whose target delegates to the block beneficiary has read its target's account and code by the time the Host refuses the delegate's load. That read is no volatile read, so the frame now pays the target's own access, as `BALANCE` does: the warm access, then the cold surcharge when the target was cold before the call, each a regular charge of the spendable part. Nothing else of the call is paid: its memory, its value transfer and the delegate's access are still taken back. A cold surcharge past what gas detention lets the frame spend is the compute stop, as for `BALANCE`; the frame's whole regular gas always covers both charges, since the call held them to reach the delegate. Every other refusal still costs nothing. The Host notes whether each account a read wrapper's opcode loads in an access-off frame was cold (`Detention::note_load`), for the running opcode only: the wrapper clears the note when the opcode begins and the transaction's reset clears it, and only a refusal at a delegate reads it. Without the charge, the accounts that delegate to the beneficiary could each be read into the witness for about 181 gas, and as the beneficiary stays the same from block to block, every such account stays usable. With it, a read of one costs the cold access, as a read of any other account does. Tests: the cold, warm and value-call boundaries now pay 3,000 or 100 on a refusal; the restoration test expects the gas at the call less the access; a new test holds a detained frame's spendable gas at 99, 100, 200, 2,999 and 3,000 (stop at the static gas, stop at the surcharge, refusal) and checks the gas handed back; another shows a refusal pays for its own target only, across opcodes and transactions; the amplification loop over 500 delegators now pays the cold access per read, the delegate's warm access less than with access on. --- crates/mega-evm/src/access/detention.rs | 59 ++++ crates/mega-evm/src/access/mod.rs | 16 +- crates/mega-evm/src/evm/host.rs | 10 +- crates/mega-evm/src/evm/instructions.rs | 43 ++- .../mega-evm/tests/satin/volatile_access.rs | 255 ++++++++++++++---- 5 files changed, 316 insertions(+), 67 deletions(-) diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 923925cea..826383948 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -186,6 +186,10 @@ pub struct Detention { observed: Cell, /// What the Host refused to load for the running opcode, waiting for its wrapper. refused: Cell, + /// Whether the last account the Host loaded for the running opcode, in a frame whose reads + /// are refused, was cold, or `None` while it loaded none: for a call the Host refused at its + /// target's EIP-7702 delegate, the target, whose access the refusal charges. + loaded_cold: Option, /// Whether the wrapper of an opcode that reads volatile data runs it: the Host refuses and /// marks a load only then. reading: bool, @@ -219,6 +223,7 @@ impl Detention { pub(crate) fn reset(&mut self, block_env_cap: u64, oracle_cap: u64) { self.observed.set(VolatileDataAccess::empty()); self.refused.set(VolatileDataAccess::empty()); + self.loaded_cold = None; self.reading = false; self.block_env_cap = (block_env_cap != u64::MAX).then_some(block_env_cap); self.oracle_cap = (oracle_cap != u64::MAX).then_some(oracle_cap); @@ -292,6 +297,16 @@ impl Detention { } } + /// Notes that the Host loaded an account that is no volatile read for the running read + /// wrapper's opcode, cold or warm, in a frame whose reads are refused: a call the Host then + /// refuses at its target's delegate charges its target's access by it. + #[inline] + pub(crate) const fn note_load(&mut self, is_cold: bool) { + if self.refusing && self.reading { + self.loaded_cold = Some(is_cold); + } + } + /* The opcode wrappers */ /// Whether the running frame's volatile reads are refused, so its opcodes must keep the gas @@ -309,6 +324,7 @@ impl Detention { #[inline] pub(crate) fn begin_read(&mut self) { debug_assert!(!self.has_reads(), "a read left over from before the opcode"); + self.loaded_cold = None; self.reading = true; } @@ -330,6 +346,12 @@ impl Detention { (!refused.is_empty()).then_some(refused) } + /// Takes whether the last account the Host loaded for the running opcode, in a frame whose + /// reads are refused, was cold, if it loaded one ([`note_load`](Self::note_load)). + pub(crate) const fn take_loaded_cold(&mut self) -> Option { + self.loaded_cold.take() + } + /// Takes what the Host observed for the running opcode. pub(crate) fn take_observed(&self) -> VolatileDataAccess { self.observed.replace(VolatileDataAccess::empty()) @@ -1278,6 +1300,43 @@ mod tests { assert_eq!(detention.take_refused(), Some(beneficiary)); } + /// Whether the account the Host loaded was cold is noted only for a read wrapper's opcode in a + /// frame whose access is off, the last load's, and only for that opcode: the next opcode's + /// wrapper and the next transaction start with none, and it is taken once. + #[test] + fn test_a_noted_load_is_the_running_opcodes_last() { + let mut detention = detaining(); + let mut frame = gas(1_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.begin_read(); + detention.note_load(true); + detention.end_read(); + assert_eq!(detention.take_loaded_cold(), None, "access on: nothing is noted"); + + detention.disable_access(0); + detention.on_frame_run(&mut frame, 0); + detention.note_load(true); + assert_eq!(detention.take_loaded_cold(), None, "outside a read: nothing is noted"); + detention.begin_read(); + detention.note_load(true); + detention.note_load(false); + detention.end_read(); + assert_eq!(detention.take_loaded_cold(), Some(false), "the last load's"); + assert_eq!(detention.take_loaded_cold(), None, "taken once"); + + detention.begin_read(); + detention.note_load(true); + detention.end_read(); + detention.begin_read(); + detention.end_read(); + assert_eq!(detention.take_loaded_cold(), None, "the next opcode starts with none"); + + detention.begin_read(); + detention.note_load(true); + detention.reset(BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + assert_eq!(detention.take_loaded_cold(), None, "the next transaction starts with none"); + } + /// A refusal's revert data decodes back to the kind it names, for every kind the engine /// names, the slot number's access type 12 included, which the contract's own ABI type cannot /// name. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index edd263170..157499ccb 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -186,11 +186,17 @@ //! that delegate, since only the target's code shows it: the call runs its steps before that load //! as with access on — its static gas, its memory, its value transfer, the load of its target, //! which a frame short of the cold access skips as an out-of-gas — and the Host refuses the -//! delegate's load. The frame then reverts on the gas it held when it reached the call, as for any -//! refusal, so the call reads its target only once it holds the gas for it, as with access on, and -//! a frame that cannot reach the delegate fails as it would with access on. A refusal -//! names the kind the opcode reads — `BLOCKHASH`'s names the hash, whatever its operand — and a -//! `SLOTNUM` refusal names access type 12 +//! delegate's load. The call has read its target by then, which is no volatile read, and pays for +//! it as an account opcode would: the frame reverts on the gas it held when it reached the call +//! less the target's access — the warm access, and the cold surcharge when the target was cold +//! before the call — as two regular charges, so a cold surcharge past what gas detention lets the +//! frame spend stops it with the compute stop instead. Nothing else of the call is paid: not its +//! memory, its value transfer or the delegate's access. So the call reads its target only once it +//! holds the gas for it, and pays a cold target's cold access, as with access on, and a frame that +//! cannot reach the delegate fails as it would with access on. Every other refusal costs nothing. +//! +//! A refusal names the kind the opcode reads — `BLOCKHASH`'s names the hash, whatever its operand +//! — and a `SLOTNUM` refusal names access type 12 //! ([`SLOT_NUM_ACCESS_TYPE`](crate::system::SLOT_NUM_ACCESS_TYPE)), which the contract's //! `VolatileDataAccessType` does not declare. The error's argument is encoded as a `uint8`, and //! Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index db81261f4..8d4332cd7 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -32,7 +32,9 @@ //! delegate, which only the target's code names: when the delegate is the beneficiary, the Host //! refuses it. A refused account or storage load fails as a skipped cold load, and a refused //! block-environment accessor answers zero. Nothing is loaded, and the opcode's wrapper turns the -//! refusal into the frame's revert, on the gas the frame held when it reached the opcode. +//! refusal into the frame's revert, on the gas the frame held when it reached the opcode, less, for +//! a call refused at its target's delegate, the target's access: the Host notes whether the target +//! was cold when it loads it. //! //! # The Oracle's storage //! @@ -230,7 +232,9 @@ impl revm::context_interface::Host /// 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)). + /// no reads (see [`Detention`](crate::Detention)). Of any other account a read wrapper's + /// opcode loads in a frame whose access is off, it notes whether it was cold: a call whose + /// delegate it then refuses pays its target's access by it. #[inline] fn load_account_info_skip_cold_load( &mut self, @@ -246,6 +250,8 @@ impl revm::context_interface::Host self.inner.load_account_info_skip_cold_load(address, load_code, skip_cold_load)?; if beneficiary { self.detention.observe(VolatileDataAccess::BENEFICIARY_BALANCE); + } else { + self.detention.note_load(load.is_cold); } Ok(load) } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 86cea6de5..53cd5100a 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -46,9 +46,10 @@ //! does not look it up: the call runs its own steps as with access on — its static gas, its //! memory, its value transfer, the load of its target, which a frame short of the cold access //! skips as an out-of-gas — and the Host refuses the load of the delegate when it is the -//! beneficiary. The wrapper then puts back the gas the frame held when it reached the call and -//! reverts the frame, so the refusal costs nothing, and the call reads its target only once it -//! holds the gas to, as with access on. +//! beneficiary. The wrapper then puts back the gas the frame held when it reached the call, +//! charges the target's access the call read it for, warm then cold, as an account opcode does, +//! and reverts the frame: the call reads its target only once it holds the gas to, and pays a cold +//! target's cold access, as with access on, and the refused read itself costs nothing. //! //! The Oracle's `SLOAD` is the one read made before any of its gas is charged: the slot is loaded, //! the oracle service asked and the read marked, at the compute before the opcode, and only then @@ -190,7 +191,7 @@ pub(crate) fn without_read_static_gas(mut table: GasTable) -> GasTable { /// `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; /// with access off, refused for the callee before the call charges anything, and for the delegate -/// where the call loads it. +/// where the call loads it, the callee's access paid. fn call( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { @@ -206,8 +207,8 @@ fn call( /// the opcode's static gas is charged, as its own charge, as the interpreter charges every other /// opcode's, and `inner` runs; a read the opcode completed is committed, capping the frame at what /// the compute limit leaves it, and a load the Host refused — a call's EIP-7702 delegate that is -/// the beneficiary — reverts the frame on the gas it held when it reached the opcode -/// ([`settle_reads`]). +/// the beneficiary — reverts the frame on the gas it held when it reached the opcode, less the +/// access of the target the call loaded ([`settle_reads`]). /// /// A read the opcode did not complete — the opcode failed after the load — is dropped: it reached /// no computation, and the frame is failing anyway. @@ -312,12 +313,19 @@ fn refused_read( /// beneficiary. The call has then run its steps before the load — its static gas, its memory, its /// value transfer, the load of its target — and fails the load as a skipped cold load, before it /// charges its target's access, any state gas or its forward, and before the frame-start hook, so -/// what it did is all in the frame's gas and memory. The frame is refused on the gas it held when -/// it reached the opcode (`gas`), the spendable and withheld parts and the reservoir as they were, -/// which takes back every charge; its revert takes back the target's warming, and leaves the -/// target's account and code in the transaction's state. The memory the call expanded stays -/// expanded until the frame's end, which follows at once; the gas's record of it is put back with -/// the rest. +/// what it did is all in the frame's gas and memory. The frame's gas is put back to what it held +/// when it reached the opcode (`gas`), the spendable and withheld parts and the reservoir as they +/// were, which takes back every charge; the memory the call expanded stays expanded until the +/// frame's end, which follows at once, and the gas's record of it is put back with the rest. +/// +/// The call read its target's account and code, which is no volatile read, so it pays the +/// target's access as `BALANCE` does: the warm access, then, when the Host found the target cold, +/// the cold surcharge, each a regular charge of the spendable part. A frame whose spendable part +/// cannot pay the surcharge holds it in its withheld part — the call held its target's access and +/// the delegate's warm access to reach the delegate — so the charge is gas detention's crossing, +/// and the frame ends with the compute stop rather than the refusal. Otherwise it is refused: its +/// revert takes back the target's warming, and leaves the target's account and code in the +/// transaction's state. #[inline(never)] fn settle_reads( interpreter: &mut Interpreter, @@ -333,6 +341,17 @@ fn settle_reads( if let Some(gas) = gas { interpreter.gas = gas; } + // The call read its target, which is no volatile read, so it pays the target's access as + // revm's account opcodes do, warm then cold, which gas detention may stop at. + if let Some(cold) = host.detention.take_loaded_cold() { + let params = host.gas_params(); + let surcharge = if cold { params.cold_account_additional_cost() } else { 0 }; + for cost in [params.warm_storage_read_cost(), surcharge] { + if !interpreter.gas.record_regular_cost(cost) { + return Err(InstructionResult::OutOfGas); + } + } + } return Err(refuse(interpreter, refused)); } let completed = match result { diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 22a4f98c4..c75022745 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -840,18 +840,19 @@ fn test_a_direct_call_of_the_beneficiary_is_refused_below_its_static_gas() { /// static gas, then the load of its target, which a frame short of the cold surcharge does not /// make, then the check that it holds its target's access with the delegate's warm access on top. /// A frame holding 2,999 at the `STATICCALL` runs out of gas without reading the delegator; one -/// holding 3,050 reads it and runs out of gas at that check; one holding 3,100 reaches the -/// delegate and is refused, spending nothing of the call. Either way the frame's end leaves the -/// delegator cold for its caller, whose `BALANCE` of it pays the cold access, and nothing reads -/// the beneficiary. +/// holding 3,000 or 3,050 reads it and runs out of gas at that check; one holding 3,100 reaches +/// the delegate and is refused, paying the delegator's cold access, 3,000, and nothing else of the +/// call, so 100 goes back to its caller. Either way the frame's end leaves the delegator cold for +/// its caller, whose `BALANCE` of it pays the cold access, and nothing reads the beneficiary. #[test] -fn test_a_cold_delegator_of_the_beneficiary_is_refused_at_its_delegate() { +fn test_a_cold_delegator_of_the_beneficiary_is_refused_for_its_cold_access() { let warm = entry(GasId::warm_storage_read_cost()); let surcharge = entry(GasId::cold_account_additional_cost()); let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); // (what the child holds at the call, whether it is refused, whether it reads the delegator) for (left, is_refused, reads) in [ (warm + surcharge - 1, false, false), + (warm + surcharge, false, true), (warm + surcharge + warm / 2, false, true), (warm + surcharge + warm, true, true), ] { @@ -870,7 +871,7 @@ fn test_a_cold_delegator_of_the_beneficiary_is_refused_at_its_delegate() { if is_refused { let refusal = refused(VolatileDataAccess::BENEFICIARY_BALANCE); assert_eq!((result, output), refusal, "{case}"); - assert_eq!(spent, pushes, "{case}: the refusal spends nothing of the call"); + assert_eq!(spent, pushes + cold_access(), "{case}: the refusal pays the access"); } else { assert_eq!(result, InstructionResult::OutOfGas, "{case}"); assert_eq!(spent, pushes + left, "{case}: the halt burns what the frame held"); @@ -886,12 +887,25 @@ fn test_a_cold_delegator_of_the_beneficiary_is_refused_at_its_delegate() { } } +/// A transaction from `CALLER` to `to` whose access list warms `listed`. +fn listing(to: Address, listed: Address, gas_limit: u64) -> MegaTransaction { + alloy_op_evm::OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(to), + gas_limit, + access_list: AccessList(vec![AccessListItem { address: listed, storage_keys: vec![] }]), + ..Default::default() + })) +} + /// A delegator of the beneficiary the transaction's access list warms is loaded with no cold /// surcharge, so the call reaches its delegate with the static gas and the delegate's warm access: /// a frame holding 199 at the `STATICCALL` runs out of gas at the check that it holds them, and -/// one holding 200 is refused, spending nothing of the call. +/// one holding 200 is refused, paying the delegator's warm access, 100, and nothing else of the +/// call, so 100 goes back to its caller. #[test] -fn test_a_warm_delegator_of_the_beneficiary_is_refused_with_the_gas_for_its_delegate() { +fn test_a_warm_delegator_of_the_beneficiary_is_refused_for_its_warm_access() { let warm = entry(GasId::warm_storage_read_cost()); let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); for (left, is_refused) in [(2 * warm - 1, false), (2 * warm, true)] { @@ -901,18 +915,7 @@ fn test_a_warm_delegator_of_the_beneficiary_is_refused_with_the_gas_for_its_dele calls_child(BytecodeBuilder::default(), Some(pushes + left)).stop().build(), ) .account_code(CHILD, child.clone()); - let listed = alloy_op_evm::OpTx(op_transaction(TxEnv { - tx_type: TransactionType::Eip2930 as u8, - caller: CALLER, - kind: TxKind::Call(CONTRACT), - gas_limit: BELOW, - access_list: AccessList(vec![AccessListItem { - address: DELEGATOR, - storage_keys: vec![], - }]), - ..Default::default() - })); - let (run, result, output, spent) = run_child(db, listed); + let (run, result, output, spent) = run_child(db, listing(CONTRACT, DELEGATOR, BELOW)); assert!(run.outcome.result.is_success(), "{left}: {:?}", run.outcome.result); if is_refused { assert_eq!( @@ -920,7 +923,7 @@ fn test_a_warm_delegator_of_the_beneficiary_is_refused_with_the_gas_for_its_dele refused(VolatileDataAccess::BENEFICIARY_BALANCE), "{left}" ); - assert_eq!(spent, pushes, "{left}"); + assert_eq!(spent, pushes + warm, "{left}: the warm access"); } else { assert_eq!(result, InstructionResult::OutOfGas, "{left}"); assert_eq!(spent, pushes + left, "{left}"); @@ -932,9 +935,10 @@ fn test_a_warm_delegator_of_the_beneficiary_is_refused_with_the_gas_for_its_dele /// delegator of the beneficiary with an input of 1 MiB, from a frame holding 5,000, runs out of /// gas on its memory without reading the delegator. A value `CALL` of it from a frame that cannot /// fund the value pays its value transfer, then loads its target: holding 14,400 — the static gas, -/// the transfer, the cold access and the delegate's warm access — it is refused before revm checks -/// the caller's balance, spending nothing of the call; holding one less, it reads the delegator -/// and runs out of gas at the check that it holds the delegate's access. +/// the transfer, the cold access and the delegate's warm access — or 15,000, it is refused before +/// revm checks the caller's balance, paying the delegator's cold access and not the transfer; +/// holding one less than 14,400, it reads the delegator and runs out of gas at the check that it +/// holds the delegate's access. #[test] fn test_a_calls_memory_and_value_transfer_come_before_its_target_is_read() { let (callcode, pushes) = call_of(CALLCODE, DELEGATOR, 0, 0x10_0000); @@ -953,7 +957,7 @@ fn test_a_calls_memory_and_value_transfer_come_before_its_target_is_read() { let warm = entry(GasId::warm_storage_read_cost()); let reach = warm + value_transfer() + entry(GasId::cold_account_additional_cost()) + warm; let (value_call, pushes) = call_of(CALL, DELEGATOR, 1, 0); - for (left, is_refused) in [(reach, true), (reach - 1, false)] { + for (left, is_refused) in [(15_000, true), (reach, true), (reach - 1, false)] { let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) .account_code( CONTRACT, @@ -968,7 +972,7 @@ fn test_a_calls_memory_and_value_transfer_come_before_its_target_is_read() { refused(VolatileDataAccess::BENEFICIARY_BALANCE), "{left}" ); - assert_eq!(spent, pushes, "{left}: the transfer is not charged"); + assert_eq!(spent, pushes + cold_access(), "{left}: the access, not the transfer"); } else { assert_eq!((result, spent), (InstructionResult::OutOfGas, pushes + left), "{left}"); } @@ -1004,13 +1008,15 @@ fn test_a_detained_memory_crossing_reads_no_call_target() { } /// Records, for the first call opcode `CHILD`'s frame runs, the frame's gas and memory size when -/// it reaches the opcode and once the opcode returned, and how the frame ended. -#[derive(Default)] +/// it reaches the opcode and once the opcode returned, and how the frame ended and the gas it +/// handed back. +#[derive(Clone, Default)] struct AtTheCall { pending: bool, before: Option<(Gas, usize)>, after: Option<(Gas, usize)>, child: Option<(InstructionResult, Bytes)>, + returned: Option, } impl Inspector, EthInterpreter> for AtTheCall { @@ -1043,23 +1049,25 @@ impl Inspector, EthInterpreter> for AtTheCal ) { if inputs.target_address == CHILD { self.child = Some((outcome.result.result, outcome.result.output.clone())); + self.returned = Some(outcome.result.gas.remaining()); } } } -/// A call refused at its delegate takes back everything it did before the load, so its frame -/// reverts on exactly the gas it held when it reached the call. A value `CALL` of a cold delegator -/// of the beneficiary, with an input of 64 KiB, from a frame that cannot fund the value, has paid -/// its static gas, its memory and its value transfer and loaded its target when the load of its -/// delegate is refused: the frame's gas once the opcode returned is its gas before it — the -/// spendable and withheld parts, the reservoir and the memory's price. The frame-start hook has not -/// run, so the transaction keeps no state or history gas but its body's and opens no start beyond -/// its two frames'. The revert leaves the delegator cold for the caller, whose `BALANCE` of it -/// pays the cold access, and the refusal marks nothing for gas detention: in a -/// transaction a read of the timestamp detained first, the refusal leaves its limit and its reads -/// as they were. The same holds above the execution cap, where the frame holds a reservoir. +/// A call refused at its delegate takes back everything it did before the load but its target's +/// access, so its frame reverts on the gas it held when it reached the call less that access. A +/// value `CALL` of a cold delegator of the beneficiary, with an input of 64 KiB, from a frame that +/// cannot fund the value, has paid its static gas, its memory and its value transfer and loaded +/// its target when the load of its delegate is refused: the frame's gas once the opcode returned +/// is its gas before it — the spendable and withheld parts, the reservoir and the memory's price — +/// with the cold access, 3,000, charged to its regular gas. The frame-start hook has not run, so +/// the transaction keeps no state or history gas but its body's and opens no start beyond its two +/// frames'. The revert leaves the delegator cold for the caller, whose `BALANCE` of it pays the +/// cold access, and the refusal marks nothing for gas detention: in a transaction a read of the +/// timestamp detained first, the refusal leaves its limit and its reads as they were. The same +/// holds above the execution cap, where the frame holds a reservoir. #[test] -fn test_a_refusal_at_the_delegate_takes_back_everything_the_call_did() { +fn test_a_refusal_at_the_delegate_takes_back_everything_but_the_targets_access() { let (child, _) = call_of(CALL, DELEGATOR, 1, 0x1_0000); for gas_limit in TIERS { for detained in [false, true] { @@ -1087,7 +1095,9 @@ fn test_a_refusal_at_the_delegate_takes_back_everything_the_call_did() { "{case}" ); let (before, after) = (inspector.before.unwrap(), inspector.after.unwrap()); - assert_eq!(after.0, before.0, "{case}: the frame's gas, as it reached the call"); + let mut expected = before.0; + assert!(expected.record_regular_cost(cold_access()), "{case}"); + assert_eq!(after.0, expected, "{case}: the frame's gas at the call, less the access"); if gas_limit == ABOVE { assert!(before.0.reservoir() > 0, "{case}: the frame holds a reservoir"); } @@ -1110,6 +1120,133 @@ fn test_a_refusal_at_the_delegate_takes_back_everything_the_call_did() { } } +/// Runs a transaction whose own frame reads the block's timestamp and then calls `CHILD`, holding +/// 5,200 at its first call opcode, of which it may spend `spendable`, with access off from `CHILD` +/// down. Returns the run and what [`AtTheCall`] recorded. The cap is derived from a run under +/// another, which detains the child too: the child's spendable gas at the call is the cap less what +/// the transaction computed since its read. +fn run_detained_child(child: &Bytes, pushes: u64, spendable: u64, warm: bool) -> (Run, AtTheCall) { + const WHOLE: u64 = 5_200; + // The parent stops once the call returned, which costs nothing of what the limit leaves it. + let parent = op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0; 5]) + .push_address(CHILD) + .push_number(pushes + WHOLE) + .append(CALL) + .stop() + .build(); + let run_under = |cap: u64| { + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child.clone()); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let ctx = context(db).with_tx_runtime_limits(limits).with_volatile_access_disabled_from(1); + let mut evm = MegaEvm::new(ctx).with_inspector(AtTheCall::default()); + let tx = + if warm { listing(CONTRACT, DELEGATOR, BELOW) } else { tx(CALLER, CONTRACT, BELOW) }; + let run = run_on(&mut evm, tx); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let at_the_call = evm.inspector().clone(); + (run, at_the_call) + }; + let held = |at_the_call: &AtTheCall| { + let gas = at_the_call.before.expect("the child reached its call").0; + (gas.remaining() - gas.tracker().withheld(), gas.remaining()) + }; + // The call the transaction's own frame makes, a cold one, fits under it, and what the child may + // spend at its call is below what it holds. + let first = cold_access() + WHOLE / 2; + let (_, at_the_call) = run_under(first); + let (first_spendable, _) = held(&at_the_call); + assert!(first_spendable < WHOLE, "the first run detains the child: {first_spendable}"); + let (run, at_the_call) = run_under(first - first_spendable + spendable); + assert_eq!(held(&at_the_call), (spendable, WHOLE), "what the child holds at the call"); + (run, at_the_call) +} + +/// Gas detention applies to the access a refusal at a delegate pays as to any account opcode's: the +/// warm access first, then the cold surcharge, each a regular charge of the spendable part. A +/// `STATICCALL` of a delegator of the beneficiary, from a frame holding 5,200 of which it may spend +/// a part, is stopped at its static gas when it may spend 99, having read nothing, and hands back +/// all 5,200. With a cold delegator, the frame that may spend from 100 to 2,999 reaches the +/// delegate, its target read, and is stopped at the cold surcharge with `MegaLimitExceeded(2, +/// limit)`, handing back 5,100; one that may spend 3,000 is refused, paying the cold access, and +/// hands back 2,200. With a delegator the access list warms, one that may spend 100 is refused, +/// paying the warm access, and hands back 5,100. +#[test] +fn test_a_refusal_at_the_delegate_pays_the_targets_access_within_the_compute_limit() { + let warm = entry(GasId::warm_storage_read_cost()); + let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); + // (whether the access list warms the delegator, what the child may spend, whether it is + // refused rather than stopped, what it hands back, whether it reads the delegator) + for (listed, spendable, is_refused, returned, reads) in [ + (false, warm - 1, false, 5_200, false), + (false, warm, false, 5_200 - warm, true), + (false, 2 * warm, false, 5_200 - warm, true), + (false, cold_access() - 1, false, 5_200 - warm, true), + (false, cold_access(), true, 5_200 - cold_access(), true), + (true, warm - 1, false, 5_200, false), + (true, warm, true, 5_200 - warm, true), + ] { + let case = format!("listed {listed}, spendable {spendable}"); + let (run, at_the_call) = run_detained_child(&child, pushes, spendable, listed); + let limit = run.limit.expect("the timestamp detains"); + let ending = if is_refused { + refused(VolatileDataAccess::BENEFICIARY_BALANCE) + } else { + (InstructionResult::Revert, stop_data(limit)) + }; + assert_eq!(at_the_call.child, Some(ending), "{case}"); + assert_eq!(at_the_call.returned, Some(returned), "{case}: handed back"); + assert_eq!(run.outcome.state.contains_key(&DELEGATOR), reads, "{case}: read"); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP, "{case}"); + } +} + +/// Contracts that load an account no transaction here funds, then do something else. +const LOADS_THEN_CALLS: Address = address!("0000000000000000000000000000000000d00006"); +const LOADS_THEN_READS_THE_TIME: Address = address!("0000000000000000000000000000000000d00007"); +const LOADS: Address = address!("0000000000000000000000000000000000d00008"); + +/// A refusal at a delegate pays for the target its own call loaded, and for no account an earlier +/// opcode or transaction loaded. With access off from the transaction's own frame, on one EVM: +/// a frame that loads a cold account and stops leaves nothing for the next transaction, whose +/// `TIMESTAMP` after the same load is refused for nothing; and a `STATICCALL` of a delegator of the +/// beneficiary the access list warms, after the same cold load in its own frame, pays the warm +/// access, 100, not the cold one. +#[test] +fn test_a_refusal_at_the_delegate_pays_for_its_own_target_alone() { + let loads = || BytecodeBuilder::default().push_address(UNTOUCHED).append_many([BALANCE, POP]); + let load = 3 + cold_access() + 2; + let (call, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); + let then_calls: Bytes = [loads().build().as_ref(), call.as_ref()].concat().into(); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(LOADS, loads().stop().build()) + .account_code(LOADS_THEN_READS_THE_TIME, loads().append(TIMESTAMP).stop().build()) + .account_code(LOADS_THEN_CALLS, then_calls); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(0)) + .with_inspector(Calls::default()); + let mut last = |tx: MegaTransaction| { + let run = run_on(&mut evm, tx); + let frame = evm.inspector().calls.last().expect("the transaction's own frame"); + (run, frame.result, frame.output.clone(), frame.spent) + }; + + let (run, result, _, spent) = last(tx(CALLER, LOADS, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!((result, spent), (InstructionResult::Stop, load)); + + let (_, result, output, spent) = last(tx(CALLER, LOADS_THEN_READS_THE_TIME, BELOW)); + assert_eq!((result, output), refused(VolatileDataAccess::TIMESTAMP)); + assert_eq!(spent, load, "a direct refusal pays nothing"); + + let _ = last(tx(CALLER, LOADS, BELOW)); + let warm = entry(GasId::warm_storage_read_cost()); + let (_, result, output, spent) = last(listing(LOADS_THEN_CALLS, DELEGATOR, BELOW)); + assert_eq!((result, output), refused(VolatileDataAccess::BENEFICIARY_BALANCE)); + assert_eq!(spent, load + pushes + warm, "the warm target's access"); +} + /// With access off, a call's target is a required read once the call reaches its load, and no /// read before: a `CALLCODE` of a delegator of the beneficiary that holds the gas to reach its /// target gives the transaction no outcome when the target's account or code cannot be read, @@ -1275,10 +1412,11 @@ impl Amplification { /// before it switched its access off, a helper whose call's memory crosses the limit is stopped /// at its memory, before it reads its target. /// -/// A delegator of the beneficiary is the one account a frame reads and is refused for nothing: a -/// helper holding the static gas, the cold access and the delegate's warm access reaches the -/// delegate, its target read, and its revert hands every gas back. What it can read so is the -/// accounts that delegate to the beneficiary, each of which an authorization created and paid for. +/// A delegator of the beneficiary is read for its access too: a helper holding the static gas, the +/// cold access and the delegate's warm access reaches the delegate and is refused, paying the +/// delegator's cold access, and its revert hands back the delegate's warm access alone. Each read +/// costs the loop the cold access, as with access on, where the call goes on to the delegate and +/// spends its warm access too. #[test] fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { const HELPER: Address = CHILD; @@ -1329,13 +1467,23 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { for delegator in &delegators { delegators_db = with_delegation(delegators_db, *delegator, BENEFICIARY); } - let refused_reads = Amplification::run(delegators_db, &delegators); + let refused_reads = Amplification::run(delegators_db.clone(), &delegators); + let delegators_on_db = delegators_db.account_code( + CONTRACT, + calls_the_helper_for_each( + start(false), + HELPER, + &delegators, + Some(pushes + cold_access() + warm), + ), + ); + let delegators_on = Amplification::run(delegators_on_db, &delegators); println!( "amplification over {} fresh addresses: starved helper reads {} at {:?} gas each \ (access on: {} for {} gas); paying helper reads {} at {:?} gas each (access on: {} at \ {:?}); detained helper reads {} for {} gas; {} delegators of the beneficiary read and \ - refused at {:?} gas each", + refused at {:?} gas each (access on: {} at {:?})", targets.len(), starved.reads, starved.gas_per_read(), @@ -1349,6 +1497,8 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { detained.gas, refused_reads.reads, refused_reads.gas_per_read(), + delegators_on.reads, + delegators_on.gas_per_read(), ); assert_eq!(starved.reads, 0, "a helper short of its static gas reads nothing"); @@ -1363,7 +1513,16 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { assert_eq!(paying.gas - starved.gas, targets.len() as u64 * cold_access(), "the cold access"); assert_eq!(detained.reads, 0, "a helper stopped at its memory reads nothing"); assert_eq!(refused_reads.reads, delegators.len(), "a delegator of the beneficiary is read"); - assert!(refused_reads.gas_per_read().unwrap() < cold_access(), "and refused for free"); + assert_eq!(delegators_on.reads, delegators.len(), "as with access on"); + assert!(refused_reads.gas_per_read().unwrap() > cold_access(), "for its cold access"); + // The two loops differ only in the call that switches access off, which the starved loops + // measure. + let disabling = starved.gas - starved_on.gas; + assert_eq!( + delegators_on.gas + disabling - refused_reads.gas, + delegators.len() as u64 * warm, + "for what it costs with access on, but the delegate's warm access" + ); } /// Calling `MegaAccessControl` costs the caller its call's overhead alone: the answer carries the From 7fe409fff229f150ab3f673c7e8fa2905df025f0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 09:56:47 +0800 Subject: [PATCH 058/190] docs: a call refused at its beneficiary delegate pays its target's access --- .claude/skills/satin-review/SKILL.md | 8 ++++---- AGENTS.md | 7 +++++-- docs/spec/upgrades/satin.md | 18 ++++++++++++------ 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index bd0167f19..1907b0354 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -174,10 +174,10 @@ Each change is stated here in plain words with its reason; the specification has 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. -- **A call's EIP-7702 delegate is refused where the call loads it.** - With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call and reverts it, which was a debug-asserted backstop before. - A frame that cannot reach the delegate (3,100 for a cold target, 200 for a warm one, with no input and no value) runs out of gas instead of being refused for free. - Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, as with access on. +- **A call's EIP-7702 delegate is refused where the call loads it, and the call pays its target's access.** + With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call, charges the target's own access — 100, then 2,900 when the Host noted the target cold (`Detention::note_load`) — and reverts it; a cold surcharge past what gas detention lets the frame spend stops it with the compute stop instead. + A frame that cannot reach the delegate (3,100 for a cold target, 200 for a warm one, with no input and no value) runs out of gas instead of being refused; every other refusal still costs nothing. + Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, and paying that access keeps a delegator of the beneficiary — which, the beneficiary being fixed, stays one for every later block — from being read for about 181 gas, so every cold account read costs the cold access. ### The stop and the configuration diff --git a/AGENTS.md b/AGENTS.md index c18aeac61..4beba90be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -431,9 +431,12 @@ Detention caps how much a transaction may still compute once it read such data ( The opcode's wrapper then refuses the read before the opcode charges or checks anything (`refused_read` in `evm/instructions.rs`), and the frame reverts with `VolatileDataAccessDisabled(accessType)` on the gas it held when it reached the opcode: a refused read costs nothing, not its static gas, which the wrapper charges itself and only once the read is not refused, so a frame below the static gas is refused rather than run out of gas. An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` included — is refused before its operands are read, so a `BLOCKHASH` on an empty stack is refused; an account, call, `SELFDESTRUCT` or Oracle read is refused only once every operand it takes is on the stack (a stack underflow stays one), when its target operand, its frame's own address (`SELFBALANCE`, `SELFDESTRUCT`) or its frame's storage (`SLOAD` of the Oracle's) is volatile, before its body's memory, copy, static-context or value checks. A call whose target operand is not the beneficiary is refused where it loads its target's one-hop EIP-7702 delegate, which only the target's code names: it runs its steps before that load as with access on — its static gas, the static-context check of a value `CALL`, its memory, its value transfer, the load of its target's account and code, which a frame short of the cold surcharge skips as an out-of-gas, and the check that the frame holds the target's access and the delegate's warm access — and the Host refuses the delegate's load when the delegate is the beneficiary (`MegaContext::load_account_info_skip_cold_load`), before the call charges its target's access, any state gas or its forward and before the frame-start hook. - The wrapper (`settle_reads` in `evm/instructions.rs`) then reverts the frame on the gas it held when it reached the call — the spendable and withheld parts and the reservoir — so the refusal costs nothing; the frame's revert takes back the target's warming, and the target's account and code stay in the transaction's state and witness, the beneficiary unloaded and nothing marked. + The wrapper (`settle_reads` in `evm/instructions.rs`) then puts back the gas the frame held when it reached the call — the spendable and withheld parts and the reservoir — and charges the target's own access the call read it for, as `BALANCE` charges it: the warm access, then the cold surcharge when the Host found the target cold as it loaded it (`Detention::note_load`, noted for the running opcode only), each a regular charge of the spendable part. + A cold surcharge past what the frame may spend is gas detention's crossing, and the frame ends with the compute stop; otherwise it reverts with the refusal, having paid that access and nothing else of the call — not its memory, its value transfer or the delegate's access; the call held the target's access and the delegate's warm access to reach the delegate, so the two charges never run out of gas. + The frame's end takes back the target's warming, and the target's account and code stay in the transaction's state and witness, the beneficiary unloaded and nothing marked. A call that fails or is stopped before the target's load reads nothing, as with access on; once the load is reached it is required, and a database error fails the transaction with its cause, never taken for a target without a delegate. - So a refused call of a delegator of the beneficiary is free only from a frame that holds the gas to reach the delegate (with no input and no value, 3,100 for a cold target, 200 for a warm one); a frame holding less runs out of gas, as with access on. + So a call of a delegator of the beneficiary is refused only from a frame that holds the gas to reach the delegate (with no input and no value, 3,100 for a cold target, 200 for a warm one), paying 3,000 or 100, as a read of the delegator with access on would; a frame holding less runs out of gas, as with access on. + Every other refused read costs nothing. The memory a refused call expanded stays expanded in the frame's buffer, its price put back with the gas, until the frame's end, which follows at once. `BLOCKHASH` names `BlockHash` (7) whatever its operand; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. The error's argument is encoded as a `uint8`, and Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value out of range, and the Rust `IMegaAccessControl` binding decodes 12 to its `__Invalid` placeholder; `decode_volatile_data_access_disabled` is the Rust side's decoder. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 3987ce238..c77c3e69c 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1005,7 +1005,7 @@ The reference implementation has no price for one, so it runs such a precompile #### Previous behavior - A read refused by `disableVolatileDataAccess()` reverts the frame immediately with `VolatileDataAccessDisabled(VolatileDataAccessType)`; `BLOCKHASH` and `BLOBHASH` are refused before their operands are checked. -- A call opcode in a frame whose access is off looks up its target's one-hop EIP-7702 delegate before it charges anything, and is refused when that delegate is the block beneficiary. +- A call opcode in a frame whose access is off looks up its target's one-hop EIP-7702 delegate before it charges anything, and is refused when that delegate is the block beneficiary, for no gas. - `MegaLimitControl.remainingComputeGas()` answers from a separate compute-gas ledger with per-frame budgets of 98/100 of the caller's remaining compute, and can exceed the caller's gas. #### New behavior @@ -1020,12 +1020,18 @@ The reference implementation has no price for one, so it runs such a precompile Either refusal comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. - A call opcode whose target operand is not the block beneficiary MUST run, in a frame whose access is off, the steps it runs with access on before it loads its target's one-hop EIP-7702 delegate: its static gas, the static-context check of a value-bearing `CALL`, its input and output memory, its value transfer, the load of its target's account and code — skipped as an out-of-gas when the target is cold and the frame's regular gas, its withheld part included, is below the cold surcharge — and, for a target that holds a delegation, the check that the frame holds the target's access and the delegate's warm access. A call that fails on one of those steps, or that gas detention stops on one, fails or is stopped as it would be with access on, and reads its target only when it reached the target's load. - When the call reaches the load of the delegate and the delegate is the block beneficiary, the load MUST be refused as the beneficiary's account (10): the beneficiary's account is not loaded, nothing is marked for gas detention, and the frame reverts with `VolatileDataAccessDisabled(10)` on the gas it held when it reached the call, everything the call charged before the load taken back. - The target's account and code stay in the transaction's read set, and the frame's revert leaves the target as warm or as cold as it was for the caller. + When the call reaches the load of the delegate and the delegate is the block beneficiary, the load MUST be refused as the beneficiary's account (10), before the call charges its target's access on its normal path, any new-account state gas, its forward or its start's history gas, and before any frame starts: the beneficiary's account is not loaded and nothing is marked for gas detention. + The call has read its target's account and code by then, which is no volatile read, so the frame MUST pay the target's own access, from the gas it held when it reached the call, as `BALANCE` pays it: `WARM_STORAGE_READ_COST` (100), then, when the target was not warm before the call, `COLD_ACCOUNT_ACCESS − WARM_STORAGE_READ_COST` (2,900), as two regular charges in that order. + Nothing else the call charged before the load is paid: its memory, its value transfer and the delegate's access are taken back, and the frame's regular gas, both the spendable and the withheld parts, and its reservoir are otherwise what it held when it reached the call. + Whether the target was warm before the call is EIP-2929's: whether it is among the transaction's accessed addresses when the call loads it, which the access list, an earlier access no revert took back and the addresses warm from the transaction's start, the precompiles among them, put it in. + When the target was not warm and the frame's spendable regular gas after the warm access cannot pay the cold surcharge, the surcharge is gas detention's crossing and the frame is stopped with `MegaLimitExceeded(2, limit)` (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)); otherwise the frame reverts with `VolatileDataAccessDisabled(10)`. + The frame's whole regular gas always covers the two charges, since the call held the target's access and the delegate's warm access to reach the delegate, so they never run out of gas. + The target's account and code stay in the transaction's read set, and the frame's end leaves the target as warm or as cold as it was for the caller. The target's load is a required read: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. - So a call of a delegator of the beneficiary with no input and no value is refused for nothing from a frame holding its static gas, the target's cold surcharge when the target is cold, and the delegate's warm access — 3,100 for a cold target, 200 for a warm one — and a frame holding less runs out of gas: holding 2,999 at a call of a cold delegator, before its target is read; holding 3,050, after. -- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. - The frame reverts on the gas it held when it reached the opcode — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged. + So a call of a delegator of the beneficiary with no input and no value is refused from a frame holding its static gas, the target's cold surcharge when the target is cold, and the delegate's warm access — 3,100 for a cold target, 200 for a warm one — paying the target's access, 3,000 or 100, and handing the rest back to its caller; a frame holding less runs out of gas: holding 2,999 at a call of a cold delegator, before its target is read; holding 3,000 to 3,099, after. + Reading a delegator of the beneficiary into the transaction's read set so costs the cold access, as reading any other account does. +- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and, but for the target's access a call refused at its target's delegate pays (above), MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. + The frame reverts on the gas it held when it reached the opcode — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged but that access. A read refused before the opcode's body, which is every refusal but a call's at its target's delegate, is refused all the same in a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. A refused read marks nothing for gas detention and asks no oracle service. - The error's argument MUST be ABI-encoded as a `uint8`: From db9688f22ddf46cdecb09cb76c6dc6bd7340dea5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 10:39:16 +0800 Subject: [PATCH 059/190] feat(evm): a call refused at its beneficiary delegate keeps its memory charged A call grows its frame's memory for its input and output ranges before it loads its target and the target's delegate. When the Host refuses a delegate that is the block beneficiary, the frame was put back to the gas it held at the call, which handed the memory expansion back although the node had grown and zeroed the memory. A loop of helper calls, each with a range of a few MiB, could have the node grow megabytes for about 250 gas each, unbounded by gas detention, since the handed-back expansion was no compute. The refusal now keeps what the call charged up to the target's load but its value transfer: after putting back the gas held at the call, it charges the warm access, the memory the opcode grew (the growth of the gas's memory record, its input and output ranges together, nothing for a range inside memory the frame already held), then the cold surcharge when the target was cold. The memory record stays at the grown memory. This is the gas the frame held once its memory was grown, less the surcharge, and the memory is charged as the same call charges it with access on. The first two charges were already made from the same spendable gas, so only the surcharge can be gas detention's crossing, as before. Tests: the restoration test expects the 64 KiB input's expansion kept; a new test checks the kept expansion for an input, an output, both, no range, and ranges inside and past memory the frame already grew, against the same call with access on; another shows a refusal leaves access-list and caller warmth to the caller; a loop at the execution cap now makes ten calls of 3 MiB each; and a call stack built in advance bounds the detention tail at 29 delegators of the beneficiary, and at 58 calls reading 116 accounts for a cold delegator of another cold account, a tail that does not depend on the refusal. --- crates/mega-evm/src/access/mod.rs | 17 +- crates/mega-evm/src/evm/host.rs | 4 +- crates/mega-evm/src/evm/instructions.rs | 46 ++- .../mega-evm/tests/satin/volatile_access.rs | 335 +++++++++++++++++- 4 files changed, 361 insertions(+), 41 deletions(-) diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 157499ccb..c63f2ba7a 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -186,14 +186,15 @@ //! that delegate, since only the target's code shows it: the call runs its steps before that load //! as with access on — its static gas, its memory, its value transfer, the load of its target, //! which a frame short of the cold access skips as an out-of-gas — and the Host refuses the -//! delegate's load. The call has read its target by then, which is no volatile read, and pays for -//! it as an account opcode would: the frame reverts on the gas it held when it reached the call -//! less the target's access — the warm access, and the cold surcharge when the target was cold -//! before the call — as two regular charges, so a cold surcharge past what gas detention lets the -//! frame spend stops it with the compute stop instead. Nothing else of the call is paid: not its -//! memory, its value transfer or the delegate's access. So the call reads its target only once it -//! holds the gas for it, and pays a cold target's cold access, as with access on, and a frame that -//! cannot reach the delegate fails as it would with access on. Every other refusal costs nothing. +//! delegate's load. The call has read its target by then, which is no volatile read, and grown +//! the frame's memory, and pays for both as with access on: the frame reverts on the gas it held +//! when it reached the call less the warm access, the memory the call grew and, when the target +//! was cold before the call, the cold surcharge, as regular charges in that order, so a cold +//! surcharge past what gas detention lets the frame spend stops it with the compute stop instead. +//! Nothing else of the call is paid: not its value transfer or the delegate's access. So the call +//! reads its target only once it holds the gas for it, and pays a cold target's cold access and +//! the memory it grew, as with access on, and a frame that cannot reach the delegate fails as it +//! would with access on. Every other refusal costs nothing. //! //! A refusal names the kind the opcode reads — `BLOCKHASH`'s names the hash, whatever its operand //! — and a `SLOTNUM` refusal names access type 12 diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 8d4332cd7..5aa4032b7 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -33,8 +33,8 @@ //! refuses it. A refused account or storage load fails as a skipped cold load, and a refused //! block-environment accessor answers zero. Nothing is loaded, and the opcode's wrapper turns the //! refusal into the frame's revert, on the gas the frame held when it reached the opcode, less, for -//! a call refused at its target's delegate, the target's access: the Host notes whether the target -//! was cold when it loads it. +//! a call refused at its target's delegate, the target's access and the memory the call grew: the +//! Host notes whether the target was cold when it loads it. //! //! # The Oracle's storage //! diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 53cd5100a..b027419a9 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -47,9 +47,10 @@ //! memory, its value transfer, the load of its target, which a frame short of the cold access //! skips as an out-of-gas — and the Host refuses the load of the delegate when it is the //! beneficiary. The wrapper then puts back the gas the frame held when it reached the call, -//! charges the target's access the call read it for, warm then cold, as an account opcode does, -//! and reverts the frame: the call reads its target only once it holds the gas to, and pays a cold -//! target's cold access, as with access on, and the refused read itself costs nothing. +//! charges what the call did for the node — the target's access the call read it for, warm then +//! cold, as an account opcode does, and the memory it grew — and reverts the frame: the call reads +//! its target only once it holds the gas to, and pays a cold target's cold access and the memory it +//! grew, as with access on; its value transfer and the refused read itself cost nothing. //! //! The Oracle's `SLOAD` is the one read made before any of its gas is charged: the slot is loaded, //! the oracle service asked and the read marked, at the compute before the opcode, and only then @@ -191,7 +192,7 @@ pub(crate) fn without_read_static_gas(mut table: GasTable) -> GasTable { /// `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; /// with access off, refused for the callee before the call charges anything, and for the delegate -/// where the call loads it, the callee's access paid. +/// where the call loads it, the callee's access and the call's memory paid. fn call( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { @@ -208,7 +209,7 @@ fn call( /// opcode's, and `inner` runs; a read the opcode completed is committed, capping the frame at what /// the compute limit leaves it, and a load the Host refused — a call's EIP-7702 delegate that is /// the beneficiary — reverts the frame on the gas it held when it reached the opcode, less the -/// access of the target the call loaded ([`settle_reads`]). +/// access of the target the call loaded and the memory it grew ([`settle_reads`]). /// /// A read the opcode did not complete — the opcode failed after the load — is dropped: it reached /// no computation, and the frame is failing anyway. @@ -315,17 +316,21 @@ fn refused_read( /// charges its target's access, any state gas or its forward, and before the frame-start hook, so /// what it did is all in the frame's gas and memory. The frame's gas is put back to what it held /// when it reached the opcode (`gas`), the spendable and withheld parts and the reservoir as they -/// were, which takes back every charge; the memory the call expanded stays expanded until the -/// frame's end, which follows at once, and the gas's record of it is put back with the rest. +/// were, which takes back every charge. /// -/// The call read its target's account and code, which is no volatile read, so it pays the -/// target's access as `BALANCE` does: the warm access, then, when the Host found the target cold, -/// the cold surcharge, each a regular charge of the spendable part. A frame whose spendable part -/// cannot pay the surcharge holds it in its withheld part — the call held its target's access and -/// the delegate's warm access to reach the delegate — so the charge is gas detention's crossing, -/// and the frame ends with the compute stop rather than the refusal. Otherwise it is refused: its -/// revert takes back the target's warming, and leaves the target's account and code in the -/// transaction's state. +/// The call read its target's account and code, which is no volatile read, and grew the frame's +/// memory, which the node did, so it pays both as it charged them with access on, each a regular +/// charge of the spendable part: the warm access, as its static gas; the memory, which is what the +/// opcode grew the gas's record of it by, its input and output ranges together, and nothing for a +/// range inside memory the frame already held, the record kept at the grown memory; then, when +/// the Host found the target cold, the cold surcharge, as `BALANCE` charges it. That is the gas +/// the frame held once its memory was grown, less the surcharge: the value transfer and the +/// delegate's access are not paid. The first two charges were made from the same spendable gas +/// already. A frame whose spendable part cannot pay the surcharge holds it in its withheld part — +/// the call held its target's access and the delegate's warm access to reach the delegate — so +/// the charge is gas detention's crossing, and the frame ends with the compute stop rather than +/// the refusal. Otherwise it is refused: its revert takes back the target's warming, and leaves +/// the target's account and code in the transaction's state. #[inline(never)] fn settle_reads( interpreter: &mut Interpreter, @@ -338,15 +343,20 @@ fn settle_reads( // The Host refuses only while the frame refuses, so the wrapper kept the frame's gas. debug_assert!(gas.is_some(), "a refusal in a frame whose access is on: {refused:?}"); // The Host refuses a load before the opcode builds a frame, so no action is pending. + let expanded = *interpreter.gas.memory(); if let Some(gas) = gas { interpreter.gas = gas; } - // The call read its target, which is no volatile read, so it pays the target's access as - // revm's account opcodes do, warm then cold, which gas detention may stop at. + // The call read its target, which is no volatile read, and grew the frame's memory: it + // pays them as it charged them with access on — the warm access, the memory, then the + // cold surcharge — which gas detention may stop at, and its memory stays grown. if let Some(cold) = host.detention.take_loaded_cold() { let params = host.gas_params(); + let memory = + expanded.expansion_cost.saturating_sub(interpreter.gas.memory().expansion_cost); + *interpreter.gas.memory_mut() = expanded; let surcharge = if cold { params.cold_account_additional_cost() } else { 0 }; - for cost in [params.warm_storage_read_cost(), surcharge] { + for cost in [params.warm_storage_read_cost(), memory, surcharge] { if !interpreter.gas.record_regular_cost(cost) { return Err(InstructionResult::OutOfGas); } diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index c75022745..266ead3f5 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -9,7 +9,7 @@ use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::ORACLE_ACCESS_COMPUTE_GAS, + constants::{ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, system::{ IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, @@ -32,6 +32,7 @@ use revm::{ }, context_interface::cfg::GasId, interpreter::{ + gas::MemoryGas, interpreter::EthInterpreter, interpreter_types::{Jumps, MemoryTr}, CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, @@ -45,9 +46,9 @@ use crate::{ common::body_history, detention::{ assert_caught, assert_stopped, burn, call, cold_access, context, execute, intrinsic, - on_beneficiary, op, run_on, spin, stop_data, tx, value_transfer, with_delegation, work, - Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, DELEGATOR, - TIERS, + memory_cost, on_beneficiary, op, run_on, spin, stop_data, tx, value_transfer, + with_delegation, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, + CONTRACT, DELEGATOR, TIERS, }, salt::entry, }; @@ -1055,19 +1056,20 @@ impl Inspector, EthInterpreter> for AtTheCal } /// A call refused at its delegate takes back everything it did before the load but its target's -/// access, so its frame reverts on the gas it held when it reached the call less that access. A -/// value `CALL` of a cold delegator of the beneficiary, with an input of 64 KiB, from a frame that -/// cannot fund the value, has paid its static gas, its memory and its value transfer and loaded -/// its target when the load of its delegate is refused: the frame's gas once the opcode returned -/// is its gas before it — the spendable and withheld parts, the reservoir and the memory's price — -/// with the cold access, 3,000, charged to its regular gas. The frame-start hook has not run, so +/// access and the memory it grew, so its frame reverts on the gas it held when it reached the call +/// less those. A value `CALL` of a cold delegator of the beneficiary, with an input of 64 KiB, from +/// a frame that cannot fund the value, has paid its static gas, its memory and its value transfer +/// and loaded its target when the load of its delegate is refused: the frame's gas once the opcode +/// returned is its gas before it — the spendable and withheld parts and the reservoir — with the +/// cold access, 3,000, and the 2,048 words of memory charged to its regular gas, and the memory's +/// record at those words; the value transfer is not charged. The frame-start hook has not run, so /// the transaction keeps no state or history gas but its body's and opens no start beyond its two /// frames'. The revert leaves the delegator cold for the caller, whose `BALANCE` of it pays the /// cold access, and the refusal marks nothing for gas detention: in a transaction a read of the /// timestamp detained first, the refusal leaves its limit and its reads as they were. The same /// holds above the execution cap, where the frame holds a reservoir. #[test] -fn test_a_refusal_at_the_delegate_takes_back_everything_but_the_targets_access() { +fn test_a_refusal_at_the_delegate_takes_back_everything_but_the_targets_access_and_memory() { let (child, _) = call_of(CALL, DELEGATOR, 1, 0x1_0000); for gas_limit in TIERS { for detained in [false, true] { @@ -1095,9 +1097,13 @@ fn test_a_refusal_at_the_delegate_takes_back_everything_but_the_targets_access() "{case}" ); let (before, after) = (inspector.before.unwrap(), inspector.after.unwrap()); + let words = 0x1_0000 / 32; + assert_eq!(before.0.memory().words_num, 0, "{case}"); let mut expected = before.0; - assert!(expected.record_regular_cost(cold_access()), "{case}"); - assert_eq!(after.0, expected, "{case}: the frame's gas at the call, less the access"); + assert!(expected.record_regular_cost(cold_access() + memory_cost(words)), "{case}"); + *expected.memory_mut() = + MemoryGas { words_num: words as usize, expansion_cost: memory_cost(words) }; + assert_eq!(after.0, expected, "{case}: the gas at the call, less access and memory"); if gas_limit == ABOVE { assert!(before.0.reservoir() > 0, "{case}: the frame holds a reservoir"); } @@ -1120,6 +1126,309 @@ fn test_a_refusal_at_the_delegate_takes_back_everything_but_the_targets_access() } } +/// A `STATICCALL` of `to` forwarding nothing, with an input of `input.1` bytes at `input.0` and an +/// output of `output.1` bytes at `output.0`, after `prefix`, then a `STOP`. +fn call_with_ranges( + prefix: BytecodeBuilder, + to: Address, + input: (u32, u32), + output: (u32, u32), +) -> Bytes { + prefix + .push_number(output.1) + .push_number(output.0) + .push_number(input.1) + .push_number(input.0) + .push_address(to) + .append_many([PUSH0, STATICCALL]) + .stop() + .build() +} + +/// The words a frame's memory holds once a range of `len` bytes at `offset` is in it, starting +/// from `words`: a range of no bytes grows nothing. +fn words_with(words: u64, (offset, len): (u32, u32)) -> u64 { + if len == 0 { + return words; + } + words.max((u64::from(offset) + u64::from(len)).div_ceil(32)) +} + +/// A call refused at its delegate keeps the memory it grew charged, and grown, as the same call +/// pays it with access on: the opcode's own expansion, from the words the frame held before it to +/// the words its input and output ranges reach, and nothing for a range inside memory the frame +/// already grew. A `STATICCALL` of a delegator of the beneficiary, cold or warmed by the access +/// list, with an input range, an output range, both, no range, or ranges after an `MSTORE` grew +/// memory first, inside it or past it, hands back the gas the frame held at the call less the warm +/// access, that expansion and, for a cold delegator, the cold surcharge; the frame's memory record +/// is the grown one. With access on, the same call's memory record grows by the same expansion. +#[test] +fn test_a_refusal_at_the_delegate_keeps_the_memory_its_call_grew() { + let warm = entry(GasId::warm_storage_read_cost()); + let surcharge = entry(GasId::cold_account_additional_cost()); + // (what the child does before the call, the words that leaves, the input, the output) + let grown = + || BytecodeBuilder::default().append_many([PUSH0]).push_number(0x1_0000_u32).append(MSTORE); + let grown_words = (0x1_0000 + 32) / 32; + let cases = [ + (BytecodeBuilder::default, 0, (0, 0x1_0000), (0, 0)), + (BytecodeBuilder::default, 0, (0, 0), (0x100, 0x2_0000)), + (BytecodeBuilder::default, 0, (0, 0x8000), (0x1_0000, 0x8000)), + (BytecodeBuilder::default, 0, (0, 0), (0, 0)), + ]; + let cases = cases + .into_iter() + .map(|(prefix, words, input, output)| (prefix(), words, input, output)) + .chain([ + (grown(), grown_words, (0, 0x8000), (0x20, 0x100)), + (grown(), grown_words, (0, 0x8000), (0x2_0000, 0x100)), + ]); + for (prefix, words, input, output) in cases { + let child = call_with_ranges(prefix, DELEGATOR, input, output); + let after_call = words_with(words_with(words, input), output); + let expansion = memory_cost(after_call) - memory_cost(words); + for listed in [false, true] { + let case = format!("input {input:?}, output {output:?}, listed {listed}"); + let at_the_call = |disabled: bool| { + let parent = calls_child(BytecodeBuilder::default(), None).stop().build(); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()); + let mut ctx = context(db); + if disabled { + ctx = ctx.with_volatile_access_disabled_from(1); + } + let mut evm = MegaEvm::new(ctx).with_inspector(AtTheCall::default()); + let tx = if listed { + listing(CONTRACT, DELEGATOR, BELOW) + } else { + tx(CALLER, CONTRACT, BELOW) + }; + let run = run_on(&mut evm, tx); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + evm.inspector().clone() + }; + + let off = at_the_call(true); + assert_eq!(off.child, Some(refused(VolatileDataAccess::BENEFICIARY_BALANCE)), "{case}"); + let (before, after) = (off.before.unwrap().0, off.after.unwrap().0); + assert_eq!(before.memory().words_num as u64, words, "{case}"); + let access = if listed { warm } else { warm + surcharge }; + assert_eq!(before.remaining() - after.remaining(), access + expansion, "{case}"); + assert_eq!( + *after.memory(), + MemoryGas { + words_num: after_call as usize, + expansion_cost: memory_cost(after_call) + }, + "{case}: the memory's record is the grown one" + ); + + let on = at_the_call(false); + let (before, after) = (on.before.unwrap().0, on.after.unwrap().0); + assert_eq!( + after.memory().expansion_cost - before.memory().expansion_cost, + expansion, + "{case}: with access on, the same expansion" + ); + } + } +} + +/// A refusal at a delegate takes back only the warming its own frame made: its revert leaves a +/// delegator the access list warmed, or one its caller loaded before the call, warm for the +/// caller, whose `BALANCE` of it then pays the warm access, and the refused call pays the warm +/// access for it, 100. +#[test] +fn test_a_refusal_at_the_delegate_leaves_earlier_warmth_to_the_caller() { + let warm = entry(GasId::warm_storage_read_cost()); + let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); + // The caller's `BALANCE` after the refusal, with its push, `POP` and the `GAS` that reads it. + let warm_balance = 3 + warm + 2 + 2; + for listed in [false, true] { + let start = if listed { + BytecodeBuilder::default() + } else { + BytecodeBuilder::default().push_address(DELEGATOR).append_many([BALANCE, POP]) + }; + let parent = then_balance_of_the_delegator(calls_child(start, Some(pushes + 2 * warm))); + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()); + let tx = + if listed { listing(CONTRACT, DELEGATOR, BELOW) } else { tx(CALLER, CONTRACT, BELOW) }; + let (run, result, output, spent) = run_child(db, tx); + assert!(run.outcome.result.is_success(), "listed {listed}: {:?}", run.outcome.result); + assert_eq!((result, output), refused(VolatileDataAccess::BENEFICIARY_BALANCE)); + assert_eq!(spent, pushes + warm, "listed {listed}: the warm access"); + assert_eq!(balance_cost(&run), warm_balance, "listed {listed}: still warm for the caller"); + } +} + +/// A contract that switches its access off, then calls `helper` forwarding `forward` for as long +/// as it holds `forward` and a fiftieth more, counting the calls, and returns the count. +fn calls_the_helper_while_it_can(helper: Address, forward: u64) -> Bytes { + let code = disables_volatile_access(BytecodeBuilder::default()).append(PUSH0); + let top = code.len() as u32; + let code = + code.append(JUMPDEST).push_number(forward + forward / 49 + 1_000).append_many([GAS, LT]); + // The jump to the end is patched in once the end is known: a four-byte push holds it. + let end_push = code.len(); + let code = code + .push_number(0_u32) + .append(JUMPI) + .append_many([PUSH0; 5]) + .push_address(helper) + .push_number(forward) + .append_many([CALL, POP]) + .push_number(1_u8) + .append(ADD) + .push_number(top) + .append(JUMP); + let end = code.len() as u32; + let code = code + .append(JUMPDEST) + .append_many([PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]); + let mut bytes = code.build().to_vec(); + assert_eq!(bytes[end_push], PUSH4, "the jump's push"); + bytes[end_push + 1..end_push + 5].copy_from_slice(&end.to_be_bytes()); + bytes.into() +} + +/// With access off, a loop cannot have the node grow memory it does not pay for. A transaction at +/// the execution cap calls a helper as long as it can, each call forwarding the helper what its +/// `STATICCALL` of a warm delegator of the beneficiary, with an output range of 3 MiB, needs to +/// grow that memory and reach the delegate. Each refusal keeps the expansion charged, so the +/// transaction makes about as many calls as the cap holds expansions, ten, and grows ten times +/// 3 MiB; a refusal that handed the expansion back would let it grow 3 MiB for each 250 gas or so. +#[test] +fn test_an_access_off_memory_loop_pays_for_the_memory_it_grows() { + const HELPER: Address = CHILD; + const OUTPUT: u32 = 3 << 20; + let warm = entry(GasId::warm_storage_read_cost()); + let words = u64::from(OUTPUT) / 32; + let helper = call_with_ranges(BytecodeBuilder::default(), DELEGATOR, (0, 0), (0, OUTPUT)); + // Four pushes of a number, the address's and a `PUSH0`, then the static gas, the memory and + // the delegate's warm access the guard asks for. + let pushes = 3 + 3 + 3 + 3 + 3 + 2; + let forward = pushes + warm + memory_cost(words) + warm; + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CONTRACT, calls_the_helper_while_it_can(HELPER, forward)) + .account_code(HELPER, helper); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let started = std::time::Instant::now(); + let run = run_on(&mut evm, listing(CONTRACT, DELEGATOR, TX_GAS_LIMIT_CAP)); + let elapsed = started.elapsed(); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let calls = U256::from_be_slice(run.outcome.result.output().unwrap()).to::(); + let helpers: Vec<_> = + evm.inspector().calls.iter().filter(|call| call.target == HELPER).collect(); + assert_eq!(helpers.len() as u64, calls); + let retained = helpers.iter().map(|call| call.spent).sum::() / calls; + println!( + "memory loop at the execution cap: {calls} calls, {} MiB grown, {retained} gas kept by \ + each refused call, {} regular gas, {elapsed:?}", + (calls * u64::from(OUTPUT)) >> 20, + run.outcome.gas.regular, + ); + for call in &helpers { + assert_eq!( + (call.result, call.output.clone()), + refused(VolatileDataAccess::BENEFICIARY_BALANCE) + ); + assert_eq!(call.spent, pushes + warm + memory_cost(words), "the expansion is kept"); + } + assert!(calls >= 1, "the loop calls the helper"); + assert!(calls <= TX_GAS_LIMIT_CAP / memory_cost(words), "no more calls than expansions fit"); +} + +/// The words a pre-built call stack's levels sit at, its delegators and their delegates. +fn stack_address(kind: u64, i: u64) -> Address { + Address::from_word(B256::from(U256::from((kind << 32) + i))) +} + +/// Runs a call stack of `levels` frames below a transaction's own frame that read the block's +/// timestamp, with access off from the first level down. Each level but the deepest pushes the +/// operands of a `STATICCALL` of its own fresh delegator, calls the next level with all its gas, +/// drops its status, then makes that `STATICCALL`; the deepest makes its `STATICCALL` at once, the +/// cap set so it may spend `spendable` there. Each delegator delegates to `delegate(i)`. Returns +/// how many delegators and how many delegates the transaction read. +fn run_pre_built_stack( + levels: u64, + spendable: u64, + delegate: impl Fn(u64) -> Address, +) -> (usize, usize) { + let level = |i: u64| if i == levels { CHILD } else { stack_address(1, i) }; + let delegator = |i: u64| stack_address(2, i); + let staticcall = |code: BytecodeBuilder, i: u64| { + code.append_many([PUSH0; 4]).push_address(delegator(i)).append(PUSH0) + }; + let root = op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0; 5]) + .push_address(level(1)) + .append_many([GAS, CALL]) + .stop() + .build(); + let mut db = MemoryDatabase::default().account_code(CONTRACT, root); + for i in 1..=levels { + let code = staticcall(BytecodeBuilder::default(), i); + let code = if i == levels { + code + } else { + code.append_many([PUSH0; 5]).push_address(level(i + 1)).append_many([GAS, CALL, POP]) + }; + db = db.account_code(level(i), code.append(STATICCALL).stop().build()); + db = with_delegation(db, delegator(i), delegate(i)); + } + let run_under = |cap: u64| { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let ctx = context(db.clone()) + .with_tx_runtime_limits(limits) + .with_volatile_access_disabled_from(1); + let mut evm = MegaEvm::new(ctx).with_inspector(AtTheCall::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let gas = evm.inspector().before.expect("the deepest level reached its call").0; + (run, gas.remaining() - gas.tracker().withheld(), gas.remaining()) + }; + let first = 1_000_000; + let (_, first_spendable, whole) = run_under(first); + assert!(first_spendable < whole, "the first run detains the deepest level"); + let (run, held, _) = run_under(first - first_spendable + spendable); + assert_eq!(held, spendable, "what the deepest level may spend at its call"); + let read = |address: Address| run.outcome.state.contains_key(&address); + let delegators = (1..=levels).filter(|&i| read(delegator(i))).count(); + let delegates = (1..=levels).filter(|&i| read(delegate(i))).count(); + (delegators, delegates) +} + +/// The detention tail of a call refused at its delegate is bounded by the warm access it keeps: +/// once what the limit leaves is below the cold access, each such call reads its cold target and +/// is stopped at the cold surcharge, keeping 100 of compute. A call stack built in advance, whose +/// levels each make that call as they resume, each paying 102 with its `POP`, reads at most 29 +/// delegators of the beneficiary from 2,999: the first call keeps 100, each later one 102, and 43 +/// are left. The tail every detained call has, which this path does not change, is wider: a call of +/// a cold delegator of another cold account reads both before it charges their 5,900, so the same +/// stack reads 58 delegators and their 58 delegates from 5,999, 85 left. +#[test] +fn test_a_detained_call_stack_reads_a_bounded_tail() { + let warm = entry(GasId::warm_storage_read_cost()); + let surcharge = entry(GasId::cold_account_additional_cost()); + // The first call keeps the warm access; each later one also its caller's `POP`. + let tail = |window: u64| 1 + (window - 1 - warm) / (warm + 2); + // The fee settlement loads the beneficiary's account in every transaction, so only the + // delegators tell what the tail read. + let (delegators, _) = run_pre_built_stack(32, warm + surcharge - 1, |_| BENEFICIARY); + assert_eq!(tail(warm + surcharge), 29); + assert_eq!(delegators, 29, "29 delegators of the beneficiary"); + let double = warm + 2 * surcharge + warm; + let doubly_cold = run_pre_built_stack(60, double - 1, |i| stack_address(3, i)); + assert_eq!(tail(double), 58); + assert_eq!(doubly_cold, (58, 58), "58 delegators and their 58 delegates"); +} + /// Runs a transaction whose own frame reads the block's timestamp and then calls `CHILD`, holding /// 5,200 at its first call opcode, of which it may spend `spendable`, with access off from `CHILD` /// down. Returns the run and what [`AtTheCall`] recorded. The cap is derived from a run under From 5a59d3b1731e5f48aff463f5cd274298aea52855 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 10:42:20 +0800 Subject: [PATCH 060/190] test(evm): a detained refusal at a delegate keeps the memory it grew The detention boundaries of a refusal at a beneficiary delegate gain a call with an output range of 32 words: a frame that cannot pay the memory is stopped there without reading its target, and one stopped at the cold surcharge hands back the gas less the warm access and the memory, which the surcharge comes after. --- .../mega-evm/tests/satin/volatile_access.rs | 62 ++++++++++++------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 266ead3f5..f722fb308 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -1473,32 +1473,50 @@ fn run_detained_child(child: &Bytes, pushes: u64, spendable: u64, warm: bool) -> (run, at_the_call) } -/// Gas detention applies to the access a refusal at a delegate pays as to any account opcode's: the -/// warm access first, then the cold surcharge, each a regular charge of the spendable part. A -/// `STATICCALL` of a delegator of the beneficiary, from a frame holding 5,200 of which it may spend -/// a part, is stopped at its static gas when it may spend 99, having read nothing, and hands back -/// all 5,200. With a cold delegator, the frame that may spend from 100 to 2,999 reaches the -/// delegate, its target read, and is stopped at the cold surcharge with `MegaLimitExceeded(2, -/// limit)`, handing back 5,100; one that may spend 3,000 is refused, paying the cold access, and -/// hands back 2,200. With a delegator the access list warms, one that may spend 100 is refused, -/// paying the warm access, and hands back 5,100. +/// Gas detention applies to what a refusal at a delegate pays as to the same charges with access +/// on: the warm access, the memory, then the cold surcharge, each a regular charge of the +/// spendable part. A `STATICCALL` of a delegator of the beneficiary, from a frame holding 5,200 of +/// which it may spend a part, is stopped at its static gas when it may spend 99, having read +/// nothing, and hands back all 5,200. With a cold delegator, the frame that may spend from 100 to +/// 2,999 reaches the delegate, its target read, and is stopped at the cold surcharge with +/// `MegaLimitExceeded(2, limit)`, handing back 5,100; one that may spend 3,000 is refused, paying +/// the cold access, and hands back 2,200. With a delegator the access list warms, one that may +/// spend 100 is refused, paying the warm access, and hands back 5,100. +/// +/// With an output range of 32 words, whose memory costs 98, the memory is charged before the +/// surcharge, so a stop at the surcharge keeps it: a frame that may spend 197 is stopped at the +/// memory, its target not read, handing back 5,100; one that may spend 1,000 or 3,097 is stopped at +/// the surcharge, handing back 5,002; one that may spend 3,098 is refused, handing back 2,102. #[test] fn test_a_refusal_at_the_delegate_pays_the_targets_access_within_the_compute_limit() { let warm = entry(GasId::warm_storage_read_cost()); - let (child, pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); - // (whether the access list warms the delegator, what the child may spend, whether it is - // refused rather than stopped, what it hands back, whether it reads the delegator) - for (listed, spendable, is_refused, returned, reads) in [ - (false, warm - 1, false, 5_200, false), - (false, warm, false, 5_200 - warm, true), - (false, 2 * warm, false, 5_200 - warm, true), - (false, cold_access() - 1, false, 5_200 - warm, true), - (false, cold_access(), true, 5_200 - cold_access(), true), - (true, warm - 1, false, 5_200, false), - (true, warm, true, 5_200 - warm, true), + let (plain, plain_pushes) = call_of(STATICCALL, DELEGATOR, 0, 0); + let words = 32; + let memory = memory_cost(words); + let ranged = + call_with_ranges(BytecodeBuilder::default(), DELEGATOR, (0, 0), (0, words as u32 * 32)); + // Four pushes of a number, the address's and a `PUSH0`. + let ranged_pushes = 4 * 3 + 3 + 2; + // (whether the call has the output range, whether the access list warms the delegator, what + // the child may spend, whether it is refused rather than stopped, what it hands back, whether + // it reads the delegator) + for (with_memory, listed, spendable, is_refused, returned, reads) in [ + (false, false, warm - 1, false, 5_200, false), + (false, false, warm, false, 5_200 - warm, true), + (false, false, 2 * warm, false, 5_200 - warm, true), + (false, false, cold_access() - 1, false, 5_200 - warm, true), + (false, false, cold_access(), true, 5_200 - cold_access(), true), + (false, true, warm - 1, false, 5_200, false), + (false, true, warm, true, 5_200 - warm, true), + (true, false, warm + memory - 1, false, 5_200 - warm, false), + (true, false, 1_000, false, 5_200 - warm - memory, true), + (true, false, cold_access() + memory - 1, false, 5_200 - warm - memory, true), + (true, false, cold_access() + memory, true, 5_200 - cold_access() - memory, true), ] { - let case = format!("listed {listed}, spendable {spendable}"); - let (run, at_the_call) = run_detained_child(&child, pushes, spendable, listed); + let case = format!("memory {with_memory}, listed {listed}, spendable {spendable}"); + let (child, pushes) = + if with_memory { (&ranged, ranged_pushes) } else { (&plain, plain_pushes) }; + let (run, at_the_call) = run_detained_child(child, pushes, spendable, listed); let limit = run.limit.expect("the timestamp detains"); let ending = if is_refused { refused(VolatileDataAccess::BENEFICIARY_BALANCE) From 78bbde5a2519d156eef83dd19b159a1bf8e02085 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 10:42:20 +0800 Subject: [PATCH 061/190] docs: a call refused at its beneficiary delegate keeps its memory charged --- .claude/skills/satin-review/SKILL.md | 6 +++--- AGENTS.md | 9 +++++---- docs/spec/upgrades/satin.md | 18 ++++++++++-------- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 1907b0354..34176ef7f 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -174,10 +174,10 @@ Each change is stated here in plain words with its reason; the specification has 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. -- **A call's EIP-7702 delegate is refused where the call loads it, and the call pays its target's access.** - With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call, charges the target's own access — 100, then 2,900 when the Host noted the target cold (`Detention::note_load`) — and reverts it; a cold surcharge past what gas detention lets the frame spend stops it with the compute stop instead. +- **A call's EIP-7702 delegate is refused where the call loads it, and the call pays its target's access and its memory.** + With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call, charges 100, the memory the opcode grew, then 2,900 when the Host noted the target cold (`Detention::note_load`) — the gas held once the memory was grown, less the surcharge, so only the value transfer and the delegate's access are not paid — and reverts it; a cold surcharge past what gas detention lets the frame spend stops it with the compute stop instead. A frame that cannot reach the delegate (3,100 for a cold target, 200 for a warm one, with no input and no value) runs out of gas instead of being refused; every other refusal still costs nothing. - Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, and paying that access keeps a delegator of the beneficiary — which, the beneficiary being fixed, stays one for every later block — from being read for about 181 gas, so every cold account read costs the cold access. + Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, and paying that access keeps a delegator of the beneficiary — which, the beneficiary being fixed, stays one for every later block — from being read for about 181 gas, so every cold account read costs the cold access; keeping the memory charged stops a loop of refused calls with MiB-sized ranges from having the node grow and zero memory for about 270 gas a call (ten 3 MiB calls fit in a transaction at the execution cap, where handing the expansion back allowed 658,337 of them, about 1.9 TiB of memory grown). ### The stop and the configuration diff --git a/AGENTS.md b/AGENTS.md index 4beba90be..5a0502513 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -431,13 +431,14 @@ Detention caps how much a transaction may still compute once it read such data ( The opcode's wrapper then refuses the read before the opcode charges or checks anything (`refused_read` in `evm/instructions.rs`), and the frame reverts with `VolatileDataAccessDisabled(accessType)` on the gas it held when it reached the opcode: a refused read costs nothing, not its static gas, which the wrapper charges itself and only once the read is not refused, so a frame below the static gas is refused rather than run out of gas. An opcode volatile whatever its operands — the block-environment opcodes, `BLOCKHASH` included — is refused before its operands are read, so a `BLOCKHASH` on an empty stack is refused; an account, call, `SELFDESTRUCT` or Oracle read is refused only once every operand it takes is on the stack (a stack underflow stays one), when its target operand, its frame's own address (`SELFBALANCE`, `SELFDESTRUCT`) or its frame's storage (`SLOAD` of the Oracle's) is volatile, before its body's memory, copy, static-context or value checks. A call whose target operand is not the beneficiary is refused where it loads its target's one-hop EIP-7702 delegate, which only the target's code names: it runs its steps before that load as with access on — its static gas, the static-context check of a value `CALL`, its memory, its value transfer, the load of its target's account and code, which a frame short of the cold surcharge skips as an out-of-gas, and the check that the frame holds the target's access and the delegate's warm access — and the Host refuses the delegate's load when the delegate is the beneficiary (`MegaContext::load_account_info_skip_cold_load`), before the call charges its target's access, any state gas or its forward and before the frame-start hook. - The wrapper (`settle_reads` in `evm/instructions.rs`) then puts back the gas the frame held when it reached the call — the spendable and withheld parts and the reservoir — and charges the target's own access the call read it for, as `BALANCE` charges it: the warm access, then the cold surcharge when the Host found the target cold as it loaded it (`Detention::note_load`, noted for the running opcode only), each a regular charge of the spendable part. - A cold surcharge past what the frame may spend is gas detention's crossing, and the frame ends with the compute stop; otherwise it reverts with the refusal, having paid that access and nothing else of the call — not its memory, its value transfer or the delegate's access; the call held the target's access and the delegate's warm access to reach the delegate, so the two charges never run out of gas. - The frame's end takes back the target's warming, and the target's account and code stay in the transaction's state and witness, the beneficiary unloaded and nothing marked. + The wrapper (`settle_reads` in `evm/instructions.rs`) then puts back the gas the frame held when it reached the call — the spendable and withheld parts and the reservoir — and charges what the call did up to the target's load but its value transfer, as with access on: the warm access, the memory the opcode grew (the growth of the gas's memory record, which stays at the grown memory) and, when the Host found the target cold as it loaded it (`Detention::note_load`, noted for the running opcode only), the cold surcharge, as `BALANCE` charges it, each a regular charge of the spendable part in that order. + A cold surcharge past what the frame may spend is gas detention's crossing, and the frame ends with the compute stop; otherwise it reverts with the refusal, having paid that and nothing else of the call — not its value transfer or the delegate's access; the warm access and the memory were paid from the same spendable gas before, and the call held the target's access and the delegate's warm access to reach the delegate, so the charges never run out of gas. + The frame's end takes back the warming the frame made, warmth from before the call staying, and the target's account and code stay in the transaction's state and witness, the beneficiary unloaded and nothing marked. A call that fails or is stopped before the target's load reads nothing, as with access on; once the load is reached it is required, and a database error fails the transaction with its cause, never taken for a target without a delegate. So a call of a delegator of the beneficiary is refused only from a frame that holds the gas to reach the delegate (with no input and no value, 3,100 for a cold target, 200 for a warm one), paying 3,000 or 100, as a read of the delegator with access on would; a frame holding less runs out of gas, as with access on. Every other refused read costs nothing. - The memory a refused call expanded stays expanded in the frame's buffer, its price put back with the gas, until the frame's end, which follows at once. + The memory a refused call grew stays grown and charged until the frame's end, which follows at once: the node grew it, so a loop of refused calls with large ranges pays for every byte it has the node grow. + Under detention, a frame that may spend less than the cold access reads such a target and is stopped at the surcharge, keeping at least the warm access: at most 29 such reads fit in that window, and a call of a cold delegator of another cold account, which reads both before it charges 5,900, allows up to 58 calls reading 116 accounts in its own (`test_a_detained_call_stack_reads_a_bounded_tail`). `BLOCKHASH` names `BlockHash` (7) whatever its operand; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. The error's argument is encoded as a `uint8`, and Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value out of range, and the Rust `IMegaAccessControl` binding decodes 12 to its `__Invalid` placeholder; `decode_volatile_data_access_disabled` is the Rust side's decoder. The system contracts are not changed for it: their bytecode, and so their code hashes, stay as deployed. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index c77c3e69c..2311c62f5 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1021,17 +1021,19 @@ The reference implementation has no price for one, so it runs such a precompile - A call opcode whose target operand is not the block beneficiary MUST run, in a frame whose access is off, the steps it runs with access on before it loads its target's one-hop EIP-7702 delegate: its static gas, the static-context check of a value-bearing `CALL`, its input and output memory, its value transfer, the load of its target's account and code — skipped as an out-of-gas when the target is cold and the frame's regular gas, its withheld part included, is below the cold surcharge — and, for a target that holds a delegation, the check that the frame holds the target's access and the delegate's warm access. A call that fails on one of those steps, or that gas detention stops on one, fails or is stopped as it would be with access on, and reads its target only when it reached the target's load. When the call reaches the load of the delegate and the delegate is the block beneficiary, the load MUST be refused as the beneficiary's account (10), before the call charges its target's access on its normal path, any new-account state gas, its forward or its start's history gas, and before any frame starts: the beneficiary's account is not loaded and nothing is marked for gas detention. - The call has read its target's account and code by then, which is no volatile read, so the frame MUST pay the target's own access, from the gas it held when it reached the call, as `BALANCE` pays it: `WARM_STORAGE_READ_COST` (100), then, when the target was not warm before the call, `COLD_ACCOUNT_ACCESS − WARM_STORAGE_READ_COST` (2,900), as two regular charges in that order. - Nothing else the call charged before the load is paid: its memory, its value transfer and the delegate's access are taken back, and the frame's regular gas, both the spendable and the withheld parts, and its reservoir are otherwise what it held when it reached the call. + The call has read its target's account and code by then, which is no volatile read, and grown the frame's memory, which the node did, so the frame MUST pay both, from the gas it held when it reached the call, as the same call charges them with access on: `WARM_STORAGE_READ_COST` (100); then the call's memory expansion, the growth its input and output ranges made to the frame's memory, nothing for a range inside memory the frame already held; then, when the target was not warm before the call, `COLD_ACCOUNT_ACCESS − WARM_STORAGE_READ_COST` (2,900), as `BALANCE` charges it; as regular charges in that order. + That is the gas the frame held once the call's memory was grown, less the cold surcharge: the call's value transfer and the delegate's access are not paid, and the frame's regular gas, both the spendable and the withheld parts, and its reservoir are otherwise what it held when it reached the call. + The memory stays grown, priced as grown. Whether the target was warm before the call is EIP-2929's: whether it is among the transaction's accessed addresses when the call loads it, which the access list, an earlier access no revert took back and the addresses warm from the transaction's start, the precompiles among them, put it in. - When the target was not warm and the frame's spendable regular gas after the warm access cannot pay the cold surcharge, the surcharge is gas detention's crossing and the frame is stopped with `MegaLimitExceeded(2, limit)` (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)); otherwise the frame reverts with `VolatileDataAccessDisabled(10)`. - The frame's whole regular gas always covers the two charges, since the call held the target's access and the delegate's warm access to reach the delegate, so they never run out of gas. - The target's account and code stay in the transaction's read set, and the frame's end leaves the target as warm or as cold as it was for the caller. + When the target was not warm and the frame's spendable regular gas after the warm access and the memory cannot pay the cold surcharge, the surcharge is gas detention's crossing and the frame is stopped with `MegaLimitExceeded(2, limit)` (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)); otherwise the frame reverts with `VolatileDataAccessDisabled(10)`. + The warm access and the memory were paid from the same spendable gas before the load, and the frame's whole regular gas then covers the cold surcharge, since the call held the target's access and the delegate's warm access to reach the delegate, so the charges never run out of gas. + The target's account and code stay in the transaction's read set, and the frame's end takes back only the warming the frame made: the target is as warm or as cold for the caller as it was before the call, warmth from the access list, the transaction's start or an earlier frame staying. The target's load is a required read: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. So a call of a delegator of the beneficiary with no input and no value is refused from a frame holding its static gas, the target's cold surcharge when the target is cold, and the delegate's warm access — 3,100 for a cold target, 200 for a warm one — paying the target's access, 3,000 or 100, and handing the rest back to its caller; a frame holding less runs out of gas: holding 2,999 at a call of a cold delegator, before its target is read; holding 3,000 to 3,099, after. - Reading a delegator of the beneficiary into the transaction's read set so costs the cold access, as reading any other account does. -- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and, but for the target's access a call refused at its target's delegate pays (above), MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. - The frame reverts on the gas it held when it reached the opcode — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged but that access. + Reading a delegator of the beneficiary into the transaction's read set so costs the cold access, as reading any other account does, and growing memory for a refused call costs what it costs with access on. + Under gas detention, a frame that may spend less than the cold access reads such a target and is stopped at the surcharge, keeping at least the warm access, so at most 29 such reads fit in that last window at the current schedule. +- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and, but for what a call refused at its target's delegate pays (above), MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. + The frame reverts on the gas it held when it reached the opcode — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged but that. A read refused before the opcode's body, which is every refusal but a call's at its target's delegate, is refused all the same in a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. A refused read marks nothing for gas detention and asks no oracle service. - The error's argument MUST be ABI-encoded as a `uint8`: From 6626bd799f4cc3e9760bceb681ee1e9d54ff2171 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 10:54:01 +0800 Subject: [PATCH 062/190] test(evm): bound the memory loop's calls A refusal that handed a call's memory expansion back would let the loop run hundreds of thousands of calls of 3 MiB each, which takes minutes in a debug build; at most 32 calls, the test fails at once instead, and with the expansion kept it still makes ten. --- .../mega-evm/tests/satin/volatile_access.rs | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index f722fb308..9dd25fa71 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -1266,14 +1266,19 @@ fn test_a_refusal_at_the_delegate_leaves_earlier_warmth_to_the_caller() { } /// A contract that switches its access off, then calls `helper` forwarding `forward` for as long -/// as it holds `forward` and a fiftieth more, counting the calls, and returns the count. -fn calls_the_helper_while_it_can(helper: Address, forward: u64) -> Bytes { +/// as it holds `forward` and a fiftieth more, at most `most` times, counting the calls, and +/// returns the count. +fn calls_the_helper_while_it_can(helper: Address, forward: u64, most: u32) -> Bytes { let code = disables_volatile_access(BytecodeBuilder::default()).append(PUSH0); let top = code.len() as u32; + // The jumps to the end are patched in once the end is known: a four-byte push holds each. + let mut to_the_end = Vec::new(); let code = code.append(JUMPDEST).push_number(forward + forward / 49 + 1_000).append_many([GAS, LT]); - // The jump to the end is patched in once the end is known: a four-byte push holds it. - let end_push = code.len(); + to_the_end.push(code.len()); + let code = + code.push_number(0_u32).append(JUMPI).push_number(most).append_many([DUP2, LT, ISZERO]); + to_the_end.push(code.len()); let code = code .push_number(0_u32) .append(JUMPI) @@ -1292,17 +1297,20 @@ fn calls_the_helper_while_it_can(helper: Address, forward: u64) -> Bytes { .push_number(32_u8) .append_many([PUSH0, RETURN]); let mut bytes = code.build().to_vec(); - assert_eq!(bytes[end_push], PUSH4, "the jump's push"); - bytes[end_push + 1..end_push + 5].copy_from_slice(&end.to_be_bytes()); + for at in to_the_end { + assert_eq!(bytes[at], PUSH4, "the jump's push"); + bytes[at + 1..at + 5].copy_from_slice(&end.to_be_bytes()); + } bytes.into() } /// With access off, a loop cannot have the node grow memory it does not pay for. A transaction at -/// the execution cap calls a helper as long as it can, each call forwarding the helper what its -/// `STATICCALL` of a warm delegator of the beneficiary, with an output range of 3 MiB, needs to -/// grow that memory and reach the delegate. Each refusal keeps the expansion charged, so the -/// transaction makes about as many calls as the cap holds expansions, ten, and grows ten times -/// 3 MiB; a refusal that handed the expansion back would let it grow 3 MiB for each 250 gas or so. +/// the execution cap calls a helper as long as it can, at most 32 times, each call forwarding the +/// helper what its `STATICCALL` of a warm delegator of the beneficiary, with an output range of +/// 3 MiB, needs to grow that memory and reach the delegate. Each refusal keeps the expansion +/// charged, so the transaction makes about as many calls as the cap holds expansions, ten, and +/// grows ten times 3 MiB; a refusal that handed the expansion back would let it grow 3 MiB for +/// each 270 gas or so, hundreds of thousands of times, which the bound of 32 calls cuts short. #[test] fn test_an_access_off_memory_loop_pays_for_the_memory_it_grows() { const HELPER: Address = CHILD; @@ -1315,7 +1323,7 @@ fn test_an_access_off_memory_loop_pays_for_the_memory_it_grows() { let pushes = 3 + 3 + 3 + 3 + 3 + 2; let forward = pushes + warm + memory_cost(words) + warm; let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) - .account_code(CONTRACT, calls_the_helper_while_it_can(HELPER, forward)) + .account_code(CONTRACT, calls_the_helper_while_it_can(HELPER, forward, 32)) .account_code(HELPER, helper); let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); let started = std::time::Instant::now(); From 5a845fd251109c8d05230105de0c4d4293300ae5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 10:56:35 +0800 Subject: [PATCH 063/190] test(evm): a pre-built call stack that reuses each status reaches the tail bounds A level that takes the stopped call's zero status as its own call's gas pays 100 a call instead of 102: the refusal's tail stays at 29 delegators of the beneficiary, and the tail of a cold delegator of another cold account, which no refusal makes, reaches 59 calls reading 118 accounts. --- AGENTS.md | 2 +- .../mega-evm/tests/satin/volatile_access.rs | 61 +++++++++++++------ 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5a0502513..23427ffaf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -438,7 +438,7 @@ Detention caps how much a transaction may still compute once it read such data ( So a call of a delegator of the beneficiary is refused only from a frame that holds the gas to reach the delegate (with no input and no value, 3,100 for a cold target, 200 for a warm one), paying 3,000 or 100, as a read of the delegator with access on would; a frame holding less runs out of gas, as with access on. Every other refused read costs nothing. The memory a refused call grew stays grown and charged until the frame's end, which follows at once: the node grew it, so a loop of refused calls with large ranges pays for every byte it has the node grow. - Under detention, a frame that may spend less than the cold access reads such a target and is stopped at the surcharge, keeping at least the warm access: at most 29 such reads fit in that window, and a call of a cold delegator of another cold account, which reads both before it charges 5,900, allows up to 58 calls reading 116 accounts in its own (`test_a_detained_call_stack_reads_a_bounded_tail`). + Under detention, a frame that may spend less than the cold access reads such a target and is stopped at the surcharge, keeping at least the warm access: at most 29 such reads fit in that window, and a call of a cold delegator of another cold account, which reads both before it charges 5,900, allows up to 59 calls reading 118 accounts in its own, a tail no refusal makes (`test_a_detained_call_stack_reads_a_bounded_tail`). `BLOCKHASH` names `BlockHash` (7) whatever its operand; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. The error's argument is encoded as a `uint8`, and Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value out of range, and the Rust `IMegaAccessControl` binding decodes 12 to its `__Invalid` placeholder; `decode_volatile_data_access_disabled` is the Rust side's decoder. The system contracts are not changed for it: their bytecode, and so their code hashes, stay as deployed. diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 9dd25fa71..a9be04374 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -1360,18 +1360,26 @@ fn stack_address(kind: u64, i: u64) -> Address { /// Runs a call stack of `levels` frames below a transaction's own frame that read the block's /// timestamp, with access off from the first level down. Each level but the deepest pushes the /// operands of a `STATICCALL` of its own fresh delegator, calls the next level with all its gas, -/// drops its status, then makes that `STATICCALL`; the deepest makes its `STATICCALL` at once, the -/// cap set so it may spend `spendable` there. Each delegator delegates to `delegate(i)`. Returns -/// how many delegators and how many delegates the transaction read. +/// then makes that `STATICCALL`, either dropping the next level's status first or, with +/// `status_as_gas`, taking it, a zero once the level was stopped, as the call's gas; the deepest +/// makes its `STATICCALL` at once, the cap set so it may spend `spendable` there. Each delegator +/// delegates to `delegate(i)`. Returns how many delegators and how many delegates the transaction +/// read. fn run_pre_built_stack( levels: u64, spendable: u64, + status_as_gas: bool, delegate: impl Fn(u64) -> Address, ) -> (usize, usize) { let level = |i: u64| if i == levels { CHILD } else { stack_address(1, i) }; let delegator = |i: u64| stack_address(2, i); let staticcall = |code: BytecodeBuilder, i: u64| { - code.append_many([PUSH0; 4]).push_address(delegator(i)).append(PUSH0) + let code = code.append_many([PUSH0; 4]).push_address(delegator(i)); + if status_as_gas && i < levels { + code + } else { + code.append(PUSH0) + } }; let root = op(BytecodeBuilder::default(), TIMESTAMP) .append_many([PUSH0; 5]) @@ -1385,7 +1393,13 @@ fn run_pre_built_stack( let code = if i == levels { code } else { - code.append_many([PUSH0; 5]).push_address(level(i + 1)).append_many([GAS, CALL, POP]) + let code = + code.append_many([PUSH0; 5]).push_address(level(i + 1)).append_many([GAS, CALL]); + if status_as_gas { + code + } else { + code.append(POP) + } }; db = db.account_code(level(i), code.append(STATICCALL).stop().build()); db = with_delegation(db, delegator(i), delegate(i)); @@ -1415,26 +1429,33 @@ fn run_pre_built_stack( /// The detention tail of a call refused at its delegate is bounded by the warm access it keeps: /// once what the limit leaves is below the cold access, each such call reads its cold target and /// is stopped at the cold surcharge, keeping 100 of compute. A call stack built in advance, whose -/// levels each make that call as they resume, each paying 102 with its `POP`, reads at most 29 -/// delegators of the beneficiary from 2,999: the first call keeps 100, each later one 102, and 43 -/// are left. The tail every detained call has, which this path does not change, is wider: a call of -/// a cold delegator of another cold account reads both before it charges their 5,900, so the same -/// stack reads 58 delegators and their 58 delegates from 5,999, 85 left. +/// levels each make that call as they resume, reads at most 29 delegators of the beneficiary from +/// 2,999, whether each level pays a `POP` of the status first, 102 a call, 43 left, or takes the +/// status as the call's gas, 100 a call, 99 left. The tail every detained call has, which this path +/// does not change, is wider: a call of a cold delegator of another cold account reads both before +/// it charges their 5,900, so the same stack reads 58 delegators and their 58 delegates from 5,999 +/// with the `POP`s, 85 left, and 59 and 59 without, 99 left. #[test] fn test_a_detained_call_stack_reads_a_bounded_tail() { let warm = entry(GasId::warm_storage_read_cost()); let surcharge = entry(GasId::cold_account_additional_cost()); - // The first call keeps the warm access; each later one also its caller's `POP`. - let tail = |window: u64| 1 + (window - 1 - warm) / (warm + 2); - // The fee settlement loads the beneficiary's account in every transaction, so only the - // delegators tell what the tail read. - let (delegators, _) = run_pre_built_stack(32, warm + surcharge - 1, |_| BENEFICIARY); - assert_eq!(tail(warm + surcharge), 29); - assert_eq!(delegators, 29, "29 delegators of the beneficiary"); + // The first call keeps the warm access; each later one also its caller's `POP`, if any. + let tail = |window: u64, pop: u64| 1 + (window - 1 - warm) / (warm + pop); let double = warm + 2 * surcharge + warm; - let doubly_cold = run_pre_built_stack(60, double - 1, |i| stack_address(3, i)); - assert_eq!(tail(double), 58); - assert_eq!(doubly_cold, (58, 58), "58 delegators and their 58 delegates"); + for (status_as_gas, pop) in [(false, 2), (true, 0)] { + let case = format!("status as gas {status_as_gas}"); + // The fee settlement loads the beneficiary's account in every transaction, so only the + // delegators tell what the tail read. + let (delegators, _) = + run_pre_built_stack(32, warm + surcharge - 1, status_as_gas, |_| BENEFICIARY); + assert_eq!(tail(warm + surcharge, pop), 29, "{case}"); + assert_eq!(delegators, 29, "{case}: 29 delegators of the beneficiary"); + let doubly_cold = + run_pre_built_stack(62, double - 1, status_as_gas, |i| stack_address(3, i)); + let calls = tail(double, pop); + assert_eq!(calls, 58 + status_as_gas as u64, "{case}"); + assert_eq!(doubly_cold, (calls as usize, calls as usize), "{case}: and as many delegates"); + } } /// Runs a transaction whose own frame reads the block's timestamp and then calls `CHILD`, holding From c5bedeebda260fe67ec5a0104c3328042eb57268 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:06:52 +0800 Subject: [PATCH 064/190] test(evm): a refused delegate call to a precompile address, and a detained value call Two cases of a call refused at its target's EIP-7702 delegate that no test held. A call of a precompile's address whose state holds a delegation to the block beneficiary is refused at the delegate's load, before the precompile's dispatch, paying the warm access and the memory its ranges grew; with access on the same call runs the precompile. A value call from a detained frame always pays its cold surcharge at the refusal, because the value transfer it was charged from its spendable gas, and is given back, leaves room for it; one unit less spendable gas stops it at the value transfer, before its target is read. The read loops no longer print what they measured, and the memory loop no longer times itself: every figure they printed is asserted. --- .../mega-evm/tests/satin/volatile_access.rs | 157 +++++++++++------- 1 file changed, 97 insertions(+), 60 deletions(-) diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index a9be04374..d100b650b 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -1326,21 +1326,12 @@ fn test_an_access_off_memory_loop_pays_for_the_memory_it_grows() { .account_code(CONTRACT, calls_the_helper_while_it_can(HELPER, forward, 32)) .account_code(HELPER, helper); let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); - let started = std::time::Instant::now(); let run = run_on(&mut evm, listing(CONTRACT, DELEGATOR, TX_GAS_LIMIT_CAP)); - let elapsed = started.elapsed(); assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); let calls = U256::from_be_slice(run.outcome.result.output().unwrap()).to::(); let helpers: Vec<_> = evm.inspector().calls.iter().filter(|call| call.target == HELPER).collect(); assert_eq!(helpers.len() as u64, calls); - let retained = helpers.iter().map(|call| call.spent).sum::() / calls; - println!( - "memory loop at the execution cap: {calls} calls, {} MiB grown, {retained} gas kept by \ - each refused call, {} regular gas, {elapsed:?}", - (calls * u64::from(OUTPUT)) >> 20, - run.outcome.gas.regular, - ); for call in &helpers { assert_eq!( (call.result, call.output.clone()), @@ -1459,17 +1450,22 @@ fn test_a_detained_call_stack_reads_a_bounded_tail() { } /// Runs a transaction whose own frame reads the block's timestamp and then calls `CHILD`, holding -/// 5,200 at its first call opcode, of which it may spend `spendable`, with access off from `CHILD` -/// down. Returns the run and what [`AtTheCall`] recorded. The cap is derived from a run under -/// another, which detains the child too: the child's spendable gas at the call is the cap less what -/// the transaction computed since its read. -fn run_detained_child(child: &Bytes, pushes: u64, spendable: u64, warm: bool) -> (Run, AtTheCall) { - const WHOLE: u64 = 5_200; +/// `whole` at its first call opcode, of which it may spend `spendable`, with access off from +/// `CHILD` down. Returns the run and what [`AtTheCall`] recorded. The cap is derived from a run +/// under another, which detains the child too: the child's spendable gas at the call is the cap +/// less what the transaction computed since its read. +fn run_detained_child( + child: &Bytes, + pushes: u64, + whole: u64, + spendable: u64, + warm: bool, +) -> (Run, AtTheCall) { // The parent stops once the call returned, which costs nothing of what the limit leaves it. let parent = op(BytecodeBuilder::default(), TIMESTAMP) .append_many([PUSH0; 5]) .push_address(CHILD) - .push_number(pushes + WHOLE) + .push_number(pushes + whole) .append(CALL) .stop() .build(); @@ -1493,12 +1489,12 @@ fn run_detained_child(child: &Bytes, pushes: u64, spendable: u64, warm: bool) -> }; // The call the transaction's own frame makes, a cold one, fits under it, and what the child may // spend at its call is below what it holds. - let first = cold_access() + WHOLE / 2; + let first = cold_access() + whole / 2; let (_, at_the_call) = run_under(first); let (first_spendable, _) = held(&at_the_call); - assert!(first_spendable < WHOLE, "the first run detains the child: {first_spendable}"); + assert!(first_spendable < whole, "the first run detains the child: {first_spendable}"); let (run, at_the_call) = run_under(first - first_spendable + spendable); - assert_eq!(held(&at_the_call), (spendable, WHOLE), "what the child holds at the call"); + assert_eq!(held(&at_the_call), (spendable, whole), "what the child holds at the call"); (run, at_the_call) } @@ -1545,7 +1541,7 @@ fn test_a_refusal_at_the_delegate_pays_the_targets_access_within_the_compute_lim let case = format!("memory {with_memory}, listed {listed}, spendable {spendable}"); let (child, pushes) = if with_memory { (&ranged, ranged_pushes) } else { (&plain, plain_pushes) }; - let (run, at_the_call) = run_detained_child(child, pushes, spendable, listed); + let (run, at_the_call) = run_detained_child(child, pushes, 5_200, spendable, listed); let limit = run.limit.expect("the timestamp detains"); let ending = if is_refused { refused(VolatileDataAccess::BENEFICIARY_BALANCE) @@ -1559,6 +1555,74 @@ fn test_a_refusal_at_the_delegate_pays_the_targets_access_within_the_compute_lim } } +/// A value call refused at its delegate always pays its cold surcharge: the value transfer it was +/// charged from its spendable gas before the load, and is given back, leaves room for the +/// surcharge there, so the surcharge is never gas detention's crossing. A value `CALL` of a cold +/// delegator of the beneficiary, from a frame that cannot fund the value and holds 20,000 at the +/// call, of which it may spend its static gas and the value transfer, 11,400, reaches the delegate +/// and is refused, paying the cold access and handing back 17,000; one that may spend 11,399 is +/// stopped at the value transfer, the charge that crosses, before its target is read, handing back +/// 19,900, the value transfer not among what it spent. +#[test] +fn test_a_detained_value_call_refused_at_the_delegate_pays_its_surcharge() { + let warm = entry(GasId::warm_storage_read_cost()); + let (child, pushes) = call_of(CALL, DELEGATOR, 1, 0); + let whole = 20_000; + let reach = warm + value_transfer(); + // (what the child may spend, whether it is refused rather than stopped, what it hands back, + // whether it reads the delegator) + for (spendable, is_refused, returned, reads) in + [(reach, true, whole - cold_access(), true), (reach - 1, false, whole - warm, false)] + { + let (run, at_the_call) = run_detained_child(&child, pushes, whole, spendable, false); + let limit = run.limit.expect("the timestamp detains"); + let ending = if is_refused { + refused(VolatileDataAccess::BENEFICIARY_BALANCE) + } else { + (InstructionResult::Revert, stop_data(limit)) + }; + assert_eq!(at_the_call.child, Some(ending), "{spendable}"); + assert_eq!(at_the_call.returned, Some(returned), "{spendable}: handed back"); + assert_eq!(run.outcome.state.contains_key(&DELEGATOR), reads, "{spendable}: read"); + } +} + +/// The identity precompile, whose address every transaction finds warm. +const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); + +/// A call runs a precompile only once it reaches the precompile's dispatch, after its own steps, +/// whatever code the state holds at the precompile's address. With access off, a `STATICCALL` of +/// the identity precompile's address, which the state gives a delegation indicator naming the +/// beneficiary, with an input of 64 bytes and an output range past it, is refused at the +/// delegate's load: the address is warm, so the frame pays the warm access and the memory its +/// ranges grew, four words, and the precompile never runs. With access on, the same call runs the +/// precompile. +#[test] +fn test_a_precompile_address_delegating_to_the_beneficiary_is_refused_before_it_runs() { + let warm = entry(GasId::warm_storage_read_cost()); + let child = call_with_ranges(BytecodeBuilder::default(), IDENTITY, (0, 64), (64, 64)); + let db = || { + with_delegation(MemoryDatabase::default(), IDENTITY, BENEFICIARY) + .account_code(CONTRACT, calls_child(BytecodeBuilder::default(), None).stop().build()) + .account_code(CHILD, child.clone()) + }; + + let mut evm = MegaEvm::new(context(db()).with_volatile_access_disabled_from(1)) + .with_inspector(AtTheCall::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let at_the_call = evm.inspector(); + assert_eq!(at_the_call.child, Some(refused(VolatileDataAccess::BENEFICIARY_BALANCE))); + let (before, after) = (at_the_call.before.unwrap().0, at_the_call.after.unwrap().0); + assert_eq!(before.remaining() - after.remaining(), warm + memory_cost(4)); + + let mut evm = MegaEvm::new(context(db())).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let call = evm.inspector().calls.iter().find(|call| call.target == IDENTITY); + assert!(call.is_some_and(|call| call.precompile_ran), "with access on the precompile runs"); +} + /// Contracts that load an account no transaction here funds, then do something else. const LOADS_THEN_CALLS: Address = address!("0000000000000000000000000000000000d00006"); const LOADS_THEN_READS_THE_TIME: Address = address!("0000000000000000000000000000000000d00007"); @@ -1676,7 +1740,7 @@ fn test_a_call_of_a_delegator_of_another_account_pays_as_with_access_on() { assert_eq!(spent(true), on, "access off"); } -/// The fresh addresses an amplification loop calls, none of which any account holds. +/// The fresh addresses a loop of reads calls, none of which any account holds. fn fresh_addresses(count: u64) -> Vec
{ (0..count).map(|i| Address::from_word(B256::from(U256::from(0xa000_0000_u64 + i)))).collect() } @@ -1732,14 +1796,14 @@ fn disables_volatile_access(code: BytecodeBuilder) -> BytecodeBuilder { .append_many([GAS, CALL, POP]) } -/// One run of an amplification loop: the regular gas the transaction spent, and how many of the -/// loop's targets its database was asked for. -struct Amplification { +/// One run of a loop of reads: the regular gas the transaction spent, and how many of the loop's +/// targets its database was asked for. +struct ReadLoop { gas: u64, reads: usize, } -impl Amplification { +impl ReadLoop { fn run(db: MemoryDatabase, targets: &[Address]) -> Self { let record = SharedWitnessRecord::default(); let outcome = MegaEvm::new(context(RecordingDatabase::new(db, record.clone()))) @@ -1750,11 +1814,6 @@ impl Amplification { let reads = targets.iter().filter(|target| record.accounts.contains_key(*target)).count(); Self { gas: outcome.gas.regular, reads } } - - /// The regular gas the transaction spent per target read, or `None` when it read none. - fn gas_per_read(&self) -> Option { - (self.reads > 0).then(|| self.gas / self.reads as u64) - } } /// With access off, a frame cannot read an account it does not pay for. A contract switches its @@ -1796,17 +1855,17 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { .account_code(HELPER, helper.clone()) }; - let starved = Amplification::run(loop_db(true, pushes), &targets); - let starved_on = Amplification::run(loop_db(false, pushes), &targets); - let paying = Amplification::run(loop_db(true, pushes + cold_access()), &targets); - let paying_on = Amplification::run(loop_db(false, pushes + cold_access()), &targets); + let starved = ReadLoop::run(loop_db(true, pushes), &targets); + let starved_on = ReadLoop::run(loop_db(false, pushes), &targets); + let paying = ReadLoop::run(loop_db(true, pushes + cold_access()), &targets); + let paying_on = ReadLoop::run(loop_db(false, pushes + cold_access()), &targets); let (crossing, _) = calls_its_input(0x32_0000); let detained_start = disables_volatile_access(op(BytecodeBuilder::default(), TIMESTAMP)); let detained_db = MemoryDatabase::default() .account_code(CONTRACT, calls_the_helper_for_each(detained_start, HELPER, &targets, None)) .account_code(HELPER, crossing); - let detained = Amplification::run(detained_db, &targets); + let detained = ReadLoop::run(detained_db, &targets); let delegators = fresh_addresses(500); let mut delegators_db = MemoryDatabase::default() @@ -1823,7 +1882,7 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { for delegator in &delegators { delegators_db = with_delegation(delegators_db, *delegator, BENEFICIARY); } - let refused_reads = Amplification::run(delegators_db.clone(), &delegators); + let refused_reads = ReadLoop::run(delegators_db.clone(), &delegators); let delegators_on_db = delegators_db.account_code( CONTRACT, calls_the_helper_for_each( @@ -1833,29 +1892,7 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { Some(pushes + cold_access() + warm), ), ); - let delegators_on = Amplification::run(delegators_on_db, &delegators); - - println!( - "amplification over {} fresh addresses: starved helper reads {} at {:?} gas each \ - (access on: {} for {} gas); paying helper reads {} at {:?} gas each (access on: {} at \ - {:?}); detained helper reads {} for {} gas; {} delegators of the beneficiary read and \ - refused at {:?} gas each (access on: {} at {:?})", - targets.len(), - starved.reads, - starved.gas_per_read(), - starved_on.reads, - starved_on.gas, - paying.reads, - paying.gas_per_read(), - paying_on.reads, - paying_on.gas_per_read(), - detained.reads, - detained.gas, - refused_reads.reads, - refused_reads.gas_per_read(), - delegators_on.reads, - delegators_on.gas_per_read(), - ); + let delegators_on = ReadLoop::run(delegators_on_db, &delegators); assert_eq!(starved.reads, 0, "a helper short of its static gas reads nothing"); assert_eq!(starved_on.reads, 0, "with access on either"); @@ -1870,7 +1907,7 @@ fn test_an_access_off_loop_reads_no_account_it_does_not_pay_for() { assert_eq!(detained.reads, 0, "a helper stopped at its memory reads nothing"); assert_eq!(refused_reads.reads, delegators.len(), "a delegator of the beneficiary is read"); assert_eq!(delegators_on.reads, delegators.len(), "as with access on"); - assert!(refused_reads.gas_per_read().unwrap() > cold_access(), "for its cold access"); + assert!(refused_reads.gas > delegators.len() as u64 * cold_access(), "for its cold access"); // The two loops differ only in the call that switches access off, which the starved loops // measure. let disabling = starved.gas - starved_on.gas; From 964884cc66eadbb5d1df80dc12310fc3cfcf2992 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:09:42 +0800 Subject: [PATCH 065/190] docs: state a call refused at its beneficiary delegate as the specification has it The Satin page now states the refusal at a delegate's load in full: the steps before the load and the delegation guard, the restoration and the three charges in their order, what memory expansion covers, that the charges made again count as compute once and the given-back value transfer as none, that a value call always pays its surcharge, which addresses are warm before the call and what the frame's end rolls back, that a precompile's address is refused before its dispatch, the two detention tails and their bounds, and what changes against Rex6. The revert-class stop and the witness's skipped reads name the detention crossing a delegate refusal can end with, and gas detention's crossing and precompile rules say that the refusal's charges come first. The code docs of the settlement, AGENTS.md and the review skill say the same. --- .claude/skills/satin-review/SKILL.md | 2 +- AGENTS.md | 2 + crates/mega-evm/src/evm/instructions.rs | 20 ++++--- docs/spec/upgrades/satin.md | 71 +++++++++++++++++-------- 4 files changed, 67 insertions(+), 28 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 34176ef7f..5680e10f3 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -175,7 +175,7 @@ Each change is stated here in plain words with its reason; the specification has 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. - **A call's EIP-7702 delegate is refused where the call loads it, and the call pays its target's access and its memory.** - With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call, charges 100, the memory the opcode grew, then 2,900 when the Host noted the target cold (`Detention::note_load`) — the gas held once the memory was grown, less the surcharge, so only the value transfer and the delegate's access are not paid — and reverts it; a cold surcharge past what gas detention lets the frame spend stops it with the compute stop instead. + With access off, a call whose target operand is the beneficiary is still refused before it charges anything; a call whose target delegates to the beneficiary is no longer looked up first, but runs its static gas, memory, value transfer and target load as with access on, and the Host refuses the delegate's load (`load_account_info_skip_cold_load`); `settle_reads` puts back the gas the frame held at the call, charges 100, the memory the opcode grew, then 2,900 when the Host noted the target cold (`Detention::note_load`) — the gas held once the memory was grown, less the surcharge, so only the value transfer and the delegate's access are not paid, and the charges made again count as compute once — and reverts it; a cold surcharge past what gas detention lets the frame spend stops it with the compute stop instead (a value call's restored spendable gas always covers its surcharge); a precompile's address holding such a delegation is refused before its dispatch. A frame that cannot reach the delegate (3,100 for a cold target, 200 for a warm one, with no input and no value) runs out of gas instead of being refused; every other refusal still costs nothing. Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, and paying that access keeps a delegator of the beneficiary — which, the beneficiary being fixed, stays one for every later block — from being read for about 181 gas, so every cold account read costs the cold access; keeping the memory charged stops a loop of refused calls with MiB-sized ranges from having the node grow and zero memory for about 270 gas a call (ten 3 MiB calls fit in a transaction at the execution cap, where handing the expansion back allowed 658,337 of them, about 1.9 TiB of memory grown). diff --git a/AGENTS.md b/AGENTS.md index 23427ffaf..98cdc4d05 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -433,7 +433,9 @@ Detention caps how much a transaction may still compute once it read such data ( A call whose target operand is not the beneficiary is refused where it loads its target's one-hop EIP-7702 delegate, which only the target's code names: it runs its steps before that load as with access on — its static gas, the static-context check of a value `CALL`, its memory, its value transfer, the load of its target's account and code, which a frame short of the cold surcharge skips as an out-of-gas, and the check that the frame holds the target's access and the delegate's warm access — and the Host refuses the delegate's load when the delegate is the beneficiary (`MegaContext::load_account_info_skip_cold_load`), before the call charges its target's access, any state gas or its forward and before the frame-start hook. The wrapper (`settle_reads` in `evm/instructions.rs`) then puts back the gas the frame held when it reached the call — the spendable and withheld parts and the reservoir — and charges what the call did up to the target's load but its value transfer, as with access on: the warm access, the memory the opcode grew (the growth of the gas's memory record, which stays at the grown memory) and, when the Host found the target cold as it loaded it (`Detention::note_load`, noted for the running opcode only), the cold surcharge, as `BALANCE` charges it, each a regular charge of the spendable part in that order. A cold surcharge past what the frame may spend is gas detention's crossing, and the frame ends with the compute stop; otherwise it reverts with the refusal, having paid that and nothing else of the call — not its value transfer or the delegate's access; the warm access and the memory were paid from the same spendable gas before, and the call held the target's access and the delegate's warm access to reach the delegate, so the charges never run out of gas. + Detention reads compute off the frame's gas, so the charges made again count once and the value transfer the restoration gave back counts as none; a value call's restored spendable gas still holds that value transfer, so a value call always pays its surcharge. The frame's end takes back the warming the frame made, warmth from before the call staying, and the target's account and code stay in the transaction's state and witness, the beneficiary unloaded and nothing marked. + A precompile's address whose state holds a delegation to the beneficiary is refused the same way, inside the call opcode, before the frame start that would dispatch the precompile, so the precompile never runs. A call that fails or is stopped before the target's load reads nothing, as with access on; once the load is reached it is required, and a database error fails the transaction with its cause, never taken for a target without a delegate. So a call of a delegator of the beneficiary is refused only from a frame that holds the gas to reach the delegate (with no input and no value, 3,100 for a cold target, 200 for a warm one), paying 3,000 or 100, as a read of the delegator with access on would; a frame holding less runs out of gas, as with access on. Every other refused read costs nothing. diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index b027419a9..6f0f17a44 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -325,12 +325,20 @@ fn refused_read( /// range inside memory the frame already held, the record kept at the grown memory; then, when /// the Host found the target cold, the cold surcharge, as `BALANCE` charges it. That is the gas /// the frame held once its memory was grown, less the surcharge: the value transfer and the -/// delegate's access are not paid. The first two charges were made from the same spendable gas -/// already. A frame whose spendable part cannot pay the surcharge holds it in its withheld part — -/// the call held its target's access and the delegate's warm access to reach the delegate — so -/// the charge is gas detention's crossing, and the frame ends with the compute stop rather than -/// the refusal. Otherwise it is refused: its revert takes back the target's warming, and leaves -/// the target's account and code in the transaction's state. +/// delegate's access are not paid. Gas detention reads compute off the frame's gas, so the charges +/// made again count once, and the value transfer the restoration gave back counts as none. +/// +/// The first two charges were made from the same spendable gas already. A frame whose spendable +/// part cannot pay the surcharge holds it in its withheld part — the call held its target's access +/// and the delegate's warm access to reach the delegate — so the charge is gas detention's +/// crossing, and the frame ends with the compute stop rather than the refusal; no charge here can +/// run out of gas. A value call's restored spendable part still holds the value transfer it paid +/// before the load, which covers the surcharge, so a value call always pays it. Otherwise the frame +/// is refused: its revert takes back the warming the frame made, and leaves the target's account +/// and code in the transaction's state. +/// +/// The target may be a precompile's address whose state holds a delegation: the refusal comes +/// before the frame start that would dispatch the precompile, so it never runs. #[inline(never)] fn settle_reads( interpreter: &mut Interpreter, diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 2311c62f5..a2763b4fe 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -926,7 +926,7 @@ The revert data: | 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. -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. +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 whose charges are not gas detention's crossing 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)). @@ -980,6 +980,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th A regular charge beyond the frame's whole regular gas, and every other out-of-gas, MUST halt as it would without the read. Each part an opcode deducts from regular gas is one charge, held to the spendable part where the opcode deducts it, in the opcode's order: its static gas, then each dynamic part it deducts on its own; the first part the spendable part cannot pay decides, as the crossing when the frame's whole regular gas can pay it and as an out-of-gas when it cannot. An Oracle read's cold access and an interceptor's answer are each one charge instead (see Interceptor answers, below, and [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)): an `SLOAD` of another contract's storage pays its static 100 and then its cold access as two charges, the Oracle's `SLOAD` its 2,100 as one. + For a call refused at its target's EIP-7702 delegate, the restoration and the charges of the refusal come before the crossing is decided: the call's gas is restored to what it held at the opcode, its static cost and its memory expansion are charged again, and only its cold surcharge, charged last, can cross, so the value-transfer cost the restoration gave back is not among what stays spent (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)). - **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. @@ -987,6 +988,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th Every precompile of the Satin set has a price for every input: an input over an Optimism pairing or MSM size limit is priced at zero, since it is refused before any gas check, and a ModExp input is priced by its Osaka formula whatever its lengths, one over EIP-7823's bound included, since ModExp charges that price before it checks the bound. An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check — a ModExp input over EIP-7823's bound among them — is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. + A call runs a precompile, and is priced by it, only once it reaches the precompile's dispatch, whatever code the state holds at the address, an EIP-7702 delegation indicator included; the call opcode's earlier charges, checks and refusal come first, so with access off a call of a precompile's address whose indicator names the block beneficiary ends at or before the delegate's load and never reaches the dispatch (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)). - **Interceptor answers.** A system contract's intercepted answer that spent more regular gas than the frame's allowance, state and history gas that spilled onto its regular gas not counted, MUST be the crossing. The answer's whole regular spend MUST be treated as the one charge that crossed: none of it is billed, the part within the allowance included, so the stop's compute is the transaction's compute when the frame started. @@ -1005,7 +1007,8 @@ The reference implementation has no price for one, so it runs such a precompile #### Previous behavior - A read refused by `disableVolatileDataAccess()` reverts the frame immediately with `VolatileDataAccessDisabled(VolatileDataAccessType)`; `BLOCKHASH` and `BLOBHASH` are refused before their operands are checked. -- A call opcode in a frame whose access is off looks up its target's one-hop EIP-7702 delegate before it charges anything, and is refused when that delegate is the block beneficiary, for no gas. +- A refused read pays nothing, not even its opcode's static gas, whatever gas the frame holds. + A call opcode whose target's one-hop EIP-7702 delegate is the beneficiary is refused the same way, before any of its charges: the node looks the target's account and code up first, as a best-effort read, even in a frame that could not pay the call's static gas. - `MegaLimitControl.remainingComputeGas()` answers from a separate compute-gas ledger with per-frame budgets of 98/100 of the caller's remaining compute, and can exceed the caller's gas. #### New behavior @@ -1017,24 +1020,49 @@ The reference implementation has no price for one, so it runs such a precompile - An opcode volatile only for the account or the storage it reads — `BALANCE`, `SELFBALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four call opcodes, `SELFDESTRUCT` and an `SLOAD` of the Oracle's storage — MUST first have every operand it takes on the stack: one that fails on its operands (a stack underflow, for example) fails as it would with access on. Once its operands are there, it MUST be refused when what its operands and its frame name is the beneficiary's account or the Oracle's storage: the target operand of `BALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH` or a call opcode; the executing frame's own address for `SELFBALANCE`, and for `SELFDESTRUCT`, whose target operand is checked too; the frame's storage for an `SLOAD`. The refusal comes before the opcode charges anything and before any other check its body makes — a memory expansion, a copy, a static-context check, a value transfer, a state charge — so an `EXTCODECOPY` of the beneficiary with a large length, or a call to it the frame could not fund, is refused rather than running out of gas. - Either refusal comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. -- A call opcode whose target operand is not the block beneficiary MUST run, in a frame whose access is off, the steps it runs with access on before it loads its target's one-hop EIP-7702 delegate: its static gas, the static-context check of a value-bearing `CALL`, its input and output memory, its value transfer, the load of its target's account and code — skipped as an out-of-gas when the target is cold and the frame's regular gas, its withheld part included, is below the cold surcharge — and, for a target that holds a delegation, the check that the frame holds the target's access and the delegate's warm access. - A call that fails on one of those steps, or that gas detention stops on one, fails or is stopped as it would be with access on, and reads its target only when it reached the target's load. - When the call reaches the load of the delegate and the delegate is the block beneficiary, the load MUST be refused as the beneficiary's account (10), before the call charges its target's access on its normal path, any new-account state gas, its forward or its start's history gas, and before any frame starts: the beneficiary's account is not loaded and nothing is marked for gas detention. - The call has read its target's account and code by then, which is no volatile read, and grown the frame's memory, which the node did, so the frame MUST pay both, from the gas it held when it reached the call, as the same call charges them with access on: `WARM_STORAGE_READ_COST` (100); then the call's memory expansion, the growth its input and output ranges made to the frame's memory, nothing for a range inside memory the frame already held; then, when the target was not warm before the call, `COLD_ACCOUNT_ACCESS − WARM_STORAGE_READ_COST` (2,900), as `BALANCE` charges it; as regular charges in that order. - That is the gas the frame held once the call's memory was grown, less the cold surcharge: the call's value transfer and the delegate's access are not paid, and the frame's regular gas, both the spendable and the withheld parts, and its reservoir are otherwise what it held when it reached the call. - The memory stays grown, priced as grown. - Whether the target was warm before the call is EIP-2929's: whether it is among the transaction's accessed addresses when the call loads it, which the access list, an earlier access no revert took back and the addresses warm from the transaction's start, the precompiles among them, put it in. - When the target was not warm and the frame's spendable regular gas after the warm access and the memory cannot pay the cold surcharge, the surcharge is gas detention's crossing and the frame is stopped with `MegaLimitExceeded(2, limit)` (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)); otherwise the frame reverts with `VolatileDataAccessDisabled(10)`. - The warm access and the memory were paid from the same spendable gas before the load, and the frame's whole regular gas then covers the cold surcharge, since the call held the target's access and the delegate's warm access to reach the delegate, so the charges never run out of gas. - The target's account and code stay in the transaction's read set, and the frame's end takes back only the warming the frame made: the target is as warm or as cold for the caller as it was before the call, warmth from the access list, the transaction's start or an earlier frame staying. - The target's load is a required read: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. - So a call of a delegator of the beneficiary with no input and no value is refused from a frame holding its static gas, the target's cold surcharge when the target is cold, and the delegate's warm access — 3,100 for a cold target, 200 for a warm one — paying the target's access, 3,000 or 100, and handing the rest back to its caller; a frame holding less runs out of gas: holding 2,999 at a call of a cold delegator, before its target is read; holding 3,000 to 3,099, after. - Reading a delegator of the beneficiary into the transaction's read set so costs the cold access, as reading any other account does, and growing memory for a refused call costs what it costs with access on. - Under gas detention, a frame that may spend less than the cold access reads such a target and is stopped at the surcharge, keeping at least the warm access, so at most 29 such reads fit in that last window at the current schedule. -- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` and, but for what a call refused at its target's delegate pays (above), MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost — a cold access, a copy's memory, a call's memory or value transfer. - The frame reverts on the gas it held when it reached the opcode — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged but that. - A read refused before the opcode's body, which is every refusal but a call's at its target's delegate, is refused all the same in a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. + A call whose target operand is not the beneficiary but whose target delegates to it follows the rule below. + Every refusal comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. +- In a frame whose access is off, a call opcode (`CALL`, `CALLCODE`, `DELEGATECALL` or `STATICCALL`) whose target operand is not the block beneficiary MUST look nothing up before its own steps, and MUST make the steps before its delegate's load as it would with access on: + - its static cost, `WARM_STORAGE_READ_COST` (100), and the static-context check of a `CALL` that carries value; + - its memory expansion for its input and output ranges, and the value-transfer cost of a `CALL` or `CALLCODE` that carries value; + - the load of its target's account and code, skipped with an out-of-gas halt when the target is not warm and the regular gas left, both parts counted, is below the cold surcharge, `COLD_ACCOUNT_ACCESS − WARM_STORAGE_READ_COST` (2,900); + - when the target holds an EIP-7702 delegation indicator, the delegation guard, which halts the call out of gas unless the regular gas left, both parts counted, covers the target's cold surcharge, not yet deducted (2,900 for a target that was not warm, zero for one that was), plus `WARM_STORAGE_READ_COST` for the delegate's access; the static cost the call has paid is not counted again. + + A call that fails at one of these steps, or is stopped at one as gas detention's crossing, has not reached its delegate's load and ends as it would with access on; it has read its target's account and code exactly when it made the target's load, which a cold load skipped for its surcharge does not make. + When the call reaches its delegate's load and that one-hop delegate is the block beneficiary, the load MUST be refused as the beneficiary's account (10) before anything else on the call's path: before the target's cold surcharge, any new-account state gas, the forward and the start's history gas, and before any frame starts. + The beneficiary's account is not loaded and nothing is marked for gas detention. + +- The call has made its earlier steps and read its target's account and code, which is not a volatile read, so it MUST pay its target's access and its memory expansion, and nothing else: + - its regular gas, the spendable and the withheld part, MUST be restored to what it held when the opcode was reached; + - it MUST then be charged, as regular charges and in this order: its static cost, `WARM_STORAGE_READ_COST`; its memory expansion; and, when the target was not warm, its cold surcharge, `COLD_ACCOUNT_ACCESS − WARM_STORAGE_READ_COST`, last; + - its memory expansion is this opcode's own growth of memory for its input and output ranges together, at the base layer's price, and nothing for a range already within the frame's memory; it is not the frame's whole memory cost. + + The first two charges leave the call's gas as it was just after its memory expansion: the static cost and the memory expansion stay charged and count as compute once, as the charges made again, and the value-transfer cost of a call that carries value is given back and is not compute; the refused delegate's access is never charged. + Nothing before the delegate's load draws on the reservoir, so the restoration and the charges leave it as the opcode found it; the frame's end rolls back its own state and history charges as any revert or stop does. + The memory stays grown. + For these rules the target was warm when it was among EIP-2929's accessed addresses as they stood when the call reached the target's load: the addresses warm from the transaction's start — the precompiles, the block beneficiary, the addresses of the access list, the sender and the recipient, and the `SequencerRegistry`'s account (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)) — and every address an earlier access warmed that no rollback has taken back, the authorities the authorization list's application warmed included; the call's own load of the target does not count. + No charge of that settlement can run out of gas: the static cost and the memory expansion were paid from the same gas before the delegate's load, and the delegation guard held the regular gas left after them and after the value-transfer cost to at least the cold surcharge plus `WARM_STORAGE_READ_COST`. + The cold surcharge MUST therefore be paid, or be gas detention's crossing when the spendable part cannot pay it, and MUST NOT halt the frame out of gas; when it is the crossing, the gas is put back to what it was just before it, so the memory expansion stays charged at the stop as well. + A call that carries value always pays it: the value-transfer cost it paid from its spendable gas before the load, and was given back, leaves room for the surcharge there. + The frame MUST revert with `VolatileDataAccessDisabled(10)`, or, when the cold surcharge is gas detention's crossing, MUST be stopped with `MegaLimitExceeded(2, limit)` instead (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). + The frame's end, the revert or the stop, leaves the target's account and code in the transaction's read set, and rolls EIP-2929's accessed addresses back to the ending frame's checkpoint, taken when that frame started: the warming the frame took, its warming of the target included, is undone, and a warmth from before the frame started stays. + Whenever the call makes its target's load, the load is a required read: a failed read of the target's account or code gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and is never taken as a target without a delegate. + A precompile's address is no exception: a call of one whose state holds an indicator naming the beneficiary is refused at the delegate's load, before the precompile's dispatch, paying the warm access and its memory expansion, and the precompile does not run. + So a call of a delegator of the beneficiary with no input and no value is refused from a frame holding its static cost, the target's cold surcharge when the target is cold, and the delegate's warm access — 3,100 for a cold target, 200 for a warm one — paying 3,000 or 100 and handing the rest back to its caller; a frame holding less runs out of gas: holding 2,999 at a call of a cold delegator, before its target is read; holding 3,000 to 3,099, after. + +- Under gas detention a cold load is decided on the frame's whole regular gas and each charge on its spendable part, so near the limit a load can complete and the charge after it cross. + On this path that charge is the cold surcharge: such a stop reads one target and keeps at least the static cost, `WARM_STORAGE_READ_COST`, as compute, and the first can come only once the allowance, what the limit leaves the transaction, is below `COLD_ACCOUNT_ACCESS` after the call's memory expansion, so at most 29 such reads fit in a transaction's last allowance window, whatever the program. + The inherited call path has a tail of its own, which this rule does not change: a call whose target and non-beneficiary delegate are both cold loads both accounts before it deducts their combined charge, 5,900 after its static cost, so its window is an allowance below 6,000, and at most 59 such calls, 118 accounts, fit in it. + A pre-built call stack that discards each returned status reads 116 accounts in 58 calls; reusing that status as the next call's gas operand permits 59 calls and 118 account reads. + Both bounds are accepted: they follow from deciding a load on the whole regular gas and a charge on the spendable part, and they apply once, at the end of a transaction's allowance. +- Against Rex6, which read the target before any charge and refused such a call for free: + - a call that reaches the delegate refusal pays its own memory expansion and 3,000 for a cold target or 100 for a warm one, and when the cold surcharge is gas detention's crossing only 100 and the memory expansion stay charged; + - a call that fails or is stopped before its target's load, or whose cold load is skipped for insufficient whole regular gas, does not read its target, which Rex6 read; a target loaded before a failed delegation guard stays in the read set; + - either failure ends the frame with an out-of-gas halt, which returns no data and none of the frame's gas, or with the stop, where Rex6 reverted with `VolatileDataAccessDisabled(10)` and returned the frame's gas; + - a cold surcharge that is gas detention's crossing ends the frame with the 68 bytes of `MegaLimitExceeded(2, limit)` instead of the 36 bytes of `VolatileDataAccessDisabled(10)`. +- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)`, unless it is a call refused at its target's delegate whose cold surcharge is gas detention's crossing, which MUST stop the frame with `MegaLimitExceeded(2, limit)` instead. + A read refused before the opcode's body — every refusal but a call's at its target's delegate — MUST NOT consume any gas: neither the opcode's static gas nor any dynamic cost, a cold access, a copy's memory, a call's memory or value transfer. + Such a frame MUST revert on the gas it held when the opcode was reached — its regular gas, both the spendable and the withheld parts, and its reservoir — nothing having been charged, and a frame whose regular gas is below the opcode's static gas, or below what the opcode's body would charge, is refused all the same and does not run out of gas: with access off, an `EXTCODECOPY` of the beneficiary of 1 MiB on 1,000 regular gas reverts with `VolatileDataAccessDisabled(10)` keeping the 1,000. A refused read marks nothing for gas detention and asks no oracle service. - The error's argument MUST be ABI-encoded as a `uint8`: @@ -1458,7 +1486,7 @@ The witness is defined by what the block's execution returns and exports, and a A failed read is reported as [Transaction and Block Refusals](#21-transaction-and-block-refusals) classifies it: the fee computation's as a read of the transaction's own execution, the footprint scalar's as a read block execution makes for the transaction outside its execution, always an internal error. The reads change nothing: the entries are not written. - **The reads a validator makes again.** - A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, other than an Oracle read, which is made before its cold access is charged (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), a `BLOCKHASH` of the current block or outside the last 256 blocks, a read a frame whose volatile-data access is off is refused (the target of a call refused at its EIP-7702 delegate is no refused read: the call loads it before the refusal, and the witness carries it), a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. + A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less whole regular gas than the cold surcharge, other than an Oracle read, which is made before its cold access is charged (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), a `BLOCKHASH` of the current block or outside the last 256 blocks, a read a frame whose volatile-data access is off is refused (a call's completed read of its target's account and code is no refused read: it stays in the witness when the call's EIP-7702 delegate is then refused, and when the target's cold surcharge is then gas detention's crossing), a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. - **The SALT buckets.** Block execution exports the set of SALT buckets the SALT environment answered with a valid capacity during the block, emptied when the block starts and accumulated over everything executed for the block. A bucket is in the set once it was answered with a valid capacity, whether or not the transaction that asked is in the block: a candidate the builder executed and dropped leaves its buckets in the set, which a validator does not need. @@ -1513,6 +1541,7 @@ 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`. +A call refused, with access off, at a target that delegates to the beneficiary now pays that target's access (3,000 cold, 100 warm) and its memory expansion, where Rex6 charged nothing (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)). Every movement of value to another account now emits a `Transfer` log from `0xff…fe`, which indexers see in receipts beside the contracts' own logs; a `CALLCODE`, a call to oneself, a deposit's mint and a self-destruct to oneself emit none. From e71fd07f4c6993486d27fc31c55067f28eab775d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:32:38 +0800 Subject: [PATCH 066/190] feat(evm): price deposit and system transaction history Keep only system calls exempt. Report failed-deposit body bytes and skip unfunded creation records. Rewrite the user-deposit detention test to include paid body history. --- AGENTS.md | 14 +- bin/mega-evme/tests/satin-differences.md | 10 +- crates/mega-evm/benches/transact.rs | 10 +- crates/mega-evm/src/evm/context.rs | 61 ++++---- crates/mega-evm/src/evm/execution.rs | 29 ++-- crates/mega-evm/src/evm/factory.rs | 4 +- crates/mega-evm/src/evm/result.rs | 9 +- crates/mega-evm/src/evm/validation.rs | 5 +- crates/mega-evm/src/limit/limit.rs | 37 +++-- crates/mega-evm/src/limit/mod.rs | 5 +- .../mega-evm/tests/block/receipt_goldens.rs | 16 +-- crates/mega-evm/tests/block/rules.rs | 2 +- .../tests/block/sequencer_registry.rs | 4 +- crates/mega-evm/tests/block/witness/basics.rs | 3 +- crates/mega-evm/tests/block/witness/state.rs | 17 ++- crates/mega-evm/tests/block/witness/system.rs | 6 +- crates/mega-evm/tests/fuzz/properties.rs | 38 +++-- crates/mega-evm/tests/satin/equivalence.rs | 10 +- crates/mega-evm/tests/satin/failed_deposit.rs | 131 +++++++++++++++++- crates/mega-evm/tests/satin/floor_exempt.rs | 59 ++++---- .../mega-evm/tests/satin/history_exemption.rs | 119 +++++++++------- crates/mega-evm/tests/satin/history_gas.rs | 8 +- .../mega-evm/tests/satin/limit_exemption.rs | 4 +- .../mega-evm/tests/satin/pool_validation.rs | 36 ++--- crates/mega-evm/tests/satin/system_call.rs | 25 ++-- crates/mega-evm/tests/satin/transfer_logs.rs | 11 +- .../mega-evm/tests/satin/volatile_access.rs | 18 ++- crates/mega-evm/tests/system/system_tx.rs | 11 +- crates/mega-evm/tests/tracers/scenarios.rs | 8 +- docs/spec/upgrades/satin.md | 24 ++-- 30 files changed, 462 insertions(+), 272 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2d256bfef..686473b75 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -184,13 +184,15 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - 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 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's record charge is the transaction's start charge on the start ledger, parked where its input is built (`first_frame_input`), which the transaction's start settlement gives back when the frame fails, and after a halt burns every regular gas the transaction's gas then holds, the refund's credit included, as revm's settlement burned it after each refund of its own. - A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas. + An ordinary transaction whose gas limit cannot cover the body is rejected at validation; a deposit is included as a failed deposit. 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 parks the frame's own as the start's charge on the start ledger, which gives it back to the caller when the frame fails (`Host::frame_settle`). 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. + Deposits and system-originated transactions pay history for their body, calldata, logs, write records and deposited code. + Only system calls pay no history (`MegaContext::prices_history`), with a schedule that prices deposited code at zero too. + A failed deposit reports its whole gas limit as regular gas and zero history gas, but keeps its body and calldata as history bytes even when validation fails before body admission. The EIP-7623 calldata floor is still computed and validated. - At the spec's byte prices it never raises the gas used of a transaction that pays history, because history charges the same bytes at a higher rate; it can raise an exempt transaction's, and it binds the figure a block counts on its execution ledger, `max(regular, floor)`. + At the spec's byte prices it never raises the gas used of a transaction that pays history, because history charges the same bytes at a higher rate; it binds the figure a block counts on its execution ledger, `max(regular, floor)`. - A value-transferring `CALL` or `CALLCODE` below the transaction's own frame grants the frame it starts a history allowance of 160 bytes — one three-topic event carrying a word — at the cost per history byte, so a `receive()` hook reached through Solidity's `transfer()` can still emit an event. It is not gas: it never enters the frame's `Gas`, only a log's charge may draw on it, and what it pays for is on no ledger, because no pool of the transaction's gas paid it. The history bytes a transaction reports count those bytes all the same, so the byte column and the history gas column part by exactly what allowances paid. @@ -255,7 +257,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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::is_exempt`, read off the class the layer begins the execution as, as `MegaContext::prices_history` is), 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. + History gas exempts only system calls; the protocol's transactions pay for what they append. The class is decided when the layer prepares a transaction or a system call, so a transaction set on the context and not run yet changes neither the exemption nor what it pays. Switching the context to the neutral configuration decides that an ordinary execution pays no history, until the next preparation decides again: switching back with `with_cfg` alone does not price it, so a system call run straight through the handler, which prepares nothing, pays none (`tests/satin/history_exemption.rs`). The exemption covers the KV updates and state growth beside data size. @@ -553,8 +555,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer The regular ledger is `total − state − history`, read off the result revm's `Gas` settled into; nothing counts compute beside it, so gas an inspector edits moves it with the receipt. The figure a block counts is `max(regular, floor)`, history taken out before the floor applies: the fork's `block_regular_gas_used` keeps history in, and subtracting it afterwards can land below the floor. The three add up to the raw spend, which is why what a history allowance paid for is on none of them: no pool of the transaction's gas paid it. - `history_bytes` counts it all the same — the body, one 40-byte record per kept write, the kept logs but for the transfer logs, and the deposited code — so the bytes at the cost per history byte exceed the history gas by exactly what allowances paid; an exempt transaction reports neither. - 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. + `history_bytes` counts it all the same — the body, one 40-byte record per kept write, the kept logs but for the transfer logs, and the deposited code — so the bytes at the cost per history byte exceed the history gas by what allowances paid, except for a failed deposit, which keeps its body and calldata as bytes and reports no history gas; a system call reports neither. + It is the history the schedule prices, not the chain's physical growth: a system call'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. diff --git a/bin/mega-evme/tests/satin-differences.md b/bin/mega-evme/tests/satin-differences.md index 40079bde1..4754fe3aa 100644 --- a/bin/mega-evme/tests/satin-differences.md +++ b/bin/mega-evme/tests/satin-differences.md @@ -39,9 +39,9 @@ The three Rex6 blocks of `tests/fixtures/blocks.tar.xz`, each replayed on both e | Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | History | Status differs | Logs | Refused | |---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:| -| 26400001 | 39 | 10592072 | 13873243 | 1.30 | 8818227 | 0 | 5065016 | 17 | 138 -> 121 | 4 | -| 26400007 | 25 | 8428932 | 10696856 | 1.26 | 6203136 | 0 | 4493720 | 0 | 119 -> 119 | 0 | -| 26400110 | 27 | 8051381 | 10550686 | 1.31 | 6059166 | 0 | 4491520 | 1 | 121 -> 121 | 1 | +| 26400001 | 39 | 10592072 | 14178164 | 1.33 | 8788572 | 0 | 5399592 | 18 | 138 -> 121 | 5 | +| 26400007 | 25 | 8428932 | 11068218 | 1.31 | 6143826 | 0 | 4924392 | 2 | 119 -> 119 | 2 | +| 26400110 | 27 | 8051381 | 10874000 | 1.35 | 5999856 | 0 | 4874144 | 3 | 121 -> 121 | 3 | ## Recorded transactions by call target @@ -49,9 +49,9 @@ The transactions of the three blocks grouped by the contract they call and the s | Call target | Selector | Transactions | Legacy gas | Satin gas | Satin / legacy | State gas | Status differs | Logs | |---|---|---:|---:|---:|---:|---:|---:|---| -| 0x6342000000000000000000000000000000000001 | 0x01caec13 | 31 | 2532545 | 771030 | 0.30 | 0 | 5 | 0 -> 0 | +| 0x6342000000000000000000000000000000000001 | 0x01caec13 | 31 | 2532545 | 1631763 | 0.64 | 0 | 10 | 0 -> 0 | | 0x897a33a0af45b3ba097bd6045187d622252e6acd | 0x9aec351f | 30 | 18019164 | 26445264 | 1.46 | 0 | 0 | 330 -> 330 | -| deposit | - | 3 | 304908 | 141288 | 0.46 | 0 | 0 | 0 -> 0 | +| deposit | - | 3 | 304908 | 280152 | 0.91 | 0 | 0 | 0 -> 0 | | 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x21d5c9bb | 2 | 601407 | 832935 | 1.38 | 0 | 0 | 6 -> 6 | | 0x57677bdc4f24d5c08ddce87e06670c26a00cac0b | 0xb7a16251 | 2 | 1559890 | 1647024 | 1.05 | 0 | 0 | 19 -> 19 | | 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fad7 | 2 | 151028 | 135924 | 0.89 | 0 | 0 | 0 -> 0 | diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 81a7def05..e28d46e01 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -11,6 +11,8 @@ //! `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. +//! - `deposit_logs`: the same logs in a deposit with 32 bytes of calldata, paying history for both +//! its body and its logs. //! - `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. //! - `intercepted_calls`: 200 `STATICCALL`s to `MegaAccessControl`'s @@ -427,7 +429,10 @@ fn bench_transact(c: &mut Criterion) { let mut depth = [0u8; 32]; depth[31] = DEPTH; + let mut deposit_logs = call_tx(LOGGER, Bytes::from(vec![0xab; 32]), 30_000_000); + deposit_logs.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); let workloads = [ + ("deposit_logs", deposit_logs), ("empty_transaction", tx(U256::ZERO)), ("ether_transfer", tx(U256::from(1))), ("deep_calls", call_tx(RECURSIVE, Bytes::from(depth.to_vec()), 30_000_000)), @@ -481,10 +486,9 @@ fn bench_transact(c: &mut Criterion) { satin.state[&RECURSIVE].storage.values().filter(|s| s.is_changed()).count(); assert_eq!(written, DEPTH as usize, "every frame of the recursion ran"); } - "logs" => assert_eq!( + "logs" | "deposit_logs" => assert_eq!( satin.gas.history, - (TX_BODY_SIZE + REPEAT * (LOG_BASE_SIZE + 2 * LOG_TOPIC_SIZE + 32)) * - COST_PER_HISTORY_BYTE, + (body + REPEAT * (LOG_BASE_SIZE + 2 * LOG_TOPIC_SIZE + 32)) * COST_PER_HISTORY_BYTE, "the logs must draw history gas, which is what this arm measures", ), "calldata" => assert_eq!( diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 8f7d3c791..ec336be0a 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -433,27 +433,17 @@ impl MegaContext { /// in the state the EVM runs on, so every EVM answers as block execution does, however it was /// built. It is the common execution layer's exemption, which is decided once with it /// ([`AdditionalLimit::is_exempt`]): the protocol's own work is held to no per-transaction - /// limit, is not detained, pays no history gas and prices at the minimum bucket, all for the - /// one reason. + /// limit, is not detained and prices at the minimum bucket. History gas is exempt only for + /// system calls. pub const fn is_system_originated(&self) -> bool { self.additional_limit.is_exempt() } /// Whether the running (or last) transaction pays history gas for the bytes it appends. /// - /// Three kinds of transaction pay none: a deposit, a transaction the protocol itself produced - /// ([`system::is_system_originated`]) and a system call. What they append is the chain - /// carrying its own weight — a deposit the sequencer relays, the maintenance a system - /// transaction performs, the pre-block calls the protocol makes — and there is no sender to - /// charge for it. - /// - /// The two predicates are distinct and both are needed. A deposit is not system-originated: - /// it carries a user's source hash and a user's caller, so it prices its state gas by the - /// SALT bucket like any other transaction — it is exempt from history alone, because the - /// bytes it appends were paid for on L1. A system transaction is both: it prices at the - /// minimum bucket *and* pays no history. - /// - /// The neutral configuration prices no history at all. + /// Deposits and system-originated transactions pay for the history they append, even though + /// a deposit pays no fee. Only system calls are exempt: they append no transaction to the + /// block. The neutral configuration prices no history either. /// /// It is decided when the transaction is prepared, with its exemption, from what it is then /// (a promoted system-address transaction is the protocol's own either way) and the @@ -461,7 +451,10 @@ impl MegaContext { /// neither until it is prepared. Switching the context to the neutral configuration decides /// it too, and switching back alone does not: the next preparation decides again. pub const fn prices_history(&self) -> bool { - matches!(self.additional_limit.class(), TxClass::Ordinary) + matches!( + self.additional_limit.class(), + TxClass::Ordinary | TxClass::Deposit | TxClass::ProtocolOwn { prices_history: true } + ) } /// The history gas of the running (or last) transaction's body — the bytes it carries and the @@ -495,8 +488,8 @@ impl MegaContext { /// validation has read the live system address, so the layer is prepared before anything /// else of the transaction runs. pub(crate) fn on_new_tx(&mut self, system_transaction: bool) { - self.prepare(system::originates_from_the_protocol(&self.inner.tx, system_transaction)); self.system_call = false; + self.prepare(system::originates_from_the_protocol(&self.inner.tx, system_transaction)); // Decided before a system-address transaction is promoted to a deposit, so it is told // apart by `system_transaction`, and any other deposit by its type. self.oracle_service = @@ -510,8 +503,8 @@ impl MegaContext { /// A system call is system-originated whatever caller it names: it is the protocol running, /// not a transaction anybody sent. pub(crate) fn on_new_system_call(&mut self) { - self.prepare(true); self.system_call = true; + self.prepare(true); self.oracle_service = false; } @@ -601,9 +594,8 @@ impl MegaContext { /// /// A system-originated transaction is exempt from every per-transaction limit — the data size /// and its frame budgets — before anything is counted, its body included: the protocol's own - /// work must not fail on a resource limit, as it pays no history gas for the same reason. What - /// it uses is counted all the same. A user's deposit is not system-originated and is held - /// to every one of them. + /// work must not fail on a resource limit. What 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.bucket_multipliers.reset(); self.oracle_reads.clear(); @@ -611,14 +603,14 @@ impl MegaContext { // creation unsettled. self.keyless_creation = None; // 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. + // a system transaction and an ordinary transaction all pay for it; a system call does not. let body = transaction_body_bytes(self.tx()); let class = if system_originated { - TxClass::ProtocolOwn - } else if self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE { - TxClass::Deposit + TxClass::ProtocolOwn { prices_history: !self.system_call && !self.runs_neutral() } } else if self.runs_neutral() { TxClass::Neutral + } else if self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE { + TxClass::Deposit } else { TxClass::Ordinary }; @@ -627,7 +619,7 @@ impl MegaContext { // The protocol's own transactions are not detained: they maintain the volatile data. Their // reads set no cap. let limits = self.additional_limit.limits(); - let (block_env_cap, oracle_cap) = if class == TxClass::ProtocolOwn { + let (block_env_cap, oracle_cap) = if self.additional_limit.is_exempt() { (u64::MAX, u64::MAX) } else { (limits.block_env_access_compute_gas_limit, limits.oracle_access_compute_gas_limit) @@ -708,9 +700,9 @@ impl MegaContext { /// estimation reads the execution cap off it — then reads the configuration the EVM runs with. /// Applying it twice changes nothing. /// -/// A deposit, a system-originated transaction and a system call pay no history gas, and the EVM -/// runs them on a schedule that prices a deposited byte at nothing; it installs that schedule for -/// such a transaction and the spec's own for every other, so a configuration never carries it. +/// A system call pays no history gas, and the EVM runs it on a schedule that prices a deposited +/// byte at nothing. Every transaction runs the spec's own history pricing, deposits and +/// system-originated transactions included; a configuration never carries the exemption. /// /// Satin runs the Satin gas schedule (see [`satin_gas_params`]) on its Karst base, with EIP-8037 /// state gas and the EIP-2780 intrinsic cost switched on and gas above the execution cap going to @@ -1333,10 +1325,9 @@ mod tests { assert!(emits_transfer_logs(ctx.journal_ref())); } - /// The protocol's own work is held to no per-transaction limit, pays no history and is not - /// detained, all off the one exemption the layer begins it with: a call from the EIP-4788 - /// system address and a system call are; a user's transaction is held, pays and is detained, - /// and a user's deposit is held and detained but pays no history. + /// The protocol's own work is held to no per-transaction limit and is not detained. Only + /// a system call is exempt from history: a system-originated transaction and a user's + /// deposit both pay it. #[test] fn test_the_protocols_own_work_is_exempt_from_every_hold() { let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); @@ -1345,8 +1336,8 @@ mod tests { deposit.0.base.tx_type = DEPOSIT_TRANSACTION_TYPE; for (case, tx, own, pays) in [ ("a user's transaction", call_from(Address::repeat_byte(0x11)), false, true), - ("a user's deposit", deposit, false, false), - ("a call from the system address", call_from(SYSTEM_ADDRESS), true, false), + ("a user's deposit", deposit, false, true), + ("a call from the system address", call_from(SYSTEM_ADDRESS), true, true), ] { ctx.set_tx(tx); ctx.on_new_tx(false); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index af6af0090..454374df8 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -470,7 +470,8 @@ where /// 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. + /// failed. Its body and calldata remain history bytes even when validation never admitted + /// their charge; no history gas is reported because the whole gas limit is regular gas. /// /// It is the fatal cleanup of every entry point, so nothing the failed execution left is read /// by the next one on the same EVM, whatever cleanup op-revm made: @@ -504,8 +505,12 @@ where .. }) ); - if failed_deposit && deposit_created_caller(evm.ctx()) { - evm.ctx_mut().additional_limit.count_created_caller(); + if failed_deposit { + let priced = evm.ctx_ref().prices_history(); + evm.ctx_mut().additional_limit.settle_failed_deposit_history(priced); + if deposit_created_caller(evm.ctx()) { + evm.ctx_mut().additional_limit.count_created_caller(); + } } result } @@ -1623,10 +1628,10 @@ fn applied_authorities( /// The authorities' records are the transaction's own and outlive a first frame that fails; the /// first frame's record does not, so that frame carries what it cost 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. +/// record. A value the sender cannot fund is never charged; a creation whose sender's nonce +/// cannot be bumped gets the charge back when its start keeps nothing. A deposit or a caller +/// that turned the nonce check off can reach that nonce, which revm answers with a success and +/// no address. /// /// Answers the history gas the first frame's record was charged, which pre-execution keeps for /// the frame's input to carry, and nothing for a transaction that pays no history; `None` when the @@ -1645,13 +1650,19 @@ fn charge_records_made_outside_a_frame( /// The write records the transaction's own frame makes, as the journal's state stands before the /// first frame: the recipient's, when the value changes an account the transaction has not -/// changed, or the account a creation creates ([`charge_records_made_outside_a_frame`]). +/// changed, or the account a creation creates. A value the sender cannot fund, its deposit mint +/// already credited, makes no record ([`charge_records_made_outside_a_frame`]). fn first_frame_records( ctx: &MegaContext, ) -> u64 { let tx = ctx.tx(); match tx.kind() { - TxKind::Create => 1, + TxKind::Create => u64::from( + ctx.journal_ref() + .state + .get(&tx.caller()) + .is_some_and(|caller| caller.info.balance >= tx.value()), + ), TxKind::Call(to) => { 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"); diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 827f9bf17..74b49fdb0 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -228,8 +228,8 @@ mod tests { let (mega, _) = runs_with(&evm); assert_eq!( mega.gas_params, - crate::satin_gas_params_history_exempt(), - "a deposit runs the schedule that prices no history", + crate::satin_gas_params(), + "a deposit runs the same history pricing as every transaction", ); assert_eq!( mega.with_spec_and_gas_params(exported.spec, exported.gas_params.clone()), diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 8662b8a57..3040f0384 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -20,7 +20,8 @@ //! gas is what its own gas paid for. //! //! The byte count is the history the schedule prices, not the chain's physical growth: a -//! transaction exempt from history gas reports none of the bytes it carries, a body counts its +//! system call reports none, a failed deposit reports its body despite paying no history gas, +//! a body counts its //! five fixed write records even when fewer fee accounts are written, and the EIP-7708 transfer //! logs of its value movements, which nothing prices, are not in it. @@ -100,11 +101,11 @@ pub struct MegaGasUsage { /// them: nothing prices them. /// /// At the cost per history byte they are worth [`history`](Self::history) plus what the - /// history allowances of its value transfers paid, which no gas ledger carries. + /// history allowances of its value transfers paid, which no gas ledger carries. A failed + /// deposit is the exception: it reports its body and calldata here but no history gas. /// /// They are the history bytes the schedule prices, not the chain's physical growth: a - /// transaction exempt from history gas (a deposit, a transaction the protocol sent, a system - /// call) reports none, and the body counts its five fixed write records — the sender's + /// system call reports none, and the body counts its five fixed write records — the sender's /// account and the four accounts fees are credited to — even when fewer fee accounts are /// written. pub history_bytes: u64, diff --git a/crates/mega-evm/src/evm/validation.rs b/crates/mega-evm/src/evm/validation.rs index 43574a6d3..e5cbf0f38 100644 --- a/crates/mega-evm/src/evm/validation.rs +++ b/crates/mega-evm/src/evm/validation.rs @@ -43,8 +43,7 @@ pub struct IntrinsicGas { pub state: u64, /// The history gas of the transaction's body: its envelope, the five write records every /// transaction makes, its calldata, access list and authorizations, at the cost per history - /// byte. Zero for a transaction exempt from history gas: a deposit and a system-address - /// transaction. + /// byte, for a deposit and a system-address transaction as for any other transaction. pub history: u64, /// The EIP-7623 calldata floor. The gas limit must cover it, and a transaction pays at least /// it. At the spec's byte prices a transaction that pays history gas pays more than the floor @@ -94,7 +93,7 @@ impl IntrinsicGas { /// /// A deposit is validated as op-revm validates one: on its intrinsic gas, and on not being flagged /// as an L1 system transaction. A system-address transaction has its chain id checked and is -/// promoted to a deposit. Neither pays history gas. +/// promoted to a deposit. Both must cover their body's history gas. /// /// What is left to the state is left out: the sender's nonce, balance and code (EIP-3607), the /// system address's nonce and code for a system-address transaction, and the charges the state diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index e7c959013..a73cae4e8 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -131,10 +131,12 @@ pub struct AdditionalLimit { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum TxClass { /// The protocol's own work, a system-originated transaction or a system call: held to no - /// per-transaction limit, not detained, priced at the minimum bucket and paying no history. - ProtocolOwn, - /// A user's deposit: held to every limit like any transaction, and paying no history, its - /// bytes paid for on L1. + /// per-transaction limit, not detained and priced at the minimum bucket. + ProtocolOwn { + /// Transactions pay history; system calls and the neutral configuration do not. + prices_history: bool, + }, + /// A user's deposit: held to every limit and paying history like any transaction. Deposit, /// Any other transaction under the neutral configuration, which prices no history: held as /// an ordinary transaction is, paying no history. Switching the context to the neutral @@ -789,7 +791,7 @@ impl AdditionalLimit { /// Whether the running transaction is exempt from every per-transaction limit: the protocol's /// own work is. pub const fn is_exempt(&self) -> bool { - matches!(self.class, TxClass::ProtocolOwn) + matches!(self.class, TxClass::ProtocolOwn { .. }) } /// What the running (or last) execution is, decided when it was begun. @@ -802,9 +804,10 @@ impl AdditionalLimit { /// decides again. #[cfg(any(test, feature = "test-utils"))] pub(crate) const fn price_no_history(&mut self) { - if matches!(self.class, TxClass::Ordinary) { - self.class = TxClass::Neutral; - } + self.class = match self.class { + TxClass::ProtocolOwn { .. } => TxClass::ProtocolOwn { prices_history: false }, + _ => TxClass::Neutral, + }; } /* The start ledger */ @@ -863,6 +866,13 @@ impl AdditionalLimit { self.history_bytes } + /// Settles a failed deposit's history: its gas limit is reported entirely as regular gas, + /// but its body and calldata remain in the block even if validation never admitted them. + pub(crate) const fn settle_failed_deposit_history(&mut self, priced: bool) { + self.history_gas_spent = 0; + self.history_bytes = if priced { self.body } else { 0 }; + } + /// 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. @@ -929,7 +939,7 @@ mod tests { #[test] fn test_the_exemption_answers_every_crossing_and_lasts_one_transaction() { let mut limit = AdditionalLimit::default(); - limit.begin_transaction(TxClass::ProtocolOwn, 0); + limit.begin_transaction(TxClass::ProtocolOwn { prices_history: false }, 0); assert!(limit.is_exempt()); for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { for frame_local in [false, true] { @@ -1072,9 +1082,10 @@ mod tests { // A frame's pool before the draw: empty, short of the count, ample; an exempt // transaction's frames start with unlimited pools. let mut cases = 0; - for (class, pools) in - [(TxClass::Ordinary, &[0_u64, 4, 100][..]), (TxClass::ProtocolOwn, &[u64::MAX - 2][..])] - { + for (class, pools) in [ + (TxClass::Ordinary, &[0_u64, 4, 100][..]), + (TxClass::ProtocolOwn { prices_history: false }, &[u64::MAX - 2][..]), + ] { for tx_limit in [10_u64, u64::MAX] { for kept in [0_u64, 3, 8] { let limits = EvmTxRuntimeLimits::no_limits() @@ -1176,7 +1187,7 @@ mod tests { assert_eq!(limit.take_first_frame_charge(), None, "taken by the frame's input"); limit.keep_first_frame_charge(7); - limit.begin_transaction(TxClass::ProtocolOwn, 0); + limit.begin_transaction(TxClass::ProtocolOwn { prices_history: false }, 0); assert_eq!(limit.take_first_frame_charge(), None, "the next execution begins without it"); } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index f7c52a928..b48a8fccd 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -151,9 +151,8 @@ //! 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, 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 +//! the data size, the KV updates, the state growth and the frame budgets. Only system calls pay +//! no history gas; system-originated transactions pay for what they append. 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. //! diff --git a/crates/mega-evm/tests/block/receipt_goldens.rs b/crates/mega-evm/tests/block/receipt_goldens.rs index a7e811510..7601bacda 100644 --- a/crates/mega-evm/tests/block/receipt_goldens.rs +++ b/crates/mega-evm/tests/block/receipt_goldens.rs @@ -125,10 +125,10 @@ struct Kept { } /// The receipts root of the six encodings at the spec's byte prices. -const RECEIPTS_ROOT: &str = "93b0c0565033f73a5b75072f5ba52e4586a3fdee75a5fbc99109cc0a16ae07b7"; +const RECEIPTS_ROOT: &str = "9263b1c78590951e8e85b46554275a2119b40588df8d41dd86792cf3ce25dcd5"; /// `cumulative_gas_used` of each receipt at the spec's byte prices. -const CUMULATIVE_GAS: [u64; 6] = [15_000, 250_400, 465_080, 507_364, 746_082, 947_264]; +const CUMULATIVE_GAS: [u64; 6] = [42_280, 277_680, 492_360, 534_644, 773_362, 1_004_992]; /// The logs bloom of a receipt that carries no logs. const EMPTY_BLOOM: &str = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; @@ -143,17 +143,17 @@ const BLOOMS: [&str; 6] = /// Each receipt's EIP-2718 encoding at the spec's byte prices. const ENCODINGS: [&str; 6] = [ // the deposit - "7ef9010a01823a98b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c08001", + "7ef9010a0182a528b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c08001", // the value transfer - "f901a7018303d220b9010000000000000000000000080000000000000000000000000004000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000008000000000000000000000000000000000000001000400000000000000004000000000000000000000002000000000000000000000000f89df89b94fffffffffffffffffffffffffffffffffffffffef863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa00000000000000000000000002000000000000000000000000000000000000002a00000000000000000000000001000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000001", + "f901a70183043cb0b9010000000000000000000000080000000000000000000000000004000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000008000000000000000000000000000000000000001000400000000000000004000000000000000000000002000000000000000000000000f89df89b94fffffffffffffffffffffffffffffffffffffffef863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa00000000000000000000000002000000000000000000000000000000000000002a00000000000000000000000001000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000001", // the limit stop - "f9010980830718b8b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + "f901098083078348b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", // the failed call - "f90109808307bde4b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + "f901098083082874b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", // the creation - "f9010901830b6262b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + "f9010901830bccf2b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", // the system-address transaction - "f9010901830e7440b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + "f9010901830f55c0b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", ]; /// The six receipts of one block, and the receipts root of their encodings. diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index 3a4521165..4da29bdef 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -317,7 +317,7 @@ fn test_the_l1_info_deposit_prices_the_transactions_after_it() { .execute_transaction(&common::deposit_tx_to( L1_BLOCK_CONTRACT, Bytes::from(word.to_be_bytes::<32>()), - 200_000, + 200_000 + common::body_history(32) + mega_evm::write_record_history_gas(1).unwrap(), )) .expect("the deposit executes"); assert_eq!(state_scalars(&mut executor), word, "the deposit wrote the block's scalars"); diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index 965713683..502acb55f 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -241,14 +241,14 @@ fn registry_call_from(sender: Address, input: Vec) -> Recovered, sender: Address) -> Outcome { let outcome = executor .run_transaction(&oracle_call_from(sender, 0)) .expect("a system-address transaction is accepted without a balance"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.history, 0, "the protocol's own transaction pays no history"); + assert_eq!(outcome.gas.history, common::body_history(36), "the Oracle read pays body history"); assert!(executor.evm().ctx().is_system_originated(), "it is the protocol's own transaction"); outcome } diff --git a/crates/mega-evm/tests/block/witness/basics.rs b/crates/mega-evm/tests/block/witness/basics.rs index f31d7a4c3..5f7b1029c 100644 --- a/crates/mega-evm/tests/block/witness/basics.rs +++ b/crates/mega-evm/tests/block/witness/basics.rs @@ -269,8 +269,9 @@ fn test_the_reads_of_a_deposit_that_failed_are_in_the_witness() { assert_eq!(tx.gas.gas_used, gas_limit, "a failed deposit uses its whole gas limit"); assert_eq!( (tx.gas.regular, tx.gas.state, tx.gas.history, tx.gas.history_bytes), - (gas_limit, 0, 0, 0), + (gas_limit, 0, 0, mega_evm::TX_BODY_SIZE), "all of it regular gas: the account it created carries no state gas" ); assert_eq!((run.gas.state, run.gas.history), (0, 0), "nor does the block count any"); + assert_eq!(run.gas.history_bytes, mega_evm::TX_BODY_SIZE, "the block keeps the body's bytes"); } diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs index e7bf169bf..9fa98bb83 100644 --- a/crates/mega-evm/tests/block/witness/state.rs +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -565,7 +565,7 @@ fn test_a_mega_system_transaction_reports_the_footprint_scalar_it_reads() { let replay = Case::new("system transaction alone", db).tx(common::system_tx()).run(); let run = &replay.recorded; assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); - assert_eq!(run.tx(0).gas.history, 0, "the protocol's own transaction"); + assert_eq!(run.tx(0).gas.history, common::body_history(36), "the protocol's own transaction"); assert_read_only("the system transaction", l1_account(&run.tx(0).state), &footprint); assert_eq!(run.tx(0).da_footprint, run.tx(0).da_size * u64::from(PARENT_FOOTPRINT_SCALAR)); @@ -601,7 +601,10 @@ fn test_the_l1_attributes_deposit_first_prices_the_transactions_after_it() { 0, U256::ZERO, Bytes::from(word.to_be_bytes::<32>()), - 200_000 + common::new_account_state_gas(), + 200_000 + + common::new_account_state_gas() + + common::body_history(32) + + mega_evm::write_record_history_gas(1).unwrap(), )) .tx(call(0, CONTRACT, slot(1), write_gas())) .run(); @@ -647,7 +650,10 @@ fn scalars_emptied_in_the_block(overhead: U256) -> Case { 0, U256::ZERO, Bytes::new(), - 200_000 + common::new_account_state_gas(), + 200_000 + + common::new_account_state_gas() + + common::body_history(0) + + mega_evm::write_record_history_gas(1).unwrap(), )) .tx(call(0, CONTRACT, slot(1), write_gas())) } @@ -848,7 +854,10 @@ fn test_a_deposit_creating_the_l1_block_contract_adds_no_slot_read() { 1_000, U256::from(1_000), Bytes::new(), - 200_000 + 2 * common::new_account_state_gas(), + 200_000 + + 2 * common::new_account_state_gas() + + common::body_history(0) + + mega_evm::write_record_history_gas(1).unwrap(), )) .tx(call(0, CONTRACT, slot(1), write_gas())); let recorded = case.record(); diff --git a/crates/mega-evm/tests/block/witness/system.rs b/crates/mega-evm/tests/block/witness/system.rs index 4bffa79be..d7fc91c37 100644 --- a/crates/mega-evm/tests/block/witness/system.rs +++ b/crates/mega-evm/tests/block/witness/system.rs @@ -67,7 +67,11 @@ fn test_a_rotation_and_a_system_transaction_replay() { let run = &replay.recorded; assert!(applies_pending_changes(&run.pre_block), "the change was applied"); assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); - assert_eq!(run.tx(0).gas.history, 0, "the protocol's own transaction pays no history"); + assert_eq!( + run.tx(0).gas.history, + common::body_history(36), + "the Oracle read pays body history" + ); assert!(run.refusal(1).contains("lack of funds"), "{}", run.refusal(1)); assert_eq!(run.receipts.len(), 1); assert!(run.bucket_ids.is_empty(), "a system transaction prices at the minimum bucket"); diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index b80765b73..666b715e1 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -121,9 +121,9 @@ fn test_property_inspector_transparency() { ); } -/// Whether the transaction is exempt from history gas and the per-transaction limits: a deposit, -/// a transaction the protocol sent, or one the engine promotes to a deposit. -fn is_exempt(tx: &MegaTransaction) -> bool { +/// Whether the transaction is fee-free: a deposit or the protocol's own transaction. +/// Failed deposits can also keep a body larger than the transaction's resource limit. +fn is_fee_exempt(tx: &MegaTransaction) -> bool { tx.0.deposit.source_hash != alloy_primitives::B256::ZERO || is_system_originated(tx, SYSTEM_ADDRESS) } @@ -190,8 +190,8 @@ fn destroyed_in_the_transaction(account: &revm::state::Account) -> bool { /// history ledgers, or all of it when they exceed it. Two rules bill it otherwise and are left /// out: the EIP-7623 floor, when it is the receipt's figure, and op-revm's failed deposit, which /// bills the whole gas limit; -/// - an exempt transaction pays no history and reports no history bytes; any other reports at least -/// its body and pays at most what its bytes cost, the allowances paying the rest; +/// - every transaction reports at least its body as history bytes and pays at most their price, the +/// allowances paying some logs and a failed deposit reporting no history gas; /// - value is conserved: the balances change by what a deposit minted, less what a self-destruction /// burned; /// - the sender's nonce moves by one, or by more when its own code creates. @@ -251,20 +251,18 @@ fn test_property_gas_ledgers() { ); } - if is_exempt(&tx) { + prop_check!( + gas.history_bytes >= transaction_body_bytes(&tx), + "the body is in the history bytes" + ); + let worth = mega_evm::history_gas(gas.history_bytes).expect("the bytes have a price"); + prop_check!(gas.history <= worth, "the history gas is at most what the bytes cost"); + if failed_deposit { prop_eq!( - (gas.history, gas.history_bytes), - (0, 0), - "an exempt transaction pays no history" - ); - } else { - prop_check!( - gas.history_bytes >= transaction_body_bytes(&tx), - "the body is in the history bytes" + gas.history_bytes, + transaction_body_bytes(&tx), + "a failed deposit retains only its body as history" ); - let worth = - mega_evm::history_gas(gas.history_bytes).expect("the bytes have a price"); - prop_check!(gas.history <= worth, "the history gas is at most what the bytes cost"); } let mut pre = case.database(); @@ -364,7 +362,7 @@ fn test_property_kv_weighs_no_more_than_data_size() { usage.data_size >= transaction_body_bytes(&tx) + hints, "the body and the {hints} bytes of hints forwarded are counted: {usage:?}" ); - if !is_exempt(&tx) { + if !is_fee_exempt(&tx) { let limits = case.world.limits.runtime(); let limit = limits.tx_data_size_limit; prop_check!( @@ -477,7 +475,7 @@ fn fee_credits( 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); + let pays_fees = !is_fee_exempt(tx); move |address: Address| { let mut credit = 0; if pays_fees && address == block.beneficiary { @@ -856,7 +854,7 @@ pub(crate) fn check_survivors( "the data size kept is the body, the records and the hints forwarded\n{rendered}" ); } - if !is_exempt(tx) { + if !is_fee_exempt(tx) { prop_eq!( outcome.gas.history_bytes, priced, diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 9ba20e682..e043d979d 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -136,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: &Settled) { +pub(super) 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()); @@ -592,7 +592,7 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { let (mut mega, mut op, cfg) = both_evms(MemoryDatabase::default(), block()); assert_satin_cfg(&cfg); - let mega_outcome = mega.transact(OpTx(deposit(tx.clone()))).unwrap(); + let mega_outcome = mega.execute_transaction(OpTx(deposit(tx.clone()))).unwrap(); let op_outcome = op.transact(deposit(tx)).unwrap(); assert!(mega_outcome.result.is_success() && op_outcome.result.is_success()); @@ -606,6 +606,12 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { 0, "op-revm charges nothing for it", ); + assert_eq!(mega_outcome.gas.history, body_history(0)); + assert_eq!(mega_outcome.gas.history_bytes, TX_BODY_SIZE); + assert_eq!( + mega_outcome.result.gas().total_gas_spent(), + op_outcome.result.gas().total_gas_spent() + account_state_gas() + body_history(0) + ); } /// A `keylessDeploy` transaction is a deployment in Satin and a call to the contract's bytecode in diff --git a/crates/mega-evm/tests/satin/failed_deposit.rs b/crates/mega-evm/tests/satin/failed_deposit.rs index c5771e264..fc0035912 100644 --- a/crates/mega-evm/tests/satin/failed_deposit.rs +++ b/crates/mega-evm/tests/satin/failed_deposit.rs @@ -13,7 +13,10 @@ use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{ + op_transaction, zero_fee_l1_block_info, BytecodeBuilder, GasInspector, MemoryDatabase, + MsgCallMeta, + }, EvmTxRuntimeLimits, ExternalEnvs, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, TestExternalEnvs, TX_BODY_SIZE, }; @@ -42,6 +45,127 @@ fn deposit(data: Bytes, system: bool) -> MegaTransaction { OpTx(tx) } +/// Runs a funded sender's deposit with a mint, no value and no calldata. +fn body_deposit(gas_limit: u64, opcode: u8) -> MegaTransactionOutcome { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10)) + .account_code(CALLEE, Bytes::from(vec![opcode])); + let mut tx = deposit(Bytes::new(), false); + tx.0.base.gas_limit = gas_limit; + tx.0.deposit.mint = Some(7); + MegaEvm::new(context(db)).execute_transaction(tx).expect("the deposit is included") +} + +/// The body, mint and nonce are kept on success and on either failure path. +#[track_caller] +fn assert_body_deposit(outcome: &MegaTransactionOutcome, regular: u64, history: u64) { + assert_eq!( + (outcome.gas.regular, outcome.gas.state, outcome.gas.history), + (regular, 0, history) + ); + assert_eq!(outcome.gas.gas_used, regular + history); + assert_eq!(outcome.gas.history_bytes, 310); + assert_eq!(outcome.usage.data_size, 310); + assert_eq!(outcome.state[&CALLER].info.nonce, 1); + assert_eq!(outcome.state[&CALLER].info.balance, U256::from(17)); +} + +/// Intrinsic regular gas is 15,000 and body history is 27,280: 30,000 cannot cover both. +#[test] +fn test_a_deposit_short_of_body_history_is_a_failed_deposit() { + if crate::common::runs_at_measurement_prices() { + return; + } + let outcome = body_deposit(30_000, revm::bytecode::opcode::STOP); + + assert!(matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + )); + assert_body_deposit(&outcome, 30_000, 0); +} + +/// An exceptional halt consumes the whole gas limit as regular gas but keeps the body's bytes. +#[test] +fn test_a_halted_deposit_reports_body_bytes_but_no_history_gas() { + if crate::common::runs_at_measurement_prices() { + return; + } + let outcome = body_deposit(100_000, INVALID); + + assert!(matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + )); + assert_body_deposit(&outcome, 100_000, 0); +} + +/// A successful deposit pays 27,280 of history for its 310-byte body, besides intrinsic gas. +#[test] +fn test_a_successful_deposit_pays_body_history() { + if crate::common::runs_at_measurement_prices() { + return; + } + let outcome = body_deposit(100_000, revm::bytecode::opcode::STOP); + + assert!(outcome.result.is_success()); + assert_body_deposit(&outcome, 15_000, 27_280); +} + +/// A mint too small for the creation's value makes no start record. The inspector must see the +/// whole forward left after the intrinsic and account charges, before revm refuses the value. +#[test] +fn test_a_deposit_creation_with_insufficient_mint_pays_no_start_record() { + let db = MemoryDatabase::default().account_nonce(CALLER, 1); + let mut tx = deposit(Bytes::new(), false); + tx.0.base.kind = TxKind::Create; + tx.0.base.value = U256::from(8); + tx.0.deposit.mint = Some(7); + let gas_limit = 24_000 + crate::common::body_history(0) + account_state_gas() + 1_000_000; + tx.0.base.gas_limit = gas_limit; + let mut evm = MegaEvm::new(context(db)).with_inspector(GasInspector::default()); + + let outcome = evm.execute_transaction(tx).expect("the deposit is included"); + + let trace = evm.inspector().trace.as_ref().expect("the creation reaches its funds check"); + let MsgCallMeta::Create(input) = &trace.borrow().meta else { panic!("a creation") }; + assert_eq!(input.gas_limit(), 1_000_000, "an unfunded creation has no record to charge"); + assert!(matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + )); + assert_eq!((outcome.gas.regular, outcome.gas.state, outcome.gas.history), (gas_limit, 0, 0)); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE); + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.state[&CALLER].info.nonce, 2); + assert_eq!(outcome.state[&CALLER].info.balance, U256::from(7)); +} + +/// History leaves only one regular gas after the read. The next two-gas charge cannot be paid +/// even without detention, so the deposit fails rather than returning a compute-limit stop. +#[test] +fn test_a_deposit_short_of_regular_gas_at_the_detention_edge_fails() { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10)) + .account_code(CALLEE, Bytes::from_static(&[revm::bytecode::opcode::TIMESTAMP, POP])); + let mut tx = deposit(Bytes::new(), false); + let gas_limit = 15_000 + crate::common::body_history(0) + 3; + tx.0.base.gas_limit = gas_limit; + let limits = EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(1); + + let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the deposit is included"); + + assert!(matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + )); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!((outcome.gas.regular, outcome.gas.history), (gas_limit, 0)); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE); +} + /// A system deposit whose body crosses the data-size limit is refused by the inherited rules, /// which refuse every system deposit under Regolith, and op-revm includes it as a failed deposit: /// the outcome reports the failure, no stop, and the body as what was kept. @@ -64,6 +188,7 @@ fn test_a_system_deposit_over_the_limit_reports_the_failed_deposit() { outcome.result ); assert_eq!(outcome.gas.gas_used, 100_000, "a failed deposit bills its gas limit"); + assert_eq!(outcome.gas.history_bytes, body, "the body survives an early validation failure"); assert_eq!(outcome.limit_exceeded, None, "the halt is what the deposit reports"); 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"); @@ -107,6 +232,7 @@ fn test_a_deposit_whose_body_is_over_the_limit_is_a_failed_deposit() { outcome.result ); assert_eq!(outcome.gas.gas_used, 100_000, "{case}: a failed deposit bills its gas limit"); + assert_eq!(outcome.gas.history_bytes, body, "{case}: the body and calldata survive"); assert_eq!(outcome.limit_exceeded, None, "{case}: the failure is what it reports"); assert_eq!( outcome.usage, @@ -192,6 +318,7 @@ fn test_a_deposit_over_the_limit_fails_at_every_gas_limit() { ); assert_eq!(outcome.limit_exceeded, None, "{row}: no stop is reported"); assert_eq!(outcome.gas.gas_used, gas_limit, "{row}: the whole gas limit"); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "{row}: the body survives"); assert_eq!( (outcome.gas.regular, outcome.gas.state, outcome.gas.history), (gas_limit, 0, 0), @@ -320,6 +447,8 @@ fn test_a_failed_deposit_keeps_the_hints_it_forwarded() { assert_eq!(hints, 1, "the hint reached the oracle service before the halt"); assert_eq!(outcome.limit_exceeded, None); assert_eq!(outcome.usage, kept, "the body and the forwarded hint stay counted"); + assert_eq!(outcome.gas.history, 0); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "the hint is not history"); let ordinary = call(CALLER, CALLEE, U256::ZERO, 1_000_000); assert_eq!( diff --git a/crates/mega-evm/tests/satin/floor_exempt.rs b/crates/mega-evm/tests/satin/floor_exempt.rs index 863a6691d..60f304ee0 100644 --- a/crates/mega-evm/tests/satin/floor_exempt.rs +++ b/crates/mega-evm/tests/satin/floor_exempt.rs @@ -1,10 +1,7 @@ -//! The EIP-7623 calldata floor of a transaction exempt from history gas. +//! The calldata floor still applies to deposits and system-originated transactions. //! -//! At the spec's prices a transaction that pays history gas pays every byte it carries at 88 gas, -//! above the floor's 64, so the floor never decides what it uses. A transaction exempt from history -//! gas — a deposit, and the protocol's own — pays its calldata only at the intrinsic token rate, -//! four gas a zero byte and sixteen a non-zero one, so once its calldata outweighs what it runs and -//! the state it adds, its gas used is the floor. +//! At the spec's prices their history costs more than the floor's per-byte rate. At lower +//! measurement prices the floor can bind, and is drawn from the whole gas limit. //! //! The floor's base is the transaction's own EIP-2780 base without its calldata, access-list, //! authorization and initcode costs: 12,000 for a transfer to the sender itself, 15,000 for a call @@ -21,7 +18,7 @@ use mega_evm::{ }; use revm::context::TxEnv; -use crate::common::{account_state_gas, context}; +use crate::common::{account_state_gas, body_history, context, history}; /// A depositor whose own code is [`SINK`], so that a transfer to itself runs it. const DEPOSITOR: Address = address!("0000000000000000000000000000000000f10000"); @@ -53,7 +50,7 @@ const fn calldata_gas(len: u64) -> u64 { /// What a transaction is, as far as the floor and the exemption are concerned. #[derive(Clone, Copy, Debug)] enum Class { - /// A deposit a user's L1 transaction made: history-exempt, priced by bucket. + /// A deposit a user's L1 transaction made, priced by bucket. UserDeposit, /// A Mega System Transaction: a legacy call from the live system address to the Oracle, which /// the engine promotes to a deposit. @@ -91,8 +88,8 @@ impl Shape { /// What a transaction of this shape carrying `len` bytes spends, by hand: its EIP-2780 /// intrinsic regular gas — the base, plus EIP-3860's two gas per initcode word for a creation, - /// plus the calldata — then [`SINK`], and for a creation the created account's state gas. An - /// exempt transaction pays no history gas, so that is all of it. + /// plus the calldata — then [`SINK`], and for a creation the created account's state gas. + /// History is added separately. fn spend(self, len: u64) -> u64 { let initcode_words = if self == Self::Creation { len.div_ceil(32) } else { 0 }; let created_account = if self == Self::Creation { account_state_gas() } else { 0 }; @@ -145,29 +142,13 @@ fn transaction(class: Class, shape: Shape, len: u64, gas_limit: u64) -> MegaTran /// 4 × 27) = 1,860 gas more in the floor than in the intrinsic charge, under what [`SINK`] costs. const SHORT: u64 = 32; -/// Calldata long enough that the floor binds: 40,000 bytes put 2,560,000 gas in the floor, more -/// than the intrinsic charge, [`SINK`] and a created account at any byte price the grid reaches -/// together. +/// Enough calldata for the floor to bind at low history prices. const LONG: u64 = 40_000; -/// An exempt transaction's gas used is the larger of what it spent and its floor, and both are -/// the spec's figures: the floor is the shape's base — 12,000 for a transfer to the sender itself, -/// 15,000 for a call without value, 21,000 with value, 24,000 for a creation — plus 64 gas a byte -/// of calldata, zero or not, a creation's initcode included; the spend is the intrinsic regular -/// gas, what the transaction ran and the state it added, and no history. -/// -/// Each case runs with [`SHORT`] calldata, where the spend is above the floor and is the gas used, -/// and with [`LONG`] calldata, where the floor binds and is the gas used. Each runs below the -/// execution cap and above it: where the floor binds it is drawn from the whole gas limit, the -/// reservoir included, so the gas used is the floor at either gas limit. The figure the block -/// counts on its execution ledger is the regular ledger at least the floor. -/// -/// Rules: [S4.19], [S4.22], [S4.23], [S5.5], [S7.34], [S7.36], [S7.37], [S5], [S7]. Independence: -/// independent — the floor's base and rate, the intrinsic costs and the memory the code expands -/// are written out; the created account's state gas is the schedule's entry at the price in -/// effect. +/// Deposits and system-originated transactions report the larger of their total spend and +/// the calldata floor. Both ledgers include their history at the active byte price. #[test] -fn test_the_floor_of_an_exempt_transaction() { +fn test_the_floor_of_deposits_and_system_transactions() { use Class::{MegaSystemTransaction, SystemDeposit, UserDeposit}; use Shape::{Call, Creation, SelfTransfer, ValueCall}; @@ -185,7 +166,11 @@ fn test_the_floor_of_an_exempt_transaction() { ]; for gas_limit in [10_000_000, TX_GAS_LIMIT_CAP + 100_000_000] { for (class, shape) in cases { - for (len, binds) in [(SHORT, false), (LONG, true)] { + for len in [SHORT, LONG] { + let records = u64::from(matches!(shape, Shape::ValueCall | Shape::Creation)); + let history_gas = + body_history(len) + history(records * mega_evm::WRITE_RECORD_SIZE); + let gas_limit = gas_limit + history_gas; let case = format!("{class:?}, {shape:?}, {len} bytes, gas limit {gas_limit}"); let tx = transaction(class, shape, len, gas_limit); let outcome = MegaEvm::new(context(db())) @@ -195,12 +180,16 @@ fn test_the_floor_of_an_exempt_transaction() { let gas = outcome.gas; let floor = shape.floor_base() + 64 * len; - let spend = shape.spend(len); + let spend = shape.spend(len) + history_gas; assert_eq!(gas.floor, floor, "{case}: the floor"); - assert_eq!(binds, floor > spend, "{case}: whether the floor binds"); - assert_eq!(gas.history, 0, "{case}: an exempt transaction pays no history"); + assert_eq!(gas.history, history_gas, "{case}: body and start record"); assert_eq!( - gas.regular + gas.state, + gas.history_bytes, + mega_evm::TX_BODY_SIZE + len + records * mega_evm::WRITE_RECORD_SIZE, + "{case}" + ); + assert_eq!( + gas.regular + gas.state + gas.history, spend, "{case}: what it spent, the intrinsic charge, the code and the state" ); diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index e1a94976d..f46ac66a4 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -1,14 +1,5 @@ -//! Who pays no history gas at all: a deposit, a transaction the protocol itself sent, and a -//! system call. -//! -//! What those three append to the chain is the chain carrying its own weight — a deposit the -//! sequencer relays and that was paid for on L1, the maintenance a system transaction performs, -//! the calls the protocol makes before a block's transactions — and there is no sender to charge -//! for it. Every one of them runs the same program as the control transaction below, which pays -//! for every byte of it. -//! -//! The exemption is history's alone. State gas is charged as usual, which each test asserts, so an -//! exempt transaction cannot grow the state for free. +//! History gas is charged to every transaction, including deposits and the protocol's own. +//! Only system calls are exempt; their state gas and resource usage are still counted. use alloy_evm::Evm; use alloy_op_evm::OpTx; @@ -166,9 +157,8 @@ fn test_a_user_transaction_pays_history_for_the_program() { /// exemption reaches it too, by handing an exempt transaction a schedule that prices a deposited /// byte at zero. /// -/// The program above deploys thirty-two bytes. A user transaction pays for them and a deposit -/// running the same program pays for nothing at all, so the difference the schedule makes is -/// visible where a ledger comparison alone would only show two zeroes. +/// The program deploys thirty-two bytes. Transactions pay for them, and a system call running +/// the same program pays no history. #[test] fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { if runs_at_measurement_prices() { @@ -190,26 +180,60 @@ fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { DEPLOYED_BYTES * mega_evm::constants::COST_PER_HISTORY_BYTE, "a user transaction pays a history byte per deployed byte", ); - assert_eq!(ledgers(deposit(call_from(CALLER, CONTRACT))).0, 0, "a deposit pays none of it"); + let mut evm = MegaEvm::new(context(db())); + Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()).unwrap(); + assert_eq!(evm.ctx().additional_limit().history_gas_spent(), 0); } -/// A deposit pays no history gas: the bytes it carries were paid for on L1. +/// A deposit pays for its body, calldata, records, logs and deployed code even without a fee. #[test] -fn test_a_deposit_pays_no_history_gas() { +fn test_a_deposit_pays_history_gas() { if runs_at_measurement_prices() { return; } - let (history, state, outcome) = ledgers(deposit(call_from(CALLER, CONTRACT))); - assert_eq!(history, 0, "a deposit pays no history gas"); - assert!(state > 0, "the exemption is history's alone"); + let mut tx = deposit(call_from(CALLER, CONTRACT)); + tx.0.base.data = Bytes::from_static(b"history"); + let (history, state, outcome) = ledgers(tx); + assert_eq!(history, (PROGRAM_HISTORY_BYTES + 7) * COST_PER_HISTORY_BYTE); assert_eq!(state, PROGRAM_STATE_GAS, "the state a user transaction pays"); - assert_eq!(outcome.gas.history_bytes, 0); + assert_eq!(outcome.gas.history_bytes, PROGRAM_HISTORY_BYTES + 7); } -/// A transaction from the system address pays no history gas: the protocol is maintaining its own -/// state, and a resource charge it cannot pay would stop it. +/// Both field-based forms of system origin pay every history site, including deposited code. #[test] -fn test_a_system_transaction_pays_no_history_gas() { +fn test_system_originated_transactions_pay_history_for_the_program() { + if runs_at_measurement_prices() { + return; + } + let mut stamped = deposit(call_from(CALLER, CONTRACT)); + stamped.0.deposit.source_hash = mega_evm::system::MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + let from_system_caller = call_from(mega_evm::SYSTEM_ADDRESS, CONTRACT); + for (name, mut tx) in [("source hash", stamped), ("system caller", from_system_caller)] { + tx.0.base.data = Bytes::from_static(b"history"); + let db = db().account_balance(mega_evm::SYSTEM_ADDRESS, U256::from(10u64.pow(18))); + let mut evm = MegaEvm::new(context(db)); + + let outcome = evm.execute_transaction(tx).expect("the transaction is included"); + + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert!(evm.ctx().is_system_originated(), "{name}"); + assert_eq!( + outcome.gas.history, + (PROGRAM_HISTORY_BYTES + 7) * COST_PER_HISTORY_BYTE, + "{name}" + ); + assert_eq!(outcome.gas.history_bytes, PROGRAM_HISTORY_BYTES + 7, "{name}"); + assert_eq!(outcome.gas.state, PROGRAM_STATE_GAS, "{name}"); + assert!( + evm.ctx().bucket_multipliers().cached_buckets().len() == 0, + "{name}: minimum bucket without a lookup" + ); + } +} + +/// A promoted Mega System Transaction pays for its body, calldata and the Oracle slot it writes. +#[test] +fn test_a_system_transaction_pays_history_gas() { if runs_at_measurement_prices() { return; } @@ -219,8 +243,9 @@ fn test_a_system_transaction_pays_no_history_gas() { let tx = system_tx(); let outcome = MegaEvm::new(context(db())).execute_transaction(tx).expect("the transaction is valid"); - assert_eq!(outcome.gas.history, 0, "the protocol's own transaction pays no history gas"); - assert_eq!(outcome.gas.history_bytes, 0, "and appends no history byte, its body included"); + let bytes = transaction_body_bytes(&system_tx()) + WRITE_RECORD_SIZE; + assert_eq!(outcome.gas.history, bytes * COST_PER_HISTORY_BYTE); + assert_eq!(outcome.gas.history_bytes, bytes); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(written_oracle_slot(&outcome), Some(ORACLE_VALUE), "it wrote the Oracle's slot"); assert_eq!( @@ -230,7 +255,7 @@ fn test_a_system_transaction_pays_no_history_gas() { write_records: 1, state_growth: 2, }, - "the body and the slot's record are counted, though neither pays history, and the new slot \ + "the body and the slot's record pay 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 @@ -259,16 +284,10 @@ fn test_a_system_call_pays_no_history_gas() { assert_eq!(evm.ctx().additional_limit().history_bytes(), 0); } -/// The bytes a transaction appended are reported beside its history gas, and they are the bytes -/// that gas priced: the control reports every byte of the program, each at the price, and an -/// exempt transaction, which prices none of them, reports none. -/// -/// Each transaction runs below the execution cap and above it. Above it the reservoir pays the -/// state gas, which the exemption leaves in place, and no history. -/// -/// A system call runs at the gas limit its entry point fixes, below the cap. +/// Every transaction reports its retained history bytes, both below and above the execution +/// cap. Above the cap its reservoir pays history and state. System calls report no history. #[test] -fn test_an_exempt_transaction_reports_no_history_bytes() { +fn test_only_a_system_call_reports_no_history_bytes() { if runs_at_measurement_prices() { return; } @@ -299,15 +318,22 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { ); let deposit = run(deposit(call_from(CALLER, CONTRACT))).gas; - assert_eq!((deposit.history, deposit.history_bytes), (0, 0), "at {gas_limit}: a deposit"); - assert!(deposit.state > 0, "at {gas_limit}: the exemption is history's alone"); + assert_eq!( + (deposit.history, deposit.history_bytes), + (PROGRAM_HISTORY_BYTES * COST_PER_HISTORY_BYTE, PROGRAM_HISTORY_BYTES), + "at {gas_limit}: a deposit" + ); + assert!(deposit.state > 0, "at {gas_limit}: state is charged too"); let system = run(system_tx()); assert!(system.result.is_success(), "at {gas_limit}: {:?}", system.result); assert_eq!(written_oracle_slot(&system), Some(ORACLE_VALUE), "at {gas_limit}"); let system = system.gas; assert_eq!( (system.history, system.history_bytes), - (0, 0), + ( + (transaction_body_bytes(&system_tx()) + WRITE_RECORD_SIZE) * COST_PER_HISTORY_BYTE, + transaction_body_bytes(&system_tx()) + WRITE_RECORD_SIZE + ), "at {gas_limit}: a system transaction", ); } @@ -326,10 +352,8 @@ fn test_the_exemption_does_not_outlive_its_transaction() { } let mut evm = MegaEvm::new(context(db())); - let exempt = evm - .execute_transaction(deposit(call_from(CALLER, CONTRACT))) - .expect("the deposit is valid"); - assert_eq!(exempt.gas.history, 0); + Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()).unwrap(); + assert_eq!(evm.ctx().additional_limit().history_gas_spent(), 0); // Nothing was committed, so the sender's nonce is where it was. let paying = @@ -342,17 +366,16 @@ fn test_the_exemption_does_not_outlive_its_transaction() { /// Whether a transaction pays history, and whether it is the protocol's own, are decided when the /// transaction is prepared to run, from what it is: a transaction set in the context's hands but /// not run yet changes neither. After a user's transaction, a deposit or a system transaction set -/// in its place still answers as the user's transaction did; after a deposit, a user's transaction -/// still answers that it pays none; after a system transaction, a user's transaction still answers -/// that it is the protocol's own. Each answers for itself once it runs. +/// in its place still answers as the user's transaction did; after a system transaction, a user's +/// transaction still answers that it is the protocol's own. Each answers for itself once it runs. #[test] fn test_what_a_transaction_pays_is_decided_when_it_is_prepared() { let user = call_from(CALLER, CONTRACT); // (case, transaction, pays history, the protocol's own) let cases = [ ("a user's transaction", user.clone(), true, false), - ("a user's deposit", deposit(user), false, false), - ("a system transaction", system_tx(), false, true), + ("a user's deposit", deposit(user), true, false), + ("a system transaction", system_tx(), true, true), ]; for (ran, run, pays, own) in cases.clone() { for (set, replacement, its_pays, its_own) in cases.clone() { diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 37bc7f614..eb93b5165 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -462,10 +462,10 @@ fn test_the_body_carries_the_writes_every_transaction_makes() { assert_eq!(paid.usage.write_records, 0, "and none of them is recorded again"); } -/// A deposit credits no fee recipient at all, and is exempt from history besides: it pays for -/// neither the body nor anything the body carries. +/// A deposit pays for the fixed body, including its bound on fee writes, even though it credits +/// no fee recipient. #[test] -fn test_a_deposit_pays_for_none_of_the_bodys_writes() { +fn test_a_deposit_pays_for_the_bodys_fixed_writes() { if runs_at_measurement_prices() { return; } @@ -474,7 +474,7 @@ fn test_a_deposit_pays_for_none_of_the_bodys_writes() { let outcome = execute(funded().account_code(CALLEE, Bytes::new()), tx); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.history, 0); + assert_eq!(outcome.gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE); assert_eq!(outcome.usage.write_records, 0); } diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index ed4e5fc30..a8dd8208f 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -3,8 +3,8 @@ //! //! 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. +//! makes before a block's transactions — must not fail on them. Only system calls are exempt +//! from history gas. 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. diff --git a/crates/mega-evm/tests/satin/pool_validation.rs b/crates/mega-evm/tests/satin/pool_validation.rs index 9707dca23..af91e148d 100644 --- a/crates/mega-evm/tests/satin/pool_validation.rs +++ b/crates/mega-evm/tests/satin/pool_validation.rs @@ -105,9 +105,8 @@ fn access_list(gas_limit: u64) -> MegaTransaction { wrap(call) } -/// A deposit carrying a kilobyte of calldata: it pays no history gas, so the floor, which prices -/// every byte at 64 gas where the intrinsic charge prices it at 16, is what the gas limit must -/// cover. +/// A deposit carrying a kilobyte of calldata: its gas limit must cover both the intrinsic +/// charges, including history, and the floor at 64 gas per calldata byte. fn deposit_with_calldata(gas_limit: u64) -> MegaTransaction { let mut deposit = call(gas_limit); deposit.0.base.data = Bytes::from(vec![0x5a; 1_024]); @@ -290,7 +289,7 @@ fn test_the_helper_and_the_evm_agree_on_what_they_admit() { Row::new("a creation", create, None), Row::new("EIP-7702 authorizations", authorizations, None), Row::new("an access list", access_list, None), - Row::new("a deposit whose floor binds", deposit_with_calldata, None).deposit_like(), + Row::new("a deposit with calldata", deposit_with_calldata, None).deposit_like(), Row::new("a system-address transaction", system_transaction, Some(SYSTEM)).deposit_like(), Row::new("the system shape from a user", system_shape_from_a_user, Some(SYSTEM)), Row::new("the system shape with no registry", system_transaction, None), @@ -307,16 +306,8 @@ fn test_the_helper_and_the_evm_agree_on_what_they_admit() { gas.state, 0, "{name}: EIP-2780 charges the state a transaction adds when it runs" ); - // The transactions executed as deposits are the ones exempt from history gas. - let body = if row.deposit_like { - 0 - } else { - history_gas(transaction_body_bytes(&(row.build)(ROOMY))).unwrap() - }; - assert_eq!( - gas.history, body, - "{name}: the body's history, or none for an exempt transaction" - ); + let body = history_gas(transaction_body_bytes(&(row.build)(ROOMY))).unwrap(); + assert_eq!(gas.history, body, "{name}: the body's history for every transaction"); } } @@ -333,21 +324,22 @@ fn test_what_the_intrinsic_gas_is_made_of() { assert!(helper(value_to_self, None).regular < helper(call, None).regular); assert!(helper(call, None).regular < helper(value_to_existing, None).regular); - // A deposit and a system-address transaction pay no history; the same transaction from - // anyone else, or with no registry naming its sender, does. - assert_eq!(helper(deposit_with_calldata, None).history, 0); - assert_eq!(helper(system_transaction, Some(SYSTEM)).history, 0); + assert_eq!( + helper(deposit_with_calldata, None).history, + history_gas(TX_BODY_SIZE + 1_024).unwrap() + ); + assert_eq!( + helper(system_transaction, Some(SYSTEM)).history, + helper(system_transaction, None).history + ); // A body priced at a fraction of a gas may round to nothing. if !history_is_free() && !history_rounds() { assert!(helper(system_shape_from_a_user, Some(SYSTEM)).history > 0); assert!(helper(system_transaction, None).history > 0); } - // The floor binds a transaction that pays no history, and it is what its gas limit must - // cover. let deposit = helper(deposit_with_calldata, None); - assert!(deposit.floor > deposit.total()); - assert_eq!(deposit.min_gas_limit(), deposit.floor); + assert_eq!(deposit.min_gas_limit(), deposit.total().max(deposit.floor)); } fn on_another_chain() -> MegaTransaction { diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 0ca8dc5f3..1ba78ce15 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -424,12 +424,12 @@ fn system_address_transaction(gas_limit: u64) -> (TxEnv, OpTransaction) { /// deposit op-revm runs for it — never the system call's 30M split, which the rows between 30M and /// the cap would see. /// -/// The one difference from op-revm's deposit is in the state: Satin's validation read the live -/// system address out of the `SequencerRegistry`, a read-only entry holding the one slot. +/// Satin also charges the body's history and reads the live system address from the registry. +/// History draws from the reservoir first, just as for a user's transaction. #[test] fn test_a_system_address_transaction_is_split_by_the_execution_cap() { for (gas_limit, reservoir) in [ - (1_000_000, 0), + (1_000_000, 0_u64), (100_000_000, 0), (TX_GAS_LIMIT_CAP, 0), (TX_GAS_LIMIT_CAP + 5_000_000, 5_000_000), @@ -446,16 +446,13 @@ fn test_a_system_address_transaction_is_split_by_the_execution_cap() { 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.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); + let history = crate::common::body_history(36); + assert_eq!(mega_outcome.gas.history, history); + assert_eq!( + mega_outcome.gas.reservoir_remaining, + reservoir.saturating_sub(history), + "{gas_limit}" + ); + crate::equivalence::assert_same_but_history(&mega_outcome, &op_outcome); } } diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 280f619a1..e38a4ff1f 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -1097,7 +1097,7 @@ fn test_a_creation_onto_an_occupied_address_fails_on_the_collision() { /// A deposit's value moves in its first frame and is logged there, from the depositor to the /// recipient; its mint is credited before any frame and is logged nowhere. The log is counted in -/// the data size like any other, though a deposit pays no history, and a user's deposit is held +/// the data size like any other, but is exempt from history, and a user's deposit is held /// to the data-size limit at it. #[test] fn test_a_deposits_value_is_logged_and_its_mint_is_not() { @@ -1122,7 +1122,14 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { }, "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"); + assert_eq!( + (outcome.gas.history, outcome.gas.history_bytes), + ( + crate::common::history(body) + crate::common::history(WRITE_RECORD_SIZE), + body + WRITE_RECORD_SIZE + ), + "the body and recipient record pay history; the transfer log does not" + ); let minted = execute_under( db(), diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 3f462e1bd..17c27fdb9 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -325,7 +325,7 @@ fn test_the_system_address_is_not_detained() { /// push of the counter, one round that expands memory to 1,024 words, then rounds of 3,108 until /// the next round's 3,072-gas copy no longer fits. /// -/// A deposit pays no history gas, and a user's deposit is not system-originated. +/// A deposit pays its body's history gas, and a user's deposit is not system-originated. /// The same body, run as a Mega System Transaction, reads the same thing and is not stopped. #[test] fn test_a_users_deposit_is_detained() { @@ -484,10 +484,18 @@ fn assert_deposit_stopped( "{name}" ); assert_eq!(run.outcome.gas.regular, intrinsic + used, "{name}: billed what ran"); - assert_eq!(run.outcome.gas.gas_used, intrinsic + used, "{name}: the receipt bills the same"); + assert_eq!( + run.outcome.gas.gas_used, + intrinsic + used + crate::common::body_history(0), + "{name}: the receipt includes history" + ); assert_eq!(run.outcome.gas.state, 0, "{name}"); - assert_eq!(run.outcome.gas.history, 0, "{name}: a deposit pays no history"); - assert_eq!(run.outcome.gas.history_bytes, 0, "{name}"); + assert_eq!( + run.outcome.gas.history, + crate::common::body_history(0), + "{name}: the body pays history" + ); + assert_eq!(run.outcome.gas.history_bytes, mega_evm::TX_BODY_SIZE, "{name}"); assert!(run.outcome.result.logs().is_empty(), "{name}"); } @@ -508,7 +516,7 @@ fn assert_system_transaction_is_not_stopped(name: &str, code: Bytes, cap: u64) { assert_eq!(run.accessed, VolatileDataAccess::empty(), "{name} system"); assert_eq!(run.limit, None, "{name} system"); assert!(run.outcome.gas.regular > cap, "{name} system: it ran past the cap"); - assert_eq!(run.outcome.gas.history, 0, "{name} system"); + assert_eq!(run.outcome.gas.history, crate::common::body_history(0), "{name} system"); } /* ---------- the beneficiary's own frame ---------- */ diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index d4559c160..a7e6651d0 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -596,13 +596,16 @@ fn test_validating_a_system_transaction_charges_its_caller_as_any_senders() { ); } -/// A system transaction spends nothing on the history ledger: the protocol's own maintenance is -/// exempt from history gas. +/// A system transaction pays for its body, calldata and the Oracle slot it writes. #[test] -fn test_a_system_transaction_spends_no_history_gas() { +fn test_a_system_transaction_pays_history_gas() { let outcome = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x66))); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.history, 0, "the protocol's own transaction pays no history gas"); + assert_eq!( + outcome.gas.history, + mega_evm::history_gas(mega_evm::TX_BODY_SIZE + 196).unwrap() + + mega_evm::write_record_history_gas(1).unwrap() + ); } /// A deposit-like transaction whose caller does not exist yet creates that account, and pays diff --git a/crates/mega-evm/tests/tracers/scenarios.rs b/crates/mega-evm/tests/tracers/scenarios.rs index d15cbe83c..0720d2e77 100644 --- a/crates/mega-evm/tests/tracers/scenarios.rs +++ b/crates/mega-evm/tests/tracers/scenarios.rs @@ -910,16 +910,16 @@ fn test_precompile_child_frame() { } /// A deposit that mints and carries value to a contract which stops. The value is logged; the -/// mint is not. A deposit pays no history gas. +/// mint is not. Its body and recipient record pay history. #[test] fn test_deposit_transaction() { let mint = 1_000_u128; let value = U256::from(7); - // A deposit pays its intrinsic gas and what it ran, here nothing, and no history. + // A deposit pays its intrinsic gas, its body and the recipient record. let expected = Ledgers { regular: gas::call_intrinsic(&[], true), state: 0, - history: 0, + history: gas::history(TX_BODY_SIZE) + gas::history(WRITE_RECORD_SIZE), floor: gas::call_floor(&[], true), }; let mut tx = op_transaction(TxEnv { @@ -938,7 +938,7 @@ fn test_deposit_transaction() { ); assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); let history = (traced.outcome.gas.history, traced.outcome.gas.history_bytes); - assert_eq!(history, (0, 0), "a deposit pays no history"); + assert_eq!(history, (expected.history, TX_BODY_SIZE + WRITE_RECORD_SIZE)); let root = traced.call_frame(true); assert_logs(&root.logs, &[transfer_log(CALLER, CONTRACT, value)]); assert_log_index_counts_discarded(&traced, &[0]); diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 1f98384e0..d70bfcd56 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -370,7 +370,7 @@ Every EIP-8037 state charge MUST be `entry × m`: - 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)). + A deposit that is not system-originated is not one of them and MUST be priced by bucket, and MUST pay history gas (see [History Gas](#7-history-gas)). At `m = 1` every state charge is the schedule's own number, so, unlike Rex6, a fresh slot or account in a minimum-size bucket is not free: it pays its state gas. @@ -405,7 +405,7 @@ The bytes MUST be those of the byte table below, which is also the table the dat When each charge is made: - The body — `TX_BODY_SIZE`, the calldata, the access list and the authorizations — MUST be charged before execution, as intrinsic state gas: the reservoir pays it first and its excess the regular budget, and it is not part of the intrinsic regular gas the execution cap is validated against. - 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)). + A gas limit that cannot cover it MUST make an ordinary transaction invalid and a deposit a failed deposit (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. A list the KV or state-growth limit skips has no authority records, and that history is not charged. @@ -444,12 +444,16 @@ These MUST NOT pay history gas: - an [EIP-7708 transfer log](#14-eip-7708-transfer-logs), which is data size only; - an Oracle hint's payload, which goes to the oracle service rather than into a block; -- any byte of a deposit transaction, of a system-originated transaction, or of a system call (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). - For these the deposited-code history gas MUST be zero too. - The exemption is from history gas alone: a deposit that is not system-originated MUST still be priced by bucket (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), held to every per-transaction limit and detained (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). +- any byte of a system call (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). + Its deposited-code history gas MUST be zero too. + +A deposit and a system-originated transaction MUST pay history gas as any transaction does: for their body, calldata, logs, write records and deposited code. +They MUST report their retained history bytes; a system call MUST report zero history bytes. +A failed deposit MUST report its body and calldata as history bytes even when validation fails before those bytes are admitted, while reporting zero history gas. +A deposit that is not system-originated MUST still be priced by bucket (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), held to every per-transaction limit and detained (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). The EIP-7623 floor is still computed and validated. -At these prices it never raises the gas used of a transaction that pays history gas, because the history gas of the same bytes is higher; it can still raise that of a transaction exempt from history gas, a deposit or one of the protocol's own; and it does bind the figure a block counts on its execution ledger, `max(regular, floor)` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +At these prices it never raises the gas used of a transaction that pays history gas, because the history gas of the same bytes is higher; it does bind the figure a block counts on its execution ledger, `max(regular, floor)` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). Where it binds, the gas used is the floor, drawn from the whole gas limit, the reservoir included, and the transaction gets back its gas limit less the floor (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)); a deposit, which paid nothing, is charged nothing either way, and only its receipt's and the block's figures move. ### 8. History Allowance Replaces the Storage Gas Stipend @@ -1283,14 +1287,14 @@ Only a deposit carries a source hash: a transaction handed to a node with one is 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, data size, KV updates and state growth included; - MUST NOT be detained; - still have their usage counted. A system-originated transaction's usage is reported and counts towards the block's counters; the pre-block calls do not count towards the block's counters or limits. -A deposit pays no history gas either (see [History Gas](#7-history-gas)), but a user's deposit is not system-originated: it is held to every per-transaction limit, detained, and priced by bucket (see [State Gas](#6-state-gas-and-salt-pricing)). +A system call MUST pay no history gas; a system-originated transaction and a deposit MUST pay it as any transaction does (see [History Gas](#7-history-gas)). +A user's deposit is not system-originated: it is held to every per-transaction limit, detained, and priced by bucket (see [State Gas](#6-state-gas-and-salt-pricing)). ### 20. Block Limits @@ -1368,6 +1372,7 @@ A deposit MUST NOT be rejected for failing a validation check: a deposit that fa 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)). +Its body and calldata MUST still be reported as history bytes, including on a failure before body admission. 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: @@ -1533,7 +1538,8 @@ A node, a stateless validator and a replay tool must agree on everything below, 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 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. + Deposits and Mega System Transactions MUST cover their body's history gas in the intrinsic check; a deposit that fails it MUST be included as a failed deposit. + A pool that recognizes a Mega System Transaction, 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. An address read from another state treats the old system address's transactions as the protocol's and the new one's as a user's, or the reverse. A deposit is never refused for failing validation: one that fails validation is included as a failed deposit, which bumps its sender's nonce and uses its whole gas limit. From efb1940022c81d6690a32430eae38d1576522b22 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:36:44 +0800 Subject: [PATCH 067/190] feat(block): deploy the system contracts every block and resolve the live system address once per block --- bin/mega-evme/src/common/schedule.rs | 43 +- bin/mega-evme/src/engine.rs | 3 +- bin/mega-evme/tests/common/blocks.rs | 9 +- bin/mega-evme/tests/limits.rs | 9 +- crates/mega-evm/src/block/chain.rs | 48 +- crates/mega-evm/src/block/executor.rs | 243 ++++--- crates/mega-evm/src/block/genesis.rs | 311 +++++++-- crates/mega-evm/src/block/hardfork.rs | 32 +- crates/mega-evm/src/evm/context.rs | 72 +- crates/mega-evm/src/evm/execution.rs | 20 +- crates/mega-evm/src/lib.rs | 5 +- crates/mega-evm/src/system/predeploys.rs | 115 +++- .../mega-evm/src/system/sequencer_registry.rs | 641 +++++++++++++---- crates/mega-evm/src/test_utils/neutral.rs | 34 +- crates/mega-evm/tests/block/activation.rs | 29 +- crates/mega-evm/tests/block/common.rs | 43 +- crates/mega-evm/tests/block/predeploys.rs | 651 ++++++++++++++---- crates/mega-evm/tests/block/schedule.rs | 5 +- .../tests/block/sequencer_registry.rs | 91 ++- crates/mega-evm/tests/block/witness/basics.rs | 15 +- .../tests/block/witness/predeploys.rs | 38 +- crates/mega-evm/tests/block/witness/skips.rs | 54 +- crates/mega-evm/tests/block/witness/system.rs | 22 +- crates/mega-evm/tests/fuzz/differential.rs | 7 +- crates/mega-evm/tests/satin/equivalence.rs | 37 +- .../tests/satin/limit_matrix/block.rs | 52 +- crates/mega-evm/tests/satin/neutral.rs | 10 +- crates/mega-evm/tests/satin/system_call.rs | 11 +- crates/mega-evm/tests/system/system_tx.rs | 90 +-- crates/mega-evm/tests/tracers/harness.rs | 13 +- 30 files changed, 2001 insertions(+), 752 deletions(-) diff --git a/bin/mega-evme/src/common/schedule.rs b/bin/mega-evme/src/common/schedule.rs index ca93f4ea0..9638731de 100644 --- a/bin/mega-evme/src/common/schedule.rs +++ b/bin/mega-evme/src/common/schedule.rs @@ -96,6 +96,9 @@ pub fn chain_activation(chain_id: u64) -> Option { Some(genesis) if genesis.chain_id == chain_id => Some(ChainActivation { chain_id, satin: genesis.satin.map(|satin| satin.activation_time), + sequencer_registry_bootstrap: genesis + .satin + .map(|satin| satin.sequencer_registry_bootstrap), }), _ => mega_evm::chain_activation(chain_id), } @@ -233,7 +236,8 @@ mod tests { const ACTIVATION: u64 = 1_800_000_000; fn scheduled() -> MegaHardforkConfig { - ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(ACTIVATION) }.hardforks() + let mainnet = mega_evm::chain_activation(MAINNET_CHAIN_ID).expect("a known chain"); + ChainActivation { satin: Some(ACTIVATION), ..mainnet }.hardforks() } /// A counterfactual runs on the chain's own schedule with Satin from genesis, whatever the @@ -324,10 +328,21 @@ mod tests { ); } - /// A genesis file whose `config` carries `chainId` and the Satin key: Satin at - /// [`ACTIVATION`]. + /// The bootstrap values the tests' genesis files carry. + const BOOTSTRAP: mega_evm::system::SequencerRegistryBootstrap = + mega_evm::system::SequencerRegistryBootstrap::new( + alloy_primitives::address!("0x0000000000000000000000000000000000000033"), + alloy_primitives::address!("0x0000000000000000000000000000000000000044"), + 1, + ); + + /// A genesis file whose `config` carries `chainId` and the Satin keys: Satin at + /// [`ACTIVATION`], and [`BOOTSTRAP`]. fn genesis_file(dir: &tempfile::TempDir, chain_id: u64) -> (String, SatinChainConfig) { - let satin = SatinChainConfig { activation_time: ACTIVATION }; + let satin = SatinChainConfig { + activation_time: ACTIVATION, + sequencer_registry_bootstrap: BOOTSTRAP, + }; let mut config = serde_json::to_value(satin).unwrap(); config["chainId"] = serde_json::json!(chain_id); config["optimism"] = serde_json::json!({ "eip1559Elasticity": 6 }); @@ -412,10 +427,24 @@ mod tests { assert_eq!(parse_genesis(&bare), Ok(GenesisChain { chain_id: 7, satin: None })); let no_chain_id = write("no-id.json", serde_json::json!({ "config": {} })); assert!(parse_genesis(&no_chain_id).unwrap_err().contains("chainId")); - let satin = write("satin.json", serde_json::json!({ "chainId": 7, "satinTime": 0 })); - let expected = - GenesisChain { chain_id: 7, satin: Some(SatinChainConfig { activation_time: 0 }) }; + let satin = write( + "satin.json", + serde_json::json!({ + "chainId": 7, + "satinTime": 0, + "rex5InitialSequencer": "0x0000000000000000000000000000000000000033", + "rex5InitialAdmin": "0x0000000000000000000000000000000000000044", + "rex6MinRotationDelay": 1, + }), + ); + let config = + SatinChainConfig { activation_time: 0, sequencer_registry_bootstrap: BOOTSTRAP }; + let expected = GenesisChain { chain_id: 7, satin: Some(config) }; assert_eq!(parse_genesis(&satin), Ok(expected)); + let without_bootstrap = + write("no-bootstrap.json", serde_json::json!({ "chainId": 7, "satinTime": 0 })); + let error = parse_genesis(&without_bootstrap).unwrap_err(); + assert!(error.contains("must carry `rex5InitialSequencer`"), "{error}"); let old = write( "old.json", serde_json::json!({ "chainId": 7, "satinTime": 0, "satinInitialAdmin": "0x33" }), diff --git a/bin/mega-evme/src/engine.rs b/bin/mega-evme/src/engine.rs index 6c3e58415..88662accf 100644 --- a/bin/mega-evme/src/engine.rs +++ b/bin/mega-evme/src/engine.rs @@ -213,7 +213,8 @@ mod tests { /// block at the timestamp is the first Satin one. A chain without a table has no engine. #[test] fn test_a_scheduled_chain_switches_at_the_timestamp() { - let scheduled = ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(1_800_000_000) }; + let mainnet = mega_evm::chain_activation(MAINNET_CHAIN_ID).expect("a known chain"); + let scheduled = ChainActivation { satin: Some(1_800_000_000), ..mainnet }; assert_eq!(Engine::under(Some(scheduled), 1_799_999_999), Some(Engine::Legacy)); assert_eq!(Engine::under(Some(scheduled), 1_800_000_000), Some(Engine::Satin)); assert_eq!(Engine::under(None, 0), None); diff --git a/bin/mega-evme/tests/common/blocks.rs b/bin/mega-evme/tests/common/blocks.rs index 443bfec2e..6cd503984 100644 --- a/bin/mega-evme/tests/common/blocks.rs +++ b/bin/mega-evme/tests/common/blocks.rs @@ -184,7 +184,14 @@ pub(crate) fn is_deposit(block: &CachedBlock, index: usize) -> bool { /// A genesis file of chain `chain_id` activating Satin at `satin_time`, written in `dir`; its /// path. pub(crate) fn satin_genesis(dir: &Path, chain_id: u64, satin_time: u64) -> String { - let satin = mega_evm::SatinChainConfig { activation_time: satin_time }; + let satin = mega_evm::SatinChainConfig { + activation_time: satin_time, + sequencer_registry_bootstrap: mega_evm::system::SequencerRegistryBootstrap::new( + mega_evm::system::MEGA_SYSTEM_ADDRESS, + mega_evm::system::MEGA_SYSTEM_ADDRESS, + 1, + ), + }; let mut config = serde_json::to_value(satin).unwrap(); config["chainId"] = chain_id.into(); let path = dir.join(format!("satin-genesis-{chain_id}-{satin_time}.json")); diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs index 5bb599f8c..88d32a7b5 100644 --- a/bin/mega-evme/tests/limits.rs +++ b/bin/mega-evme/tests/limits.rs @@ -200,7 +200,14 @@ fn test_an_override_is_refused_on_a_legacy_spec() { /// A genesis file for chain `chain_id` activating Satin at `satin_time`, in `dir`. fn genesis(dir: &tempfile::TempDir, chain_id: u64, satin_time: u64) -> String { - let satin = mega_evm::SatinChainConfig { activation_time: satin_time }; + let satin = mega_evm::SatinChainConfig { + activation_time: satin_time, + sequencer_registry_bootstrap: mega_evm::system::SequencerRegistryBootstrap::new( + mega_evm::system::MEGA_SYSTEM_ADDRESS, + mega_evm::system::MEGA_SYSTEM_ADDRESS, + 1, + ), + }; let mut config = serde_json::to_value(satin).unwrap(); config["chainId"] = json!(chain_id); let path = dir.path().join(format!("genesis-{chain_id}-{satin_time}.json")); diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index 0aac49600..8a700ecf2 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -7,9 +7,9 @@ //! chain that ran the legacy forks, and whoever runs another names its schedule. use alloy_hardforks::ForkCondition; -use alloy_primitives::BlockTimestamp; +use alloy_primitives::{address, BlockTimestamp}; -use crate::{MegaHardfork, MegaHardforkConfig}; +use crate::{system::SequencerRegistryBootstrap, MegaHardfork, MegaHardforkConfig}; /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; @@ -24,6 +24,10 @@ pub struct ChainActivation { pub chain_id: u64, /// When [`MegaHardfork::Satin`] activates; `None` while it is not scheduled. pub satin: Option, + /// The `SequencerRegistry`'s bootstrap values the chain's configuration carries: on a live + /// network, the roles Rex5 seeded its registry with and the minimum rotation delay Rex6 gave + /// it; `None` for a configuration that carries none. + pub sequencer_registry_bootstrap: Option, } impl ChainActivation { @@ -38,9 +42,12 @@ impl ChainActivation { } } - /// The hardfork schedule of this chain. + /// The hardfork schedule of this chain, carrying its bootstrap values. pub fn hardforks(&self) -> MegaHardforkConfig { let mut config = MegaHardforkConfig::new(); + if let Some(bootstrap) = self.sequencer_registry_bootstrap { + config = config.with_sequencer_registry_bootstrap(bootstrap); + } for fork in MegaHardfork::VARIANTS { config.insert(*fork, self.condition(*fork)); } @@ -48,10 +55,30 @@ impl ChainActivation { } } +/// The minimum rotation delay, in blocks, both live networks' configurations carry and Rex6 seeded +/// their registries with. +const MIN_ROTATION_DELAY: u64 = 21_600; + /// Activation table of the known `MegaETH` chains. pub const CHAIN_ACTIVATIONS: [ChainActivation; 2] = [ - ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: None }, - ChainActivation { chain_id: TESTNET_CHAIN_ID, satin: None }, + ChainActivation { + chain_id: MAINNET_CHAIN_ID, + satin: None, + sequencer_registry_bootstrap: Some(SequencerRegistryBootstrap::new( + address!("0x7a49197dd1ebb8d38c67e4eb7626af6ade432445"), + address!("0x92e0e0b15e3e99b32c9ed9ad284f939553c7b7d6"), + MIN_ROTATION_DELAY, + )), + }, + ChainActivation { + chain_id: TESTNET_CHAIN_ID, + satin: None, + sequencer_registry_bootstrap: Some(SequencerRegistryBootstrap::new( + address!("0xB8DB54eBA7Ae650d14F362de461516a4FF1551FC"), + address!("0x1d9BD232C44B39341e670B735c7F423c40426b34"), + MIN_ROTATION_DELAY, + )), + }, ]; /// The activation table of a known chain, or `None` for any other chain. @@ -112,8 +139,8 @@ mod tests { /// A scheduled chain resolves the spec its table gives, at the timestamp the table gives. #[test] fn test_a_scheduled_activation_resolves_at_its_timestamp() { - let hf = - ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(1_800_000_000) }.hardforks(); + let mainnet = chain_activation(MAINNET_CHAIN_ID).expect("a known chain"); + let hf = ChainActivation { satin: Some(1_800_000_000), ..mainnet }.hardforks(); assert_eq!(hf.spec_id(1_799_999_999), None); assert_eq!(hf.spec_id(1_800_000_000), Some(MegaSpecId::SATIN)); @@ -129,6 +156,13 @@ mod tests { for fork in MegaHardfork::VARIANTS { assert_eq!(schedule.get(*fork), Some(&activation.condition(*fork))); } + let bootstrap = activation.sequencer_registry_bootstrap.expect("a live network's"); + assert_eq!( + schedule.sequencer_registry_bootstrap(), + Some(bootstrap), + "the schedule carries the chain's bootstrap values" + ); + assert!(bootstrap.is_usable()); } for chain_id in [0, 1, 6342, 999_999] { assert!(hardfork_schedule(chain_id).is_none(), "chain {chain_id} is unknown"); diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index cb18a0bde..a4f941456 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -148,9 +148,11 @@ use crate::{ }, estimated_da_size, system::{ - check_system_contract, classify_system_transaction, is_apply_pending_changes_due, - live_system_address, system_contract_specs, transact_apply_pending_changes, - write_unexpected_code, SystemContractCheckError, + check_system_contract, classify_system_transaction, create2_factory_spec, + deploy_sequencer_registry, deploy_system_contract, flat_system_contract_specs, + is_apply_pending_changes_due, resolve_system_address, transact_apply_pending_changes, + write_unexpected_code, SequencerRegistryError, SequencerRegistryRefusal, + SystemContractCheckError, }, BlockGasCounters, BlockLimiter, BlockLimits, BucketId, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, @@ -174,14 +176,16 @@ pub struct MegaBlockExecutionCtx { /// /// With the chain's schedule and the block's own timestamp it decides whether a fork /// activates in this block, which makes the block admit only deposits, and whether Satin - /// does, which makes the pre-block step check the system contracts and the EIP-7997 factory. - /// The executor works both out itself. + /// does, which makes the pre-block step check the EIP-7997 factory. The executor works both + /// out itself. /// - /// `None` is a block with no parent to compare against, such as a genesis block, and neither - /// rule applies to it. It is accepted only where no parent could change that: when every fork - /// the schedule activates is active from genesis. Where one could, executing the block fails - /// with [`MegaBlockExecutionError::MissingParentTimestamp`], since the block would otherwise - /// run as an ordinary one. A caller that executes a block with a parent must supply it. + /// `None` is a block with no parent to compare against. The genesis block, number zero, has + /// none, and neither rule applies to it, whenever Satin activates at or before its timestamp. + /// Any other block is accepted without it only where no parent could change the rules: when + /// every fork the schedule activates is active from timestamp zero. Where one could, executing + /// the block fails with [`MegaBlockExecutionError::MissingParentTimestamp`], since the block + /// would otherwise run as an ordinary one. A caller that executes a block with a parent must + /// supply it. pub parent_timestamp: Option, /// The builder's packing policy: the limits only a builder applies, and a cap on the block's /// data-size budget below the protocol's ([`BlockLimits`]). @@ -214,10 +218,11 @@ impl MegaBlockExecutionCtx { pub enum MegaBlockExecutionError { /// A block that activates a fork carries a transaction that is not a deposit. UnexpectedNonDepositTxInActivationBlock, - /// The context names no parent timestamp for a block whose activation rules depend on it: a - /// fork the schedule activates after genesis is active at the block, and whether it activates - /// in this block, which makes the block deposit-only and, for Satin, makes the pre-block step - /// check the predeploys, is decided by the parent's timestamp. + /// The context names no parent timestamp for a block other than the genesis block whose + /// activation rules depend on it: a fork the schedule activates after timestamp zero is active + /// at the block, and whether it activates in this block, which makes the block deposit-only + /// and, for Satin, makes the pre-block step check the EIP-7997 factory, is decided by the + /// parent's timestamp. /// /// The caller's omission, not a verdict on the block: an internal error. Executing the block /// without the timestamp would run it as an ordinary block. @@ -232,12 +237,11 @@ pub enum MegaBlockExecutionError { /// The footprint the block has left. available_block_da_footprint: u64, }, - /// 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. + /// In the block in which Satin activates, the EIP-7997 factory's address does not hold the + /// factory's code: it holds other code, no code, or no account. /// - /// Satin deploys and upgrades nothing: the legacy forks install the six system contracts, the - /// `SequencerRegistry` and the Oracle at v2.0.0, and OP's genesis tooling the EIP-7997 - /// factory, so a chain without them is not one Satin runs on. + /// Satin does not deploy the factory, which OP's genesis tooling preinstalls, so a chain + /// without it is not one Satin runs on. UnexpectedSystemContractCode { /// The predeploy's address. address: Address, @@ -252,6 +256,16 @@ pub enum MegaBlockExecutionError { /// What the call ended with: its result, or the error that stopped it. message: String, }, + /// The `SequencerRegistry` makes the block invalid: its deployment found code it cannot + /// migrate, or the resolution of the block's live system address found it absent, holding + /// other code, or naming no system address. + SequencerRegistry(SequencerRegistryRefusal), + /// The block must seed the `SequencerRegistry` or migrate it from version 1.0.0, and the chain + /// configuration carries no usable bootstrap values for it: none, or one of them zero. + /// + /// The node's configuration, which its parser refuses, not a verdict on the block: an internal + /// error. + UnusableRegistryBootstrap, /// An outcome handed to a delayed commit executed against another nonce or balance of its /// sender than the block holds now: a commit since its execution moved them. /// @@ -291,6 +305,11 @@ impl fmt::Display for MegaBlockExecutionError { Self::ApplyPendingChangesFailed { message } => { write!(f, "the SequencerRegistry's pending changes could not be applied: {message}") } + Self::SequencerRegistry(refusal) => write!(f, "{refusal}"), + Self::UnusableRegistryBootstrap => f.write_str( + "the SequencerRegistry must be seeded or migrated, and the chain configuration \ + carries no usable bootstrap values for it", + ), Self::StaleOutcome { tx_hash, sender } => write!( f, "stale outcome of transaction {tx_hash}: it executed against another nonce or \ @@ -304,17 +323,19 @@ impl core::error::Error for MegaBlockExecutionError {} impl From for BlockExecutionError { /// A block refused for what the node itself does is an internal error: an outcome the builder - /// let go stale and a parent timestamp the caller left out say 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. + /// let go stale, a parent timestamp the caller left out and bootstrap values its configuration + /// lacks say 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::StaleOutcome { .. } | - MegaBlockExecutionError::MissingParentTimestamp { .. } => Self::other(error), + MegaBlockExecutionError::MissingParentTimestamp { .. } | + MegaBlockExecutionError::UnusableRegistryBootstrap => Self::other(error), MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | MegaBlockExecutionError::UnexpectedSystemContractCode { .. } | - MegaBlockExecutionError::ApplyPendingChangesFailed { .. } => { + MegaBlockExecutionError::ApplyPendingChangesFailed { .. } | + MegaBlockExecutionError::SequencerRegistry(_) => { Self::Validation(alloy_evm::block::BlockValidationError::Other(Box::new(error))) } } @@ -357,7 +378,7 @@ pub struct MegaBlockExecutor { struct ActivationRules { /// A fork activates in the block, so it admits only deposits. admits_only_deposits: bool, - /// Satin activates in the block, so the pre-block step checks the predeploys. + /// Satin activates in the block, so the pre-block step checks the EIP-7997 factory. satin_activation_block: bool, } @@ -415,10 +436,12 @@ where ) -> Self { let block_gas_limit = evm.ctx().block().gas_limit(); let block_timestamp = evm.ctx().block().timestamp().saturating_to(); + let genesis = evm.ctx().block().number().is_zero(); let protocol_limits = ProtocolLimits::for_spec(evm.ctx().spec()); evm.set_tx_runtime_limits(protocol_limits.tx_runtime_limits); let limiter = BlockLimiter::new(ctx.block_limits.within(&protocol_limits), block_gas_limit); - let activation = Self::activation_rules(&spec, ctx.parent_timestamp, block_timestamp); + let activation = + Self::activation_rules(&spec, genesis, ctx.parent_timestamp, block_timestamp); Self { spec, receipt_builder, @@ -436,18 +459,24 @@ where /// The activation rules of the block at `block_timestamp` whose parent is at /// `parent_timestamp`, decided once for the block. /// - /// Without the parent's timestamp the rules are known only where no parent could change - /// them: no fork the schedule activates after genesis is active at the block - /// ([`MegaHardforks::activation_depends_on_parent`]), so neither rule applies. That is a block - /// with no parent, such as a genesis block, or a chain whose forks are all active from the - /// start. Any other block is refused with [`MegaBlockExecutionError::MissingParentTimestamp`], - /// since running it as an ordinary block would silently skip both rules. + /// The `genesis` block has no parent, and a fork active at its timestamp is active from it: + /// no fork activates in it, so neither rule applies, as on a chain on which Satin is active + /// from genesis no block is Satin's activation block. Without the parent's timestamp the rules + /// of any other block are known only where no parent could change them: no fork the schedule + /// activates after timestamp zero is active at the block + /// ([`MegaHardforks::activation_depends_on_parent`]), so neither rule applies. Any other block + /// is refused with [`MegaBlockExecutionError::MissingParentTimestamp`], since running it as an + /// ordinary block would silently skip both rules. fn activation_rules( spec: &Spec, + genesis: bool, parent_timestamp: Option, block_timestamp: u64, ) -> Result { match parent_timestamp { + _ if genesis => { + Ok(ActivationRules { admits_only_deposits: false, satin_activation_block: false }) + } Some(parent) => Ok(ActivationRules { admits_only_deposits: spec.admits_only_deposits(parent, block_timestamp), satin_activation_block: spec.is_satin_activation_block(parent, block_timestamp), @@ -474,8 +503,8 @@ where self.activation.clone().map(|rules| rules.admits_only_deposits) } - /// Whether Satin activates in this block, which makes the pre-block step check the system - /// contracts and the EIP-7997 factory. + /// Whether Satin activates in this block, which makes the pre-block step check the EIP-7997 + /// factory. /// /// The two answers differ: an Optimism fork at or after Jovian also makes a block /// deposit-only. Decided as [`admits_only_deposits`](Self::admits_only_deposits) is. @@ -655,14 +684,35 @@ where .unwrap_or_default()) } - /// Whether `tx` is a Mega System Transaction: sent from the live system address with the - /// system shape. A transaction from that address of another shape is not (the engine refuses - /// it when it validates it). A read the database cannot serve is an internal error. + /// Whether `tx` is a Mega System Transaction: sent from the live system address the EVM + /// classifies transactions against, which the pre-block steps resolved, with the system shape. + /// A transaction from that address of another shape is not (the engine refuses it when it + /// validates it). A read the database cannot serve, which only an EVM whose read when it was + /// built failed makes before the pre-block steps resolved the address, is an internal error. fn is_system_transaction(&mut self, tx: &MegaTransaction) -> Result { - let system_address = live_system_address(&mut *self.evm.ctx_mut().db_mut()) - .map_err(BlockExecutionError::other)?; + let system_address = + self.evm.ctx_mut().live_system_address().map_err(BlockExecutionError::other)?; Ok(classify_system_transaction(tx, system_address).unwrap_or(false)) } + + /// The bootstrap values the `SequencerRegistry`'s deployment needs from the chain + /// configuration, and the refusals its deployment and the resolution of the live system + /// address make, as the block's errors: a failed read and missing bootstrap values are the + /// node's internal errors, a refusal a verdict on the block. + fn registry_error(error: SequencerRegistryError) -> BlockExecutionError + where + E: core::error::Error + Send + Sync + 'static, + { + match error { + SequencerRegistryError::Database(error) => BlockExecutionError::other(error), + SequencerRegistryError::UnusableBootstrap => { + MegaBlockExecutionError::UnusableRegistryBootstrap.into() + } + SequencerRegistryError::Refused(refusal) => { + MegaBlockExecutionError::SequencerRegistry(refusal).into() + } + } + } } impl MegaBlockExecutor, R, Spec> @@ -744,38 +794,41 @@ where /// Runs what a block does before its transactions. /// /// In order: the reset of the block-hash and bucket records and of what the block reported of - /// the L1 block contract, the EIP-2935 and EIP-4788 pre-block calls, in the block in which - /// Satin activates the check of the predeploys, and the `SequencerRegistry`'s due role - /// changes. Each step's state is committed here, on its own and read-only entries included, - /// rather than inside its helper, so a commit hook on the database sees every step's read and - /// write set. The sequence of committed states is the witness a stateless client needs. + /// the L1 block contract, then the pre-block sequence: + /// + /// 1. the EIP-2935 call, and 2. the EIP-4788 call, neither made in the genesis block, whose + /// parent beacon block root must be zero; + /// 3. in the block in which Satin activates, and in no other, the check of the EIP-7997 + /// factory; + /// 4. the deployment of the Oracle, the high-precision timestamp, `KeylessDeploy`, + /// `MegaAccessControl` and `MegaLimitControl`, each a step of its own; + /// 5. the read of whether the `SequencerRegistry` has a role change due, and when it has, the + /// `applyPendingChanges()` call; + /// 6. the deployment of the `SequencerRegistry`, from the chain configuration's bootstrap + /// values when it must be seeded or migrated; + /// 7. the resolution of the block's live system address, which the EVM classifies every + /// transaction of the block against. + /// + /// Each step's state is committed here, on its own, before the next step runs, read-only + /// entries included, rather than inside its helper, so every step sees the ones before it and + /// a commit hook on the database sees every step's read and write set. The sequence of + /// committed states is the witness a stateless client needs. Nothing is charged, and nothing + /// counts toward the block's counters. /// /// Nothing reads the L1 block contract here. op-revm's handler fetches the L1 block info when /// it deducts the caller of the first non-deposit transaction, which is after the block's own /// L1 info deposit has committed, and the first transaction that reads it reports what it read /// in its own returned state. /// - /// The EIP-2935 and EIP-4788 calls run before the check. They write the parent hash and the - /// 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 + /// Each pre-block call runs 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 before its state is committed. - /// - /// The check is made once, in the block in which Satin activates - /// (see [`MegaBlockExecutor::is_satin_activation_block`]): each of the seven predeploys must - /// hold the code Satin expects, and its account is committed as a read-only entry; any - /// other block reads none of them. Satin deploys and upgrades nothing: a chain reaches it - /// through the legacy forks, which leave the six system contracts at the versions Satin - /// runs, and the EIP-7997 factory is OP's predeploy. - /// - /// The registry's role changes come after. Its pending slots are read and committed as a - /// read-only state whatever they say, and when a change is due in this block the - /// `applyPendingChanges()` call applies it on the same pre-block budget, refusing the block - /// if it does not succeed. So a rotation due in this block governs this block's - /// system-address transactions: each reads the live system address out of the registry when - /// it is validated, after these steps are committed, and nothing inside the block can - /// change it again. + /// does not succeed refuses the block before its state is committed. A deployment installs a + /// missing system contract and replaces one whose code differs, keeping its storage, and + /// records one that holds the expected code as a read-only entry; the registry is seeded when + /// its address holds no code, migrated in place from version 1.0.0, and refuses the block when + /// it holds other code. The resolution comes last, on the state every other step left, so a + /// rotation due in this block governs this block's Mega System Transactions; nothing inside the + /// block can change the address again, and it refuses the block when the registry names none. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { // A block whose activation rules cannot be decided is refused before anything runs. self.admits_only_deposits()?; @@ -805,41 +858,51 @@ where self.commit(state); } - // The EIP-2935 / EIP-4788 calls above do not depend on these predeploys: they target - // their own contracts, not the MegaETH system addresses or the factory. + // The EIP calls above do not depend on what follows: they target their own contracts, + // not the MegaETH system addresses or the factory. if self.is_satin_activation_block()? { - for spec in system_contract_specs() { - let state = - check_system_contract(self.evm.db_mut(), &spec).map_err( - |error| match error { - SystemContractCheckError::Database(error) => { - BlockExecutionError::other(error) - } - SystemContractCheckError::UnexpectedCode { - address, - expected, - found, - } => MegaBlockExecutionError::UnexpectedSystemContractCode { - address, - expected, - found, - } - .into(), - }, - )?; - self.commit(state); - } + let state = check_system_contract(self.evm.db_mut(), &create2_factory_spec()).map_err( + |error| match error { + SystemContractCheckError::Database(error) => BlockExecutionError::other(error), + SystemContractCheckError::UnexpectedCode { address, expected, found } => { + MegaBlockExecutionError::UnexpectedSystemContractCode { + address, + expected, + found, + } + .into() + } + }, + )?; + self.commit(state); } - let block_number = self.evm.block().number().saturating_to(); - let (due, reads) = is_apply_pending_changes_due(self.evm.db_mut(), block_number) - .map_err(BlockExecutionError::other)?; + for spec in flat_system_contract_specs() { + let state = deploy_system_contract(self.evm.db_mut(), &spec) + .map_err(BlockExecutionError::other)?; + self.commit(state); + } + + let block_number = self.evm.block().number(); + let (due, reads) = + is_apply_pending_changes_due(self.evm.db_mut(), block_number.saturating_to()) + .map_err(BlockExecutionError::other)?; self.commit(reads); if due { let ResultAndState { state, .. } = transact_apply_pending_changes(&mut self.evm)?; self.commit(state); } + let bootstrap = self.spec.sequencer_registry_bootstrap(); + let state = deploy_sequencer_registry(self.evm.db_mut(), block_number, bootstrap) + .map_err(Self::registry_error)?; + self.commit(state); + + let (system_address, state) = + resolve_system_address(self.evm.db_mut()).map_err(Self::registry_error)?; + self.commit(state); + self.evm.ctx_mut().set_system_address(Some(system_address)); + Ok(()) } diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index c50facd36..b16d6dc0c 100644 --- a/crates/mega-evm/src/block/genesis.rs +++ b/crates/mega-evm/src/block/genesis.rs @@ -1,11 +1,13 @@ -//! The Satin key of a chain configuration: when Satin activates. +//! The Satin keys of a chain configuration: when Satin activates, and the `SequencerRegistry`'s +//! bootstrap values a chain that schedules it carries. //! -//! [`SatinChainConfig`] reads it and states the format, which is provisional. +//! [`SatinChainConfig`] reads them and states the format, which is provisional. #[cfg(not(feature = "std"))] use alloc as std; -use core::fmt; +use core::{fmt, str::FromStr}; use std::{ + borrow::ToOwned, collections::BTreeMap, string::{String, ToString}, }; @@ -17,7 +19,12 @@ use serde::{ Deserialize, Deserializer, Serialize, Serializer, }; -use crate::{MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError}; +use alloy_primitives::Address; + +use crate::{ + system::SequencerRegistryBootstrap, MegaHardfork, MegaHardforkConfig, MegaHardforks, + ScheduleError, +}; /// The key of Satin's activation timestamp. pub const SATIN_TIME_KEY: &str = "satinTime"; @@ -25,6 +32,26 @@ pub const SATIN_TIME_KEY: &str = "satinTime"; /// Every Satin key of a chain configuration, in the order [`SatinChainConfig`] writes them. pub const SATIN_CHAIN_CONFIG_KEYS: [&str; 1] = [SATIN_TIME_KEY]; +/// The key of the sequencer a new `SequencerRegistry` is seeded with. +pub const REX5_INITIAL_SEQUENCER_KEY: &str = "rex5InitialSequencer"; + +/// The key of the admin a new `SequencerRegistry` is seeded with. +pub const REX5_INITIAL_ADMIN_KEY: &str = "rex5InitialAdmin"; + +/// The key of the minimum rotation delay a `SequencerRegistry` is seeded or migrated with. +pub const REX6_MIN_ROTATION_DELAY_KEY: &str = "rex6MinRotationDelay"; + +/// The `SequencerRegistry`'s bootstrap keys, which a configuration that schedules Satin carries, +/// in the order [`SatinChainConfig`] writes them after [`SATIN_TIME_KEY`]. +pub const SEQUENCER_REGISTRY_BOOTSTRAP_KEYS: [&str; 3] = + [REX5_INITIAL_SEQUENCER_KEY, REX5_INITIAL_ADMIN_KEY, REX6_MIN_ROTATION_DELAY_KEY]; + +/// What a bootstrap address must be. +const ADDRESS_EXPECTED: &str = "a 20-byte hexadecimal address"; + +/// What an integer must be. +const INTEGER_EXPECTED: &str = "an integer from 0 to 2^64 - 1"; + /// The prefix every Satin key starts with, compared without regard to case. const PREFIX: &str = "satin"; @@ -32,7 +59,7 @@ const PREFIX: &str = "satin"; const ARBITRARY_PRECISION_NUMBER: &str = "$serde_json::private::Number"; /// A chain's Satin configuration, as its genesis file's `config` object carries it: when Satin -/// activates. +/// activates, and the `SequencerRegistry`'s bootstrap values. /// /// **The key format is provisional.** It is fixed when a network first publishes a genesis file /// that carries it; until then a change to it is a change to this parser and to every genesis @@ -43,32 +70,40 @@ const ARBITRARY_PRECISION_NUMBER: &str = "$serde_json::private::Number"; /// key names and the rules cannot drift apart between them: a reader that took another value for /// the key would execute another chain. /// -/// Satin carries no parameter: a chain that activates it has run the legacy forks, which deployed -/// the `SequencerRegistry` and upgraded it to v2.0.0, and the registry's roles are what it holds. -/// The legacy forks' own keys (`rex5InitialSequencer`, `rex6MinRotationDelay`, ...) are theirs -/// and are not read here. +/// Satin carries no parameter of its own: no key names a limit, a detention cap or a price. Every +/// Satin block deploys the `SequencerRegistry`, seeding it when the state does not hold it and +/// migrating it from version 1.0.0, from the bootstrap values under the keys the Rex era +/// introduced, which a configuration that schedules Satin must carry; once the registry holds its +/// roles, its storage decides them, not these values. /// -/// The key sits at the top level of the genesis file's `config` object, beside the other forks' +/// The keys sit at the top level of the genesis file's `config` object, beside the other forks' /// keys, camelCase: /// -/// | Key | Value | Field | -/// | ----------- | ------- | ------------------------------------------------------ | -/// | `satinTime` | integer | the activation timestamp ([`Self::activation_time`]) | +/// | Key | Value | Field | +/// | ---------------------- | ------- | --------------------------------------------------------- | +/// | `satinTime` | integer | the activation timestamp ([`Self::activation_time`]) | +/// | `rex5InitialSequencer` | address | a new registry's sequencer, non-zero | +/// | `rex5InitialAdmin` | address | a new registry's admin, non-zero | +/// | `rex6MinRotationDelay` | integer | the registry's minimum rotation delay in blocks, non-zero | /// -/// An integer is a JSON number that fits in 64 unsigned bits, `u64::MAX` included, which a writer -/// must emit exactly. +/// The last three are [`Self::sequencer_registry_bootstrap`]. An integer is a JSON number that +/// fits in 64 unsigned bits, `u64::MAX` included, which a writer must emit exactly; an address is +/// a JSON string of 40 hexadecimal digits, `0x` before them. /// /// The rules: /// -/// - A configuration with no key starting with `satin` does not activate Satin. +/// - A configuration with no key starting with `satin` does not activate Satin, and its other keys, +/// the bootstrap keys included, are not read. +/// - A configuration that activates Satin must carry each bootstrap key, each non-zero: one that +/// lacks one or gives one as zero is refused, naming the key. /// - A key starting with `satin`, in any case, that is not `satinTime` is refused, so a misspelled /// 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 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 key given twice, a bootstrap key included, 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 @@ -76,24 +111,26 @@ const ARBITRARY_PRECISION_NUMBER: &str = "$serde_json::private::Number"; /// same object written into the file alike, so both are read as the number; every reader parses /// here, so every reader reads it the same. /// -/// The parser reads no other fork's key. Satin runs on the OP Karst fork and the Ethereum forks -/// Karst includes, Osaka among them, and [`hardforks`](Self::hardforks) schedules those as active -/// from the first block, which no Satin block can tell apart from the file's times when they are -/// active by `satinTime`. +/// The parser reads no other fork's key but the bootstrap keys. Satin runs on the OP Karst fork and +/// the Ethereum forks Karst includes, Osaka among them, and [`hardforks`](Self::hardforks) +/// schedules those as active from the first block, which no Satin block can tell apart from the +/// file's times when they are active by `satinTime`. /// A node's own schedule times those forks from the file, and holds them to both halves of the /// timing rule [`validate_schedule`](MegaHardforks::validate_schedule) states. /// /// A flat key is one entry of the object, so a checker that freezes a configuration key by key -/// freezes `satinTime` on its own and names it when it changes. It does not stop a key being added +/// freezes each key on its own and names it when it changes. It does not stop a key being added /// later; a rule that refuses a new key starting with `satin` once the configuration was first /// loaded does. /// -/// It serializes to the key it is read from, so a generator that writes a genesis file with it +/// It serializes to the keys it is read from, so a generator that writes a genesis file with it /// writes what every reader parses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SatinChainConfig { /// The timestamp Satin activates at. pub activation_time: u64, + /// The `SequencerRegistry`'s bootstrap values. + pub sequencer_registry_bootstrap: SequencerRegistryBootstrap, } impl SatinChainConfig { @@ -115,28 +152,41 @@ impl SatinChainConfig { let mut entries = config .deserialize_map(EntriesVisitor) .map_err(|error| SatinChainConfigError::Malformed(error.to_string()))?; - if let Some(unknown) = - entries.keys().find(|key| !SATIN_CHAIN_CONFIG_KEYS.contains(&key.as_str())) + if let Some(unknown) = entries + .keys() + .find(|key| is_satin_key(key) && !SATIN_CHAIN_CONFIG_KEYS.contains(&key.as_str())) { return Err(SatinChainConfigError::UnknownKey(unknown.clone())); } let activation_time = match entries.remove(SATIN_TIME_KEY) { None => return Ok(None), - Some(Entry::Unsigned(value)) => value, - Some(Entry::Other) => { - return Err(SatinChainConfigError::InvalidValue { - key: SATIN_TIME_KEY, - expected: "an integer from 0 to 2^64 - 1", - }) - } + Some(entry) => entry.integer(SATIN_TIME_KEY)?, + }; + let mut bootstrap = |key| entries.remove(key).ok_or(SatinChainConfigError::MissingKey(key)); + let initial_sequencer = + bootstrap(REX5_INITIAL_SEQUENCER_KEY)?.non_zero_address(REX5_INITIAL_SEQUENCER_KEY)?; + let initial_admin = + bootstrap(REX5_INITIAL_ADMIN_KEY)?.non_zero_address(REX5_INITIAL_ADMIN_KEY)?; + let min_rotation_delay = + match bootstrap(REX6_MIN_ROTATION_DELAY_KEY)?.integer(REX6_MIN_ROTATION_DELAY_KEY)? { + 0 => return Err(SatinChainConfigError::ZeroValue(REX6_MIN_ROTATION_DELAY_KEY)), + delay => delay, + }; + let config = Self { + activation_time, + sequencer_registry_bootstrap: SequencerRegistryBootstrap::new( + initial_sequencer, + initial_admin, + min_rotation_delay, + ), }; - let config = Self { activation_time }; config.hardforks()?; Ok(Some(config)) } /// The hardfork schedule this configuration makes: [`MegaHardforkConfig::new`]'s base forks - /// and Satin at [`activation_time`](Self::activation_time). + /// and Satin at [`activation_time`](Self::activation_time), carrying the bootstrap values + /// ([`MegaHardforks::sequencer_registry_bootstrap`]). /// /// The base forks, every OP and Ethereum fork up to Karst, are active from the first block here /// whatever the genesis file times them at, so the schedule passes the base-fork check of @@ -149,17 +199,23 @@ impl SatinChainConfig { /// A schedule [`validate_schedule`](MegaHardforks::validate_schedule) refuses. pub fn hardforks(&self) -> Result { let schedule = MegaHardforkConfig::new() - .with(MegaHardfork::Satin, ForkCondition::Timestamp(self.activation_time)); + .with(MegaHardfork::Satin, ForkCondition::Timestamp(self.activation_time)) + .with_sequencer_registry_bootstrap(self.sequencer_registry_bootstrap); schedule.validate_schedule()?; Ok(schedule) } } impl Serialize for SatinChainConfig { - /// Writes the key, [`SATIN_TIME_KEY`]. + /// Writes the keys, [`SATIN_TIME_KEY`] then [`SEQUENCER_REGISTRY_BOOTSTRAP_KEYS`]. fn serialize(&self, serializer: S) -> Result { - let mut map = serializer.serialize_map(Some(SATIN_CHAIN_CONFIG_KEYS.len()))?; + let bootstrap = &self.sequencer_registry_bootstrap; + let len = SATIN_CHAIN_CONFIG_KEYS.len() + SEQUENCER_REGISTRY_BOOTSTRAP_KEYS.len(); + let mut map = serializer.serialize_map(Some(len))?; map.serialize_entry(SATIN_TIME_KEY, &self.activation_time)?; + map.serialize_entry(REX5_INITIAL_SEQUENCER_KEY, &bootstrap.initial_sequencer)?; + map.serialize_entry(REX5_INITIAL_ADMIN_KEY, &bootstrap.initial_admin)?; + map.serialize_entry(REX6_MIN_ROTATION_DELAY_KEY, &bootstrap.min_rotation_delay)?; map.end() } } @@ -178,6 +234,10 @@ pub enum SatinChainConfigError { /// What its value must be. expected: &'static str, }, + /// A bootstrap key a configuration that schedules Satin lacks. + MissingKey(&'static str), + /// A bootstrap key whose value is zero. + ZeroValue(&'static str), /// A schedule [`validate_schedule`](MegaHardforks::validate_schedule) refuses. Schedule(ScheduleError), } @@ -190,6 +250,10 @@ impl fmt::Display for SatinChainConfigError { } Self::UnknownKey(key) => write!(f, "`{key}` is not a Satin chain-configuration key"), Self::InvalidValue { key, expected } => write!(f, "`{key}` must be {expected}"), + Self::MissingKey(key) => { + write!(f, "a chain configuration that schedules Satin must carry `{key}`") + } + Self::ZeroValue(key) => write!(f, "`{key}` must not be zero"), Self::Schedule(error) => write!(f, "{error}"), } } @@ -203,16 +267,44 @@ impl From for SatinChainConfigError { } } -/// The value of a key, as far as reading the Satin key needs it: an unsigned integer, or anything -/// else. +/// The value of a key, as far as reading the Satin keys needs it: an unsigned integer, a string, +/// or anything else. #[derive(Debug)] enum Entry { Unsigned(u64), + Text(String), Other, } -/// 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. +impl Entry { + /// The integer the value of `key` is. + fn integer(self, key: &'static str) -> Result { + match self { + Self::Unsigned(value) => Ok(value), + Self::Text(_) | Self::Other => { + Err(SatinChainConfigError::InvalidValue { key, expected: INTEGER_EXPECTED }) + } + } + } + + /// The non-zero address the value of `key` is: 40 hexadecimal digits after `0x`. + fn non_zero_address(self, key: &'static str) -> Result { + let invalid = || SatinChainConfigError::InvalidValue { key, expected: ADDRESS_EXPECTED }; + let Self::Text(text) = self else { return Err(invalid()) }; + let digits = text.strip_prefix("0x").ok_or_else(invalid)?; + if digits.len() != 40 || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(invalid()); + } + let address = Address::from_str(digits).map_err(|_| invalid())?; + if address.is_zero() { + return Err(SatinChainConfigError::ZeroValue(key)); + } + Ok(address) + } +} + +/// Collects a configuration object's entries whose key starts with [`PREFIX`] and the bootstrap +/// keys', the last copy of a key given twice, and skips the others' values without keeping them. struct EntriesVisitor; impl<'de> Visitor<'de> for EntriesVisitor { @@ -225,7 +317,7 @@ impl<'de> Visitor<'de> for EntriesVisitor { fn visit_map>(self, mut map: A) -> Result { let mut entries = BTreeMap::new(); while let Some(key) = map.next_key::()? { - if is_satin_key(&key) { + if is_satin_key(&key) || SEQUENCER_REGISTRY_BOOTSTRAP_KEYS.contains(&key.as_str()) { entries.insert(key, map.next_value::()?); } else { map.next_value::()?; @@ -279,8 +371,8 @@ impl<'de> Visitor<'de> for EntryVisitor { Ok(Entry::Other) } - fn visit_str(self, _: &str) -> Result { - Ok(Entry::Other) + fn visit_str(self, value: &str) -> Result { + Ok(Entry::Text(value.to_owned())) } fn visit_unit(self) -> Result { @@ -334,8 +426,15 @@ mod tests { const ACTIVATION: u64 = 1_800_000_000; + /// The bootstrap values [`genesis_config`] carries. + const BOOTSTRAP: SequencerRegistryBootstrap = SequencerRegistryBootstrap::new( + alloy_primitives::address!("0x4444444444444444444444444444444444444444"), + alloy_primitives::address!("0x5555555555555555555555555555555555555555"), + 100, + ); + fn config() -> SatinChainConfig { - SatinChainConfig { activation_time: ACTIVATION } + SatinChainConfig { activation_time: ACTIVATION, sequencer_registry_bootstrap: BOOTSTRAP } } /// The keys of the configuration format's earlier versions: the `SequencerRegistry`'s roles and @@ -353,8 +452,8 @@ mod tests { "satinBlockTxsDataLimit", ]; - /// A mainnet-shaped genesis `config` object carrying [`config`] among other forks' keys, the - /// legacy forks' registry keys included. + /// A mainnet-shaped genesis `config` object carrying [`config`] among other forks' keys: the + /// legacy forks' registry keys, which are its bootstrap values, and others. fn genesis_config() -> Value { let mut object = json!({ "chainId": 4326, @@ -362,9 +461,6 @@ mod tests { "shanghaiTime": 0, "rex5Time": 1_760_000_000, "rex6Time": 1_770_000_000, - "rex5InitialSequencer": "0x4444444444444444444444444444444444444444", - "rex5InitialAdmin": "0x5555555555555555555555555555555555555555", - "rex6MinRotationDelay": 100, "optimism": { "eip1559Elasticity": 6, "eip1559Denominator": 50 }, "blobSchedule": { "cancun": { "target": 3, "max": 6 } }, "terminalTotalDifficultyPassed": true, @@ -379,13 +475,20 @@ mod tests { SatinChainConfig::from_genesis_config(config) } - /// The configuration writes `satinTime` alone, and reading it back gives the same - /// configuration, from a `serde_json::Value` and from the object's text alike, with the legacy - /// forks' keys beside it read by nobody here. + /// The configuration writes `satinTime` and the three bootstrap keys, and reading it back + /// gives the same configuration, from a `serde_json::Value` and from the object's text alike, + /// with the other forks' keys beside it read by nobody here. #[test] fn test_the_key_round_trips() { - assert_eq!(serde_json::to_string(&config()).unwrap(), r#"{"satinTime":1800000000}"#); + assert_eq!( + serde_json::to_string(&config()).unwrap(), + r#"{"satinTime":1800000000,"rex5InitialSequencer":"0x4444444444444444444444444444444444444444","rex5InitialAdmin":"0x5555555555555555555555555555555555555555","rex6MinRotationDelay":100}"# + ); assert_eq!(SATIN_CHAIN_CONFIG_KEYS, [SATIN_TIME_KEY]); + assert_eq!( + SEQUENCER_REGISTRY_BOOTSTRAP_KEYS, + ["rex5InitialSequencer", "rex5InitialAdmin", "rex6MinRotationDelay"] + ); assert_eq!(parse(&genesis_config()), Ok(Some(config()))); let text = genesis_config().to_string(); @@ -395,16 +498,104 @@ mod tests { ); } - /// The schedule the configuration makes runs Satin from its activation and passes the - /// schedule's own check. + /// The schedule the configuration makes runs Satin from its activation, carries the bootstrap + /// values, and passes the schedule's own check. #[test] fn test_the_schedule_activates_satin() { let schedule = config().hardforks().unwrap(); assert_eq!(schedule.spec_id(ACTIVATION - 1), None); assert_eq!(schedule.spec_id(ACTIVATION), Some(MegaSpecId::SATIN)); + assert_eq!(schedule.sequencer_registry_bootstrap(), Some(BOOTSTRAP)); assert_eq!(schedule.validate_schedule(), Ok(())); } + /// A configuration that schedules Satin must carry each of the three bootstrap keys: one that + /// lacks one is refused, naming it. One that does not schedule Satin needs none of them. + #[test] + fn test_a_missing_bootstrap_key_is_refused() { + for key in SEQUENCER_REGISTRY_BOOTSTRAP_KEYS { + let mut config = genesis_config(); + config.as_object_mut().unwrap().remove(key); + assert_eq!(parse(&config), Err(SatinChainConfigError::MissingKey(key)), "{key}"); + assert_eq!( + SatinChainConfigError::MissingKey(key).to_string(), + format!("a chain configuration that schedules Satin must carry `{key}`") + ); + config.as_object_mut().unwrap().remove(SATIN_TIME_KEY); + assert_eq!(parse(&config), Ok(None), "{key}: no Satin, no bootstrap needed"); + } + } + + /// A bootstrap value of zero is refused, naming its key: the zero address as either role, + /// written in any case, and a minimum rotation delay of zero. + #[test] + fn test_a_zero_bootstrap_value_is_refused() { + let zero_address = json!("0x0000000000000000000000000000000000000000"); + for (key, zero) in [ + (REX5_INITIAL_SEQUENCER_KEY, zero_address.clone()), + (REX5_INITIAL_ADMIN_KEY, zero_address), + (REX6_MIN_ROTATION_DELAY_KEY, json!(0)), + ] { + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert(key.into(), zero); + assert_eq!(parse(&config), Err(SatinChainConfigError::ZeroValue(key)), "{key}"); + } + assert_eq!( + SatinChainConfigError::ZeroValue(REX5_INITIAL_ADMIN_KEY).to_string(), + "`rex5InitialAdmin` must not be zero" + ); + } + + /// A bootstrap address must be a string of 40 hexadecimal digits after `0x`, in either case, + /// and the rotation delay an integer; anything else is refused, naming the key. The last copy + /// of a bootstrap key given twice is read. + #[test] + fn test_a_bootstrap_value_of_the_wrong_type_is_refused() { + let with = |key: &str, value: Value| { + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert(key.into(), value); + parse(&config) + }; + let mixed_case = + with(REX5_INITIAL_ADMIN_KEY, json!("0xAbCdEf0000000000000000000000000000000001")); + assert_eq!( + mixed_case.unwrap().unwrap().sequencer_registry_bootstrap.initial_admin, + alloy_primitives::address!("0xabcdef0000000000000000000000000000000001") + ); + for key in [REX5_INITIAL_SEQUENCER_KEY, REX5_INITIAL_ADMIN_KEY] { + let refused = + Err(SatinChainConfigError::InvalidValue { key, expected: ADDRESS_EXPECTED }); + for value in [ + json!("4444444444444444444444444444444444444444"), + json!("0x44"), + json!("0x44444444444444444444444444444444444444444"), + json!("0x444444444444444444444444444444444444444g"), + json!(1), + json!(null), + json!(["0x4444444444444444444444444444444444444444"]), + ] { + assert_eq!(with(key, value.clone()), refused, "{key}: {value}"); + } + } + let refused = Err(SatinChainConfigError::InvalidValue { + key: REX6_MIN_ROTATION_DELAY_KEY, + expected: INTEGER_EXPECTED, + }); + for value in [json!("100"), json!(-1), json!(1.5), json!(null)] { + assert_eq!(with(REX6_MIN_ROTATION_DELAY_KEY, value.clone()), refused, "{value}"); + } + let text = genesis_config().to_string(); + let twice = text.replacen( + "\"rex6MinRotationDelay\":100", + "\"rex6MinRotationDelay\":0,\"rex6MinRotationDelay\":7", + 1, + ); + assert_ne!(twice, text); + let streamed = + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&twice)); + assert_eq!(streamed.unwrap().unwrap().sequencer_registry_bootstrap.min_rotation_delay, 7); + } + /// A configuration without a Satin key does not activate Satin. One whose only Satin key is /// not `satinTime` is refused for that key. #[test] @@ -533,7 +724,7 @@ mod tests { key: SATIN_TIME_KEY, expected: "an integer from 0 to 2^64 - 1", }); - let at = |time| Ok(Some(SatinChainConfig { activation_time: time })); + let at = |time| Ok(Some(SatinChainConfig { activation_time: time, ..config() })); for (first, last, expected) in [ ("1", "1800000000", at(ACTIVATION)), ("1800000000", "7", at(7)), diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 8b0d730f6..aa19f7303 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -16,7 +16,7 @@ use alloy_op_hardforks::{OpHardfork, OpHardforks}; use alloy_primitives::{BlockTimestamp, U256}; use auto_impl::auto_impl; -use crate::MegaSpecId; +use crate::{system::SequencerRegistryBootstrap, MegaSpecId}; /// The Ethereum forks Satin runs on that a schedule activates by timestamp: every one from the /// first after the Merge up to Osaka. @@ -75,6 +75,18 @@ pub trait MegaHardforks: OpHardforks { /// carry it. fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition; + /// The `SequencerRegistry`'s bootstrap values the chain configuration carries, or `None` if it + /// carries none. + /// + /// A Satin block reads them only to deploy the registry: to seed a registry its state does not + /// hold, and to give one at version 1.0.0 its minimum rotation delay when it migrates it. A + /// chain configuration that schedules Satin must carry them, each non-zero, and its parser + /// refuses one that does not + /// ([`SatinChainConfig::from_genesis_config`](crate::SatinChainConfig::from_genesis_config)); + /// a block that needs them and finds none, or a zero one, cannot be executed, which is the + /// node's fault and no verdict on the block. + fn sequencer_registry_bootstrap(&self) -> Option; + /// The latest `MegaETH` fork active at `timestamp`, or `None` before the first one. /// /// Resolution reads raw activation events and walks [`MegaHardfork::VARIANTS`] from the top, @@ -260,6 +272,8 @@ impl Clone for ForkEntry { #[derive(Debug, Clone)] pub struct MegaHardforkConfig { entries: Vec, + /// The `SequencerRegistry`'s bootstrap values, which the schedule carries beside the forks. + sequencer_registry_bootstrap: Option, } impl Default for MegaHardforkConfig { @@ -281,6 +295,7 @@ where condition, }) .collect(), + sequencer_registry_bootstrap: None, } } } @@ -334,9 +349,20 @@ impl MegaHardforkConfig { .into_iter() .map(|(fork, condition)| ForkEntry { fork, condition }) .collect(), + sequencer_registry_bootstrap: None, } } + /// Carries `bootstrap`, the `SequencerRegistry`'s bootstrap values, beside the schedule + /// ([`MegaHardforks::sequencer_registry_bootstrap`]). + pub const fn with_sequencer_registry_bootstrap( + mut self, + bootstrap: SequencerRegistryBootstrap, + ) -> Self { + self.sequencer_registry_bootstrap = Some(bootstrap); + self + } + /// Activates every `MegaETH` fork at timestamp 0. pub fn with_all_activated(mut self) -> Self { for fork in MegaHardfork::VARIANTS { @@ -392,6 +418,10 @@ impl MegaHardforks for MegaHardforkConfig { fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { self.get(fork).copied().unwrap_or(ForkCondition::Never) } + + fn sequencer_registry_bootstrap(&self) -> Option { + self.sequencer_registry_bootstrap + } } #[cfg(test)] diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 8f7d3c791..179f78334 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -46,6 +46,15 @@ pub(crate) type MegaInnerContext = /// 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 /// oracle service ([`OracleReadRecord`]). +/// +/// It holds the live system address it classifies transactions against: a transaction of the +/// system shape from it is a Mega System Transaction, and one of another shape from it is invalid. +/// A context built without one reads it once, when it is built, directly off its database +/// ([`live_system_address`](crate::system::live_system_address)): outside every transaction, so +/// no transaction loads the registry, finds it warm or pays for the read, and a transaction run +/// on the context costs what it costs in a block. Block execution resolves the address after +/// every block's pre-block steps and hands it in +/// ([`set_system_address`](Self::set_system_address)). #[derive(Debug)] pub struct MegaContext { pub(crate) inner: MegaInnerContext, @@ -71,6 +80,8 @@ pub struct MegaContext, + /// The live system address the context classifies transactions against. + system_address: LiveSystemAddress, /// Whether the context runs the neutral configuration. See [`MegaContext::with_neutral_cfg`]. #[cfg(any(test, feature = "test-utils"))] neutral: bool, @@ -80,6 +91,16 @@ pub struct MegaContext, } +/// The live system address a context classifies transactions against, as far as it knows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum LiveSystemAddress { + /// Read off the database or handed in: the address, or `None` when the registry names none. + Known(Option
), + /// The read when the context was built failed: the next transaction reads it again, and fails + /// with the database's error if the read fails again. + Unread, +} + impl MegaContext { /// Creates a context over `db` that executes `spec`, without external environments. /// @@ -93,11 +114,19 @@ impl MegaContext { impl MegaContext { /// Creates a context over `db` that executes `spec` with the given external environments, /// under `spec`'s limits ([`ProtocolLimits::for_spec`]). + /// + /// It reads the live system address off `db` here, directly and outside every transaction + /// ([`live_system_address`](crate::system::live_system_address)), and classifies every + /// transaction against it until one is handed in + /// ([`with_system_address`](Self::with_system_address)). A read the database cannot serve is + /// made again by the next transaction, which fails with the database's error if it fails again. pub fn new_with_external_envs( - db: DB, + mut db: DB, spec: MegaSpecId, external_envs: ExternalEnvs, ) -> Self { + let system_address = system::live_system_address(&mut db) + .map_or(LiveSystemAddress::Unread, LiveSystemAddress::Known); let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); let limits = ProtocolLimits::for_spec(spec).tx_runtime_limits; let inner: MegaInnerContext = @@ -115,6 +144,7 @@ impl MegaContext { system_call: false, oracle_service: true, keyless_creation: None, + system_address, #[cfg(any(test, feature = "test-utils"))] neutral: false, #[cfg(any(test, feature = "test-utils"))] @@ -262,6 +292,46 @@ impl MegaContext { f(&mut self.inner.chain); } + /// Classifies every transaction from the next one on against `system_address`, the live + /// system address, in place of the one the context read when it was built: `None` makes no + /// transaction a Mega System Transaction. + pub fn with_system_address(mut self, system_address: Option
) -> Self { + self.set_system_address(system_address); + self + } + + /// Classifies every transaction from the next one on against `system_address`. Block execution + /// hands in the address it resolved after the block's pre-block steps. + pub const fn set_system_address(&mut self, system_address: Option
) { + self.system_address = LiveSystemAddress::Known(system_address); + } + + /// The live system address the context classifies transactions against: `None` when the + /// registry names none, and while a read the database could not serve when the context was + /// built is still to be made again. + pub const fn system_address(&self) -> Option
{ + match self.system_address { + LiveSystemAddress::Known(address) => address, + LiveSystemAddress::Unread => None, + } + } + + /// The live system address the next transaction is classified against, read off the database + /// now, directly and outside the transaction's journal, if the read when the context was built + /// failed. + /// + /// # Errors + /// + /// The database's, when that read fails again. + pub(crate) fn live_system_address(&mut self) -> Result, DB::Error> { + if let LiveSystemAddress::Known(address) = self.system_address { + return Ok(address); + } + let address = system::live_system_address(self.inner.db_mut())?; + self.system_address = LiveSystemAddress::Known(address); + Ok(address) + } + /// The spec this context executes. pub const fn spec(&self) -> MegaSpecId { self.cfg.spec diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index af6af0090..6d6eb46f3 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -198,18 +198,20 @@ where Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } - /// Reads the live system address out of the registry, then decides whether the transaction - /// is a system-address transaction and prepares the common execution layer for it, then - /// validates a system-address transaction and promotes it to a deposit, then validates the - /// transaction as op-revm does — as a deposit, when it was promoted. + /// Decides, against the live system address the context holds, whether the transaction is a + /// system-address transaction and prepares the common execution layer for it, then validates + /// a system-address transaction and promotes it to a deposit, then validates the transaction + /// as op-revm does — as a deposit, when it was promoted. /// /// This is the handler's first phase, so the layer is prepared before anything else of the - /// transaction runs, and a read the database cannot serve fails the transaction through the - /// handler's error path, which discards what the journal loaded. Every transaction reads the - /// live system address, whatever its shape, and the read leaves the registry's account and - /// its slot warm for the rest of the transaction, as EIP-3651 leaves the block beneficiary. + /// transaction runs. The transaction does not read the registry: the context resolved the + /// address outside every transaction — block execution after the block's pre-block steps, any + /// other EVM when it was built — so no transaction finds the registry's account or slot warm + /// or pays for the read. Only when that read failed does the context make it again here, off + /// the database and outside the journal, and a failure again fails the transaction through + /// the handler's error path. fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { - let system_address = crate::system::load_system_address(evm.ctx_mut().journal_mut())?; + let system_address = evm.ctx_mut().live_system_address()?; self.validate_env_as(evm, system_address, true) } diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 1ce6ccd3d..f2a22ce41 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -39,8 +39,9 @@ pub use block::{ 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, + L1_BLOCK_INFO_SLOTS, MAINNET_CHAIN_ID, REX5_INITIAL_ADMIN_KEY, REX5_INITIAL_SEQUENCER_KEY, + REX6_MIN_ROTATION_DELAY_KEY, SATIN_CHAIN_CONFIG_KEYS, SATIN_TIME_KEY, + SEQUENCER_REGISTRY_BOOTSTRAP_KEYS, SYSTEM_ADDRESS, TESTNET_CHAIN_ID, }; #[cfg(feature = "satin-price-override")] pub use evm::install_satin_prices; diff --git a/crates/mega-evm/src/system/predeploys.rs b/crates/mega-evm/src/system/predeploys.rs index 6fb13e090..08f26085e 100644 --- a/crates/mega-evm/src/system/predeploys.rs +++ b/crates/mega-evm/src/system/predeploys.rs @@ -1,22 +1,28 @@ -//! The predeploys Satin runs on, and the check its activation block makes of them. +//! The predeploys Satin runs on: the six `MegaETH` system contracts, which every block deploys, +//! and the EIP-7997 `CREATE2` factory, which the block in which Satin activates checks. //! -//! [`system_contract_specs`] lists them: the six `MegaETH` system contracts in address order, then -//! the EIP-7997 `CREATE2` factory, each with the code Satin expects (the bytecode -//! `mega-system-contracts` ships; the Oracle and the `SequencerRegistry` are their v2.0.0). A chain -//! reaches Satin through the legacy forks, which install the six, and OP's genesis tooling, which -//! preinstalls the factory, so Satin deploys none of them. +//! [`system_contract_specs`] lists the seven: the six system contracts in address order, then the +//! factory, each with the code Satin expects (the bytecode `mega-system-contracts` ships; the +//! Oracle and the `SequencerRegistry` are their v2.0.0). //! -//! The block in which Satin activates checks once that each address holds that code -//! ([`check_system_contract`]); no other block reads them. The check returns its read as a state -//! and never commits; the block executor commits it as a read-only state of its own, so the -//! activation block's witness, built from the committed states, carries the seven accounts. +//! Every block deploys the first five, in that order, before its transactions +//! ([`flat_system_contract_specs`], [`deploy_system_contract`]): a missing contract is installed, +//! one whose code differs has its code replaced, its nonce, balance and storage kept, and one that +//! holds the expected code is left as it is and recorded as a read-only entry. The +//! `SequencerRegistry`, which holds roles and histories, is deployed by its own rule +//! ([`deploy_sequencer_registry`](crate::system::deploy_sequencer_registry)). The factory is not a +//! `MegaETH` contract and nothing deploys it: OP's genesis tooling preinstalls it, and the block in +//! which Satin activates checks once that its address holds its code ([`check_system_contract`]). +//! +//! Each step returns its state and never commits; the block executor commits it as a state of its +//! own, so the block's witness, built from the committed states, carries every account read. use core::fmt; use alloy_primitives::{address, b256, bytes, Address, Bytes, B256}; use revm::{ primitives::KECCAK_EMPTY, - state::{Account, EvmState}, + state::{Account, Bytecode, EvmState}, Database, }; @@ -34,6 +40,10 @@ use super::{ /// the EIP-7997 factory. pub const SYSTEM_CONTRACT_COUNT: usize = 7; +/// How many system contracts [`flat_system_contract_specs`] returns: every one but the +/// `SequencerRegistry`, which is deployed by its own rule. +pub const FLAT_SYSTEM_CONTRACT_COUNT: usize = 5; + /// The EIP-7997 `CREATE2` factory address (Arachnid's deterministic deployment proxy). pub const CREATE2_FACTORY_ADDRESS: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); @@ -50,10 +60,10 @@ pub const CREATE2_FACTORY_CODE_HASH: B256 = pub struct SystemContractSpec { /// The predeploy's address. pub address: Address, - /// The runtime bytecode the address holds, which a test or a tool installs for a state of - /// its own. + /// The runtime bytecode the address holds, which the deployment installs. pub code: Bytes, - /// Keccak-256 hash of [`code`](Self::code): what the activation check compares. + /// Keccak-256 hash of [`code`](Self::code): what the deployment and the factory check + /// compare. pub code_hash: B256, } @@ -69,8 +79,8 @@ impl SystemContractSpec { pub enum SystemContractCheckError { /// The database could not load the account at the predeploy's address. Database(DbError), - /// The address does not hold the code Satin expects: it holds other code, an older version - /// of the contract, no code, or no account. + /// The address does not hold the code Satin expects: it holds other code, no code, or no + /// account. UnexpectedCode { /// The predeploy's address. address: Address, @@ -98,8 +108,8 @@ impl fmt::Display for SystemContractCheckError { } } -/// The refusal of a predeploy at `address` that holds the code hash `found` where `expected` must -/// be when Satin activates. +/// The refusal of the predeploy at `address`, the EIP-7997 factory, that holds the code hash +/// `found` where `expected` must be when Satin activates. pub(crate) fn write_unexpected_code( f: &mut fmt::Formatter<'_>, address: Address, @@ -154,9 +164,66 @@ pub fn check_system_contract( } } -/// The seven predeploys in the order the activation block checks them: Oracle, high-precision -/// timestamp, `KeylessDeploy`, `MegaAccessControl`, `MegaLimitControl`, `SequencerRegistry`, then -/// the EIP-7997 factory. +/// Deploys the system contract `spec` names as a block's pre-block step, on the state the earlier +/// steps left, and answers the step's state. Nothing is committed, and nothing is charged. +/// +/// An address with no account is given an account holding the contract's code, marked created and +/// touched. An account whose code hash is not `spec.code_hash` has its code replaced, its nonce, +/// balance and storage kept: touched, not created, so committing it keeps the storage. An account +/// that holds the code is answered as a read-only entry (neither touched nor created, no storage), +/// which records the read for the witness. +/// +/// # Errors +/// +/// The database's, when the account cannot be loaded. +pub fn deploy_system_contract( + db: &mut DB, + spec: &SystemContractSpec, +) -> Result { + debug_assert_eq!( + Bytecode::new_raw(spec.code.clone()).hash_slow(), + spec.code_hash, + "the code hash of {} is not the hash of its code", + spec.address + ); + let existing = db.basic(spec.address)?; + if let Some(info) = existing.as_ref().filter(|info| info.code_hash == spec.code_hash) { + return Ok(EvmState::from_iter([(spec.address, Account::from(info.clone()))])); + } + let created = existing.is_none(); + let mut info = existing.unwrap_or_default(); + info.code_hash = spec.code_hash; + info.code = Some(Bytecode::new_raw(spec.code.clone())); + let mut account = Account::from(info); + account.mark_touch(); + if created { + account.mark_created(); + } + Ok(EvmState::from_iter([(spec.address, account)])) +} + +/// The five system contracts every block deploys by the same rule ([`deploy_system_contract`]), in +/// the order it deploys them: Oracle, high-precision timestamp, `KeylessDeploy`, +/// `MegaAccessControl`, `MegaLimitControl`. The first five of [`system_contract_specs`]. +pub fn flat_system_contract_specs() -> [SystemContractSpec; FLAT_SYSTEM_CONTRACT_COUNT] { + let [oracle, timestamp, keyless, access_control, limit_control, ..] = system_contract_specs(); + [oracle, timestamp, keyless, access_control, limit_control] +} + +/// The EIP-7997 factory, which the block in which Satin activates checks +/// ([`check_system_contract`]). The last of [`system_contract_specs`]. +pub fn create2_factory_spec() -> SystemContractSpec { + SystemContractSpec::new( + CREATE2_FACTORY_ADDRESS, + CREATE2_FACTORY_CODE, + CREATE2_FACTORY_CODE_HASH, + ) +} + +/// The seven predeploys a chain that ran Rex6 holds: Oracle, high-precision timestamp, +/// `KeylessDeploy`, `MegaAccessControl`, `MegaLimitControl`, `SequencerRegistry`, then the EIP-7997 +/// factory. Every block deploys the six system contracts in that order, and the block in which +/// Satin activates checks the factory first. pub fn system_contract_specs() -> [SystemContractSpec; SYSTEM_CONTRACT_COUNT] { [ SystemContractSpec::new( @@ -185,11 +252,7 @@ pub fn system_contract_specs() -> [SystemContractSpec; SYSTEM_CONTRACT_COUNT] { SEQUENCER_REGISTRY_CODE, SEQUENCER_REGISTRY_CODE_HASH, ), - SystemContractSpec::new( - CREATE2_FACTORY_ADDRESS, - CREATE2_FACTORY_CODE, - CREATE2_FACTORY_CODE_HASH, - ), + create2_factory_spec(), ] } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index ce8d987b8..420f724fe 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -5,38 +5,46 @@ //! to it is an ordinary call. Its Solidity source is //! `crates/system-contracts/contracts/SequencerRegistry.sol`. //! -//! The legacy forks deployed it (Rex5) and upgraded it to v2.0.0 (Rex6); Satin neither creates nor -//! upgrades it. The block in which Satin activates checks that it holds v2.0.0 -//! ([`check_system_contract`](crate::system::check_system_contract)), and is invalid -//! otherwise. A role change the registry schedules takes effect at its activation block through a -//! pre-block call: the block executor reads whether one is due -//! ([`is_apply_pending_changes_due`]) and, when one is, calls `applyPendingChanges()` -//! ([`transact_apply_pending_changes`]). The call is permissionless and applies only what is due, -//! so a block that makes it applies the same changes whoever calls. +//! Every block takes three pre-block steps on it, after the EIP calls and the other five system +//! contracts' deployment, each returning its state for the block executor to commit on its own: //! -//! The live system address, which a system-address transaction must be sent from, is read out of -//! the registry by every transaction when it is validated ([`load_system_address`]): the read -//! loads the registry's account and `_currentSystemAddress` into the transaction's journal, warm, -//! as EIP-3651 starts the block beneficiary warm, so what a transaction pays never depends on its -//! envelope. Nothing inside a block can change the address after the pre-block call — a change can -//! only be scheduled for a later block — so every transaction of a block reads the address the -//! block's pre-block step left, and an EVM a node builds outside block execution reads the one in -//! the state it runs on without being told. +//! 1. the due-change read ([`is_apply_pending_changes_due`]) and, when a role change is due in the +//! block, the `applyPendingChanges()` call ([`transact_apply_pending_changes`]), which is +//! permissionless and applies only what is due, so a block that makes it applies the same +//! changes whoever calls; +//! 2. its deployment ([`deploy_sequencer_registry`]): left as it is when it holds v2.0.0, migrated +//! in place from v1.0.0, seeded from the chain configuration's bootstrap values +//! ([`SequencerRegistryBootstrap`]) when the address holds no code, and the block refused when +//! it holds any other code; +//! 3. the resolution of the block's live system address ([`resolve_system_address`]), the address a +//! Mega System Transaction must be sent from, read once on the state every other step left and +//! handed to execution. +//! +//! No transaction reads the registry for its classification, so none finds its account or slot +//! warm: nothing inside a block can change the address after the pre-block steps — a change can +//! only be scheduled for a later block — so every transaction of a block is classified against the +//! address its pre-block steps left. An EVM built outside block execution reads the address in the +//! state it runs on once, when it is built ([`live_system_address`]), without loading anything into +//! a transaction's journal. + +use core::fmt; use alloy_evm::block::BlockExecutionError; use alloy_primitives::{address, Address, Bytes, B256, U256}; use alloy_sol_types::SolCall; use op_revm::OpHaltReason; use revm::{ - context::{result::ResultAndState, JournalTr}, + context::result::ResultAndState, primitives::KECCAK_EMPTY, - state::{Account, EvmState, EvmStorageSlot, TransactionId}, + state::{Account, Bytecode, EvmState, EvmStorageSlot, TransactionId}, }; +use super::MEGA_SYSTEM_ADDRESS; use crate::{transact_pre_block_call, ExternalEnvTypes, MegaBlockExecutionError, MegaEvm}; use storage_slots::{ - CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, + INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, }; /// The address of the `SequencerRegistry` system contract. @@ -49,8 +57,157 @@ pub use mega_system_contracts::sequencer_registry::LATEST_CODE as SEQUENCER_REGI /// The code hash of the `SequencerRegistry` contract. pub use mega_system_contracts::sequencer_registry::LATEST_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH; +/// The code hash of the registry's version 1.0.0, which the deployment migrates in place. +pub use mega_system_contracts::sequencer_registry::V1_0_0_CODE_HASH as SEQUENCER_REGISTRY_V1_CODE_HASH; + pub use mega_system_contracts::sequencer_registry::{storage_slots, ISequencerRegistry}; +/// The values a new `SequencerRegistry` is seeded with and a migrated one is given its minimum +/// rotation delay from: the chain configuration's bootstrap values, under the keys the Rex era +/// introduced (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`). +/// +/// The initial system address is not among them: a new registry names +/// [`MEGA_SYSTEM_ADDRESS`], which every chain's first system transactions came from. Once the +/// registry holds its roles, its storage decides them, not these values. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SequencerRegistryBootstrap { + /// The sequencer a new registry starts with. + pub initial_sequencer: Address, + /// The admin a new registry starts with. + pub initial_admin: Address, + /// The least number of blocks between scheduling a sequencer change and its activation. + pub min_rotation_delay: u64, +} + +impl SequencerRegistryBootstrap { + /// The bootstrap values `initial_sequencer`, `initial_admin` and `min_rotation_delay`. + pub const fn new( + initial_sequencer: Address, + initial_admin: Address, + min_rotation_delay: u64, + ) -> Self { + Self { initial_sequencer, initial_admin, min_rotation_delay } + } + + /// Whether every value is usable: neither address zero, nor the delay, which would leave the + /// network no window to react to a scheduled rotation. + pub fn is_usable(&self) -> bool { + !self.initial_sequencer.is_zero() && + !self.initial_admin.is_zero() && + self.min_rotation_delay != 0 + } + + /// The storage a registry deployed new at `block_number` is seeded with, slot by slot: the + /// current and initial system address [`MEGA_SYSTEM_ADDRESS`], the current and initial + /// sequencer, the admin, the block it starts at and the minimum rotation delay. The pending + /// slots and the two histories start empty. + pub fn seed(&self, block_number: U256) -> [(U256, U256); 7] { + let system_address = address_word(MEGA_SYSTEM_ADDRESS); + let sequencer = address_word(self.initial_sequencer); + [ + (CURRENT_SYSTEM_ADDRESS, system_address), + (CURRENT_SEQUENCER, sequencer), + (ADMIN, address_word(self.initial_admin)), + (INITIAL_SYSTEM_ADDRESS, system_address), + (INITIAL_SEQUENCER, sequencer), + (INITIAL_FROM_BLOCK, block_number), + (MIN_ROTATION_DELAY, U256::from(self.min_rotation_delay)), + ] + } +} + +/// An address as the word a Solidity `address` slot holds. +fn address_word(address: Address) -> U256 { + U256::from_be_bytes(address.into_word().0) +} + +/// Why the registry's deployment or the resolution of the live system address could not be made +/// or refused the block. +#[derive(Debug)] +pub enum SequencerRegistryError { + /// The database could not serve a read of the registry: a fault of the node, never a verdict + /// on the block. + Database(DbError), + /// The registry has to be seeded or migrated, and the chain configuration carries no usable + /// bootstrap values for it: none, or one of them zero. A fault of the node's configuration, + /// which a node refuses when it loads it, never a verdict on the block. + UnusableBootstrap, + /// The registry makes the block invalid. + Refused(SequencerRegistryRefusal), +} + +impl fmt::Display for SequencerRegistryError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Database(error) => write!(f, "{error}"), + Self::UnusableBootstrap => f.write_str( + "the SequencerRegistry must be seeded or migrated, and the chain configuration \ + carries no usable bootstrap values for it", + ), + Self::Refused(refusal) => write!(f, "{refusal}"), + } + } +} + +impl core::error::Error for SequencerRegistryError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Database(error) => Some(error), + Self::UnusableBootstrap | Self::Refused(_) => None, + } + } +} + +/// What the `SequencerRegistry` holds that makes a block invalid. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SequencerRegistryRefusal { + /// The deployment found code it cannot migrate: neither version 2.0.0, nor version 1.0.0, nor + /// none. A stateful contract's storage is never overwritten by code it was not migrated to. + UnmigratableCode { + /// The code hash the registry's address holds. + found: B256, + }, + /// The resolution found no account at the registry's address. + Absent, + /// The resolution found code other than version 2.0.0. + UnexpectedCode { + /// The code hash the registry's address holds. + found: B256, + }, + /// The resolution found `_currentSystemAddress` zero: the registry names no system address. + NoSystemAddress, +} + +impl fmt::Display for SequencerRegistryRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnmigratableCode { found } => write!( + f, + "the SequencerRegistry at {SEQUENCER_REGISTRY_ADDRESS} holds code hash {found}, \ + which is neither version 2.0.0 ({SEQUENCER_REGISTRY_CODE_HASH}) nor version \ + 1.0.0 ({SEQUENCER_REGISTRY_V1_CODE_HASH}) nor no code: its storage is not \ + overwritten" + ), + Self::Absent => write!( + f, + "the SequencerRegistry at {SEQUENCER_REGISTRY_ADDRESS} has no account when the \ + block resolves its live system address" + ), + Self::UnexpectedCode { found } => write!( + f, + "the SequencerRegistry at {SEQUENCER_REGISTRY_ADDRESS} must hold code hash \ + {SEQUENCER_REGISTRY_CODE_HASH} when the block resolves its live system address; \ + it holds code hash {found}" + ), + Self::NoSystemAddress => write!( + f, + "the SequencerRegistry at {SEQUENCER_REGISTRY_ADDRESS} names no system address: \ + its _currentSystemAddress is zero" + ), + } + } +} + /// Whether a role change the registry holds is due at `block_number`: a pending system address /// or sequencer whose activation block has come. /// @@ -58,9 +215,7 @@ pub use mega_system_contracts::sequencer_registry::{storage_slots, ISequencerReg /// witness a stateless client replays the decision from, which the caller commits whether or /// not a change is due. Both roles' pending slots are read, and a role's activation block only /// when it has a change pending. A registry that does not exist has nothing due, and its absence -/// is what the witness records; no chain Satin runs on lacks it, its activation block refusing -/// one without the registry's code, so only a state built apart from a chain, such as a test's, -/// reaches that answer. +/// is what the witness records: the block's deployment of the registry, which follows, seeds it. /// /// # Errors /// @@ -139,15 +294,120 @@ where transact_pre_block_call(evm, "applyPendingChanges()", SEQUENCER_REGISTRY_ADDRESS, data, refused) } -/// The live system address in the state `db` holds: the address a system-address transaction -/// must be sent from, as every transaction reads it when it is validated. +/// Deploys the registry as a block's pre-block step, on the state the earlier steps left, and +/// answers the step's state. Nothing is committed, and nothing is charged. +/// +/// What it does depends on what the registry's address holds: +/// +/// - version 2.0.0: nothing; the account is answered as a read-only entry (neither touched nor +/// created, no storage), so the witness records the read; +/// - version 1.0.0: migrated in place: its code replaced by version 2.0.0 and slot 13 +/// (`_minRotationDelay`) written with the bootstrap's minimum rotation delay, every other slot — +/// the roles, the pending changes, the histories — its nonce and its balance kept; +/// - no account, or an account without code: version 2.0.0 deployed new, an existing account's +/// nonce and balance kept and its storage cleared (the account is marked created), and seeded +/// with [`SequencerRegistryBootstrap::seed`] at `block_number`. +/// +/// # Errors +/// +/// [`SequencerRegistryError::Refused`] with [`SequencerRegistryRefusal::UnmigratableCode`] when +/// the address holds any other code, which makes the block invalid; +/// [`SequencerRegistryError::UnusableBootstrap`] when the registry must be seeded or migrated and +/// `bootstrap` is `None` or holds a zero value; [`SequencerRegistryError::Database`] when a read +/// fails. +pub fn deploy_sequencer_registry( + db: &mut DB, + block_number: U256, + bootstrap: Option, +) -> Result> { + let existing = + db.basic(SEQUENCER_REGISTRY_ADDRESS).map_err(SequencerRegistryError::Database)?; + let found = existing.as_ref().map_or(KECCAK_EMPTY, |info| info.code_hash); + if let Some(info) = existing.as_ref().filter(|_| found == SEQUENCER_REGISTRY_CODE_HASH) { + return Ok(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, Account::from(info.clone()))])); + } + let migrate = found == SEQUENCER_REGISTRY_V1_CODE_HASH; + if !migrate && found != KECCAK_EMPTY { + return Err(SequencerRegistryError::Refused(SequencerRegistryRefusal::UnmigratableCode { + found, + })); + } + let bootstrap = bootstrap + .filter(SequencerRegistryBootstrap::is_usable) + .ok_or(SequencerRegistryError::UnusableBootstrap)?; + + let mut info = existing.unwrap_or_default(); + info.code_hash = SEQUENCER_REGISTRY_CODE_HASH; + info.code = Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)); + let mut registry = Account::from(info); + registry.mark_touch(); + if migrate { + // Not marked created, which would clear the roles, the pending changes and the histories + // on commit: the one slot written is the one version 1.0.0 never used. + let original = db + .storage(SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY) + .map_err(SequencerRegistryError::Database)?; + let delay = U256::from(bootstrap.min_rotation_delay); + registry.storage.insert( + MIN_ROTATION_DELAY, + EvmStorageSlot::new_changed(original, delay, TransactionId::ZERO), + ); + } else { + registry.mark_created(); + for (slot, value) in bootstrap.seed(block_number) { + registry + .storage + .insert(slot, EvmStorageSlot::new_changed(U256::ZERO, value, TransactionId::ZERO)); + } + } + Ok(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)])) +} + +/// Resolves a block's live system address, once, after every other pre-block step: the address +/// the registry's `_currentSystemAddress` holds in the state `db` holds, with the read as a +/// read-only state (the registry's account and slot 0) for the block executor to commit last. +/// +/// The registry's code hash is compared and its code neither loaded nor run; nothing is charged or +/// written. /// -/// It is what a transaction pool gives -/// [`validate_transaction_stateless`](crate::validate_transaction_stateless), read off the state -/// the pool validates against, and it holds for the block whose pre-block changes made that -/// state: a later block's pre-block step may change it, so a pool reads it again for every block. -/// `None` when the registry names no address this engine trusts: it has no account, it holds -/// other code than [`SEQUENCER_REGISTRY_CODE`], or its `_currentSystemAddress` is zero. +/// # Errors +/// +/// [`SequencerRegistryError::Refused`] when the registry has no account, holds other code than +/// [`SEQUENCER_REGISTRY_CODE`], or names no system address, each of which makes the block invalid; +/// [`SequencerRegistryError::Database`] when a read fails. +pub fn resolve_system_address( + db: &mut DB, +) -> Result<(Address, EvmState), SequencerRegistryError> { + let refused = SequencerRegistryError::Refused; + let Some(info) = + db.basic(SEQUENCER_REGISTRY_ADDRESS).map_err(SequencerRegistryError::Database)? + else { + return Err(refused(SequencerRegistryRefusal::Absent)); + }; + if info.code_hash != SEQUENCER_REGISTRY_CODE_HASH { + return Err(refused(SequencerRegistryRefusal::UnexpectedCode { found: info.code_hash })); + } + let mut registry = Account::from(info); + let current = read_slot(db, &mut registry, CURRENT_SYSTEM_ADDRESS) + .map_err(SequencerRegistryError::Database)?; + if current.is_zero() { + return Err(refused(SequencerRegistryRefusal::NoSystemAddress)); + } + let address = Address::from_word(current.into()); + Ok((address, EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)]))) +} + +/// The live system address in the state `db` holds, read directly off the database and outside any +/// transaction: what an EVM built without an address classifies its transactions against, and +/// what a transaction pool gives +/// [`validate_transaction_stateless`](crate::validate_transaction_stateless). +/// +/// It holds for the block whose pre-block steps made that state: a later block's pre-block step +/// may change it, so a reader reads it again for every block. `None` when the registry names no +/// address this engine trusts: it has no account, it holds other code than +/// [`SEQUENCER_REGISTRY_CODE`], or its `_currentSystemAddress` is zero. Block execution refuses a +/// block in each of those cases ([`resolve_system_address`]); outside it no transaction is then a +/// Mega System Transaction. /// /// It reads the registry's account and, when it holds this engine's code, the one slot, and /// writes nothing, so any database serves: pass `&mut db` for a [`Database`](revm::Database) the @@ -164,65 +424,24 @@ pub fn live_system_address(mut db: DB) -> Result( - journal: &mut J, -) -> Result, ::Error> { - let code_hash = journal.load_account(SEQUENCER_REGISTRY_ADDRESS)?.data.info.code_hash; - let current = journal.sload(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)?.data; - Ok(system_address_named_by(code_hash, current)) -} - -/// The system address a registry whose code hash is `code_hash` names when its -/// `_currentSystemAddress` holds `current`: none unless the registry holds this engine's code and -/// a non-zero address. -fn system_address_named_by(code_hash: B256, current: U256) -> Option
{ // The expected hash is the registry code this engine requires, the latest version. When the - // registry is next upgraded under a later spec, the hash compared here must be chosen per - // spec: compared with the newer code alone, a block of this spec replayed by the newer binary - // finds no system address, and its system transactions are silently demoted to ordinary ones. - (code_hash == SEQUENCER_REGISTRY_CODE_HASH && !current.is_zero()) - .then(|| Address::from_word(current.into())) + // registry is next upgraded under a later spec, the hash compared here and in the block's + // resolution must be chosen per spec: compared with the newer code alone, a block of this + // spec replayed by the newer binary is refused. + Ok((!current.is_zero()).then(|| Address::from_word(current.into()))) } #[cfg(test)] mod tests { use super::*; - use crate::{ - system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId, SYSTEM_CALL_REGULAR_GAS_LIMIT, - }; + use crate::{MegaContext, MegaSpecId, SYSTEM_CALL_REGULAR_GAS_LIMIT}; use alloy_primitives::address; use revm::{ - context::{BlockEnv, ContextTr, JournalTr, Transaction}, + context::{BlockEnv, ContextTr, Transaction}, database::{InMemoryDB, State}, - state::{AccountInfo, Bytecode}, + state::AccountInfo, Database, DatabaseCommit, }; - use storage_slots::CURRENT_SEQUENCER; const NEXT_SYSTEM_ADDRESS: Address = address!("0x1111111111111111111111111111111111111111"); const NEXT_SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); @@ -463,85 +682,202 @@ mod tests { db } - /// Reads the live system address out of `db` through a fresh journal, and answers it with the - /// journal the read left behind. - fn load(db: InMemoryDB) -> (Option
, revm::Journal) { - let mut journal = revm::Journal::new(db); - let address = load_system_address(&mut journal).expect("the read succeeds"); - (address, journal) + /// The bootstrap values the deployment tests seed from. + const BOOTSTRAP: SequencerRegistryBootstrap = + SequencerRegistryBootstrap::new(NEXT_SEQUENCER, CURRENT_SEQUENCER_ADDRESS, 7_200); + + /// The registry's entry in the state a deployment over `db` at block 1,000 answers. + fn deployed( + db: &mut InMemoryDB, + bootstrap: Option, + ) -> Result> { + let state = deploy_sequencer_registry(db, U256::from(1_000), bootstrap)?; + assert_eq!(state.len(), 1, "the registry is the only account the deployment names"); + Ok(state[&SEQUENCER_REGISTRY_ADDRESS].clone()) } - /// Asserts the read left the registry's account and its system-address slot in `journal`, - /// warm, untouched and unchanged, the slot holding `current`: a witness of the read, and what - /// the transaction's own access to either finds warm. - fn assert_warm_and_unchanged(journal: &revm::Journal, current: U256) { - let registry = &journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.is_cold_transaction_id(journal.transaction_id), "the account is warm"); - assert!(!registry.is_touched(), "a read-only entry"); - assert_eq!(registry.storage.len(), 1, "exactly the one slot read"); - let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; - assert!(!slot.is_cold, "the slot is warm"); - assert!(!slot.is_changed()); - assert_eq!(slot.present_value(), current); + /// A registry at version 2.0.0 is left as it is: a read-only entry, no slot read or written, + /// and no bootstrap needed. + #[test] + fn test_the_deployment_leaves_version_2_as_a_read_only_entry() { + let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let registry = deployed(&mut db, None).expect("version 2.0.0 needs no bootstrap"); + assert!(!registry.is_touched() && !registry.is_created(), "a read-only entry"); + assert!(registry.storage.is_empty(), "no slot is read or written"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); } - /// A registry holding the code this engine requires names the address it stores, and the read - /// leaves the account and the slot warm, without loading the code. + /// Where the address has no account, the deployment installs version 2.0.0 as a new contract + /// seeded with the seven flat slots: the system address both current and initial, the + /// bootstrap's sequencer both current and initial, its admin, the block number and its + /// minimum rotation delay. Where it holds an account without code, the account's nonce and + /// balance are kept and its storage goes: the account is marked created. #[test] - fn test_the_read_answers_the_stored_system_address_and_warms_the_registry() { - let db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); - let (address, journal) = load(db); - assert_eq!(address, Some(NEXT_SYSTEM_ADDRESS)); - assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); - assert_eq!( - journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].info.code_hash, - SEQUENCER_REGISTRY_CODE_HASH + fn test_the_deployment_seeds_a_new_registry() { + let expected_storage = [ + (CURRENT_SYSTEM_ADDRESS, word(MEGA_SYSTEM_ADDRESS)), + (CURRENT_SEQUENCER, word(NEXT_SEQUENCER)), + (ADMIN, word(CURRENT_SEQUENCER_ADDRESS)), + (INITIAL_SYSTEM_ADDRESS, word(MEGA_SYSTEM_ADDRESS)), + (INITIAL_SEQUENCER, word(NEXT_SEQUENCER)), + (INITIAL_FROM_BLOCK, U256::from(1_000)), + (MIN_ROTATION_DELAY, U256::from(7_200)), + ]; + let mut funded = InMemoryDB::default(); + funded.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { nonce: 3, balance: U256::from(9), ..Default::default() }, ); + funded + .insert_account_storage(SEQUENCER_REGISTRY_ADDRESS, U256::from(42), U256::ONE) + .unwrap(); + for (mut db, nonce, balance) in + [(InMemoryDB::default(), 0, U256::ZERO), (funded, 3, U256::from(9))] + { + let registry = deployed(&mut db, Some(BOOTSTRAP)).expect("the registry is seeded"); + assert!(registry.is_touched() && registry.is_created(), "a new contract"); + assert_eq!((registry.info.nonce, registry.info.balance), (nonce, balance)); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + let seeded: Vec<_> = registry + .storage + .iter() + .map(|(slot, value)| (*slot, value.original_value(), value.present_value())) + .collect(); + let mut expected: Vec<_> = + expected_storage.iter().map(|&(slot, value)| (slot, U256::ZERO, value)).collect(); + expected.sort(); + let mut seeded = seeded; + seeded.sort(); + assert_eq!(seeded, expected); + + db.commit(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)])); + assert_eq!(db.storage(SEQUENCER_REGISTRY_ADDRESS, U256::from(42)).unwrap(), U256::ZERO); + assert_eq!(live_system_address(&mut db).unwrap(), Some(MEGA_SYSTEM_ADDRESS)); + } } - /// A registry still holding the legacy engine's first bytecode is not the one this engine - /// requires: it names no address. Its slot is read all the same, so what a transaction pays - /// does not depend on the registry's code. + /// A registry at version 1.0.0 is migrated in place: its code becomes version 2.0.0 and slot + /// 13 the bootstrap's minimum rotation delay, and every other slot, its nonce and its balance + /// stay. The account is not marked created, which would clear them. #[test] - fn test_the_read_refuses_the_v1_code_hash() { + fn test_the_deployment_migrates_version_1_writing_slot_13_alone() { use mega_system_contracts::sequencer_registry::V1_0_0_CODE; - let (address, journal) = load(registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS))); - assert_eq!(address, None); - assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); + let mut db = registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS)); + db.insert_account_storage(SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER, U256::from(5)) + .unwrap(); + db.cache.accounts.get_mut(&SEQUENCER_REGISTRY_ADDRESS).unwrap().info.balance = + U256::from(11); + let registry = deployed(&mut db, Some(BOOTSTRAP)).expect("the registry is migrated"); + assert!(registry.is_touched() && !registry.is_created(), "migrated, not created"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(registry.info.balance, U256::from(11)); + assert_eq!(registry.storage.keys().copied().collect::>(), [MIN_ROTATION_DELAY]); + let delay = ®istry.storage[&MIN_ROTATION_DELAY]; + assert_eq!( + (delay.original_value(), delay.present_value()), + (U256::ZERO, U256::from(7_200)) + ); + + db.commit(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)])); + assert_eq!(live_system_address(&mut db).unwrap(), Some(NEXT_SYSTEM_ADDRESS), "kept"); + assert_eq!( + db.storage(SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER).unwrap(), + U256::from(5) + ); + } + + /// Any other code at the registry's address refuses the block, naming the code hash, and + /// writes nothing; no bootstrap changes that. + #[test] + fn test_the_deployment_refuses_other_code() { + let foreign = Bytes::from_static(&[0x60, 0x00]); + let found = Bytecode::new_raw(foreign.clone()).hash_slow(); + for bootstrap in [Some(BOOTSTRAP), None] { + let mut db = registry_holding(foreign.clone(), Some(NEXT_SYSTEM_ADDRESS)); + match deployed(&mut db, bootstrap) { + Err(SequencerRegistryError::Refused(refusal)) => { + assert_eq!(refusal, SequencerRegistryRefusal::UnmigratableCode { found }); + assert!(refusal.to_string().contains(&found.to_string()), "{refusal}"); + } + other => panic!("{other:?}"), + } + } } - /// A registry holding foreign code names no address, whatever it stores. + /// A registry that must be seeded or migrated needs bootstrap values none of which is zero; + /// without them the deployment cannot be made, a fault of the configuration. #[test] - fn test_the_read_refuses_foreign_code() { - let db = registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS)); - let (address, journal) = load(db); - assert_eq!(address, None); - assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); + fn test_the_deployment_needs_a_usable_bootstrap_to_seed_or_migrate() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let unusable = [ + None, + Some(SequencerRegistryBootstrap { initial_sequencer: Address::ZERO, ..BOOTSTRAP }), + Some(SequencerRegistryBootstrap { initial_admin: Address::ZERO, ..BOOTSTRAP }), + Some(SequencerRegistryBootstrap { min_rotation_delay: 0, ..BOOTSTRAP }), + ]; + for bootstrap in unusable { + for mut db in [InMemoryDB::default(), registry_holding(V1_0_0_CODE, None)] { + assert!( + matches!( + deployed(&mut db, bootstrap), + Err(SequencerRegistryError::UnusableBootstrap) + ), + "{bootstrap:?}" + ); + } + } + assert!(BOOTSTRAP.is_usable()); } - /// A registry whose system address is zero names none: no caller, the zero address included, - /// is the system address of an empty registry. + /// The resolution answers the address `_currentSystemAddress` holds, with the registry's + /// account and that one slot as a read-only entry. #[test] - fn test_the_read_answers_no_address_for_a_zero_slot() { - let (address, journal) = load(registry_holding(SEQUENCER_REGISTRY_CODE, None)); - assert_eq!(address, None); - assert_warm_and_unchanged(&journal, U256::ZERO); + fn test_the_resolution_answers_the_stored_address_with_a_read_only_entry() { + let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let (address, state) = resolve_system_address(&mut db).expect("the registry names one"); + assert_eq!(address, NEXT_SYSTEM_ADDRESS); + let registry = &state[&SEQUENCER_REGISTRY_ADDRESS]; + assert_eq!(state.len(), 1); + assert!(!registry.is_touched() && !registry.is_created(), "a read-only entry"); + assert_eq!(registry.storage.keys().copied().collect::>(), [CURRENT_SYSTEM_ADDRESS]); + assert!(!registry.storage[&CURRENT_SYSTEM_ADDRESS].is_changed()); } - /// A state without the registry names no address, and the read records the account's - /// absence and the slot it would hold, zero. + /// The resolution refuses the block for a registry that has no account, holds other code — + /// version 1.0.0 included — or names no system address. #[test] - fn test_the_read_answers_no_address_without_a_registry() { - let (address, journal) = load(InMemoryDB::default()); - assert_eq!(address, None); - assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].is_loaded_as_not_existing()); - assert_warm_and_unchanged(&journal, U256::ZERO); + fn test_the_resolution_refuses_an_unusable_registry() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let foreign = Bytes::from_static(&[0x60, 0x00]); + let cases = [ + (InMemoryDB::default(), SequencerRegistryRefusal::Absent), + ( + registry_holding(foreign.clone(), Some(NEXT_SYSTEM_ADDRESS)), + SequencerRegistryRefusal::UnexpectedCode { + found: Bytecode::new_raw(foreign).hash_slow(), + }, + ), + ( + registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS)), + SequencerRegistryRefusal::UnexpectedCode { found: SEQUENCER_REGISTRY_V1_CODE_HASH }, + ), + ( + registry_holding(SEQUENCER_REGISTRY_CODE, None), + SequencerRegistryRefusal::NoSystemAddress, + ), + ]; + for (mut db, expected) in cases { + match resolve_system_address(&mut db) { + Err(SequencerRegistryError::Refused(refusal)) => assert_eq!(refusal, expected), + other => panic!("{expected:?}: {other:?}"), + } + } } - /// Read off a database, the live system address is what a transaction's validation reads: - /// the address the registry stores when it holds this engine's code, and none otherwise. + /// Read off a database, the live system address is what the block's resolution reads, and + /// none where the resolution refuses the block. #[test] - fn test_live_system_address_reads_what_validation_reads() { + fn test_live_system_address_reads_what_the_resolution_reads() { let read = |db: InMemoryDB| live_system_address(db).expect("the read succeeds"); assert_eq!( read(registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS))), @@ -561,17 +897,32 @@ mod tests { assert_eq!(live_system_address(wrapped).unwrap(), Some(NEXT_SYSTEM_ADDRESS)); } - /// A read the database cannot serve is the database's error, not an absent address. + /// A read the database cannot serve is the database's error, in the resolution, the + /// deployment and the direct read alike: never an absent registry or a refused block. #[test] - fn test_the_read_reports_a_database_error() { + fn test_a_failed_registry_read_is_the_databases_error() { use crate::test_utils::{ErrorInjectingDatabase, MemoryDatabase}; - let mut db = ErrorInjectingDatabase::new( - MemoryDatabase::default() - .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE), - ); - db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); - let mut journal: revm::Journal<_> = revm::Journal::new(db); - let err = load_system_address(&mut journal).expect_err("the read fails"); + let failing = || { + let mut db = ErrorInjectingDatabase::new( + MemoryDatabase::default() + .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE), + ); + db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + db + }; + let err = live_system_address(failing()).expect_err("the read fails"); assert!(err.to_string().contains("injected storage() error"), "{err}"); + match resolve_system_address(&mut failing()) { + Err(SequencerRegistryError::Database(err)) => { + assert!(err.to_string().contains("injected storage() error"), "{err}") + } + other => panic!("{other:?}"), + } + let mut db = failing(); + db.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + assert!(matches!( + deploy_sequencer_registry(&mut db, U256::ZERO, Some(BOOTSTRAP)), + Err(SequencerRegistryError::Database(_)) + )); } } diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index f0af57b4c..3de1bb6bb 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -16,12 +16,6 @@ //! there as long as `no_limits` leaves it unlimited, which the limit module's own test pins field //! by field. //! -//! Every Satin transaction reads the live system address when it is validated, under the neutral -//! configuration too, which leaves the `SequencerRegistry`'s account and one slot in its returned -//! state, read-only: an engine that makes no such read returns no such entry, and a comparison -//! with one takes it out first ([`take_system_address_read`]). A commit skips an account nothing -//! touched, so the entry parts no committed state. -//! //! Satin's base spec is Osaka, and a configuration cannot take a rule the base spec gates on its //! own id away or add one: an Osaka rule stays on under an older fork's fixtures, and an //! Amsterdam rule gated on the spec id stays off under Amsterdam's. So only Osaka and the fork @@ -35,13 +29,9 @@ use revm::{ interpreter::instructions::{gas_table_spec, GasTable}, precompile::{PrecompileSpecId, Precompiles}, primitives::eip7954, - state::{Account, EvmState}, }; -use crate::{ - system::{storage_slots::CURRENT_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, - EthSpecId, ExternalEnvTypes, MegaEvm, MegaSpecId, -}; +use crate::{EthSpecId, ExternalEnvTypes, MegaEvm, MegaSpecId}; /// The configuration `fork`'s fixtures run under on Satin's machinery, or `None` for a fork /// Satin's Osaka base cannot be configured to. @@ -120,28 +110,6 @@ pub fn neutralize_evm( Some(()) } -/// Takes out of a Satin transaction's returned `state` the entry its validation's read of the live -/// system address left, and answers it: the `SequencerRegistry`'s account and its -/// `_currentSystemAddress` slot, loaded and never written. What is left is what an engine that -/// makes no such read returns for the same transaction, op-revm's or Ethereum's. -/// -/// # Panics -/// -/// When `state` holds no entry for the registry, or one that is more than the read: the account -/// touched, another slot loaded, or the slot changed. Each is a difference of its own, which a -/// comparison must not take out with the read. -pub fn take_system_address_read(state: &mut EvmState) -> Account { - let registry = - state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("every transaction reads the registry"); - assert!(!registry.is_touched(), "the registry was written, not only read: {registry:?}"); - assert!( - registry.storage.keys().eq([&CURRENT_SYSTEM_ADDRESS]), - "the registry holds more than the system address's slot: {registry:?}" - ); - assert!(!registry.storage[&CURRENT_SYSTEM_ADDRESS].is_changed(), "the slot was written"); - registry -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs index 0c253e009..39bd503cb 100644 --- a/crates/mega-evm/tests/block/activation.rs +++ b/crates/mega-evm/tests/block/activation.rs @@ -12,7 +12,6 @@ use alloy_hardforks::{EthereumHardfork, ForkCondition}; use alloy_op_hardforks::OpHardfork; use alloy_primitives::{Bytes, B256, U256}; use mega_evm::{ - system::SYSTEM_CONTRACT_COUNT, test_utils::{CommittedStates, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, }; @@ -189,9 +188,9 @@ fn test_the_activation_rule_follows_the_optimism_fork_order() { } } -/// The predeploys a node's context has the block check, from its schedule and the parent's -/// timestamp: how many of the states the pre-block steps committed are reads of a predeploy. -fn predeploys_checked(spec: MegaHardforkConfig, parent_timestamp: u64, timestamp: u64) -> usize { +/// Whether a node's context has the block check the EIP-7997 factory, from its schedule and the +/// parent's timestamp: whether one of the states the pre-block steps committed is the check. +fn factory_checked(spec: MegaHardforkConfig, parent_timestamp: u64, timestamp: u64) -> bool { let mut env = common::evm_env(); env.block_env.timestamp = U256::from(timestamp); let ctx = node_ctx(parent_timestamp); @@ -199,23 +198,23 @@ fn predeploys_checked(spec: MegaHardforkConfig, parent_timestamp: u64, timestamp let committed = CommittedStates::install(&mut state); let mut executor = executor_with_env_and_spec(&mut state, ctx, env, spec); executor.apply_pre_execution_changes().expect("the block starts"); - committed.states().iter().filter(|state| common::is_predeploy_check(state)).count() + committed.states().iter().any(common::is_factory_check) } -/// [S18] A node's context has the predeploys checked in Satin's activation block and in no other: -/// the first block at the activation and the first after a gap over it read all seven; the block +/// [S18] A node's context has the EIP-7997 factory checked in Satin's activation block and in no +/// other: the first block at the activation and the first after a gap over it read it; the block /// after the activation block, every block of a chain with Satin from genesis, and Jovian's -/// activation block on such a chain, which admits only deposits, read none. +/// activation block on such a chain, which admits only deposits, do not. /// /// Expected values: independent (the schedule's own timestamps and the rule). #[test] -fn test_a_node_context_checks_the_predeploys_where_satin_activates() { +fn test_a_node_context_checks_the_factory_where_satin_activates() { let at = ACTIVATION; let cases = [ - ("Satin's activation block", schedule(at), at - 1, at, SYSTEM_CONTRACT_COUNT), - ("the first block after a gap", schedule(at), at - 10, at + 5, SYSTEM_CONTRACT_COUNT), - ("the block after Satin's activation block", schedule(at), at, at + 1, 0), - ("a block of a chain with Satin from genesis", schedule(0), at - 1, at, 0), + ("Satin's activation block", schedule(at), at - 1, at, true), + ("the first block after a gap", schedule(at), at - 10, at + 5, true), + ("the block after Satin's activation block", schedule(at), at, at + 1, false), + ("a block of a chain with Satin from genesis", schedule(0), at - 1, at, false), ( "Jovian's activation block", schedule(0) @@ -223,11 +222,11 @@ fn test_a_node_context_checks_the_predeploys_where_satin_activates() { .with(OpHardfork::Karst, ForkCondition::Timestamp(LATER)), at - 1, at, - 0, + false, ), ]; for (name, spec, parent, timestamp, expected) in cases { - assert_eq!(predeploys_checked(spec, parent, timestamp), expected, "{name}"); + assert_eq!(factory_checked(spec, parent, timestamp), expected, "{name}"); } } diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 88962bd0e..255c32724 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -1,9 +1,10 @@ //! Shared setup of the block-executor tests. //! //! A block on a chain whose schedule activates Satin at genesis, over an in-memory database holding -//! the seven predeploys as a chain that ran Rex6 holds them, and no L1 block contract — so the L1 -//! fees, the operator fee and the data-availability footprint scalar all read as zero unless a test -//! writes them. Satin activates at genesis, so no block of these tests is its activation block. +//! the seven predeploys as a chain that ran Rex6 holds them, which every block's deployment of the +//! system contracts then only reads, and no L1 block contract — so the L1 fees, the operator fee +//! and the data-availability footprint scalar all read as zero unless a test writes them. Satin +//! activates at genesis, so no block of these tests is its activation block. use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxLegacy}; use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; @@ -13,8 +14,8 @@ use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{ - system_contract_specs, IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, + IOracle, SequencerRegistryBootstrap, CREATE2_FACTORY_ADDRESS, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, }, test_utils::{BytecodeBuilder, MemoryDatabase, SequencerRegistryRoles}, BlockLimits, EmptyExternalEnv, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, @@ -108,21 +109,34 @@ pub(crate) fn registry_roles() -> SequencerRegistryRoles { } } -/// A schedule that activates Satin at genesis. +/// The minimum rotation delay the tests' configuration carries, distinct from the one the +/// registry of [`database`] holds, so a test can tell a migration's write from what was there. +pub(crate) const BOOTSTRAP_MIN_ROTATION_DELAY: u64 = 7_200; + +/// The `SequencerRegistry`'s bootstrap values the tests' schedules carry, as a configuration that +/// schedules Satin must: the roles of [`registry_roles`], and [`BOOTSTRAP_MIN_ROTATION_DELAY`]. +pub(crate) fn bootstrap() -> SequencerRegistryBootstrap { + SequencerRegistryBootstrap::new(SEQUENCER, ADMIN, BOOTSTRAP_MIN_ROTATION_DELAY) +} + +/// A schedule that activates Satin at genesis, carrying [`bootstrap`]. /// /// Its blocks are held to the spec's limits ([`ProtocolLimits::for_spec`]), which no block this /// size reaches but gas detention's caps; a test that holds a block or a transaction to another /// limit replaces them ([`executor_with_limits`]). pub(crate) fn chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated() + MegaHardforkConfig::default() + .with_all_activated() + .with_sequencer_registry_bootstrap(bootstrap()) } /// A schedule in which Satin activates at [`BLOCK_TIMESTAMP`], the timestamp of the block /// [`evm_env`] describes, so that block is Satin's activation block when its context names a -/// parent before it ([`activation_ctx`]). +/// parent before it ([`activation_ctx`]). It carries [`bootstrap`]. pub(crate) fn activation_spec() -> MegaHardforkConfig { MegaHardforkConfig::default() .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(BLOCK_TIMESTAMP)) + .with_sequencer_registry_bootstrap(bootstrap()) } /// The context of the block [`evm_env`] describes as Satin's activation block under @@ -305,15 +319,12 @@ pub(crate) fn eip_calls(states: &[EvmState]) -> Vec
{ .collect() } -/// Whether `state` is the activation block's check of a predeploy: one of the seven accounts -/// alone, read only, with no slot. The read of the registry's pending changes names the registry -/// alone too, with the slots it read. -pub(crate) fn is_predeploy_check(state: &EvmState) -> bool { +/// Whether `state` is the activation block's check of the EIP-7997 factory: the factory's account +/// alone, read only, with no slot. No other pre-block step names the factory. +pub(crate) fn is_factory_check(state: &EvmState) -> bool { state.len() == 1 && - system_contract_specs().iter().any(|spec| { - state.get(&spec.address).is_some_and(|account| { - !account.is_touched() && !account.is_created() && account.storage.is_empty() - }) + state.get(&CREATE2_FACTORY_ADDRESS).is_some_and(|account| { + !account.is_touched() && !account.is_created() && account.storage.is_empty() }) } diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 45a13db47..70426edf4 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -1,229 +1,586 @@ -//! The check Satin's activation block makes of the predeploys, and the EIP-7997 factory round -//! trip. +//! The system contracts every block deploys, the check of the EIP-7997 factory Satin's activation +//! block makes, the resolution of the live system address that ends every block's pre-block +//! steps, and the factory round trip. //! -//! The block in which Satin activates reads the six system contracts and the factory, which a chain -//! that ran Rex6 holds, and is invalid when one of them does not hold the code Satin expects; no -//! other block reads them, and no block deploys or upgrades them. +//! Every block, after the EIP calls and, in the activation block alone, the factory check, deploys +//! the Oracle, the high-precision timestamp, `KeylessDeploy`, `MegaAccessControl` and +//! `MegaLimitControl`: a missing one is installed, one holding other code has its code replaced and +//! keeps its storage, one holding its code is read. Then come the registry's due-change read and +//! call, the registry's own deployment — seeded where the state holds none, migrated from 1.0.0, +//! refused over other code — and the resolution of the live system address, last. Each step +//! commits a state of its own, before the next runs; nothing is charged. use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use mega_evm::{ system::{ - storage_slots::{PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS}, - system_contract_specs, CREATE2_FACTORY_ADDRESS, ORACLE_CONTRACT_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, + flat_system_contract_specs, + keyless::KEYLESS_DEPLOY_ADDRESS, + storage_slots::{ + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, + INITIAL_SEQUENCER, INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, PENDING_SEQUENCER, + PENDING_SYSTEM_ADDRESS, + }, + SequencerRegistryRefusal, ACCESS_CONTROL_ADDRESS, CREATE2_FACTORY_ADDRESS, + CREATE2_FACTORY_CODE_HASH, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, LIMIT_CONTROL_ADDRESS, + LIMIT_CONTROL_CODE_HASH, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, }, test_utils::{rex6_predeploys, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, - MegaBlockExecutionCtx, MegaBlockExecutionError, + MegaBlockExecutionCtx, MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, }; use revm::{ context::result::ExecutionResult, database::State, primitives::KECCAK_EMPTY, state::EvmState, + Database, }; use crate::common::{ - self, activation_ctx, activation_spec, after_activation_ctx, executor_with_spec, - named_accounts, recovered, tx, unlimited_ctx, + self, activation_ctx, activation_spec, after_activation_ctx, executor_with_env_and_spec, + executor_with_spec, named_accounts, recovered, tx, unlimited_ctx, word, + BOOTSTRAP_MIN_ROTATION_DELAY, }; -/// The states the pre-block steps of a block over `state` held to `ctx` committed, in order, as a -/// commit hook on `state` receives them. -fn start( +/// The states the pre-block steps of a block over `state` held to `ctx` on the chain `spec` +/// describes committed, in order, as a commit hook on `state` receives them, and the steps' +/// answer. +fn start_on( state: &mut State, ctx: MegaBlockExecutionCtx, -) -> Result, BlockExecutionError> { + spec: MegaHardforkConfig, +) -> (Vec, Result<(), BlockExecutionError>) { let committed = CommittedStates::install(state); - let mut executor = executor_with_spec(state, ctx, activation_spec()); - executor.apply_pre_execution_changes()?; - assert_eq!(executor.gas().execution, 0); + let mut executor = executor_with_spec(state, ctx, spec); + let started = executor.apply_pre_execution_changes(); + assert_eq!(executor.gas().execution, 0, "no pre-block step is counted"); assert_eq!(executor.gas().state, 0); assert_eq!(executor.gas().history, 0); - Ok(committed.states()) + (committed.states(), started) } -/// The account each pre-block state of a block names, in commit order: the two EIP calls' targets, -/// in the activation block the seven predeploys in order, and the registry, whose pending changes -/// are read and found none due on these blocks. Nothing reads the L1 block contract before the +/// The states the pre-block steps of a block over `state` held to `ctx` committed, the block on +/// [`activation_spec`]. +fn start(state: &mut State, ctx: MegaBlockExecutionCtx) -> Vec { + let (states, started) = start_on(state, ctx, activation_spec()); + started.expect("the block starts"); + states +} + +/// The account each pre-block state of a block names, in commit order: the two EIP calls' +/// targets, in the activation block the factory, the five system contracts, then the registry +/// three times — the read of its pending changes, found none due on these blocks, its deployment +/// and the resolution of the live system address. Nothing reads the L1 block contract before the /// block's transactions. fn expected_accounts(activation: bool) -> Vec
{ let mut expected = vec![HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]; if activation { - expected.extend(system_contract_specs().map(|spec| spec.address)); + expected.push(CREATE2_FACTORY_ADDRESS); } - expected.push(SEQUENCER_REGISTRY_ADDRESS); + expected.extend(flat_system_contract_specs().map(|spec| spec.address)); + expected.extend([SEQUENCER_REGISTRY_ADDRESS; 3]); expected } -/// [S18] Satin's activation block over a state shaped as Rex6 leaves it finds every predeploy with -/// Satin's code. Each pre-block step commits a state of its own, and a commit hook receives them in -/// order, read-only entries included: the two EIP calls, which touch their contracts; the seven -/// accounts, each a read-only entry as the chain holds it — no write, no created mark, the six at -/// nonce 0 and the factory at its own; and the registry's two pending slots, read only. The block -/// after it, on the committed state, reads none of the predeploys, and neither block changes one. +/// The index of the state the deployment of the system contract at `address` committed in a block +/// that is not the activation block, in [`expected_accounts`] order. +fn deployment_step(address: Address) -> usize { + let position = flat_system_contract_specs().iter().position(|spec| spec.address == address); + 2 + position.expect("one of the five system contracts") +} + +/// The state the registry's deployment committed in a block that is not the activation block. +const REGISTRY_DEPLOYMENT: usize = 8; + +/// The state the resolution of the live system address committed: the last. +const RESOLUTION: usize = 9; + +/// Asserts `state` is the resolution of the live system address: the registry alone, read-only, +/// holding version 2.0.0, with its one slot naming `system_address`. +fn assert_resolves(state: &EvmState, system_address: Address) { + assert_eq!(state.len(), 1); + let registry = &state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched() && !registry.is_created(), "the resolution is read only"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(registry.storage.keys().copied().collect::>(), [CURRENT_SYSTEM_ADDRESS]); + assert_eq!(registry.storage[&CURRENT_SYSTEM_ADDRESS].present_value(), word(system_address)); +} + +/// The verdict a refused block's error carries. +fn verdict(error: &BlockExecutionError) -> MegaBlockExecutionError { + let Some(BlockValidationError::Other(inner)) = error.as_validation() else { + panic!("a verdict on the block: {error:?}"); + }; + inner.downcast_ref::().expect("the engine's refusal").clone() +} + +/// The internal error a block's start failed with. +fn internal(error: &BlockExecutionError) -> MegaBlockExecutionError { + error + .as_internal() + .and_then(|error| error.downcast_other::()) + .unwrap_or_else(|| panic!("an internal error of the engine: {error:?}")) + .clone() +} + +/// [S18] Over a state shaped as Rex6 leaves it, Satin's activation block and the block after it +/// deploy every system contract and find each holding Satin's code. Each pre-block step commits a +/// state of its own, and a commit hook receives them in order, read-only entries included: the two +/// EIP calls, which touch their contracts; in the activation block alone the factory, read only; +/// the five contracts, each a read-only entry as the chain holds it — no write, no created mark, +/// nonce 0; the registry's two pending slots, read only; the registry's deployment, a read-only +/// entry without a slot; and the resolution, the registry's system-address slot. No step changes a +/// contract. /// /// Expected values: independent (the Rex6-shaped accounts the test puts in the state). #[test] -fn test_the_activation_block_reads_the_seven_predeploys_once() { +fn test_every_block_deploys_the_system_contracts_a_rex6_chain_holds_as_read_only_entries() { let mut state = common::state(); - let activation = start(&mut state, activation_ctx()).expect("the activation block starts"); - assert_eq!(named_accounts(&activation), expected_accounts(true)); - for (call, target) in activation.iter().zip([HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]) { - assert!(call[&target].is_touched(), "the call to {target} touches it"); - } let held = rex6_predeploys(common::registry_roles()); - for (i, (address, info, _)) in held.iter().enumerate() { - let account = &activation[2 + i][address]; - assert!(!account.is_touched() && !account.is_created(), "{address} is read only"); + for (activation, ctx) in [(true, activation_ctx()), (false, after_activation_ctx())] { + let states = start(&mut state, ctx); + assert_eq!(named_accounts(&states), expected_accounts(activation), "{activation}"); + for (call, target) in states.iter().zip([HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]) { + assert!(call[&target].is_touched(), "the call to {target} touches it"); + } + let offset = usize::from(activation); + if activation { + let factory = &states[2][&CREATE2_FACTORY_ADDRESS]; + assert!(!factory.is_touched() && !factory.is_created(), "the check is read only"); + assert_eq!(factory.info.code_hash, CREATE2_FACTORY_CODE_HASH); + } + for (address, info, _) in &held[..5] { + let account = &states[deployment_step(*address) + offset][address]; + assert!(!account.is_touched() && !account.is_created(), "{address} is read only"); + assert!(account.storage.is_empty(), "{address}: no slot is written"); + assert_eq!((account.info.code_hash, account.info.nonce), (info.code_hash, info.nonce)); + } + let pending = &states[7 + offset][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!pending.is_touched(), "the due-change read is read only"); + assert_eq!( + pending.storage.keys().copied().collect::>(), + [PENDING_SYSTEM_ADDRESS, PENDING_SEQUENCER].into(), + ); + let registry = &states[REGISTRY_DEPLOYMENT + offset][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched() && !registry.is_created(), "version 2.0.0 is read"); + assert!(registry.storage.is_empty(), "the deployment reads no slot of it"); + assert_resolves(&states[RESOLUTION + offset], MEGA_SYSTEM_ADDRESS); + } + for (address, info, _) in held { + let now = state.basic(address).unwrap().expect("still there"); + assert_eq!((now.code_hash, now.nonce), (info.code_hash, info.nonce), "{address}"); + } +} + +/// [S18] A system contract the state does not hold is installed, in every block that finds it +/// missing: `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl`, which a chain that never +/// ran their forks lacks, each get an account holding their code, at nonce 0, marked created; the +/// next block reads them as the chain then holds them. +/// +/// Expected values: independent (the code each contract ships). +#[test] +fn test_a_missing_system_contract_is_installed() { + let missing = [KEYLESS_DEPLOY_ADDRESS, ACCESS_CONTROL_ADDRESS, LIMIT_CONTROL_ADDRESS]; + let mut db = common::database(); + for address in missing { + db.cache.accounts.remove(&address); + } + let mut state = State::builder().with_database(db).build(); + let states = start(&mut state, after_activation_ctx()); + assert_eq!(named_accounts(&states), expected_accounts(false)); + for spec in + flat_system_contract_specs().into_iter().filter(|spec| missing.contains(&spec.address)) + { + let account = &states[deployment_step(spec.address)][&spec.address]; + assert!(account.is_touched() && account.is_created(), "{} is installed", spec.address); + assert_eq!(account.info.code_hash, spec.code_hash); + assert_eq!((account.info.nonce, account.info.balance), (0, U256::ZERO)); + let now = state.basic(spec.address).unwrap().expect("installed"); + assert_eq!(now.code_hash, spec.code_hash, "{} holds its code", spec.address); + } + + let next = start(&mut state, after_activation_ctx()); + for address in missing { + let account = &next[deployment_step(address)][&address]; + assert!(!account.is_touched() && !account.is_created(), "{address} is now only read"); + } +} + +/// [S18] A system contract holding other code has its code replaced by Satin's and keeps its +/// nonce, its balance and its storage: the Oracle at 1.0.0, which an earlier fork left with a slot +/// written, becomes 2.0.0 with that slot, and `MegaLimitControl` holding foreign code gets its +/// own. The account is touched and not created, which would clear the storage. +/// +/// Expected values: independent (the code hashes and the storage the test puts in the state). +#[test] +fn test_a_system_contract_holding_other_code_is_rewritten_keeping_its_storage() { + use mega_system_contracts::oracle; + let mut db = common::database(); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_0_0_CODE); + db.set_account_storage(ORACLE_CONTRACT_ADDRESS, U256::from(7), U256::from(9)); + db.set_account_balance(ORACLE_CONTRACT_ADDRESS, U256::from(5)); + db.set_account_code(LIMIT_CONTROL_ADDRESS, Bytes::from_static(&[0xfe])); + let mut state = State::builder().with_database(db).build(); + let states = start(&mut state, after_activation_ctx()); + for (address, expected) in [ + (ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH), + (LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE_HASH), + ] { + let account = &states[deployment_step(address)][&address]; + assert!(account.is_touched() && !account.is_created(), "{address}: rewritten, not created"); + assert_eq!(account.info.code_hash, expected, "{address}"); assert!(account.storage.is_empty(), "{address}: no slot is written"); - assert_eq!((account.info.code_hash, account.info.nonce), (info.code_hash, info.nonce)); } - let registry = &activation[2 + held.len()][&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.is_touched() && !registry.is_created(), "the registry is read only"); + let oracle = state.basic(ORACLE_CONTRACT_ADDRESS).unwrap().expect("the Oracle"); + assert_eq!(oracle.code_hash, ORACLE_CONTRACT_CODE_HASH, "the Oracle runs 2.0.0"); + assert_eq!(oracle.balance, U256::from(5), "its balance is kept"); assert_eq!( - registry.storage.keys().copied().collect::>(), - [PENDING_SYSTEM_ADDRESS, PENDING_SEQUENCER].into(), - "the read of its pending changes" + state.storage(ORACLE_CONTRACT_ADDRESS, U256::from(7)).unwrap(), + U256::from(9), + "its storage is kept" ); - assert!(registry.storage.values().all(|slot| !slot.is_changed())); +} - let next = start(&mut state, after_activation_ctx()).expect("the next block starts"); - assert_eq!(named_accounts(&next), expected_accounts(false), "no other block reads them"); - for (address, info, _) in held { - let now = revm::Database::basic(&mut state, address).unwrap().expect("still there"); - assert_eq!((now.code_hash, now.nonce), (info.code_hash, info.nonce), "{address}"); +/// [S18] Where the state holds no registry, or an account without code at its address, the block +/// deploys version 2.0.0 new, seeded from the configuration's bootstrap values: the system address +/// both current and initial, the configured sequencer both current and initial, the configured +/// admin, the block's number as its first block and the configured minimum rotation delay. An +/// existing account keeps its nonce and its balance. The resolution then names the system address +/// the seed wrote, and the next block finds the registry as the block left it. +/// +/// Expected values: independent (the bootstrap values and the block number the test uses). +#[test] +fn test_a_registry_the_state_does_not_hold_is_seeded_from_the_bootstrap_values() { + let without = |edit: &dyn Fn(&mut MemoryDatabase)| { + let mut db = common::database(); + db.cache.accounts.remove(&SEQUENCER_REGISTRY_ADDRESS); + edit(&mut db); + db + }; + let cases = [ + ("no account", without(&|_| {}), U256::ZERO), + ( + "a funded account without code", + without(&|db| db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(3))), + U256::from(3), + ), + ]; + for (case, db, balance) in cases { + let mut state = State::builder().with_database(db).build(); + let states = start(&mut state, after_activation_ctx()); + assert_eq!(named_accounts(&states), expected_accounts(false), "{case}"); + let registry = &states[REGISTRY_DEPLOYMENT][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(registry.is_touched() && registry.is_created(), "{case}: deployed new"); + assert_eq!(registry.info.balance, balance, "{case}: the balance is kept"); + let seeded: std::collections::BTreeMap<_, _> = + registry.storage.iter().map(|(slot, value)| (*slot, value.present_value())).collect(); + let expected = std::collections::BTreeMap::from([ + (CURRENT_SYSTEM_ADDRESS, word(MEGA_SYSTEM_ADDRESS)), + (CURRENT_SEQUENCER, word(common::SEQUENCER)), + (ADMIN, word(common::ADMIN)), + (INITIAL_SYSTEM_ADDRESS, word(MEGA_SYSTEM_ADDRESS)), + (INITIAL_SEQUENCER, word(common::SEQUENCER)), + (INITIAL_FROM_BLOCK, U256::from(common::BLOCK_NUMBER)), + (MIN_ROTATION_DELAY, U256::from(BOOTSTRAP_MIN_ROTATION_DELAY)), + ]); + assert_eq!(seeded, expected, "{case}"); + assert_resolves(&states[RESOLUTION], MEGA_SYSTEM_ADDRESS); + + let next = start(&mut state, after_activation_ctx()); + let registry = &next[REGISTRY_DEPLOYMENT][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched(), "{case}: the next block reads what the block deployed"); } } -/// [S18] A block that is not Satin's activation block reads no predeploy: over a database that -/// fails every load of the Oracle's account, it starts, where the activation block fails on the -/// load as an internal error, the database's and no verdict on the block. +/// [S18] A registry at version 1.0.0 is migrated in place: its code becomes 2.0.0 and its slot 13 +/// the configured minimum rotation delay, the one slot written; its roles and every other slot are +/// what they were, so the resolution names the system address it already held. /// -/// Expected values: independent (the injected failure). +/// Expected values: independent (the roles and the delay the test puts in the state and the +/// configuration). #[test] -fn test_no_other_block_reads_a_predeploy() { - let failing = || { - let mut db = ErrorInjectingDatabase::new(common::database()); - db.fail_on_account = Some(ORACLE_CONTRACT_ADDRESS); - State::builder().with_database(db).build() - }; - let start_on = |ctx: MegaBlockExecutionCtx| { - let mut state = failing(); - let evm = alloy_evm::EvmFactory::create_evm( - &mega_evm::MegaEvmFactory::new(), - &mut state, - common::evm_env(), - ); - mega_evm::MegaBlockExecutor::new( - evm, - ctx, - common::activation_spec(), - alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), - ) - .apply_pre_execution_changes() +fn test_a_registry_at_1_0_0_is_migrated_writing_slot_13_alone() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let chain_address = alloy_primitives::address!("0x5000000000000000000000000000000000000005"); + let mut db = common::database(); + db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, V1_0_0_CODE); + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY, U256::ZERO); + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS, word(chain_address)); + let mut state = State::builder().with_database(db).build(); + let states = start(&mut state, after_activation_ctx()); + let registry = &states[REGISTRY_DEPLOYMENT][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(registry.is_touched() && !registry.is_created(), "migrated, not created"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(registry.storage.keys().copied().collect::>(), [MIN_ROTATION_DELAY]); + let delay = ®istry.storage[&MIN_ROTATION_DELAY]; + assert_eq!( + (delay.original_value(), delay.present_value()), + (U256::ZERO, U256::from(BOOTSTRAP_MIN_ROTATION_DELAY)) + ); + assert_resolves(&states[RESOLUTION], chain_address); + let slot = |state: &mut State, slot| { + state.storage(SEQUENCER_REGISTRY_ADDRESS, slot).unwrap() }; - start_on(after_activation_ctx()).expect("an ordinary block reads no predeploy"); - let error = start_on(activation_ctx()).expect_err("the activation block reads the Oracle"); - assert!(matches!(error, BlockExecutionError::Internal(_)), "{error:?}"); - assert!(error.to_string().contains("injected basic() error"), "{error}"); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), word(common::SEQUENCER), "the roles stay"); + assert_eq!(slot(&mut state, ADMIN), word(common::ADMIN)); + assert_eq!(slot(&mut state, MIN_ROTATION_DELAY), U256::from(BOOTSTRAP_MIN_ROTATION_DELAY)); } -/// The refusal of Satin's activation block over `db`: a verdict on the block, before the refused -/// predeploy's state is committed, so the last state committed is the predeploy before it. -fn refused(db: MemoryDatabase, at: Address) -> MegaBlockExecutionError { +/// [S18] A registry holding any other code than version 2.0.0, version 1.0.0 or none makes the +/// block invalid, with an error naming the code hash: its storage is never overwritten. The +/// refusal comes at the registry's deployment, after its due-change read was committed. +/// +/// Expected values: independent (the code hash the state holds). +#[test] +fn test_a_registry_holding_other_code_refuses_the_block() { + let mut db = common::database(); + db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, Bytes::from_static(&[0xfe])); let mut state = State::builder().with_database(db).build(); - let committed = CommittedStates::install(&mut state); - let mut executor = executor_with_spec(&mut state, activation_ctx(), activation_spec()); - let error = executor.apply_pre_execution_changes().expect_err("the block is refused"); - let delivered = named_accounts(&committed.states()); - let position = system_contract_specs().iter().position(|spec| spec.address == at).unwrap(); - assert_eq!(delivered, expected_accounts(true)[..2 + position], "refused at {at}"); - let Some(BlockValidationError::Other(inner)) = error.as_validation() else { - panic!("a verdict on the block: {error:?}"); + let (states, started) = start_on(&mut state, after_activation_ctx(), activation_spec()); + let error = started.expect_err("the block is refused"); + let found = keccak256([0xfe]); + assert_eq!( + verdict(&error), + MegaBlockExecutionError::SequencerRegistry(SequencerRegistryRefusal::UnmigratableCode { + found + }) + ); + assert!(error.to_string().contains(&found.to_string()), "{error}"); + assert_eq!(named_accounts(&states), expected_accounts(false)[..REGISTRY_DEPLOYMENT]); + assert_eq!( + state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, + found, + "nothing was written" + ); +} + +/// [S17] A registry that names no system address — version 2.0.0 whose `_currentSystemAddress` is +/// zero — makes the block invalid at the resolution, the last pre-block step, after the +/// registry's deployment read it. +/// +/// Expected values: independent (the slot the test clears). +#[test] +fn test_a_registry_naming_no_system_address_refuses_the_block() { + let mut db = common::database(); + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS, U256::ZERO); + let mut state = State::builder().with_database(db).build(); + let (states, started) = start_on(&mut state, after_activation_ctx(), activation_spec()); + let error = started.expect_err("the block is refused"); + assert_eq!( + verdict(&error), + MegaBlockExecutionError::SequencerRegistry(SequencerRegistryRefusal::NoSystemAddress) + ); + assert_eq!(named_accounts(&states), expected_accounts(false)[..RESOLUTION]); +} + +/// [S18] A block that must seed the registry, or migrate it from 1.0.0, on a configuration that +/// carries no bootstrap values cannot be executed: an internal error of the node, not a verdict on +/// the block. A block whose registry holds version 2.0.0 needs none, and starts. +/// +/// Expected values: independent (the registry each state holds). +#[test] +fn test_a_registry_to_seed_or_migrate_without_bootstrap_values_is_an_internal_error() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let without_bootstrap = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(0)); + let absent = { + let mut db = common::database(); + db.cache.accounts.remove(&SEQUENCER_REGISTRY_ADDRESS); + db }; - inner.downcast_ref::().expect("the engine's refusal").clone() + let migrating = common::database().account_code(SEQUENCER_REGISTRY_ADDRESS, V1_0_0_CODE); + for (case, db) in [("no registry", absent), ("version 1.0.0", migrating)] { + let mut state = State::builder().with_database(db).build(); + let (_, started) = start_on(&mut state, unlimited_ctx(), without_bootstrap.clone()); + let error = started.expect_err("the registry cannot be deployed"); + assert_eq!(internal(&error), MegaBlockExecutionError::UnusableRegistryBootstrap, "{case}"); + } + let (_, started) = start_on(&mut common::state(), unlimited_ctx(), without_bootstrap); + started.expect("version 2.0.0 needs no bootstrap values"); } -/// [S18] The activation block is invalid when a predeploy does not hold Satin's code, with one -/// error naming the address, the expected hash and the one held: other code at any of the seven, -/// no account, an account without code — funded, or at a used nonce — the Oracle at 1.0.0 or -/// 1.1.0, and the registry at 1.0.0. Nothing is created or upgraded. +/// [S18] The activation block is invalid when the EIP-7997 factory's address does not hold the +/// factory's code, with one error naming the address, the expected hash and the one held: no +/// account, an account without code at a used nonce, and other code. The refusal comes after the +/// two EIP calls and before anything is deployed. The block after the activation block does not +/// read the factory, and starts over the same state. /// /// Expected values: independent (the code hash each state holds). #[test] -fn test_an_activation_block_without_the_expected_code_is_refused() { - use mega_system_contracts::{oracle, sequencer_registry}; +fn test_an_activation_block_without_the_factory_is_refused() { let with = |edit: &dyn Fn(&mut MemoryDatabase)| { let mut db = common::database(); edit(&mut db); db }; - let mut cases: Vec<(String, Address, MemoryDatabase, B256)> = system_contract_specs() - .into_iter() - .map(|spec| { - let db = with(&|db| db.set_account_code(spec.address, Bytes::from_static(&[0xfe]))); - (format!("other code at {}", spec.address), spec.address, db, keccak256([0xfe])) - }) - .collect(); - cases.extend([ - ( - "no account at the Oracle's address".to_string(), - ORACLE_CONTRACT_ADDRESS, - with(&|db| { - db.cache.accounts.remove(&ORACLE_CONTRACT_ADDRESS); - }), - KECCAK_EMPTY, - ), + let cases = [ ( - "a funded registry without code".to_string(), - SEQUENCER_REGISTRY_ADDRESS, + "no account", with(&|db| { - db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, Bytes::new()); - db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1)); + db.cache.accounts.remove(&CREATE2_FACTORY_ADDRESS); }), KECCAK_EMPTY, ), ( - "a factory without code at a used nonce".to_string(), - CREATE2_FACTORY_ADDRESS, + "an account without code at a used nonce", with(&|db| db.set_account_code(CREATE2_FACTORY_ADDRESS, Bytes::new())), KECCAK_EMPTY, ), ( - "the Oracle at 1.0.0".to_string(), - ORACLE_CONTRACT_ADDRESS, - with(&|db| db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_0_0_CODE)), - oracle::V1_0_0_CODE_HASH, + "other code", + with(&|db| db.set_account_code(CREATE2_FACTORY_ADDRESS, Bytes::from_static(&[0xfe]))), + keccak256([0xfe]), ), - ( - "the Oracle at 1.1.0".to_string(), - ORACLE_CONTRACT_ADDRESS, - with(&|db| db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_1_0_CODE)), - oracle::V1_1_0_CODE_HASH, - ), - ( - "the registry at 1.0.0".to_string(), - SEQUENCER_REGISTRY_ADDRESS, - with(&|db| { - db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, sequencer_registry::V1_0_0_CODE) - }), - sequencer_registry::V1_0_0_CODE_HASH, - ), - ]); - for (name, address, db, found) in cases { - let expected = system_contract_specs() - .into_iter() - .find(|spec| spec.address == address) - .expect("a predeploy") - .code_hash; - let refusal = refused(db, address); + ]; + for (name, db, found) in cases { + let mut state = State::builder().with_database(db.clone()).build(); + let (states, started) = start_on(&mut state, activation_ctx(), activation_spec()); + let error = started.expect_err("the activation block is refused"); + let refusal = verdict(&error); assert_eq!( refusal, - MegaBlockExecutionError::UnexpectedSystemContractCode { address, expected, found }, + MegaBlockExecutionError::UnexpectedSystemContractCode { + address: CREATE2_FACTORY_ADDRESS, + expected: CREATE2_FACTORY_CODE_HASH, + found, + }, "{name}" ); let message = refusal.to_string(); - assert!(message.contains(&address.to_string()), "{name}: {message}"); + assert!(message.contains(&CREATE2_FACTORY_ADDRESS.to_string()), "{name}: {message}"); assert!(message.contains("when Satin activates"), "{name}: {message}"); + assert_eq!(named_accounts(&states), [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]); + + let mut state = State::builder().with_database(db).build(); + start(&mut state, after_activation_ctx()); + } +} + +/// [S18] No block but Satin's activation block reads the factory: over a database that fails +/// every load of the factory's account, an ordinary block starts, where the activation block fails +/// on the load as an internal error, the database's and no verdict on the block. +/// +/// Expected values: independent (the injected failure). +#[test] +fn test_no_other_block_reads_the_factory() { + let start_on = |ctx: MegaBlockExecutionCtx| { + let mut db = ErrorInjectingDatabase::new(common::database()); + db.fail_on_account = Some(CREATE2_FACTORY_ADDRESS); + let mut state = State::builder().with_database(db).build(); + let evm = alloy_evm::EvmFactory::create_evm( + &mega_evm::MegaEvmFactory::new(), + &mut state, + common::evm_env(), + ); + mega_evm::MegaBlockExecutor::new( + evm, + ctx, + activation_spec(), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ) + .apply_pre_execution_changes() + }; + start_on(after_activation_ctx()).expect("an ordinary block reads no factory"); + let error = start_on(activation_ctx()).expect_err("the activation block reads the factory"); + assert!(matches!(error, BlockExecutionError::Internal(_)), "{error:?}"); + assert!(error.to_string().contains("injected basic() error"), "{error}"); +} + +/// [S18] Satin may be active from genesis, its `satinTime` at or before the genesis block's +/// timestamp. The genesis block, which has no parent, is no activation block, whatever that time: +/// it makes no EIP-2935 or EIP-4788 call and checks no factory, and on a state that holds none of +/// the system contracts it installs the five and seeds the registry, at block number zero, from +/// the bootstrap values. A non-zero parent beacon block root refuses it, as EIP-4788 defines. The +/// block after it makes both calls and reads what the genesis block deployed. +/// +/// Expected values: independent (the schedule and the empty state the test uses). +#[test] +fn test_satin_active_from_genesis_deploys_every_system_contract_in_the_genesis_block() { + let genesis_time = common::BLOCK_TIMESTAMP; + let spec = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(genesis_time - 100)) + .with_sequencer_registry_bootstrap(common::bootstrap()); + let env_at = |number: u64, timestamp: u64| { + let mut env = common::evm_env(); + env.block_env.number = U256::from(number); + env.block_env.timestamp = U256::from(timestamp); + env + }; + let ctx = |root: B256, parent_timestamp| { + MegaBlockExecutionCtx::new( + B256::ZERO, + Some(root), + Bytes::new(), + mega_evm::BlockLimits::no_limits(), + parent_timestamp, + ) + }; + + let mut state = State::builder().with_database(MemoryDatabase::default()).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env_and_spec( + &mut state, + ctx(B256::ZERO, None), + env_at(0, genesis_time), + spec.clone(), + ); + assert_eq!(executor.is_satin_activation_block(), Ok(false)); + assert_eq!(executor.admits_only_deposits(), Ok(false)); + executor.apply_pre_execution_changes().expect("the genesis block starts"); + drop(executor); + let states = committed.states(); + let mut expected: Vec
= flat_system_contract_specs().map(|spec| spec.address).into(); + expected.extend([SEQUENCER_REGISTRY_ADDRESS; 3]); + assert_eq!(named_accounts(&states), expected, "no EIP call, no factory check"); + for (i, spec) in flat_system_contract_specs().into_iter().enumerate() { + let account = &states[i][&spec.address]; + assert!(account.is_created(), "{} is installed", spec.address); + assert_eq!(account.info.code_hash, spec.code_hash); + } + let registry = &states[6][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(registry.is_created(), "the registry is seeded"); + assert_eq!(registry.storage[&INITIAL_FROM_BLOCK].present_value(), U256::ZERO); + assert_resolves(&states[7], MEGA_SYSTEM_ADDRESS); + for address in [HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, SEQUENCER_REGISTRY_ADDRESS] { + assert!(state.basic(address).unwrap().is_some(), "{address} is in the state"); + } + + let mut fresh = State::builder().with_database(MemoryDatabase::default()).build(); + let error = executor_with_env_and_spec( + &mut fresh, + ctx(B256::repeat_byte(1), None), + env_at(0, genesis_time), + spec.clone(), + ) + .apply_pre_execution_changes() + .expect_err("a genesis block's parent beacon block root is zero"); + assert!( + matches!( + error, + BlockExecutionError::Validation( + BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { .. } + ) + ), + "{error:?}" + ); + + let committed = CommittedStates::install(&mut state); + let mut next = executor_with_env_and_spec( + &mut state, + ctx(B256::ZERO, Some(genesis_time)), + env_at(1, genesis_time + 1), + spec, + ); + assert_eq!(next.is_satin_activation_block(), Ok(false), "Satin was active at the parent"); + next.apply_pre_execution_changes().expect("the block after genesis starts"); + drop(next); + let states = committed.states(); + assert_eq!(named_accounts(&states)[..2], [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]); + for state in &states[2..] { + let (_, account) = state.iter().next().expect("one account"); + assert!( + !account.is_created() && !account.is_touched(), + "read as the genesis block left it" + ); } } diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index e39fbaf8e..259f6f71c 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -167,7 +167,10 @@ fn test_engine_built_schedules_keep_their_base_forks_at_genesis() { .with(MegaHardfork::Satin, ForkCondition::Timestamp(satin_time)); assert_eq!(schedule.validate_schedule(), Ok(()), "Satin at {satin_time}"); - let activation = ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(satin_time) }; + let activation = ChainActivation { + satin: Some(satin_time), + ..mega_evm::chain_activation(MAINNET_CHAIN_ID).expect("a known chain") + }; let schedule = activation.hardforks(); assert_eq!(schedule.validate_schedule(), Ok(()), "the table's Satin at {satin_time}"); } diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index 965713683..2c30eedb6 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -1,13 +1,13 @@ //! The `SequencerRegistry`'s role changes, applied before a block's transactions, and the live -//! system address read out of it. +//! system address resolved out of it once per block. //! -//! The registry the legacy forks left is checked once, by Satin's activation block, which refuses -//! a chain without it. Before every block's transactions the executor reads whether a role change -//! is due in the block and, when one is, makes the `applyPendingChanges()` system call. Each step -//! commits a state of its own, which a commit hook on the block's state receives, the read as a -//! read-only entry. The executor's pre-block steps do not read the system address: every -//! transaction reads it out of the registry when it is validated, so every EVM — the block's, or -//! one a node builds outside block execution — promotes the address the state names. +//! Before every block's transactions the executor reads whether a role change is due in the block +//! and, when one is, makes the `applyPendingChanges()` system call, then deploys the registry, then +//! resolves the block's live system address from it. Each step commits a state of its own, which a +//! commit hook on the block's state receives, the reads as read-only entries, the resolution last. +//! No transaction reads the registry for its classification: the block's EVM classifies against +//! the address the block resolved, and one a node builds outside block execution against the one +//! it read off the state when it was built. use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxEip1559}; use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory, ToTxEnv}; @@ -121,9 +121,8 @@ fn executor_on( } /// Starts a block at [`BLOCK_NUMBER`] over `state` and answers the registry's own steps, the -/// committed states that name it, in order: the read of its pending changes and the call that -/// applies them. The blocks here are not Satin's activation block, so no step checks the -/// registry's code. +/// committed states that name it, in order: the read of its pending changes, the call that applies +/// them when one is due, its deployment and the resolution of the live system address. fn start_block(state: &mut State, envs: Envs, gas_limit: u64) -> Vec { let committed = CommittedStates::install(state); let mut executor = executor(state, envs, gas_limit); @@ -151,9 +150,11 @@ fn test_a_due_change_is_applied_under_a_crowded_bucket() { State::builder().with_database(registry_with(&system_address_change(BLOCK_NUMBER))).build(); let steps = start_block(&mut state, envs.clone(), LARGE_BLOCK_GAS_LIMIT); - assert_eq!(steps.len(), 2, "the read and the call"); + assert_eq!(steps.len(), 4, "the read, the call, the deployment and the resolution"); assert!(!applies_pending_changes(&steps[..1]), "the read leaves the registry untouched"); - assert!(applies_pending_changes(&steps[1..]), "the call touches it"); + assert!(applies_pending_changes(&steps[1..2]), "the call touches it"); + assert!(!applies_pending_changes(&steps[2..]), "the deployment and the resolution read it"); + assert_resolution(&steps[3], NEXT_SYSTEM_ADDRESS); assert_eq!(envs.total_bucket_queries(), 0, "no pre-block step read a capacity"); assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), common::word(NEXT_SYSTEM_ADDRESS)); assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), U256::ZERO, "the pending slot is cleared"); @@ -161,17 +162,35 @@ fn test_a_due_change_is_applied_under_a_crowded_bucket() { } /// A block with nothing due makes no call: the block commits the read that found nothing due, -/// both pending slots and nothing else, read-only. +/// both pending slots and nothing else, read-only, then the deployment's read-only entry of the +/// registry, which holds version 2.0.0, then the resolution. #[test] fn test_a_block_with_nothing_due_makes_no_call() { let mut state = State::builder().with_database(registry_with(&[])).build(); let steps = start_block(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); - assert_eq!(steps.len(), 1, "the read alone"); + assert_eq!(steps.len(), 3, "the read, the deployment and the resolution"); let registry = &steps[0][&SEQUENCER_REGISTRY_ADDRESS]; assert!(!registry.is_touched(), "a read-only entry"); assert_eq!(registry.storage.len(), 2); assert!(registry.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); assert!(registry.storage.contains_key(&PENDING_SEQUENCER)); + let deployed = &steps[1][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!deployed.is_touched() && !deployed.is_created(), "version 2.0.0 is left as it is"); + assert!(deployed.storage.is_empty(), "the deployment reads no slot of it"); + assert_resolution(&steps[2], MEGA_SYSTEM_ADDRESS); +} + +/// Asserts `state` is the resolution of the live system address: the registry's account alone, +/// untouched, holding version 2.0.0, with the one slot naming `system_address`, unchanged. +fn assert_resolution(state: &EvmState, system_address: Address) { + assert_eq!(state.len(), 1, "the registry alone"); + let registry = &state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched() && !registry.is_created(), "a read-only entry"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(registry.storage.len(), 1, "exactly the one slot read"); + let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; + assert!(!slot.is_changed()); + assert_eq!(slot.present_value(), common::word(system_address)); } /// A change scheduled for a later block is left pending: nothing is due, and no call is made. @@ -220,8 +239,8 @@ fn gas_limit(input_len: usize) -> u64 { /// A legacy call from `sender` to the Oracle's `getSlot(0)`: a system-address transaction when /// `sender` is the system address the registry names, an ordinary one otherwise. It carries a /// gas price, so an ordinary one needs a balance its sender does not have here. `getSlot` does not -/// read the registry itself, so what the transaction's state holds of the registry is what its -/// validation read. +/// read the registry itself, so the transaction's state holds nothing of the registry unless its +/// classification read it. fn oracle_call_from(sender: Address, nonce: u64) -> Recovered { let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); let gas_limit = gas_limit(input.len()); @@ -262,39 +281,35 @@ fn assert_is_not_the_system_address(executor: &mut Executor<'_>, sender: Address assert!(err.to_string().contains("lack of funds"), "{err}"); } -/// Asserts `state` holds what a system-address transaction's validation read: the registry's -/// account, untouched, with the one slot naming `system_address`, unchanged. -fn assert_carries_the_system_address_read(state: &EvmState, system_address: Address) { - let registry = &state[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.is_touched(), "a read-only entry"); - assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(registry.storage.len(), 1, "exactly the one slot read"); - let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; - assert!(!slot.is_changed()); - assert_eq!(slot.present_value(), common::word(system_address)); +/// Asserts a transaction read nothing of the registry for its classification: its `state` holds +/// no entry of it. +fn assert_reads_no_registry(state: &EvmState) { + assert!(!state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), "the transaction read the registry"); } -/// No pre-block step carries the system address's slot: the read of the pending changes reads the -/// pending slots alone, and the activation block's check, which reads the registry's account -/// without storage, is not made here. The slot is in the system-address transaction's own state -/// instead, read-only and warm, as its validation read it. +/// The live system address is resolved once, as the block's last pre-block state: the registry's +/// account and its system-address slot, read-only, which no earlier step carries. The +/// system-address transaction after it reads nothing of the registry for its classification, and +/// a transaction that reads the registry's slot itself finds it cold. #[test] -fn test_the_slot_is_in_the_system_transactions_state_not_the_pre_block_witness() { +fn test_the_resolution_is_the_last_pre_block_state_and_no_transaction_reads_the_registry() { let mut state = State::builder().with_database(registry_with(&[])).build(); let committed = CommittedStates::install(&mut state); let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); executor.apply_pre_execution_changes().expect("the block starts"); - for (step, state) in committed.states().iter().enumerate() { + let states = committed.states(); + let (last, earlier) = states.split_last().expect("the pre-block states"); + assert_resolution(last, MEGA_SYSTEM_ADDRESS); + for (step, state) in earlier.iter().enumerate() { let slot = state .get(&SEQUENCER_REGISTRY_ADDRESS) .and_then(|registry| registry.storage.get(&CURRENT_SYSTEM_ADDRESS)); assert!(slot.is_none(), "pre-block step {step} carries the system address's slot"); } + assert_eq!(executor.evm().ctx().system_address(), Some(MEGA_SYSTEM_ADDRESS)); let outcome = assert_is_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); - assert_carries_the_system_address_read(&outcome.inner.state, MEGA_SYSTEM_ADDRESS); - let registry = &outcome.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.storage[&CURRENT_SYSTEM_ADDRESS].is_cold, "the read warmed the slot"); + assert_reads_no_registry(&outcome.inner.state); } /// A system-address transaction is recognised by the address read out of the registry: from it, @@ -309,7 +324,7 @@ fn test_system_tx_uses_resolved_system_address() { let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); executor.apply_pre_execution_changes().expect("the block starts"); let outcome = assert_is_the_system_address(&mut executor, CHAIN_SYSTEM_ADDRESS); - assert_carries_the_system_address_read(&outcome.inner.state, CHAIN_SYSTEM_ADDRESS); + assert_reads_no_registry(&outcome.inner.state); assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); } @@ -330,7 +345,7 @@ fn test_a_rotation_governs_the_blocks_from_its_activation_block() { for number in [activation, activation + 1] { let mut block = started_block_at(&mut state, number); let outcome = assert_is_the_system_address(&mut block, NEXT_SYSTEM_ADDRESS); - assert_carries_the_system_address_read(&outcome.inner.state, NEXT_SYSTEM_ADDRESS); + assert_reads_no_registry(&outcome.inner.state); assert_is_not_the_system_address(&mut block, MEGA_SYSTEM_ADDRESS); } assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), U256::ZERO, "applied once"); diff --git a/crates/mega-evm/tests/block/witness/basics.rs b/crates/mega-evm/tests/block/witness/basics.rs index f31d7a4c3..cc45246af 100644 --- a/crates/mega-evm/tests/block/witness/basics.rs +++ b/crates/mega-evm/tests/block/witness/basics.rs @@ -40,9 +40,9 @@ pub(crate) fn write_gas() -> u64 { } /// A block whose transactions write two fresh slots: the replay reads only the record and -/// produces the same block, and the exported buckets are the two slots'. The block is not Satin's -/// activation block, so its pre-block phase reads no predeploy and the record holds none that no -/// transaction reached. +/// produces the same block, and the exported buckets are the two slots'. The block's deployment of +/// the system contracts reads the Oracle's account, which holds the Oracle's code, by its code +/// hash: the record holds the account and not its code, which no load asked for. #[test] fn test_a_block_of_writes_replays_from_its_witness() { let mut db = common::database(); @@ -57,11 +57,10 @@ fn test_a_block_of_writes_replays_from_its_witness() { if !common::state_is_free() { assert_eq!(run.bucket_ids.len(), 2, "one bucket per fresh slot"); } - assert_eq!( - run.record.accounts.get(&mega_evm::system::ORACLE_CONTRACT_ADDRESS), - None, - "nothing asked about the Oracle's account" - ); + let oracle = run.record.accounts.get(&mega_evm::system::ORACLE_CONTRACT_ADDRESS); + let oracle = oracle.expect("the deployment read the Oracle").as_ref().expect("it is there"); + assert_eq!(oracle.code_hash, mega_evm::system::ORACLE_CONTRACT_CODE_HASH); + assert!(!run.record.codes.contains_key(&oracle.code_hash), "nothing loaded its code"); assert!(run.record.codes.values().all(|code| !code.is_empty()), "code travels by hash"); assert_eq!( replay.replayed.record, run.record, diff --git a/crates/mega-evm/tests/block/witness/predeploys.rs b/crates/mega-evm/tests/block/witness/predeploys.rs index 133ab19a2..54be56bf2 100644 --- a/crates/mega-evm/tests/block/witness/predeploys.rs +++ b/crates/mega-evm/tests/block/witness/predeploys.rs @@ -1,5 +1,5 @@ -//! Satin's activation block, its check of the predeploys, and the EIP-7997 factory through the -//! harness. +//! The system contracts every block deploys, Satin's activation block and its check of the +//! EIP-7997 factory, and the factory itself, through the harness. use alloy_primitives::{keccak256, Address, Bytes, U256}; use mega_evm::system::{system_contract_specs, CREATE2_FACTORY_ADDRESS}; @@ -24,13 +24,14 @@ fn init_code() -> Bytes { code.into() } -/// The state the activation block's check committed for the predeploy at `address`. -fn check_state(run: &Run, address: Address) -> &Account { +/// The read-only state a pre-block step committed for the predeploy at `address`: the factory's +/// check, or a system contract's deployment that found it holding its code. +fn read_only_state(run: &Run, address: Address) -> &Account { let state = run .pre_block .iter() - .find(|state| common::is_predeploy_check(state) && state.contains_key(&address)) - .unwrap_or_else(|| panic!("{address} has a check state")); + .find(|state| state.len() == 1 && state.contains_key(&address)) + .unwrap_or_else(|| panic!("{address} has a pre-block state")); &state[&address] } @@ -55,14 +56,14 @@ fn test_a_deployment_through_the_factory_replays() { } /// Satin's activation block over a chain shaped as Rex6 leaves it replays on both witnesses: it -/// admits deposits alone, so the deposit runs and the user transaction is refused, and its check -/// reads the seven predeploys, each with the chain's code hash, loads none of their code, and -/// commits each as a read-only entry. The witness built from those entries holds, for every -/// predeploy, the code the chain held, under its hash: no check loaded it, so it is there because -/// the account was named, resolved against the chain. +/// admits deposits alone, so the deposit runs and the user transaction is refused; its check reads +/// the factory, and its deployment of the system contracts reads the six, each with the chain's +/// code hash, loads none of their code, and commits each as a read-only entry. The witness built +/// from those entries holds, for every predeploy, the code the chain held, under its hash: no step +/// loaded it, so it is there because the account was named, resolved against the chain. /// -/// An ordinary block over the same chain reads none of the predeploys the transactions do not -/// reach: no check state, and no record of their accounts. +/// An ordinary block over the same chain reads the six system contracts too, every block deploying +/// them, and not the factory: no check state, and no record of its account. /// /// Rule [S22.4]. Expected values `independent`: the code is the bytecode the test put in the chain, /// and its hash is computed here. @@ -92,9 +93,9 @@ fn test_an_activation_block_replays() { let hash = keccak256(&spec.code); let info = run.record.accounts.get(&spec.address).expect("read").as_ref().expect("held"); assert_eq!(info.code_hash, hash, "{} was read with the chain's code hash", spec.address); - let entry = check_state(run, spec.address); + let entry = read_only_state(run, spec.address); assert!(!entry.is_touched() && !entry.is_created(), "{} was only read", spec.address); - assert!(!run.record.codes.contains_key(&hash), "{}: the check loads no code", spec.address); + assert!(!run.record.codes.contains_key(&hash), "{}: no step loads its code", spec.address); assert!( witness.codes.get(&hash).is_some_and(|carried| carried.original_bytes() == spec.code), "{}: the witness carries the code the chain held", @@ -105,9 +106,10 @@ fn test_an_activation_block_replays() { let replay = Case::new("ordinary block", db).tx(call(0, CONTRACT, slot(2), write_gas())).run(); let run = &replay.recorded; assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); - assert!(!run.pre_block.iter().any(common::is_predeploy_check), "no check state"); - for spec in &system_contract_specs()[1..5] { - assert!(!run.record.accounts.contains_key(&spec.address), "{} was read", spec.address); + assert!(!run.pre_block.iter().any(common::is_factory_check), "no check state"); + for spec in &system_contract_specs()[..6] { + let entry = read_only_state(run, spec.address); + assert!(!entry.is_touched() && !entry.is_created(), "{} was only read", spec.address); } assert!(!run.record.accounts.contains_key(&CREATE2_FACTORY_ADDRESS), "the factory was read"); } diff --git a/crates/mega-evm/tests/block/witness/skips.rs b/crates/mega-evm/tests/block/witness/skips.rs index 7fe4c2f09..1c3eadc82 100644 --- a/crates/mega-evm/tests/block/witness/skips.rs +++ b/crates/mega-evm/tests/block/witness/skips.rs @@ -141,10 +141,15 @@ fn test_a_cold_account_load_short_of_gas_reads_no_account() { assert_eq!(replay.recorded.record.accounts.get(&STRANGER), Some(&None)); } -/// Code that calls the Oracle forwarding `gas` and returns whether the call succeeded, as a word. +/// Code that calls the Oracle's `getSlot(42)` forwarding `gas` and returns whether the call +/// succeeded, as a word. fn calls_the_oracle_forwarding(gas: u64) -> Bytes { + let input = IOracle::getSlotCall { slot: U256::from(42) }.abi_encode(); BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .mstore(0, &input) + .append_many([PUSH0, PUSH0]) + .push_number(input.len() as u64) + .append_many([PUSH0, PUSH0]) .push_address(ORACLE_CONTRACT_ADDRESS) .push_number(gas) .append_many([CALL, PUSH0, MSTORE]) @@ -153,21 +158,44 @@ fn calls_the_oracle_forwarding(gas: u64) -> Bytes { .build() } -/// An Oracle read is made before any of its 2,100 is charged: whatever its frame holds at the -/// `SLOAD` — 50, 2,099, 2,100 or 4,099 — the slot is read from the database and the service -/// asked, on a chain that holds the Oracle, and the frame then runs out of gas on the first two -/// and completes the other two. The replay reads and asks the same, and replays the recorded -/// answer at each. +/// The regular gas the chain's Oracle spends in its own frame on `getSlot(42)` before its `SLOAD`, +/// and after the `SLOAD` to the frame's end, measured under a gas inspector on an EVM over the +/// chain the blocks run on: the block deploys the Oracle at its own code, which these figures are +/// of. +fn oracle_get_slot_gas() -> (u64, u64) { + use alloy_evm::{EvmFactory, ToTxEnv}; + let db = chain_with_oracle().account_code(CONTRACT, calls_the_oracle_forwarding(1_000_000)); + let mut evm = mega_evm::MegaEvmFactory::new().create_evm_with_inspector( + db, + common::evm_env(), + mega_evm::test_utils::GasInspector::new(), + ); + let tx = common::recovered(common::tx(0, CONTRACT, Bytes::new(), 3_000_000)); + let outcome = evm.execute_transaction(tx.to_tx_env()).expect("the probe runs"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + // The transaction's frame is at depth 1, the Oracle's below it at 2. + let oracle: Vec<_> = + evm.inspector().records().into_iter().filter(|record| record.depth == 2).collect(); + let sload = oracle.iter().find(|record| record.opcode.get() == SLOAD).expect("its read"); + let start = oracle.first().expect("the Oracle ran").gas_before; + let end = oracle.last().expect("the Oracle ran").gas_after; + (start - sload.gas_before, sload.gas_after - end) +} + +/// An Oracle read is made before any of its 2,100 is charged: whatever the Oracle's frame holds at +/// its `SLOAD` — 50, 2,099, or 2,100 and 4,099 with what the frame spends after it — the slot is +/// read from the database and the service asked, on a chain that holds the Oracle, and the frame +/// then runs out of gas on the first two and completes the other two. The replay reads and asks +/// the same, and replays the recorded answer at each. #[test] fn test_an_oracle_read_is_read_and_asked_whatever_its_frame_holds() { let slot = (ORACLE_CONTRACT_ADDRESS, U256::from(42)); - for (left, completes) in [(50, false), (2_099, false), (2_100, true), (4_099, true)] { + let (before, after) = oracle_get_slot_gas(); + for (left, completes) in + [(50, false), (2_099, false), (2_100 + after, true), (4_099 + after, true)] + { let mut db = chain_with_oracle(); - db.set_account_code( - ORACLE_CONTRACT_ADDRESS, - BytecodeBuilder::default().push_number(42_u8).append(SLOAD).stop().build(), - ); - db.set_account_code(CONTRACT, calls_the_oracle_forwarding(3 + left)); + db.set_account_code(CONTRACT, calls_the_oracle_forwarding(before + left)); let replay = Case::new("oracle read by gas", db) .envs(super::harness::Envs::new().with_oracle_storage(U256::from(42), U256::from(1))) .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) diff --git a/crates/mega-evm/tests/block/witness/system.rs b/crates/mega-evm/tests/block/witness/system.rs index 4bffa79be..9d701d3c6 100644 --- a/crates/mega-evm/tests/block/witness/system.rs +++ b/crates/mega-evm/tests/block/witness/system.rs @@ -84,12 +84,13 @@ fn test_a_rotation_and_a_system_transaction_replay() { ); } -/// A system transaction in a block with nothing due reads the live address out of the witness: -/// the registry's account and its one slot are in the record and in the transaction's own state, -/// and the registry's code is not among the block's reads: the slot is read without it, so no -/// load the block made asked for it. That is what execution loads, not what a witness holds: a -/// witness holds the code the chain held for every account the block loads, the registry's -/// included, and this test asserts only the loads. +/// A system transaction in a block with nothing due is classified against the live address the +/// block resolved: the registry's account and its one slot are in the record, read by the +/// resolution, the last pre-block state, and not in the transaction's own state, and the +/// registry's code is not among the block's reads: the slot is read without it, so no load the +/// block made asked for it. That is what execution loads, not what a witness holds: a witness holds +/// the code the chain held for every account the block loads, the registry's included, and this +/// test asserts only the loads. /// /// Rule [S17.4]. Expected values `independent`: the registry's code hash is computed here from the /// bytecode the test put in the chain. @@ -101,10 +102,15 @@ fn test_a_system_transaction_reads_the_live_address_from_the_witness() { let run = &replay.recorded; assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); assert!(run.record.storage.contains_key(&(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS))); - let registry = run.tx(0).state.get(&SEQUENCER_REGISTRY_ADDRESS).expect("the registry is read"); + assert!( + !run.tx(0).state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), + "the transaction does not read the registry" + ); + let resolution = run.pre_block.last().expect("the pre-block states"); + let registry = resolution.get(&SEQUENCER_REGISTRY_ADDRESS).expect("the resolution"); assert!( registry.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), - "the slot is in the transaction's state" + "the slot is in the resolution's state" ); assert!( !run.record.codes.contains_key(&keccak256(SEQUENCER_REGISTRY_CODE)), diff --git a/crates/mega-evm/tests/fuzz/differential.rs b/crates/mega-evm/tests/fuzz/differential.rs index 0b273c7e6..b41bff8d5 100644 --- a/crates/mega-evm/tests/fuzz/differential.rs +++ b/crates/mega-evm/tests/fuzz/differential.rs @@ -36,8 +36,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use alloy_op_evm::OpTx; use mega_evm::{ test_utils::{ - neutral_cfg, neutral_gas_table, neutralize_evm, take_system_address_read, - zero_fee_l1_block_info, MemoryDatabase, + neutral_cfg, neutral_gas_table, neutralize_evm, zero_fee_l1_block_info, MemoryDatabase, }, EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, }; @@ -110,9 +109,7 @@ fn run_mega( let outcome = mega .execute_transaction(OpTx(tx)) .map(|outcome| { - let mut state = outcome.result_and_state.state; - take_system_address_read(&mut state); - ExecResultAndState::new(outcome.result_and_state.result, state) + ExecResultAndState::new(outcome.result_and_state.result, outcome.result_and_state.state) }) .map_err(|error| format!("{error}")); (outcome, cfg) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 9ba20e682..9a9b74a75 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -17,12 +17,8 @@ //! absorbed. Later changes (the //! limits) add their own. //! -//! Every Satin transaction also reads the live system address when it is validated, which leaves -//! the `SequencerRegistry`'s account and its system-address slot in its returned state as a -//! read-only entry that op-revm's has no counterpart for. A commit skips an account nothing -//! touched, so the entry changes no committed state; each comparison of the two states takes it -//! out first ([`take_system_address_read`]), which fails when the entry is missing or is more than -//! the read, so the difference is pinned on every case rather than absorbed. +//! No Satin transaction reads the `SequencerRegistry` for its classification: the live system +//! address is resolved outside every transaction, so the two returned states compare whole. //! //! SALT pricing multiplies a state gas charge by the capacity of the bucket it lands in, and //! op-revm has no SALT to read. Every baseline case runs without a SALT environment, where every @@ -38,8 +34,8 @@ use mega_evm::{ }, satin_gas_params, test_utils::{ - note_price_guard, op_transaction, take_system_address_read, transfer_log, - zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + note_price_guard, op_transaction, transfer_log, zero_fee_l1_block_info, BytecodeBuilder, + MemoryDatabase, }, MegaContext, MegaEvm, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; @@ -158,14 +154,7 @@ fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Settled) { assert_eq!(mega.result.logs(), op.result.logs(), "logs"); assert_eq!(mega.result.output(), op.result.output(), "output"); assert_eq!(mega.result.is_success(), op.result.is_success(), "success"); - assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); -} - -/// `state` with the read of the live system address every Satin transaction makes taken out. -fn but_the_system_address_read(state: &EvmState) -> EvmState { - let mut state = state.clone(); - take_system_address_read(&mut state); - state + assert_eq!(mega.state, op.state, "state"); } /// Asserts the two outcomes agree field by field, then as a whole so a field added later is @@ -527,8 +516,8 @@ fn test_an_intercepted_call_diverges_from_op_revm() { /// A legacy transaction from the system address is a fee-free deposit on Satin, where op-revm /// sees an ordinary transaction and refuses it for want of a balance to pay with. Satin knows -/// the address from the `SequencerRegistry`, which the transaction's validation reads: its state -/// carries the read, which op-revm has no reason to make. +/// the address from the `SequencerRegistry`, which the EVM read when it was built, outside the +/// transaction: the transaction's state carries no read of the registry. #[test] fn test_a_system_address_transaction_diverges_from_op_revm() { use mega_evm::system::{ @@ -562,8 +551,8 @@ fn test_a_system_address_transaction_diverges_from_op_revm() { "the sender pays no fee and needed no balance", ); assert!( - mega_outcome.state.get(&SEQUENCER_REGISTRY_ADDRESS).is_some_and(|a| !a.is_touched()), - "the read of the live system address is a read-only entry of the transaction's state", + !mega_outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), + "the transaction does not read the live system address", ); let error = op.transact(op_transaction(tx)).expect_err("op-revm wants a fee"); @@ -779,7 +768,7 @@ fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { // moves the gas ledgers and nothing else. 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"); + assert_eq!(mega.state, op.state, "state"); } /// A contract whose constructor destroys the account it is creating: Satin's destruction table @@ -804,7 +793,7 @@ fn test_a_creation_that_destroys_itself_diverges_from_op_revm() { 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()); + assert!(mega.state[&CALLEE.create(0)].is_selfdestructed()); // The one difference, and its exact size. let (m, o) = (mega.result.gas(), op.result.gas()); @@ -820,7 +809,7 @@ fn test_a_creation_that_destroys_itself_diverges_from_op_revm() { 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"); + assert_eq!(mega.state, op.state, "state"); } /// A transaction that runs out of gas in the runtime gas phase, before its first frame — here on @@ -876,7 +865,7 @@ fn test_an_out_of_gas_before_the_first_frame_matches_op_revm() { assert_eq!(mega.gas.state, 0, "the account was not created"); // With no gas price the fee is nothing, so the two states are the same: the sender's nonce // moved and nothing else. - assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); + assert_eq!(mega.state, op.state, "state"); assert_eq!(mega.state[&CALLER].info.nonce, 1); } diff --git a/crates/mega-evm/tests/satin/limit_matrix/block.rs b/crates/mega-evm/tests/satin/limit_matrix/block.rs index 932e99b1c..f80e646e3 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/block.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/block.rs @@ -7,8 +7,9 @@ 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 alloy_sol_types::SolCall; use mega_evm::{ - system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, test_utils::{MemoryDatabase, SequencerRegistryRoles}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, ProtocolLimits, @@ -57,6 +58,17 @@ pub(super) fn legacy( nonce: u64, to: Address, gas_limit: u64, +) -> Recovered { + legacy_with_input(from, nonce, to, gas_limit, Bytes::new()) +} + +/// [`legacy`] carrying `input`. +fn legacy_with_input( + from: Address, + nonce: u64, + to: Address, + gas_limit: u64, + input: Bytes, ) -> Recovered { let tx = TxLegacy { chain_id: Some(CHAIN_ID), @@ -65,7 +77,7 @@ pub(super) fn legacy( gas_limit, to: TxKind::Call(to), value: U256::ZERO, - input: Bytes::new(), + input, }; Recovered::new_unchecked( MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO)), @@ -208,20 +220,31 @@ fn test_a_skip_with_every_block_dimension_reached_records_no_dimension() { assert!(results[1].is_err(), "the next ordinary transaction is skipped: {:?}", results[1]); } +/// Regular gas a Mega System Transaction's `setSlots` call runs on beyond the slots it fills: +/// the Oracle's ABI decoding, its loop and its caller check, and the calldata of a thousand +/// entries, whatever the byte prices. +const ORACLE_CALL_ROOM: u64 = 20_000_000; + +/// A Mega System Transaction writing 1 into Oracle slots `1..=n` through the Oracle's `setSlots`, +/// which every block's deployment of the Oracle leaves at its own code. +fn oracle_write(n: u64, gas_limit: u64) -> Recovered { + let slots = (1..=n).map(U256::from).collect(); + let values = vec![B256::with_last_byte(1); n as usize]; + let input = IOracle::setSlotsCall { slots, values }.abi_encode().into(); + let gas_limit = gas_limit + ORACLE_CALL_ROOM; + legacy_with_input(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas_limit, input) +} + /// 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 db = database(store_n_slots(1)); let (results, mut state) = drive( db, - vec![ - legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), - legacy(CALLER, 0, CONTRACT, gas), - ], + vec![oracle_write(TX_STATE_GROWTH_LIMIT + 1, gas), legacy(CALLER, 0, CONTRACT, gas)], ); assert!(results[0].is_ok(), "the system transaction is included: {:?}", results[0]); assert_eq!( @@ -273,13 +296,12 @@ fn test_a_pre_block_call_of_1001_slots_is_not_stopped_and_does_not_move_the_bloc #[test] fn test_a_system_transaction_after_1000_slots_is_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 db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); let (results, mut state) = drive( db, vec![ legacy(CALLER, 0, CONTRACT, gas), - legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + oracle_write(TX_STATE_GROWTH_LIMIT + 1, gas), legacy(OTHER, 0, CONTRACT, gas), ], ); @@ -308,15 +330,11 @@ fn test_a_builders_kv_and_state_growth_policy_does_not_bind_a_validator() { vec![ legacy(CALLER, 0, CONTRACT, gas), deposit(DEPOSITOR, CONTRACT, gas, false), - legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + oracle_write(2, 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 db = || database(store_n_slots(2)); 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); diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index 657c565d1..419cbf0cb 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -18,8 +18,8 @@ use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ test_utils::{ - neutral_cfg, neutralize_evm, op_transaction, take_system_address_read, - zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + neutral_cfg, neutralize_evm, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, + MemoryDatabase, }, EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, VolatileDataAccess, @@ -89,9 +89,8 @@ fn run_both(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome let mut mega = MegaEvm::new(ctx); neutralize_evm(&mut mega, fork).expect("a neutral fork"); let outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); - let mut state = outcome.result_and_state.state; - take_system_address_read(&mut state); - let mega = ExecResultAndState::new(outcome.result_and_state.result, state); + let mega = + ExecResultAndState::new(outcome.result_and_state.result, outcome.result_and_state.state); let op = OpEvm::new(op_ctx, NoOpInspector).transact(op_transaction(tx)).unwrap(); (mega, op, outcome.gas.history) @@ -280,7 +279,6 @@ fn run_against_ethereum(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outc neutralize_evm(&mut mega, fork).expect("a neutral fork"); let outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); let mut state = outcome.result_and_state.state; - take_system_address_read(&mut state); for vault in [BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { if state.get(&vault).is_some_and(|account| account.is_empty()) { state.remove(&vault); diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 0ca8dc5f3..6477c97f2 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -424,8 +424,8 @@ fn system_address_transaction(gas_limit: u64) -> (TxEnv, OpTransaction) { /// deposit op-revm runs for it — never the system call's 30M split, which the rows between 30M and /// the cap would see. /// -/// The one difference from op-revm's deposit is in the state: Satin's validation read the live -/// system address out of the `SequencerRegistry`, a read-only entry holding the one slot. +/// Its state is op-revm's deposit's: no transaction reads the `SequencerRegistry` for its +/// classification, so no entry of it is in the state. #[test] fn test_a_system_address_transaction_is_split_by_the_execution_cap() { for (gas_limit, reservoir) in [ @@ -448,14 +448,11 @@ fn test_a_system_address_transaction_is_split_by_the_execution_cap() { assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega_outcome.gas.history, 0); assert_eq!(mega_outcome.gas.reservoir_remaining, reservoir, "{gas_limit}"); - let mut satin = Settled { + let 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!(!satin.result_and_state.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS)); assert_same(&satin, &op_outcome); } } diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index d4559c160..84d3d4590 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -268,12 +268,14 @@ fn test_another_shape_from_the_live_system_address_is_invalid() { } } -/// Every transaction reads the registry when it is validated, whatever its shape and whoever -/// sends it: its returned state holds the registry's account, untouched, and the system-address -/// slot, unchanged, and a database that cannot serve the registry's account or that slot fails it -/// with the database's error, a deposit included. +/// No transaction reads the registry for its classification, whatever its shape and whoever sends +/// it: the EVM read the live system address when it was built, so the transaction's returned state +/// holds no entry of the registry, and an EVM handed the address runs every shape on a database +/// that cannot serve the registry's account or its system-address slot. Only an EVM whose own read +/// failed when it was built makes the read again, for its next transaction, and fails it with the +/// database's error, a deposit included. #[test] -fn test_every_transaction_reads_the_registry() { +fn test_no_transaction_reads_the_registry() { let funded = || { chain_db() .account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])) @@ -289,40 +291,39 @@ fn test_every_transaction_reads_the_registry() { .execute_transaction(tx.clone()) .expect("an ordinary transaction"); assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); - let registry = &outcome.state[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.is_touched(), "{shape}: a read-only entry"); - let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; - assert!(!slot.is_changed(), "{shape}"); - assert_eq!(slot.present_value(), U256::from_be_slice(MEGA_SYSTEM_ADDRESS.as_slice())); + assert!( + !outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), + "{shape}: the transaction read nothing of the registry" + ); let mut account = ErrorInjectingDatabase::new(funded()); account.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); let mut slot = ErrorInjectingDatabase::new(funded()); slot.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); for db in [account, slot] { + let handed = chain_context(db.clone()).with_system_address(Some(MEGA_SYSTEM_ADDRESS)); + let outcome = MegaEvm::new(handed) + .execute_transaction(tx.clone()) + .expect("an EVM handed the address reads no registry"); + assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); let error = MegaEvm::new(chain_context(db)) .execute_transaction(tx.clone()) - .expect_err("the registry is read"); + .expect_err("the read the EVM could not make when it was built is made again"); assert!(matches!(error, EVMError::Database(_)), "{shape}: {error:?}"); } } } -/// Every transaction starts with the registry's account and its system-address slot warm, as -/// EIP-3651 starts the block beneficiary warm: validation reads the live system address for every -/// transaction, whatever its shape. A user's call to the Oracle's `setSlots` makes the Oracle ask -/// the registry for the system address itself, and that `SLOAD` pays the warm price, as a legacy -/// call, as an EIP-2930 call, and as one whose access list names the slot alike: the shape of the -/// envelope changes nothing the transaction pays, and the access list adds only its own -/// intrinsic cost. +/// No transaction starts with the registry's account or its system-address slot warm: a user's +/// call to the Oracle's `setSlots` makes the Oracle ask the registry for the system address, and +/// that `SLOAD` pays the cold price, as a legacy call and as an EIP-2930 call alike, which spend +/// the same gas on every ledger, while an access list naming the slot makes it warm, as it makes +/// any slot. A Mega System Transaction's own call to the Oracle pays the same cold reads. #[test] -fn test_every_transaction_warms_the_registry_and_its_slot() { - let run = |tx: MegaTransaction| { - let mut evm = - MegaEvm::new(chain_context(chain_db().account_balance(CALLER, U256::from(FUNDS)))) - .with_inspector(GasInspector::new()); - let outcome = evm.execute_transaction(tx).expect("an ordinary transaction"); - assert!(!outcome.result.is_success(), "the Oracle refuses a write from a user"); +fn test_a_transaction_that_reads_the_registry_pays_cold() { + let run = |db: MemoryDatabase, tx: MegaTransaction| { + let mut evm = MegaEvm::new(chain_context(db)).with_inspector(GasInspector::new()); + let outcome = evm.execute_transaction(tx).expect("a valid transaction"); let sloads: Vec = evm .inspector() .records() @@ -334,41 +335,48 @@ fn test_every_transaction_warms_the_registry_and_its_slot() { assert_eq!(sloads.len(), 1, "the registry reads its one slot: {sloads:?}"); (outcome, sloads[0]) }; - let write = || { + let user = || chain_db().account_balance(CALLER, U256::from(FUNDS)); + let write = |caller| { legacy_tx( - CALLER, + caller, TxKind::Call(ORACLE_CONTRACT_ADDRESS), set_slot(ORACLE_SLOT, B256::with_last_byte(1)), 0, ) }; - let warm = mega_evm::satin_gas_params().warm_storage_read_cost(); + let params = mega_evm::satin_gas_params(); + let cold = params.warm_storage_read_cost() + params.cold_storage_additional_cost(); + let warm = params.warm_storage_read_cost(); - let (shaped, legacy) = run(write()); - let (unshaped, typed_call) = run(typed(write(), 1)); + let (shaped, legacy) = run(user(), write(CALLER)); + let (unshaped, typed_call) = run(user(), typed(write(CALLER), 1)); for (shape, outcome) in [("legacy", &shaped), ("EIP-2930", &unshaped)] { + assert!(!outcome.result.is_success(), "{shape}: the Oracle refuses a write from a user"); let registry = &outcome.state[&SEQUENCER_REGISTRY_ADDRESS]; - assert!(!registry.is_touched(), "{shape}: the read writes nothing"); + assert!(!registry.is_touched(), "{shape}: the Oracle's read writes nothing"); assert!(registry.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), "{shape}: the slot"); } - assert_eq!(legacy, warm, "the legacy call's SLOAD is warm"); - assert_eq!(typed_call, warm, "and so is the EIP-2930 call's"); + assert_eq!(legacy, cold, "the legacy call's SLOAD is cold"); + assert_eq!(typed_call, cold, "and so is the EIP-2930 call's"); assert_eq!(shaped.gas, unshaped.gas, "the two spend the same gas on every ledger"); - let mut listed = typed(write(), 1); + let mut listed = typed(write(CALLER), 1); listed.0.base.access_list = AccessList(vec![AccessListItem { address: SEQUENCER_REGISTRY_ADDRESS, storage_keys: vec![B256::from(CURRENT_SYSTEM_ADDRESS)], }]); - let (_, listed) = run(listed); - assert_eq!(listed, warm, "an access list naming the slot makes it no warmer"); + let (_, listed) = run(user(), listed); + assert_eq!(listed, warm, "an access list naming the slot makes it warm"); + + let (system, read) = run(chain_db(), write(MEGA_SYSTEM_ADDRESS)); + assert!(system.result.is_success(), "the system address writes the Oracle"); + assert_eq!(read, cold, "a Mega System Transaction's read of the registry is cold too"); } -/// The registry's account and slot every transaction reads are an untouched entry of its state, -/// and a commit skips an account nothing touched: committing a transaction writes nothing of the -/// registry, whether the state holds a registry or not, so the state root moves as it would -/// without the read. +/// A transaction leaves no entry of the registry in its state, and committing it writes nothing of +/// the registry, whether the state holds a registry or not, so the state root moves as it would +/// without the registry. #[test] fn test_committing_a_transaction_writes_nothing_of_the_registry() { for (holds, db) in [("a registry", chain_db()), ("no registry", MemoryDatabase::default())] { @@ -380,7 +388,7 @@ fn test_committing_a_transaction_writes_nothing_of_the_registry() { let tx = legacy_tx(CALLER, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); let outcome = evm.execute_transaction(tx).expect("an ordinary transaction"); assert!(outcome.result.is_success(), "{holds}: {:?}", outcome.result); - assert!(outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), "{holds}: it was read"); + assert!(!outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), "{holds}: not read"); drop(evm); state.commit(outcome.state.clone()); diff --git a/crates/mega-evm/tests/tracers/harness.rs b/crates/mega-evm/tests/tracers/harness.rs index aca19dfca..d05cc4ea0 100644 --- a/crates/mega-evm/tests/tracers/harness.rs +++ b/crates/mega-evm/tests/tracers/harness.rs @@ -123,7 +123,12 @@ pub(crate) struct Traced { } impl Traced { - /// Runs `tx` on a fresh Satin EVM over `db`, recording every read the database serves. + /// Runs `tx` on a fresh Satin EVM over `db`, recording every read the database serves the + /// transaction. + /// + /// The EVM reads the live system address off the database when it is built, outside every + /// transaction, as block execution resolves it in the pre-block phase: the record is emptied + /// of that read, and holds what the transaction read. pub(crate) fn run(db: MemoryDatabase, tx: MegaTransaction, limits: EvmTxRuntimeLimits) -> Self { let pre_db = db.clone(); let record = Rc::new(RefCell::new(WitnessRecord::default())); @@ -131,6 +136,7 @@ impl Traced { let inspector = TracingInspector::new(TracingInspectorConfig::all()); let mut evm = MegaEvm::new(context(recording).with_tx_runtime_limits(limits)) .with_inspector(inspector); + *record.borrow_mut() = WitnessRecord::default(); let outcome = evm.execute_transaction(tx.clone()).expect("the transaction is valid"); let inspector = evm.inspector().clone(); drop(evm); @@ -576,9 +582,8 @@ pub(crate) fn assert_root_gas_used_is_the_receipt(traced: &Traced) { /// the state of the first transaction of the block that read them. The excuse is those keys, read /// or not, and nothing else. /// -/// An account the engine read without its code — the `SequencerRegistry`'s, which every -/// transaction's validation reads by its code hash — is named with the code the pre-state holds, -/// which the prestate tracer reads itself, as a witness carries it. +/// An account the engine read without its code is named with the code the pre-state holds, which +/// the prestate tracer reads itself, as a witness carries it. pub(crate) fn assert_prestate_covers_reads(traced: &Traced) { let PreStateFrame::Default(PreStateMode(prestate)) = traced.prestate(false) else { panic!("the default prestate mode"); From dd458b8c5de0d8aed798c4d33ed5004a4c4954d1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:38:28 +0800 Subject: [PATCH 068/190] test(keyless): the differential record no longer carries a per-transaction registry read --- ...erential__keyless_differential_record.snap | 274 +++++++++--------- 1 file changed, 137 insertions(+), 137 deletions(-) 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 b57d440a4..ab18e8a7e 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=0x70efa1acc6606a24ed2001d41f9e6ac401ef411f46c929dee5043aa06be58810", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x6401f75c56ae5ba4720369e22bb4fae524a0d92109200d1b814890f050b4deb7", - "rule: arguments that do not decode @ 50000000 | keccak256=0xf200f388d13c3181bef7bd920c142d7682efb6a66a337cd89380d9c322b302e4", - "rule: malformed transaction @ 50000000 | keccak256=0x53e169618aad04c59acaa0e61bf9a259e42b3994e3df64ec789329dd04a03472", - "rule: a trailing byte @ 50000000 | keccak256=0x562d6c884cab4c6ca986bead04dc90661c3dd59026842d504f1a785f109ebde9", - "rule: not a creation @ 50000000 | keccak256=0x3931ffdc0411acf5f321a32fd6fbd0c8b9cd6fc15367d7c222838b2fc4ea9543", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0xf1790e8bea46c362feeb1df1248b98b01b49bbc09fc65d98b7115c1c62dae29f", - "rule: signed at nonce 1 @ 50000000 | keccak256=0xd530dcbaa455e42dea19995fc375f2820b11a754de9de9449e1cc94de1cd3c90", - "rule: override below the signed gas limit @ 50000000 | keccak256=0x38f956a3c77cc6277358eed1c37efbaaf1c8395a1b7f636557c79d4d10bd4b5c", - "rule: invalid signature @ 50000000 | keccak256=0xf5c63e312cfdc749521203895c1285c808f7b75cdfe450a3373886cfc483d2f7", - "rule: signer nonce 2 @ 50000000 | keccak256=0x1df4b39c2977f3c87e509a625071ede72cc178f6b3223bfe782afe53290a58e2", - "rule: signer with code @ 50000000 | keccak256=0xabddaf8853eb78b9173a941c821eacf6f99802f58d3468ad77733304b09df430", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xc78ad48afdd9001f381a0adfc0cae161686cf6ee5e5a6ca14fdb3ed6cca97d59", - "rule: occupied address @ 50000000 | keccak256=0x96edc259014ac2c99fefdefe81f2a7e3115478617546afa13ed78a17a20d5f3b", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x56c9e35e8a022786c2d4373670a0e1a104d799e84a520f594aa3384abd0018f4", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xaf969a7082886d0e4cf5afea2b20867ef5e120ab1fb8bf890032fbad5684cd59", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xa070e0164517815cf14a57192c9b7cb76ba4e182124febf91be0320a83efd149", - "deploys from nonce 1 @ 50000000 | keccak256=0xdb9a5d1313d9e12e11bc0766501e290031c22f73af8df11494857015acf7c729", - "the address already has a balance @ 50000000 | keccak256=0x02b5a107b926e0a0b867fc256cb3ab403382e9d7acfbc8cd16b1e17f2caba734", - "moves value @ 50000000 | keccak256=0x4f625126760c064a90bf9ab495a6f42dc9f2a91db86771d44d803c762dd3f285", - "moves value from nonce 1 @ 50000000 | keccak256=0x3f725d461e52c0392f80eaf6200af7a5d799d917f4aab6a62dde15a85bf11054", - "the CREATE2 factory @ 50000000 | keccak256=0x1ab746976b43499851c0deb1bfddaf798f1f7c889dbf0398a4a7e80f158662bb", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x55ea2bb23dade17a76b767000640469d37aed89924ef185bde1fd3f8ca1861f2", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x7bbb859d05d2c5079346f4b5c4adb2514271e60342bc508c7cd657b78536630b", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xd70f77f32871fedaffd9be868aa73be297b5b39af8d812a9227a6e7637eec2b7", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x1df5d50f7cd9ca327d52d3f5e7e52c52b59376acc988fede8f6b7212a1f1906a", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x2fc750cc4eeabe6870d1b9cce22fe77f7b9dd66df3ff9d9d546365944ec89f86", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x85f487e3f21dd23012cac9ee26741ecfe43b68d8a170f0ca429c23831068022d", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf1e561d3cba6267a8326ab81ded8f8edffc72b4beb15c1abe6853a7f48101e77", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xb8c8bafe75039598f433f1d7d20942d0ca7b2b0beed86f65f58f0ff194079ba9", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x2e8a101e9df5be12528cbf24cb30f1bebeeecc5df2b5268d29f9416ac175c451", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x306935b3351c2363335d1d972683d7ffbf967c9ad6404fcb8dfeb79051dbf3c9", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x1bb85e30bce7c14e98b25a0e1d9b6c2e895fe1f46c17f9472b1f21cf6ef62077", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x062278078c36e5eed12c3c3abefdd94d8e9f0a0125d272780a61565117a0f57e", - "a constructor out of gas @ 50000000 | keccak256=0xad13ba28e89f0c5d77c97fb7267b61a6e0d3ff587346ee7613371b175b54e4de", - "the signer sends it @ 50000000 | keccak256=0x07d09a10d770e7389731b55c2e6b57d23042735f561a001df883fc31075d8fce", - "the signer sends it, and it reverts @ 50000000 | keccak256=0xcdbd6d53d5b79f49e8d12db6ccc916d493cc1517be04994352e9379bfb03f78a", - "a delegated signer @ 50000000 | keccak256=0x19e5acb7f0ba435282dbbd816a80ea2b6cae219728d174e33ca777cef49ba2bc", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x6937a8cd14af128f65787d290aeb2f74b2c566c12822b8584049b094069d7557", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x03ea2d6ba86920a73c4fae1f9a328142ced7164fa707002594212fbfa32fc1ab", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x6f92465c464e4f71bb87b572126bdd5c3e8c722266f515ec81cd44f1cc05f7fa", - "limit: compute, nonce 0 @ 50000000 | keccak256=0x719b68a8c50d953107b708eedcca301ce7be644adb045eaeef4dd5c2df4f27a3", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x77099302d2c2175a512849c6f19cdb408a56309bb9b67e836881dd475b3455a0", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x3e96f6426d3b9178434293bfd3e94e69770d55722f51a162788bf6001e2c9e49", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0xec7133b31e08dc890d5e9f1d9d94ef97abefd01a30649e8c8ac497b27fc7d9a6", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xfcd346c7219b7697bd07956e48b347aba0a4d80eaf30c6d26516913c4fdcc18a", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x58a87ce6c75938b6dc28b4f35a6d37dd2c6054d7e33fed9a2218b2ea3530bf3f", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xe69b6012c385e2d2ef05a565eab6d9718035e9ebbf45f913c25f7fdaa8b32495", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x37e82390d17d9359b12421f823b3641f70ffda00505a00a328a201cabd536c4f", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x084321871ea7833360460d033aea4fee0a57dd8f2a5bb2d3b94e45cf20d22c86", + "rule: value @ 50000000 | keccak256=0xed189c7eeeed8e5dd29d336c80788cb92c7122d3ce6cfd276add6b65b1c0e744", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x1374e9f5c5606dc33b9e0de9a549d91f3d2642708f64b1bbb2c721e091ccd90a", + "rule: arguments that do not decode @ 50000000 | keccak256=0xefcbdca025b7346be336a559f602944ccf95df45afc311abfe135f3ad62e2334", + "rule: malformed transaction @ 50000000 | keccak256=0xe0bc6ce2532d69489b226d57ccf131da9b53ac2d74d3811195ea37bf2409bd4b", + "rule: a trailing byte @ 50000000 | keccak256=0x89185bdb0398b537bdf0c53e35cb15fbc36eb37c0af62aedf57565321f3b4d33", + "rule: not a creation @ 50000000 | keccak256=0xcd47efc68e4a451ba199ea4f53d28429ab76cf93b6489e56597b7edbfb6904ac", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0x0a868bf16a84248cc1f82b0e98d3abf3649a2488a90819855a40d4b939b76acb", + "rule: signed at nonce 1 @ 50000000 | keccak256=0xc9f1d5643ee4c436bc4b35a6633976c181d165908f1c6090604c8c9c8fda0187", + "rule: override below the signed gas limit @ 50000000 | keccak256=0x9719bee4e4b7c04d83996edda684ff3eb7b3ea0e78e4ba895e7d17d19f947c50", + "rule: invalid signature @ 50000000 | keccak256=0x9c89a2fdcf04d939a423a88dd49a1b768d6077b9f8f2522356cfc3d6c867179d", + "rule: signer nonce 2 @ 50000000 | keccak256=0xfa803ed7347266b5dfdc7ceb39c9900eaf071a82907f920608da3e4125872e03", + "rule: signer with code @ 50000000 | keccak256=0x8de0b8aeda4439a6a2da9e703bdbadf8623569fa5251fc9c5a04d233114c9d3e", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x36072a1358b36e0bbce5410e4c9bce3a402420bfc1d90ee3ff2309db225c7707", + "rule: occupied address @ 50000000 | keccak256=0x9b18cd74a33ca932458e51b1bdde82f5cdbd1f33d7220cc4c2aa9a5880f251ec", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x34b895ca57f6479e79a2e4febb6b3b2b0169094e5d5c467b47233b9854840e8b", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xc63b78ea0a2d879ed3b2c58201adf2d3a71fd0db64cefefaaf24d1f946a547c9", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xba32dc248914023b3675c39d9f4e5b33b9e244a782acc04d91492a06bf40d5c6", + "deploys from nonce 1 @ 50000000 | keccak256=0xb71cfff15098af3b7ef331cfdd948acf5ccc89832795b92a56aa0c3037faa5a8", + "the address already has a balance @ 50000000 | keccak256=0x0099867632ae70916a2c5ee1bb9a4c3bd394baaace1a9050c9fcfd97c8428f44", + "moves value @ 50000000 | keccak256=0xe209cb85c1d22fc2501a4e39efda60c77b519179df532bee4b00084d0a06613a", + "moves value from nonce 1 @ 50000000 | keccak256=0x903966e1ca862223b424ee76a3c230280b4718dd6832c262b8cea073fd5f5d84", + "the CREATE2 factory @ 50000000 | keccak256=0x4fb34c9c95959f80b785be7c891d48ae24658fdadc83153a3863288bc831c00e", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0xca5a0b69bb7daeb4fa68706dbd2668625470ff287ee58f2157119e2368161313", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x6ed9660d22c158fe12707e9952d42d1ef541e845b014f5a373bd1a11f87a33b6", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xa8c49ad6fcd9541260a927e41b91d0f3ab7c18909d0298197448c74601abf4b3", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x137cac9b7879905d0f0d2365a8b1e74cc1542b0abd950cf9a390872df6d88cf9", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x399a23f4764fd765452727eb99e61b70730a1a9c615389d46371b497fa26c8db", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0xbf3e2a32ffdaa16303840d833ca1cb576a3c71c620d345902472034e942da25e", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xb259aee992ff6804b08d04cff45903dc7b0f7cd341b1a0ab85ce9f685ba23076", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xe4b9fd45093754c1789929c29ae89372adc7f619a6e53efc12e1208d6bf92d93", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x0f76882282c61442e4617520f832a4dd5257aa09ec5af3ffd21249266f7d9895", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xd2a5d3d7d5663cdec3505226900786880ed8a9d8b930b0fcbcc553a05a7f6489", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x9656765cc164c64cd4f6911930350c687b6f8be809f362f91aa93f831547e42d", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x05a18de3af0220b4b445eccfadff815b5bd47ee5a3327808a88df0a8e2428c0f", + "a constructor out of gas @ 50000000 | keccak256=0x1f06f0bacce78e20e0a31f2da98dace589e45dc12ecd006285623c3afd7fcbc1", + "the signer sends it @ 50000000 | keccak256=0xbe4f5431d407ab8aa82408d7d692c78d8fa973c424744185d06a2249022a1c2a", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x211490668671d7d5728e6ebcc1f63bbb17c72028aa1585a83e0495ff274196c8", + "a delegated signer @ 50000000 | keccak256=0xca8838ec29350a9e962d4447c7c4e1089666a5c9b6644298e6d4bfa3f2d6e57b", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xec187698771f4764fd4cad443b6f739d12907a0e8e0ffcc83c041df8334b1328", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0xa463275cd85183c49deae4248c55f303d069c8927090aa88b6d0570ba4f3dc92", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x3ce68b096260790d267896e42b40a5cf846a228c472ad50fa0c2eaeecad26244", + "limit: compute, nonce 0 @ 50000000 | keccak256=0x4f76bbf8e2d19d3b3b016f422431b52b7a65a75eb756754092d816623ee43549", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x818bd52515fe2eb5439441fa0bb01a6c794604f6988c8944d842dc0ad1ba43c1", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x2fd40fb9c506e7eeba760d8ce2fd6b90ef45a1328c9f149ee73f3da05a534f04", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x94c8dca3ab785105ea8c3d85edae12a79a332409a931999e218a53c225e35aaa", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xb321eff8f52563691cd8c25fb77bb8aac03a1f7f3fd1ba194968e1bc7d7245c3", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x8dcb09bd5b4bc29315601ab8bf0c173b023d2e4b180aa99e0d5e48827b9d8f6d", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x0eee34d1d5b24c45a8932fdf4f980abb931933b69653fefdeaf1897f9630efbe", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0xe853c0a01ced2e02a86de4d4681c6e9d8815d43a9a9fd1a601c551d02ff63aa1", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xc55faf75e6f1b2a8d32a22556fed2ba0e60ea522cc5a942b5254fee5289752bf", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0x919892378222c40706e814a238a1ee4f944b46bb866c6e817f601b25ab75b1d3", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xd4d2aaed70e8037c8a580082c3a455d5b2621458ab2e185757e7f34c134d5094", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x3e77cd1122e5a36a2f263588bc31ee121153522339429c5d22a5a6edd18c2cc2", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x79784d636eedee5ab3156e061522cedd82bd44f40f5ecc31a75a41f7be2974f1", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x2770955b8680edbc970045b5bcfc9dc6b600c85a79d49aaacb5204a17373e53e", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x4016516a62f99801431f01b9ab845454efe2f0bdb8cebaa6b9aeddaf54b10dd3", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x88429a0c2b61cf28a39034867b63f3c1beffeeb1585dec174263c0d022569d00", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x00495742d5b3b72af8bc0edca3c894c807ff0ca253fb4db9d2117682a64006bb", - "not dispatched: version() @ 50000000 | keccak256=0x71a50aa1874824302b03d490d18fad98f4ee6c67c5e070f0f6c612c103c68fce", - "not dispatched: no selector @ 50000000 | keccak256=0x803c0e37355e9089a6b22f814fd5dd49e3fcbee17d268f639980683f9520ff01", - "not dispatched: from a contract @ 50000000 | keccak256=0x1a46ddada15cc027f867ea5dc0124733491439bc3a587799a8d04ae6b82a1015", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x1ed714441d5f5b08e8d82f2a27d53a8cf60560a686928e6850f43db84987ffd7", - "no contract code @ 50000000 | keccak256=0xd070c6166a53661bc3203f16a69707d9e8846b3c1737d22cbfff5a7a5f6f67c8", + "limit: the default limits @ 50000000 | keccak256=0x2def62d04e39a35b14b4be2e338ad3dc270510c8d7e3847912c63cf885b82a4e", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x9ec7a5e1d22042ac9f86ad9810d5878d2a9096ece69f5352196022fd4c7d54bb", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x05b9f2884b907d501d01e5c90194c3f5c4b6ba246c1d52995626ea549e3a2080", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xd7069745c1ed35dd2bf414a1f77de3b9b113c36fb1d6b77b6427ed6a7fb1da20", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x99a7b01006e2a01abd918e3630baf752a24ff1cd81e8d16fbec02fb860cdf96a", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0xfee59c5832c9f11b10a2c18a2d33d8ac4ba88b908a6fbec15579417e75dc7ae1", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x2cbce7f034611662e63f1519031a8991d8fb4c10a81612164173613453d003be", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x1fe4be1bf70fa5acc777b2a5f574484a1180e03fd7a30901df9fdb1fbdb7a6c8", + "not dispatched: version() @ 50000000 | keccak256=0x7f4d23a1eafe330c076c0aeca78b1ddc2f53a92cb986a1ea81fb4f26abfaa597", + "not dispatched: no selector @ 50000000 | keccak256=0x5f74e98e91891821b56eb7739838ddb22299653168e9bd4b640cf65fb5c77266", + "not dispatched: from a contract @ 50000000 | keccak256=0x3cbf321c4a146068f278c69f23d2b58492169a52c801d67503650a84df75b5a3", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0xc2f0751727fd48101a9412df5819ba2c4ae5d9df05d559939fdb3c64609c89ee", + "no contract code @ 50000000 | keccak256=0x8d10a86cd19ec6ff08132e61232b7f1d8104dc16654d704c88c302eb4b81a9a4", "a system call @ 50000000 | keccak256=0x23867bfad6c1f95ee8422b2c15dfb47ab157163fecdb69f6e142f50971b86ea2", - "rule: value @ 400000000 | keccak256=0xb00b12499990c15c1599808de7903b34b5ed9beb8673675a5a9aa77fafa9015b", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x3dcf58fea56c393d9432b8d0ddb70ab27c94f1f397297097116ab93d288638d9", - "rule: arguments that do not decode @ 400000000 | keccak256=0x1e85d077ef72d33c8bedeef7ab6a25396d2045a316422c35a003947d831b924a", - "rule: malformed transaction @ 400000000 | keccak256=0xa14ab3686735b259326aeefd8ffde19e7d03ca5f6710a8278d3c20b3588941c7", - "rule: a trailing byte @ 400000000 | keccak256=0xe3dd6f5f1d180e13aa45ac712b48ae4124f1f24283214c1aa69d30174cb444e1", - "rule: not a creation @ 400000000 | keccak256=0x228398e161b11148e9c04b5732a72a116f61e8682066063a104ac1065d76ba47", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x70e03ab019a3197e2beb416b2733c1fbfecfcb4a65f8426d33c0acdac8240f8a", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x0cb600cae0b629f42c3dd757e88a46f22d4a560e44f3638566453f9ffd5f495e", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x7bdc52f604cdd3f736d5044d4255ad3147ffb3205377c6adaad530fb6c45a342", - "rule: invalid signature @ 400000000 | keccak256=0x89ace74ee50426587d8c4d77ec5e73120ab42ffb793fd90a1a36042bfa6c3578", - "rule: signer nonce 2 @ 400000000 | keccak256=0xe5d29781298581917c3cbb3811521a98a7f1faaa6dc808eb317fc6cbfac7a4bc", - "rule: signer with code @ 400000000 | keccak256=0xe1a8336834a3b2bc39e8ec606532fe58987837155833513489670f5ee48a02cd", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x19d8abae07d5f60cc71d626a2fe05b52f49634f5a9bbd8dbc46eba04b0be153a", - "rule: occupied address @ 400000000 | keccak256=0x9c400b1873c619f57bbce100b0733b6abee2e89fed0634afffbb5170fa5b7545", - "rule: value the signer cannot fund @ 400000000 | keccak256=0xd0f45281316372225586ac044d825ca80e866f48389ab48ebe3076a037091c17", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0xaddfe60e384511929bc3915941afff9ed661f9b9d36eb5597ba64f15bfc62966", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0xbc03379378902229c9993b4430c02703af25c6632886c104493ca8f3a2f0dbcf", - "deploys from nonce 1 @ 400000000 | keccak256=0x9d7e11c1028204bdf6588c73e713b10084c132131312ff827866d63dd4318070", - "the address already has a balance @ 400000000 | keccak256=0x5e7138f7e8ab1a58e38637ee096125f705ac2b72cd4d28123d563bf85e577e29", - "moves value @ 400000000 | keccak256=0x78de09b3f6b8474e0cb7dbd6b14109ef974f219da90eb9237001dd8dd4ad20be", - "moves value from nonce 1 @ 400000000 | keccak256=0x2690289cad93a5c30acdbb39c84faddd0fddbba12c5127619464a141dd1fcd59", - "the CREATE2 factory @ 400000000 | keccak256=0x8fcc1f818461f802fa686a10bcace2b06481553aeaaec17587de4597df3b61f2", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xc13c20e0990cd146c07d62a4841e4bdb4108209cf1c6198557d22b209ce1637c", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xafcfbab9602ba7854d37050b7d9d4de693f7b5155bd9e82ffbe431309634ada3", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x14e4b2ecadf5c5b8de262f29ab527880c3b89f6238751675807c53fe78ff0cc2", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xf02bfc9aa63148fcbbc9a954168625c0be2bd6fb33f83acf227547c3ec11fae6", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x87b86bfafee294f67d1167ea8400b5395d667f8f5d5b48ba09d732a96ba18525", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x07260a9fadf457dd238f0f3731a5c7410ee88ec525ce384b5f0a4aa39759feb4", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0xa0792622b4ea74af6d05f1743376c73106310c58533c1ac129a7b63b978de355", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x2ca62b6c2400a6e5d1beb27ce072fe5a6f76aca8955ad850f481c9c39f0faec3", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x353cfb678009b8a64bcf235bdcab14c59c8e38fa15d77903b57957963e1c50e4", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x829c4a203fe9f614d49a78d00f02dc19d665be5959385f34a08e206d6df86837", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x87e563ac4638ed7a1cb7b28ac746f5fe7529f78beb2f34d331089e3ec5b0a5fe", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x1d754d06fdd43ae1b115f1d8394ecb6157ad0dd01ba6e2204701459ec4f4db7d", - "a constructor out of gas @ 400000000 | keccak256=0x8a165953e7d6b780e095bba69394619c602f95b4572c1b1af3ee37b18cf8be66", - "the signer sends it @ 400000000 | keccak256=0x3c5ed1a7b0f26ec3125e8488415cc4685b9953387eb8c1876adb9006e83bfac4", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xda4adad654303fb7efc3c45a1853248c4353fadb078119da44b7cca407bb697c", - "a delegated signer @ 400000000 | keccak256=0xd1a2bb70319354c0d740f3da55a587c30393154536ffa531e7277488042401bb", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xf5b740432d179042db6967e150b24334f6ebbe89c93463ec21392a10638c8867", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x669c28012fbf83b3fd8e1b4e7f55870a204f03976f759e8a403e8d6d28d4beaa", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xa474fe8793c49f08bba482b9c9bc75f0f58f45974ee479f4a6d84731ac0968dd", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x40d23c09775632cc70ddc91895b903311247acf7af67f94c12af1e732399a48a", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x4d4a97c2a94ff55a369d67540f7ef37a9a09eb2bebcfa283ebb93661a1b4b21f", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x7c84b6ab291fe88f6d9824e8b944804ed070bd6985c2428026a546466e80b464", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xd0854bb20fdf914624a7119d0fd53f57d1a97ea3cf491e00cf238cd01bd7babd", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x22575bf011874b0d59ac9b2e43a59a5a21dc4b123150bc1272bb599ff2a464dc", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x0af21d7722fa8d4326b54c604d9dd6860d75a1e99aabfe7311c3595bcdbb232f", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x15f213ecf86068b2a34ab80a0b6b7536184bed6652c6a4437663e67052e8acb6", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x5a7032e41e19498cd7dc56c2c2cd9d3c3d239bbb3943bcbd1fc2218cb4227562", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xd9851d97da36ec9bd032e42b9ea43ac1b31d630e5a5278f8b783ed25d9d53d5e", + "rule: value @ 400000000 | keccak256=0x5e79260aa4edb3cbeb0cf77188c06d28c86f0ebd643a21ce24d977193cad79f9", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0x1514a40446fce26f4b03cf1ca7ecf7cf4971a242c5db0790f810b5a1e84f0267", + "rule: arguments that do not decode @ 400000000 | keccak256=0x1131b4f79c395ae33bf3a8262232af01661405d97d50474681b0727ab83098cc", + "rule: malformed transaction @ 400000000 | keccak256=0xd3652f7fda35b00e1f92f1f3516b3cd62ad029942c5dc785b83c732641bfb49e", + "rule: a trailing byte @ 400000000 | keccak256=0x64e10315c1a4e287c9a3192a5947c645fa70c15e996f44611aa267598f81ae6b", + "rule: not a creation @ 400000000 | keccak256=0x0c6d4f8979ad2849d17e4213e426cb3af61b8f2a7a1da7954f4839e329c21abc", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x67c0ddf3c12ccb6eaefe47f7fae97d10f4673059644b2725334cb0ce95f516f2", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x06e5fe6e658d2f0bcecaa4542d46bf38e5161628bf6b3f99b31b22dc449507b0", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x8797806de4ff58f55e05e6378e23b55ff15835e8c8beac2cd7366948b4aabd82", + "rule: invalid signature @ 400000000 | keccak256=0xacdfc51cec2456661477ef479c26bca13a01af86e83a171a77d963585576de82", + "rule: signer nonce 2 @ 400000000 | keccak256=0xe348576409b722912e483d9349fd102b83d0ab32a391bca82d0b8989a364cb64", + "rule: signer with code @ 400000000 | keccak256=0x2f6ea1a2bff4f3bd77c893e6f4099029347dcf6c7a4438f7379ea01c9c139454", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x367bf9d3ffb7800cac9fb35aadce3f53a15fedacead949683eabb942df9bae43", + "rule: occupied address @ 400000000 | keccak256=0x587d4340e585bc4167812dbbeccffabc3a328e59ce93e739214d80c9e4279c9f", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x22e2eb96dc428e9b56d0bbb2db54065bf25d1e24dc60d74f42811e1abc4c102a", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x86eda7b77ed36f78327f3fead125101a7af2cad6acaa7fda9f94ce3e222f3874", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x18fe8084ffa1603954e5c86d7a11dfe437cb3ff907082774b679ec53472ea11d", + "deploys from nonce 1 @ 400000000 | keccak256=0xf17fc6bbd24ed22f5168e762e670b27631aa7731c642db2422e588db4c78c7fa", + "the address already has a balance @ 400000000 | keccak256=0x81b6b72e6c865d30396e740630e92bcf4ea1c3f3c2b32b2740dd211f59159bad", + "moves value @ 400000000 | keccak256=0x2244a92d12bd9461aa3d816792a8fc056ec68cf84b1eaf45cfa3bf9ecc4a8f92", + "moves value from nonce 1 @ 400000000 | keccak256=0x8a5b3343385da3497e8c512907270093271b9af424697ec5437fbb606173b46b", + "the CREATE2 factory @ 400000000 | keccak256=0x8e30a83ad199d70986b07392806eb3a674f7f774aa91a8be1b2348aad3f9cf8c", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xb6a3582be383b08673e2d3ce96e40ed86feb021d9db29c1cf4677888a6afe623", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xe46c0daccc99c1fe5aa298d8acf141478f7e2dd2fed7012a7a1b808ab7c80359", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x05871c11861c779e4b1e469cbf3555421422584a9839b625e4176590d507a1a6", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xe0704e67041eddf1b660fb725d4dfe17248c74f675459e66f92a5f56dcfd2e9f", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x0486ca94e1bd9eb2f97a571d84ab2a8b3772e4c09dd7f0497c8fc2a77e437f89", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x8921a10572f46b590c07175a4e1b685b31de776819aba39ed962dc0abe2e4247", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x572d043ab65f8b4cb9303d210e83b5a4518327ee91f20737b058e3d2684f9839", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xf7b86dd138d62cd4a2430f837ee7b18bbc3e268db9d103df358388c91f7ecb1c", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x7ed8fe16e5201e73f1e887af149703e4968d789986d1ba9a8cac2fb064f8174d", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x0bfa315b628012e0c3e9302bdae076786327adf5e3df6ba1227bb82aaa9bd04e", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x58d758de8d8633087cafc83f7f31d0c44d5667153be9ea6ecc310a30d53d7566", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x61b20d4539f44a202ed546b21a3fda3b0fed6ca5b4e787e417fd9fb9bf614d93", + "a constructor out of gas @ 400000000 | keccak256=0xba070437ea72e930ce03758b4360ac23acff6bb2d6e26b90f5296b39c58331b9", + "the signer sends it @ 400000000 | keccak256=0xfb559cc69b49810cdea188ca17eecce5bbb82e90e8ab501724decf9ace8d9b8c", + "the signer sends it, and it reverts @ 400000000 | keccak256=0x29d0ac1c7b1eeb2550cd76bd348f07965f019408aae2f48781f777b661c6a5a9", + "a delegated signer @ 400000000 | keccak256=0x64e33e9a061f57757524981b6ebf97a4766fe9d8f6f7fccb2eab7a908d0a8b14", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x194b74050491454fcaec69a0b8c3efde007605f96facf274366f80e26fd19123", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x0ce6c4dce9acfeffb5dbd78120ef598f13a3dd0e08732f22b6ce1e8de84d7c18", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xbd010fcb4c8aae97e2384ac55bd75d3baabfb99749c5b58ac8e8d219f0b8a7be", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x90590758bcd4589315591b1f92b20d39ff984dcfc232dc0b23d2ef271515d557", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x29d1abb3ef4600b75825fcfdfded00658c5148da33c178e6c82162ec52c2d050", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x2f8331f68d64394e00890a3ea84ff803292523ea3cec78beda507612342d5d1e", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xc2a3fd9d99371c50cb127fc4070d3254965d001bf6c0bde1dfa001acb97a3232", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0xf108c18b8834862f0a6613cd3a6b10884a696813aa86d7887ef423b92291f29e", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x0293bb937c1028dd8da7c5d08331177342dbc2b6154e82af703c20cabb2bb5b0", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x7e2370edf23d4c02adf0c4c02d8a84311d818ebe75cb77ff510ecba84ec81f9b", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x243da14fb2e4e456219e155ced7b47511492287ad93ca38037b13478b9cc5165", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x754211349a8986b2a11b94c209b0c536b37bb450a73a33bbf232458d23d214d5", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0xc0d3aca720daba088d71be9f88183cae938edef047c5bfdf498b17c5d75953d7", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x62d2175645da243a667798024fc434fa9d12ccb3b03d1f1aee814fc6be569122", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x7dcb32ba5e7bb600eb771f257101f5d98a53232efacf4e1d02c78c481d7a029b", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xa3feede8f1b69038dd7d5c942bb6d211494b5ddc0c5bdfd370a937da02fd315f", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xf768d159e67a14db48c7540608fd0ce6a0d5820b4f2b07465be1d577b80be8f8", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x5367a815bbe23e5d0f6465c233f44921672d6f79f6ea37d2695361a2528684fb", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x2066b1925807f12c83de2fc0243297994a28cd2ca298c710ffd2ccd90446916f", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x98f07a08f6e0392985b7c2541ea2baa5b9cf4a33566edf9e51d2ab7fedb97ee8", - "not dispatched: version() @ 400000000 | keccak256=0xb3d9e971f62fcc67aac97321c2adce9d671ab5a2069e2684de36c3475da7efd9", - "not dispatched: no selector @ 400000000 | keccak256=0x133abd242588d520143eabdedfa24c00e2ee1f392efb12e3af58cfce3a051ff5", - "not dispatched: from a contract @ 400000000 | keccak256=0xe273d69f5c4a40d8e1a2baec6807bc7cbc14f7466aa7da1d628cf84050b4afcb", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x8bb00c81518baaebed8e7d465cac07eabd9bb8fd1f2168bb675181bf6f281803", - "no contract code @ 400000000 | keccak256=0x57a5964833c89bbee89ffcf23e1585a9720f831ba488301937f16d28627c58d7", + "limit: the default limits @ 400000000 | keccak256=0xcece1e3ee7bcc7ce421e4d4a1bf1fb5d963d077fb0ca8872fd2ab9b7f1fdf64a", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x460ae101add3b3ddb5db9509d5078cc8329fbec4e0490d47a71a1093eef9c048", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x6215d89b8bdb4bef28b65f155ad607a96c5e9cdbd30606bd40bd3b90470422e6", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xe836b00bf5490f7ebbc565cf75ff77d56f125e5d449f3babe8c5f45e143c2cd2", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xfed47fb99c9ebbf3f84315b06374e933e9ce0a66626798d6b5a2b6a5bd880f24", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x049d76e9c7c973a8a9753554a2ba3c5af500aa23bcfdbf43cab1dfe8edc7e6ca", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x83ba653c00a67a52dd9defce80aee9942764d9edffe45c90908aea73c58dca57", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x4f7462da9d5f7330758ffb64f1c31484d20ead3e653b8f6ffd69377695ebeec7", + "not dispatched: version() @ 400000000 | keccak256=0x49ddb05d741a6d8474b550a05e7ddba4265eb52e89521685ef255cadbac74f79", + "not dispatched: no selector @ 400000000 | keccak256=0x470e43c3cd3337008b7a34d0477a4dcc0abc98650b8fb1ce70f495e7ebbaa0be", + "not dispatched: from a contract @ 400000000 | keccak256=0x8a2c8808e1f314bb9bf6004b0b52dba601e719dc5f3b72be8d1686dc130f59e9", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x26db781c04e7074540231552ed12115f5edfec29381ed21c2e8be69a9ef1a24d", + "no contract code @ 400000000 | keccak256=0x04e93af30d9d1db5f89de85039bb003f285fdfe53465b8952af9e39ac8fc0c7a", "a system call @ 400000000 | keccak256=0x9a9e25f65352a78b4821e39a66d1621bbd6d0fdf1e14955c05be3733619934da", - "out of gas: the overhead @ 161535 | keccak256=0xc83eefbcd1c2bd1b79b3bb8de86da7fa9a024240d70675258b1dd465a0af9d08", - "out of gas: the signer's account @ 162536 | keccak256=0xabd1dd2575c43ad8db140cf5cf3a148138a8c09f632e3dbbe7522fbc8e3c1b72", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x89fd19771ed21bd9962d7a115102f72550e3fa2c983ea297787794afda42709b", - "out of gas: the creation's charges @ 163024 | keccak256=0x19c6965f489129ac0afbece2fee046674d4d433a89910040f2e77fcf2caa7c9d", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0xd7f16815dab34f0f28d789cb6cbccde59e3d655ba31700b55f8d9bf38b1a39a5", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0xafabbf8e69b4ee84877639db23817337ab163d602a795fa6e13f2bc7a95976da", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x031b252c8c04569195a8bea5d8bf730d57440fa07b21674f4ceb3656b0fb6bba", - "rule: init code over the limit @ 150000000 | keccak256=0x9847bb9edead678c560d676d258c01854a0d882b495854a9e7ea7923bdfffb94", - "rule: init code over the limit @ 2000000000 | keccak256=0xf7949b8ae857d9eb689ab1a96b0795d150698f13795c880b330fe388ca949434" + "out of gas: the overhead @ 161535 | keccak256=0x9dbc27a7d38413c4d3d2540830f865242b6f94a43aa7b7118594cbf21fbf5d26", + "out of gas: the signer's account @ 162536 | keccak256=0xa4741e855ff7b3481381507473d4d39e0c3e5771457abff812f9cefda1a806dc", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x7daeb19e1a8c6caeb5420a3d6760eb0a4e31964dcb865876016c2238e0a5d828", + "out of gas: the creation's charges @ 163024 | keccak256=0x0f024ce4ee6396c00110ec2b3d621e8d0e8339c76e100d1f3edffa1f54415f34", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x1857f44dafecb6b897303320f713505b71ec790a75ab0462f05b792d88c341d2", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x570a35db9318b219a0d4e27766b35a5ef6bb14c127fb60b94da2c4b7f4e3eab8", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x424226cb0b33379240c427377972f9e8536eb87e6400a87345853b792984b2e2", + "rule: init code over the limit @ 150000000 | keccak256=0x3641cddfcee643292efb2040784411281dd54f75be4d955503ddd9fd88d2b955", + "rule: init code over the limit @ 2000000000 | keccak256=0x6b55109f7731d8011cc7527a5ffa4a9511522a37e2b3b37b3f801c89cd50d8c3" ], "summary": { - "bytes": 2451324, + "bytes": 2284360, "cases": 139, - "lines": 11482, + "lines": 10402, "runs": 556 } } From ca455a5c5e660b6217bc9c14e06e18955f38ea51 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:42:16 +0800 Subject: [PATCH 069/190] test(state-test): a standalone transaction's channel witness carries the EVM's system address read --- crates/mega-evm/src/test_utils/witness.rs | 11 +++++++++++ crates/mega-state-test/src/witness.rs | 3 +++ 2 files changed, 14 insertions(+) diff --git a/crates/mega-evm/src/test_utils/witness.rs b/crates/mega-evm/src/test_utils/witness.rs index cf1a54c11..137c8a137 100644 --- a/crates/mega-evm/src/test_utils/witness.rs +++ b/crates/mega-evm/src/test_utils/witness.rs @@ -106,6 +106,17 @@ pub struct WitnessKeys { } impl WitnessKeys { + /// Adds the keys of the read of the live system address an EVM built outside block execution + /// makes off its database when it is built: the `SequencerRegistry`'s account and its + /// `_currentSystemAddress` slot. A transaction run on its own reports the read in no state, + /// as a block reports it in its resolution's pre-block state, so a witness built for it from + /// its returned state alone carries the read through these keys. + pub fn add_system_address_read(&mut self) { + use crate::system::{storage_slots::CURRENT_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}; + self.accounts.insert(SEQUENCER_REGISTRY_ADDRESS); + self.slots.insert((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + } + /// Adds every account and slot `state` names. pub fn add_state(&mut self, state: &EvmState) { for (address, account) in state { diff --git a/crates/mega-state-test/src/witness.rs b/crates/mega-state-test/src/witness.rs index 96d82bdd8..5cdfef755 100644 --- a/crates/mega-state-test/src/witness.rs +++ b/crates/mega-state-test/src/witness.rs @@ -177,6 +177,9 @@ pub fn check_replay( }; let mut keys = WitnessKeys::default(); keys.add_state(&outcome.state); + // The EVM read the live system address off the pre-state when it was built, outside the + // transaction. + keys.add_system_address_read(); let buckets = recorded .bucket_ids .iter() From f0c1586bfbbd9e021d3c01e71fc5d983844c779e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:42:51 +0800 Subject: [PATCH 070/190] docs: every block deploys the system contracts and resolves the live system address once --- AGENTS.md | 60 +++++---- crates/mega-evm/README.md | 19 +-- crates/mega-evm/src/system/AGENTS.md | 32 ++--- docs/mega-evme/commands/replay.md | 2 +- .../mega-evme/configuration/chain-and-spec.md | 2 +- docs/spec/hardfork-spec.md | 4 +- docs/spec/upgrades/satin.md | 125 +++++++++++------- 7 files changed, 139 insertions(+), 105 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2d256bfef..a8eb8cd4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,23 +132,23 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - Display and `FromStr` use `"Satin"`; serde uses the variant name `"SATIN"`. - The legacy spec names (`Equivalence` … `Rex6`) parse to `ParseMegaSpecError::Legacy`; they are never mapped to Satin. - There are no spec gates yet: with one rung there is nothing to gate. -- The next spec is added as the legacy engine added Rex1 (#115, eleven files): a `MegaSpecId` variant after `SATIN` with its name and its `into_op_spec` arm; a `MegaHardfork` variant that activates it, and a params mechanism if it is the first fork to need chain-configuration parameters (Satin carries none); an `is_enabled`-style ordering on `MegaSpecId` and a gate at every site whose behavior changes; the constants it changes, keyed by spec, a limit it changes as its own arm of `ProtocolLimits::for_spec`; and its upgrade page under `docs/spec/upgrades/`. +- The next spec is added as the legacy engine added Rex1 (#115, eleven files): a `MegaSpecId` variant after `SATIN` with its name and its `into_op_spec` arm; a `MegaHardfork` variant that activates it, and its chain-configuration parameters beside the schedule if it needs any (Satin's are the `SequencerRegistry`'s Rex-era bootstrap values, `MegaHardforks::sequencer_registry_bootstrap`); an `is_enabled`-style ordering on `MegaSpecId` and a gate at every site whose behavior changes; the constants it changes, keyed by spec, a limit it changes as its own arm of `ProtocolLimits::for_spec`; and its upgrade page under `docs/spec/upgrades/`. From then on Satin's behavior is fixed: a gate keeps Satin's path as it is. The extension points it builds on are already in place: the spec argument the factory and the context take, the per-spec limits table, and `into_op_spec`. ### Core Source Layout (`crates/mega-evm/src/`) -| 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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 executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, and refusing an absent parent timestamp where the schedule activates a fork after genesis that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `MegaTransactionExt` (`helpers.rs`); the reads of the L1 block contract the fee computation and the footprint make outside every transaction's journal, reported once each per block as read-only entries of the returned state of the first committed transaction that made them, never in place of that transaction's own entries, so a witness built from the committed states holds what op-revm and the executor read on the database itself, and a block that reads none of the contract reads nothing of it; every outcome carries its reads beside its returned state (`L1BlockReads`), and the executor that commits it settles what the committed state reports against what that executor has committed (`L1BlockReport::commit`), whichever executor executed it (`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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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 start ledger's settlements, which a test records and reads (`record_start_ledger_settlements`, `take_start_ledger_settlements`, `LedgerSettlement`, `LedgerPools`); 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 parked on the start ledger as the start's charge, with the frame's budgets, history allowance and reservoir share (`forward_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 pre-block sequence in `apply_pre_execution_changes` — the EIP calls, the activation block's check of the EIP-7997 factory, every block's deployment of the system contracts, the `SequencerRegistry`'s due changes, its deployment and the resolution of the block's live system address, handed to the EVM — with the commit of each step's state on its own, and the executor's own derivation of whether a block is Satin's activation block or admits only deposits, from the schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`), made once when the executor is built, neither for the genesis block, and refusing an absent parent timestamp where the schedule activates a fork after timestamp zero that is active at the block (`MegaBlockExecutionError::MissingParentTimestamp`); `MegaTransactionExt` (`helpers.rs`); the reads of the L1 block contract the fee computation and the footprint make outside every transaction's journal, reported once each per block as read-only entries of the returned state of the first committed transaction that made them, never in place of that transaction's own entries, so a witness built from the committed states holds what op-revm and the executor read on the database itself, and a block that reads none of the contract reads nothing of it; every outcome carries its reads beside its returned state (`L1BlockReads`), and the executor that commits it settles what the committed state reports against what that executor has committed (`L1BlockReport::commit`), whichever executor executed it (`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`, and the three bootstrap keys a configuration that schedules Satin carries, 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 start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), 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 class it begins an execution as (`TxClass`: the protocol's own work, a deposit, an ordinary transaction, or one under the neutral configuration), which the exemption and whether the transaction pays history follow from, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); the start ledger beside it: what each open frame start owes and holds — its three budgets with their nets, its start charge and its history allowance — by the engine's own rules, driven by the start lifecycle hooks alone, which decides a frame's budgets, gives a failed start's charge back and grants the allowance, and the share of its caller's reservoir a start takes (`reservoir_share`) (`ledger.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`); the pool ids and amounts of a frame's three budgets (`PoolId`, `PoolAmounts`) (`pool.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 —, every block's deployment of the five flat contracts, and the check of the factory Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, its bootstrap values, its deployment (seeded, migrated from 1.0.0, or refused over other code) and the once-per-block resolution of the live system address, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the lenient read off a database an EVM built outside block execution makes when it is built, and 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 every block's deployment then only reads: `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 start ledger's settlements, which a test records and reads (`record_start_ledger_settlements`, `take_start_ledger_settlements`, `LedgerSettlement`, `LedgerPools`); 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 @@ -252,8 +252,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 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. + Satin's one chain-configuration parameter is the `SequencerRegistry`'s bootstrap values (`system::SequencerRegistryBootstrap`: the initial sequencer, the initial admin, the minimum rotation delay), under the keys the Rex era introduced (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`), which the schedule carries (`MegaHardforks::sequencer_registry_bootstrap`, `MegaHardforkConfig::with_sequencer_registry_bootstrap`, the chain table's for mainnet and testnet) and only the registry's deployment reads, to seed a registry the state does not hold or migrate one from 1.0.0. + A genesis file's `config` object schedules Satin by one key, `satinTime`, and carries the three bootstrap keys beside it, and every reader — a node, a stateless validator, a genesis generator, `mega-evme --genesis` — reads them with `SatinChainConfig::from_genesis_config` (`block/genesis.rs`), which refuses a configuration that schedules Satin and lacks a bootstrap key or gives one as zero, any other key starting with `satin`, the registry, `satinInitialFromBlock` and limit keys of the format's earlier versions among them, a value of the wrong type, 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::is_exempt`, read off the class the layer begins the execution as, as `MegaContext::prices_history` is), 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 class is decided when the layer prepares a transaction or a system call, so a transaction set on the context and not run yet changes neither the exemption nor what it pays. @@ -275,15 +275,16 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 hold it as any other non-deposit transaction; admission and the commit-time check exempt only `is_deposit`. 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`). - `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), and applies a role change the `SequencerRegistry` has due in the block (see the system calls below); it reads nothing of the L1 block contract. + `apply_pre_execution_changes` commits each pre-block step's state on its own, in order, before the next step runs, 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 (neither in the genesis block, whose parent beacon block root must be zero) it checks the EIP-7997 factory in Satin's activation block alone, deploys the five flat system contracts, applies a role change the `SequencerRegistry` has due in the block (see the system calls below), deploys the registry and resolves the block's live system address last (see below); it reads nothing of the L1 block contract. op-revm's fee computation and the executor's footprint read read the L1 block contract on the block's state rather than through a transaction's journal, so their reads land in no transaction's state; the executor adds them, once each per block, to the returned state of the first transaction that made them, as read-only entries that never replace the transaction's own (`l1_block_info.rs`): the footprint read — the account and slot 8 — with the first non-deposit transaction, a Mega System Transaction included, and the fee read — the account and slots 1, 3, 7 and 8, and the overhead (5) only when the Ecotone scalars it finds are empty, which a deposit earlier in the block decides — with the first transaction the fee computation prices, read again through op-revm's own fetch once the first transaction the executor prices in the block ran, on the state it ran on, whether or not this node's op-revm fetched it, and carried by every transaction it prices in the block, as op-revm prices them all from one fetch. Which transaction is first is decided at the commit: an outcome carries its reads beside its returned state, which holds what its executor would report if it committed it next, and the commit takes that out and adds what the committing executor has not reported, so an outcome another executor executed, or one executed before another commit, reports each key once, with the first transaction committed; an outcome committed where it executed, before anything else was committed, is committed as it was returned (`tests/block/witness/state.rs`). A failed fee read is a failed read of the transaction's execution, routed by whether the database declares it fatal; a failed footprint read is always an internal error. - 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. - The block in which Satin activates reads the seven in order, and each must hold exactly Satin's code, whatever its nonce, balance and storage (`check_system_contract`, `system/predeploys.rs`); anything else — no account, no code, an older version, other code — refuses the block with one error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and each read is a read-only pre-block state. - The executor works out which block that is (`MegaBlockExecutor::is_satin_activation_block`) from its schedule, the block's timestamp and the parent's, which the node passes to `MegaBlockExecutionCtx::new` (`None` for a block with no parent, which is no activation block); no other block reads the seven. - A test or a tool that runs a Satin block on a state of its own puts them there in the shape Rex6 left them (`test_utils::rex6_predeploys`, `MemoryDatabase::rex6_predeploys`, `SequencerRegistryRoles`). + The block-side classification of a Mega System Transaction reads the address the EVM holds, which the pre-block steps resolved (see below). +- Every block deploys the six system contracts, as Rex6 does, so Satin may be active from genesis: the Oracle (v2.0.0), the high-precision timestamp, `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl` are each installed where missing, have their code replaced, nonce, balance and storage kept, where it differs, and are committed as a read-only entry where they hold it (`deploy_system_contract`, `flat_system_contract_specs`, `system/predeploys.rs`); the `SequencerRegistry` (v2.0.0) is read when it holds v2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the bootstrap values where its address holds no code, and refuses the block over any other code (`deploy_sequencer_registry`, `MegaBlockExecutionError::SequencerRegistry`); a block that must seed or migrate it on a schedule without usable bootstrap values fails with an internal error (`MegaBlockExecutionError::UnusableRegistryBootstrap`). + On a chain that ran Rex6 every deployment is a read-only entry. + The block in which Satin activates also checks, before the deployments, that the EIP-7997 factory, which OP's genesis tooling preinstalls and nothing deploys, holds its code, whatever its nonce, balance and storage (`check_system_contract`, `create2_factory_spec`); anything else — no account, no code, other code — refuses the block with an error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and the read is a read-only pre-block state. + The executor works out which block that is (`MegaBlockExecutor::is_satin_activation_block`) from its schedule, the block's timestamp and the parent's, which the node passes to `MegaBlockExecutionCtx::new` (`None` for a block with no parent; the genesis block, number zero, is no activation block); no other block reads the factory. + A test or a tool that runs a Satin block on a state of its own may put the predeploys there in the shape Rex6 left them (`test_utils::rex6_predeploys`, `MemoryDatabase::rex6_predeploys`, `SequencerRegistryRoles`), which the deployments then only read; code a test plants at a system contract's address is replaced by every block. Three of the six system contracts have interceptors (`system/`) — `MegaAccessControl` and `MegaLimitControl` answer, the Oracle's forwards a hint and lets its bytecode run, or answers a hint that would cross the data-size limit with the stop — and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless dispatch before interception. A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input; an unknown selector is not intercepted and runs the contract's own bytecode. `MegaAccessControl` steers detention's switch for the frame that calls it (see Gas detention), `MegaLimitControl.remainingComputeGas()` answers the compute the calling frame could still spend, and the Oracle forwards a `sendHint` payload to the node's oracle service. @@ -322,14 +323,15 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` are gone from the Rust enum and from `IKeylessDeploy.sol`, which changes no deployed byte: the sandbox's preflight and validation are gone, the overhead is regular gas a call that cannot pay runs out of, and a failed read or SALT lookup fails the transaction with its cause. `tests/system/keyless/interface.rs` holds the generated binding's errors to the set `docs/spec/system-contracts/keyless-deploy.md` lists for Satin. - The system address may send transactions the protocol pays nothing for (`system/tx.rs`): a legacy transaction from it to a whitelisted contract is validated — the chain id, which it must carry and which no configuration switches off, the nonce, EIP-3607 — and promoted to a deposit by the engine as it runs it (the block decides on the legacy envelope: see the block executor above), and the account a deposit-like transaction creates for its caller is charged the account-creation state gas once. - Which address that is, the `SequencerRegistry` says, and the transaction reads it itself (`system::load_system_address`, called first thing in `MegaHandler::validate_env`): every transaction, whatever its shape, loads the registry's account and `_currentSystemAddress` with revm's own loads, without the registry's code, and the two stay warm for the rest of the transaction, as EIP-3651 leaves the block beneficiary, so what a transaction pays never depends on its envelope. + Which address that is, the `SequencerRegistry` says, resolved once per block after every other pre-block step (`system::resolve_system_address`): the registry's account and `_currentSystemAddress`, read off the state without the registry's code, committed as the block's last pre-block state and handed to the EVM (`MegaContext::set_system_address`); a registry that is absent, holds other code or names the zero address refuses the block (`MegaBlockExecutionError::SequencerRegistry`). + No transaction reads the registry for its classification (`MegaHandler::validate_env` reads the address the context holds), so no transaction finds the registry warm or carries it in its state for that reason, and a transaction that reads it pays the cold price. + An EVM built outside block execution reads the address once when its context is built (`MegaContext::new_with_external_envs`, through `system::live_system_address`, directly off the database), so it needs no setup and charges and warms nothing; a read the database cannot serve then is made again by the next transaction, off the database, which fails with the database's error if it fails again; `MegaContext::with_system_address` hands an address in. A transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — whose caller is that address is a system-address transaction. A transaction from that address without the system shape is invalid (`system::SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`, an `InvalidTransaction::Str`, so a pool and a block reject it, and op-revm includes a deposit, which never has the shape, as a failed deposit); every other sender is an ordinary one, an address a rotation retired included. - The read is an untouched entry of the transaction's state, which a commit skips, so it moves no state root; the comparisons with op-revm and Ethereum take it out first (`test_utils::take_system_address_read`). The Oracle's `onlySystemAddress` tests the sender alone, so the refusal is what keeps the system key's other transactions, an L1 deposit from it included, from writing the Oracle; the legacy engine refused them with an error that is not a transaction's, so a deposit from the system address left its block unexecutable. - Nothing inside a block can change the address after the block's pre-block call — a change is scheduled for a later block and applied by that block's pre-block call — so every transaction of a block reads the address the pre-block step left, a rotation governs its activation block, and an EVM a node builds outside block execution (an RPC call, a trace replay) reads the one in the state it runs on without being told. - 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. + Nothing inside a block can change the address after the block's pre-block call — a change is scheduled for a later block and applied by that block's pre-block call — so every transaction of a block is classified against the address the pre-block steps left, a rotation governs its activation block, and an EVM a node builds outside block execution (an RPC call, a trace replay) reads the one in the state it is built on without being told. + Outside block execution 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 there; block execution refuses such a block. + The resolution is a pre-block read, so the slot is in the block's pre-block witness, not in any transaction's state. - 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 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. @@ -761,11 +763,11 @@ When the agent is requested to implement a new feature or bug fix, it should con CI's msrv job checks the workspace on 1.94.0, every feature on, with the lock as it is. A dependency whose newer releases declare a newer compiler (alloy 2.2 and later declare 1.94.1) stays on the newest release the declared version builds: `.cargo/config.toml` sets the resolver's `incompatible-rust-versions = "fallback"`, so a `cargo update` run in the repository picks it. - **Pre-block helpers return their state and never commit.** - A helper that takes part in `apply_pre_execution_changes` (the activation block's check of the predeploys, the pre-block system calls, the registry's due-change read) never calls `db.commit(...)`: it returns the prepared state — an `EvmState`, or a `ResultAndState` for a system call — and the executor commits it on its own, in order, so the sequence of committed states is the witness a stateless client needs. - A read that changes nothing (a predeploy holding Satin's code, the registry's pending slots) returns `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. + A helper that takes part in `apply_pre_execution_changes` (the activation block's check of the factory, the system contracts' deployments, the pre-block system calls, the registry's due-change read and the resolution of the live system address) never calls `db.commit(...)`: it returns the prepared state — an `EvmState`, or a `ResultAndState` for a system call — and the executor commits it on its own, in order, so the sequence of committed states is the witness a stateless client needs. + A read that changes nothing (a system contract holding Satin's code, the factory, the registry's pending slots, the resolution) returns `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. Returning nothing there is a bug — the account disappears from the stateless witness read set. - A step that writes includes every account and storage slot it touched; a predeploy holding other code is an error, never an overwrite. - `system/predeploys.rs` holds the predeploy check, `block/eips.rs` the EIP-2935 and EIP-4788 calls, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, and the block executor is what commits them. + A step that writes includes every account and storage slot it touched; a registry holding code it cannot migrate is an error, never an overwrite. + `system/predeploys.rs` holds the factory check and the five flat contracts' deployment, `block/eips.rs` the EIP-2935 and EIP-4788 calls, `system/sequencer_registry.rs` the registry's due-change read, its `applyPendingChanges()` call, its deployment and the resolution, and the block executor is what commits them. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. Follow the existing pattern: `#[cfg(not(feature = "std"))] use alloc as std;` then `use std::{vec::Vec, ...};`. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index dcb59b266..0a345f24e 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -60,8 +60,9 @@ The execution figure a block counts for a transaction is its regular ledger — The block's packing budgets and building policy never refuse a deposit, which the block must include. They hold a Mega System Transaction as any other non-deposit transaction, and both classes count towards the budgets. 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 executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`) — 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, and applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call; it reads nothing of the L1 block contract. -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; 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`). +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls (none in the genesis block); in the block in which Satin activates — which the executor works out from its schedule, the block's timestamp and the parent's (`MegaBlockExecutionCtx::parent_timestamp`) — checks that the EIP-7997 `CREATE2` factory, which OP's genesis tooling installed, holds its code, without which that block is invalid; deploys the Oracle, the high-precision timestamp, `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl`, as Rex6 does in every block — a missing one installed, one holding other code rewritten with its storage kept, one holding its code only read; applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call; deploys the registry — read at v2.0.0, migrated from v1.0.0, seeded from the chain configuration's bootstrap values where its address holds no code, the block refused over other code; and resolves the block's live system address from it last, refusing the block when the registry names none; it reads nothing of the L1 block contract. +So Satin may be active from genesis. +It commits each pre-block state on its own, in order, before the next step runs, read-only entries included — the two EIP calls, the activation block's factory read, the five deployments, the read of the registry's pending changes and its call, its deployment and the resolution; 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`). op-revm's fee computation and the executor's footprint read read the L1 block contract on the block's state rather than through a transaction, so the executor reports what they read — the contract's account and every slot either read reaches — once each per block, as read-only entries of the state of the first committed transaction that read them, never in place of that transaction's own entries, whichever executor produced the outcome and in whatever order the builder executed its candidates. A block that reads none of the contract, such as a block of deposits alone, does not fail on a database that cannot serve it. @@ -110,11 +111,11 @@ The exception is a signer whose own code spends a nonce in the constructor that A `keylessDeploy` call a contract makes is not a deployment: it runs the method body, which reverts with `NotIntercepted()`. The system address sends the protocol's own transactions: a legacy transaction from it to a whitelisted contract is validated — the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. -It is the address the `SequencerRegistry` holds, and every transaction reads it itself when it is validated: it loads the registry's account and `_currentSystemAddress`, which stay warm for the rest of the transaction, so an access to either costs the same whatever the envelope. +It is the address the `SequencerRegistry` holds, which the block resolves once, after its other pre-block steps, and hands to the EVM: no transaction reads the registry for its classification, so none finds it warm, and an access to it is cold on its first access, whatever the envelope. A transaction of that shape from that address is a system-address transaction; one of another shape from it is invalid, and a deposit from it, which never has the shape, is a failed deposit. -The registry cannot change the address inside a block after its pre-block call, so every transaction of a block reads the address a rotation due in the block left, and an EVM a node builds outside block execution — an RPC call, the replay of a block's transactions for a trace — reads the one in the state it runs on, with nothing to set. -A registry that is absent, holds other code or names a zero address promotes nothing. -The read is in every transaction's own state and witness; the pre-block steps no longer carry it. +The registry cannot change the address inside a block after its pre-block call, so every transaction of a block is classified against the address a rotation due in the block left, and an EVM a node builds outside block execution — an RPC call, a gas estimate, the replay of a block's transactions for a trace — reads the one in the state it is built on once, when it is built, directly off the state, with nothing to set and nothing warmed or charged, so an estimate is what the transaction costs in a block (`MegaContext::with_system_address` hands an address in). +In block execution a registry that is absent, holds other code or names a zero address refuses the block; outside it, such a registry promotes nothing. +The resolution is the block's last pre-block state; no transaction's state carries it. The account such a transaction creates for its caller is charged the account-creation state gas exactly once. History gas is in place: every byte a transaction appends to the chain is priced at MegaETH's cost per history byte, and the byte counts are the ones the data-size limit meters, so a record's history bytes are its own data size. @@ -229,12 +230,12 @@ The crate builds on Rust 1.94. - `spec_cfg(cfg)` is the configuration Satin runs on: the caller's configuration with every field the spec fixes set from the spec. A node builds its `EvmEnv` through it, so what reads the env before an EVM exists — gas estimation reads the execution cap — reads what the EVM executes on. - `validate_transaction_stateless(cfg, block, tx, system_address)` is a pool's check: it runs the handler's own validation phases on an EVM over an empty database and returns the intrinsic gas by ledger, `IntrinsicGas { regular, state, history, floor }`. - `system::live_system_address(db)` reads the address it takes, off the state the pool validates against, as a transaction's validation reads it. + `system::live_system_address(db)` reads the address it takes, off the state the pool validates against, as an EVM built on that state reads it. The state a transaction adds is charged when it runs, so a new recipient or authority is not in the intrinsic gas; a deposit that fails validation is included as a failed deposit rather than refused. - `MegaTransactionOutcome::limit_stop()`, or `LimitStop::from_result(result, limit_exceeded)` for a result read elsewhere, gives the kind, limit and usage of the limit that stopped a transaction, for an RPC's error. `decode_mega_limit_exceeded` reads revert data alone; bytes that decode are no stop without the outcome's `limit_exceeded`. -- `SatinChainConfig::from_genesis_config(config)` reads a genesis file's `config` object: `satinTime`, the one Satin key; Satin carries no parameter, the limits are the spec's, and no key names them. - It refuses any other key starting with `satin`, those of the format's earlier versions among them, a mistyped value and a schedule `validate_schedule` refuses, and `hardforks()` builds the schedule; it serializes to the same key, for a genesis generator. +- `SatinChainConfig::from_genesis_config(config)` reads a genesis file's `config` object: `satinTime`, the one Satin key, and the `SequencerRegistry`'s bootstrap values a configuration that schedules Satin must carry under the Rex-era keys `rex5InitialSequencer`, `rex5InitialAdmin` and `rex6MinRotationDelay`; the limits are the spec's, and no key names them. + It refuses a missing or zero bootstrap value, any other key starting with `satin`, those of the format's earlier versions among them, a mistyped value and a schedule `validate_schedule` refuses, and `hardforks()` builds the schedule, carrying the bootstrap values; it serializes to the same keys, for a genesis generator. The key format is provisional. ## Documentation diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index ffae8acaf..4dbb252df 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## OVERVIEW -The six system contracts: their addresses and bytecode, the interceptor dispatch over four of them (`MegaAccessControl` and `MegaLimitControl` answer, the Oracle's `sendHint` runs a side effect and falls through, and `KeylessDeploy` is routed but left to the keyless dispatch), the system-address transaction, the check Satin's activation block makes of the six and the EIP-7997 factory, which the legacy forks and OP's genesis tooling installed and Satin never deploys, and the registry's pre-block steps: the due-change read and the `applyPendingChanges()` system call. The live system address is read by every transaction when it is validated, not before the block. +The six system contracts: their addresses and bytecode, the interceptor dispatch over four of them (`MegaAccessControl` and `MegaLimitControl` answer, the Oracle's `sendHint` runs a side effect and falls through, and `KeylessDeploy` is routed but left to the keyless dispatch), the system-address transaction, every block's deployment of the six — the five flat contracts by one rule, the registry by its own — the check Satin's activation block makes of the EIP-7997 factory, which OP's genesis tooling installs and Satin never deploys, and the registry's pre-block steps: the due-change read, the `applyPendingChanges()` system call, its deployment and the resolution of the block's live system address. No transaction reads the registry for its classification: the block resolves the address once, after its other pre-block steps, and an EVM built outside block execution reads it once when it is built. ## STRUCTURE - `oracle.rs`: the Oracle's address, code and ABI, and the `sendHint` side effect. Its storage is read by the Host (`evm/host.rs`), through the oracle environment. @@ -9,8 +9,8 @@ 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. -- `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. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, its bootstrap values (`SequencerRegistryBootstrap`), its four pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness), `transact_apply_pending_changes` (the system call on `PRE_BLOCK_CALL_GAS_LIMIT`), `deploy_sequencer_registry` (read when it holds v2.0.0, migrated in place from v1.0.0 writing slot 13 alone, seeded from the bootstrap values where its address holds no code, refused over other code) and `resolve_system_address` (the block's live system address and its read-only state; a refusal for an absent registry, other code or a zero slot 0) — and `live_system_address`, the lenient direct read of a database an EVM built outside block execution makes when it is built (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 five every block deploys by one rule (`flat_system_contract_specs`, `deploy_system_contract`: installed where missing, code replaced keeping nonce, balance and storage where it differs, a read-only entry where it holds the code), the EIP-7997 factory's constants (`create2_factory_spec`), and `check_system_contract`, the read Satin's activation block makes of the factory: 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. @@ -29,9 +29,9 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - 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). - `remainingComputeGas()` is read when the call reaches the dispatch, after the calling opcode charged its own costs: the lesser of the caller's regular gas with the forward counted back (`MegaEvm::intercept` passes what the caller has left; the answer returns the forward untouched) and gas detention's allowance at the call. That is the caller's spendable regular gas before the forward, which detention caps. This departs from the legacy engine's figure, 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 limit, so it could exceed the caller's gas; here compute is regular gas, and the answer is at most the caller's own. The one property carried over is that forwarded gas is not counted. - `VolatileDataAccessDisabled`'s argument is a `uint8` on the wire. A refused `SLOTNUM` names 12 (`SLOT_NUM_ACCESS_TYPE`), past the contract's enum, so Solidity handlers decode the argument as `uint8`; the contracts are not changed for it, and their code hashes stay. -- A transaction is a system-address transaction when it has the system shape (a legacy call to a whitelisted contract) and its caller is the address the registry names. Every transaction reads the registry when it is validated, whatever its shape, and the read leaves the registry's account and `_currentSystemAddress` warm for the rest of the transaction, as EIP-3651 leaves the block beneficiary, so what a transaction pays never depends on its envelope. A transaction from the system address without the shape is invalid (`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`), a deposit from it a failed deposit; every other sender is an ordinary one. +- A transaction is a system-address transaction when it has the system shape (a legacy call to a whitelisted contract) and its caller is the live system address the context holds: the one the block resolved after its pre-block steps, or the one an EVM built outside block execution read off its database when it was built. No transaction reads the registry for it, so none finds the registry's account or `_currentSystemAddress` warm or carries them in its state, and a transaction that reads them pays the cold price. A transaction from the system address without the shape is invalid (`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`), a deposit from it a failed deposit; every other sender is an ordinary one. - The system-address transaction is validated before it is promoted to a deposit, because the deposit path validates nothing. The chain id is checked there always, as the spec checks every transaction's, and must be present; the nonce and EIP-3607 each under the configuration switch a user transaction obeys. -- Accounts and slots read during validation are read with revm's own loads, which warm them: the registry's account and slot, warm for every transaction by rule, and the system address's account, the transaction's caller, which the transaction starts warm anyway. +- Accounts read during validation are read with revm's own loads, which warm them: the system address's account, the transaction's caller, which the transaction starts warm anyway. ## PRE-BLOCK STATE CHANGE CONTRACT @@ -40,13 +40,13 @@ The contract for a new or modified helper: - Never call `db.commit(...)` inside the helper. Return the prepared state; let the executor commit. -- On a read that changes nothing (a predeploy holding the expected code, the registry's due check), return `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. +- On a read that changes nothing (a system contract holding the expected code, the factory check, the registry's due check, the resolution of the live system address), return `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. Returning nothing here is a bug — the account disappears from the stateless witness read set. -- On a step that writes (`applyPendingChanges()`), include every account and storage slot the helper touched. -- A predeploy holding other code is an error, never an overwrite or an upgrade: Satin's activation block refuses a chain that does not hold the seven at the versions it runs. +- On a step that writes (a deployment that installs or rewrites a contract, `applyPendingChanges()`), include every account and storage slot the helper touched. +- A flat system contract holding other code has its code replaced and keeps its storage; the registry holding code it cannot migrate is an error, never an overwrite: its storage carries roles and histories. The returned `EvmState` is both the commit and the witness record of that step. -The executor commits it on its own, in the order the steps run: a commit hook on the block's state receives each committed state whole, read-only entries included, and that sequence is the witness a stateless client needs. +The executor commits it on its own, in the order the steps run, before the next step runs: a commit hook on the block's state receives each committed state whole, read-only entries included, and that sequence is the witness a stateless client needs. ## ANTI-PATTERNS - Do not answer an unknown selector with a synthetic revert: the on-chain bytecode is the fall-through, and what it answers is the contract's own business. @@ -58,13 +58,13 @@ The executor commits it on its own, in the order the steps run: a commit hook on - Do not add a length check to a selector match. Admission is the four bytes. - Do not accept value on a read-only or control method without saying why in the interceptor and pinning it with a test. - Do not deploy system bytecode from a literal in this crate; the `mega-system-contracts` crate ships the code and its hash. The timestamp wrapper is the one exception, because the Oracle's address is baked into its code. -- Do not read the system address from a constant or hold it on the context: the address can be rotated, and the registry in the state the EVM runs on is the one source. -- Do not skip the registry read for a transaction of some shape: every transaction starts with the registry warm, and a read that depends on the envelope makes the gas depend on it too. +- Do not read the system address from a constant: the address can be rotated, and the registry in the state is the one source. The context holds the address the block resolved, or the one it read when it was built; no transaction reads it again. +- Do not load the registry through a transaction's journal for its classification: that warms it for the transaction and puts it in the transaction's state, so a transaction would pay and witness differently in a block and in an estimate. - Do not call `db.commit(...)` inside a helper that participates in `apply_pre_execution_changes`. It takes the step out of the executor's sequence: the executor commits each step's state on its own, in order, and only once the step succeeded, and that sequence is the witness. - Do not return nothing from a helper on a "no change needed" path. Return the account entries observed, even when nothing is written. -- Do not create, overwrite or upgrade a predeploy from the engine: the legacy forks installed them, and Satin's activation block only checks them. +- Do not deploy a system contract anywhere but in the block's pre-block steps, and do not deploy the EIP-7997 factory at all: the activation block only checks it. ## 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/`. @@ -72,7 +72,7 @@ The executor commits it on its own, in the order the steps run: a commit hook on - 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. -- Change how the activation block checks the predeploys: `block/executor.rs::apply_pre_execution_changes` iterates the spec list when `MegaBlockExecutor::is_satin_activation_block` holds, commits each read as a state of its own, and refuses the block on the first unexpected code. -- Change when a role change is applied: `sequencer_registry.rs`, whose two pre-block helpers `block/executor.rs::apply_pre_execution_changes` calls after the predeploy check, in that order. -- Change how the live system address is read: `sequencer_registry.rs::load_system_address`, which `MegaHandler::validate_env` calls, and `MegaHandler::validate_env_as`, which decides from the address whether the transaction is a system-address transaction; the answer lives on the context as the transaction's system-originated flag (`MegaContext::is_system_originated`). `sequencer_registry.rs::live_system_address` makes the same read off a database, for a pool. +- Add a system contract every block deploys by the flat rule: a spec in `predeploys.rs::system_contract_specs`, among the first five `flat_system_contract_specs` takes; one with storage that must not be overwritten needs a rule of its own, as the registry has. +- Change how a block deploys the system contracts or checks the factory: `block/executor.rs::apply_pre_execution_changes`, which checks the factory when `MegaBlockExecutor::is_satin_activation_block` holds, then deploys the five, then makes the registry's steps, committing each state on its own. +- Change when a role change is applied: `sequencer_registry.rs`, whose pre-block helpers `block/executor.rs::apply_pre_execution_changes` calls after the five flat deployments, in the order due read, call, deployment, resolution. +- Change how the live system address reaches a transaction: `sequencer_registry.rs::resolve_system_address`, whose answer the executor hands to `MegaContext::set_system_address` after the pre-block steps; `MegaContext::new_with_external_envs`, which reads it with `live_system_address` when a context is built; `MegaHandler::validate_env`, which takes it from the context (`MegaContext::live_system_address`), and `MegaHandler::validate_env_as`, which decides from it whether the transaction is a system-address transaction; the answer lives on the context as the transaction's system-originated flag (`MegaContext::is_system_originated`). A pool passes the address it read with `live_system_address`. diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index ac0d9b9a3..03af45e8c 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -204,7 +204,7 @@ The replay works this out as a node does, from the schedule the block runs under A transaction replay works it out the same way, from the parent block it forks, and refuses a non-deposit transaction of such a block with an error. The parent's timestamp decides the answer only for a Satin block at which a fork its schedule activates after genesis is active; for such a block alone the replay fetches the parent's header over `--rpc` and keeps its timestamp in the cache. Every other block, a legacy one or one whose schedule activates every fork it runs at genesis as the Satin counterfactual's does, replays from what the cache holds and never asks for the parent. -Satin's activation block also checks the predeploys (the six system contracts and the EIP-7997 factory), which the legacy engine never read in full, so a block cached from a legacy replay may need them over `--rpc` once. +Every Satin block reads the six system contracts, which it deploys, and Satin's activation block also checks the EIP-7997 factory; the legacy engine never read the factory, so a block cached from a legacy replay may need it over `--rpc` once. Offline, a block that needs the parent's timestamp and whose cache entry lacks it (an entry written before the cache kept it, or by a replay that did not need it) fails rather than guess, and the error says so. To recover, replay it once with `--rpc`: the replay fetches the timestamp and writes it to the cache, and the block then replays offline. diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index e1a82cb37..8895a1fed 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -125,7 +125,7 @@ A command on a legacy spec is refused with `--override.limits`: the legacy engin A chain the tool does not know, a devnet for one, is replayed as its nodes run it only with its own Satin configuration: which blocks run Satin. Without it a replay of such a chain is refused, unless `--override.spec` names the engine; `run` and `tx` with `--spec Satin` run a counterfactual on any chain, with Satin active from genesis. `--genesis ` takes it from the chain's genesis file, on every command, `replay` included. -The file's `config` object (or a file that is the `config` object) is read for its `chainId` and its Satin key, `satinTime`, with the parser the node and the stateless validator read it with, so a key the node refuses is refused here too: a `satin`-prefixed key other than `satinTime`, the registry roles an earlier format named among them. +The file's `config` object (or a file that is the `config` object) is read for its `chainId`, its Satin key, `satinTime`, and the `SequencerRegistry`'s bootstrap keys a configuration that schedules Satin must carry (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`), with the parser the node and the stateless validator read it with, so a key the node refuses is refused here too: a `satin`-prefixed key other than `satinTime`, the registry roles an earlier format named among them, and a missing or zero bootstrap value. For that chain the file replaces the tool's table: a block runs Satin from the file's `satinTime`. The file names no limit and no `SequencerRegistry` role: a Satin run under it is held to Satin's limits, as every Satin run is, and a Satin block reads the registry the chain's state holds, which the legacy forks deployed. Satin's activation block refuses a state whose registry is missing or holds other code; a later block makes no such check and runs on the state it is given, where a missing registry names no system address. diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index 78f9b96b6..9fb68995c 100644 --- a/docs/spec/hardfork-spec.md +++ b/docs/spec/hardfork-spec.md @@ -197,8 +197,8 @@ It restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka) rather - **[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 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. +- **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; every block deploys the system contracts, as Rex6 does, so Satin may be active from genesis, and the block in which Satin activates checks that the EIP-7997 factory holds its code. +- **Live system address** — resolved once per block from the [SequencerRegistry](system-contracts/sequencer-registry.md), after the other pre-block steps, as Rex6 does; no transaction reads the registry for its classification, and a system-address transaction without the system shape is invalid. - **Block limits** — data size, KV updates and state growth are packing budgets that exempt only deposits; Mega System Transactions obey those budgets and building policy. _See [Satin Network Upgrade](upgrades/satin.md) for the current state._ diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 1f98384e0..ee06786c5 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, 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. +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 system contracts deployed in every block and the live system address resolved once per block, 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 @@ -26,7 +26,7 @@ Compute is regular gas, bounded by the execution cap and by [gas detention](../e 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, KV and state-growth limits packing budgets that exempt deposits and hold Mega System Transactions as any other non-deposit 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, deploys the system contracts in every block and resolves the live system address once per block as Rex6 does, and makes the block's data-size, KV and state-growth limits packing budgets that exempt deposits and hold Mega System Transactions as any other non-deposit 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. @@ -334,7 +334,7 @@ Deposited code MUST be charged, once the creation's code passed its checks and i 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)). +No transaction finds the `SequencerRegistry`'s account or its `_currentSystemAddress` slot warm for its classification: the block resolves the live system address once, outside 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 @@ -829,7 +829,7 @@ A deposit that runs to a success or a revert and creates its caller is the ordin 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 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 or a precompile (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. @@ -1204,23 +1204,24 @@ An out-of-gas step halts the call, consuming its regular gas. #### New behavior - The system shape is tested on the transaction's own fields: type `0x0`, a call (not a creation) to an address on `MEGA_SYSTEM_TX_WHITELIST` (the Oracle). -- Every transaction MUST read the registry when it is validated, whatever its shape and whoever sent it: the node loads the registry's account and, from the transaction's own state, its `_currentSystemAddress` slot. - When the registry's code hash is that of version 2.0.0, which this spec requires, and the slot holds a non-zero address, that address is the live system address. +- Once per block, after every other pre-block step (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)), the node MUST resolve the block's live system address from the registry, as Rex6 does: it loads the registry's account and its `_currentSystemAddress` slot from the state those steps left, compares the account's code hash with that of version 2.0.0, and takes the address the slot holds. The read compares the registry's code hash and MUST NOT load or run the registry's code. - The account and the slot MUST be warm for the rest of the transaction, as the block beneficiary is under [EIP-3651](https://eips.ethereum.org/EIPS/eip-3651), whatever the registry holds: an access to either costs every transaction the same, whatever its envelope. - The read is not charged and writes nothing, so committing the transaction leaves the registry as it was. - It lands in the transaction's returned state, and so in the block's witness, whatever the pre-block states also hold of the registry; it does not load the registry's code, but the witness carries that code as it carries the code of every account the block loads (see [The Stateless Witness](#22-the-stateless-witness)), and the Oracle's own check of its caller runs it. + It is not charged, writes nothing, and is committed as a read-only state of the pre-block phase, the last one, so it lands in the block's witness (see [The Stateless Witness](#22-the-stateless-witness)). +- Every transaction of the block MUST be classified against that address, and no transaction reads the registry for its classification: no transaction finds the registry's account or slot warm unless it accessed them itself, and none carries them in its returned state for that reason. + A transaction that accesses the registry pays for it as for any account, cold on its first access; the Oracle's own check of its caller, which a Mega System Transaction runs, reads the registry's slot and pays for it cold. +- A registry that is absent, holds other code, or whose `_currentSystemAddress` is zero when the block resolves the live system address MUST make the block invalid, as in Rex6. + The registry's deployment, which precedes the resolution, seeds a registry the state does not hold and refuses one that holds other code, so the resolution finds the registry absent or holding other code only in a state built apart from the chain. +- A transaction executed outside block execution — a call, a gas estimate, a simulation — is classified against the address the registry names in the state it runs on, read once by the reference implementation when its EVM is built, directly off the state and outside every transaction: nothing is warmed or charged, so a gas estimate is what the transaction costs in a block. + Where that registry names no address, no transaction is a Mega System Transaction there. - A transaction of the system shape whose caller is the live system address is a Mega System Transaction. - A registry that is absent, holds other code, or names the zero address names no live system address, and MUST make no transaction a Mega System Transaction. - Satin's activation block refuses a chain whose registry is absent or holds other code (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)), so on a chain Satin runs on those two arise only in a state built apart from the chain, such as a test's. - A transaction from the live system address without the system shape MUST be invalid, whatever its type, a deposit included: a transaction other than a deposit is rejected, and a deposit, which is never of the system shape, is included as a failed deposit, which runs no call (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). That includes a deposit carrying the source hash the promotion stamps, which a block never holds: a Mega System Transaction is promoted from its legacy envelope, and one handed to a node already promoted is a failed deposit. The Oracle authorizes writes on the sender alone, so no transaction from the system address other than a Mega System Transaction reaches the Oracle. - A transaction from any other address is never a Mega System Transaction, and is an ordinary transaction, validated and charged as a user's: that includes a transaction from an address a rotation retired, which is no longer the live system address. - A Mega System Transaction MUST be validated before it is promoted to a deposit, and a failure is a rejection: it MUST carry the chain's id, which a user's legacy transaction may omit and it MUST NOT; its nonce MUST be the system address's; and the system address MUST have no code, as [EIP-3607](https://eips.ethereum.org/EIPS/eip-3607) requires of any sender. It is then executed as a deposit, which checks no signature, nonce or fee of its own. -- Because a role change can only be scheduled for a later block — the registry refuses an activation block at or before the current one — and is applied by that block's pre-block call, every transaction of a block reads the address the block's pre-block step left; a call to `applyPendingChanges()` inside the block, which anyone may make, finds no change due that the pre-block step did not apply. -- A registry read the node fails to make gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). +- Because a role change can only be scheduled for a later block — the registry refuses an activation block at or before the current one — and is applied by that block's pre-block call, every transaction of a block is classified against the address the block resolved after its pre-block steps; a call to `applyPendingChanges()` inside the block, which anyone may make, finds no change due that the pre-block step did not apply. +- A registry read the node fails to make — in the resolution, in the due-change read or in the registry's deployment — is an internal error of the node, never an invalid block or a transaction's result (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). ### 18. System Calls and Pre-Block Calls @@ -1245,19 +1246,37 @@ An out-of-gas step halts the call, consuming its regular gas. Before its transactions, a block MUST, in order: 1. make the EIP-2935 call; 2. make the EIP-4788 call (a block without a parent beacon block root is invalid, as EIP-4788 defines); - 3. in the block in which Satin activates, and in no other, check the six MegaETH system contracts in address order — Oracle, High-Precision Timestamp, KeylessDeploy, MegaAccessControl, MegaLimitControl, SequencerRegistry — and then the [EIP-7997](https://eips.ethereum.org/EIPS/eip-7997) `CREATE2` factory at `0x4e59b44847b379578588920ca78fbf26c0b4956c`, as below; - 4. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`. - + 3. in the block in which Satin activates, and in no other, check the [EIP-7997](https://eips.ethereum.org/EIPS/eip-7997) `CREATE2` factory at `0x4e59b44847b379578588920ca78fbf26c0b4956c`, as below; + 4. deploy the Oracle, the High-Precision Timestamp, KeylessDeploy, MegaAccessControl and MegaLimitControl, in that order, each as a step of its own, as below; + 5. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`; + 6. deploy the `SequencerRegistry`, as below; + 7. resolve the block's live system address from the registry (see [The Live System Address](#17-the-live-system-address)). + + The genesis block, number zero, makes no EIP-2935 call and no EIP-4788 call, and its parent beacon block root MUST be zero, as those EIPs define; it makes the other steps as every block does. + Each step's state MUST be committed on its own, in that order, before the next step runs and before the block's first transaction, read-only entries included; so every step sees the ones before it, which Rex6, committing its steps' outcomes only after all of them had run, did not. The sequence reads nothing of the L1 block contract: a transaction reads it when it needs it, as [the stateless witness](#22-the-stateless-witness) lays out. - -- **The activation check.** - Satin runs on a chain that ran the legacy forks, which installed the six MegaETH system contracts at the versions Satin runs, and whose genesis OP's tooling gave the EIP-7997 factory: Satin deploys, upgrades and seeds none of them. - The block in which Satin activates — Satin active at its timestamp and not at its parent's — MUST read the seven addresses, and each MUST hold exactly the code Satin expects: the Oracle and the SequencerRegistry at version 2.0.0, the other four system contracts at the bytecode Rex6 runs, and the factory's runtime, code hash `0x2fa86add0aed31f33a762c9d88e807c475bd51d0f52bd0955754b2608f7e4989`. - Their nonces, balances and storage are not checked. - An address with no account, an account without code, an older version of its contract or any other code MUST make the block invalid. - The reference implementation reports every such refusal as one error, `MegaBlockExecutionError::UnexpectedSystemContractCode`, which names the address, the code hash expected and the one held, and is a verdict on the block. - The check writes nothing: each address it reads is a read-only entry of the activation block's pre-block states, in the order above. - No other block reads the seven addresses before its transactions. + No step is charged, and none counts toward the block's counters. + +- **The deployment of the system contracts.** + Every block deploys the MegaETH system contracts, as Rex6 does, so a chain need not have run a Rex6 block before `satinTime`: Satin may be active from genesis. + The Oracle, the High-Precision Timestamp, KeylessDeploy, MegaAccessControl and MegaLimitControl are deployed by one rule: an address with no account is given an account holding the contract's code; an account whose code hash is not the one Satin runs — the Oracle at version 2.0.0, the other four at the bytecode Rex6 runs — has its code replaced by it, its nonce, balance and storage kept; an account that holds it is left as it is, and recorded as a read-only entry of the step's state. + On a chain that ran Rex6 every one of them holds its code, so each step is a read-only entry; a chain whose Oracle is still at 1.0.0 or 1.1.0, or which lacks KeylessDeploy, MegaAccessControl or MegaLimitControl, gets them in its first Satin block. + The `SequencerRegistry` holds roles and histories, and is deployed by its own rule: + - at version 2.0.0, it is left as it is and recorded as a read-only entry; + - at version 1.0.0, it is migrated in place: its code replaced by version 2.0.0, its slot 13 (`_minRotationDelay`) written with the configured minimum rotation delay, and every other slot, its nonce and its balance kept; + - an address with no account, or an account without code, receives version 2.0.0 as a new contract, an existing account's nonce and balance kept and its storage cleared, seeded with: slots 0 and 4 (the current and initial system address) `0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d`, slots 1 and 5 (the current and initial sequencer) the configured initial sequencer, slot 2 (the admin) the configured initial admin, slot 6 (`_initialFromBlock`) the block's number, and slot 13 the configured minimum rotation delay; + - any other code MUST make the block invalid: the registry's storage is never overwritten by code it was not migrated to. + + The configured values are the chain configuration's bootstrap keys, the ones the Rex era introduced (see the chain configuration under [Implementation Notes](#implementation-notes)); once the registry holds its roles, its storage, not the configuration, decides them. + The reference implementation reports a registry it cannot migrate, and one the resolution of the live system address refuses, as `MegaBlockExecutionError::SequencerRegistry`, a verdict on the block; a block that must seed or migrate the registry on a node whose configuration carries no usable bootstrap values fails with `MegaBlockExecutionError::UnusableRegistryBootstrap`, an internal error of the node. + +- **The factory check.** + Satin does not deploy the EIP-7997 factory: OP's genesis tooling gives the chain one. + The block in which Satin activates — Satin active at its timestamp and not at its parent's — MUST read the factory's address, which MUST hold an account whose code hash is `0x2fa86add0aed31f33a762c9d88e807c475bd51d0f52bd0955754b2608f7e4989`; its nonce, balance and storage are not checked. + An address with no account, an account without code or any other code MUST make the block invalid. + The reference implementation reports the refusal as `MegaBlockExecutionError::UnexpectedSystemContractCode`, which names the address, the code hash expected and the one held, and is a verdict on the block. + The check writes nothing: the address it reads is a read-only entry of the activation block's pre-block states. + No other block reads the factory before its transactions, and a chain on which Satin is active from genesis has no activation block and checks it in no block. - **Oracle reads in a system call.** A system call MUST NOT ask the oracle service: an `SLOAD` in the Oracle's own frame during one reads the slot's value on the chain, which is loaded and priced as an Oracle read is (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), and records no answer. The pre-block calls run whatever code sits at the EIP-2935 and EIP-4788 addresses: on MegaETH's chains that is EIP-2935's and EIP-4788's own code, which reads no Oracle, and the rule keeps a system call a function of the state a stateless validator is given, which carries no service answer, whatever that code is. @@ -1265,7 +1284,8 @@ An out-of-gas step halts the call, consuming its regular gas. - **Failure.** A pre-block call that does not succeed MUST make the block invalid, before its state is used. A database error the node's database declares fatal is an internal error of the node, not a verdict on the block; any other failure of a call — a non-fatal database error, another EVM error, an outcome that is not a success — makes the block invalid. - A database error in the activation check or in the due-change read is always an internal error. + A database error in the factory check, in a deployment, in the due-change read or in the resolution of the live system address is always an internal error. + A registry the deployment cannot migrate, and one the resolution finds absent, holding other code or naming no system address, MUST make the block invalid. No pre-block step reads the L1 block contract, so a node whose database cannot serve a slot of it that no transaction of the block reads executes the block: a block of deposits alone, which reads none, or a block whose transactions never read the overhead slot (5). ### 19. The Protocol's Own Transactions @@ -1414,7 +1434,7 @@ The witness is defined by what the block's execution returns and exports, and a - the hash of every block `BLOCKHASH` read, which the block's execution exports; - the capacity of every SALT bucket the block's execution exports; - the oracle service's answer to every oracle read the block's included transactions recorded, in block order. - 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 transaction loads every account and slot its execution reads from the state: in its validation, 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 and the footprint gas scalar it is held to, which are read outside its journal and which the block reports with the first transaction that read them (see the L1 block info, 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)). @@ -1424,8 +1444,8 @@ The witness is defined by what the block's execution returns and exports, and a 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, 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, and the `applyPendingChanges()` call's state. + 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, 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 the factory's read-only entry, each system contract's deployment — the account it installed or rewrote, or the read-only entry of one it left as it was —, the registry's account and pending slots the due-change decision read, the `applyPendingChanges()` call's state when the call is made, the registry's deployment, and last the registry's account and `_currentSystemAddress` slot the resolution of the live system address read. 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. The header, the chain configuration — the schedule — the parent hash, the parent beacon block root, the extra data and the parent block's timestamp are inputs a validator is given beside the witness. @@ -1545,28 +1565,32 @@ A node, a stateless validator and a replay tool must agree on everything below, A block admits only deposits when a MegaETH fork, Satin itself, or an Optimism fork at or after Jovian in the Optimism fork order, is active at the block's timestamp and not at the parent's (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)); a user transaction in such a block is refused before it runs. A block builder and a validator MUST give block execution the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates, and a stateless validator is given the parent block's timestamp beside the witness. Both are decided once, when the block starts. - A block with no parent, such as a genesis block, is executed with an explicit absence of the parent timestamp: block execution applies neither rule to it. - It accepts the absence only where no parent could change that, which is where every fork the schedule activates is active from genesis, or none is active at the block yet. - Where a fork the schedule activates after genesis is active at the block, whether it activates in the block depends on the parent's timestamp, and block execution refuses the block with an error that names the missing timestamp instead of running it as one that admits non-deposit transactions. + The genesis block, number zero, has no parent, and block execution applies neither rule to it: a fork active at its timestamp is active from genesis, so a chain on which Satin is active from genesis has no Satin activation block. + Any other block executed with an explicit absence of the parent timestamp is accepted only where no parent could change the rules, which is where every fork the schedule activates is active from timestamp zero, or none is active at the block yet. + Where a fork the schedule activates after timestamp zero is active at the block, whether it activates in the block depends on the parent's timestamp, and block execution refuses the block with an error that names the missing timestamp instead of running it as one that admits non-deposit transactions. An implementation MUST therefore supply the parent timestamp for every block that has a parent, the block right after genesis included, since that block can be the activation block. - Satin's activation block is told apart from the other deposit-only blocks, since an Optimism fork's activation block admits only deposits too: only Satin's makes the pre-block step check the predeploys (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). - A block that is not Satin's activation block checks no predeploy, and runs on a state that may lack them. + Satin's activation block is told apart from the other deposit-only blocks, since an Optimism fork's activation block admits only deposits too: only Satin's makes the pre-block step check the EIP-7997 factory (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). + A block that is not Satin's activation block does not check the factory. - **The L1 block information.** Block execution reads the L1 block contract at the block's first non-deposit transaction other than a Mega System Transaction, after the block's L1 attributes deposit wrote it, unless the node handed it the information for this block beforehand, which it then prices with, the footprint gas scalar aside; a node that hands it over must hand over what that deposit writes, so that the block's transactions are priced as [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka) requires. What it reports of the contract with the first transaction that read it is what a node that handed nothing over reads, whether or not this node handed the information over, since a validator re-executing the block reads it (see [The Stateless Witness](#22-the-stateless-witness)). The first transaction is the first the block commits, whichever executor executed it and in whatever order the builder executed its candidates: an outcome carries what it read of the contract beside its returned state, and the executor that commits it reports what that executor has not reported yet, and nothing it has. - **The witness.** 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. + 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 factory, the system contracts every deployment left as they were, the registry's pending slots, the resolution's read 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`. - The registry's roles are what it holds: the legacy forks' own configuration keys (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`) seeded it, and Satin reads none of those keys. + Every Satin block deploys the six system contracts (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)): on a chain that ran Rex6 each is already there at the version Satin runs and is only read, and a chain that lacks one, or holds an older version, gets it in its first Satin block, the `SequencerRegistry` seeded from the configuration's bootstrap values or migrated from version 1.0.0. + OP's genesis tooling gives the chain the EIP-7997 factory, which Satin's activation block checks and nothing deploys. + The registry's roles are what it holds once it is deployed: the bootstrap values seed only a registry the state does not hold. +- **The live system address outside block execution.** + An EVM a node builds outside block execution — for a call, a gas estimate or a trace — classifies its transactions against the live system address the registry holds in the state it runs on. + The reference implementation reads it once, when the EVM is built (`MegaContext` reads it off its database with `system::live_system_address`), directly and outside every transaction, so the read is neither warmed nor charged and an estimate is what the transaction costs in a block; a node that already knows the address hands it in (`MegaContext::with_system_address`), and block execution hands in the one it resolved after the block's pre-block steps. + A read the database cannot serve when the EVM is built is made again by the next transaction, which fails with the database's error if it fails again. - **Committing a delayed outcome.** 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. @@ -1581,15 +1605,20 @@ A node, a stateless validator and a replay tool must agree on everything below, 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'. - - | Key | Value | - | ----------- | ------------------------------------ | - | `satinTime` | The activation timestamp, an integer | - - Satin carries no parameter. + A genesis file's `config` object schedules Satin by one key beside the other forks', and a configuration that schedules Satin MUST also carry the `SequencerRegistry`'s bootstrap values under the keys the Rex era introduced. + + | Key | Value | + | ---------------------- | ------------------------------------------------------------------ | + | `satinTime` | The activation timestamp, an integer | + | `rex5InitialSequencer` | The sequencer a new registry is seeded with, a non-zero address | + | `rex5InitialAdmin` | The admin a new registry is seeded with, a non-zero address | + | `rex6MinRotationDelay` | The registry's minimum rotation delay, a non-zero number of blocks | + + A node MUST refuse a configuration that schedules Satin and lacks one of the three bootstrap keys or gives one as zero; the reference parser names the key. + An address is a JSON string of forty hexadecimal digits after `0x`, and the delay a JSON number. + The bootstrap values are read only by the registry's deployment (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); a configuration that does not schedule Satin needs none of them. + Satin carries no parameter of its own. 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 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. @@ -1607,7 +1636,9 @@ A node, a stateless validator and a replay tool must agree on everything below, 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 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. +The six system contracts keep their Rex6 bytecode and ABI, but for the four errors `IKeylessDeploy` no longer declares; every Satin block deploys them as Rex6 does, so a chain that ran Rex6 finds each already there, and its activation block refuses a chain that does not hold the EIP-7997 factory. +A chain that skipped Rex6's deployments gets the missing contracts, and the Oracle at 2.0.0, in its first Satin block: such a block's post-state differs from one that only reads them. +As in Rex6, the live system address is resolved once per block and no transaction finds the `SequencerRegistry` warm for its classification: a transaction that accesses the registry pays for it cold on its first access, the Oracle's check of a Mega System Transaction's caller included. 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: 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. From f0d7746b008917bd49384a0fd88328a368c403f1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:43:44 +0800 Subject: [PATCH 071/190] test(block): an estimate outside block execution costs what the block charges --- .../tests/block/sequencer_registry.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs index 2c30eedb6..2ae250e7c 100644 --- a/crates/mega-evm/tests/block/sequencer_registry.rs +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -414,6 +414,60 @@ fn test_an_evm_outside_block_execution_promotes_the_rotated_address() { ); } +/// An account holding the registry's code and the same `_currentSystemAddress`, which no rule +/// treats as the registry: what reading the registry costs a transaction that is not special. +const TWIN: Address = address!("0x7000000000000000000000000000000000000007"); + +/// A gas estimate run outside block execution — on an EVM the factory builds over the state the +/// block's transactions run on, told nothing — costs what the block charges, on every ledger, for +/// a Mega System Transaction whose Oracle write reads the registry to check its caller, and for an +/// ordinary transaction that reads the registry's `currentSystemAddress()`: no transaction reads +/// the registry for its classification, in a block or outside one, so neither finds it warm. The +/// ordinary read costs exactly what the same read of [`TWIN`] costs, in the block and outside. +#[test] +fn test_an_estimate_outside_block_execution_costs_what_the_block_charges() { + let read = |to: Address| { + let input = ISequencerRegistry::currentSystemAddressCall {}.abi_encode(); + let gas_limit = gas_limit(input.len()); + Recovered::new_unchecked(common::tx(0, to, input.into(), gas_limit), common::CALLER) + }; + let write = || { + let input = IOracle::setSlotsCall { slots: vec![U256::from(5)], values: vec![B256::ZERO] } + .abi_encode(); + let gas_limit = gas_limit(input.len()); + Recovered::new_unchecked( + common::tx(0, ORACLE_CONTRACT_ADDRESS, input.into(), gas_limit), + MEGA_SYSTEM_ADDRESS, + ) + }; + let db = || { + let mut db = registry_with(&[]); + let registry = db.cache.accounts[&SEQUENCER_REGISTRY_ADDRESS].info.clone(); + db.insert_account_info(TWIN, registry); + db.set_account_storage(TWIN, CURRENT_SYSTEM_ADDRESS, common::word(MEGA_SYSTEM_ADDRESS)); + db + }; + // The gas the block charges `tx` and the gas an estimate on the same state charges it. + let both = |tx: &Recovered| { + let mut state = State::builder().with_database(db()).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + let in_block = executor.run_transaction(tx).expect("included"); + assert!(in_block.result.is_success(), "{:?}", in_block.result); + drop(executor); + let mut outside = MegaEvmFactory::new() + .with_external_env_factory(envs_at(1)) + .create_evm(&mut state, common::evm_env()); + let estimate = outside.execute_transaction(tx.to_tx_env()).expect("estimated"); + assert_eq!(estimate.result, in_block.inner.result); + assert_eq!(estimate.gas, in_block.inner.gas, "the estimate is the block's charge"); + estimate.gas + }; + let system = both(&write()); + assert_eq!(system.history, 0, "a Mega System Transaction"); + assert_eq!(both(&read(SEQUENCER_REGISTRY_ADDRESS)), both(&read(TWIN)), "the registry is cold"); +} + /// A deposit from `sender` to the Oracle's `setSlots`, minting `mint` to it: a write the Oracle /// accepts from the live system address, if the call ran. fn oracle_write_deposit_from(sender: Address, mint: u128) -> Recovered { From ac7ad5a0b2936b94392b0273f724d6cdc87b1470 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:49:06 +0800 Subject: [PATCH 072/190] test: no transaction carries a read of the registry in its dump, read set or recorded-block gas --- .../tests/fixtures/test_satin_run_dump_inline.json | 9 --------- bin/mega-evme/tests/satin-differences.md | 8 ++++---- crates/mega-state-test/src/runner.rs | 3 +++ crates/state-test/tests/cli.rs | 9 ++++----- 4 files changed, 11 insertions(+), 18 deletions(-) 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 5e8d601fa..7069063d5 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 @@ -42,15 +42,6 @@ "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", "storage": {} }, - "0x6342000000000000000000000000000000000006": { - "balance": "0x0", - "nonce": "0x0", - "code": "0x608060405234801561000f575f5ffd5b50600436106100e5575f3560e01c806354fd4d5011610088578063de7a36af11610063578063de7a36af146101f7578063e3093f5014610214578063e812903014610227578063f851a44014610245575f5ffd5b806354fd4d501461019d57806375829def146101dc578063c7455c42146101ef575f5ffd5b80632b659fd8116100c35780632b659fd81461014e5780633411f3c31461016157806344d744591461017457806348a2cf6d1461017c575f5ffd5b80630e18b681146100e9578063129c8240146100f35780632678224714610130575b5f5ffd5b6100f1610263565b005b610106610101366004611274565b610336565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020015b60405180910390f35b60035473ffffffffffffffffffffffffffffffffffffffff16610106565b6100f161015c3660046112b3565b61045c565b6100f161016f366004611336565b6107e1565b6100f1610a91565b61018f61018a366004611336565b610aa3565b604051908152602001610127565b604080518082018252600581527f322e302e3000000000000000000000000000000000000000000000000000000060208201529051610127919061135e565b6100f16101ea3660046113b1565b610c5b565b600d5461018f565b5f5473ffffffffffffffffffffffffffffffffffffffff16610106565b610106610222366004611274565b610d0b565b60015473ffffffffffffffffffffffffffffffffffffffff16610106565b60025473ffffffffffffffffffffffffffffffffffffffff16610106565b60035473ffffffffffffffffffffffffffffffffffffffff163381146102b5576040517f058d9a1b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6002805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff00000000000000000000000000000000000000008084168217909455600380549094169093556040519116919082907ff8ccb027dfcd135e000e9d45e6cc2d662578a8825d4c45b5e32e0adf67e79ec6905f90a35050565b5f43821115610371576040517fdbe289ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6006548210156103ad576040517fd2c461b000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600c54805b801561043b575f600c6103c66001846113fe565b815481106103d6576103d6611411565b5f91825260209091200180549091506bffffffffffffffffffffffff16851061042857546c01000000000000000000000000900473ffffffffffffffffffffffffffffffffffffffff16949350505050565b50806104338161143e565b9150506103b2565b505060055473ffffffffffffffffffffffffffffffffffffffff1692915050565b610464610e31565b43831161049d576040517fc2fdad0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83036105cd5773ffffffffffffffffffffffffffffffffffffffff841615610512576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555f600a81905560015473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f7ac0520c61d87c77ffc308e23c801f5a351140175ec3f6356a3a890aa0cfdbf97fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6040516105c091815260200190565b60405180910390a36107db565b6bffffffffffffffffffffffff831115610613576040517f9d7378d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8416610660576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600d5461066d9043611472565b8310156106a6576040517f11ede46e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f6106bb6106b48686610aa3565b8484610e82565b90508473ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610722576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6009805473ffffffffffffffffffffffffffffffffffffffff87167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155600a85905561078a60015473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167f7ac0520c61d87c77ffc308e23c801f5a351140175ec3f6356a3a890aa0cfdbf9866040516107d191815260200190565b60405180910390a3505b50505050565b6107e9610e31565b438111610822576040517fc2fdad0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81036109505773ffffffffffffffffffffffffffffffffffffffff821615610897576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555f6008819055805473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167fd839b7efbcae2bd482a7aa1c098265fdb6b43c10e3e5138a8fa2b395a02eb9157fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60405161094491815260200190565b60405180910390a35050565b6bffffffffffffffffffffffff811115610996576040517f9d7378d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff82166109e3576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff84167fffffffffffffffffffffffff000000000000000000000000000000000000000090911681179091556008829055610a4a5f5473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167fd839b7efbcae2bd482a7aa1c098265fdb6b43c10e3e5138a8fa2b395a02eb9158360405161094491815260200190565b610a9961108c565b610aa1611181565b565b604080518082018252601981527f4d6567614554482053657175656e63657252656769737472790000000000000060209182015281518083018352600181527f31000000000000000000000000000000000000000000000000000000000000009082015281517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f818301527f85da835bd1cf371efdb3f9056e5a3a6245af1400fa0ce2e878a198765a4eb9c2818401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a0808301919091528351808303909101815260c0820184528051908301207faebf84f20bcc14afc14200ed16cfb9314ef205d4d1d8fbcc0a256c39a3e79aa960e083015273ffffffffffffffffffffffffffffffffffffffff861661010083015261012080830186905284518084039091018152610140830185528051908401207f190100000000000000000000000000000000000000000000000000000000000061016084015261016283019190915261018280830191909152835180830390910181526101a290910190925281519101205b92915050565b610c63610e31565b6003805473ffffffffffffffffffffffffffffffffffffffff83167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155610cc660025473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167fe5cd1c804f1c9cc6d7009e4c0fb532f0e2d8863524c3323a6b3790c3f80bf25c60405160405180910390a350565b5f43821115610d46576040517fdbe289ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600654821015610d82576040517fd2c461b000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b54805b8015610e10575f600b610d9b6001846113fe565b81548110610dab57610dab611411565b5f91825260209091200180549091506bffffffffffffffffffffffff168510610dfd57546c01000000000000000000000000900473ffffffffffffffffffffffffffffffffffffffff16949350505050565b5080610e088161143e565b915050610d87565b505060045473ffffffffffffffffffffffffffffffffffffffff1692915050565b60025473ffffffffffffffffffffffffffffffffffffffff163314610aa1576040517f7bfa4b9f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f60418214610ebd576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f610ecb6020828587611485565b610ed4916114ac565b90505f610ee5604060208688611485565b610eee916114ac565b90505f85856040818110610f0457610f04611411565b919091013560f81c9150507f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0821115610f69576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8060ff16601b14158015610f8157508060ff16601c14155b15610fb8576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b604080515f808252602082018084528a905260ff841692820192909252606081018590526080810184905260019060a0016020604051602081039080840390855afa158015611009573d5f5f3e3d5ffd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff8116611081576040517fe415bbae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b979650505050505050565b60075473ffffffffffffffffffffffffffffffffffffffff16806110ad5750565b600854438111156110bc575050565b5f805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff000000000000000000000000000000000000000091821681178355604080518082019091526bffffffffffffffffffffffff948516815260208101918252600b8054600181018255908552905191519095166c01000000000000000000000000029316929092177f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db990930192909255600780549091169055600855565b60095473ffffffffffffffffffffffffffffffffffffffff16806111a25750565b600a54438111156111b1575050565b6001805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff000000000000000000000000000000000000000091821681178355604080518082019091526bffffffffffffffffffffffff948516815260208101918252600c805494850181555f908152905191519095166c01000000000000000000000000029316929092177fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c790910155600980549091169055600a55565b5f60208284031215611284575f5ffd5b5035919050565b803573ffffffffffffffffffffffffffffffffffffffff811681146112ae575f5ffd5b919050565b5f5f5f5f606085870312156112c6575f5ffd5b6112cf8561128b565b935060208501359250604085013567ffffffffffffffff8111156112f1575f5ffd5b8501601f81018713611301575f5ffd5b803567ffffffffffffffff811115611317575f5ffd5b876020828401011115611328575f5ffd5b949793965060200194505050565b5f5f60408385031215611347575f5ffd5b6113508361128b565b946020939093013593505050565b602081525f82518060208401528060208501604085015e5f6040828501015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011684010191505092915050565b5f602082840312156113c1575f5ffd5b6113ca8261128b565b9392505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b81810381811115610c5557610c556113d1565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f8161144c5761144c6113d1565b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b80820180821115610c5557610c556113d1565b5f5f85851115611493575f5ffd5b8386111561149f575f5ffd5b5050820193919092039150565b80356020831015610c55577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff602084900360031b1b169291505056fea164736f6c634300081e000a", - "codeHash": "0xabd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43", - "storage": { - "0x0": "0xa887dcb9d5f39ef79272801d05abdf707cfbbd1d" - } - }, "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": { "balance": "0x0", "nonce": "0x1", diff --git a/bin/mega-evme/tests/satin-differences.md b/bin/mega-evme/tests/satin-differences.md index 40079bde1..e738fb67f 100644 --- a/bin/mega-evme/tests/satin-differences.md +++ b/bin/mega-evme/tests/satin-differences.md @@ -39,9 +39,9 @@ The three Rex6 blocks of `tests/fixtures/blocks.tar.xz`, each replayed on both e | Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | History | Status differs | Logs | Refused | |---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:| -| 26400001 | 39 | 10592072 | 13873243 | 1.30 | 8818227 | 0 | 5065016 | 17 | 138 -> 121 | 4 | -| 26400007 | 25 | 8428932 | 10696856 | 1.26 | 6203136 | 0 | 4493720 | 0 | 119 -> 119 | 0 | -| 26400110 | 27 | 8051381 | 10550686 | 1.31 | 6059166 | 0 | 4491520 | 1 | 121 -> 121 | 1 | +| 26400001 | 39 | 10592072 | 13907543 | 1.31 | 8852527 | 0 | 5065016 | 17 | 138 -> 121 | 4 | +| 26400007 | 25 | 8428932 | 10745856 | 1.27 | 6252136 | 0 | 4493720 | 0 | 119 -> 119 | 0 | +| 26400110 | 27 | 8051381 | 10594786 | 1.31 | 6103266 | 0 | 4491520 | 1 | 121 -> 121 | 1 | ## Recorded transactions by call target @@ -49,7 +49,7 @@ The transactions of the three blocks grouped by the contract they call and the s | Call target | Selector | Transactions | Legacy gas | Satin gas | Satin / legacy | State gas | Status differs | Logs | |---|---|---:|---:|---:|---:|---:|---:|---| -| 0x6342000000000000000000000000000000000001 | 0x01caec13 | 31 | 2532545 | 771030 | 0.30 | 0 | 5 | 0 -> 0 | +| 0x6342000000000000000000000000000000000001 | 0x01caec13 | 31 | 2532545 | 898430 | 0.35 | 0 | 5 | 0 -> 0 | | 0x897a33a0af45b3ba097bd6045187d622252e6acd | 0x9aec351f | 30 | 18019164 | 26445264 | 1.46 | 0 | 0 | 330 -> 330 | | deposit | - | 3 | 304908 | 141288 | 0.46 | 0 | 0 | 0 -> 0 | | 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x21d5c9bb | 2 | 601407 | 832935 | 1.38 | 0 | 0 | 6 -> 6 | diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index f53ff005e..e07ae8d07 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -734,6 +734,9 @@ fn execute_and_check( let envs = factory.external_envs(block.number.saturating_to()); let db = RecordingDatabase::new(&mut state, reads.clone()); let evm = config.mode.evm_with_envs(config.fork, db, block, chain_id, envs); + // The EVM read the live system address off the pre-state when it was built, outside + // the transaction: the record keeps what the transaction read. + drop(reads.take()); execute(config, evm, tx, executed) } }; diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index a979e0271..b451d4472 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -221,12 +221,11 @@ fn test_the_witness_options_print_a_line_per_transaction() { let full = lines(&["--json-witness-full"]); assert_eq!(full.len(), 1); assert_eq!(full[0]["witness"], compact[0]["witness"]); - // A transaction rejected for its intrinsic gas read the live system address and nothing else: - // every transaction reads it first, from the `SequencerRegistry`, which the pre-state lacks. - let registry = "0x6342000000000000000000000000000000000006"; + // A transaction rejected for its intrinsic gas reads nothing: validation refuses it before it + // loads an account, and no transaction reads the `SequencerRegistry` for its classification. let reads = &full[0]["reads"]; - assert_eq!(reads["accounts"], json!({ registry: null }), "{reads}"); - assert_eq!(reads["storage"][registry].as_object().map(|slots| slots.len()), Some(1)); + assert_eq!(reads["accounts"], json!({}), "{reads}"); + assert_eq!(reads["storage"], json!({}), "{reads}"); let both = lines(&["--json-digest", "--json-witness"]); assert_eq!(both, [lines(&["--json-digest"])[0].clone(), compact[0].clone()]); From 4a02c9872dd19c68178b8ee0e0eb5def0388ad78 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:53:50 +0800 Subject: [PATCH 073/190] docs(block): the genesis block has no activation rules --- crates/mega-evm/src/block/executor.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index a4f941456..3a29f2bb3 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -180,8 +180,8 @@ pub struct MegaBlockExecutionCtx { /// out itself. /// /// `None` is a block with no parent to compare against. The genesis block, number zero, has - /// none, and neither rule applies to it, whenever Satin activates at or before its timestamp. - /// Any other block is accepted without it only where no parent could change the rules: when + /// none, and neither rule applies to it: a fork active at its timestamp is active from it, so + /// a chain on which Satin is active from genesis has no Satin activation block. Any other block is accepted without it only where no parent could change the rules: when /// every fork the schedule activates is active from timestamp zero. Where one could, executing /// the block fails with [`MegaBlockExecutionError::MissingParentTimestamp`], since the block /// would otherwise run as an ordinary one. A caller that executes a block with a parent must From 023a9c876e83292bcb170c8a21163a048ef27f37 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 12:56:34 +0800 Subject: [PATCH 074/190] feat(evm): a context built given the live system address reads nothing for it --- AGENTS.md | 2 +- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/block/executor.rs | 3 +- crates/mega-evm/src/evm/context.rs | 27 +++++++++++++ crates/mega-evm/tests/system/system_tx.rs | 49 +++++++++++++++++++++++ docs/spec/upgrades/satin.md | 2 +- 6 files changed, 81 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a8eb8cd4e..9c549c0ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -325,7 +325,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The system address may send transactions the protocol pays nothing for (`system/tx.rs`): a legacy transaction from it to a whitelisted contract is validated — the chain id, which it must carry and which no configuration switches off, the nonce, EIP-3607 — and promoted to a deposit by the engine as it runs it (the block decides on the legacy envelope: see the block executor above), and the account a deposit-like transaction creates for its caller is charged the account-creation state gas once. Which address that is, the `SequencerRegistry` says, resolved once per block after every other pre-block step (`system::resolve_system_address`): the registry's account and `_currentSystemAddress`, read off the state without the registry's code, committed as the block's last pre-block state and handed to the EVM (`MegaContext::set_system_address`); a registry that is absent, holds other code or names the zero address refuses the block (`MegaBlockExecutionError::SequencerRegistry`). No transaction reads the registry for its classification (`MegaHandler::validate_env` reads the address the context holds), so no transaction finds the registry warm or carries it in its state for that reason, and a transaction that reads it pays the cold price. - An EVM built outside block execution reads the address once when its context is built (`MegaContext::new_with_external_envs`, through `system::live_system_address`, directly off the database), so it needs no setup and charges and warms nothing; a read the database cannot serve then is made again by the next transaction, off the database, which fails with the database's error if it fails again; `MegaContext::with_system_address` hands an address in. + An EVM built outside block execution reads the address once when its context is built (`MegaContext::new_with_external_envs`, through `system::live_system_address`, directly off the database), so it needs no setup and charges and warms nothing; a read the database cannot serve then is made again by the next transaction, off the database, which fails with the database's error if it fails again; `MegaContext::new_with_system_address` builds a context given the address, which reads nothing for it, and `MegaContext::with_system_address` replaces the one a context holds. A transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — whose caller is that address is a system-address transaction. A transaction from that address without the system shape is invalid (`system::SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`, an `InvalidTransaction::Str`, so a pool and a block reject it, and op-revm includes a deposit, which never has the shape, as a failed deposit); every other sender is an ordinary one, an address a rotation retired included. The Oracle's `onlySystemAddress` tests the sender alone, so the refusal is what keeps the system key's other transactions, an L1 deposit from it included, from writing the Oracle; the legacy engine refused them with an error that is not a transaction's, so a deposit from the system address left its block unexecutable. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 0a345f24e..16a521f45 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -113,7 +113,7 @@ A `keylessDeploy` call a contract makes is not a deployment: it runs the method The system address sends the protocol's own transactions: a legacy transaction from it to a whitelisted contract is validated — the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. It is the address the `SequencerRegistry` holds, which the block resolves once, after its other pre-block steps, and hands to the EVM: no transaction reads the registry for its classification, so none finds it warm, and an access to it is cold on its first access, whatever the envelope. A transaction of that shape from that address is a system-address transaction; one of another shape from it is invalid, and a deposit from it, which never has the shape, is a failed deposit. -The registry cannot change the address inside a block after its pre-block call, so every transaction of a block is classified against the address a rotation due in the block left, and an EVM a node builds outside block execution — an RPC call, a gas estimate, the replay of a block's transactions for a trace — reads the one in the state it is built on once, when it is built, directly off the state, with nothing to set and nothing warmed or charged, so an estimate is what the transaction costs in a block (`MegaContext::with_system_address` hands an address in). +The registry cannot change the address inside a block after its pre-block call, so every transaction of a block is classified against the address a rotation due in the block left, and an EVM a node builds outside block execution — an RPC call, a gas estimate, the replay of a block's transactions for a trace — reads the one in the state it is built on once, when it is built, directly off the state, with nothing to set and nothing warmed or charged, so an estimate is what the transaction costs in a block (`MegaContext::new_with_system_address` builds a context given the address, which then reads nothing for it). In block execution a registry that is absent, holds other code or names a zero address refuses the block; outside it, such a registry promotes nothing. The resolution is the block's last pre-block state; no transaction's state carries it. The account such a transaction creates for its caller is charged the account-creation state gas exactly once. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 3a29f2bb3..9298aa72d 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -181,7 +181,8 @@ pub struct MegaBlockExecutionCtx { /// /// `None` is a block with no parent to compare against. The genesis block, number zero, has /// none, and neither rule applies to it: a fork active at its timestamp is active from it, so - /// a chain on which Satin is active from genesis has no Satin activation block. Any other block is accepted without it only where no parent could change the rules: when + /// a chain on which Satin is active from genesis has no Satin activation block. Any other + /// block is accepted without it only where no parent could change the rules: when /// every fork the schedule activates is active from timestamp zero. Where one could, executing /// the block fails with [`MegaBlockExecutionError::MissingParentTimestamp`], since the block /// would otherwise run as an ordinary one. A caller that executes a block with a parent must diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 179f78334..9755d2993 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -127,6 +127,33 @@ impl MegaContext { ) -> Self { let system_address = system::live_system_address(&mut db) .map_or(LiveSystemAddress::Unread, LiveSystemAddress::Known); + Self::build(db, spec, external_envs, system_address) + } + + /// Creates a context over `db` that executes `spec` with the given external environments, + /// under `spec`'s limits ([`ProtocolLimits::for_spec`]), classifying every transaction + /// against `system_address`, the live system address, which the caller gives: nothing is read + /// off `db` for it. `None` makes no transaction a Mega System Transaction. + /// + /// For a caller that already knows the address — read off the state with + /// [`live_system_address`](crate::system::live_system_address), or resolved by a block — or + /// that records what is read off `db` and must not record a read no transaction made. + pub fn new_with_system_address( + db: DB, + spec: MegaSpecId, + external_envs: ExternalEnvs, + system_address: Option
, + ) -> Self { + Self::build(db, spec, external_envs, LiveSystemAddress::Known(system_address)) + } + + /// The context over `db` executing `spec`, classifying against `system_address`. + fn build( + db: DB, + spec: MegaSpecId, + external_envs: ExternalEnvs, + system_address: LiveSystemAddress, + ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); let limits = ProtocolLimits::for_spec(spec).tx_runtime_limits; let inner: MegaInnerContext = diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 84d3d4590..462c01450 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -314,6 +314,55 @@ fn test_no_transaction_reads_the_registry() { } } +/// A context built without an address reads the live system address off its database when it is +/// built — the registry's account and its system-address slot, before any transaction — and a +/// Mega System Transaction run on it is then classified against it and reads nothing more of the +/// registry. A context given the address reads nothing off its database for it, and classifies +/// the same transaction the same way. +#[test] +fn test_a_context_reads_the_system_address_when_it_is_built_unless_given_one() { + use mega_evm::{ + test_utils::{RecordingDatabase, SharedWitnessRecord}, + ExternalEnvs, + }; + let registry_reads = |record: &SharedWitnessRecord| { + let record = record.borrow(); + let account = record.accounts.contains_key(&SEQUENCER_REGISTRY_ADDRESS); + let slot = + record.storage.contains_key(&(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + (account, slot) + }; + let mut cfg = CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + let tx = legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), get_slot(), 0); + + let built = SharedWitnessRecord::default(); + let ctx = MegaContext::new(RecordingDatabase::new(chain_db(), built.clone()), cfg.spec); + assert_eq!(registry_reads(&built), (true, true), "read when the context is built"); + assert_eq!(ctx.system_address(), Some(MEGA_SYSTEM_ADDRESS)); + built.borrow_mut().accounts.clear(); + built.borrow_mut().storage.clear(); + let mut evm = MegaEvm::new(ctx.with_cfg(cfg.clone())); + let outcome = evm.execute_transaction(tx.clone()).expect("a Mega System Transaction"); + assert!(evm.ctx().is_system_originated(), "classified against the address read"); + assert!(!outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS)); + assert_eq!(registry_reads(&built), (false, false), "the transaction read nothing of it"); + + let given = SharedWitnessRecord::default(); + let ctx = MegaContext::new_with_system_address( + RecordingDatabase::new(chain_db(), given.clone()), + cfg.spec, + ExternalEnvs::default(), + Some(MEGA_SYSTEM_ADDRESS), + ); + assert_eq!(registry_reads(&given), (false, false), "nothing read for a given address"); + let mut evm = MegaEvm::new(ctx.with_cfg(cfg)); + let given_outcome = evm.execute_transaction(tx).expect("a Mega System Transaction"); + assert!(evm.ctx().is_system_originated()); + assert_eq!(given_outcome.gas, outcome.gas, "the same charge either way"); + assert_eq!(registry_reads(&given), (false, false)); +} + /// No transaction starts with the registry's account or its system-address slot warm: a user's /// call to the Oracle's `setSlots` makes the Oracle ask the registry for the system address, and /// that `SLOAD` pays the cold price, as a legacy call and as an EIP-2930 call alike, which spend diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index ee06786c5..7df4be040 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1589,7 +1589,7 @@ A node, a stateless validator and a replay tool must agree on everything below, The registry's roles are what it holds once it is deployed: the bootstrap values seed only a registry the state does not hold. - **The live system address outside block execution.** An EVM a node builds outside block execution — for a call, a gas estimate or a trace — classifies its transactions against the live system address the registry holds in the state it runs on. - The reference implementation reads it once, when the EVM is built (`MegaContext` reads it off its database with `system::live_system_address`), directly and outside every transaction, so the read is neither warmed nor charged and an estimate is what the transaction costs in a block; a node that already knows the address hands it in (`MegaContext::with_system_address`), and block execution hands in the one it resolved after the block's pre-block steps. + The reference implementation reads it once, when the EVM is built (`MegaContext` reads it off its database with `system::live_system_address`), directly and outside every transaction, so the read is neither warmed nor charged and an estimate is what the transaction costs in a block; a node that already knows the address builds the EVM given it (`MegaContext::new_with_system_address`), which then reads nothing for it, and block execution hands in the one it resolved after the block's pre-block steps. A read the database cannot serve when the EVM is built is made again by the next transaction, which fails with the database's error if it fails again. - **Committing a delayed outcome.** 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)). From 838d36acf9e6613183a2e3569438345a972fb709 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:00:26 +0800 Subject: [PATCH 075/190] bench(block): a steady block deploys the system contracts and resolves the live system address --- crates/mega-evm/benches/block.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 9aa86a214..3bb7f0623 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -48,7 +48,10 @@ use alloy_primitives::{ use alloy_sol_types::SolCall; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ - system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, + system::{ + flat_system_contract_specs, IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + }, test_utils::{BytecodeBuilder, CommittedStates, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTransactionOutcome, MegaTxEnvelope, @@ -289,8 +292,10 @@ fn steady_database() -> MemoryDatabase { } /// Asserts that the pre-block changes of the bench's block on `db` are a steady block's: the two -/// calls, which write their contracts, then the read of the registry's pending changes, and no -/// read of a predeploy, which only Satin's activation block makes. Each step names one account. +/// calls, which write their contracts, then the deployment of the five flat system contracts, the +/// read of the registry's pending changes, the registry's deployment and the resolution of the +/// live system address, and no read of the EIP-7997 factory, which only Satin's activation block +/// makes. Each step names one account. fn assert_steady_pre_block(db: &MemoryDatabase) { let states = pre_block_states(db.clone(), BLOCK_NUMBER); let named: Vec<_> = states @@ -300,11 +305,10 @@ fn assert_steady_pre_block(db: &MemoryDatabase) { *state.keys().next().expect("one account") }) .collect(); - assert_eq!( - named, - [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS, SEQUENCER_REGISTRY_ADDRESS], - "a steady block reads no predeploy" - ); + let mut expected = vec![HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]; + expected.extend(flat_system_contract_specs().map(|spec| spec.address)); + expected.extend([SEQUENCER_REGISTRY_ADDRESS; 3]); + assert_eq!(named, expected, "a steady block deploys the system contracts and reads no factory"); // Outside every measured section: both calls wrote the contract the bench seeded. for (call, address) in states.iter().zip([HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]) { let writes = call[&address].storage.values().filter(|slot| slot.is_changed()).count(); From 49b2efffc779b48ded99103288922efb0c397bb2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:01:07 +0800 Subject: [PATCH 076/190] feat(evm): credit every give-back to a reservoir, and take legacy shares of state charges Satin turns on the fork's switch that credits refills, rollbacks and returned reservoirs to the reservoir alone, and sets the legacy shares of the four opcode state charges, which KeylessDeploy's signer and creation take as well. A halted first frame gives back only the part of its start record the reservoir paid. KeylessDeploy's gasUsed nets the creation's two pools together and adds back what the destruction table gave it for charges the call made. --- crates/mega-evm/src/constants.rs | 23 +++ crates/mega-evm/src/evm/context.rs | 26 ++- crates/mega-evm/src/evm/execution.rs | 23 ++- crates/mega-evm/src/evm/host.rs | 42 +++-- crates/mega-evm/src/evm/schedule.rs | 76 ++++++++- crates/mega-evm/src/limit/limit.rs | 25 ++- .../mega-evm/src/system/keyless/dispatch.rs | 50 ++++-- crates/mega-evm/src/system/keyless/settle.rs | 157 ++++++++++++------ 8 files changed, 329 insertions(+), 93 deletions(-) diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 50be6afb5..5786125be 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -23,6 +23,9 @@ //! | [`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 | +//! | [`PRE_FORK_SSTORE_SET_COST`] | 20,000 | regular gas of a fresh slot's `SSTORE` before Satin | the legacy share of a slot's state gas, in the Satin gas schedule | +//! | [`PRE_FORK_NEW_ACCOUNT_COST`] | 25,000 | regular gas of a new account before Satin | the legacy share of a new account's state gas | +//! | [`PRE_FORK_CREATE_COST`] | 32,000 | regular gas of a `CREATE` before Satin | the legacy share of a created account's state gas | //! //! 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 @@ -132,6 +135,23 @@ pub const MAX_TX_COMPUTE_GAS: u64 = pub const PRE_BLOCK_CALL_GAS_LIMIT: u64 = crate::SYSTEM_CALL_REGULAR_GAS_LIMIT + 16 * SLOT_STATE_GAS; +/// The regular gas a fresh slot's `SSTORE` cost before Satin, above its load: what a state charge +/// for a fresh slot takes from regular gas before the reservoir, less what the write already +/// charges in regular gas. A fixed pre-Satin price: the bucket multiplier does not scale it, and a +/// change of the byte prices does not move it. +pub const PRE_FORK_SSTORE_SET_COST: u64 = 20_000; + +/// The regular gas a new account cost before Satin: what a state charge for the account a value +/// call or a keyless deployment's signer creates takes from regular gas before the reservoir, and, +/// less the regular gas the schedule charges a `SELFDESTRUCT`'s new beneficiary, what that +/// beneficiary's takes. A fixed pre-Satin price. +pub const PRE_FORK_NEW_ACCOUNT_COST: u64 = 25_000; + +/// The regular gas a `CREATE` cost before Satin: less the creation's access, what a state charge +/// for the account a `CREATE`, a `CREATE2` or a keyless deployment creates takes from regular gas +/// before the reservoir. A fixed pre-Satin price. +pub const PRE_FORK_CREATE_COST: u64 = 32_000; + #[cfg(test)] mod tests { use super::*; @@ -150,5 +170,8 @@ mod tests { // 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); + assert_eq!(PRE_FORK_SSTORE_SET_COST, 20_000); + assert_eq!(PRE_FORK_NEW_ACCOUNT_COST, 25_000); + assert_eq!(PRE_FORK_CREATE_COST, 32_000); } } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 8f7d3c791..646f205ff 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -126,9 +126,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 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`. + /// disabling flag, the chain-id check, the two code-size limits, the fork's switch back to + /// revm 40.0.3's journal semantics and its switch that credits every give-back to a reservoir. + /// 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 { @@ -152,9 +152,11 @@ 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. 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. + /// cap and the code-size limits. The two exceptions are the fork's switch back to revm + /// 40.0.3's journal semantics, which stays off, the journal's semantics being part of the + /// machinery under test, not of what is priced; and its switch that credits every give-back + /// to a reservoir, which stays off too, so a give-back is credited as EIP-8037 credits it. + /// The fixture fork's schedule carries no legacy share. /// - 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 @@ -176,8 +178,10 @@ impl MegaContext { /// the fixture fork's replaces it on the [`MegaEvm`](crate::MegaEvm). #[cfg(any(test, feature = "test-utils"))] 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. + // The journal's semantics are part of the machinery, not of what is priced. Where a + // give-back goes is `MegaETH`'s pricing: the fixture's fork credits it as EIP-8037 does. cfg.legacy_journal_semantics = false; + cfg.reservoir_only_give_backs = false; self.inner = self.inner.with_cfg(op_cfg(&cfg)); self.cfg = cfg; self.neutral = true; @@ -731,6 +735,13 @@ impl MegaContext { /// 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 /// transactions a chain accepts is the chain's rule, not a caller's choice. +/// +/// Every give-back of state or history gas goes into a reservoir and never into regular gas, the +/// fork's switch for it set on whatever the caller's configuration says: a slot written back, a +/// record taken back, the destruction table's give-back, a start's charge given back when the start +/// fails, a failed frame's rollback and a reservoir a child returns. A frame's regular gas rises +/// within the frame only by the regular gas a child returns, and a frame that halts consumes its +/// regular gas with what it paid of its charges and gives back the reservoir it received. pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg.gas_params = satin_gas_params(); cfg.enable_amsterdam_eip8037 = true; @@ -742,6 +753,7 @@ pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { 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.reservoir_only_give_backs = true; cfg } diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index af6af0090..079147462 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -192,8 +192,9 @@ where runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); }; + let (first_frame, from_regular) = first_frame; let layer = &mut evm.ctx_mut().additional_limit; - layer.keep_first_frame_charge(first_frame); + layer.keep_first_frame_charge(first_frame, from_regular); layer.count_authorities(applied, created); Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -1628,19 +1629,27 @@ fn applied_authorities( /// caller that turned the nonce check off can run, and which revm answers with a success and no /// address. /// +/// The two are one charge, which the reservoir pays first and the regular budget the rest, and of +/// it the reservoir pays the authorities' records first, the list being applied first: the part of +/// the first frame's record the reservoir paid is what the authorities' records leave of it. +/// /// Answers the history gas the first frame's record was charged, which pre-execution keeps for -/// the frame's input to carry, and nothing for a transaction that pays no history; `None` when the -/// transaction cannot pay, which is an out-of-gas before it runs. +/// the frame's input to carry, with the part of it regular gas paid, which a halt of that frame +/// consumes; nothing for a transaction that pays no history; `None` when the transaction cannot +/// pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &MegaContext, gas: &mut GasTracker, applied_authorities: u64, -) -> Option { +) -> Option<(u64, u64)> { if !ctx.prices_history() { - return Some(0); + return Some((0, 0)); } - charge_write_records_history(gas, first_frame_records(ctx), applied_authorities) - .map(|(first_frame, _)| first_frame) + let reservoir = gas.reservoir(); + let (first_frame, authorities) = + charge_write_records_history(gas, first_frame_records(ctx), applied_authorities)?; + let from_reservoir = reservoir.saturating_sub(authorities).min(first_frame); + Some((first_frame, first_frame - from_reservoir)) } /// The write records the transaction's own frame makes, as the journal's state stands before the diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 637d4f99a..10d5fb085 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -480,22 +480,24 @@ impl revm::context_interface::Host /// none. It is given back as history, as it was charged, once revm's own settlement of the /// frame is made, its upfront state-gas refund included. /// - /// revm's settlement put the reservoir the frame handed back in place of the caller's, once it - /// unwound the caller's outstanding spill; a child's caller gets back here the reservoir it - /// held while the child ran (`held_reservoir`), the part it kept at the start, on top. The + /// revm's settlement put the reservoir the frame handed back in place of the caller's, as it + /// is, give-backs going to the reservoir alone; a child's caller gets back here the reservoir + /// it held while the child ran (`held_reservoir`), the part it kept at the start, on top. The /// caller then holds what it kept and what the child handed back, whatever the order of this - /// and the refunds, which read the spill and their own amount, never the reservoir. The - /// transaction's gas holds a copy of the reservoir its frame was given, which revm's - /// settlement replaced, so nothing is added back to it. + /// and the refunds, which add their own amount to the reservoir. The transaction's gas holds a + /// copy of the reservoir its frame was given, which revm's settlement replaced, so nothing is + /// added back to it. /// /// The transaction's start ends the transaction: when its frame halted, giving the charge back /// burns every regular gas the transaction's gas holds, what the refill credited and what /// revm's settlement left alike, as revm's settlement burns a halted transaction's after each /// of its own refunds; with no charge to give back nothing is burned, as revm's settlement - /// burned nothing then. revm's settlement leaves regular gas there only where an inspector - /// makes the frame hand back more reservoir than it inherited — on its input, or in its - /// result's figures — which unwinds part of the spill the charges made before the frame. A - /// child's caller runs on, and keeps its regular gas. + /// burned nothing then. With give-backs to the reservoir alone the refill credited the record + /// to the reservoir, of which only the part the reservoir paid comes back: what regular gas + /// paid of it is consumed with the frame's regular gas. revm's settlement leaves regular gas + /// there only where an inspector makes the frame hand back more reservoir than it inherited + /// — on its input, or in its result's figures — which unwinds part of the spill the charges + /// made before the frame. A child's caller runs on, and keeps its regular gas. #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); @@ -507,6 +509,13 @@ impl revm::context_interface::Host gas.refill_history(refund); if settle.depth == 0 && settle.status == SettleStatus::Halt { gas.spend_all(); + // A give-back to the reservoir alone credited the whole record there; the part + // regular gas paid is consumed with the regular gas the halt spends. + if gas.reservoir_only_give_backs() { + let from_regular = + self.additional_limit.first_frame_charge_from_regular().min(refund); + gas.set_reservoir(gas.reservoir().saturating_sub(from_regular)); + } } } } @@ -615,10 +624,23 @@ impl MegaContext { let slots = parts.slots.iter().map(|&key| { StateGasCharge::one(GasId::sstore_set_state_gas(), StateGasSite::slot(address, key)) }); + let mut leaf_given_back = 0; for charge in leaf.into_iter().chain(code).chain(slots) { let Some(price) = self.priced_state_gas(charge.id, charge.site) else { return false }; + if charge.id == GasId::new_account_state_gas() { + leaf_given_back = charge.total(price); + } gas.refill_reservoir(charge.total(price)); } + // A keyless deployment's creation that destroys the account it creates is given back the + // leaf the call paid for, or the transfer that funded the address, and its write record: + // charges the creation did not make, which its answer adds back to what it spent. + if parts.leaf { + let record = self.records_history_charge(1); + if let Some(started) = self.keyless_creation.as_mut() { + started.note_leaf_given_back(address, leaf_given_back.saturating_add(record)); + } + } true } diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 555557d5c..19b4302a6 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -2,7 +2,7 @@ //! //! 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 three 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 @@ -12,7 +12,15 @@ //! byte per byte, which is what makes a deployment pay for the bytes every node has to carry; //! 3. 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`). +//! ([`FORWARD_REDUCTION_QUOTIENT`], the fork's `GasId::call_stipend_reduction`); +//! 4. the legacy share of the state charges an opcode makes for a fresh slot, a new account and a +//! created account ([`legacy_shares`]): the part regular gas pays before the reservoir pays any +//! of it, `min(charge, PRE_FORK_COST − execution_charge)`, so state an opcode creates costs at +//! least its pre-Satin price in regular gas whether or not the transaction carries a reservoir. +//! The fork's legacy-share entries hold `PRE_FORK_COST − execution_charge`, fixed numbers that +//! neither the bucket multiplier nor the byte prices move: 10,000 for a slot, 25,000 for a value +//! call's new account, 16,000 for a `SELFDESTRUCT`'s new beneficiary and 20,000 for a created +//! account. Every other state charge has none, and no history charge has one. //! //! What else a frame start takes from its caller is the engine's, not the schedule's, and is in no //! entry of it: the share of its caller's pools — data size, KV updates, state growth — and of its @@ -145,9 +153,49 @@ pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { HISTORY_GAS_PRICED.iter().map(|&(id, bytes)| (id(), prices.cphb.fixed_size_gas(bytes))), ); params.override_gas([(GasId::call_stipend_reduction(), FORWARD_REDUCTION_QUOTIENT)]); + params.override_gas(legacy_shares(¶ms)); params } +/// The legacy shares of the state charges an opcode makes, as the fork's schedule entries hold +/// them: `PRE_FORK_COST − execution_charge` for each, the regular cost `params` gives the part of +/// the opcode that creates the state taken off its fixed pre-Satin price. +/// +/// - A fresh slot: [`PRE_FORK_SSTORE_SET_COST`] less the slot's write, +/// `sstore_set_without_load_cost`. +/// - A value call's new account: [`PRE_FORK_NEW_ACCOUNT_COST`], the call charging no regular gas +/// for the account it creates. A keyless deployment's signer takes the same share. +/// - A `SELFDESTRUCT`'s new beneficiary: [`PRE_FORK_NEW_ACCOUNT_COST`] less the schedule's new +/// account of `SELFDESTRUCT`, `new_account_cost_for_selfdestruct`. +/// - A created account: [`PRE_FORK_CREATE_COST`] less the creation's access, `create`. A keyless +/// deployment's creation takes the same share. +/// +/// [`PRE_FORK_SSTORE_SET_COST`]: crate::constants::PRE_FORK_SSTORE_SET_COST +/// [`PRE_FORK_NEW_ACCOUNT_COST`]: crate::constants::PRE_FORK_NEW_ACCOUNT_COST +/// [`PRE_FORK_CREATE_COST`]: crate::constants::PRE_FORK_CREATE_COST +pub(crate) fn legacy_shares(params: &GasParams) -> [(GasId, u64); 4] { + use crate::constants::{ + PRE_FORK_CREATE_COST, PRE_FORK_NEW_ACCOUNT_COST, PRE_FORK_SSTORE_SET_COST, + }; + [ + ( + GasId::sstore_set_state_gas_legacy_share(), + PRE_FORK_SSTORE_SET_COST + .saturating_sub(params.get(GasId::sstore_set_without_load_cost())), + ), + (GasId::new_account_state_gas_legacy_share(), PRE_FORK_NEW_ACCOUNT_COST), + ( + GasId::selfdestruct_new_account_state_gas_legacy_share(), + PRE_FORK_NEW_ACCOUNT_COST + .saturating_sub(params.get(GasId::new_account_cost_for_selfdestruct())), + ), + ( + GasId::create_state_gas_legacy_share(), + PRE_FORK_CREATE_COST.saturating_sub(params.get(GasId::create())), + ), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -178,7 +226,8 @@ mod tests { let id = GasId::new(slot); let rebuilt = STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) || - id == GasId::call_stipend_reduction(); + id == GasId::call_stipend_reduction() || + legacy_shares(&satin).iter().any(|&(entry, _)| entry == id); if rebuilt { continue; } @@ -322,6 +371,27 @@ mod tests { assert_eq!(amsterdam().get(id), 0); } + /// The legacy shares are the pre-Satin prices less what the schedule already charges in + /// regular gas for the part of the opcode that creates the state: 20,000 − 10,000 for a fresh + /// slot, 25,000 for a value call's new account, 25,000 − 9,000 for a `SELFDESTRUCT`'s new + /// beneficiary and 32,000 − 12,000 for a created account, at any byte price + /// ([`test_other_prices_move_only_the_byte_priced_entries`]). Amsterdam carries none, so its + /// state charges are EIP-8037's. + #[test] + fn test_the_legacy_shares_are_the_pre_satin_prices_less_the_execution_charges() { + let satin = satin_gas_params(); + for (id, share) in [ + (GasId::sstore_set_state_gas_legacy_share(), 10_000), + (GasId::new_account_state_gas_legacy_share(), 25_000), + (GasId::selfdestruct_new_account_state_gas_legacy_share(), 16_000), + (GasId::create_state_gas_legacy_share(), 20_000), + ] { + assert_eq!(satin.get(id), share, "{}", id.name()); + assert_eq!(satin_gas_params_history_exempt().get(id), share, "{}", id.name()); + assert_eq!(amsterdam().get(id), 0, "{}", id.name()); + } + } + /// The state entries are EIP-8037's byte counts at `MegaETH`'s price. Dividing an entry by /// the price recovers the byte count the EIP names, which is the property that survives a /// repricing. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index e7c959013..92da3e816 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -104,6 +104,11 @@ pub struct AdditionalLimit { /// makes, kept from that charge until the frame's input is built, which carries it as its /// start charge ([`take_first_frame_charge`](Self::take_first_frame_charge)). first_frame_charge: Option, + /// The part of that charge the transaction's regular gas paid, the reservoir having paid the + /// authorities' records first: what a halt of the transaction's own frame consumes with its + /// regular gas rather than gives back + /// ([`first_frame_charge_from_regular`](Self::first_frame_charge_from_regular)). + first_frame_charge_from_regular: u64, /// 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. @@ -311,6 +316,7 @@ impl AdditionalLimit { self.created_caller = false; self.pre_frame_stop = None; self.first_frame_charge = None; + self.first_frame_charge_from_regular = 0; self.kept = Kept::default(); self.decided.clear(); self.intrinsic_history_bytes = 0; @@ -477,9 +483,18 @@ impl AdditionalLimit { /// Keeps `history`, the history gas pre-execution just charged for the write record the /// transaction's own frame makes, for the frame's input to carry - /// ([`take_first_frame_charge`](Self::take_first_frame_charge)). - pub(crate) const fn keep_first_frame_charge(&mut self, history: u64) { + /// ([`take_first_frame_charge`](Self::take_first_frame_charge)), and `from_regular`, the part + /// of it the transaction's regular gas paid. + pub(crate) const fn keep_first_frame_charge(&mut self, history: u64, from_regular: u64) { self.first_frame_charge = Some(history); + self.first_frame_charge_from_regular = from_regular; + } + + /// The part of the history gas pre-execution charged for the write record the transaction's + /// own frame makes that the transaction's regular gas paid: zero until pre-execution charges + /// it, and for a transaction that pays no history. + pub(crate) const fn first_frame_charge_from_regular(&self) -> u64 { + self.first_frame_charge_from_regular } /// The history gas pre-execution charged for the write record the transaction's own frame @@ -1171,13 +1186,15 @@ mod tests { let mut limit = AdditionalLimit::default(); limit.begin_transaction(TxClass::Ordinary, 0); assert_eq!(limit.take_first_frame_charge(), None, "nothing charged yet"); - limit.keep_first_frame_charge(7); + limit.keep_first_frame_charge(7, 3); assert_eq!(limit.take_first_frame_charge(), Some(7)); assert_eq!(limit.take_first_frame_charge(), None, "taken by the frame's input"); + assert_eq!(limit.first_frame_charge_from_regular(), 3, "read where the frame settles"); - limit.keep_first_frame_charge(7); + limit.keep_first_frame_charge(7, 3); limit.begin_transaction(TxClass::ProtocolOwn, 0); assert_eq!(limit.take_first_frame_charge(), None, "the next execution begins without it"); + assert_eq!(limit.first_frame_charge_from_regular(), 0); } /// Validation admits no body whose authority records cross the data-size limit, so a debug diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 14fc16d94..2196109ed 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -52,6 +52,25 @@ pub(crate) struct Started { /// Whether the deposit of empty code at the deploy address was refused, which reverts the /// creation ([`refuses_empty_deposit`](super::settle::refuses_empty_deposit)). pub(super) empty_deposit_refused: bool, + /// The reservoir the creation was started with, its share of what the call had left. + pub(super) reservoir_share: u64, + /// What the destruction table gave the creation back for the deploy address's leaf, the last + /// time a `SELFDESTRUCT` the creation runs destroyed it: the leaf's state gas and the history + /// of its write record. Charges the creation did not make — the call made them, or the + /// transfer that funded the address — so the answer adds them back to what the creation + /// spent while the destruction stands + /// ([`note_leaf_given_back`](Self::note_leaf_given_back)). + pub(super) leaf_given_back: u64, +} + +impl Started { + /// Notes `amount`, what the destruction table just gave back for the leaf of the account at + /// `address`, when that is the deploy address. + pub(crate) fn note_leaf_given_back(&mut self, address: Address, amount: u64) { + if address == self.deploy_address { + self.leaf_given_back = amount; + } + } } /// The `keylessDeploy` call `frame_init` starts when the dispatch takes it: a `CALL` at depth 0 to @@ -150,7 +169,8 @@ pub(crate) fn ready( /// 8. Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation /// (`SignerHasCode()`). /// 9. The signer's account, when the creation's nonce bump is what creates it: state gas, priced by -/// the signer's SALT bucket. A call that cannot pay runs out of gas. +/// the signer's SALT bucket, its legacy share, a value call's new account's, from regular gas +/// before the reservoir. A call that cannot pay runs out of gas. /// 10. `gasLimitOverride`, capped to what the call has left, still covers the signed gas limit /// (`GasLimitTooLow`). /// 11. The deploy address holds no code (`ContractAlreadyExists()`), read without its code, so the @@ -159,8 +179,9 @@ pub(crate) fn ready( /// 13. What the `CREATE` opcode charges its frame for the creation's start, in the opcode's order: /// its regular gas — the schedule's `create` entry and EIP-3860's cost per word of init code — /// the created account when the deploy address is empty — state gas, priced by the deploy -/// address's SALT bucket — and the write records of the two accounts, as history. A call that -/// cannot pay runs out of gas. +/// address's SALT bucket, its legacy share from regular gas before the reservoir, as a +/// `CREATE`'s — and the write records of the two accounts, as history. A call that cannot pay +/// runs out of gas. /// 14. The gas the creation is forwarded is `gasLimitOverride`, capped to what the call has left, /// and must still cover the signed gas limit (`GasLimitTooLow`). /// @@ -170,8 +191,9 @@ pub(crate) fn ready( /// engine's, made after every rule, and step 14 holds the forward to them. /// /// A refusal writes nothing, so its return takes back the state and history gas the call was -/// charged; the regular gas it spent stays spent, as a frame's does — the overhead, and, for the -/// refusal at step 14, the `CREATE` opcode's regular gas. A database read or a SALT lookup that +/// charged, into the call's reservoir, as a reverting frame's rollback does; the regular gas it +/// spent stays spent, as a frame's does — the overhead, the legacy shares, and, for the refusal at +/// step 14, the `CREATE` opcode's regular gas. A database read or a SALT lookup that /// fails fails the transaction with its cause, as it does at every other site. /// /// # The creation @@ -219,6 +241,8 @@ pub(crate) fn start( signer_nonce: deployment.signer_nonce, signer_account_charged: deployment.signer_account_charged, empty_deposit_refused: false, + reservoir_share: reservoir, + leaf_given_back: 0, }); Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) } @@ -362,11 +386,16 @@ fn prepare( } // The signer's nonce bump is what creates an empty signer's account: a caller the `CREATE` - // opcode starts from exists already. It is charged where the legacy engine charged it, and - // the forward checked right after, before the deploy address and the balance are. + // opcode starts from exists already. It is charged where the legacy engine charged it, its + // legacy share first from regular gas as a value call's new account's is, and the forward + // checked right after, before the deploy address and the balance are. let signer_account_charged = signer_info.is_empty(); - if signer_account_charged && !gas.record_state_cost(state_gas(ctx, signer_account(signer))?) { - return Ok(Err(Refusal::OutOfGas)); + if signer_account_charged { + let share = ctx.cfg().gas_params().new_account_state_gas_legacy_share(); + let price = state_gas(ctx, signer_account(signer))?; + if !gas.record_state_cost_with_legacy_share(price, share) { + return Ok(Err(Refusal::OutOfGas)); + } } forward!(); if ctx.journal_mut().load_account(deploy_address)?.data.info.code_hash != KECCAK_EMPTY { @@ -386,9 +415,10 @@ fn prepare( let charged_create_state_gas = ctx.journal_ref().state.get(&deploy_address).is_none_or(|account| account.info.is_empty()); if charged_create_state_gas { + let share = ctx.cfg().gas_params().create_state_gas_legacy_share(); let charge = StateGasCharge::one(GasId::create_state_gas(), StateGasSite::account(deploy_address)); - if !gas.record_state_cost(state_gas(ctx, charge)?) { + if !gas.record_state_cost_with_legacy_share(state_gas(ctx, charge)?, share) { return Ok(Err(Refusal::OutOfGas)); } } diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 5541f4409..a5e8cf652 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -57,19 +57,25 @@ pub(crate) fn returning( stack: &mut FrameStack>, result: &FrameResult, ) -> Option { - ctx.keyless_creation.as_ref()?; + let started = ctx.keyless_creation.as_ref()?; if !returns_into_the_call(stack) { return None; } let result_code = result.instruction_result(); // The creation's gas as revm's settlement leaves it before the merge: a creation that failed - // rolls its state and history gas back, and one that halted spends its regular gas. + // rolls its state and history gas back into its reservoir, and one that halted spends its + // regular gas and returns the reservoir it was given. let mut gas = *result.gas(); handle_reservoir_remaining_gas(result_code, &mut GasTracker::default(), gas.tracker_mut()); + // What the destruction table gave back for the deploy address's leaf is a charge the creation + // did not make, so it does not lower what the creation spent, while the destruction stands + // when the creation ends. + let destroyed = result_code.is_ok() && ctx.accounts().is_destroyed(started.deploy_address); + let given_back = if destroyed { started.leaf_given_back } else { 0 }; Some(Creation { result: result_code, output: result.interpreter_result().output.clone(), - gas_used: creation_gas_used(&gas), + gas_used: creation_gas_used(gas.tracker(), started.reservoir_share, given_back), created: match result { FrameResult::Create(outcome) => outcome.address, FrameResult::Call(_) => None, @@ -182,9 +188,11 @@ pub(crate) fn settle( /// 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 -/// or not, and it counts nothing the call paid for the creation's start. +/// `gasUsed` is what the creation spent from both pools taken together ([`creation_gas_used`]): +/// its regular charges and the state and history gas it kept, net of every give-back of a charge it +/// made. It is the same whether the transaction has a state-gas reservoir or not, and it counts +/// nothing the call paid for the creation's start: a give-back of the call's charges the creation +/// received is added back. /// /// A creation revm reports as a success at another address than the pinned one, or at none, is a /// broken engine rather than a failed deployment: the call reverts with `AddressMismatch()` or @@ -312,18 +320,26 @@ fn halt_reason(result: InstructionResult) -> MegaHaltReason { } } -/// What a creation whose gas settled into `gas` spent, from either pool: its regular gas, and the -/// state and history gas it kept that the reservoir paid. +/// What a creation spent from both pools taken together, its gas `gas` as its own settlement left +/// it: the regular gas it was given less the regular gas it returns, plus the reservoir it was +/// given, `reservoir_share`, less the reservoir it returns, plus `given_back`, the give-backs it +/// received for charges it did not make. /// -/// Regular gas spent includes the state and history charges that spilled onto it once the -/// reservoir was empty, and nothing the reservoir paid. Adding back what the reservoir paid makes -/// the figure the same whether the transaction was funded above the execution cap or not. A -/// creation that failed kept no state or history gas: its settlement rolled both back, and a -/// halt spent its regular gas. -fn creation_gas_used(gas: &Gas) -> u64 { - let kept = gas.state_gas_spent().saturating_add(gas.history_gas_spent()); - let from_reservoir = kept.saturating_sub_unsigned(gas.state_gas_spilled()); - gas.total_gas_spent().saturating_add(u64::try_from(from_reservoir).unwrap_or_default()) +/// The two pools are netted together, not each clipped at zero: a creation that pays a state +/// charge from regular gas and then reverts returns that charge in its reservoir, which offsets +/// the regular gas it paid, so what is left is its regular charges and the state and history gas +/// it kept, net of every give-back of a charge it made. The figure is the same whether the +/// transaction carries a reservoir or not. A creation that halted returns no regular gas and the +/// reservoir it was given, so it spent its whole forward. +/// +/// The one give-back of a charge the creation did not make is the destruction table's for the +/// account being created — the state gas of its leaf and the history of its write record, which +/// the `keylessDeploy` call or the transfer that funded the address paid — and it is added back, +/// so the figure is never below the creation's regular charges. +fn creation_gas_used(gas: &GasTracker, reservoir_share: u64, given_back: u64) -> u64 { + let regular = i128::from(gas.limit()) - i128::from(gas.remaining()); + let reservoir = i128::from(reservoir_share) - i128::from(gas.reservoir()); + u64::try_from(regular + reservoir + i128::from(given_back)).unwrap_or_default() } #[cfg(test)] @@ -348,54 +364,91 @@ mod tests { ); } + /// A creation's gas with give-backs to the reservoir alone, as a Satin frame's is: `limit` of + /// regular gas and `reservoir`. + fn creation_gas(limit: u64, reservoir: u64) -> Gas { + let mut gas = Gas::new_with_regular_gas_and_reservoir(limit, reservoir); + gas.set_reservoir_only_give_backs(true); + gas + } + + /// Settles `gas` as revm settles a creation that ended with `result`. + fn settled(result: InstructionResult, mut gas: Gas) -> GasTracker { + handle_reservoir_remaining_gas(result, &mut GasTracker::default(), gas.tracker_mut()); + *gas.tracker() + } + /// The creation's spend is the same figure whichever pool paid its state and history gas. #[test] fn test_the_creation_gas_used_does_not_depend_on_the_pool() { - // No reservoir: every state and history charge spills onto regular gas. - let mut narrow = Gas::new_with_regular_gas_and_reservoir(1_000_000, 0); - assert!(narrow.record_regular_cost(30_000)); - assert!(narrow.record_state_cost(200_000)); - assert!(narrow.record_history_cost(4_000)); - - // A reservoir that pays for all of it. - let mut wide = Gas::new_with_regular_gas_and_reservoir(1_000_000, 10_000_000); - assert!(wide.record_regular_cost(30_000)); - assert!(wide.record_state_cost(200_000)); - assert!(wide.record_history_cost(4_000)); - - // Half and half: the reservoir runs dry in the middle of the state charge. - let mut split = Gas::new_with_regular_gas_and_reservoir(1_000_000, 100_000); - assert!(split.record_regular_cost(30_000)); - assert!(split.record_state_cost(200_000)); - assert!(split.record_history_cost(4_000)); - - for gas in [narrow, wide, split] { - assert_eq!(creation_gas_used(&gas), 234_000, "{gas:?}"); + for reservoir in [0, 100_000, 10_000_000] { + let mut gas = creation_gas(1_000_000, reservoir); + assert!(gas.record_regular_cost(30_000)); + assert!(gas.record_state_cost_with_legacy_share(200_000, 10_000)); + assert!(gas.record_history_cost(4_000)); + let gas = settled(InstructionResult::Stop, gas); + assert_eq!(creation_gas_used(&gas, reservoir, 0), 234_000, "reservoir {reservoir}"); } } - /// A creation that failed kept nothing but the regular gas it spent: a revert gives back the - /// spill with the rollback, a halt spends the whole forward. + /// A creation that reverts returns its state and history charges in its reservoir, whichever + /// pool paid them, so it spent its regular charges alone; one that halts spent its whole + /// forward and returns the reservoir it was given. #[test] - fn test_a_failed_creation_spent_its_regular_gas_alone() { + fn test_a_failed_creation_spent_its_regular_charges_or_its_forward() { for reservoir in [0, 10_000_000] { - let mut gas = Gas::new_with_regular_gas_and_reservoir(1_000_000, reservoir); - assert!(gas.record_regular_cost(30_000)); - assert!(gas.record_state_cost(200_000)); - gas.rollback_state_gas(); - assert_eq!(creation_gas_used(&gas), 30_000, "a revert, reservoir {reservoir}"); - gas.spend_all(); - assert_eq!(creation_gas_used(&gas), 1_000_000, "a halt, reservoir {reservoir}"); + let charged = || { + let mut gas = creation_gas(1_000_000, reservoir); + assert!(gas.record_regular_cost(30_000)); + assert!(gas.record_state_cost_with_legacy_share(200_000, 10_000)); + gas + }; + let reverted = settled(InstructionResult::Revert, charged()); + assert_eq!(creation_gas_used(&reverted, reservoir, 0), 30_000, "{reservoir}"); + let halted = settled(InstructionResult::OutOfGas, charged()); + assert_eq!(halted.reservoir(), reservoir); + assert_eq!(creation_gas_used(&halted, reservoir, 0), 1_000_000, "{reservoir}"); } } + /// A constructor that writes a fresh slot from regular gas alone and reverts reports its + /// regular charges, not the slot it gave back: 500,000 of forward and no reservoir, 113,549 of + /// regular gas spent of which 101,440 paid the slot's state gas and its record's history, both + /// returned as reservoir. + #[test] + fn test_a_reverted_fresh_slot_lowers_the_spend_by_what_regular_gas_paid_for_it() { + let mut gas = creation_gas(500_000, 0); + assert!(gas.record_regular_cost(3 + 2 + 2_100 + 10_000 + 2 + 2)); + assert!(gas.record_state_cost_with_legacy_share(97_920, 10_000)); + assert!(gas.record_history_cost(3_520)); + let gas = settled(InstructionResult::Revert, gas); + assert_eq!((gas.remaining(), gas.reservoir()), (386_451, 101_440)); + assert_eq!(creation_gas_used(&gas, 0, 0), 12_109); + } + + /// A give-back of a charge the creation did not make is added back: a constructor that + /// destroys the account it creates is given back the leaf the call paid for and its record, + /// and reports what it spent of regular gas, not that spend less the give-back. + #[test] + fn test_a_give_back_of_the_calls_charges_does_not_lower_the_spend() { + let mut gas = creation_gas(500_000, 0); + assert!(gas.record_regular_cost(2 + 5_000)); + gas.refill_reservoir(183_600); + gas.refill_history(3_520); + let gas = settled(InstructionResult::SelfDestruct, gas); + assert_eq!((gas.remaining(), gas.reservoir()), (494_998, 187_120)); + assert_eq!(creation_gas_used(&gas, 0, 187_120), 5_002); + } + /// A creation that refilled more than it charged — a slot written back that its caller had - /// filled — does not report less than the regular gas it spent. + /// filled — reports what it spent of regular gas less the give-back, which it took off a + /// charge another frame of the creation made. #[test] - fn test_a_net_refill_does_not_lower_the_regular_spend() { - let mut gas = Gas::new_with_regular_gas_and_reservoir(1_000_000, 0); + fn test_a_net_refill_nets_against_the_regular_spend() { + let mut gas = creation_gas(1_000_000, 0); assert!(gas.record_regular_cost(30_000)); - gas.refill_reservoir(50_000); - assert_eq!(creation_gas_used(&gas), 30_000); + gas.refill_reservoir(20_000); + let gas = settled(InstructionResult::Stop, gas); + assert_eq!(creation_gas_used(&gas, 0, 0), 10_000); } } From e8adc96d66477e6d30f1cac6ebc9bc3bf44d0a7e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:01:07 +0800 Subject: [PATCH 077/190] test(evm): hold the suite to reservoir-only give-backs and legacy shares Every identity that read the reservoir as gas limit less state and history now adds what regular gas paid: the legacy shares, and below the execution cap the charges a failure gave back. The destruction test that pinned a give-back crediting the spill first is rewritten for the new rule, test_a_give_back_onto_an_empty_reservoir_goes_into_the_reservoir_alone; a case pins the departure from EIP-8037's tracker against op-revm. --- crates/mega-evm/tests/block/state_gas.rs | 11 +- crates/mega-evm/tests/fuzz/properties.rs | 24 +-- crates/mega-evm/tests/satin/common.rs | 28 +++ crates/mega-evm/tests/satin/compute_gas.rs | 50 +++-- crates/mega-evm/tests/satin/data_size.rs | 44 +++-- crates/mega-evm/tests/satin/deposit_charge.rs | 22 ++- crates/mega-evm/tests/satin/detention.rs | 52 +++-- crates/mega-evm/tests/satin/equivalence.rs | 76 +++++++- crates/mega-evm/tests/satin/gas_forward.rs | 41 +++- crates/mega-evm/tests/satin/history_bytes.rs | 110 ++++++++--- .../mega-evm/tests/satin/history_exemption.rs | 20 +- crates/mega-evm/tests/satin/history_gas.rs | 27 ++- .../mega-evm/tests/satin/history_reservoir.rs | 63 +++++-- .../tests/satin/inspector_cheatcodes.rs | 6 +- .../tests/satin/inspector_settlement.rs | 111 ++++++++--- .../tests/satin/limit_matrix/destruction.rs | 35 ++-- .../tests/satin/limit_matrix/forwarding.rs | 56 +++--- .../tests/satin/limit_matrix/keyless.rs | 21 ++- crates/mega-evm/tests/satin/outcome.rs | 6 +- crates/mega-evm/tests/satin/pricing-table.md | 4 + crates/mega-evm/tests/satin/pricing_table.rs | 17 +- .../mega-evm/tests/satin/reservoir_drain.rs | 178 +++++++++++------- .../tests/satin/reservoir_settlement.rs | 82 +++++--- crates/mega-evm/tests/satin/stops.rs | 74 ++++++-- crates/mega-evm/tests/satin/strategic_stop.rs | 30 ++- .../tests/satin/synthetic_frame_gas.rs | 19 +- crates/mega-evm/tests/satin/system_call.rs | 70 ++++--- crates/mega-evm/tests/satin/transfer_logs.rs | 49 +++-- .../mega-evm/tests/system/keyless/charges.rs | 12 +- .../tests/system/keyless/inspector.rs | 9 +- .../mega-evm/tests/system/keyless/limits.rs | 49 +++-- crates/mega-evm/tests/tracers/harness.rs | 29 ++- crates/mega-evm/tests/tracers/scenarios.rs | 38 ++-- 33 files changed, 1041 insertions(+), 422 deletions(-) diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs index a1c4549c3..58cd7a017 100644 --- a/crates/mega-evm/tests/block/state_gas.rs +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -47,9 +47,9 @@ fn writes(nonce: u64, slot: u64, gas_limit: u64) -> Recovered { ) } -/// Above the execution cap the reservoir pays the state gas, and the block counts it all the same: -/// the ledger is the state gas spent, whichever pool paid it. No limit refuses a transaction for -/// the state gas the block has spent. +/// Above the execution cap the reservoir pays the state gas but each slot's legacy share, which +/// regular gas pays first, and the block counts it all the same: the ledger is the state gas spent, +/// whichever pool paid it. No limit refuses a transaction for the state gas the block has spent. #[test] fn test_the_blocks_state_gas_counts_what_the_reservoir_paid() { let slot = common::slot_state_gas(); @@ -66,7 +66,10 @@ fn test_the_blocks_state_gas_counts_what_the_reservoir_paid() { assert!(outcome.gas.reservoir_remaining > 0, "the reservoir paid it"); assert_eq!( outcome.gas.reservoir_remaining, - ABOVE_CAP - TX_GAS_LIMIT_CAP - outcome.gas.state - outcome.gas.history, + ABOVE_CAP - + TX_GAS_LIMIT_CAP - + (outcome.gas.state - slot.min(10_000)) - + outcome.gas.history, ); executor.commit_transaction_outcome(outcome).expect("no block limit refuses it"); } diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index b80765b73..67f45315c 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -185,11 +185,13 @@ fn destroyed_in_the_transaction(account: &revm::state::Account) -> bool { /// - the receipt's figure is the raw spend less the refund, at least the floor, at most the gas /// limit; /// - the refund is within its cap, a fifth of the raw spend; -/// - the reservoir is the gas above the execution cap, and it pays the state and history gas before -/// the regular budget does and nothing else: what is gone from it is exactly the state and -/// history ledgers, or all of it when they exceed it. Two rules bill it otherwise and are left -/// out: the EIP-7623 floor, when it is the receipt's figure, and op-revm's failed deposit, which -/// bills the whole gas limit; +/// - the reservoir is the gas above the execution cap, and it pays state and history gas and +/// nothing else, after a state charge's legacy share, which regular gas pays first; every +/// give-back goes into a reservoir, whichever pool paid the charge, so what comes back of it can +/// exceed what it held, and what is gone from it is at most the state and history ledgers. What +/// comes back of it and the spend fit in the gas limit. Two rules bill it otherwise and are left +/// out of the last: the EIP-7623 floor, when it is the receipt's figure, and op-revm's failed +/// deposit, which bills the whole gas limit; /// - an exempt transaction pays no history and reports no history bytes; any other reports at least /// its body and pays at most what its bytes cost, the allowances paying the rest; /// - value is conserved: the balances change by what a deposit minted, less what a self-destruction @@ -240,14 +242,14 @@ fn test_property_gas_ledgers() { let reservoir = gas_limit.saturating_sub(gas_limit.min(TX_GAS_LIMIT_CAP)); prop_check!( - gas.reservoir_remaining <= reservoir, - "no more comes back than was in the reservoir" + total + gas.reservoir_remaining <= gas_limit, + "the spend and the reservoir that comes back fit in the gas limit" ); if !failed_deposit && gas.gas_used != gas.floor { - prop_eq!( - reservoir - gas.reservoir_remaining, - reservoir.min(gas.state + gas.history), - "the reservoir pays the state and history gas first, and nothing else" + prop_check!( + reservoir.saturating_sub(gas.reservoir_remaining) <= gas.state + gas.history, + "the reservoir pays no more than the state and history gas the transaction \ + kept, and nothing else" ); } diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 24518ed4c..511f0c524 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -252,6 +252,34 @@ pub(crate) fn account_state_gas() -> u64 { mega_evm::satin_gas_params().get(revm::context_interface::cfg::GasId::new_account_state_gas()) } +/// The legacy share of a fresh slot's state gas at the byte prices in effect, in the minimum +/// bucket: the part regular gas pays before the reservoir, the slot's charge up to 10,000, the +/// pre-Satin 20,000 of a fresh slot's `SSTORE` less the 10,000 its write charges. +pub(crate) fn slot_share() -> u64 { + slot_state_gas().min(10_000) +} + +/// The legacy share of the state gas of the account a value call creates, at the byte prices in +/// effect, in the minimum bucket: the charge up to the pre-Satin 25,000. A keyless deployment's +/// signer takes the same. +pub(crate) fn account_share() -> u64 { + account_state_gas().min(25_000) +} + +/// The legacy share of the state gas of the account a `SELFDESTRUCT` creates for its beneficiary, +/// at the byte prices in effect, in the minimum bucket: the charge up to the pre-Satin 25,000 less +/// the 9,000 of regular gas the schedule charges that beneficiary. +pub(crate) fn beneficiary_share() -> u64 { + account_state_gas().min(16_000) +} + +/// The legacy share of the state gas of the account a `CREATE`, a `CREATE2` or a keyless +/// deployment creates, at the byte prices in effect, in the minimum bucket: the charge up to the +/// pre-Satin 32,000 less the creation's 12,000 access. +pub(crate) fn create_share() -> u64 { + account_state_gas().min(20_000) +} + /// The history gas `bytes` bytes cost at the byte prices in effect, by hand rather than through /// the engine's pricing: the bytes times `COST_PER_HISTORY_BYTE`, 88 gas, at the spec's price. /// diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index 45546c8fe..f7428084f 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -42,7 +42,10 @@ use revm::{ }; use crate::{ - common::{call, call_with_data, context, execute, runs_at_measurement_prices}, + common::{ + beneficiary_share, call, call_with_data, context, execute, runs_at_measurement_prices, + slot_share, + }, salt::{crowded_account, entry, minimal_envs}, }; @@ -76,14 +79,15 @@ fn arithmetic(count: usize) -> Bytes { /// The three ledgers split the raw spend, the regular one is what is neither state nor history, /// and the figure a block counts is that ledger at least the floor. Above the execution cap the -/// reservoir paid the state and history ledgers, and nothing else. -fn assert_ledgers(name: &str, gas_limit: u64, outcome: &MegaTransactionOutcome) { +/// reservoir paid the state and history ledgers but for `shares`, the legacy shares of the state +/// charges, which regular gas paid first: state gas on the state ledger all the same. +fn assert_ledgers(name: &str, gas_limit: u64, outcome: &MegaTransactionOutcome, shares: u64) { let gas = &outcome.gas; if gas_limit > TX_GAS_LIMIT_CAP { assert_eq!( gas.reservoir_remaining, - gas_limit - TX_GAS_LIMIT_CAP - gas.state - gas.history, - "{name}: the reservoir paid the state and history ledgers", + gas_limit - TX_GAS_LIMIT_CAP - (gas.state - shares) - gas.history, + "{name}: the reservoir paid the state and history ledgers but the legacy shares", ); } let result = outcome.result.gas(); @@ -119,7 +123,7 @@ fn test_a_floor_bound_transaction_counts_its_floor_and_history_comes_out_first() let tx = call_with_data(CALLER, CALLEE, Bytes::from(vec![0; CALLDATA as usize]), gas_limit); let outcome = execute(funded(), tx); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("floor-bound", gas_limit, &outcome); + assert_ledgers("floor-bound", gas_limit, &outcome, 0); let gas = outcome.gas; assert_eq!(gas.history, (TX_BODY_SIZE + CALLDATA) * COST_PER_HISTORY_BYTE); @@ -177,7 +181,7 @@ fn test_gas_an_inspector_edits_moves_the_compute_figure_with_the_receipt() { .execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)) .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("edited", gas_limit, &outcome); + assert_ledgers("edited", gas_limit, &outcome, 0); outcome.gas }; @@ -201,12 +205,15 @@ fn test_gas_an_inspector_edits_moves_the_compute_figure_with_the_receipt() { /* ---------- what the figure counts ---------- */ -/// Runs `code` at [`CALLEE`] under a plain call at `gas_limit` and requires it to succeed. +/// Runs `code` at [`CALLEE`] under a plain call at `gas_limit` and requires it to succeed. The +/// state charges it keeps take nothing from regular gas but the legacy shares of the fresh slots it +/// fills, its state ledger over a fresh slot's charge. fn computes(code: Bytes, gas_limit: u64) -> MegaGasUsage { let outcome = execute(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("computes", gas_limit, &outcome); + let shares = outcome.gas.state / SLOT_STATE_GAS * slot_share(); + assert_ledgers("computes", gas_limit, &outcome, shares); outcome.gas } @@ -314,7 +321,7 @@ fn test_a_refund_does_not_lower_the_compute_figure() { ); let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("a slot written with a refund", gas_limit, &outcome); + assert_ledgers("a slot written with a refund", gas_limit, &outcome, 0); outcome.gas }; for gas_limit in GAS_LIMITS { @@ -342,7 +349,7 @@ fn test_state_gas_stays_off_the_compute_figure_whatever_it_costs() { let db = funded().account_code(CALLEE, code.clone()).account_balance(CALLEE, U256::from(5)); let envs = crowded_account(minimal_envs(), FRESH, m); let outcome = crate::salt::run(db, envs, call(CALLER, CALLEE, U256::ZERO, gas_limit)); - assert_ledgers("a SELFDESTRUCT to a new account", gas_limit, &outcome); + assert_ledgers("a SELFDESTRUCT to a new account", gas_limit, &outcome, beneficiary_share()); outcome.gas }; let regular = destructs(1, GAS_LIMITS[0]).regular; @@ -379,7 +386,7 @@ fn with_child(rounds: usize, reverts: bool, gas_limit: u64) -> MegaGasUsage { let db = funded().account_code(CALLEE, caller).account_code(CHILD, child(rounds, reverts)); let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("a caller and its child", gas_limit, &outcome); + assert_ledgers("a caller and its child", gas_limit, &outcome, 0); outcome.gas } @@ -415,8 +422,8 @@ fn test_each_transaction_computes_its_own() { let first = evm.execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); let second = evm.execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); assert!(first.result.is_success() && second.result.is_success()); - assert_ledgers("the first transaction", gas_limit, &first); - assert_ledgers("the second transaction", gas_limit, &second); + assert_ledgers("the first transaction", gas_limit, &first, 0); + assert_ledgers("the second transaction", gas_limit, &second, 0); assert_eq!(first.gas.regular, second.gas.regular); } } @@ -465,7 +472,7 @@ fn test_below_the_cap_the_gas_limit_is_the_compute_budget() { funded().account_code(CALLEE, arithmetic(2_000)), call(CALLER, CALLEE, U256::ZERO, gas_limit), ); - assert_ledgers("the compute budget", gas_limit, &outcome); + assert_ledgers("the compute budget", gas_limit, &outcome, 0); outcome }; let spent = run(GAS_LIMITS[0]).gas.gas_used; @@ -502,7 +509,7 @@ fn test_computation_past_the_execution_cap_is_an_ordinary_out_of_gas() { outcome.result ); assert_eq!(outcome.limit_exceeded, None, "no limit of this engine stopped it"); - assert_ledgers("past the cap", gas_limit, &outcome); + assert_ledgers("past the cap", gas_limit, &outcome, 0); assert_eq!(outcome.gas.regular, TX_GAS_LIMIT_CAP, "the whole execution budget, no more"); assert_eq!(outcome.gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE); assert_eq!(outcome.gas.reservoir_remaining, reservoir - outcome.gas.history); @@ -529,7 +536,7 @@ fn test_a_nested_call_cannot_compute_past_the_cap() { let db = funded().account_code(CALLEE, caller).account_code(CHILD, past_the_cap()); let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMITS[1])); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("a nested call past the cap", GAS_LIMITS[1], &outcome); + assert_ledgers("a nested call past the cap", GAS_LIMITS[1], &outcome, 0); assert_eq!( outcome.state[&CALLEE].storage[&U256::ZERO].present_value, U256::ZERO, @@ -568,7 +575,12 @@ fn test_intrinsic_gas_past_the_execution_cap_is_rejected_before_it_runs() { let inside = (TX_GAS_LIMIT_CAP - EMPTY_CALL) / address; let admitted = execute(funded(), with_addresses(inside as usize)); assert!(admitted.result.is_success(), "{:?}", admitted.result); - assert_ledgers("an access list just inside the cap", TX_GAS_LIMIT_CAP + 200_000_000, &admitted); + assert_ledgers( + "an access list just inside the cap", + TX_GAS_LIMIT_CAP + 200_000_000, + &admitted, + 0, + ); assert_eq!(admitted.gas.regular, EMPTY_CALL + address * inside); assert_eq!( rejection(with_addresses(inside as usize + 1)), @@ -663,7 +675,7 @@ fn test_a_precompile_in_a_nested_call_is_computed() { .account_code(CHILD, child(gas).stop().build()); let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_ledgers("a precompile in a nested call", gas_limit, &outcome); + assert_ledgers("a precompile in a nested call", gas_limit, &outcome, 0); outcome.gas.regular }; run(100_000) - run(0) diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 01bb7e7ff..fee2364f0 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -35,9 +35,9 @@ use revm::{ }; use crate::common::{ - account_state_gas, body_history, call, call_with_data, constructor_returning, context, create, - execute_under, grown, history, history_is_free, history_rounds, holding_to_keep, - reservoir_giving, share, slot_state_gas, + account_state_gas, beneficiary_share, body_history, call, call_with_data, + constructor_returning, context, create, execute_under, grown, history, history_is_free, + history_rounds, holding_to_keep, reservoir_giving, share, slot_share, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000300000"); @@ -1341,14 +1341,16 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ let store_regular = params.get(GasId::sstore_static()) + 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, the new - // accounts and slots kept: the fresh slot, and `C`, which the destruction's wei creates) + // (site, code, the child's regular gas up to and including the write, the state gas's legacy + // share among it, the state gas the write 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", fresh_slot(), - 2 * 3 + store_regular, + 2 * 3 + store_regular + slot_share(), + slot_share(), slot_state_gas(), WRITE_RECORD_SIZE, WRITE_RECORD_SIZE, @@ -1360,6 +1362,7 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ log0(1), 2 * 3 + (375 + 8 + 3), 0, + 0, mega_evm::LOG_BASE_SIZE + 1, mega_evm::LOG_BASE_SIZE + 1, 0, @@ -1368,7 +1371,8 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ ( "a SELFDESTRUCT that moves value", selfdestruct_to_c(), - 3 + (5_000 + params.selfdestruct_cost(true, true)), + 3 + (5_000 + params.selfdestruct_cost(true, true)) + beneficiary_share(), + beneficiary_share(), account_state_gas(), 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, 2 * WRITE_RECORD_SIZE, @@ -1377,11 +1381,13 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ ), ]; let body = body_history(0); - for (name, code, counted_at, state, bytes, history_bytes, records, growth) in sites { + for (name, code, counted_at, share_paid, state, bytes, history_bytes, records, growth) in sites + { let record = history(history_bytes); - // `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; + // `A` holds what the body leaves of the reservoir, and hands `B` one gas short of what the + // reservoir pays of the write's state and history — all but the legacy share, which + // regular gas pays first — keeping the rest. + let given = state - share_paid + record - 1; let reservoir = body + reservoir_giving(given); let a_keeps = reservoir - body - given; let gas_limit = TX_GAS_LIMIT_CAP + reservoir; @@ -1412,7 +1418,11 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ 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"); assert_eq!(refused.usage, body_only, "{name}: the record went with the child"); - assert_eq!(refused.gas.reservoir_remaining, reservoir - body, "{name}: the reservoir"); + assert_eq!( + refused.gas.reservoir_remaining, + reservoir - body + share_paid, + "{name}: the reservoir, and the legacy share the stop gave back into it" + ); // The record kept: its history draws the reservoir's last `record - 1` and spills one gas // the child does not have, so the child runs out, and its write comes back. @@ -1424,14 +1434,12 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ assert_eq!(kept.gas.reservoir_remaining, reservoir - body, "{name}"); // 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. + // What `A` kept comes back with the transaction's own frame as it is: the reservoir `B` + // returns unwinds none of its one gas of spill. let paid = run(counted_at + 1, fits); assert!(matches!(child_bound(&paid), Bound::Success), "{name}: {:?}", paid.result); assert_eq!( - paid.gas.reservoir_remaining, - a_keeps.saturating_sub(1), + paid.gas.reservoir_remaining, a_keeps, "{name}: the share spent to the last gas" ); assert_eq!(paid.gas.history, body + record, "{name}: the body and the record"); diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 6ebb66a40..1c2d35d0e 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -40,7 +40,10 @@ use revm::{ }; use crate::{ - common::{call, context, history, history_rounds, runs_at_measurement_prices, state_is_free}, + common::{ + call, context, create_share, history, history_rounds, runs_at_measurement_prices, + state_is_free, + }, salt::entry, }; @@ -214,12 +217,13 @@ fn holding_for(pool: Pool, forward: u64) -> u64 { /// The gas `A` calls `B` with for the creation to be forwarded exactly `forward` in `pool`: what /// `B` must hold at the split, plus what it spends before it. Below the cap the created account's -/// state gas spills onto `B`'s regular gas before the split too; above it the reservoir pays it, -/// and Osaka charges none. +/// state gas spills onto `B`'s regular gas before the split too; above it regular gas pays its +/// legacy share before the reservoir pays the rest, and Osaka charges none. fn call_gas(pool: Pool, forward: u64) -> u64 { let spilled = match pool { Pool::BelowCap => created_account_state_gas(), - Pool::AboveCap | Pool::NeutralOsaka => 0, + Pool::AboveCap => create_share(), + Pool::NeutralOsaka => 0, }; let holding = holding_for(pool, forward); if pool == Pool::BelowCap { @@ -416,8 +420,16 @@ fn assert_ledgers( regular(pool, spent) + state + history, "{name}: the receipt is the three ledgers, with nothing refunded and no floor binding", ); + // Every give-back goes into a reservoir. Above the cap regular gas paid the created + // account's legacy share, which stays on the state ledger when the creation deposits and comes + // back into `B`'s reservoir when it fails, the rest of the charge with it. Below it a creation + // that failed — no state gas kept — gives `B` back the created account's state gas and its + // record's history into its reservoir, which regular gas paid. let reservoir = match pool { - Pool::AboveCap => RESERVOIR - state - history, + Pool::AboveCap => RESERVOIR + create_share() - state - history, + Pool::BelowCap if state == 0 => { + created_account_state_gas() + history_in(pool, WRITE_RECORD_SIZE) + } Pool::BelowCap | Pool::NeutralOsaka => 0, }; assert_eq!(outcome.gas.reservoir_remaining, reservoir, "{name}: the reservoir"); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 4af4fa1c2..289930375 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -301,9 +301,11 @@ pub(crate) fn assert_caught_with_stipends( /// some number of times, or forever. /// /// The stop lands on the first charge the limit leaves no room for: that charge is not made, and -/// the stopped frame keeps what it had before it ([`left`](Self::left)). +/// the stopped frame keeps what it had before it ([`left`](Self::left)). A part can carry a state +/// charge's legacy share each round makes once its regular charges are paid, which regular gas pays +/// and which is no compute ([`shares_before_crossing`](Self::shares_before_crossing)). #[derive(Clone, Debug, Default)] -pub(crate) struct Charges(Vec<(Vec, Option)>); +pub(crate) struct Charges(Vec<(Vec, Option, u64)>); impl Charges { /// `charges`, once. @@ -312,14 +314,20 @@ impl Charges { } /// `charges`, `times` times over. - pub(crate) fn repeat(mut self, charges: &[u64], times: u64) -> Self { - self.0.push((charges.to_vec(), Some(times))); + pub(crate) fn repeat(self, charges: &[u64], times: u64) -> Self { + self.repeat_with_share(charges, times, 0) + } + + /// `charges`, `times` times over, each round making a state charge whose legacy share is + /// `share` once its regular charges are paid. + fn repeat_with_share(mut self, charges: &[u64], times: u64, share: u64) -> Self { + self.0.push((charges.to_vec(), Some(times), share)); self } /// `charges`, over and over. pub(crate) fn forever(mut self, charges: &[u64]) -> Self { - self.0.push((charges.to_vec(), None)); + self.0.push((charges.to_vec(), None, 0)); self } @@ -327,7 +335,7 @@ impl Charges { pub(crate) fn total(&self) -> u64 { self.0 .iter() - .map(|(charges, times)| { + .map(|(charges, times, _)| { charges.iter().sum::() * times.expect("a program that ends") }) .sum() @@ -340,8 +348,21 @@ impl Charges { } /// [`left`](Self::left), or `None` when the program ends within `allowance`. - pub(crate) fn crossing(&self, mut allowance: u64) -> Option { - for (charges, times) in &self.0 { + pub(crate) fn crossing(&self, allowance: u64) -> Option { + self.crossing_and_shares(allowance).0 + } + + /// The legacy shares of the state charges the program made before the charge `allowance` + /// cannot pay: what regular gas paid of them, which the stop's rollback gives back into the + /// reservoir. + pub(crate) fn shares_before_crossing(&self, allowance: u64) -> u64 { + self.crossing_and_shares(allowance).1 + } + + /// [`crossing`](Self::crossing), with the legacy shares of the rounds made before it. + fn crossing_and_shares(&self, mut allowance: u64) -> (Option, u64) { + let mut shares = 0; + for (charges, times, share) in &self.0 { let round: u64 = charges.iter().sum(); if round == 0 { continue; @@ -349,18 +370,20 @@ impl Charges { let rounds = allowance / round; if times.is_some_and(|times| rounds >= times) { allowance -= round * times.unwrap(); + shares += share * times.unwrap(); continue; } allowance -= round * rounds; + shares += share * rounds; for charge in charges { if *charge > allowance { - return Some(allowance); + return (Some(allowance), shares); } allowance -= charge; } unreachable!("a round the allowance cannot pay whole has a charge it cannot pay"); } - None + (None, shares) } /// The charges of [`spin`]'s loop in a frame whose memory holds `words` words: `JUMPDEST`, the @@ -403,9 +426,14 @@ impl Charges { /// The charges of `count` writes of a fresh, cold slot, each pushing its value and its slot: /// two pushes, then `SSTORE`'s static gas and its dynamic gas, the cold access and the set. - /// Their state and history gas are not compute. + /// Their state and history gas are not compute, the slot's legacy share, which regular gas + /// pays, included. pub(crate) fn fresh_writes(self, count: u64) -> Self { - self.repeat(&[3, 3, sstore_static(), fresh_sstore()], count) + self.repeat_with_share( + &[3, 3, sstore_static(), fresh_sstore()], + count, + crate::common::slot_share(), + ) } } diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 9ba20e682..3302114ac 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -55,8 +55,8 @@ use revm::{ use crate::{ common::{ - account_state_gas, body_history, history, holding_to_keep, runs_at_measurement_prices, - slot_state_gas, + account_share, account_state_gas, body_history, history, holding_to_keep, + runs_at_measurement_prices, slot_share, slot_state_gas, }, op_reference::{self, Op, OpContext, Settled}, }; @@ -200,6 +200,7 @@ 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.reservoir_only_give_backs, "every give-back credits a reservoir"); } #[test] @@ -304,8 +305,9 @@ fn test_a_nested_value_call_with_a_reservoir_matches_op_revm() { ); assert_eq!( mega.gas.reservoir_remaining, - reservoir - mega.gas.state - mega.gas.history, - "the reservoir paid the state and the history, and nothing came back", + reservoir - (mega.gas.state - account_share()) - mega.gas.history, + "the reservoir paid the state but the new account's legacy share, which regular gas paid, \ + and the history, and nothing came back", ); assert_same_but_history(&mega, &op); } @@ -334,6 +336,68 @@ fn test_sstore_matches_op_revm() { assert_same_but_history(&mega, &op); } +/// Where Satin departs from EIP-8037's tracker: a give-back credits a reservoir and never regular +/// gas. A slot written and written back below the execution cap, where the reservoir is empty and +/// regular gas paid the slot, gives its state gas back into Satin's reservoir, where op-revm on +/// EIP-8037's tracker — the same configuration with the fork's switch off and no legacy shares — +/// credits it to regular gas. Both return what is left of either pool to the sender, so the two +/// spend the same but for Satin's history, the record it took back included, and Satin ends with +/// the slot's state gas and the record's history in its reservoir where op-revm ends with none. +/// +/// Expected values: the reservoir is the slot's state gas at the byte price in effect and one +/// record's history (`constants`); the spend is op-revm's run (`external`). +#[test] +fn test_a_slot_written_back_departs_from_eip_8037_by_crediting_the_reservoir() { + let code = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mut mega, _, cfg) = both_evms(db.clone(), block()); + assert_satin_cfg(&cfg); + let mega = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); + + let mut eip8037 = cfg.with_reservoir_only_give_backs(false); + eip8037.gas_params.override_gas( + [ + GasId::sstore_set_state_gas_legacy_share(), + GasId::new_account_state_gas_legacy_share(), + GasId::selfdestruct_new_account_state_gas_legacy_share(), + GasId::create_state_gas_legacy_share(), + ] + .map(|id| (id, 0)), + ); + let op_ctx = OpContext::new(db, OpSpecId::KARST) + .with_cfg(eip8037) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut op = OpEvm::new(op_ctx, NoOpInspector); + let op = op_reference::transact(&mut op, op_transaction(tx)).unwrap(); + + assert!(mega.result.is_success(), "{:?}", mega.result); + assert!(op.result.is_success(), "{:?}", op.result); + assert_eq!((mega.gas.state, op.result.gas().state_gas_spent_final()), (0, 0)); + assert_eq!(mega.gas.history, body_history(0), "the record was taken back"); + assert_eq!( + mega.result.gas().total_gas_spent(), + op.result.gas().total_gas_spent() + mega.gas.history, + "the two spend the same but for Satin's history", + ); + assert_eq!(op.reservoir_remaining, 0, "EIP-8037 credits the give-back to regular gas"); + assert_eq!( + mega.gas.reservoir_remaining, + slot_state_gas() + history(WRITE_RECORD_SIZE), + "Satin credits the slot's state gas and its record's history to the reservoir", + ); +} + const COINBASE: Address = address!("0x00000000000000000000000000000000000c0ffe"); /// A priced transaction pays its fee, gets its unused gas back and rewards the beneficiary and @@ -451,11 +515,13 @@ fn test_system_call_matches_op_revm() { ) .unwrap(); assert!(mega_outcome.result.is_success()); + // A system call's opcodes take their legacy shares as any frame's: the fresh slot's from its + // regular gas, the rest from its reservoir. assert_eq!( mega_outcome.reservoir_remaining, SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - - satin_gas_params().get(GasId::sstore_set_state_gas()), + (satin_gas_params().get(GasId::sstore_set_state_gas()) - slot_share()), ); assert_same(&mega_outcome, &op_outcome); } diff --git a/crates/mega-evm/tests/satin/gas_forward.rs b/crates/mega-evm/tests/satin/gas_forward.rs index 11d4f8cfc..d32e4e537 100644 --- a/crates/mega-evm/tests/satin/gas_forward.rs +++ b/crates/mega-evm/tests/satin/gas_forward.rs @@ -27,12 +27,15 @@ use revm::{ }; use crate::common::{ - account_state_gas, body_history, call, context, forward_cap, history, holding_to_keep, + account_share, account_state_gas, body_history, call, context, create_share, forward_cap, + history, holding_to_keep, }; const SENDER: Address = address!("0000000000000000000000000000000000730000"); const A: Address = address!("0000000000000000000000000000000000730001"); const B: Address = address!("0000000000000000000000000000000000730002"); +/// An account the state does not hold. +const NEW: Address = address!("0000000000000000000000000000000000730003"); /// The value call's stipend. const STIPEND: u64 = 2_300; @@ -211,7 +214,7 @@ impl Inspector, EthInterpreter> for Held { } fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { - if inputs.target_address == B { + if inputs.target_address != A { self.forwarded = Some(inputs.gas_limit); } None @@ -232,6 +235,7 @@ impl Inspector, EthInterpreter> for Held { fn held_and_forwarded(code: Bytes) -> (u64, u64) { let db = MemoryDatabase::default() .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(A, U256::from(1)) .account_balance(B, U256::from(1)) .account_code(A, code); let mut evm = MegaEvm::new(context(db)).with_inspector(Held::default()); @@ -260,9 +264,32 @@ fn test_a_call_forwards_all_but_two_percent_of_what_its_charge_leaves() { assert_eq!(forwarded, forward_cap(left)); } +/// A value `CALL` to an account empty under EIP-161 forwards all but 2 per cent of what its caller +/// holds once the call's own charges — the cold access, the value transfer and the new account's +/// legacy share, which regular gas pays before the reservoir pays the rest of its state gas — are +/// paid, and its child gets the stipend on top: the share comes off the forward. +#[test] +fn test_a_value_call_to_a_new_account_forwards_what_its_charges_and_the_share_leave() { + let params = mega_evm::satin_gas_params(); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(NEW) + .append_many([revm::bytecode::opcode::GAS, CALL, STOP]) + .build(); + let (held, forwarded) = held_and_forwarded(code); + let left = held - + params.get(GasId::warm_storage_read_cost()) - + params.get(GasId::cold_account_additional_cost()) - + params.get(GasId::transfer_value_cost()) - + account_share(); + assert_eq!(forwarded, forward_cap(left) + STIPEND); +} + /// 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. +/// charges — the `create` entry, EIP-3860's word, the memory the init code occupies and the +/// created account's legacy share — are paid; the rest of 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(); @@ -271,6 +298,10 @@ fn test_a_creation_forwards_all_but_two_percent_of_what_its_charges_leave() { .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; + let left = held - + params.get(GasId::create()) - + params.get(GasId::initcode_per_word()) - + 3 - + create_share(); assert_eq!(forwarded, forward_cap(left)); } diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 39d808df8..4b32652c2 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -45,8 +45,8 @@ use revm::{ }; use crate::common::{ - assert_answered_at_unlimited_budgets, call, call_with_data, context, create, execute, - runs_at_measurement_prices, + account_share, assert_answered_at_unlimited_budgets, beneficiary_share, call, call_with_data, + context, create, create_share, execute, runs_at_measurement_prices, slot_share, }; use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; @@ -123,8 +123,15 @@ fn callee_running(code: BytecodeBuilder) -> MemoryDatabase { } /// Asserts what the reservoir of a run above the execution cap says about its two ledgers: what -/// the transaction spent on state and history came out of it, and nothing else did. -fn assert_reservoir_paid(name: &str, gas_limit: u64, outcome: &MegaTransactionOutcome) { +/// the transaction spent on state and history came out of it, and nothing else did, but `shares`: +/// the legacy shares of the state charges its frames made, which regular gas paid before the +/// reservoir whether the charge was then kept or given back, a give-back going into a reservoir. +fn assert_reservoir_paid( + name: &str, + gas_limit: u64, + outcome: &MegaTransactionOutcome, + shares: u64, +) { if gas_limit <= TX_GAS_LIMIT_CAP { return; } @@ -132,8 +139,8 @@ fn assert_reservoir_paid(name: &str, gas_limit: u64, outcome: &MegaTransactionOu assert!(outcome.gas.reservoir_remaining > 0, "{name}: the reservoir is not exhausted"); assert_eq!( outcome.gas.reservoir_remaining, - reservoir - outcome.gas.state - outcome.gas.history, - "{name}: the reservoir paid the state and history ledgers and nothing else", + reservoir + shares - outcome.gas.state - outcome.gas.history, + "{name}: the reservoir paid the state and history ledgers but the legacy shares", ); } @@ -157,10 +164,11 @@ fn every_site_called(gas_limit: u64) -> MegaTransaction { call_with_data(CALLER, CALLEE, Bytes::from(vec![1; 10]), gas_limit) } -/// A reservoir too small for what a transaction spends on state and history runs out, and the -/// rest spills onto regular gas. That changes who paid and nothing else: the bytes, the history -/// gas and the state gas are the ones an ample reservoir leaves, the regular ledger is too — a -/// spilled charge stays on its own ledger — and the reservoir is spent to the last gas. +/// A reservoir too small for what a transaction spends on state and history, but the legacy shares +/// regular gas pays first, runs out, and the rest spills onto regular gas. That changes who paid +/// and nothing else: the bytes, the history gas and the state gas are the ones an ample reservoir +/// leaves, the regular ledger is too — a spilled charge stays on its own ledger — and the reservoir +/// is spent to the last gas. #[test] fn test_a_reservoir_that_runs_out_changes_only_who_paid() { if runs_at_measurement_prices() { @@ -168,15 +176,29 @@ fn test_a_reservoir_that_runs_out_changes_only_who_paid() { } let ample = execute(every_site(), every_site_called(TX_GAS_LIMIT_CAP + RESERVOIR)); assert!(ample.result.is_success(), "{:?}", ample.result); - assert_reservoir_paid("an ample reservoir", TX_GAS_LIMIT_CAP + RESERVOIR, &le); - let spent = ample.gas.state + ample.gas.history; + let shares = slot_share() + account_share() + create_share(); + assert_reservoir_paid("an ample reservoir", TX_GAS_LIMIT_CAP + RESERVOIR, &le, shares); + // What the reservoir pays: the state and history ledgers but the legacy shares, which regular + // gas pays first whatever the reservoir holds. + let spent = ample.gas.state + ample.gas.history - shares; - // Short of the body; short of everything but the body; short by one gas. + // Short of the body; short of everything but the body; short by one gas. A reservoir that + // runs out in the creation the callee makes last leaves what the callee kept at that start, + // which nothing after it charges: at most 2 per cent of the reservoir. for reservoir in [1, TX_BODY_SIZE * CPHB - 1, TX_BODY_SIZE * CPHB + 1, spent - 1] { let outcome = execute(every_site(), every_site_called(TX_GAS_LIMIT_CAP + reservoir)); let name = format!("a reservoir of {reservoir}"); assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - assert_eq!(outcome.gas.reservoir_remaining, 0, "{name}: spent to the last gas"); + if reservoir < spent - 1 { + assert_eq!(outcome.gas.reservoir_remaining, 0, "{name}: spent to the last gas"); + } else { + assert!( + outcome.gas.reservoir_remaining <= reservoir * 2 / 100, + "{name}: what the creator kept is left: {}", + outcome.gas.reservoir_remaining + ); + } + assert_eq!(outcome.gas.gas_used, ample.gas.gas_used, "{name}: the spend"); assert_eq!(outcome.gas.history_bytes, ample.gas.history_bytes, "{name}: the bytes"); assert_eq!(outcome.gas.history, ample.gas.history, "{name}: the history gas"); assert_eq!(outcome.gas.state, ample.gas.state, "{name}: the state gas"); @@ -189,8 +211,12 @@ fn test_a_reservoir_that_runs_out_changes_only_who_paid() { } let exact = execute(every_site(), every_site_called(TX_GAS_LIMIT_CAP + spent)); - assert_eq!(exact.gas.reservoir_remaining, 0, "a reservoir of exactly what is spent"); + assert!( + exact.gas.reservoir_remaining <= spent * 2 / 100, + "a reservoir of exactly what is spent: what the creator kept is left" + ); assert_eq!(exact.gas.regular, ample.gas.regular); + assert_eq!(exact.gas.gas_used, ample.gas.gas_used); } /// A transaction whose gas cannot pay for the record its own frame makes runs out of gas before @@ -272,7 +298,12 @@ fn test_a_creation_answered_without_running_appends_no_code() { (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); + assert_reservoir_paid( + "a creation answered without running", + gas_limit, + &outcome, + create_share(), + ); } } @@ -422,7 +453,7 @@ fn test_a_write_back_dies_with_the_frame_that_made_it() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE + WRITE_RECORD_SIZE); assert_eq!(outcome.gas.history, outcome.gas.history_bytes * CPHB); - assert_reservoir_paid("a write-back that reverts", gas_limit, &outcome); + assert_reservoir_paid("a write-back that reverts", gas_limit, &outcome, slot_share()); } } @@ -512,7 +543,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { paid_by_allowances * CPHB, "{name} at {gas_limit}: the gap is what the allowances paid", ); - assert_reservoir_paid(name, gas_limit, &outcome); + assert_reservoir_paid(name, gas_limit, &outcome, 0); } } } @@ -571,8 +602,11 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { return; } let hint = hint_call().len() as u64; + // The last column is what regular gas paid of the case's state charges, every one of which + // the reservoir pays but its legacy share: kept or given back, a legacy share is paid from + // regular gas and does not come back to it. type Case = - (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, Run, u64, u64, u64); + (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, Run, u64, u64, u64, u64); let cases: [Case; 34] = [ ( "the body", @@ -582,6 +616,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + 0, ), ( "calldata", @@ -591,6 +626,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 100, 0, 0, + 0, ), ( "an access list", @@ -600,6 +636,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 3 * ACCESS_LIST_ADDRESS_SIZE + 3 * ACCESS_LIST_SLOT_SIZE, 0, 0, + 0, ), ( "authorizations, one applied", @@ -609,6 +646,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, 0, 0, + 0, ), ( "a log", @@ -618,6 +656,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + log_bytes(2, 50), 0, 0, + 0, ), ( "a log a reverted child emitted", @@ -630,6 +669,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + 0, ), ( "a storage write", @@ -639,6 +679,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 0, + slot_share(), ), ( "a storage write written back", @@ -654,6 +695,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + slot_share(), ), ( "a value transfer's two records", @@ -663,6 +705,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, + 0, ), ( "a SELFDESTRUCT's beneficiary, and the account it clears", @@ -672,6 +715,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, + 0, ), ( "a creation transaction's code", @@ -681,6 +725,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + deploying().len() as u64 + WRITE_RECORD_SIZE + DEPLOYED, 0, 0, + 0, ), ( "a nested creation's code", @@ -690,6 +735,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + DEPLOYED, 0, 0, + create_share(), ), ( "a failed creation: its creator's nonce, and no code", @@ -699,6 +745,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 0, + create_share(), ), ( "output EIP-3541 refuses to deposit", @@ -708,6 +755,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 0, + create_share(), ), ( "output past the code-size limit", @@ -717,6 +765,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 0, + create_share(), ), ( "a creation transaction whose output EIP-3541 refuses", @@ -726,6 +775,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + refused_code().len() as u64, 0, 0, + 0, ), ( "a call an interceptor answers without a frame", @@ -738,6 +788,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 0, + slot_share(), ), ( "a value call an interceptor refuses without a frame", @@ -747,6 +798,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + 0, ), ( "a first frame answered with the stop", @@ -756,6 +808,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + 0, ), ( "a stop at a child's write, which its caller catches: its log is kept", @@ -771,6 +824,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + LOG_BASE_SIZE, 0, 0, + slot_share(), ), ( "a hint sent by the transaction: its calldata is history, its payload is not", @@ -780,6 +834,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + hint_call().len() as u64, 1, 0, + 0, ), ( "a hint sent from a frame", @@ -792,6 +847,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 1, 0, + 0, ), ( "a transfer that creates its recipient", @@ -801,6 +857,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 1, + 0, ), ( "a transaction whose own frame writes, logs, deploys and reverts", @@ -816,6 +873,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + slot_share() + create_share(), ), ( "every site at once", @@ -834,6 +892,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { DEPLOYED, 0, 1, + slot_share() + account_share() + create_share(), ), ( "an authority applied twice is one record", @@ -843,6 +902,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, 0, 0, + 0, ), ( "the sender's own authorization: in the body, and no record beside it", @@ -852,6 +912,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + AUTHORIZATION_SIZE, 0, 0, + 0, ), ( "a SELFDESTRUCT's beneficiary the destruction creates, and the account it clears", @@ -861,6 +922,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, + beneficiary_share(), ), ( "a SELFDESTRUCT to the sender records the account it clears alone: the sender's \ @@ -871,6 +933,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 1, + 0, ), ( "a SELFDESTRUCT that moves nothing records nothing", @@ -880,6 +943,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + 0, ), ( "a stop at a value call before its frame is built: nothing its start would write is \ @@ -893,6 +957,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 0, + slot_share(), ), ( "a slot written, then written back by a delegate: the record is taken back", @@ -908,6 +973,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + slot_share(), ), ( "a slot a delegate wrote, written back by its caller", @@ -923,6 +989,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + slot_share(), ), ( "a slot written, then written back by a call to itself", @@ -932,10 +999,11 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { TX_BODY_SIZE, 0, 0, + slot_share(), ), ]; - for (name, db, tx, run, bytes, hints, moves) in cases { + for (name, db, tx, run, bytes, hints, moves, shares) in cases { for gas_limit in GAS_LIMITS { let limit = match run { Run::Limited(limit) | Run::Caught(limit) => limit, @@ -972,7 +1040,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { bytes * CPHB, "{name} at {gas_limit}: the history gas is the bytes at the price", ); - assert_reservoir_paid(name, gas_limit, &outcome); + assert_reservoir_paid(name, gas_limit, &outcome, shares); } } } diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index e1a94976d..6ca513daf 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -37,7 +37,9 @@ use revm::{ ExecuteEvm, }; -use crate::common::{context, deposit, runs_at_measurement_prices}; +use crate::common::{ + account_share, context, create_share, deposit, runs_at_measurement_prices, slot_share, +}; const CALLER: Address = address!("0000000000000000000000000000000000400000"); const CONTRACT: Address = address!("0000000000000000000000000000000000400001"); @@ -274,7 +276,10 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { } const RESERVOIR: u64 = 100_000_000; for gas_limit in [GAS_LIMIT, TX_GAS_LIMIT_CAP + RESERVOIR] { - let run = |mut tx: MegaTransaction| { + // `shares` is what regular gas paid of the state charges, their legacy shares: the + // program's fresh slot, the account its value call creates and the account it creates; + // the system transaction's fresh slot in the Oracle. + let run = |mut tx: MegaTransaction, shares: u64| { tx.0.base.gas_limit = gas_limit; let outcome = MegaEvm::new(context(db())) .execute_transaction(tx) @@ -283,14 +288,15 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { if gas_limit > TX_GAS_LIMIT_CAP { assert_eq!( gas.reservoir_remaining, - RESERVOIR - gas.state - gas.history, - "the reservoir paid the state and history ledgers", + RESERVOIR + shares - gas.state - gas.history, + "the reservoir paid the state and history ledgers but the legacy shares", ); } outcome }; + let program_shares = slot_share() + account_share() + create_share(); - let paying = run(call_from(CALLER, CONTRACT)).gas; + let paying = run(call_from(CALLER, CONTRACT), program_shares).gas; assert!(paying.history_bytes > 0); assert_eq!( paying.history, @@ -298,10 +304,10 @@ fn test_an_exempt_transaction_reports_no_history_bytes() { "at {gas_limit}: the control pays for every byte it reports", ); - let deposit = run(deposit(call_from(CALLER, CONTRACT))).gas; + let deposit = run(deposit(call_from(CALLER, CONTRACT)), program_shares).gas; assert_eq!((deposit.history, deposit.history_bytes), (0, 0), "at {gas_limit}: a deposit"); assert!(deposit.state > 0, "at {gas_limit}: the exemption is history's alone"); - let system = run(system_tx()); + let system = run(system_tx(), slot_share()); assert!(system.result.is_success(), "at {gas_limit}: {:?}", system.result); assert_eq!(written_oracle_slot(&system), Some(ORACLE_VALUE), "at {gas_limit}"); let system = system.gas; diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 37bc7f614..3a8fce980 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -19,8 +19,8 @@ use revm::{ }; use crate::common::{ - body_history, call, call_with_data, create, deploying, execute, history, history_is_free, - history_rounds, reservoir_share, runs_at_measurement_prices, + account_share, body_history, call, call_with_data, create, create_share, deploying, execute, + history, history_is_free, history_rounds, reservoir_share, runs_at_measurement_prices, }; const CALLER: Address = address!("0000000000000000000000000000000000200000"); @@ -362,12 +362,13 @@ fn test_every_call_kind_charges_its_records_after_its_forward() { 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() { + // transaction's own frame and joins its reservoir as it is: a returned reservoir + // unwinds no spill, so what was kept is what is left. + if let Some(reservoir) = reservoir { assert_eq!( - exact.gas.reservoir_remaining, 0, - "{case}: the spill took what was kept" + exact.gas.reservoir_remaining, + reservoir - given, + "{case}: what was kept is left" ); } @@ -400,7 +401,12 @@ fn test_no_gas_limit_buys_a_write_record_for_nothing() { } let reservoirs = [1, body(0) / 2, body(0) + WRITE_RECORD_SIZE * CPHB, 1_000_000, 100_000_000]; let above_the_cap = reservoirs.map(|reservoir| TX_GAS_LIMIT_CAP + reservoir); - for code in [transfers_everything_to(CONTRACT), creates_everything()] { + // The transfer creates `CONTRACT`, and the creation its account: regular gas pays each + // account's legacy share before the reservoir pays any of the rest. + for (code, shares) in [ + (transfers_everything_to(CONTRACT), account_share()), + (creates_everything(), create_share()), + ] { for limit in [300_000, 400_000, 600_000, 800_000, 1_000_000, 5_000_000] .into_iter() .chain(above_the_cap) @@ -411,8 +417,9 @@ fn test_no_gas_limit_buys_a_write_record_for_nothing() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( outcome.gas.reservoir_remaining, - reservoir.saturating_sub(outcome.gas.state + outcome.gas.history), - "at a {limit} gas limit: the reservoir paid what it could of state and history", + reservoir.saturating_sub(outcome.gas.state + outcome.gas.history - shares), + "at a {limit} gas limit: the reservoir paid what it could of state and \ + history but the legacy shares", ); } assert_eq!( diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 99c2090a9..244ade5f2 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -34,8 +34,8 @@ use revm::bytecode::opcode::{ use crate::{ common::{ - body_history, call, execute, history_is_free, history_rounds, runs_at_measurement_prices, - state_is_free, + account_share, body_history, call, create_share, execute, history_is_free, history_rounds, + runs_at_measurement_prices, state_is_free, }, salt::{crowded_account, minimal_envs, salt_context}, }; @@ -110,14 +110,19 @@ fn calls_a_refusing_interceptor() -> Bytes { } /// Runs the same transaction above and below the execution cap and holds the two to the same -/// ledgers: above the cap the reservoir pays what regular gas pays below it, and the reservoir -/// left over is the gas limit above the cap less the state and history the ledgers report. +/// ledgers: above the cap the reservoir pays what regular gas pays below it but the legacy shares, +/// `shares`, which regular gas pays first either way, and the reservoir left over is the gas limit +/// above the cap less the state and history the ledgers report, the shares excepted. Below the +/// cap the reservoir holds what the frames were given back, `given_back`: regular gas paid it, and +/// a give-back goes into a reservoir. /// /// Returns the above-the-cap outcome, for a case that has more to say about it. #[track_caller] fn assert_the_reservoir_pays_what_regular_gas_pays( name: &str, db: impl Fn() -> MemoryDatabase, + shares: u64, + given_back: u64, ) -> MegaTransactionOutcome { let above = execute(db(), call(CALLER, CALLEE, U256::ZERO, ABOVE_CAP)); let below = execute(db(), call(CALLER, CALLEE, U256::ZERO, BELOW_CAP)); @@ -127,11 +132,15 @@ fn assert_the_reservoir_pays_what_regular_gas_pays( assert_eq!(above.gas.history, below.gas.history, "{name}: the history ledger"); assert_eq!(above.gas.state, below.gas.state, "{name}: the state ledger"); assert_eq!(above.gas.regular, below.gas.regular, "{name}: the regular ledger"); - assert_eq!(below.gas.reservoir_remaining, 0, "{name}: below the cap there is no reservoir"); + assert_eq!( + below.gas.reservoir_remaining, given_back, + "{name}: below the cap the reservoir holds what was given back" + ); assert_eq!( above.gas.reservoir_remaining, - ABOVE_CAP - TX_GAS_LIMIT_CAP - above.gas.state - above.gas.history, - "{name}: the reservoir paid exactly the state and the history the ledgers report", + ABOVE_CAP - TX_GAS_LIMIT_CAP + shares - above.gas.state - above.gas.history, + "{name}: the reservoir paid exactly the state and the history the ledgers report but the \ + legacy shares", ); above } @@ -145,9 +154,12 @@ fn test_a_value_call_pays_its_records_out_of_the_reservoir() { return; } let code = transfers_to(CONTRACT); - let outcome = assert_the_reservoir_pays_what_regular_gas_pays("a value call", || { - funded().account_code(CALLEE, code.clone()) - }); + let outcome = assert_the_reservoir_pays_what_regular_gas_pays( + "a value call", + || funded().account_code(CALLEE, code.clone()), + account_share(), + 0, + ); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.usage.write_records, 2, "the caller's account and the recipient's"); @@ -163,9 +175,12 @@ fn test_a_nested_creation_pays_its_records_out_of_the_reservoir() { return; } let code = creates(); - let outcome = assert_the_reservoir_pays_what_regular_gas_pays("a nested creation", || { - funded().account_code(CALLEE, code.clone()) - }); + let outcome = assert_the_reservoir_pays_what_regular_gas_pays( + "a nested creation", + || funded().account_code(CALLEE, code.clone()), + create_share(), + 0, + ); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.usage.write_records, 2, "the created account and the creator's nonce"); @@ -180,12 +195,16 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { return; } let code = transfers_to(CONTRACT); - let outcome = - assert_the_reservoir_pays_what_regular_gas_pays("a value call whose child reverts", || { + let outcome = assert_the_reservoir_pays_what_regular_gas_pays( + "a value call whose child reverts", + || { funded() .account_code(CALLEE, code.clone()) .account_code(CONTRACT, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) - }); + }, + 0, + 2 * RECORD, + ); assert!(outcome.result.is_success(), "the caller survives its child's revert"); assert_eq!( @@ -220,12 +239,16 @@ fn test_a_halting_child_gives_its_records_back_as_a_reverting_one_does() { .append(POP) .append(STOP) .build(); - let outcome = - assert_the_reservoir_pays_what_regular_gas_pays("a value call whose child halts", || { + let outcome = assert_the_reservoir_pays_what_regular_gas_pays( + "a value call whose child halts", + || { funded() .account_code(CALLEE, code.clone()) .account_code(CONTRACT, Bytes::from_static(&[INVALID])) - }); + }, + 0, + 2 * RECORD, + ); assert!(outcome.result.is_success(), "the caller survives its child's halt"); assert_eq!( @@ -259,6 +282,8 @@ fn test_an_intercepted_value_call_gives_its_records_back_once() { .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) }, + 0, + 2 * RECORD, ); assert!(outcome.result.is_success(), "the caller survives the refusal"); diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 6a296f7a5..d15238d7b 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -39,7 +39,7 @@ use revm::{ }; use crate::{ - common::{body_history, call, context, reservoir_share}, + common::{body_history, call, context, reservoir_share, slot_share}, salt::entry, }; use mega_evm::test_utils::{record_start_ledger_settlements, take_start_ledger_settlements}; @@ -453,10 +453,10 @@ fn test_a_cheatcode_at_foundrys_default_gas_limit_leaves_its_caller_what_it_kept assert_eq!(cheated.state[&TARGET].info.balance, U256::ONE, "the cheatcode ran"); let (plain, _) = run_with_gas_limit(db(), false, FOUNDRY_GAS_LIMIT); // `TEST` holds the whole reservoir when it calls the cheatcode, and the two fresh slots draw - // it. + // it but their legacy shares, which regular gas pays first. 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); + let slots = 2 * (entry(GasId::sstore_set_state_gas()) - slot_share() + 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"); diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index bb4c43dcb..b7fbb90f4 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -40,7 +40,8 @@ use revm::{ use crate::{ common::{ - assert_answered_at_unlimited_budgets, authorizing_call, history_is_free, state_is_free, + assert_answered_at_unlimited_budgets, authorizing_call, create_share, history_is_free, + slot_share, state_is_free, }, salt::{ create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, @@ -168,17 +169,37 @@ fn body_usage(tx: &MegaTransaction) -> LimitUsage { LimitUsage { data_size: transaction_body_bytes(tx), write_records: 0, state_growth: 0 } } +/// What regular gas paid of `charges`, state and history charges a failure gave back, at +/// `gas_limit`: every one of them below the execution cap, where there is no reservoir, and their +/// legacy shares, `shares`, above it. A give-back goes into a reservoir, so that is what the +/// transaction's reservoir holds beyond what its own reservoir left; a frame that halts consumes +/// it instead, and is given back nothing of it. +const fn regular_paid(gas_limit: u64, charges: u64, shares: u64) -> u64 { + if gas_limit > TX_GAS_LIMIT_CAP { + shares + } else { + charges + } +} + /// 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. -fn assert_keeps_only_its_body(case: &str, tx: &MegaTransaction, outcome: &MegaTransactionOutcome) { +/// nothing else, so what is left of it comes back, with `given_back`: what regular gas paid of the +/// charges its failures gave back ([`regular_paid`]), which went into a reservoir. +fn assert_keeps_only_its_body( + case: &str, + tx: &MegaTransaction, + outcome: &MegaTransactionOutcome, + given_back: u64, +) { let body = transaction_body_bytes(tx); assert_eq!(outcome.gas.state, 0, "{case}: no state gas"); assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "{case}: the body's history"); assert_eq!( outcome.gas.reservoir_remaining, - tx.gas_limit().saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(outcome.gas.history), - "{case}: the reservoir less the body's history" + tx.gas_limit().saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(outcome.gas.history) + + given_back, + "{case}: the reservoir less the body's history, and what was given back" ); assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); assert_eq!(outcome.usage, body_usage(tx), "{case}"); @@ -231,7 +252,11 @@ fn test_a_failed_call_revived_into_a_success_settles_as_a_success() { 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()); - assert_keeps_only_its_body("the failed call", &tx, &failed); + // The reverted frame gives back its fresh slot, its two slots' records and its log. + let record = history_gas(mega_evm::WRITE_RECORD_SIZE).unwrap(); + let charges = entry(GasId::sstore_set_state_gas()) + 2 * record + history_gas(160).unwrap(); + let given_back = regular_paid(gas_limit, charges, slot_share()); + assert_keeps_only_its_body("the failed call", &tx, &failed, given_back); let revived = inspected(reverting.clone(), minimal_envs(), tx.clone(), Revives); assert!(revived.result.is_success(), "{case}: {:?}", revived.result); @@ -276,7 +301,12 @@ fn test_a_failed_value_call_revived_into_a_success_keeps_its_charges() { 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()); - assert_keeps_only_its_body("the failed call", &tx, &failed); + // The halted call's caller is given back the account in its bucket and the start's two + // records. + let account = 3 * entry(GasId::new_account_state_gas()); + let charges = account + history_gas(2 * mega_evm::WRITE_RECORD_SIZE).unwrap(); + let given_back = regular_paid(gas_limit, charges, account.min(25_000)); + assert_keeps_only_its_body("the failed call", &tx, &failed, given_back); let revived = inspected(db(caller(0)), envs(), tx.clone(), Revives); assert!(revived.result.is_success(), "{case}: {:?}", revived.result); @@ -309,7 +339,8 @@ fn test_the_transactions_own_failed_frame_revived_into_a_success_keeps_its_charg 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); + // A halt of the transaction's own frame consumes what regular gas paid. + assert_keeps_only_its_body("the failed transaction", &tx, &failed, 0); let revived = inspected(db(Bytes::new()), envs(), tx.clone(), Revives); assert!(revived.result.is_success(), "{case}: the inspector's: {:?}", revived.result); @@ -581,10 +612,18 @@ fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_new_targets_pr 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"); + // The upfront charge took its legacy share from regular gas and the rest from the + // reservoir; everything given back — the charge at the new target's price and the + // start's two records — went into the reservoir. let kept = i128::from(account_m * account) - i128::from(retarget_m * account); + let records = i128::from(history_gas(2 * mega_evm::WRITE_RECORD_SIZE).unwrap()); 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 }; + let reservoir = if reservoir == 0 { + i128::from(retarget_m * account) + records + } else { + reservoir - kept + i128::from((account_m * account).min(25_000)) + }; assert_eq!( i128::from(reverted.gas.state), kept.max(0), @@ -686,11 +725,21 @@ 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 { + // The account in its bucket and the start's records: charged before the transaction's own + // frame, which has no legacy share, or by the call one down, whose share regular gas pays. + let account = 3 * entry(GasId::new_account_state_gas()); + let records = |count| history_gas(count * mega_evm::WRITE_RECORD_SIZE).unwrap(); let cases = [ - ("the transaction's own", Bytes::new(), to(EMPTY, 1, Bytes::new(), gas_limit)), - ("one call down", caller.clone(), to(CONTRACT, 0, Bytes::new(), gas_limit)), + ("the transaction's own", Bytes::new(), to(EMPTY, 1, Bytes::new(), gas_limit), 1, 0), + ( + "one call down", + caller.clone(), + to(CONTRACT, 0, Bytes::new(), gas_limit), + 2, + account.min(25_000), + ), ]; - for (at, code, tx) in cases { + for (at, code, tx, record_count, shares) in cases { let db = || db(code.clone()); let ran = plain(db(), envs(), tx.clone()); assert!(holds_something(&ran, EMPTY), "{at}: run, the call adds the account"); @@ -702,7 +751,15 @@ fn test_a_value_call_rewritten_into_a_failure_keeps_its_state_and_bills_its_body rewritten.state[&EMPTY].info, ran.state[&EMPTY].info, "{case}: the account the success added" ); - assert_keeps_only_its_body(&case, &tx, &rewritten); + // A revert gives the charges back; a halt of the transaction's own frame consumes + // what regular gas paid of them, while one call down the caller survives the halt + // and is given them back. + let given_back = if at == "the transaction's own" && result.is_halt() { + 0 + } else { + regular_paid(gas_limit, account + records(record_count), shares) + }; + assert_keeps_only_its_body(&case, &tx, &rewritten, given_back); } } } @@ -1085,7 +1142,9 @@ fn test_a_creation_refused_on_its_creators_account_counts_no_record() { /// [`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. +/// is on the history ledger beyond the body's bytes. The refused start gives back the created +/// account's state gas and its record's history into the creator's reservoir, of which regular gas +/// paid all below the execution cap and the account's legacy share above it. fn assert_keeps_only_its_body_and_the_opcodes_charge( case: &str, tx: &MegaTransaction, @@ -1093,12 +1152,18 @@ fn assert_keeps_only_its_body_and_the_opcodes_charge( ) { let body = transaction_body_bytes(tx); let charged = history_gas(body + mega_evm::WRITE_RECORD_SIZE).unwrap(); + let account = entry(GasId::create_state_gas()); + let given_back = regular_paid( + tx.gas_limit(), + account + history_gas(mega_evm::WRITE_RECORD_SIZE).unwrap(), + create_share(), + ); 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" + tx.gas_limit().saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(charged) + given_back, + "{case}: the reservoir less what the history ledger bills, and what was given back" ); assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); assert_eq!(outcome.usage, body_usage(tx), "{case}"); @@ -1279,10 +1344,10 @@ fn test_a_halting_child_handed_more_reservoir_leaves_its_caller_its_regular_gas( /// The transaction's own frame halts with no start charge to give back — it moves no value, so it /// makes no write record — after an authorization the transaction applied before it, whose account /// and record were charged below the execution cap and spilled onto regular gas. An inspector -/// hands the frame back one more reservoir than it inherited, which unwinds one gas of that spill -/// into regular gas, so no reservoir is left. With nothing to give back nothing is burned, as -/// revm's settlement burned nothing then: the sender keeps that one gas, and the transaction bills -/// one gas less than its run without the inspector, with the same history and reservoir. +/// hands the frame back one more reservoir than it inherited, which the transaction's reservoir +/// takes as it is: a returned reservoir unwinds no spill. With nothing to give back nothing is +/// burned: the sender gets that one gas back with the reservoir, and the transaction bills one gas +/// less than its run without the inspector, with the same history. #[test] fn test_the_transactions_own_halt_with_no_start_charge_keeps_what_its_settlement_left() { if history_is_free() || state_is_free() { @@ -1300,7 +1365,11 @@ fn test_the_transactions_own_halt_with_no_start_charge_keeps_what_its_settlement let halted = inspected(invalid(), minimal_envs(), tx.clone(), adds); assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); assert_eq!(halted.gas.history, ran.gas.history, "{case}: the history"); - assert_eq!(halted.gas.reservoir_remaining, ran.gas.reservoir_remaining, "{case}: unwound"); + assert_eq!( + halted.gas.reservoir_remaining, + ran.gas.reservoir_remaining + 1, + "{case}: the extra reservoir stays a reservoir" + ); assert_eq!(halted.gas.gas_used, ran.gas.gas_used - 1, "{case}: one regular gas kept"); } } diff --git a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs index cd9d7d23e..7bf239920 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs @@ -517,7 +517,9 @@ fn test_value_then_create2_then_destruct_gives_the_value_calls_leaf_back() { /// 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. +/// credited, and the creation fails with no beneficiary. Its creator is given back the created +/// account's state gas and its record's history, which its own regular gas paid, into its +/// reservoir, which the transaction ends with. #[test] fn test_a_beneficiary_charge_the_frame_cannot_pay_halts_before_the_give_back() { if !pins_state() { @@ -553,7 +555,11 @@ fn test_a_beneficiary_charge_the_frame_cannot_pay_halts_before_the_give_back() { 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); + assert_eq!( + outcome.gas.reservoir_remaining, + ACCOUNT_LEAF_STATE_GAS_M1 + RECORD_HISTORY, + "the failed creation's account and record come back into the creator's reservoir" + ); } /// After the mark, an `SSTORE` of the destroyed account's own slot, `(original 0, present @@ -1278,14 +1284,15 @@ impl Inspector, EthInterpreter> for DestructionGas } /// 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. +/// stores two fresh slots of its own, which its regular gas pays, 195,840 of state gas and 7,040 +/// of history, 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, all of it into the frame's reservoir: no give-back +/// credits regular gas, which falls by the opcode's own 5,000 alone. Read at the opcode with an +/// inspector. At the transaction's end the reservoir holds the whole give-back, which returns to +/// the sender, and no state gas stays. #[test] -fn test_a_give_back_onto_an_empty_reservoir_credits_the_spill_first() { +fn test_a_give_back_onto_an_empty_reservoir_goes_into_the_reservoir_alone() { if !pins_state() { return; } @@ -1320,10 +1327,14 @@ fn test_a_give_back_onto_an_empty_reservoir_credits_the_spill_first() { 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!(after + 5_000, before, "regular gas is credited nothing"); + assert_eq!(reservoir_after, spilled + rest, "the whole give-back goes to the reservoir"); assert_eq!(outcome.gas.state, 0); - assert_eq!(outcome.gas.reservoir_remaining, 0, "the credit meets the callers' spill too"); + assert_eq!( + outcome.gas.reservoir_remaining, + spilled + rest, + "the reservoir returns to the callers as it is" + ); } /// A creation transaction whose constructor destroys its own account. On success the created diff --git a/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs b/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs index be1b98ecf..5d88ad79f 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs @@ -109,9 +109,10 @@ fn test_a_child_receives_the_reservoir_share() { ); } -/// 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. +/// The child spends one fresh slot, its legacy share from regular gas and the rest from its +/// reservoir share, and reverts. Its rollback gives the whole charge back into its reservoir, the +/// share regular gas paid included, so its caller holds the reservoir it had after the body's +/// charge and the share on top. 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; @@ -126,27 +127,28 @@ fn test_a_reverted_child_returns_its_reservoir_share() { 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); + assert_eq!(outcome.gas.reservoir_remaining, R + common::slot_share()); } -/// The share a failed child returns when its caller has an outstanding spill. +/// The share a failed child returns when its caller has an outstanding spill joins what the +/// caller kept, and unwinds nothing. /// /// 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. +/// child fills 50 fresh slots, whose state gas past their legacy shares is 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 joins the part +/// the caller kept, so the caller ends with `k`, the spill standing. At `m` = 1, `R` = 4,396,000 +/// and `k` = 87,920. /// -/// 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. +/// 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 `k` stays the +/// transaction's reservoir, which returns to the sender. #[test] -fn test_a_reverted_childs_share_unwinds_the_callers_spill_first() { +fn test_a_reverted_childs_share_joins_what_its_caller_kept() { if common::state_is_free() { return; } - let r = 50 * common::slot_state_gas(); + let r = 50 * (common::slot_state_gas() - common::slot_share()); let kept = r * RESERVOIR_KEPT_PERCENT / 100; let left = kept * RESERVOIR_KEPT_PERCENT / 100; if left == 0 { @@ -171,11 +173,8 @@ fn test_a_reverted_childs_share_unwinds_the_callers_spill_first() { 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"); + assert_eq!(ended.1, kept, "the returned share joined what was kept; k = {kept}"); + assert_eq!(outcome.gas.reservoir_remaining, kept, "and the transaction's settlement kept it"); } /// `CALL` with gas argument 1 still forwards the reservoir share, `R − R × 2 / 100` of the @@ -394,13 +393,13 @@ fn test_neutral_forwards_eip150_and_satin_keeps_its_cap_without_limits() { 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. +/// Below the execution cap the reservoir starts at 0. The callee fills a fresh slot, so its +/// regular gas pays the 97,920 of state gas and the record's 3,520 of history. Called again, the +/// callee clears the slot. The refill and the record's give-back land in the callee's reservoir, +/// and the returned reservoir joins the caller's without unwinding the regular gas the caller's +/// first child paid: the 101,440 stay in the reservoir and return to the sender. #[test] -fn test_a_returned_reservoir_unwinds_the_callers_spill() { +fn test_a_returned_reservoir_does_not_unwind_the_callers_spill() { if !at_spec_prices() || common::state_is_free() { return; } @@ -432,7 +431,8 @@ fn test_a_returned_reservoir_unwinds_the_callers_spill() { 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" + outcome.gas.reservoir_remaining, + common::slot_state_gas() + common::history(mega_evm::WRITE_RECORD_SIZE), + "the returned refill stays 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 index 8459f2cc8..cde66e284 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs @@ -216,10 +216,12 @@ fn keyless_failure(outcome: &mega_evm::MegaTransactionOutcome) -> KeylessDeployE 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. +/// What the reservoir pays of the creation's state-gas and history charges the call makes before +/// it forwards the reservoir: the signer's leaf and the deploy address's leaf, each but its legacy +/// share, which regular gas pays first, and one record for each. fn start_charges() -> u64 { - 2 * common::account_state_gas() + 2 * common::history(super::WRITE_RECORD_SIZE) + 2 * common::account_state_gas() - common::account_share() - common::create_share() + + 2 * common::history(super::WRITE_RECORD_SIZE) } /// 1,001 distinct new authorities, below the execution cap. Apply none. The transaction's own @@ -575,9 +577,10 @@ fn test_a_keyless_creation_from_nonce_1_takes_the_bump_back() { /// 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 +/// the destroying frame, inside the creation: charges the call made, not the creation, so the +/// give-back is added back to what the creation returned. The code is deposited after the mark: +/// no state gas, and its data size and history stay charged, paid from the reservoir the give-back +/// filled. `gasUsed` is the regular gas the creation spent and the deposited byte's history. The /// account is removed at the end of the transaction. #[test] fn test_a_keyless_constructor_that_self_destructs_answers_empty_code() { @@ -604,7 +607,11 @@ fn test_a_keyless_constructor_that_self_destructs_answers_empty_code() { }; 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!( + gas_used, + forwarded - left + super::HISTORY_GAS_PER_BYTE, + "gasUsed is the creation's regular gas and the history it kept" + ); 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!( diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index d5d9fbf85..c67b8a5b9 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -52,7 +52,9 @@ fn test_outcome_reports_the_ledgers() { let result_gas = outcome.result.gas(); assert_eq!(gas.regular + gas.state + gas.history, result_gas.total_gas_spent()); assert_eq!(gas.gas_used, result_gas.tx_gas_used()); - // Both slots are new, so both draw state gas, and the reservoir is what pays it. + // Both slots are new, so both draw state gas, and the reservoir is what pays it but each + // slot's 10,000 legacy share, which regular gas pays first: state gas on the state ledger all + // the same. assert_eq!(gas.state, 2 * SLOT_STATE_GAS); // The body's history comes out of the same reservoir, before the state gas does, and each of // the two new slots leaves a write record that is history too. @@ -63,7 +65,7 @@ fn test_outcome_reports_the_ledgers() { ); assert_eq!( gas.reservoir_remaining, - 1_000_000_000 - TX_GAS_LIMIT_CAP - 2 * SLOT_STATE_GAS - gas.history, + 1_000_000_000 - TX_GAS_LIMIT_CAP - 2 * (SLOT_STATE_GAS - 10_000) - gas.history, ); assert_eq!( outcome.usage, diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index f491908f4..1487dff68 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -57,6 +57,10 @@ 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 | +| create_state_gas_legacy_share | 0 | 0 | 20000 | +| selfdestruct_new_account_state_gas_legacy_share | 0 | 0 | 16000 | +| new_account_state_gas_legacy_share | 0 | 0 | 25000 | +| sstore_set_state_gas_legacy_share | 0 | 0 | 10000 | | 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 92c5fef48..5a4ab25da 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -313,11 +313,22 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { // 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 — and so is the quotient of the regular gas a call forwards, Rex6's 98/100 in place - // of EIP-150's 63/64. The parts of the pools and of the reservoir a caller keeps from the - // frame it starts, and a value call's history allowance, are the engine's and in no entry. + // of EIP-150's 63/64, and so are the legacy shares of the four state charges an opcode makes, + // which Amsterdam leaves at zero. The parts of the pools and of the reservoir a caller keeps + // from the frame it starts, and a value call's history allowance, are the engine's and in no + // entry. + let mut differing = differing; + differing.sort_unstable(); assert_eq!( differing, - ["call_stipend_reduction", "code_deposit_history_gas"], + [ + "call_stipend_reduction", + "code_deposit_history_gas", + "create_state_gas_legacy_share", + "new_account_state_gas_legacy_share", + "selfdestruct_new_account_state_gas_legacy_share", + "sstore_set_state_gas_legacy_share", + ], "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 index 6ec0a0550..59c1f3e97 100644 --- a/crates/mega-evm/tests/satin/reservoir_drain.rs +++ b/crates/mega-evm/tests/satin/reservoir_drain.rs @@ -26,13 +26,14 @@ //! //! 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 +//! regular gas only, a state or history charge draws its legacy share from regular gas, then the +//! reservoir, and spills the rest 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 joining what the +//! caller kept and unwinding nothing; a frame that reverts gives every charge it made back into its +//! reservoir, whichever pool paid it, and one that halts hands back the share it was given; 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 @@ -67,8 +68,9 @@ use revm::{ }; 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, + account_state_gas, body_history, call, context, create_share, execute, forward_cap, history, + reservoir_giving, reservoir_share, runs_at_measurement_prices, share, slot_share, + slot_state_gas, }; const SENDER: Address = address!("0000000000000000000000000000000000710000"); @@ -119,8 +121,7 @@ const SWEEP: [u64; 5] = [400_000_000, 800_000_000, 1_200_000_000, 1_600_000_000, 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. +/// gas its regular gas paid, a legacy share or a spill, which no give-back lowers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Pools { regular: u64, @@ -139,16 +140,19 @@ impl Pools { 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 { + /// A state or history charge draws its legacy share, `min(cost, share)`, from regular gas, + /// then the reservoir, and spills the rest onto regular gas; regular gas must pay the share + /// and the spill together. + fn draw(&mut self, cost: u64, share: u64) -> Result<(), Halt> { + let share = cost.min(share); + let from_reservoir = (cost - share).min(self.reservoir); + let from_regular = cost - from_reservoir; + if from_regular > self.regular { return Err(Halt); } self.reservoir -= from_reservoir; - self.regular -= spill; - self.spill += spill; + self.regular -= from_regular; + self.spill += from_regular; Ok(()) } @@ -161,18 +165,14 @@ impl Pools { 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) { + /// A child's return, handing back `child`: its regular gas comes back, what its regular gas + /// paid for state and history joins this frame's count, and the reservoir it hands back joins + /// what this frame kept, unwinding nothing. A child that halted hands back no regular gas and + /// no count. + fn absorb(&mut self, child: Self) { 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; + self.spill += child.spill; + self.reservoir += child.reservoir; } } @@ -184,7 +184,7 @@ fn first_frame(gas_limit: u64) -> Pools { 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.draw(body_history(0), 0).expect("the body fits"); Pools { spill: 0, ..pools } } @@ -379,9 +379,10 @@ impl Charge { } /// 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`. + /// the reservoir paid the whole charge but its legacy share, which regular gas pays first, less + /// the closing `GAS`. fn body_regular(self) -> u64 { - self.operands_regular() + self.opcode_regular() + self.operands_regular() + self.opcode_regular() + self.share() } /// The bytes one charge appends: a log's 32 for its address and 32 per topic plus its data, @@ -405,6 +406,14 @@ impl Charge { } } + /// The legacy share of one charge's state gas, which regular gas pays before the reservoir. + fn share(self) -> u64 { + match self { + Self::Log0Data | Self::Log4 => 0, + Self::FreshSlot => slot_share(), + } + } + /// The state gas of one charge. fn state(self) -> u64 { match self { @@ -421,7 +430,12 @@ impl Charge { /// 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 + self.operands_regular() + + self.opcode_regular() + + LOOP_REGULAR + + self.state() + + self.history() + + 64 } } @@ -576,12 +590,12 @@ fn model_callee(callee: Callee, start: Pools, budget: Budget) -> CalleeModel { return Err(Halt); } pools.regular(charge.opcode_regular())?; - pools.draw(charge.state())?; + pools.draw(charge.state(), charge.share())?; // 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())?; + pools.draw(charge.history(), 0)?; state += charge.state(); history += charge.history(); pools.regular(G_BASE)?; @@ -602,11 +616,16 @@ fn model_callee(callee: Callee, start: Pools, budget: Budget) -> CalleeModel { .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) - } + // The revert gives every charge back into the reservoir, whichever pool paid it: the + // share the frame was given, and what its regular gas paid on top, which stays counted. + CalleeEnd::Crossed(_) => ( + Pools { + regular: pools.regular, + reservoir: start.reservoir + pools.spill, + spill: pools.spill, + }, + LimitUsage::ZERO, + ), CalleeEnd::Halted => (Pools::new(0, start.reservoir), LimitUsage::ZERO), }; let (state, history) = if end == CalleeEnd::Returned { (state, history) } else { (0, 0) }; @@ -701,11 +720,11 @@ fn model_work(slots: u64, mut pools: Pools, mut budget: Budget) -> WorkEnd { return Err(Halt); } pools.regular(G_SSTORE_SET_COLD)?; - pools.draw(slot_state_gas())?; + pools.draw(slot_state_gas(), slot_share())?; if let Err(stop) = budget.count(SLOT_COUNTS) { return Ok(WorkEnd::Stopped(stop, pools)); } - pools.draw(history(WRITE_RECORD_SIZE))?; + pools.draw(history(WRITE_RECORD_SIZE), 0)?; pools.regular(WORK_AFTER)?; } pools.regular(WORK_OUT)?; @@ -790,11 +809,11 @@ fn predict(scenario: Scenario, work: Option) -> Prediction { // 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.absorb(Pools::new(0, handed.reservoir)); 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); + pools.absorb(callee.handed_back); budget_after_call.merge(callee.kept); let pools_after_return = pools; pools.regular(G_BASE).unwrap(); @@ -952,9 +971,10 @@ impl Measured { self.forward() - self.callee.pools.regular } - /// The reservoir `C` consumed: what `A` held at the call less what it holds after it. + /// The reservoir `C` consumed: what `A` held at the call less what it holds after it, nothing + /// when `C` handed back more than it was given. fn consumed(&self) -> u64 { - self.reservoir_at_call - self.reservoir_after_call + self.reservoir_at_call.saturating_sub(self.reservoir_after_call) } fn completed(&self) -> bool { @@ -1031,10 +1051,13 @@ fn assert_settled( ) { let (callee_state, callee_history, callee_kept) = callee; let body = body_history(0); - let nothing_kept = |what: &str| { + // `given_back` is what regular gas paid of the charges a failure gave back into the + // reservoir: nothing on a halt, which consumes it. + let nothing_kept = |what: &str, given_back: u64| { assert_eq!( - outcome.gas.reservoir_remaining, p.reservoir_at_call, - "{name}: the reservoir comes back whole on {what}" + outcome.gas.reservoir_remaining, + p.reservoir_at_call + given_back, + "{name}: the reservoir comes back whole on {what}, with what regular gas paid" ); assert_eq!(outcome.gas.history, body, "{name}: the body alone on {what}"); assert_eq!(outcome.gas.state, 0, "{name}: no state on {what}"); @@ -1086,7 +1109,7 @@ fn assert_settled( ); // 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"); + nothing_kept("a halt", 0); assert_eq!( outcome.gas.gas_used, scenario.gas_limit - p.reservoir_at_call, @@ -1114,9 +1137,10 @@ fn assert_settled( }), "{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"); + // The revert gives A's state and history back into its reservoir, C's merged charges + // included: the reservoir it was given and what its regular gas paid, which comes back + // to the sender with its regular gas. + nothing_kept("a stop", at.spill); assert_eq!( outcome.gas.gas_used, scenario.gas_limit - p.reservoir_at_call - at.regular - at.spill, @@ -1218,7 +1242,7 @@ fn run_with(scenario: Scenario, work: Option) -> Measured { ); } } - // What C hands back, its reservoir unwinding A's spill first, is what A holds after the call. + // What C hands back, its reservoir joining what A kept, 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"); @@ -1569,14 +1593,17 @@ fn test_the_reservoir_a_logging_callee_consumes_grows_with_its_forward() { 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. +/// The same with fresh `SSTORE`s, whose state and history both draw the reservoir, each slot but +/// its legacy share, which regular gas pays first: past the forward from a forward of 1,000,000 +/// 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. A forward of 100,000 leaves the callee one slot before what it +/// keeps for another, and of that slot the reservoir pays 91,440, less than the forward. /// /// 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. +/// reverts, and its charges and the share come back to `A`, with the legacy shares of the 981 +/// slots its regular gas paid on top, so `A` holds more reservoir than at the call. 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() { @@ -1584,11 +1611,17 @@ fn test_a_writing_callees_state_growth_budget_stops_it_before_its_share_runs_out } let rows = forward_sizes(Charge::FreshSlot); let (all, explicit) = rows.split_last().unwrap(); - assert_past_the_forward(explicit); + let (one_slot, past) = explicit.split_first().unwrap(); + assert_eq!(one_slot.charges, 1, "a forward of 100,000 writes one slot"); + assert!(one_slot.consumed() < one_slot.forward(), "of which the reservoir pays less"); + assert_past_the_forward(past); for row in explicit { assert_eq!( row.consumed(), - row.charges * (Charge::FreshSlot.state() + Charge::FreshSlot.history()) + row.charges * + (Charge::FreshSlot.state() - Charge::FreshSlot.share() + + Charge::FreshSlot.history()), + "the reservoir pays each slot but its legacy share" ); assert_eq!( row.prediction.budget_after_call.left.state_growth, @@ -1599,7 +1632,8 @@ fn test_a_writing_callees_state_growth_budget_stops_it_before_its_share_runs_out 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)), + all.handed.reservoir > + (growth + 1) * (slot_state_gas() - slot_share() + 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"); @@ -1608,7 +1642,11 @@ fn test_a_writing_callees_state_growth_budget_stops_it_before_its_share_runs_out 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_eq!( + all.reservoir_after_call, + all.reservoir_at_call + all.charges * slot_share(), + "C's charges and its share come back to A, with the shares C's regular gas paid" + ); assert!(all.completed(), "A's work completes"); print_table("5. Forward sizes, fresh SSTOREs (400M)", &rows); } @@ -1699,7 +1737,11 @@ fn test_a_deploying_callee_charges_the_reservoir_hundreds_of_times_its_forward() 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()), + reservoir_share( + p.handed.reservoir - + (account_state_gas() - create_share()) - + creation_records_history() + ), "{name}: the creation's share" ); assert!(deposit_charges(size) <= created_with.reservoir, "{name}: the share pays it"); @@ -1709,7 +1751,11 @@ fn test_a_deploying_callee_charges_the_reservoir_hundreds_of_times_its_forward() 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_eq!( + consumed, + deployment_charges(size) - create_share(), + "{name}: the reservoir paid the deployment but the created account's legacy share" + ); assert!(consumed > 100 * forward, "{name}: a hundred times the forward: {consumed}"); let mut after_gas = after; diff --git a/crates/mega-evm/tests/satin/reservoir_settlement.rs b/crates/mega-evm/tests/satin/reservoir_settlement.rs index 78dd0c0b7..69bd14cbf 100644 --- a/crates/mega-evm/tests/satin/reservoir_settlement.rs +++ b/crates/mega-evm/tests/satin/reservoir_settlement.rs @@ -1,14 +1,16 @@ //! What a frame's caller holds of the EIP-8037 reservoir once its frame settled into it: the part -//! of its reservoir it kept while the frame ran, and what the frame hands back on top, once that -//! has unwound the caller's outstanding spill, last in first out. The transaction's frame is given -//! the whole reservoir, of which the transaction's gas keeps a copy until the frame settles, and -//! the transaction's gas then holds what its frame hands back alone. +//! of its reservoir it kept while the frame ran, and what the frame hands back on top, as it is — +//! a returned reservoir unwinds nothing. The transaction's frame is given the whole reservoir, of +//! which the transaction's gas keeps a copy until the frame settles, and the transaction's gas then +//! holds what its frame hands back alone. //! //! An inspector reads the transaction's frame's gas at the end of each `CALL` it makes, once the //! start took the child's share out of it; the child's gas when the child ends, before revm settles //! it; and the frame's gas again at the instruction after the `CALL`, once the child settled into -//! it. A child that failed hands back the share it was given, its draws undone; one that succeeded -//! hands back what it left, and its spill joins the caller's. +//! it. A child that succeeded hands back what it left, and what its regular gas paid for state and +//! history joins its caller's count of that; one that reverted hands back its share with every +//! charge it made in it, the part its regular gas paid included, which joins the count too; one +//! that halted hands back the share it was given, and what its regular gas paid is consumed. use alloy_primitives::{address, Address, U256}; use mega_evm::{ @@ -29,7 +31,8 @@ use revm::{ }; use crate::common::{ - body_history, call, context, history, history_is_free, slot_state_gas, state_is_free, + body_history, call, context, history, history_is_free, slot_share, slot_state_gas, + state_is_free, }; const SENDER: Address = address!("0000000000000000000000000000000000740000"); @@ -48,8 +51,8 @@ const IDLE: Address = address!("0000000000000000000000000000000000740006"); /// The new slots [`SPENDER`] writes. const SPENT_SLOTS: u64 = 4; -/// What funds a frame's state and history charges beside its regular gas: its reservoir, and the -/// spill those charges made onto its regular gas that is still outstanding. +/// What funds a frame's state and history charges beside its regular gas: its reservoir, and what +/// its regular gas paid of those charges, a legacy share or a spill, which no give-back lowers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Funding { reservoir: u64, @@ -128,8 +131,17 @@ impl Inspector, EthInterpreter> for Settlements { 2 => { let index = self.children.len() - 1; let child = &mut self.children[index]; + // A revert puts every charge the child made back into its reservoir, whichever + // pool paid it, and keeps the count of what regular gas paid; a halt gives back + // the share and consumes what regular gas paid. + let charged = gas.state_gas_spent() + gas.history_gas_spent(); child.handed_back = Some(if result.is_ok() { funding(gas) + } else if result.is_revert() { + Funding { + reservoir: gas.reservoir().saturating_add_signed(charged), + spilled: gas.state_gas_spilled(), + } } else { Funding { reservoir: child.share, spilled: 0 } }); @@ -205,23 +217,22 @@ fn run(db: MemoryDatabase, gas_limit: u64, value: u64) -> Run { } /// What a caller that kept `kept` holds once a child that hands back `handed_back` settled into -/// it: the reservoir the child hands back unwinds the caller's spill, the child's own merged in, -/// as far as it goes, and the rest joins the part the caller kept. +/// it: the reservoir the child hands back joins the part the caller kept, unwinding nothing, and +/// what the child's regular gas paid joins the caller's count of it. const fn after_settlement(kept: Funding, handed_back: Funding) -> Funding { - let spilled = kept.spilled + handed_back.spilled; - let unwound = if handed_back.reservoir < spilled { handed_back.reservoir } else { spilled }; Funding { - reservoir: kept.reservoir + handed_back.reservoir - unwound, - spilled: spilled - unwound, + reservoir: kept.reservoir + handed_back.reservoir, + spilled: kept.spilled + handed_back.spilled, } } /// Each child of the transaction's frame settles into what the frame kept of its reservoir: one -/// that succeeded after a write hands back what it left of its share, one that reverted or halted -/// after a write its whole share, and one that spent past its share hands back nothing and its -/// spill; the next child's share then unwinds that spill as it comes back. The frame kept two per -/// cent of its reservoir at every start, and the transaction's gas, which holds none of it, ends -/// with what the frame hands back. +/// that succeeded after a write hands back what it left of its share, one that reverted after a +/// write its share and the write's charges, its legacy share included, one that halted after a +/// write its share, and one that spent past its share hands back nothing and the count of what its +/// regular gas paid; the next child's share then joins what the frame kept, and the count stands. +/// The frame kept two per cent of its reservoir at every start, and the transaction's gas, which +/// holds none of it, ends with what the frame hands back. #[test] fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_hands_back() { if state_is_free() { @@ -241,14 +252,26 @@ fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_ha "{child}: kept {kept:?}, handed back {handed_back:?}" ); } - let [ok, _, _, spender, idle] = read.children[..] else { unreachable!() }; + let [ok, reverter, halter, spender, idle] = read.children[..] else { unreachable!() }; let kept = ok.kept.expect("the CALL ended").reservoir; assert!(kept > 0, "the frame keeps part of its reservoir: {kept}"); assert_eq!(kept, (kept + ok.share) * 2 / 100, "two per cent of it"); + // The reverter's write took its legacy share from regular gas and the rest, with the record's + // history, from its share, which covers them: the revert gives back all of it. + assert_eq!( + reverter.handed_back, + Some(Funding { reservoir: reverter.share + slot_share(), spilled: slot_share() }), + "the reverter hands back its share and what its regular gas paid" + ); + assert_eq!(halter.handed_back, Some(Funding { reservoir: halter.share, spilled: 0 })); assert!(spender.handed_back.expect("ended").spilled > 0, "the spender spills"); let idle_kept = idle.kept.expect("the CALL ended"); - assert!(idle_kept.spilled > 0 && idle.share > 0, "the idle child's share unwinds the spill"); - assert_eq!(idle.after.expect("settled").spilled, idle_kept.spilled - idle.share); + assert!(idle_kept.spilled > 0 && idle.share > 0, "the idle child's share and the spill"); + assert_eq!( + idle.after, + Some(Funding { reservoir: idle_kept.reservoir + idle.share, spilled: idle_kept.spilled }), + "the idle child's share joins what was kept, and unwinds no spill" + ); let (result, ended) = read.frame_ended.expect("the frame ended"); assert!(result.is_ok(), "{result:?}"); @@ -258,11 +281,12 @@ fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_ha /// The transaction's frame hands back what a child's would, into gas whose copy of the reservoir it /// gave the frame the settlement replaces, nothing added back: what the frame left after a child -/// that kept a part of it and a write of its own when it succeeds, the whole reservoir it was -/// given when it reverts or halts. A halt of a frame whose value transfer was charged a start -/// charge gives the charge back first and then burns the transaction's regular gas: above the cap -/// the charge comes back into the reservoir; below it, where the charge spilled onto the -/// transaction's regular gas, it comes back there and is burned with the rest. +/// that kept a part of it and a write of its own when it succeeds; the reservoir it was given and +/// every charge it and the child made, the two writes' legacy shares regular gas paid included, +/// when it reverts; the reservoir it was given when it halts. A halt of a frame whose value +/// transfer was charged a start charge gives back the part of the charge the reservoir paid and +/// then burns the transaction's regular gas: above the cap the reservoir paid all of it, which +/// comes back into the reservoir; below it regular gas paid it, and it is burned with the rest. #[test] fn test_the_transactions_gas_holds_what_its_frame_hands_back_and_nothing_more() { if state_is_free() { @@ -293,6 +317,8 @@ fn test_the_transactions_gas_holds_what_its_frame_hands_back_and_nothing_more() assert_eq!(start_refund != 0, value != 0 && !ok && !history_is_free(), "{case}"); let expected = if ok { after_settlement(Funding::NONE, ended).reservoir + } else if end == revm::bytecode::opcode::REVERT { + given + 2 * slot_share() } else if gas_limit > TX_GAS_LIMIT_CAP { given + start_refund } else { diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 4b47e490a..45eb7b565 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -365,8 +365,18 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { assert_eq!(outcome.gas.state, twin.gas.state, "{cell}: state"); assert_eq!(outcome.gas.history, twin.gas.history, "{cell}: history"); assert_eq!(outcome.gas.history_bytes, twin.gas.history_bytes, "{cell}"); + // Every charge the failed frames made comes back into the reservoir, the part regular gas + // paid included: the twin's crossing write charged its record's history too, which the + // stopped write never charges, so below the execution cap, where regular gas paid it, the + // twin's reservoir holds it on top. + let unpaid_record = if gas_limit <= TX_GAS_LIMIT_CAP && limit != Limit::Compute { + crate::common::history(WRITE_RECORD_SIZE) + } else { + 0 + }; assert_eq!( - outcome.gas.reservoir_remaining, twin.gas.reservoir_remaining, + outcome.gas.reservoir_remaining, + twin.gas.reservoir_remaining - unpaid_record, "{cell}: the reservoir comes back, less what was kept" ); assert_eq!( @@ -1123,11 +1133,15 @@ fn with_oracle_read(db: MemoryDatabase) -> MemoryDatabase { /// set, billed the intrinsic gas plus the compute up to the charge that crosses that limit, `left` /// short of it, and nothing of the gas the transaction had left. `A` crossed it, and ran the last /// step: itself, or after a callee that crossed first returned the stop into it, on what the limit -/// left it. Returns the limit and what the transaction read. +/// left it. The stop gives every charge its frames made back into the reservoir, of which regular +/// gas paid `shares`, the legacy shares of the fresh slots written before the crossing: the +/// reservoir holds them on top of what the intrinsic run leaves. Returns the limit and what the +/// transaction read. fn assert_detention_stop( db: MemoryDatabase, limits: EvmTxRuntimeLimits, left: u64, + shares: u64, ) -> (u64, mega_evm::VolatileDataAccess) { let intrinsic = intrinsic(roomy()); let (recorded, last) = @@ -1154,7 +1168,7 @@ fn assert_detention_stop( assert_eq!(outcome.limit_exceeded, Some(stop)); assert_eq!(outcome.gas.regular, intrinsic.gas.regular + used); assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + used); - assert_eq!(outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining); + assert_eq!(outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining + shares); assert!(outcome.result.logs().is_empty()); (limit, detention.accessed()) } @@ -1180,7 +1194,8 @@ 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, detention_limits(), left); + let shares = pop_then_writes().shares_before_crossing(CAP); + let (limit, accessed) = assert_detention_stop(db, detention_limits(), left, shares); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); assert_eq!(accessed, mega_evm::VolatileDataAccess::TIMESTAMP); } @@ -1197,9 +1212,12 @@ fn test_nested_call_block_env_access_child_oog() { .account_code(B, child.stop().build()); // The child's crossing, then the caller's `POP` and write, from the room the child's crossing // charge was not made from. + let shares = pop_then_writes().shares_before_crossing(CAP); let left = pop_then_writes().left(CAP); - let left = Charges::default().then(&[2]).fresh_writes(1).left(left); - let (limit, _) = assert_detention_stop(db, detention_limits(), left); + let after = Charges::default().then(&[2]).fresh_writes(1); + let shares = shares + after.shares_before_crossing(left); + let left = after.left(left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left, shares); assert!(limit - CAP < 10_000, "the child read near the start: {}", limit - CAP); } @@ -1215,11 +1233,11 @@ fn test_parent_block_env_access_oog_after_nested_call() { .account_code(B, child.stop().build()); // The read's `POP`, the call's five pushes, its address, `GAS` and cold access, the child's // two pushes, `ADD` and `POP`, the caller's `POP`, then the writes. - let left = Charges::default() + let charges = Charges::default() .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, detention_limits(), left); + .fresh_writes(slots_past_the_cap()); + let (left, shares) = (charges.left(CAP), charges.shares_before_crossing(CAP)); + let (limit, _) = assert_detention_stop(db, detention_limits(), left, shares); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); } @@ -1231,7 +1249,8 @@ 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, detention_limits(), left); + let shares = oracle_pops_then_writes().shares_before_crossing(ORACLE_ACCESS_COMPUTE_GAS); + let (limit, accessed) = assert_detention_stop(db, detention_limits(), left, shares); assert!(limit - ORACLE_ACCESS_COMPUTE_GAS < 10_000, "{}", limit - ORACLE_ACCESS_COMPUTE_GAS); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1242,7 +1261,8 @@ 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, detention_limits(), left); + let shares = oracle_pops_then_writes().shares_before_crossing(ORACLE_ACCESS_COMPUTE_GAS); + assert_detention_stop(db, detention_limits(), left, shares); } /// A contract that calls one that reads the Oracle's storage and then writes the fresh slots: the @@ -1261,6 +1281,7 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { // The middle contract's crossing, then the outer one's `POP`, `PUSH0` and cold `SLOAD`: its // static gas, then the cold surcharge; then its loop, in a memory of nothing. let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); + let shares = oracle_pops_then_writes().shares_before_crossing(ORACLE_ACCESS_COMPUTE_GAS); let params = mega_evm::satin_gas_params(); let sload = [ 2, @@ -1270,7 +1291,8 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { 2, ]; let left = Charges::default().then(&sload).spin(0).left(left); - let (_, accessed) = assert_detention_stop(with_oracle_read(db), detention_limits(), left); + let (_, accessed) = + assert_detention_stop(with_oracle_read(db), detention_limits(), left, shares); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1284,7 +1306,8 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { let db = MemoryDatabase::default().account_code(A, writes_past_the_cap(code).stop().build()); 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); + let shares = oracle_pops_then_writes().shares_before_crossing(ORACLE_CAP); + let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, left, shares); assert!(limit - ORACLE_CAP < 10_000, "the Oracle's read binds: {limit}"); assert_eq!( accessed, @@ -1299,7 +1322,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, detention_limits(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left, 0); assert!(limit - CAP < 1_000, "{}", limit - CAP); } @@ -1776,9 +1799,26 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { 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}"); + // The start's charges — the account its wei would create and its two records — and what + // regular gas paid of them: all of it below the execution cap, the account's legacy share + // above it. The stop gives them back into the reservoir; the rewritten success keeps them, + // the share on the state ledger. + let (paid, share) = match answered { + Answered::StartRecords => ( + crate::common::account_state_gas() + crate::common::history(2 * WRITE_RECORD_SIZE), + crate::common::account_share(), + ), + Answered::PastTheAllowance | Answered::Precompile => (0, 0), + }; + let reservoir = if gas_limit > TX_GAS_LIMIT_CAP { + intrinsic.gas.reservoir_remaining + share - kept + } else if column == "not rewritten" { + paid + } else { + 0 + }; assert_eq!( - outcome.gas.reservoir_remaining, - intrinsic.gas.reservoir_remaining.saturating_sub(kept), + outcome.gas.reservoir_remaining, reservoir, "{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 + kept, "{cell}: gas used"); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index c7d45c169..4983596b1 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -30,7 +30,7 @@ use revm::{ }; use crate::common::{ - call, context, execute_under, history, runs_at_measurement_prices, slot_state_gas, + call, context, execute_under, history, runs_at_measurement_prices, slot_share, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000200000"); @@ -223,11 +223,25 @@ fn test_stop_refills_the_reservoir_at_any_gas_limit() { }; let small = at(100_000_000); let large = at(1_000_000_000); - assert_eq!(small.gas.reservoir_remaining, 0, "a limit under the cap has no reservoir"); + // Every charge the frames made comes back into a reservoir, whichever pool paid it, so the + // reservoir ends holding what regular gas paid. The cap stops `D` at its second slot's record, + // `C` at its log, and `A` at its second slot's record; `B` succeeds. Below the execution cap + // there is no reservoir to begin with: regular gas pays `D`'s two slots and record and every + // frame's first slot and record, and of each later slot only its legacy share, the reservoir + // a failed child gave back paying the rest. + let (slot, record, share) = + (slot_state_gas(), history(mega_evm::WRITE_RECORD_SIZE), slot_share()); + assert_eq!( + small.gas.reservoir_remaining, + 5 * slot + 4 * record + 3 * share, + "a limit under the cap: what regular gas paid comes back into the reservoir" + ); + // Above it the reservoir pays everything but the eight slots' legacy shares. assert_eq!( 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", + 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history() + 8 * share, + "all of it back but the body's history, which the stop does not take back, and the legacy \ + shares regular gas paid on top", ); 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()); @@ -544,7 +558,13 @@ fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { let stopped = execute_with(chain(), cap(180), charger(), gas_limit); assert_stopped(&stopped.result, LimitKind::DataSize, 180); - assert_eq!(stopped.gas.reservoir_remaining, reservoir, "refilled by the stop"); + // The stop gives every charge back into the reservoir, and with them the legacy shares of the + // eight slots the frames wrote before their stops, which regular gas paid. + assert_eq!( + stopped.gas.reservoir_remaining, + reservoir + 8 * slot_share(), + "refilled by the stop" + ); assert_eq!(stopped.gas.state, 0); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 5df18d237..87bed696f 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -226,7 +226,9 @@ fn test_an_inspectors_answer_past_the_depth_limit_is_taken_as_given() { /// A first frame answered with the stop before it runs — its body fits the limit, the record and /// the transfer log of its value do not — gives the whole reservoir back, and costs the same at a -/// gas limit under the execution cap and far above it. +/// gas limit under the execution cap and far above it. The stop gives back the new account and +/// the record charged before the frame into the transaction's reservoir: under the cap regular gas +/// paid them, so that is what its reservoir holds. #[test] fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { let at = |gas_limit: u64| { @@ -241,7 +243,8 @@ fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { (*result.result.gas(), evm.ctx().additional_limit().reservoir_remaining()) }; let ((small, small_reservoir), (large, large_reservoir)) = (at(100_000_000), at(1_000_000_000)); - assert_eq!(small_reservoir, 0); + let record = mega_evm::write_record_history_gas(1).expect("a record has a price"); + assert_eq!(small_reservoir, crate::common::account_state_gas() + record); 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()); @@ -315,7 +318,17 @@ 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.gas.reservoir_remaining, 0, "there is no pool below the cap"); + // A value call that is refused gives back the history its transfer's record was charged before + // the frame, into the reservoir: below the cap, where regular gas paid it, that is the pool. + let given_back = if !value.is_zero() && matches!(expected, Expected::Revert(_)) { + mega_evm::write_record_history_gas(1).expect("a record has a price") + } else { + 0 + }; + assert_eq!( + narrow.gas.reservoir_remaining, given_back, + "there is no pool below the cap but what was given back" + ); assert_eq!( wide.gas.reservoir_remaining, WIDE - TX_GAS_LIMIT_CAP - body_history(data.len() as u64), diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 0ca8dc5f3..d85341d6f 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -45,7 +45,7 @@ use revm::{ }; use crate::{ - common::{runs_at_measurement_prices, state_is_free}, + common::{runs_at_measurement_prices, slot_share, state_is_free}, op_reference::{self, Op, OpContext, Settled}, }; @@ -64,6 +64,12 @@ fn slot() -> u64 { satin_gas_params().get(GasId::sstore_set_state_gas()) } +/// What the reservoir pays of a fresh slot: its state gas but its legacy share, which a system +/// call's regular gas pays first, as any frame's does. +fn slot_from_the_reservoir() -> u64 { + slot() - slot_share() +} + fn block() -> BlockEnv { BlockEnv { number: U256::from(1_000), @@ -163,7 +169,8 @@ fn db_with(code: Bytes) -> MemoryDatabase { } /// 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. +/// its gas limit as its reservoir: the fresh slot is paid out of it but its legacy share, and what +/// is left is reported. #[test] fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { let (mega, op) = run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new()); @@ -173,24 +180,28 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { 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", + DEFAULT_RESERVOIR.saturating_sub(slot_from_the_reservoir()), + "the excess, less the one slot it paid for but its legacy share", ); assert_same(&mega, &op); } -/// The default reservoir holds sixteen fresh slots at Satin's price. That many writes empty it and -/// spend no regular gas on state; the next one spills what the reservoir cannot pay onto the -/// regular budget. `GAS`, read after the writes, shows the spill: the regular gas the next write -/// took is its own regular cost, which the writes before it show, plus the part of its slot the -/// reservoir did not hold. +/// The default reservoir holds sixteen fresh slots at Satin's price. Writes it holds spend no +/// regular gas on state but each slot's legacy share; once it is empty, the next write spills what +/// the reservoir cannot pay onto the regular budget. `GAS`, read after the writes, shows the +/// spill: the regular gas the next write took is its own regular cost and share, which the writes +/// before it show, plus the part of its slot the reservoir did not hold. /// /// 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. - if state_is_free() || slot() == 0 { + if state_is_free() { + return; + } + if slot_from_the_reservoir() == 0 { + note_price_guard("a fresh slot's legacy share takes the whole of its state gas"); return; } if !runs_at_measurement_prices() { @@ -200,7 +211,7 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { 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 { + if reservoir / slot_from_the_reservoir() > 1_000 { note_price_guard("the default reservoir holds more fresh slots than 30M can write"); return; } @@ -219,14 +230,14 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { }; // The most slots the reservoir holds, and what the one after them spills. - let held = reservoir / slot(); - let spill = (held + 1) * slot() - reservoir; + let held = reservoir / slot_from_the_reservoir(); + let spill = (held + 1) * slot_from_the_reservoir() - reservoir; let (two_short, _) = run(held - 2); let (one_short, reservoir_one_short) = run(held - 1); let (at, reservoir_at) = run(held); let (past, reservoir_past) = run(held + 1); - assert_eq!(reservoir_one_short, reservoir - (held - 1) * slot()); - assert_eq!(reservoir_at, reservoir - held * slot(), "empty at Satin's price"); + assert_eq!(reservoir_one_short, reservoir - (held - 1) * slot_from_the_reservoir()); + assert_eq!(reservoir_at, reservoir - held * slot_from_the_reservoir(), "the reservoir held"); assert_eq!(reservoir_past, 0); // A write the reservoir holds takes regular gas for itself alone, the same for each. let one_write = one_short - at; @@ -239,13 +250,14 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { #[test] fn test_reservoir_remaining_is_what_the_writes_left() { // As many as five writes, and no more than the reservoir holds at the byte prices in effect. - let most = DEFAULT_RESERVOIR.checked_div(slot()).map_or(5, |held| held.min(5)); + let most = + DEFAULT_RESERVOIR.checked_div(slot_from_the_reservoir()).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()); assert_eq!( mega.reservoir_remaining, - DEFAULT_RESERVOIR - writes * slot(), + DEFAULT_RESERVOIR - writes * slot_from_the_reservoir(), "{writes} writes", ); assert_same(&mega, &op); @@ -253,14 +265,18 @@ fn test_reservoir_remaining_is_what_the_writes_left() { } /// A system call that fails settles as op-revm settles it: a revert gives the state gas of what -/// it wrote back to the reservoir and keeps its regular gas; a halt spends the regular budget and -/// still gives the reservoir back. +/// it wrote back to the reservoir, the legacy shares its regular gas paid included, and keeps its +/// regular gas; a halt spends the regular budget and gives back the reservoir it was given. #[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()); assert!(matches!(mega.result, ExecutionResult::Revert { .. }), "{:?}", mega.result); - assert_eq!(mega.reservoir_remaining, DEFAULT_RESERVOIR, "nothing kept"); + assert_eq!( + mega.reservoir_remaining, + DEFAULT_RESERVOIR + 3 * slot_share(), + "nothing kept, and the shares regular gas paid come back into the reservoir" + ); assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); @@ -322,8 +338,8 @@ fn registry_with_a_due_change() -> MemoryDatabase { /// 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. +/// the reservoir, which holds them, but their legacy shares, and it is what op-revm charges on the +/// same budget, which has no SALT. #[test] fn test_the_pre_block_apply_pending_changes_is_priced_at_the_minimum_bucket() { let crowded = @@ -353,8 +369,9 @@ fn test_the_pre_block_apply_pending_changes_is_priced_at_the_minimum_bucket() { 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", + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - state + + state / slot() * slot_share(), + "the reservoir paid for every slot but its legacy share", ); } assert_eq!(crowded.total_bucket_queries(), 0); @@ -396,7 +413,10 @@ fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_reg 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.reservoir_remaining, DEFAULT_RESERVOIR - slots * slot()); + assert_eq!( + mega_outcome.reservoir_remaining, + DEFAULT_RESERVOIR - slots * slot_from_the_reservoir() + ); assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega_outcome, &op_outcome); } diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 280f619a1..31f3d5765 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -58,7 +58,8 @@ use revm::{ }; use crate::common::{ - account_state_gas, call, context, execute_under, history_rounds, share, value_call_room, + account_share, account_state_gas, call, context, create_share, execute_under, history_rounds, + share, slot_share, value_call_room, }; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); @@ -177,6 +178,26 @@ impl Site { } } + /// What regular gas pays of `variant`'s state charges, their legacy shares, which come out + /// of regular gas before the reservoir pays the rest and do not come back to it, whether the + /// charge is kept, given back or taken back with a failed frame: the new account a value call + /// to [`PAYEE`] or the identity precompile creates, the account a creation creates, and the + /// twin's fresh slots. The transaction's own value and endowment are charged before its frame, + /// with no share. + fn shares(self, variant: Variant) -> u64 { + match (self, variant) { + (Self::TxEndowment, _) | (Self::TxValue, Variant::Plain | Variant::TakenBack) => 0, + (Self::TxValue, Variant::Twin) => slot_share(), + (Self::Call | Self::SelfDestruct, Variant::Plain | Variant::TakenBack) => 0, + ( + Self::Call | Self::CallWithoutCode | Self::CallToPrecompile | Self::SelfDestruct, + Variant::Twin, + ) => self.records() * slot_share(), + (Self::CallWithoutCode | Self::CallToPrecompile, _) => account_share(), + (Self::Create | Self::Create2, _) => create_share(), + } + } + /// The bytes the move counts: its records and its transfer log. const fn bytes(self) -> u64 { self.records() * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE @@ -349,16 +370,22 @@ fn balance(outcome: &MegaTransactionOutcome, address: Address) -> U256 { } /// Asserts what the reservoir of a run above the execution cap says: the state and history it -/// spent came out of it, and nothing else did. -fn assert_reservoir_paid(case: &str, gas_limit: u64, outcome: &MegaTransactionOutcome) { +/// spent came out of it, and nothing else did, but `shares`, the legacy shares regular gas paid +/// ([`Site::shares`]). +fn assert_reservoir_paid( + case: &str, + gas_limit: u64, + outcome: &MegaTransactionOutcome, + shares: u64, +) { if gas_limit <= TX_GAS_LIMIT_CAP { return; } let reservoir = gas_limit - TX_GAS_LIMIT_CAP; assert_eq!( outcome.gas.reservoir_remaining, - reservoir - outcome.gas.state - outcome.gas.history, - "{case}: the reservoir paid the state and history ledgers and nothing else", + reservoir + shares - outcome.gas.state - outcome.gas.history, + "{case}: the reservoir paid the state and history ledgers but the legacy shares", ); } @@ -444,7 +471,7 @@ fn test_each_site_counts_its_transfer_log() { let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); assert_completed(&case, site, Variant::Plain, &outcome, body); - assert_reservoir_paid(&case, gas_limit, &outcome); + assert_reservoir_paid(&case, gas_limit, &outcome, site.shares(Variant::Plain)); } } } @@ -475,7 +502,7 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { let (fits, body) = run(cap); assert_completed(&format!("{case}: at the budget"), site, variant, &fits, body); - assert_reservoir_paid(&case, gas_limit, &fits); + assert_reservoir_paid(&case, gas_limit, &fits, site.shares(variant)); let (over, body) = run(cap - 1); let own_frames = (site.depth() == 0).then_some(LimitCheck::ExceedsLimit { @@ -511,7 +538,7 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { } Variant::TakenBack => unreachable!(), } - assert_reservoir_paid(&case, gas_limit, &over); + assert_reservoir_paid(&case, gas_limit, &over, site.shares(variant)); } } } @@ -578,12 +605,12 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { } Variant::TakenBack => unreachable!(), } - assert_reservoir_paid(&case, gas_limit, &outcome); + assert_reservoir_paid(&case, gas_limit, &outcome, site.shares(variant)); if site.depth() == 0 { let (fits, body, _) = run(0); assert_completed(&format!("{case}: at the limit"), site, variant, &fits, body); - assert_reservoir_paid(&case, gas_limit, &fits); + assert_reservoir_paid(&case, gas_limit, &fits, site.shares(variant)); } } } @@ -673,7 +700,7 @@ fn test_a_failure_takes_each_sites_transfer_log_back() { assert_eq!(balance(&outcome, DESTRUCTOR), U256::from(VALUE), "{case}"); } assert_eq!(balance(&outcome, site.recipient()), U256::ZERO, "{case}"); - assert_reservoir_paid(&case, gas_limit, &outcome); + assert_reservoir_paid(&case, gas_limit, &outcome, site.shares(Variant::TakenBack)); } } } diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 61c17f2d1..a0e890345 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -375,8 +375,8 @@ impl /// 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. +/// the signer's account and the created account, each but its legacy share, which regular gas +/// pays first, 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))); @@ -389,9 +389,9 @@ fn test_the_creation_takes_the_reservoir_share_of_what_the_call_has_left() { 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(); + let account = entry(GasId::new_account_state_gas()); + let created = entry(GasId::create_state_gas()); + let left = + whole - (account - account.min(25_000)) - (created - created.min(20_000)) - 2 * record(); assert_eq!(evm.inspector().0, [whole, left - left * 2 / 100]); } diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index f17c463c2..83a0fa09a 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -294,8 +294,9 @@ fn test_a_rejected_transaction_is_seen_as_nothing() { /// depth below, the creation from the signer at the deploy address, which returns the runtime it /// deploys. Each reports the gas it took from its gas limit — the call what the transaction spent /// beyond its intrinsic gas, the creation its `gasUsed` — less, above the execution cap, the state -/// and history gas the reservoir paid, as for any frame. The parity and geth call traces built -/// from it say the same, and no trace has a frame of its own. +/// and history gas the reservoir paid, as for any frame: the call's regular gas paid the legacy +/// shares of the signer's account and of the created account. The parity and geth call traces +/// built from it say the same, and no trace has a frame of its own. #[test] fn test_a_tracer_sees_the_call_and_the_creation_it_starts() { let deployment = Deployment::new(deploying(&runtime(3))); @@ -315,8 +316,10 @@ fn test_a_tracer_sees_the_call_and_the_creation_it_starts() { let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); let [spent, regular, ..] = beyond(&outcome, &reference); let deposit = satin_gas_params().code_deposit_state_gas(3) + history(3); + let shares = satin_gas_params().get(GasId::new_account_state_gas()).min(25_000) + + satin_gas_params().get(GasId::create_state_gas()).min(20_000); let (call_took, creation_took) = if gas_limit > TX_GAS_LIMIT_CAP { - (regular, answer.gasUsed - deposit) + (regular + shares, answer.gasUsed - deposit) } else { (spent, answer.gasUsed) }; diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 8915a05ac..dd02e16f0 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -104,14 +104,28 @@ fn assert_nothing_kept( assert_eq!([state, history_gas, history_bytes], [0; 3], "{case} at {gas_limit}"); assert!(regular >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{case}: the overhead stays spent"); assert_eq!(outcome.usage.write_records, 0, "{case}: no record is kept"); + // The call's regular gas paid the legacy shares of the signer's account and of the created + // account before the reservoir; the call's revert gives them back into the reservoir with the + // rest of the charges. if gas_limit > TX_GAS_LIMIT_CAP { assert_eq!( - outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining, + outcome.gas.reservoir_remaining, + reference.gas.reservoir_remaining + account_share() + create_share(), "{case}: the reservoir comes back", ); } } +/// The legacy share of the signer's account, which a keyless call's regular gas pays first. +fn account_share() -> u64 { + entry(GasId::new_account_state_gas()).min(25_000) +} + +/// The legacy share of the created account, which a keyless call's regular gas pays first. +fn create_share() -> u64 { + entry(GasId::create_state_gas()).min(20_000) +} + /// A log that crosses the creation's own data-size budget reverts the creation alone: the call /// reports `ExecutionReverted` with the stop, the transaction is not stopped, and the signer's /// nonce is spent. @@ -325,7 +339,8 @@ fn test_a_deployment_within_every_limit_deploys() { /// An answer built without a frame carries the reservoir the call inherited: a call refused after /// it paid for the signer's account — the forward capped below the signed gas limit, which only a /// signed gas limit near the execution cap reaches above it — gives the charge back to the -/// reservoir and the sender gets all of it but the body's history. +/// reservoir, the legacy share its regular gas paid included, and the sender gets all of it but +/// the body's history. #[test] fn test_a_refusal_after_the_charges_gives_the_reservoir_back() { let deployment = @@ -339,26 +354,35 @@ 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.gas.reservoir_remaining, reference.gas.reservoir_remaining,); + assert_eq!( + outcome.gas.reservoir_remaining, + reference.gas.reservoir_remaining + account_share() + ); } /// And a call refused after the charges of the creation's start — the forward the `CREATE` -/// opcode's regular gas takes below the signed gas limit, which above the execution cap only a -/// signed gas limit just under what the call has left reaches — gives their state and history gas -/// back to the reservoir, and keeps their regular gas, as it keeps the overhead. +/// opcode's regular gas and the created account's legacy share take below the signed gas limit, +/// which above the execution cap only a signed gas limit just under what the call has left once it +/// paid the signer's account reaches — gives their state and history gas back to the reservoir, +/// the legacy shares its regular gas paid included, and keeps their regular gas, as it keeps the +/// overhead. #[test] fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { let gas_limit = GAS_LIMITS[1]; let init_code = deploying(&runtime(1)); // Above the cap the call has what the execution cap leaves once the body's regular gas — all - // the reference spends — and the overhead are paid. The signed gas limit is one less, and is - // part of the calldata the body is priced by, so the two are settled together. + // the reference spends — and the overhead are paid, and the signer's account its legacy share. + // The signed gas limit is one less, so the forward check after the signer's account passes, + // and is part of the calldata the body is priced by, so the two are settled together. let mut signed = TX_GAS_LIMIT_CAP - 200_000; let (deployment, left) = (0..10) .find_map(|_| { let deployment = Deployment::signed(0, signed, U256::ZERO, init_code.clone()); let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let left = TX_GAS_LIMIT_CAP - reference.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; + let left = TX_GAS_LIMIT_CAP - + reference.gas.regular - + KEYLESS_DEPLOY_OVERHEAD_GAS - + account_share(); let settled = left - 1 == signed; signed = left - 1; settled.then_some((deployment, left)) @@ -370,14 +394,17 @@ fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { refusal(&outcome), KeylessDeployError::GasLimitTooLow { tx_gas_limit: signed, - provided_gas_limit: left - opcode + provided_gas_limit: left - opcode - create_share() }, ); let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); 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.gas.reservoir_remaining, reference.gas.reservoir_remaining,); + assert_eq!( + outcome.gas.reservoir_remaining, + reference.gas.reservoir_remaining + account_share() + create_share() + ); } /// The call gets back what its creation did not spend, the same way whether the creation diff --git a/crates/mega-evm/tests/tracers/harness.rs b/crates/mega-evm/tests/tracers/harness.rs index aca19dfca..928a84a44 100644 --- a/crates/mega-evm/tests/tracers/harness.rs +++ b/crates/mega-evm/tests/tracers/harness.rs @@ -404,35 +404,30 @@ pub(crate) fn assert_ledgers(traced: &Traced, expected: Ledgers) { /// /// revm-inspectors records the regular gas the engine handed the transaction's frame as the root /// node's `gas_limit` and, when the frame ends, what the frame spent of it as `gas_used` -/// (`Gas::total_gas_spent`: the limit less what is left, so state and history gas that spilled -/// onto regular gas is in it, and what the reservoir paid is not). What the frame did not spend -/// and the reservoir left are the gas the transaction did not use; everything else its gas limit -/// bought is its raw spend, the three ledgers' sum: +/// (`Gas::total_gas_spent`: the limit less what is left, so state and history gas that regular gas +/// paid is in it, and what the reservoir paid is not). What the frame did not spend and the +/// reservoir left are the gas the transaction did not use; everything else its gas limit bought +/// is its raw spend, the three ledgers' sum: /// -/// `gas_limit = (regular + state + history) + (root.gas_limit − root.gas_used) + given_back + -/// reservoir left` +/// `gas_limit = (regular + state + history) + (root.gas_limit − root.gas_used) + reservoir left` /// /// The refund and the EIP-7623 floor change only how much of that the receipt bills, so neither -/// is in it. -/// -/// `given_back` is the state and history gas the frame spilled onto its regular gas and got back -/// because it failed. revm gives a failed frame that gas back when the frame's result is merged -/// (`handle_reservoir_remaining_gas`, for the transaction's own frame in `last_frame_result`), -/// which is after the inspector's `call_end` read it: the tracer counts it as spent, the receipt -/// does not bill it. +/// is in it. A frame that failed gives back the state and history gas its regular gas paid into +/// the reservoir, never into its regular gas, so the frame's unspent regular gas the tracer read is +/// what the transaction gets back of it, and the give-back is in the reservoir left. /// /// The first run's inspector is read here: the node path overwrites the root's gas limit with the /// transaction's. -pub(crate) fn assert_root_frame_settles(traced: &Traced, given_back: u64) { +pub(crate) fn assert_root_frame_settles(traced: &Traced) { let root = &traced.inspector.traces().nodes()[0].trace; let unspent = root.gas_limit - root.gas_used; let gas = &traced.outcome.gas; let spent = gas.regular + gas.state + gas.history; assert_eq!( traced.gas_limit(), - spent + unspent + given_back + gas.reservoir_remaining, - "the raw spend ({spent}), the root frame's unspent gas ({unspent}), what its failure gave \ - back ({given_back}) and the reservoir left do not make up the gas limit" + spent + unspent + gas.reservoir_remaining, + "the raw spend ({spent}), the root frame's unspent gas ({unspent}) and the reservoir left \ + do not make up the gas limit" ); } diff --git a/crates/mega-evm/tests/tracers/scenarios.rs b/crates/mega-evm/tests/tracers/scenarios.rs index d15cbe83c..99ed23dd0 100644 --- a/crates/mega-evm/tests/tracers/scenarios.rs +++ b/crates/mega-evm/tests/tracers/scenarios.rs @@ -116,16 +116,9 @@ fn funded() -> MemoryDatabase { /// Every test calls this last, so a relation that fails stops the test before any snapshot is /// compared. fn pin(name: &str, traced: &Traced, expected: Ledgers) { - pin_given_back(name, traced, expected, 0); -} - -/// [`pin`], for a transaction whose own frame failed after `given_back` of its state and history -/// gas had spilled onto its regular gas: the failure gives it back after the tracer read the -/// frame (see `assert_root_frame_settles`). -fn pin_given_back(name: &str, traced: &Traced, expected: Ledgers, given_back: u64) { assert!(SCENARIOS.contains(&name), "{name} is not listed in SCENARIOS"); assert_ledgers(traced, expected); - assert_root_frame_settles(traced, given_back); + assert_root_frame_settles(traced); assert_eip3155_agrees(traced); assert_prestate_covers_reads(traced); assert_root_gas_is_the_gas_limit(traced); @@ -516,8 +509,9 @@ fn test_keyless_deploy_refused() { ); assert_keyless_steps(&traced, false); // The call frame paid the signer's account out of its regular gas before the refusal gave it - // back. - pin_given_back("keyless_refused", &traced, expected, gas::account_state()); + // back, into the call's reservoir, which the transaction ends with. + assert_eq!(traced.outcome.gas.reservoir_remaining, gas::account_state(), "given back"); + pin("keyless_refused", &traced, expected); } /// A parent that calls [`CHILD`] with all its gas and no value, then, if it resumes, writes a @@ -573,9 +567,10 @@ fn test_data_size_limit_stops_the_first_frame_at_its_start() { // 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. - pin_given_back("data_size_first_frame_start_stop", &traced, expected, held); + // The record's history was charged on the transaction's gas before the frame, out of its + // regular gas, and comes back into its reservoir after the tracer read the frame. + assert_eq!(traced.outcome.gas.reservoir_remaining, held, "given back"); + pin("data_size_first_frame_start_stop", &traced, expected); } /// A child's `LOG0` that crosses the transaction's data-size limit and, with it, its own frame @@ -782,7 +777,9 @@ fn test_reservoir_pays_state_gas() { // The reservoir pays the body's history before the first frame, then the slot's state gas and // its record's history at the `SSTORE`: it holds them at the prices in effect, with the margin // on top. The regular gas below the execution cap pays the rest. - let slot = gas::slot_state() + gas::records(1); + // Regular gas pays the slot's legacy share before the reservoir. + let share = gas::slot_state().min(10_000); + let slot = gas::slot_state() - share + gas::records(1); let reservoir = ROOM + gas::body(0) + slot; let traced = Traced::run( funded().account_code(CONTRACT, code), @@ -792,15 +789,20 @@ fn test_reservoir_pays_state_gas() { assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); assert_eq!(traced.outcome.gas.state, gas::slot_state()); // The reservoir paid the body's history before the first frame, then the slot's state gas - // and its record's history at the `SSTORE`; what is left goes back to the sender. + // but its legacy share and its record's history at the `SSTORE`; what is left goes back to the + // sender. assert_eq!( traced.outcome.gas.reservoir_remaining, reservoir - gas::body(0) - slot, "the reservoir left" ); - // The opcode tracer shows only the regular part of the `SSTORE`: the rest came out of the - // reservoir, which only the EIP-3155 trace shows. - assert_eq!(step(&traced, "SSTORE", 1).gas_cost, gas::sstore_fresh_cold(), "the regular part"); + // The opcode tracer shows only the regular part of the `SSTORE`, its legacy share included: + // the rest came out of the reservoir, which only the EIP-3155 trace shows. + assert_eq!( + step(&traced, "SSTORE", 1).gas_cost, + gas::sstore_fresh_cold() + share, + "the regular part" + ); let steps = eip3155_steps(&traced); let at = |op: &str| { let line = steps.iter().find(|line| line["opName"] == op).expect("the step"); From 93941a3ecafdd438cae7da6fbc91bb433190023b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:10:09 +0800 Subject: [PATCH 078/190] feat(block): a schedule that activates Satin without usable registry bootstrap values is refused at load --- AGENTS.md | 1 + bin/mega-evme/AGENTS.md | 2 +- bin/mega-evme/src/common/schedule.rs | 33 +++++-- crates/mega-evm/src/block/chain.rs | 2 +- crates/mega-evm/src/block/executor.rs | 7 +- crates/mega-evm/src/block/genesis.rs | 35 +++----- crates/mega-evm/src/block/hardfork.rs | 65 ++++++++++++-- .../mega-evm/src/system/sequencer_registry.rs | 55 ++++++++++-- crates/mega-evm/tests/block/predeploys.rs | 9 +- crates/mega-evm/tests/block/schedule.rs | 87 ++++++++++++++++--- .../mega-state-test/src/blockchain/chain.rs | 16 ++-- .../mega-evme/configuration/chain-and-spec.md | 1 + docs/spec/upgrades/satin.md | 2 +- 13 files changed, 249 insertions(+), 66 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9c549c0ca..2ec2919fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -758,6 +758,7 @@ When the agent is requested to implement a new feature or bug fix, it should con - **Validate the schedule at load time.** `MegaHardforks::validate_schedule` refuses a schedule a chain cannot run when the chain configuration is loaded rather than at the fork's first block. It refuses a schedule in which a fork Satin runs on and the schedule activates by timestamp (Ethereum Shanghai to Osaka, Optimism Regolith to Karst) is not active at Satin's activation (`ScheduleError::InactiveBaseFork`); the engine's own schedules activate those forks from the first block, so they are active by `satinTime`, and pass. + It refuses a schedule that activates Satin without the `SequencerRegistry`'s bootstrap values (`ScheduleError::MissingRegistryBootstrap`) or with one of them zero (`ScheduleError::ZeroRegistryBootstrapValue`, naming the key), through the one check of the values, `SequencerRegistryBootstrap::validate`, which the genesis parser makes too; block execution does not validate its schedule, so an unvalidated schedule reaches `MegaBlockExecutionError::UnusableRegistryBootstrap` only at a block that must seed or migrate the registry. That Jovian, Karst and Osaka do not activate before Satin is the node's to check, not the engine's. - **Keep the workspace on its declared minimum toolchain (1.94).** CI's msrv job checks the workspace on 1.94.0, every feature on, with the lock as it is. diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 96d1408c1..9d64cafe1 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -31,7 +31,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - Do not edit or re-implement the legacy leg: it is the released 1.7.1 code, pinned with its dependency versions (`tests/legacy_line.rs`). - Do not move a package `tests/legacy_line.rs` pins without deciding it there. The leg shares most of its dependencies with the Satin engine and the tool, one copy per compatibility line: the precompiles' backends (`secp256k1`, `k256`, `sha2`, `ripemd`, `aurora-engine-modexp`, arkworks, `blst`, `c-kzg`, `p256`), hashing and word arithmetic (`alloy-primitives`, `ruint`, `sha3`) and the encodings. Each is pinned at the release's version; `alloy-rlp`, `alloy-trie` and the `alloy-sol-types` family, which the Satin engine's alloy 2 line holds above it, are pinned at the version the workspace holds (`AHEAD_OF_THE_RELEASE`). Transport, JSON and derive crates float. - Do not use `cargo ... -p mega-evme`: the name also matches the linked 1.7.1 package. Use `--manifest-path bin/mega-evme/Cargo.toml`. -- Build no Satin hardfork schedule in the CLI but the counterfactual's (`common::schedule::counterfactual`): the chain's own schedule with Satin from genesis, or the engine's base forks with Satin from genesis for a chain the table does not know. A chain's own Satin schedule — the engine's table's (`mega_evm::hardfork_schedule`, which knows mainnet and testnet and no other chain), or the one `mega_evm::SatinChainConfig::hardforks` builds from the chain's genesis file (`--genesis`) — is used as it is or refused. A replay of a chain neither names is refused unless `--override.spec` names the engine (`engine::unknown_chain`). Under `--genesis` no Satin run is a counterfactual: one the file does not run on Satin is refused (`satin_schedule`), and the file's chain is checked before a command's engine is picked (`check_genesis_chain`). Do not parse a genesis file's Satin keys here either: `SatinChainConfig::from_genesis_config` is the one parser every reader shares. +- Build no Satin hardfork schedule in the CLI but the counterfactual's (`common::schedule::counterfactual`): the chain's own schedule with Satin from genesis, or the engine's base forks with Satin from genesis for a chain the table does not know, carrying the legacy engine's placeholder `SequencerRegistry` bootstrap values for an unknown chain (the system address in both roles, delay 1), since a schedule that activates Satin must carry them. A chain's own Satin schedule — the engine's table's (`mega_evm::hardfork_schedule`, which knows mainnet and testnet and no other chain), or the one `mega_evm::SatinChainConfig::hardforks` builds from the chain's genesis file (`--genesis`) — is used as it is or refused. A replay of a chain neither names is refused unless `--override.spec` names the engine (`engine::unknown_chain`). Under `--genesis` no Satin run is a counterfactual: one the file does not run on Satin is refused (`satin_schedule`), and the file's chain is checked before a command's engine is picked (`check_genesis_chain`). Do not parse a genesis file's Satin keys here either: `SatinChainConfig::from_genesis_config` is the one parser every reader shares. - Do not duplicate chain/spec parsing logic across commands. - Add shared parsing in `src/common/` and reuse. - Do not print partial execution output before final outcome object assembly. diff --git a/bin/mega-evme/src/common/schedule.rs b/bin/mega-evme/src/common/schedule.rs index 9638731de..fec7e3aab 100644 --- a/bin/mega-evme/src/common/schedule.rs +++ b/bin/mega-evme/src/common/schedule.rs @@ -3,8 +3,10 @@ use std::sync::OnceLock; use mega_evm::{ - alloy_hardforks::ForkCondition, ChainActivation, MegaHardfork, MegaHardforkConfig, - MegaHardforks, MegaSpecId, ProtocolLimits, SatinChainConfig, + alloy_hardforks::ForkCondition, + system::{SequencerRegistryBootstrap, MEGA_SYSTEM_ADDRESS}, + ChainActivation, MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaSpecId, ProtocolLimits, + SatinChainConfig, }; use serde_json::{Map, Value}; @@ -36,11 +38,24 @@ pub fn satin_schedule(chain_id: u64, timestamp: u64) -> Result) -> MegaHardforkConfig { - chain.unwrap_or_default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)) + let schedule = chain.unwrap_or_default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)); + if schedule.sequencer_registry_bootstrap().is_some() { + schedule + } else { + schedule.with_sequencer_registry_bootstrap(PLACEHOLDER_BOOTSTRAP) + } } /// The protocol limits a Satin run is held to: Satin's ([`ProtocolLimits::for_spec`]), the ones @@ -242,7 +257,8 @@ mod tests { /// A counterfactual runs on the chain's own schedule with Satin from genesis, whatever the /// chain; a chain the engine does not know gets the engine's base forks with Satin from - /// genesis. No block of a counterfactual is Satin's activation block. + /// genesis and the placeholder bootstrap values, a known chain keeps its own, and each + /// schedule loads. No block of a counterfactual is Satin's activation block. #[test] fn test_a_counterfactual_runs_on_the_chains_schedule_with_satin_from_genesis() { for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, 6342, 1] { @@ -250,6 +266,13 @@ mod tests { assert_eq!(schedule.spec_id(0), Some(MegaSpecId::SATIN), "chain {chain_id}"); assert!(!schedule.is_satin_activation_block(0, 1_700_000_000), "chain {chain_id}"); assert_eq!(schedule.validate_schedule(), Ok(())); + let own = mega_evm::chain_activation(chain_id) + .and_then(|activation| activation.sequencer_registry_bootstrap); + assert_eq!( + schedule.sequencer_registry_bootstrap(), + Some(own.unwrap_or(PLACEHOLDER_BOOTSTRAP)), + "chain {chain_id}" + ); } let known = mega_evm::hardfork_schedule(MAINNET_CHAIN_ID).unwrap(); let counterfactual = satin_schedule(MAINNET_CHAIN_ID, 1_700_000_000).unwrap(); diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index 8a700ecf2..8f427a7a3 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -162,7 +162,7 @@ mod tests { Some(bootstrap), "the schedule carries the chain's bootstrap values" ); - assert!(bootstrap.is_usable()); + assert_eq!(bootstrap.validate(), Ok(())); } for chain_id in [0, 1, 6342, 999_999] { assert!(hardfork_schedule(chain_id).is_none(), "chain {chain_id} is unknown"); diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 9298aa72d..3bfe1e3e4 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -264,8 +264,11 @@ pub enum MegaBlockExecutionError { /// The block must seed the `SequencerRegistry` or migrate it from version 1.0.0, and the chain /// configuration carries no usable bootstrap values for it: none, or one of them zero. /// - /// The node's configuration, which its parser refuses, not a verdict on the block: an internal - /// error. + /// The node's configuration, not a verdict on the block: an internal error. The genesis parser + /// and `MegaHardforks::validate_schedule` refuse such a schedule when it is loaded, and block + /// execution does not validate the schedule it is given, so only a schedule that skipped + /// validation reaches this; it stays the block's refusal of a schedule it cannot seed or + /// migrate the registry from, rather than seeding zero roles. UnusableRegistryBootstrap, /// An outcome handed to a delayed commit executed against another nonce or balance of its /// sender than the block holds now: a commit since its execution moved them. diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index b16d6dc0c..e7977481f 100644 --- a/crates/mega-evm/src/block/genesis.rs +++ b/crates/mega-evm/src/block/genesis.rs @@ -164,22 +164,17 @@ impl SatinChainConfig { }; let mut bootstrap = |key| entries.remove(key).ok_or(SatinChainConfigError::MissingKey(key)); let initial_sequencer = - bootstrap(REX5_INITIAL_SEQUENCER_KEY)?.non_zero_address(REX5_INITIAL_SEQUENCER_KEY)?; - let initial_admin = - bootstrap(REX5_INITIAL_ADMIN_KEY)?.non_zero_address(REX5_INITIAL_ADMIN_KEY)?; + bootstrap(REX5_INITIAL_SEQUENCER_KEY)?.address(REX5_INITIAL_SEQUENCER_KEY)?; + let initial_admin = bootstrap(REX5_INITIAL_ADMIN_KEY)?.address(REX5_INITIAL_ADMIN_KEY)?; let min_rotation_delay = - match bootstrap(REX6_MIN_ROTATION_DELAY_KEY)?.integer(REX6_MIN_ROTATION_DELAY_KEY)? { - 0 => return Err(SatinChainConfigError::ZeroValue(REX6_MIN_ROTATION_DELAY_KEY)), - delay => delay, - }; - let config = Self { - activation_time, - sequencer_registry_bootstrap: SequencerRegistryBootstrap::new( - initial_sequencer, - initial_admin, - min_rotation_delay, - ), - }; + bootstrap(REX6_MIN_ROTATION_DELAY_KEY)?.integer(REX6_MIN_ROTATION_DELAY_KEY)?; + let sequencer_registry_bootstrap = + SequencerRegistryBootstrap::new(initial_sequencer, initial_admin, min_rotation_delay); + // The one check of the values, which a schedule's validation makes as well. + sequencer_registry_bootstrap + .validate() + .map_err(|zero| SatinChainConfigError::ZeroValue(zero.key))?; + let config = Self { activation_time, sequencer_registry_bootstrap }; config.hardforks()?; Ok(Some(config)) } @@ -287,19 +282,15 @@ impl Entry { } } - /// The non-zero address the value of `key` is: 40 hexadecimal digits after `0x`. - fn non_zero_address(self, key: &'static str) -> Result { + /// The address the value of `key` is: 40 hexadecimal digits after `0x`. + fn address(self, key: &'static str) -> Result { let invalid = || SatinChainConfigError::InvalidValue { key, expected: ADDRESS_EXPECTED }; let Self::Text(text) = self else { return Err(invalid()) }; let digits = text.strip_prefix("0x").ok_or_else(invalid)?; if digits.len() != 40 || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err(invalid()); } - let address = Address::from_str(digits).map_err(|_| invalid())?; - if address.is_zero() { - return Err(SatinChainConfigError::ZeroValue(key)); - } - Ok(address) + Address::from_str(digits).map_err(|_| invalid()) } } diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index aa19f7303..35dbf36f7 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -80,11 +80,12 @@ pub trait MegaHardforks: OpHardforks { /// /// A Satin block reads them only to deploy the registry: to seed a registry its state does not /// hold, and to give one at version 1.0.0 its minimum rotation delay when it migrates it. A - /// chain configuration that schedules Satin must carry them, each non-zero, and its parser - /// refuses one that does not - /// ([`SatinChainConfig::from_genesis_config`](crate::SatinChainConfig::from_genesis_config)); - /// a block that needs them and finds none, or a zero one, cannot be executed, which is the - /// node's fault and no verdict on the block. + /// schedule that activates Satin must carry them, each non-zero: the genesis parser refuses a + /// configuration that does not + /// ([`SatinChainConfig::from_genesis_config`](crate::SatinChainConfig::from_genesis_config)), + /// and so does [`validate_schedule`](Self::validate_schedule) a schedule built in code. A + /// block run on a schedule that skipped validation, needing them and finding none or a zero + /// one, cannot be executed, which is the node's fault and no verdict on the block. fn sequencer_registry_bootstrap(&self) -> Option; /// The latest `MegaETH` fork active at `timestamp`, or `None` before the first one. @@ -164,6 +165,12 @@ pub trait MegaHardforks: OpHardforks { /// Jovian, Karst and Osaka do not activate before Satin, is the node's to check: before Satin /// the chain runs its pre-Satin engine, which this crate does not execute. /// + /// - A schedule that activates Satin carries the `SequencerRegistry`'s bootstrap values + /// ([`sequencer_registry_bootstrap`](Self::sequencer_registry_bootstrap)), none of them zero + /// ([`SequencerRegistryBootstrap::validate`]): a Satin block seeds a registry its state does + /// not hold and migrates one at version 1.0.0 from them, so a schedule without them would + /// load and fail at the first block that needs them. + /// /// There is no ordering or gap check: a single fork has nothing to be out of order with. The /// spec that follows Satin brings the ladder back, and with it those checks. fn validate_schedule(&self) -> Result<(), ScheduleError> { @@ -174,7 +181,8 @@ pub trait MegaHardforks: OpHardforks { } } - require_base_forks(self) + require_base_forks(self)?; + require_registry_bootstrap(self) } } @@ -212,6 +220,24 @@ fn require_base_forks(schedule: &H) -> Result<(), Sch Ok(()) } +/// Refuses a schedule that activates Satin without usable `SequencerRegistry` bootstrap values: the +/// half of [`validate_schedule`](MegaHardforks::validate_schedule) that holds Satin's one +/// chain-configuration parameter. A schedule that does not activate Satin needs none. +fn require_registry_bootstrap( + schedule: &H, +) -> Result<(), ScheduleError> { + let fork = MegaHardfork::Satin; + if !matches!(schedule.mega_fork_activation(fork), ForkCondition::Timestamp(_)) { + return Ok(()); + } + let bootstrap = schedule + .sequencer_registry_bootstrap() + .ok_or(ScheduleError::MissingRegistryBootstrap { fork })?; + bootstrap + .validate() + .map_err(|zero| ScheduleError::ZeroRegistryBootstrapValue { fork, key: zero.key }) +} + /// A schedule a chain cannot run, as [`MegaHardforks::validate_schedule`] reports it. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ScheduleError { @@ -230,6 +256,20 @@ pub enum ScheduleError { /// The fork it runs on that is not active then, as [`Hardfork::name`] names it. base: &'static str, }, + /// A schedule that activates a fork needing the `SequencerRegistry`'s bootstrap values carries + /// none. + MissingRegistryBootstrap { + /// The scheduled fork. + fork: MegaHardfork, + }, + /// A schedule that activates a fork needing the `SequencerRegistry`'s bootstrap values carries + /// one of them zero. + ZeroRegistryBootstrapValue { + /// The scheduled fork. + fork: MegaHardfork, + /// The chain-configuration key of the zero value. + key: &'static str, + }, } impl fmt::Display for ScheduleError { @@ -245,6 +285,19 @@ impl fmt::Display for ScheduleError { it runs on is not active" ) } + Self::MissingRegistryBootstrap { fork } => { + let [sequencer, admin, delay] = crate::SEQUENCER_REGISTRY_BOOTSTRAP_KEYS; + write!( + f, + "hardfork {fork:?} is scheduled, and the schedule carries none of the \ + SequencerRegistry's bootstrap values `{sequencer}`, `{admin}` and `{delay}`" + ) + } + Self::ZeroRegistryBootstrapValue { fork, key } => write!( + f, + "hardfork {fork:?} is scheduled, and the SequencerRegistry's bootstrap value \ + `{key}` is zero" + ), } } } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 420f724fe..f4890de0f 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -89,12 +89,31 @@ impl SequencerRegistryBootstrap { Self { initial_sequencer, initial_admin, min_rotation_delay } } - /// Whether every value is usable: neither address zero, nor the delay, which would leave the - /// network no window to react to a scheduled rotation. - pub fn is_usable(&self) -> bool { - !self.initial_sequencer.is_zero() && - !self.initial_admin.is_zero() && - self.min_rotation_delay != 0 + /// Checks that no value is zero: neither address, which would seed a role nobody holds, nor the + /// delay, which would leave the network no window to react to a scheduled rotation. + /// + /// The one check of the values, made by the chain configuration's parser + /// ([`SatinChainConfig::from_genesis_config`](crate::SatinChainConfig::from_genesis_config)), + /// by a schedule's validation + /// ([`validate_schedule`](crate::MegaHardforks::validate_schedule)) and before a block seeds or + /// migrates the registry. + /// + /// # Errors + /// + /// The first zero value, in the order of [`SEQUENCER_REGISTRY_BOOTSTRAP_KEYS`], named by its + /// chain-configuration key. + /// + /// [`SEQUENCER_REGISTRY_BOOTSTRAP_KEYS`]: crate::SEQUENCER_REGISTRY_BOOTSTRAP_KEYS + pub fn validate(&self) -> Result<(), ZeroBootstrapValue> { + let zero = [ + (self.initial_sequencer.is_zero(), crate::REX5_INITIAL_SEQUENCER_KEY), + (self.initial_admin.is_zero(), crate::REX5_INITIAL_ADMIN_KEY), + (self.min_rotation_delay == 0, crate::REX6_MIN_ROTATION_DELAY_KEY), + ]; + match zero.into_iter().find(|(is_zero, _)| *is_zero) { + Some((_, key)) => Err(ZeroBootstrapValue { key }), + None => Ok(()), + } } /// The storage a registry deployed new at `block_number` is seeded with, slot by slot: the @@ -116,6 +135,22 @@ impl SequencerRegistryBootstrap { } } +/// A `SequencerRegistry` bootstrap value that is zero, which no chain configuration may carry +/// ([`SequencerRegistryBootstrap::validate`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ZeroBootstrapValue { + /// The chain-configuration key of the value. + pub key: &'static str, +} + +impl fmt::Display for ZeroBootstrapValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "the SequencerRegistry's bootstrap value `{}` is zero", self.key) + } +} + +impl core::error::Error for ZeroBootstrapValue {} + /// An address as the word a Solidity `address` slot holds. fn address_word(address: Address) -> U256 { U256::from_be_bytes(address.into_word().0) @@ -130,7 +165,9 @@ pub enum SequencerRegistryError { Database(DbError), /// The registry has to be seeded or migrated, and the chain configuration carries no usable /// bootstrap values for it: none, or one of them zero. A fault of the node's configuration, - /// which a node refuses when it loads it, never a verdict on the block. + /// which its validation refuses when it is loaded + /// ([`validate_schedule`](crate::MegaHardforks::validate_schedule)), so only a schedule that + /// skipped it reaches this; never a verdict on the block. UnusableBootstrap, /// The registry makes the block invalid. Refused(SequencerRegistryRefusal), @@ -333,7 +370,7 @@ pub fn deploy_sequencer_registry( })); } let bootstrap = bootstrap - .filter(SequencerRegistryBootstrap::is_usable) + .filter(|bootstrap| bootstrap.validate().is_ok()) .ok_or(SequencerRegistryError::UnusableBootstrap)?; let mut info = existing.unwrap_or_default(); @@ -826,7 +863,7 @@ mod tests { ); } } - assert!(BOOTSTRAP.is_usable()); + assert_eq!(BOOTSTRAP.validate(), Ok(())); } /// The resolution answers the address `_currentSystemAddress` holds, with the registry's diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 70426edf4..4753f8b20 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -29,6 +29,7 @@ use mega_evm::{ }, test_utils::{rex6_predeploys, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, MegaBlockExecutionCtx, MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, + MegaHardforks, }; use revm::{ context::result::ExecutionResult, database::State, primitives::KECCAK_EMPTY, state::EvmState, @@ -372,9 +373,10 @@ fn test_a_registry_naming_no_system_address_refuses_the_block() { assert_eq!(named_accounts(&states), expected_accounts(false)[..RESOLUTION]); } -/// [S18] A block that must seed the registry, or migrate it from 1.0.0, on a configuration that -/// carries no bootstrap values cannot be executed: an internal error of the node, not a verdict on -/// the block. A block whose registry holds version 2.0.0 needs none, and starts. +/// [S18] A block that must seed the registry, or migrate it from 1.0.0, on a schedule that +/// carries no bootstrap values — one that skipped `validate_schedule`, which refuses it at load — +/// cannot be executed: an internal error of the node, not a verdict on the block. A block whose +/// registry holds version 2.0.0 needs none, and starts. /// /// Expected values: independent (the registry each state holds). #[test] @@ -382,6 +384,7 @@ fn test_a_registry_to_seed_or_migrate_without_bootstrap_values_is_an_internal_er use mega_system_contracts::sequencer_registry::V1_0_0_CODE; let without_bootstrap = MegaHardforkConfig::default() .with(MegaHardfork::Satin, alloy_hardforks::ForkCondition::Timestamp(0)); + assert!(without_bootstrap.validate_schedule().is_err(), "refused when it is loaded"); let absent = { let mut db = common::database(); db.cache.accounts.remove(&SEQUENCER_REGISTRY_ADDRESS); diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index 259f6f71c..b9da9cc20 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -3,9 +3,12 @@ use alloy_evm::block::BlockExecutor; use alloy_hardforks::{EthereumHardfork, ForkCondition, Hardfork}; use alloy_op_hardforks::OpHardfork; +use alloy_primitives::Address; use mega_evm::{ - chain_activation, mainnet_hardforks, testnet_hardforks, ChainActivation, MegaHardfork, - MegaHardforkConfig, MegaHardforks, ScheduleError, MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, + chain_activation, mainnet_hardforks, system::SequencerRegistryBootstrap, testnet_hardforks, + ChainActivation, MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError, + MAINNET_CHAIN_ID, REX5_INITIAL_ADMIN_KEY, REX5_INITIAL_SEQUENCER_KEY, + REX6_MIN_ROTATION_DELAY_KEY, TESTNET_CHAIN_ID, }; use crate::common::{self, empty_call_gas, user_tx}; @@ -41,13 +44,14 @@ fn test_canonical_schedules_match_the_chain_activation_table() { assert_eq!(testnet_hardforks().spec_id(u64::MAX), None); } -/// Satin carries no parameter: a schedule that activates it alone loads, and a block runs on it, -/// over a state holding the registry the legacy forks left. The limits are the spec's, not a -/// parameter either. +/// A schedule that activates Satin and carries the `SequencerRegistry`'s bootstrap values, its one +/// chain-configuration parameter, loads, and a block runs on it, over a state holding the registry +/// the legacy forks left. The limits are the spec's, not a parameter. #[test] -fn test_a_schedule_activating_satin_alone_loads_and_runs() { - let satin = - MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)); +fn test_a_schedule_activating_satin_with_its_bootstrap_values_loads_and_runs() { + let satin = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(0)) + .with_sequencer_registry_bootstrap(common::bootstrap()); assert_eq!(satin.validate_schedule(), Ok(())); let mut state = common::state(); @@ -56,6 +60,65 @@ fn test_a_schedule_activating_satin_alone_loads_and_runs() { executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); } +/// A schedule built in code that activates Satin without the `SequencerRegistry`'s bootstrap +/// values is refused when it is loaded, naming the values, not at the first block that must seed +/// or migrate the registry; so is one carrying any of them zero, naming the value's key, as the +/// genesis parser names it. A schedule that does not activate Satin needs none, and the live +/// networks' schedules, which carry Rex5's and Rex6's values, load whenever Satin is scheduled. +#[test] +fn test_a_schedule_activating_satin_without_its_bootstrap_values_is_refused_at_load() { + for satin_time in [0, SATIN_TIME] { + let satin = MegaHardforkConfig::new() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(satin_time)); + assert_eq!( + satin.validate_schedule(), + Err(ScheduleError::MissingRegistryBootstrap { fork: MegaHardfork::Satin }), + "Satin at {satin_time}" + ); + let message = satin.validate_schedule().unwrap_err().to_string(); + for key in [REX5_INITIAL_SEQUENCER_KEY, REX5_INITIAL_ADMIN_KEY, REX6_MIN_ROTATION_DELAY_KEY] + { + assert!(message.contains(key), "the refusal names {key}: {message}"); + } + + let values = common::bootstrap(); + for (key, zero) in [ + ( + REX5_INITIAL_SEQUENCER_KEY, + SequencerRegistryBootstrap { initial_sequencer: Address::ZERO, ..values }, + ), + ( + REX5_INITIAL_ADMIN_KEY, + SequencerRegistryBootstrap { initial_admin: Address::ZERO, ..values }, + ), + ( + REX6_MIN_ROTATION_DELAY_KEY, + SequencerRegistryBootstrap { min_rotation_delay: 0, ..values }, + ), + ] { + let schedule = satin.clone().with_sequencer_registry_bootstrap(zero); + assert_eq!( + schedule.validate_schedule(), + Err(ScheduleError::ZeroRegistryBootstrapValue { fork: MegaHardfork::Satin, key }), + "{key}" + ); + assert!(schedule.validate_schedule().unwrap_err().to_string().contains(key), "{key}"); + } + assert_eq!(satin.with_sequencer_registry_bootstrap(values).validate_schedule(), Ok(())); + } + + let without_satin = MegaHardforkConfig::new(); + assert_eq!(without_satin.sequencer_registry_bootstrap(), None); + assert_eq!(without_satin.validate_schedule(), Ok(()), "no Satin, no values needed"); + for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID] { + let scheduled = ChainActivation { + satin: Some(SATIN_TIME), + ..chain_activation(chain_id).expect("a known chain") + }; + assert_eq!(scheduled.hardforks().validate_schedule(), Ok(()), "chain {chain_id}"); + } +} + /// When Satin activates on the schedules of [`base_fork_case`]. const SATIN_TIME: u64 = 1_800_000_000; @@ -79,11 +142,12 @@ const OP_BASE_FORKS: [OpHardfork; 9] = [ OpHardfork::Karst, ]; -/// A schedule that activates Satin at [`SATIN_TIME`], every base fork at genesis but `base`, which -/// activates on `condition`. +/// A schedule that activates Satin at [`SATIN_TIME`], carrying its bootstrap values, every base +/// fork at genesis but `base`, which activates on `condition`. fn base_fork_case(base: impl Hardfork, condition: ForkCondition) -> MegaHardforkConfig { MegaHardforkConfig::new() .with(MegaHardfork::Satin, ForkCondition::Timestamp(SATIN_TIME)) + .with_sequencer_registry_bootstrap(common::bootstrap()) .with(base, condition) } @@ -164,7 +228,8 @@ fn test_a_base_fork_at_satin_time_is_accepted() { fn test_engine_built_schedules_keep_their_base_forks_at_genesis() { for satin_time in [0, 1, SATIN_TIME] { let schedule = MegaHardforkConfig::new() - .with(MegaHardfork::Satin, ForkCondition::Timestamp(satin_time)); + .with(MegaHardfork::Satin, ForkCondition::Timestamp(satin_time)) + .with_sequencer_registry_bootstrap(common::bootstrap()); assert_eq!(schedule.validate_schedule(), Ok(()), "Satin at {satin_time}"); let activation = ChainActivation { diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs index fcda7990e..7a612d7d3 100644 --- a/crates/mega-state-test/src/blockchain/chain.rs +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -43,9 +43,9 @@ use mega_evm::{ DatabaseCommit, }, system::{ - keyless::KEYLESS_DEPLOY_ADDRESS, ACCESS_CONTROL_ADDRESS, CREATE2_FACTORY_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, LIMIT_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + keyless::KEYLESS_DEPLOY_ADDRESS, SequencerRegistryBootstrap, ACCESS_CONTROL_ADDRESS, + CREATE2_FACTORY_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, LIMIT_CONTROL_ADDRESS, + MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, }, test_utils::{ rex6_predeploys, RecordingDatabase, RecordingEnvFactory, SequencerRegistryRoles, @@ -169,9 +169,15 @@ pub fn registry_roles() -> SequencerRegistryRoles { SequencerRegistryRoles::from(MEGA_SYSTEM_ADDRESS) } -/// The schedule the blocks run on: every fork active from genesis. +/// The schedule the blocks run on: every fork active from genesis, carrying the +/// `SequencerRegistry` bootstrap values the roles of [`registry_roles`] are, as a schedule that +/// activates Satin must. A registry is seeded into every pre-state that lacks one, so no block +/// seeds one from them. pub fn chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated() + let roles = registry_roles(); + let bootstrap = + SequencerRegistryBootstrap::new(roles.sequencer, roles.admin, roles.min_rotation_delay); + MegaHardforkConfig::default().with_all_activated().with_sequencer_registry_bootstrap(bootstrap) } /// The limits the blocks are held to in place of Satin's: none ([`ProtocolLimits::no_limits`]). diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index 8895a1fed..5d57d7da4 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -124,6 +124,7 @@ A command on a legacy spec is refused with `--override.limits`: the legacy engin A chain the tool does not know, a devnet for one, is replayed as its nodes run it only with its own Satin configuration: which blocks run Satin. Without it a replay of such a chain is refused, unless `--override.spec` names the engine; `run` and `tx` with `--spec Satin` run a counterfactual on any chain, with Satin active from genesis. +A counterfactual on a chain the tool does not know carries placeholder `SequencerRegistry` bootstrap values, the system address in both roles and a rotation delay of one block, which matter only to a block that seeds a registry its state does not hold. `--genesis ` takes it from the chain's genesis file, on every command, `replay` included. The file's `config` object (or a file that is the `config` object) is read for its `chainId`, its Satin key, `satinTime`, and the `SequencerRegistry`'s bootstrap keys a configuration that schedules Satin must carry (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`), with the parser the node and the stateless validator read it with, so a key the node refuses is refused here too: a `satin`-prefixed key other than `satinTime`, the registry roles an earlier format named among them, and a missing or zero bootstrap value. For that chain the file replaces the tool's table: a block runs Satin from the file's `satinTime`. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 7df4be040..05c5976e3 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1268,7 +1268,7 @@ An out-of-gas step halts the call, consuming its regular gas. - any other code MUST make the block invalid: the registry's storage is never overwritten by code it was not migrated to. The configured values are the chain configuration's bootstrap keys, the ones the Rex era introduced (see the chain configuration under [Implementation Notes](#implementation-notes)); once the registry holds its roles, its storage, not the configuration, decides them. - The reference implementation reports a registry it cannot migrate, and one the resolution of the live system address refuses, as `MegaBlockExecutionError::SequencerRegistry`, a verdict on the block; a block that must seed or migrate the registry on a node whose configuration carries no usable bootstrap values fails with `MegaBlockExecutionError::UnusableRegistryBootstrap`, an internal error of the node. + The reference implementation reports a registry it cannot migrate, and one the resolution of the live system address refuses, as `MegaBlockExecutionError::SequencerRegistry`, a verdict on the block; its schedule validation (`MegaHardforks::validate_schedule`) refuses a schedule that activates Satin without the bootstrap values or with one of them zero when it is loaded, as the genesis parser refuses such a configuration, and a block that must seed or migrate the registry on a schedule that skipped that validation fails with `MegaBlockExecutionError::UnusableRegistryBootstrap`, an internal error of the node. - **The factory check.** Satin does not deploy the EIP-7997 factory: OP's genesis tooling gives the chain one. From 36e00ed4440c53750926eea2e5d13f9c9cf410a5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:16:00 +0800 Subject: [PATCH 079/190] test(evm): pin the give-back figures, the legacy share at every site and compute across a child's end --- .../mega-evm/tests/satin/history_reservoir.rs | 38 ++- crates/mega-evm/tests/satin/legacy_share.rs | 230 +++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/stops.rs | 67 +++++ crates/mega-evm/tests/system/common.rs | 5 + .../mega-evm/tests/system/keyless/charges.rs | 25 ++ .../mega-evm/tests/system/keyless/deploy.rs | 87 ++++++ ...erential__keyless_differential_record.snap | 276 +++++++++--------- .../tests/system/remaining_compute_gas.rs | 76 +++++ 9 files changed, 666 insertions(+), 139 deletions(-) create mode 100644 crates/mega-evm/tests/satin/legacy_share.rs diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 244ade5f2..e49d90bf1 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -29,7 +29,7 @@ use mega_evm::{ LimitUsage, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::bytecode::opcode::{ - CALL, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP, + CALL, CREATE, GAS, INVALID, LOG0, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP, }; use crate::{ @@ -220,6 +220,42 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { ); } +/// Below the cap, a frame writes a slot that already held a value, which makes its record and +/// nothing else, calls a child that logs and reverts, catches the revert, and reverts itself. The +/// child's revert gives its log's history back into the child's reservoir, which returns to the +/// frame as its reservoir, and the frame's own revert gives its record's history back on top of +/// that: neither give-back goes into regular gas, so the transaction ends holding both. +#[test] +fn test_a_frame_that_reverts_after_catching_a_reverted_log_holds_both_give_backs() { + if runs_at_measurement_prices() { + return; + } + let frame = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(2)) + .call(CONTRACT, U256::ZERO) + .append(POP) + .revert() + .build(); + let child = BytecodeBuilder::default().append_many([PUSH0, PUSH0, LOG0]).revert().build(); + let db = funded() + .account_code(CALLEE, frame) + .account_storage(CALLEE, U256::from(1), U256::from(1)) + .account_code(CONTRACT, child); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, BELOW_CAP)); + + assert!(!outcome.result.is_success(), "the frame reverts: {:?}", outcome.result); + let log = 32 * CPHB; + assert_eq!(log, 2_816, "an empty LOG0's history"); + assert_eq!(RECORD, 3_520, "a record's history"); + assert_eq!(outcome.gas.history, BODY, "neither the log nor the record is kept"); + assert_eq!( + outcome.gas.reservoir_remaining, + log + RECORD, + "the child's give-back returned as reservoir, and the frame's own on top of it", + ); + assert_eq!(outcome.gas.reservoir_remaining, 6_336); +} + /// A child that halts keeps none of the records its caller paid for either, as one that reverts: /// the charge goes back once, to the reservoir it came from, while the halt burns the gas the child /// was forwarded, a fixed forward here, so the two tiers burn the same. The net history is the body diff --git a/crates/mega-evm/tests/satin/legacy_share.rs b/crates/mega-evm/tests/satin/legacy_share.rs new file mode 100644 index 000000000..749f1e6c7 --- /dev/null +++ b/crates/mega-evm/tests/satin/legacy_share.rs @@ -0,0 +1,230 @@ +//! The legacy share: the part of a state charge regular gas pays before the reservoir. +//! +//! Four opcode sites charge state gas for state an opcode adds — a fresh slot's `SSTORE`, the +//! account a value `CALL` creates, the beneficiary a `SELFDESTRUCT` creates, the account a +//! `CREATE` or `CREATE2` creates — and at each, regular gas pays what the opcode cost before Satin +//! less what its regular entries charge now, up to the charge, and the reservoir pays the rest. So +//! each of them draws from regular gas what it drew before Satin, whatever the reservoir holds. +//! +//! No other state charge takes a share: not the account the transaction's own value or creation +//! adds, not the code a creation deposits, not an EIP-7702 authority or its delegation indicator, +//! and no history charge. +//! +//! Every case runs above the execution cap, where the reservoir could pay every charge alone, and +//! reads what regular gas paid of the state and history gas off the outcome: what they cost less +//! what the reservoir paid of them. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaTransactionOutcome, +}; +use revm::bytecode::opcode::{ + CREATE, CREATE2, GAS, LOG0, MSTORE, POP, PUSH0, PUSH1, PUSH4, RETURN, SELFDESTRUCT, SSTORE, + STOP, SUB, SWAP1, +}; + +use crate::common::{ + account_share, authorizing_call, beneficiary_share, call, create, create_share, execute, + runs_at_measurement_prices, slot_share, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000710000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000710001"); +/// An address no account holds. +const NEW: Address = address!("0000000000000000000000000000000000710002"); +/// An address an account holds. +const FUNDED: Address = address!("0000000000000000000000000000000000710003"); +/// The account an EIP-7702 authorization delegates to. +const DELEGATE: Address = address!("0000000000000000000000000000000000710004"); + +/// A gas limit above the execution cap, with a reservoir that could pay every charge here alone. +const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_000_000; + +fn db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CONTRACT, U256::from(1_000)) + .account_balance(FUNDED, U256::from(1)) +} + +/// Runs `code` as `CONTRACT`, called by the caller above the cap. +fn run(code: Bytes) -> MegaTransactionOutcome { + let outcome = + execute(db().account_code(CONTRACT, code), call(CALLER, CONTRACT, U256::ZERO, ABOVE_CAP)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome +} + +/// What regular gas paid of the state and history gas the transaction spent: what they cost less +/// what the reservoir paid of them. +fn paid_by_regular(outcome: &MegaTransactionOutcome, gas_limit: u64) -> u64 { + let reservoir_paid = gas_limit - TX_GAS_LIMIT_CAP - outcome.gas.reservoir_remaining; + (outcome.gas.state + outcome.gas.history) + .checked_sub(reservoir_paid) + .expect("the reservoir pays no more than the state and history gas") +} + +/// `prefix`, then `GAS`, `op`, `GAS`, returning the gas the second `GAS` read less than the first: +/// what `op` drew from regular gas, with the second `GAS`'s 2 on top. +fn measuring(prefix: BytecodeBuilder, op: BytecodeBuilder) -> Bytes { + prefix + .append(GAS) + .append_many(op.build_vec()) + .append(GAS) + .append_many([SWAP1, SUB, PUSH0, MSTORE]) + .append_many([PUSH1, 32, PUSH0, RETURN]) + .build() +} + +/// The word a run returned. +fn word(outcome: &MegaTransactionOutcome) -> u64 { + let output = outcome.result.output().expect("an output"); + U256::from_be_slice(output).to::() +} + +/// A fresh slot's `SSTORE` takes its share, 10,000 at the spec's prices, from regular gas, and +/// draws 22,100 from regular gas in all, the cold access and the 20,000 of a fresh slot before +/// Satin. +#[test] +fn test_a_fresh_slot_takes_its_legacy_share_from_regular_gas() { + let op = BytecodeBuilder::default().append_many([PUSH1, 1, PUSH1, 1, SSTORE]); + let outcome = run(measuring(BytecodeBuilder::default(), op)); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), slot_share()); + if runs_at_measurement_prices() { + return; + } + assert_eq!(slot_share(), 10_000); + assert_eq!(word(&outcome), 3 + 3 + 22_100 + 2, "the two pushes, the SSTORE and the GAS"); +} + +/// A value `CALL` that creates its target's account takes its share, 25,000 at the spec's prices, +/// from regular gas. +#[test] +fn test_a_value_call_creating_its_target_takes_its_legacy_share() { + let code = BytecodeBuilder::default().call(NEW, U256::from(1)).append_many([POP, STOP]).build(); + let outcome = run(code); + assert!(outcome.state.get(&NEW).is_some_and(|account| account.info.balance == U256::from(1))); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), account_share()); + if !runs_at_measurement_prices() { + assert_eq!(account_share(), 25_000); + } +} + +/// A `SELFDESTRUCT` that creates its beneficiary takes its share, 16,000 at the spec's prices, +/// from regular gas: next to one to a beneficiary that exists, it draws its 9,000 of regular gas +/// and the share, 25,000 more, 30,000 in all, which is what it drew before Satin. +#[test] +fn test_a_selfdestruct_creating_its_beneficiary_takes_its_legacy_share() { + let destroying = |beneficiary| { + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() + }; + let new = run(destroying(NEW)); + let existing = run(destroying(FUNDED)); + assert!(new.state.get(&NEW).is_some_and(|account| account.info.balance == U256::from(1_000))); + assert_eq!(paid_by_regular(&new, ABOVE_CAP), beneficiary_share()); + assert_eq!(paid_by_regular(&existing, ABOVE_CAP), 0, "an existing beneficiary adds no state"); + if runs_at_measurement_prices() { + return; + } + assert_eq!(beneficiary_share(), 16_000); + let drawn = |outcome: &MegaTransactionOutcome| { + outcome.gas.regular + paid_by_regular(outcome, ABOVE_CAP) + }; + assert_eq!(drawn(&new) - drawn(&existing), 9_000 + 16_000, "5,000 against 30,000"); +} + +/// A `CREATE` and a `CREATE2` take the share of the account they create, 20,000 at the spec's +/// prices, from regular gas, and each draws 32,000 from regular gas for an empty init code, what +/// it drew before Satin. +#[test] +fn test_a_creation_opcode_takes_its_legacy_share() { + for (opcode, zeros) in [(CREATE, 3), (CREATE2, 4)] { + let op = + BytecodeBuilder::default().append_many(vec![PUSH0; zeros]).append_many([opcode, POP]); + let outcome = run(measuring(BytecodeBuilder::default(), op)); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), create_share(), "{opcode:#x}"); + if !runs_at_measurement_prices() { + assert_eq!(create_share(), 20_000); + let pushes = 2 * zeros as u64; + assert_eq!( + word(&outcome), + pushes + 32_000 + 2 + 2, + "{opcode:#x}: the pushes, the POP, the GAS" + ); + } + } +} + +/// A `CREATE` whose init code deposits code takes the share of the account alone: the code's state +/// gas takes none. +#[test] +fn test_a_code_deposit_takes_no_legacy_share() { + // `PUSH1 1; PUSH0; RETURN`: one byte of code, a zero. + let code = BytecodeBuilder::default() + .append(PUSH4) + .append_many([PUSH1, 1, PUSH0, RETURN]) + .append_many([PUSH0, MSTORE]) + .append_many([PUSH1, 4, PUSH1, 28, PUSH0, CREATE, POP, STOP]) + .build(); + let outcome = run(code); + let created = CONTRACT.create(0); + assert!(outcome + .state + .get(&created) + .is_some_and(|account| account.info.code_hash != revm::primitives::KECCAK_EMPTY)); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), create_share()); +} + +/// The account the transaction's own value creates takes no share: the reservoir pays it whole. +#[test] +fn test_the_transactions_own_recipient_takes_no_legacy_share() { + let outcome = execute(db(), call(CALLER, NEW, U256::from(1), ABOVE_CAP)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.gas.state > 0, "the recipient is a new account"); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); +} + +/// The account a creation transaction creates and the code it deposits take no share. +#[test] +fn test_a_creation_transactions_account_and_code_take_no_legacy_share() { + let init_code = Bytes::from_static(&[PUSH1, 1, PUSH0, RETURN]); + let outcome = execute(db(), create(CALLER, init_code, ABOVE_CAP)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.gas.state > 0, "the created account and its code"); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); +} + +/// An EIP-7702 authority the authorization creates and its delegation indicator take no share. +#[test] +fn test_an_authority_and_its_delegation_indicator_take_no_legacy_share() { + let tx = authorizing_call(CALLER, FUNDED, U256::ZERO, ABOVE_CAP, DELEGATE, &[(NEW, 0)]); + let outcome = execute(db(), tx); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!( + outcome + .state + .get(&NEW) + .is_some_and(|account| account.info.code_hash != revm::primitives::KECCAK_EMPTY), + "the authority is delegated", + ); + assert!(outcome.gas.state > 0, "the authority's account and its delegation indicator"); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); +} + +/// History takes no share: a log and the record of a slot that already held a value are paid by +/// the reservoir alone. +#[test] +fn test_history_takes_no_legacy_share() { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, LOG0]) + .append_many([PUSH1, 2, PUSH1, 1, SSTORE, STOP]) + .build(); + let db = + db().account_code(CONTRACT, code).account_storage(CONTRACT, U256::from(1), U256::from(1)); + let outcome = execute(db, call(CALLER, CONTRACT, U256::ZERO, ABOVE_CAP)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "nothing new"); + assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 3699d6dac..2dd8f18ea 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -28,6 +28,7 @@ mod inspector_limits; mod inspector_settlement; mod intrinsic; mod kv_updates; +mod legacy_share; mod limit_exemption; mod limit_matrix; mod limit_stop; diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 45eb7b565..86d3122e6 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1073,6 +1073,73 @@ fn test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_ } } +/// A creation transaction whose init code halts keeps neither the created account nor its write +/// record, and both were charged before its frame: the account's state gas and the record's +/// history. They come back only for the part the reservoir paid, and the part regular gas paid is +/// burned with the rest of the regular gas. So whatever the reservoir held after the body — enough +/// for half the record, for the record and half the account, or for both — the sender gets back +/// exactly that reservoir, and below the execution cap, with no reservoir, nothing. +#[test] +fn test_a_halting_creation_transaction_returns_its_pre_frame_charges_only_where_the_reservoir_paid() +{ + let init_code = Bytes::from_static(&[revm::bytecode::opcode::INVALID]); + let body = body_history(init_code.len() as u64); + let record = mega_evm::write_record_history_gas(1).expect("a record has a price"); + let account = crate::common::account_state_gas(); + let after_the_body = [0, record / 2, record + account / 2, record + account + 1_000]; + for left in after_the_body { + let (gas_limit, expected) = + if left == 0 { (BELOW, 0) } else { (TX_GAS_LIMIT_CAP + body + left, left) }; + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let outcome = MegaEvm::new(context(db)) + .execute_transaction(create(CALLER, init_code.clone(), gas_limit)) + .expect("the transaction is valid"); + assert!( + matches!(outcome.result, ExecutionResult::Halt { .. }), + "{left}: {:?}", + outcome.result + ); + assert_eq!(outcome.gas.reservoir_remaining, expected, "{left} left after the body"); + assert_eq!(outcome.gas.gas_used + outcome.gas.reservoir_remaining, gas_limit, "{left}"); + } +} + +/// The transaction's own value transfer to a contract that halts, carrying an EIP-7702 +/// authorization: the authority's charges, which the halt does not take back, draw the reservoir +/// before the recipient's write record, so the record is paid by what the reservoir has left, half +/// of it here, and regular gas pays the rest. The halt gives back only the part the reservoir paid, +/// so the sender gets back the same reservoir as from the same transaction without value, which +/// makes no record. +#[test] +fn test_a_halting_value_transfer_after_an_authorization_returns_only_the_reservoir_paid_record() { + const AUTHORITY: Address = address!("0000000000000000000000000000000000500010"); + let record = mega_evm::write_record_history_gas(1).expect("a record has a price"); + let run = |value: u64, gas_limit: u64| { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(AUTHORITY, U256::from(1)) + .account_code(A, Bytes::from_static(&[revm::bytecode::opcode::INVALID])); + let tx = crate::common::authorizing_call( + CALLER, + A, + U256::from(value), + gas_limit, + B, + &[(AUTHORITY, 0)], + ); + let outcome = MegaEvm::new(context(db)).execute_transaction(tx).expect("valid"); + assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); + assert_eq!(outcome.gas.gas_used + outcome.gas.reservoir_remaining, gas_limit); + outcome.gas.reservoir_remaining + }; + // What the body and the authority took of a large reservoir. + let large = TX_GAS_LIMIT_CAP + 100_000_000; + let before_the_frame = 100_000_000 - run(0, large); + let gas_limit = TX_GAS_LIMIT_CAP + before_the_frame + record / 2; + assert_eq!(run(0, gas_limit), record / 2, "the authority's charges stand"); + assert_eq!(run(1, gas_limit), record / 2, "the record's reservoir-paid half comes back alone"); +} + /* ---------- the legacy engine's rows ---------- */ // The legacy engine halted a transaction a limit stopped, and gave back what detention withheld diff --git a/crates/mega-evm/tests/system/common.rs b/crates/mega-evm/tests/system/common.rs index dcd81e511..57fb1a303 100644 --- a/crates/mega-evm/tests/system/common.rs +++ b/crates/mega-evm/tests/system/common.rs @@ -198,6 +198,11 @@ pub(crate) fn state_is_free() -> bool { true } +/// The state gas one fresh storage slot costs at the byte prices in effect, in the minimum bucket. +pub(crate) fn slot_state_gas() -> u64 { + mega_evm::satin_gas_params().get(revm::context_interface::cfg::GasId::sstore_set_state_gas()) +} + /// The state gas one new account costs at the byte prices in effect, in the minimum bucket. pub(crate) fn account_state_gas() -> u64 { mega_evm::satin_gas_params().get(revm::context_interface::cfg::GasId::new_account_state_gas()) diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index a0e890345..8c91f97fe 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -78,6 +78,31 @@ fn test_an_empty_signer_is_charged_its_account_once() { } } +/// Above the execution cap, where the reservoir could pay every charge alone, the call's regular +/// gas pays the legacy share of the signer's account its nonce bump creates and of the account the +/// creation creates, 25,000 and 20,000 at the spec's prices, and the reservoir the rest. A signer +/// that holds a wei is no new account, and its deployment takes the creation's share alone. +#[test] +fn test_the_call_pays_the_legacy_shares_of_the_accounts_it_creates() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + let gas_limit = GAS_LIMITS[1]; + let paid_by_regular = |outcome: &MegaTransactionOutcome| { + let reservoir_paid = gas_limit - TX_GAS_LIMIT_CAP - outcome.gas.reservoir_remaining; + outcome.gas.state + outcome.gas.history - reservoir_paid + }; + let empty = deploy(db_for(&deployment, U256::ZERO), &deployment, gas_limit); + let funded = deploy(db_for(&deployment, U256::from(1)), &deployment, gas_limit); + assert_eq!(returned(&empty).deployedAddress, deployment.address); + assert_eq!(returned(&funded).deployedAddress, deployment.address); + let account = entry(GasId::new_account_state_gas()).min(25_000); + let created = entry(GasId::create_state_gas()).min(20_000); + assert_eq!(paid_by_regular(&empty), account + created, "the signer's and the creation's"); + assert_eq!(paid_by_regular(&funded), created, "the creation's alone"); + if mega_evm::active_satin_prices().is_constants() { + assert_eq!((account, created), (25_000, 20_000)); + } +} + /// The created account is charged only when the deploy address is empty, as the `CREATE` opcode /// charges it: an address that already holds a balance is an account already, the deployment /// lands on it, and the balance stays. diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 9144638a0..b99c217ac 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -130,6 +130,70 @@ fn test_keyless_deploy_execution_reverted() { } } +/// What the creation of a keyless deployment returned into its call: its regular gas and its +/// reservoir once revm's settlement of the result, which runs after the inspector sees the +/// creation end, rolled a failure's state and history gas back. +#[derive(Default)] +struct CreationReturn(Option<(u64, u64)>); + +impl revm::Inspector, revm::interpreter::interpreter::EthInterpreter> + for CreationReturn +{ + fn create_end( + &mut self, + _: &mut MegaContext, + _: &revm::interpreter::CreateInputs, + outcome: &mut revm::interpreter::CreateOutcome, + ) { + let mut gas = outcome.result.gas; + revm::handler::handle_reservoir_remaining_gas( + outcome.result.result, + &mut revm::context_interface::cfg::gas::GasTracker::default(), + gas.tracker_mut(), + ); + self.0 = Some((gas.remaining(), gas.reservoir())); + } +} + +/// Runs a deployment of `init_code` signed for and forwarded `forward`, below the execution cap, +/// where the call holds no reservoir to share with its creation: returns the outcome and what the +/// creation returned, its regular gas and its reservoir. +fn deploy_forwarding(init_code: Bytes, forward: u64) -> (MegaTransactionOutcome, (u64, u64)) { + let deployment = Deployment::signed(0, forward, U256::ZERO, init_code); + let mut evm = + MegaEvm::new(context(system_db()).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) + .with_inspector(CreationReturn::default()); + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(forward), U256::ZERO); + tx.0.base.gas_limit = GAS_LIMITS[0]; + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let returned = evm.inspector().0.expect("the creation ran"); + (outcome, returned) +} + +/// A constructor that writes a fresh slot and reverts, run on 500,000 of forward and no +/// reservoir: regular gas paid the slot's state gas and its record's history, and the revert gives +/// both back into the creation's reservoir, so the creation returns its unspent regular gas and a +/// reservoir of exactly those two. `gasUsed` nets both pools: the regular gas spent less the +/// reservoir it returned, which is the constructor's regular charges alone — 12,109, at any byte +/// price. +#[test] +fn test_a_reverting_constructor_returns_its_slot_as_reservoir_and_reports_its_regular_charges() { + const FORWARD: u64 = 500_000; + let init_code = Bytes::from_static(&[0x60, 0x01, PUSH0, SSTORE, PUSH0, PUSH0, REVERT]); + let (outcome, (regular, reservoir)) = deploy_forwarding(init_code, FORWARD); + let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionReverted: {:?}", outcome.result); + }; + let given_back = crate::common::slot_state_gas() + + mega_evm::write_record_history_gas(1).expect("a record has a price"); + assert_eq!(gas_used, 12_109, "the constructor's regular charges"); + assert_eq!(reservoir, given_back, "the slot and its record come back as reservoir"); + assert_eq!(regular, FORWARD - gas_used - given_back, "regular gas paid the slot"); + if mega_evm::active_satin_prices().is_constants() { + assert_eq!((regular, reservoir), (386_451, 101_440)); + } +} + /// Init code that hits an invalid opcode: `ExecutionHalted`, and the halt spends the whole /// forward. #[test] @@ -328,6 +392,29 @@ fn test_keyless_deploy_init_code_selfdestructs() { } } +/// A constructor that destroys its own account on 500,000 of forward, no reservoir and no +/// balance: the destruction gives the account the call created for it back — its state gas and its +/// record's history — into the creation's reservoir. The creation returns all its regular gas but +/// the constructor's 5,002 and a reservoir of exactly that give-back, and `gasUsed` adds the +/// give-back of the call's own charge back to the creation's net spend, reporting the 5,002. +#[test] +fn test_a_constructor_that_destroys_itself_returns_its_account_as_reservoir() { + const FORWARD: u64 = 500_000; + let (outcome, (regular, reservoir)) = + deploy_forwarding(Bytes::from_static(&[ORIGIN, SELFDESTRUCT]), FORWARD); + let KeylessDeployError::EmptyCodeDeployed { gas_used } = failure(&outcome) else { + panic!("expected EmptyCodeDeployed: {:?}", outcome.result); + }; + let given_back = crate::common::account_state_gas() + + mega_evm::write_record_history_gas(1).expect("a record has a price"); + assert_eq!(gas_used, 5_002, "ORIGIN and SELFDESTRUCT to a warm account"); + assert_eq!(regular, FORWARD - gas_used, "the constructor's regular charges alone"); + assert_eq!(reservoir, given_back, "the destroyed account comes back as reservoir"); + if mega_evm::active_satin_prices().is_constants() { + assert_eq!((regular, reservoir), (494_998, 187_120)); + } +} + /// A constructor that has its own account destroyed through a `DELEGATECALL` and then returns /// code reports `EmptyCodeDeployed`: the code the constructor returned is not code the account /// keeps (EIP-6780), and the answer is read from the account, not from the return. 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 b57d440a4..15cd6d7eb 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,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0x70efa1acc6606a24ed2001d41f9e6ac401ef411f46c929dee5043aa06be58810", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x6401f75c56ae5ba4720369e22bb4fae524a0d92109200d1b814890f050b4deb7", - "rule: arguments that do not decode @ 50000000 | keccak256=0xf200f388d13c3181bef7bd920c142d7682efb6a66a337cd89380d9c322b302e4", - "rule: malformed transaction @ 50000000 | keccak256=0x53e169618aad04c59acaa0e61bf9a259e42b3994e3df64ec789329dd04a03472", - "rule: a trailing byte @ 50000000 | keccak256=0x562d6c884cab4c6ca986bead04dc90661c3dd59026842d504f1a785f109ebde9", - "rule: not a creation @ 50000000 | keccak256=0x3931ffdc0411acf5f321a32fd6fbd0c8b9cd6fc15367d7c222838b2fc4ea9543", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0xf1790e8bea46c362feeb1df1248b98b01b49bbc09fc65d98b7115c1c62dae29f", - "rule: signed at nonce 1 @ 50000000 | keccak256=0xd530dcbaa455e42dea19995fc375f2820b11a754de9de9449e1cc94de1cd3c90", - "rule: override below the signed gas limit @ 50000000 | keccak256=0x38f956a3c77cc6277358eed1c37efbaaf1c8395a1b7f636557c79d4d10bd4b5c", - "rule: invalid signature @ 50000000 | keccak256=0xf5c63e312cfdc749521203895c1285c808f7b75cdfe450a3373886cfc483d2f7", - "rule: signer nonce 2 @ 50000000 | keccak256=0x1df4b39c2977f3c87e509a625071ede72cc178f6b3223bfe782afe53290a58e2", - "rule: signer with code @ 50000000 | keccak256=0xabddaf8853eb78b9173a941c821eacf6f99802f58d3468ad77733304b09df430", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xc78ad48afdd9001f381a0adfc0cae161686cf6ee5e5a6ca14fdb3ed6cca97d59", - "rule: occupied address @ 50000000 | keccak256=0x96edc259014ac2c99fefdefe81f2a7e3115478617546afa13ed78a17a20d5f3b", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x56c9e35e8a022786c2d4373670a0e1a104d799e84a520f594aa3384abd0018f4", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xaf969a7082886d0e4cf5afea2b20867ef5e120ab1fb8bf890032fbad5684cd59", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xa070e0164517815cf14a57192c9b7cb76ba4e182124febf91be0320a83efd149", - "deploys from nonce 1 @ 50000000 | keccak256=0xdb9a5d1313d9e12e11bc0766501e290031c22f73af8df11494857015acf7c729", - "the address already has a balance @ 50000000 | keccak256=0x02b5a107b926e0a0b867fc256cb3ab403382e9d7acfbc8cd16b1e17f2caba734", - "moves value @ 50000000 | keccak256=0x4f625126760c064a90bf9ab495a6f42dc9f2a91db86771d44d803c762dd3f285", - "moves value from nonce 1 @ 50000000 | keccak256=0x3f725d461e52c0392f80eaf6200af7a5d799d917f4aab6a62dde15a85bf11054", - "the CREATE2 factory @ 50000000 | keccak256=0x1ab746976b43499851c0deb1bfddaf798f1f7c889dbf0398a4a7e80f158662bb", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x55ea2bb23dade17a76b767000640469d37aed89924ef185bde1fd3f8ca1861f2", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x7bbb859d05d2c5079346f4b5c4adb2514271e60342bc508c7cd657b78536630b", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xd70f77f32871fedaffd9be868aa73be297b5b39af8d812a9227a6e7637eec2b7", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x1df5d50f7cd9ca327d52d3f5e7e52c52b59376acc988fede8f6b7212a1f1906a", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x2fc750cc4eeabe6870d1b9cce22fe77f7b9dd66df3ff9d9d546365944ec89f86", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x85f487e3f21dd23012cac9ee26741ecfe43b68d8a170f0ca429c23831068022d", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf1e561d3cba6267a8326ab81ded8f8edffc72b4beb15c1abe6853a7f48101e77", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xb8c8bafe75039598f433f1d7d20942d0ca7b2b0beed86f65f58f0ff194079ba9", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x2e8a101e9df5be12528cbf24cb30f1bebeeecc5df2b5268d29f9416ac175c451", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x306935b3351c2363335d1d972683d7ffbf967c9ad6404fcb8dfeb79051dbf3c9", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x1bb85e30bce7c14e98b25a0e1d9b6c2e895fe1f46c17f9472b1f21cf6ef62077", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x062278078c36e5eed12c3c3abefdd94d8e9f0a0125d272780a61565117a0f57e", - "a constructor out of gas @ 50000000 | keccak256=0xad13ba28e89f0c5d77c97fb7267b61a6e0d3ff587346ee7613371b175b54e4de", - "the signer sends it @ 50000000 | keccak256=0x07d09a10d770e7389731b55c2e6b57d23042735f561a001df883fc31075d8fce", - "the signer sends it, and it reverts @ 50000000 | keccak256=0xcdbd6d53d5b79f49e8d12db6ccc916d493cc1517be04994352e9379bfb03f78a", - "a delegated signer @ 50000000 | keccak256=0x19e5acb7f0ba435282dbbd816a80ea2b6cae219728d174e33ca777cef49ba2bc", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x6937a8cd14af128f65787d290aeb2f74b2c566c12822b8584049b094069d7557", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x03ea2d6ba86920a73c4fae1f9a328142ced7164fa707002594212fbfa32fc1ab", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x6f92465c464e4f71bb87b572126bdd5c3e8c722266f515ec81cd44f1cc05f7fa", - "limit: compute, nonce 0 @ 50000000 | keccak256=0x719b68a8c50d953107b708eedcca301ce7be644adb045eaeef4dd5c2df4f27a3", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x77099302d2c2175a512849c6f19cdb408a56309bb9b67e836881dd475b3455a0", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x3e96f6426d3b9178434293bfd3e94e69770d55722f51a162788bf6001e2c9e49", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0xec7133b31e08dc890d5e9f1d9d94ef97abefd01a30649e8c8ac497b27fc7d9a6", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xfcd346c7219b7697bd07956e48b347aba0a4d80eaf30c6d26516913c4fdcc18a", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x58a87ce6c75938b6dc28b4f35a6d37dd2c6054d7e33fed9a2218b2ea3530bf3f", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xe69b6012c385e2d2ef05a565eab6d9718035e9ebbf45f913c25f7fdaa8b32495", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x37e82390d17d9359b12421f823b3641f70ffda00505a00a328a201cabd536c4f", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x084321871ea7833360460d033aea4fee0a57dd8f2a5bb2d3b94e45cf20d22c86", + "rule: value @ 50000000 | keccak256=0xc3b43754d461dfa5918bfeffa9ce9fda217b41f87cac0cda66134e351934b406", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x43d7196d1e6199ce2e92b589b489bc02968f41e19abc4f3c41b75782dd7947ba", + "rule: arguments that do not decode @ 50000000 | keccak256=0x93acb4de193a5c435f9b36d21efd46cf474a313d7937c4916359fb4ff9c1465c", + "rule: malformed transaction @ 50000000 | keccak256=0x4faea5d2f1bd3bd07743eba4568947ee5e60e47bb08d9f991ce76f214df8f427", + "rule: a trailing byte @ 50000000 | keccak256=0x8a1eb1a2bded1e55cf53fec655d6bf71954dbe1557ffb91943d0d9b145053cfd", + "rule: not a creation @ 50000000 | keccak256=0x3eb99bc18add0322b48be4a3f233e00a2d2e9b53562729852c0ec9ec2b36c27e", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0xdcd998d59e2ebd8b3fdb27b81d32b6d40538520a7d55da9094de1438eb134618", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x808697be7470d66b58100bee933e5cd03c7085f0f60a7ec2f00a7e7a9c28752b", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xe22c9afcf1f7decacec6200cc83dfc4c5f54b94dab89126e65aeb007431cebfe", + "rule: invalid signature @ 50000000 | keccak256=0x7b878cc8e808f68c6e78540d59855de66de3ec45752e3caca40d923570cb5a5b", + "rule: signer nonce 2 @ 50000000 | keccak256=0xb24a62a13524504fe58dbde62293db20e9288a3c3a59f5ea7d3a2dcfad9aee95", + "rule: signer with code @ 50000000 | keccak256=0xc264f5fb73ba98555a5b333f88f246d505949fdedb6c29ce562ea4766b54ea22", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x565239fb5e3b27186d60a4892f0b5f716dc0b96155e59b6a59203ab1e5b86f68", + "rule: occupied address @ 50000000 | keccak256=0x782badc0f4f7e4026b3c3eb82e5eaf61be67d37cd6f4cd14193c6a7852d1807a", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x4ad52c1303eeb8fe3e52c2229c9994acd9d0485846b655206148e429ef3620d3", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x21232c1e38663e1b77afc1b66722d7f4ece80ad1af8947b31704513e76f4eddd", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x64520348cc3a5c32da19e721788407ca3a10baeed0022d2cfd877552d3c4d5f7", + "deploys from nonce 1 @ 50000000 | keccak256=0x34c98dd2349896d43c22c2c772e2dc0b828e9d6c46b8593352736c5d84e978f6", + "the address already has a balance @ 50000000 | keccak256=0xaeafefb00fd16aa517628dfa3ca2e2fd6deb0c3da7e027bd4c012a6573955e40", + "moves value @ 50000000 | keccak256=0x7e83bf3d83ecc33a967c30c91cf8de3e14b9fd82bd3ca3c38375b8d6fc17760b", + "moves value from nonce 1 @ 50000000 | keccak256=0x92cf77de731dfe50ffab58893cdc7b4696a2e463048ef25b78f15ff4f676a6f5", + "the CREATE2 factory @ 50000000 | keccak256=0xd355575f63fc93c89c34b0a3eb9bec29dc68d9d0692aa85f5e4653400752138d", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0xe6e69d4f852387bf4e0f3406845abca7e248a50ab70b0d3e9790220b218d9337", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0xd1ac026d3f84329ed597524ebdeb738a950d03faa458c240900cd08d3c8273b2", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xeedf8e92f81d19b812442e261bf89e86f81d3added3496879e72ee3f55290c1f", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0xc36b93f760ee97a66042e6d32ee9ac98bde48272c267cb87e9c13f4844325d59", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x94f60739a7f21e8d69a31f78053b1c2840a35257724c19789b333c26a4496fad", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0xfbca110b9b6bf52f07cfcd8413245ba76cf6d72fe48b25ab2de99ec22b6a80e0", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf5e3da20ddc63f2304f4750c1724d5a5a9915aec5e24daace911b8e245d2ec7a", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xa440c295448490f3ea5f2f2380241dfdb15a3e9821c387db7bff602c892181c7", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x8dd1b516567b0012de07c4f1d528353bfc5960a17c693e05752633619478c520", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xe5a0bb9a0be01370d7d2d469c3a526c2fbd3b3a2e432da01fef409172f563796", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xf289a0fb9ecddcf9d67e1822705ace6235f9e9a9c9a51cb38189218fd3f36fef", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x751a636bc589a14114361cb58d9b2a5413dfb31151cd367157f4f13257f7e81a", + "a constructor out of gas @ 50000000 | keccak256=0x29f53c9ff2810a160ecd2c4f226588a4405eb27b7c8e0b7bfc86eb75f6a2d93d", + "the signer sends it @ 50000000 | keccak256=0x38d4d4bd27d290061ed31c1c222e5d1b233fb5f602a2f8a808a153e1dce8bb06", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x775b1526ea415f212c808670ddbd07d5e0480d1f8632ee56f62948df40eca660", + "a delegated signer @ 50000000 | keccak256=0x5bb2a3dc8f16a8023d2bfeb852249194c55339c00bbeb69eef9848510c11aa5c", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x23d41e1bf2e7f6ed2e446443f9c4197481f6a38d90e84b9c29b194fa00682c9b", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x0c54859c5a5450d01362fa9ec33f979380c1f87c1aad764ccbb55e00b497e1cd", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0xdd9fc7f9b1933385d3dba06e5e78f24cb3cbdfbc3baa808845cf507d88756692", + "limit: compute, nonce 0 @ 50000000 | keccak256=0xef2ba5b0e112e47a789e769a3c6b7b81f93ff4fd535c322ea19c33ba4fa3781c", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x7c694f324ca40881b3cdb87180db35c68847a8d61088b7e384755690c2c39362", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x35ac020bcbc2ed778af92c0e9365b0d10038fc8c585cf3d90d69db76bcb9bea1", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0xedfd6eedaca50b1822557ab886c9385635e172657ac6e498efee2f9c28646512", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xd55d03627ef3792b8bf54319f4b5722ba4201e7fa3ca72fba6c5c77b85961beb", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x6694e205cdc91a7cd6402311912f2de489e411c4dee1d70db1aa0d82666b00c1", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x9b71202a63e6c75be04c1c9db3b2df8955463425b6d0e9e0acccc028d7b0a7c9", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x3b58c7f907d359c77b75f1ca75ef869c054bdf750e351cc020743d74adf88aaf", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xc4c9a8c68a28a7813ae6ac51254141a128b798fe0d313064630d6c43add015b7", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0x919892378222c40706e814a238a1ee4f944b46bb866c6e817f601b25ab75b1d3", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0xd4d2aaed70e8037c8a580082c3a455d5b2621458ab2e185757e7f34c134d5094", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x3e77cd1122e5a36a2f263588bc31ee121153522339429c5d22a5a6edd18c2cc2", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x79784d636eedee5ab3156e061522cedd82bd44f40f5ecc31a75a41f7be2974f1", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x2770955b8680edbc970045b5bcfc9dc6b600c85a79d49aaacb5204a17373e53e", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x4016516a62f99801431f01b9ab845454efe2f0bdb8cebaa6b9aeddaf54b10dd3", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x88429a0c2b61cf28a39034867b63f3c1beffeeb1585dec174263c0d022569d00", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x00495742d5b3b72af8bc0edca3c894c807ff0ca253fb4db9d2117682a64006bb", - "not dispatched: version() @ 50000000 | keccak256=0x71a50aa1874824302b03d490d18fad98f4ee6c67c5e070f0f6c612c103c68fce", - "not dispatched: no selector @ 50000000 | keccak256=0x803c0e37355e9089a6b22f814fd5dd49e3fcbee17d268f639980683f9520ff01", - "not dispatched: from a contract @ 50000000 | keccak256=0x1a46ddada15cc027f867ea5dc0124733491439bc3a587799a8d04ae6b82a1015", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x1ed714441d5f5b08e8d82f2a27d53a8cf60560a686928e6850f43db84987ffd7", - "no contract code @ 50000000 | keccak256=0xd070c6166a53661bc3203f16a69707d9e8846b3c1737d22cbfff5a7a5f6f67c8", - "a system call @ 50000000 | keccak256=0x23867bfad6c1f95ee8422b2c15dfb47ab157163fecdb69f6e142f50971b86ea2", - "rule: value @ 400000000 | keccak256=0xb00b12499990c15c1599808de7903b34b5ed9beb8673675a5a9aa77fafa9015b", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x3dcf58fea56c393d9432b8d0ddb70ab27c94f1f397297097116ab93d288638d9", - "rule: arguments that do not decode @ 400000000 | keccak256=0x1e85d077ef72d33c8bedeef7ab6a25396d2045a316422c35a003947d831b924a", - "rule: malformed transaction @ 400000000 | keccak256=0xa14ab3686735b259326aeefd8ffde19e7d03ca5f6710a8278d3c20b3588941c7", - "rule: a trailing byte @ 400000000 | keccak256=0xe3dd6f5f1d180e13aa45ac712b48ae4124f1f24283214c1aa69d30174cb444e1", - "rule: not a creation @ 400000000 | keccak256=0x228398e161b11148e9c04b5732a72a116f61e8682066063a104ac1065d76ba47", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x70e03ab019a3197e2beb416b2733c1fbfecfcb4a65f8426d33c0acdac8240f8a", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x0cb600cae0b629f42c3dd757e88a46f22d4a560e44f3638566453f9ffd5f495e", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x7bdc52f604cdd3f736d5044d4255ad3147ffb3205377c6adaad530fb6c45a342", - "rule: invalid signature @ 400000000 | keccak256=0x89ace74ee50426587d8c4d77ec5e73120ab42ffb793fd90a1a36042bfa6c3578", - "rule: signer nonce 2 @ 400000000 | keccak256=0xe5d29781298581917c3cbb3811521a98a7f1faaa6dc808eb317fc6cbfac7a4bc", - "rule: signer with code @ 400000000 | keccak256=0xe1a8336834a3b2bc39e8ec606532fe58987837155833513489670f5ee48a02cd", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x19d8abae07d5f60cc71d626a2fe05b52f49634f5a9bbd8dbc46eba04b0be153a", - "rule: occupied address @ 400000000 | keccak256=0x9c400b1873c619f57bbce100b0733b6abee2e89fed0634afffbb5170fa5b7545", - "rule: value the signer cannot fund @ 400000000 | keccak256=0xd0f45281316372225586ac044d825ca80e866f48389ab48ebe3076a037091c17", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0xaddfe60e384511929bc3915941afff9ed661f9b9d36eb5597ba64f15bfc62966", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0xbc03379378902229c9993b4430c02703af25c6632886c104493ca8f3a2f0dbcf", - "deploys from nonce 1 @ 400000000 | keccak256=0x9d7e11c1028204bdf6588c73e713b10084c132131312ff827866d63dd4318070", - "the address already has a balance @ 400000000 | keccak256=0x5e7138f7e8ab1a58e38637ee096125f705ac2b72cd4d28123d563bf85e577e29", - "moves value @ 400000000 | keccak256=0x78de09b3f6b8474e0cb7dbd6b14109ef974f219da90eb9237001dd8dd4ad20be", - "moves value from nonce 1 @ 400000000 | keccak256=0x2690289cad93a5c30acdbb39c84faddd0fddbba12c5127619464a141dd1fcd59", - "the CREATE2 factory @ 400000000 | keccak256=0x8fcc1f818461f802fa686a10bcace2b06481553aeaaec17587de4597df3b61f2", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xc13c20e0990cd146c07d62a4841e4bdb4108209cf1c6198557d22b209ce1637c", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xafcfbab9602ba7854d37050b7d9d4de693f7b5155bd9e82ffbe431309634ada3", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x14e4b2ecadf5c5b8de262f29ab527880c3b89f6238751675807c53fe78ff0cc2", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xf02bfc9aa63148fcbbc9a954168625c0be2bd6fb33f83acf227547c3ec11fae6", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0x87b86bfafee294f67d1167ea8400b5395d667f8f5d5b48ba09d732a96ba18525", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x07260a9fadf457dd238f0f3731a5c7410ee88ec525ce384b5f0a4aa39759feb4", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0xa0792622b4ea74af6d05f1743376c73106310c58533c1ac129a7b63b978de355", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x2ca62b6c2400a6e5d1beb27ce072fe5a6f76aca8955ad850f481c9c39f0faec3", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x353cfb678009b8a64bcf235bdcab14c59c8e38fa15d77903b57957963e1c50e4", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x829c4a203fe9f614d49a78d00f02dc19d665be5959385f34a08e206d6df86837", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x87e563ac4638ed7a1cb7b28ac746f5fe7529f78beb2f34d331089e3ec5b0a5fe", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x1d754d06fdd43ae1b115f1d8394ecb6157ad0dd01ba6e2204701459ec4f4db7d", - "a constructor out of gas @ 400000000 | keccak256=0x8a165953e7d6b780e095bba69394619c602f95b4572c1b1af3ee37b18cf8be66", - "the signer sends it @ 400000000 | keccak256=0x3c5ed1a7b0f26ec3125e8488415cc4685b9953387eb8c1876adb9006e83bfac4", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xda4adad654303fb7efc3c45a1853248c4353fadb078119da44b7cca407bb697c", - "a delegated signer @ 400000000 | keccak256=0xd1a2bb70319354c0d740f3da55a587c30393154536ffa531e7277488042401bb", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xf5b740432d179042db6967e150b24334f6ebbe89c93463ec21392a10638c8867", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x669c28012fbf83b3fd8e1b4e7f55870a204f03976f759e8a403e8d6d28d4beaa", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xa474fe8793c49f08bba482b9c9bc75f0f58f45974ee479f4a6d84731ac0968dd", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x40d23c09775632cc70ddc91895b903311247acf7af67f94c12af1e732399a48a", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x4d4a97c2a94ff55a369d67540f7ef37a9a09eb2bebcfa283ebb93661a1b4b21f", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x7c84b6ab291fe88f6d9824e8b944804ed070bd6985c2428026a546466e80b464", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0xd0854bb20fdf914624a7119d0fd53f57d1a97ea3cf491e00cf238cd01bd7babd", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x22575bf011874b0d59ac9b2e43a59a5a21dc4b123150bc1272bb599ff2a464dc", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x0af21d7722fa8d4326b54c604d9dd6860d75a1e99aabfe7311c3595bcdbb232f", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x15f213ecf86068b2a34ab80a0b6b7536184bed6652c6a4437663e67052e8acb6", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x5a7032e41e19498cd7dc56c2c2cd9d3c3d239bbb3943bcbd1fc2218cb4227562", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xd9851d97da36ec9bd032e42b9ea43ac1b31d630e5a5278f8b783ed25d9d53d5e", + "limit: the default limits @ 50000000 | keccak256=0x209540591c3a38d6b2e445019c2d343ce9a48f7e404b009f48f2c822b4abe593", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x13231f3cd28dd7e2edfa5565fa3fe29cac9deb4b96813cd330de5ad8abf739b6", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x578a6e5eba12e2247f5407b8d24664b1417d8c18d6e5920caea70a42ed8f9c97", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x5a334d581d838cc723854cd1beea6704ce666e23032aa4ee982fcc1140e84596", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x99387894fe7dff326531c9b2cab8e1c1e94e61d7ff6f186304017cc9d56afc96", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x0b03ac4a952ff6be872ff2ae4520936645d4cedab6fabcfe7e523e8ea96cdaaa", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xede425c3d9b69a9df798bbc6e44d1cdffe9e97d0ac4d4d9258200de8d3ddcc52", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0xd6d76652001980ec8ee4cca787027b7d1406c5bf0f19d9e25add1c9b1255241a", + "not dispatched: version() @ 50000000 | keccak256=0x541deaac8fac3b007f001f800e99927136493937a95a4c6cfba0a5f019efe16a", + "not dispatched: no selector @ 50000000 | keccak256=0x58f1e6d8f7676c41a540b8851cdac9392b801d6f6c55a740a61952a2054ba714", + "not dispatched: from a contract @ 50000000 | keccak256=0xf58fd24a5655470eae7ebf48dea32ecbd420d9db233592b111f888daef9dab5a", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x8e3c6f7c9e2783b4917dab1394ce1156eed8eace1f325a953040f5ed7b656d7e", + "no contract code @ 50000000 | keccak256=0x6752c03881eeba1f19ef9a88742cf9957939d9f610ffda9ac5507acaefabb015", + "a system call @ 50000000 | keccak256=0x12429c54282df9825596b87532e0f3e9959b1cacdacb580819e1064b7b0311a8", + "rule: value @ 400000000 | keccak256=0xabae6bd19c2845f2d65259715d280aadd786c2a162ae6ec6b810fa08a4524515", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0x5528d2521e033dbb089814d8994c897466f585f53e4edde8f6ac182aca0a51a1", + "rule: arguments that do not decode @ 400000000 | keccak256=0x83d6da72ae825b98cd6c14498a58310a676509d8effc55180c6581b1cecc2a96", + "rule: malformed transaction @ 400000000 | keccak256=0x8e145192945e11bd92445a6dbb0f57d86f44a89e8127653837c0a586863d229f", + "rule: a trailing byte @ 400000000 | keccak256=0x411fd177353cca21ca9f12ebe963358c52f195dbda598bc459bfe50152e6e81d", + "rule: not a creation @ 400000000 | keccak256=0x4dac3118706624308edda37bfeaf255b70d0be899e6accab4629caa811cd049e", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x00a66474bac782d23e56d9ef21824f38826221d0fd6e595767049653214b022d", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x5f1d11c6d25e150dda97afd81c375f2a8614c5b66ffcd3c6c8ecc9df199b5488", + "rule: override below the signed gas limit @ 400000000 | keccak256=0xd1f2b226c4d8a52688702b61bb28a4bfaa9a0b9854ab785501b90a69fa88517b", + "rule: invalid signature @ 400000000 | keccak256=0xef42132c35881c8ddc9d49795051fc37ee6b3ccaf9ef87e190f0c8b77c121e99", + "rule: signer nonce 2 @ 400000000 | keccak256=0x2dbc65e4d4612973dd7476af30991fd21c9ff55677129c90310c290cb2a5e792", + "rule: signer with code @ 400000000 | keccak256=0x88676184ce398dbbc84b1c20fbbb9595ffb78a36b008f9820c3661cc7806856a", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x2a959fc341801760e14b235e5cee36ebd5617f8de1841cf4aa937fc674911626", + "rule: occupied address @ 400000000 | keccak256=0x379893de01787694d704e98e05690ab6e52b947ef67d447d941ba997040c6145", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x29e15229205ba4aaf6af5a02d65ebaf458a92caefa20b1989d577c102d6923d6", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x0df7a96196357042132e5eab149190e86770bcbe8a8c2d5afcbeb07330936627", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x01a56cdc76be8496712cd4511d05595bda3d936bac193ab71130a06178af916c", + "deploys from nonce 1 @ 400000000 | keccak256=0xa0729131ec01d00d77fbaf3c7e2a4c333a51697e9830ace70ae9cfba3f716a68", + "the address already has a balance @ 400000000 | keccak256=0x69ffae4325b6c87d39ad7ee811426bf57a93a70e6a99da42256fadaa3020512f", + "moves value @ 400000000 | keccak256=0x4ba6baee9596212e050261034f937d9c9de0a09c222c6e8ddc21170e385db863", + "moves value from nonce 1 @ 400000000 | keccak256=0x49173f5bb526fe27fb2c073fce9fe193b5f2e67d3e8013f865cada07fc1f032e", + "the CREATE2 factory @ 400000000 | keccak256=0x9ec569f071b101ec7e3eb5d6d6c4f6a60890c9a5d790a0ea34363c5d3d5b86db", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xe313a5a4197f8da5cf8e137b1a6022ddc479aca6c20a19b4541783e28d1d71c8", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xe76db8666ad51a56be93f784eb68da643287674994653baa88f22deb6a164399", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x1b4550bf9761772dd0b549d61721fafb4326891782034570301e3fc7e177ec29", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xd88b8c64b1cf4aca61d26b0e5e6b2052cdf033228508e14ddc865f515bd3415b", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xccde5bf26745fb0863111308aac1aa6b9bb67a1dd3b200e0f25270fba4e8ee55", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x9217efc4cfe6d14272eb02c9919bc8a63c68547c27f0121d22019c738154bf5b", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x81d4f6b683091715fee7eb499f0a4ebd7122756f8ead993d6f5b569fc7b57838", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xfa1e75a1a29f6c7163ae4970d0f261c71b7cf71da831eb1d7b1b0ba06fcf2dbf", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x87e10c55079a603849fe7da38ceb444707cb05d16e9f68a410ae7f62669c4883", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x97bc02f3b8d030c247d40e8958f9570321de80c8b5e9fc6b84a1ea6c5267622a", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x4cebba01356ee32eb2c02e0ff4774011d45ba1a77e607c4ad8400b1efe216b8f", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x075e641dc65727b1f093f5721e60bca7a3f1f3a1593ef72199c069e972f22236", + "a constructor out of gas @ 400000000 | keccak256=0x1b5423a976e515c3594ebbbeba662379c15eb7fa4a4723e38df5cadfa143b599", + "the signer sends it @ 400000000 | keccak256=0xdc1cdf72937c79d7c3064ef71e9b2e1e7d91066327319091a1b75c0064e34e65", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xfc64c01f65436e8907a2902b55c26db022ea82bd1c6716527fc74c466cdcc6fc", + "a delegated signer @ 400000000 | keccak256=0xdb807928d7b0fb523b523ae25965ec3559726c44d03553ffae59d3e544ad3ef9", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x35dca5fa2ce73fb9192577f5336ca62a2a160e3c59d1b4ba7fd2b2d5c9aa0db5", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xd424255e8c387294ab969492b54fb39e61c3e4afe8275b24c59993866ea43142", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x628022aa8c9a74e0f2971cd49d08bca27142c50e889b7cadbac4ca50af9baf3a", + "limit: compute, nonce 0 @ 400000000 | keccak256=0xbe1ceff538a04766b04ec061a7342da8964906d59bfee8ba8d191a3ea1c56845", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x59fecc921717146171b2d874e7da06330b171c17d45c11f2be112b61ab358310", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x163418dd81e6b1126a3f33d3e3a46d63d51b32ec4d4d873f758b05c7dd68dab5", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x7c6bb5c4c3fc7ae04ecb9e8dfdc7a1a549938b1663dec3eae486ccdfc9d05f43", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x2332d913312335763ac3098a0fb72d789e1318b063da584253462ab6c30b1351", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x6e82eeccd31de13cf16199671dd5e91ca3b8596e920be8b146d6493a88c6bb29", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0xe4a880ff2ca526ed9b9325808db1aa42996a1e2df64541c28eba9ae069088883", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x3a07ae39293b43f6910a46498668b9114d7611d3ddef1c8d6f99bb9c0411b549", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xed75e5f9ab3c9f9fdcb52ac9e489790095e2cc5a03e83872927db96e57ffe818", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0xc0d3aca720daba088d71be9f88183cae938edef047c5bfdf498b17c5d75953d7", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x62d2175645da243a667798024fc434fa9d12ccb3b03d1f1aee814fc6be569122", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x7dcb32ba5e7bb600eb771f257101f5d98a53232efacf4e1d02c78c481d7a029b", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xa3feede8f1b69038dd7d5c942bb6d211494b5ddc0c5bdfd370a937da02fd315f", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xf768d159e67a14db48c7540608fd0ce6a0d5820b4f2b07465be1d577b80be8f8", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x5367a815bbe23e5d0f6465c233f44921672d6f79f6ea37d2695361a2528684fb", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x2066b1925807f12c83de2fc0243297994a28cd2ca298c710ffd2ccd90446916f", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x98f07a08f6e0392985b7c2541ea2baa5b9cf4a33566edf9e51d2ab7fedb97ee8", - "not dispatched: version() @ 400000000 | keccak256=0xb3d9e971f62fcc67aac97321c2adce9d671ab5a2069e2684de36c3475da7efd9", - "not dispatched: no selector @ 400000000 | keccak256=0x133abd242588d520143eabdedfa24c00e2ee1f392efb12e3af58cfce3a051ff5", - "not dispatched: from a contract @ 400000000 | keccak256=0xe273d69f5c4a40d8e1a2baec6807bc7cbc14f7466aa7da1d628cf84050b4afcb", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x8bb00c81518baaebed8e7d465cac07eabd9bb8fd1f2168bb675181bf6f281803", - "no contract code @ 400000000 | keccak256=0x57a5964833c89bbee89ffcf23e1585a9720f831ba488301937f16d28627c58d7", - "a system call @ 400000000 | keccak256=0x9a9e25f65352a78b4821e39a66d1621bbd6d0fdf1e14955c05be3733619934da", - "out of gas: the overhead @ 161535 | keccak256=0xc83eefbcd1c2bd1b79b3bb8de86da7fa9a024240d70675258b1dd465a0af9d08", - "out of gas: the signer's account @ 162536 | keccak256=0xabd1dd2575c43ad8db140cf5cf3a148138a8c09f632e3dbbe7522fbc8e3c1b72", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x89fd19771ed21bd9962d7a115102f72550e3fa2c983ea297787794afda42709b", - "out of gas: the creation's charges @ 163024 | keccak256=0x19c6965f489129ac0afbece2fee046674d4d433a89910040f2e77fcf2caa7c9d", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0xd7f16815dab34f0f28d789cb6cbccde59e3d655ba31700b55f8d9bf38b1a39a5", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0xafabbf8e69b4ee84877639db23817337ab163d602a795fa6e13f2bc7a95976da", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x031b252c8c04569195a8bea5d8bf730d57440fa07b21674f4ceb3656b0fb6bba", - "rule: init code over the limit @ 150000000 | keccak256=0x9847bb9edead678c560d676d258c01854a0d882b495854a9e7ea7923bdfffb94", - "rule: init code over the limit @ 2000000000 | keccak256=0xf7949b8ae857d9eb689ab1a96b0795d150698f13795c880b330fe388ca949434" + "limit: the default limits @ 400000000 | keccak256=0x20b1891e2840fe9d1c31470c71a0a3379ad4faa594db9f0c8d887f48471994f9", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x05876d4795cec356a548819f04ef3b651d3e3cb7b9ef019ef23fb5e61e0b950b", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xf0e515bb0cdb618c00c0b6e2cd67a18382620a63ff5062a8ef501649a5259c75", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xd6d16b313d9b46b93e03729fe713fc50a3158a89666f9a1382049b212b9a7832", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xfcfc3333e07c50498e7f2b6140d39097e19f69001aefc933375ecdd3506b28ad", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0xb2260f0e69530dc501b8c98fd5efdfad8117ff6f7fc3f7779dbf946f4592ea24", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x63eb9a94bd4451f4fa359b635ff5681d850ce560a332632e9183ddea5cd94c4c", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0xae3d675a98782bcd0b7955af4910d1724f3676dfbc72e6aadf83084a36299f73", + "not dispatched: version() @ 400000000 | keccak256=0xe093a29c20fb9c25655223029041d809334b196da44be073f57bef10b2b0f184", + "not dispatched: no selector @ 400000000 | keccak256=0x24942db7f82e7bd93efeb4496c6f66a26a7922ef4c7bd23724e28ecbce953f8d", + "not dispatched: from a contract @ 400000000 | keccak256=0x303804fa47f6793649d8ef9aba6f6c5b5a5367e64560dfc29608d9aaacf5ca54", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x618482767beb6b6a624bd4769cc2940b4326581c9102d7bda7c5bd6dbd7c8433", + "no contract code @ 400000000 | keccak256=0xb36436cf8d9907027e516d377e4ab3927e65412a6c671edac9beb2eb1a1d66e5", + "a system call @ 400000000 | keccak256=0x5e9e82f017241a41885b08b0035c9660d3b7ed21cad59b45c67d8a0a2e4cc64f", + "out of gas: the overhead @ 161535 | keccak256=0x44cd7c63207d264558c5b459c4cca4d317e05c359d781a0d79e59731a6cbdce3", + "out of gas: the signer's account @ 162536 | keccak256=0xb941698c43a65f9589e8c0dcdbbcaded8805e774074fc7edc7584feab689efb0", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0xb91690051f8a6d154cd94a31fa9aece7b0f8fac923f32703a8b07fe7ac6c6727", + "out of gas: the creation's charges @ 163024 | keccak256=0x7664f24d9c3c20ff82fbf3a42f007e4f5d4a40b5aa2c5df7bcd54f3435d1121c", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x9e614845811556edd11c7bbfbc09c31c037fda50d79aa8e39ef526cc30764423", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0xb2ce3c6da98f81059e48caa292c666803423e24129c31e649c3c9f9f6300dd56", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x37d4e8db925cdc452275d4da169143457516eda9c4514463aa8f41a0258849b6", + "rule: init code over the limit @ 150000000 | keccak256=0xa2ceab04554e5cde508db84cfb47b4c713b09cd174155ba378ca2839656f9d64", + "rule: init code over the limit @ 2000000000 | keccak256=0x2954aa6115c4d77217ba9b1774cd4b59d3d47da28a997977f638034731c0cdf4" ], "summary": { - "bytes": 2451324, + "bytes": 2484049, "cases": 139, "lines": 11482, "runs": 556 diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs index 5a4b4a7af..bddec1773 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -265,6 +265,82 @@ fn test_remaining_compute_gas_clamped_by_detention_limit() { } } +/// Below the execution cap, a read of the block environment, then a fresh slot written and +/// written back at the minimum bucket, then the query: regular gas paid the slot's state gas and +/// its record's history, and the write back gave both back into the reservoir, not into regular +/// gas, so `GAS` after the query reads them as spent. They are not compute, though: the answer is +/// the cap less the regular charges alone, which is what `GAS` measures since the read less those +/// two. The transaction ends with them in its reservoir, which returns to the sender. +#[test] +fn test_a_slot_written_back_after_the_read_is_not_compute() { + let code = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP, GAS]) + .append_many([PUSH0, MSTORE]) + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::ZERO); + let code = returning(query(code, CALL, None, 1), 3); + let outcome = execute(system_db().account_code(CONTRACT, code), tx(CONTRACT, &[], BELOW)); + let words = words(&outcome); + let [at_read, answer, after] = words[..] else { panic!("{words:?}") }; + let given_back = crate::common::slot_state_gas() + + mega_evm::write_record_history_gas(1).expect("a record has a price"); + let gas_since_the_read = (at_read + 2 + 2) - (after + READING); + assert_eq!(answer, CAP - (gas_since_the_read - given_back), "the regular charges alone"); + assert_eq!(outcome.gas.reservoir_remaining, given_back, "the give-back is reservoir"); +} + +/// After a read of the block environment, a child forwarded a fixed 1,000,000 writes a fresh slot +/// and then stops, reverts or halts, and its caller queries. What regular gas paid of the slot's +/// state gas and of its record's history is not compute in any of the three: below the cap, where +/// the child has no reservoir, that is the slot and its record; above it, where the reservoir pays +/// the rest, the slot's legacy share. The revert gives both back into the child's reservoir, never +/// into regular gas, so the caller reads the same gas as after the success; the halt burns the rest +/// of the child's forward, which is no compute either. So all three answers are the cap less the +/// regular charges alone. +#[test] +fn test_a_childs_regular_paid_slot_is_not_compute_whether_it_succeeds_reverts_or_halts() { + const FORWARD: u64 = 1_000_000; + let slot = crate::common::slot_state_gas(); + let record = mega_evm::write_record_history_gas(1).expect("a record has a price"); + for gas_limit in TIERS { + let paid_by_regular = + if gas_limit < TX_GAS_LIMIT_CAP { slot + record } else { slot.min(10_000) }; + let run = |ending: &[u8]| { + let child = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many(ending.to_vec()); + let caller = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP, GAS]) + .append_many([PUSH0, MSTORE]) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT2) + .push_number(FORWARD) + .append_many([CALL, POP]); + let caller = returning(query(caller, CALL, None, 1), 3); + let db = + system_db().account_code(CONTRACT, caller).account_code(CONTRACT2, child.build()); + let words = words(&execute(db, tx(CONTRACT, &[], gas_limit))); + let [at_read, answer, after] = words[..] else { panic!("{words:?}") }; + (at_read, answer, after) + }; + let (at_read, succeeded, after) = run(&[PUSH0, PUSH0, RETURN]); + let gas_since_the_read = (at_read + 2 + 2) - (after + READING); + assert_eq!( + succeeded, + CAP - (gas_since_the_read - paid_by_regular), + "the regular charges alone, at {gas_limit}", + ); + let (_, reverted, after_revert) = run(&[PUSH0, PUSH0, REVERT]); + assert_eq!( + after_revert, after, + "the revert gives nothing back into regular gas, at {gas_limit}" + ); + assert_eq!(reverted, succeeded, "at {gas_limit}"); + let (_, halted, _) = run(&[PUSH0, PUSH0, INVALID]); + assert_eq!(halted, succeeded, "at {gas_limit}"); + } +} + /* ---------- the four boundaries: below and above the cap, with and without a read ---------- */ /// A transaction that is the beneficiary is detained from its start, before its frame: calling From 936c6974c37d8c341f18dec885eced183df0f52d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:24:23 +0800 Subject: [PATCH 080/190] docs(evm): give-backs go into the reservoir and fresh state takes its legacy share --- AGENTS.md | 26 ++-- crates/mega-evm/src/access/detention.rs | 46 ++++--- crates/mega-evm/src/evm/execution.rs | 11 +- crates/mega-evm/src/evm/history.rs | 4 +- crates/mega-evm/src/evm/host.rs | 12 +- docs/spec/glossary.md | 10 +- docs/spec/upgrades/satin.md | 166 +++++++++++++++--------- 7 files changed, 167 insertions(+), 108 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2d256bfef..b3951703e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,6 +118,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It also uses 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. +- Give-backs to the reservoir alone and the legacy share are the fork's, behind a switch that defaults to upstream's EIP-8037 (`CfgEnv::reservoir_only_give_backs`, carried onto every frame's `GasTracker`): Satin's spec configuration turns it on and the neutral configuration off. + With it on, a refill, a take-back and a failed frame's rollback credit the reservoir alone, a returned reservoir replaces the caller's without unwinding its spill, and the tracker's spill counter (`state_gas_spilled`) is what regular gas paid of state and history gas, which no give-back lowers, merged into the caller on a child's success or revert; a halt takes it out of the reservoir the rollback credited (`consume_regular_paid_charges`), so the halting frame's reservoir is the one it received, and the first frame's halt returns the charge made before it only for the part the reservoir paid (`settle_first_frame`). + The fork reads the legacy shares from four schedule entries at the four opcode sites (`GasId::sstore_set_state_gas_legacy_share` and its three siblings, zero upstream) and draws them from regular gas before the reservoir (`GasTracker::record_state_cost_with_legacy_share`), the call's and the creation's before the forward is computed; both need the fork because the refills, the rollback and the settlement of a returned reservoir run inside revm's instructions and frame return. + The engine records the part of the first frame's start record regular gas paid (`AdditionalLimit::first_frame_charge_from_regular`) and consumes it on that frame's halt, and the keyless steps take their shares through the same tracker call. - 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 code's bytes are drawn from the creation's budget on its start's entry of the engine's start ledger, and the creating frame's tracker the fork lends the admission is not read. @@ -162,7 +166,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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 three 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 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`). +- 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`); 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`); and the four legacy-share entries the fork reads at the opcode sites (`legacy_shares`), the part of a fresh slot's, a value call's new account's, a `SELFDESTRUCT` beneficiary's and a creation's state gas that regular gas pays before the reservoir: the pre-Satin price (`PRE_FORK_SSTORE_SET_COST` 20,000, `PRE_FORK_NEW_ACCOUNT_COST` 25,000, `PRE_FORK_CREATE_COST` 32,000) less the site's regular entry, 10,000, 25,000, 16,000 and 20,000, never scaled by SALT and capped at the charge itself. + A keyless deployment's steps for the signer's account and the created account take the same shares as a value call and a creation (`keyless/dispatch.rs`); no charge made before the first frame, no deposited code, no delegation indicator and no history charge takes one. The rest of what a start takes is the engine's, in no entry of the schedule: a child starts with 98/100 of its caller's reservoir and of each of its three budgets (`FRAME_KEPT_PERCENT`, the part the caller keeps), and a value call's child with a history allowance of `HISTORY_ALLOWANCE_BYTES` at the cost per history byte, decided where the start is made (`MegaContext::forward_start`). 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`. @@ -172,7 +177,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `SLOTNUM` pushes zero whatever `BlockEnv::slot_num` holds; the read is still a volatile one, marked for detention and refused where volatile access is off. - 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 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. + Satin's one divergence from op-revm on an ordinary transaction's spend 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. + Beside the spend, Satin parts from op-revm's EIP-8037 tracker in how its two pools split it — a give-back goes into a reservoir, never into regular gas, and a fresh slot, a new account or a created account an opcode adds takes its legacy share from regular gas first — which the baseline compares with the fork's switch on and the shares in op-revm's schedule, and pins against the switch off on its own (`test_a_slot_written_back_departs_from_eip_8037_by_crediting_the_reservoir`). 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. @@ -238,7 +244,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. + The refills go into the destroying frame's reservoir alone, as every give-back does; 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. @@ -313,7 +319,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. The dispatch is by address, selector and arguments that decode as `(bytes, uint256)` (a call whose arguments do not decode is not dispatched, is charged nothing and runs the bytecode), whatever the address holds: where the state holds no contract code, the frame is built on the contract's own, which never runs. A stop of the call itself — its own charges past detention's limit, or a limit the creator's nonce record crosses on it — reverts it with the stop and takes the deployment back, the signer's nonce included; otherwise the call succeeds with the deployed address or the error the creation failed with, a limit's stop the creation crossed included. - `ORIGIN` and `GASPRICE` in the init code are the transaction's, and `gasUsed` is what the creation spent from either pool, the same below and above the execution cap. + `ORIGIN` and `GASPRICE` in the init code are the transaction's, and `gasUsed` is what the creation spent from both pools netted together, the same below and above the execution cap: `(forward − regular returned) + (reservoir share − reservoir returned)`, never clipped per pool, plus the destruction table's give-back of the call's own charge for the created account when the creation destroyed it (`creation_gas_used` in `keyless/settle.rs`), so a constructor that writes a fresh slot from regular gas and reverts reports its regular charges, and one that destroys itself is not credited the account it did not pay for. Rule 4 (signer nonce at most 1) counts real nonces: the creation's bump stands from 0 to 1, which is the replay barrier. From nonce 1 the settlement sets the nonce back, whether the deployment succeeded or failed, only when the creation's bump is the last nonce change the deployment made, so the signer stays at 1, as in the legacy engine: no number of failing calls — the call is permissionless and the signed transaction public — gets the signer's deployment refused, and a resubmission of one that deployed is refused `ContractAlreadyExists()`. The bump's write record and its history go back with it, unless the creation succeeded and moved value out of the signer, whose account then keeps a write of its own. @@ -372,7 +378,7 @@ Detention caps how much a transaction may still compute once it read such data ( The Oracle's read is the exception: its wrapper commits it once the slot is read, before the `SLOAD` charges anything, at the compute before the opcode, and the mark stands through the out-of-gas or the stop that follows. 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. + 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 its regular gas paid — a legacy share or a spill, which no give-back lowers, so a charge given back into a reservoir by a take-back or a rollback stays out of compute; 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 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. @@ -410,7 +416,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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`); 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 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 what its regular gas paid of state and history gas, which the revert gives back into its reservoir — 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.** @@ -447,11 +453,11 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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. + After an `SSTORE` it holds the frame to the compute limit again (`Detention::hold`, the one formula over the frame's `GasTracker`): under EIP-8037's own give-backs, which the neutral configuration keeps, a restore refills the state gas, revm before the hook, and the history gas, the hook, that spilled onto regular gas; under Satin's both go into the reservoir and the hold finds nothing grown. - **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 parks the part the frame's own records cost as the start's charge on the start ledger, which revm's split of the start takes and the start's settlement gives back to the caller when the frame fails; the history of a creator's nonce record is charged there and not part of the start's charge, 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. - The hook then takes the frame's share of the caller's reservoir out of the caller and names it on the start (`MegaContext::forward_start`, `FrameStart::reservoir`), which revm puts 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` (`FRAME_KEPT_PERCENT` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs; the child's return puts what it left in place of the caller's reservoir, unwinding the caller's outstanding spill first (revm's `absorb_returned_reservoir`), and the engine adds the part the caller kept back on top (`Host::frame_settle`, from `FrameSettle::held_reservoir`); it parks the frame's shares of the caller's budgets, taken out of the caller's entry, beside the charge, and, for a value-transferring `CALL` or `CALLCODE`, the frame's history allowance. + The hook then takes the frame's share of the caller's reservoir out of the caller and names it on the start (`MegaContext::forward_start`, `FrameStart::reservoir`), which revm puts 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` (`FRAME_KEPT_PERCENT` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs; the child's return puts what it left in place of the caller's reservoir, unwinding nothing under Satin's give-backs (revm's `absorb_returned_reservoir`, which unwinds the caller's outstanding spill first under EIP-8037's own, the neutral configuration's), and the engine adds the part the caller kept back on top (`Host::frame_settle`, from `FrameSettle::held_reservoir`); it parks the frame's shares of the caller's budgets, taken out of the caller's entry, beside the charge, and, for a value-transferring `CALL` or `CALLCODE`, the frame's history allowance. A keyless deployment's creation takes the same shares of what the call has left after the call's start charges (`keyless::start`, through `forward_start`). The transaction's own frame and a system call's outermost frame take the whole reservoir, of which the transaction's gas keeps a copy that the frame's return replaces, so nothing is added back there; the neutral configuration 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. @@ -513,7 +519,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer `tests/satin/reuse_after_error.rs` runs a failing call through every public entry point, plain and inspected, at a nested read, a recorded error post-execution preempts, and a post-execution read. - **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'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. + 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 of regular gas — a child's return, and under EIP-8037's own give-backs `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 inherited reservoir.** A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so revm's own frame return settles it exactly like a result of its own; it settles on its start's entry of the start ledger by status, budgets and start charge alike, so it carries neither. - **Inspectors in block execution.** @@ -549,7 +555,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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. + `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, after the legacy share, reservoir first; state or history gas that regular gas paid, a legacy share or a spill, stays on its own ledger. The regular ledger is `total − state − history`, read off the result revm's `Gas` settled into; nothing counts compute beside it, so gas an inspector edits moves it with the receipt. The figure a block counts is `max(regular, floor)`, history taken out before the floor applies: the fork's `block_regular_gas_used` keeps history in, and subtracting it afterwards can land below the floor. The three add up to the raw spend, which is why what a history allowance paid for is on none of them: no pool of the transaction's gas paid it. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 923925cea..2f7e69594 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -116,7 +116,10 @@ impl FrameFigures { /// /// 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 +/// state and history gas its regular gas paid, which are not compute. Under Satin's give-backs, +/// which credit the reservoir alone, that figure is never lowered by a give-back: what regular gas +/// paid stays spent, and stays out of compute, when the charge later comes back into a reservoir +/// by a take-back or a rollback. 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. /// @@ -148,7 +151,8 @@ impl FrameFigures { /// then refuses the call or its creation runs. /// /// 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 +/// frame that halts consumes the gas it had left, and what its regular gas paid of state and +/// history gas, without running anything with /// 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, @@ -376,8 +380,10 @@ impl Detention { /// read set one. /// /// Called where the frame's spendable gas can have grown past it: when the frame starts, when - /// 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. + /// it resumes on the gas a child handed back, and after a storage write. Under EIP-8037's own + /// give-backs a restore of a slot to its original value refills the state and history gas + /// that spilled onto regular gas; under Satin's it refills the reservoir alone, and the hold + /// there finds nothing grown. #[inline] pub(crate) fn hold(&self, gas: &mut GasTracker) { if let Some(limit) = self.limit { @@ -464,7 +470,10 @@ impl Detention { return Some(ComputeStop { limit, used: self.compute(gas.tracker()) }); } } - // The settlement rolls the spill back into regular gas and burns it all. + // The halt burns what the frame had left and what its regular gas paid of state and + // history gas: the settlement consumes both, under EIP-8037's own give-backs by rolling + // the spill back into regular gas and burning it all, under Satin's by taking it out of the + // reservoir the rollback credited. 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 @@ -488,8 +497,8 @@ impl Detention { /// the allowance it was held to ([`restore_forward`](Self::restore_forward)) — crossed the /// limit. Otherwise, an answer that halts burns the whole gas limit: nothing ran with it. An /// answer that spent more regular gas than the limit leaves the frame — the allowance it would - /// have run on — is a charge the frame could not have made; state and history gas that spilled - /// onto its regular gas are not counted, as they are not a running frame's compute. Such an + /// have run on — is a charge the frame could not have made; state and history gas its regular + /// gas paid are not counted, as they are not a running frame's compute. Such an /// answer is answered out of gas and marked as a crossing, the answer's spending being the /// charge that crossed. A crossing is settled by the same rule as a frame that ran /// ([`stop`](Self::stop)): the frame spent nothing before the charge, so it is given its whole @@ -532,7 +541,7 @@ impl Detention { return None; } let allowance = self.allowance(depth, gas_limit)?; - // The regular gas the answer spent: state and history gas that spilled onto it are not + // The regular gas the answer spent: state and history gas its regular gas paid are not // compute, as they are not a running frame's. let spent = gas_limit .saturating_sub(result.gas.remaining()) @@ -547,9 +556,10 @@ impl Detention { // 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 - // the stop credits back. The spill is below the gas limit, less the regular gas the - // answer spent, so what is left is never zero. + // less the state and history gas its regular gas paid, which the revert that settles + // the stop gives back into the frame's reservoir under Satin's give-backs, and into + // its regular gas under EIP-8037's own. That part is below the gas limit, less the + // regular gas the answer spent, so what is left is never zero. let remaining = NonZeroU64::new(gas_limit - result.gas.state_gas_spilled())?; result.result = InstructionResult::OutOfGas; result.gas.tracker_mut().set_limit(gas_limit); @@ -557,9 +567,10 @@ impl Detention { } let limit = self.stop(&mut result.gas)?; // Every crossing an answer carries was marked by the engine with the regular gas the frame - // 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. + // had before the charge: the forward less what its regular gas paid of state and history + // gas here, the forward for a precompile's, which pays none. 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.tracker()), 0, "a stopped answer spent nothing"); Some(ComputeStop { limit, used: self.compute_at_start(depth, gas_limit) }) } @@ -729,7 +740,7 @@ const fn is_out_of_gas(result: InstructionResult) -> bool { } /// 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. +/// less the state and history gas its regular gas paid. #[inline] pub(crate) const fn regular_spent(gas: &GasTracker) -> u64 { gas.limit().saturating_sub(gas.remaining()).saturating_sub(gas.state_gas_spilled()) @@ -1066,7 +1077,7 @@ mod tests { /// An answer that halts burns the gas limit; one that spent more regular gas than the frame's /// allowance is answered out of gas and stops at the limit, with its whole gas limit back but - /// the spill. State gas that spilled onto the answer's regular gas is not compute. + /// what its regular gas paid of state gas, which is not compute. #[test] fn test_an_answer_is_held_to_the_allowance_it_would_have_run_on() { let mut detention = detaining(); @@ -1097,7 +1108,8 @@ mod tests { detention.burned = 0; // The answer's spending is the charge that crossed: before it the frame had its whole gas - // limit, less the spill, which the revert that settles the stop credits back. + // limit, less what its regular gas paid of state gas, which the revert that settles the + // stop gives back. let limit = BLOCK_ENV_ACCESS_COMPUTE_GAS; for spill in [0, 1_000] { let mut beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1, InstructionResult::Return); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 079147462..c9af1b0b6 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -279,11 +279,12 @@ where /// /// 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 + /// execution cap away from computation; and, as intrinsic gas, it is charged as no spill, so + /// no reservoir a frame hands back unwinds it onto the regular budget under EIP-8037's own + /// give-backs, and under Satin's no returned reservoir unwinds anything. 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 diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs index d02b7f7d4..28463b913 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -3,8 +3,8 @@ //! History gas is the third ledger of a Satin transaction. It pays for the bytes the transaction //! appends to the chain's history — its own body, its logs, the code it deploys and one record per //! account or storage write it keeps — as opposed to the bytes it adds to the world state, which -//! EIP-8037 state gas pays for. Both draw on the same reservoir-first budget and unwind on the same -//! paths; they are counted apart so a node can report and limit them separately. +//! EIP-8037 state gas pays for. Both draw on the same reservoir-first budget and are given back on +//! the same paths; they are counted apart so a node can report and limit them separately. //! //! Every charge is a byte count from the byte table (the `limit` module) times the cost per history //! byte, and the byte counts are the ones the data-size limit meters, so a log costs history for diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 10d5fb085..e93141aed 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -338,9 +338,10 @@ impl revm::context_interface::Host /// 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. + /// A completed `SSTORE` holds the frame to the compute limit again: under EIP-8037's own + /// give-backs 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; under Satin's both go into the reservoir, and the hold finds nothing grown. #[inline] fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { let (from_allowance, holds_again) = match write { @@ -496,8 +497,9 @@ impl revm::context_interface::Host /// to the reservoir, of which only the part the reservoir paid comes back: what regular gas /// paid of it is consumed with the frame's regular gas. revm's settlement leaves regular gas /// there only where an inspector makes the frame hand back more reservoir than it inherited - /// — on its input, or in its result's figures — which unwinds part of the spill the charges - /// made before the frame. A child's caller runs on, and keeps its regular gas. + /// — on its input, or in its result's figures — which, under EIP-8037's own give-backs, + /// unwinds part of the spill the charges made before the frame. A child's caller runs on, and + /// keeps its regular gas. #[inline] fn frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker) { self.inner.frame_settle(settle, gas); diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index 836fd79fd..bbedcc801 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -93,7 +93,8 @@ Gas limit above the cap goes to the [reservoir](#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. +_(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, after the legacy share a fresh slot, a new account or a created account takes from regular gas first. +Every give-back of state gas or history gas goes into a reservoir, never into regular gas. The transaction's own frame, and a system call's outermost frame, receive the whole reservoir. @@ -101,11 +102,10 @@ A child frame of `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or ` 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. +What the child does not spend returns to the caller, and a reverted child's charges roll back into the reservoir it returns. +On every such return, whether the start was answered without building a frame or a built frame returns, the reservoir the child returns joins the reservoir the caller kept, and none of it is credited to the caller's regular gas. 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. +The caller's own charge for a leaf the child did not add is given back into the caller's reservoir after that. ## Write record diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 1f98384e0..3d094a65d 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -149,21 +149,20 @@ 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 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. +Satin adopts, of the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef) (4 September 2026) and the failure outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) (14 September 2026), what its give-back rule leaves of them (see [History Gas](#7-history-gas)), 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, a refused start) or a built frame returns, the reservoir the child returns MUST join the reservoir the caller kept, and the caller's regular gas MUST rise by the regular gas the child returns and by nothing else. +The returned reservoir MUST NOT be credited to the caller's regular gas, and the reservoir the caller kept MUST NOT be drawn. +A caller with 100 of reservoir after the start's charges keeps 2 and gives the child 98; a child that returns all 98 leaves the caller 100, whatever regular gas the caller paid for state before. +State charges and history charges are given back by the same rule (see [History Gas](#7-history-gas)). 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 charge made before the first frame — the caller a deposit creates, an authorization's charges, the history of the records made outside a frame, the state gas of the first frame's recipient or created account — MUST draw the reservoir first and the regular budget for the rest, and the first frame receives the reservoir it left. +The part the regular budget pays stays spent: no reservoir a frame returns credits it back to regular gas. +A failure of the first frame returns no reservoir an authority charge had already drawn, so that charge stays (see [The Revert-Class Stop](#11-the-revert-class-stop)). +The first frame's own start record and its recipient's or created account's state gas come back into the transaction's reservoir when that frame reverts or is stopped, and, when it halts, only for the part the reservoir paid: the part regular gas paid is consumed with the frame's regular gas. +Of the history charged before the first frame the reservoir pays the authorities' records first, so the part of the start record it paid is what they leave it. +That is the failure outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5), and not its commit of the pre-execution spill as a rule of its own: under the give-back rule the part of any charge regular gas paid stays spent, a charge made before the first frame included. 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. @@ -183,7 +182,9 @@ The removal of an unused counter ([commit `052029f362`](https://github.com/ether - **Three kinds of charge.** A regular charge (every inherited opcode and intrinsic cost) MUST draw only the regular budget. - 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. + 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 pools of the frame that makes it in this order: first the charge's legacy share, which only the state charges of [the legacy share](#the-legacy-share) have, from the frame's regular gas; then the reservoir, until it is zero; then the rest, the spill, from the regular budget. + A frame whose regular gas cannot pay the legacy share or the spill MUST run out of gas, whatever its reservoir holds. + The part of a state or history charge that regular gas pays is spent, and no give-back credits it to regular gas again. `GAS` MUST return the regular budget the frame has left, not the reservoir. - **Frames.** A call or creation MUST forward regular gas as [Gas Forwarding](#9-gas-forwarding) specifies. @@ -192,12 +193,14 @@ The removal of an unused counter ([commit `052029f362`](https://github.com/ether `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. + When a frame reverts or is stopped by a limit, its reservoir MUST become `reservoir + net_charged`. + `reservoir` is the frame's reservoir when it fails: what it kept of the reservoir it received and of what its successful children returned, every give-back it holds, and the reservoir its failed children returned after their own rollback. + `net_charged` is the state and history gas charged since the frame started, by the frame and by the children that succeeded and merged into it, legacy shares included, less every give-back they received; a failed child's charges are not part of it, that child's rollback having already returned them. + Every state and history charge the revert undoes therefore ends in the frame's reservoir, whichever pool paid it, and the frame's unspent regular gas, which none of it reaches, returns to its caller. + When a frame halts exceptionally, its reservoir MUST become the reservoir it received when it started, and its regular gas, with the part of its charges regular gas paid, is consumed; reservoir its failed children returned to it is consumed with it. + A failed frame's charges therefore never return to regular gas. + A failed child returns the share it was given, after its rollback, 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, and that reservoir joins the reservoir the caller kept. + The caller's own charge for a leaf the child did not add, its legacy share included, is given back into the caller's reservoir 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. @@ -209,7 +212,7 @@ The removal of an unused counter ([commit `052029f362`](https://github.com/ether - _state gas_ — the state charges it kept; - _history gas_ — the history charges it kept, the body included. - State or history gas that spilled onto the regular budget stays on its own ledger. + State or history gas that regular gas paid, a legacy share or a spill, stays on its own ledger. The [EIP-7623](https://eips.ethereum.org/EIPS/eip-7623) floor, as [EIP-7976](https://eips.ethereum.org/EIPS/eip-7976) and [EIP-7981](https://eips.ethereum.org/EIPS/eip-7981) amend it, MUST be computed and validated as Amsterdam computes it; the figure a block counts on its execution ledger is `max(regular, floor)`, with history gas taken out of the regular ledger before the floor applies. - **Validation.** @@ -235,19 +238,23 @@ Its freeze point is [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commi - **Base.** EIP-8037 as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) (4 September 2026), with the parameters this section and [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing) set: the execution cap, and MegaETH's cost per state byte scaled by the bucket multiplier. - **Later commits taken.** - The child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef), as the reference implementation performs it. + Of the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef), what the give-back rule leaves of it: a returned reservoir joins the reservoir its caller kept and never draws it. The failure outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5): a failure of the first frame does not give back the reservoir that an authority charge made before the frame had drawn. The collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898): a creation does not collide on storage. - **Later commits declined.** The transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950). - The commit of the pre-execution spill in [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5), which would keep a later return from unwinding it. + The commit of the pre-execution spill in [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) as a rule of its own: under the give-back rule the part of any charge regular gas paid stays spent. - **Later commits not tracked.** The removal of an unused counter ([commit `052029f362`](https://github.com/ethereum/EIPs/commit/052029f3625328d6f51dec8e62a7090201e66f17)), which changes no rule a transaction executes. - **Satin's own departures from the EIP.** - The reservoir share: a child frame receives `reservoir_share = remaining − remaining × 2 / 100` of the reservoir its caller has left, and the caller keeps the rest, where EIP-8037 passes the whole reservoir (see [Gas Forwarding](#9-gas-forwarding)). - The reservoir a child returns joins what the caller kept, after it unwinds the caller's outstanding spill (the child-merge rule above). - - History gas: a history charge draws the reservoir first and shares the spill with state charges, is given back with them when its frame fails, and is booked on a ledger of its own; the history gas of the transaction's body is the intrinsic state gas (see [History Gas](#7-history-gas)). + The reservoir a child returns joins what the caller kept (the child-merge rule above). + - History gas: a history charge draws the reservoir first and spills onto regular gas as a state charge does, is given back with the state charges when its frame fails, and is booked on a ledger of its own; the history gas of the transaction's body is the intrinsic state gas (see [History Gas](#7-history-gas)). - The destruction-table refill: the first effective `SELFDESTRUCT` of an account created in the same transaction refills the state gas of each part of it that was absent at the transaction's start, where EIP-8037 specifies that this destruction produces no state-gas refills (see [The destruction table](#the-destruction-table)). + - The give-back rule: every give-back of state or history gas — a refill, a take-back, a rollback — goes into a reservoir and never into regular gas, and a returned reservoir joins the caller's without unwinding anything, where EIP-8037 at that commit credits a refill to regular gas first, up to the state gas the frame's regular gas paid, unwinds that spill when a child returns reservoir, and returns it to regular gas when the frame reverts (see [History Gas](#7-history-gas)). + - The legacy share: a state charge for a fresh slot, a new account or a created account that an opcode or a keyless deployment makes takes a fixed pre-Satin part from regular gas before the reservoir (see [the legacy share](#the-legacy-share)). + + The last two follow the rule [ethereum/EIPs#12581](https://github.com/ethereum/EIPs/pull/12581) proposes for EIP-8037, which is not merged; they are stated here in Satin's own words, and the pull request is their provenance, not a rule of this specification. A change to EIP-8037 after [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) is an input to a later spec, not to Satin. The co-author lines and the move to Last Call came after it and change no rule a transaction executes. @@ -364,7 +371,7 @@ Every EIP-8037 state charge MUST be `entry × m`: - 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)). - 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). + 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, its legacy share included, and go into the frame's reservoir (see [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. @@ -374,6 +381,32 @@ Every EIP-8037 state charge MUST be `entry × m`: At `m = 1` every state charge is the schedule's own number, so, unlike Rex6, a fresh slot or account in a minimum-size bucket is not free: it pays its state gas. +##### The legacy share + +A state charge an opcode or a keyless deployment makes for a fresh slot, a new account or a created account MUST take its legacy share from the frame's regular gas before the reservoir pays any of it, and pay the rest as every state charge is paid (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)): + +`legacy_share = min(state_charge, max(0, PRE_FORK_COST − execution_charge))` + +- `state_charge` — the charge, `entry × m`. +- `PRE_FORK_COST` and `execution_charge` — by the component that creates the state: + +| State charge | `PRE_FORK_COST` | `execution_charge` | Legacy share at `m = 1` | +| ----------------------------------------------------------------------------- | ------------------------------------ | --------------------------------------------------- | ----------------------- | +| Fresh storage slot, by `SSTORE` | `PRE_FORK_SSTORE_SET_COST` = 20,000 | the fresh slot's write, 10,000 | 10,000 | +| New account, by a value `CALL`, or a keyless deployment's signer | `PRE_FORK_NEW_ACCOUNT_COST` = 25,000 | 0 | 25,000 | +| New account, by a `SELFDESTRUCT`'s beneficiary | `PRE_FORK_NEW_ACCOUNT_COST` = 25,000 | the schedule's new account of `SELFDESTRUCT`, 9,000 | 16,000 | +| Created account, by `CREATE` or `CREATE2`, or a keyless deployment's creation | `PRE_FORK_CREATE_COST` = 32,000 | the creation's access, 12,000 | 20,000 | + +- `PRE_FORK_COST` is a fixed pre-Satin price: it MUST NOT be scaled by the bucket multiplier and does not move when the schedule's prices do. +- Every other state charge MUST have a legacy share of zero: deployed code, a delegation indicator, and every charge made before the first frame — the caller a deposit creates, an authorization's, the transaction's recipient or created account. + A history charge has none. +- The legacy share is state gas: it is counted on the state ledger and given back with the rest of its charge, into a reservoir (see [History Gas](#7-history-gas)). + A frame whose regular gas cannot pay it runs out of gas, whatever its reservoir holds. +- A value `CALL` and a creation opcode take the share before they compute their forward, so it shrinks the forward as a spill does. + +So each of these operations draws from regular gas what it drew before Satin when it creates state, whatever the reservoir holds: a fresh slot's `SSTORE` 22,100 with the cold access, a `SELFDESTRUCT` to a new beneficiary 30,000, a `CREATE` or `CREATE2` 32,000. +Without the share, a sender who adds a reservoir could write a slot from a failure handler with 12,100 of regular gas. + ### 7. History Gas #### Previous behavior @@ -422,7 +455,7 @@ When each charge is made: - 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. 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. + 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, its legacy share from regular gas and the rest reservoir first (see [the legacy share](#the-legacy-share)), then the 98/100 forward of the regular gas left (see [Gas Forwarding](#9-gas-forwarding)), then the history of the start's records; the legacy share and a state charge that spills onto the regular budget so shrink 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. @@ -430,10 +463,9 @@ When each charge is made: - 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. -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)). +Every give-back of state gas or of history gas — a refill, a take-back, a rollback — MUST go into a reservoir, at the price it was charged, its legacy share included, and MUST NOT be credited to regular gas, whichever pool paid the charge. +A give-back inside a frame goes into the reservoir of the frame that makes it, and the rollback of a failed frame into that frame's (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +A frame can pay later state and history charges with gas given back so, but it cannot compute with it; what it does not spend returns up the chain with its reservoir when it succeeds. 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. @@ -498,11 +530,10 @@ Where it binds, the gas used is the floor, drawn from the whole gas limit, the r 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. + A frame that reverts or is stopped gives its state and history charges back into its reservoir, and one that halts returns the reservoir it received, as [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model) 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, and a reverted child returns with it what it charged and the rollback gave back. + That reservoir joins the reservoir the caller kept, and none of it is credited to the caller's regular gas. + The caller's own charge for a leaf the child did not add, its legacy share included, is given back into the caller's reservoir 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. @@ -683,17 +714,17 @@ A part that existed at the start is an ordinary deletion. | 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. +A refill MUST be the price that part was charged, the schedule entry times the bucket multiplier of that charge, its legacy share included, and it MUST go into the destroying frame's reservoir, 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. +The write record taken back returns its data size to the destroying frame's budget and its history gas into that frame's reservoir, 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). +The give-back MUST go into the destroying frame's reservoir, by the give-back rule 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. @@ -952,11 +983,11 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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 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 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 its regular gas paid — a legacy share or a part the reservoir could not pay —, also when that charge is later given back into a reservoir by a take-back or a rollback, 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. + 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 its regular gas had to pay. 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. @@ -964,12 +995,12 @@ A contract can revert with the same bytes, and so can a caller that re-raises th Both are below 199,987,900, the most compute a transaction can spend, so that they can stop one: the execution cap less EIP-2780's base cost of 12,000, which every transaction pays, and the 100 of a warm account access, the least a frame pays for the code it runs. - **Withheld gas.** 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). + The split MUST be applied when the read's opcode completes and when a frame starts or resumes: a give-back never raises a frame's regular gas, so those are the points at which it can grow. 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 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. + A forward, and the part of a state or history charge that regular gas pays — its legacy share, and what the reservoir cannot pay — 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)). @@ -988,7 +1019,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check — a ModExp input over EIP-7823's bound among them — is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. - **Interceptor answers.** - A system contract's intercepted answer that spent more regular gas than the frame's allowance, state and history gas that spilled onto its regular gas not counted, MUST be the crossing. + A system contract's intercepted answer that spent more regular gas than the frame's allowance, state and history gas its regular gas paid not counted, MUST be the crossing. The answer's whole regular spend MUST be treated as the one charge that crossed: none of it is billed, the part within the allowance included, so the stop's compute is the transaction's compute when the frame started. - **Refused reads.** See [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas). @@ -1045,6 +1076,7 @@ The reference implementation has no price for one, so it runs such a precompile - `remainingComputeGas()` MUST answer the lesser of two figures, read when the call reaches the interceptor: the calling frame's own regular gas with the gas the call forwarded counted back, and, once a read of volatile data set a limit, what the limit leaves the transaction. It is regular gas only: the reservoir is not in it, so a transaction above the execution cap hears at most the cap's share. + What the limit leaves counts as spent no state or history gas the transaction's regular gas paid, also when that charge was given back into a reservoir since: a transaction below the execution cap that reads `TIMESTAMP`, writes a zero slot to 1 and back to 0 at `m = 1`, and then calls it hears the cap less its regular charges alone, the 101,440 its regular gas paid and its reservoir now holds not counted. A transaction that calls the contract directly hears its own frame's regular gas, or less when it is detained from its start (its sender is the block beneficiary, or an EIP-7702 authority it applies is). ### 14. EIP-7708 Transfer Logs @@ -1089,23 +1121,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 carried transaction decodes (the arguments decoded when the call was recognized): 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)` | +| 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 carried transaction decodes (the arguments decoded when the call was recognized): 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`), its legacy share of 25,000 from regular gas first | 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, its legacy share of 20,000 from regular gas first, 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. @@ -1133,8 +1165,12 @@ An out-of-gas step halts the call, consuming its regular gas. 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, 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. + `gasUsed` MUST be what the creation spent from both pools taken together, with no intrinsic gas and before the EIP-3529 refund: the regular gas and the reservoir the creation was given, less the regular gas and the reservoir it returned — its regular charges plus the state and history gas it kept, net of every give-back within the creation of a charge the creation made — 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. + A give-back the creation receives for a charge it did not make MUST NOT lower `gasUsed`: the one such give-back is the destruction table's for the account being created, when a destruction of it stands when the creation ends, which returns step 14's state gas of the created account and history gas of its write record within the creation, and it MUST be added back. + So `gasUsed` is `(regular given − regular returned) + (reservoir given − reservoir returned) + the give-backs of step 14's charges the creation received`, the two pools netted together and not each clipped at zero. + A constructor that writes a fresh slot at `m = 1` from regular gas alone and reverts returns that state as reservoir, and reports 12,109 for its regular charges, not 113,549. + A constructor `ORIGIN; SELFDESTRUCT` at `m = 1`, given 500,000 of regular gas and no reservoir, with a zero balance, returns 494,998 of regular gas and 187,120 of reservoir, step 14's charges given back by the destruction, and reports `EmptyCodeDeployed(5002)`, not −182,118. + It is never less than the creation's regular charges, the regular gas it spent on anything but state and history. - **Limits.** 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. @@ -1238,8 +1274,8 @@ An out-of-gas step halts the call, consuming its regular gas. 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 `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. + A fresh slot's legacy share comes out of the regular gas, and state gas the reservoir cannot pay spills onto it (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 but the slots' legacy shares; 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: @@ -1484,6 +1520,8 @@ Calldata, logs and deployed code cost 88 gas per byte of history; a fresh slot o Gas limits above 200,000,000 behave differently: at most 200,000,000, less the intrinsic regular gas, is available to computation and `GAS`, and the rest can pay only state and history gas. A contract that checks `gasleft()` against a large constant sees at most the regular budget. +A fresh slot, a new account or a created account an opcode adds takes its pre-Satin part of the state gas from regular gas first (the [legacy share](#the-legacy-share)), so a fresh `SSTORE` draws 22,100 of regular gas with its cold access, and a `CREATE` 32,000, whatever the reservoir holds. +Gas given back — a slot written back to its original value, a reverted frame's state and history charges — goes into the reservoir and never into regular gas: a frame can pay later state and history charges with it, but cannot compute with it. 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. From d79e961518580536ed0c1e09a22a4bf8eb43a920 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:28:13 +0800 Subject: [PATCH 081/190] test(evm): merge the transfer-log share arms clippy flags --- crates/mega-evm/tests/satin/transfer_logs.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 31f3d5765..e3815ec72 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -186,9 +186,12 @@ impl Site { /// with no share. fn shares(self, variant: Variant) -> u64 { match (self, variant) { - (Self::TxEndowment, _) | (Self::TxValue, Variant::Plain | Variant::TakenBack) => 0, + (Self::TxEndowment, _) | + ( + Self::TxValue | Self::Call | Self::SelfDestruct, + Variant::Plain | Variant::TakenBack, + ) => 0, (Self::TxValue, Variant::Twin) => slot_share(), - (Self::Call | Self::SelfDestruct, Variant::Plain | Variant::TakenBack) => 0, ( Self::Call | Self::CallWithoutCode | Self::CallToPrecompile | Self::SelfDestruct, Variant::Twin, From af123900866c7e2fca35b62644e3aa917050cb58 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:47:25 +0800 Subject: [PATCH 082/190] docs: point the bootstrap keys at the node integrators section --- docs/spec/upgrades/satin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 05c5976e3..1221a74ad 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1267,7 +1267,7 @@ An out-of-gas step halts the call, consuming its regular gas. - an address with no account, or an account without code, receives version 2.0.0 as a new contract, an existing account's nonce and balance kept and its storage cleared, seeded with: slots 0 and 4 (the current and initial system address) `0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d`, slots 1 and 5 (the current and initial sequencer) the configured initial sequencer, slot 2 (the admin) the configured initial admin, slot 6 (`_initialFromBlock`) the block's number, and slot 13 the configured minimum rotation delay; - any other code MUST make the block invalid: the registry's storage is never overwritten by code it was not migrated to. - The configured values are the chain configuration's bootstrap keys, the ones the Rex era introduced (see the chain configuration under [Implementation Notes](#implementation-notes)); once the registry holds its roles, its storage, not the configuration, decides them. + The configured values are the chain configuration's bootstrap keys, the ones the Rex era introduced (see the chain configuration under [Node integrators](#node-integrators)); once the registry holds its roles, its storage, not the configuration, decides them. The reference implementation reports a registry it cannot migrate, and one the resolution of the live system address refuses, as `MegaBlockExecutionError::SequencerRegistry`, a verdict on the block; its schedule validation (`MegaHardforks::validate_schedule`) refuses a schedule that activates Satin without the bootstrap values or with one of them zero when it is loaded, as the genesis parser refuses such a configuration, and a block that must seed or migrate the registry on a schedule that skipped that validation fails with `MegaBlockExecutionError::UnusableRegistryBootstrap`, an internal error of the node. - **The factory check.** From 2e86daff0acfd630aa7bfa92b90bde390cc18626 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 13:57:18 +0800 Subject: [PATCH 083/190] test(evm): hold the give-back and legacy-share tests at any byte price --- crates/mega-evm/tests/satin/equivalence.rs | 10 ++++---- crates/mega-evm/tests/satin/legacy_share.rs | 13 +++++++---- crates/mega-evm/tests/satin/system_call.rs | 7 ++++-- crates/mega-evm/tests/satin/withheld_gas.rs | 18 +++++++++------ .../mega-evm/tests/system/keyless/deploy.rs | 23 ++++++++++--------- 5 files changed, 40 insertions(+), 31 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 3302114ac..9c68a4d50 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -354,12 +354,10 @@ fn test_a_slot_written_back_departs_from_eip_8037_by_crediting_the_reservoir() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, code); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CALLEE), - gas_limit: 1_000_000, - ..Default::default() - }; + // Regular room on top of the body's history and the slot and its record at the prices in + // effect, below the execution cap. + let gas_limit = 500_000 + body_history(0) + slot_state_gas() + history(WRITE_RECORD_SIZE); + let tx = TxEnv { caller: CALLER, kind: TxKind::Call(CALLEE), gas_limit, ..Default::default() }; let (mut mega, _, cfg) = both_evms(db.clone(), block()); assert_satin_cfg(&cfg); let mega = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); diff --git a/crates/mega-evm/tests/satin/legacy_share.rs b/crates/mega-evm/tests/satin/legacy_share.rs index 749f1e6c7..9fe7865e6 100644 --- a/crates/mega-evm/tests/satin/legacy_share.rs +++ b/crates/mega-evm/tests/satin/legacy_share.rs @@ -26,8 +26,8 @@ use revm::bytecode::opcode::{ }; use crate::common::{ - account_share, authorizing_call, beneficiary_share, call, create, create_share, execute, - runs_at_measurement_prices, slot_share, + account_share, account_state_gas, authorizing_call, beneficiary_share, call, create, + create_share, execute, runs_at_measurement_prices, slot_share, }; const CALLER: Address = address!("0000000000000000000000000000000000710000"); @@ -182,7 +182,7 @@ fn test_a_code_deposit_takes_no_legacy_share() { fn test_the_transactions_own_recipient_takes_no_legacy_share() { let outcome = execute(db(), call(CALLER, NEW, U256::from(1), ABOVE_CAP)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert!(outcome.gas.state > 0, "the recipient is a new account"); + assert!(account_state_gas() == 0 || outcome.gas.state > 0, "the recipient is a new account"); assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); } @@ -192,7 +192,7 @@ fn test_a_creation_transactions_account_and_code_take_no_legacy_share() { let init_code = Bytes::from_static(&[PUSH1, 1, PUSH0, RETURN]); let outcome = execute(db(), create(CALLER, init_code, ABOVE_CAP)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert!(outcome.gas.state > 0, "the created account and its code"); + assert!(account_state_gas() == 0 || outcome.gas.state > 0, "the created account and its code"); assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); } @@ -209,7 +209,10 @@ fn test_an_authority_and_its_delegation_indicator_take_no_legacy_share() { .is_some_and(|account| account.info.code_hash != revm::primitives::KECCAK_EMPTY), "the authority is delegated", ); - assert!(outcome.gas.state > 0, "the authority's account and its delegation indicator"); + assert!( + account_state_gas() == 0 || outcome.gas.state > 0, + "the authority's account and its delegation indicator" + ); assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), 0); } diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index d85341d6f..7b577854a 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -272,10 +272,13 @@ 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()); assert!(matches!(mega.result, ExecutionResult::Revert { .. }), "{:?}", mega.result); + // The reservoir paid each slot but its share, as far as it went, and regular gas the rest; + // the revert gives all three slots back into the reservoir. + let from_reservoir = DEFAULT_RESERVOIR.min(3 * (slot() - slot_share())); assert_eq!( mega.reservoir_remaining, - DEFAULT_RESERVOIR + 3 * slot_share(), - "nothing kept, and the shares regular gas paid come back into the reservoir" + DEFAULT_RESERVOIR - from_reservoir + 3 * slot(), + "nothing kept, and what regular gas paid comes back into the reservoir with the rest" ); assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 72c39fceb..4f1c837bc 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -198,10 +198,12 @@ fn test_gas_answers_the_whole_regular_gas_after_a_read() { /// A callee started after the caller's read with an explicit gas stays bounded by it: its state /// writes draw the reservoir the transaction has, not the caller's withheld gas. The bound pays -/// the compute of three fresh slots and what one of them spills: below the execution cap, where -/// every slot's state gas and history spill onto it, the callee runs out of gas before its third -/// write completes — at the spec's prices already on its second write's state gas, which is more -/// than one write's compute; above it the reservoir pays all three — each as without the read. +/// the compute and the legacy share of three fresh slots, and what one of them spills past its +/// share: below the execution cap, where every slot's state gas and history spill onto it, the +/// callee runs out of gas before its third write completes — at the spec's prices already on its +/// second write's state gas, which is more than one write's compute — unless a write spills no +/// more than its share; above it the reservoir pays all three but their shares — each as without +/// the read. #[test] fn test_a_bounded_callee_writes_what_it_writes_without_the_read() { let child = BytecodeBuilder::default() @@ -210,9 +212,11 @@ fn test_a_bounded_callee_writes_what_it_writes_without_the_read() { .sstore(U256::from(3), U256::from(1)) .stop() .build(); - let bound = u32::try_from(3 * fresh_write() + fresh_write_spill()).expect("a bound in a push"); - // Where a write spills nothing, the bound pays all three below the cap too. - let below = u64::from(fresh_write_spill() == 0); + let share = crate::common::slot_share(); + let bound = u32::try_from(3 * (fresh_write() + share) + fresh_write_spill() - share) + .expect("a bound in a push"); + // Where a write spills no more than its share, the bound pays all three below the cap too. + let below = u64::from(fresh_write_spill() == share); for (gas_limit, status) in [(BELOW, below), (ABOVE, 1)] { let (detained, plain) = with_and_without_read(|first| { let parent = diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index b99c217ac..758e86397 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -170,26 +170,27 @@ fn deploy_forwarding(init_code: Bytes, forward: u64) -> (MegaTransactionOutcome, (outcome, returned) } -/// A constructor that writes a fresh slot and reverts, run on 500,000 of forward and no -/// reservoir: regular gas paid the slot's state gas and its record's history, and the revert gives -/// both back into the creation's reservoir, so the creation returns its unspent regular gas and a -/// reservoir of exactly those two. `gasUsed` nets both pools: the regular gas spent less the -/// reservoir it returned, which is the constructor's regular charges alone — 12,109, at any byte -/// price. +/// A constructor that writes a fresh slot and reverts, run on no reservoir and a forward of +/// 398,560 of room on top of what the slot adds, 500,000 at the spec's prices: regular gas paid +/// the slot's state gas and its record's history, and the revert gives both back into the +/// creation's reservoir, so the creation returns its unspent regular gas and a reservoir of exactly +/// those two. `gasUsed` nets both pools: the regular gas spent less the reservoir it returned, +/// which is the constructor's regular charges alone — 12,109, at any byte price. #[test] fn test_a_reverting_constructor_returns_its_slot_as_reservoir_and_reports_its_regular_charges() { - const FORWARD: u64 = 500_000; + let given_back = crate::common::slot_state_gas() + + mega_evm::write_record_history_gas(1).expect("a record has a price"); + let forward = 398_560 + given_back; let init_code = Bytes::from_static(&[0x60, 0x01, PUSH0, SSTORE, PUSH0, PUSH0, REVERT]); - let (outcome, (regular, reservoir)) = deploy_forwarding(init_code, FORWARD); + let (outcome, (regular, reservoir)) = deploy_forwarding(init_code, forward); let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { panic!("expected ExecutionReverted: {:?}", outcome.result); }; - let given_back = crate::common::slot_state_gas() + - mega_evm::write_record_history_gas(1).expect("a record has a price"); assert_eq!(gas_used, 12_109, "the constructor's regular charges"); assert_eq!(reservoir, given_back, "the slot and its record come back as reservoir"); - assert_eq!(regular, FORWARD - gas_used - given_back, "regular gas paid the slot"); + assert_eq!(regular, forward - gas_used - given_back, "regular gas paid the slot"); if mega_evm::active_satin_prices().is_constants() { + assert_eq!(forward, 500_000); assert_eq!((regular, reservoir), (386_451, 101_440)); } } From 38942b934c14e8b4eb76684c97c06357403f8617 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 14:34:03 +0800 Subject: [PATCH 084/190] fix(evm): a halted frame's regular-paid charges stay counted on its caller --- AGENTS.md | 3 +- crates/mega-evm/src/access/detention.rs | 19 +- .../mega-evm/tests/satin/reservoir_drain.rs | 10 +- .../tests/satin/reservoir_settlement.rs | 19 +- ...erential__keyless_differential_record.snap | 276 +++++++++--------- 5 files changed, 170 insertions(+), 157 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b3951703e..370ef83b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,7 +119,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat 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. - Give-backs to the reservoir alone and the legacy share are the fork's, behind a switch that defaults to upstream's EIP-8037 (`CfgEnv::reservoir_only_give_backs`, carried onto every frame's `GasTracker`): Satin's spec configuration turns it on and the neutral configuration off. - With it on, a refill, a take-back and a failed frame's rollback credit the reservoir alone, a returned reservoir replaces the caller's without unwinding its spill, and the tracker's spill counter (`state_gas_spilled`) is what regular gas paid of state and history gas, which no give-back lowers, merged into the caller on a child's success or revert; a halt takes it out of the reservoir the rollback credited (`consume_regular_paid_charges`), so the halting frame's reservoir is the one it received, and the first frame's halt returns the charge made before it only for the part the reservoir paid (`settle_first_frame`). + With it on, a refill, a take-back and a failed frame's rollback credit the reservoir alone, a returned reservoir replaces the caller's without unwinding its spill, and the tracker's spill counter (`state_gas_spilled`) is what regular gas paid of state and history gas in a frame and in every frame below it that returned to it, which no give-back lowers, merged into the caller however the child ended, with the part halts already consumed beside it (`halted_regular_paid`, a word of its own, so `GasTracker` is 96 bytes); a halt takes the part no halt below consumed yet out of the reservoir the rollback credited (`consume_regular_paid_charges`), so the halting frame's reservoir is the one it received, and the first frame's halt returns the charge made before it only for the part the reservoir paid, read off the count before the frame's joined it (`settle_first_frame`). + Detention's halt burn is what the halting frame had left alone under the switch: what it paid from regular gas reaches its caller's count, which keeps it out of compute (`Detention::on_frame_end`). The fork reads the legacy shares from four schedule entries at the four opcode sites (`GasId::sstore_set_state_gas_legacy_share` and its three siblings, zero upstream) and draws them from regular gas before the reservoir (`GasTracker::record_state_cost_with_legacy_share`), the call's and the creation's before the forward is computed; both need the fork because the refills, the rollback and the settlement of a returned reservoir run inside revm's instructions and frame return. The engine records the part of the first frame's start record regular gas paid (`AdditionalLimit::first_frame_charge_from_regular`) and consumes it on that frame's halt, and the keyless steps take their shares through the same tracker call. - 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. diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index 2f7e69594..3e38240b9 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -151,9 +151,10 @@ impl FrameFigures { /// then refuses the call or its creation runs. /// /// 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 what its regular gas paid of state and -/// history gas, without running anything with -/// it. A frame answered without running that halts burns its whole gas limit: a precompile that +/// frame that halts consumes the gas it had left without running anything with it. What its +/// regular gas paid of state and history gas, which the halt consumes too, stays out of compute by +/// its caller's count under Satin's give-backs, and is burned with the rest under EIP-8037's own. 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 @@ -470,12 +471,14 @@ impl Detention { return Some(ComputeStop { limit, used: self.compute(gas.tracker()) }); } } - // The halt burns what the frame had left and what its regular gas paid of state and - // history gas: the settlement consumes both, under EIP-8037's own give-backs by rolling - // the spill back into regular gas and burning it all, under Satin's by taking it out of the - // reservoir the rollback credited. + // The halt burns what the frame had left. Under EIP-8037's own give-backs it burns the + // spill too: the settlement rolls it back into regular gas and burns it all, and the + // caller's count does not take it. Under Satin's the caller's count takes what the + // frame's regular gas paid of state and history gas, which keeps it out of the caller's + // regular gas spent, so it is not burned a second time here. let left = gas.failed_charge_remaining().unwrap_or_else(|| gas.remaining()); - self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled()); + let spill = if gas.reservoir_only_give_backs() { 0 } else { gas.state_gas_spilled() }; + self.burned = self.burned.saturating_add(left).saturating_add(spill); None } diff --git a/crates/mega-evm/tests/satin/reservoir_drain.rs b/crates/mega-evm/tests/satin/reservoir_drain.rs index 59c1f3e97..44bf1daeb 100644 --- a/crates/mega-evm/tests/satin/reservoir_drain.rs +++ b/crates/mega-evm/tests/satin/reservoir_drain.rs @@ -167,8 +167,8 @@ impl Pools { /// A child's return, handing back `child`: its regular gas comes back, what its regular gas /// paid for state and history joins this frame's count, and the reservoir it hands back joins - /// what this frame kept, unwinding nothing. A child that halted hands back no regular gas and - /// no count. + /// what this frame kept, unwinding nothing. A child that halted hands back no regular gas, the + /// share it was given and its count, which its halt consumed and no give-back takes back. fn absorb(&mut self, child: Self) { self.regular += child.regular; self.spill += child.spill; @@ -626,7 +626,11 @@ fn model_callee(callee: Callee, start: Pools, budget: Budget) -> CalleeModel { }, LimitUsage::ZERO, ), - CalleeEnd::Halted => (Pools::new(0, start.reservoir), LimitUsage::ZERO), + // The halt consumes the regular gas and what it paid, and hands back the share it was + // given and the count of what its regular gas paid. + CalleeEnd::Halted => { + (Pools { regular: 0, reservoir: start.reservoir, spill: pools.spill }, 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 } diff --git a/crates/mega-evm/tests/satin/reservoir_settlement.rs b/crates/mega-evm/tests/satin/reservoir_settlement.rs index 69bd14cbf..51ca9abda 100644 --- a/crates/mega-evm/tests/satin/reservoir_settlement.rs +++ b/crates/mega-evm/tests/satin/reservoir_settlement.rs @@ -133,7 +133,7 @@ impl Inspector, EthInterpreter> for Settlements { let child = &mut self.children[index]; // A revert puts every charge the child made back into its reservoir, whichever // pool paid it, and keeps the count of what regular gas paid; a halt gives back - // the share and consumes what regular gas paid. + // the share and consumes what regular gas paid, which stays counted. let charged = gas.state_gas_spent() + gas.history_gas_spent(); child.handed_back = Some(if result.is_ok() { funding(gas) @@ -143,7 +143,7 @@ impl Inspector, EthInterpreter> for Settlements { spilled: gas.state_gas_spilled(), } } else { - Funding { reservoir: child.share, spilled: 0 } + Funding { reservoir: child.share, spilled: gas.state_gas_spilled() } }); self.settling = Some(index); } @@ -229,10 +229,11 @@ const fn after_settlement(kept: Funding, handed_back: Funding) -> Funding { /// Each child of the transaction's frame settles into what the frame kept of its reservoir: one /// that succeeded after a write hands back what it left of its share, one that reverted after a /// write its share and the write's charges, its legacy share included, one that halted after a -/// write its share, and one that spent past its share hands back nothing and the count of what its -/// regular gas paid; the next child's share then joins what the frame kept, and the count stands. -/// The frame kept two per cent of its reservoir at every start, and the transaction's gas, which -/// holds none of it, ends with what the frame hands back. +/// write its share, and every one the count of what its regular gas paid, which no give-back and no +/// halt takes back — one that spent past its share hands back nothing but that count; the next +/// child's share then joins what the frame kept, and the count stands. The frame kept two per cent +/// of its reservoir at every start, and the transaction's gas, which holds none of it, ends with +/// what the frame hands back. #[test] fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_hands_back() { if state_is_free() { @@ -263,7 +264,11 @@ fn test_a_callers_reservoir_after_a_child_is_what_it_kept_with_what_the_child_ha Some(Funding { reservoir: reverter.share + slot_share(), spilled: slot_share() }), "the reverter hands back its share and what its regular gas paid" ); - assert_eq!(halter.handed_back, Some(Funding { reservoir: halter.share, spilled: 0 })); + assert_eq!( + halter.handed_back, + Some(Funding { reservoir: halter.share, spilled: slot_share() }), + "the halter hands back its share, and its legacy share stays counted as regular-paid" + ); assert!(spender.handed_back.expect("ended").spilled > 0, "the spender spills"); let idle_kept = idle.kept.expect("the CALL ended"); assert!(idle_kept.spilled > 0 && idle.share > 0, "the idle child's share and the spill"); 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 15cd6d7eb..a25d806b8 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,148 +4,148 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xc3b43754d461dfa5918bfeffa9ce9fda217b41f87cac0cda66134e351934b406", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x43d7196d1e6199ce2e92b589b489bc02968f41e19abc4f3c41b75782dd7947ba", - "rule: arguments that do not decode @ 50000000 | keccak256=0x93acb4de193a5c435f9b36d21efd46cf474a313d7937c4916359fb4ff9c1465c", - "rule: malformed transaction @ 50000000 | keccak256=0x4faea5d2f1bd3bd07743eba4568947ee5e60e47bb08d9f991ce76f214df8f427", - "rule: a trailing byte @ 50000000 | keccak256=0x8a1eb1a2bded1e55cf53fec655d6bf71954dbe1557ffb91943d0d9b145053cfd", - "rule: not a creation @ 50000000 | keccak256=0x3eb99bc18add0322b48be4a3f233e00a2d2e9b53562729852c0ec9ec2b36c27e", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0xdcd998d59e2ebd8b3fdb27b81d32b6d40538520a7d55da9094de1438eb134618", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x808697be7470d66b58100bee933e5cd03c7085f0f60a7ec2f00a7e7a9c28752b", - "rule: override below the signed gas limit @ 50000000 | keccak256=0xe22c9afcf1f7decacec6200cc83dfc4c5f54b94dab89126e65aeb007431cebfe", - "rule: invalid signature @ 50000000 | keccak256=0x7b878cc8e808f68c6e78540d59855de66de3ec45752e3caca40d923570cb5a5b", - "rule: signer nonce 2 @ 50000000 | keccak256=0xb24a62a13524504fe58dbde62293db20e9288a3c3a59f5ea7d3a2dcfad9aee95", - "rule: signer with code @ 50000000 | keccak256=0xc264f5fb73ba98555a5b333f88f246d505949fdedb6c29ce562ea4766b54ea22", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x565239fb5e3b27186d60a4892f0b5f716dc0b96155e59b6a59203ab1e5b86f68", - "rule: occupied address @ 50000000 | keccak256=0x782badc0f4f7e4026b3c3eb82e5eaf61be67d37cd6f4cd14193c6a7852d1807a", - "rule: value the signer cannot fund @ 50000000 | keccak256=0x4ad52c1303eeb8fe3e52c2229c9994acd9d0485846b655206148e429ef3620d3", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x21232c1e38663e1b77afc1b66722d7f4ece80ad1af8947b31704513e76f4eddd", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x64520348cc3a5c32da19e721788407ca3a10baeed0022d2cfd877552d3c4d5f7", - "deploys from nonce 1 @ 50000000 | keccak256=0x34c98dd2349896d43c22c2c772e2dc0b828e9d6c46b8593352736c5d84e978f6", - "the address already has a balance @ 50000000 | keccak256=0xaeafefb00fd16aa517628dfa3ca2e2fd6deb0c3da7e027bd4c012a6573955e40", - "moves value @ 50000000 | keccak256=0x7e83bf3d83ecc33a967c30c91cf8de3e14b9fd82bd3ca3c38375b8d6fc17760b", - "moves value from nonce 1 @ 50000000 | keccak256=0x92cf77de731dfe50ffab58893cdc7b4696a2e463048ef25b78f15ff4f676a6f5", - "the CREATE2 factory @ 50000000 | keccak256=0xd355575f63fc93c89c34b0a3eb9bec29dc68d9d0692aa85f5e4653400752138d", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0xe6e69d4f852387bf4e0f3406845abca7e248a50ab70b0d3e9790220b218d9337", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0xd1ac026d3f84329ed597524ebdeb738a950d03faa458c240900cd08d3c8273b2", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xeedf8e92f81d19b812442e261bf89e86f81d3added3496879e72ee3f55290c1f", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0xc36b93f760ee97a66042e6d32ee9ac98bde48272c267cb87e9c13f4844325d59", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0x94f60739a7f21e8d69a31f78053b1c2840a35257724c19789b333c26a4496fad", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0xfbca110b9b6bf52f07cfcd8413245ba76cf6d72fe48b25ab2de99ec22b6a80e0", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xf5e3da20ddc63f2304f4750c1724d5a5a9915aec5e24daace911b8e245d2ec7a", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xa440c295448490f3ea5f2f2380241dfdb15a3e9821c387db7bff602c892181c7", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x8dd1b516567b0012de07c4f1d528353bfc5960a17c693e05752633619478c520", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xe5a0bb9a0be01370d7d2d469c3a526c2fbd3b3a2e432da01fef409172f563796", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xf289a0fb9ecddcf9d67e1822705ace6235f9e9a9c9a51cb38189218fd3f36fef", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x751a636bc589a14114361cb58d9b2a5413dfb31151cd367157f4f13257f7e81a", - "a constructor out of gas @ 50000000 | keccak256=0x29f53c9ff2810a160ecd2c4f226588a4405eb27b7c8e0b7bfc86eb75f6a2d93d", - "the signer sends it @ 50000000 | keccak256=0x38d4d4bd27d290061ed31c1c222e5d1b233fb5f602a2f8a808a153e1dce8bb06", - "the signer sends it, and it reverts @ 50000000 | keccak256=0x775b1526ea415f212c808670ddbd07d5e0480d1f8632ee56f62948df40eca660", - "a delegated signer @ 50000000 | keccak256=0x5bb2a3dc8f16a8023d2bfeb852249194c55339c00bbeb69eef9848510c11aa5c", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x23d41e1bf2e7f6ed2e446443f9c4197481f6a38d90e84b9c29b194fa00682c9b", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x0c54859c5a5450d01362fa9ec33f979380c1f87c1aad764ccbb55e00b497e1cd", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0xdd9fc7f9b1933385d3dba06e5e78f24cb3cbdfbc3baa808845cf507d88756692", - "limit: compute, nonce 0 @ 50000000 | keccak256=0xef2ba5b0e112e47a789e769a3c6b7b81f93ff4fd535c322ea19c33ba4fa3781c", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x7c694f324ca40881b3cdb87180db35c68847a8d61088b7e384755690c2c39362", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x35ac020bcbc2ed778af92c0e9365b0d10038fc8c585cf3d90d69db76bcb9bea1", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0xedfd6eedaca50b1822557ab886c9385635e172657ac6e498efee2f9c28646512", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xd55d03627ef3792b8bf54319f4b5722ba4201e7fa3ca72fba6c5c77b85961beb", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x6694e205cdc91a7cd6402311912f2de489e411c4dee1d70db1aa0d82666b00c1", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x9b71202a63e6c75be04c1c9db3b2df8955463425b6d0e9e0acccc028d7b0a7c9", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x3b58c7f907d359c77b75f1ca75ef869c054bdf750e351cc020743d74adf88aaf", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xc4c9a8c68a28a7813ae6ac51254141a128b798fe0d313064630d6c43add015b7", + "rule: value @ 50000000 | keccak256=0xe77b672214965457e00c55c62ae4733d8b71561a84728c5584abf42ccb8b3cd2", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0xd396408de0734677ff12a41816c18174be7440c7769e205ca46bf66f84d1ed04", + "rule: arguments that do not decode @ 50000000 | keccak256=0xad4ba1b29efa0d595aa892e87cc96d7e34575550c272cdaba73a33405dd95716", + "rule: malformed transaction @ 50000000 | keccak256=0xe622039870f0ac09e57ee68d8b6db0a645edcc334341710cbe3fbaeeb6f61e60", + "rule: a trailing byte @ 50000000 | keccak256=0x40a34b14b479ab729a10c450208ac2f892d9f95ae7fd66885b4076a0e652d3ca", + "rule: not a creation @ 50000000 | keccak256=0xa7b41a64338a8994bc66121e64959cfda34d7813e3a699798b77dbf51aebe77c", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0x8ee0fac1c110752067fafc16ec7ea707da2a3c3220c1130a2a4dd0a45153b2b3", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x299794829c09a3c06d6b1caa827e96e3a1cf399ca8929b81f66b5c75b27e5920", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xceacb0513d151c3da45faaabf2f6b3a4b1f7d7d8e8635c4ab6ce8027ff7c1d84", + "rule: invalid signature @ 50000000 | keccak256=0xc231be3632b778d558b64e7790a5fe47066392e7b63d8ed92808e3ac5dc32346", + "rule: signer nonce 2 @ 50000000 | keccak256=0x0ea120ae292c8732fbc0648cd75ac6fa0a3817684584dcdde94cb1463180886c", + "rule: signer with code @ 50000000 | keccak256=0xc8db541ac05db5aac32ba23a74c03f82d1a48d5ea514557ed7d2d41d9b94ec3d", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x78c898fb275e0737762928c66b374506d6a8ce1681baef648475736767e95b29", + "rule: occupied address @ 50000000 | keccak256=0x4274e2b5e24b9cdd172dd83c34091b1dc27b7588269d08c08b177e70a225c83e", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x649c6c4cee5d89e64a472f0f08037ab473e080d821ee6bdc1b33a1cd1347488b", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xd4fa4c3ab9f92e1f576e756b8131b7d9199e069fb9bb9c3b1c9b6d4eb2e547b0", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xd60e9feeb76638878f7e90bb3874ec8f2cce128cac2d4469f1567584d992ae69", + "deploys from nonce 1 @ 50000000 | keccak256=0x98f8cc95ad134f3cf688d49fa7342dbf9a746fcbd5020933c81af3a3ac1afd27", + "the address already has a balance @ 50000000 | keccak256=0xc96adce4fa1d0ef7bfeec1b1b6d9d2bf88c37a2f9a2594dab40eb26cd7ba081b", + "moves value @ 50000000 | keccak256=0x81a32fdea22472567e90afe55fa95762b94c2982143612d34dba912b2e6c6b44", + "moves value from nonce 1 @ 50000000 | keccak256=0x86c2eec8c42cc9f6702932491c99c9aa456882860a63467dadd50d5af603c9ae", + "the CREATE2 factory @ 50000000 | keccak256=0x85fdc57e1202af357cc41705f51c02fe9c07d92da459d2b944111a9304c5fd91", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x40eeaac598e697ab7fab0ae38ee912bf9e11b735def342f7ec855115f14bb047", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0xf5f778e39426f0e33f8e1458f437384ca53a9f66854ef184266efbecb109f238", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0x667a297d5f7671859d8fece45e3919239f1e432ae8b4cc7824e016f7481d487a", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x932b05e44a3da8c2856551d9aff10294590039368d209a85aedc7ca063063869", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xd3d96d8b0040b66f4fa780d3b0eae80336e165f3abd1f9eed94893c7edc1c1f5", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x0e736bc37b8bf2ef1ab313808cc1df3f24ae1f9a1520f3db0d4b841f224b825b", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0xd2dabf4a6ceedfdfd40a33e81662b69e2e9b617f1306dd5db5ce19392e6c2442", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0xdbb9e7166cfd6959af02a130c00bfd30ccd8e2146eb9aa9f94fd87b8c29d2ec1", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x4c8fd8ad0384497f603eb4775e2aac85d45a72cdaf6d71ccd0d7f828380a3650", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0xb1bf37e6a10e9fed1de2ba352d8f7a002d0210e27453a4a5866b59509e4abd9e", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0xf1d934fa494d3602ae6df79955a868ba0ad8453197046d0b19dca083ca98132d", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x12e213925b48c06b3b2dc6b60ce1bbdd47a82751928fa4cad358ff4b3a4ace0c", + "a constructor out of gas @ 50000000 | keccak256=0xb5bd61f0643bb41d7dc76c3bbbca81d05ca8df30df6b45a32303cfa16bd4d70f", + "the signer sends it @ 50000000 | keccak256=0x696218e3cb740fe30113397188384476b3da81010b154ffcfa38dd2cc4fa438d", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x74063046b5408c91cfceb1488d83048df7a774dc7ad4cb667ee9f40baa75ae0f", + "a delegated signer @ 50000000 | keccak256=0x226fa3bbf398f8696f781ee1986f89d0ab601432b36da832b3df8b9450badc02", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0x0c9c1afabba0217f9612766cd70c4775a0137d54f5bbd9fb369eb19e8e6db2d6", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x024260f8f836beb10605ab69882e53b329ca356617ebb2270f51a8354b8aaa11", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0xd694feb0f511fa93a8fe04be4401d4e181c0a4194d97fc235dac5228835f8aaf", + "limit: compute, nonce 0 @ 50000000 | keccak256=0xcb3411c376ae2d87c779b872f35f55043d2238951ec6224d99f3a777bd19f446", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x9a02a97ce0ea8bb426d0c90928913fbe3dbf25770ad3a3b80cb127ba42dc60cd", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0xde0b39b4f4d79aeaaa8689be081fdcbf098601c5bf172afcb7739793d089b950", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0xee88d5a10755db3c9e2cf32cf89272d58c82bc897a8c5080d7113ea414d61ca1", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x8a75af5d47e10c4a938b218b60dbd388d6059ddcaf9ad7c60fbbfa3c45952768", + "limit: compute, nonce 1 @ 50000000 | keccak256=0xe137fae64a7ce7f8b8d93342914f2f2e64e61ad2430af73a6f87ce7f97336cca", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x5e33e50ad62eb5b985f467969f3b429dcd582592e145f3d007577a40ac2fa681", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x367da13192768d85b560f9b64e26f59ced5d5bf5d08d928d7ac2765d0932765b", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xce98b9e35e3105cd919ad16f7330f6fa96dd2410e84f45a67ed9bf59a7f2ab91", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0x209540591c3a38d6b2e445019c2d343ce9a48f7e404b009f48f2c822b4abe593", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x13231f3cd28dd7e2edfa5565fa3fe29cac9deb4b96813cd330de5ad8abf739b6", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x578a6e5eba12e2247f5407b8d24664b1417d8c18d6e5920caea70a42ed8f9c97", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x5a334d581d838cc723854cd1beea6704ce666e23032aa4ee982fcc1140e84596", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x99387894fe7dff326531c9b2cab8e1c1e94e61d7ff6f186304017cc9d56afc96", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x0b03ac4a952ff6be872ff2ae4520936645d4cedab6fabcfe7e523e8ea96cdaaa", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xede425c3d9b69a9df798bbc6e44d1cdffe9e97d0ac4d4d9258200de8d3ddcc52", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0xd6d76652001980ec8ee4cca787027b7d1406c5bf0f19d9e25add1c9b1255241a", - "not dispatched: version() @ 50000000 | keccak256=0x541deaac8fac3b007f001f800e99927136493937a95a4c6cfba0a5f019efe16a", - "not dispatched: no selector @ 50000000 | keccak256=0x58f1e6d8f7676c41a540b8851cdac9392b801d6f6c55a740a61952a2054ba714", - "not dispatched: from a contract @ 50000000 | keccak256=0xf58fd24a5655470eae7ebf48dea32ecbd420d9db233592b111f888daef9dab5a", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x8e3c6f7c9e2783b4917dab1394ce1156eed8eace1f325a953040f5ed7b656d7e", - "no contract code @ 50000000 | keccak256=0x6752c03881eeba1f19ef9a88742cf9957939d9f610ffda9ac5507acaefabb015", - "a system call @ 50000000 | keccak256=0x12429c54282df9825596b87532e0f3e9959b1cacdacb580819e1064b7b0311a8", - "rule: value @ 400000000 | keccak256=0xabae6bd19c2845f2d65259715d280aadd786c2a162ae6ec6b810fa08a4524515", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x5528d2521e033dbb089814d8994c897466f585f53e4edde8f6ac182aca0a51a1", - "rule: arguments that do not decode @ 400000000 | keccak256=0x83d6da72ae825b98cd6c14498a58310a676509d8effc55180c6581b1cecc2a96", - "rule: malformed transaction @ 400000000 | keccak256=0x8e145192945e11bd92445a6dbb0f57d86f44a89e8127653837c0a586863d229f", - "rule: a trailing byte @ 400000000 | keccak256=0x411fd177353cca21ca9f12ebe963358c52f195dbda598bc459bfe50152e6e81d", - "rule: not a creation @ 400000000 | keccak256=0x4dac3118706624308edda37bfeaf255b70d0be899e6accab4629caa811cd049e", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x00a66474bac782d23e56d9ef21824f38826221d0fd6e595767049653214b022d", - "rule: signed at nonce 1 @ 400000000 | keccak256=0x5f1d11c6d25e150dda97afd81c375f2a8614c5b66ffcd3c6c8ecc9df199b5488", - "rule: override below the signed gas limit @ 400000000 | keccak256=0xd1f2b226c4d8a52688702b61bb28a4bfaa9a0b9854ab785501b90a69fa88517b", - "rule: invalid signature @ 400000000 | keccak256=0xef42132c35881c8ddc9d49795051fc37ee6b3ccaf9ef87e190f0c8b77c121e99", - "rule: signer nonce 2 @ 400000000 | keccak256=0x2dbc65e4d4612973dd7476af30991fd21c9ff55677129c90310c290cb2a5e792", - "rule: signer with code @ 400000000 | keccak256=0x88676184ce398dbbc84b1c20fbbb9595ffb78a36b008f9820c3661cc7806856a", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x2a959fc341801760e14b235e5cee36ebd5617f8de1841cf4aa937fc674911626", - "rule: occupied address @ 400000000 | keccak256=0x379893de01787694d704e98e05690ab6e52b947ef67d447d941ba997040c6145", - "rule: value the signer cannot fund @ 400000000 | keccak256=0x29e15229205ba4aaf6af5a02d65ebaf458a92caefa20b1989d577c102d6923d6", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x0df7a96196357042132e5eab149190e86770bcbe8a8c2d5afcbeb07330936627", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x01a56cdc76be8496712cd4511d05595bda3d936bac193ab71130a06178af916c", - "deploys from nonce 1 @ 400000000 | keccak256=0xa0729131ec01d00d77fbaf3c7e2a4c333a51697e9830ace70ae9cfba3f716a68", - "the address already has a balance @ 400000000 | keccak256=0x69ffae4325b6c87d39ad7ee811426bf57a93a70e6a99da42256fadaa3020512f", - "moves value @ 400000000 | keccak256=0x4ba6baee9596212e050261034f937d9c9de0a09c222c6e8ddc21170e385db863", - "moves value from nonce 1 @ 400000000 | keccak256=0x49173f5bb526fe27fb2c073fce9fe193b5f2e67d3e8013f865cada07fc1f032e", - "the CREATE2 factory @ 400000000 | keccak256=0x9ec569f071b101ec7e3eb5d6d6c4f6a60890c9a5d790a0ea34363c5d3d5b86db", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xe313a5a4197f8da5cf8e137b1a6022ddc479aca6c20a19b4541783e28d1d71c8", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xe76db8666ad51a56be93f784eb68da643287674994653baa88f22deb6a164399", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x1b4550bf9761772dd0b549d61721fafb4326891782034570301e3fc7e177ec29", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xd88b8c64b1cf4aca61d26b0e5e6b2052cdf033228508e14ddc865f515bd3415b", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xccde5bf26745fb0863111308aac1aa6b9bb67a1dd3b200e0f25270fba4e8ee55", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x9217efc4cfe6d14272eb02c9919bc8a63c68547c27f0121d22019c738154bf5b", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x81d4f6b683091715fee7eb499f0a4ebd7122756f8ead993d6f5b569fc7b57838", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xfa1e75a1a29f6c7163ae4970d0f261c71b7cf71da831eb1d7b1b0ba06fcf2dbf", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x87e10c55079a603849fe7da38ceb444707cb05d16e9f68a410ae7f62669c4883", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x97bc02f3b8d030c247d40e8958f9570321de80c8b5e9fc6b84a1ea6c5267622a", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x4cebba01356ee32eb2c02e0ff4774011d45ba1a77e607c4ad8400b1efe216b8f", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x075e641dc65727b1f093f5721e60bca7a3f1f3a1593ef72199c069e972f22236", - "a constructor out of gas @ 400000000 | keccak256=0x1b5423a976e515c3594ebbbeba662379c15eb7fa4a4723e38df5cadfa143b599", - "the signer sends it @ 400000000 | keccak256=0xdc1cdf72937c79d7c3064ef71e9b2e1e7d91066327319091a1b75c0064e34e65", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xfc64c01f65436e8907a2902b55c26db022ea82bd1c6716527fc74c466cdcc6fc", - "a delegated signer @ 400000000 | keccak256=0xdb807928d7b0fb523b523ae25965ec3559726c44d03553ffae59d3e544ad3ef9", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x35dca5fa2ce73fb9192577f5336ca62a2a160e3c59d1b4ba7fd2b2d5c9aa0db5", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xd424255e8c387294ab969492b54fb39e61c3e4afe8275b24c59993866ea43142", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x628022aa8c9a74e0f2971cd49d08bca27142c50e889b7cadbac4ca50af9baf3a", - "limit: compute, nonce 0 @ 400000000 | keccak256=0xbe1ceff538a04766b04ec061a7342da8964906d59bfee8ba8d191a3ea1c56845", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x59fecc921717146171b2d874e7da06330b171c17d45c11f2be112b61ab358310", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x163418dd81e6b1126a3f33d3e3a46d63d51b32ec4d4d873f758b05c7dd68dab5", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x7c6bb5c4c3fc7ae04ecb9e8dfdc7a1a549938b1663dec3eae486ccdfc9d05f43", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x2332d913312335763ac3098a0fb72d789e1318b063da584253462ab6c30b1351", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x6e82eeccd31de13cf16199671dd5e91ca3b8596e920be8b146d6493a88c6bb29", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0xe4a880ff2ca526ed9b9325808db1aa42996a1e2df64541c28eba9ae069088883", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0x3a07ae39293b43f6910a46498668b9114d7611d3ddef1c8d6f99bb9c0411b549", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xed75e5f9ab3c9f9fdcb52ac9e489790095e2cc5a03e83872927db96e57ffe818", + "limit: the default limits @ 50000000 | keccak256=0xe4b686cdd7efed015a8cf322f721b3c67968c98b70b0d480fc7854487c7ccd3c", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x46c59d9064203f6a8949ed58f845ffa697197553375b9d8a23fb421988f95e30", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0x6fb7314542aa86df15cc3fe9425cbe1baa0da5f0dfb012215ce0efb4563ec91c", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x1c0b457bdad958ec5a9de17fd1ddf9b0e2834b36c24279dca30b2382a12962f5", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x7c874398e104b93ae39226bf236818528b9d72937ce4498af16e55fc8692ea56", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x1480956d02bb41de3f8cc4c7e64b2c4a45d575381ed0723453af494161124071", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xfd3a5de956944ecad724aeaa6b9da278e5945a14f3984984477933e1c318bb0a", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x5dda816666df05c7ab2ebabf951e4fc5549d45a59083e4d925dc5d416f02c213", + "not dispatched: version() @ 50000000 | keccak256=0xa3f8ee3a77d729c55a4871e341ff7327459da081a9fd0fbc913119b83b0a3db2", + "not dispatched: no selector @ 50000000 | keccak256=0x3240adbb19965f0943dd13fa89ae4264641dccbd4c9f5f799125c2fe00b3576a", + "not dispatched: from a contract @ 50000000 | keccak256=0xac2e158ce27a56d35357d4eb53e01167b5f5a686ace98216f6bc1ab8716a5902", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x6e085bc7ce13d006aec7596b7c68167d4f559560d49d63410fade6639954a29e", + "no contract code @ 50000000 | keccak256=0xbd5ec2c73a360cddb0eea53d7d2a812404878c21ec92115b336d30da5aaeac62", + "a system call @ 50000000 | keccak256=0x19781f56400c365420cfef14d3053ac669b0c692055d51dfcb97d6b238351579", + "rule: value @ 400000000 | keccak256=0x839e0892e0d8d1bd2a7e28b4b68017df1464f6d3edeb84432e9bc7beb57d3c2a", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0xdff62d46518fba183c530650e22e04f1c8dec9bb43975782fbd0ec0148e6c96b", + "rule: arguments that do not decode @ 400000000 | keccak256=0xadc0d6d1079efc39fd59c54cf01b3be961a6c4b522c4f5a413bdd363b6fe643c", + "rule: malformed transaction @ 400000000 | keccak256=0x5273086d71cb5dbf54d6b03f582595d4b7a0da83ce56482e23801c4272ac66cf", + "rule: a trailing byte @ 400000000 | keccak256=0x7fb3a7dbbe2a850dffa2b0e8605c70bb9a528333edd2a01def1c191ff22e11bc", + "rule: not a creation @ 400000000 | keccak256=0x72befd4db8f28619ec326e6208e5feb91492fc9b1e7e2d65f82f696d50200675", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x631007443dcd88cf0d4cc52f8da36db370e693470a0aeda627153e4a86f46780", + "rule: signed at nonce 1 @ 400000000 | keccak256=0xb12da4cc1ddb20c162c746cc4869f688f2d6efbc221df1e410d6125b4564ade0", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x011e20cc9b6545df70022a7f81e0bbc519a6ec4303003ebec42576863c6a7462", + "rule: invalid signature @ 400000000 | keccak256=0xb79c275de2d9a635542534a122c6361df42c6d2bbeabb81b9239ce81bb81b143", + "rule: signer nonce 2 @ 400000000 | keccak256=0x93bff26eaf1dfb7fda3b4ba9fd7048e2e4621ee0f5898b6f4a04f3b63297441b", + "rule: signer with code @ 400000000 | keccak256=0xb50220e6f3faee9dd0ad65b8a7164b3a3e57108bf63a3e44510f299c5c5f6e8b", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x0c83714983455a0c5eef32533149417d7a352bd5896ad627a278b919e8a5173d", + "rule: occupied address @ 400000000 | keccak256=0x8cbe8b82f7708d630658c404a7298a6164545f005ce91575767067d2b788ed73", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x898d2377b50e696ae2209b808088cc5b9f31cbb88b629919fdcfccd8e9c0ac07", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x9fc761baac6117cbf6bc2a7c0ce0ac5ea19c9348bd7de651eee8562b9a16acd9", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x543e3209b8647795cbe5fd3d7ac1197766916782ada18c79f1bd4eb479fdbd2f", + "deploys from nonce 1 @ 400000000 | keccak256=0x7c2625e4431b2717202b991ab3f7c66c441a4a8940847ec0ff949f9da277c222", + "the address already has a balance @ 400000000 | keccak256=0x32e77603b8cf4b72657d5d377d4e50b14169e388676b10588ef6571282be3f34", + "moves value @ 400000000 | keccak256=0x5d6262c3c836637b416ab7095ae29965e2013adc770d790db18ac6956ac69bc8", + "moves value from nonce 1 @ 400000000 | keccak256=0x8b0d30be7923d97bc8a49e8684903b800aed68068229f792410ca0ce7b0e78ea", + "the CREATE2 factory @ 400000000 | keccak256=0x100326aa75e0da26bb900707f2865c3982b290d747b77ae19d4ba0b9414763ff", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xd3ad95078f548415e9fbee72164a685b87c978cee59783bcbb58d0c064815699", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0xefbf6e17e30d231218ea5194962ceb7b89a720a5a54905b7667823188bee8390", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0xa13b80e091ed04d085733f9c2fca7f6e3c9950538638f131271907fcd1e29ab0", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0xd1e0a7962b9a568c060802b42feefe0f4cc861936ddb7703ec8c4befe56cf99e", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xe6d647dcf38ce516e6dfe978a4aa55005816f62d8189f902d1ddb9cf13c959e7", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x12688b6b9652362e2b2f5c0702e422e33a937688ba2d65e64a1a0a181b9146f3", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x8c9635415c452b643817afca92f233b7dec822872fcd02dd5d66075ae4b80df8", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x77c6cd55719d3c2d63cdcd76bf2541169b07e6c6c5339510bb5384e78c745070", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x5ce600dcf7fe4c58b753a7fd0062c1637a2cc044860e7f686d1466cc32edf49e", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x0768c13785c693255889c483853af0c6c14f9e9ce396432bb9dbae2d394cb042", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0xa1f498580c4d03f8e6df873eecf2dc2844cb182d14d425642b6ca2b5c710897e", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0xe5e8ef07d7c6df245d0033fa86591533ffdadb5c76b400a47b6ff397fd62ac12", + "a constructor out of gas @ 400000000 | keccak256=0x3f949bfad2269a20d1e40828a2e0bbfc37aab37c7eb9f95b3665e262df901115", + "the signer sends it @ 400000000 | keccak256=0x2bcdc981f59e7e06e259d5e1b1dbfd293e46ab8aa9b0c4a9038c47f6ba83b03c", + "the signer sends it, and it reverts @ 400000000 | keccak256=0x3f765527cf6c706aa5549d94425233f1ea711e3e9490dc3fb86b7cb6a3386b50", + "a delegated signer @ 400000000 | keccak256=0x0e7f6848474acc6467805a26f9c0084292bfcdd1abb5c00c0e41d726a7426ef9", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xef5f645c635c210e347851e1f43e161ca83d61dec5b63d935ee9e693ff73d813", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x58ff4f02ab8b79ea30f79cb37dd7fc41a9ced29325cc500314a3274b1ca80894", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x7702481e779cd1019e4c8e7a8c7ef4f57d551859212be0eb941253a13b64ea54", + "limit: compute, nonce 0 @ 400000000 | keccak256=0xaf03c1101d65d2e70e4e66a2c2d849bff1f398f0453578a073bfcc71f1eecd64", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0x1b289d9282720b16f300737aeed88cc814681a820bd3336ed91c591da940804d", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x3e7683e72742f404c940c1320917bdf6e0565200f85d703c5cd617fce18a318d", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x2598f5d96884848ab998896a7dd577dd563808bf3553218fb20e3f5817541113", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0xfc69781e77a9a88326504301c208d22e89a00483a5b0be2d74dd78c7b6f01c73", + "limit: compute, nonce 1 @ 400000000 | keccak256=0xb1793fa441a89edf19a3eb06b06d40895c869eb348b659890b88598311480c9d", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x803bd72b7f61e3ed3de72a36bf20c9399e764da46c8eff646f314cfdb07dc801", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xd4f203c9f30ac19a98006d685e20e3a232d3e241ca72e735928ddb7e5d77f28a", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x1bbb738df6e37baea21d043e74fbe351a3035a696a6b62579552952483faa4c4", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0x20b1891e2840fe9d1c31470c71a0a3379ad4faa594db9f0c8d887f48471994f9", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x05876d4795cec356a548819f04ef3b651d3e3cb7b9ef019ef23fb5e61e0b950b", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0xf0e515bb0cdb618c00c0b6e2cd67a18382620a63ff5062a8ef501649a5259c75", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xd6d16b313d9b46b93e03729fe713fc50a3158a89666f9a1382049b212b9a7832", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0xfcfc3333e07c50498e7f2b6140d39097e19f69001aefc933375ecdd3506b28ad", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0xb2260f0e69530dc501b8c98fd5efdfad8117ff6f7fc3f7779dbf946f4592ea24", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x63eb9a94bd4451f4fa359b635ff5681d850ce560a332632e9183ddea5cd94c4c", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0xae3d675a98782bcd0b7955af4910d1724f3676dfbc72e6aadf83084a36299f73", - "not dispatched: version() @ 400000000 | keccak256=0xe093a29c20fb9c25655223029041d809334b196da44be073f57bef10b2b0f184", - "not dispatched: no selector @ 400000000 | keccak256=0x24942db7f82e7bd93efeb4496c6f66a26a7922ef4c7bd23724e28ecbce953f8d", - "not dispatched: from a contract @ 400000000 | keccak256=0x303804fa47f6793649d8ef9aba6f6c5b5a5367e64560dfc29608d9aaacf5ca54", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x618482767beb6b6a624bd4769cc2940b4326581c9102d7bda7c5bd6dbd7c8433", - "no contract code @ 400000000 | keccak256=0xb36436cf8d9907027e516d377e4ab3927e65412a6c671edac9beb2eb1a1d66e5", - "a system call @ 400000000 | keccak256=0x5e9e82f017241a41885b08b0035c9660d3b7ed21cad59b45c67d8a0a2e4cc64f", - "out of gas: the overhead @ 161535 | keccak256=0x44cd7c63207d264558c5b459c4cca4d317e05c359d781a0d79e59731a6cbdce3", - "out of gas: the signer's account @ 162536 | keccak256=0xb941698c43a65f9589e8c0dcdbbcaded8805e774074fc7edc7584feab689efb0", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0xb91690051f8a6d154cd94a31fa9aece7b0f8fac923f32703a8b07fe7ac6c6727", - "out of gas: the creation's charges @ 163024 | keccak256=0x7664f24d9c3c20ff82fbf3a42f007e4f5d4a40b5aa2c5df7bcd54f3435d1121c", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x9e614845811556edd11c7bbfbc09c31c037fda50d79aa8e39ef526cc30764423", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0xb2ce3c6da98f81059e48caa292c666803423e24129c31e649c3c9f9f6300dd56", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x37d4e8db925cdc452275d4da169143457516eda9c4514463aa8f41a0258849b6", - "rule: init code over the limit @ 150000000 | keccak256=0xa2ceab04554e5cde508db84cfb47b4c713b09cd174155ba378ca2839656f9d64", - "rule: init code over the limit @ 2000000000 | keccak256=0x2954aa6115c4d77217ba9b1774cd4b59d3d47da28a997977f638034731c0cdf4" + "limit: the default limits @ 400000000 | keccak256=0x68551abb95b4bd802340ab2aa1c9dd1a3e7a292215772fcd6e32156bb9bdafde", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0xc3d3c05ce77884f1066c78544722844192ecb4789e9a8cf52f4529a4d7faea11", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x1859c7fd00ee746a03a79dde4f9243493813aae07ecdcfcf7298cc4623f451d2", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x05f930f3bec4fa1d89313dceb227c7f2e874b96600837a5be7e8ed43eeb9c968", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x4f4f82d67077f15786a2df9722e87a80ee0122ca378717faeb75fd94b403d833", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x548a03fbe7492707c16ff3ee5776e85c897a921cd68afe04de54fb14710efe98", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x620e28f9e07e589056fc0905f4f81263e4a722b8829cbe5dcbebfe4ae929c7d0", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0xfe87a3f94696d898a0088231c31dffb14429dd6e9116ac6c2de701751b3869d4", + "not dispatched: version() @ 400000000 | keccak256=0x6343e0a1ccd15b7e1bb523c0bb2afdae59683b9439665b2fdcb91cd18670d7de", + "not dispatched: no selector @ 400000000 | keccak256=0xe6dadfc37ddb965e220bfb3f08b8297b246bf39820c82bd6dc277fddc964fbf6", + "not dispatched: from a contract @ 400000000 | keccak256=0xe889dd65e87bb205469c29a8e635ccab76815ca75d7b6618c3970d505f0411e8", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0xdb30eaaddc61cade4c1522ecbea2e396d3e6945d5ed69ff10065d34451bba11f", + "no contract code @ 400000000 | keccak256=0x1e5e62a22c82c1ff1a27ba0dcf1c2fed26873e03bec858ec4dd605f1e9e9170b", + "a system call @ 400000000 | keccak256=0xc7b634e9251d60743b3dd02b8498903321ddcbb1623f6f5fcea43a642fd289b4", + "out of gas: the overhead @ 161535 | keccak256=0x0cb2e810df53fa9f40e46284e3af6aa6617e9b87bc078256b9d10bf0273a2183", + "out of gas: the signer's account @ 162536 | keccak256=0xdad0e9cea292909e54e016c3264abd0e80310de6837eaa21abcbe8871d79f47b", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x96a193fa363798249089a6eb36ef77a3e3ec77a289dcf0593415689cdb771219", + "out of gas: the creation's charges @ 163024 | keccak256=0x2a0c53e21a432c3115ad86fba379f3ae5d55f8fd56315544158677a7eff630be", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x7b62428d23524f340efc819ec7a4585934910c9fc00164b9170c8dbe591052dd", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0xb6e90303e28a00d53da7b638eb90ed77ab16f1b774a03d9a2700a4dfa32d921f", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0xb4fc777f2a1c9358b5e57d7508d2538de7dfdfa64a2f4c6da91ebb1c0b10036b", + "rule: init code over the limit @ 150000000 | keccak256=0x7e97a8cacb6f6b0a216744de7dd9c56770d194a69418a1a4403913f713c21639", + "rule: init code over the limit @ 2000000000 | keccak256=0xeef376fc4be105dfd946ebb99ba05e8ea8ec64f106ad61dfef6545e8ce41a28a" ], "summary": { - "bytes": 2484049, + "bytes": 2506561, "cases": 139, "lines": 11482, "runs": 556 From 5348171959e8d763a5e28ee79b08411b90749ba8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 15:11:29 +0800 Subject: [PATCH 085/190] chore: pin the revm fork at the reservoir-only give-backs --- .claude/skills/satin-review/SKILL.md | 2 +- Cargo.lock | 26 +++++++++++++------------- Cargo.toml | 24 ++++++++++++------------ 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index d34d1c0f4..d5701fd91 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -32,7 +32,7 @@ The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and 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` fork at `a125b2c45bef8476e2c1b72dac315c1d05f94f61` and the `megaeth-labs/op-revm` fork at `8c0db939291e1c4cbf2375782d1483bc371d6b94`, 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. +- Fork code: the `megaeth-labs/revm` fork at `2b71cb617f9cb401cf62f78df48e142d13eaf7de` and the `megaeth-labs/op-revm` fork at `8c0db939291e1c4cbf2375782d1483bc371d6b94`, 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). diff --git a/Cargo.lock b/Cargo.lock index 3d08fdadd..dbc1389f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" 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?rev=a125b2c45bef8476e2c1b72dac315c1d05f94f61#a125b2c45bef8476e2c1b72dac315c1d05f94f61" +source = "git+https://github.com/megaeth-labs/revm?rev=2b71cb617f9cb401cf62f78df48e142d13eaf7de#2b71cb617f9cb401cf62f78df48e142d13eaf7de" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index 5c3c023cd..21af6ea01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,18 +232,18 @@ 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", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "a125b2c45bef8476e2c1b72dac315c1d05f94f61" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "2b71cb617f9cb401cf62f78df48e142d13eaf7de" } [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 From c0c3fae872ab19338a82ca9e11f243ebfe9660b8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 16:08:20 +0800 Subject: [PATCH 086/190] docs: drop the rule tags of an earlier numbering --- bin/mega-evme/src/block/satin.rs | 4 ++-- bin/mega-evme/tests/block_replay.rs | 8 +++---- bin/mega-evme/tests/replay_paths.rs | 2 +- crates/mega-evm/src/evm/precompiles.rs | 4 ++-- crates/mega-evm/tests/block/activation.rs | 6 ++--- crates/mega-evm/tests/block/bucket_ids.rs | 2 +- crates/mega-evm/tests/block/eips.rs | 4 ++-- crates/mega-evm/tests/block/predeploys.rs | 22 ++++++++--------- crates/mega-evm/tests/block/transfer_logs.rs | 2 +- .../tests/block/witness/predeploys.rs | 2 +- crates/mega-evm/tests/block/witness/system.rs | 2 +- crates/mega-evm/tests/satin/count_order.rs | 2 +- crates/mega-evm/tests/satin/data_size.rs | 10 ++++---- crates/mega-evm/tests/satin/deposit_charge.rs | 21 +++++++--------- crates/mega-evm/tests/satin/equivalence.rs | 2 +- crates/mega-evm/tests/satin/failed_deposit.rs | 2 +- .../mega-evm/tests/satin/history_allowance.rs | 6 ++--- .../mega-evm/tests/satin/history_reservoir.rs | 8 +++---- crates/mega-evm/tests/satin/intrinsic.rs | 6 ++--- .../mega-evm/tests/satin/limit_exemption.rs | 2 +- crates/mega-evm/tests/satin/pricing_table.rs | 4 ++-- .../mega-evm/tests/satin/reservoir_drain.rs | 2 +- crates/mega-evm/tests/satin/salt.rs | 24 ++----------------- crates/mega-evm/tests/satin/state_growth.rs | 8 +++---- crates/mega-evm/tests/satin/stops.rs | 6 ++--- crates/mega-evm/tests/satin/transfer_logs.rs | 2 +- .../mega-evm/tests/satin/volatile_access.rs | 2 +- crates/mega-evm/tests/satin/withheld_gas.rs | 6 ++--- crates/mega-evm/tests/satin/write_records.rs | 2 +- .../mega-evm/tests/system/access_control.rs | 2 +- .../mega-evm/tests/system/keyless/charges.rs | 2 +- .../mega-evm/tests/system/keyless/deploy.rs | 2 +- .../tests/system/keyless/precedence.rs | 2 +- crates/mega-evm/tests/system/predeploys.rs | 6 ++--- crates/mega-evm/tests/system/system_tx.rs | 4 ++-- .../mega-state-test/src/blockchain/chain.rs | 4 ++-- 36 files changed, 84 insertions(+), 111 deletions(-) diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 67fc271dc..de8140530 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -191,7 +191,7 @@ mod tests { MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(timestamp)) } - /// [S1.8] [S21.12] [S1] With the parent's timestamp, the block admits only deposits exactly + /// With the parent's timestamp, the block admits only deposits exactly /// where a fork activates in it: active at the block, not at the parent. /// /// Expected values: independent (the schedule's own timestamps and the rule). @@ -204,7 +204,7 @@ mod tests { assert!(!admits_only_deposits(&schedule, 7, Some(0), ACTIVATION - 1).unwrap()); } - /// [S1.8] [S1] Without it, a block no parent could make an activation block admits every + /// Without it, a block no parent could make an activation block admits every /// transaction: every fork active from genesis, or none active yet. Any other block is /// refused, naming the block and how to recover. /// diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index 485f5eab0..5b3d4c652 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -169,7 +169,7 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { } } -/// [S18] A block fetched over RPC replays as the chain did, is written to the block cache with +/// A block fetched over RPC replays as the chain did, is written to the block cache with /// what its replay read beyond the trace, and then replays offline from the cache. The mock /// serves the recorded responses, and the trace is the recorded pre-state as one transaction's /// sighting. The Satin replay, a counterfactual and so no activation block, reads nothing the @@ -414,7 +414,7 @@ fn assert_refused_as_activation_block(block: &mega_evme::block::CachedBlock, rec assert_eq!(blocks_of(records)[0]["refused"], txs.len() - deposits); } -/// [S1.8] [S21.12] [S1] A replayed block is told whether it admits only deposits as a node is: +/// A replayed block is told whether it admits only deposits as a node is: /// from its schedule and its parent's timestamp, which the block cache keeps beside the block. /// Under a genesis file that activates Satin at the recorded block's own timestamp, the block /// whose parent came a second earlier is Satin's activation block: its deposits run and every @@ -571,7 +571,7 @@ async fn recorded_chain(number: u64, parent: Parent) -> wiremock::MockServer { server } -/// [S1.8] [S1] A block fetched over RPC is fetched with its parent's timestamp, and the cache +/// A block fetched over RPC is fetched with its parent's timestamp, and the cache /// keeps it: under a genesis file that activates Satin at the block's timestamp, with the parent /// a second earlier, the replay refuses the block's user transactions online, writes the /// parent's timestamp to the cache, and refuses them again offline. A cached entry that lacks the @@ -624,7 +624,7 @@ async fn parent_requests(server: &wiremock::MockServer, number: u64) -> usize { .count() } -/// [S1] A cached block asks for its parent's header only when the activation-block rule needs +/// A cached block asks for its parent's header only when the activation-block rule needs /// the parent's timestamp. With the recorded entries, written before the cache kept it, and an /// endpoint that does not have the parent, the legacy replay matches the chain and the Satin /// counterfactual, whose schedule activates every fork at genesis, runs, refusing a transaction diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs index c83b99908..dc4724f03 100644 --- a/bin/mega-evme/tests/replay_paths.rs +++ b/bin/mega-evme/tests/replay_paths.rs @@ -273,7 +273,7 @@ async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { assert_eq!(held, 1, "the limits leg checks the transaction the limit held"); } -/// [S1.8] [S21.12] [S1] A transaction replay is told whether its block admits only deposits as a +/// A transaction replay is told whether its block admits only deposits as a /// node is, from the schedule and the parent block it forks. Under a genesis file that activates /// Satin at the block's timestamp, with the parent a second earlier, the block is Satin's /// activation block: a user transaction of it is refused for the rule, and its deposit replays. diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 4ed16df28..b5de70c7f 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -410,7 +410,7 @@ mod tests { /// either: the 301st pair is refused by the bound alone. One stray byte past the bound would /// prove nothing, since a length that is not a whole number of pairs fails whatever the bound. /// - /// Rule [S2.4]. Expected values `independent`: 57,600 bytes and 300 × 192 by hand, and the + /// Expected values `independent`: 57,600 bytes and 300 × 192 by hand, and the /// EIP-1108 price of 300 pairs, 45,000 + 300 × 34,000. #[test] fn test_bn254_pairing_is_bounded_at_the_karst_size() { @@ -436,7 +436,7 @@ mod tests { /// bytes, up to past the BN254 pairing's size limit — check that each price function answers /// them rather than failing on one. /// - /// Rule [S12.47]. Expected values `independent`: a price is present, whatever the input. + /// Expected values `independent`: a price is present, whatever the input. #[test] fn test_every_satin_entry_is_priced() { let lengths = diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs index 39bd503cb..0a6a04057 100644 --- a/crates/mega-evm/tests/block/activation.rs +++ b/crates/mega-evm/tests/block/activation.rs @@ -91,7 +91,7 @@ fn refuses_a_user_transaction( refused } -/// [S1.8] [S21.12] [S1] A node's context, built from its schedule and the parent's timestamp, +/// A node's context, built from its schedule and the parent's timestamp, /// refuses a user transaction in the block in which Satin or an Optimism fork at or after Jovian /// activates, and in no other block; a deposit runs in all of them. /// @@ -159,7 +159,7 @@ fn test_a_node_context_refuses_a_user_transaction_where_a_fork_activates() { } } -/// [S1] The rule follows the Optimism fork order the dependency exports: on a chain running Satin +/// The rule follows the Optimism fork order the dependency exports: on a chain running Satin /// from genesis, the block in which an Optimism fork activates refuses a user transaction exactly /// when the fork is Jovian or comes after it in [`OpHardfork::VARIANTS`], and every fork the /// dependency lists after Jovian is one. @@ -201,7 +201,7 @@ fn factory_checked(spec: MegaHardforkConfig, parent_timestamp: u64, timestamp: u committed.states().iter().any(common::is_factory_check) } -/// [S18] A node's context has the EIP-7997 factory checked in Satin's activation block and in no +/// A node's context has the EIP-7997 factory checked in Satin's activation block and in no /// other: the first block at the activation and the first after a gap over it read it; the block /// after the activation block, every block of a chain with Satin from genesis, and Jovian's /// activation block on such a chain, which admits only deposits, do not. diff --git a/crates/mega-evm/tests/block/bucket_ids.rs b/crates/mega-evm/tests/block/bucket_ids.rs index fdca164ca..62e40e206 100644 --- a/crates/mega-evm/tests/block/bucket_ids.rs +++ b/crates/mega-evm/tests/block/bucket_ids.rs @@ -225,7 +225,7 @@ fn internal_evm_error(error: &BlockExecutionError) -> B256 { } } -/// [S21.17] [S21] [S6.7] A failed bucket read is a fault of the node and gives the transaction no +/// A failed bucket read is a fault of the node and gives the transaction no /// outcome, for a deposit as for a user transaction: through the executor's own commit, each /// returns an internal error that names the transaction and the cause, and the block commits /// nothing for it — no receipt, nothing on the block's counters, no nonce bump, no mint, no write, diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index e441069ef..b2f3cbd62 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -187,7 +187,7 @@ fn test_the_pre_block_calls_record_the_parent_hash_and_the_beacon_root() { /// states the block commits show the two writes. Each limit is set alone as well as both /// together. /// -/// Rule [S19.3]. Expected values `independent`: the parent hash and the beacon root are the +/// Expected values `independent`: the parent hash and the beacon root are the /// block's own inputs, and the crossings are counted here from the writes the calls made. #[test] fn test_the_pre_block_calls_are_held_to_no_limit() { @@ -234,7 +234,7 @@ fn test_the_pre_block_calls_are_held_to_no_limit() { /// pre-block phase every counter of the block is still zero, and a block whose data-size budget is /// one byte — reached by anything counted — still admits its first transaction. /// -/// Rule [S19.7]. Expected values `independent`: zeros, and the first transaction admitted. +/// Expected values `independent`: zeros, and the first transaction admitted. #[test] fn test_the_pre_block_calls_count_towards_no_counter_or_budget() { let policy = BlockLimits::no_limits().with_block_txs_data_limit(1); diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 4753f8b20..31c19c6bd 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -123,7 +123,7 @@ fn internal(error: &BlockExecutionError) -> MegaBlockExecutionError { .clone() } -/// [S18] Over a state shaped as Rex6 leaves it, Satin's activation block and the block after it +/// Over a state shaped as Rex6 leaves it, Satin's activation block and the block after it /// deploy every system contract and find each holding Satin's code. Each pre-block step commits a /// state of its own, and a commit hook receives them in order, read-only entries included: the two /// EIP calls, which touch their contracts; in the activation block alone the factory, read only; @@ -172,7 +172,7 @@ fn test_every_block_deploys_the_system_contracts_a_rex6_chain_holds_as_read_only } } -/// [S18] A system contract the state does not hold is installed, in every block that finds it +/// A system contract the state does not hold is installed, in every block that finds it /// missing: `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl`, which a chain that never /// ran their forks lacks, each get an account holding their code, at nonce 0, marked created; the /// next block reads them as the chain then holds them. @@ -206,7 +206,7 @@ fn test_a_missing_system_contract_is_installed() { } } -/// [S18] A system contract holding other code has its code replaced by Satin's and keeps its +/// A system contract holding other code has its code replaced by Satin's and keeps its /// nonce, its balance and its storage: the Oracle at 1.0.0, which an earlier fork left with a slot /// written, becomes 2.0.0 with that slot, and `MegaLimitControl` holding foreign code gets its /// own. The account is touched and not created, which would clear the storage. @@ -241,7 +241,7 @@ fn test_a_system_contract_holding_other_code_is_rewritten_keeping_its_storage() ); } -/// [S18] Where the state holds no registry, or an account without code at its address, the block +/// Where the state holds no registry, or an account without code at its address, the block /// deploys version 2.0.0 new, seeded from the configuration's bootstrap values: the system address /// both current and initial, the configured sequencer both current and initial, the configured /// admin, the block's number as its first block and the configured minimum rotation delay. An @@ -292,7 +292,7 @@ fn test_a_registry_the_state_does_not_hold_is_seeded_from_the_bootstrap_values() } } -/// [S18] A registry at version 1.0.0 is migrated in place: its code becomes 2.0.0 and its slot 13 +/// A registry at version 1.0.0 is migrated in place: its code becomes 2.0.0 and its slot 13 /// the configured minimum rotation delay, the one slot written; its roles and every other slot are /// what they were, so the resolution names the system address it already held. /// @@ -326,7 +326,7 @@ fn test_a_registry_at_1_0_0_is_migrated_writing_slot_13_alone() { assert_eq!(slot(&mut state, MIN_ROTATION_DELAY), U256::from(BOOTSTRAP_MIN_ROTATION_DELAY)); } -/// [S18] A registry holding any other code than version 2.0.0, version 1.0.0 or none makes the +/// A registry holding any other code than version 2.0.0, version 1.0.0 or none makes the /// block invalid, with an error naming the code hash: its storage is never overwritten. The /// refusal comes at the registry's deployment, after its due-change read was committed. /// @@ -354,7 +354,7 @@ fn test_a_registry_holding_other_code_refuses_the_block() { ); } -/// [S17] A registry that names no system address — version 2.0.0 whose `_currentSystemAddress` is +/// A registry that names no system address — version 2.0.0 whose `_currentSystemAddress` is /// zero — makes the block invalid at the resolution, the last pre-block step, after the /// registry's deployment read it. /// @@ -373,7 +373,7 @@ fn test_a_registry_naming_no_system_address_refuses_the_block() { assert_eq!(named_accounts(&states), expected_accounts(false)[..RESOLUTION]); } -/// [S18] A block that must seed the registry, or migrate it from 1.0.0, on a schedule that +/// A block that must seed the registry, or migrate it from 1.0.0, on a schedule that /// carries no bootstrap values — one that skipped `validate_schedule`, which refuses it at load — /// cannot be executed: an internal error of the node, not a verdict on the block. A block whose /// registry holds version 2.0.0 needs none, and starts. @@ -401,7 +401,7 @@ fn test_a_registry_to_seed_or_migrate_without_bootstrap_values_is_an_internal_er started.expect("version 2.0.0 needs no bootstrap values"); } -/// [S18] The activation block is invalid when the EIP-7997 factory's address does not hold the +/// The activation block is invalid when the EIP-7997 factory's address does not hold the /// factory's code, with one error naming the address, the expected hash and the one held: no /// account, an account without code at a used nonce, and other code. The refusal comes after the /// two EIP calls and before anything is deployed. The block after the activation block does not @@ -458,7 +458,7 @@ fn test_an_activation_block_without_the_factory_is_refused() { } } -/// [S18] No block but Satin's activation block reads the factory: over a database that fails +/// No block but Satin's activation block reads the factory: over a database that fails /// every load of the factory's account, an ordinary block starts, where the activation block fails /// on the load as an internal error, the database's and no verdict on the block. /// @@ -488,7 +488,7 @@ fn test_no_other_block_reads_the_factory() { assert!(error.to_string().contains("injected basic() error"), "{error}"); } -/// [S18] Satin may be active from genesis, its `satinTime` at or before the genesis block's +/// Satin may be active from genesis, its `satinTime` at or before the genesis block's /// timestamp. The genesis block, which has no parent, is no activation block, whatever that time: /// it makes no EIP-2935 or EIP-4788 call and checks no factory, and on a state that holds none of /// the system contracts it installs the five and seeds the registry, at block number zero, from diff --git a/crates/mega-evm/tests/block/transfer_logs.rs b/crates/mega-evm/tests/block/transfer_logs.rs index 503366e45..bc714cedd 100644 --- a/crates/mega-evm/tests/block/transfer_logs.rs +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -227,7 +227,7 @@ fn test_a_system_transaction_receipt_logs_no_transfer() { assert!(!logs_of(receipt).iter().any(is_transfer_log), "no value moved, nothing logged"); } -/// [S14.9] [S14] The balance of an account destroyed earlier in the transaction is burned at its +/// The balance of an account destroyed earlier in the transaction is burned at its /// end without a log. A factory creates a child endowed with 17 wei whose constructor destructs to /// [`PAYEE`], moving the 17 on, then sends the destroyed child 5 wei. The receipt carries exactly /// the three transfers — the endowment, the destruction's move and the late value — and nothing diff --git a/crates/mega-evm/tests/block/witness/predeploys.rs b/crates/mega-evm/tests/block/witness/predeploys.rs index 54be56bf2..ebedf8923 100644 --- a/crates/mega-evm/tests/block/witness/predeploys.rs +++ b/crates/mega-evm/tests/block/witness/predeploys.rs @@ -65,7 +65,7 @@ fn test_a_deployment_through_the_factory_replays() { /// An ordinary block over the same chain reads the six system contracts too, every block deploying /// them, and not the factory: no check state, and no record of its account. /// -/// Rule [S22.4]. Expected values `independent`: the code is the bytecode the test put in the chain, +/// Expected values `independent`: the code is the bytecode the test put in the chain, /// and its hash is computed here. #[test] fn test_an_activation_block_replays() { diff --git a/crates/mega-evm/tests/block/witness/system.rs b/crates/mega-evm/tests/block/witness/system.rs index 040a2479d..c23fa32b3 100644 --- a/crates/mega-evm/tests/block/witness/system.rs +++ b/crates/mega-evm/tests/block/witness/system.rs @@ -96,7 +96,7 @@ fn test_a_rotation_and_a_system_transaction_replay() { /// the code the chain held for every account the block loads, the registry's included, and this /// test asserts only the loads. /// -/// Rule [S17.4]. Expected values `independent`: the registry's code hash is computed here from the +/// Expected values `independent`: the registry's code hash is computed here from the /// bytecode the test put in the chain. #[test] fn test_a_system_transaction_reads_the_live_address_from_the_witness() { diff --git a/crates/mega-evm/tests/satin/count_order.rs b/crates/mega-evm/tests/satin/count_order.rs index d85e32bff..1ba650429 100644 --- a/crates/mega-evm/tests/satin/count_order.rs +++ b/crates/mega-evm/tests/satin/count_order.rs @@ -38,7 +38,7 @@ const GAS_LIMIT: u64 = 100_000_000; /// 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 +/// 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_names_the_frame_budget() { diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index fee2364f0..961eda655 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -1095,8 +1095,6 @@ fn start_fits() -> u64 { /// under either. The log is charged nothing at all. Under the limit they cross, the frame is /// answered with the stop, which `A` catches; under the limit they fit, the frame starts and the /// records are kept. -/// -/// Rules: [S7.28], [S10.10]. #[test] fn test_a_frame_start_is_charged_before_its_records_are_counted() { let code = value_call_to_fresh(); @@ -1124,7 +1122,7 @@ fn test_a_frame_start_is_charged_before_its_records_are_counted() { ); } -/// The frame-start order, one gas short by hand [S7.28]: a caller that forwards all but 2 per cent +/// The frame-start order, one gas short by hand: 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 @@ -1267,7 +1265,7 @@ fn selfdestruct_to_c() -> Bytes { BytecodeBuilder::default().push_address(C).append(SELFDESTRUCT).build() } -/// The same rule at a child frame's write [S7.27]: the record's history is the child's to pay, +/// The same rule at a child frame's write: the record's history is the child's to pay, /// out of the gas it was forwarded, so the forward where the write is counted and the forward /// where it is kept are exactly the record's history apart, with the caller's gas out of the /// picture. The fresh slot's forward is also the sum of its parts by hand: two pushes, the @@ -1317,8 +1315,8 @@ 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 share the child was given first and spills +/// Above the cap, where a reservoir one gas short of a record's history makes the order visible, +/// 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 diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 1c2d35d0e..8e1f1a8e6 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -3,10 +3,10 @@ //! byte — and held to the limits only once every part of its deposit is charged. //! //! A creation that cannot pay one of the four runs out of gas there, alone, and the chain keeps -//! none of its code [S5.14]. Which charge it runs out on follows from where the gas comes from. +//! none of its code. Which charge it runs out on follows from where the gas comes from. //! Above the execution cap the reservoir pays the code's state gas and history, so the only //! regular charge at the deposit is the hash. Below it there is no reservoir, and the state gas -//! and then the history are paid out of regular gas after the hash [S5.13]. The regular deposit +//! and then the history are paid out of regular gas after the hash. The regular deposit //! cost is zero under EIP-8037, so it binds only on a configuration without it: the neutral one //! of Osaka, where no state gas is charged and the data-size limit is the one that holds the //! code. @@ -158,7 +158,7 @@ const B_AFTER: u64 = 2; const INIT_EXECUTION: u64 = 3 + (3 + 3 * BURNT_WORDS + BURNT_WORDS * BURNT_WORDS / 512) + 2 + 3 + 2; const _: () = assert!(INIT_EXECUTION == 5_273_613, "the init code's cost, written out"); -/// The hashing cost of the deposit: 6 gas per 32-byte word [S5.13]. +/// The hashing cost of the deposit: 6 gas per 32-byte word. const HASH: u64 = 6 * DEPLOYED_WORDS; /// Osaka's regular deposit cost: 200 gas per byte. @@ -438,13 +438,12 @@ fn assert_ledgers( /// A creation forwarded `forward` in `pool` runs out of gas at its deposit and leaves no code: /// its caller goes on, the creator's nonce record is all the transaction keeps beyond its body, /// and every ledger is what the halt leaves — the forward consumed, no state gas, the body and -/// one record of history [S5.14]. +/// one record of history. /// /// `left` is what the creation held when the charge it cannot pay was attempted — one gas less /// than that charge, or nothing — which the creation's frame still shows at its end, and which /// prices the charge; `state_charged` says whether the deposit's state gas was charged before -/// the halt, which tells a creation short of its history from one short of its state gas -/// [S5.13]. +/// the halt, which tells a creation short of its history from one short of its state gas. #[track_caller] fn assert_runs_out(name: &str, pool: Pool, forward: u64, left: u64, state_charged: bool) { let end = creation_end(pool, forward); @@ -511,7 +510,7 @@ fn assert_deposits(name: &str, pool: Pool, forward: u64) { /// Above the execution cap the reservoir pays the code's state gas and history, so the hash is /// the only regular charge of the deposit: one gas short of it the creation runs out of gas with /// no state gas charged, and one gas more deposits the code with nothing left. The boundary is -/// the init code's cost plus 6 gas per word of code, by hand (`independent`) [S5.13] [S5.14]. +/// the init code's cost plus 6 gas per word of code, by hand (`independent`). #[test] fn test_a_creation_one_gas_short_of_the_hash_runs_out_of_gas_above_the_cap() { let enough = deposits_at(Pool::AboveCap); @@ -528,7 +527,7 @@ fn test_a_creation_one_gas_short_of_the_hash_runs_out_of_gas_above_the_cap() { /// and one gas more charges the state gas and runs out on the history instead — or, where the /// deposit's history per byte is nothing and no history charge follows, deposits the code with /// nothing left. The boundary is the init code, the hash and 1,530 per byte of code, by hand -/// (`constants`: the cost per state byte in effect) [S5.13] [S5.14]. +/// (`constants`: the cost per state byte in effect). #[test] fn test_a_creation_one_gas_short_of_its_state_gas_runs_out_of_gas_with_the_hash_paid() { // A deposit that adds no state gas has no state gas to be short of. @@ -559,7 +558,7 @@ fn test_a_creation_one_gas_short_of_its_state_gas_runs_out_of_gas_with_the_hash_ /// Below the execution cap the history is the last charge of the deposit: one gas short of it /// the creation runs out of gas with its state gas charged, and one gas more deposits the code /// with nothing left. The boundary is the init code, the hash, the state gas and 88 per byte of -/// code, by hand (`constants`: the two byte prices in effect) [S5.13] [S5.14]. +/// code, by hand (`constants`: the two byte prices in effect). #[test] fn test_a_creation_one_gas_short_of_its_history_runs_out_of_gas_with_the_state_gas_paid() { // A deposit that pays no history has no history to be short of, and one that adds no state @@ -625,8 +624,6 @@ fn assert_data_size_limit_stands_aside(pool: Pool) { /// The data-size limit counts deployed code behind the same check: a creation that cannot pay the /// hash of its code, or its history, runs out of gas whatever the limit. -/// -/// Rules: [S5.14], [S7.25], [S10.12], [S10.33]. #[test] fn test_a_creation_that_cannot_pay_for_its_code_runs_out_of_gas_under_the_data_size_limit() { assert_data_size_limit_stands_aside(Pool::AboveCap); @@ -636,8 +633,6 @@ fn test_a_creation_that_cannot_pay_for_its_code_runs_out_of_gas_under_the_data_s /// Without EIP-8037 the deposit's only charge is the regular deposit cost, 200 gas per byte: a /// creation one gas short of it runs out of gas, one gas more deposits the code with nothing /// left, and a creation that cannot pay it runs out of gas whatever the data-size limit. -/// -/// Rules: [S5.13], [S5.14], [S10.12]. #[test] fn test_a_creation_that_cannot_pay_the_deposit_cost_runs_out_of_gas_under_the_data_size_limit() { let pool = Pool::NeutralOsaka; diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index e6e471756..f3b771f36 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -254,7 +254,7 @@ fn test_value_transfer_matches_op_revm() { /// child here is answered without running and spends nothing, so this does not show that a child /// can spend the whole reservoir it inherits; a child that does is held in the data-size tests. /// -/// Rule [S4.10]. Expected values: the history ledger is `constants`, the byte table at the cost +/// Expected values: the history ledger is `constants`, the byte table at the cost /// per history byte; the reservoir is an identity against the run's own state and history /// ledgers, not a figure of its own; the rest is op-revm's run (`external`). #[test] diff --git a/crates/mega-evm/tests/satin/failed_deposit.rs b/crates/mega-evm/tests/satin/failed_deposit.rs index fc0035912..7777033ad 100644 --- a/crates/mega-evm/tests/satin/failed_deposit.rs +++ b/crates/mega-evm/tests/satin/failed_deposit.rs @@ -266,7 +266,7 @@ const ABSENT: Address = address!("0000000000000000000000000000000000f00002"); /// - a user deposit from an absent sender whose gas limit covers its intrinsic gas and all but one /// gas of its caller's account, and one whose gas limit covers that account too. /// -/// Rules: [S10.15], [S11], [S5], [S4], [S21.5], [S21.7], [S5.12]. Independence: constants — the +/// Independence: constants — the /// intrinsic gas and the body are hand arithmetic from EIP-2780 and `TX_BODY_SIZE`; the caller /// account's state gas is the schedule's entry at the price in effect. #[test] diff --git a/crates/mega-evm/tests/satin/history_allowance.rs b/crates/mega-evm/tests/satin/history_allowance.rs index 6d81cdfc9..96f2a4b03 100644 --- a/crates/mega-evm/tests/satin/history_allowance.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -252,7 +252,7 @@ fn the_allowance_outweighs_a_record() -> bool { /// exactly the cost it completes. An allowance that entered the frame's gas, or that computation /// could fall back on, would carry the short hook through. /// -/// Rule [S8.4]. Expected values `independent`: the hook's cost is summed by hand from the opcode +/// Expected values `independent`: the hook's cost is summed by hand from the opcode /// prices, which no byte price moves, and the exact run is the control that the sum is the hook's /// whole cost; the allowance and a record's history are the spec's 160 and 40 bytes at the cost /// per history byte in effect (`constants`), and at the spec's prices 14,080 and 3,520, written @@ -350,7 +350,7 @@ fn writes_slot_zero() -> Bytes { /// The slot is not fresh, so the write charges no state gas: the record's history is the only /// charge past the regular gas, and the only one the allowance could have paid. /// -/// Rule [S8.3]. Expected values `independent`: the write's regular gas is the schedule's table by +/// Expected values `independent`: the write's regular gas is the schedule's table by /// hand — `PUSH1` 3, `PUSH0` 2, and an `SSTORE` that resets a cold slot, 100 static, 10,000 for /// the reset and 2,000 for the cold load — which no byte price moves; the record's history is 40 /// bytes at the cost per history byte in effect (`constants`), 3,520 at 88 gas a byte, written @@ -391,7 +391,7 @@ fn test_the_allowance_cannot_be_spent_on_a_write_record() { /// byte — the short hook would run out on the record whether or not the allowance paid its state /// gas, and the test returns early with a note. /// -/// Rule [S8.5]. Expected values `independent`: the write's regular gas is the schedule's table by +/// Expected values `independent`: the write's regular gas is the schedule's table by /// hand — `PUSH1` 3, `PUSH0` 2, and an `SSTORE` that fills a cold fresh slot, 100 static, 10,000 /// for the fresh slot and 2,000 for the cold load — which no byte price moves; the slot's state /// gas at the minimum bucket is the schedule's entry and the record's history 40 bytes at the cost diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index e49d90bf1..258663421 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -360,10 +360,10 @@ const ANSWERING: u64 = 2 + 2 + 3 + 3 + 3 + 2; const INTRINSIC: u64 = 12_000 + 3_000; /// The body's history gas is taken from the reservoir first, and only its excess from the regular -/// budget [S4.4]; a reservoir short of the body is spent to the last gas, one of exactly the body -/// too, and one a gas larger keeps that gas [S4.7]. A body-only transaction shows it: the first +/// budget; a reservoir short of the body is spent to the last gas, one of exactly the body +/// too, and one a gas larger keeps that gas. A body-only transaction shows it: the first /// frame's `GAS` is the regular budget — the execution cap less the intrinsic gas, less the -/// excess the reservoir did not cover, less the `GAS` itself — and not the reservoir [S4.8]. +/// excess the reservoir did not cover, less the `GAS` itself — and not the reservoir. /// /// Every figure is by hand (`constants`: the execution cap and the body's history at the price in /// effect, which is 310 × 88 at the spec's price): the regular ledger is the intrinsic gas and @@ -417,7 +417,7 @@ fn test_the_body_draws_the_reservoir_first_and_only_its_excess_from_regular_gas( /// 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 +/// intrinsic. 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 diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 18db95d58..65d83ad4d 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -302,7 +302,7 @@ fn test_the_execution_cap_bounds_the_calldata_a_transaction_may_carry() { /// A floor above the transaction's own gas limit is rejected too, below the cap: the floor is /// measured against whichever of the two is smaller. The rejection leaves the sender as it was. /// -/// Rules: [S4.26], [S21.1], [S21.2]. Independence: independent — the base, the floor's rate and the +/// Independence: independent — the base, the floor's rate and the /// sender's funding are written out. #[test] fn test_a_floor_above_the_gas_limit_is_rejected() { @@ -385,7 +385,7 @@ fn test_a_creation_that_cannot_pay_its_account_runs_out_of_gas() { /// Whether the error should name one figure in both cases is undecided, so a change to it is not /// a change of the rules this test holds: the rejection, and a sender left untouched. /// -/// Rules: [S4.25], [S21.1]. Independence: independent — the intrinsic charge and the sender's +/// Independence: independent — the intrinsic charge and the sender's /// funding are written out. #[test] fn test_a_gas_limit_below_the_intrinsic_charge_is_rejected() { @@ -419,7 +419,7 @@ fn test_a_valid_call_still_passes() { /// is undecided, so a change to it is not a change of the rules this test holds: the rejection, a /// sender left untouched, and a gas limit of the whole minimum admitted. /// -/// Rules: [S4.25], [S7.17], [S21.1]. Independence: independent for the intrinsic charge and the +/// Independence: independent for the intrinsic charge and the /// sender's funding, which are written out; the body's history is priced by the production /// helper. #[test] diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index a8dd8208f..fbba99224 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -123,7 +123,7 @@ fn test_a_system_transaction_is_held_to_no_limit() { /// and the layer reports what it used: its body, three slots' records and the log, in data size, /// and the three records in the KV count. /// -/// Rule [S19.5]. Expected values `independent`: the spec's byte table by hand — a body of 310 +/// Expected values `independent`: the spec's byte table by hand — a body of 310 /// bytes, 40 a record, and a log's 32 bytes of base and its 64 bytes of data. #[test] fn test_a_system_call_is_held_to_no_limit() { diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 5a4ab25da..d1cf6a763 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -334,8 +334,8 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { } /// The SALT scaling section says what it claims: on each probe the regular ledger and the -/// history ledger are the same at every multiplier [S6.5] — history gas is not scaled by SALT -/// [S7.2] — and the state ledger is the minimum bucket's times the multiplier. Read off the +/// history ledger are the same at every multiplier — history gas is not scaled by SALT +/// — and the state ledger is the minimum bucket's times the multiplier. Read off the /// rendered table rather than the engine, so the table cannot drift from the claim above it /// (`constants`: the relation across `m` is the spec's; the `m` = 1 row is the table's own). #[test] diff --git a/crates/mega-evm/tests/satin/reservoir_drain.rs b/crates/mega-evm/tests/satin/reservoir_drain.rs index 44bf1daeb..f389bc096 100644 --- a/crates/mega-evm/tests/satin/reservoir_drain.rs +++ b/crates/mega-evm/tests/satin/reservoir_drain.rs @@ -1198,7 +1198,7 @@ fn run_with(scenario: Scenario, work: Option) -> Measured { }; let p = &prediction; - // The reservoir is the gas limit above the execution cap, less the body [S4.4]. + // The reservoir is the gas limit above the execution cap, less the body. assert_eq!( meter.at_call, Some(Pools::new(p.regular_at_call, p.reservoir_at_call)), diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 690414e18..ab04bd2fc 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -254,9 +254,9 @@ pub(crate) fn ledgers_at( (outcome.gas.state, outcome.gas.regular, outcome.gas.history) } -/// Pins one charge site at the minimum bucket and at `m` = 2 and 8 [S6.4]: the state ledger is +/// Pins one charge site at the minimum bucket and at `m` = 2 and 8: the state ledger is /// `unscaled × m` at every multiplier, and neither the regular ledger nor the history ledger -/// moves [S6.5] — history gas is not scaled by SALT [S7.2]. +/// moves — history gas is not scaled by SALT. /// /// The history ledger is anchored at `m` = 1 to `history_bytes`, the site's bytes from the byte /// table by hand, at the cost per history byte in effect (`constants`); at `m` = 2 and 8 it is @@ -287,8 +287,6 @@ pub(crate) fn assert_scales( /// `SSTORE` onto a slot that was zero: the slot's own bucket prices it. The history is the body /// and the slot's record. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_sstore_set_charge_scales_with_the_slot_s_bucket() { const SLOT: u64 = 7; @@ -307,8 +305,6 @@ fn test_the_sstore_set_charge_scales_with_the_slot_s_bucket() { /// A `CALL` carrying value to an account that does not exist: the account's bucket prices it. The /// history is the body and the transfer's two records, the sender's and the recipient's. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { assert_scales( @@ -325,8 +321,6 @@ fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { /// pays, reached from the opcode that empties an account rather than the one that funds it. The /// 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] fn test_the_selfdestruct_beneficiary_charge_scales_with_the_beneficiary_s_bucket() { assert_scales( @@ -341,8 +335,6 @@ fn test_the_selfdestruct_beneficiary_charge_scales_with_the_beneficiary_s_bucket /// `CREATE`: the bucket of the address it deploys to prices the account it adds. The history is /// the body and the creation's two records, the creator's nonce and the created account; the /// deployed code is empty. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_create_charge_scales_with_the_created_address_s_bucket() { let created = CONTRACT.create(0); @@ -358,8 +350,6 @@ fn test_the_create_charge_scales_with_the_created_address_s_bucket() { /// The EIP-2780 runtime phase charges the transaction's own recipient before the first frame, /// and reads the recipient's bucket to price it. The history is the body and the recipient's /// record; the sender is in the body. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_top_level_recipient_charge_scales_with_the_recipient_s_bucket() { assert_scales( @@ -374,8 +364,6 @@ fn test_the_top_level_recipient_charge_scales_with_the_recipient_s_bucket() { /// The same phase charges a creation transaction's target, in the target's own bucket. The /// history is the body, the three bytes of init code it carries as calldata, and the created /// account's record. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_create_transaction_target_charge_scales_with_its_bucket() { const INIT: [u8; 3] = [PUSH0, PUSH0, RETURN]; @@ -392,8 +380,6 @@ fn test_the_create_transaction_target_charge_scales_with_its_bucket() { /// An EIP-7702 authorization on an authority that does not exist pays for the account leaf it /// adds and for the delegation bytes it writes, both in the authority's bucket. The history is /// the body, the authorization it carries, and the applied authority's record. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_eip7702_authority_charges_scale_with_the_authority_s_bucket() { assert_scales( @@ -408,8 +394,6 @@ fn test_the_eip7702_authority_charges_scale_with_the_authority_s_bucket() { /// Deployed code is charged per byte, in the bucket of the address it is deployed to — the same /// bucket that priced the creation itself. The history is the body, the init code it carries as /// calldata, the created account's record and the deployed bytes. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_code_deposit_charge_scales_with_the_deployed_address_s_bucket() { const DEPLOYED: u64 = 32; @@ -868,8 +852,6 @@ fn test_clearing_a_slot_charges_no_state_gas() { /// A slot is one leaf however many times the transaction writes it: the first write off zero /// pays, the rest pay nothing. It is one record too. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_a_slot_written_twice_pays_for_one_leaf() { let set = entry(GasId::sstore_set_state_gas()); @@ -949,8 +931,6 @@ fn test_a_selfdestruct_that_adds_no_account_charges_no_state_gas() { /// `CREATE2` reaches its deployment address by hashing rather than by nonce, and is priced in /// that address's bucket just as `CREATE` is. Its history is `CREATE`'s: the body and the two /// records of the creation. -/// -/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_create2_charge_scales_with_the_created_address_s_bucket() { const SALT: U256 = U256::ZERO; diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 2307ab6df..b9cfbe4f8 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -484,7 +484,7 @@ fn test_authorities_whose_records_would_cross_the_data_size_limit_reject_the_tra /// crossed by the record of the slot the frame writes after the authority's record and, with value, /// after its own start's record and transfer log. /// -/// Rules: [S11.8], [S11.14]. Independence: constants — the limit is the byte table's sizes; what +/// Independence: constants — the limit is the byte table's sizes; what /// the authority keeps is compared with a run whose frame does nothing. #[test] fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { @@ -534,7 +534,7 @@ fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { /// deposit's mint and the state gas charged for the account. The stop is the data-size limit, /// crossed by the record of the slot the deposit's frame writes. /// -/// Rules: [S11.13]. Independence: constants — the limit is the byte table's sizes, the caller's +/// Independence: constants — the limit is the byte table's sizes, the caller's /// account the schedule's entry. #[test] fn test_a_stopped_deposit_keeps_the_caller_it_created() { @@ -584,8 +584,8 @@ fn test_a_destruction_to_itself_grows_no_state() { /// back. /// /// 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` +/// records the frame makes, after the gas it forwards is computed; one gas short of what +/// the start costs in all is an out-of-gas too, and the frame does not start. A `CREATE` /// 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 diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 86d3122e6..929b6a2c2 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -450,7 +450,7 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { /// the transaction succeeds, keeping what they did and nothing of the frame that crossed; at the /// transaction's own frame the stop is the transaction's result. /// -/// Rules: [S11.1], [S11.2], [S11.3], [S11.4], [S11.6], [S11.7], [S11.8]. Independence: constants +/// Independence: constants /// for every limit and the stop it reports, and engine-derived for the bill, which a twin run sets. #[test] fn test_every_limit_stops_the_frame_that_crosses_it_at_every_depth_and_tier() { @@ -487,7 +487,7 @@ impl Inspector, EthInterpreter> for Halter { /// 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`. +/// Independence: constants — the body is `TX_BODY_SIZE`. #[test] fn test_an_inspector_that_rewrites_a_stop_into_a_halt_gets_the_halt() { let halts = [ @@ -1478,7 +1478,7 @@ fn test_detained_gas_is_restored() { /// | `B`'s `SSTORE` of the slot it warmed: static and the storage write | 10,100 | /// | `A`'s `POP` of the call's status | 2 | /// -/// Rules: [S11.8], [S11.9]. Independence: independent — the parts are written out; the body's +/// Independence: independent — the parts are written out; the body's /// history is priced by the production helper. #[test] fn test_data_limit_exceed_in_nested_call() { diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index 4d1073bd6..46e89827a 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -1512,7 +1512,7 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { } } -/// EIP-7708 logs keep execution order. [S14.3] +/// EIP-7708 logs keep execution order. /// /// independent: each expected log is the event the bytecode emits, or the transfer of the wei /// the program moves, built from those accounts and that amount. diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index 60534e67c..f32a5221c 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -327,7 +327,7 @@ fn test_the_system_address_is_not_detained() { ); } -/// A user's deposit is detained. [S12.51] [S19.8] +/// A user's deposit is detained. /// /// independent: the cap, the compute at the read and the bill are the spec's own numbers. /// The cap is 20,000,000. diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index 4f1c837bc..0fcdf7ea0 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -268,7 +268,7 @@ fn test_the_sstore_sentry_reads_the_whole_regular_gas() { /// The sender pays what the receipt reports at the gas price, and the beneficiary is credited it; /// the same transaction without the read settles the same way. /// -/// Rules: [S12.34], [S12.42], [S12]. Independence: independent — every charge is the opcode's +/// Independence: independent — every charge is the opcode's /// price, the refund and its cap are EIP-3529's, the intrinsic gas is EIP-2780's, and the body's /// history is `TX_BODY_SIZE` at the cost per history byte in effect. #[test] @@ -623,7 +623,7 @@ const CALL_INTRINSIC: u64 = 12_000 + 3_000; /// 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 — every charge is the opcode's price, the +/// 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_burns_what_its_frame_had() { @@ -700,7 +700,7 @@ struct StaticHalts { /// 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 +/// 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] diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index de01a3cfe..d2621492e 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -944,7 +944,7 @@ enum FeeRowPath { /// A record weighs `WRITE_RECORD_SIZE` bytes of data size and history and is one KV update; the /// history is its bytes at the cost per history byte, on top of the body's `TX_BODY_SIZE`. /// -/// Rules: [S10.17], [S10.19], [S10.22], [S10.28], [S10.29], [S7], [S10]. Independence: constants — +/// Independence: constants — /// the record counts are written out per row, and the data size, KV count and history are hand /// arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE`, `TRANSFER_LOG_SIZE` and the cost per /// history byte in effect. diff --git a/crates/mega-evm/tests/system/access_control.rs b/crates/mega-evm/tests/system/access_control.rs index 98cd1f140..689c9fd13 100644 --- a/crates/mega-evm/tests/system/access_control.rs +++ b/crates/mega-evm/tests/system/access_control.rs @@ -500,7 +500,7 @@ fn test_oracle_sload_reverts_when_volatile_access_disabled() { /// timestamp, which the parent returns. The parent logs the address `CREATE` left, zero for a /// failed creation. /// -/// Rule [S13.2]. Expected values `constants`: the revert data is decoded with the contract's own +/// Expected values `constants`: the revert data is decoded with the contract's own /// error binding, and the access type is the one the init code reads. #[test] fn test_create_reverts_when_volatile_access_disabled() { diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 8c91f97fe..cd59e8459 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -317,7 +317,7 @@ fn test_a_failed_deployment_gives_the_created_account_back_at_its_price() { /// `CREATE` opcode's regular gas, the created account and one record short of what it had after /// its overhead; sent by a relayer for a signer holding a wei, one record more. /// -/// Rule [S15.22]. Expected values `constants`: the charges are the schedule's `create`, initcode +/// Expected values `constants`: the charges are the schedule's `create`, initcode /// and created-account entries and one record's history at the cost per history byte; what the /// call has after its overhead is set by the test on a gas limit built by hand — the call's /// EIP-2780 intrinsic, its calldata's cost, its body's history and the keyless overhead — so an diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 758e86397..32c3c03af 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -742,7 +742,7 @@ fn test_keyless_deploy_not_intercepted_for_inner_calls() { /// A call answered without the bytecode — refused by an interceptor, or run as a deployment that /// fails — could fail the same way, but not with the four bytes of `NotIntercepted()`. /// -/// Rule [S15.3]. Expected values `independent`: the error's selector is computed here from its +/// Expected values `independent`: the error's selector is computed here from its /// signature, `NotIntercepted()`, not taken from the contract's binding. #[test] fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 3e39599bd..0c6808565 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -360,7 +360,7 @@ fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { /// call's gas used is its whole gas limit too. Neither creation started, so the signer's nonce is /// unspent. /// -/// Rules [S15.8], [S15.22]. Expected values `independent`: the gas limit is the transaction's own, +/// Expected values `independent`: the gas limit is the transaction's own, /// and the empty ledgers are zero; the body's history is the schedule's price of its bytes /// (`constants`). #[test] diff --git a/crates/mega-evm/tests/system/predeploys.rs b/crates/mega-evm/tests/system/predeploys.rs index 5fb84f78c..b0d010ec3 100644 --- a/crates/mega-evm/tests/system/predeploys.rs +++ b/crates/mega-evm/tests/system/predeploys.rs @@ -23,7 +23,7 @@ fn test_the_factory_code_hashes_to_its_pinned_hash() { assert_eq!(keccak256(CREATE2_FACTORY_CODE), CREATE2_FACTORY_CODE_HASH); } -/// [S18.8] The list is the six `MegaETH` contracts in address order, then the factory, each with +/// The list is the six `MegaETH` contracts in address order, then the factory, each with /// the code hash of its code, and the public address list is the list's addresses in that order. /// /// Expected values: constants (the addresses and code hashes are the production constants). @@ -57,7 +57,7 @@ fn spec_at(address: Address) -> SystemContractSpec { .expect("the address is a predeploy") } -/// [S18] An address holding the expected code passes whatever else it holds — the nonce mainnet's +/// An address holding the expected code passes whatever else it holds — the nonce mainnet's /// six hold (0), the factory's (in the thousands), a balance, storage — and the check returns the /// account as a read-only entry, as held: neither touched nor created, no storage, the nonce kept. /// @@ -83,7 +83,7 @@ fn test_the_expected_code_is_read_as_it_is() { } } -/// [S18] Anything but the expected code is refused with the one error, naming the address, the +/// Anything but the expected code is refused with the one error, naming the address, the /// expected hash and the one held: no account, an account without code — funded, or at a used /// nonce — an older version of the contract, another contract's version and other code. Satin /// creates and upgrades nothing. diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index e601a1316..e45ebbec5 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -749,7 +749,7 @@ fn deposit_one_short_of_its_caller(sender: Address) -> MegaTransaction { /// first frame, and a deposit that does is a failed deposit: the `FailedDeposit` halt, not an /// out-of-gas, billed its whole gas limit. /// -/// Rules: [S5], [S21.5], [S21.7], [S5.12]. Independence: constants — the intrinsic gas is +/// Independence: constants — the intrinsic gas is /// EIP-2780's, the caller account's state gas the schedule's entry at the price in effect. #[test] fn test_a_deposit_that_cannot_pay_for_its_caller_is_a_failed_deposit() { @@ -776,7 +776,7 @@ fn test_a_deposit_that_cannot_pay_for_its_caller_is_a_failed_deposit() { /// the data-size limit does not waive the charge: a deposit that cannot pay for it is a failed /// deposit, which reports the failure and not the data-size stop, and keeps its body counted. /// -/// Rules: [S11], [S10.15], [S21.7]. Independence: constants — the body is `TX_BODY_SIZE`, the gas +/// Independence: constants — the body is `TX_BODY_SIZE`, the gas /// limit as [`deposit_one_short_of_its_caller`] works it out. #[test] fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_is_a_failed_deposit() { diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs index 7a612d7d3..85d5208cd 100644 --- a/crates/mega-state-test/src/blockchain/chain.rs +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -506,7 +506,7 @@ mod tests { ); } - /// [S10] The schedule the chain runs on loads, and the blocks are held to no limit: + /// The schedule the chain runs on loads, and the blocks are held to no limit: /// equivalence mode takes out every one `MegaETH` sets. /// /// Expected values: constants (no limit at all). @@ -519,7 +519,7 @@ mod tests { assert_eq!(limits().block_txs_data_limit, u64::MAX); } - /// [S1.8] [S21.12] [S1] A block's context says whether it admits only deposits, from the + /// A block's context says whether it admits only deposits, from the /// schedule and the head's timestamp, as a node works it out. Under a schedule that activates /// Satin at the block's timestamp, with the genesis a second earlier, the block is Satin's /// activation block: a user transaction in it is refused, and the block without it is From 59df5eeb6bd3c51165cf370d04b263d9c29cd3f7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 16:10:04 +0800 Subject: [PATCH 087/190] test(evm): a precompile crossing gives the empty account's state gas back --- crates/mega-evm/tests/satin/detained_transfers.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 30df02889..50bf33ff5 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -342,6 +342,9 @@ fn test_a_precompile_answered_from_its_price_at_a_data_size_boundary_is_the_comp "{case}: the call's answer" ); assert_eq!(balance(&run, MODEXP), U256::ZERO, "{case}: nothing moved"); + // The opcode charged the empty account's state gas before the price; the crossing + // gives it back. + assert_eq!(run.outcome.gas.state, 0, "{case}: the new account's state gas came back"); let body_alone = LimitUsage { data_size: body, write_records: 0, state_growth: 0 }; assert_eq!(run.outcome.usage, body_alone, "{case}"); } From 527cf26336640909f41001d407b95741d3d7ff13 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 16:10:53 +0800 Subject: [PATCH 088/190] docs: state the specification's clarifications of the cold destruction, the refund counter, the cold store and the precompile charges --- docs/spec/upgrades/satin.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index b25e5bb3f..badf56b5a 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -287,6 +287,7 @@ Regular-gas entries that EIP-8038 or EIP-8037 reprice, and the other entries tha | ---------------------------------------------------- | ------ | ------- | | Warm storage read | 100 | 100 | | Cold account access, additional | 2,500 | 2,900 | +| Cold `SELFDESTRUCT` beneficiary, the whole access | 2,600 | 3,000 | | Cold storage access of an `SLOAD`, additional | 2,000 | 2,000 | | Cold storage access of an `SSTORE` | 2,100 | 2,000 | | Value transfer of a call, with its 2,300 stipend | 9,000 | 11,300 | @@ -321,6 +322,10 @@ Regular-gas entries that EIP-8038 or EIP-8037 reprice, and the other entries tha The warm read, the `SLOAD` cold surcharge and the `SSTORE` static cost are EIP-8038's own values and Osaka's alike. EIP-8038 folds the warm base into a cold slot's access, so a cold `SSTORE` pays 2,100 for it with its static cost, as a cold `SLOAD` does. +The static 100 MUST be a charge of its own, made before the slot is loaded. +The 2,000 cold rest MUST be charged after the load, in one charge with the cost of the write, so gas detention holds the two charges to the spendable part one after the other. +An opcode whose static gas is the warm read pays the additional cold account access for an account that is not warm. +`SELFDESTRUCT`'s static gas holds no warm read, so a beneficiary that is not warm costs it the whole 3,000 (2,900 plus 100), as EIP-2929 charges it. Under EIP-2780 the floor's base is not the 12,000 entry: it MUST be the transaction's own decomposed base (below) without its calldata, access-list, authorization and initcode costs, which is 12,000 for a transfer to the sender itself, 15,000 for a call to another account without value, 21,000 for one with value, and 24,000 for a creation. The floor is that base plus 64 gas per calldata byte, zero or non-zero, a creation's initcode included, and 64 gas per access-list byte, 20 bytes for an address and 32 for a storage key. @@ -745,6 +750,7 @@ 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. +The mark MUST NOT change what such an `SSTORE` does to the EIP-3529 refund counter: a store that clears the slot or restores its original value moves the counter by the inherited `SSTORE` rules, on the slot's original, present and new values, as it would without the mark. 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. @@ -993,6 +999,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th 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 its regular gas had to pay. 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. + A precompile that halts on a check it makes after its gas charge, a ModExp input over EIP-7823's bound among them, burns its whole forward the same way, its charged price and a value call's stipend included, and none of it is compute. - **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)). @@ -1019,7 +1026,10 @@ A contract can revert with the same bytes, and so can a caller that re-raises th - **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. + The forward the price is held against is the child's whole regular gas, a value call's 2,300 stipend included. The value has not moved when the price is consulted, so the call MUST be held to the price alone: the crossing is the stop, kind 2, whatever records its value transfer would have made (see [Resource Limits](#10-resource-limits)). + A value call to a precompile whose account the state does not hold, or holds empty under EIP-161, pays that account's new-account state gas in the opcode, before its forward is computed and before the price is consulted. + When the call is the crossing, the account is not created, and that charge, its legacy share included, MUST be given back into the caller's reservoir when the stop returns. Every precompile of the Satin set has a price for every input: an input over an Optimism pairing or MSM size limit is priced at zero, since it is refused before any gas check, and a ModExp input is priced by its Osaka formula whatever its lengths, one over EIP-7823's bound included, since ModExp charges that price before it checks the bound. An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check — a ModExp input over EIP-7823's bound among them — is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. From c55b3b7e777944b0e61b076e9e341875f8a56c33 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 17:14:35 +0800 Subject: [PATCH 089/190] fix(evm): results the engine builds carry the configured give-back mode --- AGENTS.md | 3 +- REVIEW.md | 2 +- crates/mega-evm/src/evm/execution.rs | 64 ++-- crates/mega-evm/src/evm/frame.rs | 109 ++++-- crates/mega-evm/src/evm/mod.rs | 6 +- crates/mega-evm/src/system/AGENTS.md | 4 +- crates/mega-evm/src/system/control.rs | 12 +- crates/mega-evm/src/system/intercept.rs | 15 +- .../mega-evm/src/system/keyless/dispatch.rs | 12 +- crates/mega-evm/src/system/limit_control.rs | 5 +- crates/mega-evm/src/system/oracle.rs | 3 +- crates/mega-evm/tests/satin/history_bytes.rs | 6 +- .../mega-evm/tests/satin/inspector_limits.rs | 11 +- .../tests/satin/inspector_settlement.rs | 17 +- crates/mega-evm/tests/satin/salt_refund.rs | 5 +- .../tests/satin/synthetic_frame_gas.rs | 337 +++++++++++++++++- ...erential__keyless_differential_record.snap | 6 +- 17 files changed, 528 insertions(+), 89 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2ca38bc70..8c7fe759c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -534,8 +534,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **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'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 of regular gas — a child's return, and under EIP-8037's own give-backs `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 inherited reservoir.** +- **Synthetic frame results carry the inherited reservoir and the configured give-back mode.** A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so revm's own frame return settles it exactly like a result of its own; it settles on its start's entry of the start ledger by status, budgets and start charge alike, so it carries neither. + Its gas takes the give-back mode from the execution's configuration (`Cfg::reservoir_only_give_backs`: on under Satin's, off under the neutral one), as revm sets it on the gas of every frame it builds, so the builders take the configuration and every tracker the engine builds — an interceptor's or the keyless dispatch's answer, the depth guard's, a stop the engine answers a frame or an answer with — carries the mode before an inspector sees it; an inspector's own answer or tracker is taken as given. - **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`). diff --git a/REVIEW.md b/REVIEW.md index 049281aa4..560fbb60e 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -37,7 +37,7 @@ Defer to the baseline for everything not listed here; the rules below take prece 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. - **Pools and ledgers stay aligned with frames.** - A frame's budgets are on its start's entry of the engine's start ledger, which revm's start lifecycle opens and settles (`limit/ledger.rs`); `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 inherited reservoir (`synthetic_frame_result`), never `Gas::new(limit)`, and settles on its start's budgets and start charge by status. + A frame's budgets are on its start's entry of the engine's start ledger, which revm's start lifecycle opens and settles (`limit/ledger.rs`); `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 inherited reservoir (`synthetic_frame_result`), never `Gas::new(limit)`, and the configuration's give-back mode, and settles on its start's budgets and start charge by status. 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.** diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 96ee393cc..afaa8aade 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -23,7 +23,7 @@ use revm::{ context::{ result::{FromStringError, InvalidTransaction, ResultGas}, transaction::TransactionType, - ContextError, ContextTr, FrameStack, Journal, JournalTr, Transaction, + Cfg, ContextError, ContextTr, FrameStack, Journal, JournalTr, Transaction, }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, @@ -40,7 +40,7 @@ use revm::{ inspector::{InspectorEvmTr, InspectorHandler, JournalExt}, interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, interpreter_types::LoopControl, - CallScheme, CallValue, FrameInput, Gas, InitialAndFloorGas, InstructionResult, + CallScheme, CallValue, FrameInput, InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, }, primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, @@ -49,7 +49,9 @@ use revm::{ use crate::{ access::ComputeStop, - charge_write_records_history, history_gas, + charge_write_records_history, + evm::frame::frame_gas, + history_gas, limit::{CreatorBefore, StartBefore}, synthetic_frame_result, system::{keyless, Answer}, @@ -629,7 +631,7 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm( } /// The answer to the precompile call `input` starts when its price crosses gas detention's limit -/// ([`PrecompileHold::Crossing`]): out of gas without running, the forward untouched, and marked -/// as the crossing ([`Detention::cross_at_price`]). +/// ([`PrecompileHold::Crossing`]), built under `cfg`: out of gas without running, the forward +/// untouched, and marked as the crossing ([`Detention::cross_at_price`]). #[cold] #[inline(never)] -fn crossing_answer(input: &FrameInput) -> FrameResult { - let mut answer = synthetic_frame_result(input, InstructionResult::PrecompileOOG, Bytes::new()); +fn crossing_answer(cfg: &impl Cfg, input: &FrameInput) -> FrameResult { + let mut answer = + synthetic_frame_result(cfg, input, InstructionResult::PrecompileOOG, Bytes::new()); Detention::cross_at_price(answer.interpreter_result_mut()); answer } @@ -1382,23 +1385,23 @@ fn stop_the_answer_at( ) { if verdict.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&verdict); - stop_the_answer(answer, start, output); + stop_the_answer(ctx.cfg(), answer, start, output); ctx.additional_limit.ledger_mut().rebuild_on_shares(); } } /// 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 the call inherited, and no precompile -/// output, as [`synthetic_frame_result`] answers a frame that never started. Its budgets go back -/// to the shares the call started with on the start ledger -/// (`StartLedger::rebuild_on_shares`). +/// call's caller forwarded, untouched, with the reservoir the call inherited and the give-back +/// mode of `cfg`, the execution's configuration, and no precompile output, as +/// [`synthetic_frame_result`] answers a frame that never started. Its budgets go back to the +/// shares the call started with on the start ledger (`StartLedger::rebuild_on_shares`). #[cold] #[inline(never)] -fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) { +fn stop_the_answer(cfg: &impl Cfg, 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 gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); + let gas = frame_gas(cfg, start.gas_limit, start.reservoir); outcome.result = InterpreterResult::new(InstructionResult::Revert, output, gas); outcome.was_precompile_called = false; outcome.precompile_call_logs.clear(); @@ -1414,7 +1417,12 @@ fn stop_before_the_first_frame( ) -> 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)) + Some(synthetic_frame_result( + ctx.cfg(), + &frame_init.frame_input, + InstructionResult::Revert, + output, + )) } /// Decides the transaction's EIP-7702 authorization list before it is applied, as the spec has @@ -1515,7 +1523,8 @@ fn simulate_authorization_list( } /// The depth guard: a frame past the call-stack limit, of any call scheme or a creation, answered -/// with `CallTooDeep`, its gas untouched and its reservoir carried — the answer revm gives it. +/// with `CallTooDeep`, its gas untouched, its reservoir carried and the give-back mode of `cfg`, +/// the execution's configuration — the answer revm gives it. /// /// 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 @@ -1527,9 +1536,10 @@ fn simulate_authorization_list( /// No transaction reaches the limit: regular gas is capped by the execution cap and every call /// 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 { +fn call_too_deep(cfg: &impl Cfg, frame_init: &FrameInit) -> Option { (frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { synthetic_frame_result( + cfg, &frame_init.frame_input, InstructionResult::CallTooDeep, Bytes::new(), @@ -1688,15 +1698,17 @@ mod tests { use super::*; use crate::{ limit::{PoolAmounts, PoolId}, + spec_cfg, test_utils::MemoryDatabase, MegaSpecId, }; use alloy_primitives::{address, U256}; use revm::{ + context::CfgEnv, context_interface::journaled_state::account::JournaledAccountTr, interpreter::{ gas::WithheldCrossing, CallInput, CallInputs, CallValue, CreateInputs, CreateScheme, - SharedMemory, + Gas, SharedMemory, }, }; use std::boxed::Box; @@ -1897,14 +1909,17 @@ mod tests { } /// The answer to a call whose price crosses the limit is out of gas without running, with its - /// forward untouched and the crossing recorded with the forward. + /// forward untouched, the crossing recorded with the forward, and the give-back mode of the + /// configuration it is built under. #[test] fn test_a_crossing_answer_is_marked_with_its_forward() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); for forward in [1, 100_000, 3_000_000] { let input = static_call(crate::kzg_point_evaluation::ADDRESS, &[0; 32], forward); - let FrameResult::Call(answer) = crossing_answer(&input.frame_input) else { + let FrameResult::Call(answer) = crossing_answer(ctx.cfg(), &input.frame_input) else { panic!("a call's answer") }; + assert!(answer.result.gas.reservoir_only_give_backs(), "Satin's give-backs"); assert!(!answer.was_precompile_called, "answered without running"); assert_eq!(answer.result.result, InstructionResult::PrecompileOOG); assert_eq!(answer.result.gas.limit(), forward); @@ -1957,10 +1972,11 @@ mod tests { fn test_an_answer_switches_access_off_only_when_it_does_not_cross() { use crate::{constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, system::Answer}; const FORWARD: u64 = 90_000_000; + let cfg = spec_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN)); let answer = |spent: u64, disables_access_from| { let input = static_call(TARGET, &[], FORWARD).frame_input; let mut result = - synthetic_frame_result(&input, InstructionResult::Return, Bytes::new()); + synthetic_frame_result(&cfg, &input, InstructionResult::Return, Bytes::new()); assert!(result.gas_mut().record_regular_cost(spent)); Answer { result, disables_access_from } }; @@ -2007,7 +2023,7 @@ mod tests { 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()); + let answer = synthetic_frame_result(ctx.cfg(), &value_call(), result, Bytes::new()); take_back_a_stopped_answer(&mut ctx, start, succeeded, &answer); let nonce = ctx.journal_ref().state.get(&TARGET).map_or(0, |a| a.info.nonce); assert_eq!(nonce, u64::from(!taken_back), "{case}"); diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 52b695224..cc842ce00 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -18,12 +18,17 @@ //! 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`], [`untouched_create_gas`]), never //! `Gas::new(limit)`, which would carry no reservoir, billing the sender for the whole reservoir; -//! and it carries the calling opcode's upfront-charge flags, so step 1 refunds them. The budgets -//! and the start charge are the start ledger's, which the engine's own answers settle on by -//! status, so nothing of them is carried. [`synthetic_frame_result`] builds one. +//! its gas gives back where the execution's configuration says, as the gas of every frame revm +//! builds does: into the reservoir alone under Satin's give-backs, as EIP-8037 has it under the +//! neutral configuration's (`Cfg::reservoir_only_give_backs`), so an inspector that charges and +//! gives back on the result's gas sees the same rule whoever built the result; and it carries the +//! calling opcode's upfront-charge flags, so step 1 refunds them. The budgets and the start charge +//! are the start ledger's, which the engine's own answers settle on by status, so nothing of them +//! is carried. [`synthetic_frame_result`] builds one. use alloy_primitives::Bytes; use revm::{ + context::Cfg, handler::FrameResult, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, @@ -31,32 +36,44 @@ 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. +/// The gas of a frame built under `cfg` with `limit` of regular gas unspent and `reservoir`: its +/// give-backs go where the configuration says (`Cfg::reservoir_only_give_backs`), as they do for +/// the gas revm builds for every frame. #[inline] -pub const fn untouched_call_gas(inputs: &CallInputs) -> Gas { - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir) +pub(crate) fn frame_gas(cfg: &impl Cfg, limit: u64, reservoir: u64) -> Gas { + let mut gas = Gas::new_with_regular_gas_and_reservoir(limit, reservoir); + gas.set_reservoir_only_give_backs(cfg.reservoir_only_give_backs()); + gas } -/// The gas of a creation result built without running the init code: its whole gas limit -/// unspent, and the reservoir the creation inherited. +/// The gas of a call result built under `cfg` without running the callee: the call's whole gas +/// limit unspent, the reservoir the call inherited, and the configuration's give-back mode. #[inline] -pub const fn untouched_create_gas(inputs: &CreateInputs) -> Gas { - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()) +pub fn untouched_call_gas(cfg: &impl Cfg, inputs: &CallInputs) -> Gas { + frame_gas(cfg, inputs.gas_limit, inputs.reservoir) } -/// A result for the frame `input` would start, built without running it: `result` with -/// `output`, the frame's gas untouched, the inherited reservoir carried, and the calling opcode's -/// upfront state-gas flags, as revm builds the results of the frames it answers itself. +/// The gas of a creation result built under `cfg` without running the init code: its whole gas +/// limit unspent, the reservoir the creation inherited, and the configuration's give-back mode. +#[inline] +pub fn untouched_create_gas(cfg: &impl Cfg, inputs: &CreateInputs) -> Gas { + frame_gas(cfg, inputs.gas_limit(), inputs.reservoir()) +} + +/// A result for the frame `input` would start, built under `cfg` without running it: `result` +/// with `output`, the frame's gas untouched, the inherited reservoir carried, the configuration's +/// give-back mode, and the calling opcode's upfront state-gas flags, as revm builds the results +/// of the frames it answers itself. pub fn synthetic_frame_result( + cfg: &impl Cfg, input: &FrameInput, result: InstructionResult, output: Bytes, ) -> FrameResult { match input { - FrameInput::Call(inputs) => synthetic_call_result(inputs, result, output), + FrameInput::Call(inputs) => synthetic_call_result(cfg, inputs, result, output), FrameInput::Create(inputs) => FrameResult::Create(CreateOutcome { - result: InterpreterResult::new(result, output, untouched_create_gas(inputs)), + result: InterpreterResult::new(result, output, untouched_create_gas(cfg, inputs)), address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), @@ -66,16 +83,17 @@ pub fn synthetic_frame_result( } } -/// A result for the call `inputs` would start, built without running it, as +/// A result for the call `inputs` would start, built under `cfg` without running it, as /// [`synthetic_frame_result`] builds one: for a mechanism that already holds the call's inputs /// (a system contract interceptor). pub fn synthetic_call_result( + cfg: &impl Cfg, inputs: &CallInputs, result: InstructionResult, output: Bytes, ) -> FrameResult { FrameResult::Call(CallOutcome { - result: InterpreterResult::new(result, output, untouched_call_gas(inputs)), + result: InterpreterResult::new(result, output, untouched_call_gas(cfg, inputs)), memory_offset: inputs.return_memory_offset.clone(), was_precompile_called: false, precompile_call_logs: Default::default(), @@ -89,7 +107,10 @@ pub fn synthetic_call_result( mod tests { use super::*; use alloy_primitives::{address, Address, U256}; - use revm::interpreter::{CallInput, CallScheme, CallValue}; + use revm::{ + context::CfgEnv, + interpreter::{CallInput, CallScheme, CallValue}, + }; const TARGET: Address = address!("0000000000000000000000000000000000001234"); @@ -110,23 +131,71 @@ mod tests { } } + /// A configuration whose give-backs credit the reservoir alone when `reservoir_only` is set, + /// as Satin's do, and as EIP-8037 has them otherwise. + fn cfg(reservoir_only: bool) -> CfgEnv { + let mut cfg = CfgEnv::default(); + cfg.reservoir_only_give_backs = reservoir_only; + cfg + } + /// The untouched gas is the gas limit unspent and the inherited reservoir, not a fresh /// `Gas::new(limit)`. #[test] fn test_untouched_call_gas_carries_the_reservoir() { - let gas = untouched_call_gas(&call_inputs(50_000, 7_000, false)); + let gas = untouched_call_gas(&cfg(false), &call_inputs(50_000, 7_000, false)); assert_eq!(gas.limit(), 50_000); assert_eq!(gas.remaining(), 50_000); assert_eq!(gas.reservoir(), 7_000); assert_ne!(gas, Gas::new(50_000)); } + /// The gas of every synthetic result, a call's and a creation's, gives back as the + /// configuration it is built under says: a history charge regular gas paid comes back into + /// the reservoir alone under give-backs to the reservoir alone, and into regular gas under + /// EIP-8037's own. + #[test] + fn test_untouched_gas_gives_back_as_the_configuration_says() { + let create = CreateInputs::new( + Address::ZERO, + revm::interpreter::CreateScheme::Create, + U256::ZERO, + Bytes::new(), + 50_000, + 0, + ); + for reservoir_only in [true, false] { + let cfg = cfg(reservoir_only); + let call = FrameInput::Call(Box::new(call_inputs(50_000, 0, false))); + let results = [ + untouched_call_gas(&cfg, &call_inputs(50_000, 0, false)), + untouched_create_gas(&cfg, &create), + *synthetic_frame_result(&cfg, &call, InstructionResult::Stop, Bytes::new()).gas(), + *synthetic_frame_result( + &cfg, + &FrameInput::Create(Box::new(create.clone())), + InstructionResult::Stop, + Bytes::new(), + ) + .gas(), + ]; + for mut gas in results { + assert_eq!(gas.reservoir_only_give_backs(), reservoir_only); + assert!(gas.record_history_cost(1_000), "regular gas pays it: no reservoir"); + gas.refill_history(1_000); + let expected = if reservoir_only { (49_000, 1_000) } else { (50_000, 0) }; + assert_eq!((gas.remaining(), gas.reservoir()), expected, "{reservoir_only}"); + } + } + } + /// A synthetic call result carries the return range, the untouched gas and the upfront /// charge flags of its inputs. #[test] fn test_synthetic_call_result_carries_the_inputs() { let input = FrameInput::Call(Box::new(call_inputs(9_000, 11, true))); let FrameResult::Call(outcome) = synthetic_frame_result( + &cfg(false), &input, InstructionResult::CallTooDeep, Bytes::from_static(b"x"), diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 7693241de..336b9187b 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -35,7 +35,11 @@ //! 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. +//! with no `step` after the child's end. A result the engine builds in place of a frame — an +//! interceptor's or the keyless dispatch's answer, the depth guard's, a stop it answers a frame +//! or an answer with — carries on its gas the give-back mode of the execution's configuration, as +//! the gas of every frame revm builds does, so a charge an inspector makes on it and gives back +//! is credited where the configuration says: into the reservoir alone under Satin's. //! - **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 diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 4dbb252df..1781cbbce 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -21,7 +21,7 @@ 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 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 answer is a `synthetic_call_result`, built on the execution's configuration: the forwarded gas untouched, the reservoir share the call inherited carried, the configuration's give-back mode, 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, and gives back as EIP-8037 does whatever the configuration says. - 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 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`. @@ -51,7 +51,7 @@ The executor commits it on its own, in the order the steps run, before the next ## ANTI-PATTERNS - Do not answer an unknown selector with a synthetic revert: the on-chain bytecode is the fall-through, and what it answers is the contract's own business. - Do not materialise calldata before the address and the selector matched. `peek_selector` borrows four bytes; `CallInput::bytes` copies the whole payload. -- Do not build an answer from a bare gas limit. Use `synthetic_call_result`, which carries the reservoir and the upfront-charge flags. +- Do not build an answer from a bare gas limit. Use `synthetic_call_result`, which carries the reservoir, the configuration's give-back mode and the upfront-charge flags. - Do not charge a keyless deployment's start out of the creation's gas, and do not read the creation's result anywhere but where it returns into the call (`frame_return_result`, before revm's merge, which keeps nothing of it but its gas): the call pays the start as a `CREATE`'s frame does, and every creation's result, one answered at its start included, returns there. - Do not rebuild a step of the frame lifecycle by hand for a keyless deployment's call: its start, its suspension on the creation, the merge of the creation's gas, its checkpoint and its stops are revm's and the engine's frame wrappers'. Only its two actions are hand-made. - Do not turn a failed read or SALT lookup of a keyless deployment into an ABI error: it fails the transaction with its cause, as it does at every other site. diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index a9023b534..99d4c40f2 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -8,7 +8,10 @@ use alloy_evm::Database; use alloy_primitives::{address, Address, Bytes}; use alloy_sol_types::{SolCall, SolError}; -use revm::interpreter::{CallInputs, InstructionResult}; +use revm::{ + context::ContextTr, + interpreter::{CallInputs, InstructionResult}, +}; use crate::{ synthetic_call_result, @@ -96,14 +99,15 @@ pub(crate) fn intercept( } else { return None; }; - if let Some(rejected) = reject_non_zero_transfer(inputs) { + if let Some(rejected) = reject_non_zero_transfer(ctx.cfg(), inputs) { return Some(Answer::new(rejected)); } let caller = depth.checked_sub(1); let detention = &mut ctx.detention; let (result, output) = match method { Method::Disable => { - let result = synthetic_call_result(inputs, InstructionResult::Return, Bytes::new()); + let result = + synthetic_call_result(ctx.cfg(), inputs, InstructionResult::Return, Bytes::new()); return Some(Answer { result, disables_access_from: caller }); } Method::Enable => { @@ -120,7 +124,7 @@ pub(crate) fn intercept( (InstructionResult::Return, Bytes::from(output)) } }; - Some(Answer::new(synthetic_call_result(inputs, result, output))) + Some(Answer::new(synthetic_call_result(ctx.cfg(), inputs, result, output))) } /// The three methods `MegaAccessControl` intercepts. diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 46b1bb96a..2a4a03907 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -34,15 +34,15 @@ //! # The answer //! //! An answer is a [`synthetic_call_result`]: the forwarded gas untouched, the caller's reservoir -//! carried, and the calling opcode's upfront state-gas flags, so the caller settles it exactly -//! like a frame revm ran. It carries what follows it once it settled ([`Answer`]), so the -//! settlement knows no method. +//! carried, the give-back mode of the execution's configuration, and the calling opcode's upfront +//! state-gas flags, so the caller settles it exactly like a frame revm ran. It carries what follows +//! it once it settled ([`Answer`]), so the settlement knows no method. use alloy_evm::Database; use alloy_primitives::{Address, Bytes}; use alloy_sol_types::SolError; use revm::{ - context::{ContextTr, LocalContextTr}, + context::{Cfg, ContextTr, LocalContextTr}, handler::FrameResult, interpreter::{CallInput, CallInputs, InstructionResult}, }; @@ -180,16 +180,17 @@ pub(crate) fn peek_selector(input: &CallInput, ctx: &CTX) -> Opt Some(selector) } -/// The answer to a call that carries value to a method that takes none: a revert with -/// `NonZeroTransfer()`. `None` when the call carries no value and the method may run. +/// The answer to a call that carries value to a method that takes none, built under `cfg`: a +/// revert with `NonZeroTransfer()`. `None` when the call carries no value and the method may run. /// /// Every intercepted method of the two control contracts and of `KeylessDeploy` reads state or /// steers execution and takes no value. A method that takes value on purpose states why, in its /// own interceptor, instead of calling this. #[inline] -pub(crate) fn reject_non_zero_transfer(inputs: &CallInputs) -> Option { +pub(crate) fn reject_non_zero_transfer(cfg: &impl Cfg, inputs: &CallInputs) -> Option { inputs.transfer_value().is_some_and(|value| !value.is_zero()).then(|| { synthetic_call_result( + cfg, inputs, InstructionResult::Revert, Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA), diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 2196109ed..2467ea330 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -133,12 +133,12 @@ pub(crate) fn ready( } return Ok(None); } - let mut gas = untouched_call_gas(inputs); + let mut gas = untouched_call_gas(ctx.cfg(), inputs); ctx.detention.hold(gas.tracker_mut()); let Err(refusal) = prepare(ctx, inputs, call, &mut gas)? else { unreachable!("a call carrying value is refused at rule 2") }; - Ok(Some(refusal.answer(inputs, gas))) + Ok(Some(refusal.answer(ctx.cfg(), inputs, gas))) } /// The first action of a `keylessDeploy` call's frame, which runs no instruction: charges its gas @@ -288,11 +288,11 @@ impl Refusal { } } - /// The answer to the call `inputs` start, carrying `gas`: the call's gas as the refusal left - /// it, with the reservoir it inherited. - fn answer(self, inputs: &CallInputs, mut gas: Gas) -> FrameResult { + /// The answer to the call `inputs` start under `cfg`, carrying `gas`: the call's gas as the + /// refusal left it, with the reservoir it inherited and the configuration's give-back mode. + fn answer(self, cfg: &impl Cfg, inputs: &CallInputs, mut gas: Gas) -> FrameResult { let (result, output) = self.result(&mut gas); - let mut answer = synthetic_call_result(inputs, result, output); + let mut answer = synthetic_call_result(cfg, inputs, result, output); *answer.gas_mut() = gas; answer } diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index cccb146f6..0ea8915f9 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -9,6 +9,7 @@ use alloy_evm::Database; use alloy_primitives::{address, Address, Bytes}; use alloy_sol_types::SolCall; use revm::{ + context::ContextTr, handler::FrameResult, interpreter::{CallInputs, InstructionResult}, }; @@ -85,7 +86,7 @@ pub(crate) fn intercept( if selector != IMegaLimitControl::remainingComputeGasCall::SELECTOR { return None; } - if let Some(rejected) = reject_non_zero_transfer(inputs) { + if let Some(rejected) = reject_non_zero_transfer(ctx.cfg(), inputs) { return Some(rejected); } let own = caller_remaining.saturating_add(inputs.gas_limit); @@ -94,5 +95,5 @@ pub(crate) fn intercept( .allowance(depth, inputs.gas_limit) .map_or(own, |allowance| own.min(allowance)); let output = IMegaLimitControl::remainingComputeGasCall::abi_encode_returns(&remaining); - Some(synthetic_call_result(inputs, InstructionResult::Return, Bytes::from(output))) + Some(synthetic_call_result(ctx.cfg(), inputs, InstructionResult::Return, Bytes::from(output))) } diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index f2cb3f844..a58788375 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -15,6 +15,7 @@ use alloy_evm::Database; use alloy_primitives::{address, Address}; use alloy_sol_types::SolCall; use revm::{ + context::ContextTr, handler::FrameResult, interpreter::{CallInputs, InstructionResult}, }; @@ -94,7 +95,7 @@ pub(crate) fn intercept( 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)); + return Some(synthetic_call_result(ctx.cfg(), inputs, InstructionResult::Revert, output)); } // Trailing bytes after a valid envelope are dropped by the decoder and a malformed envelope // is refused; either way the payload is paid for above. diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 4b32652c2..88443305c 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -31,7 +31,7 @@ use revm::{ }, context::{ transaction::{AccessList, AccessListItem, TransactionType}, - TxEnv, + ContextTr, TxEnv, }, context_interface::{ either::Either, @@ -256,14 +256,14 @@ struct AnswersCreations; impl Inspector, EthInterpreter> for AnswersCreations { fn create( &mut self, - _context: &mut MegaContext, + context: &mut MegaContext, inputs: &mut CreateInputs, ) -> Option { Some(CreateOutcome::new( InterpreterResult::new( InstructionResult::Return, Bytes::from(vec![0xfe; 32]), - untouched_create_gas(inputs), + untouched_create_gas(context.cfg(), inputs), ), Some(CHILD), )) diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index fdf32052d..e0633c3ae 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -20,6 +20,7 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{BALANCE, CALL, JUMP, JUMPDEST, LOG0, POP, PUSH0, PUSH20, TIMESTAMP}, + context::ContextTr, interpreter::{ instructions::gas_table_spec, interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, InterpreterAction, @@ -341,13 +342,17 @@ struct AnswersB { } impl Inspector, EthInterpreter> for AnswersB { - fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + fn call( + &mut self, + context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { (inputs.target_address == B).then(|| { let gas = match self.gas { - AnswerGas::Untouched => untouched_call_gas(inputs), + AnswerGas::Untouched => untouched_call_gas(context.cfg(), inputs), AnswerGas::Fresh => Gas::new(inputs.gas_limit), AnswerGas::Charged => { - let mut charged = untouched_call_gas(inputs); + let mut charged = untouched_call_gas(context.cfg(), inputs); assert!( charged.record_state_cost(40_000) && charged.record_history_cost(3_000) ); diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index b7fbb90f4..4c1975363 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -95,19 +95,20 @@ impl Answers { } } -impl Inspector for Answers { - fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { +impl Inspector for Answers { + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { (inputs.target_address == self.target).then(|| { + let gas = untouched_call_gas(context.cfg(), inputs); CallOutcome::new( - InterpreterResult::new(self.result, Bytes::new(), untouched_call_gas(inputs)), + InterpreterResult::new(self.result, Bytes::new(), gas), inputs.return_memory_offset.clone(), ) }) } - fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { (self.target == Address::ZERO).then(|| { - let gas = untouched_create_gas(inputs); + let gas = untouched_create_gas(context.cfg(), inputs); CreateOutcome::new(InterpreterResult::new(self.result, Bytes::new(), gas), self.address) }) } @@ -566,7 +567,11 @@ impl Inspector for Retargets inputs.known_bytecode = (self.code.hash_slow(), self.code.clone()); self.answer.map(|result| { CallOutcome::new( - InterpreterResult::new(result, Bytes::new(), untouched_call_gas(inputs)), + InterpreterResult::new( + result, + Bytes::new(), + untouched_call_gas(context.cfg(), inputs), + ), inputs.return_memory_offset.clone(), ) }) diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 1a8788396..e3701c7ed 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -29,7 +29,7 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, - context::result::EVMError, + context::{result::EVMError, ContextTr}, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, Host, @@ -410,7 +410,8 @@ fn settle_a_synthetic_failure( // The calling opcode hands the frame a copy of the reservoir its charge left, which the // frame's return replaces with what the frame gives back. let share = caller.reservoir(); - let result = synthetic_frame_result(&input(share), InstructionResult::Revert, Bytes::new()); + let result = + synthetic_frame_result(ctx.cfg(), &input(share), InstructionResult::Revert, Bytes::new()); let mut frame = EthFrame::::default(); *frame.interpreter.gas.tracker_mut() = caller; frame diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 87bed696f..3cfc1f6e5 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -1,5 +1,6 @@ //! Frame results `MegaETH` builds without running a frame carry the reservoir the frame -//! inherited and settle like revm's own. +//! inherited and the give-back mode of the configuration the execution runs under, and settle like +//! revm's own. //! //! The matrix at the end runs every method a system contract interceptor answers at a gas limit //! under the execution cap, where a transaction has no reservoir, and at one far above it, where @@ -22,10 +23,11 @@ use mega_evm::{ ACCESS_CONTROL_CODE, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, - test_utils::MemoryDatabase, - EvmTxRuntimeLimits, LimitUsage, MegaEvm, + test_utils::{neutral_cfg, neutralize_evm, BytecodeBuilder, MemoryDatabase}, + EthSpecId, EvmTxRuntimeLimits, LimitUsage, MegaEvm, }; use revm::{ + bytecode::opcode::{CALL, GAS, POP, PUSH0}, context::{result::ExecutionResult, ContextTr, JournalTr}, handler::{EvmTr, FrameResult, ItemOrResult}, inspector::InspectorEvmTr, @@ -539,3 +541,332 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { assert_eq!(after.reservoir(), RESERVOIR, "and the inherited reservoir comes back whole"); assert_eq!(after.state_gas_spent(), before.state_gas_spent()); } + +/// The configuration an execution runs under: Satin's own, whose give-backs credit the reservoir +/// alone, or the neutral one the execution-spec gate runs Ethereum's fixtures under, which credits +/// them as EIP-8037 does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Configuration { + Satin, + Neutral, +} + +impl Configuration { + const BOTH: [Self; 2] = [Self::Satin, Self::Neutral]; + + /// The fork whose pricing the neutral configuration takes: Amsterdam, whose EIP-8037 has a + /// reservoir to give back into. + const NEUTRAL_FORK: EthSpecId = EthSpecId::AMSTERDAM; + + /// Whether every give-back of the configuration credits the reservoir alone: the mode every + /// tracker built under it must carry. + const fn reservoir_only_give_backs(self) -> bool { + matches!(self, Self::Satin) + } + + /// An EVM over `db` under this configuration, held to `limits`, inspected by `inspector`. + fn evm( + self, + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + inspector: INSP, + ) -> MegaEvm { + let mut ctx = context(db).with_tx_runtime_limits(limits); + if self == Self::Neutral { + ctx = ctx.with_neutral_cfg(neutral_cfg(Self::NEUTRAL_FORK).expect("a neutral fork")); + } + let mut evm = MegaEvm::new(ctx).with_inspector(inspector); + if self == Self::Neutral { + neutralize_evm(&mut evm, Self::NEUTRAL_FORK).expect("a neutral fork"); + } + evm + } +} + +/// Keeps, for every call that ends, its target, how it ended and the give-back mode of the gas +/// its result carries, as an inspector sees the result in `call_end`. +#[derive(Default)] +struct SeesGiveBackModes { + ends: Vec<(Address, InstructionResult, bool)>, +} + +impl Inspector for SeesGiveBackModes { + fn call_end(&mut self, _: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + let mode = outcome.result.gas.reservoir_only_give_backs(); + self.ends.push((inputs.target_address, outcome.result.result, mode)); + } +} + +/// Runs `tx` over `db` under `configuration` and `limits`, and returns what the transaction's own +/// frame ended as and the give-back mode its result carried when the inspector saw it. +fn own_frame_end( + configuration: Configuration, + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + tx: mega_evm::MegaTransaction, +) -> (Bytes, InstructionResult, bool) { + let to = tx.0.base.kind.to().copied().expect("a call"); + let mut evm = configuration.evm(db, limits, SeesGiveBackModes::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let output = outcome.result.output().cloned().unwrap_or_default(); + let ends = &evm.inspector().ends; + let [(target, result, mode)] = ends.as_slice() else { + panic!("{configuration:?}: the transaction's own frame alone ends: {ends:?}") + }; + assert_eq!(*target, to, "{configuration:?}"); + (output, *result, *mode) +} + +/// The answer a system contract interceptor or the keyless dispatch gives a call carries the give- +/// back mode of the configuration the execution runs under when an inspector sees it, as the gas +/// of every frame revm builds does: give-backs to the reservoir alone under Satin's, EIP-8037's +/// own under the neutral one. An inspector that charges and gives back on the answer's gas +/// credits it where the configuration says, whoever built the result. +/// +/// Every row is an answer the engine builds without running the contract's code, which the output +/// tells apart from a fall-through into the code, whose frame revm builds with the mode anyway: +/// the methods the two control contracts answer, the refusal of a value they take none of, a +/// `keylessDeploy` call carrying value, and a hint the Oracle answers with the stop because its +/// payload would cross the transaction's data-size limit. +#[test] +fn test_an_interceptor_answer_carries_the_configured_give_back_mode() { + let selector = |selector: [u8; 4]| Bytes::copy_from_slice(&selector); + let hint = Bytes::from( + IOracle::sendHintCall { topic: B256::ZERO, data: Bytes::from_static(b"a hint") } + .abi_encode(), + ); + let no_room_for_a_hint = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(mega_evm::TX_BODY_SIZE + hint.len() as u64); + let rows = [ + ( + LIMIT_CONTROL_ADDRESS, + selector(IMegaLimitControl::remainingComputeGasCall::SELECTOR), + U256::ZERO, + EvmTxRuntimeLimits::no_limits(), + InstructionResult::Return, + None, + ), + ( + ACCESS_CONTROL_ADDRESS, + selector(IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR), + U256::ZERO, + EvmTxRuntimeLimits::no_limits(), + InstructionResult::Return, + Some(Bytes::from( + IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&false), + )), + ), + ( + ACCESS_CONTROL_ADDRESS, + selector(IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR), + U256::ZERO, + EvmTxRuntimeLimits::no_limits(), + InstructionResult::Return, + Some(Bytes::new()), + ), + ( + LIMIT_CONTROL_ADDRESS, + selector(IMegaLimitControl::remainingComputeGasCall::SELECTOR), + U256::from(1), + EvmTxRuntimeLimits::no_limits(), + InstructionResult::Revert, + Some(Bytes::from_static(&IMegaAccessControl::NonZeroTransfer::SELECTOR)), + ), + ( + KEYLESS_DEPLOY_ADDRESS, + keyless_deploy_call(), + U256::from(1), + EvmTxRuntimeLimits::no_limits(), + InstructionResult::Revert, + Some(Bytes::from_static(&IKeylessDeploy::NoEtherTransfer::SELECTOR)), + ), + ( + ORACLE_CONTRACT_ADDRESS, + hint, + U256::ZERO, + no_room_for_a_hint, + InstructionResult::Revert, + None, + ), + ]; + for configuration in Configuration::BOTH { + for (to, data, value, limits, expected, expected_output) in rows.clone() { + let case = format!("{configuration:?}, {to}, {:?}", &data[..4]); + let mut tx = crate::common::call_with_data(CALLER, to, data, NARROW); + tx.0.base.value = value; + let (output, result, mode) = own_frame_end(configuration, system_db(), limits, tx); + assert_eq!(result, expected, "{case}: {output}"); + match (to, expected_output) { + (_, Some(expected_output)) => assert_eq!(output, expected_output, "{case}"), + // The answer is the caller's forward: no word the bytecode returns. + (LIMIT_CONTROL_ADDRESS, None) => assert_eq!(output.len(), 32, "{case}"), + // The stop: `MegaLimitExceeded` of the data size. + (_, None) => assert_eq!( + mega_evm::decode_mega_limit_exceeded(&output).map(|(kind, _)| kind), + Some(mega_evm::LimitKind::DataSize), + "{case}: {output}" + ), + } + assert_eq!(mode, configuration.reservoir_only_give_backs(), "{case}"); + } + } +} + +/// The stops the engine answers a frame with in place of what revm or the frame would have made +/// carry the configured give-back mode when an inspector sees them: a call revm answered with a +/// success whose start crossed a limit, rebuilt into the stop on the gas its caller forwarded, and +/// the transaction's own frame stopped before it runs because its authorization list was skipped +/// for a limit. +#[test] +fn test_an_engine_stop_carries_the_configured_give_back_mode() { + let authority = address!("0000000000000000000000000000000000300077"); + for configuration in Configuration::BOTH { + // The transfer's record and log cross a data-size limit the body alone fits: revm + // answers the call to an account without code with a success, which gives way to the + // stop. + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let body_only = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE); + let tx = call(CALLER, TARGET, U256::from(1), NARROW); + let (output, result, mode) = own_frame_end(configuration, db, body_only, tx); + assert_eq!(result, InstructionResult::Revert, "{configuration:?}: the answer's stop"); + assert!(mega_evm::decode_mega_limit_exceeded(&output).is_some(), "{configuration:?}"); + assert_eq!(mode, configuration.reservoir_only_give_backs(), "{configuration:?}"); + + // An authorization that would create its authority, under a state-growth limit of + // nothing: the list is skipped and the first frame answered with the stop. + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let no_growth = EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(0); + let tx = crate::common::authorizing_call( + CALLER, + TARGET, + U256::ZERO, + NARROW, + TARGET, + &[(authority, 0)], + ); + let (output, result, mode) = own_frame_end(configuration, db, no_growth, tx); + assert_eq!(result, InstructionResult::Revert, "{configuration:?}: the list's stop"); + assert!(mega_evm::decode_mega_limit_exceeded(&output).is_some(), "{configuration:?}"); + assert_eq!(mode, configuration.reservoir_only_give_backs(), "{configuration:?}"); + } +} + +/// A synthetic frame result — here the depth guard's `CallTooDeep`, to a call and to a creation — +/// carries the configured give-back mode, beside the forwarded gas untouched and the inherited +/// reservoir. +#[test] +fn test_a_synthetic_frame_result_carries_the_configured_give_back_mode() { + let past = CALL_STACK_LIMIT as usize + 1; + let creation = || FrameInit { + depth: past, + memory: SharedMemory::new(), + frame_input: FrameInput::Create(Box::new(CreateInputs::new( + CALLER, + CreateScheme::Create, + U256::ZERO, + Bytes::new(), + GAS_LIMIT, + RESERVOIR, + ))), + }; + for configuration in Configuration::BOTH { + for init in [call_frame_init(past), creation()] { + let what = format!("{configuration:?}, {:?}", init.frame_input); + let mut evm = configuration.evm( + MemoryDatabase::default(), + EvmTxRuntimeLimits::no_limits(), + SeesGiveBackModes::default(), + ); + let result = EvmTr::frame_init(&mut evm, init).expect("frame_init does not fail"); + let ItemOrResult::Result(result) = result else { panic!("{what}: answered") }; + assert_eq!(result.instruction_result(), InstructionResult::CallTooDeep, "{what}"); + let gas = result.gas(); + assert_eq!((gas.remaining(), gas.reservoir()), (GAS_LIMIT, RESERVOIR), "{what}"); + assert_eq!(gas.reservoir_only_give_backs(), configuration.reservoir_only_give_backs()); + } + } +} + +/// The forward of the call [`queries_remaining_compute_gas`] makes. +const QUERY_FORWARD: u64 = 20_000; + +/// What [`ChargesAndGivesBack`] charges the answer's gas, and gives back at once. +const INSPECTOR_CHARGE: u64 = 1_000; + +/// Code that calls `MegaLimitControl.remainingComputeGas()`, forwarding [`QUERY_FORWARD`], and +/// returns what `GAS` reads once the call returned. +fn queries_remaining_compute_gas() -> Bytes { + BytecodeBuilder::default() + .mstore(0, IMegaLimitControl::remainingComputeGasCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4_u8) + .append_many([PUSH0, PUSH0]) + .push_address(LIMIT_CONTROL_ADDRESS) + .push_number(QUERY_FORWARD) + .append_many([CALL, POP, GAS]) + .return_top() + .build() +} + +/// Charges [`INSPECTOR_CHARGE`] of history on the gas of the answer to every call to +/// `MegaLimitControl` once the call ended, through the tracker's own methods, and gives it back +/// at once; it keeps the answer's regular gas and reservoir afterwards. It neither replaces the +/// tracker nor sets its give-back mode. +#[derive(Default)] +struct ChargesAndGivesBack { + after: Option<(u64, u64)>, +} + +impl Inspector for ChargesAndGivesBack { + fn call_end(&mut self, _: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address != LIMIT_CONTROL_ADDRESS { + return; + } + let gas = &mut outcome.result.gas; + assert!(gas.record_history_cost(INSPECTOR_CHARGE), "the answer holds its forward"); + gas.refill_history(INSPECTOR_CHARGE); + self.after = Some((gas.remaining(), gas.reservoir())); + } +} + +/// An inspector that charges history on an interceptor's answer and gives it back credits the +/// give-back where the configuration says, as on the gas of a frame revm built. Under Satin's +/// give-backs to the reservoir alone the charge, which regular gas paid, comes back into the +/// answer's reservoir: the caller resumes with that much less regular gas, which `GAS` reads, and +/// that much more reservoir, which goes back to the sender, so the receipt is the same. Under the +/// neutral configuration it comes back into regular gas, as EIP-8037 has it, and the caller reads +/// what it reads without the inspector. +#[test] +fn test_an_inspectors_give_back_on_an_interceptor_answer_follows_the_configuration() { + const GAS_LIMIT: u64 = 1_000_000; + let db = || system_db().account_code(TARGET, queries_remaining_compute_gas()); + let tx = || crate::common::call(CALLER, TARGET, U256::ZERO, GAS_LIMIT); + let read_gas = |outcome: &mega_evm::MegaTransactionOutcome| { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let output = outcome.result.output().cloned().unwrap_or_default(); + U256::from_be_slice(&output).to::() + }; + for configuration in Configuration::BOTH { + let limits = EvmTxRuntimeLimits::no_limits(); + let mut plain = configuration.evm(db(), limits, SeesGiveBackModes::default()); + let without = plain.execute_transaction(tx()).expect("the transaction is valid"); + let mut evm = configuration.evm(db(), limits, ChargesAndGivesBack::default()); + let with = evm.execute_transaction(tx()).expect("the transaction is valid"); + + let after = evm.inspector().after.expect("the inspector saw the answer"); + let gas_read = read_gas(&with); + if configuration.reservoir_only_give_backs() { + assert_eq!(after, (QUERY_FORWARD - INSPECTOR_CHARGE, INSPECTOR_CHARGE), "Satin"); + assert_eq!(gas_read, read_gas(&without) - INSPECTOR_CHARGE, "Satin"); + } else { + assert_eq!(after, (QUERY_FORWARD, 0), "neutral"); + assert_eq!(gas_read, read_gas(&without), "neutral"); + } + assert_eq!( + with.result.gas().tx_gas_used(), + without.result.gas().tx_gas_used(), + "{configuration:?}: the receipt is the same", + ); + } +} 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 7c63e7474..972bb6f3d 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,7 +4,7 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xef15b199c90d2f14c16d0b91f625f537ad5c3e3782252f4dad26fcb9f89277ef", + "rule: value @ 50000000 | keccak256=0x0b03bcdca2a2c572395ea8703c1d840fce31f7e38ae2a3e56f92982c2e324e35", "rule: value, arguments that do not decode @ 50000000 | keccak256=0xba607024c2803d8c65fb57bea6f6dd1df8b6b2d0996fb363382083936bd9060d", "rule: arguments that do not decode @ 50000000 | keccak256=0xf5887e762597e4e154eb78f978729f243f948d632a90e98bcf79d24d6f737940", "rule: malformed transaction @ 50000000 | keccak256=0x43b5851716bcb77384699f05cecd29ad1148970f4934844d8329cc8465101024", @@ -69,7 +69,7 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x0c8ee23f410f276e70aedeea54791fa0eeaf7d54a07a42474dce0f0dc8b8ab96", "no contract code @ 50000000 | keccak256=0xc6cfe86e2fdd140177611023f019e3f26110c91edfca5bbd49c2ae6d81e7657f", "a system call @ 50000000 | keccak256=0x19781f56400c365420cfef14d3053ac669b0c692055d51dfcb97d6b238351579", - "rule: value @ 400000000 | keccak256=0x7e5f9c693f1df70d684c3cd2ca4fd76d1fe825e2b4a48d71af3c86355e24f572", + "rule: value @ 400000000 | keccak256=0x78bfa72388d32a3444d8054b5a041ff357f5f15501aab79d8330b37c9605654c", "rule: value, arguments that do not decode @ 400000000 | keccak256=0xf57a72f33c4a4420f5bee21f1bbba9e98d265406086121536b3cb29b4be4d71e", "rule: arguments that do not decode @ 400000000 | keccak256=0x2e187280d923f25b619ce46270a7e3d9d99be13e05e7a54f198af09833f9d71f", "rule: malformed transaction @ 400000000 | keccak256=0xb78a6a15517606850c24342c9c3d3e504bc5f0683d82bf2d1d67d5fd7f625a9f", @@ -145,7 +145,7 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca "rule: init code over the limit @ 2000000000 | keccak256=0xf7c394f5669d50ca00bcdb9af25ee29a091f2089f096a29fde596409945b9c3a" ], "summary": { - "bytes": 2339597, + "bytes": 2339591, "cases": 139, "lines": 10402, "runs": 556 From c056ab2ec3ca8bb32f29b41269777e2c9bead237 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 17:21:28 +0800 Subject: [PATCH 090/190] docs: state per-block deployment, the once-per-block resolution, history for the protocol's transactions and reservoir-only give-backs where the replaced rules stood --- AGENTS.md | 8 +-- REVIEW.md | 4 +- bin/mega-evme/tests/block_replay.rs | 22 ++++--- crates/mega-evm/README.md | 8 ++- crates/mega-evm/src/block/eips.rs | 3 +- crates/mega-evm/src/block/executor.rs | 61 +++++++++++-------- crates/mega-evm/src/evm/validation.rs | 4 +- crates/mega-evm/src/system/tx.rs | 18 +++--- crates/mega-evm/src/test_utils/database.rs | 13 ++-- crates/mega-evm/tests/block/common.rs | 12 ++-- crates/mega-evm/tests/block/sequences.rs | 5 +- crates/mega-evm/tests/satin/detention.rs | 11 ++-- .../tests/satin/inspector_settlement.rs | 9 +-- crates/mega-state-test/README.md | 2 +- .../mega-state-test/src/blockchain/chain.rs | 29 ++++----- docs/mega-evme/commands/replay.md | 11 ++-- .../mega-evme/configuration/chain-and-spec.md | 6 +- docs/mega-evme/cookbook.md | 2 +- docs/spec/overview.md | 2 +- docs/spec/upgrades/overview.md | 2 +- docs/spec/upgrades/satin.md | 2 +- 21 files changed, 133 insertions(+), 101 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8c7fe759c..72658209c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -190,7 +190,7 @@ 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 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's record charge is the transaction's start charge on the start ledger, parked where its input is built (`first_frame_input`), which the transaction's start settlement gives back when the frame fails, and after a halt burns every regular gas the transaction's gas then holds, the refund's credit included, as revm's settlement burned it after each refund of its own. + 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's record charge is the transaction's start charge on the start ledger, parked where its input is built (`first_frame_input`), which the transaction's start settlement gives back when the frame fails, into the reservoir alone, and after a halt burns every regular gas the transaction's gas then holds and takes out of the reservoir again the part of that charge regular gas paid (`AdditionalLimit::first_frame_charge_from_regular`), as revm's settlement consumes after a halt what regular gas paid of each refund of its own. An ordinary transaction whose gas limit cannot cover the body is rejected at validation; a deposit is included as a failed deposit. 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 parks the frame's own as the start's charge on the start ledger, which gives it back to the caller when the frame fails (`Host::frame_settle`). What a frame does not keep comes back, at the same price, to whoever paid it. @@ -365,7 +365,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The legacy engine's limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. Its gas leakage pitfalls have no counterpart: detention, the one mechanism that caps a frame's gas, withholds it inside the frame's own tracker, where every reader but a regular charge still counts it, so nothing it withholds is ever moved or released (see Gas detention). Its storage-gas stipend does have a counterpart, the history allowance above, and it is a different thing: it never enters a frame's gas limit, so there is nothing to burn on return. - The per-start figures the engine keeps on its start ledger — the allowance, the start charge, the budgets, and the reservoir share a start takes — are checked against the three paths the legacy engine named, each by a test: an interceptor's answer settles on its start by status, the refused value call's records given back once (`history_reservoir::test_an_intercepted_value_call_gives_its_records_back_once`, `history_allowance::test_an_intercepted_call_neither_takes_nor_adds_an_allowance`, `synthetic_frame_gas::test_an_intercepted_refusal_keeps_the_reservoir`); a stop or a halt of the transaction's own frame gives its start charge back as history alone, the settlement burning after a halt the regular gas the refund credits and any an inspector's extra reservoir unwound (`stops::test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_history_alone`, `inspector_settlement::test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_to_its_reservoir`, `history_allowance::test_a_transaction_level_stop_does_not_hand_the_allowance_back`); and a frame's return gives the start charge back on a revert and a halt alike and none of the allowance (`history_reservoir::test_a_reverting_child_gives_its_records_back_to_the_reservoir`, `test_a_halting_child_gives_its_records_back_as_a_reverting_one_does`, `history_allowance::test_an_unspent_allowance_does_not_return_to_the_caller`, `history_allowance::test_a_drained_allowance_is_not_refunded_by_a_revert`). + The per-start figures the engine keeps on its start ledger — the allowance, the start charge, the budgets, and the reservoir share a start takes — are checked against the three paths the legacy engine named, each by a test: an interceptor's answer settles on its start by status, the refused value call's records given back once (`history_reservoir::test_an_intercepted_value_call_gives_its_records_back_once`, `history_allowance::test_an_intercepted_call_neither_takes_nor_adds_an_allowance`, `synthetic_frame_gas::test_an_intercepted_refusal_keeps_the_reservoir`); a stop or a halt of the transaction's own frame gives its start charge back as history alone, into the reservoir, the settlement burning after a halt every regular gas the transaction holds and taking out of the reservoir the part of the charge regular gas paid, an inspector's extra reservoir unwinding no spill (`stops::test_the_transactions_own_value_transfer_that_halts_gives_its_record_back_as_history_alone`, `inspector_settlement::test_the_transactions_own_halt_burns_its_regular_gas_when_an_inspector_adds_to_its_reservoir`, `history_allowance::test_a_transaction_level_stop_does_not_hand_the_allowance_back`); and a frame's return gives the start charge back on a revert and a halt alike and none of the allowance (`history_reservoir::test_a_reverting_child_gives_its_records_back_to_the_reservoir`, `test_a_halting_child_gives_its_records_back_as_a_reverting_one_does`, `history_allowance::test_an_unspent_allowance_does_not_return_to_the_caller`, `history_allowance::test_a_drained_allowance_is_not_refunded_by_a_revert`). ### Gas detention @@ -398,7 +398,7 @@ Detention caps how much a transaction may still compute once it read such data ( 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. + 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 under EIP-8037's own give-backs, the neutral configuration's; under Satin's it refills the reservoir alone, and the hold finds nothing grown. 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.** @@ -497,7 +497,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer 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, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the start's 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 figures are the engine's, on its start ledger.** The start ledger (`limit/ledger.rs`) keeps an entry for each start revm opens, from `frame_split` to `frame_settle`, holding what the start owes and holds: its budgets with their nets, its start charge and its history allowance; it is driven by the start lifecycle hooks alone, and pairs nothing: revm's record says which start settles. - What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start, after its own settlement of the frame; for a transaction's start whose frame halted, the hook then burns every regular gas the transaction's gas holds, as revm's settlement burned it after each refund of its own, which leaves revm's consumption of a hook's credit after a halt nothing to consume. + What a start owes is parked where it is decided — `frame_starting`, the keyless builder, the first frame's input (`first_frame_input`) — and taken by revm's split; every draw `AdditionalLimit` makes is on the top entry; the frame cap is applied where the caller suspends (`cap_child`); and a settlement merges by status and revm's inspector flags, giving the start charge back to the caller's gas on a failure, and on a creation that took no address, through `Host::frame_settle`, where revm settles the start, after its own settlement of the frame; for a transaction's start whose frame halted, the hook then burns every regular gas the transaction's gas holds, as revm's settlement burned it after each refund of its own, which leaves revm's consumption of a hook's credit after a halt nothing to consume, and, the give-back having gone into the reservoir alone, takes out of the reservoir the part of the start charge regular gas paid. An inspector's answer and a result whose tracker an inspector replaced settle as unlimited budgets; neither an inspector's answer nor an outcome an inspector rebuilt gives the start charge back; nothing an inspector puts on an input, an answer or a result decides a budget, a start charge or an allowance, and a tracker it restores from a snapshot, or an interpreter it replaces, leaves the ledger's draws and the frame's allowance where they were. A value call's frame keeps its history allowance when an inspector replaces its interpreter, as when it restores a snapshot: an accepted change for such an inspector, since the replaced interpreter's fresh gas held no allowance while the allowance was on the frame's gas. The history allowance a value call gives its child is the entry's; only a log draws on it, first, in the completed-write hook. diff --git a/REVIEW.md b/REVIEW.md index 560fbb60e..fc7401992 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -21,7 +21,7 @@ Defer to the baseline for everything not listed here; the rules below take prece ### Consensus-critical execution - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. -- Pre-block helpers (the activation block's predeploy check, pre-block system calls, the registry's due-change 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(...)`. +- Pre-block helpers (the activation block's check of the EIP-7997 factory, the system contracts' deployments, the pre-block system calls, the registry's due-change read and the resolution of the live system address) 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. - **A write is counted once its opcode completed.** @@ -48,7 +48,7 @@ Defer to the baseline for everything not listed here; the rules below take prece 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 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. +- **System calls and system-address transactions:** a system call and a system-originated transaction are exempt from the per-transaction limits, priced at the minimum SALT bucket and not detained, and only a system call is exempt from history gas: a system-originated transaction, like a deposit, pays history for what it appends; 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. diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index 5b3d4c652..0f702c70b 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -96,13 +96,14 @@ fn test_the_legacy_leg_replays_recorded_blocks_as_the_chain_did() { } /// A Satin replay of a recorded block reads what the recording lacks only in Satin's activation -/// block. A counterfactual block is not Satin's activation block, so it reads no predeploy, and it -/// reads the L1 block contract as the legacy engine does, when a transaction is priced against it -/// or held to its footprint: the L1 fee overhead, which the recording lacks, is not read beside -/// the fee scalars the recording holds set, so every recorded block replays offline. Satin's -/// activation block — under a genesis file that activates Satin at the block, whose parent came a -/// second earlier — checks the predeploys first: offline, it fails, names the EIP-7997 factory it -/// met, and the exit code is 1. +/// block. A counterfactual block is not Satin's activation block, so it does not check the +/// EIP-7997 factory; the system contracts it deploys in every block are read as the legacy engine +/// read them in the recorded block, and it reads the L1 block contract as the legacy engine does, +/// when a transaction is priced against it or held to its footprint: the L1 fee overhead, which +/// the recording lacks, is not read beside the fee scalars the recording holds set, so every +/// recorded block replays offline. Satin's activation block — under a genesis file that activates +/// Satin at the block, whose parent came a second earlier — checks the EIP-7997 factory before it +/// deploys the system contracts: offline, it fails, names the factory, and the exit code is 1. #[test] fn test_a_satin_replay_reads_beyond_the_recording_only_in_its_activation_block() { let refusal = |dir: &Path, args: &[&str]| { @@ -173,8 +174,9 @@ fn test_the_satin_counterfactual_of_recorded_blocks() { /// what its replay read beyond the trace, and then replays offline from the cache. The mock /// serves the recorded responses, and the trace is the recorded pre-state as one transaction's /// sighting. The Satin replay, a counterfactual and so no activation block, reads nothing the -/// trace lacks: no predeploy, so the cache holds no EIP-7997 factory, and no L1 fee overhead, -/// which no transaction of the block is priced with, so the cache holds none. +/// legacy replay did not: no EIP-7997 factory, which only the activation block checks, so the +/// cache holds none, and no L1 fee overhead, which no transaction of the block is priced with, so +/// the cache holds none. /// /// Expected values: independent (the chain's own receipts, and the trace's reads). #[tokio::test(flavor = "multi_thread")] @@ -202,7 +204,7 @@ async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { assert_eq!(run.code, 0, "{}", run.stderr); assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 0); let cached = read_block(cache.path(), number).prestate; - assert!(!cached.accounts.contains_key(&FACTORY), "no predeploy was read"); + assert!(!cached.accounts.contains_key(&FACTORY), "the factory was not read"); assert_eq!(cached.accounts[&L1_BLOCK].storage.get(&overhead_slot()), None, "nor the overhead"); } diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 82ebcec7d..957d900cc 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -81,7 +81,9 @@ Capacities come from the transaction's `SaltEnv`, read once per bucket per trans Without a SALT environment every bucket is minimal, so the numbers above are what a transaction pays. `tests/satin/pricing-table.md` shows two probes at three multipliers. -The six system contracts live at their fixed `0x6342…` addresses, and the EIP-7997 factory at `0x4e59…`; the legacy forks installed the six and OP's genesis tooling the factory, and Satin deploys none of them. +The six system contracts live at their fixed `0x6342…` addresses, and the EIP-7997 factory at `0x4e59…`. +Every block deploys the six before its transactions, as Rex6 does, so Satin may be active from genesis: the five flat contracts are installed where missing and given Satin's code where they hold other code, and the `SequencerRegistry` is kept at version 2.0.0, migrated in place from 1.0.0, or seeded from the chain configuration's bootstrap values where its address holds no code, a block whose registry address holds other code being refused. +OP's genesis tooling installs the factory and Satin never deploys it: only the block in which Satin activates checks that it holds its code. Three of them answer calls through an interceptor instead of running their bytecode, and `KeylessDeploy` turns the `keylessDeploy` calls a transaction makes into the deployments they stand for. A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input: `CALLCODE` and `DELEGATECALL` never reach an interceptor, and a selector a contract does not intercept falls through to the deployed bytecode, whose answer is that contract's own — the two control contracts revert with `NotIntercepted()` from their fallback, and `KeylessDeploy` and the Oracle, which have none, revert with empty data on a selector they do not declare. A method that takes no value answers a value-bearing call with `NonZeroTransfer()`. @@ -124,8 +126,8 @@ A log costs 32 bytes for its address, 32 per topic and its data; every account o The body is charged at validation, in the EIP-8037 intrinsic state-gas slot so the reservoir pays it first: a gas limit that cannot cover it is rejected before inclusion, and the receipt's state figure does not include it. 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 and a transaction the protocol itself sent pay history as any transaction does; a system call pays none. -The last two are held to no per-transaction limit, for the same reason a system call pays no history — 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 deposit and a transaction the protocol itself sent pay history as any transaction does; a system call pays none, since nothing it appends is a transaction's. +A transaction the protocol itself sent and a system call are held to no per-transaction limit, because 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. diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 62e245c28..c149c1c9f 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -14,7 +14,8 @@ //! holds that rule for all of them. //! //! The executor's own reads of the block's state outside a call (the activation block's check of -//! the predeploys, the registry's due check, the L1 block info, a sender's account) follow the +//! the EIP-7997 factory, the system contracts' deployments, the registry's due check, the +//! resolution of the live system address, the L1 block info, a sender's account) follow the //! convention of `alloy-op-evm`'s executor for its reads: any database error is an internal error, //! fatal or not. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 3bfe1e3e4..fb1f36a10 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -55,17 +55,20 @@ //! //! # The witness is what the block commits //! -//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, the activation block's read of each -//! predeploy, the read of the `SequencerRegistry`'s pending changes and the `applyPendingChanges()` -//! call — produces an [`EvmState`], and this executor commits each one on its own, in that order, -//! before the first transaction; every committed transaction's returned state follows. A read is a -//! read-only entry of its step's state: an account neither touched nor created, its slots -//! unchanged. The sequence of committed states, with the exported block hashes and buckets, is the -//! witness a stateless client needs. A node takes it with a commit hook on revm's `State` -//! (`State::set_state_hook`), which `commit` hands every state whole, before the cache drops the -//! accounts the state did not touch. The block's transitions and bundle keep only what a state -//! changed, so a witness taken from them would miss the read-only entries — the activation block's -//! predeploys, the registry's pending slots, the L1 block info. +//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, the activation block's check of the +//! EIP-7997 factory, the deployment of each of the five flat system contracts, the read of the +//! `SequencerRegistry`'s pending changes and the `applyPendingChanges()` call, the registry's +//! deployment and the resolution of the block's live system address — produces an [`EvmState`], +//! and this executor commits each one on its own, in that order, before the first transaction; +//! every committed transaction's returned state follows. A read is a read-only entry of its step's +//! state: an account neither touched nor created, its slots unchanged. The sequence of committed +//! states, with the exported block hashes and buckets, is the witness a stateless client needs. A +//! node takes it with a commit hook on revm's `State` (`State::set_state_hook`), which `commit` +//! hands every state whole, before the cache drops the accounts the state did not touch. The +//! block's transitions and bundle keep only what a state changed, so a witness taken from them +//! would miss the read-only entries — a system contract that already holds its code, the activation +//! block's factory, the registry's pending slots and the slot the resolution reads, the L1 block +//! info. //! //! The L1 block info is read outside every transaction's journal: op-revm prices the block's first //! non-deposit transaction other than a Mega System Transaction against the L1 block contract's @@ -89,21 +92,25 @@ //! # The pre-block system calls //! //! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) makes the EIP-2935 -//! 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 +//! and EIP-4788 calls; in the block in which Satin activates, and in no other, checks that the +//! EIP-7997 factory holds the code Satin expects; deploys the five flat system contracts, each +//! installed where missing and given Satin's code where it holds other code; applies a role change +//! the `SequencerRegistry` has due in this block; deploys the registry — kept at version 2.0.0, +//! migrated in place from 1.0.0, seeded from the schedule's bootstrap values where its address +//! holds no code, and the block refused over any other code — and last resolves the block's live +//! system address from it, once. Every call is a system call 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 -//! non-deposit transaction, to decide before the transaction runs whether it is a Mega System -//! Transaction: one pays no L1 fee, so the fee computation does not price it and it reports the -//! footprint read alone, and a delayed commit checks the system address's account as its sender's. -//! The packing budgets and the builder's policy hold it as any other non-deposit transaction. -//! Every transaction, a deposit included, then reads the same slot into its own journal when it is -//! validated. +//! The resolution is the block's one read of the live system address: the executor hands the +//! address to the EVM, and every transaction of the block is classified against it. The executor +//! uses the same address before every non-deposit transaction, to decide before the transaction +//! runs whether it is a Mega System Transaction: one pays no L1 fee, so the fee computation does +//! not price it and it reports the footprint read alone, and a delayed commit checks the system +//! address's account as its sender's. The packing budgets and the builder's policy hold it as any +//! other non-deposit transaction. No transaction reads the registry for its classification, so +//! none finds the registry's account or slot warm, or carries them in its returned state, for that +//! reason. #[cfg(not(feature = "std"))] use alloc as std; @@ -1171,10 +1178,10 @@ where ); let gas_limit = inner.gas_limit(); - // A Mega System Transaction is decided before it runs, from the registry's live system - // address as the block's state holds it: the engine reads the same slot when it validates - // the transaction, and a transaction of another shape from that address is no system - // transaction here but refused there. + // A Mega System Transaction is decided before it runs, from the live system address the + // block resolved after its pre-block steps: the engine validates the transaction against + // the same address, which the EVM holds, and a transaction of another shape from that + // address is no system transaction here but refused there. let is_system_transaction = !is_deposit && self.is_system_transaction(&tx_env)?; self.limiter.pre_execution_check(tx_hash, gas_limit, tx_size, da_size, is_deposit)?; diff --git a/crates/mega-evm/src/evm/validation.rs b/crates/mega-evm/src/evm/validation.rs index e5cbf0f38..17b9a5af2 100644 --- a/crates/mega-evm/src/evm/validation.rs +++ b/crates/mega-evm/src/evm/validation.rs @@ -120,7 +120,9 @@ impl IntrinsicGas { /// ([`is_apply_pending_changes_due`](crate::system::is_apply_pending_changes_due)), and then the /// one the state [`transact_apply_pending_changes`](crate::system::transact_apply_pending_changes) /// leaves names. An address read from another state treats the old system address's transactions -/// as the protocol's — no fees, no history gas — and the new one's as a user's, or the reverse. +/// as the protocol's — no fees, no per-transaction limit, the minimum SALT bucket — and the new +/// one's as a user's, or the reverse; either pays history gas, which only a system call is exempt +/// from. /// /// # Errors /// diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index 017fd6a24..e0f1257b0 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -51,8 +51,9 @@ use crate::{ /// /// A system-address transaction is executed as a deposit: no nonce check of op-revm's own and no /// fee. Which address sends them is the registry's to say, and it can be rotated through the -/// registry: the engine reads the live one out of the registry for every transaction, and never -/// falls back to this address. +/// registry: a block resolves the live one out of the registry once, after its pre-block steps, +/// and classifies every transaction of the block against it, an EVM built outside block execution +/// reads it off its state once when it is built, and neither falls back to this address. pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); /// The contracts a system-address transaction may call. It may call nothing else and create @@ -146,11 +147,14 @@ pub(crate) fn classify_system_transaction( /// transaction that carries one is a deposit, and is executed as one, whatever type its other /// fields declare. Testing the source hash is therefore testing for a deposit that carries it. /// -/// It is what exempts the protocol's own work from the metering `MegaETH` holds users to — the -/// history gas of a system transaction is not charged, and no per-transaction limit stops it, so -/// the protocol's maintenance cannot fail on a resource limit. The engine makes the same decision -/// for the running transaction with the address it read itself -/// ([`MegaContext::is_system_originated`]). +/// It is what exempts the protocol's own work from the limits `MegaETH` holds users to: no +/// per-transaction limit stops it, gas detention does not detain it, and it prices every state +/// charge at the minimum SALT bucket, so the protocol's maintenance cannot fail on a resource limit +/// or be priced out by the growth of a region it does not control. It still pays history gas for +/// the bytes it appends — its body, its calldata, its logs, its write records and its deployed +/// code — as a deposit does: only a system call is exempt from history gas, because nothing it +/// appends is a transaction's. The engine makes the same decision for the running transaction with +/// the address it holds ([`MegaContext::is_system_originated`]). pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bool { originates_from_the_protocol(tx, is_mega_system_transaction_with(tx, system_address)) } diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs index 254aafe84..68feb8159 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -24,8 +24,10 @@ const REX6_FACTORY_NONCE: u64 = 1; /// One predeploy as a state holds it: its address, its account and its storage slots. pub type PredeployAccount = (Address, AccountInfo, Vec<(U256, U256)>); -/// The seven predeploys as a chain that ran Rex6 holds them, which is what Satin's activation -/// block finds on mainnet and testnet, in [`system_contract_specs`] order. +/// The seven predeploys as a chain that ran Rex6 holds them, which is what Satin's first block +/// finds on mainnet and testnet, in [`system_contract_specs`] order: every block's deployment of +/// the six system contracts then only reads them, and the activation block's check of the +/// EIP-7997 factory finds its code. /// /// Each holds the code Satin expects. The six `MegaETH` system contracts are at nonce 0, which the /// legacy engine never moved; the EIP-7997 factory is at a nonzero nonce, as OP's genesis tooling @@ -193,9 +195,10 @@ impl MemoryDatabase { } /// Installs the seven predeploys as a chain that ran Rex6 holds them ([`rex6_predeploys`]), - /// the `SequencerRegistry` holding `roles` — an address names it in every role. Satin's - /// activation block finds what it checks, and a legacy call from the system address to a - /// whitelisted contract is a system-address transaction. + /// the `SequencerRegistry` holding `roles` — an address names it in every role. Every block's + /// deployment of the system contracts only reads them, Satin's activation block finds the + /// factory it checks, and a legacy call from the system address to a whitelisted contract is a + /// system-address transaction. pub fn rex6_predeploys(self, roles: impl Into) -> Self { rex6_predeploys(roles).into_iter().fold(self, Self::install) } diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 255c32724..8a489ab38 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -141,7 +141,7 @@ pub(crate) fn activation_spec() -> MegaHardforkConfig { /// The context of the block [`evm_env`] describes as Satin's activation block under /// [`activation_spec`]: its parent came one second before the activation, so the block admits -/// only deposits and checks the predeploys. +/// only deposits and checks the EIP-7997 factory. pub(crate) fn activation_ctx() -> MegaBlockExecutionCtx { MegaBlockExecutionCtx::new( B256::ZERO, @@ -154,7 +154,8 @@ pub(crate) fn activation_ctx() -> MegaBlockExecutionCtx { /// The context of a block that follows the activation block under [`activation_spec`]: its parent /// is at [`BLOCK_TIMESTAMP`], where Satin is already active, so the block is an ordinary one that -/// admits user transactions and checks no predeploy. +/// admits user transactions and does not check the EIP-7997 factory; it deploys the system +/// contracts, as every block does. pub(crate) fn after_activation_ctx() -> MegaBlockExecutionCtx { MegaBlockExecutionCtx::new( B256::ZERO, @@ -276,9 +277,10 @@ fn build( } /// The one account each of `states` names, in commit order: what each pre-block step committed -/// is about. A pre-block call names its target, the activation block's check the predeploy it -/// read, the read of the registry's pending changes and the call that applies them the registry, -/// and the read of the L1 block info the L1 block contract. +/// is about. A pre-block call names its target, the activation block's check the factory it +/// read, a system contract's deployment that contract, the read of the registry's pending changes, +/// the call that applies them, the registry's deployment and the resolution of the live system +/// address the registry. No pre-block step reads the L1 block contract. /// /// # Panics /// diff --git a/crates/mega-evm/tests/block/sequences.rs b/crates/mega-evm/tests/block/sequences.rs index 573574b7d..e2620d1ad 100644 --- a/crates/mega-evm/tests/block/sequences.rs +++ b/crates/mega-evm/tests/block/sequences.rs @@ -99,8 +99,9 @@ fn next_block_env() -> EvmEnv { } /// Satin's activation block packs a deposit and refuses a user transaction. The next block, on -/// the state that block committed, packs the user transaction, and the predeploys the activation -/// block checked are as they were. +/// the state that block committed, packs the user transaction, and the predeploys are as they +/// were: the activation block's check of the factory and every block's deployment of the system +/// contracts only read a state that holds them. #[test] fn test_the_block_after_an_activation_block_packs_a_user_transaction() { let mut state = common::state(); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 2b03147b5..400bc7118 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -2030,8 +2030,9 @@ fn test_gas_spilled_before_the_read_is_not_compute() { } } -/// A slot restored to its original value refills the state gas it spilled onto regular gas; the -/// spill here predates the read, and the refill must not give the frame compute past the cap. +/// A slot restored to its original value gives back the state gas it spilled onto regular gas, +/// into the reservoir alone under Satin's give-backs; the spill here predates the read, and the +/// give-back must not give the frame compute past the cap. #[test] fn test_a_refill_after_the_read_does_not_lift_the_cap() { let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); @@ -2049,9 +2050,9 @@ fn test_a_refill_after_the_read_does_not_lift_the_cap() { /// 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. +/// state. That history spilled onto regular gas before the read, and its give-back — the +/// completed-write hook's own, after revm's state give-back, into the reservoir alone — 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. diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 4c1975363..be8fd52bc 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -1281,10 +1281,11 @@ impl Inspector for AddsReservoir { /// The transaction's own frame halts, and an inspector hands back one more reservoir than it /// inherited: on the input, on the result, or on a tracker it built. Below the execution cap the -/// history charged before execution for the frame's write record spilled onto regular gas, and the -/// extra reservoir unwinds part of that spill into regular gas before the record's charge is given -/// back. The halt burns every regular gas the settlement leaves, so the sender gets back the extra -/// reservoir and nothing more: the transaction bills one gas less than its run without the +/// history charged before execution for the frame's write record spilled onto regular gas; the +/// transaction's reservoir takes the extra reservoir as it is, unwinding no spill, and the record's +/// charge is given back into the reservoir, less the part regular gas paid, which the halt +/// consumes. The halt burns every regular gas the settlement leaves, so the sender gets back the +/// extra reservoir and nothing more: the transaction bills one gas less than its run without the /// inspector, and its gas used and the reservoir it leaves add up to its gas limit. So it does /// whether the transaction moves value, which makes the record, or not; below the cap, above it /// with a reservoir the record's charge drains, and above it with one that pays the charge. diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index b97af158f..a9c84982a 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -112,7 +112,7 @@ A blockchain test is a chain: a pre-state, a genesis block, and blocks a node im Every block is decoded from its RLP, as a node receives it, and runs through `MegaBlockExecutor` on `MegaEvm` in equivalence mode's configuration — the neutral Osaka configuration, the fork's precompile set and static opcode prices — over a copy of the state the chain holds. The executor makes the EIP-2935 and EIP-4788 pre-block system calls before the transactions, as it does for every block; `BLOCKHASH` reads the hashes of the chain's own blocks. -Satin runs on a chain that holds its predeploys — the six `MegaETH` system contracts and the EIP-7997 factory — and deploys none of them, so the runner seeds each one the fixture's pre-state lacks into the chain's genesis state, as a chain that ran Rex6 holds it, the `SequencerRegistry` naming roles that promote no fixture's transaction (`blockchain::registry_roles`). +Every Satin block deploys the six `MegaETH` system contracts before its transactions, and the EIP-7997 factory, which nothing deploys, is checked only in the block in which Satin activates; the runner seeds each of the seven the fixture's pre-state lacks into the chain's genesis state, as a chain that ran Rex6 holds it, so every block's deployment only reads them and the post-state holds exactly what the seed wrote, the `SequencerRegistry` naming roles that promote no fixture's transaction (`blockchain::registry_roles`). The runner holds the blocks to no protocol limit in place of Satin's, through the executor's test-and-tool override, as equivalence mode holds a state test's transaction to none. Each block is told whether it admits only deposits, and whether Satin activates in it, as a node works them out, from the schedule (`blockchain::chain_spec`) and its parent's timestamp; the schedule activates every fork at genesis, so no block the runner imports is either. diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs index 85d5208cd..9126f1293 100644 --- a/crates/mega-state-test/src/blockchain/chain.rs +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -6,21 +6,22 @@ //! becomes the chain's head and its state the chain's; a block it refuses is dropped with its copy, //! so the chain stays at the previous block. //! -//! Satin runs on a chain that ran the legacy forks, which holds the six system contracts, and OP's -//! EIP-7997 factory, and deploys none of them; the runner seeds each of the seven the fixture's -//! pre-state lacks into the chain's genesis state, once, as such a chain holds them -//! ([`rex6_predeploys`]), the `SequencerRegistry` with roles that bind nothing on an Osaka fixture -//! ([`registry_roles`], which says why). +//! Every Satin block deploys the six system contracts before its transactions, and OP's EIP-7997 +//! factory, which nothing deploys, is checked only in the block in which Satin activates; the +//! runner seeds each of the seven the fixture's pre-state lacks into the chain's genesis state, +//! once, as a chain that ran the legacy forks holds them ([`rex6_predeploys`]), so every block's +//! deployment only reads them, the `SequencerRegistry` with roles that bind nothing on an Osaka +//! fixture ([`registry_roles`], which says why). //! //! Each block's context tells the executor whether the block admits only deposits and whether //! Satin activates in it, worked out as a node works them out: from the schedule and the timestamp //! of the chain's head, the block's parent. Under [`chain_spec`], which activates every fork at -//! genesis, no block the runner imports is either, so no block checks the predeploys. +//! genesis, no block the runner imports is either, so no block checks the EIP-7997 factory. //! -//! A Satin chain holds accounts an Ethereum chain does not: the seven predeploys, which Satin -//! requires and does not create, so the chain's pre-state holds them; and the fee vaults op-revm -//! routes fees to. [`SATIN_ACCOUNTS`] lists them, each with the rule it is taken out of the -//! post-state by before the root is computed; any other account that differs is a failure. +//! A Satin chain holds accounts an Ethereum chain does not: the seven predeploys, which the runner +//! seeds into the chain's pre-state and every block's deployment then only reads; and the fee +//! vaults op-revm routes fees to. [`SATIN_ACCOUNTS`] lists them, each with the rule it is taken out +//! of the post-state by before the root is computed; any other account that differs is a failure. use std::collections::{BTreeMap, BTreeSet}; @@ -73,10 +74,10 @@ const BLOCK_HASH_WINDOW: u64 = 256; /// out. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Added { - /// A predeploy, which Satin requires and neither creates nor upgrades: the chain's pre-state - /// holds it as a chain that ran Rex6 holds it ([`rex6_predeploys`]), the `SequencerRegistry` - /// with the roles of [`registry_roles`]. It is taken out when it holds exactly that: the code, - /// the nonce, the storage, and no balance. + /// A predeploy, which the chain's pre-state holds as a chain that ran Rex6 holds it + /// ([`rex6_predeploys`]), the `SequencerRegistry` with the roles of [`registry_roles`], and + /// which every block's deployment of the system contracts therefore only reads. It is taken + /// out when it holds exactly that: the code, the nonce, the storage, and no balance. PreState, /// The vault op-revm credits the base fee to, where Ethereum burns it. It is taken out when it /// holds exactly the base fees of the blocks the chain accepted, and nothing else. diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index 03af45e8c..6af48d19a 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -166,15 +166,18 @@ A replay on another chain than the file's is refused for its chain, before any e Override the auto-detected spec. Useful when you want to test how the transaction would behave under a different spec, or when replaying against a chain that isn't recognized. -`--override.spec Satin` replays the transaction as it would run on Satin: a counterfactual, on the same forked state, under the chain's schedule with Satin active from genesis, so no block of it is Satin's activation block and it checks no predeploy. +`--override.spec Satin` replays the transaction as it would run on Satin: a counterfactual, on the same forked state, under the chain's schedule with Satin active from genesis, so no block of it is Satin's activation block and it does not check the EIP-7997 factory. ``` mega-evme replay --override.spec Rex2 mega-evme replay --override.spec Satin ``` -A Satin replay needs a state whose system contracts are at the versions Satin runs, which MegaETH mainnet and testnet reach at `Rex6`: Satin deploys and upgrades none of them, and the `SequencerRegistry` it reads before every transaction must be at version 2.0.0, which Rex6 left. -Replayed at its activation block, under a genesis file, Satin checks them and refuses a block whose state does not hold them, with an error naming the contract; a counterfactual checks nothing, so on an older block a transaction runs on whatever the state holds there. +A Satin replay makes the block's pre-block changes before its transactions, as a node does, so the transaction runs on the system contracts Satin runs whatever version the forked state holds. +Every block deploys them: the Oracle, the High-Precision Timestamp, KeylessDeploy, MegaAccessControl and MegaLimitControl are installed where missing and given Satin's code where they hold other code; the `SequencerRegistry` is kept at version 2.0.0, migrated in place from 1.0.0, and seeded where its address holds no code. +The block's live system address is then resolved from the registry, once, before the block's first transaction; no transaction reads the registry to be classified. +On MegaETH mainnet and testnet, which ran `Rex6`, every system contract already holds its code, so the deployment only reads them. +A block whose registry address holds other code, or whose registry names no system address, fails with an error naming the registry; under a genesis file, Satin's activation block also checks the EIP-7997 factory and fails over any other code there. ### `--override.limits ` @@ -255,7 +258,7 @@ The exit code is 0, 1 when a block could not be replayed, or 2 when `--verify` i `--override.spec Satin` runs every block as it would run on Satin: every transaction as signed, on the state its parent block left, under Satin's protocol limits, or those `--override.limits` gives, with no building policy of a block builder applied. A transaction the Satin engine refuses (it cannot pay for its gas, or a block budget is full) is reported `refused` and left out, and the block goes on. A transaction signed with a gas limit sized for legacy costs can run out of gas on Satin: that is the counterfactual's answer, not a tool fault. -`--override.spec Satin` runs no block as Satin's activation block, so it checks no predeploy, and it reads the L1 block contract as the legacy replay does, when a transaction is priced against it or held to its footprint; what it reads beyond the legacy replay is only what a transaction's Satin run reads on a path the chain's run did not take. +`--override.spec Satin` runs no block as Satin's activation block, so it does not check the EIP-7997 factory; it deploys the system contracts and resolves the live system address in every block, as `Rex6` does, and it reads the L1 block contract as the legacy replay does, when a transaction is priced against it or held to its footprint; on a block the chain ran on `Rex6`, what it reads beyond the legacy replay is only what a transaction's Satin run reads on a path the chain's run did not take. ## Transaction Overrides diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index 5d57d7da4..6f470e6d3 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -128,8 +128,10 @@ A counterfactual on a chain the tool does not know carries placeholder `Sequence `--genesis ` takes it from the chain's genesis file, on every command, `replay` included. The file's `config` object (or a file that is the `config` object) is read for its `chainId`, its Satin key, `satinTime`, and the `SequencerRegistry`'s bootstrap keys a configuration that schedules Satin must carry (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`), with the parser the node and the stateless validator read it with, so a key the node refuses is refused here too: a `satin`-prefixed key other than `satinTime`, the registry roles an earlier format named among them, and a missing or zero bootstrap value. For that chain the file replaces the tool's table: a block runs Satin from the file's `satinTime`. -The file names no limit and no `SequencerRegistry` role: a Satin run under it is held to Satin's limits, as every Satin run is, and a Satin block reads the registry the chain's state holds, which the legacy forks deployed. -Satin's activation block refuses a state whose registry is missing or holds other code; a later block makes no such check and runs on the state it is given, where a missing registry names no system address. +The file names no limit: a Satin run under it is held to Satin's limits, as every Satin run is. +Its bootstrap keys matter only to a block that seeds a `SequencerRegistry` its state does not hold, or migrates one from version 1.0.0; once the registry holds its roles, its storage decides them. +Every Satin block deploys the system contracts before its transactions, as a node does: it installs or upgrades the five others, keeps a registry at version 2.0.0, migrates one at 1.0.0, seeds one where its address holds no code, and fails over a registry address that holds other code; it then resolves the block's live system address from the registry, once, and fails when the registry names none. +Satin's activation block also checks the EIP-7997 factory, and fails over a state that does not hold its code. Every command under it holds to one rule: a run the file cannot configure is refused, never run on the tool's own table. - A command on another chain than the file's `chainId` is refused first, whatever its spec. diff --git a/docs/mega-evme/cookbook.md b/docs/mega-evme/cookbook.md index 97e090ba8..3725ff16b 100644 --- a/docs/mega-evme/cookbook.md +++ b/docs/mega-evme/cookbook.md @@ -69,7 +69,7 @@ mega-evme replay --block 26400000..26400099 \ ``` Replay the same blocks on Satin and keep the per-transaction records. -A Satin run reads the L1 block contract as the legacy replay does and checks no predeploy, so it needs `--rpc` only for a path a transaction takes on Satin that it did not take on the chain; such a read is made over RPC and added to the cache: +A Satin run reads the L1 block contract as the legacy replay does, reads the system contracts it deploys in every block as `Rex6` does, and, as a counterfactual, checks no EIP-7997 factory, so on blocks the chain ran on `Rex6` it needs `--rpc` only for a path a transaction takes on Satin that it did not take on the chain; such a read is made over RPC and added to the cache: ```bash mega-evme replay --block 26400000..26400099 --block-cache ./blocks \ diff --git a/docs/spec/overview.md b/docs/spec/overview.md index d7dfcde65..0cec0300d 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -50,7 +50,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. +Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction pays history gas, a deposit and one of the protocol's own included — only a system call, which is no transaction, is exempt — so no transaction 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 at commit `426217bb2e76c0a41d46907eb788250e8efa107c` ([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 `3d43e32029fc5cd293ab70eb0929d70e37337966` ([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). diff --git a/docs/spec/upgrades/overview.md b/docs/spec/upgrades/overview.md index 165245197..75aaca7f7 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, 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 exempt deposits and hold Mega System Transactions as any other non-deposit transaction, 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 system contracts deployed in every block and the live system address resolved once per block, the block's data-size, KV and state-growth limits as packing budgets that exempt deposits and hold Mega System Transactions as any other non-deposit transaction, and the activation block's check of the EIP-7997 factory. ## How to Read These Pages diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index badf56b5a..53b694601 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1085,7 +1085,7 @@ The reference implementation has no price for one, so it runs such a precompile The first two charges leave the call's gas as it was just after its memory expansion: the static cost and the memory expansion stay charged and count as compute once, as the charges made again, and the value-transfer cost of a call that carries value is given back and is not compute; the refused delegate's access is never charged. Nothing before the delegate's load draws on the reservoir, so the restoration and the charges leave it as the opcode found it; the frame's end rolls back its own state and history charges as any revert or stop does. The memory stays grown. - For these rules the target was warm when it was among EIP-2929's accessed addresses as they stood when the call reached the target's load: the addresses warm from the transaction's start — the precompiles, the block beneficiary, the addresses of the access list, the sender and the recipient, and the `SequencerRegistry`'s account (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)) — and every address an earlier access warmed that no rollback has taken back, the authorities the authorization list's application warmed included; the call's own load of the target does not count. + For these rules the target was warm when it was among EIP-2929's accessed addresses as they stood when the call reached the target's load: the addresses warm from the transaction's start — the precompiles, the block beneficiary, the addresses of the access list, the sender and the recipient (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)) — and every address an earlier access warmed that no rollback has taken back, the authorities the authorization list's application warmed included; the call's own load of the target does not count. No charge of that settlement can run out of gas: the static cost and the memory expansion were paid from the same gas before the delegate's load, and the delegation guard held the regular gas left after them and after the value-transfer cost to at least the cold surcharge plus `WARM_STORAGE_READ_COST`. The cold surcharge MUST therefore be paid, or be gas detention's crossing when the spendable part cannot pay it, and MUST NOT halt the frame out of gas; when it is the crossing, the gas is put back to what it was just before it, so the memory expansion stays charged at the stop as well. A call that carries value always pays it: the value-transfer cost it paid from its spendable gas before the load, and was given back, leaves room for the surcharge there. From 61ad461750261830864d575a6e0e15dc809da382 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 17:24:41 +0800 Subject: [PATCH 091/190] docs(review): bring the review guide to the reservoir-only give-backs, history for the protocol's transactions and per-block deployment --- .claude/skills/satin-review/SKILL.md | 66 +++++++++++++++++++--------- 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 6e0e706c8..8bdb0f725 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -28,7 +28,7 @@ The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and - 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. -- Satin is the first spec of a line, so keep the extension points a line needs (spec-keyed constants, a spec argument); a later fork that first needs configuration parameters adds a mechanism for them then. +- Satin is the first spec of a line, so keep the extension points a line needs (spec-keyed constants, a spec argument, the chain configuration's `SequencerRegistry` bootstrap values, which Satin's per-block deployment reads). 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. @@ -74,7 +74,7 @@ Each change is stated here in plain words with its reason; the specification has The four figures of a start are the three budgets with their nets, the part of the reservoir the caller keeps, the start charge and the history allowance. The engine decides all four itself, in every build: the budgets, the start charge and the allowance on its start ledger (`src/limit/ledger.rs`), an entry per start driven only by the fork's start lifecycle hooks (`frame_split`, `frame_settle`, `frame_lifecycle_end`), and the reservoir's share where the start is made (`MegaContext::forward_start`, named to revm on `FrameStart::reservoir`). The fork forwards and settles the reservoir as upstream does: the settlement puts the reservoir the child hands back in place of the caller's, and `frame_settle` adds back the part the caller kept (`FrameSettle::held_reservoir`) at a child's settlement, not at the transaction's, whose gas held a copy of its frame's reservoir. - A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history, and after a halt of the transaction's own frame burns the transaction's regular gas, as revm's settlement did after its own refund, so regular gas an inspector's extra reservoir unwound is not kept; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). + A limit check reads the running frame's budget off the ledger's top entry; `frame_settle` gives a failed start's charge back to the caller's gas, as history, into the reservoir alone, and after a halt of the transaction's own frame burns the transaction's regular gas, as revm's settlement did after its own refund, and takes out of the reservoir the part of the charge regular gas paid; a log's history draws the entry's allowance first; the frame cap is the ledger's (`cap_child`, which replaced `cap_the_shares` and is held to it by a unit test). The inspector shapes whose results changed when the engine took the figures over, each accepted: an answer built on gas whose pools the inspector set, or with the input's start charge copied, which an inspector can no longer build, now that the fork carries neither; a tracker an inspector restores from a snapshot leaves the ledger's draws and the allowance where they were; and an inspector that replaces a value call's interpreter leaves the frame its allowance, where the fresh gas of the replaced interpreter held none while the allowance was on the frame's gas. A test reads what the ledger settled (`test_utils::record_start_ledger_settlements`). Why: the figures are the engine's decisions, and the fork carries none of them. @@ -158,6 +158,19 @@ Each change is stated here in plain words with its reason; the specification has Made after #407 merged: the history gas pre-execution charges for the write record the transaction's own frame makes is kept on the layer (`AdditionalLimit::keep_first_frame_charge`) and taken by the frame's input as its start charge, where it used to be priced a second time on the same journal. A debug build prices it again at the input and asserts the two agree; a system call, which skips pre-execution, is priced at its input as before. Why: nothing between the charge and the input changes the journal it is priced on, and the second pricing cost about 550 instructions per value-transfer transaction, measured. +- **Every give-back goes into a reservoir, and fresh state takes a legacy share from regular gas first.** + Made after #407 merged: a slot written back, a record taken back, the destruction table's refill, a failed start's charge given back and a failed frame's rollback all credit the frame's reservoir alone, never its regular gas, whichever pool paid the charge; a returned reservoir joins the caller's without unwinding its spill; a halt consumes the regular gas with what that gas paid of the frame's charges, and returns the reservoir the frame received. + A fresh slot, a value call's new account, a `SELFDESTRUCT` beneficiary's new account and a created account — and a keyless deployment's signer and creation, as a value call and a creation — take a fixed legacy share from regular gas before the reservoir: the pre-Satin price less the site's regular entry, 10,000, 25,000, 16,000 and 20,000, never scaled by SALT and capped at the charge; deposited code, a delegation indicator, every charge made before the first frame and every history charge take none. + The mechanism is the fork's, behind a switch that defaults to upstream's EIP-8037 (`CfgEnv::reservoir_only_give_backs`): `spec_cfg` turns it on and the neutral configuration off; revm sets it on every tracker it builds, and the engine on every result it builds itself (`frame_gas` in `src/evm/frame.rs`); the fork reads the four shares from schedule entries that are zero upstream (`GasId::sstore_set_state_gas_legacy_share` and its siblings); and the tracker's spill counter, which no give-back lowers, is what keeps regular gas that paid state or history out of compute, the part halts consumed beside it (`halted_regular_paid`). + The transaction's own frame that halts returns the charge made before it only for the part the reservoir paid (`settle_first_frame`, `AdditionalLimit::first_frame_charge_from_regular`). + The op-revm baseline compares with the switch on and the shares in op-revm's schedule, and pins the departure from EIP-8037 with the switch off. + Why: contracts written for Rex and for Ethereum before Amsterdam read the gas left after a failed call, and assume that gas a frame spent does not come back while the transaction runs; a transaction at or below the execution cap has no reservoir, so under EIP-8037's rule every give-back would raise `GAS`, and crediting the reservoir keeps it from rising at no cost to the sender, whose unused reservoir returns at the settlement; the legacy share keeps creating state at least as dear in regular gas as before Satin, since a sender adds a reservoir almost for free by raising its gas limit, and a contract budgeted for Rex's prices relies on a fixed amount of regular gas being too little to write a slot. +- **Deposits and the protocol's own transactions pay history gas; only a system call does not.** + Made after #407 merged: a deposit and a system-originated transaction, a Mega System Transaction among them, pay history for their body, calldata, logs, write records and deposited code, as any transaction does; their other exemptions stand (a system-originated transaction is held to no per-transaction limit, not detained and priced at the minimum bucket). + A system call — a pre-block call among them — pays none, on a schedule that prices deposited code at zero too (`MegaContext::prices_history`, decided from the class the layer prepares the execution as). + A deposit whose gas limit cannot pay its body's history is a failed deposit; a failed deposit reports its whole gas limit as regular gas and no history gas, and keeps its body and calldata as history bytes. + So a deposit or a Mega System Transaction whose gas limit was sized for Rex6 can now fail for its history: the sequencer sizes a system transaction's gas for it. + Why: what a transaction appends is stored by every node whoever sent it, so the price that bounds it applies to a deposit and a Mega System Transaction as to any transaction (Rex6 charged them its storage gas for calldata, logs and code too, sparing only the SALT-scaled part, which the minimum-bucket pricing keeps); a pre-block system call appends no transaction to the history. ### Gas detention @@ -179,6 +192,16 @@ Each change is stated here in plain words with its reason; the specification has A frame that cannot reach the delegate (3,100 for a cold target, 200 for a warm one, with no input and no value) runs out of gas instead of being refused; every other refusal still costs nothing. Why: the lookup before any charge loaded a cold target's account and code for a frame that could not pay its static gas, so an access-off loop read about one cold account per 160 gas into the witness where access on reads none; refusing at the load reads a target only for a frame that holds its access, and paying that access keeps a delegator of the beneficiary — which, the beneficiary being fixed, stays one for every later block — from being read for about 181 gas, so every cold account read costs the cold access; keeping the memory charged stops a loop of refused calls with MiB-sized ranges from having the node grow and zero memory for about 270 gas a call (ten 3 MiB calls fit in a transaction at the execution cap, where handing the expansion back allowed 658,337 of them, about 1.9 TiB of memory grown). +### System contracts and the system address + +- **Every block deploys the system contracts, and the live system address is resolved once per block.** + Made after #407 merged: before its transactions every block deploys the six system contracts, as Rex6 does — the Oracle, the high-precision timestamp, `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl` installed where missing and given Satin's code where they hold other code, their nonce, balance and storage kept, a read-only entry where they hold it; the `SequencerRegistry` a read-only entry at version 2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the schedule's bootstrap values where its address holds no code, and the block refused over any other code — and then resolves the block's live system address from the registry, once, as the last pre-block step, and hands it to the EVM (`MegaContext::set_system_address`). + Each step's state is committed on its own before the next, so the sequence of committed states is the stateless witness. + The activation block checks only the EIP-7997 factory, which nothing deploys; Satin may be active from genesis, the genesis block making every step but the EIP-2935 and EIP-4788 calls. + The bootstrap values are Satin's one chain-configuration parameter, under the Rex-era keys (`MegaHardforks::sequencer_registry_bootstrap`, `SatinChainConfig`), refused when missing or zero at load time (`validate_schedule`) and by the genesis parser; a block that must seed or migrate the registry on a schedule without usable values fails with an internal error. + No transaction reads the registry for its classification: `MegaHandler::validate_env` takes the address the context holds, so no transaction finds the registry warm or carries it in its state for that reason; an EVM built outside block execution — an RPC call, a gas estimate, a trace — reads the address once when its context is built (`MegaContext::new_with_external_envs`, through `system::live_system_address`), directly off its database, warming and charging nothing, and a read the database cannot serve then is made again by the next transaction. + Why: deploying in every block restores Rex6's availability and repair of the contracts and lets Satin be active from genesis; a role change takes effect only in a block's pre-block step, so one read after those steps names the address for every transaction of the block, the read is a pre-block state a stateless validator holds, and no transaction's gas or read set depends on it, in a block or in an estimate. + ### The stop and the configuration - **Limit stops are revert-class in four dimensions, in a fixed order.** @@ -233,7 +256,7 @@ A test name or a line count is not a reason to trust the code: read the code aga - **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, every per-transaction limit and frame budget, and detention, and priced at the minimum bucket; its usage is still counted. + Such work is exempt from every per-transaction limit and frame budget and from detention, and priced at the minimum bucket; it pays history gas for what it appends, as a deposit does, since only a system call is exempt from history gas; its usage is still counted. - **Pool**: a frame's budget in data size, KV updates or state growth, held on its start's entry of the engine's start ledger (`src/limit/ledger.rs`); the frame-start hook parks a child's share, revm's split of the start opens the child's entry with it, and revm's settlement of the start merges the child's pools into its caller's, as revm settles 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. @@ -242,6 +265,8 @@ A test name or a line count is not a reason to trust the code: read the code aga - **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, kept on the start's entry of the start ledger and given back to the caller 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. +- **Give-back**: state or history gas returned to a frame — a slot written back, a record taken back, the destruction table's refill, a failed start's charge, a failed frame's rollback; under Satin it goes into the frame's reservoir alone, never into regular gas. +- **Legacy share**: the fixed part of a fresh slot's, a new account's or a created account's state gas that regular gas pays before the reservoir — the pre-Satin price less the site's regular entry — so creating state costs at least its pre-Satin regular price. - **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 @@ -287,7 +312,8 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - 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 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. - 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). + - `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, give-backs to the reservoir alone on); the neutral configuration turns the give-back switch off. + - Every tracker carries the configuration's give-back mode before anyone reads it: revm sets it on the gas of every frame it builds, and the engine on every result it builds itself — an interceptor's or the keyless dispatch's answer, the depth guard's, a stop it answers a frame or an answer with (`frame_gas` and the synthetic builders in `src/evm/frame.rs`, which take the configuration); an inspector's own answer or tracker is taken as given. - Per-transaction state resets with the transaction; a system call has its own entry point, and the handler splits its gas (`MegaHandler::tx_gas`). - An execution that fails with an error leaves nothing the next one on the same EVM reads: `MegaHandler::catch_error` empties the error slot before op-revm runs, discards the journal transaction on an error (a failed deposit's commit stays), and clears the L1 cost, the local context and the frame stack after op-revm; every entry point that takes the state off the journal on a success does so on an error, and a `_one` entry point keeps the calls before the failed one (`tests/satin/reuse_after_error.rs`, every public entry point, plain and inspected). - 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. @@ -302,7 +328,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - 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, 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. + - Compute is every regular charge the frames make, the work run on a value call's stipend included, less the state and history gas regular gas paid — a legacy share or a spill, counted by the fork's spill counter, which no give-back lowers, so a charge given back into a reservoir stays out of compute — 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. @@ -319,7 +345,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - 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 is never refused by the packing budgets or building policy and counts towards them; an MST, a legacy envelope, is held to them as any other non-deposit transaction, at admission and at a delayed commit, and counts towards them too; both are held to the header gas limit (`BlockLimiter::pre_execution_check`), and an MST 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; nothing of the L1 block contract is read before the block's transactions. + - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the EIP-7997 factory, the deployment of the five flat system contracts, the registry's due change, the registry's deployment, and last the resolution of the live system address, which the executor hands to the EVM; each step's state is committed on its own before the next; nothing of the L1 block contract is read before the block's transactions. - The L1 block contract's account and the slots the fee computation and the footprint read reach are reported once each per block, as read-only entries of the first committed transaction that read them, never in place of that transaction's own entries, whichever executor produced the outcome and in whatever order the builder executed its candidates (`l1_block_info.rs`). - 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. @@ -333,16 +359,15 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **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`. - **Check:** - - Every transaction reads the registry's account and its `_currentSystemAddress` slot, warm, by comparing the code hash, without running the registry's code. + - No transaction reads the registry for its classification: the block resolves the live system address once, after its other pre-block steps, by comparing the registry's code hash and reading `_currentSystemAddress` without running its code, and hands it to the EVM; an EVM built outside block execution reads it once when it is built, directly off its database, warming and charging nothing; so no transaction finds the registry's account or slot warm, or carries them in its state, for that reason, and one that reads them pays the cold price. - 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. + - 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, is not detained and is priced at the minimum bucket, though it pays history gas as any transaction does. 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 (`MegaBlockExecutor::is_satin_activation_block`, derived from the schedule, the block's timestamp and the parent's) 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. + - Every block deploys the six system contracts, as Rex6 does (`system/predeploys.rs`, `system/sequencer_registry.rs`): the five flat contracts are installed where missing, have their code replaced where it differs, nonce, balance and storage kept, and are a read-only entry where they hold Satin's code; the registry is a read-only entry at version 2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the schedule's bootstrap values where its address holds no code, and any other code refuses the block (`MegaBlockExecutionError::SequencerRegistry`); a block that must seed or migrate it on a schedule without usable bootstrap values fails with an internal error. + The block in which Satin activates (`MegaBlockExecutor::is_satin_activation_block`, derived from the schedule, the block's timestamp and the parent's) also checks the EIP-7997 factory, a read-only entry that must hold exactly its code whatever its nonce, balance and storage, or the block is invalid with `UnexpectedSystemContractCode`; no other block reads the factory. + A registry that is absent, holds other code or names the zero address when the address is resolved refuses the block. - An Oracle read in a system call reads chain storage, never the oracle service. - 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. @@ -359,7 +384,8 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - 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. + - A deposit and a protocol-produced transaction pay history gas for their body, calldata, logs, write records and deposited code; only a system call pays none, on a schedule that prices deposited code at zero too (`MegaContext::prices_history`); a failed deposit reports its whole gas limit as regular gas and no history gas, and keeps its body and calldata as history bytes. + - Every give-back goes into a reservoir, never into regular gas, and a returned reservoir joins the caller's without unwinding anything; a fresh slot, a value call's new account, a `SELFDESTRUCT` beneficiary's new account and a created account take their legacy share (10,000, 25,000, 16,000, 20,000) from regular gas first, as do a keyless deployment's signer and creation, and no other charge takes one. - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, kept on the start ledger, in no schedule entry) 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. @@ -384,11 +410,11 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **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. + - `validate_schedule` refuses a schedule in which a base fork Satin runs on is not active by `satinTime`, and one that activates Satin without the `SequencerRegistry`'s bootstrap values or with one of them zero. + - The genesis format schedules Satin by one key, `satinTime`, and carries the registry's three bootstrap keys of the Rex era beside it (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`), which a configuration that schedules Satin must carry, none zero; 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, and every authority the authorization-list simulation loaded. + - 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 system contracts every block's deployment reads, the registry's pending slots and the slot the resolution reads, 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. @@ -440,7 +466,7 @@ 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 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. | +| A deposit that fails validation — its body over the data-size limit, its gas limit short of its body's history, 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. | | Changed after #407 merged: 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 when revm built its frame or answered it with a success; a call revm answered with a failure — a precompile that fails after the value moved — kept nothing and halts as revm has it, burning its forward, and a precompile gas detention answers from its price is the compute stop, whatever its records would have crossed. | A limit is enforced at the writes it guards, which are what the journal kept: a success kept the start's writes, so it gives way to the stop; a failure's writes revm took back, and a precompile answered from its price moved nothing, so neither has a write to hold. | @@ -475,10 +501,10 @@ Each is a decision with its reason; "in this pull request" means review the code - **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. +- **No transaction reads the registry for its classification**: the block resolves the live system address once, after its pre-block steps, and an EVM built outside block execution reads it once when it is built, directly off its database, so gas and the read set depend neither on the envelope type nor on whether the transaction runs in a block or in an estimate. - **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 held to the packing budgets and builder policy as any other non-deposit transaction**: only a deposit, which L1 derivation requires, is exempt; a block full on a budget refuses an MST as it refuses any later legacy transaction. -- **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. +- **Every block deploys the system contracts, as Rex6 does**, so Satin may be active from genesis: the five flat contracts by one rule, the registry kept, migrated from 1.0.0 or seeded from the bootstrap values, foreign registry code refusing the block; the activation block checks only the EIP-7997 factory, which nothing deploys; 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. - **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. @@ -486,7 +512,7 @@ Each is a decision with its reason; "in this pull request" means review the code 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. +- **Satin's one chain-configuration parameter is the `SequencerRegistry`'s bootstrap values**, under the Rex-era keys, read only by the registry's deployment to seed or migrate it; the limits stay per-spec constants. - **An absurd state-gas price makes the operation run out of gas**; no reachable divergence. - **The pending-changes due check uses the direct-read convention** (any database error is an internal error), as the other direct reads and upstream do. - **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. From aa1cd9b400eaf15f7b4358734d9e06b55c821f38 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 18:01:07 +0800 Subject: [PATCH 092/190] test(evm): kill the batch's mutation survivors, and suppress the two equivalent ones --- crates/mega-evm/src/block/genesis.rs | 138 ++++++++++++++++++ crates/mega-evm/src/evm/context.rs | 27 ++++ .../mega-evm/src/system/sequencer_registry.rs | 28 ++++ .../mega-evm/tests/system/keyless/deploy.rs | 45 +++++- mutants/suppressions.toml | 35 +++++ 5 files changed, 270 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index e7977481f..55de7f107 100644 --- a/crates/mega-evm/src/block/genesis.rs +++ b/crates/mega-evm/src/block/genesis.rs @@ -489,6 +489,144 @@ mod tests { ); } + /// What a serializer is told of a map and given for it: the length the map announces before + /// its entries, and the entries that follow. JSON ignores the announced length; a format that + /// writes it ahead of the entries, as a length-prefixed binary format does, relies on it. + #[derive(Debug, Default)] + struct MapShape { + announced: Option, + entries: usize, + } + + type ShapeError = serde::de::value::Error; + type NoCompound = serde::ser::Impossible<(), ShapeError>; + + /// Refuses every value that is not a map: the configuration serializes as one map. + macro_rules! only_a_map { + ($($method:ident($($arg:ty),*);)*) => { + $(fn $method(self, $(_: $arg),*) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + })* + }; + } + + impl serde::Serializer for &mut MapShape { + type Ok = (); + type Error = ShapeError; + type SerializeSeq = NoCompound; + type SerializeTuple = NoCompound; + type SerializeTupleStruct = NoCompound; + type SerializeTupleVariant = NoCompound; + type SerializeMap = Self; + type SerializeStruct = NoCompound; + type SerializeStructVariant = NoCompound; + + only_a_map! { + serialize_bool(bool); serialize_i8(i8); serialize_i16(i16); serialize_i32(i32); + serialize_i64(i64); serialize_u8(u8); serialize_u16(u16); serialize_u32(u32); + serialize_u64(u64); serialize_f32(f32); serialize_f64(f64); serialize_char(char); + serialize_str(&str); serialize_bytes(&[u8]); serialize_none(); serialize_unit(); + serialize_unit_struct(&'static str); + serialize_unit_variant(&'static str, u32, &'static str); + } + + fn serialize_some(self, _: &T) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_newtype_struct( + self, + _: &'static str, + _: &T, + ) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: &T, + ) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_seq(self, _: Option) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_tuple(self, _: usize) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_map(self, len: Option) -> Result { + self.announced = len; + Ok(self) + } + + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + } + + impl serde::ser::SerializeMap for &mut MapShape { + type Ok = (); + type Error = ShapeError; + + fn serialize_key(&mut self, _: &T) -> Result<(), ShapeError> { + self.entries += 1; + Ok(()) + } + + fn serialize_value(&mut self, _: &T) -> Result<(), ShapeError> { + Ok(()) + } + + fn end(self) -> Result<(), ShapeError> { + Ok(()) + } + } + + /// The configuration announces the number of entries it writes, four — `satinTime` and the + /// three bootstrap keys — so a format that writes the length ahead of the entries encodes it + /// as it is. + #[test] + fn test_the_configuration_announces_the_entries_it_writes() { + let mut shape = MapShape::default(); + config().serialize(&mut shape).unwrap(); + assert_eq!(shape.entries, 4, "satinTime and the three bootstrap keys"); + assert_eq!(shape.announced, Some(shape.entries), "the announced length"); + } + /// The schedule the configuration makes runs Satin from its activation, carries the bootstrap /// values, and passes the schedule's own check. #[test] diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 107ef40b5..7f5f6d21a 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1382,6 +1382,33 @@ mod tests { assert_cfg_is(&ctx, &cfg); } + /// Switching a context to the neutral configuration after an execution was prepared makes + /// that execution pay no history, and changes nothing else it was decided to be: the + /// protocol's own work stays exempt from every per-transaction limit and undetained, and a + /// user's transaction stays held to them. + #[test] + fn test_switching_to_the_neutral_configuration_keeps_what_the_execution_is() { + for (case, own) in [ + ("a call from the system address", true), + ("a system call", true), + ("a user's transaction", false), + ] { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + match case { + "a system call" => ctx.on_new_system_call(), + _ => { + let caller = if own { SYSTEM_ADDRESS } else { Address::repeat_byte(0x11) }; + ctx.set_tx(call_from(caller)); + ctx.on_new_tx(false); + } + } + let ctx = ctx.with_neutral_cfg(osaka_cfg()); + assert!(!ctx.prices_history(), "{case}: the neutral configuration prices none"); + assert_eq!(ctx.is_system_originated(), own, "{case}"); + assert_eq!(ctx.additional_limit.is_exempt(), own, "{case}"); + } + } + /// [`MegaContext::with_cfg`] returns a neutral context to the spec's configuration, and its /// transactions pay history again. #[test] diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index f4890de0f..40a7077ae 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -934,6 +934,34 @@ mod tests { assert_eq!(live_system_address(wrapped).unwrap(), Some(NEXT_SYSTEM_ADDRESS)); } + /// Each registry error says what went wrong: a zero bootstrap value names its key, a database + /// failure is the database's error, which it also hands on as its source, an unusable bootstrap + /// says the configuration carries no usable values, and a refusal says what the registry holds; + /// only a database failure has a source. + #[test] + fn test_the_registry_errors_name_their_cause() { + use core::error::Error as _; + let zero = ZeroBootstrapValue { key: crate::REX6_MIN_ROTATION_DELAY_KEY }; + assert_eq!( + zero.to_string(), + "the SequencerRegistry's bootstrap value `rex6MinRotationDelay` is zero" + ); + + let database = SequencerRegistryError::Database(fmt::Error); + assert_eq!(database.to_string(), fmt::Error.to_string()); + let source = database.source().map(|source| source.to_string()); + assert_eq!(source, Some(fmt::Error.to_string()), "the database's error is the source"); + + let unusable = SequencerRegistryError::::UnusableBootstrap; + assert!(unusable.to_string().contains("no usable bootstrap values"), "{unusable}"); + assert!(unusable.source().is_none()); + + let refusal = SequencerRegistryRefusal::NoSystemAddress; + let refused = SequencerRegistryError::::Refused(refusal.clone()); + assert_eq!(refused.to_string(), refusal.to_string()); + assert!(refused.source().is_none()); + } + /// A read the database cannot serve is the database's error, in the resolution, the /// deployment and the direct read alike: never an absent registry or a refused block. #[test] diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 32c3c03af..3d4adc063 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -159,10 +159,18 @@ impl revm::Inspector, revm::interpreter::interpret /// where the call holds no reservoir to share with its creation: returns the outcome and what the /// creation returned, its regular gas and its reservoir. fn deploy_forwarding(init_code: Bytes, forward: u64) -> (MegaTransactionOutcome, (u64, u64)) { + deploy_forwarding_on(system_db(), init_code, forward) +} + +/// [`deploy_forwarding`] over `db`. +fn deploy_forwarding_on( + db: MemoryDatabase, + init_code: Bytes, + forward: u64, +) -> (MegaTransactionOutcome, (u64, u64)) { let deployment = Deployment::signed(0, forward, U256::ZERO, init_code); - let mut evm = - MegaEvm::new(context(system_db()).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) - .with_inspector(CreationReturn::default()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) + .with_inspector(CreationReturn::default()); let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(forward), U256::ZERO); tx.0.base.gas_limit = GAS_LIMITS[0]; let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); @@ -416,6 +424,37 @@ fn test_a_constructor_that_destroys_itself_returns_its_account_as_reservoir() { } } +/// A constructor whose own account is destroyed in a frame that then reverts, and which returns +/// its code afterwards: the revert takes the destruction back, with what the destruction table +/// gave back, so the account stands and the deployment succeeds. `gasUsed` is what the creation +/// spent from its two pools taken together, on no reservoir its regular gas spent less the +/// reservoir it returned, with nothing added for the call's own charge for the account, which the +/// destruction gave back only while it stood. +#[test] +fn test_a_destruction_a_revert_took_back_adds_nothing_to_gas_used() { + const FORWARD: u64 = 500_000; + const DESTROYER: Address = address!("0x0000000000000000000000000000000000500001"); + // `HELPER`, run through a `DELEGATECALL`, has the creation's account destroyed by + // `DESTROYER`, run the same way, then reverts. + let helper = calling(BytecodeBuilder::default(), DESTROYER, DELEGATECALL) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let db = system_db() + .account_code(HELPER, helper) + .account_code(DESTROYER, Bytes::from_static(&[PUSH0, SELFDESTRUCT])); + let init_code = running(calling(BytecodeBuilder::default(), HELPER, DELEGATECALL)); + let address = Deployment::signed(0, FORWARD, U256::ZERO, init_code.clone()).address; + let (outcome, (regular, reservoir)) = deploy_forwarding_on(db, init_code, FORWARD); + let ret = returned(&outcome); + assert_eq!(ret.deployedAddress, address, "the destruction was taken back: the account stands"); + assert_eq!(code_hash(&outcome, address), Some(keccak(&runtime(1)))); + assert_eq!( + ret.gasUsed + regular + reservoir, + FORWARD, + "the creation's spend from both pools, and nothing added" + ); +} + /// A constructor that has its own account destroyed through a `DELEGATECALL` and then returns /// code reports `EmptyCodeDeployed`: the code the constructor returned is not code the account /// keeps (EIP-6780), and the answer is read from the account, not from the return. diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index f92faa38d..8899833c7 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -207,6 +207,41 @@ mutant = "replace for EthSpecId>::from -> Self with Defau justification = "Equivalent: revm's SpecId::OSAKA carries #[default], and Satin's sole rung (SATIN) maps to EthSpecId::OSAKA, so Default::default() returns the same value on every current input. test_all_specs_map_to_karst_and_osaka pins the mapping; if the upstream default moves, that test kills this mutant and the entry becomes a no-op." reviewer = "RealiCZ" +# --- MegaContext::prepare's deposit test (equivalent: the two classes behave alike) -------- +# `prepare` classes an execution that is neither the protocol's own nor neutral as +# `TxClass::Deposit` when the transaction is a deposit and as `TxClass::Ordinary` otherwise. +# The two classes are read in exactly two places, `AdditionalLimit::is_exempt` (both false) and +# `MegaContext::prices_history` (both true), so `==` -> `!=`, which swaps the two labels, changes +# nothing a transaction is held to or pays. A line entry keeps the mutant generated: once the two +# classes part on a rule, a test of that rule kills it and the entry becomes a no-op. +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/evm/context.rs" +mutant = "replace == with != in MegaContext::prepare" +justification = "Equivalent: the comparison only chooses between TxClass::Deposit and TxClass::Ordinary for an execution that is neither the protocol's own nor neutral, and every reader of the class treats the two alike (is_exempt false, prices_history true). Swapping them changes no limit, exemption, detention or history charge." +reviewer = "unreviewed: proposed by the implementer, for the owner's sign-off" + +# ───────────────────────────────────────────────────────────────────────────── +# crates/mega-evm/src/block/ survivors. + +# --- Entry::address's format check (equivalent: the parser enforces the same) ------------- +# `Entry::address` refuses a value unless it is `0x` and then 40 hexadecimal digits, and then +# parses the digits with `Address::from_str`, which is alloy's `FixedBytes::from_hex`: it strips +# an optional `0x` prefix, refuses an odd length, a length other than 40 digits and any +# non-hexadecimal byte. `||` -> `&&` lets through only digits that fail one test and pass the +# other — 40 bytes that are not all hexadecimal, or an all-hexadecimal string of another +# length — and the parser refuses every one of them, with the same `invalid()` error the check +# returns. A line entry keeps the mutant generated: if alloy's parser ever accepts such a string, +# the format tests of `genesis.rs` kill it. +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/block/genesis.rs" +mutant = "replace || with && in Entry::address" +justification = "Equivalent: every string the mutated check lets through (40 bytes not all hexadecimal, or all-hexadecimal of another length) is refused by Address::from_str (alloy's FixedBytes::from_hex: exact 40 hex digits after an optional 0x), and the refusal maps to the same invalid() error, so the result is identical for every input." +reviewer = "unreviewed: proposed by the implementer, for the owner's sign-off" + # ───────────────────────────────────────────────────────────────────────────── # Infrastructure scope (.cargo/mutants-infra.toml) survivors. From 131e0d0366b1dbad093aad4e1665279d5b117eba Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 18:05:31 +0800 Subject: [PATCH 093/190] fix(evm): seeding the registry over an existing account keeps its storage --- .claude/skills/satin-review/SKILL.md | 2 +- AGENTS.md | 2 +- crates/mega-evm/src/system/AGENTS.md | 2 +- .../mega-evm/src/system/sequencer_registry.rs | 73 +++++++++++++------ crates/mega-evm/tests/block/predeploys.rs | 63 ++++++++++++++-- docs/spec/upgrades/satin.md | 2 +- 6 files changed, 114 insertions(+), 30 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 8bdb0f725..f32468da2 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -365,7 +365,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. 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. - - Every block deploys the six system contracts, as Rex6 does (`system/predeploys.rs`, `system/sequencer_registry.rs`): the five flat contracts are installed where missing, have their code replaced where it differs, nonce, balance and storage kept, and are a read-only entry where they hold Satin's code; the registry is a read-only entry at version 2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the schedule's bootstrap values where its address holds no code, and any other code refuses the block (`MegaBlockExecutionError::SequencerRegistry`); a block that must seed or migrate it on a schedule without usable bootstrap values fails with an internal error. + - Every block deploys the six system contracts, as Rex6 does (`system/predeploys.rs`, `system/sequencer_registry.rs`): the five flat contracts are installed where missing, have their code replaced where it differs, nonce, balance and storage kept, and are a read-only entry where they hold Satin's code; the registry is a read-only entry at version 2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the schedule's bootstrap values where its address holds no code — an existing account's nonce, balance and storage kept, the seeded slots written over them, and the account marked created only where none stood, as every system contract's deployment keeps an existing account's storage — and any other code refuses the block (`MegaBlockExecutionError::SequencerRegistry`); a block that must seed or migrate it on a schedule without usable bootstrap values fails with an internal error. The block in which Satin activates (`MegaBlockExecutor::is_satin_activation_block`, derived from the schedule, the block's timestamp and the parent's) also checks the EIP-7997 factory, a read-only entry that must hold exactly its code whatever its nonce, balance and storage, or the block is invalid with `UnexpectedSystemContractCode`; no other block reads the factory. A registry that is absent, holds other code or names the zero address when the address is resolved refuses the block. - An Oracle read in a system call reads chain storage, never the oracle service. diff --git a/AGENTS.md b/AGENTS.md index 72658209c..40bc3cf0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -289,7 +289,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Which transaction is first is decided at the commit: an outcome carries its reads beside its returned state, which holds what its executor would report if it committed it next, and the commit takes that out and adds what the committing executor has not reported, so an outcome another executor executed, or one executed before another commit, reports each key once, with the first transaction committed; an outcome committed where it executed, before anything else was committed, is committed as it was returned (`tests/block/witness/state.rs`). A failed fee read is a failed read of the transaction's execution, routed by whether the database declares it fatal; a failed footprint read is always an internal error. The block-side classification of a Mega System Transaction reads the address the EVM holds, which the pre-block steps resolved (see below). -- Every block deploys the six system contracts, as Rex6 does, so Satin may be active from genesis: the Oracle (v2.0.0), the high-precision timestamp, `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl` are each installed where missing, have their code replaced, nonce, balance and storage kept, where it differs, and are committed as a read-only entry where they hold it (`deploy_system_contract`, `flat_system_contract_specs`, `system/predeploys.rs`); the `SequencerRegistry` (v2.0.0) is read when it holds v2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the bootstrap values where its address holds no code, and refuses the block over any other code (`deploy_sequencer_registry`, `MegaBlockExecutionError::SequencerRegistry`); a block that must seed or migrate it on a schedule without usable bootstrap values fails with an internal error (`MegaBlockExecutionError::UnusableRegistryBootstrap`). +- Every block deploys the six system contracts, as Rex6 does, so Satin may be active from genesis: the Oracle (v2.0.0), the high-precision timestamp, `KeylessDeploy`, `MegaAccessControl` and `MegaLimitControl` are each installed where missing, have their code replaced, nonce, balance and storage kept, where it differs, and are committed as a read-only entry where they hold it (`deploy_system_contract`, `flat_system_contract_specs`, `system/predeploys.rs`); the `SequencerRegistry` (v2.0.0) is read when it holds v2.0.0, migrated in place from 1.0.0 writing slot 13 alone, seeded from the bootstrap values where its address holds no code — an existing account's nonce, balance and storage kept, the seeded slots written over them, and the account marked created only where none stood — and refuses the block over any other code (`deploy_sequencer_registry`, `MegaBlockExecutionError::SequencerRegistry`); a block that must seed or migrate it on a schedule without usable bootstrap values fails with an internal error (`MegaBlockExecutionError::UnusableRegistryBootstrap`). On a chain that ran Rex6 every deployment is a read-only entry. The block in which Satin activates also checks, before the deployments, that the EIP-7997 factory, which OP's genesis tooling preinstalls and nothing deploys, holds its code, whatever its nonce, balance and storage (`check_system_contract`, `create2_factory_spec`); anything else — no account, no code, other code — refuses the block with an error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and the read is a read-only pre-block state. The executor works out which block that is (`MegaBlockExecutor::is_satin_activation_block`) from its schedule, the block's timestamp and the parent's, which the node passes to `MegaBlockExecutionCtx::new` (`None` for a block with no parent; the genesis block, number zero, is no activation block); no other block reads the factory. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 1781cbbce..5a71f1d28 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 bootstrap values (`SequencerRegistryBootstrap`), its four pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness), `transact_apply_pending_changes` (the system call on `PRE_BLOCK_CALL_GAS_LIMIT`), `deploy_sequencer_registry` (read when it holds v2.0.0, migrated in place from v1.0.0 writing slot 13 alone, seeded from the bootstrap values where its address holds no code, refused over other code) and `resolve_system_address` (the block's live system address and its read-only state; a refusal for an absent registry, other code or a zero slot 0) — and `live_system_address`, the lenient direct read of a database an EVM built outside block execution makes when it is built (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 bootstrap values (`SequencerRegistryBootstrap`), its four pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness), `transact_apply_pending_changes` (the system call on `PRE_BLOCK_CALL_GAS_LIMIT`), `deploy_sequencer_registry` (read when it holds v2.0.0, migrated in place from v1.0.0 writing slot 13 alone, seeded from the bootstrap values where its address holds no code, an existing account's storage kept under the seeded slots, refused over other code) and `resolve_system_address` (the block's live system address and its read-only state; a refusal for an absent registry, other code or a zero slot 0) — and `live_system_address`, the lenient direct read of a database an EVM built outside block execution makes when it is built (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 five every block deploys by one rule (`flat_system_contract_specs`, `deploy_system_contract`: installed where missing, code replaced keeping nonce, balance and storage where it differs, a read-only entry where it holds the code), the EIP-7997 factory's constants (`create2_factory_spec`), and `check_system_contract`, the read Satin's activation block makes of the factory: 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. diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 40a7077ae..d91de0d33 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -341,9 +341,13 @@ where /// - version 1.0.0: migrated in place: its code replaced by version 2.0.0 and slot 13 /// (`_minRotationDelay`) written with the bootstrap's minimum rotation delay, every other slot — /// the roles, the pending changes, the histories — its nonce and its balance kept; -/// - no account, or an account without code: version 2.0.0 deployed new, an existing account's -/// nonce and balance kept and its storage cleared (the account is marked created), and seeded -/// with [`SequencerRegistryBootstrap::seed`] at `block_number`. +/// - no account: version 2.0.0 deployed new (the account is marked created, with nothing to clear) +/// and seeded with [`SequencerRegistryBootstrap::seed`] at `block_number`; +/// - an account without code: version 2.0.0 installed in it and seeded the same way, its nonce, its +/// balance and every storage slot kept, the seeded slots written over what they held (each with +/// the value the database holds as its original). The account is not marked created, which would +/// clear the storage in the step's state but not in what a node persists of it: the rule of every +/// other system contract's deployment, and of the migration from version 1.0.0. /// /// # Errors /// @@ -373,6 +377,7 @@ pub fn deploy_sequencer_registry( .filter(|bootstrap| bootstrap.validate().is_ok()) .ok_or(SequencerRegistryError::UnusableBootstrap)?; + let created = existing.is_none(); let mut info = existing.unwrap_or_default(); info.code_hash = SEQUENCER_REGISTRY_CODE_HASH; info.code = Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)); @@ -390,11 +395,22 @@ pub fn deploy_sequencer_registry( EvmStorageSlot::new_changed(original, delay, TransactionId::ZERO), ); } else { - registry.mark_created(); + // Where no account stood there is no storage to keep, and nothing to read. Over an + // existing account without code every slot is kept, and a seeded slot is written over the + // value the database holds. + if created { + registry.mark_created(); + } for (slot, value) in bootstrap.seed(block_number) { + let original = if created { + U256::ZERO + } else { + db.storage(SEQUENCER_REGISTRY_ADDRESS, slot) + .map_err(SequencerRegistryError::Database)? + }; registry .storage - .insert(slot, EvmStorageSlot::new_changed(U256::ZERO, value, TransactionId::ZERO)); + .insert(slot, EvmStorageSlot::new_changed(original, value, TransactionId::ZERO)); } } Ok(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)])) @@ -747,8 +763,10 @@ mod tests { /// Where the address has no account, the deployment installs version 2.0.0 as a new contract /// seeded with the seven flat slots: the system address both current and initial, the /// bootstrap's sequencer both current and initial, its admin, the block number and its - /// minimum rotation delay. Where it holds an account without code, the account's nonce and - /// balance are kept and its storage goes: the account is marked created. + /// minimum rotation delay. Where it holds an account without code, version 2.0.0 is installed + /// in it and seeded the same way, and the account keeps its nonce, its balance and every slot: + /// it is not marked created, a slot the seed does not write keeps its value, and a seeded slot + /// that held a value has it as its original and the seed as its present value. #[test] fn test_the_deployment_seeds_a_new_registry() { let expected_storage = [ @@ -768,28 +786,41 @@ mod tests { funded .insert_account_storage(SEQUENCER_REGISTRY_ADDRESS, U256::from(42), U256::ONE) .unwrap(); - for (mut db, nonce, balance) in - [(InMemoryDB::default(), 0, U256::ZERO), (funded, 3, U256::from(9))] - { + funded.insert_account_storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN, U256::from(77)).unwrap(); + for (case, mut db, nonce, balance) in [ + ("no account", InMemoryDB::default(), 0, U256::ZERO), + ("an account without code", funded, 3, U256::from(9)), + ] { + let existed = nonce != 0; let registry = deployed(&mut db, Some(BOOTSTRAP)).expect("the registry is seeded"); - assert!(registry.is_touched() && registry.is_created(), "a new contract"); - assert_eq!((registry.info.nonce, registry.info.balance), (nonce, balance)); - assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - let seeded: Vec<_> = registry + assert!(registry.is_touched(), "{case}"); + assert_eq!(registry.is_created(), !existed, "{case}: created only where none stood"); + assert_eq!((registry.info.nonce, registry.info.balance), (nonce, balance), "{case}"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH, "{case}"); + let mut seeded: Vec<_> = registry .storage .iter() .map(|(slot, value)| (*slot, value.original_value(), value.present_value())) .collect(); - let mut expected: Vec<_> = - expected_storage.iter().map(|&(slot, value)| (slot, U256::ZERO, value)).collect(); - expected.sort(); - let mut seeded = seeded; seeded.sort(); - assert_eq!(seeded, expected); + let mut expected: Vec<_> = expected_storage + .iter() + .map(|&(slot, value)| { + let original = + if existed && slot == ADMIN { U256::from(77) } else { U256::ZERO }; + (slot, original, value) + }) + .collect(); + expected.sort(); + assert_eq!(seeded, expected, "{case}"); db.commit(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)])); - assert_eq!(db.storage(SEQUENCER_REGISTRY_ADDRESS, U256::from(42)).unwrap(), U256::ZERO); - assert_eq!(live_system_address(&mut db).unwrap(), Some(MEGA_SYSTEM_ADDRESS)); + let kept = if existed { U256::ONE } else { U256::ZERO }; + let slot_42 = db.storage(SEQUENCER_REGISTRY_ADDRESS, U256::from(42)).unwrap(); + assert_eq!(slot_42, kept, "{case}: a slot the seed does not write is kept"); + let admin = db.storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN).unwrap(); + assert_eq!(admin, word(CURRENT_SEQUENCER_ADDRESS), "{case}: the seed wins"); + assert_eq!(live_system_address(&mut db).unwrap(), Some(MEGA_SYSTEM_ADDRESS), "{case}"); } } diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 31c19c6bd..32ba725ad 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -242,11 +242,12 @@ fn test_a_system_contract_holding_other_code_is_rewritten_keeping_its_storage() } /// Where the state holds no registry, or an account without code at its address, the block -/// deploys version 2.0.0 new, seeded from the configuration's bootstrap values: the system address +/// deploys version 2.0.0, seeded from the configuration's bootstrap values: the system address /// both current and initial, the configured sequencer both current and initial, the configured -/// admin, the block's number as its first block and the configured minimum rotation delay. An -/// existing account keeps its nonce and its balance. The resolution then names the system address -/// the seed wrote, and the next block finds the registry as the block left it. +/// admin, the block's number as its first block and the configured minimum rotation delay. Where +/// no account stood the registry is created; an existing account is not, and keeps its nonce and +/// its balance. The resolution then names the system address the seed wrote, and the next block +/// finds the registry as the block left it. /// /// Expected values: independent (the bootstrap values and the block number the test uses). #[test] @@ -270,7 +271,8 @@ fn test_a_registry_the_state_does_not_hold_is_seeded_from_the_bootstrap_values() let states = start(&mut state, after_activation_ctx()); assert_eq!(named_accounts(&states), expected_accounts(false), "{case}"); let registry = &states[REGISTRY_DEPLOYMENT][&SEQUENCER_REGISTRY_ADDRESS]; - assert!(registry.is_touched() && registry.is_created(), "{case}: deployed new"); + assert!(registry.is_touched(), "{case}: deployed"); + assert_eq!(registry.is_created(), case == "no account", "{case}: created where none stood"); assert_eq!(registry.info.balance, balance, "{case}: the balance is kept"); let seeded: std::collections::BTreeMap<_, _> = registry.storage.iter().map(|(slot, value)| (*slot, value.present_value())).collect(); @@ -292,6 +294,57 @@ fn test_a_registry_the_state_does_not_hold_is_seeded_from_the_bootstrap_values() } } +/// Seeding the registry over an account without code keeps the account's storage, as every system +/// contract's deployment and the migration from 1.0.0 keep it: committed through revm's `State`, as +/// a node commits, a slot the seed does not write reads what it held in the seeding block and in +/// the next, and the block's bundle neither destroys the account nor claims to know its storage, +/// so what a node persists holds the slot too. A seeded slot that held a value has it as its +/// original and the seed as its present value; the nonce and the balance are kept. +/// +/// Expected values: independent (the slots, the nonce and the balance the test puts in the state, +/// and the bootstrap values). +#[test] +fn test_seeding_the_registry_over_an_account_without_code_keeps_its_storage() { + use revm::database::states::bundle_state::BundleRetention; + const KEPT: U256 = U256::from_limbs([42, 0, 0, 0]); + let mut db = common::database(); + db.cache.accounts.remove(&SEQUENCER_REGISTRY_ADDRESS); + db.set_account_nonce(SEQUENCER_REGISTRY_ADDRESS, 2); + db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(3)); + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, KEPT, U256::ONE); + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN, U256::from(77)); + // With its transitions kept for the bundle, as a node's state keeps them. + let mut state = State::builder().with_database(db).with_bundle_update().build(); + + let states = start(&mut state, after_activation_ctx()); + let registry = &states[REGISTRY_DEPLOYMENT][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(registry.is_touched() && !registry.is_created(), "installed in the account, kept"); + let admin = ®istry.storage[&ADMIN]; + assert_eq!( + (admin.original_value(), admin.present_value()), + (U256::from(77), word(common::ADMIN)), + "a seeded slot is written over what it held" + ); + assert!(!registry.storage.contains_key(&KEPT), "a slot the seed does not write is not touched"); + assert_eq!(state.storage(SEQUENCER_REGISTRY_ADDRESS, KEPT).unwrap(), U256::ONE, "in the block"); + assert_eq!(state.storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN).unwrap(), word(common::ADMIN)); + let info = state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().expect("the registry"); + assert_eq!((info.nonce, info.balance), (2, U256::from(3)), "the nonce and balance are kept"); + assert_eq!(info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_resolves(&states[RESOLUTION], MEGA_SYSTEM_ADDRESS); + + state.merge_transitions(BundleRetention::Reverts); + let persisted = state.bundle_state.account(&SEQUENCER_REGISTRY_ADDRESS).expect("changed"); + assert!(!persisted.was_destroyed(), "the bundle does not destroy the account"); + assert_eq!(persisted.storage_slot(KEPT), None, "nor claims its unwritten slots are empty"); + assert_eq!(persisted.storage_slot(ADMIN), Some(word(common::ADMIN))); + + let next = start(&mut state, after_activation_ctx()); + assert!(!next[REGISTRY_DEPLOYMENT][&SEQUENCER_REGISTRY_ADDRESS].is_touched(), "read-only"); + let kept = state.storage(SEQUENCER_REGISTRY_ADDRESS, KEPT).unwrap(); + assert_eq!(kept, U256::ONE, "in the next block"); +} + /// A registry at version 1.0.0 is migrated in place: its code becomes 2.0.0 and its slot 13 /// the configured minimum rotation delay, the one slot written; its roles and every other slot are /// what they were, so the resolution names the system address it already held. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 53b694601..9a306a410 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1355,7 +1355,7 @@ An out-of-gas step halts the call, consuming its regular gas. The `SequencerRegistry` holds roles and histories, and is deployed by its own rule: - at version 2.0.0, it is left as it is and recorded as a read-only entry; - at version 1.0.0, it is migrated in place: its code replaced by version 2.0.0, its slot 13 (`_minRotationDelay`) written with the configured minimum rotation delay, and every other slot, its nonce and its balance kept; - - an address with no account, or an account without code, receives version 2.0.0 as a new contract, an existing account's nonce and balance kept and its storage cleared, seeded with: slots 0 and 4 (the current and initial system address) `0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d`, slots 1 and 5 (the current and initial sequencer) the configured initial sequencer, slot 2 (the admin) the configured initial admin, slot 6 (`_initialFromBlock`) the block's number, and slot 13 the configured minimum rotation delay; + - an address with no account, or an account without code, receives version 2.0.0, an existing account's nonce, balance and storage kept as every system contract's deployment keeps them, and is seeded with, each seeded slot written over what it held: slots 0 and 4 (the current and initial system address) `0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d`, slots 1 and 5 (the current and initial sequencer) the configured initial sequencer, slot 2 (the admin) the configured initial admin, slot 6 (`_initialFromBlock`) the block's number, and slot 13 the configured minimum rotation delay; - any other code MUST make the block invalid: the registry's storage is never overwritten by code it was not migrated to. The configured values are the chain configuration's bootstrap keys, the ones the Rex era introduced (see the chain configuration under [Node integrators](#node-integrators)); once the registry holds its roles, its storage, not the configuration, decides them. From b614f4a55f1af7e0aa225afa69a7b47cf56ec456 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 13 Nov 2026 18:10:52 +0800 Subject: [PATCH 094/190] test(mutants): name the prepare survivor as cargo-mutants names it --- mutants/suppressions.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 8899833c7..09e734d14 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -207,7 +207,7 @@ mutant = "replace for EthSpecId>::from -> Self with Defau justification = "Equivalent: revm's SpecId::OSAKA carries #[default], and Satin's sole rung (SATIN) maps to EthSpecId::OSAKA, so Default::default() returns the same value on every current input. test_all_specs_map_to_karst_and_osaka pins the mapping; if the upstream default moves, that test kills this mutant and the entry becomes a no-op." reviewer = "RealiCZ" -# --- MegaContext::prepare's deposit test (equivalent: the two classes behave alike) -------- +# --- MegaContext::prepare's deposit test (equivalent: the two classes behave alike) --------- # `prepare` classes an execution that is neither the protocol's own nor neutral as # `TxClass::Deposit` when the transaction is a deposit and as `TxClass::Ordinary` otherwise. # The two classes are read in exactly two places, `AdditionalLimit::is_exempt` (both false) and @@ -218,7 +218,7 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/evm/context.rs" -mutant = "replace == with != in MegaContext::prepare" +mutant = "replace == with != in MegaContext::prepare" justification = "Equivalent: the comparison only chooses between TxClass::Deposit and TxClass::Ordinary for an execution that is neither the protocol's own nor neutral, and every reader of the class treats the two alike (is_exempt false, prices_history true). Swapping them changes no limit, exemption, detention or history charge." reviewer = "unreviewed: proposed by the implementer, for the owner's sign-off" From 8fa875039dc7b34ed935736a04c1e9255825d017 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 16 Nov 2026 09:58:26 +0800 Subject: [PATCH 095/190] test(mutants): the owner signed off the two equivalent survivors --- mutants/suppressions.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 09e734d14..ebae1adf8 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -220,7 +220,7 @@ category = "equivalent" file = "crates/mega-evm/src/evm/context.rs" mutant = "replace == with != in MegaContext::prepare" justification = "Equivalent: the comparison only chooses between TxClass::Deposit and TxClass::Ordinary for an execution that is neither the protocol's own nor neutral, and every reader of the class treats the two alike (is_exempt false, prices_history true). Swapping them changes no limit, exemption, detention or history charge." -reviewer = "unreviewed: proposed by the implementer, for the owner's sign-off" +reviewer = "RealiCZ" # ───────────────────────────────────────────────────────────────────────────── # crates/mega-evm/src/block/ survivors. @@ -240,7 +240,7 @@ category = "equivalent" file = "crates/mega-evm/src/block/genesis.rs" mutant = "replace || with && in Entry::address" justification = "Equivalent: every string the mutated check lets through (40 bytes not all hexadecimal, or all-hexadecimal of another length) is refused by Address::from_str (alloy's FixedBytes::from_hex: exact 40 hex digits after an optional 0x), and the refusal maps to the same invalid() error, so the result is identical for every input." -reviewer = "unreviewed: proposed by the implementer, for the owner's sign-off" +reviewer = "RealiCZ" # ───────────────────────────────────────────────────────────────────────────── # Infrastructure scope (.cargo/mutants-infra.toml) survivors. From 818bf699ed52fa937cf99e923978333a1b86f0ca Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 16 Nov 2026 10:49:57 +0800 Subject: [PATCH 096/190] test(system): a system transaction short of its body's history is a failed deposit --- crates/mega-evm/tests/system/system_tx.rs | 69 +++++++++++++++++++++-- 1 file changed, 65 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index e45ebbec5..f0eb6bf49 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -28,7 +28,7 @@ use revm::{ }; use crate::common::{ - account_state_gas, block, context, state_is_free, system_db, CALLER, GAS_LIMIT, + account_state_gas, block, body_history, context, state_is_free, system_db, CALLER, GAS_LIMIT, }; /// The chain the tests run on. @@ -43,6 +43,10 @@ const FUNDS: u64 = 1_000_000_000_000_000; /// The Oracle's slot the system transactions write. const ORACLE_SLOT: U256 = U256::ZERO; +/// The intrinsic regular gas of a call carrying no value, no calldata and no access list: +/// EIP-2780's base of 12,000 and 3,000 for the recipient. It is the call's floor too. +const BARE_CALL_INTRINSIC_GAS: u64 = 12_000 + 3_000; + /// A database with the system contracts in place and the registry naming /// [`MEGA_SYSTEM_ADDRESS`] the current system address: that is what makes a legacy call from it /// to the Oracle a system-address transaction, and what lets its Oracle write through. @@ -665,6 +669,64 @@ fn test_a_system_transaction_pays_history_gas() { ); } +/// A system transaction from an existing system address to the Oracle carrying no calldata, on +/// `gas_limit`. Its intrinsic regular gas is [`BARE_CALL_INTRINSIC_GAS`], and its body is +/// `TX_BODY_SIZE` bytes. +fn bare_system_tx(gas_limit: u64) -> MegaTransaction { + let mut tx = + legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), Bytes::new(), 0); + tx.0.base.gas_limit = gas_limit; + tx +} + +/// A system transaction whose gas limit is one short of its intrinsic regular gas plus its body's +/// history passes its own checks and is promoted to a deposit, whose intrinsic check it then +/// fails: it is included as a failed deposit, not refused, and starts no frame, so the Oracle's +/// code, which would revert on the empty input, does not run. It bumps the system address's nonce +/// and changes nothing else, reports its whole gas limit as regular gas, on its own ledgers and on +/// the block's, and no history gas, and keeps its body's bytes. At the gas limit that covers both, +/// it is admitted and runs: a recipient that stops at once succeeds, paying its intrinsic regular +/// gas and its body's history. +/// +/// Independence: constants — the intrinsic regular gas is EIP-2780's for a bare call, the body's +/// history its `TX_BODY_SIZE` bytes at the price in effect, by hand. +#[test] +fn test_a_system_transaction_short_of_its_body_history_is_a_failed_deposit() { + let least = BARE_CALL_INTRINSIC_GAS + body_history(0); + let existing = || chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(FUNDS)); + + let mut evm = MegaEvm::new(chain_context(existing())).with_inspector(GasInspector::new()); + let outcome = evm.execute_transaction(bare_system_tx(least - 1)).expect("it is included"); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?} is not a failed deposit", + outcome.result, + ); + assert!(evm.inspector().trace.is_none(), "the transaction starts no frame"); + let gas = &outcome.gas; + assert_eq!((gas.regular, gas.state, gas.history), (least - 1, 0, 0)); + assert_eq!(gas.history_bytes, mega_evm::TX_BODY_SIZE, "the body's bytes stay"); + assert_eq!((gas.gas_used, gas.block_execution_gas()), (least - 1, least - 1)); + let touched: Vec
= + outcome.state.iter().filter(|(_, account)| account.is_touched()).map(|(a, _)| *a).collect(); + assert_eq!(touched, [MEGA_SYSTEM_ADDRESS], "the failed deposit changes its sender alone"); + let sender = &outcome.state[&MEGA_SYSTEM_ADDRESS].info; + assert_eq!((sender.nonce, sender.balance), (1, U256::from(FUNDS))); + + let stops = existing().account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[STOP])); + let outcome = run_outcome(stops, bare_system_tx(least)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let gas = &outcome.gas; + assert_eq!( + (gas.regular, gas.state, gas.history), + (BARE_CALL_INTRINSIC_GAS, 0, body_history(0)) + ); + assert_eq!(gas.gas_used, least); +} + /// A deposit-like transaction whose caller does not exist yet creates that account, and pays /// the account-creation charge for it exactly once: the same charge a value transfer to a /// fresh account pays. @@ -737,11 +799,10 @@ fn test_a_deposit_that_creates_two_accounts_pays_for_both() { /// A deposit from `sender`, an account that does not exist, to the Oracle, whose gas limit is one /// short of its intrinsic gas and the account it creates for its caller, at the byte prices in /// effect. It carries no value and no calldata, so its intrinsic gas, which is its floor too, is -/// EIP-2780's base of 12,000 and 3,000 for the recipient. +/// [`BARE_CALL_INTRINSIC_GAS`]. fn deposit_one_short_of_its_caller(sender: Address) -> MegaTransaction { - const INTRINSIC: u64 = 12_000 + 3_000; let mut tx = deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); - tx.0.base.gas_limit = INTRINSIC + account_state_gas() - 1; + tx.0.base.gas_limit = BARE_CALL_INTRINSIC_GAS + account_state_gas() - 1; tx } From 7127d1b266f01084a5d6a5e52f27824846020017 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 16 Nov 2026 10:53:57 +0800 Subject: [PATCH 097/190] docs: state the per-block deployment, the factory-only activation check and reservoir-only give-backs --- crates/mega-evm/benches/block.rs | 4 ++-- crates/mega-evm/src/access/mod.rs | 7 +++++-- crates/mega-evm/src/system/keyless/dispatch.rs | 4 ++-- crates/mega-evm/src/system/keyless/mod.rs | 5 +++-- crates/mega-evm/src/system/mod.rs | 3 ++- crates/mega-evm/src/test_utils/database.rs | 7 +++++-- crates/mega-evm/tests/system/predeploys.rs | 5 +++-- docs/spec/upgrades/satin.md | 3 ++- 8 files changed, 24 insertions(+), 14 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 3bb7f0623..35428a054 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -4,8 +4,8 @@ //! Every block runs as a node runs one: //! //! - on a state that holds the seven predeploys as a chain that ran Rex6 holds them, with what the -//! previous block's pre-block changes left: no block but Satin's activation block reads the -//! predeploys, and none deploys them; +//! previous block's pre-block changes left: every block deploys the system contracts, which on +//! that state only reads them, and only Satin's activation block reads the EIP-7997 factory; //! - with the EIP-2935 and EIP-4788 contracts' own code, so the pre-block calls record the parent //! hash and the beacon root; //! - under the spec's limits, `ProtocolLimits::for_spec`: the production data-size limits and gas diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index c63f2ba7a..375aed521 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -89,8 +89,11 @@ //! - **a frame's start and every resume**: a frame that starts, and a caller a child returned into, //! is held to what the limit leaves then. A child's read holds its callers as they resume, and //! the gas a child hands back cannot be computed with past the limit; -//! - **a storage write restored to its original value**: it refills state and history gas that -//! spilled onto regular gas, possibly before the read, onto the spendable part. +//! - **a storage write restored to its original value**: under EIP-8037's own give-backs, which +//! only the neutral configuration keeps, it refills state and history gas that spilled onto +//! regular gas, possibly before the read, onto the spendable part. Under Satin's a give-back +//! credits the reservoir alone, so regular gas never rises from it and the hold finds nothing +//! grown. //! //! So a transaction that read volatile data 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, diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 2467ea330..80f74a66e 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -117,8 +117,8 @@ pub(crate) fn is_dispatched( /// Any other call is built as a call to the contract, whose code it never runs: its actions are /// made by hand, its first by [`start`]. The dispatch is by address, selector and decoded /// arguments, 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. +/// built on the contract's own. A block Satin runs holds it: every block deploys it before its +/// transactions, where it is missing or holds other code. #[inline(never)] pub(crate) fn ready( ctx: &mut MegaContext, diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 5c3283d14..c272aa6cd 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -30,8 +30,9 @@ //! - 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, selector and arguments that decode, whatever the address holds: -//! 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. +//! where the state holds no contract code, the frame is built on the contract's own. A block +//! Satin runs holds it: every block deploys it before its transactions, where it is missing or +//! holds other code. //! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. //! - The creation runs at depth 1, as the call's child: one level below the same init code sent as //! a creation transaction, which runs at depth 0. Its frames reach the call-stack limit one frame diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index 13b4723a7..e64504a73 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -6,7 +6,8 @@ //! [`SequencerRegistry`](sequencer_registry). Each module carries its address, the code and code //! hash the `mega-system-contracts` crate ships, and its ABI. The EIP-7997 `CREATE2` factory //! lives at its canonical address beside them; [`predeploys`] is the single list of all seven, -//! with the check Satin's activation block makes of them. +//! with every block's deployment of the five flat contracts and the check Satin's activation +//! block makes of the factory. //! //! Four of them have an interceptor: a `CALL` or `STATICCALL` to one of their intercepted //! selectors is answered by the engine instead of by the contract's code (see the `intercept` diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs index 68feb8159..d5899f01c 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -58,8 +58,11 @@ pub fn rex6_predeploys( /// [`rex6_predeploys`] or [`MemoryDatabase::sequencer_registry`]. /// /// Test and tool support, not a chain parameter: the legacy forks deploy the registry (Rex5) and -/// upgrade it to v2.0.0 (Rex6), and Satin neither creates nor seeds it, so a state Satin runs a -/// block on must already hold it. +/// upgrade it to v2.0.0 (Rex6). Every Satin block deploys it too: it reads a registry at v2.0.0, +/// migrates one at 1.0.0 in place, and seeds one where its address holds no code, naming +/// `MEGA_SYSTEM_ADDRESS` its system address and taking its sequencer, admin and minimum rotation +/// delay from the schedule's bootstrap values. A state that holds the registry with these roles is +/// one a chain that ran Rex6 left, which a Satin block only reads. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct SequencerRegistryRoles { /// The live system address, and the initial one. diff --git a/crates/mega-evm/tests/system/predeploys.rs b/crates/mega-evm/tests/system/predeploys.rs index b0d010ec3..22981396f 100644 --- a/crates/mega-evm/tests/system/predeploys.rs +++ b/crates/mega-evm/tests/system/predeploys.rs @@ -1,5 +1,6 @@ -//! The predeploys and the check Satin's activation block makes of them: the list, a matching -//! account read as it is, and every other account refused with one error. +//! The predeploys and the check of an account against one of them, which Satin's activation block +//! makes of the EIP-7997 factory: the list, a matching account read as it is, and every other +//! account refused with one error. use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use mega_evm::{ diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 9a306a410..d2a2d3876 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1503,7 +1503,8 @@ A node that meets the failure cannot execute the block past that transaction: it A block MUST be invalid when: - a pre-block call does not succeed (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); -- it is the block in which Satin activates, and a system-contract address or the factory's does not hold the code Satin expects (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); +- it is the block in which Satin activates, and the EIP-7997 factory's address does not hold the code Satin expects: every block installs the system contracts themselves, so only the factory is checked (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); +- its `SequencerRegistry` holds code its deployment cannot migrate, or the resolution of the live system address finds the registry absent, holding other code or naming no system address (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); - it contains a transaction the rules above skip. ### 22. The Stateless Witness From 8b5870a0339482c17d4f74879512f93b0af4e293 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 16 Nov 2026 12:18:29 +0800 Subject: [PATCH 098/190] test(evm): cover registry recovery and nested keyless destruction --- crates/mega-evm/src/block/chain.rs | 12 ++++++ .../mega-evm/src/system/sequencer_registry.rs | 23 ++++++++++ crates/mega-evm/tests/block/predeploys.rs | 37 ++++++++++++++++ .../mega-evm/tests/system/keyless/deploy.rs | 42 +++++++++++++++++++ crates/mega-evm/tests/system/system_tx.rs | 36 ++++++++++++++++ 5 files changed, 150 insertions(+) diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index 8f427a7a3..77f19104a 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -106,6 +106,18 @@ mod tests { use super::*; use crate::{MegaHardforks, MegaSpecId}; + #[test] + fn test_an_unscheduled_chain_needs_no_registry_bootstrap() { + let activation = + ChainActivation { chain_id: 123, satin: None, sequencer_registry_bootstrap: None }; + + let schedule = activation.hardforks(); + + assert_eq!(schedule.sequencer_registry_bootstrap(), None); + assert_eq!(schedule.spec_id(u64::MAX), None); + assert_eq!(schedule.validate_schedule(), Ok(())); + } + #[test] fn test_known_chains_have_satin_unscheduled() { assert_eq!(MAINNET_CHAIN_ID, 4326); diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index d91de0d33..386dcff6c 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -1021,4 +1021,27 @@ mod tests { Err(SequencerRegistryError::Database(_)) )); } + /// An unusable registry's diagnostic distinguishes absence from foreign code and names + /// the address and hashes the caller needs to repair its state. + #[test] + fn test_resolution_errors_describe_the_absent_or_foreign_registry() { + let absent = resolve_system_address(&mut InMemoryDB::default()).unwrap_err(); + assert_eq!( + absent.to_string(), + format!( + "the SequencerRegistry at {SEQUENCER_REGISTRY_ADDRESS} has no account when the block resolves its live system address" + ) + ); + + let found = alloy_primitives::keccak256([0x00]); + let foreign = + resolve_system_address(&mut registry_holding(Bytes::from_static(&[0x00]), None)) + .unwrap_err(); + assert_eq!( + foreign.to_string(), + format!( + "the SequencerRegistry at {SEQUENCER_REGISTRY_ADDRESS} must hold code hash {SEQUENCER_REGISTRY_CODE_HASH} when the block resolves its live system address; it holds code hash {found}" + ) + ); + } } diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 32ba725ad..9c8609821 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -449,6 +449,11 @@ fn test_a_registry_to_seed_or_migrate_without_bootstrap_values_is_an_internal_er let (_, started) = start_on(&mut state, unlimited_ctx(), without_bootstrap.clone()); let error = started.expect_err("the registry cannot be deployed"); assert_eq!(internal(&error), MegaBlockExecutionError::UnusableRegistryBootstrap, "{case}"); + assert_eq!( + internal(&error).to_string(), + "the SequencerRegistry must be seeded or migrated, and the chain configuration carries no usable bootstrap values for it", + "{case}" + ); } let (_, started) = start_on(&mut common::state(), unlimited_ctx(), without_bootstrap); started.expect("version 2.0.0 needs no bootstrap values"); @@ -679,3 +684,35 @@ fn test_a_create2_round_trip_through_the_factory() { other => panic!("the factory call should succeed, got {other:?}"), } } + +/// A migration's storage read failure remains a database error, with no verdict on the block. +#[test] +fn test_a_registry_migration_storage_failure_is_an_internal_database_error() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let mut db = ErrorInjectingDatabase::new( + common::database().account_code(SEQUENCER_REGISTRY_ADDRESS, V1_0_0_CODE), + ); + db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY)); + let mut state = State::builder().with_database(db).build(); + let evm = alloy_evm::EvmFactory::create_evm( + &mega_evm::MegaEvmFactory::new(), + &mut state, + common::evm_env(), + ); + let error = mega_evm::MegaBlockExecutor::new( + evm, + after_activation_ctx(), + activation_spec(), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ) + .apply_pre_execution_changes() + .expect_err("the migration cannot read the original delay"); + + assert!(matches!(error, BlockExecutionError::Internal(_)), "{error:?}"); + assert!(error.to_string().contains("injected storage() error"), "{error}"); + assert_eq!( + state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, + keccak256(V1_0_0_CODE), + "a failed migration commits no new code" + ); +} diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 3d4adc063..8a40f0f8b 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -562,6 +562,48 @@ fn test_keyless_deploy_creates_child_contract() { } } +/// A child's destruction gives back the child's leaf alone: the keyless deployment still +/// reports the code its own constructor kept. +#[test] +fn test_a_keyless_constructor_keeps_its_code_when_its_child_selfdestructs() { + for gas_limit in GAS_LIMITS { + let child_init = Bytes::from_static(&[ORIGIN, SELFDESTRUCT]); + let prefix = BytecodeBuilder::default() + .mstore(0, &child_init) + .push_number(child_init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(CREATE) + .append(POP); + let init_code = running(prefix); + let init_len = init_code.len(); + let deployment = Deployment::new(init_code); + + let outcome = deploy(system_db(), &deployment, gas_limit); + + let answer = returned(&outcome); + let [total, ..] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(init_len) + + entry(GasId::new_account_state_gas()) + + entry(GasId::create_state_gas()) + + 2 * record() + + answer.gasUsed, + "the child's give-back belongs to the constructor at {gas_limit}" + ); + assert_eq!(answer.deployedAddress, deployment.address, "at {gas_limit}"); + assert!(answer.errorData.is_empty(), "{:?}", answer.errorData); + assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&[0x00]))); + assert_eq!(nonce(&outcome, deployment.address), 2); + let child = &outcome.state[&deployment.address.create(1)]; + assert!(child.is_selfdestructed()); + assert!(child.info.code.as_ref().is_none_or(|code| code.is_empty())); + } +} + /// A constructor that reads another contract, and keeps what it read in its own storage. #[test] fn test_keyless_deploy_reads_existing_contract() { diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index f0eb6bf49..eaf56450c 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -318,6 +318,42 @@ fn test_no_transaction_reads_the_registry() { } } +/// A registry read that failed while building the context can succeed before the next +/// transaction. The recovered address classifies that transaction and is cached for later ones. +#[test] +fn test_a_failed_initial_registry_read_recovers_and_caches_the_system_address() { + let mut db = ErrorInjectingDatabase::new(chain_db()); + db.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + let mut evm = MegaEvm::new(chain_context(db)); + assert_eq!(evm.ctx().system_address(), None, "the initial read failed"); + evm.db_mut().fail_on_account = None; + + let first = evm + .execute_transaction(legacy_tx( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + get_slot(), + 0, + )) + .expect("the registry can now be read"); + assert!(first.result.is_success(), "{:?}", first.result); + assert!(evm.ctx().is_system_originated()); + assert!(!first.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS)); + + evm.db_mut().fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + let second = evm + .execute_transaction(legacy_tx( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + get_slot(), + 0, + )) + .expect("the recovered address is cached"); + assert!(second.result.is_success(), "{:?}", second.result); + assert!(evm.ctx().is_system_originated()); + assert!(!second.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS)); +} + /// A context built without an address reads the live system address off its database when it is /// built — the registry's account and its system-address slot, before any transaction — and a /// Mega System Transaction run on it is then classified against it and reads nothing more of the From 4d13b9883b2cbb8931344ce8964e316ed3a58186 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 16 Nov 2026 12:20:51 +0800 Subject: [PATCH 099/190] test(evm): move the serializer-shape check into the integration tests --- crates/mega-evm/src/block/genesis.rs | 138 ----------------------- crates/mega-evm/tests/block/schedule.rs | 144 +++++++++++++++++++++++- 2 files changed, 142 insertions(+), 140 deletions(-) diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index 55de7f107..e7977481f 100644 --- a/crates/mega-evm/src/block/genesis.rs +++ b/crates/mega-evm/src/block/genesis.rs @@ -489,144 +489,6 @@ mod tests { ); } - /// What a serializer is told of a map and given for it: the length the map announces before - /// its entries, and the entries that follow. JSON ignores the announced length; a format that - /// writes it ahead of the entries, as a length-prefixed binary format does, relies on it. - #[derive(Debug, Default)] - struct MapShape { - announced: Option, - entries: usize, - } - - type ShapeError = serde::de::value::Error; - type NoCompound = serde::ser::Impossible<(), ShapeError>; - - /// Refuses every value that is not a map: the configuration serializes as one map. - macro_rules! only_a_map { - ($($method:ident($($arg:ty),*);)*) => { - $(fn $method(self, $(_: $arg),*) -> Result<(), ShapeError> { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - })* - }; - } - - impl serde::Serializer for &mut MapShape { - type Ok = (); - type Error = ShapeError; - type SerializeSeq = NoCompound; - type SerializeTuple = NoCompound; - type SerializeTupleStruct = NoCompound; - type SerializeTupleVariant = NoCompound; - type SerializeMap = Self; - type SerializeStruct = NoCompound; - type SerializeStructVariant = NoCompound; - - only_a_map! { - serialize_bool(bool); serialize_i8(i8); serialize_i16(i16); serialize_i32(i32); - serialize_i64(i64); serialize_u8(u8); serialize_u16(u16); serialize_u32(u32); - serialize_u64(u64); serialize_f32(f32); serialize_f64(f64); serialize_char(char); - serialize_str(&str); serialize_bytes(&[u8]); serialize_none(); serialize_unit(); - serialize_unit_struct(&'static str); - serialize_unit_variant(&'static str, u32, &'static str); - } - - fn serialize_some(self, _: &T) -> Result<(), ShapeError> { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_newtype_struct( - self, - _: &'static str, - _: &T, - ) -> Result<(), ShapeError> { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_newtype_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: &T, - ) -> Result<(), ShapeError> { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_seq(self, _: Option) -> Result { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_tuple(self, _: usize) -> Result { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_tuple_struct( - self, - _: &'static str, - _: usize, - ) -> Result { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_tuple_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: usize, - ) -> Result { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_map(self, len: Option) -> Result { - self.announced = len; - Ok(self) - } - - fn serialize_struct(self, _: &'static str, _: usize) -> Result { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - - fn serialize_struct_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: usize, - ) -> Result { - Err(serde::ser::Error::custom("the configuration serializes as a map")) - } - } - - impl serde::ser::SerializeMap for &mut MapShape { - type Ok = (); - type Error = ShapeError; - - fn serialize_key(&mut self, _: &T) -> Result<(), ShapeError> { - self.entries += 1; - Ok(()) - } - - fn serialize_value(&mut self, _: &T) -> Result<(), ShapeError> { - Ok(()) - } - - fn end(self) -> Result<(), ShapeError> { - Ok(()) - } - } - - /// The configuration announces the number of entries it writes, four — `satinTime` and the - /// three bootstrap keys — so a format that writes the length ahead of the entries encodes it - /// as it is. - #[test] - fn test_the_configuration_announces_the_entries_it_writes() { - let mut shape = MapShape::default(); - config().serialize(&mut shape).unwrap(); - assert_eq!(shape.entries, 4, "satinTime and the three bootstrap keys"); - assert_eq!(shape.announced, Some(shape.entries), "the announced length"); - } - /// The schedule the configuration makes runs Satin from its activation, carries the bootstrap /// values, and passes the schedule's own check. #[test] diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index b9da9cc20..c167b0ba6 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -6,11 +6,13 @@ use alloy_op_hardforks::OpHardfork; use alloy_primitives::Address; use mega_evm::{ chain_activation, mainnet_hardforks, system::SequencerRegistryBootstrap, testnet_hardforks, - ChainActivation, MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError, - MAINNET_CHAIN_ID, REX5_INITIAL_ADMIN_KEY, REX5_INITIAL_SEQUENCER_KEY, + ChainActivation, MegaHardfork, MegaHardforkConfig, MegaHardforks, SatinChainConfig, + ScheduleError, MAINNET_CHAIN_ID, REX5_INITIAL_ADMIN_KEY, REX5_INITIAL_SEQUENCER_KEY, REX6_MIN_ROTATION_DELAY_KEY, TESTNET_CHAIN_ID, }; +use serde::Serialize; + use crate::common::{self, empty_call_gas, user_tx}; /// The canonical schedules are the chain activation table: the two are one source, so a @@ -263,3 +265,141 @@ fn test_forks_scheduled_by_block_are_not_checked() { let schedule = base_fork_case(OpHardfork::Bedrock, ForkCondition::Block(u64::MAX)); assert_eq!(schedule.validate_schedule(), Ok(())); } + +/// What a serializer is told of a map and given for it: the length the map announces before +/// its entries, and the entries that follow. JSON ignores the announced length; a format that +/// writes it ahead of the entries, as a length-prefixed binary format does, relies on it. +#[derive(Debug, Default)] +struct MapShape { + announced: Option, + entries: usize, +} + +type ShapeError = serde::de::value::Error; +type NoCompound = serde::ser::Impossible<(), ShapeError>; + +/// Refuses every value that is not a map: the configuration serializes as one map. +macro_rules! only_a_map { + ($($method:ident($($arg:ty),*);)*) => { + $(fn $method(self, $(_: $arg),*) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + })* + }; +} + +impl serde::Serializer for &mut MapShape { + type Ok = (); + type Error = ShapeError; + type SerializeSeq = NoCompound; + type SerializeTuple = NoCompound; + type SerializeTupleStruct = NoCompound; + type SerializeTupleVariant = NoCompound; + type SerializeMap = Self; + type SerializeStruct = NoCompound; + type SerializeStructVariant = NoCompound; + + only_a_map! { + serialize_bool(bool); serialize_i8(i8); serialize_i16(i16); serialize_i32(i32); + serialize_i64(i64); serialize_u8(u8); serialize_u16(u16); serialize_u32(u32); + serialize_u64(u64); serialize_f32(f32); serialize_f64(f64); serialize_char(char); + serialize_str(&str); serialize_bytes(&[u8]); serialize_none(); serialize_unit(); + serialize_unit_struct(&'static str); + serialize_unit_variant(&'static str, u32, &'static str); + } + + fn serialize_some(self, _: &T) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_newtype_struct( + self, + _: &'static str, + _: &T, + ) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: &T, + ) -> Result<(), ShapeError> { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_seq(self, _: Option) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_tuple(self, _: usize) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_map(self, len: Option) -> Result { + self.announced = len; + Ok(self) + } + + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } + + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { + Err(serde::ser::Error::custom("the configuration serializes as a map")) + } +} + +impl serde::ser::SerializeMap for &mut MapShape { + type Ok = (); + type Error = ShapeError; + + fn serialize_key(&mut self, _: &T) -> Result<(), ShapeError> { + self.entries += 1; + Ok(()) + } + + fn serialize_value(&mut self, _: &T) -> Result<(), ShapeError> { + Ok(()) + } + + fn end(self) -> Result<(), ShapeError> { + Ok(()) + } +} + +/// The configuration announces the number of entries it writes, four — `satinTime` and the +/// three bootstrap keys — so a format that writes the length ahead of the entries encodes it +/// as it is. +#[test] +fn test_the_configuration_announces_the_entries_it_writes() { + let mut shape = MapShape::default(); + let config = SatinChainConfig { + activation_time: SATIN_TIME, + sequencer_registry_bootstrap: common::bootstrap(), + }; + config.serialize(&mut shape).unwrap(); + assert_eq!(shape.entries, 4, "satinTime and the three bootstrap keys"); + assert_eq!(shape.announced, Some(shape.entries), "the announced length"); +} From adca2904e62a23916438f0cb91720d3dfdb443d0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 16 Nov 2026 13:35:45 +0800 Subject: [PATCH 100/190] test(evm): pin the refused-read decision per opcode --- crates/mega-evm/src/evm/instructions.rs | 128 +++++++++++++++++- .../mega-evm/tests/satin/volatile_access.rs | 33 +++++ 2 files changed, 160 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 6f0f17a44..a1a0900a7 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -508,7 +508,13 @@ fn oracle_sload( mod tests { use super::*; use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use revm::bytecode::opcode::{CLZ, DUPN, EXCHANGE, SLOTNUM, SWAPN}; + use revm::{ + bytecode::opcode::{ + ADD, ADDRESS, CALLER, CHAINID, CLZ, CREATE, CREATE2, DUPN, EXCHANGE, GASPRICE, ORIGIN, + SLOAD, SLOTNUM, STOP, SWAPN, + }, + primitives::{Address, U256}, + }; /// The table charges the Satin static gas of every opcode but the ones the read wrappers run, /// which charge it themselves: the whole table, with their entries, is revm's Amsterdam one. @@ -530,4 +536,124 @@ mod tests { assert_eq!(charged[opcode as usize], gas, "opcode {opcode:#04x}"); } } + + const BENEFICIARY: Address = Address::repeat_byte(0xbe); + const OTHER: Address = Address::repeat_byte(0x07); + + /// What `refused_read::` decides for a frame running as `own`, with `operands` on the + /// stack (the first the top), the block's beneficiary being `BENEFICIARY`. + fn decision( + own: Address, + operands: &[Address], + ) -> Option { + let mut host = MegaContext::new(MemoryDatabase::default(), crate::MegaSpecId::SATIN); + host.inner.block.beneficiary = BENEFICIARY; + let mut interpreter = Interpreter::default_ext(); + interpreter.input.target_address = own; + for operand in operands.iter().rev() { + assert!(interpreter.stack.push(U256::from_be_slice(operand.as_slice()))); + } + refused_read::(&interpreter, &host) + } + + /// The refusal decision, opcode by opcode, with volatile-data access off: each + /// block-environment opcode names its own field whatever its operands, an account opcode is + /// refused only for the beneficiary and only with every operand on the stack, the calls + /// only for a beneficiary target operand, and an opcode the wrappers do not handle is never + /// refused. + #[test] + fn test_the_refusal_decision_truth_table() { + use VolatileDataAccess as Access; + + // The block-environment opcodes: refused with an empty stack, a full one, and in any frame. + let nothing: &[Address] = &[]; + let some: &[Address] = &[OTHER, BENEFICIARY]; + for (own, operands) in [(OTHER, nothing), (BENEFICIARY, some)] { + assert_eq!(decision::(own, operands), Some(Access::BLOCK_NUMBER)); + assert_eq!(decision::(own, operands), Some(Access::TIMESTAMP)); + assert_eq!(decision::(own, operands), Some(Access::COINBASE)); + assert_eq!(decision::(own, operands), Some(Access::PREV_RANDAO)); + assert_eq!(decision::(own, operands), Some(Access::GAS_LIMIT)); + assert_eq!(decision::(own, operands), Some(Access::BASE_FEE)); + assert_eq!(decision::(own, operands), Some(Access::BLOB_BASE_FEE)); + assert_eq!(decision::(own, operands), Some(Access::SLOT_NUM)); + assert_eq!(decision::(own, operands), Some(Access::BLOCK_HASH)); + } + + let beneficiary = Some(Access::BENEFICIARY_BALANCE); + // `SELFBALANCE` follows the frame alone, not the stack. + assert_eq!(decision::(BENEFICIARY, nothing), beneficiary); + assert_eq!(decision::(OTHER, &[BENEFICIARY]), None); + + // The one-operand account opcodes follow their target operand. + assert_eq!(decision::(OTHER, &[BENEFICIARY]), beneficiary); + assert_eq!(decision::(OTHER, &[BENEFICIARY]), beneficiary); + assert_eq!(decision::(OTHER, &[BENEFICIARY]), beneficiary); + assert_eq!(decision::(BENEFICIARY, &[OTHER]), None); + assert_eq!(decision::(BENEFICIARY, &[OTHER]), None); + assert_eq!(decision::(BENEFICIARY, &[OTHER]), None); + assert_eq!(decision::(OTHER, nothing), None, "no operand"); + assert_eq!(decision::(OTHER, nothing), None, "no operand"); + assert_eq!(decision::(OTHER, nothing), None, "no operand"); + + // `EXTCODECOPY` takes four operands. + let four = |target| [target, OTHER, OTHER, OTHER]; + assert_eq!(decision::(OTHER, &four(BENEFICIARY)), beneficiary); + assert_eq!(decision::(OTHER, &four(OTHER)), None); + assert_eq!(decision::(OTHER, &four(BENEFICIARY)[..3]), None, "three operands"); + + // `SELFDESTRUCT`: a beneficiary target, or a frame running as the beneficiary. + assert_eq!(decision::(OTHER, &[BENEFICIARY]), beneficiary); + assert_eq!(decision::(BENEFICIARY, &[OTHER]), beneficiary); + assert_eq!(decision::(OTHER, &[OTHER]), None); + assert_eq!(decision::(BENEFICIARY, nothing), None, "no operand"); + + // The calls: the target is the second operand, after the gas; seven operands for `CALL` + // and `CALLCODE`, six for the others. + let call = |operands: usize, target| { + let mut stack = vec![OTHER; operands]; + stack[1] = target; + stack + }; + assert_eq!(decision::(OTHER, &call(7, BENEFICIARY)), beneficiary); + assert_eq!(decision::(OTHER, &call(7, BENEFICIARY)), beneficiary); + assert_eq!(decision::(OTHER, &call(6, BENEFICIARY)), beneficiary); + assert_eq!(decision::(OTHER, &call(6, BENEFICIARY)), beneficiary); + assert_eq!(decision::(OTHER, &call(7, OTHER)), None); + assert_eq!(decision::(OTHER, &call(7, OTHER)), None); + assert_eq!(decision::(OTHER, &call(6, OTHER)), None); + assert_eq!(decision::(OTHER, &call(6, OTHER)), None); + // The beneficiary as the gas operand, the first, is no target. + let gas_is_beneficiary = |operands: usize| { + let mut stack = vec![OTHER; operands]; + stack[0] = BENEFICIARY; + stack + }; + assert_eq!(decision::(OTHER, &gas_is_beneficiary(7)), None); + assert_eq!(decision::(OTHER, &gas_is_beneficiary(6)), None); + // A frame running as the beneficiary reads nothing by calling. + assert_eq!(decision::(BENEFICIARY, &call(7, OTHER)), None); + // One operand short. + assert_eq!(decision::(OTHER, &call(6, BENEFICIARY)), None, "CALL, six operands"); + assert_eq!(decision::(OTHER, &call(6, BENEFICIARY)), None, "CALLCODE, six"); + assert_eq!( + decision::(OTHER, &call(5, BENEFICIARY)), + None, + "DELEGATECALL, five" + ); + assert_eq!(decision::(OTHER, &call(5, BENEFICIARY)), None, "STATICCALL, five"); + + // Opcodes the wrappers do not handle read nothing, whatever the stack and the frame. + let all = [BENEFICIARY; 8]; + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::
(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + assert_eq!(decision::(BENEFICIARY, &all), None); + } } diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs index f32a5221c..4114a63bf 100644 --- a/crates/mega-evm/tests/satin/volatile_access.rs +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -694,6 +694,39 @@ fn test_a_stack_underflow_is_not_a_refusal() { assert_eq!(refused_child(db).0, InstructionResult::StackUnderflow, "EXTCODECOPY"); } +/// A block-environment opcode in a frame whose access is off is refused before it charges or +/// runs anything: the frame holding less than its static gas, or a full stack its push cannot +/// grow, is refused rather than halted on the gas or the stack the opcode would have failed on. +#[test] +fn test_a_block_environment_opcode_is_refused_before_it_charges_or_runs() { + let opcodes = [ + (NUMBER, VolatileDataAccess::BLOCK_NUMBER), + (TIMESTAMP, VolatileDataAccess::TIMESTAMP), + (COINBASE, VolatileDataAccess::COINBASE), + (DIFFICULTY, VolatileDataAccess::PREV_RANDAO), + (GASLIMIT, VolatileDataAccess::GAS_LIMIT), + (BASEFEE, VolatileDataAccess::BASE_FEE), + (BLOBBASEFEE, VolatileDataAccess::BLOB_BASE_FEE), + (SLOTNUM, VolatileDataAccess::SLOT_NUM), + ]; + for (opcode, access) in opcodes { + // A full stack: the push would overflow it. + let full = BytecodeBuilder::default().append_many(vec![PUSH0; 1024]).append(opcode); + let db = MemoryDatabase::default().account_code(CHILD, full.stop().build()); + assert_eq!(refused_child(db), refused(access), "opcode {opcode:#04x}, a full stack"); + + // Less gas than the opcode's static gas. + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_child(BytecodeBuilder::default(), Some(1)).stop().build()) + .account_code(CHILD, BytecodeBuilder::default().append(opcode).stop().build()); + let (run, result, output, spent) = run_child(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!((result, output), refused(access), "opcode {opcode:#04x}, one gas"); + assert_eq!(spent, 0, "opcode {opcode:#04x}: a refused read costs nothing"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "opcode {opcode:#04x}"); + } +} + /// A database failure on an account an opcode loads surfaces as an error of the transaction, with /// access switched off or not; a `CALL` short of operands still fails on its stack first, even /// when its target's code would fail to load. From 82de103930fc1d45c58b2005a7cb28e368e66b80 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:32:26 +0800 Subject: [PATCH 101/190] ci: gate on the Mega EEST conformance suite --- .github/workflows/mega-eest.yml | 186 +++++++++++++ scripts/mega_eest.env | 9 + scripts/mega_eest.py | 468 ++++++++++++++++++++++++++++++++ scripts/mega_eest.sh | 183 +++++++++++++ 4 files changed, 846 insertions(+) create mode 100644 .github/workflows/mega-eest.yml create mode 100644 scripts/mega_eest.env create mode 100755 scripts/mega_eest.py create mode 100755 scripts/mega_eest.sh diff --git a/.github/workflows/mega-eest.yml b/.github/workflows/mega-eest.yml new file mode 100644 index 000000000..e32edc66c --- /dev/null +++ b/.github/workflows/mega-eest.yml @@ -0,0 +1,186 @@ +name: Mega EEST + +# Runs the Mega EEST conformance suite on this tree (scripts/mega_eest.sh): every gating case of +# the suite at the commit scripts/mega_eest.env pins, through the suite's revm adapter built against +# this checkout's mega-evm, with this checkout's root manifest's [patch] blocks and Cargo.lock, so a +# pull request that moves the revm or op-revm fork is tested with its own fork. Each case is +# consumed plain and instrumented; the gate passes when the cases consumed are exactly the slice's +# index, every one passes in both modes with the same observations, and the suite's deliberately +# wrong expectation fails where it records. +# +# A failing case pins a rule of the Satin specification. A pull request that changes that +# behaviour on purpose, or the mega-evm API the adapter calls, changes Mega EEST first (the case or +# the adapter) and moves the pin to that commit in the same pull request. An adapter that no longer +# builds against this tree fails the gate with that instruction; nothing is skipped. +# +# The `Mega EEST gate` job always runs and reports: it passes when the run passed, or when a pull +# request changes documentation alone (scripts/pull_request_needs_ci.sh) and the run was skipped. +# It is the check a branch rule requires; a path filter on the pull request trigger would leave that +# check pending on every pull request it filters out. A push to satin always runs, and saves the +# build cache pull requests restore. +# +# Timing: on a 15-core laptop the whole run takes about a minute with a warm dependency cache (the +# adapter build half a minute, each mode about fifteen seconds). On a GitHub runner, with four +# cores, expect a few minutes once the cache is warm, and a cold dependency build on top of that. + +on: + workflow_dispatch: + pull_request: + push: + branches: [satin] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + changes: + name: changes that need the run + runs-on: ubuntu-24.04 + timeout-minutes: 10 + outputs: + run: ${{ steps.diff.outputs.run }} + steps: + - uses: actions/checkout@v4 + if: github.event_name == 'pull_request' + with: + # The merge commit and its parents; the first parent is the base it merges into. + fetch-depth: 2 + persist-credentials: false + + - name: Skip a pull request that changes documentation alone + id: diff + env: + EVENT: ${{ github.event_name }} + run: | + set -euo pipefail + if [ "$EVENT" != pull_request ]; then + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then + echo "::warning::HEAD is not the pull request's merge commit; running" + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # The allowlist is in the script: only docs/ and Markdown outside crates/ and bin/ skip. + run=$(scripts/pull_request_needs_ci.sh HEAD^1 HEAD) + echo "runs: $run" + echo "run=$run" >> "$GITHUB_OUTPUT" + + mega-eest: + name: Mega EEST on this tree + needs: changes + if: needs.changes.outputs.run == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + CARGO_INCREMENTAL: "0" + # The tree's dev profile keeps full debug info; line tables are enough for a panic's + # backtrace and keep the cached build small. Debug assertions stay on. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + persist-credentials: false + + - name: Read the pin + id: pin + run: | + set -euo pipefail + rev=$(sed -n 's/^MEGA_EEST_REV=\(.*\)$/\1/p' scripts/mega_eest.env) + echo "Mega EEST at $rev" + echo "rev=$rev" >> "$GITHUB_OUTPUT" + + # The job's cargo cache is the step below: setup-rust-toolchain's own cache handles the + # workspace's target directory, and this job builds into another. + - uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + cache: false + + - uses: foundry-rs/foundry-toolchain@v1 + + # The dependencies of the adapter build, keyed on what decides them: the pin (the adapter and + # the format crate), this tree's lock and its toolchain. A pull request restores its base's + # cache, saved by the push to satin, and rebuilds mega-evm, which is a path dependency and so + # always rebuilt on a fresh checkout. + - name: Restore the build cache + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/mega-eest/target + key: mega-eest-${{ runner.os }}-${{ steps.pin.outputs.rev }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock') }} + restore-keys: | + mega-eest-${{ runner.os }}-${{ steps.pin.outputs.rev }}- + mega-eest-${{ runner.os }}- + + - name: Run Mega EEST, the gate + env: + REV: ${{ steps.pin.outputs.rev }} + run: | + set -uo pipefail + start=$SECONDS + status=0 + scripts/mega_eest.sh > summary.txt || status=$? + cat summary.txt + { + echo "### Mega EEST" + echo + echo "Pin: \`$REV\`, in $((SECONDS - start)) s." + echo + echo '```' + cat summary.txt + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + if [ "$status" -ne 0 ]; then + echo "::error::Mega EEST failed on this tree; the failing cases are in the log above and in the uploaded reports" + fi + exit "$status" + + - name: Upload the reports of a failing run + if: failure() + uses: actions/upload-artifact@v4 + with: + name: mega-eest-reports + path: | + target/mega-eest/*.json + target/mega-eest/*.log + target/mega-eest/adapter-revm/Cargo.toml + target/mega-eest/adapter-revm/Cargo.lock + if-no-files-found: ignore + retention-days: 7 + + gate: + name: Mega EEST gate + needs: [changes, mega-eest] + # Always, a cancelled run included: a required check that is skipped counts as passed. + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Report the gate's outcome + env: + CHANGES: ${{ needs.changes.result }} + RUN: ${{ needs.changes.outputs.run }} + RESULT: ${{ needs.mega-eest.result }} + run: | + if [ "$CHANGES" != success ]; then + echo "::error::could not tell whether the run was needed: the changes job ended $CHANGES" + exit 1 + fi + if [ "$RUN" != true ]; then + echo "only documentation changed; the run was skipped" + exit 0 + fi + if [ "$RESULT" != success ]; then + echo "::error::the gate ended $RESULT" + exit 1 + fi + echo "the gate passed" diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env new file mode 100644 index 000000000..9c75a35e2 --- /dev/null +++ b/scripts/mega_eest.env @@ -0,0 +1,9 @@ +# The Mega EEST commit mega-evm's CI gates on (scripts/mega_eest.sh, the Mega EEST gate in +# .github/workflows/mega-eest.yml). Mega EEST is the conformance suite both Satin implementations +# share; every case it holds at this commit must pass on this tree, plain and instrumented. +# +# Moving the pin is the one-line change of MEGA_EEST_REV, to a full commit of the repository below, +# in the pull request that needs it: a change to mega-evm's API that the suite's revm adapter calls, +# or to behaviour a case pins, lands in Mega EEST first and is then pinned here. +MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest +MEGA_EEST_REV=5e4007b47ce62c2af2b7bf770677b0e6baf1a8d2 diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py new file mode 100755 index 000000000..ce97a9f7a --- /dev/null +++ b/scripts/mega_eest.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""The parts of scripts/mega_eest.sh that read and write structured files. + +Subcommands: + + adapter --tree --suite --out + Write the Mega EEST revm adapter as a workspace of its own at , built against the + mega-evm checkout rather than the commit the adapter pins. Its sources are copied as they + are; its manifest is the adapter's with three changes. A dependency on a package of this + workspace (mega-evm) is a path dependency on that package here. A dependency this + workspace's root manifest declares in `[workspace.dependencies]` takes its source (version, + git, rev, tag, branch) from there, keeping the adapter's features, so the adapter names the + crates mega-evm links rather than a second copy of them. And the `[patch]` and `[profile]` + tables are this workspace's root manifest's, replacing the adapter's, so a change that moves + the revm or op-revm fork is built with the fork it moves to. A path dependency outside this + workspace (the format crate) stays a path dependency on the suite's checkout. The adapter's + own Cargo.lock, resolved for the commit it pins, is not used: the workspace's lock starts as + this checkout's Cargo.lock, which cargo then prunes to what the adapter links and extends + with anything only the adapter needs. + + check-lock --tree --adapter + After cargo resolved the adapter workspace: every package mega-evm links in it, through + any number of dependencies, must be a package this checkout's Cargo.lock holds, at the same + version and from the same source, and there is exactly one revm. Packages only the adapter + or the format crate links are listed when this checkout does not lock them. + + check --suite --work --modes <"plain instrumented"> --rev + Read the run reports `mega-fixture consume` wrote into (.json, and + negative.json for the suite's deliberately wrong expectation) and decide the gate: in every + mode, the cases consumed are exactly the slice's index, by case id and file digest, and + every one passed; with both modes, every case's observations are the same bytes plain and + instrumented; and the wrong expectation fails at the path the index records. Prints the + failures (case id, first differing path, both values, the rules the case pins) and one + summary line, `MEGA-EEST ...`, and exits 1 when the gate fails. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import sys +from collections import Counter +from pathlib import Path + +# tomllib is new in Python 3.11: say so rather than fail on the import below. +if sys.version_info < (3, 11): + sys.exit(f"scripts/mega_eest.py needs Python 3.11 or newer, for tomllib; this is Python " + f"{sys.version.split()[0]}.") + +import tomllib # noqa: E402 + +# The keys of a dependency that say where it comes from; the others (features, default-features, +# optional, package) say how it is used. +SOURCE_KEYS = ("version", "git", "rev", "tag", "branch", "registry", "path") + +# The adapter files that are the adapter's resolution and toolchain, which the generated workspace +# replaces with this checkout's: the manifest is rewritten, the lock is seeded from this checkout's, +# and cargo runs from this checkout, so rustup picks its rust-toolchain.toml. +NOT_COPIED = {"Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "target"} + +# Where the generated workspace records what it seeded its lock from. +SEED_MARKER = ".mega-eest-seed" + +# How many failures of one mode are printed in full; the report holds them all. +MAX_SHOWN = 20 + + +class GateError(Exception): + """A condition the gate cannot pass.""" + + +# ---- TOML output ---------------------------------------------------------------------------- + +BARE_KEY = re.compile(r"^[A-Za-z0-9_-]+$") + + +def toml_key(key: str) -> str: + return key if BARE_KEY.match(key) else json.dumps(key, ensure_ascii=False) + + +def toml_value(value) -> str: + # bool first: a bool is an int in Python. + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return repr(value) + if isinstance(value, str): + # A JSON string without ASCII escaping is a TOML basic string: the escapes JSON writes + # (\", \\, \n, \t, \uXXXX for control characters) are TOML's. + return json.dumps(value, ensure_ascii=False) + if isinstance(value, list): + return "[" + ", ".join(toml_value(v) for v in value) + "]" + if isinstance(value, dict): + return "{ " + ", ".join(f"{toml_key(k)} = {toml_value(v)}" for k, v in value.items()) + " }" + raise GateError(f"cannot write {value!r} as TOML") + + +def render_toml(doc: dict) -> str: + """A TOML document for `doc`: tables of the top two levels as headers, leaves inline. + + The text is read back and compared with `doc`, so a value this writer gets wrong fails here + rather than as a manifest that means something else. + """ + out: list[str] = [] + + def is_leaf(value: dict) -> bool: + return not any(isinstance(v, dict) for v in value.values()) + + def walk(path: list[str], table: dict) -> None: + depth = len(path) + plain, tables, arrays = [], [], [] + for key, value in table.items(): + if isinstance(value, dict) and not (depth + 1 >= 2 and is_leaf(value)): + tables.append((key, value)) + elif isinstance(value, list) and value and all(isinstance(v, dict) for v in value): + arrays.append((key, value)) + else: + plain.append((key, value)) + if path and (plain or not (tables or arrays)): + out.append("[" + ".".join(toml_key(p) for p in path) + "]") + for key, value in plain: + out.append(f"{toml_key(key)} = {toml_value(value)}") + if plain or (path and not (tables or arrays)): + out.append("") + for key, value in tables: + walk([*path, key], value) + for key, items in arrays: + for item in items: + out.append("[[" + ".".join(toml_key(p) for p in [*path, key]) + "]]") + for k, v in item.items(): + out.append(f"{toml_key(k)} = {toml_value(v)}") + out.append("") + + walk([], doc) + text = "\n".join(out).rstrip("\n") + "\n" + if tomllib.loads(text) != doc: + raise GateError("the generated manifest does not read back as the manifest meant") + return text + + +# ---- adapter -------------------------------------------------------------------------------- + + +def workspace_members(tree: Path, root: dict) -> dict[str, Path]: + """The packages of this workspace, by name, with their directories.""" + members: dict[str, Path] = {} + for member in root.get("workspace", {}).get("members", []): + if any(c in member for c in "*?["): + raise GateError(f"workspace member {member!r} is a glob, which this script does not expand") + manifest = tree / member / "Cargo.toml" + name = tomllib.loads(manifest.read_text())["package"]["name"] + members[name] = (tree / member).resolve() + return members + + +def rewrite_dependency(name: str, spec, *, adapter_dir: Path, members: dict[str, Path], + workspace_deps: dict) -> tuple[object, str]: + """The adapter's dependency `name` as the generated workspace declares it, and why.""" + if isinstance(spec, str): + spec = {"version": spec} + if not isinstance(spec, dict): + raise GateError(f"dependency {name!r} is neither a version nor a table: {spec!r}") + if spec.get("workspace"): + raise GateError(f"dependency {name!r} inherits from the adapter's workspace, which has none") + package = spec.get("package", name) + usage = {k: v for k, v in spec.items() if k not in SOURCE_KEYS} + if package in members: + return {"path": str(members[package]), **usage}, "this checkout's package" + if name in workspace_deps: + root_spec = workspace_deps[name] + if isinstance(root_spec, str): + root_spec = {"version": root_spec} + if "path" not in root_spec and root_spec.get("package", name) == package: + source = {k: v for k, v in root_spec.items() if k in SOURCE_KEYS} + return {**source, **usage}, "the source this checkout's root manifest declares" + if "path" in spec: + return {**spec, "path": str((adapter_dir / spec["path"]).resolve())}, "the suite's own path" + return spec, "the adapter's own declaration" + + +def write_if_changed(path: Path, data: bytes) -> None: + """Write `data` unless the file holds it already, so cargo's fingerprints see no change.""" + if path.exists() and path.read_bytes() == data: + return + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + + +def sync_tree(src: Path, dst: Path, keep: set[str]) -> None: + """Make `dst` hold `src`'s files but those named in NOT_COPIED; `keep` names files of `dst` + that are not `src`'s and stay.""" + wanted: set[Path] = set() + for path in sorted(src.rglob("*")): + rel = path.relative_to(src) + if rel.parts[0] in NOT_COPIED or not path.is_file(): + continue + wanted.add(rel) + write_if_changed(dst / rel, path.read_bytes()) + for path in sorted(dst.rglob("*"), reverse=True): + rel = path.relative_to(dst) + if rel.parts[0] in keep or rel.parts[0] in NOT_COPIED: + continue + if path.is_file() and rel not in wanted: + path.unlink() + elif path.is_dir() and not any(path.iterdir()): + path.rmdir() + + +def cmd_adapter(args: argparse.Namespace) -> int: + tree, suite, out = Path(args.tree).resolve(), Path(args.suite).resolve(), Path(args.out) + adapter_dir = suite / "adapters" / "revm" + adapter = tomllib.loads((adapter_dir / "Cargo.toml").read_text()) + root = tomllib.loads((tree / "Cargo.toml").read_text()) + members = workspace_members(tree, root) + workspace_deps = root.get("workspace", {}).get("dependencies", {}) + + manifest: dict = {} + for key, value in adapter.items(): + if key in ("patch", "profile", "replace"): + continue + manifest[key] = value + if "workspace" not in manifest: + raise GateError(f"{adapter_dir / 'Cargo.toml'} is no workspace of its own") + routed = Counter() + tables = [("dependencies",), ("build-dependencies",), ("dev-dependencies",)] + tables += [("target", t, d) for t in adapter.get("target", {}) + for d in ("dependencies", "build-dependencies", "dev-dependencies")] + for path in tables: + table = manifest + for part in path[:-1]: + table = table.get(part, {}) + deps = table.get(path[-1]) + if not deps: + continue + rewritten = {} + for name, spec in deps.items(): + rewritten[name], why = rewrite_dependency( + name, spec, adapter_dir=adapter_dir, members=members, workspace_deps=workspace_deps) + routed[why] += 1 + table[path[-1]] = rewritten + if not routed["this checkout's package"]: + raise GateError( + f"{adapter_dir / 'Cargo.toml'} depends on no package of this checkout " + f"({', '.join(sorted(members))}): it would not test this tree") + for key in ("patch", "profile"): + if key in root: + manifest[key] = root[key] + + out.mkdir(parents=True, exist_ok=True) + sync_tree(adapter_dir, out, keep={SEED_MARKER}) + text = render_toml(manifest) + header = ( + "# Generated by scripts/mega_eest.py from the Mega EEST revm adapter's manifest: built\n" + "# against the mega-evm checkout below, with its root manifest's [patch] and [profile].\n" + f"# mega-evm checkout: {tree}\n# Mega EEST checkout: {suite}\n\n" + ) + write_if_changed(out / "Cargo.toml", (header + text).encode()) + + # Seed the lock from this checkout's, unless it was seeded from the same lock and manifest + # before: cargo has resolved it since, and a fresh seed would only make it resolve again. + tree_lock = (tree / "Cargo.lock").read_bytes() + seed = hashlib.sha256(tree_lock + b"\0" + (header + text).encode()).hexdigest() + marker = out / SEED_MARKER + if not (out / "Cargo.lock").exists() or not marker.exists() or marker.read_text().strip() != seed: + write_if_changed(out / "Cargo.lock", tree_lock) + marker.write_text(seed + "\n") + print( + "mega-eest: adapter workspace at {}: {}".format( + out, ", ".join(f"{n} {why}" for why, n in sorted(routed.items()))), + file=sys.stderr, + ) + return 0 + + +# ---- check-lock ----------------------------------------------------------------------------- + + +def lock_packages(path: Path) -> list[dict]: + return tomllib.loads(path.read_text()).get("package", []) + + +def resolve_reference(ref: str, packages: list[dict]) -> dict: + """The package a lock entry's dependency string names: `name`, `name version` or + `name version (source)`.""" + m = re.fullmatch(r"(\S+)(?: (\S+))?(?: \((.+)\))?", ref) + if not m: + raise GateError(f"cannot read the lock reference {ref!r}") + name, version, source = m.groups() + found = [p for p in packages if p["name"] == name + and (version is None or p["version"] == version) + and (source is None or p.get("source") == source)] + if len(found) != 1: + raise GateError(f"the lock reference {ref!r} names {len(found)} packages, not one") + return found[0] + + +def cmd_check_lock(args: argparse.Namespace) -> int: + tree, adapter = Path(args.tree).resolve(), Path(args.adapter) + ours = lock_packages(tree / "Cargo.lock") + locked = {(p["name"], p["version"], p.get("source")) for p in ours} + member_names = {p["name"] for p in ours if "source" not in p} + theirs = lock_packages(adapter / "Cargo.lock") + roots = [p for p in theirs if p["name"] == "mega-evm" and "source" not in p] + if len(roots) != 1: + raise GateError(f"{adapter / 'Cargo.lock'} holds {len(roots)} path packages named mega-evm, not one") + seen: dict[tuple, dict] = {} + queue = list(roots) + while queue: + pkg = queue.pop() + key = (pkg["name"], pkg["version"], pkg.get("source")) + if key in seen: + continue + seen[key] = pkg + queue.extend(resolve_reference(ref, theirs) for ref in pkg.get("dependencies", [])) + differing = sorted(k for k in seen if k not in locked) + foreign_paths = sorted(k[0] for k in seen if k[2] is None and k[0] not in member_names) + revms = sorted(f"{p['version']} {p.get('source', '(path)')}" for p in theirs if p["name"] == "revm") + problems = [] + if differing: + problems.append("mega-evm links packages this checkout's Cargo.lock does not lock: " + + ", ".join(f"{n} {v} {s or '(path)'}" for n, v, s in differing)) + if foreign_paths: + problems.append("mega-evm links path packages that are not this checkout's: " + ", ".join(foreign_paths)) + if len(revms) != 1: + problems.append(f"the adapter workspace resolves {len(revms)} revm packages, not one: " + "; ".join(revms)) + if problems: + for p in problems: + print(f"mega-eest: error: {p}", file=sys.stderr) + print("mega-eest: error: the adapter would not build mega-evm as this checkout locks it", + file=sys.stderr) + return 1 + extra = sorted({(p["name"], p["version"]) for p in theirs + if (p["name"], p["version"], p.get("source")) not in locked and "source" in p}) + print(f"mega-eest: lock: mega-evm links {len(seen)} packages, each as this checkout locks it; " + f"one revm ({revms[0]})", file=sys.stderr) + if extra: + print("mega-eest: lock: resolved outside this checkout's lock, for the adapter alone: " + + ", ".join(f"{n} {v}" for n, v in extra), file=sys.stderr) + return 0 + + +# ---- check ---------------------------------------------------------------------------------- + + +def canonical(value) -> str: + return "(absent)" if value is None else json.dumps(value, sort_keys=True, separators=(",", ":")) + + +def cmd_check(args: argparse.Namespace) -> int: + suite, work = Path(args.suite), Path(args.work) + modes = args.modes.split() + index = json.loads((suite / "slice" / "index.json").read_text()) + expected = Counter((c["caseId"], c["fileDigest"]) for c in index["cases"]) + total = sum(expected.values()) + failed = False + summary = [f"rev={args.rev}", f"cases={total}"] + observations: dict[str, dict[str, str | None]] = {} + + if total == 0: + print("mega-eest: error: the slice's index lists no case", file=sys.stderr) + failed = True + + for mode in modes: + report_path = work / f"{mode}.json" + exit_path = work / f"{mode}.exit" + code = exit_path.read_text().strip() if exit_path.exists() else "?" + if not report_path.exists(): + print(f"mega-eest: error: {mode}: `mega-fixture consume` wrote no report (exit {code}); " + f"see {work / (mode + '.log')}", file=sys.stderr) + summary.append(f"{mode}=no-report") + failed = True + continue + cases = json.loads(report_path.read_text())["cases"] + statuses = Counter(c["status"] for c in cases) + got = Counter((c.get("caseId"), c.get("fileDigest")) for c in cases) + missing, extra = expected - got, got - expected + not_passed = [c for c in cases if c["status"] != "pass"] + observations[mode] = {c.get("caseId"): c.get("observationsDigest") for c in cases} + for c in not_passed[:MAX_SHOWN]: + line = f"mega-eest: {mode}: {c['status']} {c.get('caseId') or c['file']}" + if c["status"] == "fail": + line += (f"\n first difference at {c.get('path')}: expected {canonical(c.get('expected'))} " + f"actual {canonical(c.get('actual'))}\n rules: {', '.join(c.get('rules', [])) or '(none)'}") + elif c["status"] == "unsupported": + line += f"\n missing: {', '.join(c.get('missing', []))}" + elif c["status"] == "error": + line += f"\n {c.get('message')}" + print(line, file=sys.stderr) + if len(not_passed) > MAX_SHOWN: + print(f"mega-eest: {mode}: ... and {len(not_passed) - MAX_SHOWN} more, in {report_path}", + file=sys.stderr) + if missing or extra: + print(f"mega-eest: error: {mode}: the cases consumed are not the slice's index: " + f"{sum(missing.values())} missing, {sum(extra.values())} not in it" + + (f", {next(iter(missing))[0]} among the missing" if missing else "") + + (f", {next(iter(extra))[0]} among the others" if extra else ""), file=sys.stderr) + failed = True + if not_passed or code != "0": + failed = True + summary.append(f"{mode}=" + ",".join( + f"{s}:{statuses.get(s, 0)}" for s in ("pass", "fail", "unsupported", "error"))) + + if {"plain", "instrumented"} <= observations.keys(): + plain, inst = observations["plain"], observations["instrumented"] + differ = sorted(k for k in plain.keys() | inst.keys() + if plain.get(k) is None or plain.get(k) != inst.get(k)) + for case in differ[:MAX_SHOWN]: + print(f"mega-eest: parity: {case}: plain {plain.get(case)} instrumented {inst.get(case)}", + file=sys.stderr) + summary.append(f"parity={'identical' if not differ else f'{len(differ)}-differ'}") + failed |= bool(differ) + + negative_path = work / "negative.json" + wrong_at = {n["caseId"]: n["wrongAt"] for n in index.get("negative", [])} + if wrong_at: + verdict = "fail-as-recorded" + if not negative_path.exists(): + verdict = "no-report" + else: + cases = {c.get("caseId"): c for c in json.loads(negative_path.read_text())["cases"]} + for case_id, path in wrong_at.items(): + c = cases.get(case_id) + if not c or c["status"] != "fail" or c.get("path") != path: + print(f"mega-eest: error: the wrong expectation {case_id} did not fail at {path}: " + f"{c['status'] + ' at ' + str(c.get('path')) if c else 'not consumed'}", + file=sys.stderr) + verdict = "not-caught" + summary.append(f"negative={verdict}") + failed |= verdict != "fail-as-recorded" + + summary.append(f"result={'FAIL' if failed else 'pass'}") + print("MEGA-EEST " + " ".join(summary)) + return 1 if failed else 0 + + +def main() -> int: + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = p.add_subparsers(dest="cmd", required=True) + + pa = sub.add_parser("adapter", help="write the adapter workspace built against this checkout") + pa.add_argument("--tree", required=True) + pa.add_argument("--suite", required=True) + pa.add_argument("--out", required=True) + pa.set_defaults(func=cmd_adapter) + + pl = sub.add_parser("check-lock", help="hold the resolved adapter workspace to this checkout's lock") + pl.add_argument("--tree", required=True) + pl.add_argument("--adapter", required=True) + pl.set_defaults(func=cmd_check_lock) + + pc = sub.add_parser("check", help="decide the gate from the run reports") + pc.add_argument("--suite", required=True) + pc.add_argument("--work", required=True) + pc.add_argument("--modes", required=True) + pc.add_argument("--rev", required=True) + pc.set_defaults(func=cmd_check) + + args = p.parse_args() + try: + return args.func(args) + except GateError as err: + print(f"mega-eest: error: {err}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh new file mode 100755 index 000000000..a37ae8cf8 --- /dev/null +++ b/scripts/mega_eest.sh @@ -0,0 +1,183 @@ +#!/usr/bin/env bash +# Runs the Mega EEST conformance suite on this checkout of mega-evm, as CI's Mega EEST gate does. +# +# Usage: +# scripts/mega_eest.sh +# +# Mega EEST is the conformance suite both Satin implementations share: state-transition cases, +# each pinned to rules of the Satin specification, run on an implementation through an adapter. +# The commit this tree gates on is scripts/mega_eest.env's MEGA_EEST_REV. The script: +# +# 1. Takes Mega EEST at that commit: the checkout $MEGA_EEST_DIR names, which must be at the pin +# with its cases, specs, adapters and format crate unmodified, or else a shallow fetch of the +# commit into $MEGA_EEST_WORK/src, reused while it is at the pin. +# 2. Builds the suite's `mega-fixture` CLI, and its revm adapter against this checkout: the adapter +# is written out as a workspace of its own ($MEGA_EEST_WORK/adapter-revm, by scripts/mega_eest.py) +# whose mega-evm is a path dependency on crates/mega-evm here, whose other crates take their +# sources from this tree's [workspace.dependencies], and whose [patch] and [profile] are this +# tree's root manifest's, so a change that moves the revm or op-revm fork is tested with its own +# fork. +# The lockfile: the adapter's own Cargo.lock was resolved for the mega-evm commit it pins and is +# not used. The workspace's lock is seeded with this tree's Cargo.lock, cargo resolves it once +# (pruning what the adapter does not link and adding what only the adapter needs), every package +# mega-evm links must then be at the version and source this tree locks, with one revm, and the +# build runs --locked on that lock. +# Cargo runs from this checkout's root, so the toolchain is its rust-toolchain.toml and the +# configuration its .cargo/config.toml. +# 3. Consumes every gating case (slice/cases) with `mega-fixture consume`, plain and then +# --instrumented, and the suite's deliberately wrong expectation (slice/negative). +# 4. Decides (scripts/mega_eest.py check): in each mode the cases consumed are exactly the slice's +# index and every one passed; plain and instrumented observations are the same bytes; the wrong +# expectation fails where the index says. A failure prints the case id, the first differing path +# and both values, and the rules the case pins. +# +# It prints one summary line on stdout, `MEGA-EEST rev=... cases=... plain=pass:N,... result=pass`, +# everything else on stderr, and exits non-zero when anything above does not hold: a fetch of a +# commit that does not exist, an adapter that does not build against this tree (an API it calls +# changed), a case that does not pass. +# +# Environment: +# MEGA_EEST_DIR a Mega EEST checkout at the pin to use instead of fetching one +# MEGA_EEST_WORK where the checkout, the adapter workspace, logs and reports go +# (default target/mega-eest) +# MEGA_EEST_TARGET_DIR the cargo target directory of both builds (default $MEGA_EEST_WORK/target) +# MEGA_EEST_MODES the modes to consume in (default "plain instrumented") +# MEGA_EEST_JOBS cases run at once (default: the number of CPUs) +# +# Requires git, cargo (rustup, for this tree's toolchain), Foundry (mega-evm's system contracts +# build with forge, as for every build of this tree) and Python 3.11 or newer. + +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PIN_FILE="$ROOT_DIR/scripts/mega_eest.env" +WORK="${MEGA_EEST_WORK:-$ROOT_DIR/target/mega-eest}" +TARGET="${MEGA_EEST_TARGET_DIR:-$WORK/target}" +MODES="${MEGA_EEST_MODES:-plain instrumented}" +# macOS has no nproc. The count then comes from sysctl, then from POSIX getconf. +JOBS="${MEGA_EEST_JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || getconf _NPROCESSORS_ONLN)}" +HELPER="$ROOT_DIR/scripts/mega_eest.py" + +log() { echo "mega-eest: $*" >&2; } +die() { + echo "mega-eest: error: $*" >&2 + exit 1 +} +started=$SECONDS +elapsed() { echo "$((SECONDS - started))s"; } + +python3 -c 'import sys; sys.exit(sys.version_info < (3, 11))' 2> /dev/null \ + || die "needs Python 3.11 or newer as python3 (for tomllib); found $(python3 --version 2>&1 || echo none)" + +for mode in $MODES; do + case "$mode" in + plain | instrumented) ;; + *) die "MEGA_EEST_MODES names '$mode'; the modes are plain and instrumented" ;; + esac +done + +# One `NAME=value` line of the pin file; anything else fails rather than running another commit. +read_pin() { + local value + value=$(sed -n "s/^$1=\(.*\)$/\1/p" "$PIN_FILE") + if [ -z "$value" ] || [ "$(printf '%s\n' "$value" | grep -c .)" -ne 1 ]; then + die "$PIN_FILE: no single $1 line" + fi + printf '%s' "$value" +} +REPO=$(read_pin MEGA_EEST_REPO) +REV=$(read_pin MEGA_EEST_REV) +[[ "$REV" =~ ^[0-9a-f]{40}$ ]] || die "$PIN_FILE: MEGA_EEST_REV is '$REV', not a full commit hash" + +# The paths of a checkout that decide what runs: a change to any of them is a different suite. +SUITE_PATHS=(slice specs adapters crates Cargo.toml Cargo.lock) + +# Whether the checkout $1 is the pinned commit with those paths as committed. +at_pin() { + [ "$(git -C "$1" rev-parse HEAD 2> /dev/null)" = "$REV" ] \ + && [ -z "$(git -C "$1" status --porcelain --untracked-files=all -- "${SUITE_PATHS[@]}")" ] +} + +mkdir -p "$WORK" +if [ -n "${MEGA_EEST_DIR:-}" ]; then + SUITE="$(cd "$MEGA_EEST_DIR" && pwd)" + if ! at_pin "$SUITE"; then + head=$(git -C "$SUITE" rev-parse HEAD 2> /dev/null || echo "no commit") + die "MEGA_EEST_DIR=$SUITE is at $head, or changes the suite, and the pin is $REV:" \ + "check the pin out there, or move the pin in scripts/mega_eest.env" + fi + log "Mega EEST at $REV in $SUITE" +else + SUITE="$WORK/src" + if [ -d "$SUITE/.git" ] && at_pin "$SUITE"; then + log "Mega EEST at $REV in $SUITE (reused)" + else + log "fetching Mega EEST $REV from $REPO" + rm -rf "$SUITE" + mkdir -p "$SUITE" + git -C "$SUITE" init -q + git -C "$SUITE" remote add origin "$REPO" + # One retry: a fetch that fails twice is a network failure or a commit the repository does + # not have, and either fails the gate. + if ! git -C "$SUITE" fetch -q --depth 1 origin "$REV"; then + log "the fetch failed; retrying once" + sleep 5 + git -C "$SUITE" fetch -q --depth 1 origin "$REV" \ + || die "cannot fetch $REV from $REPO: the repository has no such commit, or the network failed" + fi + git -C "$SUITE" -c advice.detachedHead=false checkout -q FETCH_HEAD + at_pin "$SUITE" || die "the fetched checkout is not at $REV" + fi +fi + +# Every cargo command runs from this checkout's root: rustup then uses its rust-toolchain.toml and +# cargo its .cargo/config.toml, whichever manifest it builds. +cd "$ROOT_DIR" + +log "building the mega-fixture CLI ($(elapsed))" +CARGO_TARGET_DIR="$TARGET" cargo build --locked --manifest-path "$SUITE/Cargo.toml" \ + -p mega-fixture-format --bin mega-fixture \ + || die "the suite's mega-fixture CLI does not build" +CLI="$TARGET/debug/mega-fixture" + +ADAPTER_DIR="$WORK/adapter-revm" +python3 "$HELPER" adapter --tree "$ROOT_DIR" --suite "$SUITE" --out "$ADAPTER_DIR" \ + || die "cannot write the adapter workspace" +log "resolving the adapter workspace on this tree's lock ($(elapsed))" +cargo metadata --format-version 1 --manifest-path "$ADAPTER_DIR/Cargo.toml" > /dev/null \ + || die "the adapter workspace does not resolve against this tree's manifests" +python3 "$HELPER" check-lock --tree "$ROOT_DIR" --adapter "$ADAPTER_DIR" + +log "building the revm adapter against this tree's mega-evm ($(elapsed))" +if ! CARGO_TARGET_DIR="$TARGET" cargo build --locked --manifest-path "$ADAPTER_DIR/Cargo.toml"; then + die "the Mega EEST revm adapter at $REV does not build against this tree." \ + "If this change alters the mega-evm API the adapter calls, change the adapter in Mega EEST" \ + "first and move the pin in scripts/mega_eest.env to that commit (AGENTS.md, the Mega EEST gate)." +fi +ADAPTER="$TARGET/debug/adapter-revm" +"$ADAPTER" capabilities > "$WORK/capabilities.json" || die "the adapter does not report its capabilities" + +rm -f "$WORK"/plain.* "$WORK"/instrumented.* "$WORK"/negative.* +for mode in $MODES; do + flag=() + [ "$mode" = instrumented ] && flag=(--instrumented) + log "consuming slice/cases, $mode, $JOBS at once ($(elapsed))" + rc=0 + "$CLI" consume --adapter "$ADAPTER" ${flag[@]+"${flag[@]}"} --jobs "$JOBS" --specs "$SUITE/specs" \ + --report "$WORK/$mode.json" "$SUITE/slice/cases" > "$WORK/$mode.log" || rc=$? + echo "$rc" > "$WORK/$mode.exit" + grep '^CONSUME ' "$WORK/$mode.log" >&2 || log "$mode: no CONSUME line; see $WORK/$mode.log" +done +log "consuming slice/negative, the wrong expectation ($(elapsed))" +"$CLI" consume --adapter "$ADAPTER" --specs "$SUITE/specs" --report "$WORK/negative.json" \ + "$SUITE/slice/negative" > "$WORK/negative.log" || true + +status=0 +python3 "$HELPER" check --suite "$SUITE" --work "$WORK" --modes "$MODES" --rev "$REV" || status=$? +log "done in $(elapsed); logs and reports in $WORK" +if [ "$status" -ne 0 ]; then + log "a case that fails pins behaviour of the Satin specification: fix the change, or, when it" \ + "changes that behaviour on purpose, change the case in Mega EEST first and move the pin" \ + "(AGENTS.md, the Mega EEST gate)" +fi +exit "$status" From 1e7663efc63b18152e0302614e45b58d95ef70fe Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:49:55 +0800 Subject: [PATCH 102/190] ci: count Mega EEST in the coverage report and the mutation gate --- .github/workflows/coverage.yml | 7 +- .github/workflows/mutation.yml | 10 +- crates/mega-evm/tests/mega_eest/main.rs | 30 ++++ scripts/coverage_mega_evm.sh | 38 ++++- scripts/mega_eest.py | 20 ++- scripts/mega_eest.sh | 5 + scripts/mutation_gate.py | 82 ++++++++- scripts/mutation_test.sh | 76 ++++++++- scripts/test_mutation_gate.py | 214 +++++++++++++++++++++++- 9 files changed, 471 insertions(+), 11 deletions(-) create mode 100644 crates/mega-evm/tests/mega_eest/main.rs diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 6b596ed2f..0b8bb2215 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -20,7 +20,10 @@ jobs: mega-evm-core: name: mega-evm core coverage runs-on: ubuntu-24.04 - timeout-minutes: 45 + # The tests, then the Mega EEST cases through the suite's adapter, built against this tree with + # mega-evm instrumented (scripts/coverage_mega_evm.sh): a second build of mega-evm and its + # dependencies, and every case run plain and instrumented. + timeout-minutes: 60 permissions: contents: read id-token: write # Codecov upload over OIDC; no token secret @@ -40,6 +43,8 @@ jobs: - name: Install cargo-llvm-cov uses: taiki-e/install-action@cargo-llvm-cov + # The report merges the tests' coverage with the Mega EEST cases', so a line only a Mega EEST + # case runs counts as covered. - name: Generate coverage reports run: scripts/coverage_mega_evm.sh diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 520a81851..a03949161 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -71,7 +71,11 @@ jobs: # there is no PR base, so run the whole crate as an on-demand baseline # instead of feeding an empty base into `diff` mode (which would fail). # The driver re-runs a mutant that timed out once, alone, into - # target/mutants/recheck; the gate takes that outcome for it. + # target/mutants/recheck; the gate takes that outcome for it. A mutant + # the tests still miss is then run against the Mega EEST suite + # (scripts/mega_eest.sh, through mega-evm's ignored `mega_eest` test), + # into target/mutants/mega-eest: one a Mega EEST case catches counts as + # caught. run: | if [ "${{ github.event_name }}" = "pull_request" ]; then scripts/mutation_test.sh diff "${{ github.event.pull_request.base.sha }}" @@ -84,6 +88,7 @@ jobs: python3 scripts/mutation_gate.py report \ --results target/mutants/mutants.out \ --recheck target/mutants/recheck/mutants.out \ + --mega-eest target/mutants/mega-eest/mutants.out \ --suppressions mutants/suppressions.toml \ --comment mutation-report.md \ --summary "$GITHUB_STEP_SUMMARY" @@ -130,9 +135,12 @@ jobs: path: | target/mutants/mutants.out target/mutants/recheck/mutants.out + target/mutants/mega-eest/mutants.out target/mutants.diff target/mutants.log target/mutants/recheck.log + target/mutants/mega-eest.log + target/mutants/mega-eest-warmup.log mutation-report.md if-no-files-found: ignore diff --git a/crates/mega-evm/tests/mega_eest/main.rs b/crates/mega-evm/tests/mega_eest/main.rs new file mode 100644 index 000000000..9d3ad4379 --- /dev/null +++ b/crates/mega-evm/tests/mega_eest/main.rs @@ -0,0 +1,30 @@ +//! The Mega EEST conformance suite on this checkout of mega-evm. +//! +//! Mega EEST holds the state-transition cases both Satin implementations share, each pinned to +//! rules of the Satin specification. `scripts/mega_eest.sh` takes the suite at the commit +//! `scripts/mega_eest.env` pins, builds the suite's revm adapter against this checkout and consumes +//! every case, plain and instrumented; this test runs that script and fails when it fails. +//! +//! It is ignored: it builds a second copy of mega-evm for the adapter and runs for a minute or +//! more, and CI runs the script itself as the Mega EEST gate. The mutation gate runs it, with +//! nextest's `--run-ignored only`, for each mutant the rest of the suite does not catch, so a mutant +//! that only a Mega EEST case catches counts as caught. + +use std::{path::Path, process::Command}; + +#[test] +#[ignore = "runs the Mega EEST suite through scripts/mega_eest.sh, which takes minutes"] +fn test_mega_eest_cases_pass_on_this_checkout() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let script = root.join("scripts/mega_eest.sh"); + let status = Command::new("bash") + .arg(&script) + .current_dir(&root) + .status() + .unwrap_or_else(|err| panic!("cannot run {}: {err}", script.display())); + assert!( + status.success(), + "{} failed ({status}): the lines above name what failed", + script.display() + ); +} diff --git a/scripts/coverage_mega_evm.sh b/scripts/coverage_mega_evm.sh index 96204200d..996b40d74 100755 --- a/scripts/coverage_mega_evm.sh +++ b/scripts/coverage_mega_evm.sh @@ -29,12 +29,48 @@ cargo llvm-cov \ --no-fail-fast \ --no-report +# The Mega EEST cases (scripts/mega_eest.sh) through the suite's revm adapter, built against this +# tree with mega-evm and the adapter's own crate instrumented as the tests are — mega-evm's generic +# code is compiled where the adapter uses it — and the crates.io and git crates not, so a line only +# a Mega EEST case runs counts as covered. The adapter's and the suite's own sources are left out of +# the report. The adapter's profiles go where cargo-llvm-cov merges the tests' (the target directory +# of the run above), merged online into one file per pool slot, as the suite runs one adapter +# process per case. The report reads only the executables of this workspace's targets, which the +# adapter is not, so a copy of it is placed among them under the library's name; the lcov report's +# own command line is then checked to have read it. +# COVERAGE_MEGA_EEST=0 leaves the suite out, for a quicker local report of the tests alone. +ADAPTER_OBJECT="" +if [ "${COVERAGE_MEGA_EEST:-1}" != 0 ]; then + LLVM_COV_TARGET="${CARGO_LLVM_COV_TARGET_DIR:-$(cargo metadata --format-version 1 --no-deps \ + | python3 -c 'import json, sys; print(json.load(sys.stdin)["target_directory"])')/llvm-cov-target}" + EEST_WORK="$ROOT_DIR/target/mega-eest-coverage" + IGNORE_FILENAME_REGEX="$IGNORE_FILENAME_REGEX|^$(python3 -c 'import re, sys; print(re.escape(sys.argv[1]))' "$EEST_WORK")/" + # Line tables are debug info enough for a panic's backtrace; the report reads the coverage + # mapping, not the debug info. + CARGO_PROFILE_DEV_DEBUG=line-tables-only \ + LLVM_PROFILE_FILE="$LLVM_COV_TARGET/mega-eest-%15m.profraw" \ + MEGA_EEST_WORK="$EEST_WORK" \ + MEGA_EEST_ENGINE_RUSTFLAGS="-Cinstrument-coverage -Zcoverage-options=branch --cfg=coverage --cfg=coverage_nightly" \ + "$ROOT_DIR/scripts/mega_eest.sh" + ADAPTER_OBJECT="mega_evm-00000000ee57ada7" + cp "$EEST_WORK/target/debug/adapter-revm" "$LLVM_COV_TARGET/debug/deps/$ADAPTER_OBJECT" +fi + +status=0 cargo llvm-cov report \ + --verbose \ --package mega-evm \ --branch \ --ignore-filename-regex "$IGNORE_FILENAME_REGEX" \ --lcov \ - --output-path "$LCOV_PATH" + --output-path "$LCOV_PATH" 2> "$COV_DIR/lcov-report.log" || status=$? +cat "$COV_DIR/lcov-report.log" >&2 +[ "$status" -eq 0 ] || exit "$status" +if [ -n "$ADAPTER_OBJECT" ] && ! grep -q -- "$ADAPTER_OBJECT" "$COV_DIR/lcov-report.log"; then + echo "the lcov report did not read the Mega EEST adapter ($ADAPTER_OBJECT): cargo-llvm-cov no" \ + "longer picks up executables as this script expects, and the report would leave the suite out" >&2 + exit 1 +fi cargo llvm-cov report \ --package mega-evm \ diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index ce97a9f7a..cc6ed6081 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -4,6 +4,7 @@ Subcommands: adapter --tree --suite --out + [--engine-rustflags ] Write the Mega EEST revm adapter as a workspace of its own at , built against the mega-evm checkout rather than the commit the adapter pins. Its sources are copied as they are; its manifest is the adapter's with three changes. A dependency on a package of this @@ -16,7 +17,10 @@ workspace (the format crate) stays a path dependency on the suite's checkout. The adapter's own Cargo.lock, resolved for the commit it pins, is not used: the workspace's lock starts as this checkout's Cargo.lock, which cargo then prunes to what the adapter links and extends - with anything only the adapter needs. + with anything only the adapter needs. `--engine-rustflags` adds compiler flags to this + workspace's packages and the adapter's own crate alone (cargo's `profile-rustflags`, which + the pinned nightly has), so a coverage build instruments mega-evm and the instances of its + generic code the adapter compiles, and not the crates.io and git crates it links. check-lock --tree --adapter After cargo resolved the adapter workspace: every package mega-evm links in it, through @@ -245,7 +249,17 @@ def cmd_adapter(args: argparse.Namespace) -> int: f"({', '.join(sorted(members))}): it would not test this tree") for key in ("patch", "profile"): if key in root: - manifest[key] = root[key] + manifest[key] = json.loads(json.dumps(root[key])) + flags = args.engine_rustflags.split() + if flags: + manifest["cargo-features"] = ["profile-rustflags"] + overrides = manifest.setdefault("profile", {}).setdefault("dev", {}).setdefault("package", {}) + # The adapter's own crate too: mega-evm's generic code is compiled where it is used. + overrides.setdefault(manifest["package"]["name"], {})["rustflags"] = flags + for name, spec in manifest["dependencies"].items(): + package = spec.get("package", name) if isinstance(spec, dict) else name + if package in members: + overrides.setdefault(package, {})["rustflags"] = flags out.mkdir(parents=True, exist_ok=True) sync_tree(adapter_dir, out, keep={SEED_MARKER}) @@ -442,6 +456,8 @@ def main() -> int: pa.add_argument("--tree", required=True) pa.add_argument("--suite", required=True) pa.add_argument("--out", required=True) + pa.add_argument("--engine-rustflags", default="", + help="compiler flags for this workspace's packages alone, space-separated") pa.set_defaults(func=cmd_adapter) pl = sub.add_parser("check-lock", help="hold the resolved adapter workspace to this checkout's lock") diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index a37ae8cf8..51b095b24 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -43,6 +43,10 @@ # MEGA_EEST_TARGET_DIR the cargo target directory of both builds (default $MEGA_EEST_WORK/target) # MEGA_EEST_MODES the modes to consume in (default "plain instrumented") # MEGA_EEST_JOBS cases run at once (default: the number of CPUs) +# MEGA_EEST_ENGINE_RUSTFLAGS +# compiler flags for this tree's packages and the adapter's own crate in +# the adapter build, for a coverage build (scripts/coverage_mega_evm.sh): +# the crates.io and git crates it links are built without them # # Requires git, cargo (rustup, for this tree's toolchain), Foundry (mega-evm's system contracts # build with forge, as for every build of this tree) and Python 3.11 or newer. @@ -142,6 +146,7 @@ CLI="$TARGET/debug/mega-fixture" ADAPTER_DIR="$WORK/adapter-revm" python3 "$HELPER" adapter --tree "$ROOT_DIR" --suite "$SUITE" --out "$ADAPTER_DIR" \ + --engine-rustflags "${MEGA_EEST_ENGINE_RUSTFLAGS:-}" \ || die "cannot write the adapter workspace" log "resolving the adapter workspace on this tree's lock ($(elapsed))" cargo metadata --format-version 1 --manifest-path "$ADAPTER_DIR/Cargo.toml" > /dev/null \ diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 1ea725151..00ee9d354 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -21,10 +21,19 @@ that timed out, each regex matching that mutant's name alone. Consumed by scripts/mutation_test.sh to re-run those mutants one at a time. + missed-re --results [--recheck ] + [--suppressions ] + Print one `--re ` pair per line for every unsuppressed mutant + the tests missed: in the run, or in the re-check of one that timed out. + Consumed by scripts/mutation_test.sh to run those mutants against the + Mega EEST suite. + report --results [--recheck ] + [--mega-eest ] [--suppressions ] [--comment ] [--summary ] Read the run outcomes, take the re-check's outcome for a mutant that - timed out, apply line-scoped suppressions, compute the mutation score, + timed out and the Mega EEST run's outcome for a mutant the tests + missed, apply line-scoped suppressions, compute the mutation score, write a Markdown report, and exit non-zero if any unsuppressed survivor or timeout remains (the "no new survivors" gate). Exits 2, with a report saying why, when the results cannot be scored. @@ -364,6 +373,28 @@ def cmd_timeout_re(args: argparse.Namespace) -> int: return 0 +def cmd_missed_re(args: argparse.Namespace) -> int: + try: + run = load_run(Path(args.results)) + recheck = None + if run.timeout and args.recheck and Path(args.recheck).exists(): + recheck = load_run(Path(args.recheck)) + except ResultsError as err: + # Nothing to run; the gate reports why the results cannot be scored. + print(f"no missed mutants to run against Mega EEST: {err}", file=sys.stderr) + return 0 + missed = list(run.missed) + if recheck is not None: + missed += [name for name in run.timeout if name in set(recheck.missed)] + supp = suppressed_names(args.suppressions) + for name in missed: + if is_suppressed(name, supp): + continue + print("--re") + print(f"^{re.escape(name)}$") + return 0 + + def write_report(report: str, args: argparse.Namespace) -> None: if args.comment: Path(args.comment).write_text(report) @@ -426,6 +457,38 @@ def cmd_report(args: argparse.Namespace) -> int: else: timeout = list(run.timeout) + # A mutant the tests missed was run once more against the Mega EEST suite; one it catches is + # caught, one it times out on is inconclusive, and the rest stay survivors. Its results speak + # for those mutants alone, as a re-check's speak for the timeouts. + mega_eest_dir = getattr(args, "mega_eest", None) + against_eest: dict[str, list[str]] = {"caught": [], "missed": [], "timeout": [], "absent": []} + eest = None + if missed and mega_eest_dir and Path(mega_eest_dir).exists(): + try: + eest = load_run(Path(mega_eest_dir)) + except ResultsError as err: + write_report( + "## 🧬 Mutation testing — ❌ FAIL\n\n" + f"**The Mega EEST run of the mutants the tests missed cannot be scored:** {err}.\n", + args, + ) + return 2 + if eest is not None: + verdicts = {n: k for k in ("caught", "missed", "timeout", "unviable") for n in getattr(eest, k)} + remaining = [] + for name in missed: + verdict = verdicts.get(name) + if verdict == "caught": + caught.append(name) + against_eest["caught"].append(name) + elif verdict == "timeout": + timeout.append(name) + against_eest["timeout"].append(name) + else: + remaining.append(name) + against_eest["missed" if verdict else "absent"].append(name) + missed = remaining + supp = {e["mutant"].strip() for e in line_supp if "mutant" in e} def partition(items: list[str]) -> tuple[list[str], list[str]]: @@ -478,6 +541,15 @@ def partition(items: list[str]) -> tuple[list[str], list[str]]: f"{len(rechecked['caught'])} caught, {len(rechecked['missed'])} survived, " f"{len(rechecked['timeout'])} timed out again, {len(rechecked['absent'])} not re-run" ) + ran_against_eest = sum(len(v) for v in against_eest.values()) + if eest is not None: + md.append( + f"- run against Mega EEST after the tests missed them: {ran_against_eest} — " + f"{len(against_eest['caught'])} caught, {len(against_eest['missed'])} survived, " + f"{len(against_eest['timeout'])} timed out, {len(against_eest['absent'])} not run" + ) + elif mega_eest_dir and missed: + md.append(f"- run against Mega EEST: none of the {len(missed)} the tests missed (no Mega EEST results)") md.append("") def section(title: str, blurb: str, items: list[str], artifact: str) -> list[str]: @@ -591,10 +663,18 @@ def main() -> int: pt.add_argument("--suppressions", default=None) pt.set_defaults(func=cmd_timeout_re) + pm = sub.add_parser("missed-re", help="--re arguments selecting the mutants the tests missed") + pm.add_argument("--results", required=True) + pm.add_argument("--recheck", default=None) + pm.add_argument("--suppressions", default=None) + pm.set_defaults(func=cmd_missed_re) + pr = sub.add_parser("report") pr.add_argument("--results", required=True) pr.add_argument("--recheck", default=None, help="results of re-running the timed-out mutants one at a time") + pr.add_argument("--mega-eest", default=None, + help="results of running the mutants the tests missed against Mega EEST") pr.add_argument("--suppressions", default=None) pr.add_argument("--comment", default=None, help="write Markdown report here") pr.add_argument("--summary", default=None, help="append report here (GITHUB_STEP_SUMMARY)") diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 5de5b115e..085af6489 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -23,6 +23,17 @@ # MUTANTS_SHARD=k/n runs only shard k (0-based) of n of whichever mutant set the # subcommand selects (cargo-mutants' own --shard), for a diff too large for one # job; give each shard its own OUT_DIR and gate each one. See REVIEW.md. +# +# In the production scope (diff, full, file), a mutant the tests missed — in +# the run, or in the re-check of one that timed out — is run once more against +# the Mega EEST conformance suite, into $OUT_DIR/mega-eest/mutants.out: the test +# command is mega-evm's ignored `mega_eest` test alone, which runs +# scripts/mega_eest.sh (plain mode) on the mutated tree, so a mutant that only a +# Mega EEST case catches counts as caught. Pass that directory to the gate as +# --mega-eest. The suite is fetched and its adapter built once, on the unmutated +# tree, before the run; one that fails there has its exit recorded in those +# results (run-failed.txt), which the gate refuses. MUTANTS_MEGA_EEST=0 skips +# the pass, and the gate then counts those mutants as survivors. # Bash 5 or newer: the driver relies on mapfile and on expanding empty arrays # under `set -u`, which bash 3.2 (macOS's /bin/bash) does not have. Written in @@ -95,7 +106,16 @@ run_outcome() { esac } +# The arguments that scope the first run (an `--in-diff` file, a `-f` glob): the +# re-check and the Mega EEST run take them too. cargo-mutants 27.1.0 adds a +# struct-field-deletion mutant without matching it against `--re`, so a run +# selected by `--re` alone would also test every such mutant of the crate; under +# the first run's scope it tests at most the ones the first run tested, whose +# outcomes there the gate does not read. +SCOPE_ARGS=() + run_mutants() { + SCOPE_ARGS=("$@") rm -rf "$OUT_DIR" mkdir -p "$(dirname "$OUT_DIR")" # cargo-mutants creates OUT_DIR itself but not its parents # --no-shuffle: test mutants in deterministic source order so runs are @@ -123,6 +143,10 @@ run_mutants() { python3 "$ROOT_DIR/scripts/mutation_gate.py" note-empty \ --log "$OUT_DIR.log" --results "$OUT_DIR/mutants.out" recheck_timeouts + # The infrastructure scope mutates the scenario runner, which the suite's adapter never runs. + if [[ ${#CONFIG_ARGS[@]} -eq 0 && "${MUTANTS_MEGA_EEST:-1}" != 0 ]]; then + run_missed_against_mega_eest + fi } # A mutant that timed out was tested beside $JOBS others, each running the whole @@ -149,6 +173,7 @@ recheck_timeouts() { --output "$OUT_DIR/recheck" \ --no-shuffle \ -vV \ + "${SCOPE_ARGS[@]}" \ "${re_args[@]}" 2>&1 | tee "$OUT_DIR/recheck.log" || rc=$? # A re-check that fails as a run proves nothing by the files it left, which # can look like a finished run's. Its exit goes into its results, which the @@ -161,6 +186,55 @@ recheck_timeouts() { fi } +# A mutant the tests missed may still change an outcome a Mega EEST case pins. Run +# each such mutant once more with mega-evm's ignored `mega_eest` test as the only +# test (`--test mega_eest`, nextest's `--run-ignored only`); the gate takes that +# outcome for it. The suite is fetched and its adapter built on the unmutated +# tree first, which also proves the suite passes there; every build directory +# then shares that checkout, read-only, and builds the adapter against its own +# mutated mega-evm. +run_missed_against_mega_eest() { + local re_output + if ! re_output="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" missed-re \ + --results "$OUT_DIR/mutants.out" --recheck "$OUT_DIR/recheck/mutants.out" \ + --suppressions "$SUPPRESS")"; then + echo "failed to list the missed mutants in $OUT_DIR/mutants.out" >&2 + return 1 + fi + [[ -n "$re_output" ]] || return 0 + local re_args=() + mapfile -t re_args <<< "$re_output" + local results="$OUT_DIR/mega-eest/mutants.out" + echo "Running $((${#re_args[@]} / 2)) mutant(s) the tests missed against Mega EEST" >&2 + local rc=0 + # MEGA_EEST_SCRIPT stands in for the script in the driver's own tests. + MEGA_EEST_MODES=plain "${MEGA_EEST_SCRIPT:-$ROOT_DIR/scripts/mega_eest.sh}" \ + > "$OUT_DIR/mega-eest-warmup.log" 2>&1 || rc=$? + if [[ $rc -ne 0 ]]; then + echo "Mega EEST does not pass on the unmutated tree (exit $rc); see $OUT_DIR/mega-eest-warmup.log" >&2 + mkdir -p "$results" + echo "scripts/mega_eest.sh exited $rc on the unmutated tree" > "$results/run-failed.txt" + return 0 + fi + MEGA_EEST_DIR="$ROOT_DIR/target/mega-eest/src" MEGA_EEST_MODES=plain cargo mutants \ + "${PKG_ARGS[@]}" \ + --jobs "$JOBS" \ + --output "$OUT_DIR/mega-eest" \ + --no-shuffle \ + -vV \ + --cargo-arg=--test \ + --cargo-arg=mega_eest \ + "${SCOPE_ARGS[@]}" \ + "${re_args[@]}" \ + -- --run-ignored only 2>&1 | tee "$OUT_DIR/mega-eest.log" || rc=$? + # As for the re-check: a run that fails as a run proves nothing by the files it left. + if ! run_outcome "$rc"; then + echo "the Mega EEST run of the missed mutants failed (exit $rc); see $OUT_DIR/mega-eest.log" >&2 + mkdir -p "$results" + echo "cargo-mutants exited $rc" > "$results/run-failed.txt" + fi +} + cmd="${1:-}" shift || true case "$cmd" in @@ -197,4 +271,4 @@ esac echo echo "Mutation results written to $OUT_DIR/mutants.out/" -echo "Score + gate with: python3 scripts/mutation_gate.py report --results $OUT_DIR/mutants.out --recheck $OUT_DIR/recheck/mutants.out" +echo "Score + gate with: python3 scripts/mutation_gate.py report --results $OUT_DIR/mutants.out --recheck $OUT_DIR/recheck/mutants.out --mega-eest $OUT_DIR/mega-eest/mutants.out" diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index d329a767e..6570ea972 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -130,11 +130,13 @@ def suppressions(self, *mutants: str) -> Path: return path def report(self, results: Path, recheck: Path | None = None, - suppressions: Path | None = None) -> tuple[int, str]: + suppressions: Path | None = None, + mega_eest: Path | None = None) -> tuple[int, str]: comment = self.tmp / "comment.md" args = Namespace( results=str(results), recheck=str(recheck) if recheck else None, + mega_eest=str(mega_eest) if mega_eest else None, suppressions=str(suppressions) if suppressions else None, comment=str(comment), summary=None, @@ -395,6 +397,128 @@ def test_a_recheck_only_speaks_for_the_timeouts(self) -> None: self.assertIn(MISSED, text) +class MegaEestScoring(GateCase): + """A mutant the tests missed is decided by its Mega EEST run, and only such a mutant.""" + + def against_mega_eest(self, summary: str, *, suppressions: Path | None = None) -> tuple[int, str]: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) + eest = self.results("mega-eest", outcomes=outcomes_json(mutant(MISSED, summary))) + return self.report(results, suppressions=suppressions, mega_eest=eest) + + def test_a_missed_mutant_mega_eest_catches_passes(self) -> None: + code, text = self.against_mega_eest("CaughtMutant") + self.assertEqual(code, 0, text) + self.assertIn("run against Mega EEST after the tests missed them: 1 — 1 caught, 0 survived", text) + self.assertIn("(2/2 viable mutants killed)", text) + + def test_a_missed_mutant_mega_eest_misses_is_a_survivor(self) -> None: + code, text = self.against_mega_eest("MissedMutant") + self.assertEqual(code, 1, text) + self.assertIn("Survivors needing attention", text) + self.assertIn(MISSED, text) + + def test_a_missed_mutant_mega_eest_times_out_on_is_inconclusive(self) -> None: + code, text = self.against_mega_eest("Timeout") + self.assertEqual(code, 1, text) + self.assertIn("Timed-out mutants", text) + self.assertNotIn("Survivors needing attention", text) + + def test_a_missed_mutant_without_mega_eest_results_is_a_survivor(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + code, text = self.report(results, mega_eest=self.tmp / "absent") + self.assertEqual(code, 1, text) + self.assertIn("none of the 1 the tests missed (no Mega EEST results)", text) + + def test_a_missed_mutant_mega_eest_did_not_run_is_a_survivor(self) -> None: + other = "crates/mega-evm/src/b.rs:9:9: replace * with + in k" + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + eest = self.results("mega-eest", outcomes=outcomes_json(mutant(other, "CaughtMutant"))) + code, text = self.report(results, mega_eest=eest) + self.assertEqual(code, 1, text) + self.assertIn("0 caught, 0 survived, 0 timed out, 1 not run", text) + + def test_mega_eest_results_only_speak_for_the_missed(self) -> None: + # A timeout is the re-check's to decide, whatever a Mega EEST run says of it. + results = self.results(outcomes=outcomes_json( + mutant(MISSED, "MissedMutant"), mutant(TIMEOUT, "Timeout"))) + eest = self.results("mega-eest", outcomes=outcomes_json( + mutant(MISSED, "CaughtMutant"), mutant(TIMEOUT, "CaughtMutant"))) + code, text = self.report(results, self.tmp / "no-recheck", mega_eest=eest) + self.assertEqual(code, 1, text) + self.assertIn("Timed-out mutants", text) + self.assertIn(TIMEOUT, text) + + def test_a_timeout_that_survives_alone_is_decided_by_mega_eest(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) + recheck = self.results("recheck", outcomes=outcomes_json(mutant(TIMEOUT, "MissedMutant"))) + eest = self.results("mega-eest", outcomes=outcomes_json(mutant(TIMEOUT, "CaughtMutant"))) + code, text = self.report(results, recheck, mega_eest=eest) + self.assertEqual(code, 0, text) + + def test_mega_eest_results_that_cannot_be_scored_fail(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + for name, eest in [ + ("failed-baseline", outcomes_json(mutant(MISSED, "CaughtMutant"), baseline="Failure")), + ("unfinished", outcomes_json(mutant(MISSED, "CaughtMutant"), end_time=None)), + ]: + code, text = self.report(results, mega_eest=self.results(name, outcomes=eest)) + self.assertEqual(code, 2, text) + self.assertIn("Mega EEST run of the mutants the tests missed cannot be scored", text) + failed = self.results("run-failed", outcomes=outcomes_json(mutant(MISSED, "CaughtMutant")), + files={"run-failed.txt": "cargo-mutants exited 70\n"}) + code, text = self.report(results, mega_eest=failed) + self.assertEqual(code, 2, text) + self.assertIn("exited abnormally (cargo-mutants exited 70)", text) + + def test_a_suppressed_survivor_needs_no_mega_eest_run(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + code, text = self.report(results, suppressions=self.suppressions(MISSED), + mega_eest=self.tmp / "absent") + self.assertEqual(code, 0, text) + + +class MissedRe(GateCase): + """`missed-re` selects exactly the unsuppressed mutants the tests missed.""" + + def regexes(self, results: Path, recheck: Path | None = None, + suppressions: Path | None = None) -> list[str]: + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + code = gate.cmd_missed_re(Namespace( + results=str(results), recheck=str(recheck) if recheck else None, + suppressions=str(suppressions) if suppressions else None)) + self.assertEqual(code, 0) + lines = out.getvalue().splitlines() + self.assertEqual(lines[0::2], ["--re"] * (len(lines) // 2)) + return lines[1::2] + + def test_one_anchored_regex_per_missed_mutant(self) -> None: + other = "crates/mega-evm/src/a.rs:2:5: replace + with - in g2" + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"), + mutant(other, "MissedMutant"), mutant(TIMEOUT, "Timeout"))) + regexes = self.regexes(results) + names = [CAUGHT, MISSED, other, TIMEOUT] + self.assertEqual([[n for n in names if re.search(r, n)] for r in regexes], [[MISSED], [other]]) + + def test_a_timeout_the_recheck_missed_is_selected(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) + for summary, selected in [("MissedMutant", [TIMEOUT]), ("CaughtMutant", []), ("Timeout", [])]: + recheck = self.results(f"recheck-{summary}", outcomes=outcomes_json(mutant(TIMEOUT, summary))) + regexes = self.regexes(results, recheck) + self.assertEqual([n for n in [TIMEOUT] if any(re.search(r, n) for r in regexes)], selected) + + def test_suppressed_survivors_are_not_selected(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + self.assertEqual(self.regexes(results, suppressions=self.suppressions(MISSED)), []) + + def test_results_that_cannot_be_scored_select_nothing(self) -> None: + self.assertEqual(self.regexes(self.tmp / "absent"), []) + unfinished = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"), end_time=None)) + self.assertEqual(self.regexes(unfinished), []) + + class UmutateRecord(GateCase): """scripts/umutate.py writes the record the gate scores, on the contract cargo-mutants keeps.""" @@ -533,19 +657,24 @@ def bash5() -> str | None: # A stand-in for `cargo mutants`: it writes the results the test prepared for the run it is asked -# for, the first run or the re-check (the one given `--re`), and exits as the test says. +# for, by its output directory — the first run, the re-check or the Mega EEST run — records the +# arguments it was given in .argv, and exits as the test says. FAKE_CARGO = """#!/bin/sh [ "$1" = mutants ] || exit 99 shift if [ "$1" = --version ]; then echo "cargo-mutants 27.1.0"; exit 0; fi -out=""; run=main +argv="$*"; out=""; run=main while [ $# -gt 0 ]; do case "$1" in --output) out="$2"; shift ;; - --re) run=recheck ;; esac shift done +case "$(basename "$out")" in + recheck) run=recheck ;; + mega-eest) run=mega-eest ;; +esac +echo "$argv" > "$FAKE_RUNS/$run.argv" if [ -d "$FAKE_RUNS/$run" ]; then mkdir -p "$out/mutants.out" cp -R "$FAKE_RUNS/$run/." "$out/mutants.out/" @@ -581,6 +710,7 @@ def drive(self, recheck_exit: int, recheck: dict | None) -> tuple[int, str, Path capture_output=True, text=True, timeout=120, env=env) self.assertEqual(run.returncode, 0, run.stderr) self.assertIn("Re-checking 1 timed-out mutant(s) one at a time", run.stderr) + self.assertIn("-f crates/mega-evm/src/a.rs", (runs / "recheck.argv").read_text()) code, text = self.report(out / "mutants.out", out / "recheck" / "mutants.out") return code, text, out / "recheck" / "mutants.out" @@ -605,6 +735,82 @@ def test_a_recheck_that_writes_nothing_is_refused(self) -> None: self.assertIn("exited abnormally (cargo-mutants exited 1)", text) +class DriverMegaEest(GateCase): + """scripts/mutation_test.sh runs a mutant the tests missed against Mega EEST, with mega-evm's + `mega_eest` test alone, after the suite passed on the unmutated tree, and carries a failed + warm-up or run into the results, which the gate then refuses.""" + + def drive(self, *, warmup_exit: int = 0, eest_exit: int = 0, eest: dict | None = None, + env: dict[str, str] | None = None) -> tuple[int, str, Path, Path]: + shell = bash5() + if shell is None: + self.skipTest("no bash 5 or newer on this machine") + runs = self.tmp / "runs" + self.results("runs/main", outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) + (runs / "main.exit").write_text("2\n") + if eest is not None: + self.results("runs/mega-eest", outcomes=eest) + (runs / "mega-eest.exit").write_text(f"{eest_exit}\n") + bin_dir = self.tmp / "bin" + bin_dir.mkdir() + (bin_dir / "cargo").write_text(FAKE_CARGO) + (bin_dir / "cargo").chmod(0o755) + (bin_dir / "python3").symlink_to(sys.executable) + # The warm-up's stand-in records the modes it was asked for and exits as the test says. + stub = self.tmp / "mega_eest.sh" + stub.write_text(f'#!/bin/sh\necho "$MEGA_EEST_MODES" > "{runs}/warmup.modes"\nexit {warmup_exit}\n') + stub.chmod(0o755) + out = self.tmp / "out" / "mutants" + run = subprocess.run( + [shell, str(DriverGuard.DRIVER), "file", "crates/mega-evm/src/a.rs"], + capture_output=True, text=True, timeout=120, + env={"PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_RUNS": str(runs), "OUT_DIR": str(out), + "JOBS": "1", "SUPPRESS": str(self.tmp / "no-suppressions.toml"), + "MEGA_EEST_SCRIPT": str(stub), **(env or {})}) + self.assertEqual(run.returncode, 0, run.stderr) + results = out / "mega-eest" / "mutants.out" + code, text = self.report(out / "mutants.out", out / "recheck" / "mutants.out", + mega_eest=results) + return code, text, runs, results + + def test_a_missed_mutant_runs_against_mega_eest_alone(self) -> None: + code, text, runs, _ = self.drive(eest=outcomes_json(mutant(MISSED, "CaughtMutant"))) + self.assertEqual(code, 0, text) + self.assertEqual((runs / "warmup.modes").read_text(), "plain\n") + argv = (runs / "mega-eest.argv").read_text().strip() + self.assertIn("--cargo-arg=--test --cargo-arg=mega_eest", argv) + # The first run's scope, which keeps cargo-mutants' unfiltered struct-field mutants to it. + self.assertIn("-f crates/mega-evm/src/a.rs", argv) + self.assertIn(f"--re ^{re.escape(MISSED)}$", argv) + self.assertNotIn(re.escape(CAUGHT), argv) + self.assertTrue(argv.endswith("-- --run-ignored only"), argv) + + def test_a_warmup_that_fails_is_refused(self) -> None: + code, text, runs, results = self.drive( + warmup_exit=1, eest=outcomes_json(mutant(MISSED, "CaughtMutant"))) + self.assertFalse((runs / "mega-eest.argv").exists()) + self.assertEqual((results / "run-failed.txt").read_text(), + "scripts/mega_eest.sh exited 1 on the unmutated tree\n") + self.assertEqual(code, 2, text) + + def test_a_mega_eest_run_that_exits_abnormally_is_refused(self) -> None: + # Its files are those of a finished run that caught the mutant: only its exit says otherwise. + code, text, _, results = self.drive( + eest_exit=70, eest=outcomes_json(mutant(MISSED, "CaughtMutant"))) + self.assertEqual((results / "run-failed.txt").read_text(), "cargo-mutants exited 70\n") + self.assertEqual(code, 2, text) + self.assertIn("exited abnormally (cargo-mutants exited 70)", text) + + def test_the_pass_can_be_left_out(self) -> None: + code, text, runs, _ = self.drive(eest=outcomes_json(mutant(MISSED, "CaughtMutant")), + env={"MUTANTS_MEGA_EEST": "0"}) + self.assertFalse((runs / "mega-eest.argv").exists()) + self.assertFalse((runs / "warmup.modes").exists()) + self.assertEqual(code, 1, text) + self.assertIn(MISSED, text) + + class DriverGuard(unittest.TestCase): """scripts/mutation_test.sh refuses to run on a shell that is not bash 5 or newer.""" From 1aa2909611eb83e423fcd3fb3e293b07c5ccad47 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:49:55 +0800 Subject: [PATCH 103/190] docs: the Mega EEST gate --- .claude/skills/satin-review/SKILL.md | 5 +++-- AGENTS.md | 17 ++++++++++++++++- REVIEW.md | 18 +++++++++++++++++- mutants/README.md | 10 +++++++++- 4 files changed, 45 insertions(+), 5 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index f32468da2..5a66a62c0 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -222,12 +222,13 @@ Each change is stated here in plain words with its reason; the specification has ## Running the checks Commands are in [`AGENTS.md`, "Build & Development Commands"](../../../AGENTS.md#build--development-commands) and the gates in [`AGENTS.md`, "Test Gates"](../../../AGENTS.md#test-gates). -Four notes that are easy to miss: +Five notes that are easy to miss: - the `mega-evme` tests run with `--manifest-path bin/mega-evme/Cargo.toml`, not `-p`; - run the suite with `MEGA_SATIN_CPSB` and `MEGA_SATIN_CPHB` unset, or the tests that pin the spec's byte prices skip; - 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. +- the execution-spec gate needs Ethereum's fixture releases, at the versions `.github/workflows/exec-spec-satin.yml` downloads; +- the Mega EEST gate (`scripts/mega_eest.sh`) fetches the suite at the commit `scripts/mega_eest.env` pins, or reads a checkout at that commit from `MEGA_EEST_DIR`. 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. diff --git a/AGENTS.md b/AGENTS.md index 40bc3cf0c..84b3e5d55 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,6 +57,12 @@ cargo run --release -p state-test -- --mode satin --fork Osaka /s # 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 +# The Mega EEST gate (see Test Gates): the shared conformance suite at the commit scripts/mega_eest.env pins, +# through its revm adapter built against this checkout, every case plain and instrumented (logs under target/mega-eest) +scripts/mega_eest.sh +MEGA_EEST_DIR= scripts/mega_eest.sh # without the fetch +cargo test -p mega-evm --test mega_eest -- --ignored # the same run, as the mutation gate starts it + # Check compiler errors (preferred over clippy for quick checks) cargo check cargo check -p mega-evm @@ -638,7 +644,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te ## Test Gates -`REVIEW.md` lists the test gates a pull request meets ("Test gates"); three of them are this repository's own execution gates — the op-revm baseline, the execution-spec gate and the witness replay — and the byte-price grid holds the suite at other byte prices. +`REVIEW.md` lists the test gates a pull request meets ("Test gates"); four of them are this repository's own execution gates — the op-revm baseline, the execution-spec gate, the witness replay and the Mega EEST gate — and the byte-price grid holds the suite at other byte prices. - **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. @@ -659,6 +665,15 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te A fixture entry the engine rejects has no returned state to build the channel witness from, and replays on the record alone. The block tests cover each mechanism that reads, in the `test` job; `exec-spec-satin.yml` replays every Osaka and Amsterdam entry of the fixture releases in both modes and fails on any entry that does not replay, counting the entries replayed on both witnesses apart from the rejected ones. The fixture test is always ignored by default: it runs only with `-- --ignored` (or `--include-ignored`) and `MEGA_STATE_TEST_FIXTURES` set to the fixtures, and setting the variable alone runs nothing. +- **The Mega EEST gate** (`scripts/mega_eest.sh`, `.github/workflows/mega-eest.yml`): Mega EEST is the conformance suite both Satin implementations share, its state-transition cases each pinned to rules of the Satin specification, and this gate holds this tree to every gating case of it. + The commit it runs is the one line `MEGA_EEST_REV` of `scripts/mega_eest.env`; the script fetches it (or takes `MEGA_EEST_DIR`, which must be at the pin and unmodified), builds the suite's `mega-fixture` CLI and its revm adapter, and consumes every case of `slice/cases` plain and `--instrumented`. + The adapter is built against this checkout, not the mega-evm commit it pins: `scripts/mega_eest.py` writes it out as a workspace of its own (`target/mega-eest/adapter-revm`) whose mega-evm is a path dependency on `crates/mega-evm`, whose other crates take their sources from this tree's `[workspace.dependencies]`, and whose `[patch]` and `[profile]` tables are this tree's root manifest's, so a pull request that moves the revm or op-revm fork is tested with its own fork. + The adapter's `Cargo.lock`, resolved for the commit it pins, is not used: the workspace's lock is seeded with this tree's `Cargo.lock`, cargo resolves it once, every package mega-evm links must then be at the version and source this tree locks, with one revm, and the build runs `--locked`. + It passes when the cases consumed are exactly the slice's index, by case id and file digest, every one passes in both modes with the same observations, and the suite's deliberately wrong expectation fails where it records; a failure names the case, its first differing path, both values and the rules it pins, and the summary is one `MEGA-EEST` line. + The `Mega EEST gate` job always runs and is the required check: a pull request that changes documentation alone skips the run (`scripts/pull_request_needs_ci.sh`) and the job passes; every other pull request and every push to `satin` runs it. + When it fails: a case that fails pins behaviour of the specification, so the change is wrong, or it changes that behaviour on purpose, and then the case changes in Mega EEST first; an adapter that no longer builds against this tree means the change altered the mega-evm API the adapter calls (`MegaEvm::execute_transaction`, the `MegaContext` constructors, `system::live_system_address`, the error and result types), and the adapter changes in Mega EEST first. + Either way the same pull request then moves the pin to that Mega EEST commit; nothing is skipped or waived here. + The coverage report (`scripts/coverage_mega_evm.sh`) merges the suite's run, through the adapter built with mega-evm instrumented, with the tests', so a line only a Mega EEST case runs counts as covered; the mutation gate runs every mutant the tests miss against the suite (`scripts/mutation_test.sh`, through the ignored `mega_eest` test), so a mutant only a Mega EEST case catches counts as caught. - **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, the whole grid, as four parallel shards, on every pull request that changes more than documentation and on dispatch (`--pr`, five points, is the quick local mode). The prices are provisional, so a test holds at any of them — a byte price of nothing, or one gas per byte up to the grid's dearest point: it sizes its gas from the schedule at the prices in effect, and a case whose scenario is state or history gas returns early where that byte costs nothing (`state_is_free`, `history_is_free`). Below one gas per byte the schedule's entries round to nothing one at a time, and no test is held there. diff --git a/REVIEW.md b/REVIEW.md index fc7401992..c2ea7e5b6 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -99,7 +99,7 @@ Defer to the baseline for everything not listed here; the rules below take prece ## Test gates These checks guard every change to the Satin engine. -`lint`, `test`, `no-std` and `require-label` are the required checks on `satin`; the rest inform the review, and the reviewer reads them. +`lint`, `test`, `no-std`, `require-label` and `Mega EEST gate` are the required checks on `satin`; the rest inform the review, and the reviewer reads them. ### The op-revm baseline @@ -142,6 +142,19 @@ These checks guard every change to the Satin engine. `.github/workflows/exec-spec-satin.yml` runs the fixture replay after the equivalence gate, on the same fixture releases: every Osaka and Amsterdam entry, in equivalence and in Satin mode; an entry that does not replay fails the job, and so `execution-spec gate on Satin`, and so does a run that prints no single well-formed summary, executes nothing or reports a failed entry. The step summary counts the entries replayed on both witnesses apart from the rejected ones. +### Mega EEST + +- Mega EEST is the conformance suite both Satin implementations share: state-transition cases, each pinned to rules of the Satin specification, run on an implementation through an adapter. + `.github/workflows/mega-eest.yml` runs `scripts/mega_eest.sh`, which consumes every gating case of the suite at the commit `scripts/mega_eest.env` pins (`MEGA_EEST_REV`), plain and instrumented, through the suite's revm adapter built against the pull request's own mega-evm, `[patch]` blocks and `Cargo.lock` (AGENTS.md, Test Gates, has how). +- The `Mega EEST gate` job always runs and is a required check; a pull request that changes documentation alone skips the run and passes it. + The step summary has the summary line (`MEGA-EEST rev=… cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… result=…`) and the run's time; a failing run uploads its reports. +- A case that fails is a change of behaviour the specification pins. + A pull request that makes it on purpose, or that changes the mega-evm API the suite's adapter calls (the adapter then no longer builds, and the gate says so), changes Mega EEST first: the case, derived from the changed rule, or the adapter, in a pull request there. + It then moves `MEGA_EEST_REV` to that Mega EEST commit, in the same mega-evm pull request, so the gate runs the suite that pull request needs; until the Mega EEST change merges, the pin may name its branch's commit, which the fetch reaches by its hash, and it moves to the merged commit before the mega-evm pull request merges. + Locally, a Mega EEST checkout at that commit is used with `MEGA_EEST_DIR= scripts/mega_eest.sh` once the pin names it. +- Moving the pin is a one-line change and is reviewed as one: the suite's own history between the two commits says which cases and which adapter code moved. +- The coverage report and the mutation gate count the suite too: `scripts/coverage_mega_evm.sh` merges its run into the report Codecov receives, and the cargo-mutants gate runs a mutant the tests miss against it (Mutation testing, below). + ### Byte-price grid - `.github/workflows/price-grid.yml` runs the `mega-evm` suite at byte prices other than the constants, through `scripts/price_grid.sh`: a cost per state byte and a cost per history byte per point, each run with `--no-fail-fast`. @@ -181,6 +194,9 @@ These checks guard every change to the Satin engine. Reference point, the pull request that brought the Satin skeleton: 115 mutants, 49 caught, 0 survived, 1 suppressed, 65 unviable, in 7m41s on CI and 4m12s on a 15-core laptop with `JOBS=8`. That population is the diff against `a8f8c7c9`, the last commit of the legacy core, and it is reproduced by `scripts/mutation_test.sh diff a8f8c7c9` followed by `python3 scripts/mutation_gate.py report --results target/mutants/mutants.out --recheck target/mutants/recheck/mutants.out --suppressions mutants/suppressions.toml`. Take the numbers from that pair, not from `cargo mutants` on its own: the driver turns the function-scoped suppressions into `--exclude-re` before generation, and the gate filters the line-scoped ones after the run, so the bare command reports a different population and a different survivor count. +- A mutant the tests miss is run once more against the Mega EEST suite, with mega-evm's ignored `mega_eest` test as the only test, which runs `scripts/mega_eest.sh` (plain) on the mutated tree; one a Mega EEST case catches counts as caught, and the report says how many the suite decided. + The suite is fetched and its adapter built on the unmutated tree first, which must pass; a warm-up or a run that fails as a run is recorded in its results, which the gate refuses. + The pass costs nothing while the tests catch every mutant, and about one adapter build and one run of the suite per mutant they miss. - The job is bounded to 330 minutes. Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. diff --git a/mutants/README.md b/mutants/README.md index 713a61683..70f4523f9 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -32,7 +32,8 @@ It never reads `.cargo/mutants.toml`, and a change to `mutants/suppressions.toml # Mutate only what your branch changed (what CI runs on a PR): scripts/mutation_test.sh diff origin/main python3 scripts/mutation_gate.py report --results target/mutants/mutants.out \ - --recheck target/mutants/recheck/mutants.out --suppressions mutants/suppressions.toml + --recheck target/mutants/recheck/mutants.out --mega-eest target/mutants/mega-eest/mutants.out \ + --suppressions mutants/suppressions.toml # One subsystem while iterating: scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' @@ -69,6 +70,13 @@ A mutant that **timed out** was tested beside the others the run tests at once, One caught alone is caught, one that survives alone is a survivor, and one that times out again stays inconclusive and fails the gate. A re-check that exits abnormally proves nothing by the files it left, so the driver records its exit in its results (`run-failed.txt`), and the gate refuses to score them, saying why. +A mutant the tests **missed** — in the run, or in the re-check of one that timed out — may still change an outcome a case of the Mega EEST conformance suite pins. +In the production scope the driver runs each such unsuppressed mutant once more, into `mega-eest/mutants.out`, with mega-evm's ignored `mega_eest` test as the only test (`--test mega_eest`, nextest's `--run-ignored only`), which runs `scripts/mega_eest.sh` in plain mode on the mutated tree; pass that directory to the gate as `--mega-eest`. +One the suite catches counts as caught, one it times out on stays inconclusive, and the rest stay survivors. +The suite is fetched and its adapter built on the unmutated tree first, which must pass there; a warm-up that fails, or a run that exits abnormally, is recorded in those results as `run-failed.txt` and refused. +`MUTANTS_MEGA_EEST=0` leaves the pass out, and the mutants it would have run stay survivors. +The re-check and this run take the first run's own scope (its `--in-diff` file or `-f` glob) beside their `--re` selections, because cargo-mutants 27.1.0 adds struct-field-deletion mutants without matching them against `--re`; the gate reads their outcomes only for the mutants it asked about. + ## Suppressions (hybrid) A survivor that is *not* a real gap (an **equivalent mutant** that can't change behavior, or dead/defensive code) is recorded in `suppressions.toml` with a justification and reviewer. From e811988eee09ea8d425977eccd57a5a184b59245 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:51:13 +0800 Subject: [PATCH 104/190] ci: isolate the Mega EEST pass's build directories --- scripts/mega_eest.sh | 4 +++- scripts/mutation_test.sh | 7 ++++++- scripts/test_mutation_gate.py | 8 +++++++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index 51b095b24..45615157f 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -96,7 +96,9 @@ REV=$(read_pin MEGA_EEST_REV) # The paths of a checkout that decide what runs: a change to any of them is a different suite. SUITE_PATHS=(slice specs adapters crates Cargo.toml Cargo.lock) -# Whether the checkout $1 is the pinned commit with those paths as committed. +# Whether the checkout $1 is the pinned commit with those paths as committed. Git takes no optional +# lock for it: several runs may read one checkout at once (the mutation gate's build directories). +export GIT_OPTIONAL_LOCKS=0 at_pin() { [ "$(git -C "$1" rev-parse HEAD 2> /dev/null)" = "$REV" ] \ && [ -z "$(git -C "$1" status --porcelain --untracked-files=all -- "${SUITE_PATHS[@]}")" ] diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 085af6489..b0360f3cb 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -216,7 +216,12 @@ run_missed_against_mega_eest() { echo "scripts/mega_eest.sh exited $rc on the unmutated tree" > "$results/run-failed.txt" return 0 fi - MEGA_EEST_DIR="$ROOT_DIR/target/mega-eest/src" MEGA_EEST_MODES=plain cargo mutants \ + # Every build directory reads the checkout the warm-up used, and writes its adapter workspace, + # logs and build in its own target directory: a work or target directory set for the warm-up + # would be shared by builds running at once. + env -u MEGA_EEST_WORK -u MEGA_EEST_TARGET_DIR \ + MEGA_EEST_DIR="${MEGA_EEST_DIR:-${MEGA_EEST_WORK:-$ROOT_DIR/target/mega-eest}/src}" \ + MEGA_EEST_MODES=plain cargo mutants \ "${PKG_ARGS[@]}" \ --jobs "$JOBS" \ --output "$OUT_DIR/mega-eest" \ diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 6570ea972..aabf79025 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -675,6 +675,7 @@ def bash5() -> str | None: mega-eest) run=mega-eest ;; esac echo "$argv" > "$FAKE_RUNS/$run.argv" +echo "dir=${MEGA_EEST_DIR-unset} modes=${MEGA_EEST_MODES-unset} work=${MEGA_EEST_WORK-unset}" > "$FAKE_RUNS/$run.env" if [ -d "$FAKE_RUNS/$run" ]; then mkdir -p "$out/mutants.out" cp -R "$FAKE_RUNS/$run/." "$out/mutants.out/" @@ -775,9 +776,14 @@ def drive(self, *, warmup_exit: int = 0, eest_exit: int = 0, eest: dict | None = return code, text, runs, results def test_a_missed_mutant_runs_against_mega_eest_alone(self) -> None: - code, text, runs, _ = self.drive(eest=outcomes_json(mutant(MISSED, "CaughtMutant"))) + work = self.tmp / "eest-work" + code, text, runs, _ = self.drive(eest=outcomes_json(mutant(MISSED, "CaughtMutant")), + env={"MEGA_EEST_WORK": str(work)}) self.assertEqual(code, 0, text) self.assertEqual((runs / "warmup.modes").read_text(), "plain\n") + # Every build directory reads the warm-up's checkout and works in its own directory. + self.assertEqual((runs / "mega-eest.env").read_text(), + f"dir={work}/src modes=plain work=unset\n") argv = (runs / "mega-eest.argv").read_text().strip() self.assertIn("--cargo-arg=--test --cargo-arg=mega_eest", argv) # The first run's scope, which keeps cargo-mutants' unfiltered struct-field mutants to it. From 9391e604dc98b0edbebcba11a91e39eb1c6dce73 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:51:30 +0800 Subject: [PATCH 105/190] style: wrap the mega_eest test's module doc --- crates/mega-evm/tests/mega_eest/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/mega_eest/main.rs b/crates/mega-evm/tests/mega_eest/main.rs index 9d3ad4379..4340d62d8 100644 --- a/crates/mega-evm/tests/mega_eest/main.rs +++ b/crates/mega-evm/tests/mega_eest/main.rs @@ -7,8 +7,8 @@ //! //! It is ignored: it builds a second copy of mega-evm for the adapter and runs for a minute or //! more, and CI runs the script itself as the Mega EEST gate. The mutation gate runs it, with -//! nextest's `--run-ignored only`, for each mutant the rest of the suite does not catch, so a mutant -//! that only a Mega EEST case catches counts as caught. +//! nextest's `--run-ignored only`, for each mutant the rest of the suite does not catch, so a +//! mutant that only a Mega EEST case catches counts as caught. use std::{path::Path, process::Command}; From 8fc3df7a94b19f73e6aa24eb99ae6bb30cbce090 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:54:14 +0800 Subject: [PATCH 106/190] test(ci): the Mega EEST helper's manifest, lock and verdict --- scripts/test_mega_eest.py | 348 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 348 insertions(+) create mode 100644 scripts/test_mega_eest.py diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py new file mode 100644 index 000000000..468401bf0 --- /dev/null +++ b/scripts/test_mega_eest.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +"""Tests of scripts/mega_eest.py, the structured-file half of the Mega EEST gate. + +Run from the repository root with Python 3.11 or newer (the script reads TOML with tomllib): + + python3 -m unittest discover -s scripts -p 'test_*.py' -v + +Each case writes, in a temporary directory, the files the gate reads — a mega-evm root manifest +and lock, the suite's adapter manifest, the run reports `mega-fixture consume` writes and the +slice's index — in the shapes they have, and runs a subcommand on them. +""" +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import shutil +import sys +import tempfile +import tomllib +import unittest +from argparse import Namespace +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parent + + +def load_script(name: str): + spec = importlib.util.spec_from_file_location(name, SCRIPTS / f"{name}.py") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +eest = load_script("mega_eest") + +FORK = "git+https://github.com/megaeth-labs/revm?rev=aaaa#aaaa" +OTHER_FORK = "git+https://github.com/megaeth-labs/revm?rev=bbbb#bbbb" +CRATES_IO = "registry+https://github.com/rust-lang/crates.io-index" + +ROOT_MANIFEST = """ +[workspace] +members = ["crates/mega-evm"] + +[workspace.dependencies] +revm = { version = "=40.0.3", default-features = false } +alloy-rlp = { version = "0.3.16", default-features = false } +op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "new", default-features = false } +mega-evm = { path = "crates/mega-evm", version = "2.0.0" } + +[profile.dev.package] +blst.opt-level = 3 + +[patch.crates-io] +revm = { git = "https://github.com/megaeth-labs/revm", rev = "new-fork" } + +[patch."https://github.com/ethereum-optimism/optimism"] +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "new-op" } +""" + +ADAPTER_MANIFEST = """ +[workspace] + +[package] +name = "mega-eest-adapter-revm" +version = "0.1.0" +edition = "2024" + +[[bin]] +name = "adapter-revm" +path = "src/main.rs" + +[dependencies] +mega-fixture-format = { path = "../../crates/mega-fixture-format" } +mega-evm = { git = "https://github.com/megaeth-labs/mega-evm", rev = "old", features = ["test-utils"] } +revm = { version = "=40.0.3" } +alloy-rlp = { version = "0.3" } +op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "old" } +serde = "1" + +[patch.crates-io] +revm = { git = "https://github.com/megaeth-labs/revm", rev = "old-fork" } +""" + + +def lock(*packages: dict) -> str: + """A Cargo.lock holding `packages`, each `{name, version, source?, dependencies?}`.""" + out = ["version = 4", ""] + for p in packages: + out.append("[[package]]") + out.append(f'name = "{p["name"]}"') + out.append(f'version = "{p["version"]}"') + if "source" in p: + out.append(f'source = "{p["source"]}"') + if p.get("dependencies"): + out.append("dependencies = [" + ", ".join(json.dumps(d) for d in p["dependencies"]) + "]") + out.append("") + return "\n".join(out) + + +class Case(unittest.TestCase): + def setUp(self) -> None: + self.tmp = Path(tempfile.mkdtemp(prefix="mega-eest-test-")) + self.addCleanup(shutil.rmtree, self.tmp) + + def run_quietly(self, func, args: Namespace) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + code = func(args) + except eest.GateError as e: + print(f"mega-eest: error: {e}", file=sys.stderr) + code = 1 + return code, out.getvalue(), err.getvalue() + + +class RenderToml(unittest.TestCase): + """The writer's text reads back as the document it was given, or it refuses.""" + + def test_a_manifest_reads_back_as_written(self) -> None: + doc = { + "cargo-features": ["profile-rustflags"], + "workspace": {}, + "package": {"name": "a", "version": "0.1.0", "metadata": {"k": "v"}}, + "bin": [{"name": "adapter-revm", "path": "src/main.rs"}], + "dependencies": {"x": {"path": "/p q/\"r\"", "features": ["f"], "default-features": False}}, + "patch": {"https://github.com/o/r": {"op-revm": {"git": "u", "rev": "r"}}}, + "profile": {"dev": {"debug": "full", "package": {"blst": {"opt-level": 3}}}}, + } + self.assertEqual(tomllib.loads(eest.render_toml(doc)), doc) + + def test_a_value_it_cannot_write_is_refused(self) -> None: + with self.assertRaises(eest.GateError): + eest.render_toml({"package": {"when": object()}}) + + +class Adapter(Case): + """The generated workspace builds the adapter against this checkout.""" + + def write_inputs(self) -> tuple[Path, Path]: + tree, suite = self.tmp / "tree", self.tmp / "suite" + (tree / "crates" / "mega-evm").mkdir(parents=True) + (tree / "Cargo.toml").write_text(ROOT_MANIFEST) + (tree / "crates" / "mega-evm" / "Cargo.toml").write_text('[package]\nname = "mega-evm"\n') + (tree / "Cargo.lock").write_text(lock({"name": "mega-evm", "version": "2.0.0"})) + adapter = suite / "adapters" / "revm" + (adapter / "src").mkdir(parents=True) + (adapter / "Cargo.toml").write_text(ADAPTER_MANIFEST) + (adapter / "Cargo.lock").write_text("# the adapter's own lock\n") + (adapter / "rust-toolchain.toml").write_text('[toolchain]\nchannel = "other"\n') + (adapter / "build.rs").write_text("fn main() {}\n") + (adapter / "src" / "main.rs").write_text("fn main() {}\n") + return tree, suite + + def generate(self, tree: Path, suite: Path, out: Path, flags: str = "") -> dict: + code, _, err = self.run_quietly(eest.cmd_adapter, Namespace( + tree=str(tree), suite=str(suite), out=str(out), engine_rustflags=flags)) + self.assertEqual(code, 0, err) + return tomllib.loads((out / "Cargo.toml").read_text()) + + def test_the_engine_and_its_crates_follow_this_checkout(self) -> None: + tree, suite = self.write_inputs() + out = self.tmp / "out" + manifest = self.generate(tree, suite, out) + deps = manifest["dependencies"] + # This checkout's package, by path, with the adapter's features. + self.assertEqual(deps["mega-evm"], {"path": str((tree / "crates/mega-evm").resolve()), + "features": ["test-utils"]}) + # The sources this checkout declares, without its default-features choice. + self.assertEqual(deps["op-revm"], {"git": "https://github.com/ethereum-optimism/optimism", + "rev": "new"}) + self.assertEqual(deps["alloy-rlp"], {"version": "0.3.16"}) + # The suite's own path dependency, made absolute; a crate this checkout does not declare, + # as the adapter declares it. + self.assertEqual(deps["mega-fixture-format"], + {"path": str((suite / "crates/mega-fixture-format").resolve())}) + self.assertEqual(deps["serde"], {"version": "1"}) + # This checkout's patches and profiles, replacing the adapter's. + self.assertEqual(manifest["patch"]["crates-io"]["revm"]["rev"], "new-fork") + self.assertEqual(manifest["patch"]["https://github.com/ethereum-optimism/optimism"]["op-revm"]["rev"], + "new-op") + self.assertEqual(manifest["profile"]["dev"]["package"]["blst"], {"opt-level": 3}) + self.assertNotIn("cargo-features", manifest) + # The adapter's sources are copied; its lock and toolchain are not, and the lock is this + # checkout's. + self.assertEqual(sorted(p.relative_to(out).as_posix() for p in out.rglob("*") if p.is_file()), + [".mega-eest-seed", "Cargo.lock", "Cargo.toml", "build.rs", "src/main.rs"]) + self.assertEqual((out / "Cargo.lock").read_text(), (tree / "Cargo.lock").read_text()) + + def test_engine_rustflags_reach_the_engine_and_the_adapter_alone(self) -> None: + tree, suite = self.write_inputs() + manifest = self.generate(tree, suite, self.tmp / "out", "-Cinstrument-coverage --cfg=coverage") + self.assertEqual(manifest["cargo-features"], ["profile-rustflags"]) + packages = manifest["profile"]["dev"]["package"] + flags = ["-Cinstrument-coverage", "--cfg=coverage"] + self.assertEqual(packages["mega-evm"], {"rustflags": flags}) + self.assertEqual(packages["mega-eest-adapter-revm"], {"rustflags": flags}) + self.assertEqual(packages["blst"], {"opt-level": 3}) + self.assertEqual(sorted(packages), ["blst", "mega-eest-adapter-revm", "mega-evm"]) + + def test_a_resolved_lock_is_kept_and_a_changed_lock_reseeds(self) -> None: + tree, suite = self.write_inputs() + out = self.tmp / "out" + self.generate(tree, suite, out) + (out / "Cargo.lock").write_text("# what cargo resolved\n") + self.generate(tree, suite, out) + self.assertEqual((out / "Cargo.lock").read_text(), "# what cargo resolved\n") + (tree / "Cargo.lock").write_text(lock({"name": "mega-evm", "version": "2.0.1"})) + self.generate(tree, suite, out) + self.assertEqual((out / "Cargo.lock").read_text(), (tree / "Cargo.lock").read_text()) + + def test_an_adapter_that_does_not_depend_on_this_checkout_is_refused(self) -> None: + tree, suite = self.write_inputs() + manifest = suite / "adapters" / "revm" / "Cargo.toml" + manifest.write_text(manifest.read_text().replace("\nmega-evm = ", "\nother-evm = ")) + code, _, err = self.run_quietly(eest.cmd_adapter, Namespace( + tree=str(tree), suite=str(suite), out=str(self.tmp / "out"), engine_rustflags="")) + self.assertEqual(code, 1) + self.assertIn("depends on no package of this checkout", err) + + +class CheckLock(Case): + """Every package mega-evm links is one this checkout locks, and there is one revm.""" + + ENGINE = {"name": "mega-evm", "version": "2.0.0", "dependencies": ["revm", "alloy-rlp"]} + REVM = {"name": "revm", "version": "40.0.3", "source": FORK} + RLP = {"name": "alloy-rlp", "version": "0.3.16", "source": CRATES_IO} + + def check(self, adapter_lock: str) -> tuple[int, str]: + tree, adapter = self.tmp / "tree", self.tmp / "adapter" + tree.mkdir() + adapter.mkdir() + (tree / "Cargo.lock").write_text(lock(self.ENGINE, self.REVM, self.RLP)) + (adapter / "Cargo.lock").write_text(adapter_lock) + code, _, err = self.run_quietly(eest.cmd_check_lock, Namespace(tree=str(tree), adapter=str(adapter))) + return code, err + + def test_the_engine_as_this_checkout_locks_it_passes(self) -> None: + extra = {"name": "sha2", "version": "0.10.9", "source": CRATES_IO} + code, err = self.check(lock(self.ENGINE, self.REVM, self.RLP, extra)) + self.assertEqual(code, 0, err) + self.assertIn("mega-evm links 3 packages", err) + self.assertIn("for the adapter alone: sha2 0.10.9", err) + + def test_a_package_at_another_version_fails(self) -> None: + newer = {"name": "alloy-rlp", "version": "0.3.17", "source": CRATES_IO} + code, err = self.check(lock(self.ENGINE, self.REVM, newer)) + self.assertEqual(code, 1, err) + self.assertIn("alloy-rlp 0.3.17", err) + + def test_a_second_revm_fails(self) -> None: + engine = {**self.ENGINE, "dependencies": [f"revm 40.0.3 ({FORK})", "alloy-rlp"]} + other = {"name": "revm", "version": "40.0.3", "source": OTHER_FORK} + code, err = self.check(lock(engine, self.REVM, other, self.RLP)) + self.assertEqual(code, 1, err) + self.assertIn("2 revm packages, not one", err) + + +class Check(Case): + """The run reports decide the gate.""" + + CASES = [("satin/a", "sha256:1"), ("satin/b", "sha256:2")] + + def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | None = None, + exits: dict[str, int] | None = None) -> tuple[int, str, str]: + # A fresh pair for every call: a test may write several runs. + run = Path(tempfile.mkdtemp(dir=self.tmp)) + suite, work = run / "suite", run / "work" + (suite / "slice").mkdir(parents=True) + work.mkdir() + (suite / "slice" / "index.json").write_text(json.dumps({ + "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], + "negative": [{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}], + })) + for mode, cases in reports.items(): + if cases is not None: + (work / f"{mode}.json").write_text(json.dumps({"cases": cases})) + (work / f"{mode}.exit").write_text(f"{(exits or {}).get(mode, 0)}\n") + if negative is not None: + (work / "negative.json").write_text(json.dumps({"cases": negative})) + return self.run_quietly(eest.cmd_check, Namespace( + suite=str(suite), work=str(work), modes=" ".join(reports), rev="f" * 40)) + + @staticmethod + def passed(case_id: str, digest: str, observations: str = "sha256:o") -> dict: + return {"caseId": case_id, "fileDigest": digest, "status": "pass", "observationsDigest": observations, + "file": f"{case_id}.json"} + + NEGATIVE = [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/x"}] + + def all_passed(self) -> list[dict]: + return [self.passed(c, d) for c, d in self.CASES] + + def test_every_case_passing_in_both_modes_passes(self) -> None: + code, out, err = self.write({"plain": self.all_passed(), "instrumented": self.all_passed()}, self.NEGATIVE) + self.assertEqual(code, 0, err) + self.assertEqual(out.strip(), f"MEGA-EEST rev={'f' * 40} cases=2 plain=pass:2,fail:0,unsupported:0,error:0 " + "instrumented=pass:2,fail:0,unsupported:0,error:0 parity=identical " + "negative=fail-as-recorded result=pass") + + def test_a_failing_case_is_named_with_its_difference(self) -> None: + failed = {"caseId": "satin/b", "fileDigest": "sha256:2", "status": "fail", "path": "/expected/gasLedgers/state", + "expected": "0x1", "actual": "0x2", "rules": ["R-1"], "file": "b.json"} + code, out, err = self.write({"plain": [self.passed("satin/a", "sha256:1"), failed]}, self.NEGATIVE) + self.assertEqual(code, 1) + self.assertIn("result=FAIL", out) + self.assertIn("plain=pass:1,fail:1", out) + self.assertIn("fail satin/b\n first difference at /expected/gasLedgers/state: expected \"0x1\" actual \"0x2\"", err) + self.assertIn("rules: R-1", err) + + def test_cases_that_are_not_the_index_fail(self) -> None: + for cases in ([self.passed("satin/a", "sha256:1")], + [self.passed("satin/a", "sha256:1"), self.passed("satin/b", "sha256:other")], + []): + code, out, err = self.write({"plain": cases}, self.NEGATIVE) + self.assertEqual(code, 1, cases) + self.assertIn("the cases consumed are not the slice's index", err) + + def test_a_mode_without_a_report_fails(self) -> None: + code, out, err = self.write({"plain": self.all_passed(), "instrumented": None}, self.NEGATIVE, + exits={"instrumented": 2}) + self.assertEqual(code, 1) + self.assertIn("instrumented=no-report", out) + self.assertIn("wrote no report (exit 2)", err) + + def test_observations_that_differ_between_modes_fail(self) -> None: + other = [self.passed("satin/a", "sha256:1"), self.passed("satin/b", "sha256:2", "sha256:other")] + code, out, err = self.write({"plain": self.all_passed(), "instrumented": other}, self.NEGATIVE) + self.assertEqual(code, 1) + self.assertIn("parity=1-differ", out) + + def test_a_wrong_expectation_that_is_not_caught_fails(self) -> None: + for negative in (None, [{"caseId": "satin/negative/wrong", "status": "pass"}], + [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/y"}]): + code, out, err = self.write({"plain": self.all_passed()}, negative) + self.assertEqual(code, 1, negative) + self.assertNotIn("negative=fail-as-recorded", out) + + def test_a_nonzero_consume_exit_fails_even_when_every_case_passed(self) -> None: + code, out, _ = self.write({"plain": self.all_passed()}, self.NEGATIVE, exits={"plain": 1}) + self.assertEqual(code, 1) + self.assertIn("result=FAIL", out) + + +if __name__ == "__main__": + unittest.main() From 0aa023cc3e6d7e312c8e5089f3cda48e97cd5050 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 12:55:03 +0800 Subject: [PATCH 107/190] ci: say the self-test job runs the Mega EEST helper's tests --- .github/workflows/mutation.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index a03949161..185defbd0 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -210,7 +210,8 @@ jobs: # ── gate self-test: the scorer's and the driver's own tests ──────────────── # The gate reads a run fail-closed; its tests hold every way a run can leave # results that say nothing to a failure, and the driver's refusal of an old - # bash. Seconds long, so it runs on every PR. + # bash. Every scripts/test_*.py runs here, the Mega EEST gate's helper's + # (scripts/test_mega_eest.py) among them. Seconds long, so it runs on every PR. gate-selftest: name: mutation gate self-test runs-on: ubuntu-24.04 From d7518e868315af1026a85eb85a7c3bafd35e1507 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:00:38 +0800 Subject: [PATCH 108/190] ci: tell the Mega EEST gate's verdicts from runs that reached none, and check the pin --- .github/workflows/mega-eest.yml | 69 +++- crates/mega-evm/tests/mega_eest/main.rs | 44 ++- scripts/mega_eest.env | 13 +- scripts/mega_eest.py | 225 +++++++++-- scripts/mega_eest.sh | 292 ++++++++++++--- scripts/test_mega_eest.py | 478 +++++++++++++++++++++--- 6 files changed, 953 insertions(+), 168 deletions(-) diff --git a/.github/workflows/mega-eest.yml b/.github/workflows/mega-eest.yml index e32edc66c..aa83e204c 100644 --- a/.github/workflows/mega-eest.yml +++ b/.github/workflows/mega-eest.yml @@ -6,7 +6,17 @@ name: Mega EEST # pull request that moves the revm or op-revm fork is tested with its own fork. Each case is # consumed plain and instrumented; the gate passes when the cases consumed are exactly the slice's # index, every one passes in both modes with the same observations, and the suite's deliberately -# wrong expectation fails where it records. +# wrong expectation fails where it records. The script's exit says which: 0 pass, 1 cases failed, +# 2 no verdict (a fetch, a build, a report), 3 the pin refused; the job also requires the summary +# line of the full run (`run=full`) of a pin on Mega EEST's default branch. +# +# The pin is what holds every behaviour a deleted mega-evm test pinned and a Mega EEST case pins in +# its place, so it is checked too: the pinned commit must be on Mega EEST's default branch (a pin on +# the branch of a suite change still under review is a draft state, and the gate stays red until +# the pin moves to the merged commit), and a pull request that moves the pin lists the case ids +# removed, added and changed relative to its base's pin in the step summary, where any removal +# fails the gate unless scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES lists exactly the removed +# ids, a line the reviewer reads in the diff. # # A failing case pins a rule of the Satin specification. A pull request that changes that # behaviour on purpose, or the mega-evm API the adapter calls, changes Mega EEST first (the case or @@ -15,9 +25,10 @@ name: Mega EEST # # The `Mega EEST gate` job always runs and reports: it passes when the run passed, or when a pull # request changes documentation alone (scripts/pull_request_needs_ci.sh) and the run was skipped. -# It is the check a branch rule requires; a path filter on the pull request trigger would leave that -# check pending on every pull request it filters out. A push to satin always runs, and saves the -# build cache pull requests restore. +# It is the check a branch rule can require (it is required once an administrator adds it to the +# satin branch rule); a path filter on the pull request trigger would leave that check pending on +# every pull request it filters out. A push to satin always runs, and saves the build cache pull +# requests restore. # # Timing: on a 15-core laptop the whole run takes about a minute with a warm dependency cache (the # adapter build half a minute, each mode about fifteen seconds). On a GitHub runner, with four @@ -86,15 +97,33 @@ jobs: - uses: actions/checkout@v4 with: submodules: recursive + # On a pull request, the merge commit and its parents: the first parent is the base, whose + # pin the case set is compared with. + fetch-depth: 2 persist-credentials: false - - name: Read the pin + - name: Read the pin, and the base's id: pin + env: + EVENT: ${{ github.event_name }} run: | set -euo pipefail rev=$(sed -n 's/^MEGA_EEST_REV=\(.*\)$/\1/p' scripts/mega_eest.env) echo "Mega EEST at $rev" echo "rev=$rev" >> "$GITHUB_OUTPUT" + base="" + if [ "$EVENT" = pull_request ]; then + if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then + echo "::error::HEAD is not the pull request's merge commit, so the base's pin is unknown" + exit 1 + fi + # A base without the pin file (the pull request that adds the gate) has nothing to compare. + if git cat-file -e 'HEAD^1:scripts/mega_eest.env' 2> /dev/null; then + base=$(git show 'HEAD^1:scripts/mega_eest.env' | sed -n 's/^MEGA_EEST_REV=\(.*\)$/\1/p') + fi + fi + echo "the base's pin: ${base:-(none)}" + echo "base=$base" >> "$GITHUB_OUTPUT" # The job's cargo cache is the step below: setup-rust-toolchain's own cache handles the # workspace's target directory, and this job builds into another. @@ -124,25 +153,42 @@ jobs: - name: Run Mega EEST, the gate env: REV: ${{ steps.pin.outputs.rev }} + MEGA_EEST_BASE_REV: ${{ steps.pin.outputs.base }} run: | set -uo pipefail start=$SECONDS status=0 scripts/mega_eest.sh > summary.txt || status=$? cat summary.txt + line=$(grep '^MEGA-EEST ' summary.txt | tail -n 1 || true) { echo "### Mega EEST" echo - echo "Pin: \`$REV\`, in $((SECONDS - start)) s." + echo "Pin: \`$REV\`, in $((SECONDS - start)) s, exit $status." echo echo '```' - cat summary.txt + echo "$line" echo '```' + if [ -f target/mega-eest/case-diff.md ]; then + echo + cat target/mega-eest/case-diff.md + fi } >> "$GITHUB_STEP_SUMMARY" - if [ "$status" -ne 0 ]; then - echo "::error::Mega EEST failed on this tree; the failing cases are in the log above and in the uploaded reports" - fi - exit "$status" + case "$status" in + 0) ;; + 1) echo "::error::Mega EEST cases failed on this tree; the failing cases are in the log above and in the uploaded reports" ;; + 3) echo "::error::the cases passed, but the pin is refused: it is not on Mega EEST's default branch, or it removes cases scripts/mega_eest.env does not declare (see the log)" ;; + *) echo "::error::the Mega EEST run reached no verdict (exit $status): see the log for the step that failed" ;; + esac + [ "$status" -eq 0 ] || exit "$status" + # The gate is the full run, both modes, of a pin on the suite's default branch. + case "$line" in + "MEGA-EEST "*" run=full "*" provenance=default-branch "*" result=pass") echo "the gate passed" ;; + *) + echo "::error::the run passed, but its summary is not the gate's full run of a merged pin: $line" + exit 1 + ;; + esac - name: Upload the reports of a failing run if: failure() @@ -152,6 +198,7 @@ jobs: path: | target/mega-eest/*.json target/mega-eest/*.log + target/mega-eest/case-diff.md target/mega-eest/adapter-revm/Cargo.toml target/mega-eest/adapter-revm/Cargo.lock if-no-files-found: ignore diff --git a/crates/mega-evm/tests/mega_eest/main.rs b/crates/mega-evm/tests/mega_eest/main.rs index 4340d62d8..a75462e36 100644 --- a/crates/mega-evm/tests/mega_eest/main.rs +++ b/crates/mega-evm/tests/mega_eest/main.rs @@ -3,28 +3,48 @@ //! Mega EEST holds the state-transition cases both Satin implementations share, each pinned to //! rules of the Satin specification. `scripts/mega_eest.sh` takes the suite at the commit //! `scripts/mega_eest.env` pins, builds the suite's revm adapter against this checkout and consumes -//! every case, plain and instrumented; this test runs that script and fails when it fails. +//! every case, in the modes `MEGA_EEST_MODES` names (plain and instrumented by default); this test +//! runs that script and fails when it does not pass. //! //! It is ignored: it builds a second copy of mega-evm for the adapter and runs for a minute or -//! more, and CI runs the script itself as the Mega EEST gate. The mutation gate runs it, with -//! nextest's `--run-ignored only`, for each mutant the rest of the suite does not catch, so a -//! mutant that only a Mega EEST case catches counts as caught. +//! more, and CI runs the script itself as the Mega EEST gate. The mutation gate runs it in plain +//! mode alone (`MEGA_EEST_MODES=plain`, nextest's `--run-ignored only`) for each mutant the rest of +//! the suite does not catch. The script's summary line is printed and repeated in the failure +//! message, because the mutation gate counts a mutant as caught only when that line, in the +//! mutant's log, says the cases ran and failed (`result=FAIL`): a run that never reached the cases +//! (a build or fetch that failed, exit 2) fails this test too, and the gate refuses it as no +//! verdict rather than counting a kill. -use std::{path::Path, process::Command}; +use std::{ + path::Path, + process::{Command, Stdio}, +}; #[test] #[ignore = "runs the Mega EEST suite through scripts/mega_eest.sh, which takes minutes"] fn test_mega_eest_cases_pass_on_this_checkout() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let script = root.join("scripts/mega_eest.sh"); - let status = Command::new("bash") + let output = Command::new("bash") .arg(&script) .current_dir(&root) - .status() + .stderr(Stdio::inherit()) + .output() .unwrap_or_else(|err| panic!("cannot run {}: {err}", script.display())); - assert!( - status.success(), - "{} failed ({status}): the lines above name what failed", - script.display() - ); + let stdout = String::from_utf8_lossy(&output.stdout); + print!("{stdout}"); + let summary = stdout + .lines() + .filter(|line| line.starts_with("MEGA-EEST ")) + .last() + .unwrap_or("(no MEGA-EEST summary line)"); + match output.status.code() { + Some(0) => assert!( + summary.ends_with(" result=pass"), + "{} exited 0 without a passing summary: {summary}", + script.display() + ), + Some(1) => panic!("Mega EEST cases failed on this checkout: {summary}"), + _ => panic!("the Mega EEST run reached no verdict ({}): {summary}", output.status), + } } diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index 9c75a35e2..cfc385bb9 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -2,8 +2,15 @@ # .github/workflows/mega-eest.yml). Mega EEST is the conformance suite both Satin implementations # share; every case it holds at this commit must pass on this tree, plain and instrumented. # -# Moving the pin is the one-line change of MEGA_EEST_REV, to a full commit of the repository below, -# in the pull request that needs it: a change to mega-evm's API that the suite's revm adapter calls, -# or to behaviour a case pins, lands in Mega EEST first and is then pinned here. +# Moving the pin is the one-line change of MEGA_EEST_REV, to a full commit on the default branch of +# the repository below, in the pull request that needs it: a change to mega-evm's API that the +# suite's revm adapter calls, or to behaviour a case pins, lands in Mega EEST first and is then +# pinned here. A commit off the default branch (a suite change still under review) keeps the gate +# red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest MEGA_EEST_REV=5e4007b47ce62c2af2b7bf770677b0e6baf1a8d2 +# The case ids the pin's last move removed, space-separated, exactly: a pull request that moves the +# pin to a commit whose slice drops cases lists them here, or the gate fails; a move that removes +# none leaves it empty. Cases are mega-evm's tests of the behaviours they pin, so a removal is a +# change the reviewer reads in this file's diff. +MEGA_EEST_REMOVED_CASES= diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index cc6ed6081..475374cdc 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -28,14 +28,36 @@ version and from the same source, and there is exactly one revm. Packages only the adapter or the format crate links are listed when this checkout does not lock them. + executable --name + Read the JSON messages of `cargo build --message-format=json…` on standard input and print + the path of the one executable the build reported for that target, which must exist: the + file this build produced, wherever the target directory or the build target put it. + + case-diff --base-rev --rev --base-index --index + --declared --summary + Compare the case sets of two pins' slice indexes: the case ids removed, added and changed + (same id, another file digest) are listed on stderr and as Markdown in , and the word + printed on stdout says whether the removals are what scripts/mega_eest.env's + MEGA_EEST_REMOVED_CASES declares, exactly: `kept` (none removed, none declared), `declared` + (the removed ids and no other) or `undeclared` (anything else). + check --suite --work --modes <"plain instrumented"> --rev + [--provenance ] + [--caseset ] Read the run reports `mega-fixture consume` wrote into (.json, and - negative.json for the suite's deliberately wrong expectation) and decide the gate: in every - mode, the cases consumed are exactly the slice's index, by case id and file digest, and - every one passed; with both modes, every case's observations are the same bytes plain and - instrumented; and the wrong expectation fails at the path the index records. Prints the - failures (case id, first differing path, both values, the rules the case pins) and one - summary line, `MEGA-EEST ...`, and exits 1 when the gate fails. + negative.json for the suite's deliberately wrong expectation) and decide: in every mode, the + cases consumed are exactly the slice's index, by case id and file digest, and every one + passed; with both modes, every case's observations are the same bytes plain and + instrumented; and the wrong expectation, which the index must list, fails at the path it + records. Prints the failures (case id, first differing path, both values, the rules the + case pins) and one summary line, `MEGA-EEST … result=`, and exits with its code: + 0 pass; 1 FAIL, a verdict (complete reports of exactly the index in every mode, the wrong + expectation caught, and a case failed or erred, or the modes' observations differ); + 2 INCOMPLETE, no verdict (no mode, a report missing, cases that are not the index, a + consume exit its report does not explain, a case the adapter does not support, no wrong + expectation or one not caught, or the checker itself failing); 3 REFUSED, every case passed + but the pin's provenance is `unmerged` or its case set `undeclared`. `run=full` in the line + is both modes; `run=partial` one. """ from __future__ import annotations @@ -273,8 +295,11 @@ def cmd_adapter(args: argparse.Namespace) -> int: # Seed the lock from this checkout's, unless it was seeded from the same lock and manifest # before: cargo has resolved it since, and a fresh seed would only make it resolve again. + # The digest names the checkouts' paths by placeholders, so a copy of this tree (a mutation + # build directory, which carries the warm-up's resolved workspace) keeps the resolved lock. tree_lock = (tree / "Cargo.lock").read_bytes() - seed = hashlib.sha256(tree_lock + b"\0" + (header + text).encode()).hexdigest() + placed = text.replace(str(tree), "").replace(str(suite), "") + seed = hashlib.sha256(tree_lock + b"\0" + placed.encode()).hexdigest() marker = out / SEED_MARKER if not (out / "Cargo.lock").exists() or not marker.exists() or marker.read_text().strip() != seed: write_if_changed(out / "Cargo.lock", tree_lock) @@ -361,29 +386,49 @@ def canonical(value) -> str: return "(absent)" if value is None else json.dumps(value, sort_keys=True, separators=(",", ":")) +# The results of `check`, by the exit code each has. +RESULT_EXIT = {"pass": 0, "FAIL": 1, "INCOMPLETE": 2, "REFUSED": 3} + + def cmd_check(args: argparse.Namespace) -> int: + """`check`; no failure of the checker itself can read as a verdict.""" + try: + return check(args) + except Exception as err: # noqa: BLE001 - any error here is no verdict, never a pass or a FAIL + print(f"mega-eest: error: the checker could not read the run: {err!r}", file=sys.stderr) + print(f"MEGA-EEST rev={args.rev} run=unknown stage=check result=INCOMPLETE") + return RESULT_EXIT["INCOMPLETE"] + + +def check(args: argparse.Namespace) -> int: suite, work = Path(args.suite), Path(args.work) - modes = args.modes.split() + modes = list(dict.fromkeys(args.modes.split())) index = json.loads((suite / "slice" / "index.json").read_text()) expected = Counter((c["caseId"], c["fileDigest"]) for c in index["cases"]) total = sum(expected.values()) - failed = False - summary = [f"rev={args.rev}", f"cases={total}"] + run = "full" if {"plain", "instrumented"} <= set(modes) else "partial" + summary = [f"rev={args.rev}", f"run={run}", f"cases={total}"] + # Why the run reached no verdict; and whether a case failed in a run that did. + incomplete: list[str] = [] + cases_failed = False observations: dict[str, dict[str, str | None]] = {} + if not modes: + incomplete.append("no mode was run") + for mode in modes: + if mode not in ("plain", "instrumented"): + incomplete.append(f"no such mode as {mode!r}") if total == 0: - print("mega-eest: error: the slice's index lists no case", file=sys.stderr) - failed = True + incomplete.append("the slice's index lists no case") for mode in modes: report_path = work / f"{mode}.json" exit_path = work / f"{mode}.exit" code = exit_path.read_text().strip() if exit_path.exists() else "?" if not report_path.exists(): - print(f"mega-eest: error: {mode}: `mega-fixture consume` wrote no report (exit {code}); " - f"see {work / (mode + '.log')}", file=sys.stderr) + incomplete.append(f"{mode}: `mega-fixture consume` wrote no report (exit {code}); " + f"see {work / (mode + '.log')}") summary.append(f"{mode}=no-report") - failed = True continue cases = json.loads(report_path.read_text())["cases"] statuses = Counter(c["status"] for c in cases) @@ -405,13 +450,20 @@ def cmd_check(args: argparse.Namespace) -> int: print(f"mega-eest: {mode}: ... and {len(not_passed) - MAX_SHOWN} more, in {report_path}", file=sys.stderr) if missing or extra: - print(f"mega-eest: error: {mode}: the cases consumed are not the slice's index: " - f"{sum(missing.values())} missing, {sum(extra.values())} not in it" - + (f", {next(iter(missing))[0]} among the missing" if missing else "") - + (f", {next(iter(extra))[0]} among the others" if extra else ""), file=sys.stderr) - failed = True - if not_passed or code != "0": - failed = True + incomplete.append( + f"{mode}: the cases consumed are not the slice's index: " + f"{sum(missing.values())} missing, {sum(extra.values())} not in it" + + (f", {next(iter(missing))[0]} among the missing" if missing else "") + + (f", {next(iter(extra))[0]} among the others" if extra else "")) + # `consume` exits 0 when every case passed and 1 when one did not; any other exit, or one + # its report does not explain, is a run that did not finish as reported. + if code not in ("0", "1") or (code == "0") != (not not_passed): + incomplete.append(f"{mode}: `mega-fixture consume` exited {code} with " + f"{len(not_passed)} case(s) not passing in its report") + if statuses.get("unsupported"): + incomplete.append(f"{mode}: {statuses['unsupported']} case(s) the adapter does not support") + if statuses.get("fail") or statuses.get("error"): + cases_failed = True summary.append(f"{mode}=" + ",".join( f"{s}:{statuses.get(s, 0)}" for s in ("pass", "fail", "unsupported", "error"))) @@ -423,29 +475,106 @@ def cmd_check(args: argparse.Namespace) -> int: print(f"mega-eest: parity: {case}: plain {plain.get(case)} instrumented {inst.get(case)}", file=sys.stderr) summary.append(f"parity={'identical' if not differ else f'{len(differ)}-differ'}") - failed |= bool(differ) + cases_failed |= bool(differ) + # The wrong expectation is what shows the consumer and the adapter can fail at all: an index + # without one, or a run that did not fail it where recorded, says nothing about the cases. negative_path = work / "negative.json" wrong_at = {n["caseId"]: n["wrongAt"] for n in index.get("negative", [])} - if wrong_at: + if not wrong_at: + verdict = "none" + incomplete.append("the slice's index lists no wrong expectation, which shows the consumer can fail") + elif not negative_path.exists(): + verdict = "no-report" + incomplete.append("`mega-fixture consume` wrote no report of the wrong expectation") + else: verdict = "fail-as-recorded" - if not negative_path.exists(): - verdict = "no-report" - else: - cases = {c.get("caseId"): c for c in json.loads(negative_path.read_text())["cases"]} - for case_id, path in wrong_at.items(): - c = cases.get(case_id) - if not c or c["status"] != "fail" or c.get("path") != path: - print(f"mega-eest: error: the wrong expectation {case_id} did not fail at {path}: " - f"{c['status'] + ' at ' + str(c.get('path')) if c else 'not consumed'}", - file=sys.stderr) - verdict = "not-caught" - summary.append(f"negative={verdict}") - failed |= verdict != "fail-as-recorded" - - summary.append(f"result={'FAIL' if failed else 'pass'}") + cases = {c.get("caseId"): c for c in json.loads(negative_path.read_text())["cases"]} + for case_id, path in wrong_at.items(): + c = cases.get(case_id) + if not c or c["status"] != "fail" or c.get("path") != path: + incomplete.append(f"the wrong expectation {case_id} did not fail at {path}: " + f"{c['status'] + ' at ' + str(c.get('path')) if c else 'not consumed'}") + verdict = "not-caught" + summary.append(f"negative={verdict}") + summary.append(f"provenance={args.provenance}") + summary.append(f"caseset={args.caseset}") + + if incomplete: + result = "INCOMPLETE" + elif cases_failed: + result = "FAIL" + elif args.provenance == "unmerged" or args.caseset == "undeclared": + result = "REFUSED" + else: + result = "pass" + for reason in incomplete: + print(f"mega-eest: error: no verdict: {reason}", file=sys.stderr) + summary.append(f"result={result}") print("MEGA-EEST " + " ".join(summary)) - return 1 if failed else 0 + return RESULT_EXIT[result] + + +# ---- executable, case-diff -------------------------------------------------------------------- + + +def cmd_executable(args: argparse.Namespace) -> int: + found = set() + for line in sys.stdin: + line = line.strip() + if not line.startswith("{"): + continue + try: + message = json.loads(line) + except json.JSONDecodeError: + continue + if (message.get("reason") == "compiler-artifact" + and (message.get("target") or {}).get("name") == args.name + and message.get("executable")): + found.add(message["executable"]) + if len(found) != 1: + raise GateError(f"the build reported {len(found)} executables named {args.name}, not one: " + + (", ".join(sorted(found)) or "none")) + path = Path(next(iter(found))) + if not path.is_file(): + raise GateError(f"the build reported {path} for {args.name}, and there is no such file") + print(path) + return 0 + + +def cmd_case_diff(args: argparse.Namespace) -> int: + def cases(path: str) -> dict[str, str]: + return {c["caseId"]: c["fileDigest"] for c in json.loads(Path(path).read_text())["cases"]} + + base, head = cases(args.base_index), cases(args.index) + removed = sorted(base.keys() - head.keys()) + added = sorted(head.keys() - base.keys()) + changed = sorted(k for k in base.keys() & head.keys() if base[k] != head[k]) + declared = sorted(set(args.declared.split())) + if removed == declared: + caseset = "declared" if removed else "kept" + else: + caseset = "undeclared" + print(f"mega-eest: the pin moves {args.base_rev} -> {args.rev}: {len(removed)} case(s) removed, " + f"{len(added)} added, {len(changed)} changed", file=sys.stderr) + for title, ids in (("removed", removed), ("added", added), ("changed", changed)): + for case_id in ids: + print(f"mega-eest: {title} {case_id}", file=sys.stderr) + if caseset == "undeclared": + print("mega-eest: error: scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES must list exactly the " + "case ids the pin removes: removed and not declared: " + f"{' '.join(sorted(set(removed) - set(declared))) or '(none)'}; declared and not removed: " + f"{' '.join(sorted(set(declared) - set(removed))) or '(none)'}", file=sys.stderr) + md = [f"### Mega EEST case set, {args.base_rev[:12]} → {args.rev[:12]}", "", + f"{len(removed)} removed, {len(added)} added, {len(changed)} changed; removals: **{caseset}**.", ""] + for title, ids in (("Removed", removed), ("Added", added), ("Changed", changed)): + if ids: + md += [f"
{title} ({len(ids)})", ""] + md += [f"- `{case_id}`" for case_id in ids] + md += ["", "
", ""] + Path(args.summary).write_text("\n".join(md) + "\n") + print(caseset) + return 0 def main() -> int: @@ -470,8 +599,24 @@ def main() -> int: pc.add_argument("--work", required=True) pc.add_argument("--modes", required=True) pc.add_argument("--rev", required=True) + pc.add_argument("--provenance", default="unchecked", choices=["default-branch", "unmerged", "unchecked"]) + pc.add_argument("--caseset", default="unchecked", + choices=["unmoved", "kept", "declared", "undeclared", "unchecked"]) pc.set_defaults(func=cmd_check) + pe = sub.add_parser("executable", help="the executable a cargo build reported, from its JSON messages") + pe.add_argument("--name", required=True) + pe.set_defaults(func=cmd_executable) + + pd = sub.add_parser("case-diff", help="compare two pins' case sets") + pd.add_argument("--base-rev", required=True) + pd.add_argument("--rev", required=True) + pd.add_argument("--base-index", required=True) + pd.add_argument("--index", required=True) + pd.add_argument("--declared", default="") + pd.add_argument("--summary", required=True) + pd.set_defaults(func=cmd_case_diff) + args = p.parse_args() try: return args.func(args) diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index 45615157f..f7331f342 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -9,14 +9,23 @@ # The commit this tree gates on is scripts/mega_eest.env's MEGA_EEST_REV. The script: # # 1. Takes Mega EEST at that commit: the checkout $MEGA_EEST_DIR names, which must be at the pin -# with its cases, specs, adapters and format crate unmodified, or else a shallow fetch of the -# commit into $MEGA_EEST_WORK/src, reused while it is at the pin. -# 2. Builds the suite's `mega-fixture` CLI, and its revm adapter against this checkout: the adapter +# with its cases, specs, adapters and format crate as committed (no change, no untracked file, +# no file git is told to ignore changes to), or else a shallow fetch of the commit into +# $MEGA_EEST_WORK/src, reused while it is at the pin. +# 2. Checks the pin's provenance: the commit must be on Mega EEST's default branch (a blobless copy +# of its history in $MEGA_EEST_WORK/history.git). A commit that is not, such as the branch of a +# suite change still under review, is a draft state: the cases still run, and the script exits 3. +# 3. When MEGA_EEST_BASE_REV names another commit (a pull request's base pin), compares the two +# slices' case sets: the case ids removed, added and changed are listed (and written to +# $MEGA_EEST_WORK/case-diff.md), and removed ids must be exactly those scripts/mega_eest.env's +# MEGA_EEST_REMOVED_CASES declares, or the script exits 3. +# 4. Builds the suite's `mega-fixture` CLI, and its revm adapter against this checkout: the adapter # is written out as a workspace of its own ($MEGA_EEST_WORK/adapter-revm, by scripts/mega_eest.py) # whose mega-evm is a path dependency on crates/mega-evm here, whose other crates take their # sources from this tree's [workspace.dependencies], and whose [patch] and [profile] are this # tree's root manifest's, so a change that moves the revm or op-revm fork is tested with its own -# fork. +# fork. The executables run are the ones these builds report (cargo's JSON messages), never a +# path guessed from the target directory. # The lockfile: the adapter's own Cargo.lock was resolved for the mega-evm commit it pins and is # not used. The workspace's lock is seeded with this tree's Cargo.lock, cargo resolves it once # (pruning what the adapter does not link and adding what only the adapter needs), every package @@ -24,25 +33,47 @@ # build runs --locked on that lock. # Cargo runs from this checkout's root, so the toolchain is its rust-toolchain.toml and the # configuration its .cargo/config.toml. -# 3. Consumes every gating case (slice/cases) with `mega-fixture consume`, plain and then -# --instrumented, and the suite's deliberately wrong expectation (slice/negative). -# 4. Decides (scripts/mega_eest.py check): in each mode the cases consumed are exactly the slice's +# 5. Consumes every gating case (slice/cases) with `mega-fixture consume` in each mode of +# $MEGA_EEST_MODES, plain and --instrumented by default, and the suite's deliberately wrong +# expectation (slice/negative). +# 6. Decides (scripts/mega_eest.py check): in each mode the cases consumed are exactly the slice's # index and every one passed; plain and instrumented observations are the same bytes; the wrong -# expectation fails where the index says. A failure prints the case id, the first differing path -# and both values, and the rules the case pins. +# expectation, which the index must list, fails where the index says. A failure prints the case +# id, the first differing path and both values, and the rules the case pins. # -# It prints one summary line on stdout, `MEGA-EEST rev=... cases=... plain=pass:N,... result=pass`, -# everything else on stderr, and exits non-zero when anything above does not hold: a fetch of a -# commit that does not exist, an adapter that does not build against this tree (an API it calls -# changed), a case that does not pass. +# Everything goes to stderr but one line on stdout, the summary: +# +# MEGA-EEST rev= run= cases= =pass:,fail:,unsupported:,error: ... +# [parity=] negative=<...> provenance= +# caseset= result= +# +# `run=full` is both modes, which the gate requires; `run=partial` is one, which the mutation gate +# runs (plain). A run that stops before the reports are read prints +# `MEGA-EEST rev= run=<...> stage= result=INCOMPLETE` instead. +# +# Exit codes: +# 0 pass: every case passed in every mode run, the wrong expectation failed where recorded, and +# the pin's checks passed or were skipped (result=pass) +# 1 the cases failed: every mode ran to a complete report of exactly the slice's cases and the +# wrong expectation failed where recorded, and a case failed or erred, or plain and +# instrumented observations differ (result=FAIL). The only exit that is a verdict on this tree. +# 2 no verdict: anything that kept the run from one, a fetch, a build, the resolution, the lock +# check, a report missing or incomplete, cases that are not the index, a case the adapter does +# not support, a wrong expectation not caught, no mode (result=INCOMPLETE) +# 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, or it removes +# cases scripts/mega_eest.env does not declare (result=REFUSED) # # Environment: # MEGA_EEST_DIR a Mega EEST checkout at the pin to use instead of fetching one # MEGA_EEST_WORK where the checkout, the adapter workspace, logs and reports go # (default target/mega-eest) # MEGA_EEST_TARGET_DIR the cargo target directory of both builds (default $MEGA_EEST_WORK/target) -# MEGA_EEST_MODES the modes to consume in (default "plain instrumented") +# MEGA_EEST_MODES the modes to consume in (default "plain instrumented"); at least one # MEGA_EEST_JOBS cases run at once (default: the number of CPUs) +# MEGA_EEST_BASE_REV the pin to compare the case set with (CI: the pull request base's pin) +# MEGA_EEST_SKIP_PROVENANCE=1 +# skips step 2 (provenance=unchecked): for the mutation gate's runs, which +# its warm-up already checked, and the coverage report; never the gate # MEGA_EEST_ENGINE_RUSTFLAGS # compiler flags for this tree's packages and the adapter's own crate in # the adapter build, for a coverage build (scripts/coverage_mega_evm.sh): @@ -63,22 +94,50 @@ JOBS="${MEGA_EEST_JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || HELPER="$ROOT_DIR/scripts/mega_eest.py" log() { echo "mega-eest: $*" >&2; } +started=$SECONDS +elapsed() { echo "$((SECONDS - started))s"; } + +# Every way out before the verdict is exit 2 with an INCOMPLETE summary line, a `die` and an +# unexpected failure under `set -e` alike, so no failure of the run can read as exit 1, the verdict +# that cases failed. +REV="" +RUN="" +STAGE=setup +FINISHED=0 +# shellcheck disable=SC2329 # the EXIT trap below runs it +on_exit() { + local rc=$? + if [ "$FINISHED" != 1 ] && [ "$rc" -ne 0 ]; then + echo "MEGA-EEST rev=${REV:-unknown} run=${RUN:-unknown} stage=$STAGE result=INCOMPLETE" + exit 2 + fi +} +trap on_exit EXIT die() { echo "mega-eest: error: $*" >&2 - exit 1 + exit 2 } -started=$SECONDS -elapsed() { echo "$((SECONDS - started))s"; } python3 -c 'import sys; sys.exit(sys.version_info < (3, 11))' 2> /dev/null \ || die "needs Python 3.11 or newer as python3 (for tomllib); found $(python3 --version 2>&1 || echo none)" +# The modes, each once; at least one. Both are the gate's full run. +MODE_WORDS="" for mode in $MODES; do case "$mode" in plain | instrumented) ;; *) die "MEGA_EEST_MODES names '$mode'; the modes are plain and instrumented" ;; esac + case " $MODE_WORDS " in + *" $mode "*) ;; + *) MODE_WORDS="${MODE_WORDS:+$MODE_WORDS }$mode" ;; + esac done +[ -n "$MODE_WORDS" ] || die "MEGA_EEST_MODES ('$MODES') names no mode; the modes are plain and instrumented" +case " $MODE_WORDS " in + *" plain "*" instrumented "* | *" instrumented "*" plain "*) RUN=full ;; + *) RUN=partial ;; +esac # One `NAME=value` line of the pin file; anything else fails rather than running another commit. read_pin() { @@ -89,50 +148,146 @@ read_pin() { fi printf '%s' "$value" } +# At most one `NAME=value` line, whose value may be empty. +read_optional() { + local count + count=$(grep -c "^$1=" "$PIN_FILE" || true) + [ "$count" -le 1 ] || die "$PIN_FILE: more than one $1 line" + sed -n "s/^$1=\(.*\)$/\1/p" "$PIN_FILE" +} REPO=$(read_pin MEGA_EEST_REPO) REV=$(read_pin MEGA_EEST_REV) [[ "$REV" =~ ^[0-9a-f]{40}$ ]] || die "$PIN_FILE: MEGA_EEST_REV is '$REV', not a full commit hash" +DECLARED_REMOVALS=$(read_optional MEGA_EEST_REMOVED_CASES) # The paths of a checkout that decide what runs: a change to any of them is a different suite. SUITE_PATHS=(slice specs adapters crates Cargo.toml Cargo.lock) -# Whether the checkout $1 is the pinned commit with those paths as committed. Git takes no optional -# lock for it: several runs may read one checkout at once (the mutation gate's build directories). +# Whether the checkout $1 is the commit $2 with those paths as committed; PIN_PROBLEM says why not. +# Each git command's own status is checked, so a git that cannot read the checkout is no clean +# checkout; and a file marked skip-worktree or assume-unchanged, whose changes `git status` does +# not report, is refused. Git takes no optional lock: several runs may read one checkout at once +# (the mutation gate's build directories). export GIT_OPTIONAL_LOCKS=0 -at_pin() { - [ "$(git -C "$1" rev-parse HEAD 2> /dev/null)" = "$REV" ] \ - && [ -z "$(git -C "$1" status --porcelain --untracked-files=all -- "${SUITE_PATHS[@]}")" ] +PIN_PROBLEM="" +at_commit() { + local dir=$1 rev=$2 head status flags hidden + if ! head=$(git -C "$dir" rev-parse HEAD 2> /dev/null); then + PIN_PROBLEM="is no git checkout" + return 1 + fi + if [ "$head" != "$rev" ]; then + PIN_PROBLEM="is at $head" + return 1 + fi + if ! status=$(git -C "$dir" status --porcelain --untracked-files=all -- "${SUITE_PATHS[@]}"); then + PIN_PROBLEM="cannot be read by git status" + return 1 + fi + if [ -n "$status" ]; then + PIN_PROBLEM="changes the suite (${status%%$'\n'*})" + return 1 + fi + if ! flags=$(git -C "$dir" ls-files -v -- "${SUITE_PATHS[@]}"); then + PIN_PROBLEM="cannot be listed by git ls-files" + return 1 + fi + if [ -z "$flags" ]; then + PIN_PROBLEM="tracks none of the suite's files" + return 1 + fi + hidden=$(printf '%s\n' "$flags" | awk 'NF && substr($0, 1, 2) != "H " { print; exit }') + if [ -n "$hidden" ]; then + PIN_PROBLEM="marks a file skip-worktree or assume-unchanged, whose changes git status does not report ($hidden)" + return 1 + fi +} + +# A shallow fetch of commit $2 into a fresh checkout at $1. One retry: a fetch that fails twice is +# a network failure or a commit the repository does not have, and either stops the run. +fetch_commit() { + local dir=$1 rev=$2 + rm -rf "$dir" + mkdir -p "$dir" + git -C "$dir" init -q + git -C "$dir" remote add origin "$REPO" + if ! git -C "$dir" fetch -q --depth 1 origin "$rev"; then + log "the fetch failed; retrying once" + sleep 5 + git -C "$dir" fetch -q --depth 1 origin "$rev" \ + || die "cannot fetch $rev from $REPO: the repository has no such commit, or the network failed" + fi + git -C "$dir" -c advice.detachedHead=false checkout -q FETCH_HEAD + at_commit "$dir" "$rev" || die "the fetched checkout of $rev $PIN_PROBLEM" } mkdir -p "$WORK" +rm -f "$WORK/adapter.path" "$WORK/case-diff.md" +STAGE=fetch if [ -n "${MEGA_EEST_DIR:-}" ]; then SUITE="$(cd "$MEGA_EEST_DIR" && pwd)" - if ! at_pin "$SUITE"; then - head=$(git -C "$SUITE" rev-parse HEAD 2> /dev/null || echo "no commit") - die "MEGA_EEST_DIR=$SUITE is at $head, or changes the suite, and the pin is $REV:" \ - "check the pin out there, or move the pin in scripts/mega_eest.env" - fi + at_commit "$SUITE" "$REV" \ + || die "MEGA_EEST_DIR=$SUITE $PIN_PROBLEM, and the pin is $REV: check the pin out there," \ + "unchanged, or move the pin in scripts/mega_eest.env" log "Mega EEST at $REV in $SUITE" +elif [ -d "$WORK/src/.git" ] && at_commit "$WORK/src" "$REV"; then + SUITE="$WORK/src" + log "Mega EEST at $REV in $SUITE (reused)" else SUITE="$WORK/src" - if [ -d "$SUITE/.git" ] && at_pin "$SUITE"; then - log "Mega EEST at $REV in $SUITE (reused)" + log "fetching Mega EEST $REV from $REPO" + fetch_commit "$SUITE" "$REV" +fi + +# The pin's provenance: on Mega EEST's default branch, read from a blobless copy of its history. +PROVENANCE=unchecked +if [ "${MEGA_EEST_SKIP_PROVENANCE:-0}" = 1 ]; then + log "the pin's provenance is not checked (MEGA_EEST_SKIP_PROVENANCE=1)" +else + STAGE=provenance + history="$WORK/history.git" + if [ ! -d "$history" ] || [ "$(git -C "$history" config remote.origin.url 2> /dev/null)" != "$REPO" ]; then + rm -rf "$history" + git clone -q --bare --filter=blob:none "$REPO" "$history" \ + || die "cannot copy Mega EEST's history from $REPO to check the pin's provenance" + fi + if ! git -C "$history" fetch -q origin HEAD; then + log "the fetch of Mega EEST's default branch failed; retrying once" + sleep 5 + git -C "$history" fetch -q origin HEAD \ + || die "cannot fetch Mega EEST's default branch from $REPO to check the pin's provenance" + fi + if git -C "$history" merge-base --is-ancestor "$REV" FETCH_HEAD 2> /dev/null; then + PROVENANCE=default-branch + log "the pin is on Mega EEST's default branch" + else + PROVENANCE=unmerged + log "error: the pin $REV is not on Mega EEST's default branch ($(git -C "$history" rev-parse FETCH_HEAD))." \ + "A pin on a suite change still under review is a draft state: the cases run, the gate stays" \ + "red, and the pin moves to the merged commit before this change merges." + fi +fi + +# The case set against the base's pin, when one is given. +CASESET=unchecked +if [ -n "${MEGA_EEST_BASE_REV:-}" ]; then + STAGE=case-diff + BASE_REV=$MEGA_EEST_BASE_REV + [[ "$BASE_REV" =~ ^[0-9a-f]{40}$ ]] || die "MEGA_EEST_BASE_REV is '$BASE_REV', not a full commit hash" + if [ "$BASE_REV" = "$REV" ]; then + CASESET=unmoved + [ -z "$DECLARED_REMOVALS" ] \ + || log "warning: the pin did not move, and MEGA_EEST_REMOVED_CASES still declares removals; clear it" else - log "fetching Mega EEST $REV from $REPO" - rm -rf "$SUITE" - mkdir -p "$SUITE" - git -C "$SUITE" init -q - git -C "$SUITE" remote add origin "$REPO" - # One retry: a fetch that fails twice is a network failure or a commit the repository does - # not have, and either fails the gate. - if ! git -C "$SUITE" fetch -q --depth 1 origin "$REV"; then - log "the fetch failed; retrying once" - sleep 5 - git -C "$SUITE" fetch -q --depth 1 origin "$REV" \ - || die "cannot fetch $REV from $REPO: the repository has no such commit, or the network failed" + BASE="$WORK/base-src" + if ! { [ -d "$BASE/.git" ] && at_commit "$BASE" "$BASE_REV"; }; then + log "fetching the base's pin $BASE_REV" + fetch_commit "$BASE" "$BASE_REV" fi - git -C "$SUITE" -c advice.detachedHead=false checkout -q FETCH_HEAD - at_pin "$SUITE" || die "the fetched checkout is not at $REV" + CASESET=$(python3 "$HELPER" case-diff --base-rev "$BASE_REV" --rev "$REV" \ + --base-index "$BASE/slice/index.json" --index "$SUITE/slice/index.json" \ + --declared "$DECLARED_REMOVALS" --summary "$WORK/case-diff.md") \ + || die "cannot compare the case sets of $BASE_REV and $REV" fi fi @@ -140,12 +295,22 @@ fi # cargo its .cargo/config.toml, whichever manifest it builds. cd "$ROOT_DIR" +# The executable named $1 that the build with the arguments after it produced, from cargo's own +# report of its artifacts, so a stale file at another path is never what runs. +built_executable() { + local name=$1 messages + shift + messages=$(CARGO_TARGET_DIR="$TARGET" cargo build --locked --message-format=json-render-diagnostics "$@") \ + || return 1 + printf '%s\n' "$messages" | python3 "$HELPER" executable --name "$name" +} + +STAGE=cli-build log "building the mega-fixture CLI ($(elapsed))" -CARGO_TARGET_DIR="$TARGET" cargo build --locked --manifest-path "$SUITE/Cargo.toml" \ - -p mega-fixture-format --bin mega-fixture \ +CLI=$(built_executable mega-fixture --manifest-path "$SUITE/Cargo.toml" -p mega-fixture-format --bin mega-fixture) \ || die "the suite's mega-fixture CLI does not build" -CLI="$TARGET/debug/mega-fixture" +STAGE=adapter-resolve ADAPTER_DIR="$WORK/adapter-revm" python3 "$HELPER" adapter --tree "$ROOT_DIR" --suite "$SUITE" --out "$ADAPTER_DIR" \ --engine-rustflags "${MEGA_EEST_ENGINE_RUSTFLAGS:-}" \ @@ -153,19 +318,24 @@ python3 "$HELPER" adapter --tree "$ROOT_DIR" --suite "$SUITE" --out "$ADAPTER_DI log "resolving the adapter workspace on this tree's lock ($(elapsed))" cargo metadata --format-version 1 --manifest-path "$ADAPTER_DIR/Cargo.toml" > /dev/null \ || die "the adapter workspace does not resolve against this tree's manifests" -python3 "$HELPER" check-lock --tree "$ROOT_DIR" --adapter "$ADAPTER_DIR" +STAGE=lock-check +python3 "$HELPER" check-lock --tree "$ROOT_DIR" --adapter "$ADAPTER_DIR" \ + || die "the adapter workspace would not build mega-evm as this tree locks it" +STAGE=adapter-build log "building the revm adapter against this tree's mega-evm ($(elapsed))" -if ! CARGO_TARGET_DIR="$TARGET" cargo build --locked --manifest-path "$ADAPTER_DIR/Cargo.toml"; then +if ! ADAPTER=$(built_executable adapter-revm --manifest-path "$ADAPTER_DIR/Cargo.toml"); then die "the Mega EEST revm adapter at $REV does not build against this tree." \ "If this change alters the mega-evm API the adapter calls, change the adapter in Mega EEST" \ "first and move the pin in scripts/mega_eest.env to that commit (AGENTS.md, the Mega EEST gate)." fi -ADAPTER="$TARGET/debug/adapter-revm" +# The adapter this run built, for the coverage report to read. +printf '%s\n' "$ADAPTER" > "$WORK/adapter.path" "$ADAPTER" capabilities > "$WORK/capabilities.json" || die "the adapter does not report its capabilities" +STAGE=consume rm -f "$WORK"/plain.* "$WORK"/instrumented.* "$WORK"/negative.* -for mode in $MODES; do +for mode in $MODE_WORDS; do flag=() [ "$mode" = instrumented ] && flag=(--instrumented) log "consuming slice/cases, $mode, $JOBS at once ($(elapsed))" @@ -179,12 +349,24 @@ log "consuming slice/negative, the wrong expectation ($(elapsed))" "$CLI" consume --adapter "$ADAPTER" --specs "$SUITE/specs" --report "$WORK/negative.json" \ "$SUITE/slice/negative" > "$WORK/negative.log" || true +# The checker prints the summary line and exits with the code it names; anything else, a crash +# included, is no verdict. +STAGE=check status=0 -python3 "$HELPER" check --suite "$SUITE" --work "$WORK" --modes "$MODES" --rev "$REV" || status=$? +summary=$(python3 "$HELPER" check --suite "$SUITE" --work "$WORK" --modes "$MODE_WORDS" --rev "$REV" \ + --provenance "$PROVENANCE" --caseset "$CASESET") || status=$? log "done in $(elapsed); logs and reports in $WORK" -if [ "$status" -ne 0 ]; then - log "a case that fails pins behaviour of the Satin specification: fix the change, or, when it" \ +case "$status:$summary" in + "0:MEGA-EEST "*" result=pass" | "1:MEGA-EEST "*" result=FAIL" | "2:MEGA-EEST "*" result=INCOMPLETE" \ + | "3:MEGA-EEST "*" result=REFUSED") ;; + *) die "the checker exited $status with no summary line naming that result: '$summary'" ;; +esac +echo "$summary" +case "$status" in + 1) log "a case that fails pins behaviour of the Satin specification: fix the change, or, when it" \ "changes that behaviour on purpose, change the case in Mega EEST first and move the pin" \ - "(AGENTS.md, the Mega EEST gate)" -fi + "(AGENTS.md, the Mega EEST gate)" ;; + 3) log "the cases passed, but the pin is refused (provenance=$PROVENANCE caseset=$CASESET)" ;; +esac +FINISHED=1 exit "$status" diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 468401bf0..6a595bfbb 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -16,6 +16,7 @@ import io import json import shutil +import subprocess import sys import tempfile import tomllib @@ -259,12 +260,15 @@ def test_a_second_revm_fails(self) -> None: class Check(Case): - """The run reports decide the gate.""" + """The run reports decide the result, and its exit code says whether it is a verdict.""" CASES = [("satin/a", "sha256:1"), ("satin/b", "sha256:2")] + NEGATIVE = [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/x"}] def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | None = None, - exits: dict[str, int] | None = None) -> tuple[int, str, str]: + exits: dict[str, int] | None = None, *, modes: str | None = None, + index_negative: list[dict] | None = None, provenance: str = "unchecked", + caseset: str = "unchecked") -> tuple[int, str, str]: # A fresh pair for every call: a test may write several runs. run = Path(tempfile.mkdtemp(dir=self.tmp)) suite, work = run / "suite", run / "work" @@ -272,76 +276,456 @@ def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | No work.mkdir() (suite / "slice" / "index.json").write_text(json.dumps({ "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], - "negative": [{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}], + "negative": ([{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}] + if index_negative is None else index_negative), })) for mode, cases in reports.items(): if cases is not None: (work / f"{mode}.json").write_text(json.dumps({"cases": cases})) - (work / f"{mode}.exit").write_text(f"{(exits or {}).get(mode, 0)}\n") + default = 1 if cases and any(c["status"] != "pass" for c in cases) else 0 + (work / f"{mode}.exit").write_text(f"{(exits or {}).get(mode, default)}\n") if negative is not None: (work / "negative.json").write_text(json.dumps({"cases": negative})) return self.run_quietly(eest.cmd_check, Namespace( - suite=str(suite), work=str(work), modes=" ".join(reports), rev="f" * 40)) + suite=str(suite), work=str(work), modes=" ".join(reports) if modes is None else modes, + rev="f" * 40, provenance=provenance, caseset=caseset)) @staticmethod - def passed(case_id: str, digest: str, observations: str = "sha256:o") -> dict: - return {"caseId": case_id, "fileDigest": digest, "status": "pass", "observationsDigest": observations, - "file": f"{case_id}.json"} - - NEGATIVE = [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/x"}] + def case(case_id: str, digest: str, status: str = "pass", observations: str = "sha256:o") -> dict: + report = {"caseId": case_id, "fileDigest": digest, "status": status, + "observationsDigest": observations, "file": f"{case_id}.json"} + if status == "fail": + report.update(path="/expected/gasLedgers/state", expected="0x1", actual="0x2", rules=["R-1"]) + if status == "error": + report.update(message="the adapter panicked") + return report def all_passed(self) -> list[dict]: - return [self.passed(c, d) for c, d in self.CASES] + return [self.case(c, d) for c, d in self.CASES] + + def one_failing(self, status: str = "fail") -> list[dict]: + return [self.case("satin/a", "sha256:1"), self.case("satin/b", "sha256:2", status)] - def test_every_case_passing_in_both_modes_passes(self) -> None: + def test_every_case_passing_in_both_modes_is_a_full_pass(self) -> None: code, out, err = self.write({"plain": self.all_passed(), "instrumented": self.all_passed()}, self.NEGATIVE) self.assertEqual(code, 0, err) - self.assertEqual(out.strip(), f"MEGA-EEST rev={'f' * 40} cases=2 plain=pass:2,fail:0,unsupported:0,error:0 " - "instrumented=pass:2,fail:0,unsupported:0,error:0 parity=identical " - "negative=fail-as-recorded result=pass") - - def test_a_failing_case_is_named_with_its_difference(self) -> None: - failed = {"caseId": "satin/b", "fileDigest": "sha256:2", "status": "fail", "path": "/expected/gasLedgers/state", - "expected": "0x1", "actual": "0x2", "rules": ["R-1"], "file": "b.json"} - code, out, err = self.write({"plain": [self.passed("satin/a", "sha256:1"), failed]}, self.NEGATIVE) - self.assertEqual(code, 1) - self.assertIn("result=FAIL", out) + self.assertEqual(out.strip(), f"MEGA-EEST rev={'f' * 40} run=full cases=2 " + "plain=pass:2,fail:0,unsupported:0,error:0 instrumented=pass:2,fail:0,unsupported:0,error:0 " + "parity=identical negative=fail-as-recorded provenance=unchecked caseset=unchecked result=pass") + + def test_one_mode_is_a_partial_run(self) -> None: + code, out, err = self.write({"plain": self.all_passed()}, self.NEGATIVE) + self.assertEqual(code, 0, err) + self.assertIn(" run=partial ", out) + self.assertTrue(out.strip().endswith("result=pass")) + + def test_a_failing_or_erring_case_is_a_verdict(self) -> None: + for status in ("fail", "error"): + code, out, err = self.write({"plain": self.one_failing(status)}, self.NEGATIVE) + self.assertEqual(code, 1, (status, err)) + self.assertTrue(out.strip().endswith("result=FAIL"), out) + code, out, err = self.write({"plain": self.one_failing()}, self.NEGATIVE) self.assertIn("plain=pass:1,fail:1", out) - self.assertIn("fail satin/b\n first difference at /expected/gasLedgers/state: expected \"0x1\" actual \"0x2\"", err) + self.assertIn('fail satin/b\n first difference at /expected/gasLedgers/state: expected "0x1" actual "0x2"', err) self.assertIn("rules: R-1", err) - def test_cases_that_are_not_the_index_fail(self) -> None: - for cases in ([self.passed("satin/a", "sha256:1")], - [self.passed("satin/a", "sha256:1"), self.passed("satin/b", "sha256:other")], - []): + def test_observations_that_differ_between_modes_are_a_verdict(self) -> None: + other = [self.case("satin/a", "sha256:1"), self.case("satin/b", "sha256:2", observations="sha256:other")] + code, out, err = self.write({"plain": self.all_passed(), "instrumented": other}, self.NEGATIVE) + self.assertEqual(code, 1, err) + self.assertIn("parity=1-differ", out) + self.assertIn("result=FAIL", out) + + def assert_no_verdict(self, code: int, out: str, err: str, reason: str) -> None: + self.assertEqual(code, 2, (out, err)) + self.assertTrue(out.strip().endswith("result=INCOMPLETE"), out) + self.assertIn(reason, err) + + def test_no_mode_is_no_verdict(self) -> None: + for modes in ("", " ", " \t\n"): + code, out, err = self.write({}, self.NEGATIVE, modes=modes) + self.assert_no_verdict(code, out, err, "no mode was run") + + def test_cases_that_are_not_the_index_are_no_verdict(self) -> None: + for cases in ([self.case("satin/a", "sha256:1")], + [self.case("satin/a", "sha256:1"), self.case("satin/b", "sha256:other")], + [], + # A failing case does not make an incomplete run a verdict. + [self.case("satin/a", "sha256:1", "fail")]): code, out, err = self.write({"plain": cases}, self.NEGATIVE) - self.assertEqual(code, 1, cases) - self.assertIn("the cases consumed are not the slice's index", err) + self.assert_no_verdict(code, out, err, "the cases consumed are not the slice's index") - def test_a_mode_without_a_report_fails(self) -> None: - code, out, err = self.write({"plain": self.all_passed(), "instrumented": None}, self.NEGATIVE, + def test_a_mode_without_a_report_is_no_verdict(self) -> None: + code, out, err = self.write({"plain": self.one_failing(), "instrumented": None}, self.NEGATIVE, exits={"instrumented": 2}) - self.assertEqual(code, 1) + self.assert_no_verdict(code, out, err, "wrote no report (exit 2)") self.assertIn("instrumented=no-report", out) - self.assertIn("wrote no report (exit 2)", err) - def test_observations_that_differ_between_modes_fail(self) -> None: - other = [self.passed("satin/a", "sha256:1"), self.passed("satin/b", "sha256:2", "sha256:other")] - code, out, err = self.write({"plain": self.all_passed(), "instrumented": other}, self.NEGATIVE) + def test_a_consume_exit_its_report_does_not_explain_is_no_verdict(self) -> None: + for cases, exit_code in ((self.all_passed(), 1), (self.one_failing(), 0), (self.one_failing(), 101)): + code, out, err = self.write({"plain": cases}, self.NEGATIVE, exits={"plain": exit_code}) + self.assert_no_verdict(code, out, err, f"exited {exit_code}") + + def test_an_unsupported_case_is_no_verdict(self) -> None: + code, out, err = self.write({"plain": self.one_failing("unsupported")}, self.NEGATIVE) + self.assert_no_verdict(code, out, err, "the adapter does not support") + + def test_a_wrong_expectation_missing_or_not_caught_is_no_verdict(self) -> None: + for negative, reason in ( + (None, "no report of the wrong expectation"), + ([{"caseId": "satin/negative/wrong", "status": "pass"}], "did not fail at /expected/x"), + ([{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/y"}], "did not fail"), + ): + code, out, err = self.write({"plain": self.one_failing()}, negative) + self.assert_no_verdict(code, out, err, reason) + for index_negative in ([], None): + run = self.write({"plain": self.all_passed()}, self.NEGATIVE, index_negative=index_negative) \ + if index_negative is not None else None + if run: + self.assert_no_verdict(*run, "lists no wrong expectation") + self.assertIn("negative=none", run[1]) + + def test_a_refused_pin_exits_3_and_failing_cases_still_exit_1(self) -> None: + for provenance, caseset in (("unmerged", "unmoved"), ("default-branch", "undeclared")): + code, out, err = self.write({"plain": self.all_passed()}, self.NEGATIVE, + provenance=provenance, caseset=caseset) + self.assertEqual(code, 3, err) + self.assertIn(f"provenance={provenance} caseset={caseset} result=REFUSED", out) + code, out, _ = self.write({"plain": self.one_failing()}, self.NEGATIVE, provenance="unmerged") self.assertEqual(code, 1) - self.assertIn("parity=1-differ", out) + for caseset in ("unmoved", "kept", "declared"): + code, out, err = self.write({"plain": self.all_passed()}, self.NEGATIVE, + provenance="default-branch", caseset=caseset) + self.assertEqual(code, 0, err) - def test_a_wrong_expectation_that_is_not_caught_fails(self) -> None: - for negative in (None, [{"caseId": "satin/negative/wrong", "status": "pass"}], - [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/y"}]): - code, out, err = self.write({"plain": self.all_passed()}, negative) - self.assertEqual(code, 1, negative) - self.assertNotIn("negative=fail-as-recorded", out) + def test_a_checker_that_cannot_read_the_run_is_no_verdict(self) -> None: + run = Path(tempfile.mkdtemp(dir=self.tmp)) + (run / "suite" / "slice").mkdir(parents=True) + (run / "work").mkdir() + (run / "suite" / "slice" / "index.json").write_text("{ not json") + code, out, err = self.run_quietly(eest.cmd_check, Namespace( + suite=str(run / "suite"), work=str(run / "work"), modes="plain", rev="f" * 40, + provenance="unchecked", caseset="unchecked")) + self.assertEqual(code, 2, err) + self.assertTrue(out.strip().endswith("stage=check result=INCOMPLETE"), out) - def test_a_nonzero_consume_exit_fails_even_when_every_case_passed(self) -> None: - code, out, _ = self.write({"plain": self.all_passed()}, self.NEGATIVE, exits={"plain": 1}) - self.assertEqual(code, 1) - self.assertIn("result=FAIL", out) + +class Executable(Case): + """The executable is the one cargo reported building, not a file at a guessed path.""" + + @staticmethod + def artifact(name: str, path: Path | None) -> str: + return json.dumps({"reason": "compiler-artifact", "target": {"name": name}, + "executable": str(path) if path else None}) + + def run_with(self, *lines: str) -> tuple[int, str, str]: + stdin = io.StringIO("\n".join(lines) + "\n") + old, sys.stdin = sys.stdin, stdin + try: + return self.run_quietly(eest.cmd_executable, Namespace(name="adapter-revm")) + finally: + sys.stdin = old + + def test_the_reported_executable_wins_over_a_stale_file(self) -> None: + stale = self.tmp / "target" / "debug" / "adapter-revm" + built = self.tmp / "target" / "aarch64-apple-darwin" / "debug" / "adapter-revm" + for path in (stale, built): + path.parent.mkdir(parents=True) + path.write_text("#!/bin/sh\n") + code, out, err = self.run_with("Compiling noise", self.artifact("mega-evm", None), + self.artifact("adapter-revm", built), + json.dumps({"reason": "build-finished", "success": True})) + self.assertEqual(code, 0, err) + self.assertEqual(out.strip(), str(built)) + + def test_no_executable_two_executables_or_a_missing_file_are_refused(self) -> None: + a, b = self.tmp / "a" / "adapter-revm", self.tmp / "b" / "adapter-revm" + for path in (a, b): + path.parent.mkdir(parents=True) + path.write_text("") + for lines, reason in ( + ([json.dumps({"reason": "build-finished", "success": True})], "0 executables"), + ([self.artifact("adapter-revm", a), self.artifact("adapter-revm", b)], "2 executables"), + ([self.artifact("adapter-revm", self.tmp / "gone" / "adapter-revm")], "no such file"), + ): + code, _, err = self.run_with(*lines) + self.assertEqual(code, 1, lines) + self.assertIn(reason, err) + + +class CaseDiff(Case): + """A pin move lists the case set's changes, and removals must be declared exactly.""" + + BASE = {"satin/a": "sha256:1", "satin/b": "sha256:2", "satin/c": "sha256:3"} + + def diff(self, head: dict[str, str], declared: str = "") -> tuple[int, str, str, str]: + run = Path(tempfile.mkdtemp(dir=self.tmp)) + for name, cases in (("base.json", self.BASE), ("head.json", head)): + (run / name).write_text(json.dumps({"cases": [{"caseId": c, "fileDigest": d} + for c, d in cases.items()]})) + code, out, err = self.run_quietly(eest.cmd_case_diff, Namespace( + base_rev="a" * 40, rev="b" * 40, base_index=str(run / "base.json"), + index=str(run / "head.json"), declared=declared, summary=str(run / "diff.md"))) + return code, out.strip(), err, (run / "diff.md").read_text() + + def test_a_move_that_keeps_every_case_is_kept(self) -> None: + code, out, err, md = self.diff({**self.BASE, "satin/d": "sha256:4", "satin/a": "sha256:9"}) + self.assertEqual((code, out), (0, "kept"), err) + self.assertIn("0 case(s) removed, 1 added, 1 changed", err) + self.assertIn("added satin/d", err) + self.assertIn("changed satin/a", err) + self.assertIn("- `satin/d`", md) + + def test_removals_must_be_declared_exactly(self) -> None: + head = {"satin/a": "sha256:1", "satin/b": "sha256:2"} + self.assertEqual(self.diff(head, "satin/c")[1], "declared") + for declared in ("", "satin/c satin/b", "satin/x"): + code, out, err, md = self.diff(head, declared) + self.assertEqual((code, out), (0, "undeclared"), declared) + self.assertIn("must list exactly the case ids the pin removes", err) + self.assertIn("removals: **undeclared**", md) + # A declaration left over from an earlier move, with nothing removed now. + self.assertEqual(self.diff(dict(self.BASE), "satin/c")[1], "undeclared") + + +# ---- the script itself, on a stand-in suite ---------------------------------------------------- + +# A stand-in for cargo: `metadata` succeeds, and `build` writes the stand-in implementation of the +# binary the manifest builds where cargo would (under $CARGO_BUILD_TARGET when it is set) and +# reports it as cargo does. FAKE_FAIL names a step that fails: metadata, mega-fixture or +# adapter-revm. +FAKE_CARGO = """#!/bin/sh +cmd=$1 +shift +case "$cmd" in + metadata) [ "${FAKE_FAIL:-}" = metadata ] && exit 101; exit 0 ;; + build) ;; + *) exit 99 ;; +esac +manifest="" +while [ $# -gt 0 ]; do + case "$1" in --manifest-path) manifest=$2; shift ;; esac + shift +done +case "$manifest" in + */adapter-revm/Cargo.toml) name=adapter-revm ;; + *) name=mega-fixture ;; +esac +if [ "${FAKE_FAIL:-}" = "$name" ]; then echo "error: could not compile $name" >&2; exit 101; fi +dir="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}debug" +mkdir -p "$dir" +cp "$FAKE_IMPL/$name" "$dir/$name" +chmod +x "$dir/$name" +echo '{"reason":"compiler-artifact","target":{"name":"'"$name"'"},"executable":"'"$dir/$name"'"}' +echo '{"reason":"build-finished","success":true}' +""" + +# The adapter a build of this tree produces: it says the cases fail when FAKE_VERDICT is fail. +FAKE_ADAPTER = """#!/bin/sh +case "$1" in + capabilities) echo '{"adapter":"fresh"}' ;; + verdict) echo "${FAKE_VERDICT:-pass}" ;; +esac +""" + +# An adapter an earlier run left behind, which passes everything. +STALE_ADAPTER = """#!/bin/sh +case "$1" in + capabilities) echo '{"adapter":"stale"}' ;; + verdict) echo pass ;; +esac +""" + +# The consumer: every case of the index passes, or fails when the adapter says so; the wrong +# expectation fails where the index records it. +FAKE_CLI = """#!/usr/bin/env python3 +import json, subprocess, sys +from pathlib import Path +args = sys.argv[1:] +assert args[0] == "consume" +adapter, report, path = args[args.index("--adapter") + 1], args[args.index("--report") + 1], Path(args[-1]) +index = json.loads((path.parent / "index.json").read_text()) +if path.name == "negative": + cases = [{"caseId": n["caseId"], "fileDigest": "sha256:n", "status": "fail", "path": n["wrongAt"]} + for n in index["negative"]] +else: + failing = subprocess.run([adapter, "verdict"], capture_output=True, text=True).stdout.strip() == "fail" + cases = [{"caseId": c["caseId"], "fileDigest": c["fileDigest"], "observationsDigest": "sha256:o", + "status": "fail" if failing else "pass", "path": "/expected/x", "expected": 1, "actual": 2, + "rules": ["R-1"]} for c in index["cases"]] +Path(report).write_text(json.dumps({"cases": cases})) +passed = sum(c["status"] == "pass" for c in cases) +print(f"CONSUME adapter=fake cases={len(cases)} pass={passed} fail={len(cases) - passed} unsupported=0 error=0") +sys.exit(0 if passed == len(cases) else 1) +""" + + +class Script(Case): + """scripts/mega_eest.sh on a stand-in suite: its exit code and summary line for each way a run + ends, under the system's bash (3.2 on macOS).""" + + def setUp(self) -> None: + super().setUp() + self.git_env = {"HOME": str(self.tmp), "GIT_CONFIG_NOSYSTEM": "1", "GIT_AUTHOR_NAME": "t", + "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.com", "PATH": "/usr/bin:/bin"} + # The tree: the two scripts, a pin file, and the manifests and lock the adapter needs. + self.tree = self.tmp / "tree" + (self.tree / "scripts").mkdir(parents=True) + for name in ("mega_eest.sh", "mega_eest.py"): + shutil.copy(SCRIPTS / name, self.tree / "scripts" / name) + (self.tree / "crates" / "mega-evm").mkdir(parents=True) + (self.tree / "Cargo.toml").write_text(ROOT_MANIFEST) + (self.tree / "crates" / "mega-evm" / "Cargo.toml").write_text('[package]\nname = "mega-evm"\n') + (self.tree / "Cargo.lock").write_text(lock( + {"name": "mega-evm", "version": "2.0.0", "dependencies": ["revm"]}, + {"name": "revm", "version": "40.0.3", "source": FORK})) + # The suite: a git repository whose default branch is main. + self.suite = self.tmp / "suite" + self.git("init", "-q", "-b", "main", str(self.suite)) + adapter = self.suite / "adapters" / "revm" + (adapter / "src").mkdir(parents=True) + (adapter / "Cargo.toml").write_text(ADAPTER_MANIFEST) + (adapter / "src" / "main.rs").write_text("fn main() {}\n") + (self.suite / "crates" / "mega-fixture-format").mkdir(parents=True) + (self.suite / "crates" / "mega-fixture-format" / "Cargo.toml").write_text("[package]\n") + (self.suite / "specs").mkdir() + (self.suite / "specs" / "satin.json").write_text("{}\n") + (self.suite / "Cargo.toml").write_text("[workspace]\n") + (self.suite / "Cargo.lock").write_text("version = 4\n") + self.rev = self.commit_cases(["satin/a", "satin/b", "satin/c"]) + # The stand-ins. + self.bin = self.tmp / "bin" + self.bin.mkdir() + (self.bin / "python3").symlink_to(sys.executable) + impl = self.tmp / "impl" + impl.mkdir() + for path, text in ((self.bin / "cargo", FAKE_CARGO), (impl / "adapter-revm", FAKE_ADAPTER), + (impl / "mega-fixture", FAKE_CLI)): + path.write_text(text) + path.chmod(0o755) + self.impl = impl + + def git(self, *args: str, cwd: Path | None = None) -> str: + return subprocess.run(["git", *args], cwd=cwd, env=self.git_env, check=True, + capture_output=True, text=True).stdout.strip() + + def commit_cases(self, ids: list[str], branch: str | None = None) -> str: + """Commit a slice holding `ids` (on `branch`, a new branch off the current commit, when + given) and return the commit; main stays checked out.""" + if branch: + self.git("checkout", "-q", "-b", branch, cwd=self.suite) + slice_dir = self.suite / "slice" + shutil.rmtree(slice_dir, ignore_errors=True) + (slice_dir / "cases").mkdir(parents=True) + (slice_dir / "negative").mkdir() + for case_id in ids: + (slice_dir / "cases" / f"{case_id.split('/')[-1]}.json").write_text("{}\n") + (slice_dir / "negative" / "wrong.json").write_text("{}\n") + (slice_dir / "index.json").write_text(json.dumps({ + "cases": [{"caseId": c, "fileDigest": f"sha256:{c}"} for c in ids], + "negative": [{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}]})) + self.git("add", "-A", cwd=self.suite) + self.git("commit", "-q", "-m", "cases", cwd=self.suite) + rev = self.git("rev-parse", "HEAD", cwd=self.suite) + if branch: + self.git("checkout", "-q", "main", cwd=self.suite) + return rev + + def run_script(self, rev: str | None = None, declared: str | None = None, + **env: str) -> tuple[int, str, str]: + pin = [f"MEGA_EEST_REPO=file://{self.suite}", f"MEGA_EEST_REV={rev or self.rev}"] + if declared is not None: + pin.append(f"MEGA_EEST_REMOVED_CASES={declared}") + (self.tree / "scripts" / "mega_eest.env").write_text("\n".join(pin) + "\n") + run = subprocess.run( + ["bash", str(self.tree / "scripts" / "mega_eest.sh")], capture_output=True, text=True, timeout=120, + env={**self.git_env, "PATH": f"{self.bin}:/usr/bin:/bin", "FAKE_IMPL": str(self.impl), + "MEGA_EEST_JOBS": "1", **env}) + return run.returncode, run.stdout, run.stderr + + def summary(self, out: str) -> str: + lines = [line for line in out.splitlines() if line.startswith("MEGA-EEST ")] + self.assertEqual(len(lines), 1, out) + return lines[0] + + def test_a_full_run_that_passes_exits_0(self) -> None: + code, out, err = self.run_script() + self.assertEqual(code, 0, err) + line = self.summary(out) + self.assertRegex(line, r"^MEGA-EEST rev=[0-9a-f]{40} run=full cases=3 plain=pass:3,.* " + r"instrumented=pass:3,.* provenance=default-branch caseset=unchecked result=pass$") + self.assertEqual(json.loads((self.tree / "target/mega-eest/capabilities.json").read_text()), + {"adapter": "fresh"}) + + def test_failing_cases_are_the_only_exit_1(self) -> None: + code, out, err = self.run_script(FAKE_VERDICT="fail", MEGA_EEST_MODES="plain") + self.assertEqual(code, 1, err) + self.assertRegex(self.summary(out), r" run=partial cases=3 plain=pass:0,fail:3,.* result=FAIL$") + + def test_a_step_that_fails_before_the_verdict_exits_2(self) -> None: + for fail, stage in (("mega-fixture", "cli-build"), ("metadata", "adapter-resolve"), + ("adapter-revm", "adapter-build")): + # Whatever the cases would have done. + code, out, err = self.run_script(FAKE_FAIL=fail, FAKE_VERDICT="fail") + self.assertEqual(code, 2, (fail, err)) + self.assertRegex(self.summary(out), rf" stage={stage} result=INCOMPLETE$") + + def test_a_stale_binary_is_never_run(self) -> None: + # An earlier run left a passing adapter where a default build puts it; this build goes + # under a build target, and its adapter fails the cases. + self.assertEqual(self.run_script()[0], 0) + stale = self.tree / "target/mega-eest/target/debug/adapter-revm" + stale.write_text(STALE_ADAPTER) + code, out, err = self.run_script(CARGO_BUILD_TARGET="aarch64-apple-darwin", FAKE_VERDICT="fail") + self.assertEqual(code, 1, err) + self.assertIn("result=FAIL", self.summary(out)) + built = self.tree / "target/mega-eest/target/aarch64-apple-darwin/debug/adapter-revm" + self.assertEqual((self.tree / "target/mega-eest/adapter.path").read_text().strip(), str(built)) + + def test_no_mode_exits_2(self) -> None: + for modes in (" ", "\t\n"): + code, out, err = self.run_script(MEGA_EEST_MODES=modes) + self.assertEqual(code, 2, err) + self.assertIn("names no mode", err) + self.assertIn("result=INCOMPLETE", self.summary(out)) + + def test_a_checkout_with_hidden_changes_is_refused(self) -> None: + for flag in ("--skip-worktree", "--assume-unchanged"): + self.git("update-index", flag, "slice/index.json", cwd=self.suite) + code, out, err = self.run_script(MEGA_EEST_DIR=str(self.suite), MEGA_EEST_SKIP_PROVENANCE="1") + self.assertEqual(code, 2, err) + self.assertIn("skip-worktree or assume-unchanged", err) + self.assertIn("stage=fetch result=INCOMPLETE", self.summary(out)) + self.git("update-index", flag.replace("--", "--no-"), "slice/index.json", cwd=self.suite) + self.assertEqual(self.run_script(MEGA_EEST_DIR=str(self.suite))[0], 0) + + def test_a_pin_off_the_default_branch_is_refused(self) -> None: + draft = self.commit_cases(["satin/a", "satin/b", "satin/c", "satin/d"], branch="draft") + code, out, err = self.run_script(rev=draft) + self.assertEqual(code, 3, err) + self.assertIn("draft state", err) + self.assertRegex(self.summary(out), r" cases=4 .* provenance=unmerged caseset=unchecked result=REFUSED$") + # Once merged, the same pin passes. + self.git("merge", "-q", "--ff-only", "draft", cwd=self.suite) + code, out, err = self.run_script(rev=draft) + self.assertEqual(code, 0, err) + self.assertIn("provenance=default-branch", self.summary(out)) + + def test_a_pin_move_must_declare_the_cases_it_removes(self) -> None: + base = self.rev + head = self.commit_cases(["satin/a", "satin/b", "satin/e"]) + code, out, err = self.run_script(rev=head, MEGA_EEST_BASE_REV=base) + self.assertEqual(code, 3, err) + self.assertIn("removed and not declared: satin/c", err) + self.assertIn("caseset=undeclared result=REFUSED", self.summary(out)) + self.assertIn("- `satin/c`", (self.tree / "target/mega-eest/case-diff.md").read_text()) + code, out, err = self.run_script(rev=head, declared="satin/c", MEGA_EEST_BASE_REV=base) + self.assertEqual(code, 0, err) + self.assertIn("caseset=declared result=pass", self.summary(out)) + code, out, err = self.run_script(rev=head, MEGA_EEST_BASE_REV=head) + self.assertEqual(code, 0, err) + self.assertIn("caseset=unmoved", self.summary(out)) if __name__ == "__main__": From 1e805c9bd14c33e3adaabcbe6a21768c78045e17 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:00:38 +0800 Subject: [PATCH 109/190] ci: require the Mega EEST run's coverage profiles, and pin cargo-llvm-cov --- .github/workflows/coverage.yml | 6 +++++- scripts/coverage_mega_evm.sh | 18 ++++++++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 0b8bb2215..7b7ad65d8 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -41,7 +41,11 @@ jobs: uses: foundry-rs/foundry-toolchain@v1 - name: Install cargo-llvm-cov - uses: taiki-e/install-action@cargo-llvm-cov + uses: taiki-e/install-action@v2 + with: + # Pin the version: scripts/coverage_mega_evm.sh places the Mega EEST adapter where this + # release's report finds executables, and checks it did; a new release can change both. + tool: cargo-llvm-cov@0.8.7 # The report merges the tests' coverage with the Mega EEST cases', so a line only a Mega EEST # case runs counts as covered. diff --git a/scripts/coverage_mega_evm.sh b/scripts/coverage_mega_evm.sh index 996b40d74..5cbc1d104 100755 --- a/scripts/coverage_mega_evm.sh +++ b/scripts/coverage_mega_evm.sh @@ -35,9 +35,11 @@ cargo llvm-cov \ # a Mega EEST case runs counts as covered. The adapter's and the suite's own sources are left out of # the report. The adapter's profiles go where cargo-llvm-cov merges the tests' (the target directory # of the run above), merged online into one file per pool slot, as the suite runs one adapter -# process per case. The report reads only the executables of this workspace's targets, which the -# adapter is not, so a copy of it is placed among them under the library's name; the lcov report's -# own command line is then checked to have read it. +# process per case; the run must leave a non-empty profile, or the suite contributed nothing. The +# report reads only the executables of this workspace's targets, which the adapter is not, so a +# copy of the adapter this run built (the path the script records) is placed among them under the +# library's name; the lcov report's own command line is then checked to have read it. The pin's +# provenance is the gate's to check, not this report's. # COVERAGE_MEGA_EEST=0 leaves the suite out, for a quicker local report of the tests alone. ADAPTER_OBJECT="" if [ "${COVERAGE_MEGA_EEST:-1}" != 0 ]; then @@ -45,15 +47,23 @@ if [ "${COVERAGE_MEGA_EEST:-1}" != 0 ]; then | python3 -c 'import json, sys; print(json.load(sys.stdin)["target_directory"])')/llvm-cov-target}" EEST_WORK="$ROOT_DIR/target/mega-eest-coverage" IGNORE_FILENAME_REGEX="$IGNORE_FILENAME_REGEX|^$(python3 -c 'import re, sys; print(re.escape(sys.argv[1]))' "$EEST_WORK")/" + rm -f "$LLVM_COV_TARGET"/mega-eest-*.profraw # Line tables are debug info enough for a panic's backtrace; the report reads the coverage # mapping, not the debug info. CARGO_PROFILE_DEV_DEBUG=line-tables-only \ LLVM_PROFILE_FILE="$LLVM_COV_TARGET/mega-eest-%15m.profraw" \ MEGA_EEST_WORK="$EEST_WORK" \ + MEGA_EEST_SKIP_PROVENANCE=1 \ MEGA_EEST_ENGINE_RUSTFLAGS="-Cinstrument-coverage -Zcoverage-options=branch --cfg=coverage --cfg=coverage_nightly" \ "$ROOT_DIR/scripts/mega_eest.sh" + profiles=$(find "$LLVM_COV_TARGET" -maxdepth 1 -name 'mega-eest-*.profraw' -size +0c | wc -l) + if [ "$profiles" -eq 0 ]; then + echo "the Mega EEST run left no coverage profile in $LLVM_COV_TARGET: the adapter it ran was" \ + "not instrumented, or its profiles went elsewhere, and the report would leave the suite out" >&2 + exit 1 + fi ADAPTER_OBJECT="mega_evm-00000000ee57ada7" - cp "$EEST_WORK/target/debug/adapter-revm" "$LLVM_COV_TARGET/debug/deps/$ADAPTER_OBJECT" + cp "$(cat "$EEST_WORK/adapter.path")" "$LLVM_COV_TARGET/debug/deps/$ADAPTER_OBJECT" fi status=0 From 1e70a96fa20d93e80b82dca9d777c82adc96bfc9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:03:00 +0800 Subject: [PATCH 110/190] test(ci): a Mega EEST checkout git cannot read is refused --- scripts/test_mega_eest.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 6a595bfbb..5fd0419b8 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -378,12 +378,9 @@ def test_a_wrong_expectation_missing_or_not_caught_is_no_verdict(self) -> None: ): code, out, err = self.write({"plain": self.one_failing()}, negative) self.assert_no_verdict(code, out, err, reason) - for index_negative in ([], None): - run = self.write({"plain": self.all_passed()}, self.NEGATIVE, index_negative=index_negative) \ - if index_negative is not None else None - if run: - self.assert_no_verdict(*run, "lists no wrong expectation") - self.assertIn("negative=none", run[1]) + run = self.write({"plain": self.all_passed()}, self.NEGATIVE, index_negative=[]) + self.assert_no_verdict(*run, "lists no wrong expectation") + self.assertIn("negative=none", run[1]) def test_a_refused_pin_exits_3_and_failing_cases_still_exit_1(self) -> None: for provenance, caseset in (("unmerged", "unmoved"), ("default-branch", "undeclared")): @@ -700,6 +697,14 @@ def test_a_checkout_with_hidden_changes_is_refused(self) -> None: self.git("update-index", flag.replace("--", "--no-"), "slice/index.json", cwd=self.suite) self.assertEqual(self.run_script(MEGA_EEST_DIR=str(self.suite))[0], 0) + def test_a_checkout_git_cannot_read_is_refused(self) -> None: + # HEAD still resolves, but `git status` fails and prints nothing, which is not clean. + (self.suite / ".git" / "index").write_bytes(b"not an index") + code, out, err = self.run_script(MEGA_EEST_DIR=str(self.suite), MEGA_EEST_SKIP_PROVENANCE="1") + self.assertEqual(code, 2, err) + self.assertIn("cannot be read by git status", err) + self.assertIn("stage=fetch result=INCOMPLETE", self.summary(out)) + def test_a_pin_off_the_default_branch_is_refused(self) -> None: draft = self.commit_cases(["satin/a", "satin/b", "satin/c", "satin/d"], branch="draft") code, out, err = self.run_script(rev=draft) From 67b81eea768e3bda6bd2f5d345e3dfb3d25350e4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:03:41 +0800 Subject: [PATCH 111/190] docs: the Mega EEST gate's exit codes, pin checks and branch rule --- .claude/skills/satin-review/SKILL.md | 2 +- AGENTS.md | 20 ++++++++++++++------ REVIEW.md | 13 ++++++++----- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 5a66a62c0..d9d80dba8 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -228,7 +228,7 @@ Five notes that are easy to miss: - run the suite with `MEGA_SATIN_CPSB` and `MEGA_SATIN_CPHB` unset, or the tests that pin the spec's byte prices skip; - 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; -- the Mega EEST gate (`scripts/mega_eest.sh`) fetches the suite at the commit `scripts/mega_eest.env` pins, or reads a checkout at that commit from `MEGA_EEST_DIR`. +- the Mega EEST gate (`scripts/mega_eest.sh`) fetches the suite at the commit `scripts/mega_eest.env` pins, or reads a checkout at that commit from `MEGA_EEST_DIR`, and fetches the suite's history to check the pin is on its default branch; it exits 0 pass, 1 cases failed, 2 no verdict, 3 the pin refused. 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. diff --git a/AGENTS.md b/AGENTS.md index 84b3e5d55..8f2e3550f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,10 +58,12 @@ cargo run --release -p state-test -- --mode satin --fork Osaka /s UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations # The Mega EEST gate (see Test Gates): the shared conformance suite at the commit scripts/mega_eest.env pins, -# through its revm adapter built against this checkout, every case plain and instrumented (logs under target/mega-eest) +# through its revm adapter built against this checkout, every case plain and instrumented (logs under target/mega-eest); +# exit 0 pass, 1 cases failed, 2 no verdict, 3 the pin refused, and one MEGA-EEST summary line on stdout scripts/mega_eest.sh -MEGA_EEST_DIR=
scripts/mega_eest.sh # without the fetch -cargo test -p mega-evm --test mega_eest -- --ignored # the same run, as the mutation gate starts it +MEGA_EEST_DIR= scripts/mega_eest.sh # without the fetch of the pin (its provenance check still fetches) +MEGA_EEST_BASE_REV= scripts/mega_eest.sh # also list the cases a pin move removes, adds and changes +cargo test -p mega-evm --test mega_eest -- --ignored # the full run as a test; the mutation gate runs it plain only # Check compiler errors (preferred over clippy for quick checks) cargo check @@ -669,11 +671,17 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The commit it runs is the one line `MEGA_EEST_REV` of `scripts/mega_eest.env`; the script fetches it (or takes `MEGA_EEST_DIR`, which must be at the pin and unmodified), builds the suite's `mega-fixture` CLI and its revm adapter, and consumes every case of `slice/cases` plain and `--instrumented`. The adapter is built against this checkout, not the mega-evm commit it pins: `scripts/mega_eest.py` writes it out as a workspace of its own (`target/mega-eest/adapter-revm`) whose mega-evm is a path dependency on `crates/mega-evm`, whose other crates take their sources from this tree's `[workspace.dependencies]`, and whose `[patch]` and `[profile]` tables are this tree's root manifest's, so a pull request that moves the revm or op-revm fork is tested with its own fork. The adapter's `Cargo.lock`, resolved for the commit it pins, is not used: the workspace's lock is seeded with this tree's `Cargo.lock`, cargo resolves it once, every package mega-evm links must then be at the version and source this tree locks, with one revm, and the build runs `--locked`. - It passes when the cases consumed are exactly the slice's index, by case id and file digest, every one passes in both modes with the same observations, and the suite's deliberately wrong expectation fails where it records; a failure names the case, its first differing path, both values and the rules it pins, and the summary is one `MEGA-EEST` line. - The `Mega EEST gate` job always runs and is the required check: a pull request that changes documentation alone skips the run (`scripts/pull_request_needs_ci.sh`) and the job passes; every other pull request and every push to `satin` runs it. + The executables it runs are the ones those builds report (cargo's JSON messages), never a file at a path guessed from the target directory. + It passes when the cases consumed are exactly the slice's index, by case id and file digest, every one passes in both modes with the same observations, and the suite's deliberately wrong expectation, which the index must list, fails where it records; a failure names the case, its first differing path, both values and the rules it pins. + The summary is one `MEGA-EEST` line on stdout, and the exit code says what kind of result it is: 0 pass; 1 the cases failed, the only verdict on this tree (every mode ran to a complete report of exactly the index, and a case failed or erred, or the modes' observations differ); 2 no verdict (a fetch, a build, the resolution, a report missing or incomplete, no mode, a wrong expectation not caught, a case the adapter does not support), however the cases would have gone; 3 the cases passed and the pin is refused. + The line says `run=full` for both modes, which the gate requires, and `run=partial` for one. + The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and removed ids must be exactly those `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env` declares (`caseset=declared`, or `kept` with none removed); either refusal is exit 3. + A pin on the branch of a suite change still under review is a draft state: its cases run, and the gate stays red until the pin moves to the merged commit. + `MEGA_EEST_SKIP_PROVENANCE=1` (`provenance=unchecked`) is for the mutation gate's runs, whose warm-up checked the pin, and the coverage report; the gate job never sets it and requires `provenance=default-branch`. + The `Mega EEST gate` job always runs and becomes a required check once an administrator adds it to the `satin` branch rule: a pull request that changes documentation alone skips the run (`scripts/pull_request_needs_ci.sh`) and the job passes; every other pull request and every push to `satin` runs it. When it fails: a case that fails pins behaviour of the specification, so the change is wrong, or it changes that behaviour on purpose, and then the case changes in Mega EEST first; an adapter that no longer builds against this tree means the change altered the mega-evm API the adapter calls (`MegaEvm::execute_transaction`, the `MegaContext` constructors, `system::live_system_address`, the error and result types), and the adapter changes in Mega EEST first. Either way the same pull request then moves the pin to that Mega EEST commit; nothing is skipped or waived here. - The coverage report (`scripts/coverage_mega_evm.sh`) merges the suite's run, through the adapter built with mega-evm instrumented, with the tests', so a line only a Mega EEST case runs counts as covered; the mutation gate runs every mutant the tests miss against the suite (`scripts/mutation_test.sh`, through the ignored `mega_eest` test), so a mutant only a Mega EEST case catches counts as caught. + The coverage report (`scripts/coverage_mega_evm.sh`) merges the suite's run, through the adapter built with mega-evm instrumented, with the tests', so a line only a Mega EEST case runs counts as covered, and fails when that run leaves no coverage profile; the mutation gate runs every mutant the tests miss against the suite in plain mode only (`scripts/mutation_test.sh`, through the ignored `mega_eest` test), so a mutant only a Mega EEST case catches counts as caught, and only on the suite's own verdict (`result=FAIL`) in that mutant's log. - **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, the whole grid, as four parallel shards, on every pull request that changes more than documentation and on dispatch (`--pr`, five points, is the quick local mode). The prices are provisional, so a test holds at any of them — a byte price of nothing, or one gas per byte up to the grid's dearest point: it sizes its gas from the schedule at the prices in effect, and a case whose scenario is state or history gas returns early where that byte costs nothing (`state_is_free`, `history_is_free`). Below one gas per byte the schedule's entries round to nothing one at a time, and no test is held there. diff --git a/REVIEW.md b/REVIEW.md index c2ea7e5b6..c60d827a6 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -99,7 +99,7 @@ Defer to the baseline for everything not listed here; the rules below take prece ## Test gates These checks guard every change to the Satin engine. -`lint`, `test`, `no-std`, `require-label` and `Mega EEST gate` are the required checks on `satin`; the rest inform the review, and the reviewer reads them. +`lint`, `test`, `no-std` and `require-label` are the required checks on `satin`, and `Mega EEST gate` becomes one once an administrator adds it to the branch rule; the rest inform the review, and the reviewer reads them. ### The op-revm baseline @@ -146,13 +146,16 @@ These checks guard every change to the Satin engine. - Mega EEST is the conformance suite both Satin implementations share: state-transition cases, each pinned to rules of the Satin specification, run on an implementation through an adapter. `.github/workflows/mega-eest.yml` runs `scripts/mega_eest.sh`, which consumes every gating case of the suite at the commit `scripts/mega_eest.env` pins (`MEGA_EEST_REV`), plain and instrumented, through the suite's revm adapter built against the pull request's own mega-evm, `[patch]` blocks and `Cargo.lock` (AGENTS.md, Test Gates, has how). -- The `Mega EEST gate` job always runs and is a required check; a pull request that changes documentation alone skips the run and passes it. - The step summary has the summary line (`MEGA-EEST rev=… cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… result=…`) and the run's time; a failing run uploads its reports. +- The `Mega EEST gate` job always runs, and becomes a required check once an administrator adds it to the `satin` branch rule; a pull request that changes documentation alone skips the run and passes it. + The step summary has the summary line (`MEGA-EEST rev=… run=full cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… provenance=… caseset=… result=…`), the run's time and exit, and, when the pull request moves the pin, the case ids it removes, adds and changes; a failing run uploads its reports. + The script's exit says what failed: 1 the cases (a verdict), 2 no verdict (a fetch, a build, a report; the log names the step), 3 the pin refused; the job also requires the line of the full run of a pin on the suite's default branch. - A case that fails is a change of behaviour the specification pins. A pull request that makes it on purpose, or that changes the mega-evm API the suite's adapter calls (the adapter then no longer builds, and the gate says so), changes Mega EEST first: the case, derived from the changed rule, or the adapter, in a pull request there. - It then moves `MEGA_EEST_REV` to that Mega EEST commit, in the same mega-evm pull request, so the gate runs the suite that pull request needs; until the Mega EEST change merges, the pin may name its branch's commit, which the fetch reaches by its hash, and it moves to the merged commit before the mega-evm pull request merges. + It then moves `MEGA_EEST_REV` to that Mega EEST commit, in the same mega-evm pull request, so the gate runs the suite that pull request needs. + While the Mega EEST change is under review, the pin may name its branch's commit as a draft state only: the cases run and show in the log, but the gate fails (`provenance=unmerged`, exit 3) until the pin moves to the commit merged on the suite's default branch, which it must before the mega-evm pull request merges. Locally, a Mega EEST checkout at that commit is used with `MEGA_EEST_DIR= scripts/mega_eest.sh` once the pin names it. -- Moving the pin is a one-line change and is reviewed as one: the suite's own history between the two commits says which cases and which adapter code moved. +- Moving the pin is a one-line change and is reviewed as one: the step summary lists the case ids it removes, adds and changes relative to the base's pin, and the suite's own history between the two commits says why. + A removal fails the gate unless the same pull request lists exactly the removed ids in `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env`, so every behaviour the suite stops pinning is a line the reviewer reads in the diff; a move that removes nothing leaves that line empty. - The coverage report and the mutation gate count the suite too: `scripts/coverage_mega_evm.sh` merges its run into the report Codecov receives, and the cargo-mutants gate runs a mutant the tests miss against it (Mutation testing, below). ### Byte-price grid From 75a04dade7357c2fc7ce561e8b902bb950d6aa10 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:10:20 +0800 Subject: [PATCH 112/190] test(evm): remove tests duplicated by the conformance suite The calldata floor, the access-list data charge and the intrinsic charges of a plain call and a creation are pinned by Mega EEST's intrinsic and validation cases. The two rejection tests stay: they also check revm's own entry point and a commit after the rejection, which no case runs. --- crates/mega-evm/tests/satin/intrinsic.rs | 218 ++--------------------- 1 file changed, 13 insertions(+), 205 deletions(-) diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 65d83ad4d..2ba7f1f54 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -1,39 +1,28 @@ -//! The intrinsic phase: the EIP-7976 calldata floor, the EIP-7981 access-list data charge, the -//! history gas of the transaction's body, and what the execution cap admits. +//! The intrinsic phase: the EIP-7976 calldata floor, the history gas of the transaction's body, and +//! what the execution cap admits. //! //! Satin keeps Amsterdam's floor: a base of 12,000 with the recipient and value charges on top, -//! and every calldata byte at 64 gas whether it is zero or not. EIP-7981 puts the access list's -//! own bytes in the floor at the same rate, and its per-item intrinsic charge is Amsterdam's: -//! EIP-8038's cold premium with those bytes at 64 gas each on top. A transaction whose floor is -//! above the 200M execution cap is rejected before it runs, which is what bounds the calldata a -//! transaction may carry. +//! and every calldata byte at 64 gas whether it is zero or not. A transaction whose floor is above +//! the 200M execution cap is rejected before it runs, which is what bounds the calldata a +//! transaction may carry; one whose floor or intrinsic charge is above its own gas limit is +//! rejected too, and leaves its sender untouched. //! //! The floor is still computed and still validated, and it no longer decides what anyone pays: -//! history gas charges the same bytes at a higher rate, so a Satin transaction is always above -//! its own floor ([`test_the_calldata_floor_never_binds_once_history_is_charged`]). The floor -//! tests below read the floor off the result rather than off the bill. +//! history gas charges the same bytes at a higher rate, so a Satin transaction is above its own +//! floor. The tests below read the floor off the result rather than off the bill. use alloy_evm::{Evm, EvmError, InvalidTxError}; -use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - constants::{ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, - test_utils::{op_transaction, MemoryDatabase}, - MegaEvm, MegaTransaction, TX_BODY_SIZE, + constants::TX_GAS_LIMIT_CAP, test_utils::MemoryDatabase, MegaEvm, MegaTransaction, TX_BODY_SIZE, }; use op_revm::OpTransactionError; use revm::{ - context::{ - result::{EVMError, ExecutionResult, InvalidTransaction}, - transaction::{AccessList, AccessListItem, TransactionType}, - TxEnv, - }, - context_interface::cfg::GasId, - primitives::B256, + context::result::{EVMError, InvalidTransaction}, Database, ExecuteCommitEvm, ExecuteEvm, }; -use crate::common::{call, context, create, history_is_free, runs_at_measurement_prices}; +use crate::common::{call, context, history_is_free, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000800000"); const CALLEE: Address = address!("0000000000000000000000000000000000800001"); @@ -50,10 +39,6 @@ const EMPTY_CALL: u64 = 15_000; /// floor tokens at 16 gas each. const FLOOR_PER_BYTE: u64 = 64; -/// What one byte of anything a transaction carries costs on the history ledger, at the spec's own -/// price. -const HISTORY_PER_BYTE: u64 = COST_PER_HISTORY_BYTE; - /// The history gas a transaction carrying `bytes` bytes beside its envelope pays for its body, at /// the price the engine runs. fn body_history(bytes: u64) -> u64 { @@ -72,12 +57,6 @@ fn gas_used(db: MemoryDatabase, tx: MegaTransaction) -> Result { charged(db, tx).map(|charged| charged.gas_used) } -/// Runs `tx` and returns the EIP-7623 floor it was measured against, or the validation error -/// that rejected it. -fn floor(db: MemoryDatabase, tx: MegaTransaction) -> Result { - charged(db, tx).map(|charged| charged.floor) -} - /// What a transaction was charged: the receipt's figure and the floor it was measured against. struct Charged { gas_used: u64, @@ -103,148 +82,6 @@ fn charged(db: MemoryDatabase, tx: MegaTransaction) -> Result { } } -/* ---------- the EIP-7976 calldata floor ---------- */ - -/// A call carrying `len` bytes of `byte`. -fn with_calldata(len: usize, byte: u8) -> MegaTransaction { - crate::common::call_with_data(CALLER, CALLEE, Bytes::from(vec![byte; len]), 10_000_000) -} - -/// Empty calldata's floor is the intrinsic gas itself, so neither is the binding one. -#[test] -fn test_the_floor_of_empty_calldata_is_the_intrinsic_gas() { - assert_eq!(floor(funded(), with_calldata(0, 0)), Ok(EMPTY_CALL)); - assert_eq!(gas_used(funded(), with_calldata(0, 0)), Ok(EMPTY_CALL + body_history(0))); -} - -/// One byte of calldata costs 64 gas in the floor. -#[test] -fn test_one_calldata_byte_costs_sixty_four_gas() { - assert_eq!(floor(funded(), with_calldata(1, 0x42)), Ok(EMPTY_CALL + FLOOR_PER_BYTE)); -} - -/// A hundred bytes, and a kilobyte: the floor is linear in the byte count at the same rate. -#[test] -fn test_the_floor_is_sixty_four_gas_for_every_calldata_byte() { - for len in [100u64, 1_024, 4_096] { - assert_eq!( - floor(funded(), with_calldata(len as usize, 0x42)), - Ok(EMPTY_CALL + FLOOR_PER_BYTE * len), - "{len} bytes" - ); - } -} - -/// A zero byte costs the same as a non-zero one in the floor: EIP-7976 prices the space a byte -/// takes in a block, not its value. On the history ledger it costs the same too, and for the same -/// reason; only the intrinsic token rate tells the two apart, which is why the bill does. The bill -/// is the larger of the intrinsic charge with the body's history and the floor, so where a history -/// byte is cheap enough for the floor to bind, it binds both alike. -#[test] -fn test_a_zero_calldata_byte_costs_the_same_as_a_non_zero_one() { - let zeros = charged(funded(), with_calldata(1_024, 0x00)).expect("valid"); - let non_zeros = charged(funded(), with_calldata(1_024, 0xff)).expect("valid"); - assert_eq!(zeros.floor, non_zeros.floor); - assert_eq!(zeros.floor, EMPTY_CALL + FLOOR_PER_BYTE * 1_024); - let bill = - |per_byte: u64| (EMPTY_CALL + per_byte * 1_024 + body_history(1_024)).max(zeros.floor); - assert_eq!(zeros.gas_used, bill(4), "a zero byte: four gas and its history"); - assert_eq!( - non_zeros.gas_used, - bill(16), - "only the intrinsic token rate, four against sixteen, tells them apart", - ); -} - -/// The floor is computed and validated as it always was, and it never decides the bill: history -/// gas charges every calldata byte 88 where the floor charges it 64, on a base that is already -/// larger, so a Satin transaction is above its own floor from the first byte on. -#[test] -fn test_the_calldata_floor_never_binds_once_history_is_charged() { - if runs_at_measurement_prices() { - return; - } - const { assert!(HISTORY_PER_BYTE > FLOOR_PER_BYTE) }; - for len in [0u64, 1, 100, 4_096] { - let charged = charged(funded(), with_calldata(len as usize, 0x00)).expect("valid"); - assert_eq!(charged.floor, EMPTY_CALL + FLOOR_PER_BYTE * len, "{len} bytes: the floor"); - assert_eq!( - charged.gas_used, - EMPTY_CALL + 4 * len + body_history(len), - "{len} bytes: the intrinsic charge and the body, both above the floor", - ); - assert!(charged.gas_used > charged.floor, "{len} bytes: the floor does not bind"); - } -} - -/* ---------- the EIP-7981 access-list data charge ---------- */ - -/// A call whose access list names `CALLEE` with `keys` storage keys. -fn with_access_list(keys: usize) -> MegaTransaction { - let access_list = AccessList(vec![AccessListItem { - address: CALLEE, - storage_keys: (0..keys).map(|i| B256::with_last_byte(i as u8)).collect(), - }]); - OpTx(op_transaction(TxEnv { - // Legacy transactions carry no access list, so the type has to say EIP-2930. - tx_type: TransactionType::Eip2930 as u8, - caller: CALLER, - kind: TxKind::Call(CALLEE), - gas_limit: 10_000_000, - access_list, - ..Default::default() - })) -} - -/// An access-list address costs the schedule's entry in the intrinsic phase — 4,180, EIP-8038's -/// cold premium of 2,900 with its twenty bytes at 64 gas each on top — and its twenty bytes cost -/// 64 each in the floor. The intrinsic charge carries the floor's bytes and more, so it is what -/// the transaction pays. -#[test] -fn test_an_access_list_address_pays_its_cold_premium_and_its_bytes() { - assert_eq!(floor(funded(), with_access_list(0)), Ok(EMPTY_CALL + 20 * FLOOR_PER_BYTE)); - assert_eq!( - gas_used(funded(), with_access_list(0)), - Ok(EMPTY_CALL + address_entry() + body_history(20)), - "the intrinsic charge and the address's twenty bytes of history", - ); -} - -/// A storage key costs the schedule's entry in the intrinsic phase — 4,048, EIP-8038's cold -/// premium of 2,000 with its thirty-two bytes at 64 gas each on top — and those bytes cost 2,048 -/// in the floor. The bytes are in both, and the intrinsic charge has the premium besides, so -/// however many keys there are the floor stays below what the transaction pays. -#[test] -fn test_access_list_bytes_are_counted_in_the_floor_at_sixty_four_each() { - let address_bytes = 20 * FLOOR_PER_BYTE; - let key_bytes = 32 * FLOOR_PER_BYTE; - for keys in [0u64, 1, 7, 8, 16, 64] { - assert_eq!( - floor(funded(), with_access_list(keys as usize)), - Ok(EMPTY_CALL + address_bytes + key_bytes * keys), - "{keys} keys: the floor counts every byte at the same rate" - ); - let floor = EMPTY_CALL + address_bytes + key_bytes * keys; - let intrinsic = EMPTY_CALL + address_entry() + key_entry() * keys; - assert!(intrinsic > floor, "{keys} keys: the intrinsic charge carries the floor's bytes"); - assert_eq!( - gas_used(funded(), with_access_list(keys as usize)), - Ok(intrinsic + body_history(20 + 32 * keys)), - "{keys} keys: the intrinsic charge and the entry's bytes of history" - ); - } -} - -/// The intrinsic charge of an access-list address, at the schedule's price. -fn address_entry() -> u64 { - mega_evm::satin_gas_params().get(GasId::tx_access_list_address_cost()) -} - -/// The intrinsic charge of an access-list storage key, at the schedule's price. -fn key_entry() -> u64 { - mega_evm::satin_gas_params().get(GasId::tx_access_list_storage_key_cost()) -} - /* ---------- the execution cap ---------- */ /// The largest calldata the execution cap admits: its floor is the cap's own number rounded down @@ -352,27 +189,7 @@ fn assert_sender_untouched(db: &mut MemoryDatabase) { assert_eq!(info.balance, U256::from(10u64.pow(18)), "the sender's balance"); } -/* ---------- the state component is charged where it happens ---------- */ - -/// A creation transaction's created account's state gas is charged as the frame starts, not at -/// validation: a gas limit that covers the intrinsic charge alone is accepted and then runs out of -/// gas, charging the sender. -#[test] -fn test_a_creation_that_cannot_pay_its_account_runs_out_of_gas() { - if runs_at_measurement_prices() { - return; - } - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let mut evm = MegaEvm::new(context(db)); - let outcome = evm - .execute_transaction(create(CALLER, Bytes::new(), 24_000 + ACCOUNT_STATE_GAS - 1)) - .expect("the transaction is admitted"); - - assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); - assert_eq!(outcome.state[&CALLER].info.nonce, 1, "the sender paid for the attempt"); - assert_eq!(outcome.gas.gas_used, 24_000 + ACCOUNT_STATE_GAS - 1, "its whole gas limit"); - assert_eq!(outcome.gas.state, 0, "and the account it could not pay for is not created"); -} +/* ---------- the gas limit against the intrinsic charge and the body ---------- */ /// A gas limit below the intrinsic charge itself is a validation rejection, which leaves the /// sender untouched. @@ -398,15 +215,6 @@ fn test_a_gas_limit_below_the_intrinsic_charge_is_rejected() { ); } -/// A plain call within its limits still goes through, so the checks above are not too eager. -#[test] -fn test_a_valid_call_still_passes() { - assert_eq!( - gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, 1_000_000)), - Ok(EMPTY_CALL + body_history(0)), - ); -} - /// A gas limit that covers the intrinsic charge but not the body's history is a validation /// rejection too, naming the whole figure: the bytes a transaction carries are part of what makes /// it valid, so a transaction that cannot pay for them is never included, and leaves the sender From 0342fd6f1e39f5dad53963dd2085815200824a58 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:18:02 +0800 Subject: [PATCH 113/190] ci(mutation): port incremental builds, the time budget and sharding from main --- .cargo/mutants-infra.toml | 2 + .cargo/mutants.toml | 7 +- .github/workflows/mutation.yml | 192 +++++++++-- REVIEW.md | 5 +- mutants/README.md | 58 +++- mutants/suppressions.toml | 65 +++- scripts/mutation_gate.py | 572 +++++++++++++++++++++++++++------ scripts/mutation_test.sh | 301 ++++++++++++++--- scripts/test_mutation_gate.py | 530 ++++++++++++++++++++++++++++-- 9 files changed, 1486 insertions(+), 246 deletions(-) diff --git a/.cargo/mutants-infra.toml b/.cargo/mutants-infra.toml index 66772a845..aae8ab6d8 100644 --- a/.cargo/mutants-infra.toml +++ b/.cargo/mutants-infra.toml @@ -19,4 +19,6 @@ exclude_globs = ["**/generated/**"] minimum_test_timeout = 120 timeout_multiplier = 3.0 +# As in .cargo/mutants.toml: seeded from the driver's warm build, incrementally with +# CARGO_INCREMENTAL=1. copy_target = true diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 4c354b6d9..ab339ee50 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -43,6 +43,9 @@ timeout_multiplier = 3.0 # Seed each scratch build directory from ./target so mutant builds reuse the # already-compiled dependencies instead of recompiling them from scratch. Paired -# with a warm ./target (a prebuild step + Swatinem/rust-cache in CI), this is what -# lets the cache benefit the per-mutant builds, not just the dependency download. +# with a warm ./target (the driver's warm build + Swatinem/rust-cache in CI), this +# is what lets the cache benefit the per-mutant builds, not just the dependency +# download. With incremental compilation on (CI must set CARGO_INCREMENTAL=1, as +# the toolchain action turns it off), the copy also carries mega-evm's incremental +# state, so each mutant build recompiles only what the mutation changed. copy_target = true diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 185defbd0..24bbb0725 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -1,7 +1,8 @@ name: Mutation Testing # All mutation-testing CI lives here. Four concerns, one file: -# * cargo-mutants gate — generic operators (diff-scoped on PRs, full nightly) +# * cargo-mutants gate — generic operators (diff-scoped on PRs, full nightly +# in four shards) # * infrastructure gate — the same operators on the code that implements the # test gates, which the production scope excludes # * suppression hygiene — flag suppressions that no longer match a live mutant @@ -31,20 +32,46 @@ permissions: jobs: # ── cargo-mutants: diff-scoped gate on PRs, full-crate run nightly ────────── + # A PR runs one diff-scoped job. The full-crate run (nightly, dispatch) does not + # fit in one job, so it runs as four fresh shards (`cargo mutants --shard k/4`: + # consecutive slices of the mutant list) and `cargo-mutants-full` scores them + # together against the full inventory, so a missing or stopped shard shows as + # untested mutants rather than vanishing from the report. cargo-mutants: - name: cargo-mutants gate + name: ${{ matrix.shard == 'diff' && 'cargo-mutants gate' || format('cargo-mutants shard {0}', matrix.shard) }} runs-on: ubuntu-24.04 - # Diff-scoped PR runs finish in minutes; the nightly full-crate run needs - # much longer headroom. + # Diff-scoped PR runs finish in minutes; a full-crate shard needs much longer + # headroom. MUTANTS_BUDGET (below) stops the run itself before this limit, so + # a run that cannot finish still scores and uploads its results. timeout-minutes: 330 + strategy: + fail-fast: false + matrix: + shard: ${{ fromJSON(github.event_name == 'pull_request' && '["diff"]' || '["0/4", "1/4", "2/4", "3/4"]') }} steps: - uses: actions/checkout@v4 with: submodules: recursive fetch-depth: 0 # need base history for the diff + - name: Decide whether the run builds + # A PR that changes no mutatable source has nothing to mutate, and the + # driver skips its warm build. The Rust cache is then neither restored + # (nothing would use it) nor saved: the save would store a target with + # nothing compiled in it, and a later run of this PR that hit that entry + # would rebuild every dependency without ever saving a better one. + id: scope + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + scripts/mutation_test.sh changed "${{ github.event.pull_request.base.sha }}" >> "$GITHUB_OUTPUT" + else + echo "mutate=true" >> "$GITHUB_OUTPUT" + fi + - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + cache: ${{ steps.scope.outputs.mutate }} - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 @@ -59,36 +86,45 @@ jobs: # generated mutants, which would silently shift the gate's baseline. tool: cargo-mutants@27.1.0 - - name: Warm build cache - # Compile deps + test binaries into ./target so (a) Swatinem/rust-cache + - name: Run mutation testing + # On a PR: mutate only the changed lines (fast gate). On nightly or manual + # dispatch there is no PR base, so run the whole crate, sharded, instead of + # feeding an empty base into `diff` mode (which would fail). + # + # The driver first builds the tests into ./target, so (a) Swatinem/rust-cache # (bundled in setup-rust-toolchain) caches the compiled dependencies, and # (b) cargo-mutants' `copy_target` seeds each scratch build from this warm - # target — so per-mutant builds skip recompiling dependencies. - run: cargo nextest run -p mega-evm --all-features --no-run - - - name: Run mutation testing - # On a PR: mutate only the changed lines (fast gate). On manual dispatch - # there is no PR base, so run the whole crate as an on-demand baseline - # instead of feeding an empty base into `diff` mode (which would fail). - # The driver re-runs a mutant that timed out once, alone, into - # target/mutants/recheck; the gate takes that outcome for it. A mutant - # the tests still miss is then run against the Mega EEST suite - # (scripts/mega_eest.sh, through mega-evm's ignored `mega_eest` test), - # into target/mutants/mega-eest: one a Mega EEST case catches counts as - # caught. + # target — so per-mutant builds skip recompiling dependencies. It re-runs a + # mutant that timed out once, alone, into target/mutants/recheck, and runs a + # mutant the tests still miss against the Mega EEST suite + # (scripts/mega_eest.sh, through mega-evm's ignored `mega_eest` test), into + # target/mutants/mega-eest: the gate takes those outcomes for them. + env: + # setup-rust-toolchain exports CARGO_INCREMENTAL=0. Every mutant rebuilds + # mega-evm and all of its test binaries; incremental compilation, for the + # warm build and the mutant builds alike, lets each of those rebuilds + # reuse what the mutation did not touch. + CARGO_INCREMENTAL: "1" + # Seconds from the driver's start (300 min), the follow-up runs included. + # Leaves the job's 330-minute limit room for setup, the driver's stop grace + # period, scoring, upload and the cache save. + MUTANTS_BUDGET: "18000" run: | if [ "${{ github.event_name }}" = "pull_request" ]; then scripts/mutation_test.sh diff "${{ github.event.pull_request.base.sha }}" else - scripts/mutation_test.sh full + scripts/mutation_test.sh full --shard "${{ matrix.shard }}" fi - name: Score and gate + # Shards are scored together by cargo-mutants-full. + if: github.event_name == 'pull_request' run: | python3 scripts/mutation_gate.py report \ --results target/mutants/mutants.out \ --recheck target/mutants/recheck/mutants.out \ --mega-eest target/mutants/mega-eest/mutants.out \ + --status target/mutants/status \ --suppressions mutants/suppressions.toml \ --comment mutation-report.md \ --summary "$GITHUB_STEP_SUMMARY" @@ -128,12 +164,13 @@ jobs: } - name: Upload mutation artifacts - if: always() + if: always() && github.event_name == 'pull_request' uses: actions/upload-artifact@v4 with: name: mutation-results path: | target/mutants/mutants.out + target/mutants/status target/mutants/recheck/mutants.out target/mutants/mega-eest/mutants.out target/mutants.diff @@ -144,6 +181,87 @@ jobs: mutation-report.md if-no-files-found: ignore + - name: Upload shard results + # The artifact holds this shard's mutants.out/, status and follow-up runs + # (recheck/, mega-eest/) at its root. + if: always() && github.event_name != 'pull_request' + uses: actions/upload-artifact@v4 + with: + name: mutation-results-shard-${{ strategy.job-index }} + path: target/mutants + if-no-files-found: ignore + + cargo-mutants-full: + name: cargo-mutants full run + needs: cargo-mutants + # Also after a failed or timed-out shard: the report names it, and its + # mutants count as untested. + if: ${{ !cancelled() && github.event_name != 'pull_request' }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + cache: false + + - name: Install cargo-mutants + uses: taiki-e/install-action@v2 + with: + tool: cargo-mutants@27.1.0 + + - name: Download shard results + uses: actions/download-artifact@v4 + with: + pattern: mutation-results-shard-* + path: shards + + - name: List the full inventory + # The mutants the shards' `full` runs test, from the driver itself. + run: | + scripts/mutation_test.sh list > inventory.txt + echo "inventory: $(wc -l < inventory.txt) mutants" + + - name: Merge, score and gate + run: | + # One directory per shard of the cargo-mutants matrix (by job index), so + # that a shard which uploaded nothing is named in the report. + shards=(shards/mutation-results-shard-{0..3}) + python3 scripts/mutation_gate.py merge --inventory inventory.txt \ + --out target/mutants "${shards[@]}" | tee -a "$GITHUB_STEP_SUMMARY" + # The shards' re-checks and Mega EEST runs, which the report reads for the + # mutants that timed out and the ones the tests missed. + python3 scripts/mutation_gate.py merge-runs --out target/mutants/recheck/mutants.out \ + "${shards[@]/%//recheck/mutants.out}" + python3 scripts/mutation_gate.py merge-runs --out target/mutants/mega-eest/mutants.out \ + "${shards[@]/%//mega-eest/mutants.out}" + python3 scripts/mutation_gate.py report \ + --results target/mutants/mutants.out \ + --recheck target/mutants/recheck/mutants.out \ + --mega-eest target/mutants/mega-eest/mutants.out \ + --status target/mutants/status \ + --scope full \ + --suppressions mutants/suppressions.toml \ + --comment mutation-report.md \ + --summary "$GITHUB_STEP_SUMMARY" + + - name: Upload mutation artifacts + if: always() + uses: actions/upload-artifact@v4 + with: + name: mutation-results + path: | + target/mutants/mutants.out + target/mutants/status + target/mutants/unplanned.txt + target/mutants/recheck/mutants.out + target/mutants/mega-eest/mutants.out + inventory.txt + mutation-report.md + if-no-files-found: ignore + # ── cargo-mutants: the test gates' own infrastructure ────────────────────── # The second mutation scope (.cargo/mutants-infra.toml): the scenario runner's # transaction conversion and execute/commit loop. The production scope @@ -179,12 +297,13 @@ jobs: with: tool: cargo-mutants@27.1.0 - - name: Warm build cache - run: cargo nextest run -p mega-evm --all-features --no-run - - name: Run mutation testing + # The driver builds the tests first, as for the production scope. env: OUT_DIR: target/mutants-infra + CARGO_INCREMENTAL: "1" + # 80 minutes, inside the job's 90. + MUTANTS_BUDGET: "4800" run: scripts/mutation_test.sh infra - name: Score and gate @@ -192,6 +311,7 @@ jobs: python3 scripts/mutation_gate.py report \ --results target/mutants-infra/mutants.out \ --recheck target/mutants-infra/recheck/mutants.out \ + --status target/mutants-infra/status \ --suppressions mutants/suppressions.toml \ --summary "$GITHUB_STEP_SUMMARY" @@ -202,6 +322,7 @@ jobs: name: mutation-results-infra path: | target/mutants-infra/mutants.out + target/mutants-infra/status target/mutants-infra/recheck/mutants.out target/mutants-infra.log target/mutants-infra/recheck.log @@ -223,8 +344,9 @@ jobs: # ── suppression hygiene: gate on relevant PR changes, plus nightly ───────── # `changes` scopes the hygiene job to PRs that could orphan a suppression - # (suppressions, operators, or src edits) and the infrastructure job to PRs - # that touch its scope; nightly/dispatch always run both. + # (suppressions, operators, src edits, or the tools that list and match the + # mutants) and the infrastructure job to PRs that touch its scope; + # nightly/dispatch always run both. changes: if: github.event_name == 'pull_request' runs-on: ubuntu-24.04 @@ -240,6 +362,11 @@ jobs: - 'mutants/suppressions.toml' - 'mutants/operators/**' - 'crates/mega-evm/src/**' + - '.cargo/mutants.toml' + - '.cargo/mutants-infra.toml' + - 'scripts/mutation_test.sh' + - 'scripts/mutation_gate.py' + - 'scripts/umutate.py' infra: - '.cargo/mutants-infra.toml' - 'crates/mega-evm/src/test_utils/scenario.rs' @@ -278,15 +405,10 @@ jobs: comby -version - name: Build the full mutant universe (both engines, both scopes) run: | - # --package mega-evm: match the driver's production scope (otherwise --list - # also covers the CLI bins in the virtual workspace's default-members, so a - # stale mega-evm suppression could be kept alive by a same-named mutant - # in another crate). - # No --exclude-re here, so function-suppressed mutants are included — - # giving the complete universe to validate suppressions against. - # --colors never: CI forces CARGO_TERM_COLOR=always, which would otherwise - # embed ANSI codes and break exact suppression matching. - cargo mutants --list --package mega-evm --colors never > universe.txt + # The driver's production mutant set, with --all so that it keeps the + # mutants of function-scoped suppressions: the universe to check + # suppressions against (--colors never, the package alone, as the runs). + scripts/mutation_test.sh list --all > universe.txt # The infrastructure scope is a second mutant population and a suppression may live in # it, so it joins the universe. Listed through the driver, so its file list stays in # one place, with SUPPRESS=/dev/null so the driver emits no --exclude-re and function- diff --git a/REVIEW.md b/REVIEW.md index c60d827a6..76534d1b9 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -200,7 +200,10 @@ These checks guard every change to the Satin engine. - A mutant the tests miss is run once more against the Mega EEST suite, with mega-evm's ignored `mega_eest` test as the only test, which runs `scripts/mega_eest.sh` (plain) on the mutated tree; one a Mega EEST case catches counts as caught, and the report says how many the suite decided. The suite is fetched and its adapter built on the unmutated tree first, which must pass; a warm-up or a run that fails as a run is recorded in its results, which the gate refuses. The pass costs nothing while the tests catch every mutant, and about one adapter build and one run of the suite per mutant they miss. -- The job is bounded to 330 minutes. +- The job is bounded to 330 minutes, and the driver's own budget (`MUTANTS_BUDGET`, 300 minutes) stops the run before that, so a run that cannot finish still scores and uploads what it tested; the driver's `MUTANTS-STATUS` line says how far it got, and the gate (`report --status`) fails anything but a complete run. + The driver builds the tests once before the mutants (the warm build) and CI builds incrementally (`CARGO_INCREMENTAL=1`), so each mutant recompiles only what its mutation changed. + The nightly full run is four shards (`scripts/mutation_test.sh full --shard k/4`), merged against the full inventory (`mutation_gate.py merge`, and `merge-runs` for their re-checks and Mega EEST runs) and scored as a full run. + A line suppression is anchored to one mutant (`file`, `line`, `column` and its text); one whose mutant moves gates it again, and the hygiene job names where its text went. Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. - The gate has a second scope, for its own infrastructure: `.cargo/mutants-infra.toml` and `scripts/mutation_test.sh infra` mutate the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) against `mega-evm`'s tests. diff --git a/mutants/README.md b/mutants/README.md index 70f4523f9..92c681ab7 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -22,9 +22,10 @@ It never reads `.cargo/mutants.toml`, and a change to `mutants/suppressions.toml | `.cargo/mutants.toml` | Canonical `cargo-mutants` config for the production scope (nextest, excludes, timeouts). | | `.cargo/mutants-infra.toml` | Config for the infrastructure scope (no helper exclusion). | | `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating, in either scope. | -| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `, `infra`; `MUTANTS_SHARD=k/n` runs one shard. | -| `scripts/mutation_gate.py` | Scores a run, applies suppressions, gates the PR. | -| `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment, and the infrastructure job. | +| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `, `infra`; `list` prints the mutant set the runs use, `changed ` whether a diff run builds; `MUTANTS_SHARD=k/n` runs one shard. | +| `scripts/mutation_gate.py` | Scores a run, applies suppressions, gates the PR; merges the shards of the nightly full run. | +| `scripts/test_mutation_gate.py` | Tests of the scorer and the driver's guards (`python3 -m unittest discover -s scripts -p 'test_*.py'`). | +| `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment; sharded nightly full run; the infrastructure job. | ## Local use @@ -33,7 +34,7 @@ It never reads `.cargo/mutants.toml`, and a change to `mutants/suppressions.toml scripts/mutation_test.sh diff origin/main python3 scripts/mutation_gate.py report --results target/mutants/mutants.out \ --recheck target/mutants/recheck/mutants.out --mega-eest target/mutants/mega-eest/mutants.out \ - --suppressions mutants/suppressions.toml + --status target/mutants/status --suppressions mutants/suppressions.toml # One subsystem while iterating: scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' @@ -41,7 +42,8 @@ scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' # The infrastructure scope (its own output directory, so it does not overwrite the production run): OUT_DIR=target/mutants-infra scripts/mutation_test.sh infra python3 scripts/mutation_gate.py report --results target/mutants-infra/mutants.out \ - --recheck target/mutants-infra/recheck/mutants.out --suppressions mutants/suppressions.toml + --recheck target/mutants-infra/recheck/mutants.out --status target/mutants-infra/status \ + --suppressions mutants/suppressions.toml # Shard k of n of a large run (cargo-mutants' --shard), each into its own directory: MUTANTS_SHARD=0/4 OUT_DIR=target/mutants-0 scripts/mutation_test.sh diff origin/main @@ -51,6 +53,39 @@ The driver needs bash 5 or later and Python 3.11 or later on `PATH`; it refuses The gate's own tests run with `python3 -m unittest discover -s scripts -p 'test_*.py'`, on the same Python; an older one runs a single test in their place, which fails with the reason. When to shard is in `REVIEW.md` (Test gates, Mutation testing). +## Build speed and the time budget + +Every mutant rebuilds `mega-evm` and all of its test binaries, so the run's cost is dominated by builds. +The driver first builds the unmutated tests into `./target` (the warm build), which `copy_target` copies into each scratch build directory. +With incremental compilation, each mutant build then reuses everything the mutation did not touch. +Cargo builds the dev profile incrementally by default, but `actions-rust-lang/setup-rust-toolchain` exports `CARGO_INCREMENTAL=0`, so the workflow sets `CARGO_INCREMENTAL=1` on the mutation steps. +A PR that changes no mutatable source has nothing to mutate: the driver skips its warm build and still runs cargo-mutants, which says it has nothing to mutate and builds nothing, so the gate passes on its word. +The workflow asks the driver first (`scripts/mutation_test.sh changed `) and then neither restores nor saves the Rust cache, so a target with nothing compiled in it is never cached. + +`MUTANTS_BUDGET=` bounds a run, counted from the driver's start and covering the warm build, cargo-mutants and the re-check of timed-out mutants. +When it runs out, the driver interrupts the running phase; cargo-mutants stops its in-flight mutants and keeps every outcome already recorded, and the driver exits 0 so that what was tested can still be scored and uploaded. +A re-check the budget stops is recorded in its results (`run-failed.txt`), which the gate refuses. +The driver's last line, also written to `target/mutants/status`, says how far the run got: + +``` +MUTANTS-STATUS status= expected= outcomes= +``` + +`expected` is the number of mutants cargo-mutants planned (`unknown` if the run stopped before it planned them) and `outcomes` the number that got an outcome. +`followup-stopped` is a run that tested every planned mutant and ran out of budget in a follow-up run. +`baseline-failed` (the unmutated tree does not build or pass its tests) and `error` (the run itself failed) exit non-zero. +`mutation_gate.py report --status target/mutants/status` fails the gate unless the status is `complete`, while still reporting what was tested; with `complete`, it reads the results fail-closed as below. + +The nightly full-crate run does not fit in one job, so CI splits it into four fresh shards (`scripts/mutation_test.sh full --shard k/4`, consecutive slices of the mutant list). +The `cargo-mutants-full` job lists the full inventory with the driver's own mutant set (`scripts/mutation_test.sh list`), combines the shards with `mutation_gate.py merge` (and their re-checks and Mega EEST runs with `mutation_gate.py merge-runs`), and scores the result as a full run (`mutation_gate.py report --scope full`, which titles it a full-run score rather than a diff score). +The merged record keeps the contract the gate reads: the inventory as `mutants.json`, every shard's outcomes in `outcomes.json`, finished only when every shard finished. +Each shard's own status is folded into the combined status, and the report names every shard that did not complete and why. +A shard whose budget ran out makes the combined status `partial` (or `not-started`), one whose baseline failed makes it `baseline-failed`, and one that errored, ended without a status line (cancelled or killed by the job timeout) or uploaded nothing makes it `error`. +Every shard outcome is kept. +An outcome for a mutant the inventory does not list, a second outcome for one mutant, or shard plans that do not add up to the inventory mean the shards and the inventory were built from different mutant sets: the combined status is `mismatch`, and `unplanned.txt` lists the outcomes that do not fit. +Only `complete` passes the gate. +A cancelled run is not scored. + ## The gate PR CI runs **diff-scoped** (`cargo mutants --in-diff`), so every mutant lives on a line the PR touched. @@ -84,16 +119,19 @@ Two granularities: - `kind = "function"` — a regex `pattern` matched against the mutant name; excluded before generation. For whole equivalent/dead functions. -- `kind = "line"` — the exact `mutant` text; filtered from results. +- `kind = "line"` — one mutant, named by its location (`file`, `line`, `column`) and its exact `mutant` text (without the `file:line:col: ` prefix); filtered from results. For a single survivor inside an otherwise-tested function. + The anchor keeps the entry to the reviewed mutant: the same mutation text elsewhere in the function, such as a newly added `&&`, stays gated. + When code above it moves the mutant, the entry stops matching and the mutant is gated again (fail closed); the hygiene job reports the entry as stale, with the location its text moved to, and it is re-anchored once its justification is checked against the new code. + An entry without a well-formed anchor is refused. Inline `#[mutants::skip]` on a function is also honored natively by cargo-mutants; prefer `suppressions.toml` when the decision needs a record. Adding a suppression is a reviewed decision — scrutinize it like disabling a test. -A suppression that stops matching any mutant (its function was renamed/deleted, or its line text changed) silently becomes a permanent blind spot. -The **Suppression Hygiene** job (the `orphan-suppressions` job in `.github/workflows/mutation.yml`) guards against this: it assembles the full mutant universe from both engines and runs `mutation_gate.py orphans`, failing if any suppression matches nothing. -It runs on PRs that touch `suppressions.toml` or `src/`, and weekly. +A suppression that stops matching any mutant (its function was renamed or deleted, its line moved, or its text changed) silently becomes a permanent blind spot, or, for a moved line, gates the reviewed mutant again. +The **Suppression Hygiene** job (the `orphan-suppressions` job in `.github/workflows/mutation.yml`) guards against this: it assembles the full mutant universe from both engines and both scopes (`scripts/mutation_test.sh list --all`, `scripts/mutation_test.sh infra --list` and `umutate.py plan`) and runs `mutation_gate.py orphans`, failing if any suppression matches nothing. +It runs on PRs that touch `suppressions.toml`, `src/` or the mutation tooling, and nightly. For dead code, prefer deleting it or `#[mutants::skip]` over a permanent `kind = "function"` exclude. ## Fixing survivors @@ -172,7 +210,7 @@ python3 scripts/umutate.py run --packs spec-gate --diff origin/main --output tar ## Suppressions and CI -Spec-gate equivalents (e.g. a gate guarding a state no test exercises — expect a meaningful rate) go in the **same** `suppressions.toml`, as `kind = "line"` entries matching the mutant text, prefixed with the pack name. +Spec-gate equivalents (e.g. a gate guarding a state no test exercises — expect a meaningful rate) go in the **same** `suppressions.toml`, as `kind = "line"` entries anchored like any other (spec-gate mutants sit at column 1 of their line), whose text starts with the pack name. A single-spec engine has no spec gate for these operators to mutate, so mutation CI does not run the pack. The operator pack stays on disk. Suppression hygiene still plans it and accepts an empty plan. diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index ebae1adf8..bee038c3a 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -13,15 +13,20 @@ # kind = "function" -> matched as an --exclude-re against the mutant NAME. # Use for whole functions that are entirely equivalent or # dead (stable across line moves). `pattern` is a regex. -# kind = "line" -> matched against the exact mutant description line from -# missed.txt OR timeout.txt. Use for a single surviving -# mutant inside an otherwise-tested function, or to accept -# a genuinely non-terminating/equivalent timed-out mutant. -# `mutant` is the literal text (without "file:line:col: "), -# or, when several mutants share that text, the full -# "file:line:col: text" line of each one suppressed: a -# bare text that matches more than one mutant fails the -# gate. +# kind = "line" -> matched against one mutant line of missed.txt OR +# timeout.txt (`file:line:col: text`): `file`, `line` and +# `column` must name its location and `mutant` must be its +# exact text (without the "file:line:col: " prefix). Use for +# a single surviving mutant inside an otherwise-tested +# function, or to accept a genuinely non-terminating or +# equivalent timed-out mutant. The anchor keeps the entry +# to the one reviewed mutant: the same mutation text +# elsewhere in the function (a new `&&`, say) stays gated. +# When the code above it moves, the entry stops matching +# (fail closed: the mutant is gated again) and the +# suppression-hygiene job reports it as stale, with the +# location the text has moved to; re-anchor it after +# checking the justification still holds. # # Every entry also carries: # category = "equivalent" | "dead" @@ -40,7 +45,7 @@ # a caller, its mutants silently stop being generated and no gap is reported. # `kind = "line"` is safer — the mutant is still generated and run every time, so # if the code changes such that a test now kills it, it simply shows up as caught -# and the suppression becomes a harmless no-op. Prefer "line" unless the whole +# and the suppression becomes a harmless no-op; if it moves, it is gated again. Prefer "line" unless the whole # function is genuinely, permanently dead, and re-audit the "function" entries # (and every "dead" justification) whenever their surrounding code changes. The # nightly full-crate run (.github/workflows/mutation.yml) re-checks "line" @@ -58,6 +63,8 @@ kind = "line" category = "equivalent" file = "crates/mega-evm/src/external/mod.rs" +line = 98 +column = 9 mutant = "replace ::external_envs -> ExternalEnvs with ExternalEnvs::from(Default::default())" justification = "EmptyExternalEnv is a unit struct; real body builds ExternalEnvs{salt_env:EmptyExternalEnv, oracle_env:EmptyExternalEnv}; from(Default::default()) resolves to Default for ExternalEnvs producing identical fields. Value-identical, no observable behavioral difference." reviewer = "improve-mutation-score (William Aaron Cheung)" @@ -79,7 +86,9 @@ reviewer = "improve-mutation-score (William Aaron Cheung)" kind = "line" category = "equivalent" file = "crates/mega-evm/src/external/hasher/fallback.rs" -mutant = "crates/mega-evm/src/external/hasher/fallback.rs:120:48: replace | with ^ in ::write" +line = 120 +column = 48 +mutant = "replace | with ^ in ::write" justification = "Equivalent: `(front as u128) | ((back as u128) << 64)` ORs a u64-widened low half (bits 0..63 only) with a u64-widened high half shifted into bits 64..127 only. The operands have disjoint set bits by construction for every input, so | == ^ identically; no reachable input distinguishes them." reviewer = "RealiCZ" @@ -87,7 +96,9 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/external/hasher/fallback.rs" -mutant = "crates/mega-evm/src/external/hasher/fallback.rs:125:47: replace | with ^ in ::write" +line = 125 +column = 47 +mutant = "replace | with ^ in ::write" justification = "Equivalent: `(value[0] as u128) | ((value[1] as u128) << 64)` ORs a u64-widened low half (bits 0..63 only) with a u64-widened high half shifted into bits 64..127 only. The operands have disjoint set bits by construction for every input, so | == ^ identically; no reachable input distinguishes them." reviewer = "improve-mutation-score (William Aaron Cheung)" @@ -115,6 +126,8 @@ reviewer = "improve-mutation-score (William Aaron Cheung)" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 58 +column = 48 mutant = "replace ^ with | in DeterministicHasher::update" justification = "Dead outside the unit tests: bucket_id drives only the slice write() -> large_update, and update() is reached solely via the typed write_uN methods, which no non-test code calls. test_hasher_typed_write_methods runs it but asserts only that the typed hashes differ from one another, which `new_data | buffer` keeps; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -123,6 +136,8 @@ reviewer = "RealiCZ" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 58 +column = 48 mutant = "replace ^ with & in DeterministicHasher::update" justification = "Dead outside the unit tests: see the ^->| entry for update. test_hasher_typed_write_methods asserts only that the typed hashes differ from one another, which `new_data & buffer` keeps; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -131,6 +146,8 @@ reviewer = "RealiCZ" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 73 +column = 9 mutant = "replace ::write_u8 with ()" justification = "Dead outside the unit tests: bucket_id uses only the slice write() -> large_update, and no non-test code calls write_u8. test_hasher_typed_write_methods calls it but asserts only that its hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -139,6 +156,8 @@ reviewer = "RealiCZ" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 78 +column = 9 mutant = "replace ::write_u16 with ()" justification = "Dead outside the unit tests: same as write_u8. test_hasher_typed_write_methods asserts only that write_u16's hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -147,6 +166,8 @@ reviewer = "RealiCZ" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 83 +column = 9 mutant = "replace ::write_u32 with ()" justification = "Dead outside the unit tests: same as write_u8. test_hasher_typed_write_methods asserts only that write_u32's hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -155,6 +176,8 @@ reviewer = "RealiCZ" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 88 +column = 9 mutant = "replace ::write_u64 with ()" justification = "Dead outside the unit tests: same as write_u8; write_usize delegates to it. test_hasher_typed_write_methods asserts only that write_u64 and write_usize agree, which they still do, both hashing nothing; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -163,6 +186,8 @@ reviewer = "RealiCZ" kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" +line = 93 +column = 9 mutant = "replace ::write_u128 with ()" justification = "Dead outside the unit tests: bucket_id's slice write() calls large_update directly, never write_u128, and no non-test code calls it. test_hasher_typed_write_methods asserts only that its hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." reviewer = "RealiCZ" @@ -186,7 +211,9 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/external/hasher/fallback.rs" -mutant = "crates/mega-evm/src/external/hasher/fallback.rs:109:27: replace > with >= in ::write" +line = 109 +column = 27 +mutant = "replace > with >= in ::write" justification = "Equivalent (line 109 `> 16`): the > vs >= boundary only differs at len == 16, where both the mid branch (front | (back<<64)) and the large branch (read_last_u128, with no loop pass since 16 is not > 16) feed the identical le_u128(bytes[0..16]) to a single large_update. Same buffer, same bucket id; no input distinguishes them. The line-108 and line-112 mutants sharing this text are non-equivalent and are not suppressed." reviewer = "improve-mutation-score (William Aaron Cheung)" @@ -203,6 +230,8 @@ reviewer = "improve-mutation-score (William Aaron Cheung)" kind = "line" category = "equivalent" file = "crates/mega-evm/src/evm/spec.rs" +line = 136 +column = 9 mutant = "replace for EthSpecId>::from -> Self with Default::default()" justification = "Equivalent: revm's SpecId::OSAKA carries #[default], and Satin's sole rung (SATIN) maps to EthSpecId::OSAKA, so Default::default() returns the same value on every current input. test_all_specs_map_to_karst_and_osaka pins the mapping; if the upstream default moves, that test kills this mutant and the entry becomes a no-op." reviewer = "RealiCZ" @@ -218,6 +247,8 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/evm/context.rs" +line = 714 +column = 43 mutant = "replace == with != in MegaContext::prepare" justification = "Equivalent: the comparison only chooses between TxClass::Deposit and TxClass::Ordinary for an execution that is neither the protocol's own nor neutral, and every reader of the class treats the two alike (is_exempt false, prices_history true). Swapping them changes no limit, exemption, detention or history charge." reviewer = "RealiCZ" @@ -238,6 +269,8 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/block/genesis.rs" +line = 290 +column = 31 mutant = "replace || with && in Entry::address" justification = "Equivalent: every string the mutated check lets through (40 bytes not all hexadecimal, or all-hexadecimal of another length) is refused by Address::from_str (alloy's FixedBytes::from_hex: exact 40 hex digits after an optional 0x), and the refusal maps to the same invalid() error, so the result is identical for every input." reviewer = "RealiCZ" @@ -259,6 +292,8 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/test_utils/scenario.rs" +line = 238 +column = 13 mutant = "delete field timestamp from struct BlockEnv expression in Scenario::block" justification = "Equivalent: the field writes U256::from(1) and revm 40's BlockEnv::default() already has timestamp: U256::ONE, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." reviewer = "RealiCZ" @@ -267,6 +302,8 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/test_utils/scenario.rs" +line = 240 +column = 13 mutant = "delete field basefee from struct BlockEnv expression in Scenario::block" justification = "Equivalent: the field writes 0 and revm 40's BlockEnv::default() already has basefee: 0, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." reviewer = "RealiCZ" @@ -275,6 +312,8 @@ reviewer = "RealiCZ" kind = "line" category = "equivalent" file = "crates/mega-evm/src/test_utils/scenario.rs" +line = 241 +column = 13 mutant = "delete field gas_limit from struct BlockEnv expression in Scenario::block" justification = "Equivalent: the field writes u64::MAX and revm 40's BlockEnv::default() already has gas_limit: u64::MAX, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." reviewer = "RealiCZ" diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 00ee9d354..cdfb32127 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -28,19 +28,57 @@ Consumed by scripts/mutation_test.sh to run those mutants against the Mega EEST suite. + progress --results + Print `expected= outcomes=`: how many mutants the run + planned (unknown before cargo-mutants wrote its plan) and how many have + an outcome. Used by scripts/mutation_test.sh for its status line. + + merge --inventory --out ... + Combine the results of a run split into shards (cargo mutants --shard) + into /mutants.out and /status, counted against + (`cargo mutants --list` of the whole run). Each holds one + shard's mutants.out/ and status; pass one per shard, including shards + that may have uploaded nothing. The merged mutants.out keeps the + contract below: `mutants.json` is the inventory, `outcomes.json` every + shard's outcomes and baselines, with an `end_time` only when every + shard finished and the run is complete; the outcome lists are written + beside it. Every shard's own status is folded into the merged status + and named in the report: a shard whose budget ran out makes the run + partial, one that failed its baseline makes it baseline-failed, and one + that errored, left no status or uploaded nothing makes it error. Every + shard outcome is kept. An outcome the inventory does not plan, a second + outcome for one mutant, or shard plans that do not add up to the + inventory mean the shards and the inventory disagree on the mutant set: + status mismatch. Only complete passes. + + merge-runs --out ... + Combine the shards' follow-up runs (the re-checks of timed-out mutants, + the Mega EEST runs of missed ones) into one record the report reads as + --recheck or --mega-eest: their selections and outcomes together, each + mutant's log copied beside them, an `end_time` only when every one + finished, and the abnormal-exit note of any one. Directories that do + not exist are skipped; with none, nothing is written. + report --results [--recheck ] - [--mega-eest ] + [--mega-eest ] [--status ] [--scope diff|full] [--suppressions ] [--comment ] [--summary ] Read the run outcomes, take the re-check's outcome for a mutant that timed out and the Mega EEST run's outcome for a mutant the tests - missed, apply line-scoped suppressions, compute the mutation score, + missed, apply line-scoped suppressions (each anchored to one mutant's + file:line:col and text), compute the mutation score, write a Markdown report, and exit non-zero if any unsuppressed survivor or timeout remains (the "no new survivors" gate). Exits 2, with a - report saying why, when the results cannot be scored. + report saying why, when the results cannot be scored. With --status + (the driver's MUTANTS-STATUS line), a run that did not test every + planned mutant also fails: what it did test is still reported, read + without the completeness checks below. --scope says what the run + covered, for the report's wording: `diff` (the default) for a PR's + changed lines, `full` for every mutant of the crate (the nightly runs). orphans --suppressions --universe - Flag suppressions that match no live mutant, and a locator-less line - suppression that matches more than one. + Flag suppressions that match no live mutant: a function pattern that + matches no mutant name, a line entry whose anchor (file, line, column + and text) is no mutant's, with the locations its text has moved to. The results a run leaves are read fail-closed, on the contract cargo-mutants 27 keeps and scripts/umutate.py keeps with it. Before it tests anything the @@ -63,15 +101,21 @@ scripts/mutation_test.sh writes into them when the run that wrote them exited abnormally, whatever else they hold. -The gate is intended to run diff-scoped (cargo mutants --in-diff), so every -mutant it sees lives on a line the PR changed; an unsuppressed survivor there is -a test gap the PR introduced. +A line suppression names one mutant: its `file`, `line` and `column`, and its +exact `mutant` text without the `file:line:col: ` prefix. The same text anywhere +else (a new `&&` in the function, or the reviewed one after the code above it +moved) stays gated; an entry without a well-formed anchor is refused (exit 2). + +The PR gate runs diff-scoped (cargo mutants --in-diff), so every mutant it sees +lives on a line the PR changed; an unsuppressed survivor there is a test gap the +PR introduced. """ from __future__ import annotations import argparse import json import re +import shutil import sys from collections import Counter @@ -115,14 +159,61 @@ ANSI = re.compile(r"\x1b\[[0-9;]*m") +# A mutant line as both engines write it: `file:line:col: text`. +LOCATOR = re.compile(r"^(?P[^:]+):(?P\d+):(?P\d+): (?P.+)$") + +Anchor = tuple[str, int, int, str] + + +class SuppressionError(Exception): + """suppressions.toml has an entry the gate cannot apply safely.""" + + +def mutant_anchor(line: str) -> Anchor | None: + """(file, line, column, text) of a mutant line; None if it has no locator.""" + m = LOCATOR.match(ANSI.sub("", line)) + return (m["file"], int(m["line"]), int(m["col"]), m["text"]) if m else None + + +def entry_anchor(e: dict) -> Anchor: + return (e["file"], e["line"], e["column"], e["mutant"].strip()) + + +def check_line_entry(e: dict) -> str | None: + """Why a line suppression cannot be applied, or None if it is well formed. + + A line entry names one mutant: its file, line and column, and its exact text. + Matching on the text alone would also cover the same mutation anywhere else in + the function, including code added after the review.""" + def positive(v: object) -> bool: + return isinstance(v, int) and not isinstance(v, bool) and v > 0 + text = e.get("mutant") + if not isinstance(text, str) or not text.strip(): + return "no `mutant` text" + if LOCATOR.match(text.strip()): + return "`mutant` carries a `file:line:col:` prefix; put the location in `line` and `column`" + if not isinstance(e.get("file"), str) or not e["file"]: + return "no `file`" + if not (positive(e.get("line")) and positive(e.get("column"))): + return "no `line` and `column` (positive integers) anchoring it to one mutant" + return None + + def load_suppressions(path: Path) -> tuple[list[dict], list[dict]]: - """Return (function_scoped, line_scoped) suppression entries.""" + """Return (function_scoped, line_scoped) suppression entries. + + Raises SuppressionError if a line entry is not anchored to one mutant.""" if not path or not path.exists(): return [], [] data = tomllib.loads(path.read_text()) entries = data.get("suppress", []) func = [e for e in entries if e.get("kind") == "function"] line = [e for e in entries if e.get("kind") == "line"] + bad = [f'{e.get("file", "?")}: "{str(e.get("mutant", ""))[:90]}": {why}' + for e in line if (why := check_line_entry(e))] + if bad: + raise SuppressionError(f"{len(bad)} line suppression(s) in {path} cannot be applied:\n" + + "\n".join(f" - {b}" for b in bad)) return func, line @@ -133,7 +224,7 @@ def cmd_exclude_re(args: argparse.Namespace) -> int: if not pattern: print(f"suppression for {e.get('file', '?')} missing 'pattern'", file=sys.stderr) return 1 - # Emitted as two lines so `mapfile` in the driver yields separate argv items. + # Two lines per pair: the driver reads one argument per line. print("--exclude-re") print(pattern) return 0 @@ -296,6 +387,282 @@ def load_run(results: Path) -> Run: return run +def load_tested(results: Path) -> Run: + """What a run that did not finish tested, without the completeness checks of load_run: + its outcomes.json if it wrote one, else its outcome lists, else nothing.""" + run = Run() + outcomes_path = results / "outcomes.json" + if outcomes_path.exists(): + try: + outcomes = json.loads(outcomes_path.read_text())["outcomes"] + except (json.JSONDecodeError, KeyError, TypeError) as err: + raise ResultsError(f"{outcomes_path} is not a mutation run's outcomes: {err!r}") from err + for outcome in outcomes: + if not isinstance(outcome, dict) or not isinstance(outcome.get("scenario"), dict): + continue + kind = MUTANT_SUMMARIES.get(outcome.get("summary")) + name = (outcome["scenario"].get("Mutant") or {}).get("name") + if kind and isinstance(name, str): + getattr(run, kind).append(name) + return run + for kind in MUTANT_SUMMARIES.values(): + getattr(run, kind).extend(read_lines(results / f"{kind}.txt")) + return run + + +# One file per cargo-mutants outcome; every tested mutant lands in exactly one. +OUTCOME_FILES = ("caught.txt", "missed.txt", "timeout.txt", "unviable.txt") + + +def progress(results: Path) -> tuple[int | None, int]: + """Return (planned mutants or None if no plan was written, mutants with an outcome). + + The outcomes are counted in outcomes.json, which cargo-mutants rewrites after every + outcome, or, without one, in the outcome lists.""" + plan = results / "mutants.json" + expected = len(json.loads(plan.read_text())) if plan.exists() else None + record = results / "outcomes.json" + if record.exists(): + outcomes = json.loads(record.read_text()).get("outcomes", []) + return expected, sum(1 for o in outcomes if isinstance(o, dict) and outcome_name(o)) + return expected, sum(len(read_lines(results / name)) for name in OUTCOME_FILES) + + +def cmd_progress(args: argparse.Namespace) -> int: + expected, outcomes = progress(Path(args.results)) + print(f"expected={'unknown' if expected is None else expected} outcomes={outcomes}") + return 0 + + +def read_status(path: Path) -> dict[str, str] | None: + """Parse the driver's `MUTANTS-STATUS key=value ...` line; None if absent.""" + if not path.exists(): + return None + for line in reversed(path.read_text().splitlines()): + if line.startswith("MUTANTS-STATUS "): + return dict(f.split("=", 1) for f in line.split()[1:] if "=" in f) + return None + + +# Why a shard (or a single run) did not test all of its mutants, by status. +# `no-status` and `no-artifact` are recorded by `merge` for a shard that left no +# status line or no directory at all. +SHARD_CAUSES = { + "partial": "its time budget ran out", + "not-started": "its time budget ran out before it tested any mutant", + "followup-stopped": "its time budget ran out in the re-check of a timed-out mutant or the " + "Mega EEST run of a missed one", + "baseline-failed": "the unmutated tree failed to build or to pass its tests", + "error": "the run itself failed", + "no-status": "it ended without a status line (cancelled, killed by the job timeout, " + "or crashed)", + "no-artifact": "it uploaded no results", +} +BUDGET_STATES = ("partial", "not-started", "followup-stopped") + + +def incomplete_note(status: dict[str, str]) -> str: + """Describe a run that did not test every planned mutant.""" + state, expected, outcomes = status.get("status"), status.get("expected"), status.get("outcomes") + tail = " The results below cover only the tested mutants, and an incomplete run never passes." + # A merged run names each shard that did not complete. + merged = "shards" in status + shard_states = [s for s in status.get("shards", "").split(",") if s] + problems = [(i, s) for i, s in enumerate(shard_states) if s != "complete"] + listed = "".join(f"\n- shard {i}: `{s}` — {SHARD_CAUSES.get(s, 'see its log')}" + for i, s in problems) + if merged and not shard_states: + return f"**Incomplete run** — no shard results were found ({expected} planned).{tail}" + if state == "mismatch": + why = [] + if status.get("unplanned", "0") != "0": + why.append(f"{status['unplanned']} shard outcome(s) are for mutants the inventory " + f"does not list") + if status.get("duplicated", "0") != "0": + why.append(f"{status['duplicated']} mutant(s) have more than one outcome") + planned = status.get("shards-planned", "unknown") + if planned not in ("unknown", expected): + why.append(f"the shards planned {planned} mutants") + return (f"**Shards and inventory disagree** — the inventory lists {expected} mutants, " + f"{outcomes} of them have an outcome, and {'; '.join(why)}. The shards did not " + f"test the inventory's mutant set, so this run never passes. Every shard outcome " + f"is still reported below; `unplanned.txt` in the run artifacts lists the " + f"outcomes that do not fit the inventory.{listed}") + budget_only = all(s in BUDGET_STATES for _, s in problems) + if state == "partial" and budget_only: + return (f"**Incomplete run** — the time budget ran out after {outcomes} of {expected} " + f"planned mutants; the rest were not tested.{tail}{listed}") + if state == "not-started" and budget_only: + return ("**Incomplete run** — the time budget ran out before any mutant was tested " + f"({expected} planned). Nothing below is a result, and an incomplete run " + f"never passes.{listed}") + if state == "followup-stopped" and budget_only: + return (f"**Incomplete run** — the {outcomes} planned mutants were tested, and the time " + f"budget ran out in the re-check of a timed-out mutant or the Mega EEST run of a " + f"missed one, so those are not decided.{tail}{listed}") + if problems: + return (f"**Incomplete run** — {outcomes} of {expected} planned mutants were tested; " + f"these shards did not complete:{listed}\n\n{tail.strip()}") + cause = SHARD_CAUSES.get(state or "", "see the run log") + return (f"**Run did not complete** (status `{state}`: {cause}; {outcomes} of {expected} " + f"mutants tested).{tail}") + + +def read_record(results: Path) -> tuple[list[dict], list[str], object, bool]: + """A results directory's outcomes, its selection, its end_time, and whether its run + exited abnormally; no outcomes for a directory without outcomes.json.""" + failed = (results / RUN_FAILED_NOTE).exists() + path = results / "outcomes.json" + if not path.exists(): + return [], read_selection(results) or [], None, failed + data = json.loads(path.read_text()) + outcomes = [o for o in data.get("outcomes", []) if isinstance(o, dict)] + return outcomes, read_selection(results) or [], data.get("end_time"), failed + + +def outcome_name(outcome: dict) -> str | None: + scenario = outcome.get("scenario") + if not isinstance(scenario, dict): + return None + name = (scenario.get("Mutant") or {}).get("name") + return name if isinstance(name, str) else None + + +def write_record(out: Path, outcomes: list[dict], selection: list[str], end_time: object) -> None: + """Write a record in cargo-mutants' contract, with the outcome lists beside it.""" + out.mkdir(parents=True, exist_ok=True) + (out / "mutants.json").write_text(json.dumps([{"name": m} for m in selection])) + (out / "outcomes.json").write_text(json.dumps({"outcomes": outcomes, "end_time": end_time})) + lists: dict[str, list[str]] = {f"{kind}.txt": [] for kind in MUTANT_SUMMARIES.values()} + for o in outcomes: + kind, name = MUTANT_SUMMARIES.get(o.get("summary")), outcome_name(o) + if kind and name: + lists[f"{kind}.txt"].append(name) + for file, items in lists.items(): + (out / file).write_text("".join(f"{m}\n" for m in items)) + + +def copy_logs(source: Path, out: Path, prefix: str, outcomes: list[dict]) -> list[dict]: + """Copy each outcome's log to `out/log/-` and point the outcome at the copy.""" + copied = [] + for o in outcomes: + o = dict(o) + log = o.get("log_path") + if isinstance(log, str) and (source / log).is_file(): + target = Path("log") / f"{prefix}-{Path(log).name}" + (out / target).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / log, out / target) + o["log_path"] = str(target) + copied.append(o) + return copied + + +def cmd_merge(args: argparse.Namespace) -> int: + inventory = [ANSI.sub("", m) for m in read_lines(Path(args.inventory))] + if not inventory: + print(f"ERROR: empty mutant inventory at {args.inventory}", file=sys.stderr) + return 2 + planned = Counter(inventory) + out = Path(args.out) + results = out / "mutants.out" + # Every shard outcome goes into the merged record, planned or not: a survivor + # must never be dropped on the way to the report. + outcomes: list[dict] = [] + seen: Counter[str] = Counter() + # Each shard's state, and its own plan (`expected`); the plans must add up to + # the inventory. + shard_states: list[str] = [] + shard_plans: list[int | None] = [] + finished = True + print("| shard | status |") + print("|---|---|") + for i, shard in enumerate(map(Path, args.shards)): + status = read_status(shard / "status") + if not shard.is_dir(): + shard_states.append("no-artifact") + else: + shard_states.append((status or {}).get("status", "no-status")) + line = " ".join(f"{k}={v}" for k, v in status.items()) if status else shard_states[-1] + print(f"| `{shard}` | {line} |") + plan = (status or {}).get("expected", "") + shard_plans.append(int(plan) if plan.isdigit() else None) + shard_outcomes, _, end_time, _ = read_record(shard / "mutants.out") + if shard_outcomes and not end_time: + finished = False + for o in copy_logs(shard / "mutants.out", results, f"shard{i}", shard_outcomes): + outcomes.append(o) + name = outcome_name(o) + if name is not None: + seen[name] += 1 + # The shards and the inventory must describe the same mutant set. An outcome + # for a mutant the inventory does not plan, more outcomes for a mutant than the + # inventory plans, or shard plans that do not add up to the inventory show they + # do not: completeness is measured against the inventory, so it proves nothing + # then, and the run cannot pass. + unplanned = [m for m in seen if m not in planned] + duplicated = [m for m in seen if m in planned and seen[m] > planned[m]] + plans_known = bool(shard_plans) and None not in shard_plans + shards_planned = sum(p for p in shard_plans if p is not None) if plans_known else None + expected = len(inventory) + tested = sum(min(n, planned[m]) for m, n in seen.items() if m in planned) + # The most specific cause wins: a mismatch, then a failed baseline, then any + # other shard failure. A shortfall that only budget-stopped shards explain is + # partial or not-started, as for a single run. + if unplanned or duplicated or (plans_known and shards_planned != expected): + state = "mismatch" + elif "baseline-failed" in shard_states: + state = "baseline-failed" + elif any(s not in ("complete", *BUDGET_STATES) for s in shard_states): + state = "error" + elif tested == expected and "followup-stopped" in shard_states: + state = "followup-stopped" + else: + state = "complete" if tested == expected else "partial" if tested else "not-started" + # The merged record says it finished only when every shard's did and the run is complete; + # the report reads anything else as what was tested, under the status's note. + write_record(results, outcomes, inventory, "merged" if state == "complete" and finished else None) + (out / "unplanned.txt").write_text("".join(f"{m}\n" for m in unplanned + duplicated)) + line = (f"MUTANTS-STATUS status={state} expected={expected} outcomes={tested} " + f"unplanned={len(unplanned)} duplicated={len(duplicated)} " + f"shards-planned={'unknown' if shards_planned is None else shards_planned} " + f"shards={','.join(shard_states)}") + (out / "status").write_text(line + "\n") + found = sum(s != "no-artifact" for s in shard_states) + print(f"\n{len(args.shards)} shard(s), {found} with results.\n") + for title, items in (("Not in the inventory", unplanned), ("More than one outcome", duplicated)): + if items: + print(f"{title} ({len(items)}):\n") + print("".join(f"- `{m}`\n" for m in items[:MAX_SURVIVORS_SHOWN])) + print(line) + return 0 + + +def cmd_merge_runs(args: argparse.Namespace) -> int: + out = Path(args.out) + present = [Path(d) for d in args.runs if Path(d).is_dir()] + if not present: + print(f"no runs to merge into {out}", file=sys.stderr) + return 0 + outcomes: list[dict] = [] + selection: list[str] = [] + finished = True + failed: list[str] = [] + for i, run in enumerate(present): + run_outcomes, run_selection, end_time, run_failed = read_record(run) + if run_failed: + failed.append(f"{run}: {(run / RUN_FAILED_NOTE).read_text().strip()}") + if not end_time: + finished = False + selection += run_selection + outcomes += copy_logs(run, out, f"run{i}", run_outcomes) + write_record(out, outcomes, selection, "merged" if finished else None) + if failed: + (out / RUN_FAILED_NOTE).write_text("; ".join(failed) + "\n") + print(f"merged {len(present)} run(s) into {out}: {len(selection)} mutant(s) selected, " + f"{'all finished' if finished else 'not all finished'}", file=sys.stderr) + return 0 + + def cmd_note_empty(args: argparse.Namespace) -> int: results = Path(args.results) if results.exists(): @@ -316,45 +683,16 @@ def cmd_note_empty(args: argparse.Namespace) -> int: return 0 -def line_suppressions(path: str | None) -> list[dict]: - """The line-scoped suppression entries, or none when no file is given.""" +def suppressed_anchors(path: str | None) -> set[Anchor]: + """The mutants the line suppressions name, by anchor; none when no file is given.""" if not path: - return [] - _, line_supp = load_suppressions(Path(path)) - return line_supp - - -def suppressed_names(path: str | None) -> set[str]: - """The mutants line-scoped suppressions name. - - A line suppression matches either the bare mutation text (`mutant` written - without a locator) or the full `file:line:col: text` line. The latter lets - two mutants that share identical source text be suppressed independently. - A bare text that is the body of more than one mutant fails the gate. - """ - return {e["mutant"].strip() for e in line_suppressions(path) if "mutant" in e} - - -def locatorless_matching_several(entries: list[dict], mutants: list[str]) -> list[str]: - """Locator-less line suppressions whose text is the body of more than one mutant. - - A bare `mutant` matches every mutant with that text. Two of them have to be - named with their `file:line:col` locators, or one suppression hides both. - """ - counts = Counter(mutant_body(name) for name in mutants) - found: list[str] = [] - for entry in entries: - text = str(entry.get("mutant", "")).strip() - # A locator is `file:line:col: text`; the bare text has no `: `. - if not text or ": " in text: - continue - if counts[text] > 1 and text not in found: - found.append(text) - return found + return set() + _, line = load_suppressions(Path(path)) + return {entry_anchor(e) for e in line} -def is_suppressed(name: str, supp: set[str]) -> bool: - return name in supp or mutant_body(name) in supp +def is_suppressed(name: str, anchors: set[Anchor]) -> bool: + return mutant_anchor(name) in anchors def cmd_timeout_re(args: argparse.Namespace) -> int: @@ -364,7 +702,7 @@ def cmd_timeout_re(args: argparse.Namespace) -> int: # Nothing to re-check; the gate reports why the results cannot be scored. print(f"no timed-out mutants to re-check: {err}", file=sys.stderr) return 0 - supp = suppressed_names(args.suppressions) + supp = suppressed_anchors(args.suppressions) for name in run.timeout: if is_suppressed(name, supp): continue @@ -386,7 +724,7 @@ def cmd_missed_re(args: argparse.Namespace) -> int: missed = list(run.missed) if recheck is not None: missed += [name for name in run.timeout if name in set(recheck.missed)] - supp = suppressed_names(args.suppressions) + supp = suppressed_anchors(args.suppressions) for name in missed: if is_suppressed(name, supp): continue @@ -406,39 +744,47 @@ def write_report(report: str, args: argparse.Namespace) -> None: def cmd_report(args: argparse.Namespace) -> int: results = Path(args.results) + full = getattr(args, "scope", "diff") == "full" + title = "## 🧬 Mutation testing (full run)" if full else "## 🧬 Mutation testing" + + # The driver's status says whether the run tested every planned mutant. A + # stopped run must never pass, even when everything it tested was caught; what + # it did test is still reported, read without the completeness checks. + note = None + status_path = getattr(args, "status", None) + if status_path: + run_status = read_status(Path(status_path)) + if run_status is None: + print(f"ERROR: no MUTANTS-STATUS line in {status_path}: the mutation run did not " + f"finish — refusing to report a passing gate.", file=sys.stderr) + return 2 + if run_status.get("status") != "complete": + note = incomplete_note(run_status) + + try: + anchors = suppressed_anchors(args.suppressions) + except SuppressionError as err: + print(f"ERROR: {err}", file=sys.stderr) + return 2 + try: - run = load_run(results) + run = load_tested(results) if note else load_run(results) recheck = None - if run.timeout and args.recheck and Path(args.recheck).exists(): + if not note and run.timeout and args.recheck and Path(args.recheck).exists(): recheck = load_run(Path(args.recheck)) except ResultsError as err: write_report( - "## 🧬 Mutation testing — ❌ FAIL\n\n" + f"{title} — ❌ FAIL\n\n" f"**The results cannot be scored:** {err}.\n", args, ) return 2 - if run.nothing_to_test is not None: - note = f"**Nothing to test**: {run.nothing_to_test}" - write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) + if run.nothing_to_test is not None and note is None: + nothing = f"**Nothing to test**: {run.nothing_to_test}" + write_report(f"{title} — ✅ PASS\n\n{nothing}.\n", args) return 0 - line_supp = line_suppressions(args.suppressions) - ambiguous = locatorless_matching_several( - line_supp, [*run.caught, *run.missed, *run.timeout, *run.unviable] - ) - if ambiguous: - listed = "\n".join(f"- `{text}`" for text in ambiguous) - write_report( - "## 🧬 Mutation testing — ❌ FAIL\n\n" - "A locator-less line suppression matches more than one mutant.\n" - "Name each with its `file:line:col` locator.\n\n" - f"{listed}\n", - args, - ) - return 1 - caught, missed, timeout = list(run.caught), list(run.missed), [] rechecked: dict[str, list[str]] = {"caught": [], "missed": [], "timeout": [], "absent": []} if recheck is not None: @@ -460,7 +806,7 @@ def cmd_report(args: argparse.Namespace) -> int: # A mutant the tests missed was run once more against the Mega EEST suite; one it catches is # caught, one it times out on is inconclusive, and the rest stay survivors. Its results speak # for those mutants alone, as a re-check's speak for the timeouts. - mega_eest_dir = getattr(args, "mega_eest", None) + mega_eest_dir = None if note else getattr(args, "mega_eest", None) against_eest: dict[str, list[str]] = {"caught": [], "missed": [], "timeout": [], "absent": []} eest = None if missed and mega_eest_dir and Path(mega_eest_dir).exists(): @@ -468,7 +814,7 @@ def cmd_report(args: argparse.Namespace) -> int: eest = load_run(Path(mega_eest_dir)) except ResultsError as err: write_report( - "## 🧬 Mutation testing — ❌ FAIL\n\n" + f"{title} — ❌ FAIL\n\n" f"**The Mega EEST run of the mutants the tests missed cannot be scored:** {err}.\n", args, ) @@ -489,12 +835,10 @@ def cmd_report(args: argparse.Namespace) -> int: against_eest["missed" if verdict else "absent"].append(name) missed = remaining - supp = {e["mutant"].strip() for e in line_supp if "mutant" in e} - def partition(items: list[str]) -> tuple[list[str], list[str]]: sup, real = [], [] for m in items: - (sup if is_suppressed(m, supp) else real).append(m) + (sup if is_suppressed(m, anchors) else real).append(m) return sup, real suppressed, real_survivors = partition(missed) @@ -507,7 +851,7 @@ def partition(items: list[str]) -> tuple[list[str], list[str]]: scored = viable - len(suppressed) # equivalents/dead-code excluded from denominator killed = len(caught) score = (killed / scored * 100.0) if scored else 100.0 - gate_pass = not real_survivors and not real_timeouts + gate_pass = not real_survivors and not real_timeouts and note is None # ---- Markdown report (PR comment + step summary) ---- status = "✅ PASS" if gate_pass else "❌ FAIL" @@ -515,16 +859,18 @@ def partition(items: list[str]) -> tuple[list[str], list[str]]: # No viable mutants and nothing inconclusive (every mutant unviable, or every # timeout suppressed). Reporting "100% (0/0)" reads like a real result and # confuses readers — say plainly that nothing was tested. - if viable == 0 and not real_timeouts: - note = "**Nothing to test** — no viable mutant" - note += f" ({len(run.unviable)} unviable, {len(timeout)} timed out)" - write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) + if viable == 0 and not real_timeouts and note is None: + nothing = "**Nothing to test** — no viable mutant" + nothing += f" ({len(run.unviable)} unviable, {len(timeout)} timed out)" + write_report(f"{title} — ✅ PASS\n\n{nothing}.\n", args) return 0 + label = "Full-run mutation score" if full else "Diff mutation score" md = [ - f"## 🧬 Mutation testing — {status}", + f"{title} — {status}", "", - f"**Diff mutation score: {score:.1f}%** ({killed}/{scored} viable mutants killed)", + *([note, ""] if note else []), + f"**{label}: {score:.1f}%** ({killed}/{scored} viable mutants killed)", "", f"- caught: {len(caught)}", f"- survived (real gaps): **{len(real_survivors)}**", @@ -581,8 +927,9 @@ def section(title: str, blurb: str, items: list[str], artifact: str) -> list[str ) if real_survivors or real_timeouts: md += ["", "_Tip: run `/improve-mutation-score` to triage and fix these._"] - else: - md.append("No new test gaps introduced by this change. 🎉") + elif note is None: + md.append("Every viable mutant was caught or suppressed. 🎉" if full + else "No new test gaps introduced by this change. 🎉") write_report("\n".join(md) + "\n", args) return 0 if gate_pass else 1 @@ -594,20 +941,20 @@ def cmd_orphans(args: argparse.Namespace) -> int: `--universe` is a file of mutant lines (`file:line:col: text`) covering the whole crate, assembled from BOTH engines (cargo-mutants `--list` and `umutate.py plan`). A function suppression's regex `pattern` must match at - least one mutant name; a line suppression's `mutant` must match one mutant - (bare body or full locator line). Otherwise the suppression is an orphan and - should be removed or updated.""" + least one mutant name; a line suppression must match the mutant at its + anchor (file, line, column and text). Otherwise the suppression is stale and + should be removed or re-anchored; for a line entry whose text now sits + elsewhere in its file, the new locations are listed.""" func, line = load_suppressions(Path(args.suppressions)) # Strip ANSI color codes defensively: `cargo mutants --list` colorizes its # output when CARGO_TERM_COLOR=always (as CI sets), which would otherwise make # every exact line-suppression "match nothing" and fail the check spuriously. - ansi = re.compile(r"\x1b\[[0-9;]*m") - universe = [ansi.sub("", m) for m in read_lines(Path(args.universe))] + universe = [ANSI.sub("", m) for m in read_lines(Path(args.universe))] if not universe: print(f"ERROR: empty mutant universe at {args.universe}", file=sys.stderr) return 2 bodies = {mutant_body(m) for m in universe} - full = set(universe) + anchors = {a for a in map(mutant_anchor, universe) if a} orphans: list[str] = [] for e in func: @@ -622,24 +969,21 @@ def cmd_orphans(args: argparse.Namespace) -> int: if not any(rx.search(b) for b in bodies): orphans.append(f'[function] {e.get("file", "?")}: pattern "{pat}"') for e in line: - m = e.get("mutant", "").strip() - if m and m not in bodies and m not in full: - orphans.append(f'[line] {e.get("file", "?")}: "{m[:90]}"') - ambiguous = locatorless_matching_several(line, universe) + anchor = entry_anchor(e) + if anchor in anchors: + continue + file, ln, col, text = anchor + moved = sorted((a[1], a[2]) for a in anchors if a[0] == file and a[3] == text) + hint = f" — the text is now at {', '.join(f'{l}:{c}' for l, c in moved)}" if moved else "" + orphans.append(f'[line] {file}:{ln}:{col}: "{text[:90]}"{hint}') total = len(func) + len(line) - if ambiguous: - print(f"❌ {len(ambiguous)} locator-less line suppression(s) each match more than one mutant.") - print("Name each with its file:line:col locator:") - for text in ambiguous: - print(f' - "{text[:90]}"') if orphans: print(f"❌ {len(orphans)}/{total} suppressions are stale (no live mutant matches).") - print("Remove or update these — a suppression that matches nothing is a " - "silent blind spot:") + print("Remove or re-anchor these — a suppression that matches nothing is a " + "silent blind spot, and a moved one no longer suppresses its mutant:") for o in orphans: print(f" - {o}") - if orphans or ambiguous: return 1 print(f"✅ all {total} suppressions match a live mutant.") return 0 @@ -669,6 +1013,22 @@ def main() -> int: pm.add_argument("--suppressions", default=None) pm.set_defaults(func=cmd_missed_re) + pp = sub.add_parser("progress", help="count planned and tested mutants") + pp.add_argument("--results", required=True) + pp.set_defaults(func=cmd_progress) + + pg = sub.add_parser("merge", help="combine sharded results against the full inventory") + pg.add_argument("--inventory", required=True, + help="file of all mutant lines of the run (cargo mutants --list)") + pg.add_argument("--out", required=True) + pg.add_argument("shards", nargs="*", help="one directory per shard: mutants.out/ + status") + pg.set_defaults(func=cmd_merge) + + pf = sub.add_parser("merge-runs", help="combine the shards' re-check or Mega EEST runs") + pf.add_argument("--out", required=True) + pf.add_argument("runs", nargs="*", help="one mutants.out directory per shard") + pf.set_defaults(func=cmd_merge_runs) + pr = sub.add_parser("report") pr.add_argument("--results", required=True) pr.add_argument("--recheck", default=None, @@ -676,6 +1036,10 @@ def main() -> int: pr.add_argument("--mega-eest", default=None, help="results of running the mutants the tests missed against Mega EEST") pr.add_argument("--suppressions", default=None) + pr.add_argument("--status", default=None, + help="the driver's status file; fail unless it says complete") + pr.add_argument("--scope", choices=("diff", "full"), default="diff", + help="what the run covered: a PR's changed lines, or every mutant") pr.add_argument("--comment", default=None, help="write Markdown report here") pr.add_argument("--summary", default=None, help="append report here (GITHUB_STEP_SUMMARY)") pr.set_defaults(func=cmd_report) @@ -687,7 +1051,11 @@ def main() -> int: po.set_defaults(func=cmd_orphans) args = p.parse_args() - return args.func(args) + try: + return args.func(args) + except SuppressionError as err: + print(f"ERROR: {err}", file=sys.stderr) + return 2 if __name__ == "__main__": diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index b0360f3cb..343a64aa2 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -3,26 +3,71 @@ # # Subcommands: # diff Mutate only lines changed vs (PR gate mode). -# full Mutate the whole mega-evm crate (nightly mode; slow). +# full [args...] Mutate the whole mega-evm crate (nightly mode; slow). +# Extra arguments go to cargo-mutants (e.g. `-f `, +# `--shard k/n`). # file Mutate files matching (local iteration). -# infra Mutate the test gates' own infrastructure (see INFRA_FILES below). +# infra [args...] Mutate the test gates' own infrastructure (see INFRA_FILES below). +# list [--all] [args...] +# Print the mutants `full` would test, one per line, without +# building or testing anything (`cargo mutants --list`). +# Extra arguments go to cargo-mutants, as for `full`. With +# --all, include the mutants of function-scoped suppressions, +# which the runs exclude. +# changed Print mutate=true if `diff ` would build, and +# mutate=false if it would find no mutatable change. CI uses +# it to decide whether to restore and save the build cache. # # `diff`, `full` and `file` run the production scope of .cargo/mutants.toml, which excludes test # helpers as noise. `infra` runs the second scope, .cargo/mutants-infra.toml: the scenario runner # is helper code by that rule, but the benches and later tests rest on it, so it is mutated on its # own. # +# Every run first builds the unmutated tests into ./target (the warm build), which +# cargo-mutants' `copy_target` copies into each scratch build directory; with +# incremental compilation on (CARGO_INCREMENTAL=1, which CI sets: the toolchain +# action turns it off), the copy carries mega-evm's incremental state too, so each +# mutant build recompiles only what its mutation changed. A diff with no mutatable +# change skips the warm build, since nothing will be built. +# # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). # When cargo-mutants has nothing to mutate and writes no results, which it does # when --in-diff leaves no mutant, the driver records its saying so there # instead. A mutant that timed out is re-run once, alone, into # $OUT_DIR/recheck/mutants.out/; a re-check that exits abnormally has its exit # recorded there, in run-failed.txt, and the gate refuses it. Run -# scripts/mutation_gate.py afterwards to score + gate the run, passing both. +# scripts/mutation_gate.py afterwards to score + gate the run, passing both and +# the status file below. +# +# Time budget: MUTANTS_BUDGET=, counted from this script's start, bounds +# the warm build, cargo-mutants and the re-check together (unset: no limit; +# needs GNU timeout). When it runs out, the running phase gets SIGINT, so +# cargo-mutants stops its in-flight mutants and keeps every outcome it has +# recorded; it gets SIGKILL if it is still running MUTANTS_GRACE seconds later. +# A re-check the budget stops has that recorded in its results +# (run-failed.txt). The script then exits 0 with what was tested, so the caller +# can still score and upload it. +# +# The last line printed, also written to $OUT_DIR/status, is +# MUTANTS-STATUS status= expected= outcomes= +# expected: mutants planned (unknown if the run stopped before cargo-mutants +# planned them); outcomes: mutants with an outcome; status is one of +# complete every planned mutant has an outcome, and no follow-up run +# was stopped; +# partial the budget ran out after some mutants were tested; +# not-started the budget ran out before any mutant was tested; +# followup-stopped every planned mutant was tested, and the budget ran out in +# the re-check of a timed-out one; +# baseline-failed the unmutated tree failed to build or to pass its tests; +# error the run itself failed (bad arguments, an internal error). +# Only baseline-failed and error exit non-zero. `mutation_gate.py report --status` +# fails the gate on anything but complete. # # MUTANTS_SHARD=k/n runs only shard k (0-based) of n of whichever mutant set the # subcommand selects (cargo-mutants' own --shard), for a diff too large for one -# job; give each shard its own OUT_DIR and gate each one. See REVIEW.md. +# job; give each shard its own OUT_DIR and gate each one. See REVIEW.md. The +# nightly full run passes `--shard k/n` to `full` instead, and +# `mutation_gate.py merge` scores the shards together. # # In the production scope (diff, full, file), a mutant the tests missed — in # the run, or in the re-check of one that timed out — is run once more against @@ -53,10 +98,6 @@ OUT_DIR="${OUT_DIR:-$ROOT_DIR/target/mutants}" cd "$ROOT_DIR" -# Clear the results before anything that can fail, so a run that stops early -# leaves nothing behind for the gate to mistake for its results. -rm -rf "$OUT_DIR" - SUPPRESS="${SUPPRESS:-$ROOT_DIR/mutants/suppressions.toml}" # The files cargo-mutants can mutate: the crate's Rust sources, at any depth. The # `:(glob)` magic lets `**/` match no directory, so the files at the top of src/ @@ -66,6 +107,8 @@ SRC_PATHSPEC=':(glob)crates/mega-evm/src/**/*.rs' JOBS="${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || getconf _NPROCESSORS_ONLN)}" PKG_ARGS=(--package mega-evm) CONFIG_ARGS=() +BUDGET="${MUTANTS_BUDGET:-}" +GRACE="${MUTANTS_GRACE:-120}" # The test gates' own executable logic: the scenario runner's transaction conversion and its # execute/commit loop. @@ -73,32 +116,76 @@ INFRA_FILES=( crates/mega-evm/src/test_utils/scenario.rs ) -if ! cargo mutants --version >/dev/null 2>&1; then - echo "cargo-mutants is required. Install with 'cargo install cargo-mutants --locked'." >&2 - exit 1 +cmd="${1:-}" +shift || true + +# The diff `diff` mutates: only the crate's Rust sources are mutatable, so a PR +# that touches only tests/, Cargo.toml or a module guide under src/ has nothing +# to mutate. +mutatable_diff() { + git diff --no-color "$1"...HEAD -- "$SRC_PATHSPEC" +} + +if [[ "$cmd" == changed ]]; then + base="${1:?usage: mutation_test.sh changed }" + # Read the diff into a variable: piping it into `grep -q` would fail the + # pipeline under pipefail when grep exits early. + changes="$(mutatable_diff "$base")" + if [[ -n "$changes" ]]; then echo "mutate=true"; else echo "mutate=false"; fi + exit 0 fi +require_cargo_mutants() { + if ! cargo mutants --version >/dev/null 2>&1; then + echo "cargo-mutants is required. Install with 'cargo install cargo-mutants --locked'." >&2 + exit 1 + fi +} + # Function-scoped suppressions become --exclude-re so they are never generated -# (saves build/test time). Line-scoped suppressions are filtered later by the gate. -# Capture into a variable first: `mapfile < <(...)` would mask a non-zero exit -# from the helper (a malformed suppressions.toml), letting the run continue -# without the function-scoped excludes. -if ! exclude_re_output="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" exclude-re --suppressions "$SUPPRESS")"; then - echo "failed to parse function suppressions from $SUPPRESS" >&2 - exit 1 -fi +# (saves build/test time), unless called with "all"; line-scoped suppressions are +# filtered later by the gate. Capture into a variable first: `mapfile < <(...)` +# would mask a non-zero exit from the helper (a malformed suppressions.toml), +# letting the run continue without the function-scoped excludes. EXCLUDE_ARGS=() -[[ -n "$exclude_re_output" ]] && mapfile -t EXCLUDE_ARGS <<< "$exclude_re_output" +load_excludes() { + local exclude_re_output + EXCLUDE_ARGS=() + [[ "${1:-}" != all ]] || return 0 + if ! exclude_re_output="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" exclude-re --suppressions "$SUPPRESS")"; then + echo "failed to read the suppressions in $SUPPRESS" >&2 + exit 1 + fi + [[ -n "$exclude_re_output" ]] && mapfile -t EXCLUDE_ARGS <<< "$exclude_re_output" + return 0 +} + +if [[ "$cmd" == list ]]; then + scope="" + if [[ "${1:-}" == --all ]]; then + scope=all + shift + fi + require_cargo_mutants + load_excludes "$scope" + # --colors never: CI forces CARGO_TERM_COLOR=always, and colour codes in the + # list would break the exact matching against it. + exec cargo mutants --list --colors never "${PKG_ARGS[@]}" "${EXCLUDE_ARGS[@]}" "$@" +fi + +# A listing (`infra --list`, which the suppression-hygiene job reads) writes no +# results and has no status. +LISTING="" +[[ " $* " == *" --list "* ]] && LISTING=1 SHARD_ARGS=() [[ -n "${MUTANTS_SHARD:-}" ]] && SHARD_ARGS=(--shard "$MUTANTS_SHARD") # cargo-mutants exit codes (https://mutants.rs/exit-codes.html): 0 = all caught, # 2 = missed mutants, 3 = timeouts. Those three are normal run outcomes that the -# gate (scripts/mutation_gate.py) is responsible for scoring, so swallow them and -# let the gate be the single source of truth for pass/fail. Everything else -# (1 usage, 4 baseline broken, 5/6 bad --in-diff, 70 internal) is a real failure -# of the run itself and must abort. +# gate (scripts/mutation_gate.py) is responsible for scoring. 4 means the unmutated +# tree failed its tests. Everything else (1 usage, 5/6 bad --in-diff, 70 internal) +# is a real failure of the run itself. run_outcome() { case "$1" in 0 | 2 | 3) return 0 ;; @@ -106,6 +193,89 @@ run_outcome() { esac } +# How the run ended, classified into a status by `finish`: ran, stopped (by the +# budget), baseline-failed. Any other exit, including one `set -e` forces, reports +# status=error. FOLLOWUP_STOPPED is set when the budget stopped a follow-up run. +RESULT="" +FOLLOWUP_STOPPED="" +# Set once this run has cleared the previous results; until then there is +# nothing of this run's to count. +CLEARED="" + +# shellcheck disable=SC2329 # the EXIT trap below runs it +finish() { + local rc=$? status=error expected=unknown outcomes=0 counts + if [[ -n "$CLEARED" ]] && counts="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" progress --results "$OUT_DIR/mutants.out")"; then + expected="${counts#expected=}" + expected="${expected%% *}" + outcomes="${counts##*outcomes=}" + fi + case "$RESULT" in + ran) + # cargo-mutants exits 0 without an output directory when no mutant + # intersects the diff: nothing was planned. + [[ "$expected" == unknown ]] && expected=0 + [[ "$expected" == "$outcomes" ]] && status=complete + ;; + stopped) + if [[ "$expected" == "$outcomes" ]]; then + status=complete + elif ((outcomes > 0)); then + status=partial + else + status=not-started + fi + ;; + baseline-failed) status=baseline-failed ;; + esac + [[ "$status" == complete && -n "$FOLLOWUP_STOPPED" ]] && status=followup-stopped + local line="MUTANTS-STATUS status=$status expected=$expected outcomes=$outcomes" + mkdir -p "$OUT_DIR" + echo "$line" > "$OUT_DIR/status" + echo + echo "$line" + if [[ "$status" == error || "$status" == baseline-failed ]] && ((rc == 0)); then + exit 1 + fi +} + +# Run "$@" within what is left of MUTANTS_BUDGET. Returns 124 if the budget +# stopped it (or had already run out), otherwise the command's exit status. +TIMEOUT="" +run_bounded() { + [[ -n "$BUDGET" ]] || { + "$@" + return + } + local left=$((BUDGET - SECONDS)) rc=0 + ((left > 0)) || return 124 + # GNU timeout signals the command's whole process group. cargo-mutants runs + # its cargo and test processes in their own groups and stops them itself. + "$TIMEOUT" --signal=INT --kill-after="$GRACE" "$left" "$@" || rc=$? + # 124: stopped by SIGINT; 137: killed after the grace period. + if ((rc == 137 && SECONDS >= BUDGET)); then rc=124; fi + return "$rc" +} +if [[ -n "$BUDGET" ]]; then + TIMEOUT="$(command -v timeout || command -v gtimeout || true)" + if [[ -z "$TIMEOUT" ]]; then + echo "MUTANTS_BUDGET needs GNU timeout (coreutils)." >&2 + exit 1 + fi +fi + +require_cargo_mutants +load_excludes + +if [[ -z "$LISTING" ]]; then + trap finish EXIT + # Clear the previous run's results before anything that can fail, so a run that + # stops early leaves nothing behind for the gate to mistake for its results. + rm -rf "$OUT_DIR" + mkdir -p "$OUT_DIR" + CLEARED=1 +fi + # The arguments that scope the first run (an `--in-diff` file, a `-f` glob): the # re-check and the Mega EEST run take them too. cargo-mutants 27.1.0 adds a # struct-field-deletion mutant without matching it against `--re`, so a run @@ -114,10 +284,11 @@ run_outcome() { # outcomes there the gate does not read. SCOPE_ARGS=() +# WARM=0 skips the warm build: a diff with no mutatable change builds nothing. +WARM=1 + run_mutants() { SCOPE_ARGS=("$@") - rm -rf "$OUT_DIR" - mkdir -p "$(dirname "$OUT_DIR")" # cargo-mutants creates OUT_DIR itself but not its parents # --no-shuffle: test mutants in deterministic source order so runs are # reproducible and comparable (recommended by https://mutants.rs/pr-diff.html). # -vV: verbose progress + version banner, for diagnosable CI logs. @@ -132,14 +303,34 @@ run_mutants() { "${SHARD_ARGS[@]}" "$@" ) - # A listing writes no results: there is nothing to record or re-check. - if [[ " $* " == *" --list "* ]]; then + # A listing writes no results: there is nothing to build, record or re-check. + if [[ -n "$LISTING" ]]; then cargo mutants "${args[@]}" return fi local rc=0 - cargo mutants "${args[@]}" 2>&1 | tee "$OUT_DIR.log" || rc=$? - run_outcome "$rc" || return + if [[ "$WARM" == 1 ]]; then + # Build the unmutated tests into ./target. `copy_target` copies it into every + # scratch build directory, so the mutant builds reuse the compiled dependencies + # and, with incremental compilation, the compiled mega-evm too. + echo "Warm build (CARGO_INCREMENTAL=${CARGO_INCREMENTAL-unset}, budget ${BUDGET:-none}s)" + run_bounded cargo nextest run "${PKG_ARGS[@]}" --all-features --no-run || rc=$? + case "$rc" in + 0) ;; + 124) RESULT=stopped && return 0 ;; + *) RESULT=baseline-failed && return "$rc" ;; + esac + fi + run_bounded cargo mutants "${args[@]}" 2>&1 | tee "$OUT_DIR.log" || rc=$? + case "$rc" in + 0 | 2 | 3) RESULT=ran ;; + 124) + RESULT=stopped + return 0 + ;; + 4) RESULT=baseline-failed && return "$rc" ;; + *) return "$rc" ;; + esac python3 "$ROOT_DIR/scripts/mutation_gate.py" note-empty \ --log "$OUT_DIR.log" --results "$OUT_DIR/mutants.out" recheck_timeouts @@ -149,6 +340,23 @@ run_mutants() { fi } +# A follow-up run that did not finish as a run proves nothing by the files it +# left, which can look like a finished run's: its exit, or the budget that +# stopped it, goes into its results, which the gate then refuses to score, saying +# why, rather than the job ending here without a report. +record_failed_followup() { + local results=$1 rc=$2 what=$3 + mkdir -p "$results" + if [[ "$rc" == 124 ]]; then + FOLLOWUP_STOPPED=1 + echo "$what was stopped by MUTANTS_BUDGET" >&2 + echo "stopped by MUTANTS_BUDGET (${BUDGET}s)" > "$results/run-failed.txt" + else + echo "$what failed (exit $rc)" >&2 + echo "cargo-mutants exited $rc" > "$results/run-failed.txt" + fi +} + # A mutant that timed out was tested beside $JOBS others, each running the whole # suite on the same cores, so it may have timed out on the contention alone. # Re-run each once, alone; the gate takes that outcome for it. One that is @@ -166,7 +374,7 @@ recheck_timeouts() { mapfile -t re_args <<< "$re_output" echo "Re-checking $((${#re_args[@]} / 2)) timed-out mutant(s) one at a time" >&2 local rc=0 - cargo mutants \ + run_bounded cargo mutants \ "${CONFIG_ARGS[@]}" \ "${PKG_ARGS[@]}" \ --jobs 1 \ @@ -175,14 +383,9 @@ recheck_timeouts() { -vV \ "${SCOPE_ARGS[@]}" \ "${re_args[@]}" 2>&1 | tee "$OUT_DIR/recheck.log" || rc=$? - # A re-check that fails as a run proves nothing by the files it left, which - # can look like a finished run's. Its exit goes into its results, which the - # gate then refuses to score, saying why, rather than the job ending here - # without a report. if ! run_outcome "$rc"; then - echo "the re-check of the timed-out mutants failed (exit $rc); see $OUT_DIR/recheck.log" >&2 - mkdir -p "$OUT_DIR/recheck/mutants.out" - echo "cargo-mutants exited $rc" > "$OUT_DIR/recheck/mutants.out/run-failed.txt" + record_failed_followup "$OUT_DIR/recheck/mutants.out" "$rc" \ + "the re-check of the timed-out mutants (see $OUT_DIR/recheck.log)" fi } @@ -240,19 +443,16 @@ run_missed_against_mega_eest() { fi } -cmd="${1:-}" -shift || true case "$cmd" in diff) base="${1:?usage: mutation_test.sh diff }" diff_file="$OUT_DIR.diff" mkdir -p "$(dirname "$diff_file")" - # Only the crate's Rust sources are mutatable; scoping the diff to them - # avoids a non-empty diff (and a wasted run) when a PR touches only tests/, - # Cargo.toml or a module guide under src/. An empty diff still goes to - # cargo-mutants, which says it has nothing to mutate, so the gate passes on - # its word rather than on missing results. - git diff --no-color "$base"...HEAD -- "$SRC_PATHSPEC" > "$diff_file" + mutatable_diff "$base" > "$diff_file" + # An empty diff still goes to cargo-mutants, which says it has nothing to + # mutate, so the gate passes on its word rather than on missing results; it + # builds nothing, so the warm build is skipped. + [[ -s "$diff_file" ]] || WARM=0 run_mutants --in-diff "$diff_file" ;; full) @@ -269,11 +469,16 @@ case "$cmd" in run_mutants "${FILE_ARGS[@]}" "$@" ;; *) - echo "usage: mutation_test.sh {diff |full|file |infra}" >&2 + echo "usage: mutation_test.sh {diff |full [args...]|file |infra [args...]|list [--all] [args...]|changed }" >&2 exit 2 ;; esac +[[ -n "$LISTING" ]] && exit 0 +if [[ "$RESULT" == stopped ]]; then + echo + echo "MUTANTS_BUDGET (${BUDGET}s) ran out; the results cover only the mutants tested so far." +fi echo echo "Mutation results written to $OUT_DIR/mutants.out/" -echo "Score + gate with: python3 scripts/mutation_gate.py report --results $OUT_DIR/mutants.out --recheck $OUT_DIR/recheck/mutants.out --mega-eest $OUT_DIR/mega-eest/mutants.out" +echo "Score + gate with: python3 scripts/mutation_gate.py report --results $OUT_DIR/mutants.out --recheck $OUT_DIR/recheck/mutants.out --mega-eest $OUT_DIR/mega-eest/mutants.out --status $OUT_DIR/status" diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index aabf79025..6b41ad139 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -100,6 +100,20 @@ def mutants_json(*names: str) -> str: return json.dumps([{"name": n, "file": n.split(":", 1)[0]} for n in names]) +def line_entry(file: str, line: int | None, column: int | None, text: str) -> str: + """One `kind = "line"` suppression; None leaves that anchor field out.""" + out = f'[[suppress]]\nkind = "line"\nfile = "{file}"\n' + out += f"line = {line}\n" if line is not None else "" + out += f"column = {column}\n" if column is not None else "" + return out + f'mutant = "{text}"\n' + + +def anchored_entry(mutant_line: str) -> str: + """The suppression anchored to a mutant line `file:line:col: text`.""" + file, line, col, text = re.match(r"^([^:]+):(\d+):(\d+): (.+)$", mutant_line).groups() + return line_entry(file, int(line), int(col), text) + + class GateCase(unittest.TestCase): def setUp(self) -> None: self.tmp = Path(tempfile.mkdtemp(prefix="mutation-gate-test-")) @@ -120,30 +134,35 @@ def results(self, name: str = "mutants.out", outcomes: dict | None = None, if selected is not None: (path / "mutants.json").write_text(mutants_json(*selected)) for file, text in files.items(): + (path / file).parent.mkdir(parents=True, exist_ok=True) (path / file).write_text(text) return path def suppressions(self, *mutants: str) -> Path: + """Line suppressions, each anchored to the mutant line given (`file:line:col: text`).""" path = self.tmp / "suppressions.toml" - entries = [f'[[suppress]]\nkind = "line"\nfile = "x"\nmutant = "{m}"\n' for m in mutants] - path.write_text("\n".join(entries)) + path.write_text("\n".join(anchored_entry(m) for m in mutants)) return path def report(self, results: Path, recheck: Path | None = None, suppressions: Path | None = None, - mega_eest: Path | None = None) -> tuple[int, str]: + mega_eest: Path | None = None, status: Path | None = None, + scope: str = "diff") -> tuple[int, str]: comment = self.tmp / "comment.md" + comment.unlink(missing_ok=True) args = Namespace( results=str(results), recheck=str(recheck) if recheck else None, mega_eest=str(mega_eest) if mega_eest else None, + status=str(status) if status else None, + scope=scope, suppressions=str(suppressions) if suppressions else None, comment=str(comment), summary=None, ) with contextlib.redirect_stdout(io.StringIO()): code = gate.cmd_report(args) - text = comment.read_text() + text = comment.read_text() if comment.exists() else "" return code, text @@ -319,27 +338,52 @@ def test_a_survivor_fails(self) -> None: def test_a_suppressed_survivor_passes(self) -> None: results = self.results(outcomes=outcomes_json( mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) - for suppressed in (MISSED, gate.mutant_body(MISSED)): - code, text = self.report(results, suppressions=self.suppressions(suppressed)) - self.assertEqual(code, 0, text) + code, text = self.report(results, suppressions=self.suppressions(MISSED)) + self.assertEqual(code, 0, text) + self.assertIn("suppressed (equivalent/dead-code): 1", text) - def test_a_locatorless_suppression_of_two_mutants_fails(self) -> None: - body = gate.mutant_body(MISSED) - other = f"crates/mega-evm/src/b.rs:4:1: {body}" + def test_an_anchored_suppression_leaves_the_same_text_elsewhere_gated(self) -> None: + # A new `+` added to a function with a suppressed `+` mutant: same text, another + # column. Only the reviewed mutant is suppressed. + added = f"crates/mega-evm/src/a.rs:7:30: {gate.mutant_body(MISSED)}" results = self.results(outcomes=outcomes_json( - mutant(MISSED, "MissedMutant"), mutant(other, "CaughtMutant"))) - code, text = self.report(results, suppressions=self.suppressions(body)) + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"), mutant(added, "MissedMutant"))) + code, text = self.report(results, suppressions=self.suppressions(MISSED)) + self.assertEqual(code, 1, text) + self.assertIn("survived (real gaps): **1**", text) + self.assertIn(f"`{added}`", text) + self.assertNotIn(f"`{MISSED}`", text) + + def test_a_moved_mutant_is_gated_again(self) -> None: + moved = f"crates/mega-evm/src/a.rs:3:5: {gate.mutant_body(MISSED)}" + results = self.results(outcomes=outcomes_json(mutant(moved, "MissedMutant"))) + code, text = self.report(results, suppressions=self.suppressions(MISSED)) self.assertEqual(code, 1, text) - self.assertIn("more than one mutant", text) - self.assertIn(body, text) + self.assertIn(f"`{moved}`", text) - def test_located_suppressions_of_one_shared_text_pass(self) -> None: - body = gate.mutant_body(MISSED) - other = f"crates/mega-evm/src/b.rs:4:1: {body}" - results = self.results(outcomes=outcomes_json( - mutant(MISSED, "MissedMutant"), mutant(other, "MissedMutant"))) - code, text = self.report(results, suppressions=self.suppressions(MISSED, other)) - self.assertEqual(code, 0, text) + def test_an_anchor_needs_the_same_text_and_file(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + for entry in (line_entry("crates/mega-evm/src/a.rs", 2, 5, "replace + with * in g"), + line_entry("crates/mega-evm/src/b.rs", 2, 5, gate.mutant_body(MISSED))): + path = self.tmp / "suppressions.toml" + path.write_text(entry) + code, text = self.report(results, suppressions=path) + self.assertEqual(code, 1, (entry, text)) + + def test_unanchored_line_suppressions_are_refused(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + a_rs, body = "crates/mega-evm/src/a.rs", gate.mutant_body(MISSED) + for entry, why in ((line_entry(a_rs, None, None, body), "`line` and `column`"), + (line_entry(a_rs, 2, None, body), "`line` and `column`"), + (line_entry(a_rs, 0, 5, body), "`line` and `column`"), + (line_entry(a_rs, 2, 5, MISSED), "`file:line:col:` prefix")): + path = self.tmp / "suppressions.toml" + path.write_text(entry) + err = io.StringIO() + with contextlib.redirect_stderr(err): + code, _ = self.report(results, suppressions=path) + self.assertEqual(code, 2, entry) + self.assertIn(why, err.getvalue()) def test_a_timeout_without_a_recheck_fails(self) -> None: results = self.results(outcomes=outcomes_json( @@ -660,6 +704,7 @@ def bash5() -> str | None: # for, by its output directory — the first run, the re-check or the Mega EEST run — records the # arguments it was given in .argv, and exits as the test says. FAKE_CARGO = """#!/bin/sh +if [ "$1" = nextest ]; then echo "$*" > "$FAKE_RUNS/warm.argv"; exit "${FAKE_WARM_EXIT:-0}"; fi [ "$1" = mutants ] || exit 99 shift if [ "$1" = --version ]; then echo "cargo-mutants 27.1.0"; exit 0; fi @@ -817,6 +862,102 @@ def test_the_pass_can_be_left_out(self) -> None: self.assertIn(MISSED, text) +# A stand-in for GNU timeout: it runs the command, or answers 124 (stopped) for one whose +# arguments contain $FAKE_STOP. +FAKE_TIMEOUT = """#!/bin/sh +shift 3 +case "$*" in *"${FAKE_STOP:-no such argument}"*) exit 124 ;; esac +exec "$@" +""" + + +class DriverRun(GateCase): + """scripts/mutation_test.sh builds the tests first, bounds its phases by MUTANTS_BUDGET and + ends with a MUTANTS-STATUS line, as main's driver does, and keeps this branch's re-check.""" + + def drive(self, *args: str, main: dict | None = None, recheck: dict | None = None, + env: dict[str, str] | None = None) -> tuple[subprocess.CompletedProcess, Path, Path]: + shell = bash5() + if shell is None: + self.skipTest("no bash 5 or newer on this machine") + runs = self.tmp / "runs" + runs.mkdir(exist_ok=True) + if main is not None: + self.results("runs/main", outcomes=main) + (runs / "main.exit").write_text("0\n") + if recheck is not None: + self.results("runs/recheck", outcomes=recheck) + (runs / "recheck.exit").write_text("0\n") + bin_dir = self.tmp / "bin" + bin_dir.mkdir(exist_ok=True) + for name, text in (("cargo", FAKE_CARGO), ("timeout", FAKE_TIMEOUT)): + (bin_dir / name).write_text(text) + (bin_dir / name).chmod(0o755) + if not (bin_dir / "python3").exists(): + (bin_dir / "python3").symlink_to(sys.executable) + out = self.tmp / "out" / "mutants" + run = subprocess.run( + [shell, str(DriverGuard.DRIVER), *args], capture_output=True, text=True, timeout=120, + env={"PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_RUNS": str(runs), "OUT_DIR": str(out), + "JOBS": "1", "SUPPRESS": str(self.tmp / "no-suppressions.toml"), + "MUTANTS_MEGA_EEST": "0", **(env or {})}) + return run, runs, out + + def test_a_finished_run_builds_first_and_reports_complete(self) -> None: + run, runs, out = self.drive("file", "crates/mega-evm/src/a.rs", main=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable"))) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual((runs / "warm.argv").read_text().strip(), + "nextest run --package mega-evm --all-features --no-run") + self.assertEqual((out / "status").read_text().strip(), + "MUTANTS-STATUS status=complete expected=2 outcomes=2") + self.assertTrue(run.stdout.strip().endswith("MUTANTS-STATUS status=complete expected=2 outcomes=2")) + + def test_a_warm_build_that_fails_is_a_failed_baseline(self) -> None: + run, runs, out = self.drive("file", "crates/mega-evm/src/a.rs", main=outcomes_json( + mutant(CAUGHT, "CaughtMutant")), env={"FAKE_WARM_EXIT": "101"}) + self.assertEqual(run.returncode, 101, run.stderr) + self.assertFalse((runs / "main.argv").exists()) + self.assertIn("status=baseline-failed", (out / "status").read_text()) + + def test_a_spent_budget_stops_before_the_build(self) -> None: + run, runs, out = self.drive("file", "crates/mega-evm/src/a.rs", main=outcomes_json( + mutant(CAUGHT, "CaughtMutant")), env={"MUTANTS_BUDGET": "0"}) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertFalse((runs / "warm.argv").exists()) + self.assertEqual((out / "status").read_text().strip(), + "MUTANTS-STATUS status=not-started expected=unknown outcomes=0") + self.assertIn("ran out", run.stdout) + + def test_a_re_check_the_budget_stops_is_recorded_and_refused(self) -> None: + run, _, out = self.drive( + "file", "crates/mega-evm/src/a.rs", + main=outcomes_json(mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout")), + recheck=outcomes_json(mutant(TIMEOUT, "CaughtMutant")), + env={"MUTANTS_BUDGET": "3600", "FAKE_STOP": "/recheck"}) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual((out / "status").read_text().strip(), + "MUTANTS-STATUS status=followup-stopped expected=2 outcomes=2") + self.assertEqual((out / "recheck" / "mutants.out" / "run-failed.txt").read_text(), + "stopped by MUTANTS_BUDGET (3600s)\n") + code, text = self.report(out / "mutants.out", out / "recheck" / "mutants.out", + status=out / "status") + self.assertEqual(code, 1, text) + self.assertIn("re-check of a timed-out mutant", text) + + def test_list_names_the_mutant_set_without_running(self) -> None: + supp = self.tmp / "no-suppressions.toml" + supp.write_text('[[suppress]]\nkind = "function"\nfile = "a"\npattern = "in f$"\n') + run, runs, out = self.drive("list") + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual((runs / "main.argv").read_text().strip(), + "--list --colors never --package mega-evm --exclude-re in f$") + run, runs, _ = self.drive("list", "--all") + self.assertEqual((runs / "main.argv").read_text().strip(), + "--list --colors never --package mega-evm") + self.assertFalse((runs / "warm.argv").exists()) + + class DriverGuard(unittest.TestCase): """scripts/mutation_test.sh refuses to run on a shell that is not bash 5 or newer.""" @@ -854,29 +995,348 @@ def test_an_old_bash_is_refused(self) -> None: class OrphanSuppressions(GateCase): - """A suppression must name live mutants, and a bare line must name one.""" + """A suppression must name a live mutant: a line entry at its anchor.""" - def orphans(self, suppressions: Path, universe: list[str]) -> tuple[int, str]: + def orphans(self, entries: str, universe: list[str]) -> tuple[int, str]: path = self.tmp / "universe.txt" path.write_text("".join(f"{line}\n" for line in universe)) - args = Namespace(suppressions=str(suppressions), universe=str(path)) + supp = self.tmp / "suppressions.toml" + supp.write_text(entries) + args = Namespace(suppressions=str(supp), universe=str(path)) buf = io.StringIO() - with contextlib.redirect_stdout(buf): - code = gate.cmd_orphans(args) + with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(io.StringIO()): + try: + code = gate.cmd_orphans(args) + except gate.SuppressionError: + code = 2 return code, buf.getvalue() - def test_a_locatorless_line_suppression_matching_two_mutants_fails(self) -> None: - body = gate.mutant_body(MISSED) - other = f"crates/mega-evm/src/b.rs:4:1: {body}" - code, text = self.orphans(self.suppressions(body), [MISSED, other]) + BODY = "replace + with - in g" + A_RS = "crates/mega-evm/src/a.rs" + UNIVERSE = [CAUGHT, f"crates/mega-evm/src/a.rs:3:1: replace + with - in g", UNVIABLE] + + def test_an_entry_at_its_anchor_is_live(self) -> None: + code, text = self.orphans(line_entry(self.A_RS, 3, 1, self.BODY), self.UNIVERSE) + self.assertEqual(code, 0, text) + + def test_a_moved_entry_is_reported_with_where_its_text_went(self) -> None: + code, text = self.orphans(line_entry(self.A_RS, 2, 1, self.BODY), self.UNIVERSE) + self.assertEqual(code, 1, text) + self.assertIn(f"{self.A_RS}:2:1", text) + self.assertIn("the text is now at 3:1", text) + + def test_an_anchor_whose_text_changed_is_reported(self) -> None: + code, text = self.orphans(line_entry(self.A_RS, 3, 1, "replace + with * in g"), self.UNIVERSE) + self.assertEqual(code, 1, text) + self.assertNotIn("now at", text) + + def test_an_unanchored_entry_is_refused(self) -> None: + code, _ = self.orphans(line_entry(self.A_RS, None, None, self.BODY), self.UNIVERSE) + self.assertEqual(code, 2) + + def test_a_function_pattern_must_match_a_mutant(self) -> None: + live = '[[suppress]]\nkind = "function"\nfile = "a"\npattern = "in g$"\n' + dead = '[[suppress]]\nkind = "function"\nfile = "a"\npattern = "in nowhere$"\n' + self.assertEqual(self.orphans(live, self.UNIVERSE)[0], 0) + code, text = self.orphans(dead, self.UNIVERSE) self.assertEqual(code, 1, text) - self.assertIn("more than one mutant", text) + self.assertIn("[function]", text) + + +class ExcludeRe(GateCase): + """Function suppressions become one `--exclude-re` pair each.""" + + def test_one_pair_per_function_suppression(self) -> None: + path = self.tmp / "suppressions.toml" + path.write_text('[[suppress]]\nkind = "function"\npattern = "foo"\n\n' + + anchored_entry(MISSED)) + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = gate.cmd_exclude_re(Namespace(suppressions=str(path))) + self.assertEqual(code, 0) + self.assertEqual(out.getvalue().splitlines(), ["--exclude-re", "foo"]) - def test_a_located_line_suppression_matches_one_of_two(self) -> None: - body = gate.mutant_body(MISSED) - other = f"crates/mega-evm/src/b.rs:4:1: {body}" - code, text = self.orphans(self.suppressions(MISSED), [MISSED, other]) + +class Progress(GateCase): + """`progress` counts what a run planned and what has an outcome so far.""" + + def progress(self, results: Path) -> str: + out = io.StringIO() + with contextlib.redirect_stdout(out): + gate.cmd_progress(Namespace(results=str(results))) + return out.getvalue().strip() + + def test_before_any_output(self) -> None: + self.assertEqual(self.progress(self.tmp / "absent"), "expected=unknown outcomes=0") + + def test_counts_the_outcomes_the_record_holds(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"), end_time=None), + selected=[CAUGHT, MISSED, UNVIABLE]) + self.assertEqual(self.progress(results), "expected=3 outcomes=2") + + def test_counts_the_plan_and_the_outcome_lists(self) -> None: + results = self.results(selected=[CAUGHT, MISSED, UNVIABLE, TIMEOUT, "x"], files={ + "caught.txt": f"{CAUGHT}\n", "missed.txt": f"{MISSED}\n", "unviable.txt": f"{UNVIABLE}\n"}) + self.assertEqual(self.progress(results), "expected=5 outcomes=3") + + +def status_file(path: Path, line: str) -> Path: + path.write_text(f"MUTANTS-STATUS {line}\n") + return path + + +class Status(GateCase): + """With the driver's status, a run that did not test every planned mutant never passes.""" + + def test_a_complete_run_passes(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable"))) + code, text = self.report(results, status=status_file( + self.tmp / "status", "status=complete expected=2 outcomes=2")) self.assertEqual(code, 0, text) + self.assertNotIn("Incomplete", text) + + def test_a_complete_run_still_gates_survivors_and_completeness(self) -> None: + status = status_file(self.tmp / "status", "status=complete expected=2 outcomes=2") + survivor = self.results("survivor", outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) + self.assertEqual(self.report(survivor, status=status)[0], 1) + # The status says complete, the record says the run stopped: the record is refused. + stopped = self.results("stopped", outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), end_time=None)) + self.assertEqual(self.report(stopped, status=status)[0], 2) + + def test_a_partial_run_fails_even_when_all_it_tested_was_caught(self) -> None: + # The budget stopped cargo-mutants: no end_time, a mutant of the plan untested. + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable"), end_time=None), + selected=[CAUGHT, UNVIABLE, MISSED]) + code, text = self.report(results, status=status_file( + self.tmp / "status", "status=partial expected=3 outcomes=2")) + self.assertEqual(code, 1, text) + self.assertIn("Incomplete run", text) + self.assertIn("2 of 3", text) + self.assertIn("caught: 1", text) # what it tested is still reported + + def test_a_run_not_started_fails(self) -> None: + code, text = self.report(self.tmp / "absent", status=status_file( + self.tmp / "status", "status=not-started expected=unknown outcomes=0")) + self.assertEqual(code, 1, text) + self.assertIn("before any mutant was tested", text) + self.assertNotIn("PASS", text) + + def test_a_follow_up_the_budget_stopped_fails(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"))) + code, text = self.report(results, status=status_file( + self.tmp / "status", "status=followup-stopped expected=1 outcomes=1")) + self.assertEqual(code, 1, text) + self.assertIn("re-check of a timed-out mutant or the Mega EEST run", text) + + def test_a_missing_status_line_is_refused(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"))) + err = io.StringIO() + with contextlib.redirect_stderr(err): + code, _ = self.report(results, status=self.tmp / "no-status") + self.assertEqual(code, 2) + self.assertIn("MUTANTS-STATUS", err.getvalue()) + + def test_an_empty_diff_with_the_producers_word_passes(self) -> None: + results = self.results(files={gate.NO_MUTANTS_NOTE: "INFO Diff file is empty\n"}) + code, text = self.report(results, status=status_file( + self.tmp / "status", "status=complete expected=0 outcomes=0")) + self.assertEqual(code, 0, text) + + def test_a_full_run_is_titled_as_one(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable"))) + code, text = self.report(results, scope="full") + self.assertEqual(code, 0, text) + self.assertIn("## 🧬 Mutation testing (full run) — ✅ PASS", text) + self.assertIn("**Full-run mutation score: 100.0%** (1/1", text) + self.assertNotIn("this change", text) + self.assertIn("**Diff mutation score: 100.0%**", self.report(results)[1]) + + +class Merge(GateCase): + """Sharded results merge into one record, counted against the inventory.""" + + def shard(self, name: str, status: str | None, *outcomes: dict, finished: bool = True) -> Path: + """One shard's artifact: its mutants.out (the run's record) and status line.""" + shard = self.tmp / name + if outcomes: + self.results(f"{name}/mutants.out", outcomes=outcomes_json( + *outcomes, end_time=FINISHED if finished else None)) + else: + shard.mkdir(parents=True) + if status is not None: + status_file(shard / "status", status) + return shard + + def merge(self, *shards: Path) -> str: + inventory = self.tmp / "inventory.txt" + # `cargo mutants --list` output, with the colour codes CI can leave in it. + inventory.write_text(f"\x1b[33m{CAUGHT}\x1b[0m\n{MISSED}\n{UNVIABLE}\n") + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = gate.cmd_merge(Namespace(inventory=str(inventory), out=str(self.tmp / "merged"), + shards=[str(s) for s in shards])) + self.assertEqual(code, 0) + return out.getvalue() + + def merged(self) -> tuple[int, str]: + merged = self.tmp / "merged" + return self.report(merged / "mutants.out", status=merged / "status", scope="full") + + def status(self) -> str: + return (self.tmp / "merged" / "status").read_text().strip() + + def test_every_shard_complete_is_a_complete_run_scored_strictly(self) -> None: + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable")) + b = self.shard("b", "status=complete expected=1 outcomes=1", mutant(MISSED, "CaughtMutant")) + self.merge(a, b) + self.assertEqual(self.status(), "MUTANTS-STATUS status=complete expected=3 outcomes=3 " + "unplanned=0 duplicated=0 shards-planned=3 shards=complete,complete") + merged = self.tmp / "merged" / "mutants.out" + self.assertEqual((merged / "caught.txt").read_text().splitlines(), [CAUGHT, MISSED]) + # The merged record keeps the contract: the strict reading accepts it. + self.assertEqual(sorted(gate.load_run(merged).caught), sorted([CAUGHT, MISSED])) + code, text = self.merged() + self.assertEqual(code, 0, text) + + def test_a_shard_without_an_artifact_is_named(self) -> None: + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable")) + self.merge(a, self.tmp / "never-uploaded") + self.assertIn("status=error expected=3 outcomes=2 ", self.status()) + self.assertIn("shards=complete,no-artifact", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("shard 1: `no-artifact` — it uploaded no results", text) + self.assertNotIn("time budget", text) + + def test_a_baseline_failed_shard_is_named_not_blamed_on_the_budget(self) -> None: + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable")) + b = self.shard("b", "status=baseline-failed expected=unknown outcomes=0") + self.merge(a, b) + self.assertIn("status=baseline-failed expected=3 outcomes=2 ", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("shard 1: `baseline-failed` — the unmutated tree failed", text) + + def test_shard_failures_outrank_a_budget_stop(self) -> None: + a = self.shard("a", "status=error expected=2 outcomes=1", mutant(CAUGHT, "CaughtMutant")) + b = self.shard("b", "status=partial expected=1 outcomes=0") + c = self.shard("c", None) + self.merge(a, b, c) + self.assertIn("status=error ", self.status()) + self.assertIn("shards=error,partial,no-status", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("shard 0: `error` — the run itself failed", text) + self.assertIn("shard 1: `partial` — its time budget ran out", text) + self.assertIn("shard 2: `no-status` — it ended without a status line", text) + + def test_a_budget_stopped_shard_blames_the_budget(self) -> None: + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable")) + b = self.shard("b", "status=not-started expected=1 outcomes=0") + self.merge(a, b) + self.assertIn("status=partial expected=3 outcomes=2 ", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("the time budget ran out after 2 of 3", text) + + def test_no_shards_is_not_started(self) -> None: + self.merge() + self.assertIn("status=not-started expected=3 outcomes=0", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("no shard results were found", text) + + def test_an_unplanned_survivor_is_kept_and_fails(self) -> None: + unplanned = "crates/mega-evm/src/z.rs:9:9: replace z -> bool with true" + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable")) + b = self.shard("b", "status=complete expected=2 outcomes=2", + mutant(MISSED, "CaughtMutant"), mutant(unplanned, "MissedMutant")) + self.assertIn(unplanned, self.merge(a, b)) + self.assertIn("status=mismatch expected=3 outcomes=3 unplanned=1 duplicated=0", self.status()) + merged = self.tmp / "merged" + self.assertEqual((merged / "mutants.out" / "missed.txt").read_text(), f"{unplanned}\n") + self.assertEqual((merged / "unplanned.txt").read_text(), f"{unplanned}\n") + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("1 shard outcome(s) are for mutants the inventory does not list", text) + self.assertIn(f"`{unplanned}`", text) + + def test_a_mutant_tested_twice_is_a_mismatch(self) -> None: + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "CaughtMutant")) + b = self.shard("b", "status=complete expected=2 outcomes=2", + mutant(MISSED, "MissedMutant"), mutant(UNVIABLE, "Unviable")) + self.merge(a, b) + self.assertIn("status=mismatch expected=3 outcomes=3 unplanned=0 duplicated=1", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("1 mutant(s) have more than one outcome", text) + + def test_shard_plans_that_miss_inventory_mutants_are_a_mismatch(self) -> None: + a = self.shard("a", "status=complete expected=1 outcomes=1", mutant(CAUGHT, "CaughtMutant")) + b = self.shard("b", "status=complete expected=1 outcomes=1", mutant(MISSED, "MissedMutant")) + self.merge(a, b) + self.assertIn("status=mismatch expected=3 outcomes=2 unplanned=0 duplicated=0 shards-planned=2", + self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("the shards planned 2 mutants", text) + + def test_an_empty_inventory_is_refused(self) -> None: + (self.tmp / "inventory.txt").write_text("") + with contextlib.redirect_stderr(io.StringIO()): + code = gate.cmd_merge(Namespace(inventory=str(self.tmp / "inventory.txt"), + out=str(self.tmp / "merged"), shards=[])) + self.assertEqual(code, 2) + + +class MergeRuns(GateCase): + """The shards' follow-up runs merge into one record the report reads.""" + + def merge_runs(self, *runs: Path) -> Path: + out = self.tmp / "merged-followups" + with contextlib.redirect_stderr(io.StringIO()): + gate.cmd_merge_runs(Namespace(out=str(out), runs=[str(r) for r in runs])) + return out + + def test_finished_runs_merge_with_their_logs(self) -> None: + def logged(name: str, summary: str) -> dict: + return {**mutant(name, summary), "log_path": "log/m.log"} + a = self.results("a", outcomes=outcomes_json(logged(MISSED, "CaughtMutant")), + files={"log/m.log": "the verdict\n"}) + b = self.results("b", outcomes=outcomes_json(logged(TIMEOUT, "MissedMutant")), + files={"log/m.log": "another\n"}) + out = self.merge_runs(a, b, self.tmp / "absent") + run = gate.load_run(out) + self.assertEqual((run.caught, run.missed), ([MISSED], [TIMEOUT])) + logs = {gate.outcome_name(o): o["log_path"] + for o in json.loads((out / "outcomes.json").read_text())["outcomes"] if gate.outcome_name(o)} + self.assertEqual((out / logs[MISSED]).read_text(), "the verdict\n") + self.assertEqual((out / logs[TIMEOUT]).read_text(), "another\n") + + def test_an_unfinished_or_failed_run_makes_the_merge_unscorable(self) -> None: + a = self.results("a", outcomes=outcomes_json(mutant(MISSED, "CaughtMutant"))) + b = self.results("b", outcomes=outcomes_json(mutant(TIMEOUT, "CaughtMutant"), end_time=None)) + with self.assertRaises(gate.ResultsError): + gate.load_run(self.merge_runs(a, b)) + c = self.results("c", outcomes=outcomes_json(mutant(TIMEOUT, "CaughtMutant")), + files={gate.RUN_FAILED_NOTE: "cargo-mutants exited 70\n"}) + with self.assertRaisesRegex(gate.ResultsError, "exited abnormally"): + gate.load_run(self.merge_runs(a, c)) + + def test_no_runs_writes_nothing(self) -> None: + self.assertFalse(self.merge_runs(self.tmp / "absent").exists()) if __name__ == "__main__": From 10098fde696ddd2e6b7147b948a18f4e4b39c990 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:20:37 +0800 Subject: [PATCH 114/190] ci: count a Mega EEST kill only on the suite's verdict, one mutant at a time within the budget --- REVIEW.md | 8 ++- mutants/README.md | 6 ++ scripts/mutation_gate.py | 56 ++++++++++++++- scripts/mutation_test.sh | 60 ++++++++++------ scripts/test_mutation_gate.py | 132 ++++++++++++++++++++++++++++------ 5 files changed, 218 insertions(+), 44 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index 76534d1b9..298f330a3 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -197,9 +197,11 @@ These checks guard every change to the Satin engine. Reference point, the pull request that brought the Satin skeleton: 115 mutants, 49 caught, 0 survived, 1 suppressed, 65 unviable, in 7m41s on CI and 4m12s on a 15-core laptop with `JOBS=8`. That population is the diff against `a8f8c7c9`, the last commit of the legacy core, and it is reproduced by `scripts/mutation_test.sh diff a8f8c7c9` followed by `python3 scripts/mutation_gate.py report --results target/mutants/mutants.out --recheck target/mutants/recheck/mutants.out --suppressions mutants/suppressions.toml`. Take the numbers from that pair, not from `cargo mutants` on its own: the driver turns the function-scoped suppressions into `--exclude-re` before generation, and the gate filters the line-scoped ones after the run, so the bare command reports a different population and a different survivor count. -- A mutant the tests miss is run once more against the Mega EEST suite, with mega-evm's ignored `mega_eest` test as the only test, which runs `scripts/mega_eest.sh` (plain) on the mutated tree; one a Mega EEST case catches counts as caught, and the report says how many the suite decided. - The suite is fetched and its adapter built on the unmutated tree first, which must pass; a warm-up or a run that fails as a run is recorded in its results, which the gate refuses. - The pass costs nothing while the tests catch every mutant, and about one adapter build and one run of the suite per mutant they miss. +- A mutant the tests miss is run once more against the Mega EEST suite, with mega-evm's ignored `mega_eest` test as the only test, which runs `scripts/mega_eest.sh` in plain mode only on the mutated tree; one a Mega EEST case catches counts as caught, and the report says how many the suite decided. + The kill counts only on the suite's own verdict in that mutant's log (`MEGA-EEST … result=FAIL`): a run that failed before its cases ran (a build, a fetch) fails the test too, and the gate then refuses the results as unscorable rather than counting a kill. + The suite is fetched and its adapter built on the unmutated tree first, which must pass; a warm-up or a run that fails as a run, or that the budget stops, is recorded in its results, which the gate refuses. + The mutants run one at a time, each with the machine's parallelism for the cases. + The pass costs nothing while the tests catch every mutant; otherwise the warm-up, cargo-mutants' baseline, one copy of `./target` and, per mutant, two incremental builds of mega-evm and one plain run of the cases (about three minutes on a 4-vCPU runner, estimated, not measured), plus any struct-field mutant in the run's scope (`mutants/README.md` has the details). - The job is bounded to 330 minutes, and the driver's own budget (`MUTANTS_BUDGET`, 300 minutes) stops the run before that, so a run that cannot finish still scores and uploads what it tested; the driver's `MUTANTS-STATUS` line says how far it got, and the gate (`report --status`) fails anything but a complete run. The driver builds the tests once before the mutants (the warm build) and CI builds incrementally (`CARGO_INCREMENTAL=1`), so each mutant recompiles only what its mutation changed. The nightly full run is four shards (`scripts/mutation_test.sh full --shard k/4`), merged against the full inventory (`mutation_gate.py merge`, and `merge-runs` for their re-checks and Mega EEST runs) and scored as a full run. diff --git a/mutants/README.md b/mutants/README.md index 92c681ab7..114d8ffe9 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -108,7 +108,13 @@ A re-check that exits abnormally proves nothing by the files it left, so the dri A mutant the tests **missed** — in the run, or in the re-check of one that timed out — may still change an outcome a case of the Mega EEST conformance suite pins. In the production scope the driver runs each such unsuppressed mutant once more, into `mega-eest/mutants.out`, with mega-evm's ignored `mega_eest` test as the only test (`--test mega_eest`, nextest's `--run-ignored only`), which runs `scripts/mega_eest.sh` in plain mode on the mutated tree; pass that directory to the gate as `--mega-eest`. One the suite catches counts as caught, one it times out on stays inconclusive, and the rest stay survivors. +A catch counts only on the suite's own verdict: the `mega_eest` test fails on any failure of the script, a build or a fetch that never reached a case included, and cargo-mutants records every such failure as caught, so the gate reads the mutant's log and counts the kill only when the script's summary line there says `result=FAIL` (the cases ran, completely, and one failed or erred); a caught outcome without that line makes the results unscorable, as `run-failed.txt` does. The suite is fetched and its adapter built on the unmutated tree first, which must pass there; a warm-up that fails, or a run that exits abnormally, is recorded in those results as `run-failed.txt` and refused. +The mutants run one at a time (`--jobs 1`), each with the machine's parallelism for the suite's cases, as the baseline ran; mutants side by side would build mega-evm and run the cases on the same cores against a timeout the baseline set alone. +The pass counts against `MUTANTS_BUDGET`; one the budget stops is recorded as `run-failed.txt` and the status says `followup-stopped`, which never passes. +It costs nothing while the tests catch every mutant. +Otherwise it costs the warm-up (a cold build of the adapter's dependencies when the job's cache holds none, and one run of the suite), cargo-mutants' baseline in its build directory (another run of the suite), the copy of `./target` (now with the warm-up's `target/mega-eest`) into that build directory, and, per mutant, an incremental build of mega-evm for the `mega_eest` test and again for the adapter, and one plain run of the 930 cases: about three minutes a mutant on a 4-vCPU runner, estimated from local runs (30 s a mutant on 15 cores), not measured there. +The mutants it runs are those the tests missed, plus any struct-field-deletion mutant in the first run's scope (below), whose outcome the gate does not read. `MUTANTS_MEGA_EEST=0` leaves the pass out, and the mutants it would have run stay survivors. The re-check and this run take the first run's own scope (its `--in-diff` file or `-f` glob) beside their `--re` selections, because cargo-mutants 27.1.0 adds struct-field-deletion mutants without matching them against `--re`; the gate reads their outcomes only for the mutants it asked about. diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index cdfb32127..9aa18a6d3 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -64,7 +64,9 @@ [--suppressions ] [--comment ] [--summary ] Read the run outcomes, take the re-check's outcome for a mutant that timed out and the Mega EEST run's outcome for a mutant the tests - missed, apply line-scoped suppressions (each anchored to one mutant's + missed (a kill there only with the suite's `result=FAIL` summary line + in that mutant's log; a caught outcome without it makes the results + unscorable), apply line-scoped suppressions (each anchored to one mutant's file:line:col and text), compute the mutation score, write a Markdown report, and exit non-zero if any unsuppressed survivor or timeout remains (the "no new survivors" gate). Exits 2, with a @@ -256,6 +258,8 @@ class Run: unviable: list[str] = field(default_factory=list) # Set when the run tested nothing: the producer's own word for it. nothing_to_test: str | None = None + # Each mutant's log, relative to the results directory, as the outcome names it. + logs: dict[str, str] = field(default_factory=dict) def nothing_to_mutate(line: str) -> bool: @@ -361,6 +365,8 @@ def load_run(results: Path) -> Run: f"({', '.join(MUTANT_SUMMARIES)})" ) getattr(run, kind).append(name) + if isinstance(outcome.get("log_path"), str): + run.logs[name] = outcome["log_path"] selected = read_selection(results) if selected is None: @@ -711,6 +717,40 @@ def cmd_timeout_re(args: argparse.Namespace) -> int: return 0 +# The summary line scripts/mega_eest.sh prints, as the mega_eest test prints it again into a +# mutant's log; its `result` says whether the suite ran to a verdict. +MEGA_EEST_SUMMARY = re.compile(r"MEGA-EEST rev=[0-9a-f]{40} [^\n]*") +MEGA_EEST_MODE_COUNTS = re.compile( + r"\b(?:plain|instrumented)=pass:\d+,fail:(\d+),unsupported:\d+,error:(\d+)\b") + + +def mega_eest_kill_unproven(results: Path, log_path: str | None) -> str | None: + """Why a mutant the Mega EEST run reports caught is not shown to be caught; None when it is. + + The run's test fails on any failure of the suite's script, a build or a fetch that never + reached a case included, and cargo-mutants records each as caught alike. Only the script's + summary line tells them apart: a kill is a log whose summary lines all say `result=FAIL`, a + complete run of the suite's cases with a case that failed or erred, or plain and instrumented + observations that differ. + """ + if not log_path: + return "its outcome names no log" + path = results / log_path + if not path.is_file(): + return f"its log {log_path} is missing" + lines = MEGA_EEST_SUMMARY.findall(ANSI.sub("", path.read_text(errors="replace"))) + if not lines: + return "its log holds no Mega EEST summary line, so the suite never reached its cases" + found = {m.group(1) if (m := re.search(r" result=(\w+)", line)) else "none" for line in lines} + if found != {"FAIL"}: + return (f"its log's Mega EEST summary says result={'/'.join(sorted(found))}, not FAIL: " + f"the suite reached no verdict on it") + counts = MEGA_EEST_MODE_COUNTS.findall(lines[-1]) + if not any(int(failed) + int(erred) for failed, erred in counts) and "-differ" not in lines[-1]: + return "its log's Mega EEST summary shows no failing case" + return None + + def cmd_missed_re(args: argparse.Namespace) -> int: try: run = load_run(Path(args.results)) @@ -821,6 +861,20 @@ def cmd_report(args: argparse.Namespace) -> int: return 2 if eest is not None: verdicts = {n: k for k in ("caught", "missed", "timeout", "unviable") for n in getattr(eest, k)} + # A kill counts only on the suite's own verdict in the mutant's log: a run that failed + # before it reached the cases says nothing of the mutant, and fails the gate unscored. + unproven = [(name, why) for name in missed if verdicts.get(name) == "caught" + if (why := mega_eest_kill_unproven(Path(mega_eest_dir), eest.logs.get(name)))] + if unproven: + listed = "\n".join(f"- `{name}`: {why}" for name, why in unproven[:MAX_SURVIVORS_SHOWN]) + write_report( + f"{title} — ❌ FAIL\n\n" + f"**The Mega EEST run of the mutants the tests missed cannot be scored:** " + f"{len(unproven)} mutant(s) recorded as caught without the suite's verdict that " + f"cases failed.\n\n{listed}\n", + args, + ) + return 2 remaining = [] for name in missed: verdict = verdicts.get(name) diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 343a64aa2..15a0d6995 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -40,12 +40,12 @@ # the status file below. # # Time budget: MUTANTS_BUDGET=, counted from this script's start, bounds -# the warm build, cargo-mutants and the re-check together (unset: no limit; -# needs GNU timeout). When it runs out, the running phase gets SIGINT, so +# the warm build, cargo-mutants, the re-check and the Mega EEST pass together +# (unset: no limit; needs GNU timeout). When it runs out, the running phase gets SIGINT, so # cargo-mutants stops its in-flight mutants and keeps every outcome it has # recorded; it gets SIGKILL if it is still running MUTANTS_GRACE seconds later. -# A re-check the budget stops has that recorded in its results -# (run-failed.txt). The script then exits 0 with what was tested, so the caller +# A follow-up run (the re-check, the Mega EEST pass) the budget stops has that +# recorded in its results (run-failed.txt), and the status says so. The script then exits 0 with what was tested, so the caller # can still score and upload it. # # The last line printed, also written to $OUT_DIR/status, is @@ -57,7 +57,7 @@ # partial the budget ran out after some mutants were tested; # not-started the budget ran out before any mutant was tested; # followup-stopped every planned mutant was tested, and the budget ran out in -# the re-check of a timed-out one; +# the re-check of a timed-out one or the Mega EEST pass; # baseline-failed the unmutated tree failed to build or to pass its tests; # error the run itself failed (bad arguments, an internal error). # Only baseline-failed and error exit non-zero. `mutation_gate.py report --status` @@ -75,10 +75,15 @@ # command is mega-evm's ignored `mega_eest` test alone, which runs # scripts/mega_eest.sh (plain mode) on the mutated tree, so a mutant that only a # Mega EEST case catches counts as caught. Pass that directory to the gate as -# --mega-eest. The suite is fetched and its adapter built once, on the unmutated -# tree, before the run; one that fails there has its exit recorded in those -# results (run-failed.txt), which the gate refuses. MUTANTS_MEGA_EEST=0 skips -# the pass, and the gate then counts those mutants as survivors. +# --mega-eest. The gate counts such a kill only when the mutant's log holds the +# suite's own verdict that cases failed (its `MEGA-EEST ... result=FAIL` line), +# so a run that failed before it reached the cases (a build, a fetch) is no +# kill: the gate refuses the results instead. The suite is fetched and its +# adapter built once, on the unmutated tree, before the run, and the mutants +# then run one at a time (--jobs 1), each using the machine's parallelism for +# the suite's cases; a warm-up that fails has its exit recorded in those results +# (run-failed.txt), which the gate refuses. MUTANTS_MEGA_EEST=0 skips the pass, +# and the gate then counts those mutants as survivors. # Bash 5 or newer: the driver relies on mapfile and on expanding empty arrays # under `set -u`, which bash 3.2 (macOS's /bin/bash) does not have. Written in @@ -410,10 +415,16 @@ run_missed_against_mega_eest() { local results="$OUT_DIR/mega-eest/mutants.out" echo "Running $((${#re_args[@]} / 2)) mutant(s) the tests missed against Mega EEST" >&2 local rc=0 - # MEGA_EEST_SCRIPT stands in for the script in the driver's own tests. - MEGA_EEST_MODES=plain "${MEGA_EEST_SCRIPT:-$ROOT_DIR/scripts/mega_eest.sh}" \ + # MEGA_EEST_SCRIPT stands in for the script in the driver's own tests. The warm-up checks the + # pin's provenance; no case set is compared here, the Mega EEST gate does that. It counts + # against the budget, as the whole pass does. + run_bounded env -u MEGA_EEST_BASE_REV MEGA_EEST_MODES=plain \ + "${MEGA_EEST_SCRIPT:-$ROOT_DIR/scripts/mega_eest.sh}" \ > "$OUT_DIR/mega-eest-warmup.log" 2>&1 || rc=$? - if [[ $rc -ne 0 ]]; then + if [[ $rc -eq 124 ]]; then + record_failed_followup "$results" "$rc" "the Mega EEST warm-up (see $OUT_DIR/mega-eest-warmup.log)" + return 0 + elif [[ $rc -ne 0 ]]; then echo "Mega EEST does not pass on the unmutated tree (exit $rc); see $OUT_DIR/mega-eest-warmup.log" >&2 mkdir -p "$results" echo "scripts/mega_eest.sh exited $rc on the unmutated tree" > "$results/run-failed.txt" @@ -421,12 +432,22 @@ run_missed_against_mega_eest() { fi # Every build directory reads the checkout the warm-up used, and writes its adapter workspace, # logs and build in its own target directory: a work or target directory set for the warm-up - # would be shared by builds running at once. - env -u MEGA_EEST_WORK -u MEGA_EEST_TARGET_DIR \ + # would be shared by builds running at once. The warm-up checked the pin's provenance, so the + # runs do not fetch the suite's history again. Each build directory starts from the warm + # target, the warm-up's adapter build included, and builds incrementally; the script runs + # the adapter its own build reports, so the warm-up's unmutated binary in the copy is never + # what runs. + # + # One mutant at a time (--jobs 1), each running the suite's cases with the machine's whole + # parallelism, as the baseline did: mutants run side by side would each build mega-evm and run + # the cases on the same cores, against a timeout the baseline set alone. On a 4-vCPU runner a + # mutant is about three minutes (an incremental build of mega-evm for the test and again for + # the adapter, and the 930 plain cases), estimated from local runs, not measured there. + run_bounded env -u MEGA_EEST_WORK -u MEGA_EEST_TARGET_DIR -u MEGA_EEST_BASE_REV \ MEGA_EEST_DIR="${MEGA_EEST_DIR:-${MEGA_EEST_WORK:-$ROOT_DIR/target/mega-eest}/src}" \ - MEGA_EEST_MODES=plain cargo mutants \ + MEGA_EEST_MODES=plain MEGA_EEST_SKIP_PROVENANCE=1 cargo mutants \ "${PKG_ARGS[@]}" \ - --jobs "$JOBS" \ + --jobs 1 \ --output "$OUT_DIR/mega-eest" \ --no-shuffle \ -vV \ @@ -435,11 +456,10 @@ run_missed_against_mega_eest() { "${SCOPE_ARGS[@]}" \ "${re_args[@]}" \ -- --run-ignored only 2>&1 | tee "$OUT_DIR/mega-eest.log" || rc=$? - # As for the re-check: a run that fails as a run proves nothing by the files it left. + # As for the re-check: a run that fails as a run, or that the budget stops, proves nothing by + # the files it left. if ! run_outcome "$rc"; then - echo "the Mega EEST run of the missed mutants failed (exit $rc); see $OUT_DIR/mega-eest.log" >&2 - mkdir -p "$results" - echo "cargo-mutants exited $rc" > "$results/run-failed.txt" + record_failed_followup "$results" "$rc" "the Mega EEST run of the missed mutants (see $OUT_DIR/mega-eest.log)" fi } diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 6b41ad139..19c1c443a 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -69,8 +69,26 @@ def load_script(name: str): FINISHED = "2026-09-27T07:17:03.989998Z" -def mutant(name: str, summary: str) -> dict: - return {"scenario": {"Mutant": {"name": name}}, "summary": summary} +def mutant(name: str, summary: str, log_path: str | None = None) -> dict: + outcome = {"scenario": {"Mutant": {"name": name}}, "summary": summary} + if log_path is not None: + outcome["log_path"] = log_path + return outcome + + +# The summary lines scripts/mega_eest.sh prints: the suite's verdict that cases failed, and a run +# that never reached them. +EEST_FAIL = ("MEGA-EEST rev=" + "5e" * 20 + " run=partial cases=930 plain=pass:927,fail:3,unsupported:0," + "error:0 negative=fail-as-recorded provenance=unchecked caseset=unchecked result=FAIL") +EEST_INCOMPLETE = "MEGA-EEST rev=" + "5e" * 20 + " run=partial stage=adapter-build result=INCOMPLETE" + + +def eest_log(*lines: str) -> str: + """A mutant's log as cargo-mutants keeps it: nextest's output of the failing mega_eest test.""" + return "\n".join([" Starting 1 test across 1 binary", " FAIL [ 31.0s] mega-evm::mega_eest", + "--- STDOUT: mega-evm::mega_eest ---", *lines, ""]) + + def outcomes_json(*mutants: dict, baseline: str | None = "Success", @@ -138,6 +156,17 @@ def results(self, name: str = "mutants.out", outcomes: dict | None = None, (path / file).write_text(text) return path + def eest_results(self, name: str, *outcomes: tuple[str, str, str | None]) -> Path: + """A Mega EEST run's results: each (mutant, summary, log text or None for no log).""" + files, recorded = {}, [] + for i, (mutant_name, summary, log) in enumerate(outcomes): + if log is None: + recorded.append(mutant(mutant_name, summary)) + else: + files[f"log/mutant-{i}.log"] = log + recorded.append(mutant(mutant_name, summary, f"log/mutant-{i}.log")) + return self.results(name, outcomes=outcomes_json(*recorded), files=files) + def suppressions(self, *mutants: str) -> Path: """Line suppressions, each anchored to the mutant line given (`file:line:col: text`).""" path = self.tmp / "suppressions.toml" @@ -444,10 +473,15 @@ def test_a_recheck_only_speaks_for_the_timeouts(self) -> None: class MegaEestScoring(GateCase): """A mutant the tests missed is decided by its Mega EEST run, and only such a mutant.""" - def against_mega_eest(self, summary: str, *, suppressions: Path | None = None) -> tuple[int, str]: - results = self.results(outcomes=outcomes_json( + def against_mega_eest(self, summary: str, log: str | None = None, *, + suppressions: Path | None = None) -> tuple[int, str]: + # Each call its own pair of results, as a test may score several. + self.calls = getattr(self, "calls", 0) + 1 + results = self.results(f"run-{self.calls}/mutants.out", outcomes=outcomes_json( mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) - eest = self.results("mega-eest", outcomes=outcomes_json(mutant(MISSED, summary))) + if log is None and summary == "CaughtMutant": + log = eest_log(EEST_FAIL, f"Mega EEST cases failed on this checkout: {EEST_FAIL}") + eest = self.eest_results(f"run-{self.calls}/mega-eest", (MISSED, summary, log)) return self.report(results, suppressions=suppressions, mega_eest=eest) def test_a_missed_mutant_mega_eest_catches_passes(self) -> None: @@ -456,6 +490,33 @@ def test_a_missed_mutant_mega_eest_catches_passes(self) -> None: self.assertIn("run against Mega EEST after the tests missed them: 1 — 1 caught, 0 survived", text) self.assertIn("(2/2 viable mutants killed)", text) + def test_a_kill_needs_the_suites_verdict_in_the_mutants_log(self) -> None: + # Coloured as CI's CARGO_TERM_COLOR=always leaves it, the verdict still counts. + code, text = self.against_mega_eest("CaughtMutant", eest_log("\x1b[1m" + EEST_FAIL + "\x1b[0m")) + self.assertEqual(code, 0, text) + for log, reason in ( + (eest_log("error: could not compile `mega-evm`", EEST_INCOMPLETE, + f"the Mega EEST run reached no verdict (exit status: 2): {EEST_INCOMPLETE}"), + "result=INCOMPLETE, not FAIL"), + (eest_log("thread panicked: cannot run scripts/mega_eest.sh"), "no Mega EEST summary line"), + (eest_log(EEST_FAIL.replace("fail:3", "fail:0")), "shows no failing case"), + (eest_log(EEST_FAIL, EEST_INCOMPLETE), "result=FAIL/INCOMPLETE"), + ): + code, text = self.against_mega_eest("CaughtMutant", log) + self.assertEqual(code, 2, text) + self.assertIn("cannot be scored", text) + self.assertIn("recorded as caught without the suite's verdict", text) + self.assertIn(reason, text) + + def test_a_kill_without_a_log_cannot_be_scored(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) + for eest in (self.eest_results("no-log-path", (MISSED, "CaughtMutant", None)), + self.results("log-missing", outcomes=outcomes_json( + mutant(MISSED, "CaughtMutant", "log/gone.log")))): + code, text = self.report(results, mega_eest=eest) + self.assertEqual(code, 2, text) + self.assertRegex(text, "names no log|is missing") + def test_a_missed_mutant_mega_eest_misses_is_a_survivor(self) -> None: code, text = self.against_mega_eest("MissedMutant") self.assertEqual(code, 1, text) @@ -486,8 +547,9 @@ def test_mega_eest_results_only_speak_for_the_missed(self) -> None: # A timeout is the re-check's to decide, whatever a Mega EEST run says of it. results = self.results(outcomes=outcomes_json( mutant(MISSED, "MissedMutant"), mutant(TIMEOUT, "Timeout"))) - eest = self.results("mega-eest", outcomes=outcomes_json( - mutant(MISSED, "CaughtMutant"), mutant(TIMEOUT, "CaughtMutant"))) + verdict = eest_log(EEST_FAIL) + eest = self.eest_results("mega-eest", (MISSED, "CaughtMutant", verdict), + (TIMEOUT, "CaughtMutant", verdict)) code, text = self.report(results, self.tmp / "no-recheck", mega_eest=eest) self.assertEqual(code, 1, text) self.assertIn("Timed-out mutants", text) @@ -496,7 +558,7 @@ def test_mega_eest_results_only_speak_for_the_missed(self) -> None: def test_a_timeout_that_survives_alone_is_decided_by_mega_eest(self) -> None: results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) recheck = self.results("recheck", outcomes=outcomes_json(mutant(TIMEOUT, "MissedMutant"))) - eest = self.results("mega-eest", outcomes=outcomes_json(mutant(TIMEOUT, "CaughtMutant"))) + eest = self.eest_results("mega-eest", (TIMEOUT, "CaughtMutant", eest_log(EEST_FAIL))) code, text = self.report(results, recheck, mega_eest=eest) self.assertEqual(code, 0, text) @@ -720,7 +782,8 @@ def bash5() -> str | None: mega-eest) run=mega-eest ;; esac echo "$argv" > "$FAKE_RUNS/$run.argv" -echo "dir=${MEGA_EEST_DIR-unset} modes=${MEGA_EEST_MODES-unset} work=${MEGA_EEST_WORK-unset}" > "$FAKE_RUNS/$run.env" +echo "dir=${MEGA_EEST_DIR-unset} modes=${MEGA_EEST_MODES-unset} work=${MEGA_EEST_WORK-unset}" \\ + "provenance=${MEGA_EEST_SKIP_PROVENANCE-checked} base=${MEGA_EEST_BASE_REV-unset}" > "$FAKE_RUNS/$run.env" if [ -d "$FAKE_RUNS/$run" ]; then mkdir -p "$out/mutants.out" cp -R "$FAKE_RUNS/$run/." "$out/mutants.out/" @@ -786,7 +849,8 @@ class DriverMegaEest(GateCase): `mega_eest` test alone, after the suite passed on the unmutated tree, and carries a failed warm-up or run into the results, which the gate then refuses.""" - def drive(self, *, warmup_exit: int = 0, eest_exit: int = 0, eest: dict | None = None, + def drive(self, *, warmup_exit: int = 0, eest_exit: int = 0, + eest: list[tuple[str, str, str | None]] | None = None, env: dict[str, str] | None = None) -> tuple[int, str, Path, Path]: shell = bash5() if shell is None: @@ -796,12 +860,13 @@ def drive(self, *, warmup_exit: int = 0, eest_exit: int = 0, eest: dict | None = mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) (runs / "main.exit").write_text("2\n") if eest is not None: - self.results("runs/mega-eest", outcomes=eest) + self.eest_results("runs/mega-eest", *eest) (runs / "mega-eest.exit").write_text(f"{eest_exit}\n") bin_dir = self.tmp / "bin" bin_dir.mkdir() - (bin_dir / "cargo").write_text(FAKE_CARGO) - (bin_dir / "cargo").chmod(0o755) + for name, text in (("cargo", FAKE_CARGO), ("timeout", FAKE_TIMEOUT)): + (bin_dir / name).write_text(text) + (bin_dir / name).chmod(0o755) (bin_dir / "python3").symlink_to(sys.executable) # The warm-up's stand-in records the modes it was asked for and exits as the test says. stub = self.tmp / "mega_eest.sh" @@ -822,13 +887,16 @@ def drive(self, *, warmup_exit: int = 0, eest_exit: int = 0, eest: dict | None = def test_a_missed_mutant_runs_against_mega_eest_alone(self) -> None: work = self.tmp / "eest-work" - code, text, runs, _ = self.drive(eest=outcomes_json(mutant(MISSED, "CaughtMutant")), - env={"MEGA_EEST_WORK": str(work)}) + code, text, runs, _ = self.drive(eest=[(MISSED, "CaughtMutant", eest_log(EEST_FAIL))], + env={"MEGA_EEST_WORK": str(work), "MEGA_EEST_BASE_REV": "b" * 40}) self.assertEqual(code, 0, text) self.assertEqual((runs / "warmup.modes").read_text(), "plain\n") - # Every build directory reads the warm-up's checkout and works in its own directory. + # Every build directory reads the warm-up's checkout and works in its own directory; the + # warm-up checked the pin, so the runs do not, and no case set is compared. self.assertEqual((runs / "mega-eest.env").read_text(), - f"dir={work}/src modes=plain work=unset\n") + f"dir={work}/src modes=plain work=unset provenance=1 base=unset\n") + # One mutant at a time, each with the machine's parallelism for its cases. + self.assertIn("--jobs 1 ", (runs / "mega-eest.argv").read_text()) argv = (runs / "mega-eest.argv").read_text().strip() self.assertIn("--cargo-arg=--test --cargo-arg=mega_eest", argv) # The first run's scope, which keeps cargo-mutants' unfiltered struct-field mutants to it. @@ -837,9 +905,19 @@ def test_a_missed_mutant_runs_against_mega_eest_alone(self) -> None: self.assertNotIn(re.escape(CAUGHT), argv) self.assertTrue(argv.endswith("-- --run-ignored only"), argv) + def test_a_nested_build_failure_is_not_a_kill(self) -> None: + # The baseline passed; the mutant's own run of the suite failed to build the adapter, which + # fails the mega_eest test as a failing case would, and cargo-mutants records it caught. + log = eest_log("error: could not compile `mega-evm` (lib)", EEST_INCOMPLETE, + f"the Mega EEST run reached no verdict (exit status: 2): {EEST_INCOMPLETE}") + code, text, _, _ = self.drive(eest=[(MISSED, "CaughtMutant", log)]) + self.assertEqual(code, 2, text) + self.assertIn("recorded as caught without the suite's verdict", text) + self.assertIn(MISSED, text) + def test_a_warmup_that_fails_is_refused(self) -> None: code, text, runs, results = self.drive( - warmup_exit=1, eest=outcomes_json(mutant(MISSED, "CaughtMutant"))) + warmup_exit=1, eest=[(MISSED, "CaughtMutant", eest_log(EEST_FAIL))]) self.assertFalse((runs / "mega-eest.argv").exists()) self.assertEqual((results / "run-failed.txt").read_text(), "scripts/mega_eest.sh exited 1 on the unmutated tree\n") @@ -848,13 +926,27 @@ def test_a_warmup_that_fails_is_refused(self) -> None: def test_a_mega_eest_run_that_exits_abnormally_is_refused(self) -> None: # Its files are those of a finished run that caught the mutant: only its exit says otherwise. code, text, _, results = self.drive( - eest_exit=70, eest=outcomes_json(mutant(MISSED, "CaughtMutant"))) + eest_exit=70, eest=[(MISSED, "CaughtMutant", eest_log(EEST_FAIL))]) self.assertEqual((results / "run-failed.txt").read_text(), "cargo-mutants exited 70\n") self.assertEqual(code, 2, text) self.assertIn("exited abnormally (cargo-mutants exited 70)", text) + def test_a_pass_the_budget_stops_is_recorded_and_refused(self) -> None: + code, text, runs, results = self.drive( + eest=[(MISSED, "CaughtMutant", eest_log(EEST_FAIL))], + env={"MUTANTS_BUDGET": "3600", "FAKE_STOP": "/mega-eest"}) + self.assertEqual((results / "run-failed.txt").read_text(), "stopped by MUTANTS_BUDGET (3600s)\n") + self.assertEqual(code, 2, text) + out = results.parent.parent + self.assertEqual((out / "status").read_text().strip(), + "MUTANTS-STATUS status=followup-stopped expected=2 outcomes=2") + code, text = self.report(out / "mutants.out", out / "recheck" / "mutants.out", + mega_eest=results, status=out / "status") + self.assertEqual(code, 1, text) + self.assertIn("Mega EEST run of a missed one", text) + def test_the_pass_can_be_left_out(self) -> None: - code, text, runs, _ = self.drive(eest=outcomes_json(mutant(MISSED, "CaughtMutant")), + code, text, runs, _ = self.drive(eest=[(MISSED, "CaughtMutant", eest_log(EEST_FAIL))], env={"MUTANTS_MEGA_EEST": "0"}) self.assertFalse((runs / "mega-eest.argv").exists()) self.assertFalse((runs / "warmup.modes").exists()) From 56de8cb39f7a6eb7bb015f5b12352714c8c884ba Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 14:22:55 +0800 Subject: [PATCH 115/190] style: find the mega_eest test's summary line from the end --- crates/mega-evm/tests/mega_eest/main.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/mega_eest/main.rs b/crates/mega-evm/tests/mega_eest/main.rs index a75462e36..96b64891a 100644 --- a/crates/mega-evm/tests/mega_eest/main.rs +++ b/crates/mega-evm/tests/mega_eest/main.rs @@ -35,8 +35,7 @@ fn test_mega_eest_cases_pass_on_this_checkout() { print!("{stdout}"); let summary = stdout .lines() - .filter(|line| line.starts_with("MEGA-EEST ")) - .last() + .rfind(|line| line.starts_with("MEGA-EEST ")) .unwrap_or("(no MEGA-EEST summary line)"); match output.status.code() { Some(0) => assert!( From d0736290e840fa109d4a147f0788ea4787e9a729 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 15:01:46 +0800 Subject: [PATCH 116/190] ci: failing Mega EEST cases are a verdict wherever the control first differs --- .github/workflows/mega-eest.yml | 3 +- AGENTS.md | 3 +- REVIEW.md | 1 + scripts/mega_eest.py | 49 +++++++++++++++++++--------- scripts/mega_eest.sh | 20 ++++++++---- scripts/test_mega_eest.py | 57 ++++++++++++++++++++++++++------- scripts/test_mutation_gate.py | 7 ++++ 7 files changed, 105 insertions(+), 35 deletions(-) diff --git a/.github/workflows/mega-eest.yml b/.github/workflows/mega-eest.yml index aa83e204c..5ca71b45c 100644 --- a/.github/workflows/mega-eest.yml +++ b/.github/workflows/mega-eest.yml @@ -6,7 +6,8 @@ name: Mega EEST # pull request that moves the revm or op-revm fork is tested with its own fork. Each case is # consumed plain and instrumented; the gate passes when the cases consumed are exactly the slice's # index, every one passes in both modes with the same observations, and the suite's deliberately -# wrong expectation fails where it records. The script's exit says which: 0 pass, 1 cases failed, +# wrong expectation fails where it records (when gating cases fail, it need only fail somewhere: a +# change of behaviour can move where it first differs). The script's exit says which: 0 pass, 1 cases failed, # 2 no verdict (a fetch, a build, a report), 3 the pin refused; the job also requires the summary # line of the full run (`run=full`) of a pin on Mega EEST's default branch. # diff --git a/AGENTS.md b/AGENTS.md index 8f2e3550f..857368382 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -673,7 +673,8 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The adapter's `Cargo.lock`, resolved for the commit it pins, is not used: the workspace's lock is seeded with this tree's `Cargo.lock`, cargo resolves it once, every package mega-evm links must then be at the version and source this tree locks, with one revm, and the build runs `--locked`. The executables it runs are the ones those builds report (cargo's JSON messages), never a file at a path guessed from the target directory. It passes when the cases consumed are exactly the slice's index, by case id and file digest, every one passes in both modes with the same observations, and the suite's deliberately wrong expectation, which the index must list, fails where it records; a failure names the case, its first differing path, both values and the rules it pins. - The summary is one `MEGA-EEST` line on stdout, and the exit code says what kind of result it is: 0 pass; 1 the cases failed, the only verdict on this tree (every mode ran to a complete report of exactly the index, and a case failed or erred, or the modes' observations differ); 2 no verdict (a fetch, a build, the resolution, a report missing or incomplete, no mode, a wrong expectation not caught, a case the adapter does not support), however the cases would have gone; 3 the cases passed and the pin is refused. + The wrong expectation is the control that shows the pipeline can report a failure: it must fail where it records only when every gating case passed, since when gating cases fail they show that already and a change of behaviour can also move where the control first differs; then it need only have run and not passed. + The summary is one `MEGA-EEST` line on stdout, and the exit code says what kind of result it is: 0 pass; 1 the cases failed, the only verdict on this tree (every mode ran to a complete report of exactly the index, a case failed or erred or the modes' observations differ, and the control ran and did not pass, wherever it first differed); 2 no verdict (a fetch, a build, the resolution, a report missing or incomplete, no mode, a control not run or passing, a control that failed elsewhere while every gating case passed, a case the adapter does not support), however the cases would have gone; 3 the cases passed and the pin is refused. The line says `run=full` for both modes, which the gate requires, and `run=partial` for one. The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and removed ids must be exactly those `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env` declares (`caseset=declared`, or `kept` with none removed); either refusal is exit 3. A pin on the branch of a suite change still under review is a draft state: its cases run, and the gate stays red until the pin moves to the merged commit. diff --git a/REVIEW.md b/REVIEW.md index 298f330a3..819c12021 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -149,6 +149,7 @@ These checks guard every change to the Satin engine. - The `Mega EEST gate` job always runs, and becomes a required check once an administrator adds it to the `satin` branch rule; a pull request that changes documentation alone skips the run and passes it. The step summary has the summary line (`MEGA-EEST rev=… run=full cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… provenance=… caseset=… result=…`), the run's time and exit, and, when the pull request moves the pin, the case ids it removes, adds and changes; a failing run uploads its reports. The script's exit says what failed: 1 the cases (a verdict), 2 no verdict (a fetch, a build, a report; the log names the step), 3 the pin refused; the job also requires the line of the full run of a pin on the suite's default branch. + The suite's deliberately wrong expectation is a control: with every gating case passing it must fail where it records, and with gating cases failing it need only have run and not passed (`negative=fail-elsewhere`), since a change of behaviour can move where it first differs; a control that passed or did not run is never a verdict. - A case that fails is a change of behaviour the specification pins. A pull request that makes it on purpose, or that changes the mega-evm API the suite's adapter calls (the adapter then no longer builds, and the gate says so), changes Mega EEST first: the case, derived from the changed rule, or the adapter, in a pull request there. It then moves `MEGA_EEST_REV` to that Mega EEST commit, in the same mega-evm pull request, so the gate runs the suite that pull request needs. diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index 475374cdc..41d81c664 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -48,16 +48,21 @@ negative.json for the suite's deliberately wrong expectation) and decide: in every mode, the cases consumed are exactly the slice's index, by case id and file digest, and every one passed; with both modes, every case's observations are the same bytes plain and - instrumented; and the wrong expectation, which the index must list, fails at the path it - records. Prints the failures (case id, first differing path, both values, the rules the + instrumented. The wrong expectation, which the index must list, is the control that shows + the consumer and the adapter can report a failure at all: it decides only when every + gating case passed, and then it must fail at the path it records; when gating cases + failed, the failures already show that, and the control need only have run and not passed + (failed or erred, at any path), since a change of behaviour can move where it first + differs. Prints the failures (case id, first differing path, both values, the rules the case pins) and one summary line, `MEGA-EEST … result=`, and exits with its code: - 0 pass; 1 FAIL, a verdict (complete reports of exactly the index in every mode, the wrong - expectation caught, and a case failed or erred, or the modes' observations differ); + 0 pass; 1 FAIL, a verdict (complete reports of exactly the index in every mode, a case + failed or erred, or the modes' observations differ, and the control ran and did not pass); 2 INCOMPLETE, no verdict (no mode, a report missing, cases that are not the index, a - consume exit its report does not explain, a case the adapter does not support, no wrong - expectation or one not caught, or the checker itself failing); 3 REFUSED, every case passed - but the pin's provenance is `unmerged` or its case set `undeclared`. `run=full` in the line - is both modes; `run=partial` one. + consume exit its report does not explain, a case the adapter does not support, no control, + a control not run or passing, a control that failed elsewhere while every gating case + passed, or the checker itself failing); 3 REFUSED, every case passed but the pin's + provenance is `unmerged` or its case set `undeclared`. `run=full` in the line is both + modes; `run=partial` one. """ from __future__ import annotations @@ -477,8 +482,12 @@ def check(args: argparse.Namespace) -> int: summary.append(f"parity={'identical' if not differ else f'{len(differ)}-differ'}") cases_failed |= bool(differ) - # The wrong expectation is what shows the consumer and the adapter can fail at all: an index - # without one, or a run that did not fail it where recorded, says nothing about the cases. + # The wrong expectation is the control that shows the consumer and the adapter can report a + # failure at all. When every gating case passed, nothing else shows it, so the control must + # fail at the path it records. When gating cases failed, the failures show it, and a change + # of behaviour can also move where the control first differs, so it need only have run and + # not passed (failed or erred, at any path). A control that was not run, or that passed, + # says the consumer cannot be trusted either way. Without one, there is no verdict. negative_path = work / "negative.json" wrong_at = {n["caseId"]: n["wrongAt"] for n in index.get("negative", [])} if not wrong_at: @@ -488,14 +497,24 @@ def check(args: argparse.Namespace) -> int: verdict = "no-report" incomplete.append("`mega-fixture consume` wrote no report of the wrong expectation") else: - verdict = "fail-as-recorded" cases = {c.get("caseId"): c for c in json.loads(negative_path.read_text())["cases"]} + states = [] for case_id, path in wrong_at.items(): c = cases.get(case_id) - if not c or c["status"] != "fail" or c.get("path") != path: - incomplete.append(f"the wrong expectation {case_id} did not fail at {path}: " - f"{c['status'] + ' at ' + str(c.get('path')) if c else 'not consumed'}") - verdict = "not-caught" + seen = f"{c['status']} at {c.get('path')}" if c else "not consumed" + if c and c["status"] == "fail" and c.get("path") == path: + states.append("fail-as-recorded") + elif c and c["status"] in ("fail", "error") and cases_failed: + states.append("fail-elsewhere") + print(f"mega-eest: the wrong expectation {case_id} did not fail at {path} ({seen}); " + f"gating cases failed, which can move where it first differs", file=sys.stderr) + else: + states.append("not-caught") + why = ("gating cases failed, and it did not fail" if cases_failed + else "every gating case passed, so it must fail where recorded") + incomplete.append(f"the wrong expectation {case_id} did not fail at {path} ({seen}): {why}") + verdict = ("not-caught" if "not-caught" in states + else "fail-elsewhere" if "fail-elsewhere" in states else "fail-as-recorded") summary.append(f"negative={verdict}") summary.append(f"provenance={args.provenance}") summary.append(f"caseset={args.caseset}") diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index f7331f342..3111a3a42 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -37,9 +37,13 @@ # $MEGA_EEST_MODES, plain and --instrumented by default, and the suite's deliberately wrong # expectation (slice/negative). # 6. Decides (scripts/mega_eest.py check): in each mode the cases consumed are exactly the slice's -# index and every one passed; plain and instrumented observations are the same bytes; the wrong -# expectation, which the index must list, fails where the index says. A failure prints the case -# id, the first differing path and both values, and the rules the case pins. +# index and every one passed; plain and instrumented observations are the same bytes. The wrong +# expectation, which the index must list, is the control that shows the pipeline can report a +# failure: when every gating case passed it must fail where the index says; when gating cases +# failed, the failures show that already, and since a change of behaviour can also move where +# the control first differs, it need only have run and not passed (failed or erred, anywhere). +# A failure prints the case id, the first differing path and both values, and the rules the +# case pins. # # Everything goes to stderr but one line on stdout, the summary: # @@ -54,12 +58,14 @@ # Exit codes: # 0 pass: every case passed in every mode run, the wrong expectation failed where recorded, and # the pin's checks passed or were skipped (result=pass) -# 1 the cases failed: every mode ran to a complete report of exactly the slice's cases and the -# wrong expectation failed where recorded, and a case failed or erred, or plain and -# instrumented observations differ (result=FAIL). The only exit that is a verdict on this tree. +# 1 the cases failed: every mode ran to a complete report of exactly the slice's cases, a case +# failed or erred or plain and instrumented observations differ, and the wrong expectation ran +# and did not pass, wherever it first differed (result=FAIL). The only exit that is a verdict +# on this tree. # 2 no verdict: anything that kept the run from one, a fetch, a build, the resolution, the lock # check, a report missing or incomplete, cases that are not the index, a case the adapter does -# not support, a wrong expectation not caught, no mode (result=INCOMPLETE) +# not support, no mode, a wrong expectation not run or passing, or one that failed elsewhere +# while every gating case passed (result=INCOMPLETE) # 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, or it removes # cases scripts/mega_eest.env does not declare (result=REFUSED) # diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 5fd0419b8..2b93effec 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -370,14 +370,39 @@ def test_an_unsupported_case_is_no_verdict(self) -> None: code, out, err = self.write({"plain": self.one_failing("unsupported")}, self.NEGATIVE) self.assert_no_verdict(code, out, err, "the adapter does not support") - def test_a_wrong_expectation_missing_or_not_caught_is_no_verdict(self) -> None: - for negative, reason in ( - (None, "no report of the wrong expectation"), - ([{"caseId": "satin/negative/wrong", "status": "pass"}], "did not fail at /expected/x"), - ([{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/y"}], "did not fail"), - ): - code, out, err = self.write({"plain": self.one_failing()}, negative) + @staticmethod + def control(status: str, path: str | None = None) -> list[dict]: + case = {"caseId": "satin/negative/wrong", "status": status} + if path is not None: + case["path"] = path + return [case] + + def test_failing_cases_with_the_control_failing_elsewhere_are_a_verdict(self) -> None: + # A change of behaviour can move where the control first differs; the failing cases + # already show the pipeline reports failures. + for control in (self.control("fail", "/expected/gasLedgers/gasUsed"), self.control("error")): + code, out, err = self.write({"plain": self.one_failing()}, control) + self.assertEqual(code, 1, (control, err)) + self.assertIn("negative=fail-elsewhere", out) + self.assertTrue(out.strip().endswith("result=FAIL"), out) + self.assertIn("can move where it first differs", err) + + def test_failing_cases_with_a_control_that_did_not_fail_are_no_verdict(self) -> None: + for control, reason in ((self.control("pass"), "gating cases failed, and it did not fail"), + (self.control("unsupported"), "gating cases failed, and it did not fail"), + ([], "not consumed"), + (None, "no report of the wrong expectation")): + code, out, err = self.write({"plain": self.one_failing()}, control) + self.assert_no_verdict(code, out, err, reason) + + def test_passing_cases_need_the_control_to_fail_where_recorded(self) -> None: + for control, reason in ((self.control("fail", "/expected/y"), "so it must fail where recorded"), + (self.control("error"), "so it must fail where recorded"), + (self.control("pass"), "so it must fail where recorded"), + (None, "no report of the wrong expectation")): + code, out, err = self.write({"plain": self.all_passed()}, control) self.assert_no_verdict(code, out, err, reason) + self.assertNotIn("negative=fail-as-recorded", out) run = self.write({"plain": self.all_passed()}, self.NEGATIVE, index_negative=[]) self.assert_no_verdict(*run, "lists no wrong expectation") self.assertIn("negative=none", run[1]) @@ -534,17 +559,17 @@ def test_removals_must_be_declared_exactly(self) -> None: """ # The consumer: every case of the index passes, or fails when the adapter says so; the wrong -# expectation fails where the index records it. +# expectation fails where the index records it, or at FAKE_CONTROL_PATH when that is set. FAKE_CLI = """#!/usr/bin/env python3 -import json, subprocess, sys +import json, os, subprocess, sys from pathlib import Path args = sys.argv[1:] assert args[0] == "consume" adapter, report, path = args[args.index("--adapter") + 1], args[args.index("--report") + 1], Path(args[-1]) index = json.loads((path.parent / "index.json").read_text()) if path.name == "negative": - cases = [{"caseId": n["caseId"], "fileDigest": "sha256:n", "status": "fail", "path": n["wrongAt"]} - for n in index["negative"]] + cases = [{"caseId": n["caseId"], "fileDigest": "sha256:n", "status": "fail", + "path": os.environ.get("FAKE_CONTROL_PATH") or n["wrongAt"]} for n in index["negative"]] else: failing = subprocess.run([adapter, "verdict"], capture_output=True, text=True).stdout.strip() == "fail" cases = [{"caseId": c["caseId"], "fileDigest": c["fileDigest"], "observationsDigest": "sha256:o", @@ -660,6 +685,16 @@ def test_failing_cases_are_the_only_exit_1(self) -> None: self.assertEqual(code, 1, err) self.assertRegex(self.summary(out), r" run=partial cases=3 plain=pass:0,fail:3,.* result=FAIL$") + def test_failing_cases_that_move_the_control_are_still_exit_1(self) -> None: + # A change that fails the cases can also move where the control first differs. + code, out, err = self.run_script(FAKE_VERDICT="fail", FAKE_CONTROL_PATH="/expected/gasLedgers/gasUsed") + self.assertEqual(code, 1, err) + self.assertRegex(self.summary(out), r" negative=fail-elsewhere .* result=FAIL$") + # With every case passing, the control must fail where recorded. + code, out, err = self.run_script(FAKE_CONTROL_PATH="/expected/gasLedgers/gasUsed") + self.assertEqual(code, 2, err) + self.assertRegex(self.summary(out), r" negative=not-caught .* result=INCOMPLETE$") + def test_a_step_that_fails_before_the_verdict_exits_2(self) -> None: for fail, stage in (("mega-fixture", "cli-build"), ("metadata", "adapter-resolve"), ("adapter-revm", "adapter-build")): diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 19c1c443a..0198c7cfd 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -508,6 +508,13 @@ def test_a_kill_needs_the_suites_verdict_in_the_mutants_log(self) -> None: self.assertIn("recorded as caught without the suite's verdict", text) self.assertIn(reason, text) + def test_a_kill_that_moved_the_control_is_credited(self) -> None: + # The mutant failed gating cases and moved where the wrong expectation first differs. + moved = EEST_FAIL.replace("negative=fail-as-recorded", "negative=fail-elsewhere") + code, text = self.against_mega_eest("CaughtMutant", eest_log(moved)) + self.assertEqual(code, 0, text) + self.assertIn("1 caught, 0 survived", text) + def test_a_kill_without_a_log_cannot_be_scored(self) -> None: results = self.results(outcomes=outcomes_json(mutant(MISSED, "MissedMutant"))) for eest in (self.eest_results("no-log-path", (MISSED, "CaughtMutant", None)), From 6c288b1ce903c87d1011d0f2eca6c035da1eff8e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 16:17:22 +0800 Subject: [PATCH 117/190] ci(mutation): never shard the follow-up runs again --- scripts/mutation_gate.py | 39 ++++++---- scripts/mutation_test.sh | 49 +++++++++--- scripts/test_mutation_gate.py | 137 ++++++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 24 deletions(-) diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index 9aa18a6d3..e4e2322ef 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -16,13 +16,14 @@ that line to /no-mutants.txt. Does nothing when exists, and fails when it does not and the output says no such thing. - timeout-re --results [--suppressions ] + timeout-re --results [--suppressions ] [--with-files] Print one `--re ` pair per line for every unsuppressed mutant - that timed out, each regex matching that mutant's name alone. Consumed - by scripts/mutation_test.sh to re-run those mutants one at a time. + that timed out, each regex matching that mutant's name alone, and with + --with-files one `-f ` pair per file they are in. Consumed by + scripts/mutation_test.sh to re-run those mutants one at a time. missed-re --results [--recheck ] - [--suppressions ] + [--suppressions ] [--with-files] Print one `--re ` pair per line for every unsuppressed mutant the tests missed: in the run, or in the re-check of one that timed out. Consumed by scripts/mutation_test.sh to run those mutants against the @@ -709,12 +710,23 @@ def cmd_timeout_re(args: argparse.Namespace) -> int: print(f"no timed-out mutants to re-check: {err}", file=sys.stderr) return 0 supp = suppressed_anchors(args.suppressions) - for name in run.timeout: - if is_suppressed(name, supp): - continue + print_selection([name for name in run.timeout if not is_suppressed(name, supp)], + getattr(args, "with_files", False)) + return 0 + + +def print_selection(names: list[str], with_files: bool) -> None: + """One `--re ` pair per line for each name, each regex matching that name alone; with + `with_files`, one `-f ` pair for each file the names are in. The files keep the struct-field + mutants cargo-mutants adds without matching them against `--re` to those files, for a run the + first run's own restriction does not scope.""" + for name in names: print("--re") print(f"^{re.escape(name)}$") - return 0 + if with_files: + for file in sorted({name.split(":", 1)[0] for name in names}): + print("-f") + print(file) # The summary line scripts/mega_eest.sh prints, as the mega_eest test prints it again into a @@ -765,11 +777,8 @@ def cmd_missed_re(args: argparse.Namespace) -> int: if recheck is not None: missed += [name for name in run.timeout if name in set(recheck.missed)] supp = suppressed_anchors(args.suppressions) - for name in missed: - if is_suppressed(name, supp): - continue - print("--re") - print(f"^{re.escape(name)}$") + print_selection([name for name in missed if not is_suppressed(name, supp)], + getattr(args, "with_files", False)) return 0 @@ -1059,12 +1068,16 @@ def main() -> int: pt = sub.add_parser("timeout-re", help="--re arguments selecting the mutants that timed out") pt.add_argument("--results", required=True) pt.add_argument("--suppressions", default=None) + pt.add_argument("--with-files", action="store_true", + help="also print one `-f ` pair per file of the selected mutants") pt.set_defaults(func=cmd_timeout_re) pm = sub.add_parser("missed-re", help="--re arguments selecting the mutants the tests missed") pm.add_argument("--results", required=True) pm.add_argument("--recheck", default=None) pm.add_argument("--suppressions", default=None) + pm.add_argument("--with-files", action="store_true", + help="also print one `-f ` pair per file of the selected mutants") pm.set_defaults(func=cmd_missed_re) pp = sub.add_parser("progress", help="count planned and tested mutants") diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 15a0d6995..7d64815e9 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -281,19 +281,46 @@ if [[ -z "$LISTING" ]]; then CLEARED=1 fi -# The arguments that scope the first run (an `--in-diff` file, a `-f` glob): the -# re-check and the Mega EEST run take them too. cargo-mutants 27.1.0 adds a -# struct-field-deletion mutant without matching it against `--re`, so a run -# selected by `--re` alone would also test every such mutant of the crate; under -# the first run's scope it tests at most the ones the first run tested, whose -# outcomes there the gate does not read. +# The arguments that restrict the first run (an `--in-diff` file, `-f` globs), which the +# re-check and the Mega EEST run take too, without the first run's `--shard`. The follow-ups +# select their mutants by name (`--re`), and cargo-mutants 27.1.0 adds every struct-field-deletion +# mutant without matching it against `--re`; under the first run's restriction those extras are at +# most the ones the first run tested, whose outcomes there the gate does not read. A shard, though, +# is applied after the selection: it would cut the follow-ups' own short list, extras included, +# and leave out mutants they were asked to decide, so it is never passed on. A run with no +# restriction (the full run, sharded or not) has the follow-ups name the files of their mutants +# instead (FOLLOWUP_FILES), which keeps the extras to those files. SCOPE_ARGS=() +FOLLOWUP_FILES=() # WARM=0 skips the warm build: a diff with no mutatable change builds nothing. WARM=1 +# The first run's arguments without `--shard k/n` or `--shard=k/n`; and whether they restrict +# the mutants to files or a diff. +set_scope() { + local arg skip="" restricted="" + SCOPE_ARGS=() + for arg in "$@"; do + if [[ -n "$skip" ]]; then + skip="" + continue + fi + case "$arg" in + --shard) skip=1 ;; + --shard=*) ;; + *) SCOPE_ARGS+=("$arg") ;; + esac + case "$arg" in + -f | --file | --file=* | --in-diff | --in-diff=*) restricted=1 ;; + esac + done + FOLLOWUP_FILES=() + [[ -n "$restricted" ]] || FOLLOWUP_FILES=(--with-files) +} + run_mutants() { - SCOPE_ARGS=("$@") + set_scope "$@" # --no-shuffle: test mutants in deterministic source order so runs are # reproducible and comparable (recommended by https://mutants.rs/pr-diff.html). # -vV: verbose progress + version banner, for diagnosable CI logs. @@ -370,14 +397,14 @@ record_failed_followup() { recheck_timeouts() { local re_output if ! re_output="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" timeout-re \ - --results "$OUT_DIR/mutants.out" --suppressions "$SUPPRESS")"; then + --results "$OUT_DIR/mutants.out" --suppressions "$SUPPRESS" "${FOLLOWUP_FILES[@]}")"; then echo "failed to list the timed-out mutants in $OUT_DIR/mutants.out" >&2 return 1 fi [[ -n "$re_output" ]] || return 0 local re_args=() mapfile -t re_args <<< "$re_output" - echo "Re-checking $((${#re_args[@]} / 2)) timed-out mutant(s) one at a time" >&2 + echo "Re-checking $(grep -c '^--re$' <<< "$re_output") timed-out mutant(s) one at a time" >&2 local rc=0 run_bounded cargo mutants \ "${CONFIG_ARGS[@]}" \ @@ -405,7 +432,7 @@ run_missed_against_mega_eest() { local re_output if ! re_output="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" missed-re \ --results "$OUT_DIR/mutants.out" --recheck "$OUT_DIR/recheck/mutants.out" \ - --suppressions "$SUPPRESS")"; then + --suppressions "$SUPPRESS" "${FOLLOWUP_FILES[@]}")"; then echo "failed to list the missed mutants in $OUT_DIR/mutants.out" >&2 return 1 fi @@ -413,7 +440,7 @@ run_missed_against_mega_eest() { local re_args=() mapfile -t re_args <<< "$re_output" local results="$OUT_DIR/mega-eest/mutants.out" - echo "Running $((${#re_args[@]} / 2)) mutant(s) the tests missed against Mega EEST" >&2 + echo "Running $(grep -c '^--re$' <<< "$re_output") mutant(s) the tests missed against Mega EEST" >&2 local rc=0 # MEGA_EEST_SCRIPT stands in for the script in the driver's own tests. The warm-up checks the # pin's provenance; no case set is compared here, the Mega EEST gate does that. It counts diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 0198c7cfd..81e553b9e 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -16,6 +16,7 @@ import importlib.util import io import json +import os import re import shutil import subprocess @@ -776,6 +777,7 @@ def bash5() -> str | None: if [ "$1" = nextest ]; then echo "$*" > "$FAKE_RUNS/warm.argv"; exit "${FAKE_WARM_EXIT:-0}"; fi [ "$1" = mutants ] || exit 99 shift +printf '%s\\0' "$@" > "$FAKE_RUNS/last.argv0" if [ "$1" = --version ]; then echo "cargo-mutants 27.1.0"; exit 0; fi argv="$*"; out=""; run=main while [ $# -gt 0 ]; do @@ -789,6 +791,7 @@ def bash5() -> str | None: mega-eest) run=mega-eest ;; esac echo "$argv" > "$FAKE_RUNS/$run.argv" +mv "$FAKE_RUNS/last.argv0" "$FAKE_RUNS/$run.argv0" echo "dir=${MEGA_EEST_DIR-unset} modes=${MEGA_EEST_MODES-unset} work=${MEGA_EEST_WORK-unset}" \\ "provenance=${MEGA_EEST_SKIP_PROVENANCE-checked} base=${MEGA_EEST_BASE_REV-unset}" > "$FAKE_RUNS/$run.env" if [ -d "$FAKE_RUNS/$run" ]; then @@ -1057,6 +1060,140 @@ def test_list_names_the_mutant_set_without_running(self) -> None: self.assertFalse((runs / "warm.argv").exists()) +class ShardDriver(GateCase): + """Runs the driver's sharded full run with the fake cargo, recording each run's arguments.""" + + def drive_shard(self, *shard: str, timed_out: str = TIMEOUT, missed: str = MISSED, + env: dict[str, str] | None = None) -> tuple[subprocess.CompletedProcess, Path]: + shell = bash5() + if shell is None: + self.skipTest("no bash 5 or newer on this machine") + runs = self.tmp / "runs" + runs.mkdir(exist_ok=True) + # The first run: one mutant timed out, one missed; the re-check misses the timed-out one, + # so the Mega EEST pass is asked for both; it catches both, with the suite's verdict. + self.results("runs/main", outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(timed_out, "Timeout"), mutant(missed, "MissedMutant"))) + self.results("runs/recheck", outcomes=outcomes_json(mutant(timed_out, "MissedMutant"))) + self.eest_results("runs/mega-eest", (missed, "CaughtMutant", eest_log(EEST_FAIL)), + (timed_out, "CaughtMutant", eest_log(EEST_FAIL))) + for name in ("main", "recheck", "mega-eest"): + (runs / f"{name}.exit").write_text("0\n") + bin_dir = self.tmp / "bin" + bin_dir.mkdir(exist_ok=True) + for name, text in (("cargo", FAKE_CARGO), ("timeout", FAKE_TIMEOUT)): + (bin_dir / name).write_text(text) + (bin_dir / name).chmod(0o755) + if not (bin_dir / "python3").exists(): + (bin_dir / "python3").symlink_to(sys.executable) + stub = self.tmp / "mega_eest.sh" + stub.write_text("#!/bin/sh\nexit 0\n") + stub.chmod(0o755) + out = self.tmp / "out" / "mutants" + run = subprocess.run( + [shell, str(DriverGuard.DRIVER), "full", *shard], capture_output=True, text=True, timeout=120, + env={"PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_RUNS": str(runs), "OUT_DIR": str(out), + "JOBS": "1", "SUPPRESS": str(self.tmp / "no-suppressions.toml"), + "MEGA_EEST_SCRIPT": str(stub), **(env or {})}) + self.assertEqual(run.returncode, 0, run.stderr) + return run, runs + + @staticmethod + def argv(runs: Path, name: str) -> list[str]: + return (runs / f"{name}.argv0").read_text().split("\0")[:-1] + + +class DriverShardedFollowUps(ShardDriver): + """In a sharded full run the follow-up runs keep their mutants: they are not cut by the shard.""" + + def test_the_follow_ups_of_a_shard_are_not_sharded_again(self) -> None: + for shard in (["--shard", "1/4"], ["--shard=1/4"]): + with self.subTest(shard=shard): + _, runs = self.drive_shard(*shard) + main = self.argv(runs, "main") + self.assertIn(shard[-1].removeprefix("--shard="), " ".join(main)) + recheck, eest = self.argv(runs, "recheck"), self.argv(runs, "mega-eest") + for argv in (recheck, eest): + self.assertFalse([a for a in argv if a.startswith("--shard")], argv) + self.assertNotIn("1/4", argv) + # Each follow-up names its mutants, and their files keep the struct-field extras + # cargo-mutants adds to those files. + self.assertIn(f"^{re.escape(TIMEOUT)}$", recheck) + self.assertEqual(recheck[recheck.index("-f") + 1], TIMEOUT.split(":", 1)[0]) + self.assertIn(f"^{re.escape(MISSED)}$", eest) + self.assertIn(f"^{re.escape(TIMEOUT)}$", eest) + self.assertEqual(sorted(eest[i + 1] for i, a in enumerate(eest) if a == "-f"), + sorted({MISSED.split(":", 1)[0], TIMEOUT.split(":", 1)[0]})) + shutil.rmtree(self.tmp / "runs") + shutil.rmtree(self.tmp / "out") + + def test_a_restricted_run_keeps_its_own_restriction(self) -> None: + _, runs = self.drive_shard("-f", "crates/mega-evm/src/a.rs", "--shard", "2/4") + for name in ("recheck", "mega-eest"): + argv = self.argv(runs, name) + self.assertEqual([argv[i + 1] for i, a in enumerate(argv) if a == "-f"], ["crates/mega-evm/src/a.rs"]) + self.assertFalse([a for a in argv if a.startswith("--shard")], argv) + + +@unittest.skipUnless(os.environ.get("MUTANTS_REAL_LIST") == "1", + "set MUTANTS_REAL_LIST=1 to list the crate's mutants with the installed cargo-mutants") +class FollowUpSelectionAgainstCargoMutants(ShardDriver): + """The follow-up arguments the driver builds, replayed through the installed cargo-mutants' + real `--list` on this tree: for every shard of the full run, each mutant a follow-up is asked + to decide is in the list it selects.""" + + ROOT = SCRIPTS.parent + + def real_list(self, args: list[str]) -> list[str]: + run = subprocess.run(["cargo", "mutants", "--list", "--colors", "never", *args], cwd=self.ROOT, + capture_output=True, text=True, timeout=600) + self.assertEqual(run.returncode, 0, run.stderr) + return [line for line in run.stdout.splitlines() if line.strip()] + + @staticmethod + def selection(argv: list[str]) -> list[str]: + """The arguments of a follow-up run that select mutants, as `--list` takes them.""" + out, i = [], 0 + while i < len(argv): + a = argv[i] + if a == "--": + break + if a in ("--output", "--jobs"): + i += 2 + continue + if a in ("-vV", "--no-shuffle") or a.startswith("--cargo-arg"): + i += 1 + continue + out.append(a) + i += 1 + return out + + def test_every_requested_mutant_is_selected_in_every_shard(self) -> None: + shell = bash5() + if shell is None: + self.skipTest("no bash 5 or newer on this machine") + for k in range(4): + with self.subTest(shard=k): + listed = subprocess.run([shell, str(DriverGuard.DRIVER), "list", "--shard", f"{k}/4"], + cwd=self.ROOT, capture_output=True, text=True, timeout=600) + self.assertEqual(listed.returncode, 0, listed.stderr) + names = [line for line in listed.stdout.splitlines() if line.strip()] + timed_out, missed = names[0], names[-1] + _, runs = self.drive_shard("--shard", f"{k}/4", timed_out=timed_out, missed=missed) + recheck = self.real_list(self.selection(self.argv(runs, "recheck"))) + eest = self.real_list(self.selection(self.argv(runs, "mega-eest"))) + self.assertIn(timed_out, recheck) + self.assertIn(missed, eest) + self.assertIn(timed_out, eest) + # The shard, added back, is what would cut them. + cut = self.real_list([*self.selection(self.argv(runs, "mega-eest")), "--shard", f"{k}/4"]) + print(f"shard {k}/4: re-check lists {len(recheck)}, Mega EEST pass lists {len(eest)}, " + f"both requested in each; with the shard again: " + f"{sum(n in cut for n in (timed_out, missed))} of 2 kept", file=sys.stderr) + shutil.rmtree(self.tmp / "runs") + shutil.rmtree(self.tmp / "out") + + class DriverGuard(unittest.TestCase): """scripts/mutation_test.sh refuses to run on a shell that is not bash 5 or newer.""" From face3ee17798a8f64b4f47ab5aa198aa1f6258ea Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 16:18:19 +0800 Subject: [PATCH 118/190] ci: a Mega EEST case status the consumer does not define is no verdict --- scripts/mega_eest.py | 16 +++++++++++++--- scripts/test_mega_eest.py | 8 ++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index 41d81c664..121d4a993 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -58,7 +58,8 @@ 0 pass; 1 FAIL, a verdict (complete reports of exactly the index in every mode, a case failed or erred, or the modes' observations differ, and the control ran and did not pass); 2 INCOMPLETE, no verdict (no mode, a report missing, cases that are not the index, a - consume exit its report does not explain, a case the adapter does not support, no control, + consume exit its report does not explain, a case the adapter does not support, a case + status other than the consumer's four (pass, fail, unsupported, error), no control, a control not run or passing, a control that failed elsewhere while every gating case passed, or the checker itself failing); 3 REFUSED, every case passed but the pin's provenance is `unmerged` or its case set `undeclared`. `run=full` in the line is both @@ -391,6 +392,9 @@ def canonical(value) -> str: return "(absent)" if value is None else json.dumps(value, sort_keys=True, separators=(",", ":")) +# The statuses `mega-fixture consume` gives a case. +CASE_STATUSES = ("pass", "fail", "unsupported", "error") + # The results of `check`, by the exit code each has. RESULT_EXIT = {"pass": 0, "FAIL": 1, "INCOMPLETE": 2, "REFUSED": 3} @@ -467,10 +471,16 @@ def check(args: argparse.Namespace) -> int: f"{len(not_passed)} case(s) not passing in its report") if statuses.get("unsupported"): incomplete.append(f"{mode}: {statuses['unsupported']} case(s) the adapter does not support") + # The consumer has four statuses; another is one this checker cannot read, never a pass, and + # the four counts the summary line shows must add up to the cases consumed. + unknown = sorted(set(statuses) - set(CASE_STATUSES)) + if unknown or sum(statuses.get(k, 0) for k in CASE_STATUSES) != len(cases): + incomplete.append(f"{mode}: case statuses the consumer does not define: " + + ", ".join(f"{k} ({statuses[k]})" for k in unknown)) if statuses.get("fail") or statuses.get("error"): cases_failed = True - summary.append(f"{mode}=" + ",".join( - f"{s}:{statuses.get(s, 0)}" for s in ("pass", "fail", "unsupported", "error"))) + summary.append(f"{mode}=" + ",".join(f"{s}:{statuses.get(s, 0)}" for s in CASE_STATUSES) + + "".join(f",{k}:{statuses[k]}" for k in sorted(set(statuses) - set(CASE_STATUSES)))) if {"plain", "instrumented"} <= observations.keys(): plain, inst = observations["plain"], observations["instrumented"] diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 2b93effec..4e177c27e 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -366,6 +366,14 @@ def test_a_consume_exit_its_report_does_not_explain_is_no_verdict(self) -> None: code, out, err = self.write({"plain": cases}, self.NEGATIVE, exits={"plain": exit_code}) self.assert_no_verdict(code, out, err, f"exited {exit_code}") + def test_a_status_the_consumer_does_not_define_is_no_verdict(self) -> None: + # A consumer of a later pin with a fifth status: the four counts no longer add up. + cases = [self.case("satin/a", "sha256:1"), self.case("satin/b", "sha256:2", "skipped")] + for exit_code in (1, 0): + code, out, err = self.write({"plain": cases}, self.NEGATIVE, exits={"plain": exit_code}) + self.assert_no_verdict(code, out, err, "case statuses the consumer does not define: skipped (1)") + self.assertIn("plain=pass:1,fail:0,unsupported:0,error:0,skipped:1", out) + def test_an_unsupported_case_is_no_verdict(self) -> None: code, out, err = self.write({"plain": self.one_failing("unsupported")}, self.NEGATIVE) self.assert_no_verdict(code, out, err, "the adapter does not support") From cce17a4d185dccff1e0f1d481aee31f075a2ed08 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 16:27:48 +0800 Subject: [PATCH 119/190] ci: a Mega EEST pin move declares the cases it changes, and keeps its repository --- .github/workflows/mega-eest.yml | 13 +++-- scripts/mega_eest.env | 11 ++-- scripts/mega_eest.py | 47 +++++++++++------ scripts/mega_eest.sh | 56 ++++++++++++++------ scripts/test_mega_eest.py | 92 ++++++++++++++++++++++++++++----- 5 files changed, 165 insertions(+), 54 deletions(-) diff --git a/.github/workflows/mega-eest.yml b/.github/workflows/mega-eest.yml index 5ca71b45c..145522eb6 100644 --- a/.github/workflows/mega-eest.yml +++ b/.github/workflows/mega-eest.yml @@ -15,9 +15,10 @@ name: Mega EEST # its place, so it is checked too: the pinned commit must be on Mega EEST's default branch (a pin on # the branch of a suite change still under review is a draft state, and the gate stays red until # the pin moves to the merged commit), and a pull request that moves the pin lists the case ids -# removed, added and changed relative to its base's pin in the step summary, where any removal -# fails the gate unless scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES lists exactly the removed -# ids, a line the reviewer reads in the diff. +# removed, added and changed relative to its base's pin in the step summary, where any removal or +# change fails the gate unless scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES and +# MEGA_EEST_CHANGED_CASES list exactly those ids, lines the reviewer reads in the diff; and a pull +# request that changes MEGA_EEST_REPO fails it, unless the base has no pin file. # # A failing case pins a rule of the Satin specification. A pull request that changes that # behaviour on purpose, or the mega-evm API the adapter calls, changes Mega EEST first (the case or @@ -113,6 +114,7 @@ jobs: echo "Mega EEST at $rev" echo "rev=$rev" >> "$GITHUB_OUTPUT" base="" + base_repo="" if [ "$EVENT" = pull_request ]; then if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then echo "::error::HEAD is not the pull request's merge commit, so the base's pin is unknown" @@ -121,10 +123,12 @@ jobs: # A base without the pin file (the pull request that adds the gate) has nothing to compare. if git cat-file -e 'HEAD^1:scripts/mega_eest.env' 2> /dev/null; then base=$(git show 'HEAD^1:scripts/mega_eest.env' | sed -n 's/^MEGA_EEST_REV=\(.*\)$/\1/p') + base_repo=$(git show 'HEAD^1:scripts/mega_eest.env' | sed -n 's/^MEGA_EEST_REPO=\(.*\)$/\1/p') fi fi - echo "the base's pin: ${base:-(none)}" + echo "the base's pin: ${base:-(none)} in ${base_repo:-(none)}" echo "base=$base" >> "$GITHUB_OUTPUT" + echo "base_repo=$base_repo" >> "$GITHUB_OUTPUT" # The job's cargo cache is the step below: setup-rust-toolchain's own cache handles the # workspace's target directory, and this job builds into another. @@ -155,6 +159,7 @@ jobs: env: REV: ${{ steps.pin.outputs.rev }} MEGA_EEST_BASE_REV: ${{ steps.pin.outputs.base }} + MEGA_EEST_BASE_REPO: ${{ steps.pin.outputs.base_repo }} run: | set -uo pipefail start=$SECONDS diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index cfc385bb9..82634f94e 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -9,8 +9,11 @@ # red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest MEGA_EEST_REV=5e4007b47ce62c2af2b7bf770677b0e6baf1a8d2 -# The case ids the pin's last move removed, space-separated, exactly: a pull request that moves the -# pin to a commit whose slice drops cases lists them here, or the gate fails; a move that removes -# none leaves it empty. Cases are mega-evm's tests of the behaviours they pin, so a removal is a -# change the reviewer reads in this file's diff. +# The case ids the pin's last move removed, and those it changed under their ids (another file +# digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice +# drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none +# leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a +# change is a line the reviewer reads in this file's diff. Changing MEGA_EEST_REPO also fails the +# gate: the default branch the pin must be on is that repository's. MEGA_EEST_REMOVED_CASES= +MEGA_EEST_CHANGED_CASES= diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index 121d4a993..dbec4e2ec 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -34,15 +34,16 @@ file this build produced, wherever the target directory or the build target put it. case-diff --base-rev --rev --base-index --index - --declared --summary + --declared --declared-changes --summary Compare the case sets of two pins' slice indexes: the case ids removed, added and changed (same id, another file digest) are listed on stderr and as Markdown in , and the word - printed on stdout says whether the removals are what scripts/mega_eest.env's - MEGA_EEST_REMOVED_CASES declares, exactly: `kept` (none removed, none declared), `declared` - (the removed ids and no other) or `undeclared` (anything else). + printed on stdout says whether the removals and the changes are what scripts/mega_eest.env's + MEGA_EEST_REMOVED_CASES and MEGA_EEST_CHANGED_CASES declare, exactly: `kept` (none removed + or changed, none declared), `declared` (exactly the removed and the changed ids) or + `undeclared` (anything else). check --suite --work --modes <"plain instrumented"> --rev - [--provenance ] + [--provenance ] [--repo ] [--caseset ] Read the run reports `mega-fixture consume` wrote into (.json, and negative.json for the suite's deliberately wrong expectation) and decide: in every mode, the @@ -62,7 +63,8 @@ status other than the consumer's four (pass, fail, unsupported, error), no control, a control not run or passing, a control that failed elsewhere while every gating case passed, or the checker itself failing); 3 REFUSED, every case passed but the pin's - provenance is `unmerged` or its case set `undeclared`. `run=full` in the line is both + provenance is `unmerged`, its repository is not the base's (`repo=changed`) or its case set + `undeclared`. `run=full` in the line is both modes; `run=partial` one. """ from __future__ import annotations @@ -527,13 +529,15 @@ def check(args: argparse.Namespace) -> int: else "fail-elsewhere" if "fail-elsewhere" in states else "fail-as-recorded") summary.append(f"negative={verdict}") summary.append(f"provenance={args.provenance}") + repo = getattr(args, "repo", "unchecked") + summary.append(f"repo={repo}") summary.append(f"caseset={args.caseset}") if incomplete: result = "INCOMPLETE" elif cases_failed: result = "FAIL" - elif args.provenance == "unmerged" or args.caseset == "undeclared": + elif args.provenance == "unmerged" or args.caseset == "undeclared" or repo == "changed": result = "REFUSED" else: result = "pass" @@ -579,9 +583,13 @@ def cases(path: str) -> dict[str, str]: removed = sorted(base.keys() - head.keys()) added = sorted(head.keys() - base.keys()) changed = sorted(k for k in base.keys() & head.keys() if base[k] != head[k]) - declared = sorted(set(args.declared.split())) - if removed == declared: - caseset = "declared" if removed else "kept" + # A case removed, or changed under its id, stops pinning what it pinned: both are declared in + # scripts/mega_eest.env, exactly, so each is a line the reviewer reads in the diff. + declared = {"removed": sorted(set(args.declared.split())), + "changed": sorted(set(args.declared_changes.split()))} + found = {"removed": removed, "changed": changed} + if found == declared: + caseset = "declared" if removed or changed else "kept" else: caseset = "undeclared" print(f"mega-eest: the pin moves {args.base_rev} -> {args.rev}: {len(removed)} case(s) removed, " @@ -589,13 +597,16 @@ def cases(path: str) -> dict[str, str]: for title, ids in (("removed", removed), ("added", added), ("changed", changed)): for case_id in ids: print(f"mega-eest: {title} {case_id}", file=sys.stderr) - if caseset == "undeclared": - print("mega-eest: error: scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES must list exactly the " - "case ids the pin removes: removed and not declared: " - f"{' '.join(sorted(set(removed) - set(declared))) or '(none)'}; declared and not removed: " - f"{' '.join(sorted(set(declared) - set(removed))) or '(none)'}", file=sys.stderr) + for kind, variable in (("removed", "MEGA_EEST_REMOVED_CASES"), ("changed", "MEGA_EEST_CHANGED_CASES")): + if found[kind] != declared[kind]: + print(f"mega-eest: error: scripts/mega_eest.env's {variable} must list exactly the case ids " + f"the pin {'removes' if kind == 'removed' else 'changes under their ids'}: {kind} and " + f"not declared: {' '.join(sorted(set(found[kind]) - set(declared[kind]))) or '(none)'}; " + f"declared and not {kind}: " + f"{' '.join(sorted(set(declared[kind]) - set(found[kind]))) or '(none)'}", file=sys.stderr) md = [f"### Mega EEST case set, {args.base_rev[:12]} → {args.rev[:12]}", "", - f"{len(removed)} removed, {len(added)} added, {len(changed)} changed; removals: **{caseset}**.", ""] + f"{len(removed)} removed, {len(added)} added, {len(changed)} changed; removals and changes: " + f"**{caseset}**.", ""] for title, ids in (("Removed", removed), ("Added", added), ("Changed", changed)): if ids: md += [f"
{title} ({len(ids)})", ""] @@ -629,6 +640,7 @@ def main() -> int: pc.add_argument("--modes", required=True) pc.add_argument("--rev", required=True) pc.add_argument("--provenance", default="unchecked", choices=["default-branch", "unmerged", "unchecked"]) + pc.add_argument("--repo", default="unchecked", choices=["same", "changed", "unchecked"]) pc.add_argument("--caseset", default="unchecked", choices=["unmoved", "kept", "declared", "undeclared", "unchecked"]) pc.set_defaults(func=cmd_check) @@ -642,7 +654,8 @@ def main() -> int: pd.add_argument("--rev", required=True) pd.add_argument("--base-index", required=True) pd.add_argument("--index", required=True) - pd.add_argument("--declared", default="") + pd.add_argument("--declared", default="", help="the removed case ids the env file declares") + pd.add_argument("--declared-changes", default="", help="the changed case ids the env file declares") pd.add_argument("--summary", required=True) pd.set_defaults(func=cmd_case_diff) diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index 3111a3a42..0de0683b8 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -17,8 +17,10 @@ # suite change still under review, is a draft state: the cases still run, and the script exits 3. # 3. When MEGA_EEST_BASE_REV names another commit (a pull request's base pin), compares the two # slices' case sets: the case ids removed, added and changed are listed (and written to -# $MEGA_EEST_WORK/case-diff.md), and removed ids must be exactly those scripts/mega_eest.env's -# MEGA_EEST_REMOVED_CASES declares, or the script exits 3. +# $MEGA_EEST_WORK/case-diff.md), and the removed ids and the ids of cases changed under them +# (another file digest) must be exactly those scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES and +# MEGA_EEST_CHANGED_CASES declare, or the script exits 3. When MEGA_EEST_BASE_REPO names the +# base's repository, a pin file that names another one exits 3 too. # 4. Builds the suite's `mega-fixture` CLI, and its revm adapter against this checkout: the adapter # is written out as a workspace of its own ($MEGA_EEST_WORK/adapter-revm, by scripts/mega_eest.py) # whose mega-evm is a path dependency on crates/mega-evm here, whose other crates take their @@ -49,7 +51,8 @@ # # MEGA-EEST rev= run= cases= =pass:,fail:,unsupported:,error: ... # [parity=] negative=<...> provenance= -# caseset= result= +# repo= caseset= +# result= # # `run=full` is both modes, which the gate requires; `run=partial` is one, which the mutation gate # runs (plain). A run that stops before the reports are read prints @@ -66,8 +69,9 @@ # check, a report missing or incomplete, cases that are not the index, a case the adapter does # not support, no mode, a wrong expectation not run or passing, or one that failed elsewhere # while every gating case passed (result=INCOMPLETE) -# 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, or it removes -# cases scripts/mega_eest.env does not declare (result=REFUSED) +# 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, in another +# repository than the base's, or it removes or changes cases scripts/mega_eest.env does not +# declare (result=REFUSED) # # Environment: # MEGA_EEST_DIR a Mega EEST checkout at the pin to use instead of fetching one @@ -77,6 +81,7 @@ # MEGA_EEST_MODES the modes to consume in (default "plain instrumented"); at least one # MEGA_EEST_JOBS cases run at once (default: the number of CPUs) # MEGA_EEST_BASE_REV the pin to compare the case set with (CI: the pull request base's pin) +# MEGA_EEST_BASE_REPO the repository the base's pin file names (CI: when the base has the file) # MEGA_EEST_SKIP_PROVENANCE=1 # skips step 2 (provenance=unchecked): for the mutation gate's runs, which # its warm-up already checked, and the coverage report; never the gate @@ -165,6 +170,7 @@ REPO=$(read_pin MEGA_EEST_REPO) REV=$(read_pin MEGA_EEST_REV) [[ "$REV" =~ ^[0-9a-f]{40}$ ]] || die "$PIN_FILE: MEGA_EEST_REV is '$REV', not a full commit hash" DECLARED_REMOVALS=$(read_optional MEGA_EEST_REMOVED_CASES) +DECLARED_CHANGES=$(read_optional MEGA_EEST_CHANGED_CASES) # The paths of a checkout that decide what runs: a change to any of them is a different suite. SUITE_PATHS=(slice specs adapters crates Cargo.toml Cargo.lock) @@ -209,19 +215,20 @@ at_commit() { fi } -# A shallow fetch of commit $2 into a fresh checkout at $1. One retry: a fetch that fails twice is -# a network failure or a commit the repository does not have, and either stops the run. +# A shallow fetch of commit $2 into a fresh checkout at $1, from repository $3 (the pin's by +# default). One retry: a fetch that fails twice is a network failure or a commit the repository does +# not have, and either stops the run. fetch_commit() { - local dir=$1 rev=$2 + local dir=$1 rev=$2 repo=${3:-$REPO} rm -rf "$dir" mkdir -p "$dir" git -C "$dir" init -q - git -C "$dir" remote add origin "$REPO" + git -C "$dir" remote add origin "$repo" if ! git -C "$dir" fetch -q --depth 1 origin "$rev"; then log "the fetch failed; retrying once" sleep 5 git -C "$dir" fetch -q --depth 1 origin "$rev" \ - || die "cannot fetch $rev from $REPO: the repository has no such commit, or the network failed" + || die "cannot fetch $rev from $repo: the repository has no such commit, or the network failed" fi git -C "$dir" -c advice.detachedHead=false checkout -q FETCH_HEAD at_commit "$dir" "$rev" || die "the fetched checkout of $rev $PIN_PROBLEM" @@ -274,25 +281,40 @@ else fi fi +# The repository against the base's, when it is given: the default branch the provenance check +# reads is the pin repository's own, so a change of repository is a change of what is trusted. +REPO_STATE=unchecked +if [ -n "${MEGA_EEST_BASE_REPO:-}" ]; then + if [ "$MEGA_EEST_BASE_REPO" = "$REPO" ]; then + REPO_STATE=same + else + REPO_STATE=changed + log "error: MEGA_EEST_REPO moves from $MEGA_EEST_BASE_REPO to $REPO; the suite's repository is" \ + "not changed in a pull request that runs this gate" + fi +fi + # The case set against the base's pin, when one is given. CASESET=unchecked if [ -n "${MEGA_EEST_BASE_REV:-}" ]; then STAGE=case-diff BASE_REV=$MEGA_EEST_BASE_REV [[ "$BASE_REV" =~ ^[0-9a-f]{40}$ ]] || die "MEGA_EEST_BASE_REV is '$BASE_REV', not a full commit hash" - if [ "$BASE_REV" = "$REV" ]; then + if [ "$BASE_REV" = "$REV" ] && [ "$REPO_STATE" != changed ]; then CASESET=unmoved - [ -z "$DECLARED_REMOVALS" ] \ - || log "warning: the pin did not move, and MEGA_EEST_REMOVED_CASES still declares removals; clear it" + [ -z "$DECLARED_REMOVALS$DECLARED_CHANGES" ] \ + || log "warning: the pin did not move, and MEGA_EEST_REMOVED_CASES or MEGA_EEST_CHANGED_CASES" \ + "still declares cases; clear them" else BASE="$WORK/base-src" if ! { [ -d "$BASE/.git" ] && at_commit "$BASE" "$BASE_REV"; }; then log "fetching the base's pin $BASE_REV" - fetch_commit "$BASE" "$BASE_REV" + fetch_commit "$BASE" "$BASE_REV" "${MEGA_EEST_BASE_REPO:-$REPO}" fi CASESET=$(python3 "$HELPER" case-diff --base-rev "$BASE_REV" --rev "$REV" \ --base-index "$BASE/slice/index.json" --index "$SUITE/slice/index.json" \ - --declared "$DECLARED_REMOVALS" --summary "$WORK/case-diff.md") \ + --declared "$DECLARED_REMOVALS" --declared-changes "$DECLARED_CHANGES" \ + --summary "$WORK/case-diff.md") \ || die "cannot compare the case sets of $BASE_REV and $REV" fi fi @@ -360,7 +382,7 @@ log "consuming slice/negative, the wrong expectation ($(elapsed))" STAGE=check status=0 summary=$(python3 "$HELPER" check --suite "$SUITE" --work "$WORK" --modes "$MODE_WORDS" --rev "$REV" \ - --provenance "$PROVENANCE" --caseset "$CASESET") || status=$? + --provenance "$PROVENANCE" --repo "$REPO_STATE" --caseset "$CASESET") || status=$? log "done in $(elapsed); logs and reports in $WORK" case "$status:$summary" in "0:MEGA-EEST "*" result=pass" | "1:MEGA-EEST "*" result=FAIL" | "2:MEGA-EEST "*" result=INCOMPLETE" \ @@ -372,7 +394,7 @@ case "$status" in 1) log "a case that fails pins behaviour of the Satin specification: fix the change, or, when it" \ "changes that behaviour on purpose, change the case in Mega EEST first and move the pin" \ "(AGENTS.md, the Mega EEST gate)" ;; - 3) log "the cases passed, but the pin is refused (provenance=$PROVENANCE caseset=$CASESET)" ;; + 3) log "the cases passed, but the pin is refused (provenance=$PROVENANCE repo=$REPO_STATE caseset=$CASESET)" ;; esac FINISHED=1 exit "$status" diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 4e177c27e..17603605b 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -311,7 +311,7 @@ def test_every_case_passing_in_both_modes_is_a_full_pass(self) -> None: self.assertEqual(code, 0, err) self.assertEqual(out.strip(), f"MEGA-EEST rev={'f' * 40} run=full cases=2 " "plain=pass:2,fail:0,unsupported:0,error:0 instrumented=pass:2,fail:0,unsupported:0,error:0 " - "parity=identical negative=fail-as-recorded provenance=unchecked caseset=unchecked result=pass") + "parity=identical negative=fail-as-recorded provenance=unchecked repo=unchecked caseset=unchecked result=pass") def test_one_mode_is_a_partial_run(self) -> None: code, out, err = self.write({"plain": self.all_passed()}, self.NEGATIVE) @@ -415,12 +415,29 @@ def test_passing_cases_need_the_control_to_fail_where_recorded(self) -> None: self.assert_no_verdict(*run, "lists no wrong expectation") self.assertIn("negative=none", run[1]) + def test_a_changed_repository_is_refused(self) -> None: + run = Path(tempfile.mkdtemp(dir=self.tmp)) + (run / "suite" / "slice").mkdir(parents=True) + (run / "work").mkdir() + (run / "suite" / "slice" / "index.json").write_text(json.dumps({ + "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], + "negative": [{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}]})) + (run / "work" / "plain.json").write_text(json.dumps({"cases": self.all_passed()})) + (run / "work" / "plain.exit").write_text("0\n") + (run / "work" / "negative.json").write_text(json.dumps({"cases": self.NEGATIVE})) + for repo, want in (("changed", 3), ("same", 0), ("unchecked", 0)): + code, out, err = self.run_quietly(eest.cmd_check, Namespace( + suite=str(run / "suite"), work=str(run / "work"), modes="plain", rev="f" * 40, + provenance="default-branch", repo=repo, caseset="kept")) + self.assertEqual(code, want, (repo, err)) + self.assertIn(f"repo={repo} caseset=kept", out) + def test_a_refused_pin_exits_3_and_failing_cases_still_exit_1(self) -> None: for provenance, caseset in (("unmerged", "unmoved"), ("default-branch", "undeclared")): code, out, err = self.write({"plain": self.all_passed()}, self.NEGATIVE, provenance=provenance, caseset=caseset) self.assertEqual(code, 3, err) - self.assertIn(f"provenance={provenance} caseset={caseset} result=REFUSED", out) + self.assertIn(f"provenance={provenance} repo=unchecked caseset={caseset} result=REFUSED", out) code, out, _ = self.write({"plain": self.one_failing()}, self.NEGATIVE, provenance="unmerged") self.assertEqual(code, 1) for caseset in ("unmoved", "kept", "declared"): @@ -488,24 +505,40 @@ class CaseDiff(Case): BASE = {"satin/a": "sha256:1", "satin/b": "sha256:2", "satin/c": "sha256:3"} - def diff(self, head: dict[str, str], declared: str = "") -> tuple[int, str, str, str]: + def diff(self, head: dict[str, str], declared: str = "", changes: str = "") -> tuple[int, str, str, str]: run = Path(tempfile.mkdtemp(dir=self.tmp)) for name, cases in (("base.json", self.BASE), ("head.json", head)): (run / name).write_text(json.dumps({"cases": [{"caseId": c, "fileDigest": d} for c, d in cases.items()]})) code, out, err = self.run_quietly(eest.cmd_case_diff, Namespace( base_rev="a" * 40, rev="b" * 40, base_index=str(run / "base.json"), - index=str(run / "head.json"), declared=declared, summary=str(run / "diff.md"))) + index=str(run / "head.json"), declared=declared, declared_changes=changes, + summary=str(run / "diff.md"))) return code, out.strip(), err, (run / "diff.md").read_text() - def test_a_move_that_keeps_every_case_is_kept(self) -> None: - code, out, err, md = self.diff({**self.BASE, "satin/d": "sha256:4", "satin/a": "sha256:9"}) + def test_a_move_that_only_adds_cases_is_kept(self) -> None: + code, out, err, md = self.diff({**self.BASE, "satin/d": "sha256:4"}) self.assertEqual((code, out), (0, "kept"), err) - self.assertIn("0 case(s) removed, 1 added, 1 changed", err) + self.assertIn("0 case(s) removed, 1 added, 0 changed", err) self.assertIn("added satin/d", err) - self.assertIn("changed satin/a", err) self.assertIn("- `satin/d`", md) + def test_changes_under_an_id_must_be_declared_exactly(self) -> None: + head = {**self.BASE, "satin/a": "sha256:9", "satin/d": "sha256:4"} + code, out, err, md = self.diff(head) + self.assertEqual((code, out), (0, "undeclared"), err) + self.assertIn("changed satin/a", err) + self.assertIn("MEGA_EEST_CHANGED_CASES must list exactly", err) + self.assertIn("changed and not declared: satin/a", err) + self.assertIn("Changed (1)", md) + self.assertEqual(self.diff(head, changes="satin/a")[1], "declared") + for changes in ("satin/a satin/b", "satin/b"): + self.assertEqual(self.diff(head, changes=changes)[1], "undeclared", changes) + # A removal and a change, each declared in its own line. + both = {"satin/a": "sha256:9", "satin/b": "sha256:2"} + self.assertEqual(self.diff(both, declared="satin/c", changes="satin/a")[1], "declared") + self.assertEqual(self.diff(both, declared="satin/c satin/a")[1], "undeclared") + def test_removals_must_be_declared_exactly(self) -> None: head = {"satin/a": "sha256:1", "satin/b": "sha256:2"} self.assertEqual(self.diff(head, "satin/c")[1], "declared") @@ -513,7 +546,7 @@ def test_removals_must_be_declared_exactly(self) -> None: code, out, err, md = self.diff(head, declared) self.assertEqual((code, out), (0, "undeclared"), declared) self.assertIn("must list exactly the case ids the pin removes", err) - self.assertIn("removals: **undeclared**", md) + self.assertIn("removals and changes: **undeclared**", md) # A declaration left over from an earlier move, with nothing removed now. self.assertEqual(self.diff(dict(self.BASE), "satin/c")[1], "undeclared") @@ -662,11 +695,13 @@ def commit_cases(self, ids: list[str], branch: str | None = None) -> str: self.git("checkout", "-q", "main", cwd=self.suite) return rev - def run_script(self, rev: str | None = None, declared: str | None = None, + def run_script(self, rev: str | None = None, declared: str | None = None, changed: str | None = None, **env: str) -> tuple[int, str, str]: pin = [f"MEGA_EEST_REPO=file://{self.suite}", f"MEGA_EEST_REV={rev or self.rev}"] if declared is not None: pin.append(f"MEGA_EEST_REMOVED_CASES={declared}") + if changed is not None: + pin.append(f"MEGA_EEST_CHANGED_CASES={changed}") (self.tree / "scripts" / "mega_eest.env").write_text("\n".join(pin) + "\n") run = subprocess.run( ["bash", str(self.tree / "scripts" / "mega_eest.sh")], capture_output=True, text=True, timeout=120, @@ -684,7 +719,7 @@ def test_a_full_run_that_passes_exits_0(self) -> None: self.assertEqual(code, 0, err) line = self.summary(out) self.assertRegex(line, r"^MEGA-EEST rev=[0-9a-f]{40} run=full cases=3 plain=pass:3,.* " - r"instrumented=pass:3,.* provenance=default-branch caseset=unchecked result=pass$") + r"instrumented=pass:3,.* provenance=default-branch repo=unchecked caseset=unchecked result=pass$") self.assertEqual(json.loads((self.tree / "target/mega-eest/capabilities.json").read_text()), {"adapter": "fresh"}) @@ -753,13 +788,46 @@ def test_a_pin_off_the_default_branch_is_refused(self) -> None: code, out, err = self.run_script(rev=draft) self.assertEqual(code, 3, err) self.assertIn("draft state", err) - self.assertRegex(self.summary(out), r" cases=4 .* provenance=unmerged caseset=unchecked result=REFUSED$") + self.assertRegex(self.summary(out), r" cases=4 .* provenance=unmerged repo=unchecked caseset=unchecked result=REFUSED$") # Once merged, the same pin passes. self.git("merge", "-q", "--ff-only", "draft", cwd=self.suite) code, out, err = self.run_script(rev=draft) self.assertEqual(code, 0, err) self.assertIn("provenance=default-branch", self.summary(out)) + def commit_digests(self, digests: dict[str, str]) -> str: + """Commit an index whose cases carry the given file digests (the files stay as they are).""" + index = json.loads((self.suite / "slice" / "index.json").read_text()) + for case in index["cases"]: + case["fileDigest"] = digests.get(case["caseId"], case["fileDigest"]) + (self.suite / "slice" / "index.json").write_text(json.dumps(index)) + self.git("commit", "-qam", "change a case", cwd=self.suite) + return self.git("rev-parse", "HEAD", cwd=self.suite) + + def test_a_pin_move_must_declare_the_cases_it_changes(self) -> None: + base = self.rev + head = self.commit_digests({"satin/b": "sha256:rewritten"}) + code, out, err = self.run_script(rev=head, MEGA_EEST_BASE_REV=base) + self.assertEqual(code, 3, err) + self.assertIn("changed and not declared: satin/b", err) + self.assertIn("caseset=undeclared result=REFUSED", self.summary(out)) + self.assertIn("Changed (1)", (self.tree / "target/mega-eest/case-diff.md").read_text()) + (self.tree / "scripts" / "mega_eest.env").write_text("") # rewritten by run_script + code, out, err = self.run_script(rev=head, changed="satin/b", MEGA_EEST_BASE_REV=base) + self.assertEqual(code, 0, err) + self.assertIn("caseset=declared result=pass", self.summary(out)) + + def test_a_pin_move_to_another_repository_is_refused(self) -> None: + mirror = self.tmp / "mirror" + self.git("clone", "-q", str(self.suite), str(mirror)) + code, out, err = self.run_script(MEGA_EEST_BASE_REV=self.rev, MEGA_EEST_BASE_REPO=f"file://{mirror}") + self.assertEqual(code, 3, err) + self.assertIn("MEGA_EEST_REPO moves from", err) + self.assertIn("repo=changed", self.summary(out)) + code, out, err = self.run_script(MEGA_EEST_BASE_REV=self.rev, MEGA_EEST_BASE_REPO=f"file://{self.suite}") + self.assertEqual(code, 0, err) + self.assertIn("repo=same caseset=unmoved result=pass", self.summary(out)) + def test_a_pin_move_must_declare_the_cases_it_removes(self) -> None: base = self.rev head = self.commit_cases(["satin/a", "satin/b", "satin/e"]) From 810ff3ddb15424b0d02b557b4cc2b57720c2f13c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 16:34:52 +0800 Subject: [PATCH 120/190] ci(mutation): a shard or follow-up record cut off is named, never a crash or a pass --- scripts/mutation_gate.py | 49 ++++++++++++++++++++++++++++------- scripts/mutation_test.sh | 19 +++++++++----- scripts/test_mutation_gate.py | 42 ++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 16 deletions(-) diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index e4e2322ef..a9bb71d1f 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -430,13 +430,18 @@ def progress(results: Path) -> tuple[int | None, int]: expected = len(json.loads(plan.read_text())) if plan.exists() else None record = results / "outcomes.json" if record.exists(): - outcomes = json.loads(record.read_text()).get("outcomes", []) - return expected, sum(1 for o in outcomes if isinstance(o, dict) and outcome_name(o)) + outcomes, _, _, _ = read_record(results) + return expected, sum(1 for o in outcomes if outcome_name(o)) return expected, sum(len(read_lines(results / name)) for name in OUTCOME_FILES) def cmd_progress(args: argparse.Namespace) -> int: - expected, outcomes = progress(Path(args.results)) + try: + expected, outcomes = progress(Path(args.results)) + except (UnreadableRecord, json.JSONDecodeError, OSError) as err: + # The driver then reports status=error: nothing says how far the run got. + print(f"cannot count the run's outcomes: {err}", file=sys.stderr) + return 2 print(f"expected={'unknown' if expected is None else expected} outcomes={outcomes}") return 0 @@ -464,6 +469,7 @@ def read_status(path: Path) -> dict[str, str] | None: "no-status": "it ended without a status line (cancelled, killed by the job timeout, " "or crashed)", "no-artifact": "it uploaded no results", + "unreadable": "its results cannot be read (a record cut off while it was written)", } BUDGET_STATES = ("partial", "not-started", "followup-stopped") @@ -515,16 +521,27 @@ def incomplete_note(status: dict[str, str]) -> str: f"mutants tested).{tail}") +class UnreadableRecord(Exception): + """A results directory whose record cannot be read: a run cut off while it wrote it.""" + + def read_record(results: Path) -> tuple[list[dict], list[str], object, bool]: """A results directory's outcomes, its selection, its end_time, and whether its run - exited abnormally; no outcomes for a directory without outcomes.json.""" + exited abnormally; no outcomes for a directory without outcomes.json. Raises + UnreadableRecord for a record that is not a run's (truncated, say).""" failed = (results / RUN_FAILED_NOTE).exists() path = results / "outcomes.json" - if not path.exists(): - return [], read_selection(results) or [], None, failed - data = json.loads(path.read_text()) + try: + selection = read_selection(results) or [] + if not path.exists(): + return [], selection, None, failed + data = json.loads(path.read_text()) + if not isinstance(data, dict) or not isinstance(data.get("outcomes", []), list): + raise TypeError("not an object with a list of outcomes") + except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ResultsError) as err: + raise UnreadableRecord(f"{results} cannot be read: {err}") from err outcomes = [o for o in data.get("outcomes", []) if isinstance(o, dict)] - return outcomes, read_selection(results) or [], data.get("end_time"), failed + return outcomes, selection, data.get("end_time"), failed def outcome_name(outcome: dict) -> str | None: @@ -593,7 +610,14 @@ def cmd_merge(args: argparse.Namespace) -> int: print(f"| `{shard}` | {line} |") plan = (status or {}).get("expected", "") shard_plans.append(int(plan) if plan.isdigit() else None) - shard_outcomes, _, end_time, _ = read_record(shard / "mutants.out") + try: + shard_outcomes, _, end_time, _ = read_record(shard / "mutants.out") + except UnreadableRecord as err: + # Named, whatever its status line says; the other shards are still reported. + shard_states[-1] = "unreadable" + print(f"| `{shard}` | unreadable: {err} |") + finished = False + continue if shard_outcomes and not end_time: finished = False for o in copy_logs(shard / "mutants.out", results, f"shard{i}", shard_outcomes): @@ -655,7 +679,12 @@ def cmd_merge_runs(args: argparse.Namespace) -> int: finished = True failed: list[str] = [] for i, run in enumerate(present): - run_outcomes, run_selection, end_time, run_failed = read_record(run) + try: + run_outcomes, run_selection, end_time, run_failed = read_record(run) + except UnreadableRecord as err: + failed.append(str(err)) + finished = False + continue if run_failed: failed.append(f"{run}: {(run / RUN_FAILED_NOTE).read_text().strip()}") if not end_time: diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 7d64815e9..6d581988c 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -209,17 +209,23 @@ CLEARED="" # shellcheck disable=SC2329 # the EXIT trap below runs it finish() { - local rc=$? status=error expected=unknown outcomes=0 counts - if [[ -n "$CLEARED" ]] && counts="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" progress --results "$OUT_DIR/mutants.out")"; then - expected="${counts#expected=}" - expected="${expected%% *}" - outcomes="${counts##*outcomes=}" + local rc=$? status=error expected=unknown outcomes=0 counts counted=1 + if [[ -n "$CLEARED" ]]; then + if counts="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" progress --results "$OUT_DIR/mutants.out")"; then + expected="${counts#expected=}" + expected="${expected%% *}" + outcomes="${counts##*outcomes=}" + else + # A record that cannot be counted (cut off while written) says nothing of how far the + # run got: the status is error, whatever the run's exit. + counted="" + fi fi case "$RESULT" in ran) # cargo-mutants exits 0 without an output directory when no mutant # intersects the diff: nothing was planned. - [[ "$expected" == unknown ]] && expected=0 + [[ "$expected" == unknown && -n "$counted" ]] && expected=0 [[ "$expected" == "$outcomes" ]] && status=complete ;; stopped) @@ -233,6 +239,7 @@ finish() { ;; baseline-failed) status=baseline-failed ;; esac + [[ -n "$counted" ]] || status=error [[ "$status" == complete && -n "$FOLLOWUP_STOPPED" ]] && status=followup-stopped local line="MUTANTS-STATUS status=$status expected=$expected outcomes=$outcomes" mkdir -p "$OUT_DIR" diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py index 81e553b9e..f909b92a1 100644 --- a/scripts/test_mutation_gate.py +++ b/scripts/test_mutation_gate.py @@ -797,6 +797,9 @@ def bash5() -> str | None: if [ -d "$FAKE_RUNS/$run" ]; then mkdir -p "$out/mutants.out" cp -R "$FAKE_RUNS/$run/." "$out/mutants.out/" + if [ -n "${FAKE_TRUNCATE:-}" ] && [ "$run" = main ]; then + printf '{"outcomes": [' > "$out/mutants.out/outcomes.json" + fi fi exit "$(cat "$FAKE_RUNS/$run.exit")" """ @@ -1015,6 +1018,14 @@ def test_a_finished_run_builds_first_and_reports_complete(self) -> None: "MUTANTS-STATUS status=complete expected=2 outcomes=2") self.assertTrue(run.stdout.strip().endswith("MUTANTS-STATUS status=complete expected=2 outcomes=2")) + def test_a_record_that_cannot_be_counted_is_an_error(self) -> None: + runs_main = outcomes_json(mutant(CAUGHT, "CaughtMutant")) + run, runs, out = self.drive("file", "crates/mega-evm/src/a.rs", main=runs_main, + env={"FAKE_TRUNCATE": "1"}) + self.assertEqual(run.returncode, 1, run.stderr) + self.assertEqual((out / "status").read_text().strip(), + "MUTANTS-STATUS status=error expected=unknown outcomes=0") + def test_a_warm_build_that_fails_is_a_failed_baseline(self) -> None: run, runs, out = self.drive("file", "crates/mega-evm/src/a.rs", main=outcomes_json( mutant(CAUGHT, "CaughtMutant")), env={"FAKE_WARM_EXIT": "101"}) @@ -1311,6 +1322,15 @@ def test_counts_the_outcomes_the_record_holds(self) -> None: selected=[CAUGHT, MISSED, UNVIABLE]) self.assertEqual(self.progress(results), "expected=3 outcomes=2") + def test_a_record_cut_off_cannot_be_counted(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"))) + (results / "outcomes.json").write_text('{"outcomes": [{"scen') + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + code = gate.cmd_progress(Namespace(results=str(results))) + self.assertEqual(code, 2) + self.assertIn("cannot count", err.getvalue()) + def test_counts_the_plan_and_the_outcome_lists(self) -> None: results = self.results(selected=[CAUGHT, MISSED, UNVIABLE, TIMEOUT, "x"], files={ "caught.txt": f"{CAUGHT}\n", "missed.txt": f"{MISSED}\n", "unviable.txt": f"{UNVIABLE}\n"}) @@ -1529,6 +1549,21 @@ def test_shard_plans_that_miss_inventory_mutants_are_a_mismatch(self) -> None: self.assertEqual(code, 1, text) self.assertIn("the shards planned 2 mutants", text) + def test_a_shard_whose_record_is_cut_off_is_named_and_the_run_is_an_error(self) -> None: + a = self.shard("a", "status=complete expected=2 outcomes=2", + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable")) + b = self.shard("b", "status=complete expected=1 outcomes=1", mutant(MISSED, "CaughtMutant")) + record = b / "mutants.out" / "outcomes.json" + record.write_text(record.read_text()[:40]) # killed while cargo-mutants rewrote it + printed = self.merge(a, b) + self.assertIn("unreadable", printed) + self.assertIn("status=error ", self.status()) + self.assertIn("shards=complete,unreadable", self.status()) + code, text = self.merged() + self.assertEqual(code, 1, text) + self.assertIn("shard 1: `unreadable` — its results cannot be read", text) + self.assertIn("caught: 1", text) # the readable shard is still reported + def test_an_empty_inventory_is_refused(self) -> None: (self.tmp / "inventory.txt").write_text("") with contextlib.redirect_stderr(io.StringIO()): @@ -1571,6 +1606,13 @@ def test_an_unfinished_or_failed_run_makes_the_merge_unscorable(self) -> None: with self.assertRaisesRegex(gate.ResultsError, "exited abnormally"): gate.load_run(self.merge_runs(a, c)) + def test_a_run_whose_record_is_cut_off_makes_the_merge_unscorable(self) -> None: + a = self.results("a", outcomes=outcomes_json(mutant(MISSED, "CaughtMutant"))) + b = self.results("b", outcomes=outcomes_json(mutant(TIMEOUT, "CaughtMutant"))) + (b / "outcomes.json").write_text('{"outcomes": [') + with self.assertRaisesRegex(gate.ResultsError, "exited abnormally.*cannot be read"): + gate.load_run(self.merge_runs(a, b)) + def test_no_runs_writes_nothing(self) -> None: self.assertFalse(self.merge_runs(self.tmp / "absent").exists()) From 01113e017ceb18b3205f1ca18a5fb2119931cacd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 16:35:37 +0800 Subject: [PATCH 121/190] docs: changed Mega EEST cases, the repository line, and unsharded follow-ups --- AGENTS.md | 2 +- REVIEW.md | 3 ++- mutants/README.md | 6 +++++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 857368382..8d1d317c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -676,7 +676,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The wrong expectation is the control that shows the pipeline can report a failure: it must fail where it records only when every gating case passed, since when gating cases fail they show that already and a change of behaviour can also move where the control first differs; then it need only have run and not passed. The summary is one `MEGA-EEST` line on stdout, and the exit code says what kind of result it is: 0 pass; 1 the cases failed, the only verdict on this tree (every mode ran to a complete report of exactly the index, a case failed or erred or the modes' observations differ, and the control ran and did not pass, wherever it first differed); 2 no verdict (a fetch, a build, the resolution, a report missing or incomplete, no mode, a control not run or passing, a control that failed elsewhere while every gating case passed, a case the adapter does not support), however the cases would have gone; 3 the cases passed and the pin is refused. The line says `run=full` for both modes, which the gate requires, and `run=partial` for one. - The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and removed ids must be exactly those `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env` declares (`caseset=declared`, or `kept` with none removed); either refusal is exit 3. + The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and the removed ids and the ids of cases changed under them (another file digest) must be exactly those `MEGA_EEST_REMOVED_CASES` and `MEGA_EEST_CHANGED_CASES` in `scripts/mega_eest.env` declare (`caseset=declared`, or `kept` with none removed or changed); when `MEGA_EEST_BASE_REPO` names the base's repository, a pin file naming another is refused (`repo=changed`); each refusal is exit 3. A pin on the branch of a suite change still under review is a draft state: its cases run, and the gate stays red until the pin moves to the merged commit. `MEGA_EEST_SKIP_PROVENANCE=1` (`provenance=unchecked`) is for the mutation gate's runs, whose warm-up checked the pin, and the coverage report; the gate job never sets it and requires `provenance=default-branch`. The `Mega EEST gate` job always runs and becomes a required check once an administrator adds it to the `satin` branch rule: a pull request that changes documentation alone skips the run (`scripts/pull_request_needs_ci.sh`) and the job passes; every other pull request and every push to `satin` runs it. diff --git a/REVIEW.md b/REVIEW.md index 819c12021..bc2d6c04e 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -156,7 +156,8 @@ These checks guard every change to the Satin engine. While the Mega EEST change is under review, the pin may name its branch's commit as a draft state only: the cases run and show in the log, but the gate fails (`provenance=unmerged`, exit 3) until the pin moves to the commit merged on the suite's default branch, which it must before the mega-evm pull request merges. Locally, a Mega EEST checkout at that commit is used with `MEGA_EEST_DIR= scripts/mega_eest.sh` once the pin names it. - Moving the pin is a one-line change and is reviewed as one: the step summary lists the case ids it removes, adds and changes relative to the base's pin, and the suite's own history between the two commits says why. - A removal fails the gate unless the same pull request lists exactly the removed ids in `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env`, so every behaviour the suite stops pinning is a line the reviewer reads in the diff; a move that removes nothing leaves that line empty. + A removal fails the gate unless the same pull request lists exactly the removed ids in `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env`, and so does a case changed under its id (another file digest) unless it is listed exactly in `MEGA_EEST_CHANGED_CASES`, so every behaviour the suite stops pinning, or pins differently, is a line the reviewer reads in the diff; a move that removes or changes nothing leaves both lines empty. + A pull request that changes `MEGA_EEST_REPO` fails the gate (`repo=changed`, exit 3), unless its base has no pin file: the default branch the pin must be on is that repository's. - The coverage report and the mutation gate count the suite too: `scripts/coverage_mega_evm.sh` merges its run into the report Codecov receives, and the cargo-mutants gate runs a mutant the tests miss against it (Mutation testing, below). ### Byte-price grid diff --git a/mutants/README.md b/mutants/README.md index 114d8ffe9..a97dba01f 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -82,6 +82,8 @@ The merged record keeps the contract the gate reads: the inventory as `mutants.j Each shard's own status is folded into the combined status, and the report names every shard that did not complete and why. A shard whose budget ran out makes the combined status `partial` (or `not-started`), one whose baseline failed makes it `baseline-failed`, and one that errored, ended without a status line (cancelled or killed by the job timeout) or uploaded nothing makes it `error`. Every shard outcome is kept. +A shard whose results cannot be read (a record cut off while it was written) is named as `unreadable` and makes the combined status `error`; the other shards are still reported, and a follow-up run whose record cannot be read is refused like one that exited abnormally. +A shard's re-check and Mega EEST pass are not sharded again: they take the shard's mutants by name, and a shard applied after that selection would cut their own short list (see below). An outcome for a mutant the inventory does not list, a second outcome for one mutant, or shard plans that do not add up to the inventory mean the shards and the inventory were built from different mutant sets: the combined status is `mismatch`, and `unplanned.txt` lists the outcomes that do not fit. Only `complete` passes the gate. A cancelled run is not scored. @@ -116,7 +118,9 @@ It costs nothing while the tests catch every mutant. Otherwise it costs the warm-up (a cold build of the adapter's dependencies when the job's cache holds none, and one run of the suite), cargo-mutants' baseline in its build directory (another run of the suite), the copy of `./target` (now with the warm-up's `target/mega-eest`) into that build directory, and, per mutant, an incremental build of mega-evm for the `mega_eest` test and again for the adapter, and one plain run of the 930 cases: about three minutes a mutant on a 4-vCPU runner, estimated from local runs (30 s a mutant on 15 cores), not measured there. The mutants it runs are those the tests missed, plus any struct-field-deletion mutant in the first run's scope (below), whose outcome the gate does not read. `MUTANTS_MEGA_EEST=0` leaves the pass out, and the mutants it would have run stay survivors. -The re-check and this run take the first run's own scope (its `--in-diff` file or `-f` glob) beside their `--re` selections, because cargo-mutants 27.1.0 adds struct-field-deletion mutants without matching them against `--re`; the gate reads their outcomes only for the mutants it asked about. +The re-check and this run take the first run's own restriction (its `--in-diff` file or `-f` glob) beside their `--re` selections, because cargo-mutants 27.1.0 adds struct-field-deletion mutants without matching them against `--re`; the gate reads their outcomes only for the mutants it asked about. +They never take the first run's `--shard`: cargo-mutants applies a shard after the `--re` selection, so it would cut the follow-up's own short list, extras included, and drop mutants it was asked to decide. +A run with no restriction of its own (the full run, sharded or not) has the follow-ups name the files of their mutants instead (`-f`, from `mutation_gate.py timeout-re`/`missed-re --with-files`), which keeps the extras to those files. ## Suppressions (hybrid) From 30313dde752e6627486de0417c44377050a88cac Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 17:49:14 +0800 Subject: [PATCH 122/190] ci: a Mega EEST refusal names its cause, and a repository move is declared --- .github/workflows/mega-eest.yml | 15 ++-- scripts/mega_eest.env | 9 ++- scripts/mega_eest.py | 54 +++++++++++++-- scripts/mega_eest.sh | 42 +++++++++--- scripts/mutation_test.sh | 6 +- scripts/test_mega_eest.py | 117 +++++++++++++++++++++++++++++--- 6 files changed, 211 insertions(+), 32 deletions(-) diff --git a/.github/workflows/mega-eest.yml b/.github/workflows/mega-eest.yml index 145522eb6..02458c9eb 100644 --- a/.github/workflows/mega-eest.yml +++ b/.github/workflows/mega-eest.yml @@ -18,7 +18,8 @@ name: Mega EEST # removed, added and changed relative to its base's pin in the step summary, where any removal or # change fails the gate unless scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES and # MEGA_EEST_CHANGED_CASES list exactly those ids, lines the reviewer reads in the diff; and a pull -# request that changes MEGA_EEST_REPO fails it, unless the base has no pin file. +# request that changes MEGA_EEST_REPO fails it, unless the base has no pin file or the pull request +# declares the move in MEGA_EEST_REPO_MOVED_FROM. A refusal's annotation names its cause. # # A failing case pins a rule of the Satin specification. A pull request that changes that # behaviour on purpose, or the mega-evm API the adapter calls, changes Mega EEST first (the case or @@ -115,6 +116,7 @@ jobs: echo "rev=$rev" >> "$GITHUB_OUTPUT" base="" base_repo="" + base_moved_from="" if [ "$EVENT" = pull_request ]; then if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then echo "::error::HEAD is not the pull request's merge commit, so the base's pin is unknown" @@ -124,11 +126,15 @@ jobs: if git cat-file -e 'HEAD^1:scripts/mega_eest.env' 2> /dev/null; then base=$(git show 'HEAD^1:scripts/mega_eest.env' | sed -n 's/^MEGA_EEST_REV=\(.*\)$/\1/p') base_repo=$(git show 'HEAD^1:scripts/mega_eest.env' | sed -n 's/^MEGA_EEST_REPO=\(.*\)$/\1/p') + base_moved_from=$(git show 'HEAD^1:scripts/mega_eest.env' | sed -n 's/^MEGA_EEST_REPO_MOVED_FROM=\(.*\)$/\1/p') fi fi echo "the base's pin: ${base:-(none)} in ${base_repo:-(none)}" - echo "base=$base" >> "$GITHUB_OUTPUT" - echo "base_repo=$base_repo" >> "$GITHUB_OUTPUT" + { + echo "base=$base" + echo "base_repo=$base_repo" + echo "base_moved_from=$base_moved_from" + } >> "$GITHUB_OUTPUT" # The job's cargo cache is the step below: setup-rust-toolchain's own cache handles the # workspace's target directory, and this job builds into another. @@ -160,6 +166,7 @@ jobs: REV: ${{ steps.pin.outputs.rev }} MEGA_EEST_BASE_REV: ${{ steps.pin.outputs.base }} MEGA_EEST_BASE_REPO: ${{ steps.pin.outputs.base_repo }} + MEGA_EEST_BASE_REPO_MOVED_FROM: ${{ steps.pin.outputs.base_moved_from }} run: | set -uo pipefail start=$SECONDS @@ -183,7 +190,7 @@ jobs: case "$status" in 0) ;; 1) echo "::error::Mega EEST cases failed on this tree; the failing cases are in the log above and in the uploaded reports" ;; - 3) echo "::error::the cases passed, but the pin is refused: it is not on Mega EEST's default branch, or it removes cases scripts/mega_eest.env does not declare (see the log)" ;; + 3) echo "::error::the cases passed, but the pin is refused: $(python3 scripts/mega_eest.py refusal --summary "$line")" ;; *) echo "::error::the Mega EEST run reached no verdict (exit $status): see the log for the step that failed" ;; esac [ "$status" -eq 0 ] || exit "$status" diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index 82634f94e..32c7267c6 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -13,7 +13,12 @@ MEGA_EEST_REV=5e4007b47ce62c2af2b7bf770677b0e6baf1a8d2 # digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice # drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none # leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a -# change is a line the reviewer reads in this file's diff. Changing MEGA_EEST_REPO also fails the -# gate: the default branch the pin must be on is that repository's. +# change is a line the reviewer reads in this file's diff. MEGA_EEST_REMOVED_CASES= MEGA_EEST_CHANGED_CASES= +# The repository the suite moved from, exactly as the base's MEGA_EEST_REPO reads, set by the pull +# request that changes MEGA_EEST_REPO: the default branch the pin must be on is that repository's, +# so a change of repository fails the gate unless it is declared here, and the pin must then be on +# the new repository's default branch. A pull request that keeps MEGA_EEST_REPO and sets this line +# fails the gate as stale; the line a merged move left only warns, and is cleared later. +MEGA_EEST_REPO_MOVED_FROM= diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index dbec4e2ec..ea8e12cac 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -43,7 +43,8 @@ `undeclared` (anything else). check --suite --work --modes <"plain instrumented"> --rev - [--provenance ] [--repo ] + [--provenance ] + [--repo ] [--caseset ] Read the run reports `mega-fixture consume` wrote into (.json, and negative.json for the suite's deliberately wrong expectation) and decide: in every mode, the @@ -62,9 +63,15 @@ consume exit its report does not explain, a case the adapter does not support, a case status other than the consumer's four (pass, fail, unsupported, error), no control, a control not run or passing, a control that failed elsewhere while every gating case - passed, or the checker itself failing); 3 REFUSED, every case passed but the pin's - provenance is `unmerged`, its repository is not the base's (`repo=changed`) or its case set - `undeclared`. `run=full` in the line is both + passed, or the checker itself failing); 3 REFUSED, every case passed but the pin is refused + for a cause `refusal` names: its provenance is `unmerged`; its repository is not the base's + and no declaration names the base's (`repo=changed`); a declaration names a move the change + does not make (`repo=stale`); its repository moves and its provenance is unchecked; or its + case set is `undeclared`. + + refusal --summary + The causes for which the pin of a summary line is refused, one sentence, from the line's + fields: what the job's annotation and the script's log say on exit 3. `run=full` in the line is both modes; `run=partial` one. """ from __future__ import annotations @@ -537,7 +544,7 @@ def check(args: argparse.Namespace) -> int: result = "INCOMPLETE" elif cases_failed: result = "FAIL" - elif args.provenance == "unmerged" or args.caseset == "undeclared" or repo == "changed": + elif refusal_causes({"provenance": args.provenance, "repo": repo, "caseset": args.caseset}): result = "REFUSED" else: result = "pass" @@ -548,6 +555,37 @@ def check(args: argparse.Namespace) -> int: return RESULT_EXIT[result] +# ---- refusal ---------------------------------------------------------------------------------- + +# Why a run whose cases passed refuses its pin, by the summary line's fields: the checker refuses a +# pin for exactly these, and the job's annotation and the script's log name them from the same list. +def refusal_causes(fields: dict[str, str]) -> list[str]: + causes = [] + if fields.get("provenance") == "unmerged": + causes.append("the pin is not on the default branch of MEGA_EEST_REPO (provenance=unmerged)") + repo = fields.get("repo") + if repo == "changed": + causes.append("MEGA_EEST_REPO is not the base's, and MEGA_EEST_REPO_MOVED_FROM does not name the " + "base's repository (repo=changed)") + elif repo == "stale": + causes.append("MEGA_EEST_REPO_MOVED_FROM declares a move from another repository, and this " + "change makes none: clear it (repo=stale)") + elif repo == "moved" and fields.get("provenance") == "unchecked": + causes.append("MEGA_EEST_REPO moves, and the pin is not checked to be on the new repository's " + "default branch (repo=moved provenance=unchecked)") + if fields.get("caseset") == "undeclared": + causes.append("the pin removes or changes cases that MEGA_EEST_REMOVED_CASES and " + "MEGA_EEST_CHANGED_CASES do not list exactly (caseset=undeclared)") + return causes + + +def cmd_refusal(args: argparse.Namespace) -> int: + fields = dict(f.split("=", 1) for f in args.summary.split() if "=" in f) + causes = refusal_causes(fields) + print("; ".join(causes) if causes else f"no refusal cause in the summary line: {args.summary}") + return 0 + + # ---- executable, case-diff -------------------------------------------------------------------- @@ -640,11 +678,15 @@ def main() -> int: pc.add_argument("--modes", required=True) pc.add_argument("--rev", required=True) pc.add_argument("--provenance", default="unchecked", choices=["default-branch", "unmerged", "unchecked"]) - pc.add_argument("--repo", default="unchecked", choices=["same", "changed", "unchecked"]) + pc.add_argument("--repo", default="unchecked", choices=["same", "moved", "changed", "stale", "unchecked"]) pc.add_argument("--caseset", default="unchecked", choices=["unmoved", "kept", "declared", "undeclared", "unchecked"]) pc.set_defaults(func=cmd_check) + pr = sub.add_parser("refusal", help="why a summary line's pin is refused, by its fields") + pr.add_argument("--summary", required=True) + pr.set_defaults(func=cmd_refusal) + pe = sub.add_parser("executable", help="the executable a cargo build reported, from its JSON messages") pe.add_argument("--name", required=True) pe.set_defaults(func=cmd_executable) diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index 0de0683b8..23243c4dc 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -20,7 +20,10 @@ # $MEGA_EEST_WORK/case-diff.md), and the removed ids and the ids of cases changed under them # (another file digest) must be exactly those scripts/mega_eest.env's MEGA_EEST_REMOVED_CASES and # MEGA_EEST_CHANGED_CASES declare, or the script exits 3. When MEGA_EEST_BASE_REPO names the -# base's repository, a pin file that names another one exits 3 too. +# base's repository, a pin file that names another one exits 3 too, unless its +# MEGA_EEST_REPO_MOVED_FROM names the base's repository exactly (a declared move); a declaration +# of a move the change does not make exits 3 as stale, unless it is the base's own +# (MEGA_EEST_BASE_REPO_MOVED_FROM), which then only warns. # 4. Builds the suite's `mega-fixture` CLI, and its revm adapter against this checkout: the adapter # is written out as a workspace of its own ($MEGA_EEST_WORK/adapter-revm, by scripts/mega_eest.py) # whose mega-evm is a path dependency on crates/mega-evm here, whose other crates take their @@ -51,7 +54,7 @@ # # MEGA-EEST rev= run= cases= =pass:,fail:,unsupported:,error: ... # [parity=] negative=<...> provenance= -# repo= caseset= +# repo= caseset= # result= # # `run=full` is both modes, which the gate requires; `run=partial` is one, which the mutation gate @@ -70,8 +73,9 @@ # not support, no mode, a wrong expectation not run or passing, or one that failed elsewhere # while every gating case passed (result=INCOMPLETE) # 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, in another -# repository than the base's, or it removes or changes cases scripts/mega_eest.env does not -# declare (result=REFUSED) +# repository than the base's without a declared move, with a stale move declaration, or it +# removes or changes cases scripts/mega_eest.env does not declare (result=REFUSED; the log +# names the cause) # # Environment: # MEGA_EEST_DIR a Mega EEST checkout at the pin to use instead of fetching one @@ -82,6 +86,7 @@ # MEGA_EEST_JOBS cases run at once (default: the number of CPUs) # MEGA_EEST_BASE_REV the pin to compare the case set with (CI: the pull request base's pin) # MEGA_EEST_BASE_REPO the repository the base's pin file names (CI: when the base has the file) +# MEGA_EEST_BASE_REPO_MOVED_FROM the base pin file's MEGA_EEST_REPO_MOVED_FROM (CI: likewise) # MEGA_EEST_SKIP_PROVENANCE=1 # skips step 2 (provenance=unchecked): for the mutation gate's runs, which # its warm-up already checked, and the coverage report; never the gate @@ -171,6 +176,7 @@ REV=$(read_pin MEGA_EEST_REV) [[ "$REV" =~ ^[0-9a-f]{40}$ ]] || die "$PIN_FILE: MEGA_EEST_REV is '$REV', not a full commit hash" DECLARED_REMOVALS=$(read_optional MEGA_EEST_REMOVED_CASES) DECLARED_CHANGES=$(read_optional MEGA_EEST_CHANGED_CASES) +MOVED_FROM=$(read_optional MEGA_EEST_REPO_MOVED_FROM) # The paths of a checkout that decide what runs: a change to any of them is a different suite. SUITE_PATHS=(slice specs adapters crates Cargo.toml Cargo.lock) @@ -282,15 +288,31 @@ else fi # The repository against the base's, when it is given: the default branch the provenance check -# reads is the pin repository's own, so a change of repository is a change of what is trusted. +# reads is the pin repository's own, so a change of repository is a change of what is trusted, and +# is declared as a removed or changed case is. A move names the base's repository in +# MEGA_EEST_REPO_MOVED_FROM, exactly, and its pin is then checked on the new repository's default +# branch; a declaration of a move the change does not make is stale, unless it is the base's own, +# left by the move that merged, which the line describes until it is cleared. REPO_STATE=unchecked if [ -n "${MEGA_EEST_BASE_REPO:-}" ]; then - if [ "$MEGA_EEST_BASE_REPO" = "$REPO" ]; then + if [ "$MEGA_EEST_BASE_REPO" != "$REPO" ]; then + if [ "$MOVED_FROM" = "$MEGA_EEST_BASE_REPO" ]; then + REPO_STATE=moved + log "MEGA_EEST_REPO moves from $MEGA_EEST_BASE_REPO to $REPO, as MEGA_EEST_REPO_MOVED_FROM declares" + else + REPO_STATE=changed + log "error: MEGA_EEST_REPO moves from $MEGA_EEST_BASE_REPO to $REPO, and MEGA_EEST_REPO_MOVED_FROM" \ + "is '$MOVED_FROM', not the base's repository" + fi + elif [ -z "$MOVED_FROM" ]; then + REPO_STATE=same + elif [ "$MOVED_FROM" = "${MEGA_EEST_BASE_REPO_MOVED_FROM:-}" ]; then REPO_STATE=same + log "warning: MEGA_EEST_REPO_MOVED_FROM still declares the last move, from $MOVED_FROM; clear it" else - REPO_STATE=changed - log "error: MEGA_EEST_REPO moves from $MEGA_EEST_BASE_REPO to $REPO; the suite's repository is" \ - "not changed in a pull request that runs this gate" + REPO_STATE=stale + log "error: MEGA_EEST_REPO_MOVED_FROM declares a move from $MOVED_FROM, and MEGA_EEST_REPO stays" \ + "$REPO" fi fi @@ -394,7 +416,7 @@ case "$status" in 1) log "a case that fails pins behaviour of the Satin specification: fix the change, or, when it" \ "changes that behaviour on purpose, change the case in Mega EEST first and move the pin" \ "(AGENTS.md, the Mega EEST gate)" ;; - 3) log "the cases passed, but the pin is refused (provenance=$PROVENANCE repo=$REPO_STATE caseset=$CASESET)" ;; + 3) log "the cases passed, but the pin is refused: $(python3 "$HELPER" refusal --summary "$summary")" ;; esac FINISHED=1 exit "$status" diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 6d581988c..c307a8b46 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -452,7 +452,8 @@ run_missed_against_mega_eest() { # MEGA_EEST_SCRIPT stands in for the script in the driver's own tests. The warm-up checks the # pin's provenance; no case set is compared here, the Mega EEST gate does that. It counts # against the budget, as the whole pass does. - run_bounded env -u MEGA_EEST_BASE_REV MEGA_EEST_MODES=plain \ + run_bounded env -u MEGA_EEST_BASE_REV -u MEGA_EEST_BASE_REPO -u MEGA_EEST_BASE_REPO_MOVED_FROM \ + MEGA_EEST_MODES=plain \ "${MEGA_EEST_SCRIPT:-$ROOT_DIR/scripts/mega_eest.sh}" \ > "$OUT_DIR/mega-eest-warmup.log" 2>&1 || rc=$? if [[ $rc -eq 124 ]]; then @@ -477,7 +478,8 @@ run_missed_against_mega_eest() { # the cases on the same cores, against a timeout the baseline set alone. On a 4-vCPU runner a # mutant is about three minutes (an incremental build of mega-evm for the test and again for # the adapter, and the 930 plain cases), estimated from local runs, not measured there. - run_bounded env -u MEGA_EEST_WORK -u MEGA_EEST_TARGET_DIR -u MEGA_EEST_BASE_REV \ + run_bounded env -u MEGA_EEST_WORK -u MEGA_EEST_TARGET_DIR \ + -u MEGA_EEST_BASE_REV -u MEGA_EEST_BASE_REPO -u MEGA_EEST_BASE_REPO_MOVED_FROM \ MEGA_EEST_DIR="${MEGA_EEST_DIR:-${MEGA_EEST_WORK:-$ROOT_DIR/target/mega-eest}/src}" \ MEGA_EEST_MODES=plain MEGA_EEST_SKIP_PROVENANCE=1 cargo mutants \ "${PKG_ARGS[@]}" \ diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 17603605b..96db5dcde 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -25,6 +25,7 @@ from pathlib import Path SCRIPTS = Path(__file__).resolve().parent +ROOT = SCRIPTS.parent def load_script(name: str): @@ -425,12 +426,15 @@ def test_a_changed_repository_is_refused(self) -> None: (run / "work" / "plain.json").write_text(json.dumps({"cases": self.all_passed()})) (run / "work" / "plain.exit").write_text("0\n") (run / "work" / "negative.json").write_text(json.dumps({"cases": self.NEGATIVE})) - for repo, want in (("changed", 3), ("same", 0), ("unchecked", 0)): + for provenance, repo, want in (("default-branch", "changed", 3), ("default-branch", "stale", 3), + ("default-branch", "moved", 0), ("unchecked", "moved", 3), + ("default-branch", "same", 0), ("unchecked", "same", 0), + ("default-branch", "unchecked", 0)): code, out, err = self.run_quietly(eest.cmd_check, Namespace( suite=str(run / "suite"), work=str(run / "work"), modes="plain", rev="f" * 40, - provenance="default-branch", repo=repo, caseset="kept")) - self.assertEqual(code, want, (repo, err)) - self.assertIn(f"repo={repo} caseset=kept", out) + provenance=provenance, repo=repo, caseset="kept")) + self.assertEqual(code, want, (provenance, repo, err)) + self.assertIn(f"provenance={provenance} repo={repo} caseset=kept", out) def test_a_refused_pin_exits_3_and_failing_cases_still_exit_1(self) -> None: for provenance, caseset in (("unmerged", "unmoved"), ("default-branch", "undeclared")): @@ -457,6 +461,54 @@ def test_a_checker_that_cannot_read_the_run_is_no_verdict(self) -> None: self.assertTrue(out.strip().endswith("stage=check result=INCOMPLETE"), out) +class Refusal(Case): + """The causes a refused run's annotation and log name, read off the summary line.""" + + LINE = "MEGA-EEST rev={} run=full cases=2 negative=fail-as-recorded {} result=REFUSED".format("f" * 40, "{}") + + def refusal(self, fields: str) -> str: + code, out, _ = self.run_quietly(eest.cmd_refusal, Namespace(summary=self.LINE.format(fields))) + self.assertEqual(code, 0) + return out.strip() + + def test_each_cause_is_named_by_its_field(self) -> None: + for fields, cause in ( + ("provenance=unmerged repo=same caseset=kept", "(provenance=unmerged)"), + ("provenance=default-branch repo=changed caseset=kept", "(repo=changed)"), + ("provenance=default-branch repo=stale caseset=kept", "(repo=stale)"), + ("provenance=unchecked repo=moved caseset=kept", "(repo=moved provenance=unchecked)"), + ("provenance=default-branch repo=same caseset=undeclared", "(caseset=undeclared)")): + said = self.refusal(fields) + self.assertTrue(said.endswith(cause), (fields, said)) + self.assertNotIn(";", said, fields) + + def test_several_causes_are_all_named(self) -> None: + said = self.refusal("provenance=unmerged repo=changed caseset=undeclared") + for cause in ("(provenance=unmerged)", "(repo=changed)", "(caseset=undeclared)"): + self.assertIn(cause, said) + + def test_the_checker_refuses_exactly_for_a_cause(self) -> None: + for provenance in ("default-branch", "unmerged", "unchecked"): + for repo in ("same", "moved", "changed", "stale", "unchecked"): + for caseset in ("unmoved", "kept", "declared", "undeclared", "unchecked"): + fields = {"provenance": provenance, "repo": repo, "caseset": caseset} + refused = (provenance == "unmerged" or repo in ("changed", "stale") + or (repo == "moved" and provenance == "unchecked") or caseset == "undeclared") + self.assertEqual(bool(eest.refusal_causes(fields)), refused, fields) + + def test_the_jobs_annotation_names_the_cause(self) -> None: + workflow = (ROOT / ".github" / "workflows" / "mega-eest.yml").read_text() + arms = [line.strip() for line in workflow.splitlines() if line.strip().startswith("3) echo \"::error::")] + self.assertEqual(len(arms), 1, arms) + line = self.LINE.format("provenance=default-branch repo=same caseset=undeclared") + run = subprocess.run(["bash", "-c", f'status=3; case "$status" in {arms[0]} esac', "_"], + cwd=ROOT, env={"PATH": f"{Path(sys.executable).parent}:/usr/bin:/bin", + "line": line}, capture_output=True, text=True, timeout=60) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn("MEGA_EEST_CHANGED_CASES do not list exactly (caseset=undeclared)", run.stdout) + self.assertNotIn("not on Mega EEST's default branch", run.stdout) + + class Executable(Case): """The executable is the one cargo reported building, not a file at a guessed path.""" @@ -696,8 +748,10 @@ def commit_cases(self, ids: list[str], branch: str | None = None) -> str: return rev def run_script(self, rev: str | None = None, declared: str | None = None, changed: str | None = None, - **env: str) -> tuple[int, str, str]: + moved_from: str | None = None, **env: str) -> tuple[int, str, str]: pin = [f"MEGA_EEST_REPO=file://{self.suite}", f"MEGA_EEST_REV={rev or self.rev}"] + if moved_from is not None: + pin.append(f"MEGA_EEST_REPO_MOVED_FROM={moved_from}") if declared is not None: pin.append(f"MEGA_EEST_REMOVED_CASES={declared}") if changed is not None: @@ -817,17 +871,64 @@ def test_a_pin_move_must_declare_the_cases_it_changes(self) -> None: self.assertEqual(code, 0, err) self.assertIn("caseset=declared result=pass", self.summary(out)) - def test_a_pin_move_to_another_repository_is_refused(self) -> None: + def mirror(self) -> str: + """Another repository holding the suite's history: the base's, for a move from it.""" mirror = self.tmp / "mirror" - self.git("clone", "-q", str(self.suite), str(mirror)) - code, out, err = self.run_script(MEGA_EEST_BASE_REV=self.rev, MEGA_EEST_BASE_REPO=f"file://{mirror}") + if not mirror.exists(): + self.git("clone", "-q", str(self.suite), str(mirror)) + return f"file://{mirror}" + + def test_a_pin_move_to_another_repository_is_refused(self) -> None: + mirror = self.mirror() + code, out, err = self.run_script(MEGA_EEST_BASE_REV=self.rev, MEGA_EEST_BASE_REPO=mirror) self.assertEqual(code, 3, err) self.assertIn("MEGA_EEST_REPO moves from", err) self.assertIn("repo=changed", self.summary(out)) + self.assertIn("the pin is refused: MEGA_EEST_REPO is not the base's", err) code, out, err = self.run_script(MEGA_EEST_BASE_REV=self.rev, MEGA_EEST_BASE_REPO=f"file://{self.suite}") self.assertEqual(code, 0, err) self.assertIn("repo=same caseset=unmoved result=pass", self.summary(out)) + def test_a_declared_repository_move_passes(self) -> None: + mirror = self.mirror() + code, out, err = self.run_script(moved_from=mirror, MEGA_EEST_BASE_REV=self.rev, MEGA_EEST_BASE_REPO=mirror) + self.assertEqual(code, 0, err) + self.assertIn("as MEGA_EEST_REPO_MOVED_FROM declares", err) + self.assertIn("provenance=default-branch repo=moved caseset=unmoved result=pass", self.summary(out)) + + def test_a_declared_move_from_another_repository_than_the_bases_is_refused(self) -> None: + mirror = self.mirror() + code, out, err = self.run_script(moved_from=f"{mirror}-elsewhere", MEGA_EEST_BASE_REV=self.rev, + MEGA_EEST_BASE_REPO=mirror) + self.assertEqual(code, 3, err) + self.assertIn(f"is '{mirror}-elsewhere', not the base's repository", err) + self.assertIn("repo=changed caseset=kept result=REFUSED", self.summary(out)) + + def test_a_declared_move_whose_pin_is_off_the_new_default_branch_is_refused(self) -> None: + mirror = self.mirror() + off = self.commit_cases(["satin/a", "satin/b", "satin/c", "satin/d"], branch="draft") + code, out, err = self.run_script(rev=off, moved_from=mirror, MEGA_EEST_BASE_REV=self.rev, + MEGA_EEST_BASE_REPO=mirror) + self.assertEqual(code, 3, err) + self.assertIn("provenance=unmerged repo=moved", self.summary(out)) + self.assertIn("the pin is refused: the pin is not on the default branch", err) + + def test_a_move_declaration_without_a_move_is_stale(self) -> None: + mirror = self.mirror() + code, out, err = self.run_script(moved_from=mirror, MEGA_EEST_BASE_REV=self.rev, + MEGA_EEST_BASE_REPO=f"file://{self.suite}") + self.assertEqual(code, 3, err) + self.assertIn(f"declares a move from {mirror}", err) + self.assertIn("repo=stale caseset=unmoved result=REFUSED", self.summary(out)) + self.assertIn("(repo=stale)", err) + # The declaration a merged move left in the base only warns, until it is cleared. + code, out, err = self.run_script(moved_from=mirror, MEGA_EEST_BASE_REV=self.rev, + MEGA_EEST_BASE_REPO=f"file://{self.suite}", + MEGA_EEST_BASE_REPO_MOVED_FROM=mirror) + self.assertEqual(code, 0, err) + self.assertIn("still declares the last move", err) + self.assertIn("repo=same caseset=unmoved result=pass", self.summary(out)) + def test_a_pin_move_must_declare_the_cases_it_removes(self) -> None: base = self.rev head = self.commit_cases(["satin/a", "satin/b", "satin/e"]) From 7da3c5ffb72c6cbd5d0a786ba62b5345a003a53c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 17:49:42 +0800 Subject: [PATCH 123/190] docs: a declared Mega EEST repository move, and the named refusal causes --- AGENTS.md | 2 +- REVIEW.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8d1d317c9..46dbc3157 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -676,7 +676,7 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The wrong expectation is the control that shows the pipeline can report a failure: it must fail where it records only when every gating case passed, since when gating cases fail they show that already and a change of behaviour can also move where the control first differs; then it need only have run and not passed. The summary is one `MEGA-EEST` line on stdout, and the exit code says what kind of result it is: 0 pass; 1 the cases failed, the only verdict on this tree (every mode ran to a complete report of exactly the index, a case failed or erred or the modes' observations differ, and the control ran and did not pass, wherever it first differed); 2 no verdict (a fetch, a build, the resolution, a report missing or incomplete, no mode, a control not run or passing, a control that failed elsewhere while every gating case passed, a case the adapter does not support), however the cases would have gone; 3 the cases passed and the pin is refused. The line says `run=full` for both modes, which the gate requires, and `run=partial` for one. - The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and the removed ids and the ids of cases changed under them (another file digest) must be exactly those `MEGA_EEST_REMOVED_CASES` and `MEGA_EEST_CHANGED_CASES` in `scripts/mega_eest.env` declare (`caseset=declared`, or `kept` with none removed or changed); when `MEGA_EEST_BASE_REPO` names the base's repository, a pin file naming another is refused (`repo=changed`); each refusal is exit 3. + The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and the removed ids and the ids of cases changed under them (another file digest) must be exactly those `MEGA_EEST_REMOVED_CASES` and `MEGA_EEST_CHANGED_CASES` in `scripts/mega_eest.env` declare (`caseset=declared`, or `kept` with none removed or changed); when `MEGA_EEST_BASE_REPO` names the base's repository, a pin file naming another is refused (`repo=changed`) unless its `MEGA_EEST_REPO_MOVED_FROM` names the base's exactly (`repo=moved`, the pin on the new repository's default branch), and that line set without a move is refused as stale (`repo=stale`) unless the base's carries the same; each refusal is exit 3, and the job's annotation names its causes. A pin on the branch of a suite change still under review is a draft state: its cases run, and the gate stays red until the pin moves to the merged commit. `MEGA_EEST_SKIP_PROVENANCE=1` (`provenance=unchecked`) is for the mutation gate's runs, whose warm-up checked the pin, and the coverage report; the gate job never sets it and requires `provenance=default-branch`. The `Mega EEST gate` job always runs and becomes a required check once an administrator adds it to the `satin` branch rule: a pull request that changes documentation alone skips the run (`scripts/pull_request_needs_ci.sh`) and the job passes; every other pull request and every push to `satin` runs it. diff --git a/REVIEW.md b/REVIEW.md index bc2d6c04e..a6f8584a7 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -157,7 +157,9 @@ These checks guard every change to the Satin engine. Locally, a Mega EEST checkout at that commit is used with `MEGA_EEST_DIR= scripts/mega_eest.sh` once the pin names it. - Moving the pin is a one-line change and is reviewed as one: the step summary lists the case ids it removes, adds and changes relative to the base's pin, and the suite's own history between the two commits says why. A removal fails the gate unless the same pull request lists exactly the removed ids in `MEGA_EEST_REMOVED_CASES` in `scripts/mega_eest.env`, and so does a case changed under its id (another file digest) unless it is listed exactly in `MEGA_EEST_CHANGED_CASES`, so every behaviour the suite stops pinning, or pins differently, is a line the reviewer reads in the diff; a move that removes or changes nothing leaves both lines empty. - A pull request that changes `MEGA_EEST_REPO` fails the gate (`repo=changed`, exit 3), unless its base has no pin file: the default branch the pin must be on is that repository's. + The default branch the pin must be on is `MEGA_EEST_REPO`'s, so a pull request that changes it fails the gate (`repo=changed`, exit 3) unless its base has no pin file or it declares the move: `MEGA_EEST_REPO_MOVED_FROM` names the base's repository exactly, and the pin is then checked on the new repository's default branch (`repo=moved`). + A pull request that keeps `MEGA_EEST_REPO` and sets that line is refused as stale (`repo=stale`); the line a merged move left in the base only warns, and a later pull request clears it. + A refused run's annotation names its causes, from the summary line's fields. - The coverage report and the mutation gate count the suite too: `scripts/coverage_mega_evm.sh` merges its run into the report Codecov receives, and the cargo-mutants gate runs a mutant the tests miss against it (Mutation testing, below). ### Byte-price grid From e53f583c3830c499553fd6247edb744748d44c88 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 18:40:45 +0800 Subject: [PATCH 124/190] test(limits): remove tests duplicated by the conformance suite The contract and initcode size limits, a stop's bytes from a contract, the data size of a body and of a revert, the transaction limits crossed after hints, and a deposit's body history are pinned by Mega EEST's cases. --- crates/mega-evm/tests/satin/contract_size.rs | 168 ------------------ crates/mega-evm/tests/satin/data_size.rs | 17 -- .../mega-evm/tests/satin/data_size_counts.rs | 31 +--- crates/mega-evm/tests/satin/failed_deposit.rs | 67 ------- .../tests/satin/limit_matrix/limits.rs | 78 +------- crates/mega-evm/tests/satin/main.rs | 1 - crates/mega-evm/tests/satin/outcome.rs | 19 +- 7 files changed, 6 insertions(+), 375 deletions(-) delete mode 100644 crates/mega-evm/tests/satin/contract_size.rs diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs deleted file mode 100644 index 22c935f7b..000000000 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ /dev/null @@ -1,168 +0,0 @@ -//! The code-size limits the Satin configuration raises. -//! -//! A deployed contract may hold 512 KiB, eight times more than EIP-7954's bound and twenty-one -//! times EIP-170's; an initcode may hold twice that, the ratio EIP-3860 sets between the two. -//! Both bounds are `CfgEnv` limits the spec fixes, so they apply to a creation transaction and to -//! a `CREATE` alike. - -use alloy_evm::{Evm, EvmError, InvalidTxError}; -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, - test_utils::{right_pad_bytes, BytecodeBuilder, MemoryDatabase}, - MegaEvm, MegaHaltReason, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{CREATE, INVALID, ISZERO, JUMPDEST, JUMPI, PUSH1, RETURN, STOP}, - context::result::{ExecutionResult, HaltReason, InvalidTransaction}, -}; - -use crate::common::{call, context, create, history}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const FACTORY: Address = address!("0000000000000000000000000000000000100001"); - -/// Room for everything a creation here draws, all of it above the execution cap so it comes out of -/// the reservoir: the state gas of the largest deployable code, the history of that code and of a -/// body carrying twice the largest init code, and a billion more, at the byte prices in effect. -fn gas_limit() -> u64 { - TX_GAS_LIMIT_CAP + - MAX_CONTRACT_SIZE as u64 * - mega_evm::satin_gas_params() - .get(revm::context_interface::cfg::GasId::code_deposit_state_gas()) + - history((MAX_CONTRACT_SIZE + 2 * MAX_INITCODE_SIZE) as u64) + - 1_000_000_000 -} - -/// Runs `tx` from `CALLER` and returns its result, or the validation error that rejected it. -fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result, String> { - let mut evm = MegaEvm::new(context(db)); - match evm.transact_raw(tx) { - Ok(outcome) => Ok(outcome.result), - Err(err) => { - let invalid = err - .as_invalid_tx_err() - .and_then(InvalidTxError::as_invalid_tx_err) - .unwrap_or_else(|| panic!("unexpected error {err:?}")); - Err(format!("{invalid:?}")) - } - } -} - -/// Runs `init_code` as a creation transaction from `CALLER`. -fn deploy(init_code: Bytes) -> Result, String> { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - run(create(CALLER, init_code, gas_limit()), db) -} - -/// Init code of `size` bytes that does nothing. -fn initcode_of(size: usize) -> Bytes { - Bytes::from(vec![STOP; size]) -} - -/// Init code that returns `size` bytes of zeros as the deployed code. -fn constructor_returning(size: usize) -> Bytes { - let code = BytecodeBuilder::default() - .push_number(size as u64) - .append_many([PUSH1, 0x00]) - .append(RETURN) - .build_vec(); - right_pad_bytes(code, 32).into() -} - -fn assert_initcode_limit(result: Result, String>) { - let expected = format!("{:?}", InvalidTransaction::CreateInitCodeSizeLimit); - assert_eq!(result.expect_err("the transaction is rejected"), expected); -} - -fn assert_code_size_limit(result: Result, String>) { - let halt = result.expect("the transaction is valid"); - assert!( - matches!( - halt, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(HaltReason::CreateContractSizeLimit), - .. - } - ), - "{halt:?}" - ); -} - -/* ---------- the initcode bound ---------- */ - -/// The Satin bound itself is accepted. -#[test] -fn test_the_satin_initcode_size_is_accepted() { - assert!(deploy(initcode_of(MAX_INITCODE_SIZE)).unwrap().is_success()); -} - -/// One byte past it is rejected before the transaction runs. -#[test] -fn test_one_byte_past_the_satin_initcode_size_is_rejected() { - assert_initcode_limit(deploy(initcode_of(MAX_INITCODE_SIZE + 1))); -} - -/* ---------- the deployed-code bound, from a creation transaction ---------- */ - -/// Code of the Satin size deploys. -#[test] -fn test_the_satin_code_size_deploys() { - assert!(deploy(constructor_returning(MAX_CONTRACT_SIZE)).unwrap().is_success()); -} - -/// One byte past it halts the creation. -#[test] -fn test_one_byte_past_the_satin_code_size_halts() { - assert_code_size_limit(deploy(constructor_returning(MAX_CONTRACT_SIZE + 1))); -} - -/* ---------- the deployed-code bound, from a CREATE ---------- */ - -/// A contract that `CREATE`s a contract of `size` bytes and runs `INVALID` if the creation failed, -/// so a rejected creation shows up as a halt of the outer frame. -fn factory_creating(size: usize) -> Bytes { - let init_code = constructor_returning(size); - let code = BytecodeBuilder::default() - .mstore(0, &init_code) - .push_number(init_code.len() as u64) - .push_number(0u64) - .push_number(0u64) - .append(CREATE) - .append(ISZERO); - let len = code.len(); - code.push_number(len as u8 + 4) - .append(JUMPI) - .append(STOP) - .append(JUMPDEST) - .append(INVALID) - .build() -} - -/// Runs a factory that creates `size` bytes of code and returns whether the creation succeeded. -fn create_through_factory(size: usize) -> bool { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(FACTORY, factory_creating(size)); - let result = - run(call(CALLER, FACTORY, U256::ZERO, gas_limit()), db).expect("the transaction is valid"); - match result { - ExecutionResult::Success { .. } => true, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(HaltReason::InvalidFEOpcode), .. - } => false, - other => panic!("unexpected result {other:?}"), - } -} - -/// A `CREATE` of the Satin size succeeds. -#[test] -fn test_create_of_the_satin_code_size_succeeds() { - assert!(create_through_factory(MAX_CONTRACT_SIZE)); -} - -/// One byte past it fails the creation, which the factory turns into a halt. -#[test] -fn test_create_one_byte_past_the_satin_code_size_fails() { - assert!(!create_through_factory(MAX_CONTRACT_SIZE + 1)); -} diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 961eda655..074f2e584 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -271,23 +271,6 @@ fn run_create( (outcome, probe) } -/// Calldata is part of the body, and a zero byte counts the same as any other. -#[test] -fn test_calldata_counts_in_the_body() { - let db = || funded().account_code(A, BytecodeBuilder::default().append(STOP).build()); - let run = |byte: u8| { - let outcome = MegaEvm::new(context(db())) - .execute_transaction(call_with_data(CALLER, A, Bytes::from(vec![byte; 50]), GAS_LIMIT)) - .unwrap(); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - outcome.usage - }; - 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"); -} - /// Asserts `error` is the refusal of a body whose bytes and authorization records exceed the /// transaction's data-size limit. fn assert_body_refused(error: &str) { diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 5c1069362..dc352ff48 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -14,12 +14,9 @@ use mega_evm::{ EvmTxRuntimeLimits, LimitUsage, MegaEvm, MegaTransaction, AUTHORIZATION_SIZE, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::{ - bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, INVALID, LOG0, LOG1, POP, PUSH0, SELFDESTRUCT, SLOAD, - SSTORE, STATICCALL, STOP, - }, - context::result::ExecutionResult, +use revm::bytecode::opcode::{ + CALL, CREATE, DELEGATECALL, GAS, INVALID, LOG0, LOG1, POP, PUSH0, SELFDESTRUCT, SLOAD, SSTORE, + STATICCALL, STOP, }; use crate::common::{ @@ -327,17 +324,6 @@ fn test_a_reverted_childs_write_and_write_back_leave_its_callers_write() { ); } -/// The sender's own authorization in [`call_with_body`] applies: its bytes are the body's, and -/// the account it writes is the sender's, which the body already records. -#[test] -fn test_the_senders_own_authorization_applies_and_records_nothing() { - let outcome = execute(funded(), call_with_body(Bytes::new())); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let code = outcome.state[&CALLER].info.code.clone().expect("the sender is delegated"); - assert_eq!(code.eip7702_address(), Some(LIBRARY)); - assert_eq!(outcome.usage, kept(20 + 32 + AUTHORIZATION_SIZE, 0, 0)); -} - /// A `SELFDESTRUCT` in a static frame halts before it moves anything, so the frame keeps what a /// frame that stops keeps: nothing. #[test] @@ -358,17 +344,6 @@ fn test_a_selfdestruct_in_a_static_frame_keeps_nothing() { assert!(selfdestruct.state.get(&EXISTING).is_none_or(|a| a.info.balance.is_zero())); } -/// A transaction whose own frame reverts keeps its body: the body is the transaction's, not the -/// frame's. -#[test] -fn test_a_top_level_revert_keeps_the_body() { - let db = funded().account_code(CALLEE, BytecodeBuilder::default().revert().build()); - let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); - assert!(matches!(outcome.result, ExecutionResult::Revert { .. }), "{:?}", outcome.result); - assert_eq!(outcome.usage, kept(0, 0, 0)); - assert_eq!(outcome.limit_exceeded, None); -} - /// A transaction limit equal to what the transaction keeps does not stop it, however much of it /// is calldata. #[test] diff --git a/crates/mega-evm/tests/satin/failed_deposit.rs b/crates/mega-evm/tests/satin/failed_deposit.rs index 7777033ad..dc8e52eaa 100644 --- a/crates/mega-evm/tests/satin/failed_deposit.rs +++ b/crates/mega-evm/tests/satin/failed_deposit.rs @@ -45,73 +45,6 @@ fn deposit(data: Bytes, system: bool) -> MegaTransaction { OpTx(tx) } -/// Runs a funded sender's deposit with a mint, no value and no calldata. -fn body_deposit(gas_limit: u64, opcode: u8) -> MegaTransactionOutcome { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10)) - .account_code(CALLEE, Bytes::from(vec![opcode])); - let mut tx = deposit(Bytes::new(), false); - tx.0.base.gas_limit = gas_limit; - tx.0.deposit.mint = Some(7); - MegaEvm::new(context(db)).execute_transaction(tx).expect("the deposit is included") -} - -/// The body, mint and nonce are kept on success and on either failure path. -#[track_caller] -fn assert_body_deposit(outcome: &MegaTransactionOutcome, regular: u64, history: u64) { - assert_eq!( - (outcome.gas.regular, outcome.gas.state, outcome.gas.history), - (regular, 0, history) - ); - assert_eq!(outcome.gas.gas_used, regular + history); - assert_eq!(outcome.gas.history_bytes, 310); - assert_eq!(outcome.usage.data_size, 310); - assert_eq!(outcome.state[&CALLER].info.nonce, 1); - assert_eq!(outcome.state[&CALLER].info.balance, U256::from(17)); -} - -/// Intrinsic regular gas is 15,000 and body history is 27,280: 30,000 cannot cover both. -#[test] -fn test_a_deposit_short_of_body_history_is_a_failed_deposit() { - if crate::common::runs_at_measurement_prices() { - return; - } - let outcome = body_deposit(30_000, revm::bytecode::opcode::STOP); - - assert!(matches!( - outcome.result, - ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } - )); - assert_body_deposit(&outcome, 30_000, 0); -} - -/// An exceptional halt consumes the whole gas limit as regular gas but keeps the body's bytes. -#[test] -fn test_a_halted_deposit_reports_body_bytes_but_no_history_gas() { - if crate::common::runs_at_measurement_prices() { - return; - } - let outcome = body_deposit(100_000, INVALID); - - assert!(matches!( - outcome.result, - ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } - )); - assert_body_deposit(&outcome, 100_000, 0); -} - -/// A successful deposit pays 27,280 of history for its 310-byte body, besides intrinsic gas. -#[test] -fn test_a_successful_deposit_pays_body_history() { - if crate::common::runs_at_measurement_prices() { - return; - } - let outcome = body_deposit(100_000, revm::bytecode::opcode::STOP); - - assert!(outcome.result.is_success()); - assert_body_deposit(&outcome, 15_000, 27_280); -} - /// A mint too small for the creation's value makes no start record. The inspector must see the /// whole forward left after the intrinsic and account charges, before revm refuses the value. #[test] diff --git a/crates/mega-evm/tests/satin/limit_matrix/limits.rs b/crates/mega-evm/tests/satin/limit_matrix/limits.rs index d9d4a5a3f..106d225d4 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/limits.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/limits.rs @@ -10,7 +10,7 @@ use mega_evm::{ test_utils::BytecodeBuilder, EvmTxRuntimeLimits, MegaLimitExceeded, }; -use revm::bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0}; +use revm::bytecode::opcode::{CALL, GAS, POP, PUSH0}; use super::{ balance_of, call_tx, delegatecall, execute, execute_under, forward_to, frame_share, @@ -26,21 +26,6 @@ fn join(prefix: Vec, rest: BytecodeBuilder) -> Bytes { 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. @@ -253,67 +238,6 @@ fn hint_call(len: u32) -> BytecodeBuilder { .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) diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 2dd8f18ea..231e1831a 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -2,7 +2,6 @@ mod common; mod compute_gas; -mod contract_size; mod corpus; mod count_order; mod create_opcodes; diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index c67b8a5b9..e1a52a173 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -1,12 +1,11 @@ //! The transaction outcome: the result, the gas by ledger, the usage counted and the stop. -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolError; +use alloy_primitives::{address, Address, U256}; use mega_evm::{ constants::{COST_PER_HISTORY_BYTE, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, BlockGasCounters, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, - MegaLimitExceeded, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, + MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use crate::common::{ @@ -112,20 +111,6 @@ fn test_outcome_reports_the_stop() { ); } -/// A contract reverting with `MegaLimitExceeded`'s bytes on its own is not a stop. -#[test] -fn test_spoofed_revert_data_is_not_a_stop() { - let data: Bytes = MegaLimitExceeded { kind: 0, limit: 1 }.abi_encode().into(); - let code = BytecodeBuilder::default().revert_with_data(&data).build(); - let outcome = execute( - MemoryDatabase::default().account_code(CONTRACT, code), - EvmTxRuntimeLimits::no_limits(), - 1_000_000, - ); - assert_eq!(outcome.result.output(), Some(&data)); - assert_eq!(outcome.limit_exceeded, None); -} - /// Counts the steps it sees. #[derive(Default)] struct Steps(usize); From 91ad711d84c9bd2d95441cb356b435531ca530cb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 18:44:36 +0800 Subject: [PATCH 125/190] test(gas): remove tests duplicated by the conformance suite The intrinsic and creation charges of the schedule, the warm and cold first calls, and a fresh slot's legacy share are pinned by Mega EEST's cases. --- .../mega-evm/tests/satin/inherited_costs.rs | 90 +------------------ crates/mega-evm/tests/satin/legacy_share.rs | 17 +--- crates/mega-evm/tests/satin/schedule.rs | 87 +----------------- 3 files changed, 6 insertions(+), 188 deletions(-) diff --git a/crates/mega-evm/tests/satin/inherited_costs.rs b/crates/mega-evm/tests/satin/inherited_costs.rs index a9da22840..3c6b3e18b 100644 --- a/crates/mega-evm/tests/satin/inherited_costs.rs +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -7,25 +7,14 @@ //! //! 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 alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + test_utils::{BytecodeBuilder, MemoryDatabase}, MegaTransaction, }; -use revm::{ - bytecode::opcode::{CALL, CALLCODE, POP, PUSH0, STATICCALL, STOP}, - context::{ - transaction::{AccessList, AccessListItem, TransactionType}, - TxEnv, - }, - context_interface::cfg::GasId, -}; +use revm::bytecode::opcode::{POP, PUSH0, STATICCALL, STOP}; -use crate::{ - common::{block, call, execute}, - salt::entry, -}; +use crate::common::{call, execute}; const CALLER: Address = address!("0000000000000000000000000000000000e20000"); const CONTRACT: Address = address!("0000000000000000000000000000000000e20001"); @@ -34,12 +23,6 @@ const EXISTING: Address = address!("0000000000000000000000000000000000e20002"); /// The identity precompile. const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); -/// What the first touch of an address costs over a warm one: the schedule's cold account access -/// less its warm read. -fn cold_over_warm() -> u64 { - entry(GasId::cold_account_additional_cost()) -} - /* ---------- preload-warm addresses ---------- */ /// `units` identical calls of `opcode` to `to`, each forwarding 50,000 and dropping its status. @@ -55,18 +38,6 @@ fn calls(opcode: u8, to: Address, units: usize) -> Bytes { code.append(STOP).build() } -/// A call from `CALLER` to `CONTRACT` carrying `access_list`, as an EIP-2930 transaction. -fn with_access_list(access_list: AccessList) -> MegaTransaction { - OpTx(op_transaction(TxEnv { - tx_type: TransactionType::Eip2930 as u8, - caller: CALLER, - kind: TxKind::Call(CONTRACT), - gas_limit: 10_000_000 + crate::common::body_history(100), - access_list, - ..Default::default() - })) -} - /// How much more the first of the calls `opcode` makes to `to` costs than the second, on the /// regular ledger: the 0-, 1- and 2-call programs are run and differenced, so what every call /// costs alike cancels, and what is left is the first touch's price over a warm touch's. @@ -87,61 +58,8 @@ fn plain() -> MegaTransaction { call(CALLER, CONTRACT, U256::ZERO, 10_000_000 + crate::common::body_history(0)) } -/// The control the other cases are measured against: an address nothing preloads costs the cold -/// price on its first touch, so the measurement sees a cold touch where there is one. -#[test] -fn test_the_first_call_to_an_address_nothing_warmed_is_charged_cold() { - assert_eq!(first_call_over_second(CALL, EXISTING, plain), cold_over_warm() as i64); -} - -/// A precompile is warm from the transaction's start: the first `CALL` to one costs what the -/// second does. -#[test] -fn test_the_first_call_to_a_precompile_is_charged_warm() { - assert_eq!(first_call_over_second(CALL, IDENTITY, plain), 0); -} - /// So does the first `STATICCALL`. #[test] fn test_the_first_staticcall_to_a_precompile_is_charged_warm() { assert_eq!(first_call_over_second(STATICCALL, IDENTITY, plain), 0); } - -/// An access-list address is warm from the start whether it is listed with storage keys or -/// without: the first `CALL` to it costs what the second does, where without the list it pays the -/// cold price. -#[test] -fn test_the_first_call_to_an_access_list_address_is_charged_warm() { - let listed = |keys: Vec| { - move || { - with_access_list(AccessList(vec![AccessListItem { - address: EXISTING, - storage_keys: keys.clone(), - }])) - } - }; - assert_eq!(first_call_over_second(CALL, EXISTING, listed(vec![])), 0, "without keys"); - assert_eq!(first_call_over_second(CALL, EXISTING, listed(vec![B256::ZERO])), 0, "with a key"); -} - -/// The same for `CALLCODE`: its first touch of an access-list address listed without keys costs -/// what the second does. -#[test] -fn test_the_first_callcode_to_an_access_list_address_is_charged_warm() { - let listed = || { - with_access_list(AccessList(vec![AccessListItem { - address: EXISTING, - storage_keys: vec![], - }])) - }; - assert_eq!(first_call_over_second(CALLCODE, EXISTING, listed), 0); -} - -/// The block beneficiary is warm from the start (EIP-3651): the first `CALL` to it costs what the -/// second does. The call reads the beneficiary's account, which gas detention marks, but a mark -/// charges nothing. -#[test] -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); -} diff --git a/crates/mega-evm/tests/satin/legacy_share.rs b/crates/mega-evm/tests/satin/legacy_share.rs index 9fe7865e6..11f2baf6a 100644 --- a/crates/mega-evm/tests/satin/legacy_share.rs +++ b/crates/mega-evm/tests/satin/legacy_share.rs @@ -27,7 +27,7 @@ use revm::bytecode::opcode::{ use crate::common::{ account_share, account_state_gas, authorizing_call, beneficiary_share, call, create, - create_share, execute, runs_at_measurement_prices, slot_share, + create_share, execute, runs_at_measurement_prices, }; const CALLER: Address = address!("0000000000000000000000000000000000710000"); @@ -84,21 +84,6 @@ fn word(outcome: &MegaTransactionOutcome) -> u64 { U256::from_be_slice(output).to::() } -/// A fresh slot's `SSTORE` takes its share, 10,000 at the spec's prices, from regular gas, and -/// draws 22,100 from regular gas in all, the cold access and the 20,000 of a fresh slot before -/// Satin. -#[test] -fn test_a_fresh_slot_takes_its_legacy_share_from_regular_gas() { - let op = BytecodeBuilder::default().append_many([PUSH1, 1, PUSH1, 1, SSTORE]); - let outcome = run(measuring(BytecodeBuilder::default(), op)); - assert_eq!(paid_by_regular(&outcome, ABOVE_CAP), slot_share()); - if runs_at_measurement_prices() { - return; - } - assert_eq!(slot_share(), 10_000); - assert_eq!(word(&outcome), 3 + 3 + 22_100 + 2, "the two pushes, the SSTORE and the GAS"); -} - /// A value `CALL` that creates its target's account takes its share, 25,000 at the spec's prices, /// from regular gas. #[test] diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 22ebeb063..f2a5ae9bc 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -11,7 +11,6 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - constants::ACCOUNT_STATE_GAS, test_utils::{BytecodeBuilder, MemoryDatabase}, MegaEvm, }; @@ -21,8 +20,7 @@ use revm::{ }; use crate::common::{ - account_state_gas, call, call_with_data, context, create, history, runs_at_measurement_prices, - slot_state_gas, + account_state_gas, call, call_with_data, context, create, history, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000900000"); @@ -49,13 +47,6 @@ struct Spend { floor: u64, } -impl Spend { - /// What the schedule charged: everything the transaction used but the history ledger. - const fn schedule_gas(&self) -> u64 { - self.gas_used - self.history - } -} - /// Runs `tx` on `db` and returns what it spent. The transaction must succeed. fn spend(db: MemoryDatabase, tx: mega_evm::MegaTransaction) -> Spend { let outcome = @@ -78,65 +69,6 @@ fn with_code(code: Bytes) -> MemoryDatabase { /* ---------- the intrinsic numbers ---------- */ -/// A call that reaches an existing account and does nothing pays the EIP-2780 sender base of -/// 12,000 plus 3,000 for reaching the recipient, and draws no state gas. -/// -/// The 3,000 is EIP-2780's own fixed charge and not the schedule's cold-account entry, which -/// prices an access inside execution at 2,600. -#[test] -fn test_an_empty_call_costs_fifteen_thousand() { - let spent = spend(with_code(Bytes::new()), call(CALLER, CALLEE, U256::ZERO, gas_limit())); - assert_eq!(spent.schedule_gas(), 15_000); - assert_eq!(spent.state, 0); -} - -/// A value transfer to an account that already exists adds the value charge, and still draws no -/// state gas: nothing is created. -#[test] -fn test_a_value_transfer_to_an_existing_account_costs_twenty_one_thousand() { - let db = with_code(Bytes::new()).account_balance(CALLEE, U256::from(1)); - let spent = spend(db, call(CALLER, CALLEE, U256::from(7), gas_limit())); - assert_eq!(spent.schedule_gas(), 21_000); - assert_eq!(spent.state, 0); -} - -/// A transfer to an account that does not exist creates it, which is the account's state gas on -/// top of the transfer's own cost. -#[test] -fn test_a_value_transfer_that_creates_the_recipient_draws_the_account_state_gas() { - if runs_at_measurement_prices() { - return; - } - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, call(CALLER, CALLEE, U256::from(7), gas_limit())); - assert_eq!(spent.state, ACCOUNT_STATE_GAS); - assert_eq!(spent.schedule_gas(), 21_000 + ACCOUNT_STATE_GAS); -} - -/// A transfer to the sender itself pays the sender base alone: neither the recipient charge nor -/// the value charge applies, because the recipient is the sender. -#[test] -fn test_a_self_transfer_costs_twelve_thousand() { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, call(CALLER, CALLER, U256::from(7), gas_limit())); - assert_eq!(spent.schedule_gas(), 12_000); - assert_eq!(spent.state, 0); -} - -/// A creation transaction pays the sender base plus the creation access charge, and the created -/// account's state gas on top. With empty init code nothing else is charged, so the fixed part is -/// what is left when the state gas is taken out. -#[test] -fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_gas() { - if runs_at_measurement_prices() { - return; - } - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, create(CALLER, Bytes::new(), gas_limit())); - assert_eq!(spent.state, ACCOUNT_STATE_GAS, "the created account"); - assert_eq!(spent.schedule_gas() - spent.state, 24_000, "the fixed part"); -} - /// Init code is transaction data twice over: every byte is a calldata token, and EIP-3860 charges /// two gas for each 32-byte word of it. Sixty-four bytes of zeros is two words; sixty-five is /// three, so the word charge steps by two where the token charge steps by four. @@ -163,23 +95,6 @@ fn test_init_code_costs_its_calldata_tokens_and_an_eip3860_word() { /* ---------- the state entries ---------- */ -/// A creation that reverts deposits nothing, so it draws no state gas at all: neither the -/// created account's nor the code's. The state gas a creation draws is charged on the deposit, -/// not on the attempt. -#[test] -fn test_a_reverted_creation_draws_no_state_gas() { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let mut evm = MegaEvm::new(context(db)); - let init_code = BytecodeBuilder::default().mstore(0, [0u8; 32]).revert().build(); - let result = evm - .transact_raw(create(CALLER, init_code, gas_limit())) - .expect("the transaction is valid") - .result; - - assert!(!result.is_success(), "{result:?}"); - assert_eq!(result.gas().state_gas_spent_final(), 0); -} - /// Init code that returns a single `0xEF` byte as the deployed code, which EIP-3541 rejects. fn depositing_an_ef_byte() -> Bytes { BytecodeBuilder::default() From 18e2a4068ff67d608eb1dd989a374519507202c0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 18:48:07 +0800 Subject: [PATCH 126/190] test(history): remove tests duplicated by the conformance suite The history allowance, a body's and a deposit's history, a log's and deployed code's history, and a start whose records the caller cannot pay are pinned by Mega EEST's cases. --- .../mega-evm/tests/satin/history_allowance.rs | 220 +----------------- crates/mega-evm/tests/satin/history_bytes.rs | 26 --- .../mega-evm/tests/satin/history_exemption.rs | 14 -- crates/mega-evm/tests/satin/history_gas.rs | 196 +--------------- 4 files changed, 9 insertions(+), 447 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_allowance.rs b/crates/mega-evm/tests/satin/history_allowance.rs index 96f2a4b03..cd39d7873 100644 --- a/crates/mega-evm/tests/satin/history_allowance.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -24,12 +24,9 @@ use mega_evm::{ constants::COST_PER_HISTORY_BYTE, history_allowance_gas, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{ - is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, - }, + test_utils::{is_transfer_log, note_price_guard, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitKind, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, - HISTORY_ALLOWANCE_BYTES, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + HISTORY_ALLOWANCE_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -44,10 +41,7 @@ use revm::{ Inspector, }; -use crate::common::{ - body_history, call, context, execute, history, runs_at_measurement_prices, slot_state_gas, - state_is_free, -}; +use crate::common::{body_history, call, context, execute, history, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000500000"); const SENDER: Address = address!("0000000000000000000000000000000000500001"); @@ -129,52 +123,6 @@ fn test_the_allowance_is_one_three_topic_event_of_history() { 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 -/// `receive()` hook that emits one event, and the event's history costs the sender nothing beyond -/// the two write records the transfer itself writes. -/// -/// Without the allowance the event's 160 bytes would have to come out of the 2,300, which does -/// not cover them at any price a history byte is worth. -#[test] -fn test_a_transfer_can_emit_one_event_because_of_the_allowance() { - if runs_at_measurement_prices() { - return; - } - let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); - let receiver = event().append(STOP).build(); - let outcome = execute(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); - assert_eq!( - outcome.result.logs()[0], - transfer_log(SENDER, RECEIVER, U256::from(1)), - "after the transfer's own log, which took nothing from the allowance", - ); - assert_eq!( - outcome.gas.history, - body() + 2 * record(), - "the body and the transfer's two records; the event's bytes the allowance paid for", - ); -} - -/// One event is all it buys: a second one has to come out of the 2,300 gas, which cannot cover -/// it, so the hook runs out of gas and the transfer fails. -#[test] -fn test_the_allowance_buys_one_event_and_no_more() { - if runs_at_measurement_prices() { - return; - } - // The caller records whether the transfer succeeded, then stops. - let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); - let two_events = event().append_many(event().build().iter().copied()).append(STOP).build(); - let outcome = execute(db(sender, two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - - assert!(outcome.result.is_success(), "the caller survives the hook's failure"); - assert!(outcome.result.logs().is_empty(), "the hook ran out and kept neither event"); - assert_eq!(outcome.gas.history, body(), "and the transfer's records came back with it"); -} - /// A sender that makes one value transfer to [`RECEIVER`], forwarding `gas` beside the 2,300 the /// transfer's stipend adds, and returns the call's success flag. fn transfer_returning_its_flag(gas: u64) -> Bytes { @@ -284,59 +232,6 @@ 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]) @@ -380,99 +275,8 @@ fn test_the_allowance_cannot_be_spent_on_a_write_record() { assert_eq!(record, 3_520, "40 bytes at 88 gas"); } -/// The allowance cannot pay state gas either: a hook that fills a fresh slot, given the write's -/// regular gas and one gas less than the slot's state gas, runs out of gas and keeps no write. -/// An allowance that paid the state gas would carry it through: drawn first, it would pay the -/// smaller of the state gas and itself, and leave the hook that much less one gas of its own to -/// pay the record's history with. Given the state gas and the record in full it keeps the write. -/// -/// So the leak shows only where both the slot's state gas and the allowance outweigh a record. -/// At a price where the state gas does not — a gas or so a state byte against a dear history -/// byte — the short hook would run out on the record whether or not the allowance paid its state -/// gas, and the test returns early with a note. -/// -/// Expected values `independent`: the write's regular gas is the schedule's table by -/// hand — `PUSH1` 3, `PUSH0` 2, and an `SSTORE` that fills a cold fresh slot, 100 static, 10,000 -/// for the fresh slot and 2,000 for the cold load — which no byte price moves; the slot's state -/// gas at the minimum bucket is the schedule's entry and the record's history 40 bytes at the cost -/// per history byte, both at the prices in effect (`constants`), and at the spec's prices 97,920 -/// and 3,520, written out. -#[test] -fn test_the_allowance_cannot_be_spent_on_state() { - // A slot that costs no state gas has no state charge the allowance could pay. - if state_is_free() || !the_allowance_outweighs_a_record() { - return; - } - let state = slot_state_gas(); - let record = record_history(); - // A leaked allowance leaves the short hook `min(state, allowance) - 1` of its own gas for the - // record, which must cover it for the leak to show. - if state.min(allowance()) - 1 < record { - note_price_guard( - "the slot's state gas is worth no more than a write record at these prices", - ); - return; - } - let regular = 3 + 2 + 100 + 10_000 + 2_000; - - let short = run_hook(writes_slot_zero(), regular + state - 1, U256::ZERO); - assert!(!transfer_succeeded(&short), "one gas short of the state gas is out of gas"); - assert_eq!(short.usage.write_records, 0, "the hook kept no write"); - assert_eq!(short.gas.state, 0, "and no state gas"); - - let exact = run_hook(writes_slot_zero(), regular + state + record, U256::ZERO); - assert!(transfer_succeeded(&exact), "the slot paid from the hook's own gas"); - assert_eq!(exact.gas.state, state); - assert_eq!(exact.usage.write_records, 3, "the transfer's two accounts and the slot"); - - if runs_at_measurement_prices() { - return; - } - assert_eq!((state, record), (97_920, 3_520), "64 bytes at 1,530 gas, 40 bytes at 88 gas"); -} - /* ---------- who is granted one ---------- */ -/// A transaction's own frame is granted nothing: its sender chose the gas limit, so a value -/// transaction whose recipient emits an event pays for that event itself. -#[test] -fn test_a_top_level_transfer_gets_no_allowance() { - if runs_at_measurement_prices() { - return; - } - let receiver = event().append(STOP).build(); - let mut tx = call(CALLER, RECEIVER, U256::from(1), GAS_LIMIT); - tx.0.base.value = U256::from(1); - let outcome = execute(db(Bytes::new(), receiver), tx); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!( - outcome.gas.history, - body() + record() + HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE, - "the body, the recipient's record, and the event the transaction paid for itself", - ); -} - -/// A call that carries no value is granted nothing, whatever it forwards: the allowance follows -/// the transfer, not the call. -#[test] -fn test_a_call_without_value_gets_no_allowance() { - if runs_at_measurement_prices() { - return; - } - 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 = 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)); - - assert!(paid.result.is_success() && granted.result.is_success()); - assert_eq!(paid.gas.history, body() + event_history, "no transfer, no allowance"); - assert_eq!(granted.gas.history, body() + 2 * record(), "the allowance paid for the event"); -} - /// `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 moves the value /// from the calling account to itself and writes no account at all. @@ -840,24 +644,6 @@ fn test_a_drained_allowance_is_not_refunded_by_a_revert() { ); } -/// A call that forwards no gas at all still reaches a `receive()` hook that emits one event: the -/// EVM's own `CALL_STIPEND` pays for the computation and the allowance for the bytes. -#[test] -fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { - if runs_at_measurement_prices() { - return; - } - let sender = call_with(CALL, RECEIVER, 1, 0).append(STOP).build(); - let outcome = execute( - db(sender, event().append(STOP).build()), - call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), - ); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); - assert_eq!(outcome.gas.history, body() + 2 * record()); -} - /* ---------- an inspector that replaces the interpreter ---------- */ /// Replaces the interpreter of every frame running `target`'s code, as revm initialises it, with diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 88443305c..aa49860b0 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -219,32 +219,6 @@ fn test_a_reservoir_that_runs_out_changes_only_who_paid() { assert_eq!(exact.gas.gas_used, ample.gas.gas_used); } -/// A transaction whose gas cannot pay for the record its own frame makes runs out of gas before -/// that frame, and the record is not made: it reports its body alone, in bytes and in gas. -#[test] -fn test_a_transaction_that_cannot_pay_its_first_record_reports_its_body_alone() { - if runs_at_measurement_prices() { - return; - } - let transfer = |gas| call(CALLER, PAYEE, U256::from(1), gas); - // What the transfer spends is its intrinsic gas and the one record, nothing else: that is the - // least gas limit that pays for all of it. - let ample = execute(funded(), transfer(GAS_LIMITS[0])); - assert!(ample.result.is_success(), "{:?}", ample.result); - let fits = ample.gas.gas_used; - - let exact = execute(funded(), transfer(fits)); - assert!(exact.result.is_success(), "{:?}", exact.result); - assert_eq!(exact.gas.history_bytes, TX_BODY_SIZE + WRITE_RECORD_SIZE); - assert_eq!(exact.gas.history, exact.gas.history_bytes * CPHB); - - let short = execute(funded(), transfer(fits - 1)); - assert!(short.result.is_halt(), "{:?}", short.result); - assert_eq!(short.usage.write_records, 0, "no frame ran, so no record was made"); - assert_eq!(short.gas.history_bytes, TX_BODY_SIZE, "the body alone"); - assert_eq!(short.gas.history, TX_BODY_SIZE * CPHB); -} - /// Answers every creation itself with a success whose output is a word of bytes, so no frame runs /// and nothing is deposited. /// diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 9526fddba..9bbacddd1 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -187,20 +187,6 @@ fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { assert_eq!(evm.ctx().additional_limit().history_gas_spent(), 0); } -/// A deposit pays for its body, calldata, records, logs and deployed code even without a fee. -#[test] -fn test_a_deposit_pays_history_gas() { - if runs_at_measurement_prices() { - return; - } - let mut tx = deposit(call_from(CALLER, CONTRACT)); - tx.0.base.data = Bytes::from_static(b"history"); - let (history, state, outcome) = ledgers(tx); - assert_eq!(history, (PROGRAM_HISTORY_BYTES + 7) * COST_PER_HISTORY_BYTE); - assert_eq!(state, PROGRAM_STATE_GAS, "the state a user transaction pays"); - assert_eq!(outcome.gas.history_bytes, PROGRAM_HISTORY_BYTES + 7); -} - /// Both field-based forms of system origin pay every history site, including deposited code. #[test] fn test_system_originated_transactions_pay_history_for_the_program() { diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 13b48aadc..2d2bba0b1 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -5,22 +5,21 @@ 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}, + constants::{COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, - LOG_BASE_SIZE, LOG_TOPIC_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, - WRITE_RECORD_SIZE, + TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ - CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, RETURN, - REVERT, STATICCALL, STOP, + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, POP, PUSH0, PUSH1, RETURN, REVERT, + STATICCALL, STOP, }, context_interface::cfg::GasId, }; use crate::common::{ - account_share, body_history, call, call_with_data, create, create_share, deploying, execute, - history, history_is_free, history_rounds, reservoir_share, runs_at_measurement_prices, + account_share, body_history, call, create_share, execute, history, history_is_free, + history_rounds, reservoir_share, runs_at_measurement_prices, }; const CALLER: Address = address!("0000000000000000000000000000000000200000"); @@ -42,121 +41,6 @@ fn funded() -> MemoryDatabase { MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) } -/// Init code that reverts without deploying anything. -fn reverting() -> Bytes { - BytecodeBuilder::default().append_many([PUSH0, PUSH0, REVERT]).build() -} - -/// Deployed code is both state and history: its bytes enter the world state and the chain's -/// history, so a deployment pays the per-byte state rate and the per-byte history rate on the -/// same length. -#[test] -fn test_deployed_code_pays_history_for_every_byte() { - if runs_at_measurement_prices() { - return; - } - let short = execute(funded(), create(CALLER, deploying(32), GAS_LIMIT)); - let long = execute(funded(), create(CALLER, deploying(64), GAS_LIMIT)); - - assert!(short.result.is_success(), "{:?}", short.result); - assert!(long.result.is_success(), "{:?}", long.result); - assert_eq!(long.gas.history - short.gas.history, 32 * CPHB, "32 more bytes of history"); - assert_eq!(long.gas.state - short.gas.state, 32 * COST_PER_STATE_BYTE, "and of state"); -} - -/// A deployment that reverts appends no code, so it pays no code-deposit history at all. -#[test] -fn test_a_reverted_deployment_pays_no_code_deposit_history() { - if runs_at_measurement_prices() { - return; - } - let deployed = execute(funded(), create(CALLER, deploying(32), GAS_LIMIT)); - let reverted = execute(funded(), create(CALLER, reverting(), GAS_LIMIT)); - - assert!(deployed.result.is_success(), "{:?}", deployed.result); - assert!(!reverted.result.is_success(), "the creation reverts"); - assert_eq!( - deployed.gas.history, - body(deploying(32).len() as u64) + WRITE_RECORD_SIZE * CPHB + 32 * CPHB, - "the body the init code travels in, the created account's record, the deployed bytes", - ); - assert_eq!( - reverted.gas.history, - body(reverting().len() as u64), - "the body alone: nothing was deployed, and the account's record went with the failure", - ); -} - -/* ---------- the transaction body ---------- */ - -/// Calldata is part of the body, one history byte per byte, whatever the bytes are: a zero byte -/// takes the same space in a block as a non-zero one. -#[test] -fn test_calldata_costs_one_history_byte_per_byte() { - if runs_at_measurement_prices() { - return; - } - let run = |len: usize, byte: u8| { - let db = funded().account_code(CALLEE, Bytes::new()); - let data = Bytes::from(vec![byte; len]); - execute(db, call_with_data(CALLER, CALLEE, data, GAS_LIMIT)) - }; - let zeros = run(100, 0x00); - let non_zeros = run(100, 0xff); - let longer = run(200, 0x00); - - assert_eq!(zeros.gas.history, body(100)); - assert_eq!(non_zeros.gas.history, zeros.gas.history, "the value of a byte is not its size"); - assert_eq!(longer.gas.history - zeros.gas.history, 100 * CPHB, "a hundred bytes more"); -} - -/* ---------- 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. -fn log_body(topics: u8, data_len: u64) -> BytecodeBuilder { - let mut code = BytecodeBuilder::default(); - for topic in 0..topics { - code = code.push_number(u64::from(topic) + 1); - } - code.push_number(data_len).push_number(0u64).append(LOG0 + topics) -} - -/// A program that emits one such log and stops. -fn logging(topics: u8, data_len: u64) -> Bytes { - log_body(topics, data_len).stop().build() -} - -/// A log costs history on top of what the EVM itself charges for the opcode: the schedule's own -/// price is untouched, and the history is the bytes. -#[test] -fn test_a_log_pays_history_on_top_of_the_schedules_price() { - if runs_at_measurement_prices() { - return; - } - let run = |code: Bytes| { - let db = funded().account_code(CALLEE, code); - execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) - }; - let quiet = run(BytecodeBuilder::default().stop().build()); - let logging = run(logging(1, 32)); - - // The EVM's own price for the opcode: two pushes for the offset and length, one for the - // topic, the `LOG` base, the per-topic and per-byte rates, and one word of memory. - let params = mega_evm::satin_gas_params(); - let native = - 3 * 3 + 375 + params.get(GasId::logtopic()) + 32 * params.get(GasId::logdata()) + 3; - assert_eq!( - logging.gas.regular - quiet.gas.regular, - native, - "the schedule charges what it always did", - ); - assert_eq!( - logging.gas.history - quiet.gas.history, - (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB - ); -} - /* ---------- a frame-start charge the caller cannot pay ---------- */ /// `CALL(GAS, target, 1 wei, [], [])`, discarding the flag, then `STOP`: a value transfer that @@ -191,27 +75,6 @@ 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 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() { - if runs_at_measurement_prices() { - return; - } - let code = transfers_everything_to(CONTRACT); - 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"); - assert_eq!(short.usage.write_records, 0, "the frame that never ran wrote nothing"); - assert_eq!(short.gas.history, body(0), "and the transaction pays for its body alone"); - - assert!(ample.result.is_success(), "{:?}", ample.result); - assert_eq!(ample.usage.write_records, 2, "the caller's account and the recipient's"); - assert_eq!(ample.gas.history, body(0) + 2 * WRITE_RECORD_SIZE * CPHB); -} - /// The same for a creation, whose start records the created account and the creator's nonce. #[test] fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { @@ -438,53 +301,6 @@ fn test_no_gas_limit_buys_a_write_record_for_nothing() { /* ---------- the writes every transaction makes ---------- */ -/// The transaction body carries the writes every transaction makes whatever it runs: the sender's -/// account, and the four accounts its fees are credited to. -/// -/// They are in the body rather than charged where they happen because the body is priced before -/// the transaction runs, when how many of the four are actually credited is not yet known — a -/// zero fee credits none, and a beneficiary that is one of the vaults is one account, not two. -/// The body carries the bound; nothing counts them again afterwards. -#[test] -fn test_the_body_carries_the_writes_every_transaction_makes() { - if runs_at_measurement_prices() { - return; - } - assert_eq!(TX_BODY_SIZE, TX_BASE_SIZE + TX_FIXED_WRITE_RECORDS * WRITE_RECORD_SIZE); - assert_eq!(TX_BODY_SIZE, 110 + 5 * 40); - - // A transaction that actually pays a fee credits the beneficiary and the fee vaults, and - // records none of them: what it pays is what a fee-free transaction pays. - let db = || funded().account_code(CALLEE, Bytes::new()); - let free = execute(db(), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); - let paid = execute(db(), { - let mut tx = call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT); - tx.0.base.gas_price = 10; - tx - }); - - assert!(free.result.is_success() && paid.result.is_success()); - assert_eq!(free.gas.history, body(0), "the body, and the body alone"); - assert_eq!(paid.gas.history, free.gas.history, "the fee recipients are already in the body"); - assert_eq!(paid.usage.write_records, 0, "and none of them is recorded again"); -} - -/// A deposit pays for the fixed body, including its bound on fee writes, even though it credits -/// no fee recipient. -#[test] -fn test_a_deposit_pays_for_the_bodys_fixed_writes() { - if runs_at_measurement_prices() { - return; - } - let mut tx = call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT); - tx.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); - let outcome = execute(funded().account_code(CALLEE, Bytes::new()), tx); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE); - assert_eq!(outcome.usage.write_records, 0); -} - /// The body carries a bound on the fee recipients, not a count of them, so a beneficiary that is /// one of the fee vaults is not something anything has to notice: the two transactions pay the /// same history, and neither reads a recipient to find out. From 001a7f4c8e4cfefb2caa37c03aeeb35e9e743dfb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 18:51:33 +0800 Subject: [PATCH 127/190] test(salt): remove tests duplicated by the conformance suite SALT pricing of a beneficiary, of the minimum capacity, of an authority, and the give-backs of charges kept, restored or rolled back at their own multiplier are pinned by Mega EEST's cases. --- crates/mega-evm/tests/satin/salt.rs | 46 ---- crates/mega-evm/tests/satin/salt_failure.rs | 11 - crates/mega-evm/tests/satin/salt_refund.rs | 242 +------------------- 3 files changed, 4 insertions(+), 295 deletions(-) diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index ab04bd2fc..463869dff 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -316,22 +316,6 @@ 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 destruction's two records, the beneficiary's and that of the -/// account it clears. -#[test] -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 + 2 * WRITE_RECORD_SIZE, - |envs, m| crowded_account(envs, EMPTY, m), - || (db(selfdestruct_to(EMPTY).build()), call_contract()), - ); -} - /// `CREATE`: the bucket of the address it deploys to prices the account it adds. The history is /// the body and the creation's two records, the creator's nonce and the created account; the /// deployed code is empty. @@ -896,36 +880,6 @@ fn test_a_transfer_to_an_account_that_exists_charges_no_state_gas() { ); } -/// A `SELFDESTRUCT` pays for a beneficiary's leaf only when it has a balance to move and the -/// beneficiary does not exist yet. Neither half alone adds state, so neither is charged, however -/// crowded the beneficiary's bucket is. -#[test] -fn test_a_selfdestruct_that_adds_no_account_charges_no_state_gas() { - const FUNDED: Address = address!("0000000000000000000000000000000000c00007"); - - assert_charges_no_state_gas( - "a SELFDESTRUCT with nothing to move", - |envs, m| crowded_account(envs, EMPTY, m), - || { - // The contract holds no balance, so the beneficiary receives nothing and is not - // created. - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(CONTRACT, selfdestruct_to(EMPTY).build()); - (db, call_contract()) - }, - ); - - assert_charges_no_state_gas( - "a SELFDESTRUCT to an account that exists", - |envs, m| crowded_account(envs, FUNDED, m), - || { - let db = db(selfdestruct_to(FUNDED).build()).account_balance(FUNDED, U256::from(1)); - (db, call_contract()) - }, - ); -} - /* The remaining creation sites. */ /// `CREATE2` reaches its deployment address by hashing rather than by nonce, and is priced in diff --git a/crates/mega-evm/tests/satin/salt_failure.rs b/crates/mega-evm/tests/satin/salt_failure.rs index 2e3d8bfa8..82ec5dbac 100644 --- a/crates/mega-evm/tests/satin/salt_failure.rs +++ b/crates/mega-evm/tests/satin/salt_failure.rs @@ -235,17 +235,6 @@ fn test_a_capacity_below_the_minimum_bucket_fails_the_transaction() { } } -/// The same report at the minimum itself is a bucket, not a misreport: it prices at `m = 1`. -#[test] -fn test_the_minimum_capacity_itself_is_priced_not_refused() { - let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); - let envs = minimal_envs() - .with_bucket_capacity(slot_bucket(CONTRACT, U256::from(SLOT)), MIN_BUCKET_SIZE as u64); - - let outcome = run(db(code), envs, call_contract()); - assert_eq!(outcome.gas.state, entry(GasId::sstore_set_state_gas())); -} - /// A system-originated transaction is priced at the minimum bucket without reading SALT, so a /// SALT environment that cannot answer does not stop the protocol's own work. #[test] diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index e3701c7ed..36071f47a 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -28,7 +28,7 @@ use mega_evm::{ MegaTransaction, }; use revm::{ - bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, + bytecode::opcode::{CALL, PUSH0, RETURN}, context::{result::EVMError, ContextTr}, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, @@ -44,25 +44,15 @@ use revm::{ use crate::{ common::{history, state_is_free}, salt::{ - account_bucket, authorization_tx, call_contract, create_with, crowded_account, - crowded_slot, db, entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, - try_run, tx, tx_with_gas, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, + account_bucket, call_contract, create_with, crowded_account, crowded_slot, db, entry, + minimal_envs, run, salt_context, slot_bucket, try_run, tx, tx_with_gas, SaltEnvs, CALLER, + CONTRACT, GAS_LIMIT, }, }; -/// The contract a probe's inner frame runs in. -const SUB: Address = alloy_primitives::address!("0000000000000000000000000000000000c00005"); - /// The slot every probe that writes storage uses. const SLOT: u64 = 7; -/// The gas a probe's inner call forwards: 2,000,000 on top of `unit` of state gas at the largest -/// multiplier the probes crowd a bucket to, so the inner frame can pay for what it adds at every -/// multiplier and byte price. -fn inner_gas(unit: u64) -> u64 { - 2_000_000 + 8 * unit -} - /// Runs `probe` at each multiplier and returns the state gas it netted, requiring the regular /// ledger to be the same at all of them. fn net_state_at( @@ -116,207 +106,6 @@ fn test_a_slot_written_and_restored_nets_nothing_at_every_multiplier() { ); } -/// A creation whose init code reverts: the `CREATE` opcode charged its caller for the account -/// leaf upfront, and the frame that did not create it gives the charge back at the same price. -#[test] -fn test_a_reverting_creation_gives_its_upfront_charge_back() { - let created = CONTRACT.create(0); - let probe = || { - // Init code `PUSH0 PUSH0 REVERT`: the creation fails, so no account leaf is added. - let code = create_with(&[PUSH0, PUSH0, REVERT]).stop().build(); - (db(code), call_contract()) - }; - - assert_eq!( - net_state_at([1, 2, 8], move |envs, m| crowded_account(envs, created, m), probe), - [0, 0, 0], - "a creation that deployed nothing pays no state gas", - ); -} - -/// A `CALL` that charged for a new account leaf and then failed gives the charge back: the -/// caller cannot afford the transfer, so no account is created. -#[test] -fn test_a_failed_value_call_gives_its_new_account_charge_back() { - let probe = || { - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(1u64) - .push_address(EMPTY) - .push_number(1_000_000u64) - .append(CALL) - .stop() - .build(); - // The contract holds nothing, so the transfer the CALL attempts cannot be made. - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(CONTRACT, code); - (db, call_contract()) - }; - - assert_eq!( - net_state_at([1, 2, 8], |envs, m| crowded_account(envs, EMPTY, m), probe), - [0, 0, 0], - "no account was created, so the upfront charge comes back", - ); -} - -/// A charge made two frames deep and rolled back with its frame comes back whole: the inner -/// frame wrote a slot in a crowded bucket and reverted. -#[test] -fn test_a_charge_in_a_reverting_inner_frame_comes_back_whole() { - let forwarded = inner_gas(entry(GasId::sstore_set_state_gas())); - let probe = || { - let sub = BytecodeBuilder::default() - .sstore(U256::from(SLOT), U256::from(1)) - .revert_with_data([0xaa]) - .build(); - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_address(SUB) - .push_number(forwarded) - .append(CALL) - .stop() - .build(); - (db(code).account_code(SUB, sub), call_contract()) - }; - - assert_eq!( - net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, SUB, U256::from(SLOT), m), probe), - [0, 0, 0], - "the frame's rollback takes its state charge with it", - ); -} - -/// What an inner frame keeps still scales: the same program with the inner frame succeeding -/// pays the crowded price, so the arms above are not passing because nothing was charged. -#[test] -fn test_a_charge_an_inner_frame_keeps_scales_with_its_bucket() { - let forwarded = inner_gas(entry(GasId::sstore_set_state_gas())); - let probe = || { - let sub = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_address(SUB) - .push_number(forwarded) - .append(CALL) - .stop() - .build(); - (db(code).account_code(SUB, sub), call_contract()) - }; - - let set = entry(GasId::sstore_set_state_gas()); - assert_eq!( - net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, SUB, U256::from(SLOT), m), probe), - [set, set * 2, set * 8], - ); -} - -/// A `SELFDESTRUCT` charges for the beneficiary's leaf inside the frame that runs it, and a frame -/// whose caller does not survive gives the charge back: the inner frame self-destructed, the outer -/// one reverted, and the beneficiary was never created after all. -#[test] -fn test_a_selfdestruct_whose_caller_reverts_gives_its_charge_back() { - let forwarded = inner_gas(entry(GasId::new_account_state_gas())); - let probe = |outer_reverts: bool| { - move || { - let sub = selfdestruct_to(EMPTY).build(); - let mut code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_number(0u64) - .push_address(SUB) - .push_number(forwarded) - .append(CALL); - code = if outer_reverts { code.revert_with_data([0xaa]) } else { code.stop() }; - let db = db(code.build()) - .account_code(SUB, sub) - .account_balance(SUB, U256::from(1_000_000u64)); - (db, call_contract()) - } - }; - let crowd = |envs, m| crowded_account(envs, EMPTY, m); - - assert_eq!( - net_state_at([1, 2, 8], crowd, probe(true)), - [0, 0, 0], - "the reverting caller takes the beneficiary's leaf back with it", - ); - - // The control: the same program whose outer frame survives keeps the charge, scaled. Without - // it the zeroes above could be passing because nothing was ever charged. - let new_account = entry(GasId::new_account_state_gas()); - assert_eq!( - net_state_at([1, 2, 8], crowd, probe(false)), - [new_account, new_account * 2, new_account * 8], - ); -} - -/// The whole transaction reverting is the same story one level up: the outermost frame's charge -/// goes back with it. -#[test] -fn test_a_transaction_that_reverts_pays_no_state_gas() { - let probe = || { - let code = BytecodeBuilder::default() - .sstore(U256::from(SLOT), U256::from(1)) - .revert_with_data([0xaa]) - .build(); - (db(code), call_contract()) - }; - - assert_eq!( - net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, CONTRACT, U256::from(SLOT), m), probe), - [0, 0, 0], - ); -} - -/// An applied EIP-7702 authorization is not a frame's doing: the delegation it wrote outlives a -/// frame that reverts afterwards, and so does the state gas it paid. -#[test] -fn test_an_applied_authorization_keeps_its_charge_through_a_revert() { - let authority_charges = - entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()); - let probe = || { - let code = BytecodeBuilder::default().revert_with_data([0xaa]).build(); - (db(code), authorization_tx(CONTRACT)) - }; - - assert_eq!( - net_state_at([1, 2, 8], |envs, m| crowded_account(envs, AUTHORITY, m), probe), - [authority_charges, authority_charges * 2, authority_charges * 8], - "the authority's leaf and its delegation bytes are still there after the revert", - ); - - // And the delegation really did survive: the authority carries the designation. - let outcome = try_run( - db(BytecodeBuilder::default().revert_with_data([0xaa]).build()), - crowded_account(minimal_envs(), AUTHORITY, 8), - authorization_tx(CONTRACT), - ) - .expect("the transaction is valid"); - assert!( - outcome.state.get(&AUTHORITY).is_some_and(|account| account - .info - .code - .as_ref() - .is_some_and(|code| !code.is_empty())), - "the authority kept its delegation", - ); -} - /// A creation whose deployed code is refused before any deposit charge is made: EIP-3541 turns /// down a runtime code starting `0xEF` at validation, so the only state gas in play is the /// account leaf the transaction's own create target was charged for upfront, which comes back. @@ -342,29 +131,6 @@ fn test_a_refused_code_deposit_pays_no_state_gas() { ); } -/// A charge kept beside one given back: the kept one scales, the other nets out, and the -/// transaction pays exactly the difference. -#[test] -fn test_a_kept_charge_and_a_restored_one_settle_independently() { - const KEPT: u64 = 3; - let probe = || { - let code = BytecodeBuilder::default() - .sstore(U256::from(KEPT), U256::from(1)) - .sstore(U256::from(SLOT), U256::from(1)) - .sstore(U256::from(SLOT), U256::ZERO) - .stop() - .build(); - (db(code), call_contract()) - }; - let crowd = |envs: SaltEnvs, m: u64| { - let envs = crowded_slot(envs, CONTRACT, U256::from(KEPT), m); - crowded_slot(envs, CONTRACT, U256::from(SLOT), m) - }; - - let set = entry(GasId::sstore_set_state_gas()); - assert_eq!(net_state_at([1, 2, 8], crowd, probe), [set, set * 2, set * 8]); -} - /* The refund route that runs without a frame. */ /// The address a synthetic frame would have added a leaf at. From 9a719af933edaff73e7b4b51abe140922e5587ea Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 18:53:31 +0800 Subject: [PATCH 128/190] test(state-growth): remove tests duplicated by the conformance suite The destruction table's give-backs, the state-growth sites and budgets at depth, a keyless creation's budget, and an authorization list over the limit are pinned by Mega EEST's cases. --- .../tests/satin/limit_matrix/destruction.rs | 438 +----------------- .../tests/satin/limit_matrix/keyless.rs | 86 ---- crates/mega-evm/tests/satin/state_growth.rs | 312 ------------- 3 files changed, 2 insertions(+), 834 deletions(-) diff --git a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs index 7bf239920..f6051ef8a 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs @@ -14,8 +14,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATALOAD, CALLDATASIZE, CALLVALUE, GAS, JUMPDEST, JUMPI, LT, MLOAD, POP, - PUSH0, SELFDESTRUCT, SLOAD, SSTORE, STOP, + ADDRESS, CALL, CALLDATALOAD, CALLDATASIZE, GAS, JUMPDEST, JUMPI, LT, POP, PUSH0, + SELFDESTRUCT, SSTORE, STOP, }, context::{result::ExecutionResult, TxEnv}, interpreter::{ @@ -176,36 +176,6 @@ fn test_a_kept_destruction_gives_back_the_leaf_the_code_and_the_slot() { 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 @@ -287,64 +257,6 @@ fn test_stores_after_the_mark_and_a_reverted_enclosing_frame() { } } -/// 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, @@ -378,108 +290,6 @@ fn test_a_destroying_childs_negative_net_does_not_raise_the_parents_budget() { 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 @@ -633,61 +443,6 @@ fn test_a_cleared_account_with_no_kv_room_stops_at_the_frame_budget() { } } -/// 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. @@ -710,112 +465,6 @@ fn test_a_prefunded_destruction_that_moves_no_balance_keeps_the_nonce_record() { 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. @@ -1036,51 +685,6 @@ fn test_a_detention_crossing_at_the_destruction_applies_none_of_the_table() { /// 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 @@ -1134,44 +738,6 @@ fn test_a_deposit_after_the_mark_is_not_charged_what_its_frame_cannot_pay() { } } -/// 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 diff --git a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs index cde66e284..24a4ea871 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs @@ -224,24 +224,6 @@ fn start_charges() -> u64 { 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. @@ -506,74 +488,6 @@ fn test_authorization_list_boundaries() { 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 diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index b9cfbe4f8..302767782 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -167,109 +167,6 @@ fn account_and_delegation() -> (u64, u64) { (entry(GasId::new_account_state_gas()), entry(GasId::tx_eip7702_state_gas_bytecode())) } -/// An authorization adds state only when it applies: a new account for an authority that did not -/// exist, and the delegation's bytes once for an authority that was not delegated. Each authority -/// it applies to is one write record, however many of its authorizations applied, except the -/// sender, whose account is the body's. An authorization that does not apply — a wrong nonce, a -/// wrong chain, a nonce that cannot be bumped, an account with code, a signature that recovers to -/// nobody — adds nothing and leaves its authority as it was. -#[test] -fn test_an_authorization_adds_state_only_when_it_applies() { - if state_is_free() { - return; - } - let (account, delegation) = account_and_delegation(); - let a1 = Some(AUTHORITY_1); - let a2 = Some(AUTHORITY_2); - let with_code = || funded().account_code(AUTHORITY_1, Bytes::from_static(&[STOP])); - // (case, database, authorizations, state gas, records, AUTHORITY_1's nonce after) - type Case = (&'static str, MemoryDatabase, Vec, u64, u64, u64); - let cases: Vec = vec![ - ("a new authority", funded(), vec![(a1, 0, 0)], account + delegation, 1, 1), - ( - "two new authorities", - funded(), - vec![(a1, 0, 0), (a2, 0, 0)], - 2 * (account + delegation), - 2, - 1, - ), - ( - "one new authority authorized twice at its first nonce", - funded(), - vec![(a1, 0, 0), (a1, 0, 0)], - account + delegation, - 1, - 1, - ), - ( - "one new authority authorized twice in sequence", - funded(), - vec![(a1, 0, 0), (a1, 0, 1)], - account + delegation, - 1, - 2, - ), - ( - "an authority that exists", - funded().account_balance(AUTHORITY_1, U256::from(1)), - vec![(a1, 0, 0)], - delegation, - 1, - 1, - ), - ( - "an authority on the transaction's chain", - funded(), - vec![(a1, 1, 0)], - account + delegation, - 1, - 1, - ), - ("an authority on another chain", funded(), vec![(a1, 999, 0)], 0, 0, 0), - ("a wrong nonce", funded(), vec![(a1, 0, 1)], 0, 0, 0), - ("a nonce that cannot be bumped", funded(), vec![(a1, 0, u64::MAX)], 0, 0, 0), - ("an authority with code", with_code(), vec![(a1, 0, 0)], 0, 0, 0), - ("a signature that recovers to nobody", funded(), vec![(None, 0, 0)], 0, 0, 0), - ( - "the sender, at the nonce its transaction leaves it", - funded(), - vec![(Some(CALLER), 0, 1)], - delegation, - 0, - 0, - ), - ( - "the sender, at its transaction's own nonce", - funded(), - vec![(Some(CALLER), 0, 0)], - 0, - 0, - 0, - ), - ]; - for (name, db, authorizations, state_gas, records, nonce) in cases { - let tuples = authorizations.len() as u64 * mega_evm::AUTHORIZATION_SIZE; - let outcome = run( - db.account_code(A, Bytes::from_static(&[STOP])), - authorizing(A, U256::ZERO, &authorizations), - ); - assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); - assert_eq!(outcome.gas.state, state_gas, "{name}: the state gas"); - assert_eq!(outcome.usage.write_records, records, "{name}: the records"); - assert_eq!( - outcome.usage.data_size, - TX_BODY_SIZE + tuples + records * WRITE_RECORD_SIZE, - "{name}: the data size", - ); - let authority = outcome.state.get(&AUTHORITY_1); - assert_eq!(authority.map_or(0, |a| a.info.nonce), nonce, "{name}: the authority's nonce"); - let delegated = - outcome.state.values().any(|a| a.info.code.as_ref().is_some_and(|c| c.is_eip7702())); - assert_eq!(delegated, state_gas >= delegation, "{name}: whether anything was delegated"); - } -} - /// 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. @@ -330,44 +227,6 @@ fn test_an_authority_an_earlier_transaction_touched_is_charged_as_new_when_commi assert_eq!(outcome.usage.write_records, 1); } -/// An account the database holds empty under EIP-161 — nonce zero, no balance, no code, and -/// storage holding nothing — exists for an authorization and is new for a value transfer: an -/// authority is new only where the state holds no account at its address, while a transaction's -/// value counts an empty recipient as new as it counts an absent one. The authorization charges the -/// delegation's bytes alone and counts no rise, and still writes the account, one record; the -/// value charges the new account and counts the rise. -#[test] -fn test_an_account_the_database_holds_empty_is_new_to_a_value_transfer_and_not_to_an_authority() { - if state_is_free() { - return; - } - let (account, delegation) = account_and_delegation(); - let held_empty = || { - funded().account_code(A, Bytes::from_static(&[STOP])).account_storage( - AUTHORITY_1, - U256::ZERO, - U256::ZERO, - ) - }; - let held = revm::Database::basic(&mut held_empty(), AUTHORITY_1).expect("in memory"); - assert!( - held.is_some_and(|info| info.is_empty()), - "the database holds the authority's account, empty" - ); - - let authorized = run(held_empty(), authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)])); - assert!(authorized.result.is_success(), "{:?}", authorized.result); - assert_eq!(authorized.state[&AUTHORITY_1].info.nonce, 1, "the authorization applied"); - assert_eq!(authorized.gas.state, delegation, "the delegation's bytes, and no new account"); - assert_eq!(authorized.usage.state_growth, 0, "the authority existed"); - assert_eq!(authorized.usage.write_records, 1, "the authority's record"); - - let paid = run(held_empty(), call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP)); - assert!(paid.result.is_success(), "{:?}", paid.result); - assert_eq!(paid.gas.state, account, "the new account"); - assert_eq!(paid.usage.state_growth, 1, "the empty recipient is a new account"); -} - /// The same two transactions on one journal that is not finalized in between differ from the /// committed path, in simulation only: revm's flag of the call's touch outlives the call's /// transaction, so the application finds the authority touched, not new, and charges the @@ -432,21 +291,6 @@ fn test_an_authority_the_transaction_cannot_pay_for_is_not_applied() { assert!(run(crowded_account(minimal_envs(), AUTHORITY_1, 100), roomy).result.is_success()); } -/// A value transaction to an authority it creates pays for one new account, not two: by the time -/// EIP-2780 looks at the recipient the authorization has created it. It is one record too. -#[test] -fn test_an_authority_that_is_the_recipient_pays_for_one_account() { - let (account, delegation) = account_and_delegation(); - let outcome = - run(funded(), authorizing(AUTHORITY_1, U256::from(1), &[(Some(AUTHORITY_1), 0, 0)])); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.state, account + delegation); - assert_eq!(outcome.usage.write_records, 1); - - let unauthorized = run(funded(), call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP)); - assert_eq!(unauthorized.gas.state, account, "the same transfer without it pays the account"); -} - /// A transaction whose authorities' records would cross the data-size limit is rejected at /// validation, whether the authorities are new or exist already: validation holds the body and a /// record for each entry of the authorization list to the limit, before anything is applied or @@ -560,18 +404,6 @@ fn test_a_stopped_deposit_keeps_the_caller_it_created() { assert_eq!(stopped.gas.state, account_state_gas(), "the caller's account"); } -/// A `SELFDESTRUCT` of value to itself grows no state and records nothing. The destructions that -/// move value to another account are held with the SALT pricing and the write records. -#[test] -fn test_a_destruction_to_itself_grows_no_state() { - let db = funded() - .account_code(A, BytecodeBuilder::default().push_address(A).append(SELFDESTRUCT).build()); - let outcome = run(db, call(CALLER, A, U256::ZERO, BELOW_CAP)); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.gas.state, 0, "the state gas"); - assert_eq!(outcome.usage.write_records, 0, "the records"); -} - /// A state charge the frame cannot pay is an out-of-gas, which no limit turns into a stop. /// /// Each case is a transaction below the execution cap, so there is no reservoir, whose gas limit @@ -933,31 +765,6 @@ fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { ); } -/// 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 @@ -1057,125 +864,6 @@ fn test_a_slot_written_back_to_zero_falls_and_makes_room() { } } -/// 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 From affc482f5891fab5708bd1b7531144302988a430 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 18:58:03 +0800 Subject: [PATCH 129/190] test(write-records): remove tests duplicated by the conformance suite The write records of value transfers, creations, destructions, storage writes, fee accounts and applied authorities are pinned by Mega EEST's cases. The test of an out-of-gas after the authorities stays: it is the only one that catches a change to their take-back. --- crates/mega-evm/tests/satin/write_records.rs | 633 +------------------ 1 file changed, 2 insertions(+), 631 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index d2621492e..0f18419d7 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,9 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, - JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, - STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, + LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -96,50 +95,6 @@ fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) } -/* ---------- value transfers and creations: a record per account that changed ---------- */ - -/// 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, value_call_room()), - ); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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 @@ -186,69 +141,6 @@ 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 @@ -323,20 +215,6 @@ fn test_a_child_that_reverts_after_writing_keeps_nothing() { } } -/// 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] @@ -370,43 +248,6 @@ fn test_nested_creations_record_each_account_once() { 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 @@ -575,24 +416,6 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { } } -/// A creation and a value transfer from one frame record the frame's account once. -#[test] -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, value_call_room()), - ); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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" - ); -} - /// Two creations from one frame record the creator once and each created account. #[test] fn test_two_creates_record_the_creator_once() { @@ -611,48 +434,6 @@ fn test_two_creates_record_the_creator_once() { ); } -/// A value transfer into a child that fails is discarded with the child, sender included. -#[test] -fn test_failed_child_discards_its_transfer_records() { - let code = - 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, value_call_room())); - assert!(result.result.is_success(), "the outer call succeeds although the child halts"); - assert_eq!(usage, body_only()); -} - -/// After a failed transfer the sender can be recorded again by the next one. -/// -/// The first child burns the gas it was forwarded, so the second transfer forwards none: its -/// recipient runs no code, and the records it makes are paid out of what the caller keeps, which -/// then does not depend on the price of the recipient's new account. -#[test] -fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { - let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); - let code = code - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .append(PUSH1) - .append(1u8) - .push_address(CONTRACT2) - .append(PUSH0) - .append(CALL) - .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, value_call_room())); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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 { @@ -706,62 +487,10 @@ fn reverting_creations(n: usize) -> Bytes { code.into() } -/// Two reverted creations record the creator once: the first record survives, so the second -/// finds the creator recorded. -#[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, value_call_room())); - assert!(result.result.is_success()); - assert_eq!(usage, records(1)); -} - -/// A creation the creator cannot fund never starts (the opcode checks the endowment before it -/// builds a frame), so it records nothing. -#[test] -fn test_creation_without_funds_records_nothing() { - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0]) - .push_number(1_000_000_000_000_u64) - .append(CREATE) - .append(POP) - .stop() - .build(); - let db = MemoryDatabase::default().account_code(CALLEE, code); - 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"); -} - const A: Address = address!("00000000000000000000000000000000A0000001"); const B: Address = address!("00000000000000000000000000000000B0000002"); 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), 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) -} - -/// A top-level transfer to the sender itself writes no account the body does not already count. -#[test] -fn test_top_level_self_transfer_no_double_count() { - assert_eq!(value_delta(A), LimitUsage::ZERO); -} - -/// A top-level transfer to another account records the recipient. -#[test] -fn test_top_level_transfer_counts_the_recipient() { - 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 /// calldata stops at once. fn self_calling_code(targets: &[Address], value: u64) -> Bytes { @@ -808,251 +537,6 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { ); } -/* ---------- storage, logs, selfdestruct ---------- */ - -/// A slot's first change is a record; writing it back to its original value takes it back. -#[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, 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)), - ]; - for (writes, original, expected) in cases { - let mut code = BytecodeBuilder::default(); - for (slot, value) in writes { - code = code.sstore(U256::from(*slot), U256::from(*value)); - } - 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, value_call_room())); - assert!(result.result.is_success()); - assert_eq!(usage, expected, "writes {writes:?} over original {original}"); - } -} - -/// A write-back in a child refunds the record its caller made, and the refund dies with a -/// failing child. -#[test] -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(); - // 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() - .sstore(U256::ZERO, U256::from(1)) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(CONTRACT) - .append(GAS) - .append(revm::bytecode::opcode::DELEGATECALL) - .append(POP) - .stop() - .build(); - let db = - MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - 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 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 = [ - // 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(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, value_call_room())); - assert!(result.result.is_success()); - assert_eq!(usage, expected, "balance {balance}, beneficiary {beneficiary}"); - } -} - -/// A top-level creation records the created account, and nothing when it fails. -#[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]), value_call_room()), - ); - assert!(result.result.is_success()); - 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]), value_call_room()), - ); - assert!(!result.result.is_success()); - assert_eq!(usage, with_extra(body_only(), 1)); -} - -/* ---------- the fee accounts and the sender ---------- */ - -/// The block beneficiary of the fee-account rows: an account of its own, not the zero address. -const COINBASE: Address = address!("00000000000000000000000000000000000C0B00"); - -/// How execution reaches an account in the rows of -/// [`test_execution_writes_to_the_fee_accounts_are_records`]. -#[derive(Clone, Copy, Debug)] -enum FeeRowPath { - /// `CALLEE` sends it one wei with a `CALL`. - ValueTransfer, - /// `CALLEE` destructs itself naming it as beneficiary, which moves `CALLEE`'s balance to it. - SelfDestruct, -} - -/// A write execution makes to one of the four accounts a transaction's fees are credited to is a -/// record like a write to any other account: the body's five fixed records bound the fee credits -/// the settlement makes, not what the transaction's frames write. The sender's account is the -/// converse: the body counts it, so nothing execution writes to it is recorded again, and that -/// holds for a fee account that is the sender too. -/// -/// 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 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 -/// the settlement credits the beneficiary and the base fee vault on top of what execution wrote. -/// -/// A record weighs `WRITE_RECORD_SIZE` bytes of data size and history and is one KV update; the -/// history is its bytes at the cost per history byte, on top of the body's `TX_BODY_SIZE`. -/// -/// Independence: constants — -/// the record counts are written out per row, and the data size, KV count and history are hand -/// arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE`, `TRANSFER_LOG_SIZE` and the cost per -/// history byte in effect. -#[test] -fn test_execution_writes_to_the_fee_accounts_are_records() { - use op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}; - use FeeRowPath::{SelfDestruct, ValueTransfer}; - - // (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, 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, 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, 2), - ( - "the operator fee vault, by a value transfer", - CALLER, - OPERATOR_FEE_RECIPIENT, - ValueTransfer, - 2, - ), - ( - "the operator fee vault, by a SELFDESTRUCT", - CALLER, - OPERATOR_FEE_RECIPIENT, - SelfDestruct, - 2, - ), - ("the sender, by a value transfer", CALLER, CALLER, ValueTransfer, 1), - ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 1), - ( - "the block beneficiary that is the sender, by a value transfer", - COINBASE, - COINBASE, - ValueTransfer, - 1, - ), - ( - "the block beneficiary that is the sender, by a SELFDESTRUCT", - COINBASE, - COINBASE, - SelfDestruct, - 1, - ), - ]; - for (row, sender, target, path, records) in rows { - let code = match path { - ValueTransfer => append_value_call(BytecodeBuilder::default(), target, 1) - .append(POP) - .append(STOP) - .build(), - SelfDestruct => { - BytecodeBuilder::default().push_address(target).append(SELFDESTRUCT).build() - } - }; - let mut db = funded().account_code(CALLEE, code).account_balance(sender, U256::MAX >> 2); - for account in [COINBASE, L1_FEE_RECIPIENT, BASE_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { - if account != sender { - db = db.account_balance(account, U256::from(1)); - } - } - 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() }; - let outcome = MegaEvm::new(context(db).with_block(block)) - .execute_transaction(tx) - .expect("the transaction is valid"); - assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); - assert_eq!(transfer_logs(&outcome.result), 1, "{row}: the transfer log"); - // The settlement credited the fees on top of what execution moved: the priority fee of - // nine a gas to the beneficiary, the base fee of one a gas to the base fee vault. - for (credited, per_gas) in [(COINBASE, 9u64), (BASE_FEE_RECIPIENT, 1)] { - if credited == sender { - continue; - } - let moved = match path { - _ if credited != target => 0, - ValueTransfer => 1, - SelfDestruct => 10_000_000, - }; - assert_eq!( - outcome.state[&credited].info.balance, - U256::from(1 + moved + outcome.gas.gas_used * per_gas), - "{row}: the fee credited to {credited}" - ); - } - - let history_bytes = TX_BODY_SIZE + records * WRITE_RECORD_SIZE; - assert_eq!(outcome.usage.write_records, records, "{row}: the records, the KV count"); - assert_eq!( - outcome.usage.data_size, - history_bytes + TRANSFER_LOG_SIZE, - "{row}: the data size: the body, the records and the transfer log" - ); - assert_eq!(outcome.gas.history_bytes, history_bytes, "{row}: the history bytes"); - if !crate::common::history_rounds() { - assert_eq!( - outcome.gas.history, - history(history_bytes), - "{row}: the history gas: the body and the records at the cost per history byte" - ); - } - } -} - /* ---------- the commit happens after the opcode ---------- */ /// Records, after each opcode, what the layer holds. @@ -1145,7 +629,6 @@ fn test_a_tools_log_in_step_counts_nothing() { const DELEGATE: Address = address!("00000000000000000000000000000000DE1E0001"); const AUTHORITY_1: Address = address!("00000000000000000000000000000000A0717001"); -const AUTHORITY_2: Address = address!("00000000000000000000000000000000A0717002"); /// A type-4 transaction from `CALLER` to `to` with value `value`, carrying authorizations /// `(authority, nonce)` that delegate to `DELEGATE`. @@ -1164,69 +647,6 @@ fn authorizing_call( ) } -/// Each distinct applied authority is one record, however many of its authorizations applied; -/// an authorization that does not apply (a wrong nonce) records nothing. -#[test] -fn test_applied_authorities_record_once_each() { - let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let (result, usage) = run( - db(), - 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, 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()); - assert_eq!( - usage, - with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE), - "a wrong nonce applies nothing, and its tuple is still in the body" - ); -} - -/// A value transfer to an applied authority records the authority once, not again as the -/// recipient. -#[test] -fn test_value_to_an_applied_authority_records_it_once() { - let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let (result, usage) = run(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!( - usage, - 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 - // authority's account is already written. A transfer to an account that is not an authority - // pays for the recipient on top of the one authority it applied. - if crate::common::runs_at_measurement_prices() { - return; - } - const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; - let to_authority = - crate::common::execute(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); - let to_another = - crate::common::execute(db(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)])); - let body = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE; - - assert!(to_another.result.is_success(), "{:?}", to_another.result); - assert_eq!( - to_authority.gas.history, - (body + WRITE_RECORD_SIZE) * CPHB, - "the authority's record, and no recipient record beside it", - ); - assert_eq!( - to_another.gas.history, - (body + 2 * WRITE_RECORD_SIZE) * CPHB, - "the authority's record and the recipient's", - ); -} - /// A frame running as the transaction's sender (a delegated sender called back) records no /// write to the sender's account: the transaction body counts it. #[test] @@ -1588,32 +1008,6 @@ fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authoriti const D: Address = address!("00000000000000000000000000000000000000D1"); -/// 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 = - append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); - let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) - .append(POP) - .append(STOP) - .build(); - let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); - 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, - 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 has its own account unchanged, whatever its caller's state: its /// first value transfer records it. #[test] @@ -1765,29 +1159,6 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { ); } -/// 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) - .append(POP) - .append(STOP) - .build(); - let mut db = funded().account_code(CONTRACT, sender_code); - let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); - 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, value_call_room())); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - 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. struct AnswerContract; From aa88293161b41a3e4b1da3da1131ef0fafea8560 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 19:02:24 +0800 Subject: [PATCH 130/190] test(system): remove tests duplicated by the conformance suite The interceptor dispatch by address and selector, a value-bearing call's refusal, MegaLimitControl's answers and its fall-through are pinned by Mega EEST's cases. --- crates/mega-evm/tests/system/control.rs | 13 +-- crates/mega-evm/tests/system/dispatch.rs | 75 +----------------- crates/mega-evm/tests/system/limit_control.rs | 79 ------------------- crates/mega-evm/tests/system/main.rs | 1 - 4 files changed, 2 insertions(+), 166 deletions(-) delete mode 100644 crates/mega-evm/tests/system/limit_control.rs diff --git a/crates/mega-evm/tests/system/control.rs b/crates/mega-evm/tests/system/control.rs index a26445c9d..f609d5e7a 100644 --- a/crates/mega-evm/tests/system/control.rs +++ b/crates/mega-evm/tests/system/control.rs @@ -4,7 +4,7 @@ use alloy_primitives::{Bytes, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, NON_ZERO_TRANSFER_REVERT_DATA}, + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS}, test_utils::MemoryDatabase, }; use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}; @@ -64,17 +64,6 @@ fn test_a_static_call_is_intercepted() { assert!(data.is_empty()); } -/// A call that carries value to one of the three methods is refused with `NonZeroTransfer()`: -/// they read or steer execution and take no value. -#[test] -fn test_a_value_bearing_call_is_refused() { - for selector in [DISABLE, ENABLE, IS_DISABLED] { - let (status, data) = through_contract(CALL, &selector, 1); - assert!(!status, "a value-bearing call must not succeed"); - assert_eq!(data, Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA)); - } -} - /// The value policy is per method, after the selector matched: a value-bearing call to a /// selector the contract does not intercept still falls through to the bytecode. #[test] diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs index 51015dca3..abab39218 100644 --- a/crates/mega-evm/tests/system/dispatch.rs +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -3,7 +3,7 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; +use alloy_sol_types::SolCall; use mega_evm::{ system::{ storage_slots::CURRENT_SYSTEM_ADDRESS, IMegaAccessControl, IMegaLimitControl, IOracle, @@ -68,49 +68,6 @@ fn test_an_intercepted_call_costs_what_a_plain_call_costs() { assert_eq!(spent(intercepted), spent(plain)); } -/// How much gas the caller forwards to an intercepted call does not change what it costs: the -/// forwarded gas comes back in full. -#[test] -fn test_the_forwarded_gas_of_an_intercepted_call_comes_back() { - let low = call_with_gas(LIMIT_CONTROL_ADDRESS, &REMAINING_COMPUTE_GAS, 1_000_000); - let high = call_with_gas(LIMIT_CONTROL_ADDRESS, &REMAINING_COMPUTE_GAS, 9_000_000); - assert_eq!(low.len(), high.len(), "the two programs differ only in the gas they forward"); - assert_eq!(spent(low), spent(high)); -} - -/// Admission is the four selector bytes: the exact selector and the selector followed by -/// anything are both intercepted, and an input too short to hold one is not. -#[test] -fn test_admission_is_the_selector_alone() { - let intercepted = |data: Vec| { - let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, &data, U256::ZERO)); - // The interceptor answers `false`; the deployed bytecode reverts. - result.result.is_success() - }; - assert!(intercepted(IS_DISABLED.to_vec()), "the exact selector"); - assert!(intercepted(IS_DISABLED.iter().copied().chain([0xff]).collect()), "one byte after it"); - assert!( - intercepted(IS_DISABLED.iter().copied().chain([0_u8; 32]).collect()), - "a padded argument after it", - ); - assert!(!intercepted(IS_DISABLED[..3].to_vec()), "three bytes are not a selector"); - assert!(!intercepted(Vec::new()), "no input is not a selector"); - assert!(!intercepted(vec![0xde, 0xad, 0xbe, 0xef]), "another selector"); -} - -/// The dispatch reaches a system contract only at its own address: the same selectors sent -/// anywhere else run whatever code is there. -#[test] -fn test_the_address_admits_the_dispatch() { - let db = system_db().account_code(PLAIN_TARGET, Bytes::new()); - let result = run(db, call_tx(PLAIN_TARGET, IS_DISABLED, U256::ZERO)); - assert!(result.result.is_success()); - assert!( - result.result.output().is_none_or(|output| output.is_empty()), - "an account without code answers nothing, so nothing was intercepted", - ); -} - /// Records which addresses an inspector sees called, and in which order they end. #[derive(Default)] struct CallTracker { @@ -196,28 +153,6 @@ fn test_a_database_error_reading_the_registry_fails_the_transaction() { assert!(format!("{error}").contains("injected storage() error"), "{error}"); } -/// The value policy is the interceptor's, not the account's: a value-bearing transaction to a -/// control contract is refused with `NonZeroTransfer()` before any value moves. -#[test] -fn test_a_value_bearing_transaction_is_refused_before_the_value_moves() { - let db = system_db(); - let mut tx = call_tx(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS, U256::from(1)); - tx.0.base.caller = crate::common::CALLER; - let result = run(db, tx); - - let revm::context::result::ExecutionResult::Revert { output, .. } = &result.result else { - panic!("the transaction did not revert: {:?}", result.result); - }; - assert_eq!(output[..], IMegaLimitControl::NonZeroTransfer::SELECTOR); - assert!( - result - .state - .get(&LIMIT_CONTROL_ADDRESS) - .is_none_or(|account| account.info.balance.is_zero()), - "the refused value stayed with its sender", - ); -} - /// A `STATICCALL` to a system contract from inside a static frame is intercepted too: nothing /// about the answer writes state. #[test] @@ -264,14 +199,6 @@ fn test_a_nested_static_call_is_intercepted() { ); } -/// A transaction that reaches no system contract is untouched by the dispatch. -#[test] -fn test_a_transaction_that_touches_no_system_contract_is_untouched() { - let code = BytecodeBuilder::default().append(STOP).build(); - let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert!(result.result.is_success()); -} - /// The two system contracts without an interceptor run their bytecode, whatever the call /// carries and whichever scheme makes it: an unknown selector reverts in their dispatcher, where /// a call to an account without code would succeed. diff --git a/crates/mega-evm/tests/system/limit_control.rs b/crates/mega-evm/tests/system/limit_control.rs deleted file mode 100644 index 03c0eca3a..000000000 --- a/crates/mega-evm/tests/system/limit_control.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! The `MegaLimitControl` interceptor: `remainingComputeGas`, the value policy, the unknown -//! selector and the call schemes. - -use alloy_primitives::{Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS, NON_ZERO_TRANSFER_REVERT_DATA}; -use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL}; - -use crate::common::{call_tx, output, revert_data, run, system_db, GAS_LIMIT}; - -const REMAINING_COMPUTE_GAS: [u8; 4] = IMegaLimitControl::remainingComputeGasCall::SELECTOR; -const NOT_INTERCEPTED: [u8; 4] = IMegaLimitControl::NotIntercepted::SELECTOR; - -/// A call from a contract to the limit control contract, run as a transaction. -fn through_contract(scheme: u8, data: &[u8], value: u64) -> (bool, Bytes) { - crate::common::through_contract(LIMIT_CONTROL_ADDRESS, scheme, data, value) -} - -/// Decodes what `remainingComputeGas()` answered. -fn remaining(data: &Bytes) -> u64 { - IMegaLimitControl::remainingComputeGasCall::abi_decode_returns(data) - .expect("the answer is a uint64") -} - -/// `remainingComputeGas()` is intercepted and answers the caller's regular gas, which is below the -/// execution cap and below what the transaction had. What the figure is exactly is in -/// `remaining_compute_gas`. -#[test] -fn test_remaining_compute_gas_is_intercepted() { - let (status, data) = through_contract(CALL, &REMAINING_COMPUTE_GAS, 0); - assert!(status); - let remaining = remaining(&data); - assert!(remaining > 0, "the call was forwarded gas"); - assert!(remaining < GAS_LIMIT, "the caller spent gas before the call"); - assert!( - remaining <= mega_evm::constants::TX_GAS_LIMIT_CAP, - "regular gas never exceeds the execution cap", - ); -} - -/// A call that carries value is refused with `NonZeroTransfer()`: the method reads and takes no -/// value. -#[test] -fn test_a_value_bearing_call_is_refused() { - let (status, data) = through_contract(CALL, &REMAINING_COMPUTE_GAS, 1); - assert!(!status); - assert_eq!(data, Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA)); -} - -/// A selector the contract does not intercept, and an input too short to hold one, fall through -/// to the deployed bytecode, which reverts with `NotIntercepted()`. -#[test] -fn test_an_unknown_selector_falls_through_to_not_intercepted() { - for data in [vec![0xde, 0xad, 0xbe, 0xef], vec![], REMAINING_COMPUTE_GAS[..3].to_vec()] { - let result = run(system_db(), call_tx(LIMIT_CONTROL_ADDRESS, &data, U256::ZERO)); - assert_eq!(revert_data(&result), Bytes::from_static(&NOT_INTERCEPTED), "input {data:?}"); - } -} - -/// A selector followed by trailing bytes is intercepted: admission is the four bytes alone. -#[test] -fn test_a_selector_with_trailing_bytes_is_intercepted() { - for tail in [vec![0xff], vec![0x00; 32]] { - let data: Vec = REMAINING_COMPUTE_GAS.iter().copied().chain(tail).collect(); - let result = run(system_db(), call_tx(LIMIT_CONTROL_ADDRESS, &data, U256::ZERO)); - assert!(remaining(&output(&result)) > 0); - } -} - -/// `CALLCODE` and `DELEGATECALL` never reach an interceptor: the scheme guard refuses them, and -/// the contract's own bytecode runs, which reverts with `NotIntercepted()`. -#[test] -fn test_callcode_and_delegatecall_are_not_intercepted() { - for scheme in [CALLCODE, DELEGATECALL] { - let (status, data) = through_contract(scheme, &REMAINING_COMPUTE_GAS, 0); - assert!(!status, "scheme {scheme:#x} must not be intercepted"); - assert_eq!(data, Bytes::from_static(&NOT_INTERCEPTED)); - } -} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index 51a97c9fa..875f7ba44 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -6,7 +6,6 @@ mod common; mod control; mod dispatch; mod keyless; -mod limit_control; mod oracle; mod oracle_storage; mod predeploys; From aff278697515b28384a1284ddef27ffa0e81b605 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 19:03:51 +0800 Subject: [PATCH 131/190] test(system): remove Oracle and system-transaction tests duplicated by the conformance suite The Oracle's hints and reads, and the Mega System Transaction's validation, promotion and created caller are pinned by Mega EEST's cases. --- crates/mega-evm/tests/system/oracle.rs | 307 +--------------------- crates/mega-evm/tests/system/system_tx.rs | 148 ----------- 2 files changed, 2 insertions(+), 453 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 3c6ada677..71a90cecd 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -13,7 +13,7 @@ use mega_evm::{ RecordedHint, TestExternalEnvs, }; use revm::{ - bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, + bytecode::opcode::CALL, context::{result::ResultAndState, CfgEnv}, context_interface::ContextTr, interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome}, @@ -22,8 +22,7 @@ use revm::{ }; use crate::common::{ - block, call_tx, call_tx_with_gas, calls_with, run, steer, system_db, with_contract, CALLER, - CONTRACT, + block, call_tx, call_tx_with_gas, steer, system_db, with_contract, CALLER, CONTRACT, }; /// A topic and payload the tests send. @@ -88,95 +87,6 @@ fn try_run_with_oracle_under( Some((outcome, envs.recorded_hints())) } -/// A `sendHint` transaction reaches the oracle service with the caller, the topic and the -/// payload, and the call itself succeeds through the contract's own bytecode. -#[test] -fn test_send_hint_reaches_the_oracle_service() { - let payload = b"a hint".to_vec(); - let (result, hints, _) = run_with_oracle( - system_db(), - call_tx(ORACLE_CONTRACT_ADDRESS, send_hint(&payload), U256::ZERO), - ); - - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!( - hints, - vec![RecordedHint { from: CALLER, topic: TOPIC, data: Bytes::from(payload) }], - ); -} - -/// The bytes the node materialised for the hint are counted on the transaction's data size, -/// trailing bytes the decoder ignores included. -#[test] -fn test_the_hint_payload_is_counted_on_the_transaction() { - let data = send_hint(b"a hint"); - let (_, hints, usage) = - run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO)); - assert_eq!(hints.len(), 1); - assert_eq!(usage.data_size, top_level_hint(data.len() as u64)); - - // The same call with bytes the ABI decoder drops pays for them too. - let padded: Vec = data.iter().copied().chain([0_u8; 64]).collect(); - let (_, hints, padded_usage) = - run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, &padded, U256::ZERO)); - assert_eq!(hints.len(), 1, "the trailing bytes do not stop the decoding"); - assert_eq!(padded_usage.data_size, top_level_hint(padded.len() as u64)); -} - -/// A payload that does not decode is paid for and forwards nothing. -#[test] -fn test_a_malformed_payload_is_paid_for_and_not_forwarded() { - let data: Vec = - IOracle::sendHintCall::SELECTOR.iter().copied().chain([0xff_u8; 8]).collect(); - let (_, hints, usage) = - run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); - assert!(hints.is_empty(), "a payload that does not decode carries no hint"); - assert_eq!(usage.data_size, top_level_hint(data.len() as u64)); -} - -/// A `STATICCALL` forwards the hint: `sendHint` is a view method. -#[test] -fn test_a_static_call_forwards_the_hint() { - let data = send_hint(b"static"); - let code = calls_with(STATICCALL, ORACLE_CONTRACT_ADDRESS, &data, 0); - let (result, hints, _) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert!(result.result.is_success()); - assert_eq!(hints.len(), 1); - assert_eq!(hints[0].from, CONTRACT, "the frame that called is the sender of the hint"); -} - -/// A call that carries value is judged on its gas like any other, and a call that requests none -/// still holds the value call's stipend, so its hint is admitted. `sendHint` is not payable, so -/// the bytecode refuses the value; the hint is a message to the service and was already sent, and -/// its bytes stay counted. -#[test] -fn test_a_value_bearing_call_forwards_its_hint() { - use revm::bytecode::opcode::{POP, PUSH0, REVERT}; - - let data = send_hint(b"paid"); - let code = BytecodeBuilder::default() - .mstore(0x0, &data) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(data.len() as u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(0_u64) // gas: none requested, the stipend is all the call holds - .append(CALL) - .append(POP) - .append_many([PUSH0, PUSH0, REVERT]) - .build(); - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(!result.result.is_success(), "the frame that sent the hint reverted"); - assert_eq!(hints.len(), 1, "the hint reached the service"); - assert_eq!(hints[0].from, CONTRACT); - assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); -} - /// Code that calls the Oracle with `data`, one unit of value and no requested gas, and returns /// the call's status followed by its return data. The contract holds no balance, so the call /// cannot be funded. @@ -215,34 +125,6 @@ fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) } -/// A value-bearing `sendHint` whose caller cannot fund the value is intercepted before revm -/// starts the call and checks the funds: the hint is forwarded and its input counted, then the -/// call fails for the funds with empty return data and moves no value, and the Oracle's bytecode -/// never runs. -#[test] -fn test_an_unfunded_value_hint_is_forwarded_and_then_fails_for_funds() { - let data = send_hint(b"unfunded"); - let (result, hints, usage) = - run_with_oracle(unfunded_contract_db(&data), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(result.result.is_success(), "the contract survives the failed call"); - let returned = result.result.output().cloned().unwrap_or_default(); - let (status, return_data) = crate::common::split_outcome(&returned); - assert!(!status, "the call fails for funds"); - assert!(return_data.is_empty(), "with empty return data"); - assert_eq!( - hints, - vec![RecordedHint { from: CONTRACT, topic: TOPIC, data: Bytes::from_static(b"unfunded") }], - "the hint reached the service", - ); - assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its input is counted"); - assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + data.len() as u64); - let balance = - |address| result.state.get(&address).map_or(U256::ZERO, |account| account.info.balance); - assert_eq!(balance(CONTRACT), U256::ZERO, "no value moved from the caller"); - assert_eq!(balance(ORACLE_CONTRACT_ADDRESS), U256::ZERO, "and none reached the Oracle"); -} - /// The same unfunded call under a data-size limit its input would cross is answered with the /// stop, not with the funds failure: nothing is forwarded and nothing is counted. #[test] @@ -269,22 +151,6 @@ fn test_an_unfunded_value_hint_over_the_limit_is_answered_with_the_stop() { assert_eq!(outcome.limit_exceeded, None, "a stop below is no stop of the transaction"); } -/// The bytecode refuses the value of a value-bearing call that holds gas, as before: the hint is -/// forwarded and the call reports failure. -#[test] -fn test_a_value_bearing_call_with_gas_forwards_its_hint_and_the_bytecode_refuses() { - let data = send_hint(b"paid with gas"); - let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &data, 1); - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - let outcome = result.result.output().cloned().unwrap_or_default(); - let (status, _) = crate::common::split_outcome(&outcome); - assert!(!status, "the bytecode refuses the value"); - assert_eq!(hints.len(), 1); - assert_eq!(usage.data_size, nested_hint(data.len() as u64)); -} - /// Records the gas the first frame of the Oracle call holds: the gas limit of the call as the /// interceptor sees it, which an inspector's `call` hook is handed before the engine decides the /// start. @@ -383,83 +249,6 @@ fn test_a_transactions_own_value_hint_is_admitted_on_one_gas_and_more() { } } -/// A call forwarded no gas forwards nothing: it cannot run the contract either, so its hint -/// would be a free message to the service. -#[test] -fn test_a_call_without_gas_forwards_nothing() { - use revm::bytecode::opcode::{POP, STOP}; - - let data = send_hint(b"free"); - let code = BytecodeBuilder::default() - .mstore(0x0, &data) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(data.len() as u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(0_u64) // gas - .append(CALL) - .append(POP) - .append(STOP) - .build(); - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(result.result.is_success(), "the caller survives the failed call"); - assert!(hints.is_empty()); - assert_eq!(usage.data_size, nested_hint(0)); -} - -/// A call forwarded one gas does forward its hint, and the frame it was sent from then runs out -/// of gas: positive gas is what admits a hint, not a promise that the bytecode can run. The hint -/// is a synchronous side effect, so the service holds it whatever the frame does next. -#[test] -fn test_a_call_with_one_gas_forwards_the_hint_it_cannot_deliver() { - use revm::bytecode::opcode::{MSTORE, RETURN}; - - let data = send_hint(b"one gas"); - let code = BytecodeBuilder::default() - .mstore(0x0, &data) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(data.len() as u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_u64) // gas: enough to admit the hint, not to run the bytecode - .append(CALL) - // memory[0..32] = the call's status, and return it - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(result.result.is_success(), "the caller survives the failed call"); - let outcome = result.result.output().cloned().unwrap_or_default(); - let (status, _) = crate::common::split_outcome(&outcome); - assert!(!status, "one gas does not run the contract's dispatcher"); - assert_eq!(hints.len(), 1, "the hint reached the service before the frame ran out of gas"); - assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); -} - -/// `CALLCODE` and `DELEGATECALL` never reach the interceptor, so they forward nothing. -#[test] -fn test_callcode_and_delegatecall_forward_nothing() { - let data = send_hint(b"scheme"); - for scheme in [CALLCODE, DELEGATECALL] { - let code = calls_with(scheme, ORACLE_CONTRACT_ADDRESS, &data, 0); - let (_, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert!(hints.is_empty(), "scheme {scheme:#x} must not reach the interceptor"); - assert_eq!(usage.data_size, nested_hint(0)); - } -} - /// A selector the Oracle's interceptor does not know is not intercepted: the call runs the /// contract's bytecode, which reverts with empty data on a selector it does not declare — the /// Oracle carries no fallback of its own. @@ -479,52 +268,6 @@ fn test_an_unknown_selector_runs_the_bytecode() { assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + 4); } -/// Reading the Oracle's storage is not intercepted: `getSlot` runs the contract's code. -#[test] -fn test_reading_a_slot_runs_the_bytecode() { - let db = system_db().account_storage(ORACLE_CONTRACT_ADDRESS, U256::from(3), U256::from(42)); - let data = IOracle::getSlotCall { slot: U256::from(3) }.abi_encode(); - let result = run(db, call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!( - IOracle::getSlotCall::abi_decode_returns(result.result.output().unwrap()).unwrap(), - B256::from(U256::from(42)), - ); -} - -/// A hint cannot be un-sent, so the bytes it cost stay counted even when the frame that sent it -/// reverts and takes its writes back. -#[test] -fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { - use revm::bytecode::opcode::{POP, PUSH0, REVERT}; - - let data = send_hint(b"a hint that was sent"); - let code = BytecodeBuilder::default() - .mstore(0x0, &data) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(data.len() as u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(200_000_u64) - .append(CALL) - .append(POP) - .append_many([PUSH0, PUSH0, REVERT]) - .build(); - - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(!result.result.is_success(), "the frame that sent the hint reverted"); - assert_eq!(hints.len(), 1, "the hint reached the service before the revert"); - assert_eq!( - usage.data_size, - nested_hint(data.len() as u64), - "the bytes stay counted: a revert cannot take the hint back", - ); -} - /// A payload that does not fit in what is left of the transaction's data-size limit is not /// forwarded, and the crossing stops the transaction: the limit is checked on the hint's bytes /// before the payload is decoded, so it is crossed before the frame the call would have started. @@ -623,27 +366,6 @@ const DISABLE: [u8; 4] = const ENABLE: [u8; 4] = mega_evm::system::IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; -/// A contract's hint reaches the service with the contract as its sender, and the call runs the -/// Oracle's `sendHint`, which succeeds. -#[test] -fn test_a_contracts_hint_reaches_the_service_from_the_contract() { - let data = send_hint(&[0xde, 0xad, 0xbe, 0xef]); - let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 1_000_000)); - let (result, hints, _) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - let outcome = result.result.output().cloned().unwrap_or_default(); - assert_eq!(U256::from_be_slice(&outcome), U256::ONE, "sendHint succeeded"); - assert_eq!( - hints, - vec![RecordedHint { - from: CONTRACT, - topic: TOPIC, - data: Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef]) - }], - ); -} - /// The Oracle's code at another address is not the Oracle: its `sendHint` runs and forwards /// nothing. #[test] @@ -658,31 +380,6 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } -/// Two hints reach the service in the order they were sent. -#[test] -fn test_hints_reach_the_service_in_the_order_they_were_sent() { - use revm::bytecode::opcode::POP; - - let first = IOracle::sendHintCall { - topic: B256::repeat_byte(0x11), - data: Bytes::from_static(&[0xaa, 0xbb]), - }; - let second = IOracle::sendHintCall { - topic: B256::repeat_byte(0x22), - data: Bytes::from_static(&[0xcc, 0xdd]), - }; - let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); - let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); - let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert_eq!( - hints, - vec![ - RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, - RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, - ], - ); -} - /// A malformed `sendHint` payload, and one followed by bytes the decoder drops, are counted /// whole: the first forwards nothing, the second forwards its envelope. Under a limit that holds /// half of the payload, both are stopped before anything is forwarded: the call is answered with diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index eaf56450c..bd356c9a6 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -120,14 +120,6 @@ fn run_outcome(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcom MegaEvm::new(chain_context(db)).execute_transaction(tx).expect("the transaction is valid") } -/// Runs `tx` and returns the error it was rejected with, as a string. -fn rejection(db: MemoryDatabase, tx: MegaTransaction) -> String { - let error = MegaEvm::new(chain_context(db)) - .execute_transaction(tx) - .expect_err("the transaction must be rejected"); - format!("{error:?}") -} - /// The Oracle's slot as the database holds it. fn oracle_slot(db: &mut DB, slot: U256) -> U256 where @@ -581,39 +573,6 @@ fn test_two_system_transactions_in_a_block_both_go_through() { assert_eq!(nonce_of(&mut state, MEGA_SYSTEM_ADDRESS), 2); } -/// A system transaction carries the chain's id, so it cannot be replayed on another chain; one -/// without an id at all is refused too. -#[test] -fn test_a_system_transaction_is_bound_to_the_chain() { - let foreign = legacy_tx_with_chain_id( - MEGA_SYSTEM_ADDRESS, - TxKind::Call(ORACLE_CONTRACT_ADDRESS), - set_slot(ORACLE_SLOT, B256::with_last_byte(0xcc)), - 0, - Some(31_337), - ); - let rejected = rejection(chain_db(), foreign); - assert!(rejected.contains("InvalidChainId"), "{rejected}"); - - let no_chain_id = legacy_tx_with_chain_id( - MEGA_SYSTEM_ADDRESS, - TxKind::Call(ORACLE_CONTRACT_ADDRESS), - set_slot(ORACLE_SLOT, B256::with_last_byte(0xdd)), - 0, - None, - ); - let rejected = rejection(chain_db(), no_chain_id); - assert!(rejected.contains("MissingChainId"), "{rejected}"); -} - -/// The system address may not carry code (EIP-3607), as no sender may. -#[test] -fn test_a_system_address_with_code_is_refused() { - let db = chain_db().account_code(MEGA_SYSTEM_ADDRESS, Bytes::from_static(&[0x00])); - let rejected = rejection(db, system_tx(0, B256::with_last_byte(0xce))); - assert!(rejected.contains("RejectCallerWithCode"), "{rejected}"); -} - /// Runs `tx` on `db` under the chain's configuration with `mutate` applied. fn run_with( mutate: fn(&mut CfgEnv), @@ -763,40 +722,6 @@ fn test_a_system_transaction_short_of_its_body_history_is_a_failed_deposit() { assert_eq!(gas.gas_used, least); } -/// A deposit-like transaction whose caller does not exist yet creates that account, and pays -/// the account-creation charge for it exactly once: the same charge a value transfer to a -/// fresh account pays. -#[test] -fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { - // The reference charge: a user transaction that creates one account by sending value to it. - let fresh = address!("0x00000000000000000000000000000000000f0001"); - let reference = - run_outcome(chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), { - let mut tx = legacy_tx(CALLER, TxKind::Call(fresh), Bytes::new(), 0); - tx.0.base.value = U256::from(1); - tx - }); - let one_account = reference.gas.state; - assert_eq!(one_account, account_state_gas(), "a fresh recipient costs state gas"); - - // A system transaction whose sender does not exist yet creates it, for the same charge. - let created = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x77))); - assert!(created.result.is_success(), "{:?}", created.result); - // The same transaction from a sender that already exists: what it pays is the slot it - // writes, and nothing for its own account. - let slot_charge = run_outcome( - chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), - system_tx(0, B256::with_last_byte(0x77)), - ) - .gas - .state; - assert_eq!( - created.gas.state - slot_charge, - one_account, - "the caller's account costs one account creation, and the slot the same either way", - ); -} - /// A deposit whose recipient is its own caller pays for that one account once: by the time the /// recipient is looked at, the caller's materialisation has created it. #[test] @@ -842,33 +767,6 @@ fn deposit_one_short_of_its_caller(sender: Address) -> MegaTransaction { tx } -/// A deposit that cannot pay for the account it creates for its caller runs out of gas before its -/// first frame, and a deposit that does is a failed deposit: the `FailedDeposit` halt, not an -/// out-of-gas, billed its whole gas limit. -/// -/// Independence: constants — the intrinsic gas is -/// EIP-2780's, the caller account's state gas the schedule's entry at the price in effect. -#[test] -fn test_a_deposit_that_cannot_pay_for_its_caller_is_a_failed_deposit() { - // An account that costs nothing is one any deposit can pay for. - if state_is_free() { - return; - } - let sender = address!("0x00000000000000000000000000000000000f0006"); - let tx = deposit_one_short_of_its_caller(sender); - let gas_limit = tx.0.base.gas_limit; - let outcome = run_outcome(chain_db(), tx); - assert!( - matches!( - outcome.result, - ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } - ), - "{:?} is not a failed deposit", - outcome.result, - ); - assert_eq!(outcome.gas.gas_used, gas_limit, "a failed deposit bills its whole gas limit"); -} - /// The account a deposit creates for its caller is charged before its first frame, and a body over /// the data-size limit does not waive the charge: a deposit that cannot pay for it is a failed /// deposit, which reports the failure and not the data-size stop, and keeps its body counted. @@ -963,27 +861,6 @@ 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. 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))); - let existing = run_outcome( - chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), - system_tx(0, B256::with_last_byte(0x99)), - ); - assert!(fresh.result.is_success() && existing.result.is_success()); - assert_eq!( - (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 /// caller as well as for the contract. #[test] @@ -1007,28 +884,3 @@ fn test_a_deposit_that_creates_a_contract_pays_for_its_caller_too() { "the created caller costs state gas on top of the created contract", ); } - -/// A transaction that already carries the system source hash is a deposit by type, so it does -/// not have the system shape: from the live system address it is a failed deposit, as every -/// deposit from that address is. No promotion is made for -/// it, so none of the promotion's checks runs: its nonce is not the system address's. -/// -/// A block's transactions are decoded from their legacy encoding, which carries no source hash, -/// so this is the shape a caller hands the engine directly, not one a block holds. -#[test] -fn test_a_transaction_that_arrives_promoted_is_a_failed_deposit() { - let mut tx = - legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), get_slot(), 7); - tx.0.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - let outcome = MegaEvm::new(chain_context(chain_db())) - .execute_transaction(tx) - .expect("a deposit is not refused"); - assert!( - matches!( - outcome.result, - ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } - ), - "{:?}", - outcome.result - ); -} From 2e1853d1e61f4a5b00902a8949fef4b3e18a9489 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 19:06:35 +0800 Subject: [PATCH 132/190] test(keyless): remove tests duplicated by the conformance suite The keyless deployment's rules, their order and the charges before the creation are pinned by Mega EEST's cases. Two refusal tests stay: they are the only ones that reach the decoder's NotContractCreation and NotPreEIP155 branches. --- .../tests/system/keyless/precedence.rs | 235 +--------- crates/mega-evm/tests/system/keyless/rules.rs | 421 +----------------- 2 files changed, 4 insertions(+), 652 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 0c6808565..93eea761a 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -14,52 +14,9 @@ //! bytecode and reverted with empty data. A call whose arguments do not decode is no deployment //! at all, with or without value, and runs the bytecode as the legacy engine did. -use mega_evm::{ - system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, - test_utils::MemoryDatabase, -}; +use mega_evm::{system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::MemoryDatabase}; use super::*; -use crate::common::state_is_free; - -/// The gas limit the matrix's deployments are signed with: 500,000 on top of the state gas of the -/// account the creation adds, at the byte prices in effect, so the creation's charges leave part of -/// it whatever a state byte costs. -fn signed_gas() -> u64 { - 500_000 + entry(GasId::create_state_gas()) -} - -/// What a call is answered with. -#[derive(Debug, PartialEq, Eq)] -enum Answer { - /// A revert with a rule's error. - Refused(KeylessDeployError), - /// An out-of-gas halt. - OutOfGas, -} - -/// A call that fails the rules named, over `db`, carrying `data`, at `gas_limit`. -struct Case { - rules: &'static str, - db: MemoryDatabase, - data: Bytes, - gas_limit: u64, - answer: Answer, -} - -impl Case { - fn check(self) { - let outcome = run_with(self.db, self.data, self.gas_limit, EvmTxRuntimeLimits::no_limits()); - let answer = match &outcome.result { - ExecutionResult::Revert { output, .. } => { - Answer::Refused(decode_error_result(output).expect("a keyless deploy error")) - } - ExecutionResult::Halt { .. } => Answer::OutOfGas, - other => panic!("{}: the call was not refused: {other:?}", self.rules), - }; - assert_eq!(answer, self.answer, "{} at {}", self.rules, self.gas_limit); - } -} /// A deployment signed with `gas_limit`, carrying `value`. fn signed(gas_limit: u64, value: u64) -> Deployment { @@ -85,66 +42,6 @@ fn leaving(data: &Bytes, left: u64) -> u64 { left } -/// `GasLimitTooLow` for a deployment signed with [`signed_gas`], with `provided`. -fn too_low(provided: u64) -> Answer { - Answer::Refused(KeylessDeployError::GasLimitTooLow { - tx_gas_limit: signed_gas(), - provided_gas_limit: provided, - }) -} - -/// Pairs of failing rules that do not depend on the call's gas, at both gas limits: the rule the -/// legacy engine checked first is the one reported. -#[test] -fn test_a_call_two_rules_refuse_reports_the_first_the_legacy_engine_checked() { - let plain = signed(signed_gas(), 0); - let carrying = signed(signed_gas(), 1); - for gas_limit in GAS_LIMITS { - let data = plain.call_data(LARGE_OVERRIDE); - let cases = [ - Case { - rules: "gasLimitOverride below the signed gas limit, and an occupied address", - db: occupied(funded(system_db(), &plain), &plain), - data: plain.call_data(signed_gas() - 1), - gas_limit, - answer: too_low(signed_gas() - 1), - }, - Case { - rules: "the signer's nonce, and an occupied address", - db: occupied(system_db().account_nonce(plain.signer, 2), &plain), - data: data.clone(), - gas_limit, - answer: Answer::Refused(KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }), - }, - Case { - rules: "the signer's nonce, and a value it cannot fund", - db: system_db().account_nonce(carrying.signer, 2), - data: carrying.call_data(LARGE_OVERRIDE), - gas_limit, - answer: Answer::Refused(KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }), - }, - Case { - rules: "the signer's code, and an occupied address", - db: occupied( - system_db().account_code(plain.signer, Bytes::from_static(&[0x00])), - &plain, - ), - data, - gas_limit, - answer: Answer::Refused(KeylessDeployError::SignerHasCode), - }, - Case { - rules: "an occupied address, and a value the signer cannot fund", - db: occupied(system_db().account_nonce(carrying.signer, 1), &carrying), - data: carrying.call_data(LARGE_OVERRIDE), - gas_limit, - answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), - }, - ]; - cases.into_iter().for_each(Case::check); - } -} - /// A call that carries value and a transaction that does not decode is refused for the value: the /// value rule comes before decoding the transaction. The same call without value is refused /// `MalformedEncoding()`. Arguments that do not decode as `(bytes, uint256)` are no deployment at @@ -183,103 +80,6 @@ fn test_a_value_bearing_call_that_does_not_decode_is_refused_for_the_value() { } } -/// Pairs of failing rules one of which is the call's gas, below the execution cap, where the call -/// pays every charge out of the gas it forwards. The signer's account and the forward come before -/// the deploy address and the balance, as they did in the legacy engine; the charges of the -/// creation's start come after every rule, so a rule they would have run out of gas behind still -/// refuses the call. -#[test] -fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_balance() { - let new_account = entry(GasId::new_account_state_gas()); - // What a call left one short of the signer's account has once it paid its overhead. The cases - // that leave it are filtered out below where the account costs nothing. - let short_of_the_account = new_account.saturating_sub(1); - let plain = signed(signed_gas(), 0); - let carrying = signed(signed_gas(), 1); - let carrying_two = signed(signed_gas(), 2); - let small = signed(1_000, 0); - let small_carrying = signed(1_000, 1); - let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); - let cases = [ - Case { - rules: "the signer's account the call cannot pay, and an occupied address", - db: occupied(system_db(), &plain), - data: data(&plain), - gas_limit: leaving(&data(&plain), short_of_the_account), - answer: Answer::OutOfGas, - }, - Case { - rules: "the signer's account the call cannot pay, and a value it cannot fund", - db: system_db(), - data: data(&carrying), - gas_limit: leaving(&data(&carrying), short_of_the_account), - answer: Answer::OutOfGas, - }, - Case { - rules: "a forward below the signed gas limit, and an occupied address", - db: occupied(funded(system_db(), &plain), &plain), - data: data(&plain), - gas_limit: leaving(&data(&plain), signed_gas() - 1), - answer: too_low(signed_gas() - 1), - }, - Case { - rules: "a forward the signer's account takes below the signed gas limit, and an \ - occupied address", - db: occupied(system_db(), &plain), - data: data(&plain), - gas_limit: leaving(&data(&plain), new_account + signed_gas() - 1), - answer: too_low(signed_gas() - 1), - }, - Case { - rules: "a forward below the signed gas limit, and a value the signer cannot fund", - db: funded(system_db(), &carrying_two), - data: data(&carrying_two), - gas_limit: leaving(&data(&carrying_two), signed_gas() - 1), - answer: too_low(signed_gas() - 1), - }, - Case { - rules: - "an occupied address, and a forward the creation's charges would take below the \ - signed gas limit", - db: occupied(funded(system_db(), &plain), &plain), - data: data(&plain), - gas_limit: leaving(&data(&plain), signed_gas()), - answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), - }, - Case { - rules: "an occupied address, and creation charges the call cannot pay", - db: occupied(funded(system_db(), &small), &small), - data: data(&small), - gas_limit: leaving(&data(&small), 1_500), - answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), - }, - Case { - rules: "a value the signer cannot fund, and a forward the creation's charges would \ - take below the signed gas limit", - db: system_db(), - data: data(&carrying), - gas_limit: leaving(&data(&carrying), new_account + signed_gas()), - answer: Answer::Refused(KeylessDeployError::InsufficientBalance), - }, - Case { - rules: "a value the signer cannot fund, and creation charges the call cannot pay", - db: system_db(), - data: data(&small_carrying), - gas_limit: leaving(&data(&small_carrying), new_account + 1_500), - answer: Answer::Refused(KeylessDeployError::InsufficientBalance), - }, - ]; - // An account that costs nothing is one any call can pay for: the two cases of a signer's - // account the call cannot pay have nothing to run where a state byte is free. - let free = state_is_free(); - cases - .into_iter() - .filter(|case| { - !(free && case.rules.starts_with("the signer's account the call cannot pay")) - }) - .for_each(Case::check); -} - /// Above the execution cap the reservoir pays the signer's account, and only a signed gas limit /// near the cap leaves the forward short of it: the forward still comes before the deploy address /// and the balance. @@ -316,39 +116,6 @@ fn test_the_forward_comes_before_the_address_and_the_balance_above_the_cap() { } } -/// What the `CREATE` opcode charges the call for the creation's start can refuse a call no rule -/// refuses: a call that cannot pay it runs out of gas, and one it leaves short of the signed gas -/// limit is refused `GasLimitTooLow` with what it left. The legacy engine charged none of it to -/// the call, and ran such a deployment in its sandbox on what the call had. Above the execution -/// cap the refusal is -/// `limits::test_a_refusal_after_the_creations_charges_gives_the_reservoir_back`. -#[test] -fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { - let plain = signed(signed_gas(), 0); - let small = signed(1_000, 0); - let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); - let charges = create_regular(deploying(&runtime(1)).len()) + - entry(GasId::create_state_gas()) + - 2 * record(); - let cases = [ - Case { - rules: "creation charges the call cannot pay", - db: funded(system_db(), &small), - data: data(&small), - gas_limit: leaving(&data(&small), 1_500), - answer: Answer::OutOfGas, - }, - Case { - rules: "a forward the creation's charges take below the signed gas limit", - db: funded(system_db(), &plain), - data: data(&plain), - gas_limit: leaving(&data(&plain), signed_gas()), - answer: too_low(signed_gas() - charges), - }, - ]; - cases.into_iter().for_each(Case::check); -} - /// An out-of-gas at step 14 halts the call, consuming its regular gas, and gives back the state /// and history gas the call was charged: the transaction's gas used is its gas limit, its state /// ledger is empty and its history ledger is its body's. diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 95e82d629..4f20d3ec2 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -16,13 +16,9 @@ use mega_evm::{ active_satin_prices, alloy_consensus::TxEip1559, constants::MAX_INITCODE_SIZE, - system::keyless::{ - tests::{ - CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, - EIP1820_CONTRACT, EIP1820_DEPLOYER, EIP1820_TX, NON_CONTRACT_CREATION_TX, - POST_EIP155_CHAIN_1_TX, - }, - KEYLESS_DEPLOY_OVERHEAD_GAS, + system::keyless::tests::{ + CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, EIP1820_CONTRACT, + EIP1820_DEPLOYER, EIP1820_TX, NON_CONTRACT_CREATION_TX, POST_EIP155_CHAIN_1_TX, }, test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError}, MegaSpecId, MegaTransactionError, TestExternalEnvs, @@ -32,7 +28,6 @@ use revm::{ CALL, CALLER, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH3, REVERT, STOP, }, context::{result::EVMError, CfgEnv}, - context_interface::cfg::GasId, primitives::KECCAK_EMPTY, state::{AccountInfo, Bytecode}, DatabaseCommit, @@ -69,21 +64,6 @@ fn small() -> Deployment { Deployment::new(deploying(&runtime(1))) } -/// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. -#[test] -fn test_keyless_deploy_gas_limit_too_low() { - for gas_limit in GAS_LIMITS { - let outcome = submit(system_db(), CREATE2_FACTORY_TX, 99_999, gas_limit); - assert_eq!( - refusal(&outcome), - KeylessDeployError::GasLimitTooLow { - tx_gas_limit: 100_000, - provided_gas_limit: 99_999 - }, - ); - } -} - /// An override equal to the signed gas limit passes rule 2, and the creation runs with exactly /// that much: signed short of what its creation spends below the execution cap, it runs out of gas /// having spent all of it. The canonical `CREATE2` factory was signed for a chain that charges no @@ -157,102 +137,6 @@ fn short_of_their_creation() -> Vec { short } -/// The gas limit at which a `keylessDeploy` of `deployment`, carrying `init_len` bytes of init -/// code, leaves the call `forward` to forward to its creation, below the execution cap, for a -/// signer that has an account and a deploy address that is empty: the reference transaction's -/// spend, the overhead, the `CREATE` opcode's regular gas, the created account and the two -/// records, and the forward. -fn gas_limit_forwarding(deployment: &Deployment, init_len: usize, forward: u64) -> u64 { - let intrinsic = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]) - .result - .gas() - .total_gas_spent(); - intrinsic + - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(init_len) + - entry(GasId::create_state_gas()) + - 2 * record() + - forward -} - -/// A signed gas limit the signer's account can take the forward below: 500,000 on top of the -/// account's state gas at the byte prices in effect, so the call can pay for the account out of -/// the forward whatever a state byte costs. -fn signed_above_the_account() -> u64 { - 500_000 + entry(GasId::new_account_state_gas()) -} - -/// The length of the init code the forwarding tests deploy: a one-byte runtime. -fn one_byte_init_len() -> usize { - deploying(&runtime(1)).len() -} - -/// Rule 2 again, once the call has paid for the creation's start: the override is capped to what -/// the call has left, and the capped gas must still cover the signed gas limit. A relayer that -/// sizes its transaction below that is refused, with the capped figure. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself -/// and the reservoir pays the call's state and history charges, so no gas limit leaves the -/// call this little. The refusal above the cap is -/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. -#[test] -fn test_a_forward_capped_below_the_signed_gas_limit_is_refused() { - let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); - let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 499_999); - let outcome = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!( - refusal(&outcome), - KeylessDeployError::GasLimitTooLow { tx_gas_limit: 500_000, provided_gas_limit: 499_999 }, - ); - assert_nothing_written(&outcome, &deployment, 0); -} - -/// A transaction that leaves the call exactly the signed gas limit deploys. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself -/// and the reservoir pays the call's state and history charges, so no gas limit leaves the -/// call this little. The refusal above the cap is -/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. -#[test] -fn test_a_forward_at_the_signed_gas_limit_deploys() { - let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); - let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 500_000); - let outcome = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); -} - -/// The charge for the signer's account comes out of the gas the creation would be forwarded when -/// the transaction has no reservoir, so it can take the forward below the signed gas limit: the -/// same transaction deploys for a signer that has an account and is refused for one that has -/// none. Above the execution cap the reservoir pays the charge, and both deploy. -#[test] -fn test_the_signers_account_can_take_the_forward_below_the_signed_gas_limit() { - // An account that costs nothing takes nothing from the forward. - if state_is_free() { - return; - } - let signed = signed_above_the_account(); - let deployment = Deployment::signed(0, signed, U256::ZERO, deploying(&runtime(1))); - let new_account = entry(GasId::new_account_state_gas()); - let gas_limit = - gas_limit_forwarding(&deployment, one_byte_init_len(), signed + new_account / 2); - - let funded = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&funded).deployedAddress, deployment.address, "the control deploys"); - let empty = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!( - refusal(&empty), - KeylessDeployError::GasLimitTooLow { - tx_gas_limit: signed, - provided_gas_limit: signed + new_account / 2 - new_account, - }, - ); - assert_nothing_written(&empty, &deployment, 0); - - let wide = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[1]); - assert_eq!(returned(&wide).deployedAddress, deployment.address, "the reservoir pays"); -} - /// Rule 3: the signer is recovered from the signature. `r` above the curve order recovers /// nothing. #[test] @@ -265,24 +149,6 @@ fn test_keyless_deploy_invalid_signature() { } } -/// So does `r = 0`, which no signature has. -#[test] -fn test_keyless_deploy_rejects_corrupted_signature() { - for gas_limit in GAS_LIMITS { - let signed = mega_evm::system::keyless::decode_keyless_tx(CREATE2_FACTORY_TX).unwrap(); - let s = signed.signature().s(); - let corrupted = Signed::new_unchecked( - signed.tx().clone(), - Signature::new(U256::ZERO, s, false), - B256::ZERO, - ); - let mut encoded = Vec::new(); - corrupted.rlp_encode(&mut encoded); - let outcome = submit(system_db(), &encoded, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); - } -} - /// A different `s` is a different signer, not an invalid signature: the deployment goes to that /// signer's address, never to the canonical one. #[test] @@ -302,21 +168,6 @@ fn test_keyless_deploy_modified_s_changes_signer() { } } -/// The transaction must be RLP a legacy transaction decodes from. -#[test] -fn test_keyless_deploy_malformed_encoding() { - for gas_limit in GAS_LIMITS { - for garbage in [&[0xde, 0xad, 0xbe, 0xef][..], &[], &CREATE2_FACTORY_TX[..100]] { - let outcome = submit(system_db(), garbage, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "{garbage:02x?}"); - } - let mut trailing = CREATE2_FACTORY_TX.to_vec(); - trailing.push(0x00); - let outcome = submit(system_db(), &trailing, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "a trailing byte"); - } -} - /// An EIP-2718 typed envelope is not a legacy transaction. #[test] fn test_keyless_deploy_rejects_eip2718_typed_envelope() { @@ -362,18 +213,6 @@ fn test_keyless_deploy_not_pre_eip155() { } } -/// The transaction must be signed at nonce 0: the deploy address is the signer's first. -#[test] -fn test_keyless_deploy_non_zero_tx_nonce() { - for gas_limit in GAS_LIMITS { - let deployment = - Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// Rule 8: the init code is within the initcode size limit the spec fixes. #[test] fn test_init_code_over_the_limit_is_refused() { @@ -408,18 +247,6 @@ fn test_init_code_at_the_limit_is_admitted() { } } -/// Rule 4: the signer's nonce is at most 1. -#[test] -fn test_keyless_deploy_signer_nonce_too_high() { - for gas_limit in GAS_LIMITS { - let deployment = small(); - let db = system_db().account_nonce(deployment.signer, 2); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); - assert_nothing_written(&outcome, &deployment, 2); - } -} - /// The two canonical keyless deployments: the transaction, the gas limit it was signed with, its /// signer and the address it deploys at. Signed for chains that charge no state gas for deployed /// code: at the spec's prices, without a reservoir, the signed gas limit does not cover the code @@ -529,56 +356,6 @@ fn test_a_resubmission_after_failures_and_a_deployment_finds_the_address_taken() } } -/// A deployment that succeeds from nonce 1 leaves the signer at 1 too: the creation's bump goes -/// with its record, so the deployment costs exactly one record's history less than the same one -/// from nonce 0, which keeps its bump. The record stays when the creation moved value out of the -/// signer's account, and then stands for that write. -#[test] -fn test_a_success_from_nonce_one_leaves_the_nonce_at_one() { - for gas_limit in GAS_LIMITS { - for (value, kept) in [(U256::ZERO, 0), (U256::ONE, 1)] { - let deployment = Deployment::with_value(deploying(&runtime(1)), value); - let funded = db_for(&deployment, U256::from(1_000)); - let at_zero = deploy(funded.clone(), &deployment, gas_limit); - let at_one = deploy(funded.account_nonce(deployment.signer, 1), &deployment, gas_limit); - assert_eq!(returned(&at_one).deployedAddress, deployment.address, "at {gas_limit}"); - assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); - assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); - assert_eq!(at_one.usage.write_records, 1 + kept, "value {value} at {gas_limit}"); - let taken_back = 1 - kept; - assert_eq!( - beyond(&at_zero, &at_one), - [taken_back * record(), 0, 0, taken_back * record(), taken_back * 40], - "value {value} at {gas_limit}", - ); - } - } -} - -/// A deployment that fails from nonce 1 keeps nothing of the signer: its records, its data size, -/// its history gas and its history bytes are those of a transaction that bumped no nonce — the -/// reference, which pays the same intrinsic gas and writes nothing — and it spends exactly one -/// record's history less than the same failure from nonce 0, which keeps its bump. -#[test] -fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - for gas_limit in GAS_LIMITS { - let at_one = - deploy(system_db().account_nonce(deployment.signer, 1), &deployment, gas_limit); - let at_zero = deploy(db_for(&deployment, U256::ONE), &deployment, gas_limit); - assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); - assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); - - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let [_, _, state, history_gas, history_bytes] = beyond(&at_one, &reference); - assert_eq!([state, history_gas, history_bytes], [0; 3], "at {gas_limit}"); - assert_eq!(at_one.usage, reference.usage, "at {gas_limit}"); - - assert_eq!(at_zero.usage.write_records, 1, "the signer's nonce record"); - assert_eq!(beyond(&at_zero, &at_one), [record(), 0, 0, record(), 40], "at {gas_limit}"); - } -} - /// However a deployment from nonce 1 fails — its init code reverts or halts, it deploys no code, /// or a limit stops its creation at its start — the signer stays at 1 and its nonce record goes. /// A creation that deployed no code is refused its empty deposit and reverts, so it keeps neither @@ -655,18 +432,6 @@ fn test_a_signer_that_sends_its_failing_deployment_ends_at_nonce_one() { } } -/// Rule 9: the signer has no code — EIP-3607 for a sender that is not the transaction's. -#[test] -fn test_a_signer_with_code_is_refused() { - for gas_limit in GAS_LIMITS { - let deployment = small(); - let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::SignerHasCode); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// A chain that disables EIP-3607 disables rule 9 with it, as it does for its own transactions. #[test] fn test_disabling_eip3607_disables_the_signer_code_rule() { @@ -714,30 +479,6 @@ fn test_a_disabled_eip3607_reads_no_signer_code() { } } -/// An EIP-7702 delegation is not code: a signer that delegated deploys. -#[test] -fn test_a_delegated_signer_deploys() { - for gas_limit in GAS_LIMITS { - let deployment = small(); - let delegation = - Bytecode::new_eip7702(address!("0x00000000000000000000000000000000000d1e6a")); - let mut db = system_db(); - db.insert_account_info( - deployment.signer, - AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash: delegation.hash_slow(), - code: Some(delegation), - ..Default::default() - }, - ); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - /// A delegated signer's own code can spend its nonces while its deployment runs: a constructor /// that calls the signer runs the delegation, which creates two accounts at the signer's next /// nonces. Those stay spent, and so does the creation's own bump below them — the settlement @@ -879,23 +620,6 @@ fn test_a_delegated_signer_whose_creation_reverts_keeps_every_bump() { } } -/// Rule 5: the deploy address holds no code. The occupancy read goes through the journal, so the -/// deploy address is in the transaction's state — the witness a stateless client replays the -/// refusal from — even though the call reverts. -#[test] -fn test_keyless_deploy_contract_already_exists() { - let db = system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - for gas_limit in GAS_LIMITS { - let outcome = submit(db.clone(), CREATE2_FACTORY_TX, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists, "at {gas_limit}"); - assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 0); - assert!( - outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT), - "the occupancy read is in the witness, at {gas_limit}", - ); - } -} - /// A second deployment of the same transaction finds its address taken. #[test] fn test_keyless_deploy_twice_fails_second_time() { @@ -910,18 +634,6 @@ fn test_keyless_deploy_twice_fails_second_time() { } } -/// Rule 6: the signer funds the transaction's value, and nothing else. A signer with nothing is -/// refused a deployment that carries a value. -#[test] -fn test_keyless_deploy_insufficient_balance_zero() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// A signer holding part of the value is refused too, and the refusal writes nothing. #[test] fn test_keyless_deploy_insufficient_balance_partial() { @@ -934,133 +646,6 @@ fn test_keyless_deploy_insufficient_balance_partial() { } } -/// A signer holding exactly the value deploys, and the value moves to the contract. -#[test] -fn test_keyless_deploy_balance_exactly_sufficient() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(10)); - let outcome = - submit(db_for(&deployment, U256::from(10)), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); - assert_eq!(balance(deployment.signer), Some(U256::ZERO)); - assert_eq!(balance(deployment.address), Some(U256::from(10))); - } -} - -/// A deployment pays no gas out of the signer's balance: a signer with nothing deploys a -/// deployment that carries no value, whatever gas price it was signed at. -#[test] -fn test_a_signer_with_nothing_deploys_what_carries_no_value() { - let deployment = small(); - for gas_limit in GAS_LIMITS { - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); - assert_eq!( - outcome.state.get(&deployment.signer).map(|account| account.info.balance), - Some(U256::ZERO), - ); - } -} - -/// Rule 7: a call that cannot pay the overhead runs out of gas at once, before any rule reads the -/// state: the signer is untouched. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself, -/// and the reservoir pays the state charges, so no gas limit leaves the call this little. -#[test] -fn test_a_call_below_the_overhead_reads_nothing() { - let deployment = small(); - let reference = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]); - let intrinsic = reference.result.gas().total_gas_spent(); - let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS - 1; - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); - assert_eq!(outcome.result.gas().tx_gas_used(), gas_limit); - assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); -} - -/// A call that cannot pay for the signer's account runs out of gas before the creation starts: -/// no nonce is bumped and nothing is deployed. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself, -/// and the reservoir pays the state charges, so no gas limit leaves the call this little. -#[test] -fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { - // An account that costs nothing is one any call can pay for. - if state_is_free() { - return; - } - let deployment = small(); - let reference = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]); - let intrinsic = reference.result.gas().total_gas_spent(); - // One short of the account, once the overhead is paid. - let short = entry(GasId::new_account_state_gas()) - 1; - let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS + short; - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); - assert_nothing_written(&outcome, &deployment, 0); - assert_eq!(outcome.gas.state, 0, "the halt takes the charges back"); -} - -/// A call refused after it paid for the creation's start — the forward capped below the signed -/// gas limit — keeps none of its state and history: no account was added, so neither the signer's -/// account nor the created one is charged, the refusal writes nothing, and no record is kept. The -/// regular gas the `CREATE` opcode charged stays spent, as the overhead does. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself -/// and the reservoir pays the call's state and history charges, so no gas limit leaves the -/// call this little. The refusal above the cap is -/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. -#[test] -fn test_a_call_refused_after_its_charges_keeps_their_regular_gas_alone() { - // An account that costs nothing takes nothing from the forward. - if state_is_free() { - return; - } - let signed = signed_above_the_account(); - let deployment = Deployment::signed(0, signed, U256::ZERO, deploying(&runtime(1))); - // Enough for everything but the signer's account, which the empty signer adds. - let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), signed); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(refusal(&outcome), KeylessDeployError::GasLimitTooLow { .. })); - let [total, regular, state, history_gas, _] = - beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); - let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(one_byte_init_len()); - assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); - assert_nothing_written(&outcome, &deployment, 0); -} - -/// The signer's account is charged exactly when its nonce is spent: a refused call does neither, -/// a deployment that fails at run time does both. -/// -/// The refusal runs below the execution cap, as the refusals above; the failure runs at both. -#[test] -fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { - let signed = signed_above_the_account(); - let deployment = - Deployment::signed(0, signed, U256::ZERO, Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - // An account that costs nothing takes nothing from the forward, and refuses nothing. - if !state_is_free() { - let refused = submit( - system_db(), - &deployment.tx, - LARGE_OVERRIDE, - gas_limit_forwarding(&deployment, 3, signed), - ); - assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); - assert_eq!(nonce(&refused, deployment.signer), 0); - assert_eq!(refused.gas.state, 0); - } - - for gas_limit in GAS_LIMITS { - let failed = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(failure(&failed), KeylessDeployError::ExecutionReverted { .. })); - assert_eq!(nonce(&failed, deployment.signer), 1); - assert_eq!(failed.gas.state, entry(GasId::new_account_state_gas())); - } -} - /// A database read a rule needs fails the transaction with the database's error: the deploy /// address's, whose occupancy rule 5 reads. #[test] From 168ed249e893ebd5113fb0609e93145a26189949 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 19:09:43 +0800 Subject: [PATCH 133/190] test(keyless): remove deployment tests duplicated by the conformance suite A keyless deployment's outcomes, its constructor's effects and logs, a collision, a carried value and the unspent forward are pinned by Mega EEST's cases. --- .../mega-evm/tests/system/keyless/deploy.rs | 380 +----------------- .../mega-evm/tests/system/keyless/limits.rs | 41 +- 2 files changed, 3 insertions(+), 418 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 8a40f0f8b..66da768b2 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -20,9 +20,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, GASPRICE, INVALID, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, - ORIGIN, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, SHR, SSTORE, - STATICCALL, + CALL, CREATE, DELEGATECALL, GAS, JUMP, JUMPDEST, LOG0, MLOAD, ORIGIN, POP, PUSH0, REVERT, + SELFDESTRUCT, SSTORE, STATICCALL, }, context::BlockEnv, primitives::KECCAK_EMPTY, @@ -30,7 +29,6 @@ use revm::{ }; use super::*; -use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); @@ -78,20 +76,6 @@ fn test_keyless_deploy_eip1820() { } } -/// A deployment lands at the signer's first creation address, whoever the signer is, and the -/// deployed code is the runtime the init code returned. -#[test] -fn test_the_deploy_address_is_the_signers_first_creation_address() { - for gas_limit in GAS_LIMITS { - for len in [1, 2, 3] { - let deployment = Deployment::new(deploying(&runtime(len))); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.signer.create(0)); - assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&runtime(len)))); - } - } -} - /// The hash of `code`. fn keccak(code: &[u8]) -> B256 { alloy_primitives::keccak256(code) @@ -112,24 +96,6 @@ fn test_a_deployment_survives_a_commit() { } } -/// Init code that reverts: the call succeeds and reports `ExecutionReverted` with the revert -/// data, the deployment writes no code, and the signer's nonce is spent. -#[test] -fn test_keyless_deploy_execution_reverted() { - let deployment = - Deployment::new(BytecodeBuilder::default().revert_with_data([0xc0, 0xff, 0xee]).build()); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let KeylessDeployError::ExecutionReverted { gas_used, output } = failure(&outcome) else { - panic!("expected ExecutionReverted: {:?}", outcome.result); - }; - assert_eq!(output, Bytes::from_static(&[0xc0, 0xff, 0xee])); - assert_eq!(gas_used, returned(&outcome).gasUsed); - assert_eq!(nonce(&outcome, deployment.signer), 1); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - } -} - /// What the creation of a keyless deployment returned into its call: its regular gas and its /// reservoir once revm's settlement of the result, which runs after the inspector sees the /// creation end, rolled a failure's state and history gas back. @@ -203,26 +169,6 @@ fn test_a_reverting_constructor_returns_its_slot_as_reservoir_and_reports_its_re } } -/// Init code that hits an invalid opcode: `ExecutionHalted`, and the halt spends the whole -/// forward. -#[test] -fn test_keyless_deploy_execution_halted_invalid_opcode() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(Bytes::from_static(&[INVALID])); - let outcome = run_with( - system_db(), - deployment.call_data(2_000_000), - gas_limit, - EvmTxRuntimeLimits::no_limits(), - ); - let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { - panic!("expected ExecutionHalted: {:?}", outcome.result); - }; - assert_eq!(gas_used, 2_000_000, "a halt spends what it was forwarded"); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - /// A constructor that runs out of gas halts the same way, below and above the execution cap, /// and spends its whole forward in both. #[test] @@ -242,48 +188,6 @@ fn test_a_constructor_out_of_gas_is_execution_halted() { } } -/// A halted deployment is paid for, and its nonce is spent: the transaction spends the overhead, -/// the `CREATE` opcode's regular gas, the signer's account and its nonce record, and the whole -/// forward. -#[test] -fn test_a_halted_deployment_is_paid_for_and_spends_the_nonce() { - let deployment = Deployment::new(Bytes::from_static(&[INVALID])); - for gas_limit in GAS_LIMITS { - let data = deployment.call_data(SIGNED_GAS_LIMIT); - let outcome = - run_with(system_db(), data.clone(), gas_limit, EvmTxRuntimeLimits::no_limits()); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); - assert_eq!(nonce(&outcome, deployment.signer), 1); - let [total, ..] = beyond(&outcome, &reference(data, gas_limit)); - let new_account = entry(GasId::new_account_state_gas()); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(1) + - new_account + - record() + - SIGNED_GAS_LIMIT, - "at {gas_limit}", - ); - } -} - -/// Init code that returns nothing deploys no code: `EmptyCodeDeployed`, and the nonce is spent. -#[test] -fn test_keyless_deploy_empty_initcode() { - for gas_limit in GAS_LIMITS { - for init_code in [Bytes::new(), Bytes::from_static(&[PUSH0, PUSH0, RETURN])] { - let deployment = Deployment::new(init_code); - let outcome = deploy(system_db(), &deployment, gas_limit); - let KeylessDeployError::EmptyCodeDeployed { gas_used } = failure(&outcome) else { - panic!("expected EmptyCodeDeployed: {:?}", outcome.result); - }; - assert_eq!(gas_used, returned(&outcome).gasUsed); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } - } -} - /// A deployment whose initcode returns empty code at the deploy address is refused: the creation /// reverts, the call answers `EmptyCodeDeployed`, and the deploy address keeps no account, so the /// signed bytes can still be deployed. The initcode returns empty code when it has more than @@ -333,55 +237,6 @@ fn test_an_empty_code_deployment_leaves_the_address_deployable() { } } -/// A deploy address at nonce 1 without code — what a Rex6 deployment whose creation returned -/// empty code left — passes the occupancy rule, which reads the code alone, and the creation -/// collides there before its init code runs: whatever the init code would do, the call answers -/// `ExecutionHalted` with the whole forward spent, the address keeps its nonce and no code, and the -/// signer's bump from 0 stands. -#[test] -fn test_a_deploy_address_with_a_nonce_and_no_code_collides() { - let init_codes = - [deploying(&runtime(1)), Bytes::new(), Bytes::from_static(&[INVALID]), logging(32)]; - for init_code in init_codes { - let deployment = Deployment::new(init_code); - let db = system_db().account_nonce(deployment.address, 1); - for gas_limit in GAS_LIMITS { - for forward in [SIGNED_GAS_LIMIT, 2 * SIGNED_GAS_LIMIT] { - let outcome = run_with( - db.clone(), - deployment.call_data(forward), - gas_limit, - EvmTxRuntimeLimits::no_limits(), - ); - let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { - panic!("expected ExecutionHalted: {:?}", outcome.result); - }; - assert_eq!(gas_used, forward, "a collision spends the forward, at {gas_limit}"); - assert_eq!(nonce(&outcome, deployment.signer), 1, "the bump from 0 stands"); - assert_eq!(nonce(&outcome, deployment.address), 1, "the address keeps its nonce"); - assert_eq!(code_hash(&outcome, deployment.address), Some(KECCAK_EMPTY)); - assert!(outcome.result.logs().is_empty(), "the init code never ran"); - } - } - } -} - -/// An empty deposit is refused at the deploy address alone: a constructor's own `CREATE` that -/// returns empty code is admitted, and the deployment around it succeeds. -#[test] -fn test_a_constructors_own_creation_may_return_empty_code() { - for gas_limit in GAS_LIMITS { - // CREATE of empty init code, then the deployment's own runtime. - let prefix = [PUSH0, PUSH0, PUSH0, CREATE, POP]; - let deployment = Deployment::new(constructor(&prefix, &runtime(1))); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); - let inner = deployment.address.create(1); - assert_eq!(nonce(&outcome, inner), 1, "the inner creation stands, with no code"); - assert_eq!(code_hash(&outcome, inner), Some(KECCAK_EMPTY)); - } -} - /// Init code that destroys its own account: the value it held goes to the beneficiary, no code /// is left, and the call reports `EmptyCodeDeployed`. #[test] @@ -476,17 +331,6 @@ fn test_a_constructor_destroyed_through_delegatecall_deploys_no_code() { } } -/// Code starting with `0xEF` is refused by the creation (EIP-3541): `ExecutionHalted`. -#[test] -fn test_code_starting_with_ef_is_refused() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(deploying(&[0xef, 0x00])); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - } -} - /// Code over the contract size limit is refused by the creation (EIP-170): `ExecutionHalted`. #[test] fn test_code_over_the_size_limit_is_refused() { @@ -501,19 +345,6 @@ fn test_code_over_the_size_limit_is_refused() { } } -/// A deployment carrying a value moves it from the signer to the contract. -#[test] -fn test_keyless_deploy_with_value_transfer() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); - let outcome = deploy(db_for(&deployment, U256::from(10_000)), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); - assert_eq!(balance(deployment.address), Some(U256::from(7_777))); - assert_eq!(balance(deployment.signer), Some(U256::from(2_223))); - } -} - /// A constructor that writes another contract's storage: the write is kept. #[test] fn test_keyless_deploy_modifies_other_contract_state() { @@ -632,82 +463,6 @@ fn test_keyless_deploy_reads_existing_contract() { } } -/// A constructor that writes storage and then reverts leaves neither the storage nor code, and -/// the call still reports the revert with a gas figure. -#[test] -fn test_failed_initcode_keeps_no_storage() { - let init_code = - BytecodeBuilder::default().sstore(U256::from(1), U256::from(7)).revert().build(); - let deployment = Deployment::new(init_code); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { - panic!("expected ExecutionReverted: {:?}", outcome.result); - }; - assert!(gas_used > 0); - let kept = outcome - .state - .get(&deployment.address) - .and_then(|account| account.storage.get(&U256::from(1)).map(|slot| slot.present_value)); - assert!(kept.is_none_or(|value| value.is_zero()), "at {gas_limit}"); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); - } -} - -/// A constructor's log is the transaction's: it is in the receipt, emitted by the deployed -/// address. -#[test] -fn test_keyless_deploy_emits_logs() { - for gas_limit in GAS_LIMITS { - let prefix = BytecodeBuilder::default() - .mstore(0, B256::repeat_byte(0xab)) - .push_number(32_u64) - .push_number(0_u64) - .append(LOG0); - let deployment = Deployment::new(running(prefix)); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let logs = outcome.result.logs(); - assert_eq!(logs.len(), 1); - assert_eq!(logs[0].address, deployment.address); - assert_eq!(logs[0].data.data, Bytes::from(B256::repeat_byte(0xab).to_vec())); - } -} - -/// Init code that logs and deploys nothing keeps no log: the call reports `EmptyCodeDeployed`, and -/// the creation, refused its empty deposit, reverted with its log. -#[test] -fn test_an_empty_code_deployment_keeps_no_log() { - for gas_limit in GAS_LIMITS { - let topic = B256::repeat_byte(0x11); - let init_code = BytecodeBuilder::default() - .mstore(0, [0xde, 0xad, 0xbe, 0xef]) - .push_bytes(topic) - .push_number(4_u64) - .push_number(0_u64) - .append(LOG1) - .return_empty() - .build(); - let deployment = Deployment::new(init_code); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); - assert!(outcome.result.logs().is_empty()); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - -/// And init code that logs nothing leaves none. -#[test] -fn test_an_empty_code_deployment_adds_no_log() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(BytecodeBuilder::default().return_empty().build()); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); - assert!(outcome.result.logs().is_empty()); - } -} - /// A deployment that fails keeps no log: the creation's revert takes its logs with it. #[test] fn test_a_failed_deployment_keeps_no_log() { @@ -733,34 +488,6 @@ fn priced_tx(deployment: &Deployment, gas_limit: u64, gas_price: u128) -> MegaTr tx } -/// `ORIGIN` and `GASPRICE` in the init code are the transaction's own: the relayer, and the gas -/// price the relayer pays — not the signer, and not the price the deployment was signed at. -#[test] -fn test_origin_and_gasprice_follow_the_outer_transaction() { - let prefix = BytecodeBuilder::default() - .append(ORIGIN) - .push_number(0_u64) - .append(SSTORE) - .append(GASPRICE) - .push_number(1_u64) - .append(SSTORE); - let deployment = Deployment::new(running(prefix)); - for gas_limit in GAS_LIMITS { - let outcome = MegaEvm::new(context(system_db())) - .execute_transaction(priced_tx(&deployment, gas_limit, 7)) - .expect("a valid transaction"); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let slot = |key: u64| { - outcome.state[&deployment.address] - .storage - .get(&U256::from(key)) - .map(|s| s.present_value) - }; - assert_eq!(slot(0), Some(U256::from_be_slice(RELAYER.as_slice())), "ORIGIN"); - assert_eq!(slot(1), Some(U256::from(7)), "GASPRICE"); - } -} - /// The block's beneficiary is paid for the whole transaction, deployment included, whether the /// deployment succeeds or fails, and the signer pays nothing. fn assert_beneficiary_paid(init_code: Bytes) { @@ -781,115 +508,12 @@ fn assert_beneficiary_paid(init_code: Bytes) { ); } -/// The beneficiary is paid for a deployment that succeeds. -#[test] -fn test_beneficiary_receives_fees_on_success() { - assert_beneficiary_paid(deploying(&runtime(1))); -} - /// And for one that fails. #[test] fn test_beneficiary_receives_fees_on_execution_failure() { assert_beneficiary_paid(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); } -/// A contract's `keylessDeploy` call is not dispatched: it runs the method body, which reverts -/// with `NotIntercepted()`, and nothing is deployed. -#[test] -fn test_keyless_deploy_not_intercepted_for_inner_calls() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(deploying(&runtime(1))); - let code = - calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &deployment.call_data(LARGE_OVERRIDE), 0); - let mut tx = call_tx(CONTRACT, [], U256::ZERO); - tx.0.base.gas_limit = gas_limit; - let outcome = MegaEvm::new(context(with_contract(code))) - .execute_transaction(tx) - .expect("a valid transaction"); - let output = outcome.result.output().cloned().unwrap_or_default(); - let (status, returned) = split_outcome(&output); - assert!(!status); - assert_eq!(returned, IKeylessDeploy::NotIntercepted::SELECTOR); - assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); - assert!(!outcome.state.contains_key(&deployment.address)); - } -} - -/// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: -/// not dispatched. The contract's bytecode runs and reverts with `NotIntercepted()`, which the -/// outer constructor stores, and nothing of the inner deployment happens: its address holds no -/// code and its signer's nonce is unspent. The outer deployment deploys. -/// -/// A call answered without the bytecode — refused by an interceptor, or run as a deployment that -/// fails — could fail the same way, but not with the four bytes of `NotIntercepted()`. -/// -/// Expected values `independent`: the error's selector is computed here from its -/// signature, `NotIntercepted()`, not taken from the contract's binding. -#[test] -fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { - let not_intercepted = &alloy_primitives::keccak256("NotIntercepted()")[..4]; - let selector = U256::from_be_slice(not_intercepted); - for gas_limit in GAS_LIMITS { - let inner = Deployment::new(deploying(&[0x00, 0x00])); - let data = inner.call_data(LARGE_OVERRIDE); - // The inner call's status in slot 0, the size of its revert data in slot 2, and the first - // four bytes of that data, as a number, in slot 1. - let prefix = BytecodeBuilder::default() - .mstore(0, &data) - .push_number(0_u64) - .push_number(0_u64) - .push_number(data.len() as u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(KEYLESS_DEPLOY_ADDRESS) - .append(GAS) - .append(CALL) - .push_number(0_u64) - .append(SSTORE) - .append(RETURNDATASIZE) - .push_number(2_u64) - .append(SSTORE) - .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, PUSH0, MLOAD]) - .push_number(224_u64) - .append(SHR) - .push_number(1_u64) - .append(SSTORE); - let outer = Deployment::new(running(prefix)); - let outcome = deploy(system_db(), &outer, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, outer.address); - let slot = |index: u64| { - outcome.state[&outer.address] - .storage - .get(&U256::from(index)) - .map(|slot| slot.present_value) - }; - assert_eq!(slot(0), Some(U256::ZERO), "the inner call failed"); - assert_eq!(slot(2), Some(U256::from(4)), "with four bytes of revert data"); - assert_eq!(slot(1), Some(selector), "which are NotIntercepted(): the bytecode ran"); - assert!(code_hash(&outcome, inner.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - assert_eq!(nonce(&outcome, inner.signer), 0); - } -} - -/// A constructor's storage writes are priced by the SALT environment the transaction runs in: a -/// crowded bucket at the deploy address makes the deposited code cost more state gas, and the -/// creation's `gasUsed` grows by exactly that. -#[test] -fn test_a_deployment_is_priced_by_the_transactions_salt_env() { - let deployment = Deployment::new(deploying(&runtime(5))); - let deposit = satin_gas_params().code_deposit_state_gas(5); - for gas_limit in GAS_LIMITS { - let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); - let envs = crowded(TestExternalEnvs::new(), deployment.address, 3); - let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); - assert_eq!( - returned(&crowded_run).gasUsed - returned(&minimal).gasUsed, - 2 * deposit, - "at {gas_limit}", - ); - } -} - /// A constructor that sends an Oracle hint reaches the node's oracle service: the creation runs /// in the transaction's own environment. #[test] diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index dd02e16f0..05be35361 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -24,7 +24,7 @@ use mega_evm::{ LimitCheck, LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, GAS, POP, PUSH0, REVERT, TIMESTAMP}, + bytecode::opcode::{CALL, GAS, POP, PUSH0, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, InstructionResult, @@ -407,45 +407,6 @@ fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { ); } -/// The call gets back what its creation did not spend, the same way whether the creation -/// succeeds or reverts: the transaction spends the overhead, the `CREATE` opcode's regular gas, -/// what the call kept of the creation's start, and the creation's `gasUsed`, and nothing else, -/// below and above the execution cap. -#[test] -fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { - let succeeding = Deployment::new(deploying(&runtime(1))); - let reverting = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let new_account = entry(GasId::new_account_state_gas()); - for gas_limit in GAS_LIMITS { - let success = limited(&succeeding, gas_limit, EvmTxRuntimeLimits::no_limits()); - let [total, ..] = - beyond(&success, &reference(succeeding.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(deploying(&runtime(1)).len()) + - new_account + - entry(GasId::create_state_gas()) + - 2 * record() + - returned(&success).gasUsed, - "success at {gas_limit}", - ); - - let revert = limited(&reverting, gas_limit, EvmTxRuntimeLimits::no_limits()); - let [total, ..] = - beyond(&revert, &reference(reverting.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(3) + - new_account + - record() + - returned(&revert).gasUsed, - "revert at {gas_limit}", - ); - } -} - /* ---------- the stop, as a column of the matrix ---------- */ /// A limit a deployment's creation crosses. From 3936ed977aaadf7fc9e3d79906b794fbb0ec7995 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 19:11:10 +0800 Subject: [PATCH 134/190] test(keyless): remove charge and dispatch tests duplicated by the conformance suite A keyless deployment's upfront charges, their buckets and refunds, and which calls the dispatch takes are pinned by Mega EEST's cases. --- .../mega-evm/tests/system/keyless/charges.rs | 132 ----------- .../mega-evm/tests/system/keyless/dispatch.rs | 220 +----------------- 2 files changed, 5 insertions(+), 347 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index cd59e8459..e0e4402e1 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -103,76 +103,6 @@ fn test_the_call_pays_the_legacy_shares_of_the_accounts_it_creates() { } } -/// The created account is charged only when the deploy address is empty, as the `CREATE` opcode -/// charges it: an address that already holds a balance is an account already, the deployment -/// lands on it, and the balance stays. -#[test] -fn test_the_created_account_is_charged_only_when_the_address_is_empty() { - let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); - for gas_limit in GAS_LIMITS { - let empty = deploy(system_db(), &deployment, gas_limit); - let held = system_db().account_balance(deployment.address, U256::from(7_777)); - let held = deploy(held, &deployment, gas_limit); - assert_eq!(returned(&held).deployedAddress, deployment.address); - assert_eq!( - held.state.get(&deployment.address).map(|account| account.info.balance), - Some(U256::from(7_777)), - ); - let [total, regular, state, history_gas, _] = beyond(&empty, &held); - let created = entry(GasId::create_state_gas()); - assert_eq!([total, regular, state, history_gas], [created, 0, created, 0]); - } -} - -/// A refused call keeps the overhead and nothing else: every charge made after it is taken back -/// with the revert, whatever the pools. -#[test] -fn test_a_refused_call_keeps_the_overhead_alone() { - // A value the signer cannot fund: refused at the last rule, after every read. - let deployment = Deployment::with_value(deploying(&runtime(RUNTIME_LEN)), U256::from(1)); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); - assert_eq!( - [total, regular, state, history_gas, history_bytes], - [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0, 0], - "at {gas_limit}", - ); - assert_eq!(outcome.usage.write_records, 0); - } -} - -/// A deployment whose init code reverts gives the created account's charge back, and the record -/// of the account it did not create; the signer's account and its nonce record stay, because the -/// nonce stays spent. -#[test] -fn test_a_failed_deployment_gives_the_created_account_back() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let error = failure(&outcome); - let KeylessDeployError::ExecutionReverted { gas_used, .. } = error else { - panic!("expected ExecutionReverted, got {error:?}"); - }; - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); - let new_account = entry(GasId::new_account_state_gas()); - assert_eq!(state, new_account, "at {gas_limit}"); - assert_eq!(history_gas, record(), "at {gas_limit}"); - assert_eq!(history_bytes, 40, "at {gas_limit}"); - assert_eq!( - regular, - KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(3) + gas_used, - "at {gas_limit}" - ); - assert_eq!(total, regular + state + history_gas); - assert_eq!(nonce(&outcome, deployment.signer), 1, "the nonce stays spent"); - assert_eq!(outcome.usage.write_records, 1, "the signer's nonce"); - } -} - /// The call pays the regular gas the `CREATE` opcode charges its frame on top of the overhead, /// whatever the pools: the schedule's `create` entry, 12,000, and EIP-3860's 2 gas per word of /// init code, 65,536 for init code of the maximum size. Init code of zero bytes stops at once and @@ -206,68 +136,6 @@ fn test_the_call_pays_the_create_opcodes_regular_gas() { } } -/// `gasUsed` is what the creation spent before refunds: a constructor that fills a slot and -/// clears it again earns a refund, which is the transaction's, as any frame's is. The charges add -/// up to the transaction's spend before its refund, and the receipt's gas is that spend less the -/// refund. -#[test] -fn test_gas_used_counts_the_creations_spend_before_its_refund() { - let prefix = mega_evm::test_utils::BytecodeBuilder::default() - .sstore(U256::ZERO, U256::ONE) - .sstore(U256::ZERO, U256::ZERO) - .build_vec(); - let init_code = constructor(&prefix, &runtime(1)); - let opcode = create_regular(init_code.len()); - let deployment = Deployment::new(init_code); - let upfront = - entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()) + 2 * record(); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let gas_used = returned(&outcome).gasUsed; - let refund = outcome.result.gas().inner_refunded(); - assert!(refund > 0, "the constructor earns a refund at {gas_limit}"); - let [total, ..] = - beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + opcode + upfront + gas_used, - "at {gas_limit}" - ); - assert_eq!( - outcome.result.gas().tx_gas_used(), - outcome.result.gas().total_gas_spent() - refund, - "at {gas_limit}", - ); - } -} - -/// Both upfront charges are priced by the SALT bucket they land in — the signer's account in the -/// signer's, the created account in the deploy address's — and regular gas does not move with it. -#[test] -fn test_the_upfront_charges_scale_with_their_buckets() { - let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); - let new_account = entry(GasId::new_account_state_gas()); - let created = entry(GasId::create_state_gas()); - for gas_limit in GAS_LIMITS { - let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); - for (m_signer, m_address) in [(2, 1), (1, 2), (3, 2)] { - let envs = crowded( - crowded(TestExternalEnvs::new(), deployment.signer, m_signer), - deployment.address, - m_address, - ); - let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); - assert_eq!(crowded_run.gas.regular, minimal.gas.regular, "m does not touch regular"); - assert_eq!( - crowded_run.gas.state - minimal.gas.state, - (m_signer - 1) * new_account + - (m_address - 1) * (created + satin_gas_params().code_deposit_state_gas(5)), - "signer at m = {m_signer}, address at m = {m_address}, gas limit {gas_limit}", - ); - } - } -} - /// A deployment that fails gives the created account back at the price it was charged, however /// crowded the deploy address's bucket, and the bucket is read once for both; the signer's /// account is kept at its own bucket's price. diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index 40a8eecab..ccfcb1a2e 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -7,32 +7,15 @@ //! overhead alone. use alloy_primitives::{Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - system::keyless::{ - IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, - }, - EvmTxRuntimeLimits, -}; -use revm::{ - bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, - context::result::ExecutionResult, -}; - -use super::{beyond, reference, refusal, run_with, GAS_LIMITS}; -use crate::common::{ - body_history, call_tx, calls_with, output, revert_data, run, split_outcome, system_db, - with_contract, CONTRACT, GAS_LIMIT, +use alloy_sol_types::SolCall; +use mega_evm::system::keyless::{ + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, }; +use revm::context::result::ExecutionResult; -/// No runtime limit. -fn no_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits::no_limits() -} +use crate::common::{body_history, call_tx, revert_data, run, system_db}; const KEYLESS_DEPLOY: [u8; 4] = IKeylessDeploy::keylessDeployCall::SELECTOR; -const NOT_INTERCEPTED: [u8; 4] = IKeylessDeploy::NotIntercepted::SELECTOR; -const NO_ETHER_TRANSFER: [u8; 4] = IKeylessDeploy::NoEtherTransfer::SELECTOR; /// The calldata of a `keylessDeploy` call carrying `transaction` bytes. fn keyless_deploy(transaction: &[u8]) -> Bytes { @@ -53,66 +36,6 @@ fn unknown_selector(data: &Bytes) -> Bytes { Bytes::from(data) } -/// A dispatched `keylessDeploy` transaction pays the fixed overhead, then is refused by the -/// rules: bytes that do not decode as a signed transaction are `MalformedEncoding()`. The -/// deployed bytecode does not run, and the overhead is all the refusal keeps. -#[test] -fn test_a_keyless_deploy_transaction_pays_the_overhead() { - let data = keyless_deploy(b"a transaction"); - for gas_limit in GAS_LIMITS { - let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); - assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); - let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); - assert_eq!([total, regular], [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], "at {gas_limit}"); - } -} - -/// A call that carries value is refused with the ABI's own `NoEtherTransfer()`, and the -/// overhead is charged all the same. -#[test] -fn test_a_value_bearing_call_is_refused() { - let data = keyless_deploy(b"a transaction"); - let code = calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &data, 1); - let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - let outcome = output(&result); - let (status, returned) = split_outcome(&outcome); - - // A call from a contract is at depth 1, where nothing is dispatched: the bytecode runs and - // refuses the value itself, with the empty revert data of a non-payable method. - assert!(!status); - assert!(returned.is_empty(), "the bytecode refuses the value before it reaches the method"); - - // The transaction itself is at depth 0, where the dispatch refuses it. - let result = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::from(1))); - assert_eq!(revert_data(&result), Bytes::from_static(&NO_ETHER_TRANSFER)); - assert!( - result.result.gas().total_gas_spent() > KEYLESS_DEPLOY_OVERHEAD_GAS, - "the refusal keeps the overhead", - ); -} - -/// A call a contract makes is not dispatched, whatever its selector: only a transaction -/// deploys. The deployed bytecode runs and reverts with `NotIntercepted()`, and no overhead is -/// charged. -#[test] -fn test_a_call_from_a_contract_is_not_dispatched() { - let data = keyless_deploy(b"a transaction"); - for scheme in [CALL, STATICCALL, CALLCODE, DELEGATECALL] { - let code = calls_with(scheme, KEYLESS_DEPLOY_ADDRESS, &data, 0); - let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - let outcome = output(&result); - let (status, returned) = split_outcome(&outcome); - assert!(!status, "scheme {scheme:#x}"); - assert_eq!(returned, NOT_INTERCEPTED, "scheme {scheme:#x}"); - // The transaction's body is its only history: what it spent beside it is less than the - // overhead. - assert!( - result.result.gas().total_gas_spent() - body_history(0) < KEYLESS_DEPLOY_OVERHEAD_GAS, - "scheme {scheme:#x} paid the overhead of a dispatch that did not happen", - ); - } -} - /// A selector the contract does not know, and an input too short to hold one, are not /// dispatched: the bytecode runs and reverts on its own, with empty data. /// @@ -161,139 +84,6 @@ fn test_a_call_that_cannot_pay_the_overhead_runs_out_of_gas() { assert_eq!(result.result.tx_gas_used(), gas_limit, "an out-of-gas frame spends what it had",); } -/// The overhead is fixed: an empty deployment transaction is charged the same as one with a -/// payload. -#[test] -fn test_the_overhead_does_not_depend_on_the_payload() { - for payload in [&b""[..], &[0xab; 512]] { - let data = keyless_deploy(payload); - let dispatched = run_with(system_db(), data.clone(), GAS_LIMIT, no_limits()); - assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); - let [total, ..] = beyond(&dispatched, &reference(data, GAS_LIMIT)); - assert_eq!(total, KEYLESS_DEPLOY_OVERHEAD_GAS, "a payload of {} bytes", payload.len()); - } -} - -/// A call is recognised only once its arguments decode as `(bytes, uint256)`: a payload too short -/// to hold them, an offset that points past the data, and a length that runs past it are not -/// dispatched. The deployed bytecode runs and its decoder reverts with empty data, and the -/// overhead is not charged. -#[test] -fn test_arguments_that_do_not_decode_are_not_dispatched() { - let selector = KEYLESS_DEPLOY.to_vec(); - let word = |value: u64| U256::from(value).to_be_bytes::<32>().to_vec(); - let well_formed = keyless_deploy(b"a transaction").to_vec(); - - let mut offset_past_the_data = selector.clone(); - offset_past_the_data.extend(word(0x1000)); - offset_past_the_data.extend(word(1_000_000)); - let mut length_past_the_data = selector.clone(); - length_past_the_data.extend(word(0x40)); - length_past_the_data.extend(word(1_000_000)); - length_past_the_data.extend(word(32)); - let cases = [ - ("short", [selector.clone(), vec![0_u8; 16]].concat()), - ("selector alone", selector), - ("offset past the data", offset_past_the_data), - ("length past the data", length_past_the_data), - ("cut inside the bytes", well_formed[..well_formed.len() - 40].to_vec()), - ]; - for (name, input) in cases { - let data = Bytes::from(input); - for gas_limit in GAS_LIMITS { - let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); - let ExecutionResult::Revert { output, .. } = &outcome.result else { - panic!("{name}: the bytecode did not revert: {:?}", outcome.result); - }; - assert!(output.is_empty(), "{name}: the bytecode's decoder reverts with empty data"); - let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); - assert!( - total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, - "{name} at {gas_limit}: paid {total} beyond a plain call, an overhead it does not \ - owe", - ); - } - } -} - -/// Bytes after a valid encoding do not prevent the recognition: the call is dispatched and pays -/// the overhead, and the deployment rejects what the first argument carries. -#[test] -fn test_bytes_after_a_valid_encoding_are_still_dispatched() { - let mut data = keyless_deploy(b"a transaction").to_vec(); - data.extend([0xab; 5]); - let data = Bytes::from(data); - let dispatched = run_with(system_db(), data.clone(), GAS_LIMIT, no_limits()); - assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); - let [total, ..] = beyond(&dispatched, &reference(data, GAS_LIMIT)); - assert_eq!(total, KEYLESS_DEPLOY_OVERHEAD_GAS); -} - -/// The calldata of a `keylessDeploy` call: the selector and `words` as 32-byte words, then -/// `tail` as it is. -fn raw_call(words: &[u64], tail: &[u8]) -> Bytes { - let mut data = KEYLESS_DEPLOY.to_vec(); - for word in words { - data.extend(U256::from(*word).to_be_bytes::<32>()); - } - data.extend(tail); - Bytes::from(data) -} - -/// A call is recognised exactly when the contract's own calldata decoder for `(bytes, uint256)` -/// accepts its arguments, and that decoder asks for no padding and no canonical offset: the -/// padding of the bytes' tail cut off, an offset that points at the head's second word, which is -/// then read as the length, and an offset of zero are all recognised. Each pays the overhead and -/// reaches the rule that refuses a payload that is no signed transaction. -#[test] -fn test_arguments_the_contracts_decoder_accepts_are_dispatched() { - let cases = [ - // offset 0x40, gas limit, length 5, five bytes and none of the 27 bytes of padding - ("the tail's padding cut off", raw_call(&[0x40, 1_000_000, 5], &[0xab; 5])), - // offset 0x20 points at the second head word (3), which is read as the length of the - // three bytes after the head - ("an offset at the second head word", raw_call(&[0x20, 3], &[0xab; 3])), - // offset zero points at the first head word (0), read as an empty payload - ("an offset of zero", raw_call(&[0, 1_000_000], &[])), - ]; - for (name, data) in cases { - for gas_limit in GAS_LIMITS { - let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); - assert_eq!( - refusal(&dispatched), - KeylessDeployError::MalformedEncoding, - "{name} at {gas_limit}", - ); - let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); - assert_eq!( - [total, regular], - [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], - "{name} at {gas_limit}: recognised, so the overhead is charged", - ); - } - } -} - -/// The first of those cases one byte short of the declared length is refused by the same -/// decoder: the call is not recognised, pays no overhead, and the bytecode reverts with empty -/// data. -#[test] -fn test_a_payload_one_byte_short_of_its_declared_length_is_not_dispatched() { - let data = raw_call(&[0x40, 1_000_000, 5], &[0xab; 4]); - for gas_limit in GAS_LIMITS { - let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); - let ExecutionResult::Revert { output, .. } = &outcome.result else { - panic!("the bytecode did not revert: {:?}", outcome.result); - }; - assert!(output.is_empty(), "the bytecode's decoder reverts with empty data"); - let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); - assert!( - total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, - "at {gas_limit}: paid {total} beyond a plain call, an overhead it does not owe", - ); - } -} - /// A call that carries value and whose arguments do not decode is not dispatched either: the /// bytecode runs and refuses the value itself, with the empty revert data of a non-payable /// method, and no overhead is charged. From 96bd50145bbd652e79543b6cfb809d4ffe4378b4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 135/190] test(limits): restore tests whose gas tier or halt reason no conformance case pins The initcode-size checks and the 1,001st fresh slot run above the execution cap, where Mega EEST's cases run below it, and the creation transaction past the code-size limit asserts a halt reason the conformance suite's adapter does not report. --- crates/mega-evm/tests/satin/contract_size.rs | 111 ++++++++++++++++++ .../tests/satin/limit_matrix/limits.rs | 15 +++ crates/mega-evm/tests/satin/main.rs | 1 + 3 files changed, 127 insertions(+) create mode 100644 crates/mega-evm/tests/satin/contract_size.rs diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs new file mode 100644 index 000000000..703e5420b --- /dev/null +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -0,0 +1,111 @@ +//! The code-size limits the Satin configuration raises. +//! +//! A deployed contract may hold 512 KiB, eight times more than EIP-7954's bound and twenty-one +//! times EIP-170's; an initcode may hold twice that, the ratio EIP-3860 sets between the two. +//! Both bounds are `CfgEnv` limits the spec fixes, so they apply to a creation transaction and to +//! a `CREATE` alike. + +use alloy_evm::{Evm, EvmError, InvalidTxError}; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, + test_utils::{right_pad_bytes, BytecodeBuilder, MemoryDatabase}, + MegaEvm, MegaHaltReason, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{PUSH1, RETURN, STOP}, + context::result::{ExecutionResult, HaltReason, InvalidTransaction}, +}; + +use crate::common::{context, create, history}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); + +/// Room for everything a creation here draws, all of it above the execution cap so it comes out of +/// the reservoir: the state gas of the largest deployable code, the history of that code and of a +/// body carrying twice the largest init code, and a billion more, at the byte prices in effect. +fn gas_limit() -> u64 { + TX_GAS_LIMIT_CAP + + MAX_CONTRACT_SIZE as u64 * + mega_evm::satin_gas_params() + .get(revm::context_interface::cfg::GasId::code_deposit_state_gas()) + + history((MAX_CONTRACT_SIZE + 2 * MAX_INITCODE_SIZE) as u64) + + 1_000_000_000 +} + +/// Runs `tx` from `CALLER` and returns its result, or the validation error that rejected it. +fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result, String> { + let mut evm = MegaEvm::new(context(db)); + match evm.transact_raw(tx) { + Ok(outcome) => Ok(outcome.result), + Err(err) => { + let invalid = err + .as_invalid_tx_err() + .and_then(InvalidTxError::as_invalid_tx_err) + .unwrap_or_else(|| panic!("unexpected error {err:?}")); + Err(format!("{invalid:?}")) + } + } +} + +/// Runs `init_code` as a creation transaction from `CALLER`. +fn deploy(init_code: Bytes) -> Result, String> { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + run(create(CALLER, init_code, gas_limit()), db) +} + +/// Init code of `size` bytes that does nothing. +fn initcode_of(size: usize) -> Bytes { + Bytes::from(vec![STOP; size]) +} + +/// Init code that returns `size` bytes of zeros as the deployed code. +fn constructor_returning(size: usize) -> Bytes { + let code = BytecodeBuilder::default() + .push_number(size as u64) + .append_many([PUSH1, 0x00]) + .append(RETURN) + .build_vec(); + right_pad_bytes(code, 32).into() +} + +fn assert_initcode_limit(result: Result, String>) { + let expected = format!("{:?}", InvalidTransaction::CreateInitCodeSizeLimit); + assert_eq!(result.expect_err("the transaction is rejected"), expected); +} + +fn assert_code_size_limit(result: Result, String>) { + let halt = result.expect("the transaction is valid"); + assert!( + matches!( + halt, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::CreateContractSizeLimit), + .. + } + ), + "{halt:?}" + ); +} + +/* ---------- the initcode bound ---------- */ + +/// The Satin bound itself is accepted. +#[test] +fn test_the_satin_initcode_size_is_accepted() { + assert!(deploy(initcode_of(MAX_INITCODE_SIZE)).unwrap().is_success()); +} + +/// One byte past it is rejected before the transaction runs. +#[test] +fn test_one_byte_past_the_satin_initcode_size_is_rejected() { + assert_initcode_limit(deploy(initcode_of(MAX_INITCODE_SIZE + 1))); +} + +/* ---------- the deployed-code bound, from a creation transaction ---------- */ + +/// One byte past it halts the creation. +#[test] +fn test_one_byte_past_the_satin_code_size_halts() { + assert_code_size_limit(deploy(constructor_returning(MAX_CONTRACT_SIZE + 1))); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/limits.rs b/crates/mega-evm/tests/satin/limit_matrix/limits.rs index 106d225d4..9aac9729a 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/limits.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/limits.rs @@ -26,6 +26,21 @@ fn join(prefix: Vec, rest: BytecodeBuilder) -> Bytes { 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. diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 231e1831a..2dd8f18ea 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -2,6 +2,7 @@ mod common; mod compute_gas; +mod contract_size; mod corpus; mod count_order; mod create_opcodes; From 6a2e2c6902022d30bc93fc643ee302ff0de016b2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 136/190] test(gas): restore the control the warm-access test is measured against The first STATICCALL to a precompile reads as warm only next to a first call that reads the cold surcharge; without it the remaining test passes for a measurement that sees no access at all. --- .../mega-evm/tests/satin/inherited_costs.rs | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/inherited_costs.rs b/crates/mega-evm/tests/satin/inherited_costs.rs index 3c6b3e18b..5e637884e 100644 --- a/crates/mega-evm/tests/satin/inherited_costs.rs +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -12,9 +12,15 @@ use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, MegaTransaction, }; -use revm::bytecode::opcode::{POP, PUSH0, STATICCALL, STOP}; +use revm::{ + bytecode::opcode::{CALL, POP, PUSH0, STATICCALL, STOP}, + context_interface::cfg::GasId, +}; -use crate::common::{call, execute}; +use crate::{ + common::{call, execute}, + salt::entry, +}; const CALLER: Address = address!("0000000000000000000000000000000000e20000"); const CONTRACT: Address = address!("0000000000000000000000000000000000e20001"); @@ -23,6 +29,12 @@ const EXISTING: Address = address!("0000000000000000000000000000000000e20002"); /// The identity precompile. const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); +/// What the first touch of an address costs over a warm one: the schedule's cold account access +/// less its warm read. +fn cold_over_warm() -> u64 { + entry(GasId::cold_account_additional_cost()) +} + /* ---------- preload-warm addresses ---------- */ /// `units` identical calls of `opcode` to `to`, each forwarding 50,000 and dropping its status. @@ -58,6 +70,13 @@ fn plain() -> MegaTransaction { call(CALLER, CONTRACT, U256::ZERO, 10_000_000 + crate::common::body_history(0)) } +/// The control the other cases are measured against: an address nothing preloads costs the cold +/// price on its first touch, so the measurement sees a cold touch where there is one. +#[test] +fn test_the_first_call_to_an_address_nothing_warmed_is_charged_cold() { + assert_eq!(first_call_over_second(CALL, EXISTING, plain), cold_over_warm() as i64); +} + /// So does the first `STATICCALL`. #[test] fn test_the_first_staticcall_to_a_precompile_is_charged_warm() { From c1567308d4c0292e87ec142ec20262c9644097b7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 137/190] test(salt): restore tests whose crowded-bucket arm no conformance case pins Each of these runs its scenario at a crowded SALT bucket on a path where Mega EEST has a case at the minimum bucket only. --- crates/mega-evm/tests/satin/salt.rs | 30 +++++ crates/mega-evm/tests/satin/salt_refund.rs | 140 ++++++++++++++++++++- 2 files changed, 167 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 463869dff..29bd03b74 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -880,6 +880,36 @@ fn test_a_transfer_to_an_account_that_exists_charges_no_state_gas() { ); } +/// A `SELFDESTRUCT` pays for a beneficiary's leaf only when it has a balance to move and the +/// beneficiary does not exist yet. Neither half alone adds state, so neither is charged, however +/// crowded the beneficiary's bucket is. +#[test] +fn test_a_selfdestruct_that_adds_no_account_charges_no_state_gas() { + const FUNDED: Address = address!("0000000000000000000000000000000000c00007"); + + assert_charges_no_state_gas( + "a SELFDESTRUCT with nothing to move", + |envs, m| crowded_account(envs, EMPTY, m), + || { + // The contract holds no balance, so the beneficiary receives nothing and is not + // created. + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, selfdestruct_to(EMPTY).build()); + (db, call_contract()) + }, + ); + + assert_charges_no_state_gas( + "a SELFDESTRUCT to an account that exists", + |envs, m| crowded_account(envs, FUNDED, m), + || { + let db = db(selfdestruct_to(FUNDED).build()).account_balance(FUNDED, U256::from(1)); + (db, call_contract()) + }, + ); +} + /* The remaining creation sites. */ /// `CREATE2` reaches its deployment address by hashing rather than by nonce, and is priced in diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 36071f47a..8deaca2ee 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -44,15 +44,25 @@ use revm::{ use crate::{ common::{history, state_is_free}, salt::{ - account_bucket, call_contract, create_with, crowded_account, crowded_slot, db, entry, - minimal_envs, run, salt_context, slot_bucket, try_run, tx, tx_with_gas, SaltEnvs, CALLER, - CONTRACT, GAS_LIMIT, + account_bucket, authorization_tx, call_contract, create_with, crowded_account, + crowded_slot, db, entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, + try_run, tx, tx_with_gas, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, }, }; +/// The contract a probe's inner frame runs in. +const SUB: Address = alloy_primitives::address!("0000000000000000000000000000000000c00005"); + /// The slot every probe that writes storage uses. const SLOT: u64 = 7; +/// The gas a probe's inner call forwards: 2,000,000 on top of `unit` of state gas at the largest +/// multiplier the probes crowd a bucket to, so the inner frame can pay for what it adds at every +/// multiplier and byte price. +fn inner_gas(unit: u64) -> u64 { + 2_000_000 + 8 * unit +} + /// Runs `probe` at each multiplier and returns the state gas it netted, requiring the regular /// ledger to be the same at all of them. fn net_state_at( @@ -106,6 +116,130 @@ fn test_a_slot_written_and_restored_nets_nothing_at_every_multiplier() { ); } +/// A `CALL` that charged for a new account leaf and then failed gives the charge back: the +/// caller cannot afford the transfer, so no account is created. +#[test] +fn test_a_failed_value_call_gives_its_new_account_charge_back() { + let probe = || { + let code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(1u64) + .push_address(EMPTY) + .push_number(1_000_000u64) + .append(CALL) + .stop() + .build(); + // The contract holds nothing, so the transfer the CALL attempts cannot be made. + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, code); + (db, call_contract()) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_account(envs, EMPTY, m), probe), + [0, 0, 0], + "no account was created, so the upfront charge comes back", + ); +} + +/// A `SELFDESTRUCT` charges for the beneficiary's leaf inside the frame that runs it, and a frame +/// whose caller does not survive gives the charge back: the inner frame self-destructed, the outer +/// one reverted, and the beneficiary was never created after all. +#[test] +fn test_a_selfdestruct_whose_caller_reverts_gives_its_charge_back() { + let forwarded = inner_gas(entry(GasId::new_account_state_gas())); + let probe = |outer_reverts: bool| { + move || { + let sub = selfdestruct_to(EMPTY).build(); + let mut code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(SUB) + .push_number(forwarded) + .append(CALL); + code = if outer_reverts { code.revert_with_data([0xaa]) } else { code.stop() }; + let db = db(code.build()) + .account_code(SUB, sub) + .account_balance(SUB, U256::from(1_000_000u64)); + (db, call_contract()) + } + }; + let crowd = |envs, m| crowded_account(envs, EMPTY, m); + + assert_eq!( + net_state_at([1, 2, 8], crowd, probe(true)), + [0, 0, 0], + "the reverting caller takes the beneficiary's leaf back with it", + ); + + // The control: the same program whose outer frame survives keeps the charge, scaled. Without + // it the zeroes above could be passing because nothing was ever charged. + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!( + net_state_at([1, 2, 8], crowd, probe(false)), + [new_account, new_account * 2, new_account * 8], + ); +} + +/// The whole transaction reverting is the same story one level up: the outermost frame's charge +/// goes back with it. +#[test] +fn test_a_transaction_that_reverts_pays_no_state_gas() { + let probe = || { + let code = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .revert_with_data([0xaa]) + .build(); + (db(code), call_contract()) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, CONTRACT, U256::from(SLOT), m), probe), + [0, 0, 0], + ); +} + +/// An applied EIP-7702 authorization is not a frame's doing: the delegation it wrote outlives a +/// frame that reverts afterwards, and so does the state gas it paid. +#[test] +fn test_an_applied_authorization_keeps_its_charge_through_a_revert() { + let authority_charges = + entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()); + let probe = || { + let code = BytecodeBuilder::default().revert_with_data([0xaa]).build(); + (db(code), authorization_tx(CONTRACT)) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_account(envs, AUTHORITY, m), probe), + [authority_charges, authority_charges * 2, authority_charges * 8], + "the authority's leaf and its delegation bytes are still there after the revert", + ); + + // And the delegation really did survive: the authority carries the designation. + let outcome = try_run( + db(BytecodeBuilder::default().revert_with_data([0xaa]).build()), + crowded_account(minimal_envs(), AUTHORITY, 8), + authorization_tx(CONTRACT), + ) + .expect("the transaction is valid"); + assert!( + outcome.state.get(&AUTHORITY).is_some_and(|account| account + .info + .code + .as_ref() + .is_some_and(|code| !code.is_empty())), + "the authority kept its delegation", + ); +} + /// A creation whose deployed code is refused before any deposit charge is made: EIP-3541 turns /// down a runtime code starting `0xEF` at validation, so the only state gas in play is the /// account leaf the transaction's own create target was charged for upfront, which comes back. From d1e1cd0f9e1820d1c73aa491a78aac455db2a17a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 138/190] test(state-growth): restore tests whose arms or observations no conformance case pins The destruction scenarios and the keyless creations run above the execution cap, where their cases run below it; the destruction probes pin a kept net of exactly zero, which the adapter reports clipped, and two assert the entry of an account created and destroyed in the transaction, which the adapter drops. One authorization variant and the fitting side of the depth-three budget have no case. --- .../tests/satin/limit_matrix/destruction.rs | 438 +++++++++++++++++- .../tests/satin/limit_matrix/keyless.rs | 68 +++ crates/mega-evm/tests/satin/state_growth.rs | 128 +++++ 3 files changed, 632 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs index f6051ef8a..7bf239920 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs @@ -14,8 +14,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATALOAD, CALLDATASIZE, GAS, JUMPDEST, JUMPI, LT, POP, PUSH0, - SELFDESTRUCT, SSTORE, STOP, + ADDRESS, CALL, CALLDATALOAD, CALLDATASIZE, CALLVALUE, GAS, JUMPDEST, JUMPI, LT, MLOAD, POP, + PUSH0, SELFDESTRUCT, SLOAD, SSTORE, STOP, }, context::{result::ExecutionResult, TxEnv}, interpreter::{ @@ -176,6 +176,36 @@ fn test_a_kept_destruction_gives_back_the_leaf_the_code_and_the_slot() { 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 @@ -257,6 +287,64 @@ fn test_stores_after_the_mark_and_a_reverted_enclosing_frame() { } } +/// 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, @@ -290,6 +378,108 @@ fn test_a_destroying_childs_negative_net_does_not_raise_the_parents_budget() { 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 @@ -443,6 +633,61 @@ fn test_a_cleared_account_with_no_kv_room_stops_at_the_frame_budget() { } } +/// 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. @@ -465,6 +710,112 @@ fn test_a_prefunded_destruction_that_moves_no_balance_keeps_the_nonce_record() { 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. @@ -685,6 +1036,51 @@ fn test_a_detention_crossing_at_the_destruction_applies_none_of_the_table() { /// 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 @@ -738,6 +1134,44 @@ fn test_a_deposit_after_the_mark_is_not_charged_what_its_frame_cannot_pay() { } } +/// 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 diff --git a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs index 24a4ea871..a8c36f19d 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs @@ -488,6 +488,74 @@ fn test_authorization_list_boundaries() { 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 diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 302767782..48adad8b1 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -167,6 +167,109 @@ fn account_and_delegation() -> (u64, u64) { (entry(GasId::new_account_state_gas()), entry(GasId::tx_eip7702_state_gas_bytecode())) } +/// An authorization adds state only when it applies: a new account for an authority that did not +/// exist, and the delegation's bytes once for an authority that was not delegated. Each authority +/// it applies to is one write record, however many of its authorizations applied, except the +/// sender, whose account is the body's. An authorization that does not apply — a wrong nonce, a +/// wrong chain, a nonce that cannot be bumped, an account with code, a signature that recovers to +/// nobody — adds nothing and leaves its authority as it was. +#[test] +fn test_an_authorization_adds_state_only_when_it_applies() { + if state_is_free() { + return; + } + let (account, delegation) = account_and_delegation(); + let a1 = Some(AUTHORITY_1); + let a2 = Some(AUTHORITY_2); + let with_code = || funded().account_code(AUTHORITY_1, Bytes::from_static(&[STOP])); + // (case, database, authorizations, state gas, records, AUTHORITY_1's nonce after) + type Case = (&'static str, MemoryDatabase, Vec, u64, u64, u64); + let cases: Vec = vec![ + ("a new authority", funded(), vec![(a1, 0, 0)], account + delegation, 1, 1), + ( + "two new authorities", + funded(), + vec![(a1, 0, 0), (a2, 0, 0)], + 2 * (account + delegation), + 2, + 1, + ), + ( + "one new authority authorized twice at its first nonce", + funded(), + vec![(a1, 0, 0), (a1, 0, 0)], + account + delegation, + 1, + 1, + ), + ( + "one new authority authorized twice in sequence", + funded(), + vec![(a1, 0, 0), (a1, 0, 1)], + account + delegation, + 1, + 2, + ), + ( + "an authority that exists", + funded().account_balance(AUTHORITY_1, U256::from(1)), + vec![(a1, 0, 0)], + delegation, + 1, + 1, + ), + ( + "an authority on the transaction's chain", + funded(), + vec![(a1, 1, 0)], + account + delegation, + 1, + 1, + ), + ("an authority on another chain", funded(), vec![(a1, 999, 0)], 0, 0, 0), + ("a wrong nonce", funded(), vec![(a1, 0, 1)], 0, 0, 0), + ("a nonce that cannot be bumped", funded(), vec![(a1, 0, u64::MAX)], 0, 0, 0), + ("an authority with code", with_code(), vec![(a1, 0, 0)], 0, 0, 0), + ("a signature that recovers to nobody", funded(), vec![(None, 0, 0)], 0, 0, 0), + ( + "the sender, at the nonce its transaction leaves it", + funded(), + vec![(Some(CALLER), 0, 1)], + delegation, + 0, + 0, + ), + ( + "the sender, at its transaction's own nonce", + funded(), + vec![(Some(CALLER), 0, 0)], + 0, + 0, + 0, + ), + ]; + for (name, db, authorizations, state_gas, records, nonce) in cases { + let tuples = authorizations.len() as u64 * mega_evm::AUTHORIZATION_SIZE; + let outcome = run( + db.account_code(A, Bytes::from_static(&[STOP])), + authorizing(A, U256::ZERO, &authorizations), + ); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.gas.state, state_gas, "{name}: the state gas"); + assert_eq!(outcome.usage.write_records, records, "{name}: the records"); + assert_eq!( + outcome.usage.data_size, + TX_BODY_SIZE + tuples + records * WRITE_RECORD_SIZE, + "{name}: the data size", + ); + let authority = outcome.state.get(&AUTHORITY_1); + assert_eq!(authority.map_or(0, |a| a.info.nonce), nonce, "{name}: the authority's nonce"); + let delegated = + outcome.state.values().any(|a| a.info.code.as_ref().is_some_and(|c| c.is_eip7702())); + assert_eq!(delegated, state_gas >= delegation, "{name}: whether anything was delegated"); + } +} + /// 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. @@ -765,6 +868,31 @@ fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { ); } +/// 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 From cd904a6826048a3bb562de4353626940c07daa66 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 139/190] test(write-records): restore tests whose target accounts no conformance case pins No case writes the block beneficiary, the L1 fee vault or the operator fee vault from execution, and these tests count those writes as records. --- crates/mega-evm/tests/satin/write_records.rs | 162 +++++++++++++++++++ 1 file changed, 162 insertions(+) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 0f18419d7..bd1e22e9e 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -248,6 +248,26 @@ fn test_nested_creations_record_each_account_once() { assert!(result.state.contains_key(&created.create(1))); } +/// 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 @@ -537,6 +557,148 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { ); } +/* ---------- the fee accounts and the sender ---------- */ + +/// The block beneficiary of the fee-account rows: an account of its own, not the zero address. +const COINBASE: Address = address!("00000000000000000000000000000000000C0B00"); + +/// How execution reaches an account in the rows of +/// [`test_execution_writes_to_the_fee_accounts_are_records`]. +#[derive(Clone, Copy, Debug)] +enum FeeRowPath { + /// `CALLEE` sends it one wei with a `CALL`. + ValueTransfer, + /// `CALLEE` destructs itself naming it as beneficiary, which moves `CALLEE`'s balance to it. + SelfDestruct, +} + +/// A write execution makes to one of the four accounts a transaction's fees are credited to is a +/// record like a write to any other account: the body's five fixed records bound the fee credits +/// the settlement makes, not what the transaction's frames write. The sender's account is the +/// converse: the body counts it, so nothing execution writes to it is recorded again, and that +/// holds for a fee account that is the sender too. +/// +/// 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 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 +/// the settlement credits the beneficiary and the base fee vault on top of what execution wrote. +/// +/// A record weighs `WRITE_RECORD_SIZE` bytes of data size and history and is one KV update; the +/// history is its bytes at the cost per history byte, on top of the body's `TX_BODY_SIZE`. +/// +/// Independence: constants — +/// the record counts are written out per row, and the data size, KV count and history are hand +/// arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE`, `TRANSFER_LOG_SIZE` and the cost per +/// history byte in effect. +#[test] +fn test_execution_writes_to_the_fee_accounts_are_records() { + use op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}; + use FeeRowPath::{SelfDestruct, ValueTransfer}; + + // (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, 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, 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, 2), + ( + "the operator fee vault, by a value transfer", + CALLER, + OPERATOR_FEE_RECIPIENT, + ValueTransfer, + 2, + ), + ( + "the operator fee vault, by a SELFDESTRUCT", + CALLER, + OPERATOR_FEE_RECIPIENT, + SelfDestruct, + 2, + ), + ("the sender, by a value transfer", CALLER, CALLER, ValueTransfer, 1), + ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 1), + ( + "the block beneficiary that is the sender, by a value transfer", + COINBASE, + COINBASE, + ValueTransfer, + 1, + ), + ( + "the block beneficiary that is the sender, by a SELFDESTRUCT", + COINBASE, + COINBASE, + SelfDestruct, + 1, + ), + ]; + for (row, sender, target, path, records) in rows { + let code = match path { + ValueTransfer => append_value_call(BytecodeBuilder::default(), target, 1) + .append(POP) + .append(STOP) + .build(), + SelfDestruct => { + BytecodeBuilder::default().push_address(target).append(SELFDESTRUCT).build() + } + }; + let mut db = funded().account_code(CALLEE, code).account_balance(sender, U256::MAX >> 2); + for account in [COINBASE, L1_FEE_RECIPIENT, BASE_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { + if account != sender { + db = db.account_balance(account, U256::from(1)); + } + } + 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() }; + let outcome = MegaEvm::new(context(db).with_block(block)) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); + assert_eq!(transfer_logs(&outcome.result), 1, "{row}: the transfer log"); + // The settlement credited the fees on top of what execution moved: the priority fee of + // nine a gas to the beneficiary, the base fee of one a gas to the base fee vault. + for (credited, per_gas) in [(COINBASE, 9u64), (BASE_FEE_RECIPIENT, 1)] { + if credited == sender { + continue; + } + let moved = match path { + _ if credited != target => 0, + ValueTransfer => 1, + SelfDestruct => 10_000_000, + }; + assert_eq!( + outcome.state[&credited].info.balance, + U256::from(1 + moved + outcome.gas.gas_used * per_gas), + "{row}: the fee credited to {credited}" + ); + } + + let history_bytes = TX_BODY_SIZE + records * WRITE_RECORD_SIZE; + assert_eq!(outcome.usage.write_records, records, "{row}: the records, the KV count"); + assert_eq!( + outcome.usage.data_size, + history_bytes + TRANSFER_LOG_SIZE, + "{row}: the data size: the body, the records and the transfer log" + ); + assert_eq!(outcome.gas.history_bytes, history_bytes, "{row}: the history bytes"); + if !crate::common::history_rounds() { + assert_eq!( + outcome.gas.history, + history(history_bytes), + "{row}: the history gas: the body and the records at the cost per history byte" + ); + } + } +} + /* ---------- the commit happens after the opcode ---------- */ /// Records, after each opcode, what the layer holds. From 1626d3cf7500aaac16d4aeaa7ac42940d7a78fe6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 140/190] test(system): restore tests whose selectors no conformance case pins No case calls enableVolatileDataAccess or isVolatileDataAccessDisabled, with or without value, or sends MegaAccessControl's selectors through the dispatch's admission. --- crates/mega-evm/tests/system/control.rs | 13 ++++++++++++- crates/mega-evm/tests/system/dispatch.rs | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/control.rs b/crates/mega-evm/tests/system/control.rs index f609d5e7a..a26445c9d 100644 --- a/crates/mega-evm/tests/system/control.rs +++ b/crates/mega-evm/tests/system/control.rs @@ -4,7 +4,7 @@ use alloy_primitives::{Bytes, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS}, + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, NON_ZERO_TRANSFER_REVERT_DATA}, test_utils::MemoryDatabase, }; use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}; @@ -64,6 +64,17 @@ fn test_a_static_call_is_intercepted() { assert!(data.is_empty()); } +/// A call that carries value to one of the three methods is refused with `NonZeroTransfer()`: +/// they read or steer execution and take no value. +#[test] +fn test_a_value_bearing_call_is_refused() { + for selector in [DISABLE, ENABLE, IS_DISABLED] { + let (status, data) = through_contract(CALL, &selector, 1); + assert!(!status, "a value-bearing call must not succeed"); + assert_eq!(data, Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA)); + } +} + /// The value policy is per method, after the selector matched: a value-bearing call to a /// selector the contract does not intercept still falls through to the bytecode. #[test] diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs index abab39218..aa48413cd 100644 --- a/crates/mega-evm/tests/system/dispatch.rs +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -68,6 +68,26 @@ fn test_an_intercepted_call_costs_what_a_plain_call_costs() { assert_eq!(spent(intercepted), spent(plain)); } +/// Admission is the four selector bytes: the exact selector and the selector followed by +/// anything are both intercepted, and an input too short to hold one is not. +#[test] +fn test_admission_is_the_selector_alone() { + let intercepted = |data: Vec| { + let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, &data, U256::ZERO)); + // The interceptor answers `false`; the deployed bytecode reverts. + result.result.is_success() + }; + assert!(intercepted(IS_DISABLED.to_vec()), "the exact selector"); + assert!(intercepted(IS_DISABLED.iter().copied().chain([0xff]).collect()), "one byte after it"); + assert!( + intercepted(IS_DISABLED.iter().copied().chain([0_u8; 32]).collect()), + "a padded argument after it", + ); + assert!(!intercepted(IS_DISABLED[..3].to_vec()), "three bytes are not a selector"); + assert!(!intercepted(Vec::new()), "no input is not a selector"); + assert!(!intercepted(vec![0xde, 0xad, 0xbe, 0xef]), "another selector"); +} + /// Records which addresses an inspector sees called, and in which order they end. #[derive(Default)] struct CallTracker { From 2c057ce9eacc8fd40c202305dea160c1e39518dd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 141/190] test(system): restore Oracle and system-transaction tests whose arm or error variant no conformance case pins No case reads the Oracle's storage from an ordinary transaction, and the conformance suite's adapter reports a wrong chain id and a missing one as the same refusal. --- crates/mega-evm/tests/system/oracle.rs | 15 ++++++++++- crates/mega-evm/tests/system/system_tx.rs | 33 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 71a90cecd..44ec25209 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -22,7 +22,7 @@ use revm::{ }; use crate::common::{ - block, call_tx, call_tx_with_gas, steer, system_db, with_contract, CALLER, CONTRACT, + block, call_tx, call_tx_with_gas, run, steer, system_db, with_contract, CALLER, CONTRACT, }; /// A topic and payload the tests send. @@ -268,6 +268,19 @@ fn test_an_unknown_selector_runs_the_bytecode() { assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + 4); } +/// Reading the Oracle's storage is not intercepted: `getSlot` runs the contract's code. +#[test] +fn test_reading_a_slot_runs_the_bytecode() { + let db = system_db().account_storage(ORACLE_CONTRACT_ADDRESS, U256::from(3), U256::from(42)); + let data = IOracle::getSlotCall { slot: U256::from(3) }.abi_encode(); + let result = run(db, call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + IOracle::getSlotCall::abi_decode_returns(result.result.output().unwrap()).unwrap(), + B256::from(U256::from(42)), + ); +} + /// A payload that does not fit in what is left of the transaction's data-size limit is not /// forwarded, and the crossing stops the transaction: the limit is checked on the hint's bytes /// before the payload is decoded, so it is crossed before the frame the call would have started. diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index bd356c9a6..eb8e77913 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -120,6 +120,14 @@ fn run_outcome(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcom MegaEvm::new(chain_context(db)).execute_transaction(tx).expect("the transaction is valid") } +/// Runs `tx` and returns the error it was rejected with, as a string. +fn rejection(db: MemoryDatabase, tx: MegaTransaction) -> String { + let error = MegaEvm::new(chain_context(db)) + .execute_transaction(tx) + .expect_err("the transaction must be rejected"); + format!("{error:?}") +} + /// The Oracle's slot as the database holds it. fn oracle_slot(db: &mut DB, slot: U256) -> U256 where @@ -573,6 +581,31 @@ fn test_two_system_transactions_in_a_block_both_go_through() { assert_eq!(nonce_of(&mut state, MEGA_SYSTEM_ADDRESS), 2); } +/// A system transaction carries the chain's id, so it cannot be replayed on another chain; one +/// without an id at all is refused too. +#[test] +fn test_a_system_transaction_is_bound_to_the_chain() { + let foreign = legacy_tx_with_chain_id( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, B256::with_last_byte(0xcc)), + 0, + Some(31_337), + ); + let rejected = rejection(chain_db(), foreign); + assert!(rejected.contains("InvalidChainId"), "{rejected}"); + + let no_chain_id = legacy_tx_with_chain_id( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, B256::with_last_byte(0xdd)), + 0, + None, + ); + let rejected = rejection(chain_db(), no_chain_id); + assert!(rejected.contains("MissingChainId"), "{rejected}"); +} + /// Runs `tx` on `db` under the chain's configuration with `mutate` applied. fn run_with( mutate: fn(&mut CfgEnv), From 3335e7972e9ef0808dc26da331a0e0d102676f98 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:07:22 +0800 Subject: [PATCH 142/190] test(keyless): restore tests whose above-cap arm or variant no conformance case pins These run each rule, outcome and charge both below and above the execution cap, and Mega EEST's above-cap keyless cases cover an ordinary deployment, a halt in the code deposit, the step-15 refusal and the authorization limits alone; a few also run calling schemes, rule pairs and encodings no case has. --- .../mega-evm/tests/system/keyless/charges.rs | 132 +++++++ .../mega-evm/tests/system/keyless/deploy.rs | 360 +++++++++++++++++- .../mega-evm/tests/system/keyless/dispatch.rs | 169 +++++++- .../mega-evm/tests/system/keyless/limits.rs | 41 +- .../tests/system/keyless/precedence.rs | 202 +++++++++- crates/mega-evm/tests/system/keyless/rules.rs | 267 ++++++++++++- 6 files changed, 1159 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index e0e4402e1..cd59e8459 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -103,6 +103,76 @@ fn test_the_call_pays_the_legacy_shares_of_the_accounts_it_creates() { } } +/// The created account is charged only when the deploy address is empty, as the `CREATE` opcode +/// charges it: an address that already holds a balance is an account already, the deployment +/// lands on it, and the balance stays. +#[test] +fn test_the_created_account_is_charged_only_when_the_address_is_empty() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + for gas_limit in GAS_LIMITS { + let empty = deploy(system_db(), &deployment, gas_limit); + let held = system_db().account_balance(deployment.address, U256::from(7_777)); + let held = deploy(held, &deployment, gas_limit); + assert_eq!(returned(&held).deployedAddress, deployment.address); + assert_eq!( + held.state.get(&deployment.address).map(|account| account.info.balance), + Some(U256::from(7_777)), + ); + let [total, regular, state, history_gas, _] = beyond(&empty, &held); + let created = entry(GasId::create_state_gas()); + assert_eq!([total, regular, state, history_gas], [created, 0, created, 0]); + } +} + +/// A refused call keeps the overhead and nothing else: every charge made after it is taken back +/// with the revert, whatever the pools. +#[test] +fn test_a_refused_call_keeps_the_overhead_alone() { + // A value the signer cannot fund: refused at the last rule, after every read. + let deployment = Deployment::with_value(deploying(&runtime(RUNTIME_LEN)), U256::from(1)); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); + assert_eq!( + [total, regular, state, history_gas, history_bytes], + [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0, 0], + "at {gas_limit}", + ); + assert_eq!(outcome.usage.write_records, 0); + } +} + +/// A deployment whose init code reverts gives the created account's charge back, and the record +/// of the account it did not create; the signer's account and its nonce record stay, because the +/// nonce stays spent. +#[test] +fn test_a_failed_deployment_gives_the_created_account_back() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let error = failure(&outcome); + let KeylessDeployError::ExecutionReverted { gas_used, .. } = error else { + panic!("expected ExecutionReverted, got {error:?}"); + }; + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!(state, new_account, "at {gas_limit}"); + assert_eq!(history_gas, record(), "at {gas_limit}"); + assert_eq!(history_bytes, 40, "at {gas_limit}"); + assert_eq!( + regular, + KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(3) + gas_used, + "at {gas_limit}" + ); + assert_eq!(total, regular + state + history_gas); + assert_eq!(nonce(&outcome, deployment.signer), 1, "the nonce stays spent"); + assert_eq!(outcome.usage.write_records, 1, "the signer's nonce"); + } +} + /// The call pays the regular gas the `CREATE` opcode charges its frame on top of the overhead, /// whatever the pools: the schedule's `create` entry, 12,000, and EIP-3860's 2 gas per word of /// init code, 65,536 for init code of the maximum size. Init code of zero bytes stops at once and @@ -136,6 +206,68 @@ fn test_the_call_pays_the_create_opcodes_regular_gas() { } } +/// `gasUsed` is what the creation spent before refunds: a constructor that fills a slot and +/// clears it again earns a refund, which is the transaction's, as any frame's is. The charges add +/// up to the transaction's spend before its refund, and the receipt's gas is that spend less the +/// refund. +#[test] +fn test_gas_used_counts_the_creations_spend_before_its_refund() { + let prefix = mega_evm::test_utils::BytecodeBuilder::default() + .sstore(U256::ZERO, U256::ONE) + .sstore(U256::ZERO, U256::ZERO) + .build_vec(); + let init_code = constructor(&prefix, &runtime(1)); + let opcode = create_regular(init_code.len()); + let deployment = Deployment::new(init_code); + let upfront = + entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()) + 2 * record(); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let gas_used = returned(&outcome).gasUsed; + let refund = outcome.result.gas().inner_refunded(); + assert!(refund > 0, "the constructor earns a refund at {gas_limit}"); + let [total, ..] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + opcode + upfront + gas_used, + "at {gas_limit}" + ); + assert_eq!( + outcome.result.gas().tx_gas_used(), + outcome.result.gas().total_gas_spent() - refund, + "at {gas_limit}", + ); + } +} + +/// Both upfront charges are priced by the SALT bucket they land in — the signer's account in the +/// signer's, the created account in the deploy address's — and regular gas does not move with it. +#[test] +fn test_the_upfront_charges_scale_with_their_buckets() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + let new_account = entry(GasId::new_account_state_gas()); + let created = entry(GasId::create_state_gas()); + for gas_limit in GAS_LIMITS { + let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); + for (m_signer, m_address) in [(2, 1), (1, 2), (3, 2)] { + let envs = crowded( + crowded(TestExternalEnvs::new(), deployment.signer, m_signer), + deployment.address, + m_address, + ); + let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); + assert_eq!(crowded_run.gas.regular, minimal.gas.regular, "m does not touch regular"); + assert_eq!( + crowded_run.gas.state - minimal.gas.state, + (m_signer - 1) * new_account + + (m_address - 1) * (created + satin_gas_params().code_deposit_state_gas(5)), + "signer at m = {m_signer}, address at m = {m_address}, gas limit {gas_limit}", + ); + } + } +} + /// A deployment that fails gives the created account back at the price it was charged, however /// crowded the deploy address's bucket, and the bucket is read once for both; the signer's /// account is kept at its own bucket's price. diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 66da768b2..14b022c5f 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -20,8 +20,9 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, JUMP, JUMPDEST, LOG0, MLOAD, ORIGIN, POP, PUSH0, REVERT, - SELFDESTRUCT, SSTORE, STATICCALL, + CALL, CREATE, DELEGATECALL, GAS, GASPRICE, INVALID, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, + ORIGIN, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, SHR, SSTORE, + STATICCALL, }, context::BlockEnv, primitives::KECCAK_EMPTY, @@ -29,6 +30,7 @@ use revm::{ }; use super::*; +use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); @@ -96,6 +98,24 @@ fn test_a_deployment_survives_a_commit() { } } +/// Init code that reverts: the call succeeds and reports `ExecutionReverted` with the revert +/// data, the deployment writes no code, and the signer's nonce is spent. +#[test] +fn test_keyless_deploy_execution_reverted() { + let deployment = + Deployment::new(BytecodeBuilder::default().revert_with_data([0xc0, 0xff, 0xee]).build()); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::ExecutionReverted { gas_used, output } = failure(&outcome) else { + panic!("expected ExecutionReverted: {:?}", outcome.result); + }; + assert_eq!(output, Bytes::from_static(&[0xc0, 0xff, 0xee])); + assert_eq!(gas_used, returned(&outcome).gasUsed); + assert_eq!(nonce(&outcome, deployment.signer), 1); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + /// What the creation of a keyless deployment returned into its call: its regular gas and its /// reservoir once revm's settlement of the result, which runs after the inspector sees the /// creation end, rolled a failure's state and history gas back. @@ -169,6 +189,26 @@ fn test_a_reverting_constructor_returns_its_slot_as_reservoir_and_reports_its_re } } +/// Init code that hits an invalid opcode: `ExecutionHalted`, and the halt spends the whole +/// forward. +#[test] +fn test_keyless_deploy_execution_halted_invalid_opcode() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(Bytes::from_static(&[INVALID])); + let outcome = run_with( + system_db(), + deployment.call_data(2_000_000), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ); + let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionHalted: {:?}", outcome.result); + }; + assert_eq!(gas_used, 2_000_000, "a halt spends what it was forwarded"); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + /// A constructor that runs out of gas halts the same way, below and above the execution cap, /// and spends its whole forward in both. #[test] @@ -188,6 +228,48 @@ fn test_a_constructor_out_of_gas_is_execution_halted() { } } +/// A halted deployment is paid for, and its nonce is spent: the transaction spends the overhead, +/// the `CREATE` opcode's regular gas, the signer's account and its nonce record, and the whole +/// forward. +#[test] +fn test_a_halted_deployment_is_paid_for_and_spends_the_nonce() { + let deployment = Deployment::new(Bytes::from_static(&[INVALID])); + for gas_limit in GAS_LIMITS { + let data = deployment.call_data(SIGNED_GAS_LIMIT); + let outcome = + run_with(system_db(), data.clone(), gas_limit, EvmTxRuntimeLimits::no_limits()); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 1); + let [total, ..] = beyond(&outcome, &reference(data, gas_limit)); + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(1) + + new_account + + record() + + SIGNED_GAS_LIMIT, + "at {gas_limit}", + ); + } +} + +/// Init code that returns nothing deploys no code: `EmptyCodeDeployed`, and the nonce is spent. +#[test] +fn test_keyless_deploy_empty_initcode() { + for gas_limit in GAS_LIMITS { + for init_code in [Bytes::new(), Bytes::from_static(&[PUSH0, PUSH0, RETURN])] { + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::EmptyCodeDeployed { gas_used } = failure(&outcome) else { + panic!("expected EmptyCodeDeployed: {:?}", outcome.result); + }; + assert_eq!(gas_used, returned(&outcome).gasUsed); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } + } +} + /// A deployment whose initcode returns empty code at the deploy address is refused: the creation /// reverts, the call answers `EmptyCodeDeployed`, and the deploy address keeps no account, so the /// signed bytes can still be deployed. The initcode returns empty code when it has more than @@ -237,6 +319,55 @@ fn test_an_empty_code_deployment_leaves_the_address_deployable() { } } +/// A deploy address at nonce 1 without code — what a Rex6 deployment whose creation returned +/// empty code left — passes the occupancy rule, which reads the code alone, and the creation +/// collides there before its init code runs: whatever the init code would do, the call answers +/// `ExecutionHalted` with the whole forward spent, the address keeps its nonce and no code, and the +/// signer's bump from 0 stands. +#[test] +fn test_a_deploy_address_with_a_nonce_and_no_code_collides() { + let init_codes = + [deploying(&runtime(1)), Bytes::new(), Bytes::from_static(&[INVALID]), logging(32)]; + for init_code in init_codes { + let deployment = Deployment::new(init_code); + let db = system_db().account_nonce(deployment.address, 1); + for gas_limit in GAS_LIMITS { + for forward in [SIGNED_GAS_LIMIT, 2 * SIGNED_GAS_LIMIT] { + let outcome = run_with( + db.clone(), + deployment.call_data(forward), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ); + let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionHalted: {:?}", outcome.result); + }; + assert_eq!(gas_used, forward, "a collision spends the forward, at {gas_limit}"); + assert_eq!(nonce(&outcome, deployment.signer), 1, "the bump from 0 stands"); + assert_eq!(nonce(&outcome, deployment.address), 1, "the address keeps its nonce"); + assert_eq!(code_hash(&outcome, deployment.address), Some(KECCAK_EMPTY)); + assert!(outcome.result.logs().is_empty(), "the init code never ran"); + } + } + } +} + +/// An empty deposit is refused at the deploy address alone: a constructor's own `CREATE` that +/// returns empty code is admitted, and the deployment around it succeeds. +#[test] +fn test_a_constructors_own_creation_may_return_empty_code() { + for gas_limit in GAS_LIMITS { + // CREATE of empty init code, then the deployment's own runtime. + let prefix = [PUSH0, PUSH0, PUSH0, CREATE, POP]; + let deployment = Deployment::new(constructor(&prefix, &runtime(1))); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + let inner = deployment.address.create(1); + assert_eq!(nonce(&outcome, inner), 1, "the inner creation stands, with no code"); + assert_eq!(code_hash(&outcome, inner), Some(KECCAK_EMPTY)); + } +} + /// Init code that destroys its own account: the value it held goes to the beneficiary, no code /// is left, and the call reports `EmptyCodeDeployed`. #[test] @@ -331,6 +462,17 @@ fn test_a_constructor_destroyed_through_delegatecall_deploys_no_code() { } } +/// Code starting with `0xEF` is refused by the creation (EIP-3541): `ExecutionHalted`. +#[test] +fn test_code_starting_with_ef_is_refused() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&[0xef, 0x00])); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + /// Code over the contract size limit is refused by the creation (EIP-170): `ExecutionHalted`. #[test] fn test_code_over_the_size_limit_is_refused() { @@ -345,6 +487,19 @@ fn test_code_over_the_size_limit_is_refused() { } } +/// A deployment carrying a value moves it from the signer to the contract. +#[test] +fn test_keyless_deploy_with_value_transfer() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); + let outcome = deploy(db_for(&deployment, U256::from(10_000)), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); + assert_eq!(balance(deployment.address), Some(U256::from(7_777))); + assert_eq!(balance(deployment.signer), Some(U256::from(2_223))); + } +} + /// A constructor that writes another contract's storage: the write is kept. #[test] fn test_keyless_deploy_modifies_other_contract_state() { @@ -463,6 +618,82 @@ fn test_keyless_deploy_reads_existing_contract() { } } +/// A constructor that writes storage and then reverts leaves neither the storage nor code, and +/// the call still reports the revert with a gas figure. +#[test] +fn test_failed_initcode_keeps_no_storage() { + let init_code = + BytecodeBuilder::default().sstore(U256::from(1), U256::from(7)).revert().build(); + let deployment = Deployment::new(init_code); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionReverted: {:?}", outcome.result); + }; + assert!(gas_used > 0); + let kept = outcome + .state + .get(&deployment.address) + .and_then(|account| account.storage.get(&U256::from(1)).map(|slot| slot.present_value)); + assert!(kept.is_none_or(|value| value.is_zero()), "at {gas_limit}"); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); + } +} + +/// A constructor's log is the transaction's: it is in the receipt, emitted by the deployed +/// address. +#[test] +fn test_keyless_deploy_emits_logs() { + for gas_limit in GAS_LIMITS { + let prefix = BytecodeBuilder::default() + .mstore(0, B256::repeat_byte(0xab)) + .push_number(32_u64) + .push_number(0_u64) + .append(LOG0); + let deployment = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let logs = outcome.result.logs(); + assert_eq!(logs.len(), 1); + assert_eq!(logs[0].address, deployment.address); + assert_eq!(logs[0].data.data, Bytes::from(B256::repeat_byte(0xab).to_vec())); + } +} + +/// Init code that logs and deploys nothing keeps no log: the call reports `EmptyCodeDeployed`, and +/// the creation, refused its empty deposit, reverted with its log. +#[test] +fn test_an_empty_code_deployment_keeps_no_log() { + for gas_limit in GAS_LIMITS { + let topic = B256::repeat_byte(0x11); + let init_code = BytecodeBuilder::default() + .mstore(0, [0xde, 0xad, 0xbe, 0xef]) + .push_bytes(topic) + .push_number(4_u64) + .push_number(0_u64) + .append(LOG1) + .return_empty() + .build(); + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + assert!(outcome.result.logs().is_empty()); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + +/// And init code that logs nothing leaves none. +#[test] +fn test_an_empty_code_deployment_adds_no_log() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(BytecodeBuilder::default().return_empty().build()); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + assert!(outcome.result.logs().is_empty()); + } +} + /// A deployment that fails keeps no log: the creation's revert takes its logs with it. #[test] fn test_a_failed_deployment_keeps_no_log() { @@ -488,6 +719,34 @@ fn priced_tx(deployment: &Deployment, gas_limit: u64, gas_price: u128) -> MegaTr tx } +/// `ORIGIN` and `GASPRICE` in the init code are the transaction's own: the relayer, and the gas +/// price the relayer pays — not the signer, and not the price the deployment was signed at. +#[test] +fn test_origin_and_gasprice_follow_the_outer_transaction() { + let prefix = BytecodeBuilder::default() + .append(ORIGIN) + .push_number(0_u64) + .append(SSTORE) + .append(GASPRICE) + .push_number(1_u64) + .append(SSTORE); + let deployment = Deployment::new(running(prefix)); + for gas_limit in GAS_LIMITS { + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(priced_tx(&deployment, gas_limit, 7)) + .expect("a valid transaction"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let slot = |key: u64| { + outcome.state[&deployment.address] + .storage + .get(&U256::from(key)) + .map(|s| s.present_value) + }; + assert_eq!(slot(0), Some(U256::from_be_slice(RELAYER.as_slice())), "ORIGIN"); + assert_eq!(slot(1), Some(U256::from(7)), "GASPRICE"); + } +} + /// The block's beneficiary is paid for the whole transaction, deployment included, whether the /// deployment succeeds or fails, and the signer pays nothing. fn assert_beneficiary_paid(init_code: Bytes) { @@ -514,6 +773,103 @@ fn test_beneficiary_receives_fees_on_execution_failure() { assert_beneficiary_paid(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); } +/// A contract's `keylessDeploy` call is not dispatched: it runs the method body, which reverts +/// with `NotIntercepted()`, and nothing is deployed. +#[test] +fn test_keyless_deploy_not_intercepted_for_inner_calls() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&runtime(1))); + let code = + calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &deployment.call_data(LARGE_OVERRIDE), 0); + let mut tx = call_tx(CONTRACT, [], U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(with_contract(code))) + .execute_transaction(tx) + .expect("a valid transaction"); + let output = outcome.result.output().cloned().unwrap_or_default(); + let (status, returned) = split_outcome(&output); + assert!(!status); + assert_eq!(returned, IKeylessDeploy::NotIntercepted::SELECTOR); + assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); + assert!(!outcome.state.contains_key(&deployment.address)); + } +} + +/// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: +/// not dispatched. The contract's bytecode runs and reverts with `NotIntercepted()`, which the +/// outer constructor stores, and nothing of the inner deployment happens: its address holds no +/// code and its signer's nonce is unspent. The outer deployment deploys. +/// +/// A call answered without the bytecode — refused by an interceptor, or run as a deployment that +/// fails — could fail the same way, but not with the four bytes of `NotIntercepted()`. +/// +/// Expected values `independent`: the error's selector is computed here from its +/// signature, `NotIntercepted()`, not taken from the contract's binding. +#[test] +fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { + let not_intercepted = &alloy_primitives::keccak256("NotIntercepted()")[..4]; + let selector = U256::from_be_slice(not_intercepted); + for gas_limit in GAS_LIMITS { + let inner = Deployment::new(deploying(&[0x00, 0x00])); + let data = inner.call_data(LARGE_OVERRIDE); + // The inner call's status in slot 0, the size of its revert data in slot 2, and the first + // four bytes of that data, as a number, in slot 1. + let prefix = BytecodeBuilder::default() + .mstore(0, &data) + .push_number(0_u64) + .push_number(0_u64) + .push_number(data.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .push_address(KEYLESS_DEPLOY_ADDRESS) + .append(GAS) + .append(CALL) + .push_number(0_u64) + .append(SSTORE) + .append(RETURNDATASIZE) + .push_number(2_u64) + .append(SSTORE) + .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, PUSH0, MLOAD]) + .push_number(224_u64) + .append(SHR) + .push_number(1_u64) + .append(SSTORE); + let outer = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &outer, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, outer.address); + let slot = |index: u64| { + outcome.state[&outer.address] + .storage + .get(&U256::from(index)) + .map(|slot| slot.present_value) + }; + assert_eq!(slot(0), Some(U256::ZERO), "the inner call failed"); + assert_eq!(slot(2), Some(U256::from(4)), "with four bytes of revert data"); + assert_eq!(slot(1), Some(selector), "which are NotIntercepted(): the bytecode ran"); + assert!(code_hash(&outcome, inner.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + assert_eq!(nonce(&outcome, inner.signer), 0); + } +} + +/// A constructor's storage writes are priced by the SALT environment the transaction runs in: a +/// crowded bucket at the deploy address makes the deposited code cost more state gas, and the +/// creation's `gasUsed` grows by exactly that. +#[test] +fn test_a_deployment_is_priced_by_the_transactions_salt_env() { + let deployment = Deployment::new(deploying(&runtime(5))); + let deposit = satin_gas_params().code_deposit_state_gas(5); + for gas_limit in GAS_LIMITS { + let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); + let envs = crowded(TestExternalEnvs::new(), deployment.address, 3); + let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); + assert_eq!( + returned(&crowded_run).gasUsed - returned(&minimal).gasUsed, + 2 * deposit, + "at {gas_limit}", + ); + } +} + /// A constructor that sends an Oracle hint reaches the node's oracle service: the creation runs /// in the transaction's own environment. #[test] diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index ccfcb1a2e..a21575889 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -7,15 +7,31 @@ //! overhead alone. use alloy_primitives::{Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::system::keyless::{ - IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + system::keyless::{ + IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + EvmTxRuntimeLimits, +}; +use revm::{ + bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, + context::result::ExecutionResult, }; -use revm::context::result::ExecutionResult; -use crate::common::{body_history, call_tx, revert_data, run, system_db}; +use super::{beyond, reference, refusal, run_with, GAS_LIMITS}; +use crate::common::{ + body_history, call_tx, calls_with, output, revert_data, run, split_outcome, system_db, + with_contract, CONTRACT, +}; + +/// No runtime limit. +fn no_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits() +} const KEYLESS_DEPLOY: [u8; 4] = IKeylessDeploy::keylessDeployCall::SELECTOR; +const NOT_INTERCEPTED: [u8; 4] = IKeylessDeploy::NotIntercepted::SELECTOR; /// The calldata of a `keylessDeploy` call carrying `transaction` bytes. fn keyless_deploy(transaction: &[u8]) -> Bytes { @@ -36,6 +52,42 @@ fn unknown_selector(data: &Bytes) -> Bytes { Bytes::from(data) } +/// A dispatched `keylessDeploy` transaction pays the fixed overhead, then is refused by the +/// rules: bytes that do not decode as a signed transaction are `MalformedEncoding()`. The +/// deployed bytecode does not run, and the overhead is all the refusal keeps. +#[test] +fn test_a_keyless_deploy_transaction_pays_the_overhead() { + let data = keyless_deploy(b"a transaction"); + for gas_limit in GAS_LIMITS { + let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); + assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); + let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); + assert_eq!([total, regular], [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], "at {gas_limit}"); + } +} + +/// A call a contract makes is not dispatched, whatever its selector: only a transaction +/// deploys. The deployed bytecode runs and reverts with `NotIntercepted()`, and no overhead is +/// charged. +#[test] +fn test_a_call_from_a_contract_is_not_dispatched() { + let data = keyless_deploy(b"a transaction"); + for scheme in [CALL, STATICCALL, CALLCODE, DELEGATECALL] { + let code = calls_with(scheme, KEYLESS_DEPLOY_ADDRESS, &data, 0); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, returned) = split_outcome(&outcome); + assert!(!status, "scheme {scheme:#x}"); + assert_eq!(returned, NOT_INTERCEPTED, "scheme {scheme:#x}"); + // The transaction's body is its only history: what it spent beside it is less than the + // overhead. + assert!( + result.result.gas().total_gas_spent() - body_history(0) < KEYLESS_DEPLOY_OVERHEAD_GAS, + "scheme {scheme:#x} paid the overhead of a dispatch that did not happen", + ); + } +} + /// A selector the contract does not know, and an input too short to hold one, are not /// dispatched: the bytecode runs and reverts on its own, with empty data. /// @@ -84,6 +136,113 @@ fn test_a_call_that_cannot_pay_the_overhead_runs_out_of_gas() { assert_eq!(result.result.tx_gas_used(), gas_limit, "an out-of-gas frame spends what it had",); } +/// A call is recognised only once its arguments decode as `(bytes, uint256)`: a payload too short +/// to hold them, an offset that points past the data, and a length that runs past it are not +/// dispatched. The deployed bytecode runs and its decoder reverts with empty data, and the +/// overhead is not charged. +#[test] +fn test_arguments_that_do_not_decode_are_not_dispatched() { + let selector = KEYLESS_DEPLOY.to_vec(); + let word = |value: u64| U256::from(value).to_be_bytes::<32>().to_vec(); + let well_formed = keyless_deploy(b"a transaction").to_vec(); + + let mut offset_past_the_data = selector.clone(); + offset_past_the_data.extend(word(0x1000)); + offset_past_the_data.extend(word(1_000_000)); + let mut length_past_the_data = selector.clone(); + length_past_the_data.extend(word(0x40)); + length_past_the_data.extend(word(1_000_000)); + length_past_the_data.extend(word(32)); + let cases = [ + ("short", [selector.clone(), vec![0_u8; 16]].concat()), + ("selector alone", selector), + ("offset past the data", offset_past_the_data), + ("length past the data", length_past_the_data), + ("cut inside the bytes", well_formed[..well_formed.len() - 40].to_vec()), + ]; + for (name, input) in cases { + let data = Bytes::from(input); + for gas_limit in GAS_LIMITS { + let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("{name}: the bytecode did not revert: {:?}", outcome.result); + }; + assert!(output.is_empty(), "{name}: the bytecode's decoder reverts with empty data"); + let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); + assert!( + total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, + "{name} at {gas_limit}: paid {total} beyond a plain call, an overhead it does not \ + owe", + ); + } + } +} + +/// The calldata of a `keylessDeploy` call: the selector and `words` as 32-byte words, then +/// `tail` as it is. +fn raw_call(words: &[u64], tail: &[u8]) -> Bytes { + let mut data = KEYLESS_DEPLOY.to_vec(); + for word in words { + data.extend(U256::from(*word).to_be_bytes::<32>()); + } + data.extend(tail); + Bytes::from(data) +} + +/// A call is recognised exactly when the contract's own calldata decoder for `(bytes, uint256)` +/// accepts its arguments, and that decoder asks for no padding and no canonical offset: the +/// padding of the bytes' tail cut off, an offset that points at the head's second word, which is +/// then read as the length, and an offset of zero are all recognised. Each pays the overhead and +/// reaches the rule that refuses a payload that is no signed transaction. +#[test] +fn test_arguments_the_contracts_decoder_accepts_are_dispatched() { + let cases = [ + // offset 0x40, gas limit, length 5, five bytes and none of the 27 bytes of padding + ("the tail's padding cut off", raw_call(&[0x40, 1_000_000, 5], &[0xab; 5])), + // offset 0x20 points at the second head word (3), which is read as the length of the + // three bytes after the head + ("an offset at the second head word", raw_call(&[0x20, 3], &[0xab; 3])), + // offset zero points at the first head word (0), read as an empty payload + ("an offset of zero", raw_call(&[0, 1_000_000], &[])), + ]; + for (name, data) in cases { + for gas_limit in GAS_LIMITS { + let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); + assert_eq!( + refusal(&dispatched), + KeylessDeployError::MalformedEncoding, + "{name} at {gas_limit}", + ); + let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); + assert_eq!( + [total, regular], + [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], + "{name} at {gas_limit}: recognised, so the overhead is charged", + ); + } + } +} + +/// The first of those cases one byte short of the declared length is refused by the same +/// decoder: the call is not recognised, pays no overhead, and the bytecode reverts with empty +/// data. +#[test] +fn test_a_payload_one_byte_short_of_its_declared_length_is_not_dispatched() { + let data = raw_call(&[0x40, 1_000_000, 5], &[0xab; 4]); + for gas_limit in GAS_LIMITS { + let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("the bytecode did not revert: {:?}", outcome.result); + }; + assert!(output.is_empty(), "the bytecode's decoder reverts with empty data"); + let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); + assert!( + total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, + "at {gas_limit}: paid {total} beyond a plain call, an overhead it does not owe", + ); + } +} + /// A call that carries value and whose arguments do not decode is not dispatched either: the /// bytecode runs and refuses the value itself, with the empty revert data of a non-payable /// method, and no overhead is charged. diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 05be35361..dd02e16f0 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -24,7 +24,7 @@ use mega_evm::{ LimitCheck, LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, GAS, POP, PUSH0, TIMESTAMP}, + bytecode::opcode::{CALL, GAS, POP, PUSH0, REVERT, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, InstructionResult, @@ -407,6 +407,45 @@ fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { ); } +/// The call gets back what its creation did not spend, the same way whether the creation +/// succeeds or reverts: the transaction spends the overhead, the `CREATE` opcode's regular gas, +/// what the call kept of the creation's start, and the creation's `gasUsed`, and nothing else, +/// below and above the execution cap. +#[test] +fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { + let succeeding = Deployment::new(deploying(&runtime(1))); + let reverting = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let new_account = entry(GasId::new_account_state_gas()); + for gas_limit in GAS_LIMITS { + let success = limited(&succeeding, gas_limit, EvmTxRuntimeLimits::no_limits()); + let [total, ..] = + beyond(&success, &reference(succeeding.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(deploying(&runtime(1)).len()) + + new_account + + entry(GasId::create_state_gas()) + + 2 * record() + + returned(&success).gasUsed, + "success at {gas_limit}", + ); + + let revert = limited(&reverting, gas_limit, EvmTxRuntimeLimits::no_limits()); + let [total, ..] = + beyond(&revert, &reference(reverting.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(3) + + new_account + + record() + + returned(&revert).gasUsed, + "revert at {gas_limit}", + ); + } +} + /* ---------- the stop, as a column of the matrix ---------- */ /// A limit a deployment's creation crosses. diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 93eea761a..65c8cf505 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -14,9 +14,52 @@ //! bytecode and reverted with empty data. A call whose arguments do not decode is no deployment //! at all, with or without value, and runs the bytecode as the legacy engine did. -use mega_evm::{system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::MemoryDatabase}; +use mega_evm::{ + system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, + test_utils::MemoryDatabase, +}; use super::*; +use crate::common::state_is_free; + +/// The gas limit the matrix's deployments are signed with: 500,000 on top of the state gas of the +/// account the creation adds, at the byte prices in effect, so the creation's charges leave part of +/// it whatever a state byte costs. +fn signed_gas() -> u64 { + 500_000 + entry(GasId::create_state_gas()) +} + +/// What a call is answered with. +#[derive(Debug, PartialEq, Eq)] +enum Answer { + /// A revert with a rule's error. + Refused(KeylessDeployError), + /// An out-of-gas halt. + OutOfGas, +} + +/// A call that fails the rules named, over `db`, carrying `data`, at `gas_limit`. +struct Case { + rules: &'static str, + db: MemoryDatabase, + data: Bytes, + gas_limit: u64, + answer: Answer, +} + +impl Case { + fn check(self) { + let outcome = run_with(self.db, self.data, self.gas_limit, EvmTxRuntimeLimits::no_limits()); + let answer = match &outcome.result { + ExecutionResult::Revert { output, .. } => { + Answer::Refused(decode_error_result(output).expect("a keyless deploy error")) + } + ExecutionResult::Halt { .. } => Answer::OutOfGas, + other => panic!("{}: the call was not refused: {other:?}", self.rules), + }; + assert_eq!(answer, self.answer, "{} at {}", self.rules, self.gas_limit); + } +} /// A deployment signed with `gas_limit`, carrying `value`. fn signed(gas_limit: u64, value: u64) -> Deployment { @@ -42,6 +85,66 @@ fn leaving(data: &Bytes, left: u64) -> u64 { left } +/// `GasLimitTooLow` for a deployment signed with [`signed_gas`], with `provided`. +fn too_low(provided: u64) -> Answer { + Answer::Refused(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: signed_gas(), + provided_gas_limit: provided, + }) +} + +/// Pairs of failing rules that do not depend on the call's gas, at both gas limits: the rule the +/// legacy engine checked first is the one reported. +#[test] +fn test_a_call_two_rules_refuse_reports_the_first_the_legacy_engine_checked() { + let plain = signed(signed_gas(), 0); + let carrying = signed(signed_gas(), 1); + for gas_limit in GAS_LIMITS { + let data = plain.call_data(LARGE_OVERRIDE); + let cases = [ + Case { + rules: "gasLimitOverride below the signed gas limit, and an occupied address", + db: occupied(funded(system_db(), &plain), &plain), + data: plain.call_data(signed_gas() - 1), + gas_limit, + answer: too_low(signed_gas() - 1), + }, + Case { + rules: "the signer's nonce, and an occupied address", + db: occupied(system_db().account_nonce(plain.signer, 2), &plain), + data: data.clone(), + gas_limit, + answer: Answer::Refused(KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }), + }, + Case { + rules: "the signer's nonce, and a value it cannot fund", + db: system_db().account_nonce(carrying.signer, 2), + data: carrying.call_data(LARGE_OVERRIDE), + gas_limit, + answer: Answer::Refused(KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }), + }, + Case { + rules: "the signer's code, and an occupied address", + db: occupied( + system_db().account_code(plain.signer, Bytes::from_static(&[0x00])), + &plain, + ), + data, + gas_limit, + answer: Answer::Refused(KeylessDeployError::SignerHasCode), + }, + Case { + rules: "an occupied address, and a value the signer cannot fund", + db: occupied(system_db().account_nonce(carrying.signer, 1), &carrying), + data: carrying.call_data(LARGE_OVERRIDE), + gas_limit, + answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), + }, + ]; + cases.into_iter().for_each(Case::check); + } +} + /// A call that carries value and a transaction that does not decode is refused for the value: the /// value rule comes before decoding the transaction. The same call without value is refused /// `MalformedEncoding()`. Arguments that do not decode as `(bytes, uint256)` are no deployment at @@ -80,6 +183,103 @@ fn test_a_value_bearing_call_that_does_not_decode_is_refused_for_the_value() { } } +/// Pairs of failing rules one of which is the call's gas, below the execution cap, where the call +/// pays every charge out of the gas it forwards. The signer's account and the forward come before +/// the deploy address and the balance, as they did in the legacy engine; the charges of the +/// creation's start come after every rule, so a rule they would have run out of gas behind still +/// refuses the call. +#[test] +fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_balance() { + let new_account = entry(GasId::new_account_state_gas()); + // What a call left one short of the signer's account has once it paid its overhead. The cases + // that leave it are filtered out below where the account costs nothing. + let short_of_the_account = new_account.saturating_sub(1); + let plain = signed(signed_gas(), 0); + let carrying = signed(signed_gas(), 1); + let carrying_two = signed(signed_gas(), 2); + let small = signed(1_000, 0); + let small_carrying = signed(1_000, 1); + let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); + let cases = [ + Case { + rules: "the signer's account the call cannot pay, and an occupied address", + db: occupied(system_db(), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), short_of_the_account), + answer: Answer::OutOfGas, + }, + Case { + rules: "the signer's account the call cannot pay, and a value it cannot fund", + db: system_db(), + data: data(&carrying), + gas_limit: leaving(&data(&carrying), short_of_the_account), + answer: Answer::OutOfGas, + }, + Case { + rules: "a forward below the signed gas limit, and an occupied address", + db: occupied(funded(system_db(), &plain), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), signed_gas() - 1), + answer: too_low(signed_gas() - 1), + }, + Case { + rules: "a forward the signer's account takes below the signed gas limit, and an \ + occupied address", + db: occupied(system_db(), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), new_account + signed_gas() - 1), + answer: too_low(signed_gas() - 1), + }, + Case { + rules: "a forward below the signed gas limit, and a value the signer cannot fund", + db: funded(system_db(), &carrying_two), + data: data(&carrying_two), + gas_limit: leaving(&data(&carrying_two), signed_gas() - 1), + answer: too_low(signed_gas() - 1), + }, + Case { + rules: + "an occupied address, and a forward the creation's charges would take below the \ + signed gas limit", + db: occupied(funded(system_db(), &plain), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), signed_gas()), + answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), + }, + Case { + rules: "an occupied address, and creation charges the call cannot pay", + db: occupied(funded(system_db(), &small), &small), + data: data(&small), + gas_limit: leaving(&data(&small), 1_500), + answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), + }, + Case { + rules: "a value the signer cannot fund, and a forward the creation's charges would \ + take below the signed gas limit", + db: system_db(), + data: data(&carrying), + gas_limit: leaving(&data(&carrying), new_account + signed_gas()), + answer: Answer::Refused(KeylessDeployError::InsufficientBalance), + }, + Case { + rules: "a value the signer cannot fund, and creation charges the call cannot pay", + db: system_db(), + data: data(&small_carrying), + gas_limit: leaving(&data(&small_carrying), new_account + 1_500), + answer: Answer::Refused(KeylessDeployError::InsufficientBalance), + }, + ]; + // An account that costs nothing is one any call can pay for: the two cases of a signer's + // account the call cannot pay have nothing to run where a state byte is free. + let free = state_is_free(); + cases + .into_iter() + .filter(|case| { + !(free && case.rules.starts_with("the signer's account the call cannot pay")) + }) + .for_each(Case::check); +} + /// Above the execution cap the reservoir pays the signer's account, and only a signed gas limit /// near the cap leaves the forward short of it: the forward still comes before the deploy address /// and the balance. diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 4f20d3ec2..94e406548 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -16,9 +16,13 @@ use mega_evm::{ active_satin_prices, alloy_consensus::TxEip1559, constants::MAX_INITCODE_SIZE, - system::keyless::tests::{ - CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, EIP1820_CONTRACT, - EIP1820_DEPLOYER, EIP1820_TX, NON_CONTRACT_CREATION_TX, POST_EIP155_CHAIN_1_TX, + system::keyless::{ + tests::{ + CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, + EIP1820_CONTRACT, EIP1820_DEPLOYER, EIP1820_TX, NON_CONTRACT_CREATION_TX, + POST_EIP155_CHAIN_1_TX, + }, + KEYLESS_DEPLOY_OVERHEAD_GAS, }, test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError}, MegaSpecId, MegaTransactionError, TestExternalEnvs, @@ -28,6 +32,7 @@ use revm::{ CALL, CALLER, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH3, REVERT, STOP, }, context::{result::EVMError, CfgEnv}, + context_interface::cfg::GasId, primitives::KECCAK_EMPTY, state::{AccountInfo, Bytecode}, DatabaseCommit, @@ -64,6 +69,21 @@ fn small() -> Deployment { Deployment::new(deploying(&runtime(1))) } +/// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. +#[test] +fn test_keyless_deploy_gas_limit_too_low() { + for gas_limit in GAS_LIMITS { + let outcome = submit(system_db(), CREATE2_FACTORY_TX, 99_999, gas_limit); + assert_eq!( + refusal(&outcome), + KeylessDeployError::GasLimitTooLow { + tx_gas_limit: 100_000, + provided_gas_limit: 99_999 + }, + ); + } +} + /// An override equal to the signed gas limit passes rule 2, and the creation runs with exactly /// that much: signed short of what its creation spends below the execution cap, it runs out of gas /// having spent all of it. The canonical `CREATE2` factory was signed for a chain that charges no @@ -137,6 +157,31 @@ fn short_of_their_creation() -> Vec { short } +/// The gas limit at which a `keylessDeploy` of `deployment`, carrying `init_len` bytes of init +/// code, leaves the call `forward` to forward to its creation, below the execution cap, for a +/// signer that has an account and a deploy address that is empty: the reference transaction's +/// spend, the overhead, the `CREATE` opcode's regular gas, the created account and the two +/// records, and the forward. +fn gas_limit_forwarding(deployment: &Deployment, init_len: usize, forward: u64) -> u64 { + let intrinsic = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]) + .result + .gas() + .total_gas_spent(); + intrinsic + + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(init_len) + + entry(GasId::create_state_gas()) + + 2 * record() + + forward +} + +/// A signed gas limit the signer's account can take the forward below: 500,000 on top of the +/// account's state gas at the byte prices in effect, so the call can pay for the account out of +/// the forward whatever a state byte costs. +fn signed_above_the_account() -> u64 { + 500_000 + entry(GasId::new_account_state_gas()) +} + /// Rule 3: the signer is recovered from the signature. `r` above the curve order recovers /// nothing. #[test] @@ -149,6 +194,24 @@ fn test_keyless_deploy_invalid_signature() { } } +/// So does `r = 0`, which no signature has. +#[test] +fn test_keyless_deploy_rejects_corrupted_signature() { + for gas_limit in GAS_LIMITS { + let signed = mega_evm::system::keyless::decode_keyless_tx(CREATE2_FACTORY_TX).unwrap(); + let s = signed.signature().s(); + let corrupted = Signed::new_unchecked( + signed.tx().clone(), + Signature::new(U256::ZERO, s, false), + B256::ZERO, + ); + let mut encoded = Vec::new(); + corrupted.rlp_encode(&mut encoded); + let outcome = submit(system_db(), &encoded, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); + } +} + /// A different `s` is a different signer, not an invalid signature: the deployment goes to that /// signer's address, never to the canonical one. #[test] @@ -168,6 +231,21 @@ fn test_keyless_deploy_modified_s_changes_signer() { } } +/// The transaction must be RLP a legacy transaction decodes from. +#[test] +fn test_keyless_deploy_malformed_encoding() { + for gas_limit in GAS_LIMITS { + for garbage in [&[0xde, 0xad, 0xbe, 0xef][..], &[], &CREATE2_FACTORY_TX[..100]] { + let outcome = submit(system_db(), garbage, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "{garbage:02x?}"); + } + let mut trailing = CREATE2_FACTORY_TX.to_vec(); + trailing.push(0x00); + let outcome = submit(system_db(), &trailing, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "a trailing byte"); + } +} + /// An EIP-2718 typed envelope is not a legacy transaction. #[test] fn test_keyless_deploy_rejects_eip2718_typed_envelope() { @@ -213,6 +291,18 @@ fn test_keyless_deploy_not_pre_eip155() { } } +/// The transaction must be signed at nonce 0: the deploy address is the signer's first. +#[test] +fn test_keyless_deploy_non_zero_tx_nonce() { + for gas_limit in GAS_LIMITS { + let deployment = + Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); + assert_nothing_written(&outcome, &deployment, 0); + } +} + /// Rule 8: the init code is within the initcode size limit the spec fixes. #[test] fn test_init_code_over_the_limit_is_refused() { @@ -247,6 +337,18 @@ fn test_init_code_at_the_limit_is_admitted() { } } +/// Rule 4: the signer's nonce is at most 1. +#[test] +fn test_keyless_deploy_signer_nonce_too_high() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_nonce(deployment.signer, 2); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); + assert_nothing_written(&outcome, &deployment, 2); + } +} + /// The two canonical keyless deployments: the transaction, the gas limit it was signed with, its /// signer and the address it deploys at. Signed for chains that charge no state gas for deployed /// code: at the spec's prices, without a reservoir, the signed gas limit does not cover the code @@ -356,6 +458,56 @@ fn test_a_resubmission_after_failures_and_a_deployment_finds_the_address_taken() } } +/// A deployment that succeeds from nonce 1 leaves the signer at 1 too: the creation's bump goes +/// with its record, so the deployment costs exactly one record's history less than the same one +/// from nonce 0, which keeps its bump. The record stays when the creation moved value out of the +/// signer's account, and then stands for that write. +#[test] +fn test_a_success_from_nonce_one_leaves_the_nonce_at_one() { + for gas_limit in GAS_LIMITS { + for (value, kept) in [(U256::ZERO, 0), (U256::ONE, 1)] { + let deployment = Deployment::with_value(deploying(&runtime(1)), value); + let funded = db_for(&deployment, U256::from(1_000)); + let at_zero = deploy(funded.clone(), &deployment, gas_limit); + let at_one = deploy(funded.account_nonce(deployment.signer, 1), &deployment, gas_limit); + assert_eq!(returned(&at_one).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(at_one.usage.write_records, 1 + kept, "value {value} at {gas_limit}"); + let taken_back = 1 - kept; + assert_eq!( + beyond(&at_zero, &at_one), + [taken_back * record(), 0, 0, taken_back * record(), taken_back * 40], + "value {value} at {gas_limit}", + ); + } + } +} + +/// A deployment that fails from nonce 1 keeps nothing of the signer: its records, its data size, +/// its history gas and its history bytes are those of a transaction that bumped no nonce — the +/// reference, which pays the same intrinsic gas and writes nothing — and it spends exactly one +/// record's history less than the same failure from nonce 0, which keeps its bump. +#[test] +fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for gas_limit in GAS_LIMITS { + let at_one = + deploy(system_db().account_nonce(deployment.signer, 1), &deployment, gas_limit); + let at_zero = deploy(db_for(&deployment, U256::ONE), &deployment, gas_limit); + assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); + + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [_, _, state, history_gas, history_bytes] = beyond(&at_one, &reference); + assert_eq!([state, history_gas, history_bytes], [0; 3], "at {gas_limit}"); + assert_eq!(at_one.usage, reference.usage, "at {gas_limit}"); + + assert_eq!(at_zero.usage.write_records, 1, "the signer's nonce record"); + assert_eq!(beyond(&at_zero, &at_one), [record(), 0, 0, record(), 40], "at {gas_limit}"); + } +} + /// However a deployment from nonce 1 fails — its init code reverts or halts, it deploys no code, /// or a limit stops its creation at its start — the signer stays at 1 and its nonce record goes. /// A creation that deployed no code is refused its empty deposit and reverts, so it keeps neither @@ -432,6 +584,18 @@ fn test_a_signer_that_sends_its_failing_deployment_ends_at_nonce_one() { } } +/// Rule 9: the signer has no code — EIP-3607 for a sender that is not the transaction's. +#[test] +fn test_a_signer_with_code_is_refused() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerHasCode); + assert_nothing_written(&outcome, &deployment, 0); + } +} + /// A chain that disables EIP-3607 disables rule 9 with it, as it does for its own transactions. #[test] fn test_disabling_eip3607_disables_the_signer_code_rule() { @@ -479,6 +643,30 @@ fn test_a_disabled_eip3607_reads_no_signer_code() { } } +/// An EIP-7702 delegation is not code: a signer that delegated deploys. +#[test] +fn test_a_delegated_signer_deploys() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let delegation = + Bytecode::new_eip7702(address!("0x00000000000000000000000000000000000d1e6a")); + let mut db = system_db(); + db.insert_account_info( + deployment.signer, + AccountInfo { + balance: U256::ZERO, + nonce: 1, + code_hash: delegation.hash_slow(), + code: Some(delegation), + ..Default::default() + }, + ); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + /// A delegated signer's own code can spend its nonces while its deployment runs: a constructor /// that calls the signer runs the delegation, which creates two accounts at the signer's next /// nonces. Those stay spent, and so does the creation's own bump below them — the settlement @@ -620,6 +808,23 @@ fn test_a_delegated_signer_whose_creation_reverts_keeps_every_bump() { } } +/// Rule 5: the deploy address holds no code. The occupancy read goes through the journal, so the +/// deploy address is in the transaction's state — the witness a stateless client replays the +/// refusal from — even though the call reverts. +#[test] +fn test_keyless_deploy_contract_already_exists() { + let db = system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); + for gas_limit in GAS_LIMITS { + let outcome = submit(db.clone(), CREATE2_FACTORY_TX, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists, "at {gas_limit}"); + assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 0); + assert!( + outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT), + "the occupancy read is in the witness, at {gas_limit}", + ); + } +} + /// A second deployment of the same transaction finds its address taken. #[test] fn test_keyless_deploy_twice_fails_second_time() { @@ -634,6 +839,18 @@ fn test_keyless_deploy_twice_fails_second_time() { } } +/// Rule 6: the signer funds the transaction's value, and nothing else. A signer with nothing is +/// refused a deployment that carries a value. +#[test] +fn test_keyless_deploy_insufficient_balance_zero() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + assert_nothing_written(&outcome, &deployment, 0); + } +} + /// A signer holding part of the value is refused too, and the refusal writes nothing. #[test] fn test_keyless_deploy_insufficient_balance_partial() { @@ -646,6 +863,50 @@ fn test_keyless_deploy_insufficient_balance_partial() { } } +/// A signer holding exactly the value deploys, and the value moves to the contract. +#[test] +fn test_keyless_deploy_balance_exactly_sufficient() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(10)); + let outcome = + submit(db_for(&deployment, U256::from(10)), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); + assert_eq!(balance(deployment.signer), Some(U256::ZERO)); + assert_eq!(balance(deployment.address), Some(U256::from(10))); + } +} + +/// The signer's account is charged exactly when its nonce is spent: a refused call does neither, +/// a deployment that fails at run time does both. +/// +/// The refusal runs below the execution cap, as the refusals above; the failure runs at both. +#[test] +fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { + let signed = signed_above_the_account(); + let deployment = + Deployment::signed(0, signed, U256::ZERO, Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + // An account that costs nothing takes nothing from the forward, and refuses nothing. + if !state_is_free() { + let refused = submit( + system_db(), + &deployment.tx, + LARGE_OVERRIDE, + gas_limit_forwarding(&deployment, 3, signed), + ); + assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); + assert_eq!(nonce(&refused, deployment.signer), 0); + assert_eq!(refused.gas.state, 0); + } + + for gas_limit in GAS_LIMITS { + let failed = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(failure(&failed), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&failed, deployment.signer), 1); + assert_eq!(failed.gas.state, entry(GasId::new_account_state_gas())); + } +} + /// A database read a rule needs fails the transaction with the database's error: the deploy /// address's, whose occupancy rule 5 reads. #[test] From 66df3ca2d2dd3399bc7b405b7718f288a78086bd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 20:08:49 +0800 Subject: [PATCH 143/190] test: reword doc comments that leaned on removed tests Six doc comments opened on the test that preceded them, which is gone; each now says what its own test pins. The schedule tests' module doc lists what the file holds. --- crates/mega-evm/tests/satin/history_gas.rs | 3 ++- crates/mega-evm/tests/satin/inherited_costs.rs | 2 +- crates/mega-evm/tests/satin/schedule.rs | 14 +++++++------- crates/mega-evm/tests/system/keyless/deploy.rs | 2 +- crates/mega-evm/tests/system/oracle.rs | 5 +++-- 5 files changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 2d2bba0b1..2918a4d34 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -75,7 +75,8 @@ fn caller_running(code: Bytes) -> MemoryDatabase { funded().account_balance(CALLEE, U256::from(10_000_000)).account_code(CALLEE, code) } -/// The same for a creation, whose start records the created account and the creator's nonce. +/// A creator that cannot pay the records its creation's start makes, the created account's and its +/// own nonce's, halts without starting the creation, and the transaction pays for its body alone. #[test] fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { if runs_at_measurement_prices() { diff --git a/crates/mega-evm/tests/satin/inherited_costs.rs b/crates/mega-evm/tests/satin/inherited_costs.rs index 5e637884e..f805fc6ad 100644 --- a/crates/mega-evm/tests/satin/inherited_costs.rs +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -77,7 +77,7 @@ fn test_the_first_call_to_an_address_nothing_warmed_is_charged_cold() { assert_eq!(first_call_over_second(CALL, EXISTING, plain), cold_over_warm() as i64); } -/// So does the first `STATICCALL`. +/// The first `STATICCALL` to a precompile is charged warm, as the control above is charged cold. #[test] fn test_the_first_staticcall_to_a_precompile_is_charged_warm() { assert_eq!(first_call_over_second(STATICCALL, IDENTITY, plain), 0); diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index f2a5ae9bc..035cf994b 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -1,12 +1,12 @@ //! What the Satin gas schedule charges, measured on real transactions. //! -//! The intrinsic numbers, the state gas a new slot and a new account draw, and the Amsterdam -//! opcodes the schedule brings with it. Each number is read off a transaction the engine ran, not -//! computed from the schedule, so a change to either side shows up here. +//! What init code costs as transaction data, the state gas a `CREATE` frame rejected for its +//! deployed code gives back, and the Amsterdam opcodes the schedule brings with it. Each number is +//! read off a transaction the engine ran, not computed from the schedule, so a change to either +//! side shows up here. //! //! Every transaction also pays the history gas of its body, which is not a schedule entry and is -//! priced by the history mechanism. The numbers below are what is left once that ledger is taken -//! out ([`Spend::schedule_gas`]); what the body costs is pinned in `history_gas.rs`. +//! priced by the history mechanism; the figures below take it from the transaction's own ledgers. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; @@ -104,8 +104,8 @@ fn depositing_an_ef_byte() -> Bytes { .build() } -/// The same from a `CREATE` frame: the frame fails and returns the zero address, the transaction -/// around it goes through, and the state gas the frame took upfront is back. +/// A `CREATE` frame whose deployed code starts with `0xEF` fails and returns the zero address, the +/// transaction around it goes through, and the state gas the frame took upfront is back. #[test] fn test_a_create_frame_rejected_for_its_first_byte_draws_no_state_gas() { let init_code = depositing_an_ef_byte(); diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 14b022c5f..8e582585e 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -767,7 +767,7 @@ fn assert_beneficiary_paid(init_code: Bytes) { ); } -/// And for one that fails. +/// The beneficiary is paid for a deployment whose creation fails, as for one that succeeds. #[test] fn test_beneficiary_receives_fees_on_execution_failure() { assert_beneficiary_paid(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 44ec25209..b678b2703 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -125,8 +125,9 @@ fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) } -/// The same unfunded call under a data-size limit its input would cross is answered with the -/// stop, not with the funds failure: nothing is forwarded and nothing is counted. +/// A value-bearing `sendHint` its caller cannot fund, under a data-size limit its input would +/// cross, is answered with the stop, not with the funds failure: nothing is forwarded and nothing +/// is counted. #[test] fn test_an_unfunded_value_hint_over_the_limit_is_answered_with_the_stop() { let data = send_hint(b"unfunded"); From 1496c8cca2b1bf561b60c56eddf3403e8bc73f65 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 22:47:25 +0800 Subject: [PATCH 144/190] test(keyless): restore the test whose returned code hash no conformance case pins It asserts the deployed account's code hash as the outcome returns it; the conformance suite's adapter exports the code's bytes and no hash. --- crates/mega-evm/tests/system/keyless/deploy.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 8e582585e..601bc4650 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -78,6 +78,20 @@ fn test_keyless_deploy_eip1820() { } } +/// A deployment lands at the signer's first creation address, whoever the signer is, and the +/// deployed code is the runtime the init code returned. +#[test] +fn test_the_deploy_address_is_the_signers_first_creation_address() { + for gas_limit in GAS_LIMITS { + for len in [1, 2, 3] { + let deployment = Deployment::new(deploying(&runtime(len))); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.signer.create(0)); + assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&runtime(len)))); + } + } +} + /// The hash of `code`. fn keccak(code: &[u8]) -> B256 { alloy_primitives::keccak256(code) From 03591f411d4c39617c6615a10f9a6107ed96811e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 22:47:25 +0800 Subject: [PATCH 145/190] test(write-records): restore the test whose halting write-back child no conformance case pins A DELEGATECALLed child writes a fresh slot back and halts, and the parent catches the halt and keeps its record and one unit of growth; no case runs that combination. --- crates/mega-evm/tests/satin/write_records.rs | 34 ++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index bd1e22e9e..894f39843 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, - LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, + JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -557,6 +557,36 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { ); } +/* ---------- storage, logs, selfdestruct ---------- */ + +/// A write-back in a child refunds the record its caller made, and the refund dies with a +/// failing child. +#[test] +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(); + // 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() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build(); + let db = + MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(result.result.is_success()); + assert_eq!(usage, expected); + } +} + /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. From 377cf20d44755264d2bcd46e51457cb459c0e098 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 22:47:25 +0800 Subject: [PATCH 146/190] test(system): restore system-transaction tests whose fresh Oracle slot no conformance case pins Both run a system transaction that writes a fresh Oracle slot, from a caller it creates and from an existing one; the conformance cases of a promoted transaction only read the Oracle. --- crates/mega-evm/tests/system/system_tx.rs | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index eb8e77913..75aca18be 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -755,6 +755,40 @@ fn test_a_system_transaction_short_of_its_body_history_is_a_failed_deposit() { assert_eq!(gas.gas_used, least); } +/// A deposit-like transaction whose caller does not exist yet creates that account, and pays +/// the account-creation charge for it exactly once: the same charge a value transfer to a +/// fresh account pays. +#[test] +fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { + // The reference charge: a user transaction that creates one account by sending value to it. + let fresh = address!("0x00000000000000000000000000000000000f0001"); + let reference = + run_outcome(chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), { + let mut tx = legacy_tx(CALLER, TxKind::Call(fresh), Bytes::new(), 0); + tx.0.base.value = U256::from(1); + tx + }); + let one_account = reference.gas.state; + assert_eq!(one_account, account_state_gas(), "a fresh recipient costs state gas"); + + // A system transaction whose sender does not exist yet creates it, for the same charge. + let created = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x77))); + assert!(created.result.is_success(), "{:?}", created.result); + // The same transaction from a sender that already exists: what it pays is the slot it + // writes, and nothing for its own account. + let slot_charge = run_outcome( + chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), + system_tx(0, B256::with_last_byte(0x77)), + ) + .gas + .state; + assert_eq!( + created.gas.state - slot_charge, + one_account, + "the caller's account costs one account creation, and the slot the same either way", + ); +} + /// A deposit whose recipient is its own caller pays for that one account once: by the time the /// recipient is looked at, the caller's materialisation has created it. #[test] @@ -894,6 +928,27 @@ 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. 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))); + let existing = run_outcome( + chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), + system_tx(0, B256::with_last_byte(0x99)), + ); + assert!(fresh.result.is_success() && existing.result.is_success()); + assert_eq!( + (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 /// caller as well as for the contract. #[test] From 256b215a67c83acdae8e269408509abe616967c4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 23:08:33 +0800 Subject: [PATCH 147/190] test(limits): restore the test whose outer halt reason no conformance case pins Its factory halts on its own INVALID when the CREATE past the code-size limit returns zero, and the test requires that halt; the conformance case returns the zero instead, and the adapter reports no halt reason. --- crates/mega-evm/tests/satin/contract_size.rs | 49 +++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs index 703e5420b..823462310 100644 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -13,13 +13,14 @@ use mega_evm::{ MegaEvm, MegaHaltReason, MegaTransaction, }; use revm::{ - bytecode::opcode::{PUSH1, RETURN, STOP}, + bytecode::opcode::{CREATE, INVALID, ISZERO, JUMPDEST, JUMPI, PUSH1, RETURN, STOP}, context::result::{ExecutionResult, HaltReason, InvalidTransaction}, }; -use crate::common::{context, create, history}; +use crate::common::{call, context, create, history}; const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const FACTORY: Address = address!("0000000000000000000000000000000000100001"); /// Room for everything a creation here draws, all of it above the execution cap so it comes out of /// the reservoir: the state gas of the largest deployable code, the history of that code and of a @@ -109,3 +110,47 @@ fn test_one_byte_past_the_satin_initcode_size_is_rejected() { fn test_one_byte_past_the_satin_code_size_halts() { assert_code_size_limit(deploy(constructor_returning(MAX_CONTRACT_SIZE + 1))); } + +/* ---------- the deployed-code bound, from a CREATE ---------- */ + +/// A contract that `CREATE`s a contract of `size` bytes and runs `INVALID` if the creation failed, +/// so a rejected creation shows up as a halt of the outer frame. +fn factory_creating(size: usize) -> Bytes { + let init_code = constructor_returning(size); + let code = BytecodeBuilder::default() + .mstore(0, &init_code) + .push_number(init_code.len() as u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .append(ISZERO); + let len = code.len(); + code.push_number(len as u8 + 4) + .append(JUMPI) + .append(STOP) + .append(JUMPDEST) + .append(INVALID) + .build() +} + +/// Runs a factory that creates `size` bytes of code and returns whether the creation succeeded. +fn create_through_factory(size: usize) -> bool { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(FACTORY, factory_creating(size)); + let result = + run(call(CALLER, FACTORY, U256::ZERO, gas_limit()), db).expect("the transaction is valid"); + match result { + ExecutionResult::Success { .. } => true, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::InvalidFEOpcode), .. + } => false, + other => panic!("unexpected result {other:?}"), + } +} + +/// One byte past it fails the creation, which the factory turns into a halt. +#[test] +fn test_create_one_byte_past_the_satin_code_size_fails() { + assert!(!create_through_factory(MAX_CONTRACT_SIZE + 1)); +} From 5fe60b150d1a7e136088b8cf70dd26b7267ede57 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 23:08:33 +0800 Subject: [PATCH 148/190] test(history): restore tests whose LOG3 events or combined deposit program no conformance case pins The allowance tests emit a three-topic event of one word, where the conformance cases emit empty LOG0s, and the deposit test runs a fresh slot, a log, a value call and a creation in one program, which no deposit case combines. --- .../mega-evm/tests/satin/history_allowance.rs | 68 ++++++++++++++++++- .../mega-evm/tests/satin/history_exemption.rs | 14 ++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/history_allowance.rs b/crates/mega-evm/tests/satin/history_allowance.rs index cd39d7873..241734b01 100644 --- a/crates/mega-evm/tests/satin/history_allowance.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -24,7 +24,9 @@ use mega_evm::{ constants::COST_PER_HISTORY_BYTE, history_allowance_gas, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{is_transfer_log, note_price_guard, BytecodeBuilder, MemoryDatabase}, + test_utils::{ + is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, + }, EvmTxRuntimeLimits, LimitKind, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, HISTORY_ALLOWANCE_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; @@ -123,6 +125,52 @@ fn test_the_allowance_is_one_three_topic_event_of_history() { 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 +/// `receive()` hook that emits one event, and the event's history costs the sender nothing beyond +/// the two write records the transfer itself writes. +/// +/// Without the allowance the event's 160 bytes would have to come out of the 2,300, which does +/// not cover them at any price a history byte is worth. +#[test] +fn test_a_transfer_can_emit_one_event_because_of_the_allowance() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); + let receiver = event().append(STOP).build(); + let outcome = execute(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); + assert_eq!( + outcome.result.logs()[0], + transfer_log(SENDER, RECEIVER, U256::from(1)), + "after the transfer's own log, which took nothing from the allowance", + ); + assert_eq!( + outcome.gas.history, + body() + 2 * record(), + "the body and the transfer's two records; the event's bytes the allowance paid for", + ); +} + +/// One event is all it buys: a second one has to come out of the 2,300 gas, which cannot cover +/// it, so the hook runs out of gas and the transfer fails. +#[test] +fn test_the_allowance_buys_one_event_and_no_more() { + if runs_at_measurement_prices() { + return; + } + // The caller records whether the transfer succeeded, then stops. + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); + let two_events = event().append_many(event().build().iter().copied()).append(STOP).build(); + let outcome = execute(db(sender, two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "the caller survives the hook's failure"); + assert!(outcome.result.logs().is_empty(), "the hook ran out and kept neither event"); + assert_eq!(outcome.gas.history, body(), "and the transfer's records came back with it"); +} + /// A sender that makes one value transfer to [`RECEIVER`], forwarding `gas` beside the 2,300 the /// transfer's stipend adds, and returns the call's success flag. fn transfer_returning_its_flag(gas: u64) -> Bytes { @@ -644,6 +692,24 @@ fn test_a_drained_allowance_is_not_refunded_by_a_revert() { ); } +/// A call that forwards no gas at all still reaches a `receive()` hook that emits one event: the +/// EVM's own `CALL_STIPEND` pays for the computation and the allowance for the bytes. +#[test] +fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, 0).append(STOP).build(); + let outcome = execute( + db(sender, event().append(STOP).build()), + call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), + ); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); + assert_eq!(outcome.gas.history, body() + 2 * record()); +} + /* ---------- an inspector that replaces the interpreter ---------- */ /// Replaces the interpreter of every frame running `target`'s code, as revm initialises it, with diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 9bbacddd1..9526fddba 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -187,6 +187,20 @@ fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { assert_eq!(evm.ctx().additional_limit().history_gas_spent(), 0); } +/// A deposit pays for its body, calldata, records, logs and deployed code even without a fee. +#[test] +fn test_a_deposit_pays_history_gas() { + if runs_at_measurement_prices() { + return; + } + let mut tx = deposit(call_from(CALLER, CONTRACT)); + tx.0.base.data = Bytes::from_static(b"history"); + let (history, state, outcome) = ledgers(tx); + assert_eq!(history, (PROGRAM_HISTORY_BYTES + 7) * COST_PER_HISTORY_BYTE); + assert_eq!(state, PROGRAM_STATE_GAS, "the state a user transaction pays"); + assert_eq!(outcome.gas.history_bytes, PROGRAM_HISTORY_BYTES + 7); +} + /// Both field-based forms of system origin pay every history site, including deposited code. #[test] fn test_system_originated_transactions_pay_history_for_the_program() { From 77dd990b2a5bad74cf288e5c1ca5e54d1fa161da Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 23:08:33 +0800 Subject: [PATCH 149/190] test(write-records): restore tests whose new recipients, frame endings or unchanged entries no conformance case pins These pay value to accounts the transfer creates, end a first child with a halt, create from a transaction whose init code halts, or index the returned entries of accounts the transaction left unchanged; the conformance cases pay existing accounts, end the child with a revert, fail the creation later, or drop unchanged accounts from the state. --- crates/mega-evm/tests/satin/write_records.rs | 268 ++++++++++++++++++- 1 file changed, 266 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 894f39843..3abd47551 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,9 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, - JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, + JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, + STOP, }, context::ContextTr, interpreter::{ @@ -95,6 +96,50 @@ fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) } +/* ---------- value transfers and creations: a record per account that changed ---------- */ + +/// 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, value_call_room()), + ); + assert!(result.result.is_success()); + assert_eq!( + usage, + 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 @@ -141,6 +186,33 @@ fn body_and_records(records: u64) -> u64 { history(TX_BODY_SIZE + 1 + records * WRITE_RECORD_SIZE) } +/// 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 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 @@ -436,6 +508,24 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { } } +/// A creation and a value transfer from one frame record the frame's account once. +#[test] +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, value_call_room()), + ); + assert!(result.result.is_success()); + assert_eq!( + usage, + 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" + ); +} + /// Two creations from one frame record the creator once and each created account. #[test] fn test_two_creates_record_the_creator_once() { @@ -454,6 +544,36 @@ fn test_two_creates_record_the_creator_once() { ); } +/// After a failed transfer the sender can be recorded again by the next one. +/// +/// The first child burns the gas it was forwarded, so the second transfer forwards none: its +/// recipient runs no code, and the records it makes are paid out of what the caller keeps, which +/// then does not depend on the price of the recipient's new account. +#[test] +fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + let code = code + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(CONTRACT2) + .append(PUSH0) + .append(CALL) + .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, value_call_room())); + assert!(result.result.is_success()); + assert_eq!( + usage, + 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 { @@ -507,10 +627,46 @@ fn reverting_creations(n: usize) -> Bytes { code.into() } +/// A creation the creator cannot fund never starts (the opcode checks the endowment before it +/// builds a frame), so it records nothing. +#[test] +fn test_creation_without_funds_records_nothing() { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_000_000_000_000_u64) + .append(CREATE) + .append(POP) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + 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"); +} + const A: Address = address!("00000000000000000000000000000000A0000001"); const B: Address = address!("00000000000000000000000000000000B0000002"); 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), 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) +} + +/// A top-level transfer to another account records the recipient. +#[test] +fn test_top_level_transfer_counts_the_recipient() { + 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 /// calldata stops at once. fn self_calling_code(targets: &[Address], value: u64) -> Bytes { @@ -587,6 +743,25 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { } } +/// A top-level creation records the created account, and nothing when it fails. +#[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]), value_call_room()), + ); + assert!(result.result.is_success()); + 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]), value_call_room()), + ); + assert!(!result.result.is_success()); + assert_eq!(usage, with_extra(body_only(), 1)); +} + /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. @@ -839,6 +1014,46 @@ fn authorizing_call( ) } +/// A value transfer to an applied authority records the authority once, not again as the +/// recipient. +#[test] +fn test_value_to_an_applied_authority_records_it_once() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + usage, + 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 + // authority's account is already written. A transfer to an account that is not an authority + // pays for the recipient on top of the one authority it applied. + if crate::common::runs_at_measurement_prices() { + return; + } + const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; + let to_authority = + crate::common::execute(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + let to_another = + crate::common::execute(db(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)])); + let body = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE; + + assert!(to_another.result.is_success(), "{:?}", to_another.result); + assert_eq!( + to_authority.gas.history, + (body + WRITE_RECORD_SIZE) * CPHB, + "the authority's record, and no recipient record beside it", + ); + assert_eq!( + to_another.gas.history, + (body + 2 * WRITE_RECORD_SIZE) * CPHB, + "the authority's record and the recipient's", + ); +} + /// A frame running as the transaction's sender (a delegated sender called back) records no /// write to the sender's account: the transaction body counts it. #[test] @@ -1200,6 +1415,32 @@ fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authoriti const D: Address = address!("00000000000000000000000000000000000000D1"); +/// 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 = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); + 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, + 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 has its own account unchanged, whatever its caller's state: its /// first value transfer records it. #[test] @@ -1351,6 +1592,29 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { ); } +/// 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) + .append(POP) + .append(STOP) + .build(); + let mut db = funded().account_code(CONTRACT, sender_code); + let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); + 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, value_call_room())); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + 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. struct AnswerContract; From fad164a87ec8151da933122c4a1e4e64faa5e698 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 23:08:33 +0800 Subject: [PATCH 150/190] test(system): restore Oracle tests whose ordinary-transaction revert or hint order no conformance case pins An ordinary transaction's hints that survive its own revert, and two hints in order from an ordinary transaction, are observed by no case: the only case with two hints is a failed deposit, and none with a hint reverts. --- crates/mega-evm/tests/system/oracle.rs | 89 ++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index b678b2703..03349eb35 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -87,6 +87,37 @@ fn try_run_with_oracle_under( Some((outcome, envs.recorded_hints())) } +/// A call that carries value is judged on its gas like any other, and a call that requests none +/// still holds the value call's stipend, so its hint is admitted. `sendHint` is not payable, so +/// the bytecode refuses the value; the hint is a message to the service and was already sent, and +/// its bytes stay counted. +#[test] +fn test_a_value_bearing_call_forwards_its_hint() { + use revm::bytecode::opcode::{POP, PUSH0, REVERT}; + + let data = send_hint(b"paid"); + let code = BytecodeBuilder::default() + .mstore(0x0, &data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(1_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(0_u64) // gas: none requested, the stipend is all the call holds + .append(CALL) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(!result.result.is_success(), "the frame that sent the hint reverted"); + assert_eq!(hints.len(), 1, "the hint reached the service"); + assert_eq!(hints[0].from, CONTRACT); + assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); +} + /// Code that calls the Oracle with `data`, one unit of value and no requested gas, and returns /// the call's status followed by its return data. The contract holds no balance, so the call /// cannot be funded. @@ -282,6 +313,39 @@ fn test_reading_a_slot_runs_the_bytecode() { ); } +/// A hint cannot be un-sent, so the bytes it cost stay counted even when the frame that sent it +/// reverts and takes its writes back. +#[test] +fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { + use revm::bytecode::opcode::{POP, PUSH0, REVERT}; + + let data = send_hint(b"a hint that was sent"); + let code = BytecodeBuilder::default() + .mstore(0x0, &data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(200_000_u64) + .append(CALL) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(!result.result.is_success(), "the frame that sent the hint reverted"); + assert_eq!(hints.len(), 1, "the hint reached the service before the revert"); + assert_eq!( + usage.data_size, + nested_hint(data.len() as u64), + "the bytes stay counted: a revert cannot take the hint back", + ); +} + /// A payload that does not fit in what is left of the transaction's data-size limit is not /// forwarded, and the crossing stops the transaction: the limit is checked on the hint's bytes /// before the payload is decoded, so it is crossed before the frame the call would have started. @@ -394,6 +458,31 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } +/// Two hints reach the service in the order they were sent. +#[test] +fn test_hints_reach_the_service_in_the_order_they_were_sent() { + use revm::bytecode::opcode::POP; + + let first = IOracle::sendHintCall { + topic: B256::repeat_byte(0x11), + data: Bytes::from_static(&[0xaa, 0xbb]), + }; + let second = IOracle::sendHintCall { + topic: B256::repeat_byte(0x22), + data: Bytes::from_static(&[0xcc, 0xdd]), + }; + let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); + let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); + let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!( + hints, + vec![ + RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, + RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, + ], + ); +} + /// A malformed `sendHint` payload, and one followed by bytes the decoder drops, are counted /// whole: the first forwards nothing, the second forwards its envelope. Under a limit that holds /// half of the payload, both are stopped before anything is forwarded: the call is answered with From b217d7e9c63daa3bc91c04594a2b3d39fff28544 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Tue, 17 Nov 2026 23:08:33 +0800 Subject: [PATCH 151/190] test(keyless): restore tests whose decoded refusal or returned code hash no conformance case pins They read the refusal through the engine's keyless error decoder and the deploy address's returned code hash; the conformance suite's adapter calls no decoder and exports no hash. --- .../tests/system/keyless/precedence.rs | 33 ++++++++ crates/mega-evm/tests/system/keyless/rules.rs | 76 +++++++++++++++++++ 2 files changed, 109 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 65c8cf505..0c6808565 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -316,6 +316,39 @@ fn test_the_forward_comes_before_the_address_and_the_balance_above_the_cap() { } } +/// What the `CREATE` opcode charges the call for the creation's start can refuse a call no rule +/// refuses: a call that cannot pay it runs out of gas, and one it leaves short of the signed gas +/// limit is refused `GasLimitTooLow` with what it left. The legacy engine charged none of it to +/// the call, and ran such a deployment in its sandbox on what the call had. Above the execution +/// cap the refusal is +/// `limits::test_a_refusal_after_the_creations_charges_gives_the_reservoir_back`. +#[test] +fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { + let plain = signed(signed_gas(), 0); + let small = signed(1_000, 0); + let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); + let charges = create_regular(deploying(&runtime(1)).len()) + + entry(GasId::create_state_gas()) + + 2 * record(); + let cases = [ + Case { + rules: "creation charges the call cannot pay", + db: funded(system_db(), &small), + data: data(&small), + gas_limit: leaving(&data(&small), 1_500), + answer: Answer::OutOfGas, + }, + Case { + rules: "a forward the creation's charges take below the signed gas limit", + db: funded(system_db(), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), signed_gas()), + answer: too_low(signed_gas() - charges), + }, + ]; + cases.into_iter().for_each(Case::check); +} + /// An out-of-gas at step 14 halts the call, consuming its regular gas, and gives back the state /// and history gas the call was charged: the transaction's gas used is its gas limit, its state /// ledger is empty and its history ledger is its body's. diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 94e406548..c613e6403 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -182,6 +182,31 @@ fn signed_above_the_account() -> u64 { 500_000 + entry(GasId::new_account_state_gas()) } +/// The length of the init code the forwarding tests deploy: a one-byte runtime. +fn one_byte_init_len() -> usize { + deploying(&runtime(1)).len() +} + +/// Rule 2 again, once the call has paid for the creation's start: the override is capped to what +/// the call has left, and the capped gas must still cover the signed gas limit. A relayer that +/// sizes its transaction below that is refused, with the capped figure. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself +/// and the reservoir pays the call's state and history charges, so no gas limit leaves the +/// call this little. The refusal above the cap is +/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. +#[test] +fn test_a_forward_capped_below_the_signed_gas_limit_is_refused() { + let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 499_999); + let outcome = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!( + refusal(&outcome), + KeylessDeployError::GasLimitTooLow { tx_gas_limit: 500_000, provided_gas_limit: 499_999 }, + ); + assert_nothing_written(&outcome, &deployment, 0); +} + /// Rule 3: the signer is recovered from the signature. `r` above the curve order recovers /// nothing. #[test] @@ -877,6 +902,57 @@ fn test_keyless_deploy_balance_exactly_sufficient() { } } +/// A call that cannot pay for the signer's account runs out of gas before the creation starts: +/// no nonce is bumped and nothing is deployed. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself, +/// and the reservoir pays the state charges, so no gas limit leaves the call this little. +#[test] +fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { + // An account that costs nothing is one any call can pay for. + if state_is_free() { + return; + } + let deployment = small(); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]); + let intrinsic = reference.result.gas().total_gas_spent(); + // One short of the account, once the overhead is paid. + let short = entry(GasId::new_account_state_gas()) - 1; + let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS + short; + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); + assert_nothing_written(&outcome, &deployment, 0); + assert_eq!(outcome.gas.state, 0, "the halt takes the charges back"); +} + +/// A call refused after it paid for the creation's start — the forward capped below the signed +/// gas limit — keeps none of its state and history: no account was added, so neither the signer's +/// account nor the created one is charged, the refusal writes nothing, and no record is kept. The +/// regular gas the `CREATE` opcode charged stays spent, as the overhead does. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself +/// and the reservoir pays the call's state and history charges, so no gas limit leaves the +/// call this little. The refusal above the cap is +/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. +#[test] +fn test_a_call_refused_after_its_charges_keeps_their_regular_gas_alone() { + // An account that costs nothing takes nothing from the forward. + if state_is_free() { + return; + } + let signed = signed_above_the_account(); + let deployment = Deployment::signed(0, signed, U256::ZERO, deploying(&runtime(1))); + // Enough for everything but the signer's account, which the empty signer adds. + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), signed); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(refusal(&outcome), KeylessDeployError::GasLimitTooLow { .. })); + let [total, regular, state, history_gas, _] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(one_byte_init_len()); + assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); + assert_nothing_written(&outcome, &deployment, 0); +} + /// The signer's account is charged exactly when its nonce is spent: a refused call does neither, /// a deployment that fails at run time does both. /// From e4db24232fdd9f6d2cc73d584428a8cf368fe9d3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:11:23 +0800 Subject: [PATCH 152/190] test(mega-eest): move the conformance suite pin to fb0a46a --- scripts/mega_eest.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index 32c7267c6..c0617d66c 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -8,14 +8,14 @@ # pinned here. A commit off the default branch (a suite change still under review) keeps the gate # red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest -MEGA_EEST_REV=5e4007b47ce62c2af2b7bf770677b0e6baf1a8d2 +MEGA_EEST_REV=fb0a46a544bb2599b6ad88da6f861ed47b40424f # The case ids the pin's last move removed, and those it changed under their ids (another file # digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice # drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none # leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a # change is a line the reviewer reads in this file's diff. MEGA_EEST_REMOVED_CASES= -MEGA_EEST_CHANGED_CASES= +MEGA_EEST_CHANGED_CASES=satin/keyless/deploy/with-reservoir satin/keyless/contract-call/no-value # The repository the suite moved from, exactly as the base's MEGA_EEST_REPO reads, set by the pull # request that changes MEGA_EEST_REPO: the default branch the pin must be on is that repository's, # so a change of repository fails the gate unless it is declared here, and the pin must then be on From 3afefa298fc556088b4756a89afeced86d0fd5e8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:28:38 +0800 Subject: [PATCH 153/190] test(contract-size): remove tests the conformance suite pins --- crates/mega-evm/tests/satin/contract_size.rs | 97 +------------------- 1 file changed, 3 insertions(+), 94 deletions(-) diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs index 823462310..3bd6865fc 100644 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -9,18 +9,14 @@ use alloy_evm::{Evm, EvmError, InvalidTxError}; use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, - test_utils::{right_pad_bytes, BytecodeBuilder, MemoryDatabase}, + test_utils::MemoryDatabase, MegaEvm, MegaHaltReason, MegaTransaction, }; -use revm::{ - bytecode::opcode::{CREATE, INVALID, ISZERO, JUMPDEST, JUMPI, PUSH1, RETURN, STOP}, - context::result::{ExecutionResult, HaltReason, InvalidTransaction}, -}; +use revm::{bytecode::opcode::STOP, context::result::ExecutionResult}; -use crate::common::{call, context, create, history}; +use crate::common::{context, create, history}; const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const FACTORY: Address = address!("0000000000000000000000000000000000100001"); /// Room for everything a creation here draws, all of it above the execution cap so it comes out of /// the reservoir: the state gas of the largest deployable code, the history of that code and of a @@ -60,35 +56,6 @@ fn initcode_of(size: usize) -> Bytes { Bytes::from(vec![STOP; size]) } -/// Init code that returns `size` bytes of zeros as the deployed code. -fn constructor_returning(size: usize) -> Bytes { - let code = BytecodeBuilder::default() - .push_number(size as u64) - .append_many([PUSH1, 0x00]) - .append(RETURN) - .build_vec(); - right_pad_bytes(code, 32).into() -} - -fn assert_initcode_limit(result: Result, String>) { - let expected = format!("{:?}", InvalidTransaction::CreateInitCodeSizeLimit); - assert_eq!(result.expect_err("the transaction is rejected"), expected); -} - -fn assert_code_size_limit(result: Result, String>) { - let halt = result.expect("the transaction is valid"); - assert!( - matches!( - halt, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(HaltReason::CreateContractSizeLimit), - .. - } - ), - "{halt:?}" - ); -} - /* ---------- the initcode bound ---------- */ /// The Satin bound itself is accepted. @@ -96,61 +63,3 @@ fn assert_code_size_limit(result: Result, String fn test_the_satin_initcode_size_is_accepted() { assert!(deploy(initcode_of(MAX_INITCODE_SIZE)).unwrap().is_success()); } - -/// One byte past it is rejected before the transaction runs. -#[test] -fn test_one_byte_past_the_satin_initcode_size_is_rejected() { - assert_initcode_limit(deploy(initcode_of(MAX_INITCODE_SIZE + 1))); -} - -/* ---------- the deployed-code bound, from a creation transaction ---------- */ - -/// One byte past it halts the creation. -#[test] -fn test_one_byte_past_the_satin_code_size_halts() { - assert_code_size_limit(deploy(constructor_returning(MAX_CONTRACT_SIZE + 1))); -} - -/* ---------- the deployed-code bound, from a CREATE ---------- */ - -/// A contract that `CREATE`s a contract of `size` bytes and runs `INVALID` if the creation failed, -/// so a rejected creation shows up as a halt of the outer frame. -fn factory_creating(size: usize) -> Bytes { - let init_code = constructor_returning(size); - let code = BytecodeBuilder::default() - .mstore(0, &init_code) - .push_number(init_code.len() as u64) - .push_number(0u64) - .push_number(0u64) - .append(CREATE) - .append(ISZERO); - let len = code.len(); - code.push_number(len as u8 + 4) - .append(JUMPI) - .append(STOP) - .append(JUMPDEST) - .append(INVALID) - .build() -} - -/// Runs a factory that creates `size` bytes of code and returns whether the creation succeeded. -fn create_through_factory(size: usize) -> bool { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(FACTORY, factory_creating(size)); - let result = - run(call(CALLER, FACTORY, U256::ZERO, gas_limit()), db).expect("the transaction is valid"); - match result { - ExecutionResult::Success { .. } => true, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(HaltReason::InvalidFEOpcode), .. - } => false, - other => panic!("unexpected result {other:?}"), - } -} - -/// One byte past it fails the creation, which the factory turns into a halt. -#[test] -fn test_create_one_byte_past_the_satin_code_size_fails() { - assert!(!create_through_factory(MAX_CONTRACT_SIZE + 1)); -} From cca7239d1c412630883e545628f89d16c5a67b5e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:28:38 +0800 Subject: [PATCH 154/190] test(write-records): remove tests the conformance suite pins --- crates/mega-evm/tests/satin/write_records.rs | 69 +------------------- 1 file changed, 2 insertions(+), 67 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 3abd47551..fcf25c6be 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,9 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, - JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, - STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, + JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -186,33 +185,6 @@ fn body_and_records(records: u64) -> u64 { history(TX_BODY_SIZE + 1 + records * WRITE_RECORD_SIZE) } -/// 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 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 @@ -627,24 +599,6 @@ fn reverting_creations(n: usize) -> Bytes { code.into() } -/// A creation the creator cannot fund never starts (the opcode checks the endowment before it -/// builds a frame), so it records nothing. -#[test] -fn test_creation_without_funds_records_nothing() { - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0]) - .push_number(1_000_000_000_000_u64) - .append(CREATE) - .append(POP) - .stop() - .build(); - let db = MemoryDatabase::default().account_code(CALLEE, code); - 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"); -} - const A: Address = address!("00000000000000000000000000000000A0000001"); const B: Address = address!("00000000000000000000000000000000B0000002"); const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); @@ -743,25 +697,6 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { } } -/// A top-level creation records the created account, and nothing when it fails. -#[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]), value_call_room()), - ); - assert!(result.result.is_success()); - 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]), value_call_room()), - ); - assert!(!result.result.is_success()); - assert_eq!(usage, with_extra(body_only(), 1)); -} - /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. From 9a13b7e286956cfa46e55d44e12b69678e3f824c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:28:39 +0800 Subject: [PATCH 155/190] test(system-tx): remove tests the conformance suite pins --- crates/mega-evm/tests/system/system_tx.rs | 33 ----------------------- 1 file changed, 33 deletions(-) diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 75aca18be..2f7960f28 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -120,14 +120,6 @@ fn run_outcome(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcom MegaEvm::new(chain_context(db)).execute_transaction(tx).expect("the transaction is valid") } -/// Runs `tx` and returns the error it was rejected with, as a string. -fn rejection(db: MemoryDatabase, tx: MegaTransaction) -> String { - let error = MegaEvm::new(chain_context(db)) - .execute_transaction(tx) - .expect_err("the transaction must be rejected"); - format!("{error:?}") -} - /// The Oracle's slot as the database holds it. fn oracle_slot(db: &mut DB, slot: U256) -> U256 where @@ -581,31 +573,6 @@ fn test_two_system_transactions_in_a_block_both_go_through() { assert_eq!(nonce_of(&mut state, MEGA_SYSTEM_ADDRESS), 2); } -/// A system transaction carries the chain's id, so it cannot be replayed on another chain; one -/// without an id at all is refused too. -#[test] -fn test_a_system_transaction_is_bound_to_the_chain() { - let foreign = legacy_tx_with_chain_id( - MEGA_SYSTEM_ADDRESS, - TxKind::Call(ORACLE_CONTRACT_ADDRESS), - set_slot(ORACLE_SLOT, B256::with_last_byte(0xcc)), - 0, - Some(31_337), - ); - let rejected = rejection(chain_db(), foreign); - assert!(rejected.contains("InvalidChainId"), "{rejected}"); - - let no_chain_id = legacy_tx_with_chain_id( - MEGA_SYSTEM_ADDRESS, - TxKind::Call(ORACLE_CONTRACT_ADDRESS), - set_slot(ORACLE_SLOT, B256::with_last_byte(0xdd)), - 0, - None, - ); - let rejected = rejection(chain_db(), no_chain_id); - assert!(rejected.contains("MissingChainId"), "{rejected}"); -} - /// Runs `tx` on `db` under the chain's configuration with `mutate` applied. fn run_with( mutate: fn(&mut CfgEnv), From a071d91b4e1670ce6abf6a8f94f6e1f694cdd7f7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:28:39 +0800 Subject: [PATCH 156/190] test(keyless): remove tests the conformance suite pins --- .../mega-evm/tests/system/keyless/deploy.rs | 40 +---- .../mega-evm/tests/system/keyless/dispatch.rs | 85 +--------- .../tests/system/keyless/precedence.rs | 57 ++++--- crates/mega-evm/tests/system/keyless/rules.rs | 145 +++--------------- 4 files changed, 61 insertions(+), 266 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 601bc4650..eaab8f236 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -30,7 +30,7 @@ use revm::{ }; use super::*; -use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; +use crate::common::CALLER as RELAYER; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); @@ -78,18 +78,12 @@ fn test_keyless_deploy_eip1820() { } } -/// A deployment lands at the signer's first creation address, whoever the signer is, and the -/// deployed code is the runtime the init code returned. #[test] -fn test_the_deploy_address_is_the_signers_first_creation_address() { - for gas_limit in GAS_LIMITS { - for len in [1, 2, 3] { - let deployment = Deployment::new(deploying(&runtime(len))); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.signer.create(0)); - assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&runtime(len)))); - } - } +fn test_a_keyless_deployment_returns_the_deploy_code_hash() { + let code = runtime(3); + let deployment = Deployment::new(deploying(&code)); + let outcome = deploy(system_db(), &deployment, GAS_LIMITS[0]); + assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&code))); } /// The hash of `code`. @@ -787,28 +781,6 @@ fn test_beneficiary_receives_fees_on_execution_failure() { assert_beneficiary_paid(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); } -/// A contract's `keylessDeploy` call is not dispatched: it runs the method body, which reverts -/// with `NotIntercepted()`, and nothing is deployed. -#[test] -fn test_keyless_deploy_not_intercepted_for_inner_calls() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(deploying(&runtime(1))); - let code = - calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &deployment.call_data(LARGE_OVERRIDE), 0); - let mut tx = call_tx(CONTRACT, [], U256::ZERO); - tx.0.base.gas_limit = gas_limit; - let outcome = MegaEvm::new(context(with_contract(code))) - .execute_transaction(tx) - .expect("a valid transaction"); - let output = outcome.result.output().cloned().unwrap_or_default(); - let (status, returned) = split_outcome(&output); - assert!(!status); - assert_eq!(returned, IKeylessDeploy::NotIntercepted::SELECTOR); - assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); - assert!(!outcome.state.contains_key(&deployment.address)); - } -} - /// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: /// not dispatched. The contract's bytecode runs and reverts with `NotIntercepted()`, which the /// outer constructor stores, and nothing of the inner deployment happens: its address holds no diff --git a/crates/mega-evm/tests/system/keyless/dispatch.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs index a21575889..a09f77b88 100644 --- a/crates/mega-evm/tests/system/keyless/dispatch.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -9,9 +9,7 @@ use alloy_primitives::{Bytes, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - system::keyless::{ - IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, - }, + system::keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS}, EvmTxRuntimeLimits, }; use revm::{ @@ -19,7 +17,7 @@ use revm::{ context::result::ExecutionResult, }; -use super::{beyond, reference, refusal, run_with, GAS_LIMITS}; +use super::{beyond, reference, run_with, GAS_LIMITS}; use crate::common::{ body_history, call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, CONTRACT, @@ -52,20 +50,6 @@ fn unknown_selector(data: &Bytes) -> Bytes { Bytes::from(data) } -/// A dispatched `keylessDeploy` transaction pays the fixed overhead, then is refused by the -/// rules: bytes that do not decode as a signed transaction are `MalformedEncoding()`. The -/// deployed bytecode does not run, and the overhead is all the refusal keeps. -#[test] -fn test_a_keyless_deploy_transaction_pays_the_overhead() { - let data = keyless_deploy(b"a transaction"); - for gas_limit in GAS_LIMITS { - let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); - assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); - let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); - assert_eq!([total, regular], [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], "at {gas_limit}"); - } -} - /// A call a contract makes is not dispatched, whatever its selector: only a transaction /// deploys. The deployed bytecode runs and reverts with `NotIntercepted()`, and no overhead is /// charged. @@ -178,71 +162,6 @@ fn test_arguments_that_do_not_decode_are_not_dispatched() { } } -/// The calldata of a `keylessDeploy` call: the selector and `words` as 32-byte words, then -/// `tail` as it is. -fn raw_call(words: &[u64], tail: &[u8]) -> Bytes { - let mut data = KEYLESS_DEPLOY.to_vec(); - for word in words { - data.extend(U256::from(*word).to_be_bytes::<32>()); - } - data.extend(tail); - Bytes::from(data) -} - -/// A call is recognised exactly when the contract's own calldata decoder for `(bytes, uint256)` -/// accepts its arguments, and that decoder asks for no padding and no canonical offset: the -/// padding of the bytes' tail cut off, an offset that points at the head's second word, which is -/// then read as the length, and an offset of zero are all recognised. Each pays the overhead and -/// reaches the rule that refuses a payload that is no signed transaction. -#[test] -fn test_arguments_the_contracts_decoder_accepts_are_dispatched() { - let cases = [ - // offset 0x40, gas limit, length 5, five bytes and none of the 27 bytes of padding - ("the tail's padding cut off", raw_call(&[0x40, 1_000_000, 5], &[0xab; 5])), - // offset 0x20 points at the second head word (3), which is read as the length of the - // three bytes after the head - ("an offset at the second head word", raw_call(&[0x20, 3], &[0xab; 3])), - // offset zero points at the first head word (0), read as an empty payload - ("an offset of zero", raw_call(&[0, 1_000_000], &[])), - ]; - for (name, data) in cases { - for gas_limit in GAS_LIMITS { - let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); - assert_eq!( - refusal(&dispatched), - KeylessDeployError::MalformedEncoding, - "{name} at {gas_limit}", - ); - let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); - assert_eq!( - [total, regular], - [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], - "{name} at {gas_limit}: recognised, so the overhead is charged", - ); - } - } -} - -/// The first of those cases one byte short of the declared length is refused by the same -/// decoder: the call is not recognised, pays no overhead, and the bytecode reverts with empty -/// data. -#[test] -fn test_a_payload_one_byte_short_of_its_declared_length_is_not_dispatched() { - let data = raw_call(&[0x40, 1_000_000, 5], &[0xab; 4]); - for gas_limit in GAS_LIMITS { - let outcome = run_with(system_db(), data.clone(), gas_limit, no_limits()); - let ExecutionResult::Revert { output, .. } = &outcome.result else { - panic!("the bytecode did not revert: {:?}", outcome.result); - }; - assert!(output.is_empty(), "the bytecode's decoder reverts with empty data"); - let [total, regular, ..] = beyond(&outcome, &reference(data.clone(), gas_limit)); - assert!( - total < KEYLESS_DEPLOY_OVERHEAD_GAS && regular < KEYLESS_DEPLOY_OVERHEAD_GAS, - "at {gas_limit}: paid {total} beyond a plain call, an overhead it does not owe", - ); - } -} - /// A call that carries value and whose arguments do not decode is not dispatched either: the /// bytecode runs and refuses the value itself, with the empty revert data of a non-payable /// method, and no overhead is charged. diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index 0c6808565..d7786d24c 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -6,14 +6,15 @@ //! deploy address and the balance. So each pair of failing rules below reports the error the //! legacy engine reported for it. What the `CREATE` opcode charges the call for the creation's //! start is this engine's alone, and comes after every rule: a call a rule refuses is refused -//! with that rule, whether or not it could have paid those charges. The last test pins what those -//! charges refuse on their own, where the legacy engine charged nothing. +//! with that rule, whether or not it could have paid those charges. The tests also pin what those +//! charges refuse on their own. //! //! One pair reports an error the legacy engine never reported: a call carrying value whose //! carried transaction does not decode is refused for the value, where the legacy engine ran the //! bytecode and reverted with empty data. A call whose arguments do not decode is no deployment //! at all, with or without value, and runs the bytecode as the legacy engine did. +use alloy_sol_types::SolError; use mega_evm::{ system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, test_utils::MemoryDatabase, @@ -93,6 +94,19 @@ fn too_low(provided: u64) -> Answer { }) } +#[test] +fn test_decode_gas_limit_too_low_preserves_both_limits() { + let bytes = IKeylessDeploy::GasLimitTooLow { txGasLimit: 100_000, providedGasLimit: 99_999 } + .abi_encode(); + assert_eq!( + decode_error_result(&bytes), + Some(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: 100_000, + provided_gas_limit: 99_999, + }), + ); +} + /// Pairs of failing rules that do not depend on the call's gas, at both gas limits: the rule the /// legacy engine checked first is the one reported. #[test] @@ -316,37 +330,22 @@ fn test_the_forward_comes_before_the_address_and_the_balance_above_the_cap() { } } -/// What the `CREATE` opcode charges the call for the creation's start can refuse a call no rule -/// refuses: a call that cannot pay it runs out of gas, and one it leaves short of the signed gas -/// limit is refused `GasLimitTooLow` with what it left. The legacy engine charged none of it to -/// the call, and ran such a deployment in its sandbox on what the call had. Above the execution -/// cap the refusal is -/// `limits::test_a_refusal_after_the_creations_charges_gives_the_reservoir_back`. +/// A funded signer's forward falls below the signed limit only after the creation charges. #[test] -fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { - let plain = signed(signed_gas(), 0); - let small = signed(1_000, 0); - let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); +fn test_the_creation_charges_reduce_the_reported_forward() { + let deployment = signed(signed_gas(), 0); + let data = deployment.call_data(LARGE_OVERRIDE); let charges = create_regular(deploying(&runtime(1)).len()) + entry(GasId::create_state_gas()) + 2 * record(); - let cases = [ - Case { - rules: "creation charges the call cannot pay", - db: funded(system_db(), &small), - data: data(&small), - gas_limit: leaving(&data(&small), 1_500), - answer: Answer::OutOfGas, - }, - Case { - rules: "a forward the creation's charges take below the signed gas limit", - db: funded(system_db(), &plain), - data: data(&plain), - gas_limit: leaving(&data(&plain), signed_gas()), - answer: too_low(signed_gas() - charges), - }, - ]; - cases.into_iter().for_each(Case::check); + Case { + rules: "creation charges reduce the regular gas available to forward", + db: funded(system_db(), &deployment), + gas_limit: leaving(&data, signed_gas()), + data, + answer: too_low(signed_gas() - charges), + } + .check(); } /// An out-of-gas at step 14 halts the call, consuming its regular gas, and gives back the state diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index c613e6403..594cd070a 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -69,21 +69,6 @@ fn small() -> Deployment { Deployment::new(deploying(&runtime(1))) } -/// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. -#[test] -fn test_keyless_deploy_gas_limit_too_low() { - for gas_limit in GAS_LIMITS { - let outcome = submit(system_db(), CREATE2_FACTORY_TX, 99_999, gas_limit); - assert_eq!( - refusal(&outcome), - KeylessDeployError::GasLimitTooLow { - tx_gas_limit: 100_000, - provided_gas_limit: 99_999 - }, - ); - } -} - /// An override equal to the signed gas limit passes rule 2, and the creation runs with exactly /// that much: signed short of what its creation spends below the execution cap, it runs out of gas /// having spent all of it. The canonical `CREATE2` factory was signed for a chain that charges no @@ -207,6 +192,31 @@ fn test_a_forward_capped_below_the_signed_gas_limit_is_refused() { assert_nothing_written(&outcome, &deployment, 0); } +#[test] +fn test_a_keyless_refusal_returns_the_deploy_code_hash() { + let deployment = Deployment::signed(0, 200_000, U256::ZERO, deploying(&runtime(1))); + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 199_999) + + crate::common::account_state_gas(); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(code_hash(&outcome, deployment.address), Some(KECCAK_EMPTY)); +} + +#[test] +fn test_a_keyless_halt_omits_the_unread_deploy_code_hash() { + if state_is_free() { + return; + } + let deployment = small(); + let intrinsic = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]) + .result + .gas() + .total_gas_spent(); + let gas_limit = + intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS + crate::common::account_state_gas() - 1; + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(code_hash(&outcome, deployment.address), None); +} + /// Rule 3: the signer is recovered from the signature. `r` above the curve order recovers /// nothing. #[test] @@ -219,24 +229,6 @@ fn test_keyless_deploy_invalid_signature() { } } -/// So does `r = 0`, which no signature has. -#[test] -fn test_keyless_deploy_rejects_corrupted_signature() { - for gas_limit in GAS_LIMITS { - let signed = mega_evm::system::keyless::decode_keyless_tx(CREATE2_FACTORY_TX).unwrap(); - let s = signed.signature().s(); - let corrupted = Signed::new_unchecked( - signed.tx().clone(), - Signature::new(U256::ZERO, s, false), - B256::ZERO, - ); - let mut encoded = Vec::new(); - corrupted.rlp_encode(&mut encoded); - let outcome = submit(system_db(), &encoded, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); - } -} - /// A different `s` is a different signer, not an invalid signature: the deployment goes to that /// signer's address, never to the canonical one. #[test] @@ -316,18 +308,6 @@ fn test_keyless_deploy_not_pre_eip155() { } } -/// The transaction must be signed at nonce 0: the deploy address is the signer's first. -#[test] -fn test_keyless_deploy_non_zero_tx_nonce() { - for gas_limit in GAS_LIMITS { - let deployment = - Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// Rule 8: the init code is within the initcode size limit the spec fixes. #[test] fn test_init_code_over_the_limit_is_refused() { @@ -362,18 +342,6 @@ fn test_init_code_at_the_limit_is_admitted() { } } -/// Rule 4: the signer's nonce is at most 1. -#[test] -fn test_keyless_deploy_signer_nonce_too_high() { - for gas_limit in GAS_LIMITS { - let deployment = small(); - let db = system_db().account_nonce(deployment.signer, 2); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); - assert_nothing_written(&outcome, &deployment, 2); - } -} - /// The two canonical keyless deployments: the transaction, the gas limit it was signed with, its /// signer and the address it deploys at. Signed for chains that charge no state gas for deployed /// code: at the spec's prices, without a reservoir, the signed gas limit does not cover the code @@ -609,18 +577,6 @@ fn test_a_signer_that_sends_its_failing_deployment_ends_at_nonce_one() { } } -/// Rule 9: the signer has no code — EIP-3607 for a sender that is not the transaction's. -#[test] -fn test_a_signer_with_code_is_refused() { - for gas_limit in GAS_LIMITS { - let deployment = small(); - let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::SignerHasCode); - assert_nothing_written(&outcome, &deployment, 0); - } -} - /// A chain that disables EIP-3607 disables rule 9 with it, as it does for its own transactions. #[test] fn test_disabling_eip3607_disables_the_signer_code_rule() { @@ -902,57 +858,6 @@ fn test_keyless_deploy_balance_exactly_sufficient() { } } -/// A call that cannot pay for the signer's account runs out of gas before the creation starts: -/// no nonce is bumped and nothing is deployed. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself, -/// and the reservoir pays the state charges, so no gas limit leaves the call this little. -#[test] -fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { - // An account that costs nothing is one any call can pay for. - if state_is_free() { - return; - } - let deployment = small(); - let reference = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]); - let intrinsic = reference.result.gas().total_gas_spent(); - // One short of the account, once the overhead is paid. - let short = entry(GasId::new_account_state_gas()) - 1; - let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS + short; - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); - assert_nothing_written(&outcome, &deployment, 0); - assert_eq!(outcome.gas.state, 0, "the halt takes the charges back"); -} - -/// A call refused after it paid for the creation's start — the forward capped below the signed -/// gas limit — keeps none of its state and history: no account was added, so neither the signer's -/// account nor the created one is charged, the refusal writes nothing, and no record is kept. The -/// regular gas the `CREATE` opcode charged stays spent, as the overhead does. -/// -/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself -/// and the reservoir pays the call's state and history charges, so no gas limit leaves the -/// call this little. The refusal above the cap is -/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. -#[test] -fn test_a_call_refused_after_its_charges_keeps_their_regular_gas_alone() { - // An account that costs nothing takes nothing from the forward. - if state_is_free() { - return; - } - let signed = signed_above_the_account(); - let deployment = Deployment::signed(0, signed, U256::ZERO, deploying(&runtime(1))); - // Enough for everything but the signer's account, which the empty signer adds. - let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), signed); - let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(refusal(&outcome), KeylessDeployError::GasLimitTooLow { .. })); - let [total, regular, state, history_gas, _] = - beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); - let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(one_byte_init_len()); - assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); - assert_nothing_written(&outcome, &deployment, 0); -} - /// The signer's account is charged exactly when its nonce is spent: a refused call does neither, /// a deployment that fails at run time does both. /// From f84695d90939439c0ce06dda5d708b0972bb8bd4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:55:02 +0800 Subject: [PATCH 157/190] test(write-records): restore tests whose returned state no conformance case pins --- crates/mega-evm/tests/satin/write_records.rs | 50 +++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index fcf25c6be..cf2905994 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,9 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, - JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, + JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, + STOP, }, context::ContextTr, interpreter::{ @@ -185,6 +186,33 @@ fn body_and_records(records: u64) -> u64 { history(TX_BODY_SIZE + 1 + records * WRITE_RECORD_SIZE) } +/// 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 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 @@ -599,6 +627,24 @@ fn reverting_creations(n: usize) -> Bytes { code.into() } +/// A creation the creator cannot fund never starts (the opcode checks the endowment before it +/// builds a frame), so it records nothing. +#[test] +fn test_creation_without_funds_records_nothing() { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_000_000_000_000_u64) + .append(CREATE) + .append(POP) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + 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"); +} + const A: Address = address!("00000000000000000000000000000000A0000001"); const B: Address = address!("00000000000000000000000000000000B0000002"); const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); From 512279c22b1cfa1ec60acd1011942f275e7496b6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 17:55:02 +0800 Subject: [PATCH 158/190] test(keyless): restore tests whose refusal state no conformance case pins --- .../tests/system/keyless/interface.rs | 18 +++++++++- .../tests/system/keyless/precedence.rs | 14 -------- crates/mega-evm/tests/system/keyless/rules.rs | 36 +++++++++++++++++++ 3 files changed, 53 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/interface.rs b/crates/mega-evm/tests/system/keyless/interface.rs index 466a38882..b3eddbdb1 100644 --- a/crates/mega-evm/tests/system/keyless/interface.rs +++ b/crates/mega-evm/tests/system/keyless/interface.rs @@ -3,7 +3,10 @@ use std::collections::BTreeSet; -use mega_evm::system::keyless::IKeylessDeploy::IKeylessDeployErrors; +use alloy_sol_types::SolError; +use mega_evm::system::keyless::{ + decode_error_result, IKeylessDeploy, IKeylessDeploy::IKeylessDeployErrors, KeylessDeployError, +}; /// The `KeylessDeploy` spec page. const KEYLESS_DEPLOY_MD: &str = @@ -29,3 +32,16 @@ fn test_the_interface_declares_exactly_the_documented_errors() { assert_eq!(declared.len(), IKeylessDeployErrors::SIGNATURES.len(), "a signature repeats"); assert_eq!(declared, documented_errors()); } + +#[test] +fn test_decode_gas_limit_too_low_preserves_both_limits() { + let bytes = IKeylessDeploy::GasLimitTooLow { txGasLimit: 100_000, providedGasLimit: 99_999 } + .abi_encode(); + assert_eq!( + decode_error_result(&bytes), + Some(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: 100_000, + provided_gas_limit: 99_999, + }), + ); +} diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs index d7786d24c..26d5aabc6 100644 --- a/crates/mega-evm/tests/system/keyless/precedence.rs +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -14,7 +14,6 @@ //! bytecode and reverted with empty data. A call whose arguments do not decode is no deployment //! at all, with or without value, and runs the bytecode as the legacy engine did. -use alloy_sol_types::SolError; use mega_evm::{ system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, test_utils::MemoryDatabase, @@ -94,19 +93,6 @@ fn too_low(provided: u64) -> Answer { }) } -#[test] -fn test_decode_gas_limit_too_low_preserves_both_limits() { - let bytes = IKeylessDeploy::GasLimitTooLow { txGasLimit: 100_000, providedGasLimit: 99_999 } - .abi_encode(); - assert_eq!( - decode_error_result(&bytes), - Some(KeylessDeployError::GasLimitTooLow { - tx_gas_limit: 100_000, - provided_gas_limit: 99_999, - }), - ); -} - /// Pairs of failing rules that do not depend on the call's gas, at both gas limits: the rule the /// legacy engine checked first is the one reported. #[test] diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 594cd070a..28f0f4b78 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -308,6 +308,18 @@ fn test_keyless_deploy_not_pre_eip155() { } } +/// The transaction must be signed at nonce 0: the deploy address is the signer's first. +#[test] +fn test_keyless_deploy_non_zero_tx_nonce() { + for gas_limit in GAS_LIMITS { + let deployment = + Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); + assert_nothing_written(&outcome, &deployment, 0); + } +} + /// Rule 8: the init code is within the initcode size limit the spec fixes. #[test] fn test_init_code_over_the_limit_is_refused() { @@ -342,6 +354,18 @@ fn test_init_code_at_the_limit_is_admitted() { } } +/// Rule 4: the signer's nonce is at most 1. +#[test] +fn test_keyless_deploy_signer_nonce_too_high() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_nonce(deployment.signer, 2); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); + assert_nothing_written(&outcome, &deployment, 2); + } +} + /// The two canonical keyless deployments: the transaction, the gas limit it was signed with, its /// signer and the address it deploys at. Signed for chains that charge no state gas for deployed /// code: at the spec's prices, without a reservoir, the signed gas limit does not cover the code @@ -577,6 +601,18 @@ fn test_a_signer_that_sends_its_failing_deployment_ends_at_nonce_one() { } } +/// Rule 9: the signer has no code — EIP-3607 for a sender that is not the transaction's. +#[test] +fn test_a_signer_with_code_is_refused() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerHasCode); + assert_nothing_written(&outcome, &deployment, 0); + } +} + /// A chain that disables EIP-3607 disables rule 9 with it, as it does for its own transactions. #[test] fn test_disabling_eip3607_disables_the_signer_code_rule() { From 1bd7619ed569443ab55672ba2d10dbfe0014bd86 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 18:05:52 +0800 Subject: [PATCH 159/190] test(keyless): restore the test whose returned state no conformance case pins --- .../mega-evm/tests/system/keyless/deploy.rs | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index eaab8f236..eccdfb9e6 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -30,7 +30,7 @@ use revm::{ }; use super::*; -use crate::common::CALLER as RELAYER; +use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); @@ -781,6 +781,28 @@ fn test_beneficiary_receives_fees_on_execution_failure() { assert_beneficiary_paid(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); } +/// A contract's `keylessDeploy` call is not dispatched: it runs the method body, which reverts +/// with `NotIntercepted()`, and nothing is deployed. +#[test] +fn test_keyless_deploy_not_intercepted_for_inner_calls() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&runtime(1))); + let code = + calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &deployment.call_data(LARGE_OVERRIDE), 0); + let mut tx = call_tx(CONTRACT, [], U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(with_contract(code))) + .execute_transaction(tx) + .expect("a valid transaction"); + let output = outcome.result.output().cloned().unwrap_or_default(); + let (status, returned) = split_outcome(&output); + assert!(!status); + assert_eq!(returned, IKeylessDeploy::NotIntercepted::SELECTOR); + assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); + assert!(!outcome.state.contains_key(&deployment.address)); + } +} + /// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: /// not dispatched. The contract's bytecode runs and reverts with `NotIntercepted()`, which the /// outer constructor stores, and nothing of the inner deployment happens: its address holds no From f12d9f5035f4f91115205d7a3bb31cc447b6aa5e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 18:05:52 +0800 Subject: [PATCH 160/190] test(keyless): assert the signer nonce on an unpaid account charge --- crates/mega-evm/tests/system/keyless/rules.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 28f0f4b78..c69948df5 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -214,6 +214,8 @@ fn test_a_keyless_halt_omits_the_unread_deploy_code_hash() { let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS + crate::common::account_state_gas() - 1; let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + // A failed signer-account charge must leave the signer nonce unspent. + assert_eq!(nonce(&outcome, deployment.signer), 0); assert_eq!(code_hash(&outcome, deployment.address), None); } From 841d68af5f546656ada375c1abcac56e03084902 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Wed, 18 Nov 2026 20:29:14 +0800 Subject: [PATCH 161/190] test(system): restore tests whose returned balance no conformance case pins --- crates/mega-evm/tests/system/dispatch.rs | 24 +++++++++++++++++++- crates/mega-evm/tests/system/oracle.rs | 28 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs index aa48413cd..260546173 100644 --- a/crates/mega-evm/tests/system/dispatch.rs +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -3,7 +3,7 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ system::{ storage_slots::CURRENT_SYSTEM_ADDRESS, IMegaAccessControl, IMegaLimitControl, IOracle, @@ -173,6 +173,28 @@ fn test_a_database_error_reading_the_registry_fails_the_transaction() { assert!(format!("{error}").contains("injected storage() error"), "{error}"); } +/// The value policy is the interceptor's, not the account's: a value-bearing transaction to a +/// control contract is refused with `NonZeroTransfer()` before any value moves. +#[test] +fn test_a_value_bearing_transaction_is_refused_before_the_value_moves() { + let db = system_db(); + let mut tx = call_tx(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS, U256::from(1)); + tx.0.base.caller = crate::common::CALLER; + let result = run(db, tx); + + let revm::context::result::ExecutionResult::Revert { output, .. } = &result.result else { + panic!("the transaction did not revert: {:?}", result.result); + }; + assert_eq!(output[..], IMegaLimitControl::NonZeroTransfer::SELECTOR); + assert!( + result + .state + .get(&LIMIT_CONTROL_ADDRESS) + .is_none_or(|account| account.info.balance.is_zero()), + "the refused value stayed with its sender", + ); +} + /// A `STATICCALL` to a system contract from inside a static frame is intercepted too: nothing /// about the answer writes state. #[test] diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 03349eb35..20a874055 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -156,6 +156,34 @@ fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) } +/// A value-bearing `sendHint` whose caller cannot fund the value is intercepted before revm +/// starts the call and checks the funds: the hint is forwarded and its input counted, then the +/// call fails for the funds with empty return data and moves no value, and the Oracle's bytecode +/// never runs. +#[test] +fn test_an_unfunded_value_hint_is_forwarded_and_then_fails_for_funds() { + let data = send_hint(b"unfunded"); + let (result, hints, usage) = + run_with_oracle(unfunded_contract_db(&data), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(result.result.is_success(), "the contract survives the failed call"); + let returned = result.result.output().cloned().unwrap_or_default(); + let (status, return_data) = crate::common::split_outcome(&returned); + assert!(!status, "the call fails for funds"); + assert!(return_data.is_empty(), "with empty return data"); + assert_eq!( + hints, + vec![RecordedHint { from: CONTRACT, topic: TOPIC, data: Bytes::from_static(b"unfunded") }], + "the hint reached the service", + ); + assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its input is counted"); + assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + data.len() as u64); + let balance = + |address| result.state.get(&address).map_or(U256::ZERO, |account| account.info.balance); + assert_eq!(balance(CONTRACT), U256::ZERO, "no value moved from the caller"); + assert_eq!(balance(ORACLE_CONTRACT_ADDRESS), U256::ZERO, "and none reached the Oracle"); +} + /// A value-bearing `sendHint` its caller cannot fund, under a data-size limit its input would /// cross, is answered with the stop, not with the funds failure: nothing is forwarded and nothing /// is counted. From c7fb725d9d9a13e40e862b69d33a942c5df5bba8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 09:46:52 +0800 Subject: [PATCH 162/190] ci: accept the conformance suite's error-form negative control --- AGENTS.md | 12 +++-- REVIEW.md | 5 ++- scripts/mega_eest.py | 93 +++++++++++++++++++++++---------------- scripts/mega_eest.sh | 30 +++++++------ scripts/test_mega_eest.py | 77 +++++++++++++++++++++++++++----- 5 files changed, 152 insertions(+), 65 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 46dbc3157..bd0d02883 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -672,9 +672,15 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The adapter is built against this checkout, not the mega-evm commit it pins: `scripts/mega_eest.py` writes it out as a workspace of its own (`target/mega-eest/adapter-revm`) whose mega-evm is a path dependency on `crates/mega-evm`, whose other crates take their sources from this tree's `[workspace.dependencies]`, and whose `[patch]` and `[profile]` tables are this tree's root manifest's, so a pull request that moves the revm or op-revm fork is tested with its own fork. The adapter's `Cargo.lock`, resolved for the commit it pins, is not used: the workspace's lock is seeded with this tree's `Cargo.lock`, cargo resolves it once, every package mega-evm links must then be at the version and source this tree locks, with one revm, and the build runs `--locked`. The executables it runs are the ones those builds report (cargo's JSON messages), never a file at a path guessed from the target directory. - It passes when the cases consumed are exactly the slice's index, by case id and file digest, every one passes in both modes with the same observations, and the suite's deliberately wrong expectation, which the index must list, fails where it records; a failure names the case, its first differing path, both values and the rules it pins. - The wrong expectation is the control that shows the pipeline can report a failure: it must fail where it records only when every gating case passed, since when gating cases fail they show that already and a change of behaviour can also move where the control first differs; then it need only have run and not passed. - The summary is one `MEGA-EEST` line on stdout, and the exit code says what kind of result it is: 0 pass; 1 the cases failed, the only verdict on this tree (every mode ran to a complete report of exactly the index, a case failed or erred or the modes' observations differ, and the control ran and did not pass, wherever it first differed); 2 no verdict (a fetch, a build, the resolution, a report missing or incomplete, no mode, a control not run or passing, a control that failed elsewhere while every gating case passed, a case the adapter does not support), however the cases would have gone; 3 the cases passed and the pin is refused. + The gate passes when every case in the slice's index passes in both modes with identical observations, each report contains exactly the indexed case IDs and file digests, and every negative control matches its index entry. + A case failure names the case, its first differing path, both values and the rules it pins. + The negative controls exercise failure reporting: each must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. + If gating cases fail or their observations differ between modes, each control must report a failure or an error, and its first difference or error message can vary with the change. + The summary is one `MEGA-EEST` line on stdout. + Exit 0 means the gate passed. + Exit 1 means the reports are complete, a case failed or erred or the modes differed, and every control failed or erred. + Exit 2 means the run reached no verdict, for example due to an incomplete report, an unsupported case, a malformed control entry or a control outcome that does not satisfy the gate. + Exit 3 means the cases passed and the pin is refused. The line says `run=full` for both modes, which the gate requires, and `run=partial` for one. The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and the removed ids and the ids of cases changed under them (another file digest) must be exactly those `MEGA_EEST_REMOVED_CASES` and `MEGA_EEST_CHANGED_CASES` in `scripts/mega_eest.env` declare (`caseset=declared`, or `kept` with none removed or changed); when `MEGA_EEST_BASE_REPO` names the base's repository, a pin file naming another is refused (`repo=changed`) unless its `MEGA_EEST_REPO_MOVED_FROM` names the base's exactly (`repo=moved`, the pin on the new repository's default branch), and that line set without a move is refused as stale (`repo=stale`) unless the base's carries the same; each refusal is exit 3, and the job's annotation names its causes. A pin on the branch of a suite change still under review is a draft state: its cases run, and the gate stays red until the pin moves to the merged commit. diff --git a/REVIEW.md b/REVIEW.md index a6f8584a7..22ef26140 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -149,7 +149,10 @@ These checks guard every change to the Satin engine. - The `Mega EEST gate` job always runs, and becomes a required check once an administrator adds it to the `satin` branch rule; a pull request that changes documentation alone skips the run and passes it. The step summary has the summary line (`MEGA-EEST rev=… run=full cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… provenance=… caseset=… result=…`), the run's time and exit, and, when the pull request moves the pin, the case ids it removes, adds and changes; a failing run uploads its reports. The script's exit says what failed: 1 the cases (a verdict), 2 no verdict (a fetch, a build, a report; the log names the step), 3 the pin refused; the job also requires the line of the full run of a pin on the suite's default branch. - The suite's deliberately wrong expectation is a control: with every gating case passing it must fail where it records, and with gating cases failing it need only have run and not passed (`negative=fail-elsewhere`), since a change of behaviour can move where it first differs; a control that passed or did not run is never a verdict. + When all gating cases pass, every negative control must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. + If gating cases fail or their observations differ between modes, every control must still report a failure or an error. + The summary shows `negative=fail-as-recorded` when every control matches its index entry and `negative=fail-elsewhere` when the gating run fails and at least one control fails differently. + A malformed control entry, a missing control result or a passing control leaves the run without a verdict. - A case that fails is a change of behaviour the specification pins. A pull request that makes it on purpose, or that changes the mega-evm API the suite's adapter calls (the adapter then no longer builds, and the gate says so), changes Mega EEST first: the case, derived from the changed rule, or the adapter, in a pull request there. It then moves `MEGA_EEST_REV` to that Mega EEST commit, in the same mega-evm pull request, so the gate runs the suite that pull request needs. diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index ea8e12cac..2e4b5f221 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -47,27 +47,24 @@ [--repo ] [--caseset ] Read the run reports `mega-fixture consume` wrote into (.json, and - negative.json for the suite's deliberately wrong expectation) and decide: in every mode, the + negative.json for the suite's negative controls) and decide: in every mode, the cases consumed are exactly the slice's index, by case id and file digest, and every one passed; with both modes, every case's observations are the same bytes plain and - instrumented. The wrong expectation, which the index must list, is the control that shows - the consumer and the adapter can report a failure at all: it decides only when every - gating case passed, and then it must fail at the path it records; when gating cases - failed, the failures already show that, and the control need only have run and not passed - (failed or erred, at any path), since a change of behaviour can move where it first - differs. Prints the failures (case id, first differing path, both values, the rules the + instrumented. When every gating case passed, each indexed negative control must fail at + its recorded path or report an error with its exact recorded message, according to its + index entry. When gating cases failed, each control must have run and reported a failure + or an error. Prints the failures (case id, first differing path, both values, the rules the case pins) and one summary line, `MEGA-EEST … result=`, and exits with its code: 0 pass; 1 FAIL, a verdict (complete reports of exactly the index in every mode, a case - failed or erred, or the modes' observations differ, and the control ran and did not pass); + failed or erred, or the modes' observations differ, and every control failed or erred); 2 INCOMPLETE, no verdict (no mode, a report missing, cases that are not the index, a consume exit its report does not explain, a case the adapter does not support, a case - status other than the consumer's four (pass, fail, unsupported, error), no control, - a control not run or passing, a control that failed elsewhere while every gating case - passed, or the checker itself failing); 3 REFUSED, every case passed but the pin is refused - for a cause `refusal` names: its provenance is `unmerged`; its repository is not the base's - and no declaration names the base's (`repo=changed`); a declaration names a move the change - does not make (`repo=stale`); its repository moves and its provenance is unchecked; or its - case set is `undeclared`. + status other than the consumer's four (pass, fail, unsupported, error), a missing or + malformed control, a control not run or passing, a control that did not fail as recorded + while every gating case passed, or the checker itself failing). + 3 REFUSED means every case passed and the pin has a cause `refusal` names, such as + `provenance=unmerged`, `repo=changed`, `repo=stale`, a repository move with unchecked + provenance, or `caseset=undeclared`. refusal --summary The causes for which the pin of a summary line is refused, one sentence, from the line's @@ -501,37 +498,57 @@ def check(args: argparse.Namespace) -> int: summary.append(f"parity={'identical' if not differ else f'{len(differ)}-differ'}") cases_failed |= bool(differ) - # The wrong expectation is the control that shows the consumer and the adapter can report a - # failure at all. When every gating case passed, nothing else shows it, so the control must - # fail at the path it records. When gating cases failed, the failures show it, and a change - # of behaviour can also move where the control first differs, so it need only have run and - # not passed (failed or erred, at any path). A control that was not run, or that passed, - # says the consumer cannot be trusted either way. Without one, there is no verdict. + # The controls show that the consumer can report a mismatch or an adapter error. + # When gating cases failed, a change of behaviour can also change a control's first failure. negative_path = work / "negative.json" - wrong_at = {n["caseId"]: n["wrongAt"] for n in index.get("negative", [])} - if not wrong_at: + controls = index.get("negative", []) + control_keys = {"caseId", "file"} + if not isinstance(controls, list) or any( + not isinstance(control, dict) + or control.keys() not in (control_keys | {"wrongAt"}, control_keys | {"error"}) + or not all(isinstance(value, str) and value for value in control.values()) + for control in controls + ): + verdict = "invalid-index" + incomplete.append("malformed negative control index: expected caseId, file and exactly one of wrongAt or error") + elif len({control["caseId"] for control in controls}) != len(controls): + verdict = "invalid-index" + incomplete.append("malformed negative control index: repeated case IDs") + elif not controls: verdict = "none" - incomplete.append("the slice's index lists no wrong expectation, which shows the consumer can fail") + incomplete.append("the slice's index lists no negative control") elif not negative_path.exists(): verdict = "no-report" - incomplete.append("`mega-fixture consume` wrote no report of the wrong expectation") + incomplete.append("`mega-fixture consume` wrote no report of the negative controls") else: - cases = {c.get("caseId"): c for c in json.loads(negative_path.read_text())["cases"]} - states = [] - for case_id, path in wrong_at.items(): - c = cases.get(case_id) - seen = f"{c['status']} at {c.get('path')}" if c else "not consumed" - if c and c["status"] == "fail" and c.get("path") == path: - states.append("fail-as-recorded") - elif c and c["status"] in ("fail", "error") and cases_failed: - states.append("fail-elsewhere") - print(f"mega-eest: the wrong expectation {case_id} did not fail at {path} ({seen}); " + reports = json.loads(negative_path.read_text())["cases"] + cases = {report.get("caseId"): report for report in reports} + states = set() + if len(cases) != len(reports) or cases.keys() - {control["caseId"] for control in controls}: + states.add("not-caught") + incomplete.append("negative control report has extra or repeated case IDs") + for control in controls: + case_id = control["caseId"] + if "wrongAt" in control: + status, field, value = "fail", "path", control["wrongAt"] + else: + status, field, value = "error", "message", control["error"] + report = cases.get(case_id) + if report and report["status"] == status and report.get(field) == value: + states.add("fail-as-recorded") + continue + want = f"{status} with {field} {canonical(value)}" + seen = (f"{report['status']} with {field} {canonical(report.get(field))}" + if report else "not consumed") + if report and report["status"] in ("fail", "error") and cases_failed: + states.add("fail-elsewhere") + print(f"mega-eest: negative control {case_id} expected {want} ({seen}); " f"gating cases failed, which can move where it first differs", file=sys.stderr) else: - states.append("not-caught") + states.add("not-caught") why = ("gating cases failed, and it did not fail" if cases_failed - else "every gating case passed, so it must fail where recorded") - incomplete.append(f"the wrong expectation {case_id} did not fail at {path} ({seen}): {why}") + else "every gating case passed, so it must match the recorded failure") + incomplete.append(f"negative control {case_id} expected {want} ({seen}): {why}") verdict = ("not-caught" if "not-caught" in states else "fail-elsewhere" if "fail-elsewhere" in states else "fail-as-recorded") summary.append(f"negative={verdict}") diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index 23243c4dc..fd7c7dd6a 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -39,14 +39,13 @@ # Cargo runs from this checkout's root, so the toolchain is its rust-toolchain.toml and the # configuration its .cargo/config.toml. # 5. Consumes every gating case (slice/cases) with `mega-fixture consume` in each mode of -# $MEGA_EEST_MODES, plain and --instrumented by default, and the suite's deliberately wrong -# expectation (slice/negative). +# $MEGA_EEST_MODES, plain and --instrumented by default, and the suite's negative controls +# (slice/negative). # 6. Decides (scripts/mega_eest.py check): in each mode the cases consumed are exactly the slice's -# index and every one passed; plain and instrumented observations are the same bytes. The wrong -# expectation, which the index must list, is the control that shows the pipeline can report a -# failure: when every gating case passed it must fail where the index says; when gating cases -# failed, the failures show that already, and since a change of behaviour can also move where -# the control first differs, it need only have run and not passed (failed or erred, anywhere). +# index and every one passed, with identical plain and instrumented observations. When every +# gating case passed, each indexed negative control must fail at its `wrongAt` path or report +# status `error` with its exact `error` message, according to its index entry. When gating cases +# failed, each control must have run and reported a failure or an error. # A failure prints the case id, the first differing path and both values, and the rules the # case pins. # @@ -57,21 +56,26 @@ # repo= caseset= # result= # +# `negative=fail-as-recorded` means every control matched its own expectation. +# `fail-elsewhere` means each control failed or erred and at least one differed during a failing run. +# `not-caught` means the report did not meet the conditions for a verdict. +# `none`, `invalid-index` and `no-report` identify missing controls, malformed entries and a missing report. +# # `run=full` is both modes, which the gate requires; `run=partial` is one, which the mutation gate # runs (plain). A run that stops before the reports are read prints # `MEGA-EEST rev= run=<...> stage= result=INCOMPLETE` instead. # # Exit codes: -# 0 pass: every case passed in every mode run, the wrong expectation failed where recorded, and +# 0 pass: every case passed in every mode run, the negative controls matched the index, and # the pin's checks passed or were skipped (result=pass) # 1 the cases failed: every mode ran to a complete report of exactly the slice's cases, a case -# failed or erred or plain and instrumented observations differ, and the wrong expectation ran -# and did not pass, wherever it first differed (result=FAIL). The only exit that is a verdict +# failed or erred or plain and instrumented observations differ, and every negative control +# failed or erred (result=FAIL). The only exit that is a verdict # on this tree. # 2 no verdict: anything that kept the run from one, a fetch, a build, the resolution, the lock # check, a report missing or incomplete, cases that are not the index, a case the adapter does -# not support, no mode, a wrong expectation not run or passing, or one that failed elsewhere -# while every gating case passed (result=INCOMPLETE) +# not support, no mode, missing or malformed controls, a control not run or passing, or +# a control that did not match the index while every gating case passed (result=INCOMPLETE) # 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, in another # repository than the base's without a declared move, with a stale move declaration, or it # removes or changes cases scripts/mega_eest.env does not declare (result=REFUSED; the log @@ -395,7 +399,7 @@ for mode in $MODE_WORDS; do echo "$rc" > "$WORK/$mode.exit" grep '^CONSUME ' "$WORK/$mode.log" >&2 || log "$mode: no CONSUME line; see $WORK/$mode.log" done -log "consuming slice/negative, the wrong expectation ($(elapsed))" +log "consuming slice/negative, the negative controls ($(elapsed))" "$CLI" consume --adapter "$ADAPTER" --specs "$SUITE/specs" --report "$WORK/negative.json" \ "$SUITE/slice/negative" > "$WORK/negative.log" || true diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 96db5dcde..8082fcbb8 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -265,6 +265,10 @@ class Check(Case): CASES = [("satin/a", "sha256:1"), ("satin/b", "sha256:2")] NEGATIVE = [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/x"}] + INDEX_NEGATIVE = [{"caseId": "satin/negative/wrong", "file": "negative/wrong.json", + "wrongAt": "/expected/x"}] + ORACLE_CONTROL = {"caseId": "satin/negative/oracle", "file": "negative/oracle.json", + "error": "unexpected oracle request for slot 0x3"} def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | None = None, exits: dict[str, int] | None = None, *, modes: str | None = None, @@ -277,8 +281,7 @@ def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | No work.mkdir() (suite / "slice" / "index.json").write_text(json.dumps({ "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], - "negative": ([{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}] - if index_negative is None else index_negative), + "negative": self.INDEX_NEGATIVE if index_negative is None else index_negative, })) for mode, cases in reports.items(): if cases is not None: @@ -400,29 +403,82 @@ def test_failing_cases_with_a_control_that_did_not_fail_are_no_verdict(self) -> for control, reason in ((self.control("pass"), "gating cases failed, and it did not fail"), (self.control("unsupported"), "gating cases failed, and it did not fail"), ([], "not consumed"), - (None, "no report of the wrong expectation")): + (None, "no report of the negative controls")): code, out, err = self.write({"plain": self.one_failing()}, control) self.assert_no_verdict(code, out, err, reason) def test_passing_cases_need_the_control_to_fail_where_recorded(self) -> None: - for control, reason in ((self.control("fail", "/expected/y"), "so it must fail where recorded"), - (self.control("error"), "so it must fail where recorded"), - (self.control("pass"), "so it must fail where recorded"), - (None, "no report of the wrong expectation")): + for control, reason in ((self.control("fail", "/expected/y"), "so it must match the recorded failure"), + (self.control("error"), "so it must match the recorded failure"), + (self.control("pass"), "so it must match the recorded failure"), + (None, "no report of the negative controls")): code, out, err = self.write({"plain": self.all_passed()}, control) self.assert_no_verdict(code, out, err, reason) self.assertNotIn("negative=fail-as-recorded", out) run = self.write({"plain": self.all_passed()}, self.NEGATIVE, index_negative=[]) - self.assert_no_verdict(*run, "lists no wrong expectation") + self.assert_no_verdict(*run, "lists no negative control") self.assertIn("negative=none", run[1]) + def test_passing_cases_accept_both_recorded_control_forms(self) -> None: + oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "status": "error", + "message": self.ORACLE_CONTROL["error"]} + code, out, err = self.write({"plain": self.all_passed()}, [*self.NEGATIVE, oracle], + index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) + self.assertEqual(code, 0, err) + self.assertIn("negative=fail-as-recorded", out) + self.assertTrue(out.strip().endswith("result=pass"), out) + + def test_passing_cases_require_the_exact_recorded_error(self) -> None: + for result in ({"status": "error", "message": self.ORACLE_CONTROL["error"] + " (retry)"}, + {"status": "fail", "path": "/expected/x", "message": self.ORACLE_CONTROL["error"]}): + with self.subTest(result=result): + oracle = {"caseId": self.ORACLE_CONTROL["caseId"], **result} + code, out, err = self.write({"plain": self.all_passed()}, [*self.NEGATIVE, oracle], + index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) + self.assert_no_verdict(code, out, err, "so it must match the recorded failure") + self.assertIn("negative=not-caught", out) + + def test_malformed_control_entries_are_no_verdict(self) -> None: + entry = self.INDEX_NEGATIVE[0] + common = {k: entry[k] for k in ("caseId", "file")} + for malformed in (common, {**entry, "error": "an error"}, {**entry, "extra": "unexpected"}, + {**entry, "wrongAt": None}): + with self.subTest(entry=malformed): + code, out, err = self.write({"plain": self.one_failing()}, self.NEGATIVE, + index_negative=[malformed]) + self.assert_no_verdict(code, out, err, "malformed negative control") + self.assertIn("negative=invalid-index", out) + + def test_failing_cases_accept_an_error_control_that_errs_differently(self) -> None: + oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "status": "error", + "message": "a different adapter error"} + code, out, err = self.write({"plain": self.one_failing()}, [*self.NEGATIVE, oracle], + index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) + self.assertEqual(code, 1, err) + self.assertIn("negative=fail-elsewhere", out) + self.assertTrue(out.strip().endswith("result=FAIL"), out) + + def test_failing_cases_with_an_error_control_that_passes_are_no_verdict(self) -> None: + oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "status": "pass"} + code, out, err = self.write({"plain": self.one_failing()}, [*self.NEGATIVE, oracle], + index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) + self.assert_no_verdict(code, out, err, "gating cases failed, and it did not fail") + self.assertIn("negative=not-caught", out) + + def test_an_extra_or_repeated_control_report_is_no_verdict(self) -> None: + for extra in ({"caseId": "satin/negative/extra", "status": "error"}, self.NEGATIVE[0]): + with self.subTest(extra=extra): + code, out, err = self.write({"plain": self.one_failing()}, [*self.NEGATIVE, extra]) + self.assert_no_verdict(code, out, err, "negative control report has extra or repeated case IDs") + self.assertIn("negative=not-caught", out) + def test_a_changed_repository_is_refused(self) -> None: run = Path(tempfile.mkdtemp(dir=self.tmp)) (run / "suite" / "slice").mkdir(parents=True) (run / "work").mkdir() (run / "suite" / "slice" / "index.json").write_text(json.dumps({ "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], - "negative": [{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}]})) + "negative": self.INDEX_NEGATIVE})) (run / "work" / "plain.json").write_text(json.dumps({"cases": self.all_passed()})) (run / "work" / "plain.exit").write_text("0\n") (run / "work" / "negative.json").write_text(json.dumps({"cases": self.NEGATIVE})) @@ -739,7 +795,8 @@ def commit_cases(self, ids: list[str], branch: str | None = None) -> str: (slice_dir / "negative" / "wrong.json").write_text("{}\n") (slice_dir / "index.json").write_text(json.dumps({ "cases": [{"caseId": c, "fileDigest": f"sha256:{c}"} for c in ids], - "negative": [{"caseId": "satin/negative/wrong", "wrongAt": "/expected/x"}]})) + "negative": [{"caseId": "satin/negative/wrong", "file": "negative/wrong.json", + "wrongAt": "/expected/x"}]})) self.git("add", "-A", cwd=self.suite) self.git("commit", "-q", "-m", "cases", cwd=self.suite) rev = self.git("rev-parse", "HEAD", cwd=self.suite) From 49977717409b983f245d31d210daad286079d977 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 09:46:52 +0800 Subject: [PATCH 163/190] test(mega-eest): move the conformance suite pin to ab250af --- scripts/mega_eest.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index c0617d66c..92b384eca 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -8,14 +8,14 @@ # pinned here. A commit off the default branch (a suite change still under review) keeps the gate # red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest -MEGA_EEST_REV=fb0a46a544bb2599b6ad88da6f861ed47b40424f +MEGA_EEST_REV=ab250afa0b24dd011857e7d65eda9f47b1b7d6b8 # The case ids the pin's last move removed, and those it changed under their ids (another file # digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice # drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none # leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a # change is a line the reviewer reads in this file's diff. MEGA_EEST_REMOVED_CASES= -MEGA_EEST_CHANGED_CASES=satin/keyless/deploy/with-reservoir satin/keyless/contract-call/no-value +MEGA_EEST_CHANGED_CASES=satin/access-control/delegate-refusal/call-cold-target-refusal-reads satin/access-control/delegate-refusal/callcode-cold-target-refusal-reads satin/access-control/delegate-refusal/delegatecall-cold-target-refusal-reads satin/access-control/delegate-refusal/max-forward-cold-target-refused satin/access-control/delegate-refusal/max-forward-warm-target-refused satin/access-control/delegate-refusal/value-call-at-the-guard satin/access-control/delegate-refusal/value-call-refused satin/access-control/delegate-refusal/value-callcode-refused satin/accounting/fee-account/beneficiary-is-sender satin/accounting/merge/creation-endowment-unfunded satin/accounting/sender/value-call-to-sender satin/authorizations/absent-authority satin/authorizations/limit/one-over-all-or-nothing satin/authorizations/limit/one-over-with-fees satin/authorizations/reads/simulation-past-crossing satin/call-order/unfunded/empty-account satin/detention/delegate-refusal/memory-crossing-reads-nothing satin/detention/delegate-refusal/surcharge-crossing satin/detention/delegate-refusal/surcharge-crossing-keeps-the-memory satin/detention/delegate-refusal/surcharge-crossing-one-short satin/detention/delegate-refusal/surcharge-paid satin/gas-pools/first-frame-revert/authorization-charges-kept satin/keyless/authorizations/1001-new-authorities satin/keyless/contract-call/no-value satin/keyless/refusal/signer-has-code satin/keyless/refusal/signer-nonce-two satin/keyless/refusal/taken-and-unfunded satin/limit-stops/authorization-list/one-authority-over satin/oracle/send-hint/stipend-unfunded satin/outcomes/pre-frame/created-account-one-short satin/outcomes/pre-frame/created-account-paid satin/outcomes/revert/after-fresh-slot satin/reads/balance-cold-paid satin/reads/balance-cold-unpaid satin/reads/oracle-slot-before-charge satin/selfdestruct/created/fresh-slot-on-little-gas satin/selfdestruct/marked/fresh-slot-on-little-gas satin/selfdestruct/not-created/new-beneficiary-caller-reverts satin/system-contracts/limit-control/own-call-with-value satin/take-backs/sent-back/round-trip # The repository the suite moved from, exactly as the base's MEGA_EEST_REPO reads, set by the pull # request that changes MEGA_EEST_REPO: the default branch the pin must be on is that repository's, # so a change of repository fails the gate unless it is declared here, and the pin must then be on From 9a5cfa1ddb28e2f95028fd7d08083d93082c150a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:02:27 +0800 Subject: [PATCH 164/190] fix(ci): verify Mega EEST controls in every mode --- AGENTS.md | 11 +-- REVIEW.md | 10 ++- scripts/mega_eest.py | 153 +++++++++++++++++++++++--------------- scripts/mega_eest.sh | 39 +++++----- scripts/test_mega_eest.py | 98 +++++++++++++++++------- 5 files changed, 201 insertions(+), 110 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bd0d02883..2d614f4e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -672,14 +672,15 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The adapter is built against this checkout, not the mega-evm commit it pins: `scripts/mega_eest.py` writes it out as a workspace of its own (`target/mega-eest/adapter-revm`) whose mega-evm is a path dependency on `crates/mega-evm`, whose other crates take their sources from this tree's `[workspace.dependencies]`, and whose `[patch]` and `[profile]` tables are this tree's root manifest's, so a pull request that moves the revm or op-revm fork is tested with its own fork. The adapter's `Cargo.lock`, resolved for the commit it pins, is not used: the workspace's lock is seeded with this tree's `Cargo.lock`, cargo resolves it once, every package mega-evm links must then be at the version and source this tree locks, with one revm, and the build runs `--locked`. The executables it runs are the ones those builds report (cargo's JSON messages), never a file at a path guessed from the target directory. - The gate passes when every case in the slice's index passes in both modes with identical observations, each report contains exactly the indexed case IDs and file digests, and every negative control matches its index entry. + The gate passes when every case in the slice's index passes in both modes with identical observation digests, each gating report contains exactly the indexed case IDs and file digests, and every negative control matches its index entry in both modes. A case failure names the case, its first differing path, both values and the rules it pins. - The negative controls exercise failure reporting: each must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. - If gating cases fail or their observations differ between modes, each control must report a failure or an error, and its first difference or error message can vary with the change. + The gate runs the negative controls in each requested mode and checks that the consumer exited 1 and reported the indexed case IDs and fixture paths relative to the suite's `slice` directory. + When the gating cases pass and their observations agree, each control must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. + If gating cases fail or their observations differ between modes, each control must report a failure or an error in every requested mode, and its first difference or error message can vary with the change. The summary is one `MEGA-EEST` line on stdout. Exit 0 means the gate passed. - Exit 1 means the reports are complete, a case failed or erred or the modes differed, and every control failed or erred. - Exit 2 means the run reached no verdict, for example due to an incomplete report, an unsupported case, a malformed control entry or a control outcome that does not satisfy the gate. + Exit 1 means the reports are complete, a case failed or erred or the modes differed, and every control failed or erred in each mode run. + Exit 2 means the run reached no verdict, for example due to a passing case without an observation digest, an unsupported case, a missing control report, a wrong fixture path or an unexpected consumer exit. Exit 3 means the cases passed and the pin is refused. The line says `run=full` for both modes, which the gate requires, and `run=partial` for one. The pin is the trust anchor of every behaviour a Mega EEST case pins in place of a deleted mega-evm test, so it is checked too: its commit must be on Mega EEST's default branch (`provenance=default-branch`, read from a blobless copy of the suite's history), and when `MEGA_EEST_BASE_REV` names the pull request base's pin, the case ids the move removes, adds and changes are listed (in the step summary on CI), and the removed ids and the ids of cases changed under them (another file digest) must be exactly those `MEGA_EEST_REMOVED_CASES` and `MEGA_EEST_CHANGED_CASES` in `scripts/mega_eest.env` declare (`caseset=declared`, or `kept` with none removed or changed); when `MEGA_EEST_BASE_REPO` names the base's repository, a pin file naming another is refused (`repo=changed`) unless its `MEGA_EEST_REPO_MOVED_FROM` names the base's exactly (`repo=moved`, the pin on the new repository's default branch), and that line set without a move is refused as stale (`repo=stale`) unless the base's carries the same; each refusal is exit 3, and the job's annotation names its causes. diff --git a/REVIEW.md b/REVIEW.md index 22ef26140..5e0630660 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -149,10 +149,12 @@ These checks guard every change to the Satin engine. - The `Mega EEST gate` job always runs, and becomes a required check once an administrator adds it to the `satin` branch rule; a pull request that changes documentation alone skips the run and passes it. The step summary has the summary line (`MEGA-EEST rev=… run=full cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… provenance=… caseset=… result=…`), the run's time and exit, and, when the pull request moves the pin, the case ids it removes, adds and changes; a failing run uploads its reports. The script's exit says what failed: 1 the cases (a verdict), 2 no verdict (a fetch, a build, a report; the log names the step), 3 the pin refused; the job also requires the line of the full run of a pin on the suite's default branch. - When all gating cases pass, every negative control must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. - If gating cases fail or their observations differ between modes, every control must still report a failure or an error. - The summary shows `negative=fail-as-recorded` when every control matches its index entry and `negative=fail-elsewhere` when the gating run fails and at least one control fails differently. - A malformed control entry, a missing control result or a passing control leaves the run without a verdict. + Each mode has a negative control report that must contain the indexed case IDs and fixture paths relative to `slice`, with consumer exit 1. + When all gating cases pass and their observations agree, every negative control must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. + If gating cases fail or their observations differ between modes, every control must still report a failure or an error in each mode. + The summary shows `negative=fail-as-recorded` when every control matches its index entry in every mode and `negative=fail-elsewhere` when the gating run fails and at least one control fails differently. + A passing case without an observation digest leaves the run without a verdict before the modes are compared. + A malformed control entry, a missing, unsupported or passing control, a mismatched fixture path or an unexpected consumer exit also leaves the run without a verdict. - A case that fails is a change of behaviour the specification pins. A pull request that makes it on purpose, or that changes the mega-evm API the suite's adapter calls (the adapter then no longer builds, and the gate says so), changes Mega EEST first: the case, derived from the changed rule, or the adapter, in a pull request there. It then moves `MEGA_EEST_REV` to that Mega EEST commit, in the same mega-evm pull request, so the gate runs the suite that pull request needs. diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index 2e4b5f221..1face693c 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -46,22 +46,21 @@ [--provenance ] [--repo ] [--caseset ] - Read the run reports `mega-fixture consume` wrote into (.json, and - negative.json for the suite's negative controls) and decide: in every mode, the - cases consumed are exactly the slice's index, by case id and file digest, and every one - passed; with both modes, every case's observations are the same bytes plain and - instrumented. When every gating case passed, each indexed negative control must fail at - its recorded path or report an error with its exact recorded message, according to its - index entry. When gating cases failed, each control must have run and reported a failure - or an error. Prints the failures (case id, first differing path, both values, the rules the - case pins) and one summary line, `MEGA-EEST … result=`, and exits with its code: + Read .json and negative-.json with their recorded exits for every requested mode. + The gating reports must match the slice's index by case ID and file digest. Each passed + case must have an observation digest before the modes are compared. Each control report + must match the indexed case IDs and fixture paths relative to slice, with consumer exit 1. + When every gating case passes and observations agree, each negative control must fail at + its indexed path or report an error with its exact indexed message. If a gating case + fails or the observations differ, a control can report any failure or error. + Prints the failures (case ID, first differing path, both values, the rules the case pins) + and one summary line, `MEGA-EEST … result=`, and exits with its code: 0 pass; 1 FAIL, a verdict (complete reports of exactly the index in every mode, a case failed or erred, or the modes' observations differ, and every control failed or erred); 2 INCOMPLETE, no verdict (no mode, a report missing, cases that are not the index, a - consume exit its report does not explain, a case the adapter does not support, a case - status other than the consumer's four (pass, fail, unsupported, error), a missing or - malformed control, a control not run or passing, a control that did not fail as recorded - while every gating case passed, or the checker itself failing). + consume exit its report does not explain, a passing case with no observation digest, + an unsupported case, an unknown case status, a missing or malformed control, + an unexpected control consumer exit, an unsatisfied control, or a checker error). 3 REFUSED means every case passed and the pin has a cause `refusal` names, such as `provenance=unmerged`, `repo=changed`, `repo=stale`, a repository move with unchecked provenance, or `caseset=undeclared`. @@ -418,7 +417,8 @@ def cmd_check(args: argparse.Namespace) -> int: def check(args: argparse.Namespace) -> int: suite, work = Path(args.suite), Path(args.work) modes = list(dict.fromkeys(args.modes.split())) - index = json.loads((suite / "slice" / "index.json").read_text()) + slice_dir = (suite / "slice").absolute() + index = json.loads((slice_dir / "index.json").read_text()) expected = Counter((c["caseId"], c["fileDigest"]) for c in index["cases"]) total = sum(expected.values()) run = "full" if {"plain", "instrumented"} <= set(modes) else "partial" @@ -426,7 +426,7 @@ def check(args: argparse.Namespace) -> int: # Why the run reached no verdict; and whether a case failed in a run that did. incomplete: list[str] = [] cases_failed = False - observations: dict[str, dict[str, str | None]] = {} + observations: dict[str, dict[str, str]] = {} if not modes: incomplete.append("no mode was run") @@ -450,7 +450,17 @@ def check(args: argparse.Namespace) -> int: got = Counter((c.get("caseId"), c.get("fileDigest")) for c in cases) missing, extra = expected - got, got - expected not_passed = [c for c in cases if c["status"] != "pass"] - observations[mode] = {c.get("caseId"): c.get("observationsDigest") for c in cases} + mode_observations = observations[mode] = {} + missing_digests = [] + for case in cases: + digest = case.get("observationsDigest") + if isinstance(digest, str) and digest: + mode_observations[case.get("caseId")] = digest + elif case["status"] == "pass": + missing_digests.append(case.get("caseId")) + if missing_digests: + incomplete.append(f"{mode}: passed case {missing_digests[0]} has no observation digest " + f"({len(missing_digests)} passed case(s) without a digest)") for c in not_passed[:MAX_SHOWN]: line = f"mega-eest: {mode}: {c['status']} {c.get('caseId') or c['file']}" if c["status"] == "fail": @@ -488,20 +498,41 @@ def check(args: argparse.Namespace) -> int: summary.append(f"{mode}=" + ",".join(f"{s}:{statuses.get(s, 0)}" for s in CASE_STATUSES) + "".join(f",{k}:{statuses[k]}" for k in sorted(set(statuses) - set(CASE_STATUSES)))) - if {"plain", "instrumented"} <= observations.keys(): + if not incomplete and {"plain", "instrumented"} <= observations.keys(): plain, inst = observations["plain"], observations["instrumented"] - differ = sorted(k for k in plain.keys() | inst.keys() - if plain.get(k) is None or plain.get(k) != inst.get(k)) + # An adapter error can stop a case before it produces observations. + differ = sorted(k for k in plain.keys() & inst.keys() if plain[k] != inst[k]) for case in differ[:MAX_SHOWN]: print(f"mega-eest: parity: {case}: plain {plain.get(case)} instrumented {inst.get(case)}", file=sys.stderr) summary.append(f"parity={'identical' if not differ else f'{len(differ)}-differ'}") cases_failed |= bool(differ) - # The controls show that the consumer can report a mismatch or an adapter error. - # When gating cases failed, a change of behaviour can also change a control's first failure. - negative_path = work / "negative.json" - controls = index.get("negative", []) + verdict = check_controls(index.get("negative", []), modes, slice_dir, work, cases_failed, incomplete) + summary.append(f"negative={verdict}") + summary.append(f"provenance={args.provenance}") + repo = getattr(args, "repo", "unchecked") + summary.append(f"repo={repo}") + summary.append(f"caseset={args.caseset}") + + if incomplete: + result = "INCOMPLETE" + elif cases_failed: + result = "FAIL" + elif refusal_causes({"provenance": args.provenance, "repo": repo, "caseset": args.caseset}): + result = "REFUSED" + else: + result = "pass" + for reason in incomplete: + print(f"mega-eest: error: no verdict: {reason}", file=sys.stderr) + summary.append(f"result={result}") + print("MEGA-EEST " + " ".join(summary)) + return RESULT_EXIT[result] + + +def check_controls(controls, modes: list[str], slice_dir: Path, work: Path, cases_failed: bool, + incomplete: list[str]) -> str: + """Check that each mode's controls demonstrate mismatch and adapter error reporting.""" control_keys = {"caseId", "file"} if not isinstance(controls, list) or any( not isinstance(control, dict) @@ -509,24 +540,40 @@ def check(args: argparse.Namespace) -> int: or not all(isinstance(value, str) and value for value in control.values()) for control in controls ): - verdict = "invalid-index" incomplete.append("malformed negative control index: expected caseId, file and exactly one of wrongAt or error") - elif len({control["caseId"] for control in controls}) != len(controls): - verdict = "invalid-index" + return "invalid-index" + indexed_files = {control["caseId"]: Path(control["file"]) for control in controls} + if len(indexed_files) != len(controls): incomplete.append("malformed negative control index: repeated case IDs") - elif not controls: - verdict = "none" + return "invalid-index" + if any(path.is_absolute() or ".." in path.parts for path in indexed_files.values()): + incomplete.append("malformed negative control index: each file must be relative to the slice") + return "invalid-index" + if not controls: incomplete.append("the slice's index lists no negative control") - elif not negative_path.exists(): - verdict = "no-report" - incomplete.append("`mega-fixture consume` wrote no report of the negative controls") - else: + return "none" + if not modes: + return "no-report" + + states = set() + for mode in modes: + negative_path = work / f"negative-{mode}.json" + exit_path = work / f"negative-{mode}.exit" + code = exit_path.read_text().strip() if exit_path.exists() else "?" + if not negative_path.exists(): + states.add("no-report") + incomplete.append(f"{mode}: negative controls: no report (exit {code}); " + f"see {negative_path.with_suffix('.log')}") + continue + # A completed consume with at least one non-passing case exits 1. + if code != "1": + states.add("not-caught") + incomplete.append(f"{mode}: negative controls: `mega-fixture consume` exited {code}; expected 1") reports = json.loads(negative_path.read_text())["cases"] cases = {report.get("caseId"): report for report in reports} - states = set() - if len(cases) != len(reports) or cases.keys() - {control["caseId"] for control in controls}: + if len(cases) != len(reports) or cases.keys() - indexed_files.keys(): states.add("not-caught") - incomplete.append("negative control report has extra or repeated case IDs") + incomplete.append(f"{mode}: negative control report has extra or repeated case IDs") for control in controls: case_id = control["caseId"] if "wrongAt" in control: @@ -534,42 +581,30 @@ def check(args: argparse.Namespace) -> int: else: status, field, value = "error", "message", control["error"] report = cases.get(case_id) + if report: + file = report.get("file") + if not isinstance(file, str) or Path(file).absolute() != slice_dir / indexed_files[case_id]: + states.add("not-caught") + incomplete.append(f"{mode}: negative control {case_id} expected fixture {indexed_files[case_id]}, " + f"reported {canonical(file)}") + continue if report and report["status"] == status and report.get(field) == value: - states.add("fail-as-recorded") continue want = f"{status} with {field} {canonical(value)}" seen = (f"{report['status']} with {field} {canonical(report.get(field))}" if report else "not consumed") + # A gating failure can also change a control's first failure. if report and report["status"] in ("fail", "error") and cases_failed: states.add("fail-elsewhere") - print(f"mega-eest: negative control {case_id} expected {want} ({seen}); " + print(f"mega-eest: {mode}: negative control {case_id} expected {want} ({seen}); " f"gating cases failed, which can move where it first differs", file=sys.stderr) else: states.add("not-caught") why = ("gating cases failed, and it did not fail" if cases_failed else "every gating case passed, so it must match the recorded failure") - incomplete.append(f"negative control {case_id} expected {want} ({seen}): {why}") - verdict = ("not-caught" if "not-caught" in states - else "fail-elsewhere" if "fail-elsewhere" in states else "fail-as-recorded") - summary.append(f"negative={verdict}") - summary.append(f"provenance={args.provenance}") - repo = getattr(args, "repo", "unchecked") - summary.append(f"repo={repo}") - summary.append(f"caseset={args.caseset}") - - if incomplete: - result = "INCOMPLETE" - elif cases_failed: - result = "FAIL" - elif refusal_causes({"provenance": args.provenance, "repo": repo, "caseset": args.caseset}): - result = "REFUSED" - else: - result = "pass" - for reason in incomplete: - print(f"mega-eest: error: no verdict: {reason}", file=sys.stderr) - summary.append(f"result={result}") - print("MEGA-EEST " + " ".join(summary)) - return RESULT_EXIT[result] + incomplete.append(f"{mode}: negative control {case_id} expected {want} ({seen}): {why}") + return next((state for state in ("no-report", "not-caught", "fail-elsewhere") if state in states), + "fail-as-recorded") # ---- refusal ---------------------------------------------------------------------------------- diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index fd7c7dd6a..0ec12ef86 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -38,14 +38,16 @@ # build runs --locked on that lock. # Cargo runs from this checkout's root, so the toolchain is its rust-toolchain.toml and the # configuration its .cargo/config.toml. -# 5. Consumes every gating case (slice/cases) with `mega-fixture consume` in each mode of -# $MEGA_EEST_MODES, plain and --instrumented by default, and the suite's negative controls -# (slice/negative). -# 6. Decides (scripts/mega_eest.py check): in each mode the cases consumed are exactly the slice's -# index and every one passed, with identical plain and instrumented observations. When every -# gating case passed, each indexed negative control must fail at its `wrongAt` path or report -# status `error` with its exact `error` message, according to its index entry. When gating cases -# failed, each control must have run and reported a failure or an error. +# 5. Consumes every gating case (slice/cases) and negative control (slice/negative) with +# `mega-fixture consume` in each mode of $MEGA_EEST_MODES, plain and --instrumented by default. +# It saves each control run's report, log and exit as negative-.{json,log,exit}. +# 6. Uses scripts/mega_eest.py check to decide. Each mode's gating report must match the slice's +# index, and each passing case needs an observation digest before plain and instrumented +# observations can be compared. Each control report must match the indexed case IDs and +# fixture paths, relative to slice, and its consumer must have exited 1. When every gating +# case passed and the observations agree, each control must fail at its indexed `wrongAt` +# path or report status `error` with its exact indexed `error` message. A gating failure or an +# observation difference allows each control to report any failure or error. # A failure prints the case id, the first differing path and both values, and the rules the # case pins. # @@ -56,7 +58,7 @@ # repo= caseset= # result= # -# `negative=fail-as-recorded` means every control matched its own expectation. +# `negative=fail-as-recorded` means every control matched its own expectation in every mode run. # `fail-elsewhere` means each control failed or erred and at least one differed during a failing run. # `not-caught` means the report did not meet the conditions for a verdict. # `none`, `invalid-index` and `no-report` identify missing controls, malformed entries and a missing report. @@ -70,12 +72,12 @@ # the pin's checks passed or were skipped (result=pass) # 1 the cases failed: every mode ran to a complete report of exactly the slice's cases, a case # failed or erred or plain and instrumented observations differ, and every negative control -# failed or erred (result=FAIL). The only exit that is a verdict -# on this tree. +# failed or erred in every mode (result=FAIL). The only exit that is a verdict on this tree. # 2 no verdict: anything that kept the run from one, a fetch, a build, the resolution, the lock # check, a report missing or incomplete, cases that are not the index, a case the adapter does -# not support, no mode, missing or malformed controls, a control not run or passing, or -# a control that did not match the index while every gating case passed (result=INCOMPLETE) +# not support, a passing case without an observation digest, no mode, missing or malformed +# controls, a control consumer exit other than 1, or a control outcome that does not satisfy +# the gate (result=INCOMPLETE) # 3 the cases passed, but the pin is refused: not on Mega EEST's default branch, in another # repository than the base's without a declared move, with a stale move declaration, or it # removes or changes cases scripts/mega_eest.env does not declare (result=REFUSED; the log @@ -388,7 +390,7 @@ printf '%s\n' "$ADAPTER" > "$WORK/adapter.path" "$ADAPTER" capabilities > "$WORK/capabilities.json" || die "the adapter does not report its capabilities" STAGE=consume -rm -f "$WORK"/plain.* "$WORK"/instrumented.* "$WORK"/negative.* +rm -f "$WORK"/plain.* "$WORK"/instrumented.* "$WORK"/negative.* "$WORK"/negative-{plain,instrumented}.* for mode in $MODE_WORDS; do flag=() [ "$mode" = instrumented ] && flag=(--instrumented) @@ -398,10 +400,13 @@ for mode in $MODE_WORDS; do --report "$WORK/$mode.json" "$SUITE/slice/cases" > "$WORK/$mode.log" || rc=$? echo "$rc" > "$WORK/$mode.exit" grep '^CONSUME ' "$WORK/$mode.log" >&2 || log "$mode: no CONSUME line; see $WORK/$mode.log" + + log "consuming slice/negative, $mode ($(elapsed))" + rc=0 + "$CLI" consume --adapter "$ADAPTER" ${flag[@]+"${flag[@]}"} --specs "$SUITE/specs" \ + --report "$WORK/negative-$mode.json" "$SUITE/slice/negative" > "$WORK/negative-$mode.log" || rc=$? + echo "$rc" > "$WORK/negative-$mode.exit" done -log "consuming slice/negative, the negative controls ($(elapsed))" -"$CLI" consume --adapter "$ADAPTER" --specs "$SUITE/specs" --report "$WORK/negative.json" \ - "$SUITE/slice/negative" > "$WORK/negative.log" || true # The checker prints the summary line and exits with the code it names; anything else, a crash # included, is no verdict. diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 8082fcbb8..13493feca 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -264,7 +264,8 @@ class Check(Case): """The run reports decide the result, and its exit code says whether it is a verdict.""" CASES = [("satin/a", "sha256:1"), ("satin/b", "sha256:2")] - NEGATIVE = [{"caseId": "satin/negative/wrong", "status": "fail", "path": "/expected/x"}] + NEGATIVE = [{"caseId": "satin/negative/wrong", "file": "negative/wrong.json", + "status": "fail", "path": "/expected/x"}] INDEX_NEGATIVE = [{"caseId": "satin/negative/wrong", "file": "negative/wrong.json", "wrongAt": "/expected/x"}] ORACLE_CONTROL = {"caseId": "satin/negative/oracle", "file": "negative/oracle.json", @@ -273,7 +274,7 @@ class Check(Case): def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | None = None, exits: dict[str, int] | None = None, *, modes: str | None = None, index_negative: list[dict] | None = None, provenance: str = "unchecked", - caseset: str = "unchecked") -> tuple[int, str, str]: + repo: str = "unchecked", caseset: str = "unchecked") -> tuple[int, str, str]: # A fresh pair for every call: a test may write several runs. run = Path(tempfile.mkdtemp(dir=self.tmp)) suite, work = run / "suite", run / "work" @@ -288,11 +289,15 @@ def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | No (work / f"{mode}.json").write_text(json.dumps({"cases": cases})) default = 1 if cases and any(c["status"] != "pass" for c in cases) else 0 (work / f"{mode}.exit").write_text(f"{(exits or {}).get(mode, default)}\n") - if negative is not None: - (work / "negative.json").write_text(json.dumps({"cases": negative})) + if negative is not None: + controls = [{**c, "file": str(suite / "slice" / c["file"])} if "file" in c else c + for c in negative] + (work / f"negative-{mode}.json").write_text(json.dumps({"cases": controls})) + control_exit = 1 if any(c["status"] != "pass" for c in controls) else 0 + (work / f"negative-{mode}.exit").write_text(f"{control_exit}\n") return self.run_quietly(eest.cmd_check, Namespace( suite=str(suite), work=str(work), modes=" ".join(reports) if modes is None else modes, - rev="f" * 40, provenance=provenance, caseset=caseset)) + rev="f" * 40, provenance=provenance, repo=repo, caseset=caseset)) @staticmethod def case(case_id: str, digest: str, status: str = "pass", observations: str = "sha256:o") -> dict: @@ -335,11 +340,24 @@ def test_a_failing_or_erring_case_is_a_verdict(self) -> None: def test_observations_that_differ_between_modes_are_a_verdict(self) -> None: other = [self.case("satin/a", "sha256:1"), self.case("satin/b", "sha256:2", observations="sha256:other")] - code, out, err = self.write({"plain": self.all_passed(), "instrumented": other}, self.NEGATIVE) + code, out, err = self.write({"plain": self.all_passed(), "instrumented": other}, + self.control("fail", "/expected/y")) self.assertEqual(code, 1, err) self.assertIn("parity=1-differ", out) + self.assertIn("negative=fail-elsewhere", out) self.assertIn("result=FAIL", out) + def test_a_passing_case_without_a_digest_is_incomplete_before_parity(self) -> None: + for modes, control, verdict in (("plain instrumented", self.control("fail", "/expected/y"), "not-caught"), + ("instrumented", self.NEGATIVE, "fail-as-recorded")): + with self.subTest(modes=modes): + reports = {mode: self.all_passed() for mode in modes.split()} + del reports["instrumented"][1]["observationsDigest"] + run = self.write(reports, control) + self.assert_no_verdict(*run, "instrumented: passed case satin/b has no observation digest") + self.assertNotIn(" parity=", run[1]) + self.assertIn(f"negative={verdict}", run[1]) + def assert_no_verdict(self, code: int, out: str, err: str, reason: str) -> None: self.assertEqual(code, 2, (out, err)) self.assertTrue(out.strip().endswith("result=INCOMPLETE"), out) @@ -384,7 +402,7 @@ def test_an_unsupported_case_is_no_verdict(self) -> None: @staticmethod def control(status: str, path: str | None = None) -> list[dict]: - case = {"caseId": "satin/negative/wrong", "status": status} + case = {"caseId": "satin/negative/wrong", "file": "negative/wrong.json", "status": status} if path is not None: case["path"] = path return [case] @@ -403,7 +421,7 @@ def test_failing_cases_with_a_control_that_did_not_fail_are_no_verdict(self) -> for control, reason in ((self.control("pass"), "gating cases failed, and it did not fail"), (self.control("unsupported"), "gating cases failed, and it did not fail"), ([], "not consumed"), - (None, "no report of the negative controls")): + (None, "negative controls: no report")): code, out, err = self.write({"plain": self.one_failing()}, control) self.assert_no_verdict(code, out, err, reason) @@ -411,7 +429,7 @@ def test_passing_cases_need_the_control_to_fail_where_recorded(self) -> None: for control, reason in ((self.control("fail", "/expected/y"), "so it must match the recorded failure"), (self.control("error"), "so it must match the recorded failure"), (self.control("pass"), "so it must match the recorded failure"), - (None, "no report of the negative controls")): + (None, "negative controls: no report")): code, out, err = self.write({"plain": self.all_passed()}, control) self.assert_no_verdict(code, out, err, reason) self.assertNotIn("negative=fail-as-recorded", out) @@ -421,6 +439,7 @@ def test_passing_cases_need_the_control_to_fail_where_recorded(self) -> None: def test_passing_cases_accept_both_recorded_control_forms(self) -> None: oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "status": "error", + "file": "negative/oracle.json", "message": self.ORACLE_CONTROL["error"]} code, out, err = self.write({"plain": self.all_passed()}, [*self.NEGATIVE, oracle], index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) @@ -432,7 +451,7 @@ def test_passing_cases_require_the_exact_recorded_error(self) -> None: for result in ({"status": "error", "message": self.ORACLE_CONTROL["error"] + " (retry)"}, {"status": "fail", "path": "/expected/x", "message": self.ORACLE_CONTROL["error"]}): with self.subTest(result=result): - oracle = {"caseId": self.ORACLE_CONTROL["caseId"], **result} + oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "file": "negative/oracle.json", **result} code, out, err = self.write({"plain": self.all_passed()}, [*self.NEGATIVE, oracle], index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) self.assert_no_verdict(code, out, err, "so it must match the recorded failure") @@ -442,7 +461,8 @@ def test_malformed_control_entries_are_no_verdict(self) -> None: entry = self.INDEX_NEGATIVE[0] common = {k: entry[k] for k in ("caseId", "file")} for malformed in (common, {**entry, "error": "an error"}, {**entry, "extra": "unexpected"}, - {**entry, "wrongAt": None}): + {**entry, "wrongAt": None}, {**entry, "file": "/wrong.json"}, + {**entry, "file": "../wrong.json"}): with self.subTest(entry=malformed): code, out, err = self.write({"plain": self.one_failing()}, self.NEGATIVE, index_negative=[malformed]) @@ -451,6 +471,7 @@ def test_malformed_control_entries_are_no_verdict(self) -> None: def test_failing_cases_accept_an_error_control_that_errs_differently(self) -> None: oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "status": "error", + "file": "negative/oracle.json", "message": "a different adapter error"} code, out, err = self.write({"plain": self.one_failing()}, [*self.NEGATIVE, oracle], index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) @@ -459,7 +480,7 @@ def test_failing_cases_accept_an_error_control_that_errs_differently(self) -> No self.assertTrue(out.strip().endswith("result=FAIL"), out) def test_failing_cases_with_an_error_control_that_passes_are_no_verdict(self) -> None: - oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "status": "pass"} + oracle = {"caseId": self.ORACLE_CONTROL["caseId"], "file": "negative/oracle.json", "status": "pass"} code, out, err = self.write({"plain": self.one_failing()}, [*self.NEGATIVE, oracle], index_negative=[*self.INDEX_NEGATIVE, self.ORACLE_CONTROL]) self.assert_no_verdict(code, out, err, "gating cases failed, and it did not fail") @@ -472,23 +493,22 @@ def test_an_extra_or_repeated_control_report_is_no_verdict(self) -> None: self.assert_no_verdict(code, out, err, "negative control report has extra or repeated case IDs") self.assertIn("negative=not-caught", out) + def test_a_control_report_must_name_the_indexed_file(self) -> None: + index_negative = [{**self.INDEX_NEGATIVE[0], "file": "negative/other.json"}] + for gating, control in ((self.all_passed(), self.NEGATIVE), + (self.one_failing(), self.control("error"))): + with self.subTest(gating=gating): + run = self.write({"plain": gating}, control, index_negative=index_negative) + self.assert_no_verdict(*run, "expected fixture negative/other.json") + self.assertIn("negative=not-caught", run[1]) + def test_a_changed_repository_is_refused(self) -> None: - run = Path(tempfile.mkdtemp(dir=self.tmp)) - (run / "suite" / "slice").mkdir(parents=True) - (run / "work").mkdir() - (run / "suite" / "slice" / "index.json").write_text(json.dumps({ - "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], - "negative": self.INDEX_NEGATIVE})) - (run / "work" / "plain.json").write_text(json.dumps({"cases": self.all_passed()})) - (run / "work" / "plain.exit").write_text("0\n") - (run / "work" / "negative.json").write_text(json.dumps({"cases": self.NEGATIVE})) for provenance, repo, want in (("default-branch", "changed", 3), ("default-branch", "stale", 3), ("default-branch", "moved", 0), ("unchecked", "moved", 3), ("default-branch", "same", 0), ("unchecked", "same", 0), ("default-branch", "unchecked", 0)): - code, out, err = self.run_quietly(eest.cmd_check, Namespace( - suite=str(run / "suite"), work=str(run / "work"), modes="plain", rev="f" * 40, - provenance=provenance, repo=repo, caseset="kept")) + code, out, err = self.write({"plain": self.all_passed()}, self.NEGATIVE, + provenance=provenance, repo=repo, caseset="kept") self.assertEqual(code, want, (provenance, repo, err)) self.assertIn(f"provenance={provenance} repo={repo} caseset=kept", out) @@ -717,7 +737,12 @@ def test_removals_must_be_declared_exactly(self) -> None: adapter, report, path = args[args.index("--adapter") + 1], args[args.index("--report") + 1], Path(args[-1]) index = json.loads((path.parent / "index.json").read_text()) if path.name == "negative": - cases = [{"caseId": n["caseId"], "fileDigest": "sha256:n", "status": "fail", + status = "fail" + if "--instrumented" in args: + status = os.environ.get("FAKE_INSTRUMENTED_CONTROL", status) + if status == "no-report": + sys.exit(2) + cases = [{"caseId": n["caseId"], "file": str(path / "wrong.json"), "fileDigest": "sha256:n", "status": status, "path": os.environ.get("FAKE_CONTROL_PATH") or n["wrongAt"]} for n in index["negative"]] else: failing = subprocess.run([adapter, "verdict"], capture_output=True, text=True).stdout.strip() == "fail" @@ -727,6 +752,8 @@ def test_removals_must_be_declared_exactly(self) -> None: Path(report).write_text(json.dumps({"cases": cases})) passed = sum(c["status"] == "pass" for c in cases) print(f"CONSUME adapter=fake cases={len(cases)} pass={passed} fail={len(cases) - passed} unsupported=0 error=0") +if path.name == "negative" and "--instrumented" in args and "FAKE_INSTRUMENTED_CONTROL_EXIT" in os.environ: + sys.exit(int(os.environ["FAKE_INSTRUMENTED_CONTROL_EXIT"])) sys.exit(0 if passed == len(cases) else 1) """ @@ -839,6 +866,27 @@ def test_failing_cases_are_the_only_exit_1(self) -> None: self.assertEqual(code, 1, err) self.assertRegex(self.summary(out), r" run=partial cases=3 plain=pass:0,fail:3,.* result=FAIL$") + def test_every_requested_mode_needs_a_failing_control(self) -> None: + for modes in ("plain instrumented", "instrumented"): + for gating in ("pass", "fail"): + for control in ("no-report", "unsupported", "pass"): + with self.subTest(modes=modes, gating=gating, control=control): + code, out, err = self.run_script(MEGA_EEST_MODES=modes, FAKE_VERDICT=gating, + FAKE_INSTRUMENTED_CONTROL=control) + self.assertEqual(code, 2, (out, err)) + self.assertRegex(self.summary(out), r" result=INCOMPLETE$") + self.assertIn("instrumented: negative control", err) + + def test_a_control_report_cannot_mask_the_consumer_exit(self) -> None: + for gating in ("pass", "fail"): + for exit_code in (0, 2, 101): + with self.subTest(gating=gating, exit_code=exit_code): + code, out, err = self.run_script(FAKE_VERDICT=gating, + FAKE_INSTRUMENTED_CONTROL_EXIT=str(exit_code)) + self.assertEqual(code, 2, (out, err)) + self.assertRegex(self.summary(out), r" negative=not-caught .* result=INCOMPLETE$") + self.assertIn(f"instrumented: negative controls: `mega-fixture consume` exited {exit_code}", err) + def test_failing_cases_that_move_the_control_are_still_exit_1(self) -> None: # A change that fails the cases can also move where the control first differs. code, out, err = self.run_script(FAKE_VERDICT="fail", FAKE_CONTROL_PATH="/expected/gasLedgers/gasUsed") From 8023d6fec9757aab783086fd16afc84a898b7c13 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:16:22 +0800 Subject: [PATCH 165/190] fix(ci): validate Mega EEST report modes and parity --- AGENTS.md | 2 ++ REVIEW.md | 2 ++ scripts/mega_eest.py | 35 ++++++++++++++++++++++++++++------- scripts/mega_eest.sh | 11 ++++++----- scripts/test_mega_eest.py | 38 ++++++++++++++++++++++++++++++++++---- 5 files changed, 72 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2d614f4e3..1ae81dae6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -673,6 +673,8 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te The adapter's `Cargo.lock`, resolved for the commit it pins, is not used: the workspace's lock is seeded with this tree's `Cargo.lock`, cargo resolves it once, every package mega-evm links must then be at the version and source this tree locks, with one revm, and the build runs `--locked`. The executables it runs are the ones those builds report (cargo's JSON messages), never a file at a path guessed from the target directory. The gate passes when every case in the slice's index passes in both modes with identical observation digests, each gating report contains exactly the indexed case IDs and file digests, and every negative control matches its index entry in both modes. + Every gating or control report must declare its requested mode. + When the gate compares modes, a case that errors without an observation digest in either mode counts as a parity difference. A case failure names the case, its first differing path, both values and the rules it pins. The gate runs the negative controls in each requested mode and checks that the consumer exited 1 and reported the indexed case IDs and fixture paths relative to the suite's `slice` directory. When the gating cases pass and their observations agree, each control must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. diff --git a/REVIEW.md b/REVIEW.md index 5e0630660..0f0865c87 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -150,10 +150,12 @@ These checks guard every change to the Satin engine. The step summary has the summary line (`MEGA-EEST rev=… run=full cases=… plain=pass:…,fail:…,unsupported:…,error:… instrumented=… parity=… negative=… provenance=… caseset=… result=…`), the run's time and exit, and, when the pull request moves the pin, the case ids it removes, adds and changes; a failing run uploads its reports. The script's exit says what failed: 1 the cases (a verdict), 2 no verdict (a fetch, a build, a report; the log names the step), 3 the pin refused; the job also requires the line of the full run of a pin on the suite's default branch. Each mode has a negative control report that must contain the indexed case IDs and fixture paths relative to `slice`, with consumer exit 1. + A gating or control report with a missing or mismatched mode leaves the run without a verdict. When all gating cases pass and their observations agree, every negative control must fail at its indexed `wrongAt` path or report status `error` with the exact indexed `error` message. If gating cases fail or their observations differ between modes, every control must still report a failure or an error in each mode. The summary shows `negative=fail-as-recorded` when every control matches its index entry in every mode and `negative=fail-elsewhere` when the gating run fails and at least one control fails differently. A passing case without an observation digest leaves the run without a verdict before the modes are compared. + A case that errors without an observation digest in either mode counts as a parity difference. A malformed control entry, a missing, unsupported or passing control, a mismatched fixture path or an unexpected consumer exit also leaves the run without a verdict. - A case that fails is a change of behaviour the specification pins. A pull request that makes it on purpose, or that changes the mega-evm API the suite's adapter calls (the adapter then no longer builds, and the gate says so), changes Mega EEST first: the case, derived from the changed rule, or the adapter, in a pull request there. diff --git a/scripts/mega_eest.py b/scripts/mega_eest.py index 1face693c..884fa0816 100755 --- a/scripts/mega_eest.py +++ b/scripts/mega_eest.py @@ -47,9 +47,11 @@ [--repo ] [--caseset ] Read .json and negative-.json with their recorded exits for every requested mode. - The gating reports must match the slice's index by case ID and file digest. Each passed - case must have an observation digest before the modes are compared. Each control report - must match the indexed case IDs and fixture paths relative to slice, with consumer exit 1. + Each report must identify the requested mode. The gating reports must match the slice's + index by case ID and file digest. Each passed case must have an observation digest before + the modes are compared. If both modes ran and a case errored without observations, its + missing digest counts as a parity difference. Each control report must match the indexed + case IDs and fixture paths relative to slice, with consumer exit 1. When every gating case passes and observations agree, each negative control must fail at its indexed path or report an error with its exact indexed message. If a gating case fails or the observations differ, a control can report any failure or error. @@ -404,6 +406,16 @@ def canonical(value) -> str: RESULT_EXIT = {"pass": 0, "FAIL": 1, "INCOMPLETE": 2, "REFUSED": 3} +def read_report(path: Path, mode: str, incomplete: list[str]) -> dict | None: + report = json.loads(path.read_text()) + reported_mode = report.get("mode") + if reported_mode != mode: + incomplete.append(f"{path.name}: expected report mode {canonical(mode)}, " + f"got {canonical(reported_mode)}") + return None + return report + + def cmd_check(args: argparse.Namespace) -> int: """`check`; no failure of the checker itself can read as a verdict.""" try: @@ -445,7 +457,11 @@ def check(args: argparse.Namespace) -> int: f"see {work / (mode + '.log')}") summary.append(f"{mode}=no-report") continue - cases = json.loads(report_path.read_text())["cases"] + report = read_report(report_path, mode, incomplete) + if report is None: + summary.append(f"{mode}=invalid-mode") + continue + cases = report["cases"] statuses = Counter(c["status"] for c in cases) got = Counter((c.get("caseId"), c.get("fileDigest")) for c in cases) missing, extra = expected - got, got - expected @@ -500,8 +516,9 @@ def check(args: argparse.Namespace) -> int: if not incomplete and {"plain", "instrumented"} <= observations.keys(): plain, inst = observations["plain"], observations["instrumented"] - # An adapter error can stop a case before it produces observations. - differ = sorted(k for k in plain.keys() & inst.keys() if plain[k] != inst[k]) + # An adapter error can leave an indexed case without observations in either mode. + differ = sorted({case_id for case_id, _ in expected + if case_id not in plain or plain[case_id] != inst.get(case_id)}) for case in differ[:MAX_SHOWN]: print(f"mega-eest: parity: {case}: plain {plain.get(case)} instrumented {inst.get(case)}", file=sys.stderr) @@ -569,7 +586,11 @@ def check_controls(controls, modes: list[str], slice_dir: Path, work: Path, case if code != "1": states.add("not-caught") incomplete.append(f"{mode}: negative controls: `mega-fixture consume` exited {code}; expected 1") - reports = json.loads(negative_path.read_text())["cases"] + control_report = read_report(negative_path, mode, incomplete) + if control_report is None: + states.add("not-caught") + continue + reports = control_report["cases"] cases = {report.get("caseId"): report for report in reports} if len(cases) != len(reports) or cases.keys() - indexed_files.keys(): states.add("not-caught") diff --git a/scripts/mega_eest.sh b/scripts/mega_eest.sh index 0ec12ef86..6e6481621 100755 --- a/scripts/mega_eest.sh +++ b/scripts/mega_eest.sh @@ -41,11 +41,12 @@ # 5. Consumes every gating case (slice/cases) and negative control (slice/negative) with # `mega-fixture consume` in each mode of $MEGA_EEST_MODES, plain and --instrumented by default. # It saves each control run's report, log and exit as negative-.{json,log,exit}. -# 6. Uses scripts/mega_eest.py check to decide. Each mode's gating report must match the slice's -# index, and each passing case needs an observation digest before plain and instrumented -# observations can be compared. Each control report must match the indexed case IDs and -# fixture paths, relative to slice, and its consumer must have exited 1. When every gating -# case passed and the observations agree, each control must fail at its indexed `wrongAt` +# 6. Uses scripts/mega_eest.py check to decide. Each report must identify the requested mode. +# Each mode's gating report must match the slice's index, and each passing case needs an +# observation digest before plain and instrumented observations can be compared. An errored +# case without a digest in either mode counts as a parity difference. Each control report must +# match the indexed case IDs and fixture paths relative to slice, with consumer exit 1. When +# every gating case passed and the observations agree, each control must fail at its indexed `wrongAt` # path or report status `error` with its exact indexed `error` message. A gating failure or an # observation difference allows each control to report any failure or error. # A failure prints the case id, the first differing path and both values, and the rules the diff --git a/scripts/test_mega_eest.py b/scripts/test_mega_eest.py index 13493feca..0ff4f7650 100644 --- a/scripts/test_mega_eest.py +++ b/scripts/test_mega_eest.py @@ -274,7 +274,8 @@ class Check(Case): def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | None = None, exits: dict[str, int] | None = None, *, modes: str | None = None, index_negative: list[dict] | None = None, provenance: str = "unchecked", - repo: str = "unchecked", caseset: str = "unchecked") -> tuple[int, str, str]: + repo: str = "unchecked", caseset: str = "unchecked", + report_modes: dict[str, str | None] | None = None) -> tuple[int, str, str]: # A fresh pair for every call: a test may write several runs. run = Path(tempfile.mkdtemp(dir=self.tmp)) suite, work = run / "suite", run / "work" @@ -284,15 +285,23 @@ def write(self, reports: dict[str, list[dict] | None], negative: list[dict] | No "cases": [{"caseId": c, "fileDigest": d} for c, d in self.CASES], "negative": self.INDEX_NEGATIVE if index_negative is None else index_negative, })) + + def write_report(stem: str, mode: str, cases: list[dict]) -> None: + reported_mode = (report_modes or {}).get(stem, mode) + report = {"cases": cases} + if reported_mode is not None: + report["mode"] = reported_mode + (work / f"{stem}.json").write_text(json.dumps(report)) + for mode, cases in reports.items(): if cases is not None: - (work / f"{mode}.json").write_text(json.dumps({"cases": cases})) + write_report(mode, mode, cases) default = 1 if cases and any(c["status"] != "pass" for c in cases) else 0 (work / f"{mode}.exit").write_text(f"{(exits or {}).get(mode, default)}\n") if negative is not None: controls = [{**c, "file": str(suite / "slice" / c["file"])} if "file" in c else c for c in negative] - (work / f"negative-{mode}.json").write_text(json.dumps({"cases": controls})) + write_report(f"negative-{mode}", mode, controls) control_exit = 1 if any(c["status"] != "pass" for c in controls) else 0 (work / f"negative-{mode}.exit").write_text(f"{control_exit}\n") return self.run_quietly(eest.cmd_check, Namespace( @@ -347,6 +356,18 @@ def test_observations_that_differ_between_modes_are_a_verdict(self) -> None: self.assertIn("negative=fail-elsewhere", out) self.assertIn("result=FAIL", out) + def test_parity_counts_cases_without_an_observation_pair(self) -> None: + for modes_without_digest in (("plain",), ("instrumented",), ("plain", "instrumented")): + with self.subTest(modes_without_digest=modes_without_digest): + reports = {"plain": self.all_passed(), "instrumented": self.all_passed()} + for mode in modes_without_digest: + reports[mode] = self.one_failing("error") + del reports[mode][1]["observationsDigest"] + code, out, err = self.write(reports, self.NEGATIVE) + self.assertEqual(code, 1, err) + self.assertIn("parity=1-differ", out) + self.assertIn("result=FAIL", out) + def test_a_passing_case_without_a_digest_is_incomplete_before_parity(self) -> None: for modes, control, verdict in (("plain instrumented", self.control("fail", "/expected/y"), "not-caught"), ("instrumented", self.NEGATIVE, "fail-as-recorded")): @@ -383,6 +404,14 @@ def test_a_mode_without_a_report_is_no_verdict(self) -> None: self.assert_no_verdict(code, out, err, "wrote no report (exit 2)") self.assertIn("instrumented=no-report", out) + def test_reports_must_identify_the_requested_mode(self) -> None: + reports = {"plain": self.all_passed(), "instrumented": self.all_passed()} + for stem in ("instrumented", "negative-instrumented"): + for reported_mode in ("plain", None): + with self.subTest(report=stem, reported_mode=reported_mode): + run = self.write(reports, self.NEGATIVE, report_modes={stem: reported_mode}) + self.assert_no_verdict(*run, f'{stem}.json: expected report mode "instrumented"') + def test_a_consume_exit_its_report_does_not_explain_is_no_verdict(self) -> None: for cases, exit_code in ((self.all_passed(), 1), (self.one_failing(), 0), (self.one_failing(), 101)): code, out, err = self.write({"plain": cases}, self.NEGATIVE, exits={"plain": exit_code}) @@ -749,7 +778,8 @@ def test_removals_must_be_declared_exactly(self) -> None: cases = [{"caseId": c["caseId"], "fileDigest": c["fileDigest"], "observationsDigest": "sha256:o", "status": "fail" if failing else "pass", "path": "/expected/x", "expected": 1, "actual": 2, "rules": ["R-1"]} for c in index["cases"]] -Path(report).write_text(json.dumps({"cases": cases})) +mode = "instrumented" if "--instrumented" in args else "plain" +Path(report).write_text(json.dumps({"mode": mode, "cases": cases})) passed = sum(c["status"] == "pass" for c in cases) print(f"CONSUME adapter=fake cases={len(cases)} pass={passed} fail={len(cases) - passed} unsupported=0 error=0") if path.name == "negative" and "--instrumented" in args and "FAKE_INSTRUMENTED_CONTROL_EXIT" in os.environ: From a76b43ec48b61f681dc4065bae9eac2c0073eea8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:18:00 +0800 Subject: [PATCH 166/190] test(limit-matrix): remove tests the conformance suite pins --- .../tests/satin/limit_matrix/keyless.rs | 79 +++++-------------- 1 file changed, 21 insertions(+), 58 deletions(-) diff --git a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs index a8c36f19d..d5354396d 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs @@ -488,71 +488,34 @@ fn test_authorization_list_boundaries() { 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. +/// A caught child stop leaves no top-level limit or deploy code in the returned outcome. #[test] -fn test_a_keyless_creation_from_nonce_0_stopped_in_its_initcode() { +fn test_a_caught_keyless_stop_returns_no_outer_limit_or_deploy_code() { 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"); + for signer_nonce in [0, 1] { + let mut db = keyless_db(); + if signer_nonce == 1 { + db.set_account_nonce(deployment.signer, 1); + db.set_account_balance(deployment.signer, U256::ONE); + } + let state = + 980 * common::slot_state_gas() + (2 - signer_nonce) * 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.clone(), gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + assert_eq!( + MegaLimitExceeded::abi_decode(&output).expect("the revert data is a stop"), + MegaLimitExceeded { kind: 3, limit: frame_share(TX_STATE_GROWTH_LIMIT) }, + ); + assert_eq!(outcome.limit_exceeded, None); + assert!(!super::has_code(&outcome, deployment.address)); } } From f4d7045dda7494a88d39788b3464e971e2ecb770 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:18:00 +0800 Subject: [PATCH 167/190] test(keyless): remove tests the conformance suite pins --- .../mega-evm/tests/system/keyless/charges.rs | 132 -------- .../mega-evm/tests/system/keyless/deploy.rs | 297 +----------------- .../tests/system/keyless/interface.rs | 11 + .../mega-evm/tests/system/keyless/limits.rs | 41 +-- crates/mega-evm/tests/system/keyless/rules.rs | 125 -------- 5 files changed, 15 insertions(+), 591 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index cd59e8459..e0e4402e1 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -103,76 +103,6 @@ fn test_the_call_pays_the_legacy_shares_of_the_accounts_it_creates() { } } -/// The created account is charged only when the deploy address is empty, as the `CREATE` opcode -/// charges it: an address that already holds a balance is an account already, the deployment -/// lands on it, and the balance stays. -#[test] -fn test_the_created_account_is_charged_only_when_the_address_is_empty() { - let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); - for gas_limit in GAS_LIMITS { - let empty = deploy(system_db(), &deployment, gas_limit); - let held = system_db().account_balance(deployment.address, U256::from(7_777)); - let held = deploy(held, &deployment, gas_limit); - assert_eq!(returned(&held).deployedAddress, deployment.address); - assert_eq!( - held.state.get(&deployment.address).map(|account| account.info.balance), - Some(U256::from(7_777)), - ); - let [total, regular, state, history_gas, _] = beyond(&empty, &held); - let created = entry(GasId::create_state_gas()); - assert_eq!([total, regular, state, history_gas], [created, 0, created, 0]); - } -} - -/// A refused call keeps the overhead and nothing else: every charge made after it is taken back -/// with the revert, whatever the pools. -#[test] -fn test_a_refused_call_keeps_the_overhead_alone() { - // A value the signer cannot fund: refused at the last rule, after every read. - let deployment = Deployment::with_value(deploying(&runtime(RUNTIME_LEN)), U256::from(1)); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); - assert_eq!( - [total, regular, state, history_gas, history_bytes], - [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0, 0], - "at {gas_limit}", - ); - assert_eq!(outcome.usage.write_records, 0); - } -} - -/// A deployment whose init code reverts gives the created account's charge back, and the record -/// of the account it did not create; the signer's account and its nonce record stay, because the -/// nonce stays spent. -#[test] -fn test_a_failed_deployment_gives_the_created_account_back() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let error = failure(&outcome); - let KeylessDeployError::ExecutionReverted { gas_used, .. } = error else { - panic!("expected ExecutionReverted, got {error:?}"); - }; - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); - let new_account = entry(GasId::new_account_state_gas()); - assert_eq!(state, new_account, "at {gas_limit}"); - assert_eq!(history_gas, record(), "at {gas_limit}"); - assert_eq!(history_bytes, 40, "at {gas_limit}"); - assert_eq!( - regular, - KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(3) + gas_used, - "at {gas_limit}" - ); - assert_eq!(total, regular + state + history_gas); - assert_eq!(nonce(&outcome, deployment.signer), 1, "the nonce stays spent"); - assert_eq!(outcome.usage.write_records, 1, "the signer's nonce"); - } -} - /// The call pays the regular gas the `CREATE` opcode charges its frame on top of the overhead, /// whatever the pools: the schedule's `create` entry, 12,000, and EIP-3860's 2 gas per word of /// init code, 65,536 for init code of the maximum size. Init code of zero bytes stops at once and @@ -206,68 +136,6 @@ fn test_the_call_pays_the_create_opcodes_regular_gas() { } } -/// `gasUsed` is what the creation spent before refunds: a constructor that fills a slot and -/// clears it again earns a refund, which is the transaction's, as any frame's is. The charges add -/// up to the transaction's spend before its refund, and the receipt's gas is that spend less the -/// refund. -#[test] -fn test_gas_used_counts_the_creations_spend_before_its_refund() { - let prefix = mega_evm::test_utils::BytecodeBuilder::default() - .sstore(U256::ZERO, U256::ONE) - .sstore(U256::ZERO, U256::ZERO) - .build_vec(); - let init_code = constructor(&prefix, &runtime(1)); - let opcode = create_regular(init_code.len()); - let deployment = Deployment::new(init_code); - let upfront = - entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()) + 2 * record(); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let gas_used = returned(&outcome).gasUsed; - let refund = outcome.result.gas().inner_refunded(); - assert!(refund > 0, "the constructor earns a refund at {gas_limit}"); - let [total, ..] = - beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + opcode + upfront + gas_used, - "at {gas_limit}" - ); - assert_eq!( - outcome.result.gas().tx_gas_used(), - outcome.result.gas().total_gas_spent() - refund, - "at {gas_limit}", - ); - } -} - -/// Both upfront charges are priced by the SALT bucket they land in — the signer's account in the -/// signer's, the created account in the deploy address's — and regular gas does not move with it. -#[test] -fn test_the_upfront_charges_scale_with_their_buckets() { - let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); - let new_account = entry(GasId::new_account_state_gas()); - let created = entry(GasId::create_state_gas()); - for gas_limit in GAS_LIMITS { - let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); - for (m_signer, m_address) in [(2, 1), (1, 2), (3, 2)] { - let envs = crowded( - crowded(TestExternalEnvs::new(), deployment.signer, m_signer), - deployment.address, - m_address, - ); - let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); - assert_eq!(crowded_run.gas.regular, minimal.gas.regular, "m does not touch regular"); - assert_eq!( - crowded_run.gas.state - minimal.gas.state, - (m_signer - 1) * new_account + - (m_address - 1) * (created + satin_gas_params().code_deposit_state_gas(5)), - "signer at m = {m_signer}, address at m = {m_address}, gas limit {gas_limit}", - ); - } - } -} - /// A deployment that fails gives the created account back at the price it was charged, however /// crowded the deploy address's bucket, and the bucket is read once for both; the signer's /// account is kept at its own bucket's price. diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index eccdfb9e6..18e0a5371 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -20,9 +20,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, GASPRICE, INVALID, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, - ORIGIN, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, SHR, SSTORE, - STATICCALL, + CALL, CREATE, DELEGATECALL, GAS, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, ORIGIN, POP, PUSH0, + REVERT, SELFDESTRUCT, SSTORE, STATICCALL, }, context::BlockEnv, primitives::KECCAK_EMPTY, @@ -30,7 +29,7 @@ use revm::{ }; use super::*; -use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; +use crate::common::{calls_with, split_outcome, with_contract, CONTRACT}; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); @@ -106,24 +105,6 @@ fn test_a_deployment_survives_a_commit() { } } -/// Init code that reverts: the call succeeds and reports `ExecutionReverted` with the revert -/// data, the deployment writes no code, and the signer's nonce is spent. -#[test] -fn test_keyless_deploy_execution_reverted() { - let deployment = - Deployment::new(BytecodeBuilder::default().revert_with_data([0xc0, 0xff, 0xee]).build()); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let KeylessDeployError::ExecutionReverted { gas_used, output } = failure(&outcome) else { - panic!("expected ExecutionReverted: {:?}", outcome.result); - }; - assert_eq!(output, Bytes::from_static(&[0xc0, 0xff, 0xee])); - assert_eq!(gas_used, returned(&outcome).gasUsed); - assert_eq!(nonce(&outcome, deployment.signer), 1); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - } -} - /// What the creation of a keyless deployment returned into its call: its regular gas and its /// reservoir once revm's settlement of the result, which runs after the inspector sees the /// creation end, rolled a failure's state and history gas back. @@ -197,26 +178,6 @@ fn test_a_reverting_constructor_returns_its_slot_as_reservoir_and_reports_its_re } } -/// Init code that hits an invalid opcode: `ExecutionHalted`, and the halt spends the whole -/// forward. -#[test] -fn test_keyless_deploy_execution_halted_invalid_opcode() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(Bytes::from_static(&[INVALID])); - let outcome = run_with( - system_db(), - deployment.call_data(2_000_000), - gas_limit, - EvmTxRuntimeLimits::no_limits(), - ); - let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { - panic!("expected ExecutionHalted: {:?}", outcome.result); - }; - assert_eq!(gas_used, 2_000_000, "a halt spends what it was forwarded"); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - /// A constructor that runs out of gas halts the same way, below and above the execution cap, /// and spends its whole forward in both. #[test] @@ -236,48 +197,6 @@ fn test_a_constructor_out_of_gas_is_execution_halted() { } } -/// A halted deployment is paid for, and its nonce is spent: the transaction spends the overhead, -/// the `CREATE` opcode's regular gas, the signer's account and its nonce record, and the whole -/// forward. -#[test] -fn test_a_halted_deployment_is_paid_for_and_spends_the_nonce() { - let deployment = Deployment::new(Bytes::from_static(&[INVALID])); - for gas_limit in GAS_LIMITS { - let data = deployment.call_data(SIGNED_GAS_LIMIT); - let outcome = - run_with(system_db(), data.clone(), gas_limit, EvmTxRuntimeLimits::no_limits()); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); - assert_eq!(nonce(&outcome, deployment.signer), 1); - let [total, ..] = beyond(&outcome, &reference(data, gas_limit)); - let new_account = entry(GasId::new_account_state_gas()); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(1) + - new_account + - record() + - SIGNED_GAS_LIMIT, - "at {gas_limit}", - ); - } -} - -/// Init code that returns nothing deploys no code: `EmptyCodeDeployed`, and the nonce is spent. -#[test] -fn test_keyless_deploy_empty_initcode() { - for gas_limit in GAS_LIMITS { - for init_code in [Bytes::new(), Bytes::from_static(&[PUSH0, PUSH0, RETURN])] { - let deployment = Deployment::new(init_code); - let outcome = deploy(system_db(), &deployment, gas_limit); - let KeylessDeployError::EmptyCodeDeployed { gas_used } = failure(&outcome) else { - panic!("expected EmptyCodeDeployed: {:?}", outcome.result); - }; - assert_eq!(gas_used, returned(&outcome).gasUsed); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } - } -} - /// A deployment whose initcode returns empty code at the deploy address is refused: the creation /// reverts, the call answers `EmptyCodeDeployed`, and the deploy address keeps no account, so the /// signed bytes can still be deployed. The initcode returns empty code when it has more than @@ -327,55 +246,6 @@ fn test_an_empty_code_deployment_leaves_the_address_deployable() { } } -/// A deploy address at nonce 1 without code — what a Rex6 deployment whose creation returned -/// empty code left — passes the occupancy rule, which reads the code alone, and the creation -/// collides there before its init code runs: whatever the init code would do, the call answers -/// `ExecutionHalted` with the whole forward spent, the address keeps its nonce and no code, and the -/// signer's bump from 0 stands. -#[test] -fn test_a_deploy_address_with_a_nonce_and_no_code_collides() { - let init_codes = - [deploying(&runtime(1)), Bytes::new(), Bytes::from_static(&[INVALID]), logging(32)]; - for init_code in init_codes { - let deployment = Deployment::new(init_code); - let db = system_db().account_nonce(deployment.address, 1); - for gas_limit in GAS_LIMITS { - for forward in [SIGNED_GAS_LIMIT, 2 * SIGNED_GAS_LIMIT] { - let outcome = run_with( - db.clone(), - deployment.call_data(forward), - gas_limit, - EvmTxRuntimeLimits::no_limits(), - ); - let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { - panic!("expected ExecutionHalted: {:?}", outcome.result); - }; - assert_eq!(gas_used, forward, "a collision spends the forward, at {gas_limit}"); - assert_eq!(nonce(&outcome, deployment.signer), 1, "the bump from 0 stands"); - assert_eq!(nonce(&outcome, deployment.address), 1, "the address keeps its nonce"); - assert_eq!(code_hash(&outcome, deployment.address), Some(KECCAK_EMPTY)); - assert!(outcome.result.logs().is_empty(), "the init code never ran"); - } - } - } -} - -/// An empty deposit is refused at the deploy address alone: a constructor's own `CREATE` that -/// returns empty code is admitted, and the deployment around it succeeds. -#[test] -fn test_a_constructors_own_creation_may_return_empty_code() { - for gas_limit in GAS_LIMITS { - // CREATE of empty init code, then the deployment's own runtime. - let prefix = [PUSH0, PUSH0, PUSH0, CREATE, POP]; - let deployment = Deployment::new(constructor(&prefix, &runtime(1))); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); - let inner = deployment.address.create(1); - assert_eq!(nonce(&outcome, inner), 1, "the inner creation stands, with no code"); - assert_eq!(code_hash(&outcome, inner), Some(KECCAK_EMPTY)); - } -} - /// Init code that destroys its own account: the value it held goes to the beneficiary, no code /// is left, and the call reports `EmptyCodeDeployed`. #[test] @@ -470,17 +340,6 @@ fn test_a_constructor_destroyed_through_delegatecall_deploys_no_code() { } } -/// Code starting with `0xEF` is refused by the creation (EIP-3541): `ExecutionHalted`. -#[test] -fn test_code_starting_with_ef_is_refused() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(deploying(&[0xef, 0x00])); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - } -} - /// Code over the contract size limit is refused by the creation (EIP-170): `ExecutionHalted`. #[test] fn test_code_over_the_size_limit_is_refused() { @@ -495,19 +354,6 @@ fn test_code_over_the_size_limit_is_refused() { } } -/// A deployment carrying a value moves it from the signer to the contract. -#[test] -fn test_keyless_deploy_with_value_transfer() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); - let outcome = deploy(db_for(&deployment, U256::from(10_000)), &deployment, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); - assert_eq!(balance(deployment.address), Some(U256::from(7_777))); - assert_eq!(balance(deployment.signer), Some(U256::from(2_223))); - } -} - /// A constructor that writes another contract's storage: the write is kept. #[test] fn test_keyless_deploy_modifies_other_contract_state() { @@ -626,29 +472,6 @@ fn test_keyless_deploy_reads_existing_contract() { } } -/// A constructor that writes storage and then reverts leaves neither the storage nor code, and -/// the call still reports the revert with a gas figure. -#[test] -fn test_failed_initcode_keeps_no_storage() { - let init_code = - BytecodeBuilder::default().sstore(U256::from(1), U256::from(7)).revert().build(); - let deployment = Deployment::new(init_code); - for gas_limit in GAS_LIMITS { - let outcome = deploy(system_db(), &deployment, gas_limit); - let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { - panic!("expected ExecutionReverted: {:?}", outcome.result); - }; - assert!(gas_used > 0); - let kept = outcome - .state - .get(&deployment.address) - .and_then(|account| account.storage.get(&U256::from(1)).map(|slot| slot.present_value)); - assert!(kept.is_none_or(|value| value.is_zero()), "at {gas_limit}"); - assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); - } -} - /// A constructor's log is the transaction's: it is in the receipt, emitted by the deployed /// address. #[test] @@ -691,17 +514,6 @@ fn test_an_empty_code_deployment_keeps_no_log() { } } -/// And init code that logs nothing leaves none. -#[test] -fn test_an_empty_code_deployment_adds_no_log() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::new(BytecodeBuilder::default().return_empty().build()); - let outcome = deploy(system_db(), &deployment, gas_limit); - assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); - assert!(outcome.result.logs().is_empty()); - } -} - /// A deployment that fails keeps no log: the creation's revert takes its logs with it. #[test] fn test_a_failed_deployment_keeps_no_log() { @@ -727,34 +539,6 @@ fn priced_tx(deployment: &Deployment, gas_limit: u64, gas_price: u128) -> MegaTr tx } -/// `ORIGIN` and `GASPRICE` in the init code are the transaction's own: the relayer, and the gas -/// price the relayer pays — not the signer, and not the price the deployment was signed at. -#[test] -fn test_origin_and_gasprice_follow_the_outer_transaction() { - let prefix = BytecodeBuilder::default() - .append(ORIGIN) - .push_number(0_u64) - .append(SSTORE) - .append(GASPRICE) - .push_number(1_u64) - .append(SSTORE); - let deployment = Deployment::new(running(prefix)); - for gas_limit in GAS_LIMITS { - let outcome = MegaEvm::new(context(system_db())) - .execute_transaction(priced_tx(&deployment, gas_limit, 7)) - .expect("a valid transaction"); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let slot = |key: u64| { - outcome.state[&deployment.address] - .storage - .get(&U256::from(key)) - .map(|s| s.present_value) - }; - assert_eq!(slot(0), Some(U256::from_be_slice(RELAYER.as_slice())), "ORIGIN"); - assert_eq!(slot(1), Some(U256::from(7)), "GASPRICE"); - } -} - /// The block's beneficiary is paid for the whole transaction, deployment included, whether the /// deployment succeeds or fails, and the signer pays nothing. fn assert_beneficiary_paid(init_code: Bytes) { @@ -803,81 +587,6 @@ fn test_keyless_deploy_not_intercepted_for_inner_calls() { } } -/// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: -/// not dispatched. The contract's bytecode runs and reverts with `NotIntercepted()`, which the -/// outer constructor stores, and nothing of the inner deployment happens: its address holds no -/// code and its signer's nonce is unspent. The outer deployment deploys. -/// -/// A call answered without the bytecode — refused by an interceptor, or run as a deployment that -/// fails — could fail the same way, but not with the four bytes of `NotIntercepted()`. -/// -/// Expected values `independent`: the error's selector is computed here from its -/// signature, `NotIntercepted()`, not taken from the contract's binding. -#[test] -fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { - let not_intercepted = &alloy_primitives::keccak256("NotIntercepted()")[..4]; - let selector = U256::from_be_slice(not_intercepted); - for gas_limit in GAS_LIMITS { - let inner = Deployment::new(deploying(&[0x00, 0x00])); - let data = inner.call_data(LARGE_OVERRIDE); - // The inner call's status in slot 0, the size of its revert data in slot 2, and the first - // four bytes of that data, as a number, in slot 1. - let prefix = BytecodeBuilder::default() - .mstore(0, &data) - .push_number(0_u64) - .push_number(0_u64) - .push_number(data.len() as u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(KEYLESS_DEPLOY_ADDRESS) - .append(GAS) - .append(CALL) - .push_number(0_u64) - .append(SSTORE) - .append(RETURNDATASIZE) - .push_number(2_u64) - .append(SSTORE) - .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, PUSH0, MLOAD]) - .push_number(224_u64) - .append(SHR) - .push_number(1_u64) - .append(SSTORE); - let outer = Deployment::new(running(prefix)); - let outcome = deploy(system_db(), &outer, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, outer.address); - let slot = |index: u64| { - outcome.state[&outer.address] - .storage - .get(&U256::from(index)) - .map(|slot| slot.present_value) - }; - assert_eq!(slot(0), Some(U256::ZERO), "the inner call failed"); - assert_eq!(slot(2), Some(U256::from(4)), "with four bytes of revert data"); - assert_eq!(slot(1), Some(selector), "which are NotIntercepted(): the bytecode ran"); - assert!(code_hash(&outcome, inner.address).is_none_or(|hash| hash == KECCAK_EMPTY)); - assert_eq!(nonce(&outcome, inner.signer), 0); - } -} - -/// A constructor's storage writes are priced by the SALT environment the transaction runs in: a -/// crowded bucket at the deploy address makes the deposited code cost more state gas, and the -/// creation's `gasUsed` grows by exactly that. -#[test] -fn test_a_deployment_is_priced_by_the_transactions_salt_env() { - let deployment = Deployment::new(deploying(&runtime(5))); - let deposit = satin_gas_params().code_deposit_state_gas(5); - for gas_limit in GAS_LIMITS { - let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); - let envs = crowded(TestExternalEnvs::new(), deployment.address, 3); - let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); - assert_eq!( - returned(&crowded_run).gasUsed - returned(&minimal).gasUsed, - 2 * deposit, - "at {gas_limit}", - ); - } -} - /// A constructor that sends an Oracle hint reaches the node's oracle service: the creation runs /// in the transaction's own environment. #[test] diff --git a/crates/mega-evm/tests/system/keyless/interface.rs b/crates/mega-evm/tests/system/keyless/interface.rs index b3eddbdb1..8f7915f11 100644 --- a/crates/mega-evm/tests/system/keyless/interface.rs +++ b/crates/mega-evm/tests/system/keyless/interface.rs @@ -45,3 +45,14 @@ fn test_decode_gas_limit_too_low_preserves_both_limits() { }), ); } + +#[test] +fn test_decode_execution_reverted_preserves_gas_and_output() { + let output = alloy_primitives::Bytes::from_static(&[0xc0, 0xff, 0xee]); + let bytes = + IKeylessDeploy::ExecutionReverted { gasUsed: 16, output: output.clone() }.abi_encode(); + assert_eq!( + decode_error_result(&bytes), + Some(KeylessDeployError::ExecutionReverted { gas_used: 16, output }), + ); +} diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index dd02e16f0..05be35361 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -24,7 +24,7 @@ use mega_evm::{ LimitCheck, LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, GAS, POP, PUSH0, REVERT, TIMESTAMP}, + bytecode::opcode::{CALL, GAS, POP, PUSH0, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, InstructionResult, @@ -407,45 +407,6 @@ fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { ); } -/// The call gets back what its creation did not spend, the same way whether the creation -/// succeeds or reverts: the transaction spends the overhead, the `CREATE` opcode's regular gas, -/// what the call kept of the creation's start, and the creation's `gasUsed`, and nothing else, -/// below and above the execution cap. -#[test] -fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { - let succeeding = Deployment::new(deploying(&runtime(1))); - let reverting = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - let new_account = entry(GasId::new_account_state_gas()); - for gas_limit in GAS_LIMITS { - let success = limited(&succeeding, gas_limit, EvmTxRuntimeLimits::no_limits()); - let [total, ..] = - beyond(&success, &reference(succeeding.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(deploying(&runtime(1)).len()) + - new_account + - entry(GasId::create_state_gas()) + - 2 * record() + - returned(&success).gasUsed, - "success at {gas_limit}", - ); - - let revert = limited(&reverting, gas_limit, EvmTxRuntimeLimits::no_limits()); - let [total, ..] = - beyond(&revert, &reference(reverting.call_data(LARGE_OVERRIDE), gas_limit)); - assert_eq!( - total, - KEYLESS_DEPLOY_OVERHEAD_GAS + - create_regular(3) + - new_account + - record() + - returned(&revert).gasUsed, - "revert at {gas_limit}", - ); - } -} - /* ---------- the stop, as a column of the matrix ---------- */ /// A limit a deployment's creation crosses. diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index c69948df5..c047bbad9 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -160,13 +160,6 @@ fn gas_limit_forwarding(deployment: &Deployment, init_len: usize, forward: u64) forward } -/// A signed gas limit the signer's account can take the forward below: 500,000 on top of the -/// account's state gas at the byte prices in effect, so the call can pay for the account out of -/// the forward whatever a state byte costs. -fn signed_above_the_account() -> u64 { - 500_000 + entry(GasId::new_account_state_gas()) -} - /// The length of the init code the forwarding tests deploy: a one-byte runtime. fn one_byte_init_len() -> usize { deploying(&runtime(1)).len() @@ -477,56 +470,6 @@ fn test_a_resubmission_after_failures_and_a_deployment_finds_the_address_taken() } } -/// A deployment that succeeds from nonce 1 leaves the signer at 1 too: the creation's bump goes -/// with its record, so the deployment costs exactly one record's history less than the same one -/// from nonce 0, which keeps its bump. The record stays when the creation moved value out of the -/// signer's account, and then stands for that write. -#[test] -fn test_a_success_from_nonce_one_leaves_the_nonce_at_one() { - for gas_limit in GAS_LIMITS { - for (value, kept) in [(U256::ZERO, 0), (U256::ONE, 1)] { - let deployment = Deployment::with_value(deploying(&runtime(1)), value); - let funded = db_for(&deployment, U256::from(1_000)); - let at_zero = deploy(funded.clone(), &deployment, gas_limit); - let at_one = deploy(funded.account_nonce(deployment.signer, 1), &deployment, gas_limit); - assert_eq!(returned(&at_one).deployedAddress, deployment.address, "at {gas_limit}"); - assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); - assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); - assert_eq!(at_one.usage.write_records, 1 + kept, "value {value} at {gas_limit}"); - let taken_back = 1 - kept; - assert_eq!( - beyond(&at_zero, &at_one), - [taken_back * record(), 0, 0, taken_back * record(), taken_back * 40], - "value {value} at {gas_limit}", - ); - } - } -} - -/// A deployment that fails from nonce 1 keeps nothing of the signer: its records, its data size, -/// its history gas and its history bytes are those of a transaction that bumped no nonce — the -/// reference, which pays the same intrinsic gas and writes nothing — and it spends exactly one -/// record's history less than the same failure from nonce 0, which keeps its bump. -#[test] -fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { - let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - for gas_limit in GAS_LIMITS { - let at_one = - deploy(system_db().account_nonce(deployment.signer, 1), &deployment, gas_limit); - let at_zero = deploy(db_for(&deployment, U256::ONE), &deployment, gas_limit); - assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); - assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); - - let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); - let [_, _, state, history_gas, history_bytes] = beyond(&at_one, &reference); - assert_eq!([state, history_gas, history_bytes], [0; 3], "at {gas_limit}"); - assert_eq!(at_one.usage, reference.usage, "at {gas_limit}"); - - assert_eq!(at_zero.usage.write_records, 1, "the signer's nonce record"); - assert_eq!(beyond(&at_zero, &at_one), [record(), 0, 0, record(), 40], "at {gas_limit}"); - } -} - /// However a deployment from nonce 1 fails — its init code reverts or halts, it deploys no code, /// or a limit stops its creation at its start — the signer stays at 1 and its nonce record goes. /// A creation that deployed no code is refused its empty deposit and reverts, so it keeps neither @@ -662,30 +605,6 @@ fn test_a_disabled_eip3607_reads_no_signer_code() { } } -/// An EIP-7702 delegation is not code: a signer that delegated deploys. -#[test] -fn test_a_delegated_signer_deploys() { - for gas_limit in GAS_LIMITS { - let deployment = small(); - let delegation = - Bytecode::new_eip7702(address!("0x00000000000000000000000000000000000d1e6a")); - let mut db = system_db(); - db.insert_account_info( - deployment.signer, - AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash: delegation.hash_slow(), - code: Some(delegation), - ..Default::default() - }, - ); - let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - assert_eq!(nonce(&outcome, deployment.signer), 1); - } -} - /// A delegated signer's own code can spend its nonces while its deployment runs: a constructor /// that calls the signer runs the delegation, which creates two accounts at the signer's next /// nonces. Those stay spent, and so does the creation's own bump below them — the settlement @@ -882,50 +801,6 @@ fn test_keyless_deploy_insufficient_balance_partial() { } } -/// A signer holding exactly the value deploys, and the value moves to the contract. -#[test] -fn test_keyless_deploy_balance_exactly_sufficient() { - for gas_limit in GAS_LIMITS { - let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(10)); - let outcome = - submit(db_for(&deployment, U256::from(10)), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); - assert_eq!(balance(deployment.signer), Some(U256::ZERO)); - assert_eq!(balance(deployment.address), Some(U256::from(10))); - } -} - -/// The signer's account is charged exactly when its nonce is spent: a refused call does neither, -/// a deployment that fails at run time does both. -/// -/// The refusal runs below the execution cap, as the refusals above; the failure runs at both. -#[test] -fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { - let signed = signed_above_the_account(); - let deployment = - Deployment::signed(0, signed, U256::ZERO, Bytes::from_static(&[PUSH0, PUSH0, REVERT])); - // An account that costs nothing takes nothing from the forward, and refuses nothing. - if !state_is_free() { - let refused = submit( - system_db(), - &deployment.tx, - LARGE_OVERRIDE, - gas_limit_forwarding(&deployment, 3, signed), - ); - assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); - assert_eq!(nonce(&refused, deployment.signer), 0); - assert_eq!(refused.gas.state, 0); - } - - for gas_limit in GAS_LIMITS { - let failed = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); - assert!(matches!(failure(&failed), KeylessDeployError::ExecutionReverted { .. })); - assert_eq!(nonce(&failed, deployment.signer), 1); - assert_eq!(failed.gas.state, entry(GasId::new_account_state_gas())); - } -} - /// A database read a rule needs fails the transaction with the database's error: the deploy /// address's, whose occupancy rule 5 reads. #[test] From 96962237f7540df9394d09082fa9796a256aee06 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:29 +0800 Subject: [PATCH 168/190] test(contract-size): remove tests the conformance suite pins --- crates/mega-evm/tests/satin/contract_size.rs | 65 -------------------- crates/mega-evm/tests/satin/main.rs | 1 - 2 files changed, 66 deletions(-) delete mode 100644 crates/mega-evm/tests/satin/contract_size.rs diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs deleted file mode 100644 index 3bd6865fc..000000000 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! The code-size limits the Satin configuration raises. -//! -//! A deployed contract may hold 512 KiB, eight times more than EIP-7954's bound and twenty-one -//! times EIP-170's; an initcode may hold twice that, the ratio EIP-3860 sets between the two. -//! Both bounds are `CfgEnv` limits the spec fixes, so they apply to a creation transaction and to -//! a `CREATE` alike. - -use alloy_evm::{Evm, EvmError, InvalidTxError}; -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, - test_utils::MemoryDatabase, - MegaEvm, MegaHaltReason, MegaTransaction, -}; -use revm::{bytecode::opcode::STOP, context::result::ExecutionResult}; - -use crate::common::{context, create, history}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); - -/// Room for everything a creation here draws, all of it above the execution cap so it comes out of -/// the reservoir: the state gas of the largest deployable code, the history of that code and of a -/// body carrying twice the largest init code, and a billion more, at the byte prices in effect. -fn gas_limit() -> u64 { - TX_GAS_LIMIT_CAP + - MAX_CONTRACT_SIZE as u64 * - mega_evm::satin_gas_params() - .get(revm::context_interface::cfg::GasId::code_deposit_state_gas()) + - history((MAX_CONTRACT_SIZE + 2 * MAX_INITCODE_SIZE) as u64) + - 1_000_000_000 -} - -/// Runs `tx` from `CALLER` and returns its result, or the validation error that rejected it. -fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result, String> { - let mut evm = MegaEvm::new(context(db)); - match evm.transact_raw(tx) { - Ok(outcome) => Ok(outcome.result), - Err(err) => { - let invalid = err - .as_invalid_tx_err() - .and_then(InvalidTxError::as_invalid_tx_err) - .unwrap_or_else(|| panic!("unexpected error {err:?}")); - Err(format!("{invalid:?}")) - } - } -} - -/// Runs `init_code` as a creation transaction from `CALLER`. -fn deploy(init_code: Bytes) -> Result, String> { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - run(create(CALLER, init_code, gas_limit()), db) -} - -/// Init code of `size` bytes that does nothing. -fn initcode_of(size: usize) -> Bytes { - Bytes::from(vec![STOP; size]) -} - -/* ---------- the initcode bound ---------- */ - -/// The Satin bound itself is accepted. -#[test] -fn test_the_satin_initcode_size_is_accepted() { - assert!(deploy(initcode_of(MAX_INITCODE_SIZE)).unwrap().is_success()); -} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 2dd8f18ea..231e1831a 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -2,7 +2,6 @@ mod common; mod compute_gas; -mod contract_size; mod corpus; mod count_order; mod create_opcodes; From 6318928628cf9282a3e54a30fd12f344fe68d8b1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:29 +0800 Subject: [PATCH 169/190] test(state-growth): remove tests the conformance suite pins --- .../tests/satin/limit_matrix/limits.rs | 15 ----------- crates/mega-evm/tests/satin/state_growth.rs | 25 ------------------- 2 files changed, 40 deletions(-) diff --git a/crates/mega-evm/tests/satin/limit_matrix/limits.rs b/crates/mega-evm/tests/satin/limit_matrix/limits.rs index 9aac9729a..106d225d4 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/limits.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/limits.rs @@ -26,21 +26,6 @@ fn join(prefix: Vec, rest: BytecodeBuilder) -> Bytes { 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. diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 48adad8b1..772a609d9 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -868,31 +868,6 @@ fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { ); } -/// 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 From 3219a0ae9f0b16d4c7031424438ebeb99af0376b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:30 +0800 Subject: [PATCH 170/190] test(history): remove tests the conformance suite pins --- .../mega-evm/tests/satin/history_allowance.rs | 68 +------------------ .../mega-evm/tests/satin/history_exemption.rs | 14 ---- 2 files changed, 1 insertion(+), 81 deletions(-) diff --git a/crates/mega-evm/tests/satin/history_allowance.rs b/crates/mega-evm/tests/satin/history_allowance.rs index 241734b01..cd39d7873 100644 --- a/crates/mega-evm/tests/satin/history_allowance.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -24,9 +24,7 @@ use mega_evm::{ constants::COST_PER_HISTORY_BYTE, history_allowance_gas, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{ - is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, - }, + test_utils::{is_transfer_log, note_price_guard, BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitKind, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, HISTORY_ALLOWANCE_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; @@ -125,52 +123,6 @@ fn test_the_allowance_is_one_three_topic_event_of_history() { 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 -/// `receive()` hook that emits one event, and the event's history costs the sender nothing beyond -/// the two write records the transfer itself writes. -/// -/// Without the allowance the event's 160 bytes would have to come out of the 2,300, which does -/// not cover them at any price a history byte is worth. -#[test] -fn test_a_transfer_can_emit_one_event_because_of_the_allowance() { - if runs_at_measurement_prices() { - return; - } - let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); - let receiver = event().append(STOP).build(); - let outcome = execute(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); - assert_eq!( - outcome.result.logs()[0], - transfer_log(SENDER, RECEIVER, U256::from(1)), - "after the transfer's own log, which took nothing from the allowance", - ); - assert_eq!( - outcome.gas.history, - body() + 2 * record(), - "the body and the transfer's two records; the event's bytes the allowance paid for", - ); -} - -/// One event is all it buys: a second one has to come out of the 2,300 gas, which cannot cover -/// it, so the hook runs out of gas and the transfer fails. -#[test] -fn test_the_allowance_buys_one_event_and_no_more() { - if runs_at_measurement_prices() { - return; - } - // The caller records whether the transfer succeeded, then stops. - let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); - let two_events = event().append_many(event().build().iter().copied()).append(STOP).build(); - let outcome = execute(db(sender, two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); - - assert!(outcome.result.is_success(), "the caller survives the hook's failure"); - assert!(outcome.result.logs().is_empty(), "the hook ran out and kept neither event"); - assert_eq!(outcome.gas.history, body(), "and the transfer's records came back with it"); -} - /// A sender that makes one value transfer to [`RECEIVER`], forwarding `gas` beside the 2,300 the /// transfer's stipend adds, and returns the call's success flag. fn transfer_returning_its_flag(gas: u64) -> Bytes { @@ -692,24 +644,6 @@ fn test_a_drained_allowance_is_not_refunded_by_a_revert() { ); } -/// A call that forwards no gas at all still reaches a `receive()` hook that emits one event: the -/// EVM's own `CALL_STIPEND` pays for the computation and the allowance for the bytes. -#[test] -fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { - if runs_at_measurement_prices() { - return; - } - let sender = call_with(CALL, RECEIVER, 1, 0).append(STOP).build(); - let outcome = execute( - db(sender, event().append(STOP).build()), - call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), - ); - - assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); - assert_eq!(outcome.gas.history, body() + 2 * record()); -} - /* ---------- an inspector that replaces the interpreter ---------- */ /// Replaces the interpreter of every frame running `target`'s code, as revm initialises it, with diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 9526fddba..9bbacddd1 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -187,20 +187,6 @@ fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { assert_eq!(evm.ctx().additional_limit().history_gas_spent(), 0); } -/// A deposit pays for its body, calldata, records, logs and deployed code even without a fee. -#[test] -fn test_a_deposit_pays_history_gas() { - if runs_at_measurement_prices() { - return; - } - let mut tx = deposit(call_from(CALLER, CONTRACT)); - tx.0.base.data = Bytes::from_static(b"history"); - let (history, state, outcome) = ledgers(tx); - assert_eq!(history, (PROGRAM_HISTORY_BYTES + 7) * COST_PER_HISTORY_BYTE); - assert_eq!(state, PROGRAM_STATE_GAS, "the state a user transaction pays"); - assert_eq!(outcome.gas.history_bytes, PROGRAM_HISTORY_BYTES + 7); -} - /// Both field-based forms of system origin pay every history site, including deposited code. #[test] fn test_system_originated_transactions_pay_history_for_the_program() { From 6b3672823895ab69bc12c1a3fa62327c9244b1f2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:30 +0800 Subject: [PATCH 171/190] test(write-records): remove tests the conformance suite pins --- crates/mega-evm/tests/satin/write_records.rs | 299 +------------------ 1 file changed, 2 insertions(+), 297 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index cf2905994..5c5c60f81 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,9 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, - JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, - STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, + LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -96,50 +95,6 @@ fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) } -/* ---------- value transfers and creations: a record per account that changed ---------- */ - -/// 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, value_call_room()), - ); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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 @@ -186,33 +141,6 @@ fn body_and_records(records: u64) -> u64 { history(TX_BODY_SIZE + 1 + records * WRITE_RECORD_SIZE) } -/// 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 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 @@ -320,26 +248,6 @@ fn test_nested_creations_record_each_account_once() { assert!(result.state.contains_key(&created.create(1))); } -/// 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 @@ -508,24 +416,6 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { } } -/// A creation and a value transfer from one frame record the frame's account once. -#[test] -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, value_call_room()), - ); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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" - ); -} - /// Two creations from one frame record the creator once and each created account. #[test] fn test_two_creates_record_the_creator_once() { @@ -544,36 +434,6 @@ fn test_two_creates_record_the_creator_once() { ); } -/// After a failed transfer the sender can be recorded again by the next one. -/// -/// The first child burns the gas it was forwarded, so the second transfer forwards none: its -/// recipient runs no code, and the records it makes are paid out of what the caller keeps, which -/// then does not depend on the price of the recipient's new account. -#[test] -fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { - let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); - let code = code - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .append(PUSH1) - .append(1u8) - .push_address(CONTRACT2) - .append(PUSH0) - .append(CALL) - .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, value_call_room())); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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 { @@ -627,46 +487,10 @@ fn reverting_creations(n: usize) -> Bytes { code.into() } -/// A creation the creator cannot fund never starts (the opcode checks the endowment before it -/// builds a frame), so it records nothing. -#[test] -fn test_creation_without_funds_records_nothing() { - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0]) - .push_number(1_000_000_000_000_u64) - .append(CREATE) - .append(POP) - .stop() - .build(); - let db = MemoryDatabase::default().account_code(CALLEE, code); - 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"); -} - const A: Address = address!("00000000000000000000000000000000A0000001"); const B: Address = address!("00000000000000000000000000000000B0000002"); 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), 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) -} - -/// A top-level transfer to another account records the recipient. -#[test] -fn test_top_level_transfer_counts_the_recipient() { - 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 /// calldata stops at once. fn self_calling_code(targets: &[Address], value: u64) -> Bytes { @@ -713,36 +537,6 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { ); } -/* ---------- storage, logs, selfdestruct ---------- */ - -/// A write-back in a child refunds the record its caller made, and the refund dies with a -/// failing child. -#[test] -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(); - // 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() - .sstore(U256::ZERO, U256::from(1)) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(CONTRACT) - .append(GAS) - .append(revm::bytecode::opcode::DELEGATECALL) - .append(POP) - .stop() - .build(); - let db = - MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); - assert!(result.result.is_success()); - assert_eq!(usage, expected); - } -} - /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. @@ -995,46 +789,6 @@ fn authorizing_call( ) } -/// A value transfer to an applied authority records the authority once, not again as the -/// recipient. -#[test] -fn test_value_to_an_applied_authority_records_it_once() { - let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let (result, usage) = run(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!( - usage, - 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 - // authority's account is already written. A transfer to an account that is not an authority - // pays for the recipient on top of the one authority it applied. - if crate::common::runs_at_measurement_prices() { - return; - } - const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; - let to_authority = - crate::common::execute(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); - let to_another = - crate::common::execute(db(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)])); - let body = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE; - - assert!(to_another.result.is_success(), "{:?}", to_another.result); - assert_eq!( - to_authority.gas.history, - (body + WRITE_RECORD_SIZE) * CPHB, - "the authority's record, and no recipient record beside it", - ); - assert_eq!( - to_another.gas.history, - (body + 2 * WRITE_RECORD_SIZE) * CPHB, - "the authority's record and the recipient's", - ); -} - /// A frame running as the transaction's sender (a delegated sender called back) records no /// write to the sender's account: the transaction body counts it. #[test] @@ -1396,32 +1150,6 @@ fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authoriti const D: Address = address!("00000000000000000000000000000000000000D1"); -/// 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 = - append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); - let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) - .append(POP) - .append(STOP) - .build(); - let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); - 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, - 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 has its own account unchanged, whatever its caller's state: its /// first value transfer records it. #[test] @@ -1573,29 +1301,6 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { ); } -/// 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) - .append(POP) - .append(STOP) - .build(); - let mut db = funded().account_code(CONTRACT, sender_code); - let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); - 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, value_call_room())); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - 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. struct AnswerContract; From 1f9127bdd9934f1b5d3052353b91392978f168bc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:30 +0800 Subject: [PATCH 172/190] test(dispatch): remove tests the conformance suite pins --- crates/mega-evm/tests/system/dispatch.rs | 44 +----------------------- 1 file changed, 1 insertion(+), 43 deletions(-) diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs index 260546173..abab39218 100644 --- a/crates/mega-evm/tests/system/dispatch.rs +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -3,7 +3,7 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; +use alloy_sol_types::SolCall; use mega_evm::{ system::{ storage_slots::CURRENT_SYSTEM_ADDRESS, IMegaAccessControl, IMegaLimitControl, IOracle, @@ -68,26 +68,6 @@ fn test_an_intercepted_call_costs_what_a_plain_call_costs() { assert_eq!(spent(intercepted), spent(plain)); } -/// Admission is the four selector bytes: the exact selector and the selector followed by -/// anything are both intercepted, and an input too short to hold one is not. -#[test] -fn test_admission_is_the_selector_alone() { - let intercepted = |data: Vec| { - let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, &data, U256::ZERO)); - // The interceptor answers `false`; the deployed bytecode reverts. - result.result.is_success() - }; - assert!(intercepted(IS_DISABLED.to_vec()), "the exact selector"); - assert!(intercepted(IS_DISABLED.iter().copied().chain([0xff]).collect()), "one byte after it"); - assert!( - intercepted(IS_DISABLED.iter().copied().chain([0_u8; 32]).collect()), - "a padded argument after it", - ); - assert!(!intercepted(IS_DISABLED[..3].to_vec()), "three bytes are not a selector"); - assert!(!intercepted(Vec::new()), "no input is not a selector"); - assert!(!intercepted(vec![0xde, 0xad, 0xbe, 0xef]), "another selector"); -} - /// Records which addresses an inspector sees called, and in which order they end. #[derive(Default)] struct CallTracker { @@ -173,28 +153,6 @@ fn test_a_database_error_reading_the_registry_fails_the_transaction() { assert!(format!("{error}").contains("injected storage() error"), "{error}"); } -/// The value policy is the interceptor's, not the account's: a value-bearing transaction to a -/// control contract is refused with `NonZeroTransfer()` before any value moves. -#[test] -fn test_a_value_bearing_transaction_is_refused_before_the_value_moves() { - let db = system_db(); - let mut tx = call_tx(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS, U256::from(1)); - tx.0.base.caller = crate::common::CALLER; - let result = run(db, tx); - - let revm::context::result::ExecutionResult::Revert { output, .. } = &result.result else { - panic!("the transaction did not revert: {:?}", result.result); - }; - assert_eq!(output[..], IMegaLimitControl::NonZeroTransfer::SELECTOR); - assert!( - result - .state - .get(&LIMIT_CONTROL_ADDRESS) - .is_none_or(|account| account.info.balance.is_zero()), - "the refused value stayed with its sender", - ); -} - /// A `STATICCALL` to a system contract from inside a static frame is intercepted too: nothing /// about the answer writes state. #[test] From c49a7bb0f8fc799abde13f61bac5e8357457dff4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:30 +0800 Subject: [PATCH 173/190] test(oracle): remove tests the conformance suite pins --- crates/mega-evm/tests/system/oracle.rs | 132 +------------------------ 1 file changed, 1 insertion(+), 131 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 20a874055..4bf33a530 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -22,7 +22,7 @@ use revm::{ }; use crate::common::{ - block, call_tx, call_tx_with_gas, run, steer, system_db, with_contract, CALLER, CONTRACT, + block, call_tx, call_tx_with_gas, steer, system_db, with_contract, CALLER, CONTRACT, }; /// A topic and payload the tests send. @@ -87,37 +87,6 @@ fn try_run_with_oracle_under( Some((outcome, envs.recorded_hints())) } -/// A call that carries value is judged on its gas like any other, and a call that requests none -/// still holds the value call's stipend, so its hint is admitted. `sendHint` is not payable, so -/// the bytecode refuses the value; the hint is a message to the service and was already sent, and -/// its bytes stay counted. -#[test] -fn test_a_value_bearing_call_forwards_its_hint() { - use revm::bytecode::opcode::{POP, PUSH0, REVERT}; - - let data = send_hint(b"paid"); - let code = BytecodeBuilder::default() - .mstore(0x0, &data) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(data.len() as u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(0_u64) // gas: none requested, the stipend is all the call holds - .append(CALL) - .append(POP) - .append_many([PUSH0, PUSH0, REVERT]) - .build(); - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(!result.result.is_success(), "the frame that sent the hint reverted"); - assert_eq!(hints.len(), 1, "the hint reached the service"); - assert_eq!(hints[0].from, CONTRACT); - assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); -} - /// Code that calls the Oracle with `data`, one unit of value and no requested gas, and returns /// the call's status followed by its return data. The contract holds no balance, so the call /// cannot be funded. @@ -156,34 +125,6 @@ fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) } -/// A value-bearing `sendHint` whose caller cannot fund the value is intercepted before revm -/// starts the call and checks the funds: the hint is forwarded and its input counted, then the -/// call fails for the funds with empty return data and moves no value, and the Oracle's bytecode -/// never runs. -#[test] -fn test_an_unfunded_value_hint_is_forwarded_and_then_fails_for_funds() { - let data = send_hint(b"unfunded"); - let (result, hints, usage) = - run_with_oracle(unfunded_contract_db(&data), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(result.result.is_success(), "the contract survives the failed call"); - let returned = result.result.output().cloned().unwrap_or_default(); - let (status, return_data) = crate::common::split_outcome(&returned); - assert!(!status, "the call fails for funds"); - assert!(return_data.is_empty(), "with empty return data"); - assert_eq!( - hints, - vec![RecordedHint { from: CONTRACT, topic: TOPIC, data: Bytes::from_static(b"unfunded") }], - "the hint reached the service", - ); - assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its input is counted"); - assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + data.len() as u64); - let balance = - |address| result.state.get(&address).map_or(U256::ZERO, |account| account.info.balance); - assert_eq!(balance(CONTRACT), U256::ZERO, "no value moved from the caller"); - assert_eq!(balance(ORACLE_CONTRACT_ADDRESS), U256::ZERO, "and none reached the Oracle"); -} - /// A value-bearing `sendHint` its caller cannot fund, under a data-size limit its input would /// cross, is answered with the stop, not with the funds failure: nothing is forwarded and nothing /// is counted. @@ -328,52 +269,6 @@ fn test_an_unknown_selector_runs_the_bytecode() { assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + 4); } -/// Reading the Oracle's storage is not intercepted: `getSlot` runs the contract's code. -#[test] -fn test_reading_a_slot_runs_the_bytecode() { - let db = system_db().account_storage(ORACLE_CONTRACT_ADDRESS, U256::from(3), U256::from(42)); - let data = IOracle::getSlotCall { slot: U256::from(3) }.abi_encode(); - let result = run(db, call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!( - IOracle::getSlotCall::abi_decode_returns(result.result.output().unwrap()).unwrap(), - B256::from(U256::from(42)), - ); -} - -/// A hint cannot be un-sent, so the bytes it cost stay counted even when the frame that sent it -/// reverts and takes its writes back. -#[test] -fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { - use revm::bytecode::opcode::{POP, PUSH0, REVERT}; - - let data = send_hint(b"a hint that was sent"); - let code = BytecodeBuilder::default() - .mstore(0x0, &data) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(data.len() as u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(200_000_u64) - .append(CALL) - .append(POP) - .append_many([PUSH0, PUSH0, REVERT]) - .build(); - - let (result, hints, usage) = - run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(!result.result.is_success(), "the frame that sent the hint reverted"); - assert_eq!(hints.len(), 1, "the hint reached the service before the revert"); - assert_eq!( - usage.data_size, - nested_hint(data.len() as u64), - "the bytes stay counted: a revert cannot take the hint back", - ); -} - /// A payload that does not fit in what is left of the transaction's data-size limit is not /// forwarded, and the crossing stops the transaction: the limit is checked on the hint's bytes /// before the payload is decoded, so it is crossed before the frame the call would have started. @@ -486,31 +381,6 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } -/// Two hints reach the service in the order they were sent. -#[test] -fn test_hints_reach_the_service_in_the_order_they_were_sent() { - use revm::bytecode::opcode::POP; - - let first = IOracle::sendHintCall { - topic: B256::repeat_byte(0x11), - data: Bytes::from_static(&[0xaa, 0xbb]), - }; - let second = IOracle::sendHintCall { - topic: B256::repeat_byte(0x22), - data: Bytes::from_static(&[0xcc, 0xdd]), - }; - let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); - let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); - let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert_eq!( - hints, - vec![ - RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, - RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, - ], - ); -} - /// A malformed `sendHint` payload, and one followed by bytes the decoder drops, are counted /// whole: the first forwards nothing, the second forwards its envelope. Under a limit that holds /// half of the payload, both are stopped before anything is forwarded: the call is answered with From 2b8907ff23a3b0714949fdf4b0d02ac05f3f874d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:19:30 +0800 Subject: [PATCH 174/190] test(system-tx): remove tests the conformance suite pins --- crates/mega-evm/tests/system/system_tx.rs | 55 ----------------------- 1 file changed, 55 deletions(-) diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 2f7960f28..bd356c9a6 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -722,40 +722,6 @@ fn test_a_system_transaction_short_of_its_body_history_is_a_failed_deposit() { assert_eq!(gas.gas_used, least); } -/// A deposit-like transaction whose caller does not exist yet creates that account, and pays -/// the account-creation charge for it exactly once: the same charge a value transfer to a -/// fresh account pays. -#[test] -fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { - // The reference charge: a user transaction that creates one account by sending value to it. - let fresh = address!("0x00000000000000000000000000000000000f0001"); - let reference = - run_outcome(chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), { - let mut tx = legacy_tx(CALLER, TxKind::Call(fresh), Bytes::new(), 0); - tx.0.base.value = U256::from(1); - tx - }); - let one_account = reference.gas.state; - assert_eq!(one_account, account_state_gas(), "a fresh recipient costs state gas"); - - // A system transaction whose sender does not exist yet creates it, for the same charge. - let created = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x77))); - assert!(created.result.is_success(), "{:?}", created.result); - // The same transaction from a sender that already exists: what it pays is the slot it - // writes, and nothing for its own account. - let slot_charge = run_outcome( - chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), - system_tx(0, B256::with_last_byte(0x77)), - ) - .gas - .state; - assert_eq!( - created.gas.state - slot_charge, - one_account, - "the caller's account costs one account creation, and the slot the same either way", - ); -} - /// A deposit whose recipient is its own caller pays for that one account once: by the time the /// recipient is looked at, the caller's materialisation has created it. #[test] @@ -895,27 +861,6 @@ 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. 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))); - let existing = run_outcome( - chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), - system_tx(0, B256::with_last_byte(0x99)), - ); - assert!(fresh.result.is_success() && existing.result.is_success()); - assert_eq!( - (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 /// caller as well as for the contract. #[test] From 7e4be7aad1dd60e318ad41947bb0a955c3803aa5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:39:48 +0800 Subject: [PATCH 175/190] test(contract-size): restore tests whose plain creation boundary no conformance case pins --- crates/mega-evm/tests/satin/contract_size.rs | 65 ++++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 2 files changed, 66 insertions(+) create mode 100644 crates/mega-evm/tests/satin/contract_size.rs diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs new file mode 100644 index 000000000..3bd6865fc --- /dev/null +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -0,0 +1,65 @@ +//! The code-size limits the Satin configuration raises. +//! +//! A deployed contract may hold 512 KiB, eight times more than EIP-7954's bound and twenty-one +//! times EIP-170's; an initcode may hold twice that, the ratio EIP-3860 sets between the two. +//! Both bounds are `CfgEnv` limits the spec fixes, so they apply to a creation transaction and to +//! a `CREATE` alike. + +use alloy_evm::{Evm, EvmError, InvalidTxError}; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, + test_utils::MemoryDatabase, + MegaEvm, MegaHaltReason, MegaTransaction, +}; +use revm::{bytecode::opcode::STOP, context::result::ExecutionResult}; + +use crate::common::{context, create, history}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); + +/// Room for everything a creation here draws, all of it above the execution cap so it comes out of +/// the reservoir: the state gas of the largest deployable code, the history of that code and of a +/// body carrying twice the largest init code, and a billion more, at the byte prices in effect. +fn gas_limit() -> u64 { + TX_GAS_LIMIT_CAP + + MAX_CONTRACT_SIZE as u64 * + mega_evm::satin_gas_params() + .get(revm::context_interface::cfg::GasId::code_deposit_state_gas()) + + history((MAX_CONTRACT_SIZE + 2 * MAX_INITCODE_SIZE) as u64) + + 1_000_000_000 +} + +/// Runs `tx` from `CALLER` and returns its result, or the validation error that rejected it. +fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result, String> { + let mut evm = MegaEvm::new(context(db)); + match evm.transact_raw(tx) { + Ok(outcome) => Ok(outcome.result), + Err(err) => { + let invalid = err + .as_invalid_tx_err() + .and_then(InvalidTxError::as_invalid_tx_err) + .unwrap_or_else(|| panic!("unexpected error {err:?}")); + Err(format!("{invalid:?}")) + } + } +} + +/// Runs `init_code` as a creation transaction from `CALLER`. +fn deploy(init_code: Bytes) -> Result, String> { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + run(create(CALLER, init_code, gas_limit()), db) +} + +/// Init code of `size` bytes that does nothing. +fn initcode_of(size: usize) -> Bytes { + Bytes::from(vec![STOP; size]) +} + +/* ---------- the initcode bound ---------- */ + +/// The Satin bound itself is accepted. +#[test] +fn test_the_satin_initcode_size_is_accepted() { + assert!(deploy(initcode_of(MAX_INITCODE_SIZE)).unwrap().is_success()); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 231e1831a..2dd8f18ea 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -2,6 +2,7 @@ mod common; mod compute_gas; +mod contract_size; mod corpus; mod count_order; mod create_opcodes; From c0120b9a71faf04e7cf5ea93054ca5f051269c1b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:39:48 +0800 Subject: [PATCH 176/190] test(state-growth): restore tests whose native growth stops no conformance case pins --- .../tests/satin/limit_matrix/limits.rs | 15 +++++++++++ crates/mega-evm/tests/satin/state_growth.rs | 25 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/mega-evm/tests/satin/limit_matrix/limits.rs b/crates/mega-evm/tests/satin/limit_matrix/limits.rs index 106d225d4..9aac9729a 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/limits.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/limits.rs @@ -26,6 +26,21 @@ fn join(prefix: Vec, rest: BytecodeBuilder) -> Bytes { 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. diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 772a609d9..48adad8b1 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -868,6 +868,31 @@ fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { ); } +/// 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 From fed789c9939cfd4d7aa431adda7de4b82de18e64 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:39:48 +0800 Subject: [PATCH 177/190] test(oracle): restore tests whose hint payloads no conformance case pins --- crates/mega-evm/tests/system/oracle.rs | 53 ++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 4bf33a530..4c7bad26f 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -125,6 +125,34 @@ fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) } +/// A value-bearing `sendHint` whose caller cannot fund the value is intercepted before revm +/// starts the call and checks the funds: the hint is forwarded and its input counted, then the +/// call fails for the funds with empty return data and moves no value, and the Oracle's bytecode +/// never runs. +#[test] +fn test_an_unfunded_value_hint_is_forwarded_and_then_fails_for_funds() { + let data = send_hint(b"unfunded"); + let (result, hints, usage) = + run_with_oracle(unfunded_contract_db(&data), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(result.result.is_success(), "the contract survives the failed call"); + let returned = result.result.output().cloned().unwrap_or_default(); + let (status, return_data) = crate::common::split_outcome(&returned); + assert!(!status, "the call fails for funds"); + assert!(return_data.is_empty(), "with empty return data"); + assert_eq!( + hints, + vec![RecordedHint { from: CONTRACT, topic: TOPIC, data: Bytes::from_static(b"unfunded") }], + "the hint reached the service", + ); + assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its input is counted"); + assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + data.len() as u64); + let balance = + |address| result.state.get(&address).map_or(U256::ZERO, |account| account.info.balance); + assert_eq!(balance(CONTRACT), U256::ZERO, "no value moved from the caller"); + assert_eq!(balance(ORACLE_CONTRACT_ADDRESS), U256::ZERO, "and none reached the Oracle"); +} + /// A value-bearing `sendHint` its caller cannot fund, under a data-size limit its input would /// cross, is answered with the stop, not with the funds failure: nothing is forwarded and nothing /// is counted. @@ -381,6 +409,31 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } +/// Two hints reach the service in the order they were sent. +#[test] +fn test_hints_reach_the_service_in_the_order_they_were_sent() { + use revm::bytecode::opcode::POP; + + let first = IOracle::sendHintCall { + topic: B256::repeat_byte(0x11), + data: Bytes::from_static(&[0xaa, 0xbb]), + }; + let second = IOracle::sendHintCall { + topic: B256::repeat_byte(0x22), + data: Bytes::from_static(&[0xcc, 0xdd]), + }; + let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); + let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); + let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!( + hints, + vec![ + RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, + RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, + ], + ); +} + /// A malformed `sendHint` payload, and one followed by bytes the decoder drops, are counted /// whole: the first forwards nothing, the second forwards its envelope. Under a limit that holds /// half of the payload, both are stopped before anything is forwarded: the call is answered with From f96e8125a497e13011739677d18834b547f4ae9c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 10:39:48 +0800 Subject: [PATCH 178/190] test(write-records): restore tests whose call and creation inputs no conformance case pins --- crates/mega-evm/tests/satin/write_records.rs | 168 ++++++++++++++++++- 1 file changed, 166 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 5c5c60f81..e56676a9b 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, - LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, + JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -248,6 +248,26 @@ fn test_nested_creations_record_each_account_once() { assert!(result.state.contains_key(&created.create(1))); } +/// 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 @@ -416,6 +436,24 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { } } +/// A creation and a value transfer from one frame record the frame's account once. +#[test] +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, value_call_room()), + ); + assert!(result.result.is_success()); + assert_eq!( + usage, + 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" + ); +} + /// Two creations from one frame record the creator once and each created account. #[test] fn test_two_creates_record_the_creator_once() { @@ -434,6 +472,36 @@ fn test_two_creates_record_the_creator_once() { ); } +/// After a failed transfer the sender can be recorded again by the next one. +/// +/// The first child burns the gas it was forwarded, so the second transfer forwards none: its +/// recipient runs no code, and the records it makes are paid out of what the caller keeps, which +/// then does not depend on the price of the recipient's new account. +#[test] +fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + let code = code + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(CONTRACT2) + .append(PUSH0) + .append(CALL) + .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, value_call_room())); + assert!(result.result.is_success()); + assert_eq!( + usage, + 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 { @@ -537,6 +605,36 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { ); } +/* ---------- storage, logs, selfdestruct ---------- */ + +/// A write-back in a child refunds the record its caller made, and the refund dies with a +/// failing child. +#[test] +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(); + // 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() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build(); + let db = + MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(result.result.is_success()); + assert_eq!(usage, expected); + } +} + /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. @@ -789,6 +887,46 @@ fn authorizing_call( ) } +/// A value transfer to an applied authority records the authority once, not again as the +/// recipient. +#[test] +fn test_value_to_an_applied_authority_records_it_once() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + usage, + 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 + // authority's account is already written. A transfer to an account that is not an authority + // pays for the recipient on top of the one authority it applied. + if crate::common::runs_at_measurement_prices() { + return; + } + const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; + let to_authority = + crate::common::execute(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + let to_another = + crate::common::execute(db(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)])); + let body = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE; + + assert!(to_another.result.is_success(), "{:?}", to_another.result); + assert_eq!( + to_authority.gas.history, + (body + WRITE_RECORD_SIZE) * CPHB, + "the authority's record, and no recipient record beside it", + ); + assert_eq!( + to_another.gas.history, + (body + 2 * WRITE_RECORD_SIZE) * CPHB, + "the authority's record and the recipient's", + ); +} + /// A frame running as the transaction's sender (a delegated sender called back) records no /// write to the sender's account: the transaction body counts it. #[test] @@ -1150,6 +1288,32 @@ fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authoriti const D: Address = address!("00000000000000000000000000000000000000D1"); +/// 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 = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); + 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, + 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 has its own account unchanged, whatever its caller's state: its /// first value transfer records it. #[test] From 4b2bba6a025fd6421fabe9f0b8c6f4f947a9ce4f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 13:26:06 +0800 Subject: [PATCH 179/190] test(mega-eest): move the conformance suite pin to 7f32bdc --- scripts/mega_eest.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index 92b384eca..9a49d9232 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -8,14 +8,14 @@ # pinned here. A commit off the default branch (a suite change still under review) keeps the gate # red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest -MEGA_EEST_REV=ab250afa0b24dd011857e7d65eda9f47b1b7d6b8 +MEGA_EEST_REV=7f32bdc9472aaadda90f517a1ccc63956dccb3eb # The case ids the pin's last move removed, and those it changed under their ids (another file # digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice # drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none # leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a # change is a line the reviewer reads in this file's diff. MEGA_EEST_REMOVED_CASES= -MEGA_EEST_CHANGED_CASES=satin/access-control/delegate-refusal/call-cold-target-refusal-reads satin/access-control/delegate-refusal/callcode-cold-target-refusal-reads satin/access-control/delegate-refusal/delegatecall-cold-target-refusal-reads satin/access-control/delegate-refusal/max-forward-cold-target-refused satin/access-control/delegate-refusal/max-forward-warm-target-refused satin/access-control/delegate-refusal/value-call-at-the-guard satin/access-control/delegate-refusal/value-call-refused satin/access-control/delegate-refusal/value-callcode-refused satin/accounting/fee-account/beneficiary-is-sender satin/accounting/merge/creation-endowment-unfunded satin/accounting/sender/value-call-to-sender satin/authorizations/absent-authority satin/authorizations/limit/one-over-all-or-nothing satin/authorizations/limit/one-over-with-fees satin/authorizations/reads/simulation-past-crossing satin/call-order/unfunded/empty-account satin/detention/delegate-refusal/memory-crossing-reads-nothing satin/detention/delegate-refusal/surcharge-crossing satin/detention/delegate-refusal/surcharge-crossing-keeps-the-memory satin/detention/delegate-refusal/surcharge-crossing-one-short satin/detention/delegate-refusal/surcharge-paid satin/gas-pools/first-frame-revert/authorization-charges-kept satin/keyless/authorizations/1001-new-authorities satin/keyless/contract-call/no-value satin/keyless/refusal/signer-has-code satin/keyless/refusal/signer-nonce-two satin/keyless/refusal/taken-and-unfunded satin/limit-stops/authorization-list/one-authority-over satin/oracle/send-hint/stipend-unfunded satin/outcomes/pre-frame/created-account-one-short satin/outcomes/pre-frame/created-account-paid satin/outcomes/revert/after-fresh-slot satin/reads/balance-cold-paid satin/reads/balance-cold-unpaid satin/reads/oracle-slot-before-charge satin/selfdestruct/created/fresh-slot-on-little-gas satin/selfdestruct/marked/fresh-slot-on-little-gas satin/selfdestruct/not-created/new-beneficiary-caller-reverts satin/system-contracts/limit-control/own-call-with-value satin/take-backs/sent-back/round-trip +MEGA_EEST_CHANGED_CASES= # The repository the suite moved from, exactly as the base's MEGA_EEST_REPO reads, set by the pull # request that changes MEGA_EEST_REPO: the default branch the pin must be on is that repository's, # so a change of repository fails the gate unless it is declared here, and the pin must then be on From 5f4151231ff042206d20accb6c1881920cce05bc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 13:28:14 +0800 Subject: [PATCH 180/190] test(keyless): restore constructor environment slot assertions --- .../mega-evm/tests/system/keyless/deploy.rs | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 18e0a5371..f37da0383 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -20,8 +20,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, ORIGIN, POP, PUSH0, - REVERT, SELFDESTRUCT, SSTORE, STATICCALL, + CALL, CREATE, DELEGATECALL, GAS, GASPRICE, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, ORIGIN, POP, + PUSH0, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, }, context::BlockEnv, primitives::KECCAK_EMPTY, @@ -29,7 +29,7 @@ use revm::{ }; use super::*; -use crate::common::{calls_with, split_outcome, with_contract, CONTRACT}; +use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); @@ -539,6 +539,34 @@ fn priced_tx(deployment: &Deployment, gas_limit: u64, gas_price: u128) -> MegaTr tx } +/// `ORIGIN` and `GASPRICE` in the init code are the transaction's own: the relayer, and the gas +/// price the relayer pays — not the signer, and not the price the deployment was signed at. +#[test] +fn test_origin_and_gasprice_follow_the_outer_transaction() { + let prefix = BytecodeBuilder::default() + .append(ORIGIN) + .push_number(0_u64) + .append(SSTORE) + .append(GASPRICE) + .push_number(1_u64) + .append(SSTORE); + let deployment = Deployment::new(running(prefix)); + for gas_limit in GAS_LIMITS { + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(priced_tx(&deployment, gas_limit, 7)) + .expect("a valid transaction"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let slot = |key: u64| { + outcome.state[&deployment.address] + .storage + .get(&U256::from(key)) + .map(|s| s.present_value) + }; + assert_eq!(slot(0), Some(U256::from_be_slice(RELAYER.as_slice())), "ORIGIN"); + assert_eq!(slot(1), Some(U256::from(7)), "GASPRICE"); + } +} + /// The block's beneficiary is paid for the whole transaction, deployment included, whether the /// deployment succeeds or fails, and the signer pays nothing. fn assert_beneficiary_paid(init_code: Bytes) { From b9ed9c28ada91d2efd61863df787dd1a6f7e67ed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:08:22 +0800 Subject: [PATCH 181/190] test(eest): update the conformance suite pin --- scripts/mega_eest.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index 9a49d9232..1bbd63abc 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -8,14 +8,14 @@ # pinned here. A commit off the default branch (a suite change still under review) keeps the gate # red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest -MEGA_EEST_REV=7f32bdc9472aaadda90f517a1ccc63956dccb3eb +MEGA_EEST_REV=26b8e3cc0cacaf915960fb9d5cbd069c469a6473 # The case ids the pin's last move removed, and those it changed under their ids (another file # digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice # drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none # leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a # change is a line the reviewer reads in this file's diff. MEGA_EEST_REMOVED_CASES= -MEGA_EEST_CHANGED_CASES= +MEGA_EEST_CHANGED_CASES=satin/authorizations/gates/chain-id-zero # The repository the suite moved from, exactly as the base's MEGA_EEST_REPO reads, set by the pull # request that changes MEGA_EEST_REPO: the default branch the pin must be on is that repository's, # so a change of repository fails the gate unless it is declared here, and the pin must then be on From 6161bd7184cfbcc6d0dacd31cf9fe18518f7a198 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:13:09 +0800 Subject: [PATCH 182/190] test(oracle): keep focused hint recorder coverage --- crates/mega-evm/tests/system/oracle.rs | 60 +++++++------------------- 1 file changed, 15 insertions(+), 45 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 4c7bad26f..44ce69c02 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -125,34 +125,6 @@ fn unfunded_contract_db(data: &[u8]) -> MemoryDatabase { system_db().account_code(CONTRACT, unfunded_value_hint_call(data)) } -/// A value-bearing `sendHint` whose caller cannot fund the value is intercepted before revm -/// starts the call and checks the funds: the hint is forwarded and its input counted, then the -/// call fails for the funds with empty return data and moves no value, and the Oracle's bytecode -/// never runs. -#[test] -fn test_an_unfunded_value_hint_is_forwarded_and_then_fails_for_funds() { - let data = send_hint(b"unfunded"); - let (result, hints, usage) = - run_with_oracle(unfunded_contract_db(&data), call_tx(CONTRACT, [], U256::ZERO)); - - assert!(result.result.is_success(), "the contract survives the failed call"); - let returned = result.result.output().cloned().unwrap_or_default(); - let (status, return_data) = crate::common::split_outcome(&returned); - assert!(!status, "the call fails for funds"); - assert!(return_data.is_empty(), "with empty return data"); - assert_eq!( - hints, - vec![RecordedHint { from: CONTRACT, topic: TOPIC, data: Bytes::from_static(b"unfunded") }], - "the hint reached the service", - ); - assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its input is counted"); - assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + data.len() as u64); - let balance = - |address| result.state.get(&address).map_or(U256::ZERO, |account| account.info.balance); - assert_eq!(balance(CONTRACT), U256::ZERO, "no value moved from the caller"); - assert_eq!(balance(ORACLE_CONTRACT_ADDRESS), U256::ZERO, "and none reached the Oracle"); -} - /// A value-bearing `sendHint` its caller cannot fund, under a data-size limit its input would /// cross, is answered with the stop, not with the funds failure: nothing is forwarded and nothing /// is counted. @@ -409,29 +381,27 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } -/// Two hints reach the service in the order they were sent. #[test] -fn test_hints_reach_the_service_in_the_order_they_were_sent() { - use revm::bytecode::opcode::POP; +fn test_recorded_hints_preserve_order_and_fields_across_clones() { + use mega_evm::OracleEnv; - let first = IOracle::sendHintCall { + let env = TestExternalEnvs::default(); + let writer = env.clone(); + let first = RecordedHint { + from: CALLER, topic: B256::repeat_byte(0x11), - data: Bytes::from_static(&[0xaa, 0xbb]), + data: Bytes::from_static(b"first hint"), }; - let second = IOracle::sendHintCall { + let second = RecordedHint { + from: CONTRACT, topic: B256::repeat_byte(0x22), - data: Bytes::from_static(&[0xcc, 0xdd]), + data: Bytes::from_static(b"second hint"), }; - let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); - let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); - let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert_eq!( - hints, - vec![ - RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, - RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, - ], - ); + + writer.on_hint(first.from, first.topic, first.data.clone()); + writer.on_hint(second.from, second.topic, second.data.clone()); + + assert_eq!(env.recorded_hints(), vec![first, second]); } /// A malformed `sendHint` payload, and one followed by bytes the decoder drops, are counted From f76a9c175751a911a47cc3e2333642edfeb10b0f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:32:57 +0800 Subject: [PATCH 183/190] test(write-records): remove tests the conformance suite pins --- crates/mega-evm/tests/satin/write_records.rs | 162 ------------------- 1 file changed, 162 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index e56676a9b..4975570d4 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -248,26 +248,6 @@ fn test_nested_creations_record_each_account_once() { assert!(result.state.contains_key(&created.create(1))); } -/// 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 @@ -436,24 +416,6 @@ fn test_a_creation_records_its_account_only_when_it_changes_it() { } } -/// A creation and a value transfer from one frame record the frame's account once. -#[test] -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, value_call_room()), - ); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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" - ); -} - /// Two creations from one frame record the creator once and each created account. #[test] fn test_two_creates_record_the_creator_once() { @@ -472,36 +434,6 @@ fn test_two_creates_record_the_creator_once() { ); } -/// After a failed transfer the sender can be recorded again by the next one. -/// -/// The first child burns the gas it was forwarded, so the second transfer forwards none: its -/// recipient runs no code, and the records it makes are paid out of what the caller keeps, which -/// then does not depend on the price of the recipient's new account. -#[test] -fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { - let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); - let code = code - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .append(PUSH1) - .append(1u8) - .push_address(CONTRACT2) - .append(PUSH0) - .append(CALL) - .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, value_call_room())); - assert!(result.result.is_success()); - assert_eq!( - usage, - 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 { @@ -607,34 +539,6 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { /* ---------- storage, logs, selfdestruct ---------- */ -/// A write-back in a child refunds the record its caller made, and the refund dies with a -/// failing child. -#[test] -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(); - // 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() - .sstore(U256::ZERO, U256::from(1)) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(CONTRACT) - .append(GAS) - .append(revm::bytecode::opcode::DELEGATECALL) - .append(POP) - .stop() - .build(); - let db = - MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); - assert!(result.result.is_success()); - assert_eq!(usage, expected); - } -} - /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. @@ -887,46 +791,6 @@ fn authorizing_call( ) } -/// A value transfer to an applied authority records the authority once, not again as the -/// recipient. -#[test] -fn test_value_to_an_applied_authority_records_it_once() { - let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let (result, usage) = run(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!( - usage, - 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 - // authority's account is already written. A transfer to an account that is not an authority - // pays for the recipient on top of the one authority it applied. - if crate::common::runs_at_measurement_prices() { - return; - } - const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; - let to_authority = - crate::common::execute(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); - let to_another = - crate::common::execute(db(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)])); - let body = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE; - - assert!(to_another.result.is_success(), "{:?}", to_another.result); - assert_eq!( - to_authority.gas.history, - (body + WRITE_RECORD_SIZE) * CPHB, - "the authority's record, and no recipient record beside it", - ); - assert_eq!( - to_another.gas.history, - (body + 2 * WRITE_RECORD_SIZE) * CPHB, - "the authority's record and the recipient's", - ); -} - /// A frame running as the transaction's sender (a delegated sender called back) records no /// write to the sender's account: the transaction body counts it. #[test] @@ -1288,32 +1152,6 @@ fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authoriti const D: Address = address!("00000000000000000000000000000000000000D1"); -/// 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 = - append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); - let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) - .append(POP) - .append(STOP) - .build(); - let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); - 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, - 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 has its own account unchanged, whatever its caller's state: its /// first value transfer records it. #[test] From f0ae8075572484a453391af8aab48a7fb30aa59d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:32:57 +0800 Subject: [PATCH 184/190] test(keyless): remove tests the conformance suite pins --- .../mega-evm/tests/system/keyless/deploy.rs | 32 ++----------------- 1 file changed, 2 insertions(+), 30 deletions(-) diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index f37da0383..9eb40c8f2 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -20,8 +20,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, GASPRICE, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, ORIGIN, POP, - PUSH0, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, + CALL, CREATE, DELEGATECALL, GAS, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, ORIGIN, POP, PUSH0, + REVERT, SELFDESTRUCT, SSTORE, STATICCALL, }, context::BlockEnv, primitives::KECCAK_EMPTY, @@ -539,34 +539,6 @@ fn priced_tx(deployment: &Deployment, gas_limit: u64, gas_price: u128) -> MegaTr tx } -/// `ORIGIN` and `GASPRICE` in the init code are the transaction's own: the relayer, and the gas -/// price the relayer pays — not the signer, and not the price the deployment was signed at. -#[test] -fn test_origin_and_gasprice_follow_the_outer_transaction() { - let prefix = BytecodeBuilder::default() - .append(ORIGIN) - .push_number(0_u64) - .append(SSTORE) - .append(GASPRICE) - .push_number(1_u64) - .append(SSTORE); - let deployment = Deployment::new(running(prefix)); - for gas_limit in GAS_LIMITS { - let outcome = MegaEvm::new(context(system_db())) - .execute_transaction(priced_tx(&deployment, gas_limit, 7)) - .expect("a valid transaction"); - assert_eq!(returned(&outcome).deployedAddress, deployment.address); - let slot = |key: u64| { - outcome.state[&deployment.address] - .storage - .get(&U256::from(key)) - .map(|s| s.present_value) - }; - assert_eq!(slot(0), Some(U256::from_be_slice(RELAYER.as_slice())), "ORIGIN"); - assert_eq!(slot(1), Some(U256::from(7)), "GASPRICE"); - } -} - /// The block's beneficiary is paid for the whole transaction, deployment included, whether the /// deployment succeeds or fails, and the signer pays nothing. fn assert_beneficiary_paid(init_code: Bytes) { From bae76c471ca749d0b6c10d4fbe19999540871fa0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:35:14 +0800 Subject: [PATCH 185/190] test: remove unused imports after conformance migration --- crates/mega-evm/tests/satin/write_records.rs | 4 ++-- crates/mega-evm/tests/system/keyless/deploy.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 4975570d4..a7966690e 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, - JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, + LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 9eb40c8f2..18e0a5371 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -29,7 +29,7 @@ use revm::{ }; use super::*; -use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; +use crate::common::{calls_with, split_outcome, with_contract, CONTRACT}; /// An account the deployments below call into. const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); From f85d4a8a9a41d0031adafd9bf45c5616ecc23512 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:48:38 +0800 Subject: [PATCH 186/190] test(oracle): restore tests whose hint input offset no conformance case pins --- crates/mega-evm/tests/system/oracle.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 44ce69c02..9e0c6bc13 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -381,6 +381,31 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } +/// Two hints reach the service in the order they were sent. +#[test] +fn test_hints_reach_the_service_in_the_order_they_were_sent() { + use revm::bytecode::opcode::POP; + + let first = IOracle::sendHintCall { + topic: B256::repeat_byte(0x11), + data: Bytes::from_static(&[0xaa, 0xbb]), + }; + let second = IOracle::sendHintCall { + topic: B256::repeat_byte(0x22), + data: Bytes::from_static(&[0xcc, 0xdd]), + }; + let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); + let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); + let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!( + hints, + vec![ + RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, + RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, + ], + ); +} + #[test] fn test_recorded_hints_preserve_order_and_fields_across_clones() { use mega_evm::OracleEnv; From 98658e5754ca417e1138844c9a7f4bc69073ce81 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 14:48:38 +0800 Subject: [PATCH 187/190] test(write-records): restore tests whose absent sender no conformance case pins --- crates/mega-evm/tests/satin/write_records.rs | 32 ++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index a7966690e..dfe9f6741 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, - LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, + JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -539,6 +539,34 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { /* ---------- storage, logs, selfdestruct ---------- */ +/// A write-back in a child refunds the record its caller made, and the refund dies with a +/// failing child. +#[test] +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(); + // 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() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build(); + let db = + MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(result.result.is_success()); + assert_eq!(usage, expected); + } +} + /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. From 14d2b5cddfd810296a2e31d9a6c96ee2fef2787a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 17:04:32 +0800 Subject: [PATCH 188/190] test(eest): update the conformance suite pin --- scripts/mega_eest.env | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mega_eest.env b/scripts/mega_eest.env index 1bbd63abc..16865ca63 100644 --- a/scripts/mega_eest.env +++ b/scripts/mega_eest.env @@ -8,14 +8,14 @@ # pinned here. A commit off the default branch (a suite change still under review) keeps the gate # red until the pin moves to the merged commit. MEGA_EEST_REPO=https://github.com/RealiCZ/mega-eest -MEGA_EEST_REV=26b8e3cc0cacaf915960fb9d5cbd069c469a6473 +MEGA_EEST_REV=990447bc82a6cbaea2e3539ddd8702a7e7a5ac44 # The case ids the pin's last move removed, and those it changed under their ids (another file # digest), each space-separated and exact: a pull request that moves the pin to a commit whose slice # drops or rewrites cases lists them here, or the gate fails; a move that removes or changes none # leaves the line empty. Cases are mega-evm's tests of the behaviours they pin, so a removal or a # change is a line the reviewer reads in this file's diff. MEGA_EEST_REMOVED_CASES= -MEGA_EEST_CHANGED_CASES=satin/authorizations/gates/chain-id-zero +MEGA_EEST_CHANGED_CASES=satin/oracle/send-hint/full-topics-in-order satin/take-backs/descendant/fresh-slot-restore-halted-gas satin/take-backs/descendant/fresh-slot-restore-kept-gas # The repository the suite moved from, exactly as the base's MEGA_EEST_REPO reads, set by the pull # request that changes MEGA_EEST_REPO: the default branch the pin must be on is that repository's, # so a change of repository fails the gate unless it is declared here, and the pin must then be on From 9de72ef3730c06b5f7005947cef7bc121a2f3a8f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 17:41:31 +0800 Subject: [PATCH 189/190] test(write-records): remove the covered child write-back test --- crates/mega-evm/tests/satin/write_records.rs | 34 ++------------------ 1 file changed, 2 insertions(+), 32 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index dfe9f6741..5c5c60f81 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -30,8 +30,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, INVALID, JUMPDEST, - JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, + LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STATICCALL, STOP, }, context::ContextTr, interpreter::{ @@ -537,36 +537,6 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { ); } -/* ---------- storage, logs, selfdestruct ---------- */ - -/// A write-back in a child refunds the record its caller made, and the refund dies with a -/// failing child. -#[test] -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(); - // 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() - .sstore(U256::ZERO, U256::from(1)) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(CONTRACT) - .append(GAS) - .append(revm::bytecode::opcode::DELEGATECALL) - .append(POP) - .stop() - .build(); - let db = - MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); - assert!(result.result.is_success()); - assert_eq!(usage, expected); - } -} - /* ---------- the fee accounts and the sender ---------- */ /// The block beneficiary of the fee-account rows: an account of its own, not the zero address. From ae840ff636413c20269b20b44ddf90587c73c325 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 19 Nov 2026 17:56:49 +0800 Subject: [PATCH 190/190] test(oracle): remove covered ordered hint integration test --- crates/mega-evm/tests/system/oracle.rs | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 9e0c6bc13..44ce69c02 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -381,31 +381,6 @@ fn test_the_oracles_code_elsewhere_forwards_no_hint() { assert!(hints.is_empty()); } -/// Two hints reach the service in the order they were sent. -#[test] -fn test_hints_reach_the_service_in_the_order_they_were_sent() { - use revm::bytecode::opcode::POP; - - let first = IOracle::sendHintCall { - topic: B256::repeat_byte(0x11), - data: Bytes::from_static(&[0xaa, 0xbb]), - }; - let second = IOracle::sendHintCall { - topic: B256::repeat_byte(0x22), - data: Bytes::from_static(&[0xcc, 0xdd]), - }; - let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); - let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); - let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - assert_eq!( - hints, - vec![ - RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, - RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, - ], - ); -} - #[test] fn test_recorded_hints_preserve_order_and_fields_across_clones() { use mega_evm::OracleEnv;