Skip to main content

foundry_evm_core/evm/
snapshot.rs

1//! User-visible state snapshots.
2
3use super::{EvmEnv, ForkRegistry, PersistentWrite, SendableExt, StoredExt};
4use evm2::{
5    EvmFeatures, EvmTypesHost,
6    evm::{EmptyDB, State, StateCheckpoint, StateSnapshot},
7};
8use std::{fmt, mem};
9
10/// Persistent writes with the depth and journal length they were recorded at.
11type Ledger = Vec<(usize, usize, PersistentWrite)>;
12
13/// Everything a snapshot revert restores.
14///
15/// evm2's [`StateSnapshot`] covers the running context's accepted and in-flight state but not its
16/// backing database; the fork registry supplies that, along with every inactive fork's accepted
17/// state.
18pub struct LifecycleSnapshot<T: EvmTypesHost> {
19    /// The running context's state.
20    pub(super) state: StateSnapshot,
21    /// Forks, persistent accounts and the active selection.
22    pub(super) forks: ForkRegistry<T>,
23    /// Environment of the running context.
24    pub(super) env: EvmEnv<T>,
25    /// Network extension state of the running context.
26    pub(super) ext: StoredExt<T::EvmExt>,
27}
28
29impl<T: EvmTypesHost<EvmExt: SendableExt>> Clone for LifecycleSnapshot<T> {
30    fn clone(&self) -> Self {
31        Self {
32            state: self.state.clone(),
33            forks: self.forks.clone(),
34            env: self.env,
35            ext: self.ext.clone(),
36        }
37    }
38}
39
40impl<T: EvmTypesHost> fmt::Debug for LifecycleSnapshot<T> {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.debug_struct("LifecycleSnapshot").field("forks", &self.forks).finish_non_exhaustive()
43    }
44}
45
46/// Running states replaced by snapshot restorations inside the open frames of a transaction.
47///
48/// A restoration replaces the running state, journal included, so evm2 can no longer unwind it
49/// with the checkpoint of a frame that was open when it happened. Those frames own it instead:
50/// when one of them fails, the state the restoration replaced is reinstated and rolled back to the
51/// failing frame's checkpoint, which undoes the restoration together with the frame's earlier
52/// writes, as a reverted or halted frame does. A frame that succeeds keeps the restoration, and
53/// its caller takes over the retained state.
54///
55/// The failing frame also keeps the persistent writes made since the restoration, which it
56/// replays over the reinstated state after the writes its rollback undid. They were made on the
57/// state the restoration installed, so the ones that set a balance or nonce, such as `deal`,
58/// replay as the values they left, while changes such as a nested transaction's value transfers
59/// keep replaying as deltas, see [`Replay`](super::Replay). The writes later restorations in the
60/// frame dropped from the running ledger are kept too, since the failing frame also undoes those
61/// restorations. Once a context switch, which the failing frame keeps, drops them from the running
62/// ledger, none of them are kept.
63///
64/// The backend, active fork and environment a restoration installed are kept either way, and the
65/// reinstated state reads from the backing database of the running state it replaces. Retained
66/// states and checkpoints also survive context switches that replace the running journal, such as
67/// fork selections, so a frame that fails after selecting another fork still reinstates the state
68/// a restoration replaced on the source fork.
69///
70/// Only the first restoration since a frame started is retained, which is the one that frame needs
71/// to unwind, so retained states are bounded by call depth. A nested transaction has its own
72/// journal and needs its own instance.
73#[derive(Clone, Debug, Default)]
74pub struct SnapshotRestores {
75    frames: Vec<RestoreFrame>,
76    /// Each retained state.
77    replaced: Vec<ReplacedState>,
78    /// Whether a restoration survived the outermost frame.
79    kept: bool,
80}
81
82/// A running state a restoration replaced.
83#[derive(Clone, Debug)]
84struct ReplacedState {
85    state: StateSnapshot,
86    /// The persistent writes recorded when the state was replaced.
87    ledger: Ledger,
88    /// The persistent writes recorded since, or `None` once a context switch dropped them.
89    later: Option<LaterWrites>,
90    /// The length of `dropped` and the `since` of the `later` writes of each earlier retained
91    /// state when this one was replaced, which reinstating this state restores along with its
92    /// ledger.
93    earlier: Vec<Option<(usize, usize)>>,
94}
95
96/// The persistent writes recorded since a restoration.
97#[derive(Clone, Debug)]
98struct LaterWrites {
99    /// The ones later restorations dropped from the running ledger.
100    dropped: Ledger,
101    /// The position in the running ledger past which it holds the rest.
102    since: usize,
103}
104
105#[derive(Clone, Debug)]
106struct RestoreFrame {
107    depth: u16,
108    /// The checkpoint evm2 rolls the frame back to if it fails.
109    checkpoint: StateCheckpoint,
110    /// Number of retained states when the frame started.
111    replaced_len: usize,
112}
113
114impl SnapshotRestores {
115    /// Opens the interpreter frame at `depth`, which rolls back to `checkpoint` if it fails.
116    pub fn frame_start(&mut self, depth: u16, checkpoint: StateCheckpoint) {
117        self.frames.push(RestoreFrame { depth, checkpoint, replaced_len: self.replaced.len() });
118    }
119
120    /// Retains `replaced`, the running state a restoration in the innermost frame replaced, with
121    /// the persistent writes `ledger` recorded over it, if it is the first restoration since that
122    /// frame started. The restoration keeps the first `len` writes of `ledger`.
123    pub fn capture(
124        &mut self,
125        replaced: StateSnapshot,
126        ledger: &[(usize, usize, PersistentWrite)],
127        len: usize,
128    ) {
129        let len = len.min(ledger.len());
130        let first =
131            self.frames.last().is_some_and(|frame| frame.replaced_len == self.replaced.len());
132        let earlier = if first {
133            let lengths = |later: &LaterWrites| (later.dropped.len(), later.since);
134            self.replaced.iter().map(|retained| retained.later.as_ref().map(lengths)).collect()
135        } else {
136            Vec::new()
137        };
138        // The running ledger only keeps its first `len` writes, so each retained restoration sets
139        // aside the ones recorded since it and continues past `len`.
140        for later in self.replaced.iter_mut().filter_map(|retained| retained.later.as_mut()) {
141            later.dropped.extend(ledger.iter().skip(later.since).cloned());
142            later.since = len;
143        }
144        if first {
145            self.replaced.push(ReplacedState {
146                state: replaced,
147                ledger: ledger.to_vec(),
148                later: Some(LaterWrites { dropped: Vec::new(), since: len }),
149                earlier,
150            });
151        }
152    }
153
154    /// Stops keeping the persistent writes recorded since each retained restoration, after a
155    /// context switch accepted the running state and dropped them. Failing frames keep the switch,
156    /// so reinstating a state does not keep them again.
157    pub fn accept_writes(&mut self) {
158        for retained in &mut self.replaced {
159            retained.later = None;
160            retained.earlier.fill(None);
161        }
162    }
163
164    /// Closes the interpreter frame at `depth`, if one is open. If it failed, reinstates the state
165    /// replaced by the first restoration made inside it, rolled back to the frame's checkpoint,
166    /// and replaces `ledger` with the persistent writes to replay over it.
167    ///
168    /// Returns the checkpoint of the closed frame.
169    pub fn frame_end(
170        &mut self,
171        state: &mut State<'_>,
172        ledger: &mut Ledger,
173        depth: u16,
174        failed: bool,
175        features: EvmFeatures,
176    ) -> Option<StateCheckpoint> {
177        // Frames above `depth` aborted with an execution error and never ended.
178        while self.frames.pop_if(|frame| frame.depth > depth).is_some() {}
179        let frame = self.frames.pop_if(|frame| frame.depth == depth)?;
180        if failed && self.replaced.len() > frame.replaced_len {
181            self.replaced.truncate(frame.replaced_len + 1);
182            let replaced = self.replaced.pop().expect("a restoration was retained");
183            let db = mem::replace(&mut state.overlay_db_mut().db, Box::new(EmptyDB::default()));
184            *state = replaced.state.into_state(EmptyDB::default());
185            state.overlay_db_mut().db = db;
186            state.rollback(frame.checkpoint.clone(), features);
187            // The writes recorded since the restoration were made on the state it installed, so
188            // the frame's rollback did not reach them, and the ones that set a balance or nonce
189            // set the value they left. Marking them past its checkpoint has them replayed after
190            // the writes recorded over the reinstated state.
191            let running = mem::replace(ledger, replaced.ledger);
192            if let Some(later) = replaced.later {
193                let writes = later.dropped.into_iter().chain(running.into_iter().skip(later.since));
194                ledger.extend(
195                    writes.map(|(depth, _, write)| (depth, usize::MAX, write.reinstated())),
196                );
197            }
198            // The reinstated ledger holds the writes the restoration and the later ones dropped,
199            // so earlier restorations keep them in the running ledger again.
200            for (retained, earlier) in self.replaced.iter_mut().zip(replaced.earlier) {
201                retained.later =
202                    retained.later.take().zip(earlier).map(|(mut later, (dropped, since))| {
203                        later.dropped.truncate(dropped);
204                        later.since = since;
205                        later
206                    });
207            }
208        }
209        // The caller only needs the first restoration made since it started.
210        if let Some(caller) = self.frames.last() {
211            self.replaced.truncate(caller.replaced_len + 1);
212        } else {
213            self.kept |= !self.replaced.is_empty();
214            self.replaced.clear();
215        }
216        Some(frame.checkpoint)
217    }
218
219    /// Returns whether a restoration survived the outermost frame.
220    pub const fn kept(&self) -> bool {
221        self.kept
222    }
223}