revm-database-interface 12.0.0

Revm Database interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Database interface.
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc as std;

use core::convert::Infallible;

use auto_impl::auto_impl;
use primitives::{address, Address, AddressMap, StorageKey, StorageValue, B256, U256};
use state::{Account, AccountId, AccountInfo, Bytecode, TransactionId};
use std::vec::Vec;

/// Address with all `0xff..ff` in it. Used for testing.
pub const FFADDRESS: Address = address!("0xffffffffffffffffffffffffffffffffffffffff");
/// BENCH_TARGET address
pub const BENCH_TARGET: Address = FFADDRESS;
/// Common test balance used for benchmark addresses
pub const TEST_BALANCE: U256 = U256::from_limbs([10_000_000_000_000_000, 0, 0, 0]);
/// BENCH_TARGET_BALANCE balance
pub const BENCH_TARGET_BALANCE: U256 = TEST_BALANCE;
/// Address with all `0xee..ee` in it. Used for testing.
pub const EEADDRESS: Address = address!("0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
/// BENCH_CALLER address
pub const BENCH_CALLER: Address = EEADDRESS;
/// BENCH_CALLER_BALANCE balance
pub const BENCH_CALLER_BALANCE: U256 = TEST_BALANCE;

pub use primitives;
pub use state;

#[cfg(feature = "asyncdb")]
pub mod async_db;
pub mod bal;
pub mod either;
pub mod empty_db;
pub mod erased_error;
pub mod try_commit;

#[cfg(feature = "asyncdb")]
pub use async_db::{DatabaseAsync, WrapDatabaseAsync};
pub use empty_db::{EmptyDB, EmptyDBTyped};
pub use erased_error::ErasedError;
pub use try_commit::{ArcUpgradeError, TryDatabaseCommit};

/// Database error marker is needed to implement From conversion for Error type.
pub trait DBErrorMarker: core::error::Error + Send + Sync + 'static {}

/// Implement marker for `()`.
impl DBErrorMarker for Infallible {}
impl DBErrorMarker for ErasedError {}

/// EVM database interface.
#[auto_impl(&mut, Box)]
pub trait Database {
    /// The database error type.
    type Error: DBErrorMarker;

    /// Gets basic account information.
    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error>;

    /// Gets account code by its hash.
    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error>;

    /// Gets storage value of address at index.
    fn storage(&mut self, address: Address, index: StorageKey)
        -> Result<StorageValue, Self::Error>;

    /// Gets storage value of account by its id. By default call [`Database::storage`] method.
    ///
    /// If basic account sets account_id inside [`AccountInfo::account_id`], evm will call this
    /// function with that given account_id. This can be useful if IndexMap is used to get faster access to the account.
    #[inline]
    fn storage_by_account_id(
        &mut self,
        address: Address,
        account_id: AccountId,
        storage_key: StorageKey,
    ) -> Result<StorageValue, Self::Error> {
        let _ = account_id;
        self.storage(address, storage_key)
    }

    /// Gets block hash by block number.
    fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error>;
}

/// EVM database commit interface.
///
/// # Dyn Compatibility
///
/// This trait is dyn-compatible. The `commit_iter` method uses `&mut dyn Iterator`
/// which allows it to be called on trait objects while remaining in the vtable.
#[auto_impl(&mut, Box)]
pub trait DatabaseCommit {
    /// Commit changes to the database.
    fn commit(&mut self, changes: AddressMap<Account>);

    /// Commit changes to the database with an iterator.
    ///
    /// Implementors of [`DatabaseCommit`] should override this method when possible for efficiency.
    ///
    /// Callers should prefer using [`DatabaseCommit::commit`] when they already have a [`AddressMap`].
    ///
    /// # Dyn Compatibility
    ///
    /// This method uses `&mut dyn Iterator` to remain object-safe and callable on trait objects.
    /// For ergonomic usage with `impl IntoIterator`, use the inherent method
    /// `commit_from_iter` on `dyn DatabaseCommit`.
    fn commit_iter(&mut self, changes: &mut dyn Iterator<Item = (Address, Account)>) {
        let changes: AddressMap<Account> = changes.collect();
        self.commit(changes);
    }
}

/// Inherent implementation for `dyn DatabaseCommit` trait objects.
///
/// This provides `commit_from_iter` as an ergonomic wrapper around the trait's
/// `commit_iter` method, accepting `impl IntoIterator` for convenience.
impl dyn DatabaseCommit {
    /// Commit changes to the database with an iterator.
    ///
    /// This is an ergonomic wrapper that accepts `impl IntoIterator` and delegates
    /// to the trait's [`commit_iter`](DatabaseCommit::commit_iter) method.
    #[inline]
    pub fn commit_from_iter(&mut self, changes: impl IntoIterator<Item = (Address, Account)>) {
        self.commit_iter(&mut changes.into_iter())
    }
}

/// EVM database interface.
///
/// Contains the same methods as [`Database`], but with `&self` receivers instead of `&mut self`.
///
/// Use [`WrapDatabaseRef`] to provide [`Database`] implementation for a type
/// that only implements this trait.
#[auto_impl(&, &mut, Box, Rc, Arc)]
pub trait DatabaseRef {
    /// The database error type.
    type Error: DBErrorMarker;

    /// Gets basic account information.
    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error>;

    /// Gets account code by its hash.
    fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error>;

    /// Gets storage value of address at index.
    fn storage_ref(&self, address: Address, index: StorageKey)
        -> Result<StorageValue, Self::Error>;

    /// Gets storage value of account by its id.
    ///
    /// Default implementation is to call [`DatabaseRef::storage_ref`] method.
    #[inline]
    fn storage_by_account_id_ref(
        &self,
        address: Address,
        account_id: AccountId,
        storage_key: StorageKey,
    ) -> Result<StorageValue, Self::Error> {
        let _ = account_id;
        self.storage_ref(address, storage_key)
    }

    /// Gets block hash by block number.
    fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error>;
}

/// Wraps a [`DatabaseRef`] to provide a [`Database`] implementation.
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WrapDatabaseRef<T: DatabaseRef>(pub T);

impl<F: DatabaseRef> From<F> for WrapDatabaseRef<F> {
    #[inline]
    fn from(f: F) -> Self {
        WrapDatabaseRef(f)
    }
}

impl<T: DatabaseRef> Database for WrapDatabaseRef<T> {
    type Error = T::Error;

    #[inline]
    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
        self.0.basic_ref(address)
    }

    #[inline]
    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
        self.0.code_by_hash_ref(code_hash)
    }

    #[inline]
    fn storage(
        &mut self,
        address: Address,
        index: StorageKey,
    ) -> Result<StorageValue, Self::Error> {
        self.0.storage_ref(address, index)
    }

    #[inline]
    fn storage_by_account_id(
        &mut self,
        address: Address,
        account_id: AccountId,
        storage_key: StorageKey,
    ) -> Result<StorageValue, Self::Error> {
        self.0
            .storage_by_account_id_ref(address, account_id, storage_key)
    }

    #[inline]
    fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
        self.0.block_hash_ref(number)
    }
}

impl<T: DatabaseRef + DatabaseCommit> DatabaseCommit for WrapDatabaseRef<T> {
    #[inline]
    fn commit(&mut self, changes: AddressMap<Account>) {
        self.0.commit(changes)
    }

    #[inline]
    fn commit_iter(&mut self, changes: &mut dyn Iterator<Item = (Address, Account)>) {
        self.0.commit_iter(changes)
    }
}

impl<T: DatabaseRef> DatabaseRef for WrapDatabaseRef<T> {
    type Error = T::Error;

    #[inline]
    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
        self.0.basic_ref(address)
    }

    #[inline]
    fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
        self.0.code_by_hash_ref(code_hash)
    }

    #[inline]
    fn storage_ref(
        &self,
        address: Address,
        index: StorageKey,
    ) -> Result<StorageValue, Self::Error> {
        self.0.storage_ref(address, index)
    }

    #[inline]
    fn storage_by_account_id_ref(
        &self,
        address: Address,
        account_id: AccountId,
        storage_key: StorageKey,
    ) -> Result<StorageValue, Self::Error> {
        self.0
            .storage_by_account_id_ref(address, account_id, storage_key)
    }

    #[inline]
    fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
        self.0.block_hash_ref(number)
    }
}

impl<T: Database + DatabaseCommit> DatabaseCommitExt for T {
    // default implementation
}

/// EVM database commit interface.
pub trait DatabaseCommitExt: Database + DatabaseCommit {
    /// Iterates over received balances and increment all account balances.
    ///
    /// Update will create transitions for all accounts that are updated.
    fn increment_balances(
        &mut self,
        balances: impl IntoIterator<Item = (Address, u128)>,
    ) -> Result<(), Self::Error> {
        // Make transition and update cache state
        let transitions = balances
            .into_iter()
            .map(|(address, balance)| {
                let mut original_account = match self.basic(address)? {
                    Some(acc_info) => Account::from(acc_info),
                    None => Account::new_not_existing(TransactionId::ZERO),
                };
                original_account.info.balance = original_account
                    .info
                    .balance
                    .saturating_add(U256::from(balance));
                original_account.mark_touch();
                Ok((address, original_account))
            })
            // Unfortunately must collect here to short circuit on error
            .collect::<Result<Vec<_>, _>>()?;

        self.commit_iter(&mut transitions.into_iter());
        Ok(())
    }

    /// Drains balances from given account and return those values.
    ///
    /// It is used for DAO hardfork state change to move values from given accounts.
    fn drain_balances(
        &mut self,
        addresses: impl IntoIterator<Item = Address>,
    ) -> Result<Vec<u128>, Self::Error> {
        // Make transition and update cache state
        let addresses_iter = addresses.into_iter();
        let (lower, _) = addresses_iter.size_hint();
        let mut transitions = Vec::with_capacity(lower);
        let balances = addresses_iter
            .map(|address| {
                let mut original_account = match self.basic(address)? {
                    Some(acc_info) => Account::from(acc_info),
                    None => Account::new_not_existing(TransactionId::ZERO),
                };
                let balance = core::mem::take(&mut original_account.info.balance);
                original_account.mark_touch();
                transitions.push((address, original_account));
                Ok(balance.try_into().unwrap())
            })
            .collect::<Result<Vec<_>, _>>()?;

        self.commit_iter(&mut transitions.into_iter());
        Ok(balances)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Compile-time test that DatabaseCommit is dyn-compatible.
    /// This mirrors Foundry's approach: `struct _ObjectSafe(dyn DatabaseExt);`
    struct _DatabaseCommitObjectSafe(dyn DatabaseCommit);

    /// Test that dyn DatabaseCommit works correctly.
    #[test]
    fn test_dyn_database_commit() {
        use std::collections::HashMap as StdHashMap;

        struct MockDb {
            commits: Vec<StdHashMap<Address, Account>>,
        }

        impl DatabaseCommit for MockDb {
            fn commit(&mut self, changes: AddressMap<Account>) {
                let std_map: StdHashMap<_, _> = changes.into_iter().collect();
                self.commits.push(std_map);
            }
        }

        let mut db = MockDb { commits: vec![] };

        // Test commit_iter on concrete types
        let items: Vec<(Address, Account)> = vec![];
        db.commit_iter(&mut items.into_iter());
        assert_eq!(db.commits.len(), 1);

        // Test commit() on trait objects
        {
            let db_dyn: &mut dyn DatabaseCommit = &mut db;
            db_dyn.commit(AddressMap::default());
        }
        assert_eq!(db.commits.len(), 2);

        // Test commit_iter on trait objects (now works directly!)
        {
            let db_dyn: &mut dyn DatabaseCommit = &mut db;
            let items: Vec<(Address, Account)> = vec![];
            db_dyn.commit_iter(&mut items.into_iter());
        }
        assert_eq!(db.commits.len(), 3);

        // Test ergonomic commit_from_iter on trait objects
        {
            let db_dyn: &mut dyn DatabaseCommit = &mut db;
            db_dyn.commit_from_iter(vec![]);
        }
        assert_eq!(db.commits.len(), 4);
    }

    #[test]
    fn wrappers_forward_commit_iter() {
        #[derive(Default)]
        struct MockDb {
            commits: usize,
            commit_iters: usize,
            committed_accounts: usize,
        }

        impl DatabaseCommit for MockDb {
            fn commit(&mut self, changes: AddressMap<Account>) {
                self.commits += 1;
                self.committed_accounts += changes.len();
            }

            fn commit_iter(&mut self, changes: &mut dyn Iterator<Item = (Address, Account)>) {
                self.commit_iters += 1;
                self.committed_accounts += changes.count();
            }
        }

        impl DatabaseRef for MockDb {
            type Error = Infallible;

            fn basic_ref(&self, _address: Address) -> Result<Option<AccountInfo>, Self::Error> {
                Ok(None)
            }

            fn code_by_hash_ref(&self, _code_hash: B256) -> Result<Bytecode, Self::Error> {
                Ok(Bytecode::default())
            }

            fn storage_ref(
                &self,
                _address: Address,
                _index: StorageKey,
            ) -> Result<StorageValue, Self::Error> {
                Ok(StorageValue::ZERO)
            }

            fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
                Ok(B256::ZERO)
            }
        }

        fn changes() -> Vec<(Address, Account)> {
            vec![(Address::with_last_byte(1), Account::default())]
        }

        let mut db = WrapDatabaseRef(MockDb::default());
        db.commit_iter(&mut changes().into_iter());
        assert_eq!(db.0.commits, 0);
        assert_eq!(db.0.commit_iters, 1);
        assert_eq!(db.0.committed_accounts, 1);

        let mut db: ::either::Either<MockDb, MockDb> = ::either::Either::Left(MockDb::default());
        db.commit_iter(&mut changes().into_iter());
        let ::either::Either::Left(db) = db else {
            unreachable!()
        };
        assert_eq!(db.commits, 0);
        assert_eq!(db.commit_iters, 1);
        assert_eq!(db.committed_accounts, 1);

        let address = Address::with_last_byte(2);
        let mut account = Account::default();
        account.mark_touch();

        let mut db = bal::BalDatabase::new(MockDb::default()).with_bal_builder();
        db.commit_iter(&mut [(address, account)].into_iter());
        assert_eq!(db.db.commits, 0);
        assert_eq!(db.db.commit_iters, 1);
        assert_eq!(db.db.committed_accounts, 1);

        let bal = db.bal_state.take_built_bal().expect("BAL should be built");
        assert!(bal.accounts.get(&address).is_some());
    }
}