revm_database/states/
cache.rs

1use super::{
2    plain_account::PlainStorage, transition_account::TransitionAccount, CacheAccount, PlainAccount,
3};
4use bytecode::Bytecode;
5use primitives::{Address, HashMap, B256};
6use state::{Account, AccountInfo, EvmState};
7use std::vec::Vec;
8
9/// Cache state contains both modified and original values
10///
11/// # Note
12/// Cache state is main state that revm uses to access state.
13///
14/// It loads all accounts from database and applies revm output to it.
15///
16/// It generates transitions that is used to build BundleState.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct CacheState {
19    /// Block state account with account state
20    pub accounts: HashMap<Address, CacheAccount>,
21    /// Created contracts
22    pub contracts: HashMap<B256, Bytecode>,
23    /// Has EIP-161 state clear enabled (Spurious Dragon hardfork)
24    pub has_state_clear: bool,
25}
26
27impl Default for CacheState {
28    fn default() -> Self {
29        Self::new(true)
30    }
31}
32
33impl CacheState {
34    /// Creates a new default state.
35    pub fn new(has_state_clear: bool) -> Self {
36        Self {
37            accounts: HashMap::default(),
38            contracts: HashMap::default(),
39            has_state_clear,
40        }
41    }
42
43    /// Sets state clear flag. EIP-161.
44    pub fn set_state_clear_flag(&mut self, has_state_clear: bool) {
45        self.has_state_clear = has_state_clear;
46    }
47
48    /// Helper function that returns all accounts.
49    ///
50    /// Used inside tests to generate merkle tree.
51    pub fn trie_account(&self) -> impl IntoIterator<Item = (Address, &PlainAccount)> {
52        self.accounts.iter().filter_map(|(address, account)| {
53            account
54                .account
55                .as_ref()
56                .map(|plain_acc| (*address, plain_acc))
57        })
58    }
59
60    /// Inserts not existing account.
61    pub fn insert_not_existing(&mut self, address: Address) {
62        self.accounts
63            .insert(address, CacheAccount::new_loaded_not_existing());
64    }
65
66    /// Inserts Loaded (Or LoadedEmptyEip161 if account is empty) account.
67    pub fn insert_account(&mut self, address: Address, info: AccountInfo) {
68        let account = if !info.is_empty() {
69            CacheAccount::new_loaded(info, HashMap::default())
70        } else {
71            CacheAccount::new_loaded_empty_eip161(HashMap::default())
72        };
73        self.accounts.insert(address, account);
74    }
75
76    /// Similar to `insert_account` but with storage.
77    pub fn insert_account_with_storage(
78        &mut self,
79        address: Address,
80        info: AccountInfo,
81        storage: PlainStorage,
82    ) {
83        let account = if !info.is_empty() {
84            CacheAccount::new_loaded(info, storage)
85        } else {
86            CacheAccount::new_loaded_empty_eip161(storage)
87        };
88        self.accounts.insert(address, account);
89    }
90
91    /// Applies output of revm execution and create account transitions that are used to build BundleState.
92    pub fn apply_evm_state(&mut self, evm_state: EvmState) -> Vec<(Address, TransitionAccount)> {
93        let mut transitions = Vec::with_capacity(evm_state.len());
94        for (address, account) in evm_state {
95            if let Some(transition) = self.apply_account_state(address, account) {
96                transitions.push((address, transition));
97            }
98        }
99        transitions
100    }
101
102    /// Applies updated account state to the cached account.
103    ///
104    /// Returns account transition if applicable.
105    fn apply_account_state(
106        &mut self,
107        address: Address,
108        account: Account,
109    ) -> Option<TransitionAccount> {
110        // Not touched account are never changed.
111        if !account.is_touched() {
112            return None;
113        }
114
115        let this_account = self
116            .accounts
117            .get_mut(&address)
118            .expect("All accounts should be present inside cache");
119
120        // If it is marked as selfdestructed inside revm
121        // we need to changed state to destroyed.
122        if account.is_selfdestructed() {
123            return this_account.selfdestruct();
124        }
125
126        let is_created = account.is_created();
127        let is_empty = account.is_empty();
128
129        // Transform evm storage to storage with previous value.
130        let changed_storage = account
131            .storage
132            .into_iter()
133            .filter(|(_, slot)| slot.is_changed())
134            .map(|(key, slot)| (key, slot.into()))
135            .collect();
136
137        // Note: It can happen that created contract get selfdestructed in same block
138        // that is why is_created is checked after selfdestructed
139        //
140        // Note: Create2 opcode (Petersburg) was after state clear EIP (Spurious Dragon)
141        //
142        // Note: It is possibility to create KECCAK_EMPTY contract with some storage
143        // by just setting storage inside CRATE constructor. Overlap of those contracts
144        // is not possible because CREATE2 is introduced later.
145        if is_created {
146            return Some(this_account.newly_created(account.info, changed_storage));
147        }
148
149        // Account is touched, but not selfdestructed or newly created.
150        // Account can be touched and not changed.
151        // And when empty account is touched it needs to be removed from database.
152        // EIP-161 state clear
153        if is_empty {
154            if self.has_state_clear {
155                // Touch empty account.
156                this_account.touch_empty_eip161()
157            } else {
158                // If account is empty and state clear is not enabled we should save
159                // empty account.
160                this_account.touch_create_pre_eip161(changed_storage)
161            }
162        } else {
163            Some(this_account.change(account.info, changed_storage))
164        }
165    }
166}