1#![doc(
10 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
11 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
12 issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
13)]
14#![cfg_attr(not(test), warn(unused_crate_dependencies))]
15#![cfg_attr(docsrs, feature(doc_cfg))]
16#![cfg_attr(not(feature = "std"), no_std)]
17
18extern crate alloc;
19
20use alloc::{borrow::Cow, sync::Arc};
21use alloy_consensus::Header;
22use alloy_evm::{
23 eth::{EthBlockExecutionCtx, EthBlockExecutorFactory},
24 EthEvmFactory, FromRecoveredTx, FromTxWithEncoded,
25};
26use core::{convert::Infallible, fmt::Debug};
27use reth_chainspec::{ChainSpec, EthChainSpec, MAINNET};
28use reth_ethereum_primitives::{Block, EthPrimitives, TransactionSigned};
29use reth_evm::{
30 eth::NextEvmEnvAttributes, precompiles::PrecompilesMap, ConfigureEvm, EvmEnv, EvmFactory,
31 NextBlockEnvAttributes, TransactionEnv,
32};
33use reth_primitives_traits::{SealedBlock, SealedHeader};
34use revm::{context::BlockEnv, primitives::hardfork::SpecId};
35
36#[cfg(feature = "std")]
37use reth_evm::{ConfigureEngineEvm, ExecutableTxIterator};
38#[allow(unused_imports)]
39use {
40 alloy_eips::Decodable2718,
41 alloy_primitives::{Bytes, U256},
42 alloy_rpc_types_engine::ExecutionData,
43 reth_chainspec::EthereumHardforks,
44 reth_evm::{EvmEnvFor, ExecutionCtxFor},
45 reth_primitives_traits::{constants::MAX_TX_GAS_LIMIT_OSAKA, SignedTransaction, TxTy},
46 reth_storage_errors::any::AnyError,
47 revm::context::CfgEnv,
48 revm::context_interface::block::BlobExcessGasAndPrice,
49};
50
51pub use alloy_evm::EthEvm;
52
53mod config;
54use alloy_evm::eth::spec::EthExecutorSpec;
55pub use config::{revm_spec, revm_spec_by_timestamp_and_block_number};
56use reth_ethereum_forks::Hardforks;
57
58#[doc(hidden)]
61pub mod execute {
62 use crate::EthEvmConfig;
63
64 #[deprecated(note = "Use `EthEvmConfig` instead")]
65 pub type EthExecutorProvider = EthEvmConfig;
66}
67
68mod build;
69pub use build::EthBlockAssembler;
70
71mod receipt;
72pub use receipt::RethReceiptBuilder;
73
74#[cfg(feature = "test-utils")]
75mod test_utils;
76#[cfg(feature = "test-utils")]
77pub use test_utils::*;
78
79#[derive(Debug, Clone)]
81pub struct EthEvmConfig<C = ChainSpec, EvmFactory = EthEvmFactory> {
82 pub executor_factory: EthBlockExecutorFactory<RethReceiptBuilder, Arc<C>, EvmFactory>,
84 pub block_assembler: EthBlockAssembler<C>,
86}
87
88impl EthEvmConfig {
89 pub fn mainnet() -> Self {
91 Self::ethereum(MAINNET.clone())
92 }
93}
94
95impl<ChainSpec> EthEvmConfig<ChainSpec> {
96 pub fn new(chain_spec: Arc<ChainSpec>) -> Self {
98 Self::ethereum(chain_spec)
99 }
100
101 pub fn ethereum(chain_spec: Arc<ChainSpec>) -> Self {
103 Self::new_with_evm_factory(chain_spec, EthEvmFactory::default())
104 }
105}
106
107impl<ChainSpec, EvmFactory> EthEvmConfig<ChainSpec, EvmFactory> {
108 pub fn new_with_evm_factory(chain_spec: Arc<ChainSpec>, evm_factory: EvmFactory) -> Self {
110 Self {
111 block_assembler: EthBlockAssembler::new(chain_spec.clone()),
112 executor_factory: EthBlockExecutorFactory::new(
113 RethReceiptBuilder::default(),
114 chain_spec,
115 evm_factory,
116 ),
117 }
118 }
119
120 pub const fn chain_spec(&self) -> &Arc<ChainSpec> {
122 self.executor_factory.spec()
123 }
124}
125
126impl<ChainSpec, EvmF> ConfigureEvm for EthEvmConfig<ChainSpec, EvmF>
127where
128 ChainSpec: EthExecutorSpec + EthChainSpec<Header = Header> + Hardforks + 'static,
129 EvmF: EvmFactory<
130 Tx: TransactionEnv
131 + FromRecoveredTx<TransactionSigned>
132 + FromTxWithEncoded<TransactionSigned>,
133 Spec = SpecId,
134 BlockEnv = BlockEnv,
135 Precompiles = PrecompilesMap,
136 > + Clone
137 + Debug
138 + Send
139 + Sync
140 + Unpin
141 + 'static,
142{
143 type Primitives = EthPrimitives;
144 type Error = Infallible;
145 type NextBlockEnvCtx = NextBlockEnvAttributes;
146 type BlockExecutorFactory = EthBlockExecutorFactory<RethReceiptBuilder, Arc<ChainSpec>, EvmF>;
147 type BlockAssembler = EthBlockAssembler<ChainSpec>;
148
149 fn block_executor_factory(&self) -> &Self::BlockExecutorFactory {
150 &self.executor_factory
151 }
152
153 fn block_assembler(&self) -> &Self::BlockAssembler {
154 &self.block_assembler
155 }
156
157 fn evm_env(&self, header: &Header) -> Result<EvmEnv<SpecId>, Self::Error> {
158 Ok(EvmEnv::for_eth_block(
159 header,
160 self.chain_spec(),
161 self.chain_spec().chain().id(),
162 self.chain_spec().blob_params_at_timestamp(header.timestamp),
163 ))
164 }
165
166 fn next_evm_env(
167 &self,
168 parent: &Header,
169 attributes: &NextBlockEnvAttributes,
170 ) -> Result<EvmEnv, Self::Error> {
171 Ok(EvmEnv::for_eth_next_block(
172 parent,
173 NextEvmEnvAttributes {
174 timestamp: attributes.timestamp,
175 suggested_fee_recipient: attributes.suggested_fee_recipient,
176 prev_randao: attributes.prev_randao,
177 gas_limit: attributes.gas_limit,
178 },
179 self.chain_spec().next_block_base_fee(parent, attributes.timestamp).unwrap_or_default(),
180 self.chain_spec(),
181 self.chain_spec().chain().id(),
182 self.chain_spec().blob_params_at_timestamp(attributes.timestamp),
183 ))
184 }
185
186 fn context_for_block<'a>(
187 &self,
188 block: &'a SealedBlock<Block>,
189 ) -> Result<EthBlockExecutionCtx<'a>, Self::Error> {
190 Ok(EthBlockExecutionCtx {
191 parent_hash: block.header().parent_hash,
192 parent_beacon_block_root: block.header().parent_beacon_block_root,
193 ommers: &block.body().ommers,
194 withdrawals: block.body().withdrawals.as_ref().map(Cow::Borrowed),
195 extra_data: block.header().extra_data.clone(),
196 })
197 }
198
199 fn context_for_next_block(
200 &self,
201 parent: &SealedHeader,
202 attributes: Self::NextBlockEnvCtx,
203 ) -> Result<EthBlockExecutionCtx<'_>, Self::Error> {
204 Ok(EthBlockExecutionCtx {
205 parent_hash: parent.hash(),
206 parent_beacon_block_root: attributes.parent_beacon_block_root,
207 ommers: &[],
208 withdrawals: attributes.withdrawals.map(Cow::Owned),
209 extra_data: attributes.extra_data,
210 })
211 }
212}
213
214#[cfg(feature = "std")]
215impl<ChainSpec, EvmF> ConfigureEngineEvm<ExecutionData> for EthEvmConfig<ChainSpec, EvmF>
216where
217 ChainSpec: EthExecutorSpec + EthChainSpec<Header = Header> + Hardforks + 'static,
218 EvmF: EvmFactory<
219 Tx: TransactionEnv
220 + FromRecoveredTx<TransactionSigned>
221 + FromTxWithEncoded<TransactionSigned>,
222 Spec = SpecId,
223 BlockEnv = BlockEnv,
224 Precompiles = PrecompilesMap,
225 > + Clone
226 + Debug
227 + Send
228 + Sync
229 + Unpin
230 + 'static,
231{
232 fn evm_env_for_payload(&self, payload: &ExecutionData) -> Result<EvmEnvFor<Self>, Self::Error> {
233 let timestamp = payload.payload.timestamp();
234 let block_number = payload.payload.block_number();
235
236 let blob_params = self.chain_spec().blob_params_at_timestamp(timestamp);
237 let spec =
238 revm_spec_by_timestamp_and_block_number(self.chain_spec(), timestamp, block_number);
239
240 let mut cfg_env =
242 CfgEnv::new().with_chain_id(self.chain_spec().chain().id()).with_spec(spec);
243
244 if let Some(blob_params) = &blob_params {
245 cfg_env.set_max_blobs_per_tx(blob_params.max_blobs_per_tx);
246 }
247
248 if self.chain_spec().is_osaka_active_at_timestamp(timestamp) {
249 cfg_env.tx_gas_limit_cap = Some(MAX_TX_GAS_LIMIT_OSAKA);
250 }
251
252 let blob_excess_gas_and_price =
255 payload.payload.excess_blob_gas().zip(blob_params).map(|(excess_blob_gas, params)| {
256 let blob_gasprice = params.calc_blob_fee(excess_blob_gas);
257 BlobExcessGasAndPrice { excess_blob_gas, blob_gasprice }
258 });
259
260 let block_env = BlockEnv {
261 number: U256::from(block_number),
262 beneficiary: payload.payload.fee_recipient(),
263 timestamp: U256::from(timestamp),
264 difficulty: if spec >= SpecId::MERGE {
265 U256::ZERO
266 } else {
267 payload.payload.as_v1().prev_randao.into()
268 },
269 prevrandao: (spec >= SpecId::MERGE).then(|| payload.payload.as_v1().prev_randao),
270 gas_limit: payload.payload.gas_limit(),
271 basefee: payload.payload.saturated_base_fee_per_gas(),
272 blob_excess_gas_and_price,
273 };
274
275 Ok(EvmEnv { cfg_env, block_env })
276 }
277
278 fn context_for_payload<'a>(
279 &self,
280 payload: &'a ExecutionData,
281 ) -> Result<ExecutionCtxFor<'a, Self>, Self::Error> {
282 Ok(EthBlockExecutionCtx {
283 parent_hash: payload.parent_hash(),
284 parent_beacon_block_root: payload.sidecar.parent_beacon_block_root(),
285 ommers: &[],
286 withdrawals: payload.payload.withdrawals().map(|w| Cow::Owned(w.clone().into())),
287 extra_data: payload.payload.as_v1().extra_data.clone(),
288 })
289 }
290
291 fn tx_iterator_for_payload(
292 &self,
293 payload: &ExecutionData,
294 ) -> Result<impl ExecutableTxIterator<Self>, Self::Error> {
295 let txs = payload.payload.transactions().clone();
296 let convert = |tx: Bytes| {
297 let tx =
298 TxTy::<Self::Primitives>::decode_2718_exact(tx.as_ref()).map_err(AnyError::new)?;
299 let signer = tx.try_recover().map_err(AnyError::new)?;
300 Ok::<_, AnyError>(tx.with_signer(signer))
301 };
302
303 Ok((txs, convert))
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use alloy_consensus::Header;
311 use alloy_genesis::Genesis;
312 use reth_chainspec::{Chain, ChainSpec};
313 use reth_evm::{execute::ProviderError, EvmEnv};
314 use revm::{
315 context::{BlockEnv, CfgEnv},
316 database::CacheDB,
317 database_interface::EmptyDBTyped,
318 inspector::NoOpInspector,
319 };
320
321 #[test]
322 fn test_fill_cfg_and_block_env() {
323 let header = Header::default();
325
326 let chain_spec = ChainSpec::builder()
329 .chain(Chain::mainnet())
330 .genesis(Genesis::default())
331 .london_activated()
332 .paris_activated()
333 .shanghai_activated()
334 .build();
335
336 let EvmEnv { cfg_env, .. } =
339 EthEvmConfig::new(Arc::new(chain_spec.clone())).evm_env(&header).unwrap();
340
341 assert_eq!(cfg_env.chain_id, chain_spec.chain().id());
344 }
345
346 #[test]
347 fn test_evm_with_env_default_spec() {
348 let evm_config = EthEvmConfig::mainnet();
349
350 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
351
352 let evm_env = EvmEnv::default();
353
354 let evm = evm_config.evm_with_env(db, evm_env.clone());
355
356 assert_eq!(evm.block, evm_env.block_env);
358 assert_eq!(evm.cfg, evm_env.cfg_env);
359 }
360
361 #[test]
362 fn test_evm_with_env_custom_cfg() {
363 let evm_config = EthEvmConfig::mainnet();
364
365 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
366
367 let cfg = CfgEnv::default().with_chain_id(111);
369
370 let evm_env = EvmEnv { cfg_env: cfg.clone(), ..Default::default() };
371
372 let evm = evm_config.evm_with_env(db, evm_env);
373
374 assert_eq!(evm.cfg, cfg);
376 }
377
378 #[test]
379 fn test_evm_with_env_custom_block_and_tx() {
380 let evm_config = EthEvmConfig::mainnet();
381
382 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
383
384 let block = BlockEnv {
386 basefee: 1000,
387 gas_limit: 10_000_000,
388 number: U256::from(42),
389 ..Default::default()
390 };
391
392 let evm_env = EvmEnv { block_env: block, ..Default::default() };
393
394 let evm = evm_config.evm_with_env(db, evm_env.clone());
395
396 assert_eq!(evm.block, evm_env.block_env);
398
399 assert_eq!(evm.cfg.spec, SpecId::default());
401 }
402
403 #[test]
404 fn test_evm_with_spec_id() {
405 let evm_config = EthEvmConfig::mainnet();
406
407 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
408
409 let evm_env = EvmEnv {
410 cfg_env: CfgEnv::new().with_spec(SpecId::CONSTANTINOPLE),
411 ..Default::default()
412 };
413
414 let evm = evm_config.evm_with_env(db, evm_env);
415
416 assert_eq!(evm.cfg.spec, SpecId::CONSTANTINOPLE);
418 }
419
420 #[test]
421 fn test_evm_with_env_and_default_inspector() {
422 let evm_config = EthEvmConfig::mainnet();
423 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
424
425 let evm_env = EvmEnv::default();
426
427 let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
428
429 assert_eq!(evm.block, evm_env.block_env);
431 assert_eq!(evm.cfg, evm_env.cfg_env);
432 }
433
434 #[test]
435 fn test_evm_with_env_inspector_and_custom_cfg() {
436 let evm_config = EthEvmConfig::mainnet();
437 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
438
439 let cfg_env = CfgEnv::default().with_chain_id(111);
440 let block = BlockEnv::default();
441 let evm_env = EvmEnv { cfg_env: cfg_env.clone(), block_env: block };
442
443 let evm = evm_config.evm_with_env_and_inspector(db, evm_env, NoOpInspector {});
444
445 assert_eq!(evm.cfg, cfg_env);
447 assert_eq!(evm.cfg.spec, SpecId::default());
448 }
449
450 #[test]
451 fn test_evm_with_env_inspector_and_custom_block_tx() {
452 let evm_config = EthEvmConfig::mainnet();
453 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
454
455 let block = BlockEnv {
457 basefee: 1000,
458 gas_limit: 10_000_000,
459 number: U256::from(42),
460 ..Default::default()
461 };
462 let evm_env = EvmEnv { block_env: block, ..Default::default() };
463
464 let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
465
466 assert_eq!(evm.block, evm_env.block_env);
468 assert_eq!(evm.cfg.spec, SpecId::default());
469 }
470
471 #[test]
472 fn test_evm_with_env_inspector_and_spec_id() {
473 let evm_config = EthEvmConfig::mainnet();
474 let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
475
476 let evm_env = EvmEnv {
477 cfg_env: CfgEnv::new().with_spec(SpecId::CONSTANTINOPLE),
478 ..Default::default()
479 };
480
481 let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
482
483 assert_eq!(evm.block, evm_env.block_env);
485 assert_eq!(evm.cfg, evm_env.cfg_env);
486 assert_eq!(evm.tx, Default::default());
487 }
488}