Skip to main content

foundry_evm_core/evm/
fork.rs

1//! Fork registry: which backing databases exist, which one is active, and the accepted state each
2//! inactive one resumes with.
3
4use super::{AcceptedView, BackingDb, EvmEnv, SendableExt, StoredExt};
5use crate::fork::{Fork, ForkId};
6use alloy_eips::BlockNumHash;
7use alloy_primitives::{
8    Address, B256, U256,
9    map::{AddressMap, AddressSet, HashMap, HashSet},
10};
11use evm2::{EvmFeatures, EvmTypesHost, evm::Cache};
12use std::{collections::BTreeMap, fmt, mem, sync::Arc};
13
14/// Identity of a fork as Foundry users see it: its RPC endpoint and pinned block.
15///
16/// It travels with the fork's context, so snapshot reverts restore it together with the state.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct ForkInfo {
19    /// Deduplicating identifier of the RPC endpoint and block.
20    pub id: ForkId,
21    /// RPC endpoint.
22    pub url: String,
23    /// RPC block number whose state the fork executes on, if any.
24    ///
25    /// After rolling to a transaction this is the transaction's block, whose parent state was
26    /// replayed up to the transaction.
27    pub block: Option<u64>,
28    /// The remote fork backing the context, if it is RPC-backed.
29    pub remote: Option<Fork>,
30    /// Canonical chain position of the fork's accepted state, for networks whose execution
31    /// depends on it, such as Monad.
32    ///
33    /// The matching block cursor is retained in the context's network extension state; both move
34    /// together on canonical replays and are restored together by snapshot reverts. Synthetic
35    /// transactions never advance it.
36    pub position: Option<ForkPosition>,
37}
38
39impl ForkInfo {
40    /// Creates the identity of a fork that is not RPC-backed, such as one over an in-memory
41    /// database.
42    pub fn new(id: ForkId, url: impl Into<String>, block: Option<u64>) -> Self {
43        Self { id, url: url.into(), block, remote: None, position: None }
44    }
45}
46
47/// Canonical chain position of a fork's accepted state.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum ForkPosition {
50    /// The state contains every transaction through `block`.
51    AfterBlock(BlockNumHash),
52    /// The state contains the transactions of `block` before `index`.
53    BeforeTransaction {
54        /// Block whose transactions are partially applied.
55        block: BlockNumHash,
56        /// Index of the next canonical transaction in `block`.
57        index: usize,
58    },
59}
60
61impl ForkPosition {
62    /// Returns the position after the transaction at `index` of `block`, whose parent is
63    /// `parent_hash` and which has `count` transactions, if that transaction immediately follows
64    /// this position.
65    pub fn after_transaction(
66        self,
67        block: BlockNumHash,
68        parent_hash: B256,
69        index: usize,
70        count: usize,
71    ) -> Option<Self> {
72        let is_next = match self {
73            Self::AfterBlock(previous) => {
74                index == 0
75                    && previous.number.checked_add(1) == Some(block.number)
76                    && previous.hash == parent_hash
77            }
78            Self::BeforeTransaction { block: current, index: next } => {
79                current == block && next == index
80            }
81        };
82        let next = index.checked_add(1)?;
83        if !is_next || next > count {
84            return None;
85        }
86        Some(if next == count {
87            Self::AfterBlock(block)
88        } else {
89            Self::BeforeTransaction { block, index: next }
90        })
91    }
92}
93
94/// An execution context that is not running: its backing database, environment, network
95/// extension state and accepted state.
96pub struct Parked<T: EvmTypesHost> {
97    /// Backing database.
98    pub db: Box<dyn BackingDb>,
99    /// Environment to resume with. A fork keeps the chain ID it was created or rolled with,
100    /// whatever chain ID it last ran with.
101    pub env: EvmEnv<T>,
102    /// Network extension state to resume with.
103    pub ext: StoredExt<T::EvmExt>,
104    /// Accepted state to resume with; `None` until the context is first initialized.
105    ///
106    /// The cache is shared with snapshots and with EVMs created over the context, so taking a
107    /// snapshot or starting an execution does not copy it.
108    pub cache: Option<Arc<Cache>>,
109    /// Whether `cache` holds carried accounts but the network initialization of a context that
110    /// never ran is still due.
111    pub(super) needs_init: bool,
112    /// Accounts loaded in this context before it was suspended, with their loaded slots. They are
113    /// cleared when the context finishes a transaction.
114    pub(super) loaded: AddressMap<HashSet<U256>>,
115    /// Accounts created in this context before it was suspended, with the same lifetime as
116    /// `loaded`.
117    pub(super) created: AddressSet,
118    /// Accounts warm in this context when the running transaction last suspended it, with their
119    /// warm slots. Cleared between transactions, so the next transaction starts them cold.
120    pub(super) warm: AddressMap<HashSet<U256>>,
121    /// Transaction-start values of the slots the running transaction changed in this context
122    /// before it last suspended it, which its accepted state no longer holds. Cleared between
123    /// transactions, like `warm`.
124    pub(super) originals: AddressMap<HashMap<U256, U256>>,
125    /// Values at the last fork switch of the slots whose transaction-start originals the running
126    /// transaction restored on resuming this context, which a revert that leaves the context
127    /// keeps as its accepted state. Cleared when the context is suspended and between
128    /// transactions.
129    pub(super) switched: AddressMap<HashMap<U256, U256>>,
130    /// Transient storage of the running transaction in this context when it last suspended it, as
131    /// address, key and value. Cleared between transactions, like `warm`.
132    pub(super) transient: Vec<(Address, U256, U256)>,
133}
134
135impl<T: EvmTypesHost<EvmExt: SendableExt>> Parked<T> {
136    /// Creates a context that has never run.
137    pub fn new(db: Box<dyn BackingDb>, env: EvmEnv<T>, ext: T::EvmExt) -> Self {
138        Self {
139            db,
140            env,
141            ext: StoredExt::new(&ext),
142            cache: None,
143            needs_init: false,
144            loaded: AddressMap::default(),
145            created: AddressSet::default(),
146            warm: AddressMap::default(),
147            originals: AddressMap::default(),
148            switched: AddressMap::default(),
149            transient: Vec::new(),
150        }
151    }
152
153    /// Returns a database reading this context's accepted state over its backing database, with
154    /// the context's empty-account policy, for reads between executions.
155    pub fn accepted_db(&self) -> impl BackingDb + use<T> {
156        let backing = self.db.clone_backing();
157        backing.set_eip161(self.env.version.feature(EvmFeatures::EIP161));
158        AcceptedView { cache: self.cache.clone().unwrap_or_default(), backing }
159    }
160
161    /// Makes the `loaded` accounts and slots visible in this context and carries the `created`
162    /// accounts over from `source` with wiped storage.
163    ///
164    /// Other accounts keep this context's state, so their values are never stale copies from
165    /// another fork.
166    pub(super) fn inherit(
167        &mut self,
168        loaded: &AddressMap<HashSet<U256>>,
169        created: &AddressSet,
170        source: &Cache,
171    ) {
172        for (address, slots) in loaded {
173            self.loaded.entry(*address).or_default().extend(slots);
174        }
175        if created.is_empty() {
176            return;
177        }
178        self.needs_init |= self.cache.is_none();
179        let target = Arc::make_mut(self.cache.get_or_insert_default());
180        for address in created {
181            copy_account(address, source, target);
182            let mut storage = source.storage.get(address).cloned().unwrap_or_default();
183            storage.wiped = true;
184            target.storage.insert(*address, storage);
185        }
186        self.created.extend(created);
187    }
188
189    /// Starts this fork from what the running transaction loaded and created in the `local`
190    /// context before it first selected a fork, and from its transient storage there. Loaded
191    /// storage values are kept even when a non-created account's info comes from the fork.
192    pub(super) fn inherit_local(&mut self, local: &Self) {
193        self.transient.clone_from(&local.transient);
194        for (address, slots) in &local.warm {
195            self.warm.entry(*address).or_default().extend(slots);
196        }
197        if let Some(cache) = &local.cache {
198            self.inherit(&local.loaded, &local.created, cache);
199            for (address, slots) in &local.originals {
200                self.originals.entry(*address).or_default().extend(slots);
201            }
202            for (address, slots) in &local.loaded {
203                if slots.is_empty() {
204                    continue;
205                }
206                self.needs_init |= self.cache.is_none();
207                let target = Arc::make_mut(self.cache.get_or_insert_default());
208                let target = target.storage.entry(*address).or_default();
209                let source = cache.storage.get(address);
210                for slot in slots {
211                    let value = source
212                        .and_then(|storage| storage.slots.get(slot))
213                        .copied()
214                        .unwrap_or_default();
215                    target.slots.insert(*slot, value);
216                }
217            }
218        }
219    }
220
221    /// Returns the accounts and slots the running transaction is warm in this context from its
222    /// earlier visits, which fork switches carry back in when it resumes.
223    pub const fn carried_warmth(&self) -> &AddressMap<HashSet<U256>> {
224        &self.warm
225    }
226}
227
228impl<T: EvmTypesHost<EvmExt: SendableExt>> Clone for Parked<T> {
229    fn clone(&self) -> Self {
230        Self {
231            db: self.db.clone_backing(),
232            env: self.env,
233            ext: self.ext.clone(),
234            cache: self.cache.clone(),
235            needs_init: self.needs_init,
236            loaded: self.loaded.clone(),
237            created: self.created.clone(),
238            warm: self.warm.clone(),
239            originals: self.originals.clone(),
240            switched: self.switched.clone(),
241            transient: self.transient.clone(),
242        }
243    }
244}
245
246impl<T: EvmTypesHost> fmt::Debug for Parked<T> {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.debug_struct("Parked").field("cache", &self.cache.is_some()).finish_non_exhaustive()
249    }
250}
251
252/// A registered fork.
253pub struct ForkEntry<T: EvmTypesHost> {
254    /// User-visible identity.
255    pub info: ForkInfo,
256    /// The fork's context. Its accepted state is stale while the fork is active.
257    pub context: Parked<T>,
258}
259
260impl<T: EvmTypesHost> fmt::Debug for ForkEntry<T> {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        f.debug_struct("ForkEntry").field("info", &self.info).finish_non_exhaustive()
263    }
264}
265
266impl<T: EvmTypesHost<EvmExt: SendableExt>> Clone for ForkEntry<T> {
267    fn clone(&self) -> Self {
268        Self { info: self.info.clone(), context: self.context.clone() }
269    }
270}
271
272/// Registered forks, the local context, the active selection and persistent accounts.
273///
274/// The active context's accepted state lives in the running EVM; every other context keeps its
275/// own here. Switching is driven by [`ExecutionLifecycle`](super::ExecutionLifecycle).
276pub struct ForkRegistry<T: EvmTypesHost> {
277    /// The non-forked context.
278    pub(super) local: Parked<T>,
279    /// Forks by local fork ID.
280    pub(super) forks: BTreeMap<U256, ForkEntry<T>>,
281    /// Active fork, or `None` for the local context.
282    pub(super) active: Option<U256>,
283    /// Next local fork ID. Never reused, even across snapshot reverts.
284    pub(super) next_id: U256,
285    /// Accounts whose state follows every fork switch.
286    pub(super) persistent: AddressSet,
287}
288
289impl<T: EvmTypesHost> fmt::Debug for ForkRegistry<T> {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        f.debug_struct("ForkRegistry")
292            .field("forks", &self.forks)
293            .field("active", &self.active)
294            .field("persistent", &self.persistent)
295            .finish_non_exhaustive()
296    }
297}
298
299impl<T: EvmTypesHost<EvmExt: SendableExt>> Clone for ForkRegistry<T> {
300    fn clone(&self) -> Self {
301        Self {
302            local: self.local.clone(),
303            forks: self.forks.clone(),
304            active: self.active,
305            next_id: self.next_id,
306            persistent: self.persistent.clone(),
307        }
308    }
309}
310
311impl<T: EvmTypesHost> ForkRegistry<T> {
312    /// Creates a registry whose active context is the local one.
313    pub fn new(local: Parked<T>) -> Self {
314        Self {
315            local,
316            forks: BTreeMap::new(),
317            active: None,
318            next_id: U256::ZERO,
319            persistent: AddressSet::default(),
320        }
321    }
322
323    /// Registers a fork and returns its local fork ID. The fork is not selected.
324    pub fn insert(&mut self, info: ForkInfo, context: Parked<T>) -> U256 {
325        let id = self.next_id;
326        self.next_id += U256::ONE;
327        self.forks.insert(id, ForkEntry { info, context });
328        id
329    }
330
331    /// Returns the active fork, or `None` for the local context.
332    pub const fn active(&self) -> Option<U256> {
333        self.active
334    }
335
336    /// Returns a registered fork.
337    pub fn get(&self, id: U256) -> Option<&ForkEntry<T>> {
338        self.forks.get(&id)
339    }
340
341    /// Returns a registered fork mutably.
342    pub fn get_mut(&mut self, id: U256) -> Option<&mut ForkEntry<T>> {
343        self.forks.get_mut(&id)
344    }
345
346    /// Returns the number of registered forks.
347    pub fn len(&self) -> usize {
348        self.forks.len()
349    }
350
351    /// Returns whether no fork is registered.
352    pub fn is_empty(&self) -> bool {
353        self.forks.is_empty()
354    }
355
356    /// Returns the registered forks.
357    pub fn iter(&self) -> impl Iterator<Item = (U256, &ForkEntry<T>)> {
358        self.forks.iter().map(|(id, entry)| (*id, entry))
359    }
360
361    /// Returns a context, or `None` for an unknown fork.
362    ///
363    /// The active context's accepted state is stale while an EVM runs it.
364    pub fn context(&self, id: Option<U256>) -> Option<&Parked<T>> {
365        match id {
366            None => Some(&self.local),
367            Some(id) => self.forks.get(&id).map(|entry| &entry.context),
368        }
369    }
370
371    /// Returns a context mutably, or `None` for an unknown fork.
372    pub fn context_mut(&mut self, id: Option<U256>) -> Option<&mut Parked<T>> {
373        match id {
374            None => Some(&mut self.local),
375            Some(id) => self.forks.get_mut(&id).map(|entry| &mut entry.context),
376        }
377    }
378
379    /// Returns a new handle to the active context's backing database.
380    pub fn active_db(&self) -> Box<dyn BackingDb> {
381        self.context(self.active).expect("active context exists").db.clone_backing()
382    }
383
384    /// Marks an account as persistent across fork switches. Returns whether it was not yet
385    /// persistent.
386    pub fn add_persistent(&mut self, address: Address) -> bool {
387        self.persistent.insert(address)
388    }
389
390    /// Stops an account from persisting across fork switches. Returns whether it was persistent.
391    pub fn remove_persistent(&mut self, address: &Address) -> bool {
392        self.persistent.remove(address)
393    }
394
395    /// Returns whether an account persists across fork switches.
396    pub fn is_persistent(&self, address: &Address) -> bool {
397        self.persistent.contains(address)
398    }
399
400    /// Returns the accounts that persist across fork switches.
401    pub fn persistent_accounts(&self) -> impl Iterator<Item = Address> + '_ {
402        self.persistent.iter().copied()
403    }
404
405    /// Merges persistent accounts' accepted state from `source` into `target`.
406    ///
407    /// Slots of `source` override those of `target`, and other `target` slots are kept unless
408    /// `source` wiped the account's storage.
409    pub(super) fn merge_persistent(&self, source: &Cache, target: &mut Cache) {
410        for address in &self.persistent {
411            copy_account(address, source, target);
412            if let Some(storage) = source.storage.get(address) {
413                let target = target.storage.entry(*address).or_default();
414                if storage.wiped {
415                    target.wipe();
416                }
417                // Copying the source's slot table and looking up the target's own slots is
418                // cheaper than reinserting every source slot, as the source usually holds them all.
419                let kept = mem::replace(&mut target.slots, storage.slots.clone());
420                for (key, value) in kept {
421                    target.slots.entry(key).or_insert(value);
422                }
423            }
424        }
425    }
426
427    /// Makes persistent accounts loaded in `source` visible in `target`, along with their slots.
428    pub(super) fn merge_persistent_loaded(
429        &self,
430        source: &AddressMap<HashSet<U256>>,
431        target: &mut AddressMap<HashSet<U256>>,
432    ) {
433        for address in &self.persistent {
434            if let Some(slots) = source.get(address) {
435                target.entry(*address).or_default().extend(slots);
436            }
437        }
438    }
439}
440
441/// Copies the account info and code of `address` from `source` into `target`, if `source` holds
442/// the account.
443fn copy_account(address: &Address, source: &Cache, target: &mut Cache) {
444    if let Some(account) = source.accounts.get(address) {
445        target.accounts.insert(*address, account.clone());
446        if let Some(info) = account
447            && let Some(code) = source.contracts.get(&info.code_hash)
448        {
449            target.contracts.insert(info.code_hash, code.clone());
450        }
451    }
452}