Skip to main content

revm_database_interface/
bal.rs

1//! Database implementation for BAL.
2use core::{
3    error::Error,
4    fmt::Display,
5    ops::{Deref, DerefMut},
6};
7use primitives::{Address, StorageKey, StorageValue, B256};
8use state::{
9    bal::{alloy::AlloyBal, Bal, BalError},
10    Account, AccountInfo, Bytecode, EvmState,
11};
12use std::sync::Arc;
13
14use crate::{DBErrorMarker, Database, DatabaseCommit};
15
16/// Contains both the BAL for reads and BAL builders.
17#[derive(Clone, Default, Debug, PartialEq, Eq)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub struct BalState {
20    /// BAL used to execute transactions.
21    pub bal: Option<Arc<Bal>>,
22    /// BAL builder that is used to build BAL.
23    /// It is create from State output of transaction execution.
24    pub bal_builder: Option<Bal>,
25    /// BAL index, used by bal to fetch appropriate values and used by bal_builder on commit
26    /// to submit changes.
27    pub bal_index: u64,
28}
29
30impl BalState {
31    /// Create a new BAL manager.
32    #[inline]
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    /// Reset BAL index.
38    #[inline]
39    pub fn reset_bal_index(&mut self) {
40        self.bal_index = 0;
41    }
42
43    /// Bump BAL index.
44    #[inline]
45    pub fn bump_bal_index(&mut self) {
46        self.bal_index += 1;
47    }
48
49    /// Get BAL index.
50    #[inline]
51    pub fn bal_index(&self) -> u64 {
52        self.bal_index
53    }
54
55    /// Get BAL.
56    #[inline]
57    pub fn bal(&self) -> Option<Arc<Bal>> {
58        self.bal.clone()
59    }
60
61    /// Get BAL builder.
62    #[inline]
63    pub fn bal_builder(&self) -> Option<Bal> {
64        self.bal_builder.clone()
65    }
66
67    /// Set BAL.
68    #[inline]
69    pub fn with_bal(mut self, bal: Arc<Bal>) -> Self {
70        self.bal = Some(bal);
71        self
72    }
73
74    /// Set BAL builder.
75    #[inline]
76    pub fn with_bal_builder(mut self) -> Self {
77        self.bal_builder = Some(Bal::new());
78        self
79    }
80
81    /// Take BAL builder.
82    #[inline]
83    pub fn take_built_bal(&mut self) -> Option<Bal> {
84        self.reset_bal_index();
85        self.bal_builder.take()
86    }
87
88    /// Take built BAL as AlloyBAL.
89    #[inline]
90    pub fn take_built_alloy_bal(&mut self) -> Option<AlloyBal> {
91        self.take_built_bal().map(|bal| bal.into_alloy_bal())
92    }
93
94    /// Get account id from BAL.
95    ///
96    /// Return Error if BAL is not found and Account is not
97    #[inline]
98    pub fn get_account_id(&self, address: &Address) -> Result<Option<usize>, BalError> {
99        self.bal
100            .as_ref()
101            .map(|bal| {
102                bal.accounts
103                    .get_full(address)
104                    .map(|i| i.0)
105                    .ok_or(BalError::AccountNotFound)
106            })
107            .transpose()
108    }
109
110    /// Fetch account from database and apply bal changes to it.
111    ///
112    /// Return Some if BAL is existing, None if not.
113    /// Return Err if Accounts is not found inside BAL.
114    /// And return true
115    #[inline]
116    pub fn basic(
117        &self,
118        address: Address,
119        basic: &mut Option<AccountInfo>,
120    ) -> Result<bool, BalError> {
121        let Some(account_id) = self.get_account_id(&address)? else {
122            return Ok(false);
123        };
124        Ok(self.basic_by_account_id(account_id, basic))
125    }
126
127    /// Fetch account from database and apply bal changes to it by account id.
128    ///
129    /// Panics if account_id is invalid
130    #[inline]
131    pub fn basic_by_account_id(&self, account_id: usize, basic: &mut Option<AccountInfo>) -> bool {
132        if let Some(bal) = &self.bal {
133            let is_none = basic.is_none();
134            let mut bal_basic = core::mem::take(basic).unwrap_or_default();
135            let changed = bal
136                .populate_account_info(account_id, self.bal_index, &mut bal_basic)
137                .expect("Invalid account id");
138
139            // If account was not in DB and BAL has no changes, keep it as None.
140            if !changed && is_none {
141                return true;
142            }
143
144            *basic = Some(bal_basic);
145            return true;
146        }
147        false
148    }
149
150    /// Get storage value from BAL.
151    ///
152    /// Return Err if bal is present but account or storage is not found inside BAL.
153    #[inline]
154    pub fn storage(
155        &self,
156        account: &Address,
157        storage_key: StorageKey,
158    ) -> Result<Option<StorageValue>, BalError> {
159        let Some(bal) = &self.bal else {
160            return Ok(None);
161        };
162
163        let Some(bal_account) = bal.accounts.get(account) else {
164            return Err(BalError::AccountNotFound);
165        };
166
167        Ok(bal_account
168            .storage
169            .get_bal_writes(storage_key)?
170            .get(self.bal_index))
171    }
172
173    /// Get the storage value by account id.
174    ///
175    /// Return Err if bal is present but account or storage is not found inside BAL.
176    ///
177    ///
178    #[inline]
179    pub fn storage_by_account_id(
180        &self,
181        account_id: usize,
182        storage_key: StorageKey,
183    ) -> Result<Option<StorageValue>, BalError> {
184        let Some(bal) = &self.bal else {
185            return Ok(None);
186        };
187
188        let Some((_, bal_account)) = bal.accounts.get_index(account_id) else {
189            return Err(BalError::AccountNotFound);
190        };
191
192        Ok(bal_account
193            .storage
194            .get_bal_writes(storage_key)?
195            .get(self.bal_index))
196    }
197
198    /// Apply changed from EvmState to the bal_builder
199    #[inline]
200    pub fn commit(&mut self, changes: &EvmState) {
201        if let Some(bal_builder) = &mut self.bal_builder {
202            for (address, account) in changes.iter() {
203                bal_builder.update_account(self.bal_index, *address, account);
204            }
205        }
206    }
207
208    /// Commit one account to the BAL builder.
209    #[inline]
210    pub fn commit_one(&mut self, address: Address, account: &Account) {
211        if let Some(bal_builder) = &mut self.bal_builder {
212            bal_builder.update_account(self.bal_index, address, account);
213        }
214    }
215}
216
217/// Database implementation for BAL.
218#[derive(Clone, Debug, PartialEq, Eq)]
219#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
220pub struct BalDatabase<DB> {
221    /// BAL manager.
222    pub bal_state: BalState,
223    /// Database.
224    pub db: DB,
225}
226
227impl<DB> Deref for BalDatabase<DB> {
228    type Target = DB;
229
230    fn deref(&self) -> &Self::Target {
231        &self.db
232    }
233}
234
235impl<DB> DerefMut for BalDatabase<DB> {
236    fn deref_mut(&mut self) -> &mut Self::Target {
237        &mut self.db
238    }
239}
240
241impl<DB> BalDatabase<DB> {
242    /// Create a new BAL database.
243    #[inline]
244    pub fn new(db: DB) -> Self {
245        Self {
246            bal_state: BalState::default(),
247            db,
248        }
249    }
250
251    /// With BAL.
252    #[inline]
253    pub fn with_bal_option(self, bal: Option<Arc<Bal>>) -> Self {
254        Self {
255            bal_state: BalState {
256                bal,
257                ..self.bal_state
258            },
259            ..self
260        }
261    }
262
263    /// With BAL builder.
264    #[inline]
265    pub fn with_bal_builder(self) -> Self {
266        Self {
267            bal_state: self.bal_state.with_bal_builder(),
268            ..self
269        }
270    }
271
272    /// Reset BAL index.
273    #[inline]
274    pub fn reset_bal_index(mut self) -> Self {
275        self.bal_state.reset_bal_index();
276        self
277    }
278
279    /// Bump BAL index.
280    #[inline]
281    pub fn bump_bal_index(&mut self) {
282        self.bal_state.bump_bal_index();
283    }
284}
285
286/// Error type from database.
287#[derive(Clone, Debug, PartialEq, Eq)]
288#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
289pub enum EvmDatabaseError<ERROR> {
290    /// BAL error.
291    Bal(BalError),
292    /// External database error.
293    Database(ERROR),
294}
295
296impl<ERROR> From<BalError> for EvmDatabaseError<ERROR> {
297    fn from(error: BalError) -> Self {
298        Self::Bal(error)
299    }
300}
301
302impl<ERROR: core::error::Error + Send + Sync + 'static> DBErrorMarker for EvmDatabaseError<ERROR> {}
303
304impl<ERROR: Display> Display for EvmDatabaseError<ERROR> {
305    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
306        match self {
307            Self::Bal(error) => write!(f, "Bal error: {error}"),
308            Self::Database(error) => write!(f, "Database error: {error}"),
309        }
310    }
311}
312
313impl<ERROR: Error> Error for EvmDatabaseError<ERROR> {}
314
315impl<ERROR> EvmDatabaseError<ERROR> {
316    /// Convert BAL database error to database error.
317    ///
318    /// Panics if BAL error is present.
319    pub fn into_external_error(self) -> ERROR {
320        match self {
321            Self::Bal(_) => panic!("Expected database error, got BAL error"),
322            Self::Database(error) => error,
323        }
324    }
325}
326
327impl<DB: Database> Database for BalDatabase<DB> {
328    type Error = EvmDatabaseError<DB::Error>;
329
330    #[inline]
331    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
332        let account_id = self.bal_state.get_account_id(&address)?;
333
334        let mut account = self.db.basic(address).map_err(EvmDatabaseError::Database)?;
335
336        if let Some(account_id) = account_id {
337            self.bal_state.basic_by_account_id(account_id, &mut account);
338        }
339
340        Ok(account)
341    }
342
343    #[inline]
344    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
345        self.db
346            .code_by_hash(code_hash)
347            .map_err(EvmDatabaseError::Database)
348    }
349
350    #[inline]
351    fn storage(&mut self, address: Address, key: StorageKey) -> Result<StorageValue, Self::Error> {
352        if let Some(storage) = self.bal_state.storage(&address, key)? {
353            return Ok(storage);
354        }
355
356        self.db
357            .storage(address, key)
358            .map_err(EvmDatabaseError::Database)
359    }
360
361    #[inline]
362    fn storage_by_account_id(
363        &mut self,
364        address: Address,
365        account_id: usize,
366        storage_key: StorageKey,
367    ) -> Result<StorageValue, Self::Error> {
368        if let Some(value) = self
369            .bal_state
370            .storage_by_account_id(account_id, storage_key)?
371        {
372            return Ok(value);
373        }
374
375        self.db
376            .storage(address, storage_key)
377            .map_err(EvmDatabaseError::Database)
378    }
379
380    fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
381        self.db
382            .block_hash(number)
383            .map_err(EvmDatabaseError::Database)
384    }
385}
386
387impl<DB: DatabaseCommit> DatabaseCommit for BalDatabase<DB> {
388    fn commit(&mut self, changes: EvmState) {
389        self.bal_state.commit(&changes);
390        self.db.commit(changes);
391    }
392}