Skip to main content

anvil/eth/backend/mem/
fork_db.rs

1use crate::eth::backend::db::{
2    Db, MaybeForkedDatabase, MaybeFullDatabase, SerializableAccountRecord, SerializableBlock,
3    SerializableHistoricalStates, SerializableState, SerializableTransaction, StateDb,
4    cache_block_hash,
5};
6use alloy_network::Network;
7use alloy_primitives::{Address, B256, U256, map::AddressMap};
8use alloy_rpc_types::BlockId;
9use foundry_evm::{
10    backend::{
11        BlockchainDb, DatabaseResult, RevertStateSnapshotAction, SharedBackend, StateSnapshot,
12    },
13    fork::database::ForkDbStateSnapshot,
14};
15use revm::{
16    context::BlockEnv,
17    database::{Database, DbAccount},
18    state::AccountInfo,
19};
20
21pub use foundry_evm::fork::database::ForkedDatabase;
22
23impl<N: Network> MaybeFullDatabase for SharedBackend<N> {
24    fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
25        StateSnapshot::default()
26    }
27
28    fn read_as_state_snapshot(&self) -> StateSnapshot {
29        StateSnapshot::default()
30    }
31
32    fn clear(&mut self) {}
33
34    fn init_from_state_snapshot(&mut self, _state_snapshot: StateSnapshot) {}
35}
36
37impl<N: Network> Db for ForkedDatabase<N> {
38    fn insert_account(&mut self, address: Address, account: AccountInfo) {
39        self.database_mut().insert_account(address, account)
40    }
41
42    fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
43        // this ensures the account is loaded first
44        let _ = Database::basic(self, address)?;
45        self.database_mut().set_storage_at(address, slot, val)
46    }
47
48    fn insert_block_hash(&mut self, number: U256, hash: B256) {
49        cache_block_hash(&mut self.database_mut().cache.block_hashes, number, hash);
50    }
51
52    fn set_block_hashes(&mut self, block_hashes: Vec<(U256, B256)>) {
53        self.database_mut().cache.block_hashes = block_hashes.into_iter().collect();
54    }
55
56    fn dump_state(
57        &self,
58        at: BlockEnv,
59        best_number: u64,
60        blocks: Vec<SerializableBlock>,
61        transactions: Vec<SerializableTransaction>,
62        historical_states: Option<SerializableHistoricalStates>,
63    ) -> DatabaseResult<Option<SerializableState>> {
64        let mut db = self.database().clone();
65        let accounts = self
66            .database()
67            .cache
68            .accounts
69            .clone()
70            .into_iter()
71            .map(|(k, v)| -> DatabaseResult<_> {
72                let code = if let Some(code) = v.info.code {
73                    code
74                } else {
75                    db.code_by_hash(v.info.code_hash)?
76                };
77                Ok((
78                    k,
79                    SerializableAccountRecord {
80                        nonce: v.info.nonce,
81                        balance: v.info.balance,
82                        code: code.original_bytes(),
83                        storage: v.storage.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
84                    },
85                ))
86            })
87            .collect::<Result<_, _>>()?;
88        Ok(Some(SerializableState {
89            block: Some(at),
90            accounts,
91            best_block_number: Some(best_number),
92            blocks,
93            transactions,
94            #[cfg(feature = "monad")]
95            monad_block_participants: Default::default(),
96            #[cfg(feature = "monad")]
97            monad_block_replay_profiles: Default::default(),
98            historical_states,
99        }))
100    }
101
102    fn snapshot_state(&mut self) -> U256 {
103        self.insert_state_snapshot()
104    }
105
106    fn revert_state(&mut self, id: U256, action: RevertStateSnapshotAction) -> bool {
107        self.revert_state_snapshot(id, action)
108    }
109
110    fn current_state(&self) -> StateDb {
111        StateDb::new(self.create_state_snapshot())
112    }
113}
114
115impl<N: Network> MaybeFullDatabase for ForkedDatabase<N> {
116    fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
117        Some(&self.database().cache.accounts)
118    }
119
120    fn maybe_full_db(&self) -> Option<AddressMap<DbAccount>> {
121        None
122    }
123
124    fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
125        let db = self.inner().db();
126        let accounts = std::mem::take(&mut *db.accounts.write());
127        let storage = std::mem::take(&mut *db.storage.write());
128        let block_hashes = std::mem::take(&mut *db.block_hashes.write());
129        StateSnapshot { accounts, storage, block_hashes }
130    }
131
132    fn read_as_state_snapshot(&self) -> StateSnapshot {
133        let db = self.inner().db();
134        let accounts = db.accounts.read().clone();
135        let storage = db.storage.read().clone();
136        let block_hashes = db.block_hashes.read().clone();
137        StateSnapshot { accounts, storage, block_hashes }
138    }
139
140    fn clear(&mut self) {
141        self.flush_cache();
142        self.clear_into_state_snapshot();
143    }
144
145    fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot) {
146        let db = self.inner().db();
147        let StateSnapshot { accounts, storage, block_hashes } = state_snapshot;
148        *db.accounts.write() = accounts;
149        *db.storage.write() = storage;
150        *db.block_hashes.write() = block_hashes;
151    }
152}
153
154impl<N: Network> MaybeFullDatabase for ForkDbStateSnapshot<N> {
155    fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
156        Some(&self.local.cache.accounts)
157    }
158
159    fn maybe_full_db(&self) -> Option<AddressMap<DbAccount>> {
160        None
161    }
162
163    fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
164        let mut state_snapshot = std::mem::take(&mut self.state_snapshot);
165        let local_state_snapshot = self.local.clear_into_state_snapshot();
166        state_snapshot.accounts.extend(local_state_snapshot.accounts);
167        state_snapshot.storage.extend(local_state_snapshot.storage);
168        state_snapshot.block_hashes.extend(local_state_snapshot.block_hashes);
169        state_snapshot
170    }
171
172    fn read_as_state_snapshot(&self) -> StateSnapshot {
173        let mut state_snapshot = self.state_snapshot.clone();
174        let local_state_snapshot = self.local.read_as_state_snapshot();
175        state_snapshot.accounts.extend(local_state_snapshot.accounts);
176        state_snapshot.storage.extend(local_state_snapshot.storage);
177        state_snapshot.block_hashes.extend(local_state_snapshot.block_hashes);
178        state_snapshot
179    }
180
181    fn clear(&mut self) {
182        std::mem::take(&mut self.state_snapshot);
183        self.local.clear()
184    }
185
186    fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot) {
187        self.state_snapshot = state_snapshot;
188    }
189}
190
191impl<N: Network> MaybeForkedDatabase for ForkedDatabase<N> {
192    fn maybe_reset(&mut self, urls: Vec<String>, block_number: BlockId) -> Result<(), String> {
193        self.reset(urls, block_number)
194    }
195
196    fn maybe_flush_cache(&self) -> Result<(), String> {
197        self.flush_cache();
198        Ok(())
199    }
200
201    fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
202        Ok(self.inner())
203    }
204}