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