Skip to main content

foundry_evm_core/evm/
db.rs

1//! Backing databases.
2//!
3//! A backing database only serves reads that miss evm2's accepted-state overlay. Fork lifecycle,
4//! snapshots and cheatcode policy live in [`ForkRegistry`](super::ForkRegistry) and
5//! [`ExecutionLifecycle`](super::ExecutionLifecycle), not here.
6
7use crate::fork::prefetch;
8use alloy_network::Network;
9use alloy_primitives::{Address, B256, Bytes, U256, map::B256Map};
10use evm2::{
11    DatabaseError,
12    bytecode::Bytecode,
13    evm::{AccountInfo, Cache, DbResult, DynDatabase, EmptyDB, InMemoryDB, NonStaticAny},
14    interpreter::Word,
15};
16use foundry_fork_db::{ForkBlockEnv, SharedBackend};
17use parking_lot::RwLock;
18use std::{
19    any::TypeId,
20    sync::{
21        Arc,
22        atomic::{AtomicBool, Ordering},
23    },
24};
25
26/// Database view the factory needs at construction time.
27pub trait FoundryDatabase: DynDatabase {
28    /// Whether the database is currently in forked mode.
29    fn is_forked_mode(&self) -> bool {
30        false
31    }
32
33    /// Returns the source chain ID of the active fork, independent of execution overrides.
34    fn active_fork_source_chain_id(&self) -> Option<u64> {
35        None
36    }
37
38    /// Drops remotely cached state of `address`, so the next read refetches it.
39    fn evict_account(&self, _address: &Address) {}
40
41    /// Drops a remotely cached storage slot, so the next read refetches it.
42    fn evict_storage(&self, _address: &Address, _slot: &U256) {}
43
44    /// Sets whether the execution reading this database applies EIP-161, under which empty
45    /// accounts do not exist.
46    fn set_eip161(&self, _eip161: bool) {}
47
48    /// Prefetches the remote state a call is about to read, if this database reads a remote
49    /// fork. With `overrides`, the `local` state over this database goes along as overrides.
50    /// A call sent without overrides is skipped when the fork loaded its target without code. It
51    /// is also skipped when `local` holds its target but the fork never loaded it.
52    fn prefetch_call(
53        &self,
54        _caller: Address,
55        _target: Address,
56        _value: U256,
57        _input: Bytes,
58        _local: Option<&Cache>,
59        _overrides: bool,
60    ) {
61    }
62}
63
64impl FoundryDatabase for EmptyDB {}
65
66impl FoundryDatabase for InMemoryDB {}
67
68/// A shareable backing database: every fork and every nested transaction reads through its own
69/// handle to the same source.
70pub trait BackingDb: FoundryDatabase + Send + Sync + 'static {
71    /// Returns another handle to the same source.
72    fn clone_backing(&self) -> Box<dyn BackingDb>;
73}
74
75impl<D: FoundryDatabase + Clone + Send + Sync + 'static> BackingDb for D {
76    fn clone_backing(&self) -> Box<dyn BackingDb> {
77        Box::new(self.clone())
78    }
79}
80
81impl FoundryDatabase for Box<dyn BackingDb> {
82    fn is_forked_mode(&self) -> bool {
83        (**self).is_forked_mode()
84    }
85
86    fn active_fork_source_chain_id(&self) -> Option<u64> {
87        (**self).active_fork_source_chain_id()
88    }
89
90    fn evict_account(&self, address: &Address) {
91        (**self).evict_account(address);
92    }
93
94    fn evict_storage(&self, address: &Address, slot: &U256) {
95        (**self).evict_storage(address, slot);
96    }
97
98    fn set_eip161(&self, eip161: bool) {
99        (**self).set_eip161(eip161);
100    }
101
102    fn prefetch_call(
103        &self,
104        caller: Address,
105        target: Address,
106        value: U256,
107        input: Bytes,
108        local: Option<&Cache>,
109        overrides: bool,
110    ) {
111        (**self).prefetch_call(caller, target, value, input, local, overrides);
112    }
113}
114
115/// Converts accounts of the fork cache, which holds raw code, into evm2 accounts.
116///
117/// Each distinct code is built into [`Bytecode`] once and shared by every account and handle that
118/// reads it, so loads do not copy code and its jump analysis is reused.
119#[derive(Clone, Debug, Default)]
120pub struct ForkCode(Arc<RwLock<B256Map<Bytecode>>>);
121
122impl ForkCode {
123    /// Returns the fork cache's `account` as an evm2 account.
124    pub fn account(&self, account: foundry_fork_db::AccountInfo) -> AccountInfo {
125        let code = account.code.map(|code| self.bytecode(account.code_hash, code));
126        AccountInfo {
127            extension: account.extension.into(),
128            ..AccountInfo::new(account.balance, account.nonce, account.code_hash, code)
129        }
130    }
131
132    /// Returns the bytecode of `code`, whose hash is `code_hash`.
133    fn bytecode(&self, code_hash: B256, code: alloy_primitives::Bytes) -> Bytecode {
134        if code.is_empty() {
135            return Bytecode::new();
136        }
137        if let Some(bytecode) = self.0.read().get(&code_hash) {
138            return bytecode.clone();
139        }
140        self.0.write().entry(code_hash).or_insert_with(|| Bytecode::from_stored(code)).clone()
141    }
142
143    /// Returns the code with `code_hash` that an account of `db` holds.
144    pub fn code_by_hash(
145        &self,
146        db: &foundry_fork_db::cache::MemDb,
147        code_hash: B256,
148    ) -> Option<Bytecode> {
149        if let Some(bytecode) = self.0.read().get(&code_hash) {
150            return Some(bytecode.clone());
151        }
152        let code =
153            db.accounts.read().values().find_map(|info| {
154                (info.code_hash == code_hash).then(|| info.code.clone()).flatten()
155            })?;
156        Some(self.bytecode(code_hash, code))
157    }
158}
159
160/// A remote fork's backing database: Foundry's RPC-backed fork cache, read by evm2.
161///
162/// The fork cache stores raw remote accounts. This adapter converts them into evm2 accounts and
163/// supplies the source chain identity and the execution spec's empty-account policy.
164#[derive(Debug)]
165pub struct ForkDb<D> {
166    db: D,
167    source_chain_id: u64,
168    /// Whether empty accounts do not exist (EIP-161), local to this execution's handle.
169    eip161: AtomicBool,
170    /// Bytecode built from the fork cache, shared by every handle.
171    code: ForkCode,
172}
173
174impl<D> ForkDb<D> {
175    /// Wraps a fork cache whose remote state belongs to `source_chain_id`.
176    pub fn new(db: D, source_chain_id: u64) -> Self {
177        Self { db, source_chain_id, eip161: AtomicBool::new(true), code: ForkCode::default() }
178    }
179
180    /// Returns the wrapped fork cache.
181    pub const fn inner(&self) -> &D {
182        &self.db
183    }
184}
185
186impl<D: Clone> Clone for ForkDb<D> {
187    fn clone(&self) -> Self {
188        Self {
189            db: self.db.clone(),
190            source_chain_id: self.source_chain_id,
191            eip161: AtomicBool::new(self.eip161.load(Ordering::Relaxed)),
192            code: self.code.clone(),
193        }
194    }
195}
196
197impl<N: Network, B: ForkBlockEnv> DynDatabase for ForkDb<SharedBackend<N, B>> {
198    fn get_account(&mut self, address: &Address) -> DbResult<Option<AccountInfo>> {
199        let info = self.db.account(*address).map_err(fatal)?.map(|info| self.code.account(info));
200        // The fork cache reports accounts the remote does not hold as existing empty accounts.
201        // From Spurious Dragon on an empty account does not exist (EIP-161), so load it as absent;
202        // otherwise fresh EIP-7702 authorities would be refunded as existing ones. Before, the
203        // remote cannot tell an existing empty account apart from an absent one; load it as
204        // existing, as the account a historical call reaches usually is.
205        Ok(existing_account(self.eip161.load(Ordering::Relaxed), info))
206    }
207
208    fn get_code_by_hash(&mut self, code_hash: &B256) -> DbResult<Bytecode> {
209        // RPC cannot fetch code by hash; the fork cache stores it inline.
210        self.code
211            .code_by_hash(&self.db.data(), *code_hash)
212            .ok_or_else(|| fatal(foundry_fork_db::DatabaseError::MissingCode(*code_hash)))
213    }
214
215    fn get_storage(&mut self, address: &Address, key: &U256) -> DbResult<U256> {
216        self.db.storage_at(*address, *key).map_err(fatal)
217    }
218
219    fn get_block_hash(&mut self, number: &U256) -> DbResult<B256> {
220        self.db.block_hash(u64::try_from(*number).map_err(fatal)?).map_err(fatal)
221    }
222}
223
224impl<N: Network, B: ForkBlockEnv> FoundryDatabase for ForkDb<SharedBackend<N, B>> {
225    fn is_forked_mode(&self) -> bool {
226        true
227    }
228
229    fn active_fork_source_chain_id(&self) -> Option<u64> {
230        Some(self.source_chain_id)
231    }
232
233    fn evict_account(&self, address: &Address) {
234        self.db.evict(*address, None);
235    }
236
237    fn evict_storage(&self, address: &Address, slot: &U256) {
238        self.db.evict(*address, Some(*slot));
239    }
240
241    fn set_eip161(&self, eip161: bool) {
242        self.eip161.store(eip161, Ordering::Relaxed);
243    }
244
245    fn prefetch_call(
246        &self,
247        caller: Address,
248        target: Address,
249        value: U256,
250        input: Bytes,
251        local: Option<&Cache>,
252        overrides: bool,
253    ) {
254        prefetch::prefetch_call(&self.db, caller, target, value, input, local, overrides);
255    }
256}
257
258/// Returns `account`, which a database reports as an existing empty account when it does not hold
259/// it, as an execution applying EIP-161 or not loads it. Under EIP-161 an empty account does not
260/// exist, so it is loaded as absent.
261pub fn existing_account(eip161: bool, account: Option<AccountInfo>) -> Option<AccountInfo> {
262    account.filter(|account| !eip161 || !account.is_empty())
263}
264
265fn fatal(err: impl std::error::Error + Send + Sync + 'static) -> DatabaseError {
266    DatabaseError::new(err, true)
267}
268
269/// A context's accepted state layered over its backing database, shared without copying.
270///
271/// EVMs start over this view, so creating one does not copy the accepted state; their overlay
272/// only collects what they read and write. Operations that capture or replace the whole state
273/// first materialize the view into the overlay (see
274/// [`ExecutionLifecycle`](super::ExecutionLifecycle)).
275pub(super) struct AcceptedView {
276    pub(super) cache: Arc<Cache>,
277    pub(super) backing: Box<dyn BackingDb>,
278}
279
280impl Clone for AcceptedView {
281    fn clone(&self) -> Self {
282        Self { cache: Arc::clone(&self.cache), backing: self.backing.clone_backing() }
283    }
284}
285
286impl AcceptedView {
287    /// Returns whether `db` is an accepted view.
288    pub(super) fn is(db: &dyn DynDatabase) -> bool {
289        let db: &dyn NonStaticAny = db;
290        db.type_id() == TypeId::of::<Self>()
291    }
292}
293
294impl DynDatabase for AcceptedView {
295    fn get_account(&mut self, address: &Address) -> DbResult<Option<AccountInfo>> {
296        let account = match self.cache.accounts.get(address) {
297            Some(account) => account.clone(),
298            None => self.backing.get_account(address)?,
299        };
300        // Storage written to an absent account, such as by `vm.store`, is accepted without the
301        // account. evm2 reads no storage for an absent account, so report it as an empty one.
302        if account.is_none()
303            && self
304                .cache
305                .storage
306                .get(address)
307                .is_some_and(|storage| storage.slots.values().any(|value| !value.is_zero()))
308        {
309            return Ok(Some(AccountInfo::default()));
310        }
311        Ok(account)
312    }
313
314    fn get_code_by_hash(&mut self, hash: &B256) -> DbResult<Bytecode> {
315        match self.cache.contracts.get(hash) {
316            Some(code) => Ok(code.clone()),
317            None => self.backing.get_code_by_hash(hash),
318        }
319    }
320
321    fn get_storage(&mut self, address: &Address, key: &Word) -> DbResult<Word> {
322        if let Some(storage) = self.cache.storage.get(address) {
323            if let Some(value) = storage.slots.get(key) {
324                return Ok(*value);
325            }
326            if storage.wiped {
327                return Ok(Word::ZERO);
328            }
329        }
330        if matches!(self.cache.accounts.get(address), Some(None)) {
331            return Ok(Word::ZERO);
332        }
333        self.backing.get_storage(address, key)
334    }
335
336    fn get_block_hash(&mut self, number: &Word) -> DbResult<B256> {
337        match self.cache.block_hashes.get(number) {
338            Some(hash) => Ok(*hash),
339            None => self.backing.get_block_hash(number),
340        }
341    }
342}
343
344impl FoundryDatabase for AcceptedView {
345    fn is_forked_mode(&self) -> bool {
346        self.backing.is_forked_mode()
347    }
348
349    fn active_fork_source_chain_id(&self) -> Option<u64> {
350        self.backing.active_fork_source_chain_id()
351    }
352
353    fn evict_account(&self, address: &Address) {
354        self.backing.evict_account(address);
355    }
356
357    fn evict_storage(&self, address: &Address, slot: &U256) {
358        self.backing.evict_storage(address, slot);
359    }
360
361    fn set_eip161(&self, eip161: bool) {
362        self.backing.set_eip161(eip161);
363    }
364
365    fn prefetch_call(
366        &self,
367        caller: Address,
368        target: Address,
369        value: U256,
370        input: Bytes,
371        local: Option<&Cache>,
372        overrides: bool,
373    ) {
374        self.backing.prefetch_call(caller, target, value, input, local, overrides);
375    }
376}