Skip to main content

evm_fork_cache/cache/
snapshot.rs

1//! Immutable, shareable EVM state snapshots.
2//!
3//! # Two-tier copy-on-write model (Pillar A)
4//!
5//! A snapshot is split into two tiers:
6//!
7//! - a **memoized immutable base** (`BaseState`) flattening the *cold* layer-2
8//!   `BlockchainDb` index, shared across successive snapshots by `Arc` — both the
9//!   base as a whole and each account's storage map (`Arc<HashMap<U256, U256>>`) —
10//!   so taking a snapshot when the cold index is unchanged is an `Arc` handle
11//!   copy, never a per-slot deep copy;
12//! - a small per-snapshot **overlay** folding the *hot* layer-1 CacheDB delta
13//!   (committed sim changes, write-throughs, freshness corrections), which always
14//!   shadows the base on a read.
15//!
16//! [`super::EvmCache::snapshot`] memoizes the base (via the internal
17//! `refresh_base`) and folds only layer 1 fresh, so its cost tracks *changed*
18//! state, not *total* state. The retained
19//! [`super::EvmCache::snapshot_deep_clone`] produces the same two-tier
20//! shape with everything flattened into the base and empty overlay maps; it is the
21//! A/B benchmark baseline and the read-equivalence reference.
22//!
23//! Reads stay O(1) `HashMap` lookups with no locks (Decision D1: `Arc` sharing,
24//! not a persistent/HAMT map), so the snapshot is `Send + Sync` and an
25//! [`EvmOverlay`] built from it is `Send`.
26//!
27//! # Per-simulation dirty layer
28//!
29//! Each simulation does not mutate the shared snapshot. Instead it wraps the
30//! `Arc<EvmSnapshot>` in an [`EvmOverlay`], which adds a per-simulation
31//! *dirty layer* on top: writes (committed account/storage changes, RPC
32//! fallbacks, freshness overrides) land in the overlay's own maps and take
33//! precedence over the snapshot on subsequent reads. Two overlays built from
34//! the same `Arc<EvmSnapshot>` are fully isolated from one another, so
35//! simulations can run in parallel without contending for or corrupting the
36//! shared base state.
37//!
38//! [`EvmOverlay`]: super::EvmOverlay
39
40use std::collections::{HashMap, HashSet};
41use std::sync::Arc;
42
43use alloy_primitives::{Address, B256, U256};
44use revm::primitives::hardfork::SpecId;
45use revm::state::{AccountInfo, Bytecode};
46
47/// Memoized, immutable flatten of the **cold layer-2** index (Pillar A).
48///
49/// Holds layer-2 (`BlockchainDb`) account info and storage only; the layer-1
50/// `StorageCleared` / `NotExisting` classification is purely a layer-1 property
51/// and lives on [`EvmSnapshot`], not here (see the read rules on
52/// [`EvmSnapshot::storage_value`]). Each account's storage is wrapped in an `Arc`
53/// so that rebuilding the base on a partial change (copy-on-write) shares the
54/// `Arc` handles of unchanged accounts instead of deep-copying their slots.
55///
56/// Built and memoized by [`EvmCache::refresh_base`](super::EvmCache::refresh_base);
57/// shared across snapshots and across threads via `Arc<BaseState>`.
58pub(crate) struct BaseState {
59    /// Layer-2 account info, by address. (Layer 2 has no `NotExisting` concept;
60    /// that classification is purely a layer-1 property — see [`EvmSnapshot`].)
61    pub(crate) accounts: HashMap<Address, AccountInfo>,
62    /// Layer-2 storage, per account, **shared by `Arc`** so cloning a base — or
63    /// rebuilding it for an unchanged account — is a handle copy, never a per-slot
64    /// copy.
65    pub(crate) storage: HashMap<Address, Arc<HashMap<U256, U256>>>,
66    /// Bytecode by `code_hash`, derived from `accounts` at build time.
67    pub(crate) code_by_hash: HashMap<B256, Bytecode>,
68}
69
70/// Immutable EVM state snapshot — `Send + Sync`, shared via `Arc` across threads.
71///
72/// A two-tier copy-on-write view (see the [module docs](self)): an `Arc`-shared,
73/// memoized cold base (layer 2) plus a small per-snapshot overlay folding the hot
74/// layer-1 CacheDB delta, which shadows the base on reads. Lookups (including the
75/// public [`storage_value`](Self::storage_value)) are O(1) and lock-free, and
76/// reproduce the live cache's layered semantics bit-for-bit.
77///
78/// Created via [`super::EvmCache::snapshot()`]. Each parallel simulation
79/// task gets its own [`super::EvmOverlay`] backed by a cheap `Arc::clone` of
80/// the snapshot.
81pub struct EvmSnapshot {
82    /// Memoized, `Arc`-shared cold layer-2 base.
83    pub(crate) base: Arc<BaseState>,
84    /// Layer-1 accounts that are present to the EVM (`NotExisting` excluded).
85    /// Shadows [`BaseState::accounts`] on a read.
86    pub(crate) overlay_accounts: HashMap<Address, AccountInfo>,
87    /// Layer-1 storage delta, per account. A cleared account (revm
88    /// `StorageCleared` / `NotExisting`) ALWAYS has an entry here (possibly empty)
89    /// so the cleared rule is decided without consulting the base.
90    pub(crate) overlay_storage: HashMap<Address, HashMap<U256, U256>>,
91    /// Bytecode introduced by layer 1 (checked before [`BaseState::code_by_hash`]).
92    pub(crate) overlay_code_by_hash: HashMap<B256, Bytecode>,
93    /// Accounts whose storage is locally complete (revm `StorageCleared` /
94    /// `NotExisting`): a slot absent from `overlay_storage` for such an account
95    /// reads as ZERO and must NOT fall through to the base or an `ext_db`,
96    /// mirroring the live EVM SLOAD and
97    /// [`EvmCache::cached_storage_value`](super::EvmCache::cached_storage_value).
98    pub(crate) storage_cleared: HashSet<Address>,
99    /// Accounts that are absent to the EVM (revm `NotExisting`):
100    /// [`account_info`](Self::account_info) returns `None` for them and must NOT
101    /// fall through to the base or an `ext_db`, mirroring revm `DbAccount::info()`
102    /// and [`EvmCache`](super::EvmCache)'s live account read. These addresses are
103    /// excluded from `overlay_accounts` / `overlay_code_by_hash`.
104    pub(crate) accounts_not_existing: HashSet<Address>,
105    pub(crate) block_hashes: HashMap<u64, B256>,
106    // Block context
107    pub(crate) block_number: Option<u64>,
108    pub(crate) basefee: Option<u64>,
109    pub(crate) coinbase: Option<Address>,
110    pub(crate) prevrandao: Option<B256>,
111    pub(crate) gas_limit: Option<u64>,
112    pub(crate) chain_id: u64,
113    pub(crate) timestamp: Option<u64>,
114    pub(crate) spec_id: SpecId,
115    /// Per-context EVM shared-memory pre-allocation (bytes) copied from the
116    /// [`EvmCache`](super::EvmCache) at snapshot time, so an [`EvmOverlay`] built
117    /// from this snapshot pre-allocates the same working-memory size the live cache
118    /// was configured with (see
119    /// [`SharedMemoryCapacity`](super::SharedMemoryCapacity)).
120    pub(crate) shared_memory_capacity: usize,
121}
122
123impl EvmSnapshot {
124    /// Account info as the EVM sees it: overlay (layer 1) wins, else the base
125    /// (layer 2), else `None`.
126    ///
127    /// Returns `None` for a `NotExisting` account without consulting the base,
128    /// mirroring revm `DbAccount::info()` and the live `EvmCache` account read.
129    pub(crate) fn account_info(&self, address: Address) -> Option<&AccountInfo> {
130        if self.accounts_not_existing.contains(&address) {
131            return None;
132        }
133        self.overlay_accounts
134            .get(&address)
135            .or_else(|| self.base.accounts.get(&address))
136    }
137
138    /// Return the snapshot's value for a storage slot, mirroring the live read.
139    ///
140    /// Used by the freshness validator to compare a freshly-fetched value against
141    /// the value the snapshot was built from. Resolution matches
142    /// [`EvmCache::cached_storage_value`](super::EvmCache::cached_storage_value)
143    /// over the two tiers: an overlay (layer-1) slot wins; for a cleared account
144    /// an absent overlay slot returns `Some(ZERO)` (its storage is locally
145    /// complete — the base is never consulted); otherwise the base (layer-2) slot
146    /// is returned, or `None` if neither tier has seen the slot.
147    pub fn storage_value(&self, address: Address, slot: U256) -> Option<U256> {
148        if let Some(account_storage) = self.overlay_storage.get(&address) {
149            if let Some(value) = account_storage.get(&slot) {
150                return Some(*value);
151            }
152            // A StorageCleared / NotExisting account's storage is locally complete:
153            // an absent slot reads ZERO and never falls through to the base.
154            if self.storage_cleared.contains(&address) {
155                return Some(U256::ZERO);
156            }
157            // Non-cleared overlay account: fall through to the base below.
158        }
159        self.base
160            .storage
161            .get(&address)
162            .and_then(|s| s.get(&slot).copied())
163    }
164
165    /// Bytecode by `code_hash`: overlay (layer 1) wins, else the base (layer 2).
166    pub(crate) fn code(&self, code_hash: B256) -> Option<&Bytecode> {
167        self.overlay_code_by_hash
168            .get(&code_hash)
169            .or_else(|| self.base.code_by_hash.get(&code_hash))
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    /// Build an empty `Arc<BaseState>` for snapshot literals in tests.
178    fn empty_base() -> Arc<BaseState> {
179        Arc::new(BaseState {
180            accounts: HashMap::new(),
181            storage: HashMap::new(),
182            code_by_hash: HashMap::new(),
183        })
184    }
185
186    #[test]
187    fn test_snapshot_is_send_sync() {
188        fn assert_send_sync<T: Send + Sync>() {}
189        assert_send_sync::<EvmSnapshot>();
190        assert_send_sync::<Arc<EvmSnapshot>>();
191    }
192
193    #[test]
194    fn test_empty_snapshot() {
195        let snap = EvmSnapshot {
196            base: empty_base(),
197            overlay_accounts: HashMap::new(),
198            overlay_storage: HashMap::new(),
199            overlay_code_by_hash: HashMap::new(),
200            storage_cleared: HashSet::new(),
201            accounts_not_existing: HashSet::new(),
202            block_hashes: HashMap::new(),
203            block_number: Some(100),
204            basefee: Some(1000),
205            coinbase: None,
206            prevrandao: None,
207            gas_limit: None,
208            chain_id: 42161,
209            timestamp: None,
210            spec_id: SpecId::CANCUN,
211            shared_memory_capacity: 64_000,
212        };
213        assert_eq!(snap.chain_id, 42161);
214        assert_eq!(snap.block_number, Some(100));
215    }
216}