revm_context/journal/
inner.rs

1//! Module containing the [`JournalInner`] that is part of [`crate::Journal`].
2use super::warm_addresses::WarmAddresses;
3use bytecode::Bytecode;
4use context_interface::{
5    context::{SStoreResult, SelfDestructResult, StateLoad},
6    journaled_state::{
7        account::JournaledAccount,
8        entry::{JournalEntryTr, SelfdestructionRevertStatus},
9    },
10    journaled_state::{AccountLoad, JournalCheckpoint, JournalLoadError, TransferError},
11};
12use core::mem;
13use database_interface::Database;
14use primitives::{
15    hardfork::SpecId::{self, *},
16    hash_map::Entry,
17    Address, HashMap, Log, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256,
18};
19use state::{Account, EvmState, EvmStorageSlot, TransientStorage};
20use std::vec::Vec;
21/// Inner journal state that contains journal and state changes.
22///
23/// Spec Id is a essential information for the Journal.
24#[derive(Debug, Clone, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26pub struct JournalInner<ENTRY> {
27    /// The current state
28    pub state: EvmState,
29    /// Transient storage that is discarded after every transaction.
30    ///
31    /// See [EIP-1153](https://eips.ethereum.org/EIPS/eip-1153).
32    pub transient_storage: TransientStorage,
33    /// Emitted logs
34    pub logs: Vec<Log>,
35    /// The current call stack depth
36    pub depth: usize,
37    /// The journal of state changes, one for each transaction
38    pub journal: Vec<ENTRY>,
39    /// Global transaction id that represent number of transactions executed (Including reverted ones).
40    /// It can be different from number of `journal_history` as some transaction could be
41    /// reverted or had a error on execution.
42    ///
43    /// This ID is used in `Self::state` to determine if account/storage is touched/warm/cold.
44    pub transaction_id: usize,
45    /// The spec ID for the EVM. Spec is required for some journal entries and needs to be set for
46    /// JournalInner to be functional.
47    ///
48    /// If spec is set it assumed that precompile addresses are set as well for this particular spec.
49    ///
50    /// This spec is used for two things:
51    ///
52    /// - [EIP-161]: Prior to this EIP, Ethereum had separate definitions for empty and non-existing accounts.
53    /// - [EIP-6780]: `SELFDESTRUCT` only in same transaction
54    ///
55    /// [EIP-161]: https://eips.ethereum.org/EIPS/eip-161
56    /// [EIP-6780]: https://eips.ethereum.org/EIPS/eip-6780
57    pub spec: SpecId,
58    /// Warm addresses containing both coinbase and current precompiles.
59    pub warm_addresses: WarmAddresses,
60}
61
62impl<ENTRY: JournalEntryTr> Default for JournalInner<ENTRY> {
63    fn default() -> Self {
64        Self::new()
65    }
66}
67
68impl<ENTRY: JournalEntryTr> JournalInner<ENTRY> {
69    /// Creates new [`JournalInner`].
70    ///
71    /// `warm_preloaded_addresses` is used to determine if address is considered warm loaded.
72    /// In ordinary case this is precompile or beneficiary.
73    pub fn new() -> JournalInner<ENTRY> {
74        Self {
75            state: HashMap::default(),
76            transient_storage: TransientStorage::default(),
77            logs: Vec::new(),
78            journal: Vec::default(),
79            transaction_id: 0,
80            depth: 0,
81            spec: SpecId::default(),
82            warm_addresses: WarmAddresses::new(),
83        }
84    }
85
86    /// Returns the logs
87    #[inline]
88    pub fn take_logs(&mut self) -> Vec<Log> {
89        mem::take(&mut self.logs)
90    }
91
92    /// Prepare for next transaction, by committing the current journal to history, incrementing the transaction id
93    /// and returning the logs.
94    ///
95    /// This function is used to prepare for next transaction. It will save the current journal
96    /// and clear the journal for the next transaction.
97    ///
98    /// `commit_tx` is used even for discarding transactions so transaction_id will be incremented.
99    pub fn commit_tx(&mut self) {
100        // Clears all field from JournalInner. Doing it this way to avoid
101        // missing any field.
102        let Self {
103            state,
104            transient_storage,
105            logs,
106            depth,
107            journal,
108            transaction_id,
109            spec,
110            warm_addresses,
111        } = self;
112        // Spec precompiles and state are not changed. It is always set again execution.
113        let _ = spec;
114        let _ = state;
115        transient_storage.clear();
116        *depth = 0;
117
118        // Do nothing with journal history so we can skip cloning present journal.
119        journal.clear();
120
121        // Clear coinbase address warming for next tx
122        warm_addresses.clear_coinbase_and_access_list();
123        // increment transaction id.
124        *transaction_id += 1;
125        logs.clear();
126    }
127
128    /// Discard the current transaction, by reverting the journal entries and incrementing the transaction id.
129    pub fn discard_tx(&mut self) {
130        // if there is no journal entries, there has not been any changes.
131        let Self {
132            state,
133            transient_storage,
134            logs,
135            depth,
136            journal,
137            transaction_id,
138            spec,
139            warm_addresses,
140        } = self;
141        let is_spurious_dragon_enabled = spec.is_enabled_in(SPURIOUS_DRAGON);
142        // iterate over all journals entries and revert our global state
143        journal.drain(..).rev().for_each(|entry| {
144            entry.revert(state, None, is_spurious_dragon_enabled);
145        });
146        transient_storage.clear();
147        *depth = 0;
148        logs.clear();
149        *transaction_id += 1;
150
151        // Clear coinbase address warming for next tx
152        warm_addresses.clear_coinbase_and_access_list();
153    }
154
155    /// Take the [`EvmState`] and clears the journal by resetting it to initial state.
156    ///
157    /// Note: Precompile addresses and spec are preserved and initial state of
158    /// warm_preloaded_addresses will contain precompiles addresses.
159    #[inline]
160    pub fn finalize(&mut self) -> EvmState {
161        // Clears all field from JournalInner. Doing it this way to avoid
162        // missing any field.
163        let Self {
164            state,
165            transient_storage,
166            logs,
167            depth,
168            journal,
169            transaction_id,
170            spec,
171            warm_addresses,
172        } = self;
173        // Spec is not changed. And it is always set again in execution.
174        let _ = spec;
175        // Clear coinbase address warming for next tx
176        warm_addresses.clear_coinbase_and_access_list();
177
178        let state = mem::take(state);
179        logs.clear();
180        transient_storage.clear();
181
182        // clear journal and journal history.
183        journal.clear();
184        *depth = 0;
185        // reset transaction id.
186        *transaction_id = 0;
187
188        state
189    }
190
191    /// Return reference to state.
192    #[inline]
193    pub fn state(&mut self) -> &mut EvmState {
194        &mut self.state
195    }
196
197    /// Sets SpecId.
198    #[inline]
199    pub fn set_spec_id(&mut self, spec: SpecId) {
200        self.spec = spec;
201    }
202
203    /// Mark account as touched as only touched accounts will be added to state.
204    /// This is especially important for state clear where touched empty accounts needs to
205    /// be removed from state.
206    #[inline]
207    pub fn touch(&mut self, address: Address) {
208        if let Some(account) = self.state.get_mut(&address) {
209            Self::touch_account(&mut self.journal, address, account);
210        }
211    }
212
213    /// Mark account as touched.
214    #[inline]
215    fn touch_account(journal: &mut Vec<ENTRY>, address: Address, account: &mut Account) {
216        if !account.is_touched() {
217            journal.push(ENTRY::account_touched(address));
218            account.mark_touch();
219        }
220    }
221
222    /// Returns the _loaded_ [Account] for the given address.
223    ///
224    /// This assumes that the account has already been loaded.
225    ///
226    /// # Panics
227    ///
228    /// Panics if the account has not been loaded and is missing from the state set.
229    #[inline]
230    pub fn account(&self, address: Address) -> &Account {
231        self.state
232            .get(&address)
233            .expect("Account expected to be loaded") // Always assume that acc is already loaded
234    }
235
236    /// Set code and its hash to the account.
237    ///
238    /// Note: Assume account is warm and that hash is calculated from code.
239    #[inline]
240    pub fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256) {
241        let account = self.state.get_mut(&address).unwrap();
242        Self::touch_account(&mut self.journal, address, account);
243
244        self.journal.push(ENTRY::code_changed(address));
245
246        account.info.code_hash = hash;
247        account.info.code = Some(code);
248    }
249
250    /// Use it only if you know that acc is warm.
251    ///
252    /// Assume account is warm.
253    ///
254    /// In case of EIP-7702 code with zero address, the bytecode will be erased.
255    #[inline]
256    pub fn set_code(&mut self, address: Address, code: Bytecode) {
257        if let Bytecode::Eip7702(eip7702_bytecode) = &code {
258            if eip7702_bytecode.address().is_zero() {
259                self.set_code_with_hash(address, Bytecode::default(), KECCAK_EMPTY);
260                return;
261            }
262        }
263
264        let hash = code.hash_slow();
265        self.set_code_with_hash(address, code, hash)
266    }
267
268    /// Add journal entry for caller accounting.
269    #[inline]
270    pub fn caller_accounting_journal_entry(
271        &mut self,
272        address: Address,
273        old_balance: U256,
274        bump_nonce: bool,
275    ) {
276        // account balance changed.
277        self.journal
278            .push(ENTRY::balance_changed(address, old_balance));
279        // account is touched.
280        self.journal.push(ENTRY::account_touched(address));
281
282        if bump_nonce {
283            // nonce changed.
284            self.journal.push(ENTRY::nonce_changed(address));
285        }
286    }
287
288    /// Increments the balance of the account.
289    ///
290    /// Mark account as touched.
291    #[inline]
292    pub fn balance_incr<DB: Database>(
293        &mut self,
294        db: &mut DB,
295        address: Address,
296        balance: U256,
297    ) -> Result<(), DB::Error> {
298        let mut account = self.load_account_mut(db, address)?.data;
299        account.incr_balance(balance);
300        Ok(())
301    }
302
303    /// Increments the nonce of the account.
304    #[inline]
305    pub fn nonce_bump_journal_entry(&mut self, address: Address) {
306        self.journal.push(ENTRY::nonce_changed(address));
307    }
308
309    /// Transfers balance from two accounts. Returns error if sender balance is not enough.
310    ///
311    /// # Panics
312    ///
313    /// Panics if from or to are not loaded.
314    #[inline]
315    pub fn transfer_loaded(
316        &mut self,
317        from: Address,
318        to: Address,
319        balance: U256,
320    ) -> Option<TransferError> {
321        if from == to {
322            let from_balance = self.state.get_mut(&to).unwrap().info.balance;
323            // Check if from balance is enough to transfer the balance.
324            if balance > from_balance {
325                return Some(TransferError::OutOfFunds);
326            }
327            return None;
328        }
329
330        if balance.is_zero() {
331            Self::touch_account(&mut self.journal, to, self.state.get_mut(&to).unwrap());
332            return None;
333        }
334
335        // sub balance from
336        let from_account = self.state.get_mut(&from).unwrap();
337        Self::touch_account(&mut self.journal, from, from_account);
338        let from_balance = &mut from_account.info.balance;
339        let Some(from_balance_decr) = from_balance.checked_sub(balance) else {
340            return Some(TransferError::OutOfFunds);
341        };
342        *from_balance = from_balance_decr;
343
344        // add balance to
345        let to_account = self.state.get_mut(&to).unwrap();
346        Self::touch_account(&mut self.journal, to, to_account);
347        let to_balance = &mut to_account.info.balance;
348        let Some(to_balance_incr) = to_balance.checked_add(balance) else {
349            // Overflow of U256 balance is not possible to happen on mainnet. We don't bother to return funds from from_acc.
350            return Some(TransferError::OverflowPayment);
351        };
352        *to_balance = to_balance_incr;
353
354        // add journal entry
355        self.journal
356            .push(ENTRY::balance_transfer(from, to, balance));
357
358        None
359    }
360
361    /// Transfers balance from two accounts. Returns error if sender balance is not enough.
362    #[inline]
363    pub fn transfer<DB: Database>(
364        &mut self,
365        db: &mut DB,
366        from: Address,
367        to: Address,
368        balance: U256,
369    ) -> Result<Option<TransferError>, DB::Error> {
370        self.load_account(db, from)?;
371        self.load_account(db, to)?;
372        Ok(self.transfer_loaded(from, to, balance))
373    }
374
375    /// Creates account or returns false if collision is detected.
376    ///
377    /// There are few steps done:
378    /// 1. Make created account warm loaded (AccessList) and this should
379    ///    be done before subroutine checkpoint is created.
380    /// 2. Check if there is collision of newly created account with existing one.
381    /// 3. Mark created account as created.
382    /// 4. Add fund to created account
383    /// 5. Increment nonce of created account if SpuriousDragon is active
384    /// 6. Decrease balance of caller account.
385    ///
386    /// # Panics
387    ///
388    /// Panics if the caller is not loaded inside the EVM state.
389    /// This should have been done inside `create_inner`.
390    #[inline]
391    pub fn create_account_checkpoint(
392        &mut self,
393        caller: Address,
394        target_address: Address,
395        balance: U256,
396        spec_id: SpecId,
397    ) -> Result<JournalCheckpoint, TransferError> {
398        // Enter subroutine
399        let checkpoint = self.checkpoint();
400
401        // Newly created account is present, as we just loaded it.
402        let target_acc = self.state.get_mut(&target_address).unwrap();
403        let last_journal = &mut self.journal;
404
405        // New account can be created if:
406        // Bytecode is not empty.
407        // Nonce is not zero
408        // Account is not precompile.
409        if target_acc.info.code_hash != KECCAK_EMPTY || target_acc.info.nonce != 0 {
410            self.checkpoint_revert(checkpoint);
411            return Err(TransferError::CreateCollision);
412        }
413
414        // set account status to create.
415        let is_created_globally = target_acc.mark_created_locally();
416
417        // this entry will revert set nonce.
418        last_journal.push(ENTRY::account_created(target_address, is_created_globally));
419        target_acc.info.code = None;
420        // EIP-161: State trie clearing (invariant-preserving alternative)
421        if spec_id.is_enabled_in(SPURIOUS_DRAGON) {
422            // nonce is going to be reset to zero in AccountCreated journal entry.
423            target_acc.info.nonce = 1;
424        }
425
426        // touch account. This is important as for pre SpuriousDragon account could be
427        // saved even empty.
428        Self::touch_account(last_journal, target_address, target_acc);
429
430        // Add balance to created account, as we already have target here.
431        let Some(new_balance) = target_acc.info.balance.checked_add(balance) else {
432            self.checkpoint_revert(checkpoint);
433            return Err(TransferError::OverflowPayment);
434        };
435        target_acc.info.balance = new_balance;
436
437        // safe to decrement for the caller as balance check is already done.
438        self.state.get_mut(&caller).unwrap().info.balance -= balance;
439
440        // add journal entry of transferred balance
441        last_journal.push(ENTRY::balance_transfer(caller, target_address, balance));
442
443        Ok(checkpoint)
444    }
445
446    /// Makes a checkpoint that in case of Revert can bring back state to this point.
447    #[inline]
448    pub fn checkpoint(&mut self) -> JournalCheckpoint {
449        let checkpoint = JournalCheckpoint {
450            log_i: self.logs.len(),
451            journal_i: self.journal.len(),
452        };
453        self.depth += 1;
454        checkpoint
455    }
456
457    /// Commits the checkpoint.
458    #[inline]
459    pub fn checkpoint_commit(&mut self) {
460        self.depth = self.depth.saturating_sub(1);
461    }
462
463    /// Reverts all changes to state until given checkpoint.
464    #[inline]
465    pub fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) {
466        let is_spurious_dragon_enabled = self.spec.is_enabled_in(SPURIOUS_DRAGON);
467        let state = &mut self.state;
468        let transient_storage = &mut self.transient_storage;
469        self.depth = self.depth.saturating_sub(1);
470        self.logs.truncate(checkpoint.log_i);
471
472        // iterate over last N journals sets and revert our global state
473        if checkpoint.journal_i < self.journal.len() {
474            self.journal
475                .drain(checkpoint.journal_i..)
476                .rev()
477                .for_each(|entry| {
478                    entry.revert(state, Some(transient_storage), is_spurious_dragon_enabled);
479                });
480        }
481    }
482
483    /// Performs selfdestruct action.
484    /// Transfers balance from address to target. Check if target exist/is_cold
485    ///
486    /// Note: Balance will be lost if address and target are the same BUT when
487    /// current spec enables Cancun, this happens only when the account associated to address
488    /// is created in the same tx
489    ///
490    /// # References:
491    ///  * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/vm/instructions.go#L832-L833>
492    ///  * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/state/statedb.go#L449>
493    ///  * <https://eips.ethereum.org/EIPS/eip-6780>
494    #[inline]
495    pub fn selfdestruct<DB: Database>(
496        &mut self,
497        db: &mut DB,
498        address: Address,
499        target: Address,
500    ) -> Result<StateLoad<SelfDestructResult>, DB::Error> {
501        let spec = self.spec;
502        let account_load = self.load_account(db, target)?;
503        let is_cold = account_load.is_cold;
504        let is_empty = account_load.state_clear_aware_is_empty(spec);
505
506        if address != target {
507            // Both accounts are loaded before this point, `address` as we execute its contract.
508            // and `target` at the beginning of the function.
509            let acc_balance = self.state.get(&address).unwrap().info.balance;
510
511            let target_account = self.state.get_mut(&target).unwrap();
512            Self::touch_account(&mut self.journal, target, target_account);
513            target_account.info.balance += acc_balance;
514        }
515
516        let acc = self.state.get_mut(&address).unwrap();
517        let balance = acc.info.balance;
518
519        let destroyed_status = if !acc.is_selfdestructed() {
520            SelfdestructionRevertStatus::GloballySelfdestroyed
521        } else if !acc.is_selfdestructed_locally() {
522            SelfdestructionRevertStatus::LocallySelfdestroyed
523        } else {
524            SelfdestructionRevertStatus::RepeatedSelfdestruction
525        };
526
527        let is_cancun_enabled = spec.is_enabled_in(CANCUN);
528
529        // EIP-6780 (Cancun hard-fork): selfdestruct only if contract is created in the same tx
530        let journal_entry = if acc.is_created_locally() || !is_cancun_enabled {
531            acc.mark_selfdestructed_locally();
532            acc.info.balance = U256::ZERO;
533            Some(ENTRY::account_destroyed(
534                address,
535                target,
536                destroyed_status,
537                balance,
538            ))
539        } else if address != target {
540            acc.info.balance = U256::ZERO;
541            Some(ENTRY::balance_transfer(address, target, balance))
542        } else {
543            // State is not changed:
544            // * if we are after Cancun upgrade and
545            // * Selfdestruct account that is created in the same transaction and
546            // * Specify the target is same as selfdestructed account. The balance stays unchanged.
547            None
548        };
549
550        if let Some(entry) = journal_entry {
551            self.journal.push(entry);
552        };
553
554        Ok(StateLoad {
555            data: SelfDestructResult {
556                had_value: !balance.is_zero(),
557                target_exists: !is_empty,
558                previously_destroyed: destroyed_status
559                    == SelfdestructionRevertStatus::RepeatedSelfdestruction,
560            },
561            is_cold,
562        })
563    }
564
565    /// Loads account into memory. return if it is cold or warm accessed
566    #[inline]
567    pub fn load_account<DB: Database>(
568        &mut self,
569        db: &mut DB,
570        address: Address,
571    ) -> Result<StateLoad<&Account>, DB::Error> {
572        self.load_account_optional(db, address, false, false)
573            .map_err(JournalLoadError::unwrap_db_error)
574    }
575
576    /// Loads account into memory. If account is EIP-7702 type it will additionally
577    /// load delegated account.
578    ///
579    /// It will mark both this and delegated account as warm loaded.
580    ///
581    /// Returns information about the account (If it is empty or cold loaded) and if present the information
582    /// about the delegated account (If it is cold loaded).
583    #[inline]
584    pub fn load_account_delegated<DB: Database>(
585        &mut self,
586        db: &mut DB,
587        address: Address,
588    ) -> Result<StateLoad<AccountLoad>, DB::Error> {
589        let spec = self.spec;
590        let is_eip7702_enabled = spec.is_enabled_in(SpecId::PRAGUE);
591        let account = self
592            .load_account_optional(db, address, is_eip7702_enabled, false)
593            .map_err(JournalLoadError::unwrap_db_error)?;
594        let is_empty = account.state_clear_aware_is_empty(spec);
595
596        let mut account_load = StateLoad::new(
597            AccountLoad {
598                is_delegate_account_cold: None,
599                is_empty,
600            },
601            account.is_cold,
602        );
603
604        // load delegate code if account is EIP-7702
605        if let Some(Bytecode::Eip7702(code)) = &account.info.code {
606            let address = code.address();
607            let delegate_account = self
608                .load_account_optional(db, address, true, false)
609                .map_err(JournalLoadError::unwrap_db_error)?;
610            account_load.data.is_delegate_account_cold = Some(delegate_account.is_cold);
611        }
612
613        Ok(account_load)
614    }
615
616    /// Loads account and its code. If account is already loaded it will load its code.
617    ///
618    /// It will mark account as warm loaded. If not existing Database will be queried for data.
619    ///
620    /// In case of EIP-7702 delegated account will not be loaded,
621    /// [`Self::load_account_delegated`] should be used instead.
622    #[inline]
623    pub fn load_code<DB: Database>(
624        &mut self,
625        db: &mut DB,
626        address: Address,
627    ) -> Result<StateLoad<&Account>, DB::Error> {
628        self.load_account_optional(db, address, true, false)
629            .map_err(JournalLoadError::unwrap_db_error)
630    }
631
632    /// Loads account into memory. If account is already loaded it will be marked as warm.
633    #[inline]
634    pub fn load_account_optional<DB: Database>(
635        &mut self,
636        db: &mut DB,
637        address: Address,
638        load_code: bool,
639        skip_cold_load: bool,
640    ) -> Result<StateLoad<&Account>, JournalLoadError<DB::Error>> {
641        let load = self.load_account_mut_optional_code(db, address, load_code, skip_cold_load)?;
642        Ok(load.map(|i| i.into_account_ref()))
643    }
644
645    /// Loads account into memory. If account is already loaded it will be marked as warm.
646    #[inline]
647    pub fn load_account_mut<DB: Database>(
648        &mut self,
649        db: &mut DB,
650        address: Address,
651    ) -> Result<StateLoad<JournaledAccount<'_, ENTRY>>, DB::Error> {
652        self.load_account_mut_optional_code(db, address, false, false)
653            .map_err(JournalLoadError::unwrap_db_error)
654    }
655
656    /// Loads account. If account is already loaded it will be marked as warm.
657    #[inline(never)]
658    pub fn load_account_mut_optional_code<DB: Database>(
659        &mut self,
660        db: &mut DB,
661        address: Address,
662        load_code: bool,
663        skip_cold_load: bool,
664    ) -> Result<StateLoad<JournaledAccount<'_, ENTRY>>, JournalLoadError<DB::Error>> {
665        let load = match self.state.entry(address) {
666            Entry::Occupied(entry) => {
667                let account = entry.into_mut();
668
669                // skip load if account is cold.
670                let mut is_cold = account.is_cold_transaction_id(self.transaction_id);
671                if is_cold {
672                    // account can be loaded by we still need to check warm_addresses to see if it is cold.
673                    let should_be_cold = self.warm_addresses.is_cold(&address);
674
675                    // dont load it cold if skipping cold load is true.
676                    if should_be_cold && skip_cold_load {
677                        return Err(JournalLoadError::ColdLoadSkipped);
678                    }
679                    is_cold = should_be_cold;
680
681                    // mark it warm.
682                    account.mark_warm_with_transaction_id(self.transaction_id);
683
684                    // if it is cold loaded and we have selfdestructed locally it means that
685                    // account was selfdestructed in previous transaction and we need to clear its information and storage.
686                    if account.is_selfdestructed_locally() {
687                        account.selfdestruct();
688                        account.unmark_selfdestructed_locally();
689                    }
690                    // unmark locally created
691                    account.unmark_created_locally();
692                }
693                StateLoad {
694                    data: account,
695                    is_cold,
696                }
697            }
698            Entry::Vacant(vac) => {
699                // Precompiles among some other account(coinbase included) are warm loaded so we need to take that into account
700                let is_cold = self.warm_addresses.is_cold(&address);
701
702                // dont load cold account if skip_cold_load is true
703                if is_cold && skip_cold_load {
704                    return Err(JournalLoadError::ColdLoadSkipped);
705                }
706                let account = if let Some(account) = db.basic(address)? {
707                    account.into()
708                } else {
709                    Account::new_not_existing(self.transaction_id)
710                };
711
712                StateLoad {
713                    data: vac.insert(account),
714                    is_cold,
715                }
716            }
717        };
718
719        // journal loading of cold account.
720        if load.is_cold {
721            self.journal.push(ENTRY::account_warmed(address));
722        }
723
724        if load_code && load.data.info.code.is_none() {
725            let info = &mut load.data.info;
726            let code = if info.code_hash == KECCAK_EMPTY {
727                Bytecode::default()
728            } else {
729                db.code_by_hash(info.code_hash)?
730            };
731            info.code = Some(code);
732        }
733
734        Ok(load.map(|i| JournaledAccount::new(address, i, &mut self.journal)))
735    }
736
737    /// Loads storage slot.
738    ///
739    /// # Panics
740    ///
741    /// Panics if the account is not present in the state.
742    #[inline]
743    pub fn sload<DB: Database>(
744        &mut self,
745        db: &mut DB,
746        address: Address,
747        key: StorageKey,
748        skip_cold_load: bool,
749    ) -> Result<StateLoad<StorageValue>, JournalLoadError<DB::Error>> {
750        // assume acc is warm
751        let account = self.state.get_mut(&address).unwrap();
752
753        let is_newly_created = account.is_created();
754        let (value, is_cold) = match account.storage.entry(key) {
755            Entry::Occupied(occ) => {
756                let slot = occ.into_mut();
757                // skip load if account is cold.
758                let is_cold = slot.is_cold_transaction_id(self.transaction_id);
759                if skip_cold_load && is_cold {
760                    return Err(JournalLoadError::ColdLoadSkipped);
761                }
762                slot.mark_warm_with_transaction_id(self.transaction_id);
763                (slot.present_value, is_cold)
764            }
765            Entry::Vacant(vac) => {
766                if skip_cold_load {
767                    return Err(JournalLoadError::ColdLoadSkipped);
768                }
769                // if storage was cleared, we don't need to ping db.
770                let value = if is_newly_created {
771                    StorageValue::ZERO
772                } else {
773                    db.storage(address, key)?
774                };
775                vac.insert(EvmStorageSlot::new(value, self.transaction_id));
776
777                // is storage cold
778                let is_cold = !self.warm_addresses.is_storage_warm(&address, &key);
779
780                (value, is_cold)
781            }
782        };
783
784        if is_cold {
785            // add it to journal as cold loaded.
786            self.journal.push(ENTRY::storage_warmed(address, key));
787        }
788
789        Ok(StateLoad::new(value, is_cold))
790    }
791
792    /// Stores storage slot.
793    ///
794    /// And returns (original,present,new) slot value.
795    ///
796    /// **Note**: Account should already be present in our state.
797    #[inline]
798    pub fn sstore<DB: Database>(
799        &mut self,
800        db: &mut DB,
801        address: Address,
802        key: StorageKey,
803        new: StorageValue,
804        skip_cold_load: bool,
805    ) -> Result<StateLoad<SStoreResult>, JournalLoadError<DB::Error>> {
806        // assume that acc exists and load the slot.
807        let present = self.sload(db, address, key, skip_cold_load)?;
808        let acc = self.state.get_mut(&address).unwrap();
809
810        // if there is no original value in dirty return present value, that is our original.
811        let slot = acc.storage.get_mut(&key).unwrap();
812
813        // new value is same as present, we don't need to do anything
814        if present.data == new {
815            return Ok(StateLoad::new(
816                SStoreResult {
817                    original_value: slot.original_value(),
818                    present_value: present.data,
819                    new_value: new,
820                },
821                present.is_cold,
822            ));
823        }
824
825        self.journal
826            .push(ENTRY::storage_changed(address, key, present.data));
827        // insert value into present state.
828        slot.present_value = new;
829        Ok(StateLoad::new(
830            SStoreResult {
831                original_value: slot.original_value(),
832                present_value: present.data,
833                new_value: new,
834            },
835            present.is_cold,
836        ))
837    }
838
839    /// Read transient storage tied to the account.
840    ///
841    /// EIP-1153: Transient storage opcodes
842    #[inline]
843    pub fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue {
844        self.transient_storage
845            .get(&(address, key))
846            .copied()
847            .unwrap_or_default()
848    }
849
850    /// Store transient storage tied to the account.
851    ///
852    /// If values is different add entry to the journal
853    /// so that old state can be reverted if that action is needed.
854    ///
855    /// EIP-1153: Transient storage opcodes
856    #[inline]
857    pub fn tstore(&mut self, address: Address, key: StorageKey, new: StorageValue) {
858        let had_value = if new.is_zero() {
859            // if new values is zero, remove entry from transient storage.
860            // if previous values was some insert it inside journal.
861            // If it is none nothing should be inserted.
862            self.transient_storage.remove(&(address, key))
863        } else {
864            // insert values
865            let previous_value = self
866                .transient_storage
867                .insert((address, key), new)
868                .unwrap_or_default();
869
870            // check if previous value is same
871            if previous_value != new {
872                // if it is different, insert previous values inside journal.
873                Some(previous_value)
874            } else {
875                None
876            }
877        };
878
879        if let Some(had_value) = had_value {
880            // insert in journal only if value was changed.
881            self.journal
882                .push(ENTRY::transient_storage_changed(address, key, had_value));
883        }
884    }
885
886    /// Pushes log into subroutine.
887    #[inline]
888    pub fn log(&mut self, log: Log) {
889        self.logs.push(log);
890    }
891}