Skip to content

refactor(revm): eliminate custom SLOAD/SSTORE instruction overrides by properly managing storage slot transaction_id #187

Closed

Description

@panos-xyz

Description

Currently, MorphEvm in crates/revm/src/evm.rs overrides standard EVM opcodes SLOAD (0x54) and SSTORE (0x55) via custom instruction implementations (sload_morph and sstore_morph). Notably, sstore_morph duplicates ~80 lines of revm's internal SSTORE execution logic (static check, reentrancy sentry, Berlin cold loading, dynamic gas, and refund accounting).

While this workaround successfully prevents a ~2800 gas divergence vs morph-geth, maintaining custom implementations for fundamental EVM storage opcodes introduces significant technical debt and high consensus-divergence risk during upstream revm/reth upgrades.

Background & Root Cause

In Morph's alternative token fee model (feeTokenID > 0), the caller's ERC20 balance storage slot is deducted during validate_against_state_and_deduct_caller prior to transaction execution. To ensure that the subsequent transaction execution pays the EIP-2929 cold access fee (2100 gas) if it touches the same fee-token slot (matching morph-geth), the account and storage slot are marked cold (slot.mark_cold()).

In revm-state (40+ / 42.0.0), StorageSlot::mark_warm_with_transaction_id handles cold-to-warm transitions. If self.transaction_id.get() != transaction_id.get(), revm assumes the slot belonged to a previous transaction and re-baselines:

self.original_value = self.present_value;

Because present_value was already mutated by the token fee deduction, resetting original_value = present_value causes EIP-2200 to treat the slot as "clean" rather than "dirty", charging 2900 gas (SSTORE_RESET) instead of 100 gas (WARM_STORAGE_READ_COST), creating a 2800 gas discrepancy vs go-ethereum.

Current Workaround & Risks

To fix this, sload_morph and sstore_morph were introduced to re-fetch the committed value from the DB on cold access and restore slot.original_value.

However, sstore_morph re-implements the full SSTORE lifecycle:

  1. Upstream Fragility: Any upstream refactors in gas_params, sstore_dynamic_gas, or hardfork rules (Prague, Osaka, EOF) require manual synchronization.
  2. Consensus Risk: If upstream fixes an edge case in SSTORE and sstore_morph is not updated, a consensus divergence / chain split could occur.

Proposed Solution

Re-inspecting revm-state-42.0.0/src/lib.rs:620-633:

pub const fn mark_warm_with_transaction_id(&mut self, transaction_id: TransactionId) -> bool {
    let is_cold = self.is_cold_transaction_id(transaction_id);
    // Re-baseline the EIP-2200 original_value only when the slot belongs to a *previous* transaction
    if self.transaction_id.get() != transaction_id.get() {
        self.original_value = self.present_value;
    }
    self.transaction_id = transaction_id;
    self.is_cold = false;
    is_cold
}

revm already protects against resetting original_value if self.transaction_id == transaction_id. The reset was triggered because the slot's transaction_id was not properly aligned with the main transaction (e.g., after sub-execution evm.finalize() or pre-execution slot loading).

We can resolve this cleanly at the state/handler level without touching opcodes:

  1. In crates/revm/src/handler.rs at the end of validate_and_deduct_token_fee:
    • Keep the committed DB value as slot.original_value;
    • Keep the fee-deducted balance as slot.present_value;
    • Explicitly sync slot.transaction_id = evm.ctx().journal().transaction_id;
    • Set slot.is_cold = true and ensure warm cache/access-list entries are purged so the cold check succeeds.
  2. When the main transaction executes, revm's native mark_warm_with_transaction_id sees matching transaction_ids and skips overwriting original_value.
  3. Completely remove sload_morph and sstore_morph from crates/revm/src/evm.rs, restoring native EthInstructions::new_mainnet_with_spec(...).

Activity

  1. panos-xyz commented on Sep 7, 2026

    @panos-xyz
    ContributorAuthor

    Verdict: the proposed solution cannot work as written on the revm version we actually pin

    I verified this both at unit level and end-to-end. Summary: the motivation is valid and this issue should stay open, but the proposed mechanism is based on a version mismatch and would silently reintroduce the 2800 gas divergence.


    1. The quoted revm code is 42.0.0; we are pinned to 41.0.0

    The issue quotes:

    if self.transaction_id.get() != transaction_id.get() {
        self.original_value = self.present_value;
    }

    That is revm-state 42.0.0. The root Cargo.toml pins revm = "41.0.0" and Cargo.lock resolves a single revm 41.0.0 (no [patch] section). revm-state 41.0.0 reads:

    let is_cold = self.is_cold_transaction_id(transaction_id);  // = tx_id differs || self.is_cold
    if is_cold {
        self.original_value = self.present_value;               // one condition drives BOTH gas and re-baseline
    }

    The narrowed condition landed via our own upstream PR bluealloy/revm#3746 (merged 2026-06-18), first released in revm-state 42.0.0 (still present in 43.0.0). So "revm already protects against resetting original_value if self.transaction_id == transaction_id" is true for 42+, false for 41.

    Unit-level check against the pinned crate — slot with original=100, present=90, matching transaction_id, mark_cold() applied:

    was_cold=true  original=90  present=90     // original clobbered even though tx ids match
    

    2. The stated root cause is wrong: the trigger is is_cold, not a transaction_id mismatch

    Instrumented run at the first cold SLOAD of the fee slot:

    cold-sload key=740682...058  db_original=1000000000000000000000
               slot.original=999997999999999999919  slot.present=999997999999999999919
               slot.tx_id=TransactionId(0)  journal.tx_id=TransactionId(0)
    

    The ids are already equal, and original_value has already been clobbered by the time the instruction body runs. Why the ids can never diverge here:

    • reth v2.4.0 contains no commit_tx call anywhere; each transaction goes through ExecuteEvm::transact = transact_one + finalize().
    • JournalInner::finalize() resets transaction_id to TransactionId::ZERO (it does not increment it).

    So transaction_id is a constant 0 throughout morph's execution path. The only thing that makes is_cold_transaction_id() return true is the is_cold flag set by slot.mark_cold() — and that flag is exactly what we need in order to charge the EIP-2929 2100 cold cost like morph-geth. On revm 41 this is a deadlock: charging the cold cost requires setting is_cold, and setting is_cold forces the original_value re-baseline.

    Consequently step 1's "explicitly sync slot.transaction_id" is a no-op on the balance_slot path — they are already in sync.

    3. End-to-end: implementing the proposal costs exactly +2800 gas

    I implemented the proposal literally (dropped the 0x54/0x55 overrides, and in validate_and_deduct_token_fee set slot.transaction_id = journal.inner.transaction_id; slot.is_cold = true while keeping the DB-committed original_value and the fee-deducted present_value):

    morph_tx::morph_tx_v0_token_fee_transfer_to_fee_token_contract_gas_regression ... FAILED
      left: 50928        right: 48128        delta: 2800
    

    Good news: the existing golden test (crates/node/tests/it/morph_tx.rs:459) does catch it, so this class of regression cannot reach mainnet silently.

    4. One step of the proposal would introduce a new divergence

    "ensure warm cache/access-list entries are purged so the cold check succeeds"

    Cold determination in revm is slot.is_cold_transaction_id(tx_id) && access_list lookup misses. That access_list is the transaction's own EIP-2930 list — morph-geth treats those slots as warm too (SlotInAccessList). Purging it would make us charge 2100 where geth charges 100. It is also unnecessary: mark_cold() alone already makes the cold check succeed (the experiment above did charge the cold cost).


    5. The motivation is sound — the upstream drift has already happened

    This is not a hypothetical:

    1. sstore_morph is missing the EIP-8037 branch that upstream sstore_default_gas_accounting has (state_gas! plus refill_reservoir). It is dormant only because every MorphHardfork maps below SpecId::AMSTERDAM, guarded by test_morph_hardforks_do_not_enable_amsterdam_state_gas.
    2. sload_morph unconditionally takes the Berlin path, while upstream sload still has a pre-Berlin branch. Safe only because morph's earliest fork maps to CANCUN.

    So the concern about hand-maintained SSTORE drifting from upstream is real and has already materialised once. The issue should stay — the plan needs rewriting.


    6. Suggested replacement plan

    Track A — the actual precondition for deleting the overrides: revm >= 42.

    Note this cannot be done by bumping revm alone: reth v2.4.0 depends on revm ^41, so a standalone bump resolves two semver-incompatible revm versions and the types no longer line up across the reth API boundary. It has to ride a reth upgrade (reth main is already on revm 43). Two invariants to keep when we get there:

    • Keep the 48_128 golden e2e test. It is the tripwire.
    • The transfer_erc20_with_evm branch (handler.rs:628, evm.finalize()) stays fragile even on 42: finalize() resets the journal's transaction_id to ZERO while the slots re-inserted via state.extend() keep their old id. Both are 0 today, but if upstream ever switches to commit_tx (incrementing ids), that branch gets a genuine id mismatch and original_value is re-baselined again — on 42 as well. The issue's "explicitly sync transaction_id" idea is genuinely useful here, as an asserted invariant, even though it is a no-op on the slot path.
    • Upstream PR #3746 only fixed the storage slot. revm-context 42 still calls account.set_current_info_as_original() unconditionally on a cold account load, gated on the same is_cold_transaction_id. Harmless for us today (token fee deduction only touches storage, never account info), but the same bug class remains one layer up.

    Track B — removes the duplication the issue complains about, today, without any revm bump.

    revm 41 already exposes the extension point upstream intended for exactly this: revm::interpreter::instructions::host::sstore_with_gas_accounting, documented as "Custom instruction sets can override the SSTORE opcode and call this helper with their own gas accounting closure", plus the public sstore_default_gas_accounting. SLOAD can delegate to host::sload the same way.

    Mechanics that make it work:

    • read the storage key non-destructively via StackTr::data().last() before delegating;
    • InstructionContext { interpreter, host } has public fields, so it can be reborrowed to keep access after the delegated call;
    • replace the DB read-back with snapshot original_value before the access, restore it after if it changed — a local, opcode-scoped implementation of PR #3746's semantics, with no DB lookup.

    The static check, reentrancy sentry, cold loading, EIP-8037 state gas and refund accounting all go back to upstream; morph keeps roughly a dozen lines of original_value repair instead of ~80 lines of copied SSTORE lifecycle.

    I prototyped this locally and it is green:

    morph-revm + morph-evm:   110 tests run: 110 passed
    morph-node e2e (binary it): 102 tests run: 102 passed   (including the 48_128 golden)
    

    Happy to open a PR for Track B.


    7. Side finding (low severity, separate issue)

    sload_morph / sstore_morph currently repair original_value from the DB for every cold slot, including slots of an account created within the same transaction. revm returns ZERO with original = ZERO for is_newly_created accounts; if the DB holds residual storage for that (address, key), the repair writes a non-zero original_value and EIP-2200 gas/refund come out wrong. Practically unreachable (SELFDESTRUCT is disabled in Morph, so it needs an address with pre-existing storage and no code), but worth noting — the Track B snapshot/restore approach avoids it by construction.

  2. panos-xyz commented on Sep 7, 2026

    @panos-xyz
    ContributorAuthor

    PR #194 implements this — deleting sload_morph/sstore_morph and restoring native EthInstructions, stacked behind #188 (which brings revm 42 and therefore bluealloy/revm#3746) and #191.

    Not via the mechanism proposed in the description: on revm 41 the transaction_id sync is a no-op (the ids already match — the trigger is the is_cold flag), and implementing it as written reintroduced the divergence at exactly +2800 gas. Details in the comment above.

    Verified as a controlled comparison on the morph_tx_v0_token_fee_transfer_to_fee_token_contract_gas_regression golden test — revm 41 + overrides 48_128, revm 41 − overrides 50_928, revm 42 − overrides 48_128 — so the golden test is confirmed to be a real tripwire and is kept unchanged as the gate.

  3. added 2 commits that reference this issue on Sep 7, 2026
    322ad1a
    af7f036
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions