anvil/eth/backend/
executor.rs

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