revm_context/
journal.rs

1//! This module contains [`Journal`] struct and implements [`JournalTr`] trait for it.
2//!
3//! Entry submodule contains [`JournalEntry`] and [`JournalEntryTr`] traits.
4//! and inner submodule contains [`JournalInner`] struct that contains state.
5pub mod inner;
6pub mod warm_addresses;
7
8pub use context_interface::journaled_state::entry::{JournalEntry, JournalEntryTr};
9pub use inner::JournalInner;
10
11use bytecode::Bytecode;
12use context_interface::{
13    context::{SStoreResult, SelfDestructResult, StateLoad},
14    journaled_state::{
15        account::JournaledAccount, AccountInfoLoad, AccountLoad, JournalCheckpoint,
16        JournalLoadError, JournalTr, TransferError,
17    },
18};
19use core::ops::{Deref, DerefMut};
20use database_interface::Database;
21use primitives::{
22    hardfork::SpecId, Address, HashMap, HashSet, Log, StorageKey, StorageValue, B256, U256,
23};
24use state::{Account, EvmState};
25use std::vec::Vec;
26
27/// A journal of state changes internal to the EVM
28///
29/// On each additional call, the depth of the journaled state is increased (`depth`) and a new journal is added.
30///
31/// The journal contains every state change that happens within that call, making it possible to revert changes made in a specific call.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34pub struct Journal<DB, ENTRY = JournalEntry>
35where
36    ENTRY: JournalEntryTr,
37{
38    /// Database
39    pub database: DB,
40    /// Inner journal state.
41    pub inner: JournalInner<ENTRY>,
42}
43
44impl<DB, ENTRY> Deref for Journal<DB, ENTRY>
45where
46    ENTRY: JournalEntryTr,
47{
48    type Target = JournalInner<ENTRY>;
49
50    fn deref(&self) -> &Self::Target {
51        &self.inner
52    }
53}
54
55impl<DB, ENTRY> DerefMut for Journal<DB, ENTRY>
56where
57    ENTRY: JournalEntryTr,
58{
59    fn deref_mut(&mut self) -> &mut Self::Target {
60        &mut self.inner
61    }
62}
63
64impl<DB, ENTRY: JournalEntryTr> Journal<DB, ENTRY> {
65    /// Creates a new JournaledState by copying state data from a JournalInit and provided database.
66    /// This allows reusing the state, logs, and other data from a previous execution context while
67    /// connecting it to a different database backend.
68    pub fn new_with_inner(database: DB, inner: JournalInner<ENTRY>) -> Self {
69        Self { database, inner }
70    }
71
72    /// Consumes the [`Journal`] and returns [`JournalInner`].
73    ///
74    /// If you need to preserve the original journal, use [`Self::to_inner`] instead which clones the state.
75    pub fn into_init(self) -> JournalInner<ENTRY> {
76        self.inner
77    }
78}
79
80impl<DB, ENTRY: JournalEntryTr + Clone> Journal<DB, ENTRY> {
81    /// Creates a new [`JournalInner`] by cloning all internal state data (state, storage, logs, etc)
82    /// This allows creating a new journaled state with the same state data but without
83    /// carrying over the original database.
84    ///
85    /// This is useful when you want to reuse the current state for a new transaction or
86    /// execution context, but want to start with a fresh database.
87    pub fn to_inner(&self) -> JournalInner<ENTRY> {
88        self.inner.clone()
89    }
90}
91
92impl<DB: Database, ENTRY: JournalEntryTr> JournalTr for Journal<DB, ENTRY> {
93    type Database = DB;
94    type State = EvmState;
95    type JournalEntry = ENTRY;
96
97    fn new(database: DB) -> Journal<DB, ENTRY> {
98        Self {
99            inner: JournalInner::new(),
100            database,
101        }
102    }
103
104    fn db(&self) -> &Self::Database {
105        &self.database
106    }
107
108    fn db_mut(&mut self) -> &mut Self::Database {
109        &mut self.database
110    }
111
112    fn sload(
113        &mut self,
114        address: Address,
115        key: StorageKey,
116    ) -> Result<StateLoad<StorageValue>, <Self::Database as Database>::Error> {
117        self.inner
118            .sload(&mut self.database, address, key, false)
119            .map_err(JournalLoadError::unwrap_db_error)
120    }
121
122    fn sstore(
123        &mut self,
124        address: Address,
125        key: StorageKey,
126        value: StorageValue,
127    ) -> Result<StateLoad<SStoreResult>, <Self::Database as Database>::Error> {
128        self.inner
129            .sstore(&mut self.database, address, key, value, false)
130            .map_err(JournalLoadError::unwrap_db_error)
131    }
132
133    fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue {
134        self.inner.tload(address, key)
135    }
136
137    fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue) {
138        self.inner.tstore(address, key, value)
139    }
140
141    fn log(&mut self, log: Log) {
142        self.inner.log(log)
143    }
144
145    fn selfdestruct(
146        &mut self,
147        address: Address,
148        target: Address,
149    ) -> Result<StateLoad<SelfDestructResult>, DB::Error> {
150        self.inner.selfdestruct(&mut self.database, address, target)
151    }
152
153    #[inline]
154    fn warm_access_list(&mut self, access_list: HashMap<Address, HashSet<StorageKey>>) {
155        self.inner.warm_addresses.set_access_list(access_list);
156    }
157
158    fn warm_coinbase_account(&mut self, address: Address) {
159        self.inner.warm_addresses.set_coinbase(address);
160    }
161
162    fn warm_precompiles(&mut self, precompiles: HashSet<Address>) {
163        self.inner
164            .warm_addresses
165            .set_precompile_addresses(precompiles);
166    }
167
168    #[inline]
169    fn precompile_addresses(&self) -> &HashSet<Address> {
170        self.inner.warm_addresses.precompiles()
171    }
172
173    /// Returns call depth.
174    #[inline]
175    fn depth(&self) -> usize {
176        self.inner.depth
177    }
178
179    #[inline]
180    fn set_spec_id(&mut self, spec_id: SpecId) {
181        self.inner.spec = spec_id;
182    }
183
184    #[inline]
185    fn transfer(
186        &mut self,
187        from: Address,
188        to: Address,
189        balance: U256,
190    ) -> Result<Option<TransferError>, DB::Error> {
191        self.inner.transfer(&mut self.database, from, to, balance)
192    }
193
194    #[inline]
195    fn transfer_loaded(
196        &mut self,
197        from: Address,
198        to: Address,
199        balance: U256,
200    ) -> Option<TransferError> {
201        self.inner.transfer_loaded(from, to, balance)
202    }
203
204    #[inline]
205    fn touch_account(&mut self, address: Address) {
206        self.inner.touch(address);
207    }
208
209    #[inline]
210    fn caller_accounting_journal_entry(
211        &mut self,
212        address: Address,
213        old_balance: U256,
214        bump_nonce: bool,
215    ) {
216        self.inner
217            .caller_accounting_journal_entry(address, old_balance, bump_nonce);
218    }
219
220    /// Increments the balance of the account.
221    #[inline]
222    fn balance_incr(
223        &mut self,
224        address: Address,
225        balance: U256,
226    ) -> Result<(), <Self::Database as Database>::Error> {
227        self.inner
228            .balance_incr(&mut self.database, address, balance)
229    }
230
231    /// Increments the nonce of the account.
232    #[inline]
233    fn nonce_bump_journal_entry(&mut self, address: Address) {
234        self.inner.nonce_bump_journal_entry(address)
235    }
236
237    #[inline]
238    fn load_account(&mut self, address: Address) -> Result<StateLoad<&Account>, DB::Error> {
239        self.inner.load_account(&mut self.database, address)
240    }
241
242    #[inline]
243    fn load_account_mut_optional_code(
244        &mut self,
245        address: Address,
246        load_code: bool,
247    ) -> Result<
248        StateLoad<JournaledAccount<'_, Self::JournalEntry>>,
249        <Self::Database as Database>::Error,
250    > {
251        self.inner
252            .load_account_mut_optional_code(&mut self.database, address, load_code, false)
253            .map_err(JournalLoadError::unwrap_db_error)
254    }
255
256    #[inline]
257    fn load_account_with_code(
258        &mut self,
259        address: Address,
260    ) -> Result<StateLoad<&Account>, DB::Error> {
261        self.inner.load_code(&mut self.database, address)
262    }
263
264    #[inline]
265    fn load_account_delegated(
266        &mut self,
267        address: Address,
268    ) -> Result<StateLoad<AccountLoad>, DB::Error> {
269        self.inner
270            .load_account_delegated(&mut self.database, address)
271    }
272
273    #[inline]
274    fn checkpoint(&mut self) -> JournalCheckpoint {
275        self.inner.checkpoint()
276    }
277
278    #[inline]
279    fn checkpoint_commit(&mut self) {
280        self.inner.checkpoint_commit()
281    }
282
283    #[inline]
284    fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) {
285        self.inner.checkpoint_revert(checkpoint)
286    }
287
288    #[inline]
289    fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256) {
290        self.inner.set_code_with_hash(address, code, hash);
291    }
292
293    #[inline]
294    fn create_account_checkpoint(
295        &mut self,
296        caller: Address,
297        address: Address,
298        balance: U256,
299        spec_id: SpecId,
300    ) -> Result<JournalCheckpoint, TransferError> {
301        // Ignore error.
302        self.inner
303            .create_account_checkpoint(caller, address, balance, spec_id)
304    }
305
306    #[inline]
307    fn take_logs(&mut self) -> Vec<Log> {
308        self.inner.take_logs()
309    }
310
311    #[inline]
312    fn commit_tx(&mut self) {
313        self.inner.commit_tx()
314    }
315
316    #[inline]
317    fn discard_tx(&mut self) {
318        self.inner.discard_tx();
319    }
320
321    /// Clear current journal resetting it to initial state and return changes state.
322    #[inline]
323    fn finalize(&mut self) -> Self::State {
324        self.inner.finalize()
325    }
326
327    #[inline]
328    fn sload_skip_cold_load(
329        &mut self,
330        address: Address,
331        key: StorageKey,
332        skip_cold_load: bool,
333    ) -> Result<StateLoad<StorageValue>, JournalLoadError<<Self::Database as Database>::Error>>
334    {
335        self.inner
336            .sload(&mut self.database, address, key, skip_cold_load)
337    }
338
339    #[inline]
340    fn sstore_skip_cold_load(
341        &mut self,
342        address: Address,
343        key: StorageKey,
344        value: StorageValue,
345        skip_cold_load: bool,
346    ) -> Result<StateLoad<SStoreResult>, JournalLoadError<<Self::Database as Database>::Error>>
347    {
348        self.inner
349            .sstore(&mut self.database, address, key, value, skip_cold_load)
350    }
351
352    #[inline]
353    fn load_account_info_skip_cold_load(
354        &mut self,
355        address: Address,
356        load_code: bool,
357        skip_cold_load: bool,
358    ) -> Result<AccountInfoLoad<'_>, JournalLoadError<<Self::Database as Database>::Error>> {
359        let spec = self.inner.spec;
360        self.inner
361            .load_account_optional(&mut self.database, address, load_code, skip_cold_load)
362            .map(|a| {
363                AccountInfoLoad::new(&a.data.info, a.is_cold, a.state_clear_aware_is_empty(spec))
364            })
365    }
366}