1use alloy_primitives::{
3 map::{AddressMap, B256Map, Entry, HashMap, U256Map},
4 Address, B256, U256,
5};
6use core::cell::RefCell;
7use revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};
8
9#[derive(Debug, Clone, Default)]
32pub struct CachedReads {
33 pub accounts: AddressMap<CachedAccount>,
35 pub contracts: B256Map<Bytecode>,
37 pub block_hashes: HashMap<u64, B256>,
39}
40
41impl CachedReads {
44 pub const fn as_db<DB>(&mut self, db: DB) -> CachedReadsDBRef<'_, DB> {
46 self.as_db_mut(db).into_db()
47 }
48
49 pub const fn as_db_mut<DB>(&mut self, db: DB) -> CachedReadsDbMut<'_, DB> {
51 CachedReadsDbMut { cached: self, db }
52 }
53
54 pub fn insert_account(&mut self, address: Address, info: AccountInfo, storage: U256Map<U256>) {
56 self.accounts.insert(address, CachedAccount { info: Some(info), storage });
57 }
58
59 pub fn extend(&mut self, other: Self) {
63 self.accounts.extend(other.accounts);
64 self.contracts.extend(other.contracts);
65 self.block_hashes.extend(other.block_hashes);
66 }
67}
68
69#[derive(Debug)]
75pub struct CachedReadsDbMut<'a, DB> {
76 pub cached: &'a mut CachedReads,
78 pub db: DB,
80}
81
82impl<'a, DB> CachedReadsDbMut<'a, DB> {
83 pub const fn into_db(self) -> CachedReadsDBRef<'a, DB> {
86 CachedReadsDBRef { inner: RefCell::new(self) }
87 }
88
89 pub const fn inner(&self) -> &DB {
91 &self.db
92 }
93}
94
95impl<DB, T> AsRef<T> for CachedReadsDbMut<'_, DB>
96where
97 DB: AsRef<T>,
98{
99 fn as_ref(&self) -> &T {
100 self.inner().as_ref()
101 }
102}
103
104impl<DB: DatabaseRef> Database for CachedReadsDbMut<'_, DB> {
105 type Error = <DB as DatabaseRef>::Error;
106
107 fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
108 let basic = match self.cached.accounts.entry(address) {
109 Entry::Occupied(entry) => entry.get().info.clone(),
110 Entry::Vacant(entry) => {
111 entry.insert(CachedAccount::new(self.db.basic_ref(address)?)).info.clone()
112 }
113 };
114 Ok(basic)
115 }
116
117 fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
118 let code = match self.cached.contracts.entry(code_hash) {
119 Entry::Occupied(entry) => entry.get().clone(),
120 Entry::Vacant(entry) => entry.insert(self.db.code_by_hash_ref(code_hash)?).clone(),
121 };
122 Ok(code)
123 }
124
125 fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error> {
126 match self.cached.accounts.entry(address) {
127 Entry::Occupied(mut acc_entry) => match acc_entry.get_mut().storage.entry(index) {
128 Entry::Occupied(entry) => Ok(*entry.get()),
129 Entry::Vacant(entry) => Ok(*entry.insert(self.db.storage_ref(address, index)?)),
130 },
131 Entry::Vacant(acc_entry) => {
132 let info = self.db.basic_ref(address)?;
134 let (account, value) = if info.is_some() {
135 let value = self.db.storage_ref(address, index)?;
136 let mut account = CachedAccount::new(info);
137 account.storage.insert(index, value);
138 (account, value)
139 } else {
140 (CachedAccount::new(info), U256::ZERO)
141 };
142 acc_entry.insert(account);
143 Ok(value)
144 }
145 }
146 }
147
148 fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
149 let hash = match self.cached.block_hashes.entry(number) {
150 Entry::Occupied(entry) => *entry.get(),
151 Entry::Vacant(entry) => *entry.insert(self.db.block_hash_ref(number)?),
152 };
153 Ok(hash)
154 }
155}
156
157#[derive(Debug)]
167pub struct CachedReadsDBRef<'a, DB> {
168 pub inner: RefCell<CachedReadsDbMut<'a, DB>>,
170}
171
172impl<DB: DatabaseRef> DatabaseRef for CachedReadsDBRef<'_, DB> {
173 type Error = <DB as DatabaseRef>::Error;
174
175 fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
176 self.inner.borrow_mut().basic(address)
177 }
178
179 fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
180 self.inner.borrow_mut().code_by_hash(code_hash)
181 }
182
183 fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
184 self.inner.borrow_mut().storage(address, index)
185 }
186
187 fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
188 self.inner.borrow_mut().block_hash(number)
189 }
190}
191
192#[derive(Debug, Clone)]
195pub struct CachedAccount {
196 pub info: Option<AccountInfo>,
198 pub storage: U256Map<U256>,
200}
201
202impl CachedAccount {
203 fn new(info: Option<AccountInfo>) -> Self {
204 Self { info, storage: U256Map::default() }
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn test_extend_with_two_cached_reads() {
214 let hash1 = B256::from_slice(&[1u8; 32]);
216 let hash2 = B256::from_slice(&[2u8; 32]);
217 let address1 = Address::from_slice(&[1u8; 20]);
218 let address2 = Address::from_slice(&[2u8; 20]);
219
220 let mut primary = {
222 let mut cache = CachedReads::default();
223 cache.accounts.insert(address1, CachedAccount::new(Some(AccountInfo::default())));
224 cache.contracts.insert(hash1, Bytecode::default());
225 cache.block_hashes.insert(1, hash1);
226 cache
227 };
228
229 let additional = {
231 let mut cache = CachedReads::default();
232 cache.accounts.insert(address2, CachedAccount::new(Some(AccountInfo::default())));
233 cache.contracts.insert(hash2, Bytecode::default());
234 cache.block_hashes.insert(2, hash2);
235 cache
236 };
237
238 primary.extend(additional);
240
241 assert!(
243 primary.accounts.len() == 2 &&
244 primary.contracts.len() == 2 &&
245 primary.block_hashes.len() == 2,
246 "All maps should contain 2 entries"
247 );
248
249 assert!(
251 primary.accounts.contains_key(&address1) &&
252 primary.accounts.contains_key(&address2) &&
253 primary.contracts.contains_key(&hash1) &&
254 primary.contracts.contains_key(&hash2) &&
255 primary.block_hashes.get(&1) == Some(&hash1) &&
256 primary.block_hashes.get(&2) == Some(&hash2),
257 "All expected entries should be present"
258 );
259 }
260}