Skip to main content

anvil/eth/backend/mem/
in_memory_db.rs

1//! The in memory DB
2
3use crate::{
4    eth::backend::db::{
5        BLOCKHASH_HISTORY, Db, MaybeForkedDatabase, MaybeFullDatabase, SerializableAccountRecord,
6        SerializableBlock, SerializableHistoricalStates, SerializableState,
7        SerializableTransaction, StateDb, cache_block_hash,
8    },
9    mem::state::{StateRootCache, state_root},
10};
11use alloy_primitives::{
12    Address, B256, U256,
13    map::{AddressMap, B256Map, HashSet},
14};
15use alloy_rpc_types::BlockId;
16use foundry_evm::backend::{BlockchainDb, DatabaseError, DatabaseResult, StateSnapshot};
17use imbl::HashMap as PersistentMap;
18use parking_lot::Mutex;
19use revm::{
20    Database, DatabaseCommit,
21    bytecode::Bytecode,
22    context::BlockEnv,
23    database::{AccountState, DatabaseRef, DbAccount},
24    state::{Account, AccountInfo},
25};
26use std::sync::OnceLock;
27
28// reexport for convenience
29pub use foundry_evm::backend::MemDb;
30use foundry_evm::backend::RevertStateSnapshotAction;
31
32/// An in-memory database that incrementally maintains Anvil's mined-block state root.
33#[derive(Debug, Default)]
34pub struct StateRootDb {
35    inner: MemDb,
36    state_root: Mutex<StateRootCache>,
37    history: Mutex<HistoricalStateCache>,
38    /// Live cache head used to make sequential block-hash insertion constant-time.
39    block_hash_head: Option<U256>,
40}
41
42impl StateRootDb {
43    /// Creates a new database, optionally tracking the state used by block-history snapshots.
44    ///
45    /// Anvil disables history tracking when state history is pruned, since historical snapshots
46    /// are never taken in that mode and the recorded dirty sets would accumulate without ever
47    /// being drained. With tracking disabled, [`Db::current_state`] still returns a correct,
48    /// freshly built snapshot.
49    pub fn new(track_history: bool) -> Self {
50        Self {
51            history: Mutex::new(HistoricalStateCache {
52                disabled: !track_history,
53                ..Default::default()
54            }),
55            ..Default::default()
56        }
57    }
58
59    fn normalize_block_hashes(&mut self) {
60        let block_hashes = &mut self.inner.inner.cache.block_hashes;
61        let Some(head) = block_hashes.keys().copied().max() else {
62            self.block_hash_head = None;
63            return;
64        };
65        let min_number = head.saturating_sub(U256::from(BLOCKHASH_HISTORY));
66        block_hashes.retain(|cached, _| *cached >= min_number && *cached <= head);
67        self.block_hash_head = Some(head);
68    }
69}
70
71/// Incrementally maintained, structurally shared state used by block-history snapshots.
72#[derive(Debug, Default)]
73struct HistoricalStateCache {
74    state: Option<PersistentStateDb>,
75    dirty: AddressMap<DirtyHistoricalAccount>,
76    /// Disables recording and snapshot caching; set when historical snapshots are never taken.
77    disabled: bool,
78}
79
80#[derive(Debug, Default)]
81struct DirtyHistoricalAccount {
82    storage: HashSet<U256>,
83    reset_storage: bool,
84}
85
86impl HistoricalStateCache {
87    fn record_changes(&mut self, changes: &AddressMap<Account>) {
88        if self.disabled {
89            return;
90        }
91        for (address, account) in changes {
92            if !account.is_touched() {
93                continue;
94            }
95
96            let dirty = self.dirty.entry(*address).or_default();
97            dirty.reset_storage |= account.is_created() || account.is_selfdestructed();
98            dirty.storage.extend(account.changed_storage_slots().map(|(slot, _)| *slot));
99        }
100    }
101
102    fn record_account(&mut self, address: Address) {
103        if self.disabled {
104            return;
105        }
106        self.dirty.entry(address).or_default();
107    }
108
109    fn record_storage(&mut self, address: Address, slot: U256) {
110        if self.disabled {
111            return;
112        }
113        self.dirty.entry(address).or_default().storage.insert(slot);
114    }
115
116    fn record_block_hash(&mut self, number: U256, hash: B256, is_next: bool) {
117        if self.disabled {
118            return;
119        }
120        let Some(state) = &mut self.state else { return };
121        if is_next {
122            let min_number = number.saturating_sub(U256::from(BLOCKHASH_HISTORY));
123            if min_number > U256::ZERO {
124                state.block_hashes.remove(&(min_number - U256::from(1)));
125            }
126            state.block_hashes.insert(number, hash);
127            return;
128        }
129
130        let head = state.block_hashes.keys().copied().max().map_or(number, |head| head.max(number));
131        let min_number = head.saturating_sub(U256::from(BLOCKHASH_HISTORY));
132        state.block_hashes.retain(|cached, _| *cached >= min_number && *cached <= head);
133        if number >= min_number {
134            state.block_hashes.insert(number, hash);
135        }
136    }
137
138    fn invalidate(&mut self) {
139        self.state = None;
140        self.dirty.clear();
141    }
142
143    fn snapshot(&mut self, db: &MemDb) -> PersistentStateDb {
144        if self.disabled {
145            return PersistentStateDb::from_mem_db(db);
146        }
147        let Some(state) = &mut self.state else {
148            let state = PersistentStateDb::from_mem_db(db);
149            self.state = Some(state.clone());
150            self.dirty.clear();
151            return state;
152        };
153
154        for (address, dirty) in std::mem::take(&mut self.dirty) {
155            let Some(account) = db.inner.cache.accounts.get(&address) else {
156                state.accounts.remove(&address);
157                continue;
158            };
159
160            let mut storage = if dirty.reset_storage {
161                account.storage.iter().map(|(slot, value)| (*slot, *value)).collect()
162            } else {
163                state
164                    .accounts
165                    .get(&address)
166                    .map(|account| account.storage.clone())
167                    .unwrap_or_default()
168            };
169            if !dirty.reset_storage {
170                for slot in dirty.storage {
171                    if let Some(value) = account.storage.get(&slot) {
172                        storage.insert(slot, *value);
173                    } else {
174                        storage.remove(&slot);
175                    }
176                }
177            }
178
179            let info = account_info_with_code(&account.info, &db.inner.cache.contracts);
180            if let Some(code) = &info.code {
181                state.contracts.insert(info.code_hash, code.clone());
182            }
183            state.accounts.insert(
184                address,
185                PersistentAccount { info, account_state: account.account_state.clone(), storage },
186            );
187        }
188
189        state.full = OnceLock::new();
190        state.clone()
191    }
192}
193
194#[derive(Clone, Debug, Default)]
195struct PersistentAccount {
196    info: AccountInfo,
197    account_state: AccountState,
198    storage: PersistentMap<U256, U256>,
199}
200
201/// A read-only historical state whose maps are cheap structural-sharing clones.
202#[derive(Clone, Debug, Default)]
203struct PersistentStateDb {
204    accounts: PersistentMap<Address, PersistentAccount>,
205    contracts: PersistentMap<B256, Bytecode>,
206    block_hashes: PersistentMap<U256, B256>,
207    #[allow(clippy::type_complexity)]
208    full: OnceLock<AddressMap<DbAccount>>,
209}
210
211impl PersistentStateDb {
212    fn from_mem_db(db: &MemDb) -> Self {
213        let contracts = db
214            .inner
215            .cache
216            .contracts
217            .iter()
218            .map(|(hash, code)| (*hash, code.clone()))
219            .collect::<PersistentMap<_, _>>();
220        let accounts = db
221            .inner
222            .cache
223            .accounts
224            .iter()
225            .map(|(address, account)| {
226                (
227                    *address,
228                    PersistentAccount {
229                        info: account_info_with_code(&account.info, &db.inner.cache.contracts),
230                        account_state: account.account_state.clone(),
231                        storage: account
232                            .storage
233                            .iter()
234                            .map(|(slot, value)| (*slot, *value))
235                            .collect(),
236                    },
237                )
238            })
239            .collect();
240        let block_hashes =
241            db.inner.cache.block_hashes.iter().map(|(number, hash)| (*number, *hash)).collect();
242        Self { accounts, contracts, block_hashes, full: OnceLock::new() }
243    }
244
245    fn state_snapshot(&self) -> StateSnapshot {
246        StateSnapshot {
247            accounts: self
248                .accounts
249                .iter()
250                .map(|(address, account)| (*address, account.info.clone()))
251                .collect(),
252            storage: self
253                .accounts
254                .iter()
255                .map(|(address, account)| {
256                    (
257                        *address,
258                        account.storage.iter().map(|(slot, value)| (*slot, *value)).collect(),
259                    )
260                })
261                .collect(),
262            block_hashes: self.block_hashes.iter().map(|(number, hash)| (*number, *hash)).collect(),
263        }
264    }
265
266    fn full_db(&self) -> AddressMap<DbAccount> {
267        self.accounts
268            .iter()
269            .map(|(address, account)| {
270                (
271                    *address,
272                    DbAccount {
273                        info: account.info.clone(),
274                        account_state: account.account_state.clone(),
275                        storage: account
276                            .storage
277                            .iter()
278                            .map(|(slot, value)| (*slot, *value))
279                            .collect(),
280                    },
281                )
282            })
283            .collect()
284    }
285}
286
287fn account_info_with_code(info: &AccountInfo, contracts: &B256Map<Bytecode>) -> AccountInfo {
288    let mut info = info.clone();
289    if info.code.is_none() {
290        info.code = contracts.get(&info.code_hash).cloned();
291    }
292    info
293}
294
295impl DatabaseRef for PersistentStateDb {
296    type Error = DatabaseError;
297
298    fn basic_ref(&self, address: Address) -> DatabaseResult<Option<AccountInfo>> {
299        Ok(match self.accounts.get(&address) {
300            Some(account) if account.account_state == AccountState::NotExisting => None,
301            Some(account) => Some(account.info.clone()),
302            None => Some(AccountInfo::default()),
303        })
304    }
305
306    fn code_by_hash_ref(&self, code_hash: B256) -> DatabaseResult<Bytecode> {
307        Ok(self.contracts.get(&code_hash).cloned().unwrap_or_default())
308    }
309
310    fn storage_ref(&self, address: Address, index: U256) -> DatabaseResult<U256> {
311        Ok(self
312            .accounts
313            .get(&address)
314            .and_then(|account| account.storage.get(&index).copied())
315            .unwrap_or_default())
316    }
317
318    fn block_hash_ref(&self, number: u64) -> DatabaseResult<B256> {
319        Ok(self.block_hashes.get(&U256::from(number)).copied().unwrap_or_default())
320    }
321}
322
323impl MaybeFullDatabase for PersistentStateDb {
324    fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
325        Some(self.full.get_or_init(|| self.full_db()))
326    }
327
328    fn is_persistent(&self) -> bool {
329        true
330    }
331
332    fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
333        let snapshot = self.state_snapshot();
334        self.clear();
335        snapshot
336    }
337
338    fn read_as_state_snapshot(&self) -> StateSnapshot {
339        self.state_snapshot()
340    }
341
342    fn clear(&mut self) {
343        *self = Self::default();
344    }
345
346    fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
347        let StateSnapshot { accounts, mut storage, block_hashes } = snapshot;
348        let mut contracts = PersistentMap::new();
349        let accounts = accounts
350            .into_iter()
351            .map(|(address, info)| {
352                if let Some(code) = &info.code {
353                    contracts.insert(info.code_hash, code.clone());
354                }
355                let storage = storage
356                    .remove(&address)
357                    .unwrap_or_default()
358                    .into_iter()
359                    .collect::<PersistentMap<_, _>>();
360                (address, PersistentAccount { info, account_state: AccountState::None, storage })
361            })
362            .collect();
363        let block_hashes = block_hashes.into_iter().collect();
364        *self = Self { accounts, contracts, block_hashes, full: OnceLock::new() };
365    }
366}
367
368impl DatabaseRef for StateRootDb {
369    type Error = <MemDb as DatabaseRef>::Error;
370
371    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
372        self.inner.basic_ref(address)
373    }
374
375    fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
376        self.inner.code_by_hash_ref(code_hash)
377    }
378
379    fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
380        self.inner.storage_ref(address, index)
381    }
382
383    fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
384        self.inner.block_hash_ref(number)
385    }
386}
387
388impl Database for StateRootDb {
389    type Error = <MemDb as Database>::Error;
390
391    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
392        self.state_root.get_mut().record_account(address);
393        self.history.get_mut().record_account(address);
394        self.inner.basic(address)
395    }
396
397    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
398        self.inner.code_by_hash(code_hash)
399    }
400
401    fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error> {
402        self.state_root.get_mut().record_storage(address, index);
403        self.history.get_mut().record_storage(address, index);
404        self.inner.storage(address, index)
405    }
406
407    fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
408        self.inner.block_hash(number)
409    }
410}
411
412impl DatabaseCommit for StateRootDb {
413    fn commit(&mut self, changes: revm::state::EvmState) {
414        self.state_root.get_mut().record_changes(&changes);
415        self.history.get_mut().record_changes(&changes);
416        self.inner.commit(changes);
417    }
418}
419
420impl Db for StateRootDb {
421    fn insert_account(&mut self, address: Address, account: AccountInfo) {
422        self.state_root.get_mut().record_account(address);
423        self.history.get_mut().record_account(address);
424        Db::insert_account(&mut self.inner, address, account);
425    }
426
427    fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
428        let storage_slot = slot.into();
429        self.state_root.get_mut().record_storage(address, storage_slot);
430        self.history.get_mut().record_storage(address, storage_slot);
431        Db::set_storage_at(&mut self.inner, address, slot, val)
432    }
433
434    fn insert_block_hash(&mut self, number: U256, hash: B256) {
435        let is_next =
436            self.block_hash_head.is_some_and(|head| number == head.saturating_add(U256::from(1)));
437        if is_next {
438            let min_number = number.saturating_sub(U256::from(BLOCKHASH_HISTORY));
439            if min_number > U256::ZERO {
440                self.inner.inner.cache.block_hashes.remove(&(min_number - U256::from(1)));
441            }
442            self.inner.inner.cache.block_hashes.insert(number, hash);
443            self.block_hash_head = Some(number);
444        } else {
445            self.block_hash_head =
446                Some(cache_block_hash(&mut self.inner.inner.cache.block_hashes, number, hash));
447        }
448        self.history.get_mut().record_block_hash(number, hash, is_next);
449    }
450
451    fn set_block_hashes(&mut self, block_hashes: Vec<(U256, B256)>) {
452        Db::set_block_hashes(&mut self.inner, block_hashes);
453        self.normalize_block_hashes();
454        self.history.get_mut().invalidate();
455    }
456
457    fn dump_state(
458        &self,
459        at: BlockEnv,
460        best_number: u64,
461        blocks: Vec<SerializableBlock>,
462        transactions: Vec<SerializableTransaction>,
463        historical_states: Option<SerializableHistoricalStates>,
464    ) -> DatabaseResult<Option<SerializableState>> {
465        Db::dump_state(&self.inner, at, best_number, blocks, transactions, historical_states)
466    }
467
468    fn snapshot_state(&mut self) -> U256 {
469        Db::snapshot_state(&mut self.inner)
470    }
471
472    fn revert_state(&mut self, id: U256, action: RevertStateSnapshotAction) -> bool {
473        let reverted = Db::revert_state(&mut self.inner, id, action);
474        if reverted {
475            self.state_root.get_mut().invalidate();
476            self.history.get_mut().invalidate();
477            self.block_hash_head = self.inner.inner.cache.block_hashes.keys().copied().max();
478        }
479        reverted
480    }
481
482    fn maybe_state_root(&self) -> Option<B256> {
483        Some(self.state_root.lock().root(&self.inner.inner.cache.accounts))
484    }
485
486    fn current_state(&self) -> StateDb {
487        StateDb::new(self.history.lock().snapshot(&self.inner))
488    }
489}
490
491impl MaybeFullDatabase for StateRootDb {
492    fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
493        MaybeFullDatabase::maybe_as_full_db(&self.inner)
494    }
495
496    fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
497        self.state_root.get_mut().invalidate();
498        self.history.get_mut().invalidate();
499        self.block_hash_head = None;
500        MaybeFullDatabase::clear_into_state_snapshot(&mut self.inner)
501    }
502
503    fn read_as_state_snapshot(&self) -> StateSnapshot {
504        MaybeFullDatabase::read_as_state_snapshot(&self.inner)
505    }
506
507    fn clear(&mut self) {
508        self.state_root.get_mut().invalidate();
509        self.history.get_mut().invalidate();
510        self.block_hash_head = None;
511        MaybeFullDatabase::clear(&mut self.inner)
512    }
513
514    fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
515        MaybeFullDatabase::init_from_state_snapshot(&mut self.inner, snapshot);
516        self.state_root.get_mut().invalidate();
517        self.history.get_mut().invalidate();
518        self.normalize_block_hashes();
519    }
520}
521
522impl MaybeForkedDatabase for StateRootDb {
523    fn maybe_reset(&mut self, urls: Vec<String>, block_number: BlockId) -> Result<(), String> {
524        self.inner.maybe_reset(urls, block_number)
525    }
526
527    fn maybe_flush_cache(&self) -> Result<(), String> {
528        self.inner.maybe_flush_cache()
529    }
530
531    fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
532        self.inner.maybe_inner()
533    }
534}
535
536impl Db for MemDb {
537    fn insert_account(&mut self, address: Address, account: AccountInfo) {
538        self.inner.insert_account_info(address, account)
539    }
540
541    fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
542        self.inner.insert_account_storage(address, slot.into(), val.into())
543    }
544
545    fn insert_block_hash(&mut self, number: U256, hash: B256) {
546        cache_block_hash(&mut self.inner.cache.block_hashes, number, hash);
547    }
548
549    fn set_block_hashes(&mut self, block_hashes: Vec<(U256, B256)>) {
550        self.inner.cache.block_hashes = block_hashes.into_iter().collect();
551    }
552
553    fn dump_state(
554        &self,
555        at: BlockEnv,
556        best_number: u64,
557        blocks: Vec<SerializableBlock>,
558        transactions: Vec<SerializableTransaction>,
559        historical_states: Option<SerializableHistoricalStates>,
560    ) -> DatabaseResult<Option<SerializableState>> {
561        let accounts = self
562            .inner
563            .cache
564            .accounts
565            .clone()
566            .into_iter()
567            .map(|(k, v)| -> DatabaseResult<_> {
568                let code = if let Some(code) = v.info.code {
569                    code
570                } else {
571                    self.inner.code_by_hash_ref(v.info.code_hash)?
572                };
573                Ok((
574                    k,
575                    SerializableAccountRecord {
576                        nonce: v.info.nonce,
577                        balance: v.info.balance,
578                        code: code.original_bytes(),
579                        storage: v.storage.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
580                    },
581                ))
582            })
583            .collect::<Result<_, _>>()?;
584
585        Ok(Some(SerializableState {
586            block: Some(at),
587            accounts,
588            best_block_number: Some(best_number),
589            blocks,
590            transactions,
591            historical_states,
592        }))
593    }
594
595    /// Creates a new snapshot
596    fn snapshot_state(&mut self) -> U256 {
597        let id = self.state_snapshots.insert(self.inner.clone());
598        trace!(target: "backend::memdb", "Created new state snapshot {}", id);
599        id
600    }
601
602    fn revert_state(&mut self, id: U256, action: RevertStateSnapshotAction) -> bool {
603        if let Some(state_snapshot) = self.state_snapshots.remove(id) {
604            if action.is_keep() {
605                self.state_snapshots.insert_at(state_snapshot.clone(), id);
606            }
607            self.inner = state_snapshot;
608            trace!(target: "backend::memdb", "Reverted state snapshot {}", id);
609            true
610        } else {
611            warn!(target: "backend::memdb", "No state snapshot to revert for {}", id);
612            false
613        }
614    }
615
616    fn maybe_state_root(&self) -> Option<B256> {
617        Some(state_root(&self.inner.cache.accounts))
618    }
619
620    fn current_state(&self) -> StateDb {
621        StateDb::new(Self { inner: self.inner.clone(), ..Default::default() })
622    }
623}
624
625impl MaybeFullDatabase for MemDb {
626    fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
627        Some(&self.inner.cache.accounts)
628    }
629
630    fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
631        self.inner.clear_into_state_snapshot()
632    }
633
634    fn read_as_state_snapshot(&self) -> StateSnapshot {
635        self.inner.read_as_state_snapshot()
636    }
637
638    fn clear(&mut self) {
639        self.inner.clear();
640    }
641
642    fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
643        self.inner.init_from_state_snapshot(snapshot)
644    }
645}
646
647impl MaybeForkedDatabase for MemDb {
648    fn maybe_reset(&mut self, _urls: Vec<String>, _block_number: BlockId) -> Result<(), String> {
649        Err("not supported".to_string())
650    }
651
652    fn maybe_flush_cache(&self) -> Result<(), String> {
653        Err("not supported".to_string())
654    }
655
656    fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
657        Err("not supported".to_string())
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use super::*;
664    use alloy_primitives::{Bytes, address};
665    use revm::primitives::KECCAK_EMPTY;
666    use std::collections::BTreeMap;
667
668    // verifies that all substantial aspects of a loaded account remain the same after an account
669    // is dumped and reloaded
670    #[test]
671    fn test_dump_reload_cycle() {
672        let test_addr: Address = address!("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
673
674        let mut dump_db = MemDb::default();
675
676        let contract_code = Bytecode::new_raw(Bytes::from("fake contract code"));
677        dump_db.insert_account(
678            test_addr,
679            AccountInfo {
680                balance: U256::from(123456),
681                code_hash: KECCAK_EMPTY,
682                code: Some(contract_code.clone()),
683                nonce: 1234,
684                account_id: None,
685            },
686        );
687        dump_db
688            .set_storage_at(test_addr, U256::from(1234567).into(), U256::from(1).into())
689            .unwrap();
690
691        // blocks dumping/loading tested in storage.rs
692        let state = dump_db
693            .dump_state(Default::default(), 0, Vec::new(), Vec::new(), Default::default())
694            .unwrap()
695            .unwrap();
696
697        let mut load_db = MemDb::default();
698
699        load_db.load_state(state).unwrap();
700
701        let loaded_account = load_db.basic_ref(test_addr).unwrap().unwrap();
702
703        assert_eq!(loaded_account.balance, U256::from(123456));
704        assert_eq!(load_db.code_by_hash_ref(loaded_account.code_hash).unwrap(), contract_code);
705        assert_eq!(loaded_account.nonce, 1234);
706        assert_eq!(load_db.storage_ref(test_addr, U256::from(1234567)).unwrap(), U256::from(1));
707    }
708
709    // verifies that multiple accounts can be loaded at a time, and storage is merged within those
710    // accounts as well.
711    #[test]
712    fn test_load_state_merge() {
713        let test_addr: Address = address!("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
714        let test_addr2: Address = address!("0x70997970c51812dc3a010c7d01b50e0d17dc79c8");
715
716        let contract_code = Bytecode::new_raw(Bytes::from("fake contract code"));
717
718        let mut db = MemDb::default();
719
720        db.insert_account(
721            test_addr,
722            AccountInfo {
723                balance: U256::from(123456),
724                code_hash: KECCAK_EMPTY,
725                code: Some(contract_code.clone()),
726                nonce: 1234,
727                account_id: None,
728            },
729        );
730
731        db.set_storage_at(test_addr, U256::from(1234567).into(), U256::from(1).into()).unwrap();
732        db.set_storage_at(test_addr, U256::from(1234568).into(), U256::from(2).into()).unwrap();
733
734        let mut new_state = SerializableState::default();
735
736        new_state.accounts.insert(
737            test_addr2,
738            SerializableAccountRecord {
739                balance: Default::default(),
740                code: Default::default(),
741                nonce: 1,
742                storage: Default::default(),
743            },
744        );
745
746        let mut new_storage = BTreeMap::default();
747        new_storage.insert(U256::from(1234568).into(), U256::from(5).into());
748
749        new_state.accounts.insert(
750            test_addr,
751            SerializableAccountRecord {
752                balance: U256::from(100100),
753                code: contract_code.bytes()[..contract_code.len()].to_vec().into(),
754                nonce: 100,
755                storage: new_storage,
756            },
757        );
758
759        db.load_state(new_state).unwrap();
760
761        let loaded_account = db.basic_ref(test_addr).unwrap().unwrap();
762        let loaded_account2 = db.basic_ref(test_addr2).unwrap().unwrap();
763
764        assert_eq!(loaded_account2.nonce, 1);
765
766        assert_eq!(loaded_account.balance, U256::from(100100));
767        assert_eq!(db.code_by_hash_ref(loaded_account.code_hash).unwrap(), contract_code);
768        assert_eq!(loaded_account.nonce, 1234);
769        assert_eq!(db.storage_ref(test_addr, U256::from(1234567)).unwrap(), U256::from(1));
770        assert_eq!(db.storage_ref(test_addr, U256::from(1234568)).unwrap(), U256::from(5));
771    }
772
773    #[test]
774    fn incremental_state_root_matches_full_rebuild() {
775        let address = address!("0000000000000000000000000000000000002935");
776        let mut db = StateRootDb::default();
777        db.insert_account(address, AccountInfo::default());
778
779        assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
780
781        // Model the EIP-2935 history contract filling one new ring-buffer slot per block.
782        for slot in 0..1_024 {
783            db.set_storage_at(address, U256::from(slot).into(), B256::from(U256::from(slot + 1)))
784                .unwrap();
785            let _ = db.maybe_state_root().unwrap();
786        }
787
788        db.set_balance(address, U256::from(42)).unwrap();
789        db.set_storage_at(address, U256::from(7).into(), B256::ZERO).unwrap();
790        db.insert_account(Address::with_last_byte(1), AccountInfo::from_balance(U256::from(1)));
791        assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
792
793        let snapshot = db.snapshot_state();
794        db.set_balance(address, U256::from(43)).unwrap();
795        assert!(db.revert_state(snapshot, RevertStateSnapshotAction::RevertRemove));
796        assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
797    }
798
799    #[test]
800    fn evm_block_hash_cache_is_bounded() {
801        let mut db = StateRootDb::default();
802        for number in 0..1_024 {
803            db.insert_block_hash(U256::from(number), B256::from(U256::from(number)));
804        }
805
806        let block_hashes = &db.inner.inner.cache.block_hashes;
807        assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
808        assert!(!block_hashes.contains_key(&U256::from(766)));
809        assert!(block_hashes.contains_key(&U256::from(767)));
810        assert!(block_hashes.contains_key(&U256::from(768)));
811        assert!(block_hashes.contains_key(&U256::from(1_023)));
812
813        let snapshot = db.snapshot_state();
814        db.insert_block_hash(U256::from(1_024), B256::from(U256::from(1_024)));
815        assert!(db.revert_state(snapshot, RevertStateSnapshotAction::RevertRemove));
816        db.insert_block_hash(U256::from(1_024), B256::from(U256::from(1_024)));
817
818        let block_hashes = &db.inner.inner.cache.block_hashes;
819        assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
820        assert!(!block_hashes.contains_key(&U256::from(767)));
821        assert!(block_hashes.contains_key(&U256::from(768)));
822        assert!(block_hashes.contains_key(&U256::from(1_024)));
823    }
824
825    #[test]
826    fn oversized_seeded_block_hash_caches_are_normalized() {
827        let block_hashes = (0..=1_000)
828            .map(|number| (U256::from(number), B256::from(U256::from(number))))
829            .collect::<Vec<_>>();
830
831        let mut db = StateRootDb::default();
832        db.set_block_hashes(block_hashes.clone());
833        assert_block_hash_window(&db, 744, 1_000);
834        db.insert_block_hash(U256::from(1_001), B256::from(U256::from(1_001)));
835        assert_block_hash_window(&db, 745, 1_001);
836
837        let mut snapshot_source = MemDb::default();
838        snapshot_source.set_block_hashes(block_hashes);
839        let snapshot = snapshot_source.read_as_state_snapshot();
840        let mut restored = StateRootDb::default();
841        restored.init_from_state_snapshot(snapshot);
842        assert_block_hash_window(&restored, 744, 1_000);
843        restored.insert_block_hash(U256::from(1_001), B256::from(U256::from(1_001)));
844        assert_block_hash_window(&restored, 745, 1_001);
845    }
846
847    fn assert_block_hash_window(db: &StateRootDb, min: u64, head: u64) {
848        let block_hashes = &db.inner.inner.cache.block_hashes;
849        assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
850        assert!(
851            block_hashes
852                .keys()
853                .all(|number| *number >= U256::from(min) && *number <= U256::from(head))
854        );
855        assert!(block_hashes.contains_key(&U256::from(min)));
856        assert!(block_hashes.contains_key(&U256::from(head)));
857    }
858
859    #[test]
860    fn evm_block_hash_cache_is_bounded_across_block_number_jumps() {
861        let mut db = StateRootDb::default();
862        // Initialize the persistent historical-state cache as well as the live EVM cache.
863        db.current_state();
864
865        for number in [0, 516, 400] {
866            db.insert_block_hash(U256::from(number), B256::from(U256::from(number)));
867        }
868
869        // An out-of-order insertion within the active window must not discard the current head.
870        let block_hashes = &db.inner.inner.cache.block_hashes;
871        assert_eq!(block_hashes.len(), 2);
872        assert!(block_hashes.contains_key(&U256::from(400)));
873        assert!(block_hashes.contains_key(&U256::from(516)));
874
875        db.insert_block_hash(U256::from(774), B256::from(U256::from(774)));
876
877        let block_hashes = &db.inner.inner.cache.block_hashes;
878        assert_eq!(block_hashes.len(), 1);
879        assert!(block_hashes.contains_key(&U256::from(774)));
880
881        let historical = db.history.get_mut().state.as_ref().unwrap();
882        assert_eq!(historical.block_hashes.len(), 1);
883        assert!(historical.block_hashes.contains_key(&U256::from(774)));
884    }
885
886    #[test]
887    fn historical_states_are_persistent_and_isolated() {
888        let address = address!("0000000000000000000000000000000000002935");
889        let slot = U256::from(1);
890        let mut db = StateRootDb::default();
891        db.insert_account(address, AccountInfo::from_balance(U256::from(1)));
892
893        let first = db.current_state();
894        assert!(first.is_persistent());
895
896        db.set_balance(address, U256::from(2)).unwrap();
897        db.set_storage_at(address, slot.into(), B256::from(U256::from(3))).unwrap();
898        let second = db.current_state();
899
900        assert_eq!(first.basic_ref(address).unwrap().unwrap().balance, U256::from(1));
901        assert_eq!(first.storage_ref(address, slot).unwrap(), U256::ZERO);
902        assert_eq!(second.basic_ref(address).unwrap().unwrap().balance, U256::from(2));
903        assert_eq!(second.storage_ref(address, slot).unwrap(), U256::from(3));
904    }
905
906    #[test]
907    fn historical_missing_accounts_match_live_state() {
908        let address = Address::with_last_byte(1);
909        let db = StateRootDb::default();
910        let historical = db.current_state();
911
912        let live_account = db.basic_ref(address).unwrap();
913        assert_eq!(live_account, Some(AccountInfo::default()));
914        assert_eq!(historical.basic_ref(address).unwrap(), live_account);
915
916        let mut persistent = PersistentStateDb::default();
917        persistent.accounts.insert(
918            address,
919            PersistentAccount { account_state: AccountState::NotExisting, ..Default::default() },
920        );
921        assert_eq!(persistent.basic_ref(address).unwrap(), None);
922    }
923
924    #[test]
925    fn disabled_history_tracking_records_nothing() {
926        let address = address!("0000000000000000000000000000000000002935");
927        let slot = U256::from(1);
928        let mut db = StateRootDb::new(false);
929
930        db.insert_account(address, AccountInfo::from_balance(U256::from(1)));
931        db.set_storage_at(address, slot.into(), B256::from(U256::from(2))).unwrap();
932        db.basic(address).unwrap();
933        db.storage(address, slot).unwrap();
934        db.maybe_state_root().unwrap();
935
936        assert!(db.history.get_mut().dirty.is_empty());
937        assert!(db.history.get_mut().state.is_none());
938
939        // `current_state` must still produce a correct snapshot without caching it.
940        let historical = db.current_state();
941        assert_eq!(historical.basic_ref(address).unwrap().unwrap().balance, U256::from(1));
942        assert_eq!(historical.storage_ref(address, slot).unwrap(), U256::from(2));
943        assert!(db.history.get_mut().state.is_none());
944    }
945}