diff --git a/Cargo.toml b/Cargo.toml index 773ed379..655df6e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -185,9 +185,13 @@ reth-trie-sparse = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-mor reth-revm = { git = "https://github.com/morph-l2/reth", tag = "v2.5.2-morph.1", default-features = false, features = [ "optional-checks", ] } +# `optional_no_base_fee` keeps `CfgEnv::disable_base_fee` and +# `is_base_fee_check_disabled()` available to standalone `morph-revm` builds; the +# node build already enables it through `reth-engine-tree`. revm = { version = "42.0.1", features = [ "optional_fee_charge", "optional_eip7623", + "optional_no_base_fee", ], default-features = false } alloy = { version = "2.3.0", default-features = false } diff --git a/crates/evm/src/block/mod.rs b/crates/evm/src/block/mod.rs index 9b66a3f9..37b49922 100644 --- a/crates/evm/src/block/mod.rs +++ b/crates/evm/src/block/mod.rs @@ -7,6 +7,7 @@ mod factory; mod receipt; +mod simulate; pub(crate) use factory::MorphBlockExecutorFactory; pub(crate) use receipt::{ @@ -24,7 +25,10 @@ use alloy_evm::{ }; use alloy_primitives::{Address, U256}; use morph_primitives::{MorphReceipt, MorphTxEnvelope}; -use morph_revm::{L1_GAS_PRICE_ORACLE_ADDRESS, MorphHaltReason, TokenFeeInfo, evm::MorphContext}; +use morph_revm::{ + L1_GAS_PRICE_ORACLE_ADDRESS, MorphHaltReason, TokenFeeInfo, encode_simulated_tx_for_l1_fee, + evm::MorphContext, +}; use reth_primitives_traits::Recovered; use reth_revm::{DatabaseCommit, Inspector, context::result::ResultAndState}; use revm::context::Block; @@ -208,7 +212,7 @@ where &mut self, tx: impl ExecutableTx, ) -> Result { - let (tx_env, recovered) = tx.into_parts(); + let (mut tx_env, recovered) = tx.into_parts(); // Validate gas limit against the geth-compatible block gas pool. Receipt gas cannot be // used here: L1 messages report their actual execution cost in receipts but reserve their @@ -226,6 +230,10 @@ where ))); } + if simulate::needs_simulated_l1_encoding(self.evm.cfg_env(), tx_env.rlp_bytes.as_ref()) { + tx_env.rlp_bytes = Some(encode_simulated_tx_for_l1_fee(recovered.tx())); + } + // Clone the consensus tx and signer BEFORE transact (since we can't move out later). let consensus_tx = recovered.tx().clone(); let signer = *recovered.signer(); diff --git a/crates/evm/src/block/simulate.rs b/crates/evm/src/block/simulate.rs new file mode 100644 index 00000000..fa5b1205 --- /dev/null +++ b/crates/evm/src/block/simulate.rs @@ -0,0 +1,80 @@ +//! L1 data fee encoding for `eth_simulateV1` calls executed by [`super::MorphBlockExecutor`]. + +use alloy_primitives::Bytes; +use revm::context::Cfg; + +/// Whether a simulated transaction must be priced with a placeholder-signature encoding. +/// +/// Upstream `eth_simulateV1` (`simulate::execute_transactions`) wraps resolved calls in an empty +/// `WithEncoded` envelope with a zero signature on the recovered transaction. A +/// `validation: true` simulation (EIP-3607 disabled, nonce checks and fee charging on) is +/// priced like a real signed transaction, so the executor encodes a copy with a full-size +/// placeholder signature for Morph's L1 data fee without touching the recovered transaction. +/// A `validation: false` simulation keeps the empty envelope, which the handler prices at zero +/// L1 fee as upstream does for L2s. Consensus execution never disables EIP-3607, so a real +/// transaction is never given a fabricated encoding. +pub(super) fn needs_simulated_l1_encoding(cfg: &impl Cfg, rlp_bytes: Option<&Bytes>) -> bool { + cfg.is_eip3607_disabled() + && !cfg.is_nonce_check_disabled() + && !cfg.is_fee_charge_disabled() + && rlp_bytes.is_none_or(|bytes| bytes.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::needs_simulated_l1_encoding; + use alloy_primitives::Bytes; + use morph_chainspec::MorphHardfork; + use revm::context::CfgEnv; + + fn cfg( + eip3607_disabled: bool, + nonce_check_disabled: bool, + fee_charge_disabled: bool, + ) -> CfgEnv { + let mut cfg = CfgEnv::new_with_spec(MorphHardfork::Celadon); + cfg.disable_eip3607 = eip3607_disabled; + cfg.disable_nonce_check = nonce_check_disabled; + cfg.disable_fee_charge = fee_charge_disabled; + cfg + } + + #[test] + fn consensus_execution_never_gets_a_placeholder_encoding() { + let consensus = cfg(false, false, false); + assert!(!needs_simulated_l1_encoding(&consensus, None)); + assert!(!needs_simulated_l1_encoding( + &consensus, + Some(&Bytes::new()) + )); + } + + #[test] + fn only_validating_simulations_get_a_placeholder_encoding() { + // `eth_simulateV1` with `validation: true`. + assert!(needs_simulated_l1_encoding( + &cfg(true, false, false), + Some(&Bytes::new()) + )); + assert!(needs_simulated_l1_encoding(&cfg(true, false, false), None)); + // `validation: false` keeps the empty envelope, priced at zero L1 fee by the handler. + assert!(!needs_simulated_l1_encoding( + &cfg(true, true, false), + Some(&Bytes::new()) + )); + // Fee charging disabled (`eth_call`-style) never computes an L1 fee. + assert!(!needs_simulated_l1_encoding( + &cfg(true, false, true), + Some(&Bytes::new()) + )); + } + + #[test] + fn real_encoding_is_never_replaced() { + let encoded = Bytes::from_static(&[0x02, 0xc0]); + assert!(!needs_simulated_l1_encoding( + &cfg(true, false, false), + Some(&encoded) + )); + } +} diff --git a/crates/node/src/test_utils.rs b/crates/node/src/test_utils.rs index 8874e847..1b9af469 100644 --- a/crates/node/src/test_utils.rs +++ b/crates/node/src/test_utils.rs @@ -282,6 +282,38 @@ impl TestNodeBuilder { self } + /// Override a storage slot for an account in the test genesis. + pub fn with_account_storage(mut self, address: Address, slot: U256, value: U256) -> Self { + let alloc = self + .genesis_json + .get_mut("alloc") + .and_then(serde_json::Value::as_object_mut) + .expect("test genesis alloc must be an object"); + let address_lower = address.to_string().to_ascii_lowercase(); + let key = alloc + .keys() + .find(|existing| existing.eq_ignore_ascii_case(&address_lower)) + .cloned() + .unwrap_or(address_lower); + let entry = alloc + .entry(key) + .or_insert_with(|| serde_json::json!({ "balance": "0x0" })); + let entry = entry + .as_object_mut() + .expect("test genesis account entry must be an object"); + let storage = entry + .entry("storage") + .or_insert_with(|| serde_json::json!({})); + let storage = storage + .as_object_mut() + .expect("test genesis account storage must be an object"); + storage.insert( + format!("{slot:#066x}"), + serde_json::json!(format!("{value:#066x}")), + ); + self + } + /// Set the number of nodes to start. /// /// When `num_nodes > 1`, all nodes are interconnected via a simulated P2P network. diff --git a/crates/node/tests/it/rpc.rs b/crates/node/tests/it/rpc.rs index 2e49b44a..2976cf90 100644 --- a/crates/node/tests/it/rpc.rs +++ b/crates/node/tests/it/rpc.rs @@ -1310,3 +1310,636 @@ async fn native_get_proof_and_get_multi_proof_succeed_on_latest() -> eyre::Resul Ok(()) } + +/// Decodes a 32-byte hex string (with `0x` prefix) returned by EVM calls into a [`U256`]. +fn decode_u256_word(hex: &str) -> U256 { + let bytes = + alloy_primitives::hex::decode(hex.trim_start_matches("0x")).expect("valid hex return data"); + assert_eq!(bytes.len(), 32, "expected 32-byte ABI word, got {hex}"); + U256::from_be_slice(&bytes) +} + +/// Decodes two concatenated 32-byte hex words returned by the 2-address balance reader. +fn decode_two_u256_words(hex: &str) -> (U256, U256) { + let bytes = + alloy_primitives::hex::decode(hex.trim_start_matches("0x")).expect("valid hex return data"); + assert_eq!(bytes.len(), 64, "expected 64-byte ABI output, got {hex}"); + ( + U256::from_be_slice(&bytes[..32]), + U256::from_be_slice(&bytes[32..]), + ) +} + +/// ABI-encodes a single address as a 32-byte calldata word. +fn encode_address_word(addr: Address) -> String { + let mut buf = [0u8; 32]; + buf[12..].copy_from_slice(addr.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// ABI-encodes two addresses as 64 bytes of calldata. +fn encode_two_address_words(a: Address, b: Address) -> String { + let mut buf = [0u8; 64]; + buf[12..32].copy_from_slice(a.as_slice()); + buf[44..64].copy_from_slice(b.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// ABI-encodes ERC-20 `balanceOf(address)`. +fn encode_balance_of(addr: Address) -> String { + let mut buf = [0u8; 36]; + buf[..4].copy_from_slice(&[0x70, 0xa0, 0x82, 0x31]); + buf[16..].copy_from_slice(addr.as_slice()); + format!("0x{}", alloy_primitives::hex::encode(buf)) +} + +/// End-to-end `eth_simulateV1` coverage on a single post-Curie node with non-zero L1 oracle fees: +/// 1. `validation: false` runs calls in an empty envelope with no L1 fee: calls without fee fields +/// (ETH & call-mode token MorphTxs, including `traceTransfers: true`) leave FeeVault/caller +/// balances unchanged and move only `value`; an explicit gas price pays the L2 fee only; and, +/// as upstream, `value` or a gas price the caller cannot cover fails with insufficient funds. +/// 2. `validation: true` charges full placeholder-signature Curie `commit + blob` L1 + L2 fees +/// (for both ETH and token-fee MorphTxs) while keeping zero `r`/`s`/`v`/`yParity` on returned txs. +/// 3. `validation: true` with legacy `gasPrice` + `feeTokenID` on a zero-ETH caller executes as +/// a `0x7f` token-fee MorphTx rather than degrading to Legacy ETH. +#[tokio::test(flavor = "multi_thread")] +async fn eth_simulate_v1_morph_l1_fee_and_token_semantics() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + const L1_ORACLE: Address = + alloy_primitives::address!("530000000000000000000000000000000000000f"); + const FEE_VAULT: Address = + alloy_primitives::address!("530000000000000000000000000000000000000a"); + const TEST_TOKEN: Address = + alloy_primitives::address!("5300000000000000000000000000000000000022"); + const L1_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + const L1_BLOB_BASE_FEE: u64 = 10_000_000_000; // 10 gwei + // Matches `tests/assets/test-genesis.json` slots 7 & 8. + const COMMIT_SCALAR: u128 = 0x35ba5d7b55; + const BLOB_SCALAR: u128 = 0x18e38a4c; + const L1_FEE_PRECISION: u128 = 1_000_000_000; + const TRANSFER_TOPIC: &str = + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; + // Return `BALANCE(calldataload(0))` (32 bytes) / `(BALANCE(0), BALANCE(32))` (64 bytes). + const BALANCE_READER_CODE: &str = "0x6000353160005260206000f3"; + const DUAL_BALANCE_READER_CODE: &str = "0x600035316000526020353160205260406000f3"; + + let (mut nodes, wallet) = TestNodeBuilder::new() + .with_account_storage(L1_ORACLE, U256::from(1u64), U256::from(L1_BASE_FEE)) + .with_account_storage(L1_ORACLE, U256::from(6u64), U256::from(L1_BLOB_BASE_FEE)) + .build() + .await?; + let mut node = nodes.pop().unwrap(); + let chain_id = wallet.chain_id; + let funded = wallet.inner.address(); + advance_chain(1, &mut node, wallet_to_arc(wallet)).await?; + + let client = node + .rpc_client() + .ok_or_else(|| eyre::eyre!("HTTP RPC client not available"))?; + + let latest_state = node.inner.provider.latest()?; + let funded_account = latest_state + .basic_account(&funded)? + .expect("funded wallet exists"); + let initial_funded_balance = funded_account.balance; + let initial_funded_nonce = funded_account.nonce; + let initial_vault_balance = latest_state + .basic_account(&FEE_VAULT)? + .map(|a| a.balance) + .unwrap_or_default(); + + let initial_token_hex: String = client + .request( + "eth_call", + ( + serde_json::json!({ "to": TEST_TOKEN, "input": encode_balance_of(funded) }), + "latest", + ), + ) + .await?; + let initial_token_balance = decode_u256_word(&initial_token_hex); + assert!(initial_token_balance > U256::ZERO); + + let has_transfer_log = |call: &Value| { + call["logs"] + .as_array() + .expect("logs array") + .iter() + .any(|log| { + log["topics"] + .as_array() + .and_then(|t| t.first()) + .and_then(Value::as_str) + == Some(TRANSFER_TOPIC) + }) + }; + + // ------------------------------------------------------------------------- + // 1. `validation: false` charges no L1 fee for ETH & call-mode token MorphTxs + // ------------------------------------------------------------------------- + { + let reader_addr = Address::random(); + let unfunded_caller = Address::random(); + let recipient = Address::random(); + let value_recipient = Address::random(); + let transfer_value = U256::from(1_000_000_000_000_000_000u128); + let calldata = format!("0x{}", alloy_primitives::hex::encode(vec![0xaa; 128])); + + let payload = serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { "code": BALANCE_READER_CODE }, + }, + "calls": [ + // 0: omitted `from` + { "to": recipient, "input": calldata }, + // 1: zero-balance caller; the empty envelope carries no L1 fee + { "from": unfunded_caller, "to": recipient, "input": calldata }, + // 2: funded caller, value = 0 + { "from": funded, "to": recipient, "input": calldata }, + // 3-4: check funded caller & FeeVault ETH balances unchanged + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + // 5: funded caller, value = 1 ETH transfer + { "from": funded, "to": value_recipient, "value": format!("{transfer_value:#x}") }, + // 6-8: check funded, recipient, and FeeVault balances + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(value_recipient) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + // 9-10: unfunded & funded call-mode token-fee MorphTxs + { "from": unfunded_caller, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0x0", "input": calldata }, + { "from": funded, "to": recipient, "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), "feeLimit": "0xde0b6b3a7640000", "input": calldata }, + // 11-12: check funded & FeeVault token balances unchanged + { "to": TEST_TOKEN, "input": encode_balance_of(funded) }, + { "to": TEST_TOKEN, "input": encode_balance_of(FEE_VAULT) }, + ], + }], + "validation": false, + "returnFullTransactions": true, + }); + + let blocks: Value = client + .request("eth_simulateV1", (payload, "latest")) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().expect("calls array"); + assert_eq!(calls.len(), 13); + for (idx, call) in calls.iter().enumerate() { + assert_eq!(call["status"].as_str(), Some("0x1"), "call {idx}: {call}"); + } + + assert_eq!( + decode_u256_word(calls[3]["returnData"].as_str().unwrap()), + initial_funded_balance + ); + assert_eq!( + decode_u256_word(calls[4]["returnData"].as_str().unwrap()), + initial_vault_balance + ); + assert_eq!( + decode_u256_word(calls[6]["returnData"].as_str().unwrap()), + initial_funded_balance - transfer_value + ); + assert_eq!( + decode_u256_word(calls[7]["returnData"].as_str().unwrap()), + transfer_value + ); + assert_eq!( + decode_u256_word(calls[8]["returnData"].as_str().unwrap()), + initial_vault_balance + ); + assert!(calls[9]["logs"].as_array().unwrap().is_empty()); + assert!(calls[10]["logs"].as_array().unwrap().is_empty()); + assert_eq!( + decode_u256_word(calls[11]["returnData"].as_str().unwrap()), + initial_token_balance + ); + assert_eq!( + decode_u256_word(calls[12]["returnData"].as_str().unwrap()), + U256::ZERO + ); + + let txs = block["transactions"] + .as_array() + .expect("transactions array"); + assert_eq!( + txs[2]["nonce"].as_str(), + Some(format!("{initial_funded_nonce:#x}").as_str()) + ); + assert_eq!( + txs[5]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 1).as_str()) + ); + assert_eq!( + txs[10]["nonce"].as_str(), + Some(format!("{:#x}", initial_funded_nonce + 2).as_str()) + ); + + // `traceTransfers: true` with `validation: false` records only the value transfer log. + let trace_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": value_recipient, + "value": format!("{transfer_value:#x}"), + }], + }], + "traceTransfers": true, + "validation": false, + }), + "latest", + ), + ) + .await?; + let trace_call = &trace_blocks[0]["calls"][0]; + assert_eq!(trace_call["status"].as_str(), Some("0x1")); + assert_eq!(trace_call["logs"].as_array().unwrap().len(), 1); + + // An explicit gas price still pays the L2 fee (upstream keeps fee charging on with + // `validation: false`), but the empty envelope adds no L1 fee: the caller loses and the + // FeeVault gains exactly `gasUsed * gasPrice`. + let gas_price = 1_000_000_000u128; + let charged: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + reader_addr.to_string(): { "code": BALANCE_READER_CODE }, + }, + "calls": [ + { "from": funded, "to": recipient, "gasPrice": format!("{gas_price:#x}"), "input": calldata }, + { "to": reader_addr, "input": encode_address_word(funded) }, + { "to": reader_addr, "input": encode_address_word(FEE_VAULT) }, + ], + }], + "validation": false, + }), + "latest", + ), + ) + .await?; + let calls = charged[0]["calls"].as_array().expect("calls array"); + for (idx, call) in calls.iter().enumerate() { + assert_eq!(call["status"].as_str(), Some("0x1"), "call {idx}: {call}"); + } + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let l2_fee = U256::from(gas_used) * U256::from(gas_price); + assert_eq!( + decode_u256_word(calls[1]["returnData"].as_str().unwrap()), + initial_funded_balance - l2_fee + ); + assert_eq!( + decode_u256_word(calls[2]["returnData"].as_str().unwrap()), + initial_vault_balance + l2_fee + ); + + // As upstream, a `value` or gas price the caller cannot cover fails the request. + for underfunded in [ + serde_json::json!({ "from": unfunded_caller, "to": recipient, "value": "0x3e8" }), + serde_json::json!({ "from": unfunded_caller, "to": recipient, "gasPrice": format!("{gas_price:#x}"), "input": calldata }), + ] { + let err = client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ "calls": [underfunded] }], + "validation": false, + }), + "latest", + ), + ) + .await + .expect_err("an unaffordable value or gas price must fail"); + let err_str = err.to_string(); + assert!( + err_str.contains("insufficient funds") || err_str.contains("-38014"), + "unexpected error: {err_str}" + ); + } + + // `validation: false` disables the base-fee check, so a non-zero `baseFeePerGas` block + // override must not reject a zero-fee MorphTx either. + let override_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "blockOverrides": { "baseFeePerGas": "0x3b9aca00" }, + "calls": [{ + "from": unfunded_caller, + "to": recipient, + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": "0x0", + "input": calldata, + }], + }], + "validation": false, + }), + "latest", + ), + ) + .await?; + assert_eq!( + override_blocks[0]["calls"][0]["status"].as_str(), + Some("0x1"), + "baseFeePerGas override must not reject zero-fee MorphTx under validation:false: {override_blocks}" + ); + } + + // ------------------------------------------------------------------------- + // 2. `validation: true` charges full placeholder-sig Curie L1 + L2 fees + // ------------------------------------------------------------------------- + { + let sender = Address::random(); + let recipient = Address::random(); + let reader_addr = Address::random(); + let calldata = Bytes::from(vec![0xab; 1024]); + let gas_limit = 50_000u64; + let max_fee_per_gas = 2_000_000_000u128; + let max_priority_fee_per_gas = 1_000_000_000u128; + + let zero_sig = alloy_primitives::Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = alloy_primitives::Signature::new(U256::MAX, U256::MAX, true); + let tx_inner = alloy_consensus::TxEip1559 { + chain_id, + nonce: 0, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to: TxKind::Call(recipient), + value: U256::ZERO, + access_list: Default::default(), + input: calldata.clone(), + }; + let zero_sig_len = MorphTxEnvelope::Eip1559(tx_inner.clone().into_signed(zero_sig)) + .encoded_2718() + .len() as u128; + let encoded_len = MorphTxEnvelope::Eip1559(tx_inner.into_signed(placeholder_sig)) + .encoded_2718() + .len() as u128; + assert_eq!(encoded_len, zero_sig_len + 64); + + let commit_only_l1_fee = + U256::from((COMMIT_SCALAR * u128::from(L1_BASE_FEE)) / L1_FEE_PRECISION); + let zero_sig_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * zero_sig_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + let full_l1_fee = U256::from( + (COMMIT_SCALAR * u128::from(L1_BASE_FEE) + + BLOB_SCALAR * encoded_len * u128::from(L1_BLOB_BASE_FEE)) + / L1_FEE_PRECISION, + ); + let l2_max_fee = U256::from(gas_limit) * U256::from(max_fee_per_gas); + let tx_call = serde_json::json!({ + "from": sender, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": calldata.to_string(), + }); + + // Balance omitting the 64B placeholder signature L1 fee must fail. + let err = client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { "balance": format!("{:#x}", l2_max_fee + zero_sig_l1_fee) }, + }, + "calls": [tx_call], + }], + "validation": true, + }), + "latest", + ), + ) + .await + .expect_err("balance omitting 64B placeholder signature L1 fee must fail"); + let err_str = err.to_string(); + assert!(err_str.contains("insufficient funds") || err_str.contains("-38014")); + + // Exact `l2_max_fee + full_l1_fee` succeeds, debits exact fees, and keeps zero r/s/v. + let exact_budget = l2_max_fee + full_l1_fee; + let blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { + sender.to_string(): { "balance": format!("{exact_budget:#x}") }, + reader_addr.to_string(): { "code": DUAL_BALANCE_READER_CODE }, + }, + "calls": [ + tx_call, + { + "from": funded, + "to": reader_addr, + "gas": "0x186a0", + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "input": encode_two_address_words(sender, FEE_VAULT), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }), + "latest", + ), + ) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().unwrap(); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let txs = block["transactions"].as_array().unwrap(); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + + let block_base_fee = u128::from_str_radix( + block["baseFeePerGas"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let gas_used = u64::from_str_radix( + calls[0]["gasUsed"] + .as_str() + .unwrap() + .trim_start_matches("0x"), + 16, + )?; + let effective_gas_price = max_fee_per_gas.min(block_base_fee + max_priority_fee_per_gas); + let expected_total_fee = + U256::from(gas_used) * U256::from(effective_gas_price) + full_l1_fee; + + let (sender_after, vault_after) = + decode_two_u256_words(calls[1]["returnData"].as_str().unwrap()); + assert_eq!(sender_after, exact_budget - expected_total_fee); + assert_eq!(vault_after, initial_vault_balance + expected_total_fee); + + // Token-fee MorphTx under `validation: true`: tight `feeLimit` fails, generous succeeds. + let token_tight_limit = U256::from(gas_limit) * U256::from(effective_gas_price) + + commit_only_l1_fee + + (full_l1_fee - commit_only_l1_fee) / U256::from(2u64); + client + .request::( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{token_tight_limit:#x}"), + "input": calldata.to_string(), + }], + }], + "validation": true, + }), + "latest", + ), + ) + .await + .expect_err("token-fee MorphTx must fail when feeLimit omits Curie blob L1 fee"); + + let morph_blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "calls": [{ + "from": funded, + "to": recipient, + "gas": format!("{gas_limit:#x}"), + "maxFeePerGas": format!("{max_fee_per_gas:#x}"), + "maxPriorityFeePerGas": format!("{max_priority_fee_per_gas:#x}"), + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "feeLimit": format!("{:#x}", l2_max_fee + full_l1_fee * U256::from(2u64)), + "input": calldata.to_string(), + }], + }], + "validation": true, + }), + "latest", + ), + ) + .await?; + let morph_call = &morph_blocks[0]["calls"][0]; + assert_eq!(morph_call["status"].as_str(), Some("0x1")); + assert!(has_transfer_log(morph_call)); + } + + // ------------------------------------------------------------------------- + // 3. `validation: true` with legacy `gasPrice` + `feeTokenID` executes MorphTx + // ------------------------------------------------------------------------- + { + let recipient = Address::random(); + let calldata = Bytes::from(vec![0xcd; 128]); + let blocks: Value = client + .request( + "eth_simulateV1", + ( + serde_json::json!({ + "blockStateCalls": [{ + "stateOverrides": { funded.to_string(): { "balance": "0x0" } }, + "calls": [ + { + "from": funded, + "to": recipient, + "gas": "0xc350", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": calldata.to_string(), + }, + { + "from": funded, + "to": TEST_TOKEN, + "gas": "0x186a0", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + "input": encode_balance_of(funded), + }, + ], + }], + "validation": true, + "returnFullTransactions": true, + }), + "latest", + ), + ) + .await?; + let block = &blocks[0]; + let calls = block["calls"].as_array().unwrap(); + assert_eq!(calls[0]["status"].as_str(), Some("0x1")); + assert_eq!(calls[1]["status"].as_str(), Some("0x1")); + + let txs = block["transactions"].as_array().unwrap(); + assert_eq!(txs[0]["type"].as_str(), Some("0x7f")); + assert_eq!(txs[0]["feeTokenID"].as_str(), Some("0x1")); + assert_eq!(txs[0]["r"].as_str(), Some("0x0")); + assert_eq!(txs[0]["s"].as_str(), Some("0x0")); + assert_eq!(txs[0]["v"].as_str(), Some("0x0")); + assert_eq!(txs[0]["yParity"].as_str(), Some("0x0")); + assert!(has_transfer_log(&calls[0])); + assert!(decode_u256_word(calls[1]["returnData"].as_str().unwrap()) < initial_token_balance); + } + + // ------------------------------------------------------------------------- + // 4. `eth_fillTransaction` keeps geth's `toTransaction` rule: legacy `gasPrice` builds a + // legacy transaction even with `feeTokenID`, so the simulate-only normalization above + // must not reach it. + // ------------------------------------------------------------------------- + { + let filled: Value = client + .request( + "eth_fillTransaction", + (serde_json::json!({ + "from": funded, + "to": Address::random(), + "gas": "0x5208", + "gasPrice": "0x77359400", + "feeTokenID": format!("{TEST_TOKEN_ID:#x}"), + }),), + ) + .await?; + let tx = &filled["tx"]; + assert!( + matches!(tx["type"].as_str(), Some("0x0") | None), + "legacy gasPrice must fill a legacy transaction: {filled}" + ); + assert!(tx.get("feeTokenID").is_none_or(Value::is_null), "{filled}"); + } + + Ok(()) +} diff --git a/crates/revm/src/handler.rs b/crates/revm/src/handler.rs index 4a701649..7770f638 100644 --- a/crates/revm/src/handler.rs +++ b/crates/revm/src/handler.rs @@ -234,6 +234,14 @@ where evm: &mut Self::Evm, exec_result: &mut <::Frame as FrameTr>::FrameResult, ) -> Result<(), Self::Error> { + // Mirror upstream `revm_handler::post_execution::reward_beneficiary`: + // when fee charging is disabled (e.g. `eth_call`, `eth_estimateGas`, + // `debug_traceCall`), the caller was never charged for gas or L1 data + // fees so no reward may be credited to the beneficiary / FeeVault. + if evm.ctx_ref().cfg().is_fee_charge_disabled() { + return Ok(()); + } + // Reuse the L1 data fee cached during validate_and_deduct_eth_fee / // validate_and_deduct_token_fee, avoiding a redundant calculate_tx_l1_cost call. // Read before ctx().all_mut() borrows evm. @@ -281,7 +289,8 @@ where // does not enforce EIP-1559 fee-cap rules. Those rules are independent // of which asset ultimately pays the fee, matching Morph geth's preCheck. if evm.ctx_ref().tx().is_morph_tx() && !evm.ctx_ref().cfg().is_fee_charge_disabled() { - let base_fee = Some(evm.ctx_ref().block().basefee() as u128); + let base_fee = (!evm.ctx_ref().cfg().is_base_fee_check_disabled()) + .then_some(evm.ctx_ref().block().basefee() as u128); validation::validate_priority_fee_tx( evm.ctx_ref().tx().max_fee_per_gas(), evm.ctx_ref() @@ -443,24 +452,29 @@ where &self, evm: &mut MorphEvm, ) -> Result<(), EVMError> { - let hardfork = *evm.ctx_ref().cfg().spec(); - - // Fetch L1 block info from the L1 Gas Price Oracle contract per-tx. - // Must NOT use a per-block cache because the oracle can be updated by a - // regular transaction (from the external gas-oracle service) within the - // same block. Subsequent user txs must see the updated fee parameters, - // matching go-ethereum's per-tx L1BlockInfo read. - let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().db_mut(), hardfork)?; - - let rlp_bytes = evm - .ctx_ref() - .tx() - .rlp_bytes - .as_ref() - .map(|b| b.as_ref()) - .unwrap_or_default(); - - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork); + let is_fee_charge_disabled = evm.ctx_ref().cfg().is_fee_charge_disabled(); + let l1_data_fee = if is_fee_charge_disabled || is_unencoded_rpc_simulation(evm) { + U256::ZERO + } else { + let hardfork = *evm.ctx_ref().cfg().spec(); + + // Fetch L1 block info from the L1 Gas Price Oracle contract per-tx. + // Must NOT use a per-block cache because the oracle can be updated by a + // regular transaction (from the external gas-oracle service) within the + // same block. Subsequent user txs must see the updated fee parameters, + // matching go-ethereum's per-tx L1BlockInfo read. + let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().db_mut(), hardfork)?; + + let rlp_bytes = evm + .ctx_ref() + .tx() + .rlp_bytes + .as_ref() + .map(|b| b.as_ref()) + .unwrap_or_default(); + + l1_block_info.calculate_tx_l1_cost(rlp_bytes, hardfork) + }; evm.cached_l1_data_fee = l1_data_fee; let (block, tx, cfg, journal, _, _) = evm.ctx().all_mut(); @@ -675,8 +689,13 @@ where // Get RLP-encoded transaction bytes for L1 fee calculation // Fetch L1 block info per-tx (same rationale as validate_and_deduct_eth_fee). - let l1_block_info = L1BlockInfo::try_fetch(evm.ctx_mut().journal_mut().db_mut(), hardfork)?; - let l1_data_fee = l1_block_info.calculate_tx_l1_cost(rlp_bytes.as_ref(), hardfork); + let l1_data_fee = if is_unencoded_rpc_simulation(evm) { + U256::ZERO + } else { + let l1_block_info = + L1BlockInfo::try_fetch(evm.ctx_mut().journal_mut().db_mut(), hardfork)?; + l1_block_info.calculate_tx_l1_cost(rlp_bytes.as_ref(), hardfork) + }; // Calculate L2 gas fee using effective_gas_price (= min(gasTipCap + baseFee, gasFeeCap)), // matching go-ethereum's buyAltTokenGas() which uses st.gasPrice (effective gas price). @@ -807,6 +826,31 @@ where } } +/// Whether the transaction is an RPC simulation of an unsigned call that carries no encoding. +/// +/// Upstream `eth_simulateV1` executes each call in an empty `WithEncoded` envelope and treats +/// that as carrying no L1 cost on an L2 (`simulate::execute_transactions`). Morph's post-Curie +/// formula still charges a commit fee for zero bytes, so such calls are priced at zero L1 fee +/// here. `MorphBlockExecutor` gives `validation: true` simulations a placeholder-signature +/// encoding, so only `validation: false` simulations reach the handler unencoded. +/// +/// EIP-3607 is never disabled during consensus execution, where every transaction carries its +/// signed encoding, so a missing encoding there is still priced by the formula instead of +/// silently becoming free. +#[inline] +fn is_unencoded_rpc_simulation(evm: &MorphEvm) -> bool +where + DB: alloy_evm::Database, +{ + evm.ctx_ref().cfg().is_eip3607_disabled() + && evm + .ctx_ref() + .tx() + .rlp_bytes + .as_ref() + .is_none_or(|bytes| bytes.is_empty()) +} + /// Execute `f` within a journal checkpoint. Commits on `Ok`, reverts on `Err`. #[inline] fn with_journal_checkpoint( @@ -1685,6 +1729,48 @@ mod tests { )); } + #[test] + fn validate_env_skips_morph_tx_base_fee_check_when_disabled() { + let mut evm = MorphEvm::new( + MorphContext::new(CacheDB::new(EmptyDB::default()), MorphHardfork::default()), + NoOpInspector, + ); + evm.cfg.disable_base_fee = true; + evm.block = MorphBlockEnv { + inner: BlockEnv { + basefee: 100, + ..Default::default() + }, + }; + evm.tx = MorphTxEnv { + inner: TxEnv { + tx_type: MORPH_TX_TYPE_ID, + gas_limit: 21_000, + gas_price: 0, + gas_priority_fee: Some(0), + kind: TxKind::Call(Address::ZERO), + ..Default::default() + }, + fee_token_id: Some(1), + ..Default::default() + }; + + as Handler>::validate_env(&MorphEvmHandler::default(), &mut evm) + .expect("disable_base_fee must exempt MorphTx from basefee floor"); + + // Priority fee > max fee is still rejected when disable_priority_fee_check is false. + evm.tx.inner.gas_priority_fee = Some(1); + let err = + as Handler>::validate_env(&MorphEvmHandler::default(), &mut evm) + .unwrap_err(); + assert!(matches!( + err, + EVMError::Transaction(MorphInvalidTransaction::EthInvalidTransaction( + InvalidTransaction::PriorityFeeGreaterThanMaxFee + )) + )); + } + // ========================================================================= // MorphTx V2 (EIP-7702 authorization list) handler rules // ========================================================================= @@ -2483,6 +2569,170 @@ mod tests { assert_eq!(new_balance, balance); } + /// Post-Curie simulation (`disable_fee_charge = true`) must credit 0 ETH to + /// the beneficiary / FeeVault even when L1 oracle fees and gas price are + /// non-zero, and must not touch the beneficiary account in the state diff. + #[test] + fn disable_fee_charge_credits_zero_eth_to_beneficiary_post_curie() { + use crate::l1block::{ + GPO_BLOB_SCALAR_SLOT, GPO_COMMIT_SCALAR_SLOT, GPO_IS_CURIE_SLOT, GPO_L1_BASE_FEE_SLOT, + GPO_L1_BLOB_BASE_FEE_SLOT, L1_GAS_PRICE_ORACLE_ADDRESS, + }; + + let caller = address!("1000000000000000000000000000000000000011"); + let recipient = address!("2000000000000000000000000000000000000022"); + let fee_vault = address!("530000000000000000000000000000000000000a"); + let initial_caller_balance = U256::from(10_000_000_000_000_000u128); + let initial_vault_balance = U256::from(1_000u64); + let transfer_value = U256::from(123_456u64); + let gas_price = 2_000_000_000u128; // 2 gwei + let rlp_bytes = Bytes::from(vec![0xab; 256]); + + let build_db = || { + let mut db = CacheDB::new(EmptyDB::default()); + db.insert_account_info( + caller, + AccountInfo { + balance: initial_caller_balance, + ..Default::default() + }, + ); + db.insert_account_info( + fee_vault, + AccountInfo { + balance: initial_vault_balance, + ..Default::default() + }, + ); + db.insert_account_info(L1_GAS_PRICE_ORACLE_ADDRESS, AccountInfo::default()); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_L1_BASE_FEE_SLOT, + U256::from(10_000_000_000u64), // 10 gwei + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_L1_BLOB_BASE_FEE_SLOT, + U256::from(5_000_000_000u64), // 5 gwei + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_COMMIT_SCALAR_SLOT, + U256::from(230_760_020_821u64), + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_BLOB_SCALAR_SLOT, + U256::from(417_565_260u64), + ) + .unwrap(); + db.insert_account_storage( + L1_GAS_PRICE_ORACLE_ADDRESS, + GPO_IS_CURIE_SLOT, + U256::from(1u64), + ) + .unwrap(); + db + }; + + let make_tx = |value: U256| MorphTxEnv { + inner: TxEnv { + caller, + kind: TxKind::Call(recipient), + gas_limit: 50_000, + gas_price, + gas_priority_fee: Some(gas_price), + value, + data: Bytes::from(vec![0xaa; 64]), + ..Default::default() + }, + rlp_bytes: Some(rlp_bytes.clone()), + ..Default::default() + }; + + // 1. With `disable_fee_charge = true`: beneficiary receives 0 ETH (and is not even + // touched in the returned state diff), caller only pays `value`, and cached L1 fee is 0. + let mut sim_evm = MorphEvm::new( + MorphContext::new(build_db(), MorphHardfork::Celadon), + NoOpInspector, + ); + sim_evm.block.inner.beneficiary = fee_vault; + sim_evm.block.inner.basefee = 1_000_000; + sim_evm.cfg.disable_fee_charge = true; + + let sim_res = sim_evm.transact(make_tx(transfer_value)).unwrap(); + assert!(sim_res.result.is_success()); + assert_eq!(sim_evm.cached_l1_data_fee(), U256::ZERO); + assert!( + !sim_res.state.contains_key(&fee_vault), + "FeeVault must not be credited or touched when disable_fee_charge is true" + ); + assert_eq!( + sim_res.state.get(&caller).unwrap().info.balance, + initial_caller_balance - transfer_value, + "caller must only pay tx.value, not L1 or L2 fees" + ); + assert_eq!( + sim_res.state.get(&recipient).unwrap().info.balance, + transfer_value + ); + + // 2. Direct `reward_beneficiary` guard: even if `cached_l1_data_fee` were populated + // directly, `reward_beneficiary` must still skip crediting FeeVault when + // `disable_fee_charge = true`. + let mut direct_evm = MorphEvm::new( + MorphContext::new(build_db(), MorphHardfork::Celadon), + NoOpInspector, + ); + direct_evm.block.inner.beneficiary = fee_vault; + direct_evm.block.inner.basefee = 1_000_000; + direct_evm.cfg.disable_fee_charge = true; + direct_evm.tx = make_tx(U256::ZERO); + direct_evm.cached_l1_data_fee = U256::from(999_999u64); + let mut frame_result = revm::handler::FrameResult::Call(revm::interpreter::CallOutcome { + result: revm::interpreter::InterpreterResult::new( + revm::interpreter::InstructionResult::Stop, + Bytes::new(), + Gas::new(21_000), + ), + memory_offset: 0..0, + was_precompile_called: false, + precompile_call_logs: Vec::new(), + charged_new_account_state_gas: false, + }); + as Handler>::reward_beneficiary( + &MorphEvmHandler::default(), + &mut direct_evm, + &mut frame_result, + ) + .unwrap(); + assert!( + !direct_evm.ctx.journal_mut().state.contains_key(&fee_vault), + "reward_beneficiary must return early without crediting beneficiary when fee charge is disabled" + ); + + // 3. Sanity contrast: with `disable_fee_charge = false`, FeeVault receives exact + // `execution_fee + l1_data_fee`. + let mut real_evm = MorphEvm::new( + MorphContext::new(build_db(), MorphHardfork::Celadon), + NoOpInspector, + ); + real_evm.block.inner.beneficiary = fee_vault; + real_evm.block.inner.basefee = 1_000_000; + let real_res = real_evm.transact(make_tx(transfer_value)).unwrap(); + assert!(real_res.result.is_success()); + let expected_l1_fee = real_evm.cached_l1_data_fee(); + assert!(expected_l1_fee > U256::ZERO); + let expected_exec_fee = U256::from(gas_price) * U256::from(real_res.result.tx_gas_used()); + assert_eq!( + real_res.state.get(&fee_vault).unwrap().info.balance, + initial_vault_balance + expected_exec_fee + expected_l1_fee + ); + } + #[test] fn validate_and_deduct_token_fee_rejects_unregistered_token_in_simulation() { let caller = address!("1000000000000000000000000000000000000001"); diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index 5e420dda..f4661fb6 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -76,4 +76,4 @@ pub use token_fee::{ L2_TOKEN_REGISTRY_ADDRESS, MorphEvmEnv, TokenFeeInfo, TokenRegistryEntry, compute_mapping_slot, compute_mapping_slot_for_address, encode_balance_of_calldata, }; -pub use tx::{MorphTxEnv, MorphTxExt}; +pub use tx::{MorphTxEnv, MorphTxExt, encode_simulated_tx_for_l1_fee}; diff --git a/crates/revm/src/tx.rs b/crates/revm/src/tx.rs index f5541be0..222f4947 100644 --- a/crates/revm/src/tx.rs +++ b/crates/revm/src/tx.rs @@ -3,7 +3,7 @@ //! This module defines the Morph-specific transaction environment with token fee support. use alloy_consensus::{ - EthereumTxEnvelope, SignableTransaction, Transaction as AlloyTransaction, TxEip4844, + EthereumTxEnvelope, SignableTransaction, Signed, Transaction as AlloyTransaction, TxEip4844, }; use alloy_eips::eip2718::Encodable2718; use alloy_eips::eip2930::AccessList; @@ -23,6 +23,52 @@ use std::ops::{Deref, DerefMut}; /// Re-export Either for authorization list use alloy_consensus::transaction::Either; +/// Encodes a simulated transaction with a full-size placeholder signature for L1 +/// data fee sizing, without mutating the transaction itself. +/// +/// `TryIntoSimTx` attaches `Signature::new(U256::ZERO, U256::ZERO, false)` (3 RLP +/// bytes instead of 67 bytes) so `returnFullTransactions: true` exposes zero +/// `r`/`s`/`v` per the Ethereum `eth_simulateV1` spec. Using the same 64-byte +/// `0xff` + `yParity = 1` placeholder as [`MorphTxEnv::encode_for_l1_fee`] sizes the +/// L1 fee like a real signed transaction while keeping `tx`'s zero signature intact. +/// +/// The envelope type is kept as simulated, so a legacy or EIP-2930 call is priced as +/// that type. `eth_estimateGas` instead always sizes an EIP-1559, EIP-7702 or MorphTx +/// envelope (as geth does once a base fee exists), so for those two types the L1 fees +/// differ by the few bytes between the encodings. +pub fn encode_simulated_tx_for_l1_fee(tx: &MorphTxEnvelope) -> Bytes { + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let envelope = match tx { + MorphTxEnvelope::Legacy(s) => MorphTxEnvelope::Legacy(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip2930(s) => MorphTxEnvelope::Eip2930(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip1559(s) => MorphTxEnvelope::Eip1559(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Eip7702(s) => MorphTxEnvelope::Eip7702(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::Morph(s) => MorphTxEnvelope::Morph(Signed::new_unchecked( + s.tx().clone(), + placeholder_sig, + B256::ZERO, + )), + MorphTxEnvelope::L1Msg(_) => return tx.encoded_2718().into(), + }; + envelope.encoded_2718().into() +} + /// Morph transaction environment with token fee support. /// /// This wraps the standard [`TxEnv`] and adds Morph-specific fields for: @@ -1085,4 +1131,174 @@ mod tests { other => panic!("expected a recovered authorization, got {other:?}"), } } + + #[test] + fn encode_simulated_tx_for_l1_fee_uses_full_placeholder_sig_without_mutating_tx() { + use alloy_consensus::{TxEip1559, TxEip2930, TxEip7702, TxLegacy}; + use alloy_eips::{ + eip2718::Decodable2718, + eip7702::{Authorization, SignedAuthorization}, + }; + use alloy_primitives::{Sealed, address}; + use morph_primitives::TxL1Msg; + + let chain_id = 2818u64; + let signer = address!("0000000000000000000000000000000000000001"); + let to = address!("0000000000000000000000000000000000000002"); + let input = Bytes::from(vec![0xab; 64]); + let zero_sig = Signature::new(U256::ZERO, U256::ZERO, false); + let placeholder_sig = Signature::new(U256::MAX, U256::MAX, true); + let auth: SignedAuthorization = Authorization { + chain_id: U256::from(chain_id), + address: address!("0000000000000000000000000000000000000042"), + nonce: 1, + } + .into_signed(Signature::new(U256::from(1u64), U256::from(2u64), true)); + let sig_of = |env: &MorphTxEnvelope| match env { + MorphTxEnvelope::Legacy(s) => Some(*s.signature()), + MorphTxEnvelope::Eip2930(s) => Some(*s.signature()), + MorphTxEnvelope::Eip1559(s) => Some(*s.signature()), + MorphTxEnvelope::Eip7702(s) => Some(*s.signature()), + MorphTxEnvelope::Morph(s) => Some(*s.signature()), + MorphTxEnvelope::L1Msg(_) => None, + }; + + let cases = [ + ( + "legacy", + MorphTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(chain_id), + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip2930", + MorphTxEnvelope::Eip2930(Signed::new_unchecked( + TxEip2930 { + chain_id, + gas_price: 2_000_000_000, + gas_limit: 50_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "eip1559", + MorphTxEnvelope::Eip1559(Signed::new_unchecked( + TxEip1559 { + chain_id, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "eip7702", + MorphTxEnvelope::Eip7702(Signed::new_unchecked( + TxEip7702 { + chain_id, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to, + authorization_list: vec![auth.clone()], + input: input.clone(), + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ( + "morph_v1", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + gas_limit: 50_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + fee_token_id: 1, + fee_limit: U256::from(10_000u64), + version: MORPH_TX_VERSION_1, + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + true, + ), + ( + "morph_v2", + MorphTxEnvelope::Morph(Signed::new_unchecked( + TxMorph { + chain_id, + gas_limit: 80_000, + max_fee_per_gas: 2_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Call(to), + input: input.clone(), + fee_token_id: 1, + version: MORPH_TX_VERSION_2, + authorization_list: vec![auth], + ..Default::default() + }, + zero_sig, + B256::ZERO, + )), + false, + ), + ]; + + for (label, tx, compare_tx_env) in cases { + let sized = encode_simulated_tx_for_l1_fee(&tx); + assert_eq!(sized.len(), tx.encoded_2718().len() + 64, "{label}"); + let decoded = MorphTxEnvelope::decode_2718(&mut sized.as_ref()).unwrap(); + assert_eq!(sig_of(&decoded), Some(placeholder_sig), "{label}"); + assert_eq!(sig_of(&tx), Some(zero_sig), "{label}"); + if compare_tx_env { + let env_encoded = + MorphTxEnv::from_recovered_tx(&tx, signer).encode_for_l1_fee(chain_id); + assert_eq!(sized, env_encoded, "{label}"); + } + } + + let l1_msg = MorphTxEnvelope::L1Msg(Sealed::new_unchecked( + TxL1Msg { + queue_index: 1, + gas_limit: 50_000, + to, + input, + ..Default::default() + }, + B256::ZERO, + )); + assert_eq!( + encode_simulated_tx_for_l1_fee(&l1_msg), + Bytes::from(l1_msg.encoded_2718()) + ); + } } diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 4f880141..31fab25d 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -42,7 +42,7 @@ reth-transaction-pool.workspace = true # Alloy alloy-consensus.workspace = true -alloy-evm.workspace = true +alloy-evm = { workspace = true, features = ["call-util"] } alloy-primitives.workspace = true alloy-rpc-types-debug.workspace = true alloy-rpc-types-eth.workspace = true diff --git a/crates/rpc/src/eth/call.rs b/crates/rpc/src/eth/call.rs index b1141e31..36ec5e4a 100644 --- a/crates/rpc/src/eth/call.rs +++ b/crates/rpc/src/eth/call.rs @@ -1,25 +1,32 @@ -//! Morph `eth_call` / `eth_estimateGas` overrides. +//! Morph `eth_call` / `eth_estimateGas` / `eth_simulateV1` overrides. //! -//! [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps -//! gas by `balance − value − l1_fee` (ETH path) or a token-denominated limit -//! (MorphTx `fee_token_id > 0`, see `token_gas_allowance`). `eth_call` and -//! `eth_createAccessList` are detected via `cfg_env.disable_block_gas_limit = true` and fall -//! through to the upstream allowance without the L1-fee extension, except -//! that fee-token callers are left uncapped for the handler. - -use crate::MorphEthApiError; -use crate::eth::{MorphEthApi, MorphNodeCore}; +//! - [`Call::caller_gas_allowance`] is overridden so `eth_estimateGas` caps +//! gas by `balance − value − l1_fee` (ETH path) or a token-denominated limit +//! (MorphTx `fee_token_id > 0`, see `token_gas_allowance`). `eth_call` and +//! `eth_createAccessList` are detected via `cfg_env.disable_block_gas_limit = true` and fall +//! through to the upstream allowance without the L1-fee extension, except +//! that fee-token callers are left uncapped for the handler. +//! - [`EthCall::simulate_v1`] normalizes calls that combine Morph fields with +//! legacy `gasPrice` and delegates execution to the inner upstream +//! [`EthCall::simulate_v1`]; Morph L1 fee pricing is handled in +//! [`morph_evm::MorphBlockExecutor`] (`validation: true` placeholder encoding) +//! and `morph_revm` (`validation: false` empty envelope priced at zero L1 fee). + +use crate::eth::{MorphEthApi, MorphNodeCore, transaction::normalize_simulate_call}; +use crate::{MorphEthApiError, MorphTransactionRequest}; use alloy_evm::call::{CallError, caller_gas_allowance as upstream_caller_gas_allowance}; use alloy_primitives::U256; +use alloy_rpc_types_eth::{BlockId, simulate::SimulatePayload}; use morph_chainspec::{MorphChainSpec, MorphHardforks}; use morph_revm::{L1BlockInfo, MorphTxExt, TokenFeeInfo}; use reth_evm::{EvmEnvFor, TxEnvFor}; use reth_provider::ChainSpecProvider; +use reth_rpc_convert::{RpcConvert, RpcTxReq}; use reth_rpc_eth_api::{ - EthApiTypes, RpcNodeCore, - helpers::{Call, EthCall, estimate::EstimateCall}, + EthApiTypes, RpcNodeCore, RpcTypes, + helpers::{Call, EthCall, call::SimulatedBlocksResult, estimate::EstimateCall}, }; -use reth_rpc_eth_types::EthApiError; +use reth_rpc_eth_types::{EthApiError, error::FromEthApiError, simulate::EthSimulateError}; use revm::{Database, context::Transaction as RevmTransaction}; impl EthCall for MorphEthApi @@ -28,8 +35,29 @@ where N::Provider: ChainSpecProvider, Rpc: reth_rpc_convert::RpcConvert, + Rpc::Network: RpcTypes, MorphEthApiError: reth_rpc_eth_types::error::FromEvmError, { + async fn simulate_v1( + &self, + mut payload: SimulatePayload::Network>>, + block: Option, + ) -> SimulatedBlocksResult { + if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { + return Err(EthApiError::other(EthSimulateError::TooManyBlocks).into()); + } + for sim_block in &mut payload.block_state_calls { + sim_block.calls = std::mem::take(&mut sim_block.calls) + .into_iter() + .map(normalize_simulate_call) + .collect::, _>>() + .map_err(Self::Error::from_eth_err)?; + } + self.eth_api() + .simulate_v1(payload, block) + .await + .map_err(Into::into) + } } impl EstimateCall for MorphEthApi diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index d3d0339a..db394af7 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -53,6 +53,38 @@ impl TryIntoSimTx for MorphTransactionRequest { } } +/// Normalizes one `eth_simulateV1` call before upstream resolves its defaults. +/// +/// geth's `ToMessage` keeps the Morph fields (`feeTokenID`, `reference`, `memo`) of a request +/// that uses legacy `gasPrice` and maps `gasPrice` onto both EIP-1559 fee caps, so a simulated +/// call is priced as the same MorphTx `eth_call` would execute. `TryIntoSimTx` cannot do this +/// itself: it also builds the transaction returned by `eth_fillTransaction`, which must keep +/// geth's `toTransaction` rule that legacy `gasPrice` produces a legacy transaction. Running +/// before upstream's `resolve_transaction` also means only fee fields the caller actually set +/// count as a conflict, not the zero defaults it fills in. +pub(crate) fn normalize_simulate_call( + mut request: MorphTransactionRequest, +) -> Result { + let Some(gas_price) = request.inner.gas_price else { + return Ok(request); + }; + let has_morph_fields = request.fee_token_id.is_some_and(|id| id.to::() > 0) + || is_nonzero_reference(normalize_reference(request.reference).as_ref()) + || request.memo.as_ref().is_some_and(|memo| !memo.is_empty()); + if !has_morph_fields { + return Ok(request); + } + if request.inner.max_fee_per_gas.is_some() || request.inner.max_priority_fee_per_gas.is_some() { + return Err(EthApiError::InvalidParams( + "both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified".to_string(), + )); + } + request.inner.gas_price = None; + request.inner.max_fee_per_gas = Some(gas_price); + request.inner.max_priority_fee_per_gas = Some(gas_price); + Ok(request) +} + /// Builds and signs a transaction from an RPC request. /// /// Supports both standard Ethereum transactions and Morph fee token transactions. @@ -1560,4 +1592,107 @@ mod tests { // = 500_000_000 + 1_000_000_000 = 1_500_000_000 assert_eq!(rpc_tx.effective_gas_price, Some(1_500_000_000)); } + + #[test] + fn simulate_call_normalization_keeps_morph_fields_with_legacy_gas_price() { + let base_inner = || TransactionRequest { + chain_id: Some(2818), + nonce: Some(3), + gas: Some(50_000), + gas_price: Some(2_000_000_000), + to: Some(TxKind::Call(address!( + "0000000000000000000000000000000000000002" + ))), + ..Default::default() + }; + let morph_req = || MorphTransactionRequest { + inner: base_inner(), + fee_token_id: Some(U64::from(1)), + fee_limit: Some(U256::from(1234)), + reference: Some(B256::repeat_byte(0xab)), + memo: Some(Bytes::from_static(b"sim")), + }; + + // `eth_simulateV1`: `feeTokenID`, `reference`, or `memo` with legacy `gasPrice` builds + // TxMorph with `max_fee_per_gas == max_priority_fee_per_gas == gasPrice`. + let normalized = normalize_simulate_call(morph_req()).expect("no fee conflict"); + assert_eq!(normalized.inner.gas_price, None); + match normalized + .try_into_sim_tx() + .expect("normalized call must build TxMorph") + { + MorphTxEnvelope::Morph(signed) => { + assert_eq!(signed.tx().fee_token_id, 1); + assert_eq!(signed.tx().fee_limit, U256::from(1234)); + assert_eq!(signed.tx().reference, Some(B256::repeat_byte(0xab))); + assert_eq!(signed.tx().memo, Some(Bytes::from_static(b"sim"))); + assert_eq!(signed.tx().max_fee_per_gas, 2_000_000_000); + assert_eq!(signed.tx().max_priority_fee_per_gas, 2_000_000_000); + } + other => panic!("expected MorphTx, got {other:?}"), + } + + // `eth_fillTransaction` converts the raw request: legacy `gasPrice` keeps building a + // legacy transaction, as geth's `toTransaction` does. + assert!(matches!( + morph_req().try_into_sim_tx().unwrap(), + MorphTxEnvelope::Legacy(_) + )); + + // Without Morph fields, normalization leaves legacy `gasPrice` untouched. + let legacy_req = MorphTransactionRequest { + inner: base_inner(), + fee_token_id: None, + fee_limit: None, + reference: None, + memo: None, + }; + let legacy_req = normalize_simulate_call(legacy_req).unwrap(); + assert_eq!(legacy_req.inner.gas_price, Some(2_000_000_000)); + assert!(matches!( + legacy_req.try_into_sim_tx().unwrap(), + MorphTxEnvelope::Legacy(_) + )); + + // `gasPrice` plus an explicit EIP-1559 fee field on a MorphTx is a conflict. + let mut conflicting = morph_req(); + conflicting.inner.max_fee_per_gas = Some(3_000_000_000); + assert!(matches!( + normalize_simulate_call(conflicting), + Err(EthApiError::InvalidParams(_)) + )); + } + + #[test] + fn simulate_call_normalization_accepts_legacy_gas_price_with_authorization_list() { + // Upstream `resolve_transaction` later fills unset EIP-1559 fields with zero for a + // 7702-shaped request; normalizing first must not mistake those for caller input. + let request = MorphTransactionRequest { + inner: TransactionRequest { + chain_id: Some(2818), + nonce: Some(0), + gas: Some(100_000), + gas_price: Some(1_000_000), + to: Some(TxKind::Call(address!( + "0000000000000000000000000000000000000002" + ))), + authorization_list: Some(vec![sample_signed_authorization()]), + ..Default::default() + }, + fee_token_id: Some(U64::from(1)), + fee_limit: None, + reference: None, + memo: None, + }; + let normalized = normalize_simulate_call(request).expect("only gasPrice was set"); + assert_eq!(normalized.inner.max_fee_per_gas, Some(1_000_000)); + assert_eq!(normalized.inner.max_priority_fee_per_gas, Some(1_000_000)); + match normalized.try_into_sim_tx().expect("must build a MorphTx") { + MorphTxEnvelope::Morph(signed) => { + assert_eq!(signed.tx().version, MORPH_TX_VERSION_2); + assert_eq!(signed.tx().authorization_list.len(), 1); + } + other => panic!("expected MorphTx, got {other:?}"), + } + } }