1use 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
26pub trait FoundryDatabase: DynDatabase {
28 fn is_forked_mode(&self) -> bool {
30 false
31 }
32
33 fn active_fork_source_chain_id(&self) -> Option<u64> {
35 None
36 }
37
38 fn evict_account(&self, _address: &Address) {}
40
41 fn evict_storage(&self, _address: &Address, _slot: &U256) {}
43
44 fn set_eip161(&self, _eip161: bool) {}
47
48 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
68pub trait BackingDb: FoundryDatabase + Send + Sync + 'static {
71 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#[derive(Clone, Debug, Default)]
120pub struct ForkCode(Arc<RwLock<B256Map<Bytecode>>>);
121
122impl ForkCode {
123 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 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 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#[derive(Debug)]
165pub struct ForkDb<D> {
166 db: D,
167 source_chain_id: u64,
168 eip161: AtomicBool,
170 code: ForkCode,
172}
173
174impl<D> ForkDb<D> {
175 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 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 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 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
258pub 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
269pub(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 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 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}