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
47use crate::access_set::StorageAccessList;
48
49/// Memoized, immutable flatten of the **cold layer-2** index (Pillar A).
50///
51/// Holds layer-2 (`BlockchainDb`) account info and storage only; the layer-1
52/// `StorageCleared` / `NotExisting` classification is purely a layer-1 property
53/// and lives on [`EvmSnapshot`], not here (see the read rules on
54/// [`EvmSnapshot::storage_value`]). Each account's storage is wrapped in an `Arc`
55/// so that rebuilding the base on a partial change (copy-on-write) shares the
56/// `Arc` handles of unchanged accounts instead of deep-copying their slots.
57///
58/// Built and memoized by [`EvmCache::refresh_base`](super::EvmCache::refresh_base);
59/// shared across snapshots and across threads via `Arc<BaseState>`.
60pub(crate) struct BaseState {
61 /// Layer-2 account info, by address. (Layer 2 has no `NotExisting` concept;
62 /// that classification is purely a layer-1 property — see [`EvmSnapshot`].)
63 pub(crate) accounts: HashMap<Address, AccountInfo>,
64 /// Layer-2 storage, per account, **shared by `Arc`** so cloning a base — or
65 /// rebuilding it for an unchanged account — is a handle copy, never a per-slot
66 /// copy.
67 pub(crate) storage: HashMap<Address, Arc<HashMap<U256, U256>>>,
68 /// Bytecode by `code_hash`, derived from `accounts` at build time.
69 pub(crate) code_by_hash: HashMap<B256, Bytecode>,
70}
71
72/// Immutable EVM state snapshot — `Send + Sync`, shared via `Arc` across threads.
73///
74/// A two-tier copy-on-write view (see the [module docs](self)): an `Arc`-shared,
75/// memoized cold base (layer 2) plus a small per-snapshot overlay folding the hot
76/// layer-1 CacheDB delta, which shadows the base on reads. Lookups (including the
77/// public [`storage_value`](Self::storage_value)) are O(1) and lock-free, and
78/// reproduce the live cache's layered semantics bit-for-bit.
79///
80/// Created via [`super::EvmCache::snapshot()`]. Each parallel simulation
81/// task gets its own [`super::EvmOverlay`] backed by a cheap `Arc::clone` of
82/// the snapshot.
83pub struct EvmSnapshot {
84 /// Memoized, `Arc`-shared cold layer-2 base.
85 pub(crate) base: Arc<BaseState>,
86 /// Layer-1 accounts that are present to the EVM (`NotExisting` excluded).
87 /// Shadows [`BaseState::accounts`] on a read.
88 pub(crate) overlay_accounts: HashMap<Address, AccountInfo>,
89 /// Layer-1 storage delta, per account. A cleared account (revm
90 /// `StorageCleared` / `NotExisting`) ALWAYS has an entry here (possibly empty)
91 /// so the cleared rule is decided without consulting the base.
92 pub(crate) overlay_storage: HashMap<Address, HashMap<U256, U256>>,
93 /// Bytecode introduced by layer 1 (checked before [`BaseState::code_by_hash`]).
94 pub(crate) overlay_code_by_hash: HashMap<B256, Bytecode>,
95 /// Accounts whose storage is locally complete (revm `StorageCleared` /
96 /// `NotExisting`): a slot absent from `overlay_storage` for such an account
97 /// reads as ZERO and must NOT fall through to the base or an `ext_db`,
98 /// mirroring the live EVM SLOAD and
99 /// [`EvmCache::cached_storage_value`](super::EvmCache::cached_storage_value).
100 pub(crate) storage_cleared: HashSet<Address>,
101 /// Accounts that are absent to the EVM (revm `NotExisting`):
102 /// [`account_info`](Self::account_info) returns `None` for them and must NOT
103 /// fall through to the base or an `ext_db`, mirroring revm `DbAccount::info()`
104 /// and [`EvmCache`](super::EvmCache)'s live account read. These addresses are
105 /// excluded from `overlay_accounts` / `overlay_code_by_hash`.
106 pub(crate) accounts_not_existing: HashSet<Address>,
107 pub(crate) block_hashes: HashMap<u64, B256>,
108 // Block context
109 pub(crate) block_number: Option<u64>,
110 pub(crate) basefee: Option<u64>,
111 pub(crate) coinbase: Option<Address>,
112 pub(crate) prevrandao: Option<B256>,
113 pub(crate) gas_limit: Option<u64>,
114 pub(crate) chain_id: u64,
115 pub(crate) timestamp: Option<u64>,
116 pub(crate) spec_id: SpecId,
117 /// Per-context EVM shared-memory pre-allocation (bytes) copied from the
118 /// [`EvmCache`](super::EvmCache) at snapshot time, so an [`EvmOverlay`] built
119 /// from this snapshot pre-allocates the same working-memory size the live cache
120 /// was configured with (see
121 /// [`SharedMemoryCapacity`](super::SharedMemoryCapacity)).
122 pub(crate) shared_memory_capacity: usize,
123}
124
125impl EvmSnapshot {
126 /// Chain ID captured by this immutable simulation snapshot.
127 pub const fn chain_id(&self) -> u64 {
128 self.chain_id
129 }
130
131 /// Block number installed in the snapshot's EVM context.
132 pub const fn block_number(&self) -> Option<u64> {
133 self.block_number
134 }
135
136 /// Base fee installed in the snapshot's EVM context.
137 pub const fn basefee(&self) -> Option<u64> {
138 self.basefee
139 }
140
141 /// Block beneficiary installed in the snapshot's EVM context.
142 pub const fn coinbase(&self) -> Option<Address> {
143 self.coinbase
144 }
145
146 /// PREVRANDAO value installed in the snapshot's EVM context.
147 pub const fn prevrandao(&self) -> Option<B256> {
148 self.prevrandao
149 }
150
151 /// Block gas limit installed in the snapshot's EVM context.
152 pub const fn gas_limit(&self) -> Option<u64> {
153 self.gas_limit
154 }
155
156 /// Timestamp installed in the snapshot's EVM context.
157 pub const fn timestamp(&self) -> Option<u64> {
158 self.timestamp
159 }
160
161 /// Enumerate account, code, explicit storage, and block-hash entries held by
162 /// this immutable snapshot.
163 ///
164 /// Accounts already proven absent are included because their `None` result
165 /// is locally authoritative. Storage entries implied to be zero by a
166 /// `StorageCleared` account are not enumerable; use
167 /// [`missing_read_set`](Self::missing_read_set) when checking a concrete
168 /// required set.
169 pub fn resident_read_set(&self) -> StorageAccessList {
170 let mut resident = StorageAccessList::default();
171 resident.accounts.extend(self.base.accounts.keys().copied());
172 resident
173 .accounts
174 .extend(self.overlay_accounts.keys().copied());
175 resident
176 .accounts
177 .extend(self.accounts_not_existing.iter().copied());
178 resident
179 .code_hashes
180 .extend(self.base.code_by_hash.keys().copied());
181 resident
182 .code_hashes
183 .extend(self.overlay_code_by_hash.keys().copied());
184 for (address, slots) in &self.base.storage {
185 resident
186 .slots
187 .extend(slots.keys().copied().map(|slot| (*address, slot)));
188 }
189 for (address, slots) in &self.overlay_storage {
190 resident
191 .slots
192 .extend(slots.keys().copied().map(|slot| (*address, slot)));
193 }
194 resident
195 .block_numbers
196 .extend(self.block_hashes.keys().copied());
197 resident
198 }
199
200 /// Return the concrete subset of `required` this snapshot cannot resolve
201 /// without an external database.
202 pub fn missing_read_set(&self, required: &StorageAccessList) -> StorageAccessList {
203 StorageAccessList {
204 accounts: required
205 .accounts
206 .iter()
207 .copied()
208 .filter(|address| {
209 !self.accounts_not_existing.contains(address)
210 && self.account_info(*address).is_none()
211 })
212 .collect(),
213 code_hashes: required
214 .code_hashes
215 .iter()
216 .copied()
217 .filter(|hash| self.code(*hash).is_none())
218 .collect(),
219 slots: required
220 .slots
221 .iter()
222 .copied()
223 .filter(|(address, slot)| self.storage_value(*address, *slot).is_none())
224 .collect(),
225 block_numbers: required
226 .block_numbers
227 .iter()
228 .copied()
229 .filter(|number| !self.block_hashes.contains_key(number))
230 .collect(),
231 }
232 }
233
234 /// Account info as the EVM sees it: overlay (layer 1) wins, else the base
235 /// (layer 2), else `None`.
236 ///
237 /// Returns `None` for a `NotExisting` account without consulting the base,
238 /// mirroring revm `DbAccount::info()` and the live `EvmCache` account read.
239 pub(crate) fn account_info(&self, address: Address) -> Option<&AccountInfo> {
240 if self.accounts_not_existing.contains(&address) {
241 return None;
242 }
243 self.overlay_accounts
244 .get(&address)
245 .or_else(|| self.base.accounts.get(&address))
246 }
247
248 /// Return the snapshot's value for a storage slot, mirroring the live read.
249 ///
250 /// Used by the freshness validator to compare a freshly-fetched value against
251 /// the value the snapshot was built from. Resolution matches
252 /// [`EvmCache::cached_storage_value`](super::EvmCache::cached_storage_value)
253 /// over the two tiers: an overlay (layer-1) slot wins; for a cleared account
254 /// an absent overlay slot returns `Some(ZERO)` (its storage is locally
255 /// complete — the base is never consulted); otherwise the base (layer-2) slot
256 /// is returned, or `None` if neither tier has seen the slot.
257 pub fn storage_value(&self, address: Address, slot: U256) -> Option<U256> {
258 if let Some(account_storage) = self.overlay_storage.get(&address) {
259 if let Some(value) = account_storage.get(&slot) {
260 return Some(*value);
261 }
262 // A StorageCleared / NotExisting account's storage is locally complete:
263 // an absent slot reads ZERO and never falls through to the base.
264 if self.storage_cleared.contains(&address) {
265 return Some(U256::ZERO);
266 }
267 // Non-cleared overlay account: fall through to the base below.
268 }
269 self.base
270 .storage
271 .get(&address)
272 .and_then(|s| s.get(&slot).copied())
273 }
274
275 /// Bytecode by `code_hash`: overlay (layer 1) wins, else the base (layer 2).
276 pub(crate) fn code(&self, code_hash: B256) -> Option<&Bytecode> {
277 self.overlay_code_by_hash
278 .get(&code_hash)
279 .or_else(|| self.base.code_by_hash.get(&code_hash))
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 /// Build an empty `Arc<BaseState>` for snapshot literals in tests.
288 fn empty_base() -> Arc<BaseState> {
289 Arc::new(BaseState {
290 accounts: HashMap::new(),
291 storage: HashMap::new(),
292 code_by_hash: HashMap::new(),
293 })
294 }
295
296 #[test]
297 fn test_snapshot_is_send_sync() {
298 fn assert_send_sync<T: Send + Sync>() {}
299 assert_send_sync::<EvmSnapshot>();
300 assert_send_sync::<Arc<EvmSnapshot>>();
301 }
302
303 #[test]
304 fn test_empty_snapshot() {
305 let snap = EvmSnapshot {
306 base: empty_base(),
307 overlay_accounts: HashMap::new(),
308 overlay_storage: HashMap::new(),
309 overlay_code_by_hash: HashMap::new(),
310 storage_cleared: HashSet::new(),
311 accounts_not_existing: HashSet::new(),
312 block_hashes: HashMap::new(),
313 block_number: Some(100),
314 basefee: Some(1000),
315 coinbase: None,
316 prevrandao: None,
317 gas_limit: None,
318 chain_id: 42161,
319 timestamp: None,
320 spec_id: SpecId::CANCUN,
321 shared_memory_capacity: 64_000,
322 };
323 assert_eq!(snap.chain_id, 42161);
324 assert_eq!(snap.block_number, Some(100));
325 }
326}