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 let had_code_hash = account.info.code_hash;
384 let had_code = account.info.code.take();
385 self.journal
386 .push(ENTRY::code_changed(address, had_code_hash, had_code));
387
388 account.info.code_hash = hash;
389 account.info.code = Some(code);
390 }
391
392 /// Use it only if you know that acc is warm.
393 ///
394 /// Assume account is warm.
395 ///
396 /// In case of EIP-7702 code with zero address, the bytecode will be erased.
397 #[inline]
398 pub fn set_code(&mut self, address: Address, code: Bytecode) {
399 if let Some(eip7702_address) = code.eip7702_address() {
400 if eip7702_address.is_zero() {
401 self.set_code_with_hash(address, Bytecode::default(), KECCAK_EMPTY);
402 return;
403 }
404 }
405
406 let hash = code.hash_slow();
407 self.set_code_with_hash(address, code, hash)
408 }
409
410 /// Add journal entry for caller accounting.
411 #[inline]
412 #[deprecated]
413 pub fn caller_accounting_journal_entry(
414 &mut self,
415 address: Address,
416 old_balance: U256,
417 bump_nonce: bool,
418 ) {
419 // account balance changed.
420 self.journal
421 .push(ENTRY::balance_changed(address, old_balance));
422 // account is touched.
423 self.journal.push(ENTRY::account_touched(address));
424
425 if bump_nonce {
426 // nonce changed.
427 self.journal.push(ENTRY::nonce_bumped(address));
428 }
429 }
430
431 /// Increments the balance of the account.
432 ///
433 /// Mark account as touched.
434 #[inline]
435 pub fn balance_incr<DB: Database>(
436 &mut self,
437 db: &mut DB,
438 address: Address,
439 balance: U256,
440 ) -> Result<(), DB::Error> {
441 let mut account = self.load_account_mut(db, address)?.data;
442 account.incr_balance(balance);
443 Ok(())
444 }
445
446 /// Increments the nonce of the account.
447 #[inline]
448 #[deprecated]
449 pub fn nonce_bump_journal_entry(&mut self, address: Address) {
450 self.journal.push(ENTRY::nonce_bumped(address));
451 }
452
453 /// Transfers balance from two accounts. Returns error if sender balance is not enough.
454 ///
455 /// # Panics
456 ///
457 /// Panics if from or to are not loaded.
458 #[inline]
459 pub fn transfer_loaded(
460 &mut self,
461 from: Address,
462 to: Address,
463 balance: U256,
464 ) -> Option<TransferError> {
465 if from == to {
466 let from_balance = self.state.get(&to).unwrap().info.balance;
467 // Check if from balance is enough to transfer the balance.
468 if balance > from_balance {
469 return Some(TransferError::OutOfFunds);
470 }
471 return None;
472 }
473
474 if balance.is_zero() {
475 Self::touch_account(&mut self.journal, to, self.state.get_mut(&to).unwrap());
476 return None;
477 }
478
479 // sub balance from
480 let from_account = self.state.get_mut(&from).unwrap();
481 Self::touch_account(&mut self.journal, from, from_account);
482 let from_balance = &mut from_account.info.balance;
483 let Some(from_balance_decr) = from_balance.checked_sub(balance) else {
484 return Some(TransferError::OutOfFunds);
485 };
486 *from_balance = from_balance_decr;
487
488 // add balance to
489 let to_account = self.state.get_mut(&to).unwrap();
490 Self::touch_account(&mut self.journal, to, to_account);
491 let to_balance = &mut to_account.info.balance;
492 let Some(to_balance_incr) = to_balance.checked_add(balance) else {
493 // Overflow of U256 balance is not possible to happen on mainnet. We don't bother to return funds from from_acc.
494 return Some(TransferError::OverflowPayment);
495 };
496 *to_balance = to_balance_incr;
497
498 // add journal entry
499 self.journal
500 .push(ENTRY::balance_transfer(from, to, balance));
501
502 // EIP-7708: emit ETH transfer log
503 self.eip7708_transfer_log(from, to, balance);
504
505 None
506 }
507
508 /// Transfers balance from two accounts. Returns error if sender balance is not enough.
509 #[inline]
510 pub fn transfer<DB: Database>(
511 &mut self,
512 db: &mut DB,
513 from: Address,
514 to: Address,
515 balance: U256,
516 ) -> Result<Option<TransferError>, DB::Error> {
517 self.load_account(db, from)?;
518 self.load_account(db, to)?;
519 Ok(self.transfer_loaded(from, to, balance))
520 }
521
522 /// Creates account or returns false if collision is detected.
523 ///
524 /// There are few steps done:
525 /// 1. Make created account warm loaded (AccessList) and this should
526 /// be done before subroutine checkpoint is created.
527 /// 2. Check if there is collision of newly created account with existing one.
528 /// 3. Mark created account as created.
529 /// 4. Add fund to created account
530 /// 5. Increment nonce of created account if SpuriousDragon is active
531 /// 6. Decrease balance of caller account.
532 ///
533 /// # Panics
534 ///
535 /// Panics if the caller is not loaded inside the EVM state.
536 /// This should have been done inside `create_inner`.
537 #[inline]
538 pub fn create_account_checkpoint(
539 &mut self,
540 caller: Address,
541 target_address: Address,
542 balance: U256,
543 spec_id: SpecId,
544 ) -> Result<JournalCheckpoint, TransferError> {
545 // Enter subroutine
546 let checkpoint = self.checkpoint();
547
548 // Newly created account is present, as we just loaded it.
549 let target_acc = self.state.get_mut(&target_address).unwrap();
550 let last_journal = &mut self.journal;
551
552 // New account can be created if:
553 // Bytecode is not empty.
554 // Nonce is not zero
555 // Account is not precompile.
556 if target_acc.info.code_hash != KECCAK_EMPTY || target_acc.info.nonce != 0 {
557 self.checkpoint_revert(checkpoint);
558 return Err(TransferError::CreateCollision);
559 }
560
561 // set account status to create.
562 let is_created_globally = target_acc.mark_created_locally();
563
564 // this entry will revert set nonce.
565 last_journal.push(ENTRY::account_created(target_address, is_created_globally));
566 target_acc.info.code = None;
567 // EIP-161: State trie clearing (invariant-preserving alternative)
568 if spec_id.is_enabled_in(SPURIOUS_DRAGON) {
569 // nonce is going to be reset to zero in AccountCreated journal entry.
570 target_acc.info.nonce = 1;
571 }
572
573 // touch account. This is important as for pre SpuriousDragon account could be
574 // saved even empty.
575 Self::touch_account(last_journal, target_address, target_acc);
576
577 // If balance is zero, we don't need to add any journal entries or emit any logs.
578 if balance.is_zero() {
579 return Ok(checkpoint);
580 }
581
582 // Add balance to created account, as we already have target here.
583 let Some(new_balance) = target_acc.info.balance.checked_add(balance) else {
584 self.checkpoint_revert(checkpoint);
585 return Err(TransferError::OverflowPayment);
586 };
587 target_acc.info.balance = new_balance;
588
589 // safe to decrement for the caller as balance check is already done.
590 let caller_account = self.state.get_mut(&caller).unwrap();
591 caller_account.info.balance -= balance;
592
593 // add journal entry of transferred balance
594 last_journal.push(ENTRY::balance_transfer(caller, target_address, balance));
595
596 // EIP-7708: emit ETH transfer log
597 self.eip7708_transfer_log(caller, target_address, balance);
598
599 Ok(checkpoint)
600 }
601
602 /// Makes a checkpoint that in case of Revert can bring back state to this point.
603 #[inline]
604 pub const fn checkpoint(&mut self) -> JournalCheckpoint {
605 let checkpoint = JournalCheckpoint {
606 log_i: self.logs.len(),
607 journal_i: self.journal.len(),
608 selfdestructed_i: self.selfdestructed_addresses.len(),
609 };
610 self.depth += 1;
611 checkpoint
612 }
613
614 /// Commits the checkpoint.
615 #[inline]
616 pub const fn checkpoint_commit(&mut self) {
617 self.depth = self.depth.saturating_sub(1);
618 }
619
620 /// Reverts all changes to state until given checkpoint.
621 #[inline]
622 pub fn checkpoint_revert(&mut self, checkpoint: JournalCheckpoint) {
623 let is_spurious_dragon_enabled = self.cfg.spec.is_enabled_in(SPURIOUS_DRAGON);
624 let state = &mut self.state;
625 let transient_storage = &mut self.transient_storage;
626 self.depth = self.depth.saturating_sub(1);
627 self.logs.truncate(checkpoint.log_i);
628 // EIP-7708: Remove selfdestructed addresses added after checkpoint
629 self.selfdestructed_addresses
630 .truncate(checkpoint.selfdestructed_i);
631
632 // iterate over last N journals sets and revert our global state
633 if checkpoint.journal_i < self.journal.len() {
634 self.journal
635 .drain(checkpoint.journal_i..)
636 .rev()
637 .for_each(|entry| {
638 entry.revert(state, Some(transient_storage), is_spurious_dragon_enabled);
639 });
640 }
641 }
642
643 /// Performs selfdestruct action.
644 /// Transfers balance from address to target. Check if target exist/is_cold
645 ///
646 /// Note: Balance will be lost if address and target are the same BUT when
647 /// current spec enables Cancun, this happens only when the account associated to address
648 /// is created in the same tx
649 ///
650 /// # References:
651 /// * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/vm/instructions.go#L832-L833>
652 /// * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/state/statedb.go#L449>
653 /// * <https://eips.ethereum.org/EIPS/eip-6780>
654 #[inline]
655 pub fn selfdestruct<DB: Database>(
656 &mut self,
657 db: &mut DB,
658 address: Address,
659 target: Address,
660 skip_cold_load: bool,
661 ) -> Result<StateLoad<SelfDestructResult>, JournalLoadError<DB::Error>> {
662 let spec = self.cfg.spec;
663 let account_load = self.load_account_optional(db, target, false, skip_cold_load)?;
664 let is_cold = account_load.is_cold;
665 let is_empty = account_load.state_clear_aware_is_empty(spec);
666
667 if address != target {
668 // Both accounts are loaded before this point, `address` as we execute its contract.
669 // and `target` at the beginning of the function.
670 let acc_balance = self.state.get(&address).unwrap().info.balance;
671
672 let target_account = self.state.get_mut(&target).unwrap();
673 Self::touch_account(&mut self.journal, target, target_account);
674 target_account.info.balance += acc_balance;
675 }
676
677 let acc = self.state.get_mut(&address).unwrap();
678 let balance = acc.info.balance;
679
680 let destroyed_status = if !acc.is_selfdestructed() {
681 SelfdestructionRevertStatus::GloballySelfdestroyed
682 } else if !acc.is_selfdestructed_locally() {
683 SelfdestructionRevertStatus::LocallySelfdestroyed
684 } else {
685 SelfdestructionRevertStatus::RepeatedSelfdestruction
686 };
687
688 let is_cancun_enabled = spec.is_enabled_in(CANCUN);
689
690 // EIP-6780 (Cancun hard-fork): selfdestruct only if contract is created in the same tx
691 let journal_entry = if acc.is_created_locally() || !is_cancun_enabled {
692 // EIP-8246: Track first self-destruction so the account can be cleared (code, storage
693 // and nonce) while preserving its balance at finalization.
694 // Only track when account is actually destroyed and delayed clearing is not disabled.
695 if destroyed_status == SelfdestructionRevertStatus::GloballySelfdestroyed
696 && !self.cfg.eip8246_delayed_clear_disabled
697 {
698 self.selfdestructed_addresses.push(address);
699 }
700
701 acc.mark_selfdestructed_locally();
702
703 // `had_balance` records the balance that left the account so it can be restored
704 // on revert.
705 let had_balance = if target != address {
706 // Balance was transferred to target above; zero out the source.
707 acc.info.balance = U256::ZERO;
708 // EIP-7708: transfer log for balance moved to a different address.
709 self.eip7708_transfer_log(address, target, balance);
710 balance
711 } else if spec.is_enabled_in(AMSTERDAM) {
712 // EIP-8246: self-destruct to self no longer burns the balance. The balance is
713 // kept and the account is cleared at finalization
714 // (see `eip8246_clear_selfdestructed_accounts`).
715 U256::ZERO
716 } else {
717 // Pre-EIP-8246: self-destruct to self burns the balance.
718 acc.info.balance = U256::ZERO;
719 balance
720 };
721
722 Some(ENTRY::account_destroyed(
723 address,
724 target,
725 destroyed_status,
726 had_balance,
727 ))
728 } else if address != target {
729 acc.info.balance = U256::ZERO;
730 // EIP-7708: emit appropriate log for selfdestruct
731 // Transfer log for balance transferred to different address
732 self.eip7708_transfer_log(address, target, balance);
733 Some(ENTRY::balance_transfer(address, target, balance))
734 } else {
735 // State is not changed:
736 // * if we are after Cancun upgrade and
737 // * Selfdestruct account that is created in the same transaction and
738 // * Specify the target is same as selfdestructed account. The balance stays unchanged.
739 None
740 };
741
742 if let Some(entry) = journal_entry {
743 self.journal.push(entry);
744 };
745
746 Ok(StateLoad {
747 data: SelfDestructResult {
748 had_value: !balance.is_zero(),
749 target_exists: !is_empty,
750 previously_destroyed: destroyed_status
751 == SelfdestructionRevertStatus::RepeatedSelfdestruction,
752 },
753 is_cold,
754 })
755 }
756
757 /// Loads account into memory. return if it is cold or warm accessed
758 #[inline]
759 pub fn load_account<'a, 'db, DB: Database>(
760 &'a mut self,
761 db: &'db mut DB,
762 address: Address,
763 ) -> Result<StateLoad<&'a Account>, DB::Error>
764 where
765 'db: 'a,
766 {
767 self.load_account_optional(db, address, false, false)
768 .map_err(JournalLoadError::unwrap_db_error)
769 }
770
771 /// Loads account into memory. If account is EIP-7702 type it will additionally
772 /// load delegated account.
773 ///
774 /// It will mark both this and delegated account as warm loaded.
775 ///
776 /// Returns information about the account (If it is empty or cold loaded) and if present the information
777 /// about the delegated account (If it is cold loaded).
778 #[inline]
779 pub fn load_account_delegated<DB: Database>(
780 &mut self,
781 db: &mut DB,
782 address: Address,
783 ) -> Result<StateLoad<AccountLoad>, DB::Error> {
784 let spec = self.cfg.spec;
785 let is_eip7702_enabled = spec.is_enabled_in(SpecId::PRAGUE);
786 let account = self
787 .load_account_optional(db, address, is_eip7702_enabled, false)
788 .map_err(JournalLoadError::unwrap_db_error)?;
789 let is_empty = account.state_clear_aware_is_empty(spec);
790
791 let mut account_load = StateLoad::new(
792 AccountLoad {
793 is_delegate_account_cold: None,
794 is_empty,
795 },
796 account.is_cold,
797 );
798
799 // load delegate code if account is EIP-7702
800 if let Some(address) = account
801 .info
802 .code
803 .as_ref()
804 .and_then(Bytecode::eip7702_address)
805 {
806 let delegate_account = self
807 .load_account_optional(db, address, true, false)
808 .map_err(JournalLoadError::unwrap_db_error)?;
809 account_load.data.is_delegate_account_cold = Some(delegate_account.is_cold);
810 }
811
812 Ok(account_load)
813 }
814
815 /// Loads account and its code. If account is already loaded it will load its code.
816 ///
817 /// It will mark account as warm loaded. If not existing Database will be queried for data.
818 ///
819 /// In case of EIP-7702 delegated account will not be loaded,
820 /// [`Self::load_account_delegated`] should be used instead.
821 #[inline]
822 pub fn load_code<'a, 'db, DB: Database>(
823 &'a mut self,
824 db: &'db mut DB,
825 address: Address,
826 ) -> Result<StateLoad<&'a Account>, DB::Error>
827 where
828 'db: 'a,
829 {
830 self.load_account_optional(db, address, true, false)
831 .map_err(JournalLoadError::unwrap_db_error)
832 }
833
834 /// Loads account into memory. If account is already loaded it will be marked as warm.
835 #[inline]
836 pub fn load_account_optional<'a, 'db, DB: Database>(
837 &'a mut self,
838 db: &'db mut DB,
839 address: Address,
840 load_code: bool,
841 skip_cold_load: bool,
842 ) -> Result<StateLoad<&'a Account>, JournalLoadError<DB::Error>>
843 where
844 'db: 'a,
845 {
846 let mut load = self.load_account_mut_optional(db, address, skip_cold_load)?;
847 if load_code {
848 load.data.load_code_preserve_error()?;
849 }
850 Ok(load.map(|i| i.into_account()))
851 }
852
853 /// Loads account into memory. If account is already loaded it will be marked as warm.
854 #[inline]
855 pub fn load_account_mut<'a, 'db, DB: Database>(
856 &'a mut self,
857 db: &'db mut DB,
858 address: Address,
859 ) -> Result<StateLoad<JournaledAccount<'a, DB, ENTRY>>, DB::Error>
860 where
861 'db: 'a,
862 {
863 self.load_account_mut_optional(db, address, false)
864 .map_err(JournalLoadError::unwrap_db_error)
865 }
866
867 /// Loads account. If account is already loaded it will be marked as warm.
868 #[inline]
869 pub fn load_account_mut_optional_code<'a, 'db, DB: Database>(
870 &'a mut self,
871 db: &'db mut DB,
872 address: Address,
873 load_code: bool,
874 skip_cold_load: bool,
875 ) -> Result<StateLoad<JournaledAccount<'a, DB, ENTRY>>, JournalLoadError<DB::Error>>
876 where
877 'db: 'a,
878 {
879 let mut load = self.load_account_mut_optional(db, address, skip_cold_load)?;
880 if load_code {
881 load.data.load_code_preserve_error()?;
882 }
883 Ok(load)
884 }
885
886 /// Gets the account mut reference.
887 ///
888 /// # Load Unsafe
889 ///
890 /// Use this function only if you know what you are doing. It will not mark the account as warm or cold.
891 /// It will not bump transition_id or return if it is cold or warm loaded. This function is useful
892 /// when we know account is warm, touched and already loaded.
893 ///
894 /// It is useful when we want to access storage from account that is currently being executed.
895 #[inline]
896 pub fn get_account_mut<'a, 'db, DB: Database>(
897 &'a mut self,
898 db: &'db mut DB,
899 address: Address,
900 ) -> Option<JournaledAccount<'a, DB, ENTRY>>
901 where
902 'db: 'a,
903 {
904 let account = self.state.get_mut(&address)?;
905 Some(JournaledAccount::new(
906 address,
907 account,
908 &mut self.journal,
909 db,
910 self.warm_addresses.access_list(),
911 self.transaction_id,
912 ))
913 }
914
915 /// Loads account. If account is already loaded it will be marked as warm.
916 #[inline(never)]
917 pub fn load_account_mut_optional<'a, 'db, DB: Database>(
918 &'a mut self,
919 db: &'db mut DB,
920 address: Address,
921 skip_cold_load: bool,
922 ) -> Result<StateLoad<JournaledAccount<'a, DB, ENTRY>>, JournalLoadError<DB::Error>>
923 where
924 'db: 'a,
925 {
926 let (account, is_cold) = match self.state.entry(address) {
927 Entry::Occupied(entry) => {
928 let account = entry.into_mut();
929
930 // skip load if account is cold.
931 let mut is_cold = account.is_cold_transaction_id(self.transaction_id);
932
933 if unlikely(is_cold) {
934 is_cold = self
935 .warm_addresses
936 .check_is_cold(&address, skip_cold_load)?;
937
938 // mark it warm.
939 account.mark_warm_with_transaction_id(self.transaction_id);
940
941 // if it is cold loaded and we have selfdestructed locally it means that
942 // account was selfdestructed in previous transaction and we need to clear its information and storage.
943 if account.is_selfdestructed_locally() {
944 account.selfdestruct();
945 account.unmark_selfdestructed_locally();
946 }
947 account.set_current_info_as_original();
948
949 // unmark locally created
950 account.unmark_created_locally();
951
952 // journal loading of cold account.
953 self.journal.push(ENTRY::account_warmed(address));
954 }
955 (account, is_cold)
956 }
957 Entry::Vacant(vac) => {
958 // Precompiles, among some other account(access list and coinbase included)
959 // are warm loaded so we need to take that into account
960 let is_cold = self
961 .warm_addresses
962 .check_is_cold(&address, skip_cold_load)?;
963
964 let account = if let Some(account) = db.basic(address)? {
965 let mut account: Account = account.into();
966 account.transaction_id = self.transaction_id;
967 account
968 } else {
969 Account::new_not_existing(self.transaction_id)
970 };
971
972 // journal loading of cold account.
973 if is_cold {
974 self.journal.push(ENTRY::account_warmed(address));
975 }
976
977 (vac.insert(account), is_cold)
978 }
979 };
980
981 Ok(StateLoad::new(
982 JournaledAccount::new(
983 address,
984 account,
985 &mut self.journal,
986 db,
987 self.warm_addresses.access_list(),
988 self.transaction_id,
989 ),
990 is_cold,
991 ))
992 }
993
994 /// Loads storage slot.
995 #[inline]
996 pub fn sload<DB: Database>(
997 &mut self,
998 db: &mut DB,
999 address: Address,
1000 key: StorageKey,
1001 skip_cold_load: bool,
1002 ) -> Result<StateLoad<StorageValue>, JournalLoadError<DB::Error>> {
1003 self.load_account_mut(db, address)?
1004 .sload_concrete_error(key, skip_cold_load)
1005 .map(|s| s.map(|s| s.present_value))
1006 }
1007
1008 /// Loads storage slot.
1009 ///
1010 /// If account is not present it will return [`JournalLoadError::ColdLoadSkipped`] error.
1011 #[inline]
1012 pub fn sload_assume_account_present<DB: Database>(
1013 &mut self,
1014 db: &mut DB,
1015 address: Address,
1016 key: StorageKey,
1017 skip_cold_load: bool,
1018 ) -> Result<StateLoad<StorageValue>, JournalLoadError<DB::Error>> {
1019 let Some(mut account) = self.get_account_mut(db, address) else {
1020 return Err(JournalLoadError::ColdLoadSkipped);
1021 };
1022
1023 account
1024 .sload_concrete_error(key, skip_cold_load)
1025 .map(|s| s.map(|s| s.present_value))
1026 }
1027
1028 /// Stores storage slot.
1029 ///
1030 /// If account is not present it will load from database
1031 #[inline]
1032 pub fn sstore<DB: Database>(
1033 &mut self,
1034 db: &mut DB,
1035 address: Address,
1036 key: StorageKey,
1037 new: StorageValue,
1038 skip_cold_load: bool,
1039 ) -> Result<StateLoad<SStoreResult>, JournalLoadError<DB::Error>> {
1040 self.load_account_mut(db, address)?
1041 .sstore_concrete_error(key, new, skip_cold_load)
1042 }
1043
1044 /// Stores storage slot.
1045 ///
1046 /// And returns (original,present,new) slot value.
1047 ///
1048 /// **Note**: Account should already be present in our state.
1049 #[inline]
1050 pub fn sstore_assume_account_present<DB: Database>(
1051 &mut self,
1052 db: &mut DB,
1053 address: Address,
1054 key: StorageKey,
1055 new: StorageValue,
1056 skip_cold_load: bool,
1057 ) -> Result<StateLoad<SStoreResult>, JournalLoadError<DB::Error>> {
1058 let Some(mut account) = self.get_account_mut(db, address) else {
1059 return Err(JournalLoadError::ColdLoadSkipped);
1060 };
1061
1062 account.sstore_concrete_error(key, new, skip_cold_load)
1063 }
1064
1065 /// Read transient storage tied to the account.
1066 ///
1067 /// EIP-1153: Transient storage opcodes
1068 #[inline]
1069 pub fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue {
1070 self.transient_storage.get_value(address, key)
1071 }
1072
1073 /// Store transient storage tied to the account.
1074 ///
1075 /// If values is different add entry to the journal
1076 /// so that old state can be reverted if that action is needed.
1077 ///
1078 /// EIP-1153: Transient storage opcodes
1079 #[inline]
1080 pub fn tstore(&mut self, address: Address, key: StorageKey, new: StorageValue) {
1081 let had_value = if new.is_zero() {
1082 // if new values is zero, remove entry from transient storage.
1083 // if previous values was some insert it inside journal.
1084 // If it is none nothing should be inserted.
1085 self.transient_storage.remove_value(address, key)
1086 } else {
1087 // insert values
1088 let previous_value = self
1089 .transient_storage
1090 .insert_value(address, key, new)
1091 .unwrap_or_default();
1092
1093 // check if previous value is same
1094 if previous_value != new {
1095 // if it is different, insert previous values inside journal.
1096 Some(previous_value)
1097 } else {
1098 None
1099 }
1100 };
1101
1102 if let Some(had_value) = had_value {
1103 // insert in journal only if value was changed.
1104 self.journal
1105 .push(ENTRY::transient_storage_changed(address, key, had_value));
1106 }
1107 }
1108
1109 /// Pushes log into subroutine.
1110 #[inline]
1111 pub fn log(&mut self, log: Log) {
1112 self.logs.push(log);
1113 }
1114
1115 /// Creates and pushes an EIP-7708 ETH transfer log.
1116 ///
1117 /// This emits a LOG3 with the Transfer event signature, matching ERC-20 transfer events.
1118 /// Only emitted if EIP-7708 is enabled (Amsterdam and later) and balance is non-zero.
1119 ///
1120 /// [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708)
1121 #[inline]
1122 pub fn eip7708_transfer_log(&mut self, from: Address, to: Address, balance: U256) {
1123 // Only emit log if EIP-7708 is enabled and balance is non-zero
1124 if !self.cfg.spec.is_enabled_in(AMSTERDAM) || self.cfg.eip7708_disabled || balance.is_zero()
1125 {
1126 return;
1127 }
1128
1129 // Create LOG3 with Transfer(address,address,uint256) event signature
1130 // Topic[0]: Transfer event signature
1131 // Topic[1]: from address (zero-padded to 32 bytes)
1132 // Topic[2]: to address (zero-padded to 32 bytes)
1133 // Data: amount in wei (big-endian uint256)
1134 let topics = std::vec![
1135 ETH_TRANSFER_LOG_TOPIC,
1136 B256::left_padding_from(from.as_slice()),
1137 B256::left_padding_from(to.as_slice()),
1138 ];
1139 let data = Bytes::copy_from_slice(&balance.to_be_bytes::<32>());
1140
1141 self.logs.push(Log {
1142 address: ETH_TRANSFER_LOG_ADDRESS,
1143 data: LogData::new(topics, data).expect("3 topics is valid"),
1144 });
1145 }
1146}
1147
1148#[cfg(test)]
1149mod tests {
1150 use super::*;
1151 use context_interface::journaled_state::entry::JournalEntry;
1152 use database_interface::EmptyDB;
1153 use primitives::{address, HashSet, U256};
1154 use state::AccountInfo;
1155
1156 #[test]
1157 fn test_sload_skip_cold_load() {
1158 let mut journal = JournalInner::<JournalEntry>::new();
1159 let test_address = address!("1000000000000000000000000000000000000000");
1160 let test_key = U256::from(1);
1161
1162 // Insert account into state
1163 let account_info = AccountInfo {
1164 balance: U256::from(1000),
1165 nonce: 1,
1166 code_hash: KECCAK_EMPTY,
1167 code: Some(Bytecode::default()),
1168 account_id: None,
1169 };
1170 journal
1171 .state
1172 .insert(test_address, Account::from(account_info));
1173
1174 // Add storage slot to access list (make it warm)
1175 let mut access_list = HashMap::default();
1176 let mut storage_keys = HashSet::default();
1177 storage_keys.insert(test_key);
1178 access_list.insert(test_address, storage_keys);
1179 journal.warm_addresses.set_access_list(access_list);
1180
1181 // Try to sload with skip_cold_load=true - should succeed because slot is in access list
1182 let mut db = EmptyDB::new();
1183 let result = journal.sload_assume_account_present(&mut db, test_address, test_key, true);
1184
1185 // Should succeed and return as warm
1186 assert!(result.is_ok());
1187 let state_load = result.unwrap();
1188 assert!(!state_load.is_cold); // Should be warm
1189 assert_eq!(state_load.data, U256::ZERO); // Empty slot
1190 }
1191}