Skip to main content

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, JournaledAccountTr},
8        entry::{JournalEntryTr, SelfdestructionRevertStatus},
9        AccountLoad, JournalCheckpoint, JournalLoadError, TransferError,
10    },
11};
12use core::mem;
13use database_interface::Database;
14use primitives::{
15    eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC},
16    hardfork::SpecId::{self, *},
17    hash_map::Entry,
18    hints_util::unlikely,
19    Address, Bytes, HashMap, Log, LogData, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256,
20};
21use state::{Account, EvmState, TransactionId, TransientStorage};
22use std::vec::Vec;
23
24/// Configuration for the journal that affects EVM execution behavior.
25///
26/// This struct bundles the spec ID and EIP-7708 configuration flags.
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct JournalCfg {
30    /// The spec ID for the EVM. Spec is required for some journal entries and needs to be set for
31    /// JournalInner to be functional.
32    ///
33    /// If spec is set it assumed that precompile addresses are set as well for this particular spec.
34    ///
35    /// This spec is used for two things:
36    ///
37    /// - [EIP-161]: Prior to this EIP, Ethereum had separate definitions for empty and non-existing accounts.
38    /// - [EIP-6780]: `SELFDESTRUCT` only in same transaction
39    ///
40    /// [EIP-161]: https://eips.ethereum.org/EIPS/eip-161
41    /// [EIP-6780]: https://eips.ethereum.org/EIPS/eip-6780
42    pub spec: SpecId,
43    /// Whether EIP-7708 (ETH transfers emit logs) is disabled.
44    pub eip7708_disabled: bool,
45    /// Whether the EIP-8246 delayed clearing of self-destructed accounts is disabled.
46    ///
47    /// When enabled, revm tracks all self-destructed addresses and, at the end of the
48    /// transaction, clears the code, storage and nonce of any that still have a remaining
49    /// balance while preserving the balance (see [EIP-8246]). This can be disabled for
50    /// performance reasons as it requires storing and iterating over all self-destructed
51    /// accounts. When disabled, this clearing can be done outside of revm when applying
52    /// accounts to database state.
53    ///
54    /// [EIP-8246]: https://eips.ethereum.org/EIPS/eip-8246
55    pub eip8246_delayed_clear_disabled: bool,
56}
57/// Inner journal state that contains journal and state changes.
58///
59/// Spec Id is a essential information for the Journal.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
62pub struct JournalInner<ENTRY> {
63    /// The current state
64    pub state: EvmState,
65    /// Transient storage that is discarded after every transaction.
66    ///
67    /// See [EIP-1153](https://eips.ethereum.org/EIPS/eip-1153).
68    pub transient_storage: TransientStorage,
69    /// Emitted logs
70    pub logs: Vec<Log>,
71    /// The current call stack depth
72    pub depth: usize,
73    /// The journal of state changes, one for each transaction
74    pub journal: Vec<ENTRY>,
75    /// Global transaction id that represent number of transactions executed (Including reverted ones).
76    /// It can be different from number of `journal_history` as some transaction could be
77    /// reverted or had a error on execution.
78    ///
79    /// This ID is used in `Self::state` to determine if account/storage is touched/warm/cold.
80    pub transaction_id: TransactionId,
81    /// Journal configuration containing spec ID and EIP-7708 flags.
82    pub cfg: JournalCfg,
83    /// Warm addresses containing both coinbase and current precompiles.
84    pub warm_addresses: WarmAddresses,
85    /// Addresses that were self-destructed for the first time in this transaction.
86    ///
87    /// This is used by [EIP-8246] to clear (code, storage and nonce) self-destructed accounts
88    /// that still have balance at the end of the transaction, preserving their balance.
89    ///
90    /// The vec is indexed by checkpoint - on revert, entries added after the checkpoint
91    /// are removed.
92    ///
93    /// [EIP-8246]: https://eips.ethereum.org/EIPS/eip-8246
94    pub selfdestructed_addresses: Vec<Address>,
95}
96
97impl<ENTRY: JournalEntryTr> Default for JournalInner<ENTRY> {
98    fn default() -> Self {
99        Self::new()
100    }
101}
102
103impl<ENTRY: JournalEntryTr> JournalInner<ENTRY> {
104    /// Creates new [`JournalInner`].
105    ///
106    /// `warm_preloaded_addresses` is used to determine if address is considered warm loaded.
107    /// In ordinary case this is precompile or beneficiary.
108    pub fn new() -> JournalInner<ENTRY> {
109        Self {
110            state: HashMap::default(),
111            transient_storage: TransientStorage::default(),
112            logs: Vec::new(),
113            journal: Vec::default(),
114            transaction_id: TransactionId::ZERO,
115            depth: 0,
116            cfg: JournalCfg::default(),
117            warm_addresses: WarmAddresses::new(),
118            selfdestructed_addresses: Vec::new(),
119        }
120    }
121
122    /// Returns the logs.
123    ///
124    /// Before returning, this function applies EIP-8246 to any self-destructed
125    /// accounts that still have a non-zero balance, clearing their code, storage and
126    /// nonce while preserving the balance.
127    #[inline]
128    pub fn take_logs(&mut self) -> Vec<Log> {
129        // EIP-8246: clear self-destructed accounts that still hold a balance.
130        self.eip8246_clear_selfdestructed_accounts();
131        mem::take(&mut self.logs)
132    }
133
134    /// Prepare for next transaction, by committing the current journal to history, incrementing the transaction id
135    /// and returning the logs.
136    ///
137    /// This function is used to prepare for next transaction. It will save the current journal
138    /// and clear the journal for the next transaction.
139    ///
140    /// `commit_tx` is used even for discarding transactions so transaction_id will be incremented.
141    pub fn commit_tx(&mut self) {
142        // Clears all field from JournalInner. Doing it this way to avoid
143        // missing any field.
144        let Self {
145            state,
146            transient_storage,
147            logs,
148            depth,
149            journal,
150            transaction_id,
151            cfg,
152            warm_addresses,
153            selfdestructed_addresses,
154        } = self;
155        // Cfg and state are not changed. They are always set again before execution.
156        let _ = cfg;
157        let _ = state;
158        transient_storage.clear();
159        *depth = 0;
160
161        // Do nothing with journal history so we can skip cloning present journal.
162        journal.clear();
163
164        // Clear coinbase address warming for next tx
165        warm_addresses.clear_coinbase_and_access_list();
166        // increment transaction id.
167        transaction_id.increment();
168
169        logs.clear();
170        selfdestructed_addresses.clear();
171    }
172
173    /// Discard the current transaction, by reverting the journal entries and incrementing the transaction id.
174    pub fn discard_tx(&mut self) {
175        // if there is no journal entries, there has not been any changes.
176        let Self {
177            state,
178            transient_storage,
179            logs,
180            depth,
181            journal,
182            transaction_id,
183            cfg,
184            warm_addresses,
185            selfdestructed_addresses,
186        } = self;
187        let is_spurious_dragon_enabled = cfg.spec.is_enabled_in(SPURIOUS_DRAGON);
188        // iterate over all journals entries and revert our global state
189        journal.drain(..).rev().for_each(|entry| {
190            entry.revert(state, None, is_spurious_dragon_enabled);
191        });
192        transient_storage.clear();
193        *depth = 0;
194        logs.clear();
195        selfdestructed_addresses.clear();
196        transaction_id.increment();
197
198        // Clear coinbase address warming for next tx
199        warm_addresses.clear_coinbase_and_access_list();
200    }
201
202    /// Take the [`EvmState`] and clears the journal by resetting it to initial state.
203    ///
204    /// Note: Precompile addresses and spec are preserved and initial state of
205    /// warm_preloaded_addresses will contain precompiles addresses.
206    #[inline]
207    pub fn finalize(&mut self) -> EvmState {
208        // Clears all field from JournalInner. Doing it this way to avoid
209        // missing any field.
210        let Self {
211            state,
212            transient_storage,
213            logs,
214            depth,
215            journal,
216            transaction_id,
217            cfg,
218            warm_addresses,
219            selfdestructed_addresses,
220        } = self;
221        // Clear coinbase address warming for next tx
222        warm_addresses.clear_coinbase_and_access_list();
223        selfdestructed_addresses.clear();
224
225        let mut state = mem::take(state);
226
227        // Pre-EIP-161 normalization: adjust empty touched accounts so the database
228        // layer can always apply post-EIP-161 commit semantics (destroy empty touched
229        // accounts). For pre-Spurious Dragon blocks, we prevent destruction by either
230        // marking the account as created (materialized) or clearing the touched flag.
231        if !cfg.spec.is_enabled_in(SPURIOUS_DRAGON) {
232            for acc in state.values_mut() {
233                if acc.is_touched()
234                    && acc.is_empty()
235                    && !acc.is_selfdestructed()
236                    && !acc.is_created()
237                {
238                    if acc.is_loaded_as_not_existing() {
239                        // Materialize empty account that didn't exist before.
240                        acc.mark_created();
241                    } else {
242                        // Preserve existing empty account, don't let the DB layer destroy it.
243                        acc.unmark_touch();
244                    }
245                }
246            }
247        }
248
249        logs.clear();
250        transient_storage.clear();
251
252        // clear journal and journal history.
253        journal.clear();
254        *depth = 0;
255        // reset transaction id.
256        *transaction_id = TransactionId::ZERO;
257
258        state
259    }
260
261    /// Apply [EIP-8246] to self-destructed accounts that still have a balance.
262    ///
263    /// This should be called before `take_logs()` at the end of transaction execution.
264    /// It iterates over all accounts that were self-destructed in this transaction and,
265    /// for any that still hold a non-zero balance, clears the rest of the account instead
266    /// of letting the balance be burned: the nonce is reset to `0`, the code and storage are
267    /// cleared, the balance is left unchanged and the self-destruct flag is removed so the
268    /// account is preserved in state as a balance-only account.
269    ///
270    /// A non-zero balance can remain when an account receives ETH after being self-destructed
271    /// in the same transaction, or when a contract created in the same transaction
272    /// self-destructs to itself (see [`Self::selfdestruct`]).
273    ///
274    /// Accounts with a zero balance keep their self-destruct flag and are removed from state as
275    /// before (they are *empty* and deleted by [EIP-161]).
276    ///
277    /// Self-destructed accounts can only reach this point if they were created in the same
278    /// transaction (EIP-6780 is always active alongside EIP-8246), so they never have storage
279    /// stored in the database and clearing the in-memory storage is sufficient.
280    ///
281    /// [EIP-8246]: https://eips.ethereum.org/EIPS/eip-8246
282    /// [EIP-161]: https://eips.ethereum.org/EIPS/eip-161
283    #[inline]
284    pub fn eip8246_clear_selfdestructed_accounts(&mut self) {
285        if !self.cfg.spec.is_enabled_in(AMSTERDAM) || self.cfg.eip8246_delayed_clear_disabled {
286            return;
287        }
288
289        for address in &self.selfdestructed_addresses {
290            let Some(account) = self.state.get_mut(address) else {
291                continue;
292            };
293
294            // Zero-balance accounts stay self-destructed and are removed from state (EIP-161).
295            if account.info.balance.is_zero() {
296                continue;
297            }
298
299            // EIP-8246: keep the balance but clear the rest of the account.
300            account.info.nonce = 0;
301            account.info.code_hash = KECCAK_EMPTY;
302            account.info.code = Some(Bytecode::default());
303            // Wipe storage to zero in place rather than dropping the entries: the
304            // slots were accessed during the (now self-destructed) execution and
305            // EIP-7928 records those accesses in the block access list. Keeping the
306            // entries (present_value = 0) preserves the access — read-only slots
307            // stay read-only and written slots become writes-to-zero — while the
308            // committed state is still an empty (balance-only) account.
309            for slot in account.storage.values_mut() {
310                slot.present_value = StorageValue::ZERO;
311            }
312
313            // Remove the self-destruct flags so the account is preserved instead of destroyed.
314            account.unmark_selfdestruct();
315            account.unmark_selfdestructed_locally();
316        }
317    }
318
319    /// Return reference to state.
320    #[inline]
321    pub const fn state(&mut self) -> &mut EvmState {
322        &mut self.state
323    }
324
325    /// Sets SpecId.
326    #[inline]
327    pub const fn set_spec_id(&mut self, spec: SpecId) {
328        self.cfg.spec = spec;
329    }
330
331    /// Sets EIP-7708 and EIP-8246 configuration flags.
332    #[inline]
333    pub const fn set_eip7708_config(
334        &mut self,
335        disabled: bool,
336        eip8246_delayed_clear_disabled: bool,
337    ) {
338        self.cfg.eip7708_disabled = disabled;
339        self.cfg.eip8246_delayed_clear_disabled = eip8246_delayed_clear_disabled;
340    }
341
342    /// Mark account as touched as only touched accounts will be added to state.
343    /// This is especially important for state clear where touched empty accounts needs to
344    /// be removed from state.
345    #[inline]
346    pub fn touch(&mut self, address: Address) {
347        if let Some(account) = self.state.get_mut(&address) {
348            Self::touch_account(&mut self.journal, address, account);
349        }
350    }
351
352    /// Mark account as touched.
353    #[inline]
354    fn touch_account(journal: &mut Vec<ENTRY>, address: Address, account: &mut Account) {
355        if !account.is_touched() {
356            journal.push(ENTRY::account_touched(address));
357            account.mark_touch();
358        }
359    }
360
361    /// Returns the _loaded_ [Account] for the given address.
362    ///
363    /// This assumes that the account has already been loaded.
364    ///
365    /// # Panics
366    ///
367    /// Panics if the account has not been loaded and is missing from the state set.
368    #[inline]
369    pub fn account(&self, address: Address) -> &Account {
370        self.state
371            .get(&address)
372            .expect("Account expected to be loaded") // Always assume that acc is already loaded
373    }
374
375    /// Set code and its hash to the account.
376    ///
377    /// Note: Assume account is warm and that hash is calculated from code.
378    #[inline]
379    pub fn set_code_with_hash(&mut self, address: Address, code: Bytecode, hash: B256) {
380        let account = self.state.get_mut(&address).unwrap();
381        Self::touch_account(&mut self.journal, address, account);
382
383        self.journal.push(ENTRY::code_changed(address));
384
385        account.info.code_hash = hash;
386        account.info.code = Some(code);
387    }
388
389    /// Use it only if you know that acc is warm.
390    ///
391    /// Assume account is warm.
392    ///
393    /// In case of EIP-7702 code with zero address, the bytecode will be erased.
394    #[inline]
395    pub fn set_code(&mut self, address: Address, code: Bytecode) {
396        if let Some(eip7702_address) = code.eip7702_address() {
397            if eip7702_address.is_zero() {
398                self.set_code_with_hash(address, Bytecode::default(), KECCAK_EMPTY);
399                return;
400            }
401        }
402
403        let hash = code.hash_slow();
404        self.set_code_with_hash(address, code, hash)
405    }
406
407    /// Add journal entry for caller accounting.
408    #[inline]
409    #[deprecated]
410    pub fn caller_accounting_journal_entry(
411        &mut self,
412        address: Address,
413        old_balance: U256,
414        bump_nonce: bool,
415    ) {
416        // account balance changed.
417        self.journal
418            .push(ENTRY::balance_changed(address, old_balance));
419        // account is touched.
420        self.journal.push(ENTRY::account_touched(address));
421
422        if bump_nonce {
423            // nonce changed.
424            self.journal.push(ENTRY::nonce_bumped(address));
425        }
426    }
427
428    /// Increments the balance of the account.
429    ///
430    /// Mark account as touched.
431    #[inline]
432    pub fn balance_incr<DB: Database>(
433        &mut self,
434        db: &mut DB,
435        address: Address,
436        balance: U256,
437    ) -> Result<(), DB::Error> {
438        let mut account = self.load_account_mut(db, address)?.data;
439        account.incr_balance(balance);
440        Ok(())
441    }
442
443    /// Increments the nonce of the account.
444    #[inline]
445    #[deprecated]
446    pub fn nonce_bump_journal_entry(&mut self, address: Address) {
447        self.journal.push(ENTRY::nonce_bumped(address));
448    }
449
450    /// Transfers balance from two accounts. Returns error if sender balance is not enough.
451    ///
452    /// # Panics
453    ///
454    /// Panics if from or to are not loaded.
455    #[inline]
456    pub fn transfer_loaded(
457        &mut self,
458        from: Address,
459        to: Address,
460        balance: U256,
461    ) -> Option<TransferError> {
462        if from == to {
463            let from_balance = self.state.get(&to).unwrap().info.balance;
464            // Check if from balance is enough to transfer the balance.
465            if balance > from_balance {
466                return Some(TransferError::OutOfFunds);
467            }
468            return None;
469        }
470
471        if balance.is_zero() {
472            Self::touch_account(&mut self.journal, to, self.state.get_mut(&to).unwrap());
473            return None;
474        }
475
476        // sub balance from
477        let from_account = self.state.get_mut(&from).unwrap();
478        Self::touch_account(&mut self.journal, from, from_account);
479        let from_balance = &mut from_account.info.balance;
480        let Some(from_balance_decr) = from_balance.checked_sub(balance) else {
481            return Some(TransferError::OutOfFunds);
482        };
483        *from_balance = from_balance_decr;
484
485        // add balance to
486        let to_account = self.state.get_mut(&to).unwrap();
487        Self::touch_account(&mut self.journal, to, to_account);
488        let to_balance = &mut to_account.info.balance;
489        let Some(to_balance_incr) = to_balance.checked_add(balance) else {
490            // Overflow of U256 balance is not possible to happen on mainnet. We don't bother to return funds from from_acc.
491            return Some(TransferError::OverflowPayment);
492        };
493        *to_balance = to_balance_incr;
494
495        // add journal entry
496        self.journal
497            .push(ENTRY::balance_transfer(from, to, balance));
498
499        // EIP-7708: emit ETH transfer log
500        self.eip7708_transfer_log(from, to, balance);
501
502        None
503    }
504
505    /// Transfers balance from two accounts. Returns error if sender balance is not enough.
506    #[inline]
507    pub fn transfer<DB: Database>(
508        &mut self,
509        db: &mut DB,
510        from: Address,
511        to: Address,
512        balance: U256,
513    ) -> Result<Option<TransferError>, DB::Error> {
514        self.load_account(db, from)?;
515        self.load_account(db, to)?;
516        Ok(self.transfer_loaded(from, to, balance))
517    }
518
519    /// Creates account or returns false if collision is detected.
520    ///
521    /// There are few steps done:
522    /// 1. Make created account warm loaded (AccessList) and this should
523    ///    be done before subroutine checkpoint is created.
524    /// 2. Check if there is collision of newly created account with existing one.
525    /// 3. Mark created account as created.
526    /// 4. Add fund to created account
527    /// 5. Increment nonce of created account if SpuriousDragon is active
528    /// 6. Decrease balance of caller account.
529    ///
530    /// # Panics
531    ///
532    /// Panics if the caller is not loaded inside the EVM state.
533    /// This should have been done inside `create_inner`.
534    #[inline]
535    pub fn create_account_checkpoint(
536        &mut self,
537        caller: Address,
538        target_address: Address,
539        balance: U256,
540        spec_id: SpecId,
541    ) -> Result<JournalCheckpoint, TransferError> {
542        // Enter subroutine
543        let checkpoint = self.checkpoint();
544
545        // Newly created account is present, as we just loaded it.
546        let target_acc = self.state.get_mut(&target_address).unwrap();
547        let last_journal = &mut self.journal;
548
549        // New account can be created if:
550        // Bytecode is not empty.
551        // Nonce is not zero
552        // Account is not precompile.
553        if target_acc.info.code_hash != KECCAK_EMPTY || target_acc.info.nonce != 0 {
554            self.checkpoint_revert(checkpoint);
555            return Err(TransferError::CreateCollision);
556        }
557
558        // set account status to create.
559        let is_created_globally = target_acc.mark_created_locally();
560
561        // this entry will revert set nonce.
562        last_journal.push(ENTRY::account_created(target_address, is_created_globally));
563        target_acc.info.code = None;
564        // EIP-161: State trie clearing (invariant-preserving alternative)
565        if spec_id.is_enabled_in(SPURIOUS_DRAGON) {
566            // nonce is going to be reset to zero in AccountCreated journal entry.
567            target_acc.info.nonce = 1;
568        }
569
570        // touch account. This is important as for pre SpuriousDragon account could be
571        // saved even empty.
572        Self::touch_account(last_journal, target_address, target_acc);
573
574        // If balance is zero, we don't need to add any journal entries or emit any logs.
575        if balance.is_zero() {
576            return Ok(checkpoint);
577        }
578
579        // Add balance to created account, as we already have target here.
580        let Some(new_balance) = target_acc.info.balance.checked_add(balance) else {
581            self.checkpoint_revert(checkpoint);
582            return Err(TransferError::OverflowPayment);
583        };
584        target_acc.info.balance = new_balance;
585
586        // safe to decrement for the caller as balance check is already done.
587        let caller_account = self.state.get_mut(&caller).unwrap();
588        caller_account.info.balance -= balance;
589
590        // add journal entry of transferred balance
591        last_journal.push(ENTRY::balance_transfer(caller, target_address, balance));
592
593        // EIP-7708: emit ETH transfer log
594        self.eip7708_transfer_log(caller, target_address, balance);
595
596        Ok(checkpoint)
597    }
598
599    /// Makes a checkpoint that in case of Revert can bring back state to this point.
600    #[inline]
601    pub const fn checkpoint(&mut self) -> JournalCheckpoint {
602        let checkpoint = JournalCheckpoint {
603            log_i: self.logs.len(),
604            journal_i: self.journal.len(),
605            selfdestructed_i: self.selfdestructed_addresses.len(),
606        };
607        self.depth += 1;
608        checkpoint
609    }
610
611    /// Commits the checkpoint.
612    #[inline]
613    pub const fn checkpoint_commit(&mut self) {
614        self.depth = self.depth.saturating_sub(1);
615    }
616
617    /// Reverts all changes to state until given checkpoint.
618    #[inline]
619    pub fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) {
620        let is_spurious_dragon_enabled = self.cfg.spec.is_enabled_in(SPURIOUS_DRAGON);
621        let state = &mut self.state;
622        let transient_storage = &mut self.transient_storage;
623        self.depth = self.depth.saturating_sub(1);
624        self.logs.truncate(checkpoint.log_i);
625        // EIP-7708: Remove selfdestructed addresses added after checkpoint
626        self.selfdestructed_addresses
627            .truncate(checkpoint.selfdestructed_i);
628
629        // iterate over last N journals sets and revert our global state
630        if checkpoint.journal_i < self.journal.len() {
631            self.journal
632                .drain(checkpoint.journal_i..)
633                .rev()
634                .for_each(|entry| {
635                    entry.revert(state, Some(transient_storage), is_spurious_dragon_enabled);
636                });
637        }
638    }
639
640    /// Performs selfdestruct action.
641    /// Transfers balance from address to target. Check if target exist/is_cold
642    ///
643    /// Note: Balance will be lost if address and target are the same BUT when
644    /// current spec enables Cancun, this happens only when the account associated to address
645    /// is created in the same tx
646    ///
647    /// # References:
648    ///  * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/vm/instructions.go#L832-L833>
649    ///  * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/state/statedb.go#L449>
650    ///  * <https://eips.ethereum.org/EIPS/eip-6780>
651    #[inline]
652    pub fn selfdestruct<DB: Database>(
653        &mut self,
654        db: &mut DB,
655        address: Address,
656        target: Address,
657        skip_cold_load: bool,
658    ) -> Result<StateLoad<SelfDestructResult>, JournalLoadError<DB::Error>> {
659        let spec = self.cfg.spec;
660        let account_load = self.load_account_optional(db, target, false, skip_cold_load)?;
661        let is_cold = account_load.is_cold;
662        let is_empty = account_load.state_clear_aware_is_empty(spec);
663
664        if address != target {
665            // Both accounts are loaded before this point, `address` as we execute its contract.
666            // and `target` at the beginning of the function.
667            let acc_balance = self.state.get(&address).unwrap().info.balance;
668
669            let target_account = self.state.get_mut(&target).unwrap();
670            Self::touch_account(&mut self.journal, target, target_account);
671            target_account.info.balance += acc_balance;
672        }
673
674        let acc = self.state.get_mut(&address).unwrap();
675        let balance = acc.info.balance;
676
677        let destroyed_status = if !acc.is_selfdestructed() {
678            SelfdestructionRevertStatus::GloballySelfdestroyed
679        } else if !acc.is_selfdestructed_locally() {
680            SelfdestructionRevertStatus::LocallySelfdestroyed
681        } else {
682            SelfdestructionRevertStatus::RepeatedSelfdestruction
683        };
684
685        let is_cancun_enabled = spec.is_enabled_in(CANCUN);
686
687        // EIP-6780 (Cancun hard-fork): selfdestruct only if contract is created in the same tx
688        let journal_entry = if acc.is_created_locally() || !is_cancun_enabled {
689            // EIP-8246: Track first self-destruction so the account can be cleared (code, storage
690            // and nonce) while preserving its balance at finalization.
691            // Only track when account is actually destroyed and delayed clearing is not disabled.
692            if destroyed_status == SelfdestructionRevertStatus::GloballySelfdestroyed
693                && !self.cfg.eip8246_delayed_clear_disabled
694            {
695                self.selfdestructed_addresses.push(address);
696            }
697
698            acc.mark_selfdestructed_locally();
699
700            // `had_balance` records the balance that left the account so it can be restored
701            // on revert.
702            let had_balance = if target != address {
703                // Balance was transferred to target above; zero out the source.
704                acc.info.balance = U256::ZERO;
705                // EIP-7708: transfer log for balance moved to a different address.
706                self.eip7708_transfer_log(address, target, balance);
707                balance
708            } else if spec.is_enabled_in(AMSTERDAM) {
709                // EIP-8246: self-destruct to self no longer burns the balance. The balance is
710                // kept and the account is cleared at finalization
711                // (see `eip8246_clear_selfdestructed_accounts`).
712                U256::ZERO
713            } else {
714                // Pre-EIP-8246: self-destruct to self burns the balance.
715                acc.info.balance = U256::ZERO;
716                balance
717            };
718
719            Some(ENTRY::account_destroyed(
720                address,
721                target,
722                destroyed_status,
723                had_balance,
724            ))
725        } else if address != target {
726            acc.info.balance = U256::ZERO;
727            // EIP-7708: emit appropriate log for selfdestruct
728            // Transfer log for balance transferred to different address
729            self.eip7708_transfer_log(address, target, balance);
730            Some(ENTRY::balance_transfer(address, target, balance))
731        } else {
732            // State is not changed:
733            // * if we are after Cancun upgrade and
734            // * Selfdestruct account that is created in the same transaction and
735            // * Specify the target is same as selfdestructed account. The balance stays unchanged.
736            None
737        };
738
739        if let Some(entry) = journal_entry {
740            self.journal.push(entry);
741        };
742
743        Ok(StateLoad {
744            data: SelfDestructResult {
745                had_value: !balance.is_zero(),
746                target_exists: !is_empty,
747                previously_destroyed: destroyed_status
748                    == SelfdestructionRevertStatus::RepeatedSelfdestruction,
749            },
750            is_cold,
751        })
752    }
753
754    /// Loads account into memory. return if it is cold or warm accessed
755    #[inline]
756    pub fn load_account<'a, 'db, DB: Database>(
757        &'a mut self,
758        db: &'db mut DB,
759        address: Address,
760    ) -> Result<StateLoad<&'a Account>, DB::Error>
761    where
762        'db: 'a,
763    {
764        self.load_account_optional(db, address, false, false)
765            .map_err(JournalLoadError::unwrap_db_error)
766    }
767
768    /// Loads account into memory. If account is EIP-7702 type it will additionally
769    /// load delegated account.
770    ///
771    /// It will mark both this and delegated account as warm loaded.
772    ///
773    /// Returns information about the account (If it is empty or cold loaded) and if present the information
774    /// about the delegated account (If it is cold loaded).
775    #[inline]
776    pub fn load_account_delegated<DB: Database>(
777        &mut self,
778        db: &mut DB,
779        address: Address,
780    ) -> Result<StateLoad<AccountLoad>, DB::Error> {
781        let spec = self.cfg.spec;
782        let is_eip7702_enabled = spec.is_enabled_in(SpecId::PRAGUE);
783        let account = self
784            .load_account_optional(db, address, is_eip7702_enabled, false)
785            .map_err(JournalLoadError::unwrap_db_error)?;
786        let is_empty = account.state_clear_aware_is_empty(spec);
787
788        let mut account_load = StateLoad::new(
789            AccountLoad {
790                is_delegate_account_cold: None,
791                is_empty,
792            },
793            account.is_cold,
794        );
795
796        // load delegate code if account is EIP-7702
797        if let Some(address) = account
798            .info
799            .code
800            .as_ref()
801            .and_then(Bytecode::eip7702_address)
802        {
803            let delegate_account = self
804                .load_account_optional(db, address, true, false)
805                .map_err(JournalLoadError::unwrap_db_error)?;
806            account_load.data.is_delegate_account_cold = Some(delegate_account.is_cold);
807        }
808
809        Ok(account_load)
810    }
811
812    /// Loads account and its code. If account is already loaded it will load its code.
813    ///
814    /// It will mark account as warm loaded. If not existing Database will be queried for data.
815    ///
816    /// In case of EIP-7702 delegated account will not be loaded,
817    /// [`Self::load_account_delegated`] should be used instead.
818    #[inline]
819    pub fn load_code<'a, 'db, DB: Database>(
820        &'a mut self,
821        db: &'db mut DB,
822        address: Address,
823    ) -> Result<StateLoad<&'a Account>, DB::Error>
824    where
825        'db: 'a,
826    {
827        self.load_account_optional(db, address, true, false)
828            .map_err(JournalLoadError::unwrap_db_error)
829    }
830
831    /// Loads account into memory. If account is already loaded it will be marked as warm.
832    #[inline]
833    pub fn load_account_optional<'a, 'db, DB: Database>(
834        &'a mut self,
835        db: &'db mut DB,
836        address: Address,
837        load_code: bool,
838        skip_cold_load: bool,
839    ) -> Result<StateLoad<&'a Account>, JournalLoadError<DB::Error>>
840    where
841        'db: 'a,
842    {
843        let mut load = self.load_account_mut_optional(db, address, skip_cold_load)?;
844        if load_code {
845            load.data.load_code_preserve_error()?;
846        }
847        Ok(load.map(|i| i.into_account()))
848    }
849
850    /// Loads account into memory. If account is already loaded it will be marked as warm.
851    #[inline]
852    pub fn load_account_mut<'a, 'db, DB: Database>(
853        &'a mut self,
854        db: &'db mut DB,
855        address: Address,
856    ) -> Result<StateLoad<JournaledAccount<'a, DB, ENTRY>>, DB::Error>
857    where
858        'db: 'a,
859    {
860        self.load_account_mut_optional(db, address, false)
861            .map_err(JournalLoadError::unwrap_db_error)
862    }
863
864    /// Loads account. If account is already loaded it will be marked as warm.
865    #[inline]
866    pub fn load_account_mut_optional_code<'a, 'db, DB: Database>(
867        &'a mut self,
868        db: &'db mut DB,
869        address: Address,
870        load_code: bool,
871        skip_cold_load: bool,
872    ) -> Result<StateLoad<JournaledAccount<'a, DB, ENTRY>>, JournalLoadError<DB::Error>>
873    where
874        'db: 'a,
875    {
876        let mut load = self.load_account_mut_optional(db, address, skip_cold_load)?;
877        if load_code {
878            load.data.load_code_preserve_error()?;
879        }
880        Ok(load)
881    }
882
883    /// Gets the account mut reference.
884    ///
885    /// # Load Unsafe
886    ///
887    /// Use this function only if you know what you are doing. It will not mark the account as warm or cold.
888    /// It will not bump transition_id or return if it is cold or warm loaded. This function is useful
889    /// when we know account is warm, touched and already loaded.
890    ///
891    /// It is useful when we want to access storage from account that is currently being executed.
892    #[inline]
893    pub fn get_account_mut<'a, 'db, DB: Database>(
894        &'a mut self,
895        db: &'db mut DB,
896        address: Address,
897    ) -> Option<JournaledAccount<'a, DB, ENTRY>>
898    where
899        'db: 'a,
900    {
901        let account = self.state.get_mut(&address)?;
902        Some(JournaledAccount::new(
903            address,
904            account,
905            &mut self.journal,
906            db,
907            self.warm_addresses.access_list(),
908            self.transaction_id,
909        ))
910    }
911
912    /// Loads account. If account is already loaded it will be marked as warm.
913    #[inline(never)]
914    pub fn load_account_mut_optional<'a, 'db, DB: Database>(
915        &'a mut self,
916        db: &'db mut DB,
917        address: Address,
918        skip_cold_load: bool,
919    ) -> Result<StateLoad<JournaledAccount<'a, DB, ENTRY>>, JournalLoadError<DB::Error>>
920    where
921        'db: 'a,
922    {
923        let (account, is_cold) = match self.state.entry(address) {
924            Entry::Occupied(entry) => {
925                let account = entry.into_mut();
926
927                // skip load if account is cold.
928                let mut is_cold = account.is_cold_transaction_id(self.transaction_id);
929
930                if unlikely(is_cold) {
931                    is_cold = self
932                        .warm_addresses
933                        .check_is_cold(&address, skip_cold_load)?;
934
935                    // mark it warm.
936                    account.mark_warm_with_transaction_id(self.transaction_id);
937
938                    // if it is cold loaded and we have selfdestructed locally it means that
939                    // account was selfdestructed in previous transaction and we need to clear its information and storage.
940                    if account.is_selfdestructed_locally() {
941                        account.selfdestruct();
942                        account.unmark_selfdestructed_locally();
943                    }
944                    account.set_current_info_as_original();
945
946                    // unmark locally created
947                    account.unmark_created_locally();
948
949                    // journal loading of cold account.
950                    self.journal.push(ENTRY::account_warmed(address));
951                }
952                (account, is_cold)
953            }
954            Entry::Vacant(vac) => {
955                // Precompiles,  among some other account(access list and coinbase included)
956                // are warm loaded so we need to take that into account
957                let is_cold = self
958                    .warm_addresses
959                    .check_is_cold(&address, skip_cold_load)?;
960
961                let account = if let Some(account) = db.basic(address)? {
962                    let mut account: Account = account.into();
963                    account.transaction_id = self.transaction_id;
964                    account
965                } else {
966                    Account::new_not_existing(self.transaction_id)
967                };
968
969                // journal loading of cold account.
970                if is_cold {
971                    self.journal.push(ENTRY::account_warmed(address));
972                }
973
974                (vac.insert(account), is_cold)
975            }
976        };
977
978        Ok(StateLoad::new(
979            JournaledAccount::new(
980                address,
981                account,
982                &mut self.journal,
983                db,
984                self.warm_addresses.access_list(),
985                self.transaction_id,
986            ),
987            is_cold,
988        ))
989    }
990
991    /// Loads storage slot.
992    #[inline]
993    pub fn sload<DB: Database>(
994        &mut self,
995        db: &mut DB,
996        address: Address,
997        key: StorageKey,
998        skip_cold_load: bool,
999    ) -> Result<StateLoad<StorageValue>, JournalLoadError<DB::Error>> {
1000        self.load_account_mut(db, address)?
1001            .sload_concrete_error(key, skip_cold_load)
1002            .map(|s| s.map(|s| s.present_value))
1003    }
1004
1005    /// Loads storage slot.
1006    ///
1007    /// If account is not present it will return [`JournalLoadError::ColdLoadSkipped`] error.
1008    #[inline]
1009    pub fn sload_assume_account_present<DB: Database>(
1010        &mut self,
1011        db: &mut DB,
1012        address: Address,
1013        key: StorageKey,
1014        skip_cold_load: bool,
1015    ) -> Result<StateLoad<StorageValue>, JournalLoadError<DB::Error>> {
1016        let Some(mut account) = self.get_account_mut(db, address) else {
1017            return Err(JournalLoadError::ColdLoadSkipped);
1018        };
1019
1020        account
1021            .sload_concrete_error(key, skip_cold_load)
1022            .map(|s| s.map(|s| s.present_value))
1023    }
1024
1025    /// Stores storage slot.
1026    ///
1027    /// If account is not present it will load from database
1028    #[inline]
1029    pub fn sstore<DB: Database>(
1030        &mut self,
1031        db: &mut DB,
1032        address: Address,
1033        key: StorageKey,
1034        new: StorageValue,
1035        skip_cold_load: bool,
1036    ) -> Result<StateLoad<SStoreResult>, JournalLoadError<DB::Error>> {
1037        self.load_account_mut(db, address)?
1038            .sstore_concrete_error(key, new, skip_cold_load)
1039    }
1040
1041    /// Stores storage slot.
1042    ///
1043    /// And returns (original,present,new) slot value.
1044    ///
1045    /// **Note**: Account should already be present in our state.
1046    #[inline]
1047    pub fn sstore_assume_account_present<DB: Database>(
1048        &mut self,
1049        db: &mut DB,
1050        address: Address,
1051        key: StorageKey,
1052        new: StorageValue,
1053        skip_cold_load: bool,
1054    ) -> Result<StateLoad<SStoreResult>, JournalLoadError<DB::Error>> {
1055        let Some(mut account) = self.get_account_mut(db, address) else {
1056            return Err(JournalLoadError::ColdLoadSkipped);
1057        };
1058
1059        account.sstore_concrete_error(key, new, skip_cold_load)
1060    }
1061
1062    /// Read transient storage tied to the account.
1063    ///
1064    /// EIP-1153: Transient storage opcodes
1065    #[inline]
1066    pub fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue {
1067        self.transient_storage.get_value(address, key)
1068    }
1069
1070    /// Store transient storage tied to the account.
1071    ///
1072    /// If values is different add entry to the journal
1073    /// so that old state can be reverted if that action is needed.
1074    ///
1075    /// EIP-1153: Transient storage opcodes
1076    #[inline]
1077    pub fn tstore(&mut self, address: Address, key: StorageKey, new: StorageValue) {
1078        let had_value = if new.is_zero() {
1079            // if new values is zero, remove entry from transient storage.
1080            // if previous values was some insert it inside journal.
1081            // If it is none nothing should be inserted.
1082            self.transient_storage.remove_value(address, key)
1083        } else {
1084            // insert values
1085            let previous_value = self
1086                .transient_storage
1087                .insert_value(address, key, new)
1088                .unwrap_or_default();
1089
1090            // check if previous value is same
1091            if previous_value != new {
1092                // if it is different, insert previous values inside journal.
1093                Some(previous_value)
1094            } else {
1095                None
1096            }
1097        };
1098
1099        if let Some(had_value) = had_value {
1100            // insert in journal only if value was changed.
1101            self.journal
1102                .push(ENTRY::transient_storage_changed(address, key, had_value));
1103        }
1104    }
1105
1106    /// Pushes log into subroutine.
1107    #[inline]
1108    pub fn log(&mut self, log: Log) {
1109        self.logs.push(log);
1110    }
1111
1112    /// Creates and pushes an EIP-7708 ETH transfer log.
1113    ///
1114    /// This emits a LOG3 with the Transfer event signature, matching ERC-20 transfer events.
1115    /// Only emitted if EIP-7708 is enabled (Amsterdam and later) and balance is non-zero.
1116    ///
1117    /// [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708)
1118    #[inline]
1119    pub fn eip7708_transfer_log(&mut self, from: Address, to: Address, balance: U256) {
1120        // Only emit log if EIP-7708 is enabled and balance is non-zero
1121        if !self.cfg.spec.is_enabled_in(AMSTERDAM) || self.cfg.eip7708_disabled || balance.is_zero()
1122        {
1123            return;
1124        }
1125
1126        // Create LOG3 with Transfer(address,address,uint256) event signature
1127        // Topic[0]: Transfer event signature
1128        // Topic[1]: from address (zero-padded to 32 bytes)
1129        // Topic[2]: to address (zero-padded to 32 bytes)
1130        // Data: amount in wei (big-endian uint256)
1131        let topics = std::vec![
1132            ETH_TRANSFER_LOG_TOPIC,
1133            B256::left_padding_from(from.as_slice()),
1134            B256::left_padding_from(to.as_slice()),
1135        ];
1136        let data = Bytes::copy_from_slice(&balance.to_be_bytes::<32>());
1137
1138        self.logs.push(Log {
1139            address: ETH_TRANSFER_LOG_ADDRESS,
1140            data: LogData::new(topics, data).expect("3 topics is valid"),
1141        });
1142    }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147    use super::*;
1148    use context_interface::journaled_state::entry::JournalEntry;
1149    use database_interface::EmptyDB;
1150    use primitives::{address, HashSet, U256};
1151    use state::AccountInfo;
1152
1153    #[test]
1154    fn test_sload_skip_cold_load() {
1155        let mut journal = JournalInner::<JournalEntry>::new();
1156        let test_address = address!("1000000000000000000000000000000000000000");
1157        let test_key = U256::from(1);
1158
1159        // Insert account into state
1160        let account_info = AccountInfo {
1161            balance: U256::from(1000),
1162            nonce: 1,
1163            code_hash: KECCAK_EMPTY,
1164            code: Some(Bytecode::default()),
1165            account_id: None,
1166        };
1167        journal
1168            .state
1169            .insert(test_address, Account::from(account_info));
1170
1171        // Add storage slot to access list (make it warm)
1172        let mut access_list = HashMap::default();
1173        let mut storage_keys = HashSet::default();
1174        storage_keys.insert(test_key);
1175        access_list.insert(test_address, storage_keys);
1176        journal.warm_addresses.set_access_list(access_list);
1177
1178        // Try to sload with skip_cold_load=true - should succeed because slot is in access list
1179        let mut db = EmptyDB::new();
1180        let result = journal.sload_assume_account_present(&mut db, test_address, test_key, true);
1181
1182        // Should succeed and return as warm
1183        assert!(result.is_ok());
1184        let state_load = result.unwrap();
1185        assert!(!state_load.is_cold); // Should be warm
1186        assert_eq!(state_load.data, U256::ZERO); // Empty slot
1187    }
1188}