Skip to main content

foundry_evm_core/evm/
eth.rs

1//! Ethereum on evm2.
2
3use super::{
4    EvmEnv, FoundryEvmFactory, FoundryEvmNetwork, FoundryExecutionHooks, FoundryTxConversion,
5    TxPayload, eth_envelope_from_any_rpc, eth_tx, eth_tx_from_request, with_eip7702_delegations,
6};
7use crate::edgecov;
8use alloy_consensus::transaction::Recovered;
9use alloy_network::{AnyRpcTransaction, Ethereum};
10use alloy_primitives::{Address, Bytes, U256, address};
11use alloy_rpc_types::TransactionRequest;
12use evm2::{
13    BaseEvmTypes, Evm, EvmTypes, ExecutionConfig, PrecompileError, Precompiles, SpecId, TxResult,
14    Version,
15    ethereum::TxEnvelope,
16    evm::precompile::{PrecompileOutput, PrecompileProvider},
17    interpreter::{GasTracker, Message},
18    precompiles::{MovePrecompileError, PrecompileHalt, PrecompileId, PrecompileResult},
19    registry::TxRegistry,
20};
21use foundry_evm_networks::{
22    NetworkConfigs,
23    celo::transfer::{CELO_TRANSFER_ADDRESS, CELO_TRANSFER_PRECOMPILE_NAME},
24};
25
26/// Gas Celo's transfer precompile charges.
27const CELO_TRANSFER_GAS_COST: u64 = 9000;
28
29/// Address of BSC's `P256VERIFY` precompile.
30const BSC_P256_ADDRESS: Address = address!("0x0000000000000000000000000000000000000100");
31
32const BSC_MAINNET_CHAIN_ID: u64 = 56;
33const BSC_TESTNET_CHAIN_ID: u64 = 97;
34const BSC_MAINNET_HABER_TIMESTAMP: u64 = 1_718_863_500;
35const BSC_TESTNET_HABER_TIMESTAMP: u64 = 1_716_962_820;
36const BSC_MAINNET_OSAKA_TIMESTAMP: u64 = 1_777_343_400;
37const BSC_TESTNET_OSAKA_TIMESTAMP: u64 = 1_774_319_400;
38
39/// Ethereum evm2 factory over evm2's stock type family.
40#[derive(Clone, Copy, Debug, Default)]
41pub struct EthEvmFactory {
42    /// Whether Celo's transfer precompile is installed.
43    celo: bool,
44}
45
46/// Ethereum EVM network.
47#[derive(Clone, Copy, Debug, Default)]
48pub struct EthEvmNetwork;
49
50impl FoundryEvmNetwork for EthEvmNetwork {
51    type Network = Ethereum;
52    type EvmFactory = EthEvmFactory;
53}
54
55impl FoundryExecutionHooks for BaseEvmTypes {}
56
57impl FoundryTxConversion<Ethereum> for BaseEvmTypes {
58    fn evm_tx(
59        envelope: alloy_consensus::TxEnvelope,
60        sender: Address,
61        _payload: TxPayload,
62    ) -> eyre::Result<Recovered<TxEnvelope>> {
63        Ok(Recovered::new_unchecked(eth_tx(envelope), sender))
64    }
65
66    fn tx_from_request(request: TransactionRequest) -> eyre::Result<Recovered<TxEnvelope>> {
67        eth_tx_from_request(request)
68    }
69
70    fn envelope_from_any_rpc(tx: &AnyRpcTransaction) -> eyre::Result<alloy_consensus::TxEnvelope> {
71        eth_envelope_from_any_rpc(tx, "TxEnv")
72    }
73}
74
75impl FoundryEvmFactory for EthEvmFactory {
76    type Types = BaseEvmTypes;
77
78    fn version(&self, spec: SpecId, chain_id: u64) -> Version {
79        let mut version = Version::new(spec);
80        version.chain_id = chain_id;
81        with_eip7702_delegations(version)
82    }
83
84    fn execution_config(&self, spec: SpecId, version: Version) -> ExecutionConfig<BaseEvmTypes> {
85        edgecov::execution_config(spec, version)
86    }
87
88    fn tx_registry(&self, spec: SpecId) -> TxRegistry<BaseEvmTypes, TxResult<BaseEvmTypes>> {
89        evm2::ethereum::ethereum_tx_registry(spec)
90    }
91
92    fn precompiles(
93        &self,
94        env: &EvmEnv<BaseEvmTypes>,
95        _ext: &(),
96    ) -> Box<dyn PrecompileProvider<BaseEvmTypes>> {
97        let inner = Precompiles::base(env.spec);
98        let p256 = bsc_p256(env.chain_id(), env.block.timestamp.saturating_to());
99        if !self.celo && p256.is_none() {
100            return Box::new(inner);
101        }
102        Box::new(EthPrecompiles { inner, celo: self.celo, p256 })
103    }
104
105    fn with_networks(&self, networks: NetworkConfigs) -> Self {
106        Self { celo: networks.is_celo() }
107    }
108}
109
110/// Ethereum precompiles with network additions: Celo's transfer precompile and BSC's
111/// `P256VERIFY` rules.
112struct EthPrecompiles {
113    inner: Precompiles<BaseEvmTypes>,
114    celo: bool,
115    /// BSC's `P256VERIFY`, see [`bsc_p256`].
116    p256: Option<Option<bool>>,
117}
118
119impl PrecompileProvider<BaseEvmTypes> for EthPrecompiles {
120    fn addresses(&self) -> Vec<Address> {
121        let mut addresses = self.inner.addresses();
122        if self.celo {
123            addresses.push(CELO_TRANSFER_ADDRESS);
124        }
125        if self.p256.is_some() {
126            addresses.retain(|address| *address != BSC_P256_ADDRESS);
127        }
128        if let Some(Some(_)) = self.p256 {
129            addresses.push(BSC_P256_ADDRESS);
130        }
131        addresses
132    }
133
134    fn precompile_ids(&self) -> Vec<(Address, PrecompileId)> {
135        let mut ids = self.inner.precompile_ids();
136        if self.celo {
137            ids.push((CELO_TRANSFER_ADDRESS, PrecompileId::custom(CELO_TRANSFER_PRECOMPILE_NAME)));
138        }
139        if self.p256.is_some() {
140            ids.retain(|(address, _)| *address != BSC_P256_ADDRESS);
141        }
142        if let Some(Some(_)) = self.p256 {
143            ids.push((BSC_P256_ADDRESS, PrecompileId::P256Verify));
144        }
145        ids
146    }
147
148    fn contains(&self, address: &Address) -> bool {
149        if self.celo && *address == CELO_TRANSFER_ADDRESS {
150            return true;
151        }
152        if self.p256.is_some() && *address == BSC_P256_ADDRESS {
153            return self.p256.flatten().is_some();
154        }
155        self.inner.contains(address)
156    }
157
158    fn move_precompiles(
159        &mut self,
160        moves: &[(Address, Address)],
161    ) -> Result<(), MovePrecompileError> {
162        self.inner.move_precompiles(moves)
163    }
164
165    fn execute(
166        &mut self,
167        evm: &mut Evm<'_, BaseEvmTypes>,
168        message: &Message<BaseEvmTypes>,
169        gas: &mut GasTracker,
170    ) -> Option<PrecompileResult> {
171        let target = message.call_target;
172        if target == CELO_TRANSFER_ADDRESS {
173            return self.celo.then(|| {
174                let input = Bytes::copy_from_slice(evm.message_input(message));
175                celo_transfer(evm, &input, gas)
176            });
177        }
178        if target == BSC_P256_ADDRESS
179            && let Some(p256) = self.p256
180        {
181            return p256.map(|osaka| {
182                if osaka {
183                    evm2::precompiles::secp256r1::run_osaka(evm.message_input(message), gas)
184                } else {
185                    evm2::precompiles::secp256r1::run(evm.message_input(message), gas)
186                }
187            });
188        }
189        self.inner.execute(evm, message, gas)
190    }
191}
192
193/// Runs Celo's native token transfer precompile.
194///
195/// See <https://specs.celo.org/token_duality.html#the-transfer-precompile>
196pub fn celo_transfer<T: EvmTypes>(
197    evm: &mut Evm<'_, T>,
198    input: &[u8],
199    gas: &mut GasTracker,
200) -> PrecompileResult {
201    let halt =
202        |reason: &'static str| Err(PrecompileError::Halt(PrecompileHalt::Other(reason.into())));
203    gas.spend(CELO_TRANSFER_GAS_COST)?;
204    if input.len() != 96 {
205        return halt("invalid input length for Celo transfer precompile");
206    }
207    let from = Address::from_slice(&input[12..32]);
208    let to = Address::from_slice(&input[44..64]);
209    let value = U256::from_be_slice(&input[64..96]);
210    let state = evm.state_mut();
211    let balance = {
212        let mut account = state.account(&from)?;
213        account.warm();
214        account.balance()
215    };
216    if balance < value {
217        return halt("insufficient balance");
218    }
219    state.account(&to)?.warm();
220    if !state.transfer(&from, &to, &value)? {
221        return halt("balance overflow in to account");
222    }
223    Ok(PrecompileOutput::new(Bytes::new()))
224}
225
226/// Returns BSC's `P256VERIFY` on `chain_id` at `timestamp`. The outer option distinguishes BSC
227/// chains from unrelated chains, while the inner option disables P256 before Haber and otherwise
228/// tells whether it uses the Osaka gas schedule.
229pub const fn bsc_p256(chain_id: u64, timestamp: u64) -> Option<Option<bool>> {
230    let (haber_timestamp, osaka_timestamp) = match chain_id {
231        BSC_MAINNET_CHAIN_ID => (BSC_MAINNET_HABER_TIMESTAMP, BSC_MAINNET_OSAKA_TIMESTAMP),
232        BSC_TESTNET_CHAIN_ID => (BSC_TESTNET_HABER_TIMESTAMP, BSC_TESTNET_OSAKA_TIMESTAMP),
233        _ => return None,
234    };
235    if timestamp < haber_timestamp { Some(None) } else { Some(Some(timestamp >= osaka_timestamp)) }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use alloy_sol_types::SolValue;
242    use evm2::{
243        evm::{AccountInfo, InMemoryDB},
244        interpreter::{Host, InstrStop},
245    };
246
247    fn ids(factory: EthEvmFactory, spec: SpecId, chain_id: u64, timestamp: u64) -> Vec<Address> {
248        let block = evm2::env::BlockEnv::<BaseEvmTypes> {
249            timestamp: U256::from(timestamp),
250            ..Default::default()
251        };
252        let env = EvmEnv::new(spec, factory.version(spec, chain_id), block);
253        factory.precompiles(&env, &()).precompile_ids().into_iter().map(|(a, _)| a).collect()
254    }
255
256    #[test]
257    fn bsc_precompile_overrides_stock_p256() {
258        let eth = EthEvmFactory::default();
259        // Osaka includes P256, but BSC removes it before Haber and adds it from Haber on.
260        assert!(ids(eth, SpecId::OSAKA, 1, 0).contains(&BSC_P256_ADDRESS));
261        assert!(
262            !ids(eth, SpecId::OSAKA, 56, BSC_MAINNET_HABER_TIMESTAMP - 1)
263                .contains(&BSC_P256_ADDRESS)
264        );
265        assert!(
266            ids(eth, SpecId::CANCUN, 56, BSC_MAINNET_HABER_TIMESTAMP).contains(&BSC_P256_ADDRESS)
267        );
268        assert!(
269            !ids(eth, SpecId::CANCUN, 1, BSC_MAINNET_HABER_TIMESTAMP).contains(&BSC_P256_ADDRESS)
270        );
271    }
272
273    #[test]
274    fn celo_transfer_warms_accounts() {
275        let from = Address::with_last_byte(0xa1);
276        let recipient = Address::with_last_byte(0xb2);
277        let factory = EthEvmFactory::default().with_networks(NetworkConfigs::with_celo());
278        let spec = SpecId::OSAKA;
279        let env = EvmEnv::new(spec, factory.version(spec, 42220), Default::default());
280        let mut db = InMemoryDB::default();
281        db.insert_account_info(&from, AccountInfo::default().with_balance(U256::from(10)));
282        let mut evm = factory.create_evm(db, env);
283
284        for (to, value) in [(recipient, 0), (recipient, 3), (from, 3)] {
285            let checkpoint = evm.state().checkpoint();
286            let mut message = Message::<BaseEvmTypes> {
287                destination: CELO_TRANSFER_ADDRESS,
288                call_target: CELO_TRANSFER_ADDRESS,
289                code_address: CELO_TRANSFER_ADDRESS,
290                gas_limit: 9000,
291                input: Bytes::from((from, to, U256::from(value)).abi_encode()).into(),
292                ..Default::default()
293            };
294
295            assert_eq!(
296                Host::execute_message(&mut evm, &mut message).unwrap().stop,
297                InstrStop::Return
298            );
299            for address in [from, to] {
300                assert!(evm.state_mut().account(&address).unwrap().is_warm());
301            }
302
303            // An enclosing revert must undo the transfer's warmth.
304            let features = evm.version().features;
305            evm.state_mut().rollback(checkpoint, features);
306            for address in [from, to] {
307                assert!(!evm.state_mut().account(&address).unwrap().is_warm());
308            }
309        }
310    }
311}