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    #[inline]
146    fn logs(&self) -> &[Log] {
147        &self.inner.logs
148    }
149
150    #[inline]
151    fn take_logs(&mut self) -> Vec<Log> {
152        self.inner.take_logs()
153    }
154
155    fn selfdestruct(
156        &mut self,
157        address: Address,
158        target: Address,
159        skip_cold_load: bool,
160    ) -> Result<StateLoad<SelfDestructResult>, JournalLoadError<<Self::Database as Database>::Error>>
161    {
162        self.inner
163            .selfdestruct(&mut self.database, address, target, skip_cold_load)
164    }
165
166    #[inline]
167    fn warm_access_list(&mut self, access_list: HashMap<Address, HashSet<StorageKey>>) {
168        self.inner.warm_addresses.set_access_list(access_list);
169    }
170
171    fn warm_coinbase_account(&mut self, address: Address) {
172        self.inner.warm_addresses.set_coinbase(address);
173    }
174
175    fn warm_precompiles(&mut self, precompiles: HashSet<Address>) {
176        self.inner
177            .warm_addresses
178            .set_precompile_addresses(precompiles);
179    }
180
181    #[inline]
182    fn precompile_addresses(&self) -> &HashSet<Address> {
183        self.inner.warm_addresses.precompiles()
184    }
185
186    /// Returns call depth.
187    #[inline]
188    fn depth(&self) -> usize {
189        self.inner.depth
190    }
191
192    #[inline]
193    fn set_spec_id(&mut self, spec_id: SpecId) {
194        self.inner.spec = spec_id;
195    }
196
197    #[inline]
198    fn transfer(
199        &mut self,
200        from: Address,
201        to: Address,
202        balance: U256,
203    ) -> Result<Option<TransferError>, DB::Error> {
204        self.inner.transfer(&mut self.database, from, to, balance)
205    }
206
207    #[inline]
208    fn transfer_loaded(
209        &mut self,
210        from: Address,
211        to: Address,
212        balance: U256,
213    ) -> Option<TransferError> {
214        self.inner.transfer_loaded(from, to, balance)
215    }
216
217    #[inline]
218    fn touch_account(&mut self, address: Address) {
219        self.inner.touch(address);
220    }
221
222    #[inline]
223    fn caller_accounting_journal_entry(
224        &mut self,
225        address: Address,
226        old_balance: U256,
227        bump_nonce: bool,
228    ) {
229        self.inner
230            .caller_accounting_journal_entry(address, old_balance, bump_nonce);
231    }
232
233    /// Increments the balance of the account.
234    #[inline]
235    fn balance_incr(
236        &mut self,
237        address: Address,
238        balance: U256,
239    ) -> Result<(), <Self::Database as Database>::Error> {
240        self.inner
241            .balance_incr(&mut self.database, address, balance)
242    }
243
244    /// Increments the nonce of the account.
245    #[inline]
246    fn nonce_bump_journal_entry(&mut self, address: Address) {
247        self.inner.nonce_bump_journal_entry(address)
248    }
249
250    #[inline]
251    fn load_account(&mut self, address: Address) -> Result<StateLoad<&Account>, DB::Error> {
252        self.inner.load_account(&mut self.database, address)
253    }
254
255    #[inline]
256    fn load_account_mut_optional_code(
257        &mut self,
258        address: Address,
259        load_code: bool,
260    ) -> Result<
261        StateLoad<JournaledAccount<'_, Self::JournalEntry>>,
262        <Self::Database as Database>::Error,
263    > {
264        self.inner
265            .load_account_mut_optional_code(&mut self.database, address, load_code, false)
266            .map_err(JournalLoadError::unwrap_db_error)
267    }
268
269    #[inline]
270    fn load_account_with_code(
271        &mut self,
272        address: Address,
273    ) -> Result<StateLoad<&Account>, DB::Error> {
274        self.inner.load_code(&mut self.database, address)
275    }
276
277    #[inline]
278    fn load_account_delegated(
279        &mut self,
280        address: Address,
281    ) -> Result<StateLoad<AccountLoad>, DB::Error> {
282        self.inner
283            .load_account_delegated(&mut self.database, address)
284    }
285
286    #[inline]
287    fn checkpoint(&mut self) -> JournalCheckpoint {
288        self.inner.checkpoint()
289    }
290
291    #[inline]
292    fn checkpoint_commit(&mut self) {
293        self.inner.checkpoint_commit()
294    }
295
296    #[inline]
297    fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) {
298        self.inner.checkpoint_revert(checkpoint)
299    }
300
301    #[inline]
302    fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256) {
303        self.inner.set_code_with_hash(address, code, hash);
304    }
305
306    #[inline]
307    fn create_account_checkpoint(
308        &mut self,
309        caller: Address,
310        address: Address,
311        balance: U256,
312        spec_id: SpecId,
313    ) -> Result<JournalCheckpoint, TransferError> {
314        // Ignore error.
315        self.inner
316            .create_account_checkpoint(caller, address, balance, spec_id)
317    }
318
319    #[inline]
320    fn commit_tx(&mut self) {
321        self.inner.commit_tx()
322    }
323
324    #[inline]
325    fn discard_tx(&mut self) {
326        self.inner.discard_tx();
327    }
328
329    /// Clear current journal resetting it to initial state and return changes state.
330    #[inline]
331    fn finalize(&mut self) -> Self::State {
332        self.inner.finalize()
333    }
334
335    #[inline]
336    fn sload_skip_cold_load(
337        &mut self,
338        address: Address,
339        key: StorageKey,
340        skip_cold_load: bool,
341    ) -> Result<StateLoad<StorageValue>, JournalLoadError<<Self::Database as Database>::Error>>
342    {
343        self.inner
344            .sload(&mut self.database, address, key, skip_cold_load)
345    }
346
347    #[inline]
348    fn sstore_skip_cold_load(
349        &mut self,
350        address: Address,
351        key: StorageKey,
352        value: StorageValue,
353        skip_cold_load: bool,
354    ) -> Result<StateLoad<SStoreResult>, JournalLoadError<<Self::Database as Database>::Error>>
355    {
356        self.inner
357            .sstore(&mut self.database, address, key, value, skip_cold_load)
358    }
359
360    #[inline]
361    fn load_account_info_skip_cold_load(
362        &mut self,
363        address: Address,
364        load_code: bool,
365        skip_cold_load: bool,
366    ) -> Result<AccountInfoLoad<'_>, JournalLoadError<<Self::Database as Database>::Error>> {
367        let spec = self.inner.spec;
368        self.inner
369            .load_account_optional(&mut self.database, address, load_code, skip_cold_load)
370            .map(|a| {
371                AccountInfoLoad::new(&a.data.info, a.is_cold, a.state_clear_aware_is_empty(spec))
372            })
373    }
374}