Skip to main content

anvil/eth/backend/
replay.rs

1//! Transaction-hash fork replay preparation and execution.
2
3use crate::{
4    config::ForkTransactionReplay,
5    eth::backend::executor::AnvilBlockExecutor,
6    mem::inspector::{AnvilInspector, InspectorTxConfig},
7};
8use alloy_consensus::{
9    BlockHeader, Transaction, Typed2718,
10    transaction::{Recovered, SignerRecoverable, TxHashRef},
11};
12use alloy_evm::{
13    Evm, FromRecoveredTx, FromTxWithEncoded, RecoveredTx,
14    block::{
15        BalIndexedDatabase, BlockExecutionError, BlockExecutionResult, BlockExecutor, StateDB,
16        TxResult,
17    },
18    precompiles::PrecompilesMap,
19};
20use alloy_network::{BlockResponse, TransactionResponse};
21use alloy_primitives::B256;
22use anvil_core::eth::transaction::{MaybeImpersonatedTransaction, TransactionInfo};
23use eyre::{Context, Result};
24use foundry_common::sh_warn;
25use foundry_evm::core::evm::IntoInstructionResult;
26use foundry_primitives::{FoundryReceiptEnvelope, FoundryTxEnvelope, FoundryTxType};
27use revm::{
28    Database,
29    context_interface::result::{ExecutionResult, Output},
30    interpreter::InstructionResult,
31    state::EvmState,
32};
33
34/// A source transaction prepared for direct historical execution.
35#[derive(Clone, Debug)]
36pub(crate) struct HistoricalReplayTransaction {
37    pub(crate) transaction: Recovered<FoundryTxEnvelope>,
38    /// Where this transaction sat in the source block, for diagnostics only.
39    ///
40    /// The replayed block holds just the transactions anvil executed, so this is not its index
41    /// there; storage keys receipts and traces by position in that block.
42    pub(crate) source_index: usize,
43}
44
45/// A validated transaction prefix together with its source block execution inputs.
46pub(crate) struct PreparedForkTransactionReplay {
47    pub(crate) transactions: Vec<HistoricalReplayTransaction>,
48    pub(crate) timestamp: u64,
49    pub(crate) parent_beacon_block_root: Option<B256>,
50}
51
52impl PreparedForkTransactionReplay {
53    /// Resolves the execution chain ID encoded by the source prefix.
54    ///
55    /// Unprotected legacy prefixes inherit the execution identity exposed by the endpoint.
56    pub(crate) fn execution_chain_id(&self, fallback: u64) -> Result<u64> {
57        let mut resolved = None;
58        for replay in &self.transactions {
59            let Some(chain_id) = replay.transaction.tx().chain_id() else { continue };
60            if let Some(expected) = resolved {
61                eyre::ensure!(
62                    chain_id == expected,
63                    "source transaction at index {} uses chain ID {chain_id}, expected {expected}",
64                    replay.source_index
65                );
66            } else {
67                resolved = Some(chain_id);
68            }
69        }
70        Ok(resolved.unwrap_or(fallback))
71    }
72}
73
74/// The complete result of executing a historical prefix against an overlay.
75pub(crate) struct ExecutedHistoricalReplay {
76    pub(crate) block_result: BlockExecutionResult<FoundryReceiptEnvelope>,
77    pub(crate) transactions: Vec<MaybeImpersonatedTransaction<FoundryTxEnvelope>>,
78    pub(crate) transaction_infos: Vec<TransactionInfo>,
79    pub(crate) state_changes: Vec<EvmState>,
80}
81
82/// Converts and validates every source-prefix transaction before database execution.
83pub(crate) fn prepare_fork_transaction_replay(
84    replay: ForkTransactionReplay,
85    #[cfg_attr(not(feature = "monad"), allow(unused_variables))] trust_monad_protocol_sender: bool,
86    allow_cip64: bool,
87) -> Result<PreparedForkTransactionReplay> {
88    let source_hash = replay.source_block.header().hash;
89    let source_number = replay.source_block.header().number;
90    let timestamp = replay.source_block.header().timestamp();
91    let parent_beacon_block_root = replay.source_block.header().parent_beacon_block_root();
92    let source_transactions = replay
93        .source_block
94        .transactions()
95        .as_transactions()
96        .expect("full source block validated during resolution");
97
98    let target_index = replay.target_index;
99    let transactions = source_transactions
100        .iter()
101        .take(target_index.saturating_add(1))
102        .enumerate()
103        .map(|(source_index, source_transaction)| {
104            let source_transaction_hash = source_transaction.tx_hash();
105            // Chains anvil can fork but not execute, such as Arbitrum and its Orbit rollups, mint
106            // their own transaction types; Arbitrum opens every block with an `ArbitrumInternalTx`.
107            // Those carry no EVM semantics anvil could apply, so the prefix skips them instead of
108            // failing the whole replay. The requested transaction itself must still be executable,
109            // otherwise the resulting fork would not be the state the caller asked for.
110            if FoundryTxType::try_from(source_transaction.ty()).is_err()
111                || (source_transaction.ty() == foundry_primitives::CIP64_TX_TYPE && !allow_cip64)
112            {
113                eyre::ensure!(
114                    source_index != target_index,
115                    "fork transaction {source_transaction_hash} in block {source_hash} \
116                     ({source_number}) has type 0x{:x}, which anvil cannot execute",
117                    source_transaction.ty(),
118                );
119                sh_warn!(
120                    "skipping source transaction {source_transaction_hash} at index \
121                     {source_index} with unsupported type 0x{:x}; replayed state will not \
122                     include its effects",
123                    source_transaction.ty(),
124                )?;
125                return Ok(None);
126            }
127            let transaction = FoundryTxEnvelope::try_from(source_transaction.clone())
128                .wrap_err_with(|| {
129                    format!(
130                        "failed to convert source transaction {source_transaction_hash} at index \
131                         {source_index} in block {source_hash} ({source_number})"
132                    )
133                })?;
134            eyre::ensure!(
135                transaction.tx_hash() == &source_transaction_hash,
136                "converted source transaction at index {source_index} in block {source_hash} \
137                 ({source_number}) changed hash from {source_transaction_hash} to {}",
138                transaction.tx_hash()
139            );
140            #[cfg(feature = "monad")]
141            let sender = if trust_monad_protocol_sender
142                && source_transaction.from() == monad_revm::staking::constants::SYSTEM_ADDRESS
143            {
144                source_transaction.from()
145            } else {
146                transaction.recover_signer().wrap_err_with(|| {
147                    format!(
148                        "failed to recover sender for source transaction \
149                         {source_transaction_hash} at index {source_index} in block {source_hash} \
150                         ({source_number})"
151                    )
152                })?
153            };
154            #[cfg(not(feature = "monad"))]
155            let sender = transaction.recover_signer().wrap_err_with(|| {
156                format!(
157                    "failed to recover sender for source transaction {source_transaction_hash} at \
158                     index {source_index} in block {source_hash} ({source_number})"
159                )
160            })?;
161            Ok(Some(HistoricalReplayTransaction {
162                transaction: Recovered::new_unchecked(transaction, sender),
163                source_index,
164            }))
165        })
166        .filter_map(Result::transpose)
167        .collect::<Result<_>>()?;
168
169    Ok(PreparedForkTransactionReplay { transactions, timestamp, parent_beacon_block_root })
170}
171
172/// Executes a prepared prefix strictly and captures changesets for deferred publication.
173pub(crate) fn execute_historical_replay<E>(
174    executor: &mut AnvilBlockExecutor<E>,
175    transactions: &[HistoricalReplayTransaction],
176    inspector_config: &InspectorTxConfig,
177) -> Result<(Vec<MaybeImpersonatedTransaction<FoundryTxEnvelope>>, Vec<TransactionInfo>)>
178where
179    E: Evm<
180            DB: StateDB + BalIndexedDatabase,
181            Inspector = AnvilInspector,
182            Precompiles = PrecompilesMap,
183            Tx: FromRecoveredTx<FoundryTxEnvelope> + FromTxWithEncoded<FoundryTxEnvelope>,
184        >,
185    E::HaltReason: Clone + IntoInstructionResult,
186{
187    execute_historical_replay_with(
188        executor,
189        transactions,
190        inspector_config,
191        |evm, tx_env, transaction_hash| {
192            evm.transact(tx_env).map_err(|err| BlockExecutionError::evm(err, transaction_hash))
193        },
194    )
195}
196
197/// Executes a prepared prefix using a caller-selected network transaction entry point.
198pub(crate) fn execute_historical_replay_with<E, F>(
199    executor: &mut AnvilBlockExecutor<E>,
200    transactions: &[HistoricalReplayTransaction],
201    inspector_config: &InspectorTxConfig,
202    mut transact: F,
203) -> Result<(Vec<MaybeImpersonatedTransaction<FoundryTxEnvelope>>, Vec<TransactionInfo>)>
204where
205    E: Evm<
206            DB: StateDB + BalIndexedDatabase,
207            Inspector = AnvilInspector,
208            Precompiles = PrecompilesMap,
209            Tx: FromRecoveredTx<FoundryTxEnvelope> + FromTxWithEncoded<FoundryTxEnvelope>,
210        >,
211    E::HaltReason: Clone + IntoInstructionResult,
212    F: FnMut(
213        &mut E,
214        E::Tx,
215        B256,
216    ) -> Result<
217        revm::context_interface::result::ResultAndState<E::HaltReason>,
218        BlockExecutionError,
219    >,
220{
221    let mut stored_transactions = Vec::with_capacity(transactions.len());
222    let mut transaction_infos = Vec::with_capacity(transactions.len());
223
224    for (execution_index, replay) in transactions.iter().enumerate() {
225        let transaction = replay.transaction.tx();
226        let transaction_hash = *transaction.tx_hash();
227        let sender = replay.transaction.signer();
228        let nonce = executor
229            .evm_mut()
230            .db_mut()
231            .basic(sender)
232            .wrap_err_with(|| {
233                format!(
234                    "database error preparing source transaction {transaction_hash} at index {}",
235                    replay.source_index
236                )
237            })?
238            .unwrap_or_default()
239            .nonce;
240
241        let result = executor
242            .execute_transaction_without_commit_with(
243                replay.transaction.clone().into_encoded(),
244                &mut transact,
245            )
246            .map_err(|err| {
247                eyre::eyre!(
248                    "failed to execute source transaction {transaction_hash} at index {}: {err}",
249                    replay.source_index
250                )
251            })?;
252        let execution_result = result.result().result.clone();
253        let gas_used = execution_result.tx_gas_used();
254        executor.commit_transaction(result);
255
256        let (_, inspector, precompiles) = executor.evm_mut().components_mut();
257        let traces = inspector.finish_transaction(inspector_config, precompiles);
258        let (exit_reason, out) = match execution_result {
259            ExecutionResult::Success { reason, output, .. } => (reason.into(), Some(output)),
260            ExecutionResult::Revert { output, .. } => {
261                (InstructionResult::Revert, Some(Output::Call(output)))
262            }
263            ExecutionResult::Halt { reason, .. } => (reason.into_instruction_result(), None),
264        };
265        let contract_address = transaction.to().is_none().then(|| sender.create(nonce));
266        transaction_infos.push(TransactionInfo {
267            transaction_hash,
268            transaction_index: execution_index as u64,
269            from: sender,
270            to: transaction.to(),
271            contract_address,
272            traces,
273            exit: exit_reason,
274            out: out.map(Output::into_data),
275            nonce,
276            gas_used,
277        });
278        stored_transactions.push(MaybeImpersonatedTransaction::new(transaction.clone()));
279    }
280
281    Ok((stored_transactions, transaction_infos))
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use alloy_consensus::{SignableTransaction, TxEip1559};
288    use alloy_network::AnyRpcBlock;
289    use alloy_primitives::{Signature, U256};
290    use alloy_rpc_types::BlockTransactions;
291    use foundry_primitives::TxCip64;
292
293    /// A real signed legacy transaction, so signer recovery and the hash check pass.
294    const LEGACY_TX: &str = r#"{
295        "type": "0x0",
296        "chainId": "0x1",
297        "nonce": "0x0",
298        "gas": "0x5208",
299        "gasPrice": "0x1",
300        "to": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
301        "value": "0x1",
302        "input": "0x",
303        "r": "0x85c2794a580da137e24ccc823b45ae5cea99371ae23ee13860fcc6935f8305b0",
304        "s": "0x41de7fa4121dab284af4453d30928241208bafa90cdb701fe9bc7054759fe3cd",
305        "v": "0x1b",
306        "hash": "0x8c9b68e8947ace33028dba167354fde369ed7bbe34911b772d09b3c64b861515",
307        "from": "0xa1e4380a3b1f749673e270229993ee55f35663b4",
308        "blockHash": "0x1111111111111111111111111111111111111111111111111111111111111111",
309        "blockNumber": "0x1",
310        "transactionIndex": "0x1"
311    }"#;
312
313    /// An `ArbitrumInternalTx`, the type Arbitrum opens each block with.
314    const ARBITRUM_INTERNAL_TX: &str = r#"{
315        "type": "0x6a",
316        "chainId": "0xa4b1",
317        "nonce": "0x0",
318        "gas": "0x0",
319        "gasPrice": "0x0",
320        "to": "0x00000000000000000000000000000000000a4b05",
321        "value": "0x0",
322        "input": "0x6bf6a42d",
323        "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
324        "from": "0x00000000000000000000000000000000000a4b05",
325        "blockHash": "0x1111111111111111111111111111111111111111111111111111111111111111",
326        "blockNumber": "0x1",
327        "transactionIndex": "0x0"
328    }"#;
329
330    fn source_block() -> AnyRpcBlock {
331        let json = format!(
332            r#"{{
333                "hash": "0x1111111111111111111111111111111111111111111111111111111111111111",
334                "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
335                "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
336                "miner": "0x0000000000000000000000000000000000000000",
337                "stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
338                "transactionsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
339                "receiptsRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
340                "logsBloom": "0x{bloom}",
341                "difficulty": "0x0",
342                "number": "0x1",
343                "gasLimit": "0x1c9c380",
344                "gasUsed": "0x5208",
345                "timestamp": "0x64",
346                "extraData": "0x",
347                "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
348                "nonce": "0x0000000000000000",
349                "uncles": [],
350                "transactions": [{ARBITRUM_INTERNAL_TX}, {LEGACY_TX}]
351            }}"#,
352            bloom = "0".repeat(512),
353        );
354        serde_json::from_str(&json).unwrap()
355    }
356
357    fn replay_for(target_index: usize) -> ForkTransactionReplay {
358        ForkTransactionReplay { source_block: source_block(), target_index }
359    }
360
361    #[test]
362    fn skips_unsupported_prefix_transactions() {
363        let prepared = prepare_fork_transaction_replay(replay_for(1), false, false).unwrap();
364
365        // The Arbitrum-typed transaction at index 0 is dropped, and the standard one keeps its
366        // position in the source block.
367        assert_eq!(prepared.transactions.len(), 1);
368        assert_eq!(prepared.transactions[0].source_index, 1);
369    }
370
371    #[test]
372    fn rejects_unsupported_target_transaction() {
373        let Err(err) = prepare_fork_transaction_replay(replay_for(0), false, false) else {
374            panic!("expected the unsupported target transaction to be rejected");
375        };
376        assert!(err.to_string().contains("0x6a"), "unexpected error: {err}");
377    }
378
379    #[test]
380    fn fork_replay_cip64_requires_celo_mode() {
381        let envelope = FoundryTxEnvelope::Celo(
382            TxCip64 { inner: TxEip1559 { chain_id: 1, ..Default::default() }, fee_currency: None }
383                .into_signed(Signature::new(U256::ONE, U256::from(2), false)),
384        );
385        let mut transaction = serde_json::to_value(&envelope).unwrap();
386        transaction["from"] = serde_json::to_value(envelope.recover_signer().unwrap()).unwrap();
387        let mut block = source_block();
388        block.transactions = BlockTransactions::Full(vec![
389            serde_json::from_value(transaction).unwrap(),
390            serde_json::from_str(LEGACY_TX).unwrap(),
391        ]);
392        let replay =
393            |target_index| ForkTransactionReplay { source_block: block.clone(), target_index };
394        let prepared = prepare_fork_transaction_replay(replay(1), false, false).unwrap();
395        assert_eq!(prepared.transactions.len(), 1);
396        assert_eq!(prepared.transactions[0].source_index, 1);
397        assert!(prepare_fork_transaction_replay(replay(0), false, false).is_err());
398        let prepared = prepare_fork_transaction_replay(replay(0), false, true).unwrap();
399        assert_eq!(prepared.transactions[0].transaction.tx(), &envelope);
400    }
401}