anvil/eth/backend/mem/
state.rs

1//! Support for generating the state root for memdb storage
2
3use crate::eth::error::BlockchainError;
4use alloy_primitives::{Address, B256, U256, keccak256, map::HashMap};
5use alloy_rlp::Encodable;
6use alloy_rpc_types::state::StateOverride;
7use alloy_trie::{HashBuilder, Nibbles};
8use foundry_evm::backend::DatabaseError;
9use revm::{
10    bytecode::Bytecode,
11    database::{CacheDB, DatabaseRef, DbAccount},
12    state::AccountInfo,
13};
14
15pub fn build_root(values: impl IntoIterator<Item = (Nibbles, Vec<u8>)>) -> B256 {
16    let mut builder = HashBuilder::default();
17    for (key, value) in values {
18        builder.add_leaf(key, value.as_ref());
19    }
20    builder.root()
21}
22
23/// Builds state root from the given accounts
24pub fn state_root(accounts: &HashMap<Address, DbAccount>) -> B256 {
25    build_root(trie_accounts(accounts))
26}
27
28/// Builds storage root from the given storage
29pub fn storage_root(storage: &HashMap<U256, U256>) -> B256 {
30    build_root(trie_storage(storage))
31}
32
33/// Builds iterator over stored key-value pairs ready for storage trie root calculation.
34pub fn trie_storage(storage: &HashMap<U256, U256>) -> Vec<(Nibbles, Vec<u8>)> {
35    let mut storage = storage
36        .iter()
37        .map(|(key, value)| {
38            let data = alloy_rlp::encode(value);
39            (Nibbles::unpack(keccak256(key.to_be_bytes::<32>())), data)
40        })
41        .collect::<Vec<_>>();
42    storage.sort_by(|(key1, _), (key2, _)| key1.cmp(key2));
43
44    storage
45}
46
47/// Builds iterator over stored key-value pairs ready for account trie root calculation.
48pub fn trie_accounts(accounts: &HashMap<Address, DbAccount>) -> Vec<(Nibbles, Vec<u8>)> {
49    let mut accounts = accounts
50        .iter()
51        .map(|(address, account)| {
52            let data = trie_account_rlp(&account.info, &account.storage);
53            (Nibbles::unpack(keccak256(*address)), data)
54        })
55        .collect::<Vec<_>>();
56    accounts.sort_by(|(key1, _), (key2, _)| key1.cmp(key2));
57
58    accounts
59}
60
61/// Returns the RLP for this account.
62pub fn trie_account_rlp(info: &AccountInfo, storage: &HashMap<U256, U256>) -> Vec<u8> {
63    let mut out: Vec<u8> = Vec::new();
64    let list: [&dyn Encodable; 4] =
65        [&info.nonce, &info.balance, &storage_root(storage), &info.code_hash];
66
67    alloy_rlp::encode_list::<_, dyn Encodable>(&list, &mut out);
68
69    out
70}
71
72/// Applies the given state overrides to the given CacheDB
73pub fn apply_state_overrides<D>(
74    overrides: StateOverride,
75    cache_db: &mut CacheDB<D>,
76) -> Result<(), BlockchainError>
77where
78    D: DatabaseRef<Error = DatabaseError>,
79{
80    for (account, account_overrides) in &overrides {
81        let mut account_info = cache_db.basic_ref(*account)?.unwrap_or_default();
82
83        if let Some(nonce) = account_overrides.nonce {
84            account_info.nonce = nonce;
85        }
86        if let Some(code) = &account_overrides.code {
87            account_info.code = Some(Bytecode::new_raw(code.to_vec().into()));
88        }
89        if let Some(balance) = account_overrides.balance {
90            account_info.balance = balance;
91        }
92
93        cache_db.insert_account_info(*account, account_info);
94
95        // We ensure that not both state and state_diff are set.
96        // If state is set, we must mark the account as "NewlyCreated", so that the old storage
97        // isn't read from
98        match (&account_overrides.state, &account_overrides.state_diff) {
99            (Some(_), Some(_)) => {
100                return Err(BlockchainError::StateOverrideError(
101                    "state and state_diff can't be used together".to_string(),
102                ));
103            }
104            (None, None) => (),
105            (Some(new_account_state), None) => {
106                cache_db.replace_account_storage(
107                    *account,
108                    new_account_state
109                        .iter()
110                        .map(|(key, value)| ((*key).into(), (*value).into()))
111                        .collect(),
112                )?;
113            }
114            (None, Some(account_state_diff)) => {
115                for (key, value) in account_state_diff {
116                    cache_db.insert_account_storage(*account, (*key).into(), (*value).into())?;
117                }
118            }
119        };
120    }
121    Ok(())
122}