Skip to main content

foundry_evm_core/backend/
cow.rs

1//! A clone-on-write wrapper around [`Backend`] used for fuzzing.
2
3use crate::{
4    backend::Backend,
5    evm::{FoundryEvmFor, FoundryEvmNetwork},
6};
7use alloy_primitives::{Address, TxKind};
8use std::{
9    borrow::Cow,
10    fmt::Debug,
11    ops::{Deref, DerefMut},
12};
13
14/// A clone-on-write [`Backend`].
15///
16/// Reads and executions that discard their state ([`Backend::create_evm`]) borrow the wrapped
17/// backend. The first mutable access, such as a
18/// cheatcode that switches forks, clones it and applies the pending test initialization, so the
19/// original backend is never modified.
20///
21/// Entire purpose of this type is for fuzzing. A test function fuzzer will repeatedly execute the
22/// function via immutable raw (no state changes) calls.
23///
24/// **N.B.**: we're assuming cheatcodes that alter the state (like multi fork swapping) are niche.
25/// If they executed, it will require a clone of the initial input database.
26/// This way we can support these cheatcodes cheaply without adding overhead for tests that
27/// don't make use of them. Alternatively each test case would require its own `Backend` clone,
28/// which would add significant overhead for large fuzz sets even if the Database is not big after
29/// setup.
30#[derive(Clone, Debug)]
31pub struct CowBackend<'a, FEN: FoundryEvmNetwork> {
32    /// The underlying `Backend`.
33    ///
34    /// No calls on the `CowBackend` will ever persistently modify the `backend`'s state.
35    pub backend: Cow<'a, Backend<FEN>>,
36    /// Test initialization applied on first mutable access.
37    pending_init: Option<(Address, TxKind)>,
38}
39
40impl<'a, FEN: FoundryEvmNetwork> CowBackend<'a, FEN> {
41    /// Creates a new `CowBackend` with the given `Backend`.
42    pub const fn new_borrowed(backend: &'a Backend<FEN>) -> Self {
43        Self { backend: Cow::Borrowed(backend), pending_init: None }
44    }
45
46    /// Records the caller and test contract of the next execution, applied with
47    /// [`Backend::initialize`] on first mutable access.
48    pub const fn initialize(&mut self, caller: Address, kind: TxKind) {
49        self.pending_init = Some((caller, kind));
50    }
51
52    /// Returns whether the backend was cloned.
53    pub const fn is_owned(&self) -> bool {
54        matches!(self.backend, Cow::Owned(_))
55    }
56
57    /// Parks accepted state on owned backends; leaves pending writes uncommitted.
58    pub fn park_detached(&mut self, evm: FoundryEvmFor<'_, FEN>) {
59        if let Cow::Owned(backend) = &mut self.backend {
60            backend.lifecycle.park_detached(evm);
61            backend.bal = None;
62        }
63    }
64}
65
66impl<FEN: FoundryEvmNetwork> Deref for CowBackend<'_, FEN> {
67    type Target = Backend<FEN>;
68
69    fn deref(&self) -> &Self::Target {
70        &self.backend
71    }
72}
73
74impl<FEN: FoundryEvmNetwork> DerefMut for CowBackend<'_, FEN> {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        let backend = self.backend.to_mut();
77        if let Some((caller, kind)) = self.pending_init.take() {
78            backend.initialize(caller, kind);
79        }
80        backend
81    }
82}