Skip to main content

reth_revm/
cached.rs

1//! Database adapters for payload building.
2use 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/// A container type that caches reads from an underlying [`DatabaseRef`].
10///
11/// This is intended to be used in conjunction with `revm::db::State`
12/// during payload building which repeatedly accesses the same data.
13///
14/// [`CachedReads::as_db_mut`] transforms this type into a [`Database`] implementation that uses
15/// [`CachedReads`] as a caching layer for operations, and records any cache misses.
16///
17/// # Example
18///
19/// ```
20/// use reth_revm::{cached::CachedReads, DatabaseRef, db::State};
21///
22/// fn build_payload<DB: DatabaseRef>(db: DB) {
23///     let mut cached_reads = CachedReads::default();
24///     let db = cached_reads.as_db_mut(db);
25///     // this is `Database` and can be used to build a payload, it never commits to `CachedReads` or the underlying database, but all reads from the underlying database are cached in `CachedReads`.
26///     // Subsequent payload build attempts can use cached reads and avoid hitting the underlying database.
27///     // Note: `cached_reads` must outlive `db` to satisfy lifetime requirements.
28///     let state = State::builder().with_database(db).build();
29/// }
30/// ```
31#[derive(Debug, Clone, Default)]
32pub struct CachedReads {
33    /// Block state account with storage.
34    pub accounts: AddressMap<CachedAccount>,
35    /// Created contracts.
36    pub contracts: B256Map<Bytecode>,
37    /// Block hash mapped to the block number.
38    pub block_hashes: HashMap<u64, B256>,
39}
40
41// === impl CachedReads ===
42
43impl CachedReads {
44    /// Gets a [`DatabaseRef`] that will cache reads from the given database.
45    pub const fn as_db<DB>(&mut self, db: DB) -> CachedReadsDBRef<'_, DB> {
46        self.as_db_mut(db).into_db()
47    }
48
49    /// Gets a mutable [`Database`] that will cache reads from the underlying database.
50    pub const fn as_db_mut<DB>(&mut self, db: DB) -> CachedReadsDbMut<'_, DB> {
51        CachedReadsDbMut { cached: self, db }
52    }
53
54    /// Inserts an account info into the cache.
55    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    /// Extends current cache with entries from another [`CachedReads`] instance.
60    ///
61    /// Note: It is expected that both instances are based on the exact same state.
62    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/// A [Database] that caches reads inside [`CachedReads`].
70///
71/// The lifetime parameter `'a` is tied to the lifetime of the underlying [`CachedReads`] instance.
72/// This ensures that the cache remains valid for the entire duration this wrapper is used.
73/// The original [`CachedReads`] must outlive this wrapper to prevent use-after-free.
74#[derive(Debug)]
75pub struct CachedReadsDbMut<'a, DB> {
76    /// The cache of reads.
77    pub cached: &'a mut CachedReads,
78    /// The underlying database.
79    pub db: DB,
80}
81
82impl<'a, DB> CachedReadsDbMut<'a, DB> {
83    /// Converts this [`Database`] implementation into a [`DatabaseRef`] that will still cache
84    /// reads.
85    pub const fn into_db(self) -> CachedReadsDBRef<'a, DB> {
86        CachedReadsDBRef { inner: RefCell::new(self) }
87    }
88
89    /// Returns access to wrapped [`DatabaseRef`].
90    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                // acc needs to be loaded for us to access slots.
133                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/// A [`DatabaseRef`] that caches reads inside [`CachedReads`].
158///
159/// This is intended to be used as the [`DatabaseRef`] for
160/// `revm::db::State` for repeated payload build jobs.
161///
162/// The lifetime parameter `'a` matches the lifetime of the underlying [`CachedReadsDbMut`],
163/// which in turn is tied to the [`CachedReads`] cache. [`RefCell`] is used here to provide
164/// interior mutability for the [`DatabaseRef`] trait (which requires `&self`), while the
165/// lifetime ensures the cache remains valid throughout the wrapper's usage.
166#[derive(Debug)]
167pub struct CachedReadsDBRef<'a, DB> {
168    /// The inner cache reads db mut.
169    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/// Cached account contains the account state with storage
193/// but lacks the account status.
194#[derive(Debug, Clone)]
195pub struct CachedAccount {
196    /// Account state.
197    pub info: Option<AccountInfo>,
198    /// Account's storage.
199    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        // Setup test data
215        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        // Create primary cache
221        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        // Create additional cache
230        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        // Extending primary with additional cache
239        primary.extend(additional);
240
241        // Verify the combined state
242        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        // Verify specific entries
250        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}