anvil/eth/backend/
executor.rs

1use crate::{
2    PrecompileFactory,
3    eth::{
4        backend::{
5            cheats::{CheatEcrecover, CheatsManager},
6            db::Db,
7            env::Env,
8            mem::op_haltreason_to_instruction_result,
9            validate::TransactionValidator,
10        },
11        error::InvalidTransactionError,
12        pool::transactions::PoolTransaction,
13    },
14    evm::celo_precompile,
15    inject_precompiles,
16    mem::inspector::AnvilInspector,
17};
18use alloy_consensus::{
19    Receipt, ReceiptWithBloom, constants::EMPTY_WITHDRAWALS, proofs::calculate_receipt_root,
20};
21use alloy_eips::{eip7685::EMPTY_REQUESTS_HASH, eip7840::BlobParams};
22use alloy_evm::{
23    EthEvm, Evm,
24    eth::EthEvmContext,
25    precompiles::{DynPrecompile, Precompile, PrecompilesMap},
26};
27use alloy_op_evm::OpEvm;
28use alloy_primitives::{B256, Bloom, BloomInput, Log};
29use anvil_core::eth::{
30    block::{Block, BlockInfo, PartialHeader},
31    transaction::{
32        DepositReceipt, PendingTransaction, TransactionInfo, TypedReceipt, TypedTransaction,
33    },
34};
35use foundry_evm::{
36    backend::DatabaseError,
37    traces::{CallTraceDecoder, CallTraceNode},
38};
39use foundry_evm_core::{either_evm::EitherEvm, precompiles::EC_RECOVER};
40use op_revm::{L1BlockInfo, OpContext, precompiles::OpPrecompiles};
41use revm::{
42    Database, DatabaseRef, Inspector, Journal,
43    context::{Block as RevmBlock, BlockEnv, CfgEnv, Evm as RevmEvm, JournalTr, LocalContext},
44    context_interface::result::{EVMError, ExecutionResult, Output},
45    database::WrapDatabaseRef,
46    handler::{EthPrecompiles, instructions::EthInstructions},
47    interpreter::InstructionResult,
48    precompile::{
49        PrecompileSpecId, Precompiles,
50        secp256r1::{P256VERIFY, P256VERIFY_BASE_GAS_FEE},
51    },
52    primitives::hardfork::SpecId,
53};
54use std::{fmt::Debug, sync::Arc};
55
56/// Represents an executed transaction (transacted on the DB)
57#[derive(Debug)]
58pub struct ExecutedTransaction {
59    transaction: Arc<PoolTransaction>,
60    exit_reason: InstructionResult,
61    out: Option<Output>,
62    gas_used: u64,
63    logs: Vec<Log>,
64    traces: Vec<CallTraceNode>,
65    nonce: u64,
66}
67
68// == impl ExecutedTransaction ==
69
70impl ExecutedTransaction {
71    /// Creates the receipt for the transaction
72    fn create_receipt(&self, cumulative_gas_used: &mut u64) -> TypedReceipt {
73        let logs = self.logs.clone();
74        *cumulative_gas_used = cumulative_gas_used.saturating_add(self.gas_used);
75
76        // successful return see [Return]
77        let status_code = u8::from(self.exit_reason as u8 <= InstructionResult::SelfDestruct as u8);
78        let receipt_with_bloom: ReceiptWithBloom = Receipt {
79            status: (status_code == 1).into(),
80            cumulative_gas_used: *cumulative_gas_used,
81            logs,
82        }
83        .into();
84
85        match &self.transaction.pending_transaction.transaction.transaction {
86            TypedTransaction::Legacy(_) => TypedReceipt::Legacy(receipt_with_bloom),
87            TypedTransaction::EIP2930(_) => TypedReceipt::EIP2930(receipt_with_bloom),
88            TypedTransaction::EIP1559(_) => TypedReceipt::EIP1559(receipt_with_bloom),
89            TypedTransaction::EIP4844(_) => TypedReceipt::EIP4844(receipt_with_bloom),
90            TypedTransaction::EIP7702(_) => TypedReceipt::EIP7702(receipt_with_bloom),
91            TypedTransaction::Deposit(_tx) => TypedReceipt::Deposit(DepositReceipt {
92                inner: receipt_with_bloom,
93                deposit_nonce: Some(0),
94                deposit_receipt_version: Some(1),
95            }),
96        }
97    }
98}
99
100/// Represents the outcome of mining a new block
101#[derive(Clone, Debug)]
102pub struct ExecutedTransactions {
103    /// The block created after executing the `included` transactions
104    pub block: BlockInfo,
105    /// All transactions included in the block
106    pub included: Vec<Arc<PoolTransaction>>,
107    /// All transactions that were invalid at the point of their execution and were not included in
108    /// the block
109    pub invalid: Vec<Arc<PoolTransaction>>,
110}
111
112/// An executor for a series of transactions
113pub struct TransactionExecutor<'a, Db: ?Sized, V: TransactionValidator> {
114    /// where to insert the transactions
115    pub db: &'a mut Db,
116    /// type used to validate before inclusion
117    pub validator: &'a V,
118    /// all pending transactions
119    pub pending: std::vec::IntoIter<Arc<PoolTransaction>>,
120    pub block_env: BlockEnv,
121    /// The configuration environment and spec id
122    pub cfg_env: CfgEnv,
123    pub parent_hash: B256,
124    /// Cumulative gas used by all executed transactions
125    pub gas_used: u64,
126    /// Cumulative blob gas used by all executed transactions
127    pub blob_gas_used: u64,
128    pub enable_steps_tracing: bool,
129    pub odyssey: bool,
130    pub optimism: bool,
131    pub celo: bool,
132    pub print_logs: bool,
133    pub print_traces: bool,
134    /// Recorder used for decoding traces, used together with print_traces
135    pub call_trace_decoder: Arc<CallTraceDecoder>,
136    /// Precompiles to inject to the EVM.
137    pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
138    pub blob_params: BlobParams,
139    pub cheats: CheatsManager,
140}
141
142impl<DB: Db + ?Sized, V: TransactionValidator> TransactionExecutor<'_, DB, V> {
143    /// Executes all transactions and puts them in a new block with the provided `timestamp`
144    pub fn execute(mut self) -> ExecutedTransactions {
145        let mut transactions = Vec::new();
146        let mut transaction_infos = Vec::new();
147        let mut receipts = Vec::new();
148        let mut bloom = Bloom::default();
149        let mut cumulative_gas_used = 0u64;
150        let mut invalid = Vec::new();
151        let mut included = Vec::new();
152        let gas_limit = self.block_env.gas_limit;
153        let parent_hash = self.parent_hash;
154        let block_number = self.block_env.number;
155        let difficulty = self.block_env.difficulty;
156        let mix_hash = self.block_env.prevrandao;
157        let beneficiary = self.block_env.beneficiary;
158        let timestamp = self.block_env.timestamp;
159        let base_fee = if self.cfg_env.spec.is_enabled_in(SpecId::LONDON) {
160            Some(self.block_env.basefee)
161        } else {
162            None
163        };
164
165        let is_shanghai = self.cfg_env.spec >= SpecId::SHANGHAI;
166        let is_cancun = self.cfg_env.spec >= SpecId::CANCUN;
167        let is_prague = self.cfg_env.spec >= SpecId::PRAGUE;
168        let excess_blob_gas = if is_cancun { self.block_env.blob_excess_gas() } else { None };
169        let mut cumulative_blob_gas_used = if is_cancun { Some(0u64) } else { None };
170
171        for tx in self.into_iter() {
172            let tx = match tx {
173                TransactionExecutionOutcome::Executed(tx) => {
174                    included.push(tx.transaction.clone());
175                    tx
176                }
177                TransactionExecutionOutcome::Exhausted(tx) => {
178                    trace!(target: "backend",  tx_gas_limit = %tx.pending_transaction.transaction.gas_limit(), ?tx,  "block gas limit exhausting, skipping transaction");
179                    continue;
180                }
181                TransactionExecutionOutcome::BlobGasExhausted(tx) => {
182                    trace!(target: "backend",  blob_gas = %tx.pending_transaction.transaction.blob_gas().unwrap_or_default(), ?tx,  "block blob gas limit exhausting, skipping transaction");
183                    continue;
184                }
185                TransactionExecutionOutcome::Invalid(tx, _) => {
186                    trace!(target: "backend", ?tx,  "skipping invalid transaction");
187                    invalid.push(tx);
188                    continue;
189                }
190                TransactionExecutionOutcome::DatabaseError(_, err) => {
191                    // Note: this is only possible in forking mode, if for example a rpc request
192                    // failed
193                    trace!(target: "backend", ?err,  "Failed to execute transaction due to database error");
194                    continue;
195                }
196            };
197            if is_cancun {
198                let tx_blob_gas = tx
199                    .transaction
200                    .pending_transaction
201                    .transaction
202                    .transaction
203                    .blob_gas()
204                    .unwrap_or(0);
205                cumulative_blob_gas_used =
206                    Some(cumulative_blob_gas_used.unwrap_or(0u64).saturating_add(tx_blob_gas));
207            }
208            let receipt = tx.create_receipt(&mut cumulative_gas_used);
209
210            let ExecutedTransaction { transaction, logs, out, traces, exit_reason: exit, .. } = tx;
211            build_logs_bloom(logs.clone(), &mut bloom);
212
213            let contract_address = out.as_ref().and_then(|out| {
214                if let Output::Create(_, contract_address) = out {
215                    trace!(target: "backend", "New contract deployed: at {:?}", contract_address);
216                    *contract_address
217                } else {
218                    None
219                }
220            });
221
222            let transaction_index = transaction_infos.len() as u64;
223            let info = TransactionInfo {
224                transaction_hash: transaction.hash(),
225                transaction_index,
226                from: *transaction.pending_transaction.sender(),
227                to: transaction.pending_transaction.transaction.to(),
228                contract_address,
229                traces,
230                exit,
231                out: out.map(Output::into_data),
232                nonce: tx.nonce,
233                gas_used: tx.gas_used,
234            };
235
236            transaction_infos.push(info);
237            receipts.push(receipt);
238            transactions.push(transaction.pending_transaction.transaction.clone());
239        }
240
241        let receipts_root = calculate_receipt_root(&receipts);
242
243        let partial_header = PartialHeader {
244            parent_hash,
245            beneficiary,
246            state_root: self.db.maybe_state_root().unwrap_or_default(),
247            receipts_root,
248            logs_bloom: bloom,
249            difficulty,
250            number: block_number.saturating_to(),
251            gas_limit,
252            gas_used: cumulative_gas_used,
253            timestamp: timestamp.saturating_to(),
254            extra_data: Default::default(),
255            mix_hash: mix_hash.unwrap_or_default(),
256            nonce: Default::default(),
257            base_fee,
258            parent_beacon_block_root: is_cancun.then_some(Default::default()),
259            blob_gas_used: cumulative_blob_gas_used,
260            excess_blob_gas,
261            withdrawals_root: is_shanghai.then_some(EMPTY_WITHDRAWALS),
262            requests_hash: is_prague.then_some(EMPTY_REQUESTS_HASH),
263        };
264
265        let block = Block::new(partial_header, transactions.clone());
266        let block = BlockInfo { block, transactions: transaction_infos, receipts };
267        ExecutedTransactions { block, included, invalid }
268    }
269
270    fn env_for(&self, tx: &PendingTransaction) -> Env {
271        let mut tx_env = tx.to_revm_tx_env();
272
273        if self.optimism {
274            tx_env.enveloped_tx = Some(alloy_rlp::encode(&tx.transaction.transaction).into());
275        }
276
277        Env::new(self.cfg_env.clone(), self.block_env.clone(), tx_env, self.optimism, self.celo)
278    }
279}
280
281/// Represents the result of a single transaction execution attempt
282#[derive(Debug)]
283pub enum TransactionExecutionOutcome {
284    /// Transaction successfully executed
285    Executed(ExecutedTransaction),
286    /// Invalid transaction not executed
287    Invalid(Arc<PoolTransaction>, InvalidTransactionError),
288    /// Execution skipped because could exceed gas limit
289    Exhausted(Arc<PoolTransaction>),
290    /// Execution skipped because it exceeded the blob gas limit
291    BlobGasExhausted(Arc<PoolTransaction>),
292    /// When an error occurred during execution
293    DatabaseError(Arc<PoolTransaction>, DatabaseError),
294}
295
296impl<DB: Db + ?Sized, V: TransactionValidator> Iterator for &mut TransactionExecutor<'_, DB, V> {
297    type Item = TransactionExecutionOutcome;
298
299    fn next(&mut self) -> Option<Self::Item> {
300        let transaction = self.pending.next()?;
301        let sender = *transaction.pending_transaction.sender();
302        let account = match self.db.basic(sender).map(|acc| acc.unwrap_or_default()) {
303            Ok(account) => account,
304            Err(err) => return Some(TransactionExecutionOutcome::DatabaseError(transaction, err)),
305        };
306        let env = self.env_for(&transaction.pending_transaction);
307
308        // check that we comply with the block's gas limit, if not disabled
309        let max_gas = self.gas_used.saturating_add(env.tx.base.gas_limit);
310        if !env.evm_env.cfg_env.disable_block_gas_limit && max_gas > env.evm_env.block_env.gas_limit
311        {
312            return Some(TransactionExecutionOutcome::Exhausted(transaction));
313        }
314
315        // check that we comply with the block's blob gas limit
316        let max_blob_gas = self.blob_gas_used.saturating_add(
317            transaction.pending_transaction.transaction.transaction.blob_gas().unwrap_or(0),
318        );
319        if max_blob_gas > self.blob_params.max_blob_gas_per_block() {
320            return Some(TransactionExecutionOutcome::BlobGasExhausted(transaction));
321        }
322
323        // validate before executing
324        if let Err(err) = self.validator.validate_pool_transaction_for(
325            &transaction.pending_transaction,
326            &account,
327            &env,
328        ) {
329            warn!(target: "backend", "Skipping invalid tx execution [{:?}] {}", transaction.hash(), err);
330            return Some(TransactionExecutionOutcome::Invalid(transaction, err));
331        }
332
333        let nonce = account.nonce;
334
335        let mut inspector = AnvilInspector::default().with_tracing();
336        if self.enable_steps_tracing {
337            inspector = inspector.with_steps_tracing();
338        }
339        if self.print_logs {
340            inspector = inspector.with_log_collector();
341        }
342        if self.print_traces {
343            inspector = inspector.with_trace_printer();
344        }
345
346        let exec_result = {
347            let mut evm = new_evm_with_inspector(&mut *self.db, &env, &mut inspector);
348
349            if self.odyssey {
350                inject_precompiles(&mut evm, vec![(P256VERIFY, P256VERIFY_BASE_GAS_FEE)]);
351            }
352
353            if self.celo {
354                evm.precompiles_mut()
355                    .apply_precompile(&celo_precompile::CELO_TRANSFER_ADDRESS, move |_| {
356                        Some(celo_precompile::precompile())
357                    });
358            }
359
360            if let Some(factory) = &self.precompile_factory {
361                inject_precompiles(&mut evm, factory.precompiles());
362            }
363
364            let cheats = Arc::new(self.cheats.clone());
365            if cheats.has_recover_overrides() {
366                let cheat_ecrecover = CheatEcrecover::new(Arc::clone(&cheats));
367                evm.precompiles_mut().apply_precompile(&EC_RECOVER, move |_| {
368                    Some(DynPrecompile::new_stateful(
369                        cheat_ecrecover.precompile_id().clone(),
370                        move |input| cheat_ecrecover.call(input),
371                    ))
372                });
373            }
374
375            trace!(target: "backend", "[{:?}] executing", transaction.hash());
376            // transact and commit the transaction
377            match evm.transact_commit(env.tx) {
378                Ok(exec_result) => exec_result,
379                Err(err) => {
380                    warn!(target: "backend", "[{:?}] failed to execute: {:?}", transaction.hash(), err);
381                    match err {
382                        EVMError::Database(err) => {
383                            return Some(TransactionExecutionOutcome::DatabaseError(
384                                transaction,
385                                err,
386                            ));
387                        }
388                        EVMError::Transaction(err) => {
389                            return Some(TransactionExecutionOutcome::Invalid(
390                                transaction,
391                                err.into(),
392                            ));
393                        }
394                        // This will correspond to prevrandao not set, and it should never happen.
395                        // If it does, it's a bug.
396                        e => panic!("failed to execute transaction: {e}"),
397                    }
398                }
399            }
400        };
401
402        if self.print_traces {
403            inspector.print_traces(self.call_trace_decoder.clone());
404        }
405        inspector.print_logs();
406
407        let (exit_reason, gas_used, out, logs) = match exec_result {
408            ExecutionResult::Success { reason, gas_used, logs, output, .. } => {
409                (reason.into(), gas_used, Some(output), Some(logs))
410            }
411            ExecutionResult::Revert { gas_used, output } => {
412                (InstructionResult::Revert, gas_used, Some(Output::Call(output)), None)
413            }
414            ExecutionResult::Halt { reason, gas_used } => {
415                (op_haltreason_to_instruction_result(reason), gas_used, None, None)
416            }
417        };
418
419        if exit_reason == InstructionResult::OutOfGas {
420            // this currently useful for debugging estimations
421            warn!(target: "backend", "[{:?}] executed with out of gas", transaction.hash())
422        }
423
424        trace!(target: "backend", ?exit_reason, ?gas_used, "[{:?}] executed with out={:?}", transaction.hash(), out);
425
426        // Track the total gas used for total gas per block checks
427        self.gas_used = self.gas_used.saturating_add(gas_used);
428
429        // Track the total blob gas used for total blob gas per blob checks
430        if let Some(blob_gas) = transaction.pending_transaction.transaction.transaction.blob_gas() {
431            self.blob_gas_used = self.blob_gas_used.saturating_add(blob_gas);
432        }
433
434        trace!(target: "backend::executor", "transacted [{:?}], result: {:?} gas {}", transaction.hash(), exit_reason, gas_used);
435
436        let tx = ExecutedTransaction {
437            transaction,
438            exit_reason,
439            out,
440            gas_used,
441            logs: logs.unwrap_or_default(),
442            traces: inspector.tracer.map(|t| t.into_traces().into_nodes()).unwrap_or_default(),
443            nonce,
444        };
445
446        Some(TransactionExecutionOutcome::Executed(tx))
447    }
448}
449
450/// Inserts all logs into the bloom
451fn build_logs_bloom(logs: Vec<Log>, bloom: &mut Bloom) {
452    for log in logs {
453        bloom.accrue(BloomInput::Raw(&log.address[..]));
454        for topic in log.topics() {
455            bloom.accrue(BloomInput::Raw(&topic[..]));
456        }
457    }
458}
459
460/// Creates a database with given database and inspector, optionally enabling odyssey features.
461pub fn new_evm_with_inspector<DB, I>(
462    db: DB,
463    env: &Env,
464    inspector: I,
465) -> EitherEvm<DB, I, PrecompilesMap>
466where
467    DB: Database<Error = DatabaseError> + Debug,
468    I: Inspector<EthEvmContext<DB>> + Inspector<OpContext<DB>>,
469{
470    if env.is_optimism {
471        let op_cfg = env.evm_env.cfg_env.clone().with_spec(op_revm::OpSpecId::ISTHMUS);
472        let op_context = OpContext {
473            journaled_state: {
474                let mut journal = Journal::new(db);
475                // Converting SpecId into OpSpecId
476                journal.set_spec_id(env.evm_env.cfg_env.spec);
477                journal
478            },
479            block: env.evm_env.block_env.clone(),
480            cfg: op_cfg.clone(),
481            tx: env.tx.clone(),
482            chain: L1BlockInfo::default(),
483            local: LocalContext::default(),
484            error: Ok(()),
485        };
486
487        let op_precompiles = OpPrecompiles::new_with_spec(op_cfg.spec).precompiles();
488        let op_evm = op_revm::OpEvm(RevmEvm::new_with_inspector(
489            op_context,
490            inspector,
491            EthInstructions::default(),
492            PrecompilesMap::from_static(op_precompiles),
493        ));
494
495        let op = OpEvm::new(op_evm, true);
496
497        EitherEvm::Op(op)
498    } else {
499        let spec = env.evm_env.cfg_env.spec;
500        let eth_context = EthEvmContext {
501            journaled_state: {
502                let mut journal = Journal::new(db);
503                journal.set_spec_id(spec);
504                journal
505            },
506            block: env.evm_env.block_env.clone(),
507            cfg: env.evm_env.cfg_env.clone(),
508            tx: env.tx.base.clone(),
509            chain: (),
510            local: LocalContext::default(),
511            error: Ok(()),
512        };
513
514        let eth_precompiles = EthPrecompiles {
515            precompiles: Precompiles::new(PrecompileSpecId::from_spec_id(spec)),
516            spec,
517        }
518        .precompiles;
519        let eth_evm = RevmEvm::new_with_inspector(
520            eth_context,
521            inspector,
522            EthInstructions::default(),
523            PrecompilesMap::from_static(eth_precompiles),
524        );
525
526        let eth = EthEvm::new(eth_evm, true);
527
528        EitherEvm::Eth(eth)
529    }
530}
531
532/// Creates a new EVM with the given inspector and wraps the database in a `WrapDatabaseRef`.
533pub fn new_evm_with_inspector_ref<'db, DB, I>(
534    db: &'db DB,
535    env: &Env,
536    inspector: &'db mut I,
537) -> EitherEvm<WrapDatabaseRef<&'db DB>, &'db mut I, PrecompilesMap>
538where
539    DB: DatabaseRef<Error = DatabaseError> + Debug + 'db + ?Sized,
540    I: Inspector<EthEvmContext<WrapDatabaseRef<&'db DB>>>
541        + Inspector<OpContext<WrapDatabaseRef<&'db DB>>>,
542    WrapDatabaseRef<&'db DB>: Database<Error = DatabaseError>,
543{
544    new_evm_with_inspector(WrapDatabaseRef(db), env, inspector)
545}