1use 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#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct ForkInfo {
19 pub id: ForkId,
21 pub url: String,
23 pub block: Option<u64>,
28 pub remote: Option<Fork>,
30 pub position: Option<ForkPosition>,
37}
38
39impl ForkInfo {
40 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum ForkPosition {
50 AfterBlock(BlockNumHash),
52 BeforeTransaction {
54 block: BlockNumHash,
56 index: usize,
58 },
59}
60
61impl ForkPosition {
62 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
94pub struct Parked<T: EvmTypesHost> {
97 pub db: Box<dyn BackingDb>,
99 pub env: EvmEnv<T>,
102 pub ext: StoredExt<T::EvmExt>,
104 pub cache: Option<Arc<Cache>>,
109 pub(super) needs_init: bool,
112 pub(super) loaded: AddressMap<HashSet<U256>>,
115 pub(super) created: AddressSet,
118 pub(super) warm: AddressMap<HashSet<U256>>,
121 pub(super) originals: AddressMap<HashMap<U256, U256>>,
125 pub(super) switched: AddressMap<HashMap<U256, U256>>,
130 pub(super) transient: Vec<(Address, U256, U256)>,
133}
134
135impl<T: EvmTypesHost<EvmExt: SendableExt>> Parked<T> {
136 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 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 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 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 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
252pub struct ForkEntry<T: EvmTypesHost> {
254 pub info: ForkInfo,
256 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
272pub struct ForkRegistry<T: EvmTypesHost> {
277 pub(super) local: Parked<T>,
279 pub(super) forks: BTreeMap<U256, ForkEntry<T>>,
281 pub(super) active: Option<U256>,
283 pub(super) next_id: U256,
285 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 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 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 pub const fn active(&self) -> Option<U256> {
333 self.active
334 }
335
336 pub fn get(&self, id: U256) -> Option<&ForkEntry<T>> {
338 self.forks.get(&id)
339 }
340
341 pub fn get_mut(&mut self, id: U256) -> Option<&mut ForkEntry<T>> {
343 self.forks.get_mut(&id)
344 }
345
346 pub fn len(&self) -> usize {
348 self.forks.len()
349 }
350
351 pub fn is_empty(&self) -> bool {
353 self.forks.is_empty()
354 }
355
356 pub fn iter(&self) -> impl Iterator<Item = (U256, &ForkEntry<T>)> {
358 self.forks.iter().map(|(id, entry)| (*id, entry))
359 }
360
361 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 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 pub fn active_db(&self) -> Box<dyn BackingDb> {
381 self.context(self.active).expect("active context exists").db.clone_backing()
382 }
383
384 pub fn add_persistent(&mut self, address: Address) -> bool {
387 self.persistent.insert(address)
388 }
389
390 pub fn remove_persistent(&mut self, address: &Address) -> bool {
392 self.persistent.remove(address)
393 }
394
395 pub fn is_persistent(&self, address: &Address) -> bool {
397 self.persistent.contains(address)
398 }
399
400 pub fn persistent_accounts(&self) -> impl Iterator<Item = Address> + '_ {
402 self.persistent.iter().copied()
403 }
404
405 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 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 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
441fn 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}