ethrex_levm/db/gen_db.rs
1use std::sync::Arc;
2
3use ethrex_common::Address;
4use ethrex_common::H256;
5use ethrex_common::U256;
6use ethrex_common::types::Account;
7use ethrex_common::types::Code;
8use ethrex_common::types::CodeMetadata;
9#[cfg(feature = "rayon")]
10use ethrex_common::types::block_access_list::SlotChange;
11use ethrex_common::types::block_access_list::{
12 BalAddressIndex, BlockAccessList, BlockAccessListRecorder,
13};
14use ethrex_common::utils::ZERO_U256;
15
16use super::Database;
17use crate::account::AccountStatus;
18use crate::account::LevmAccount;
19use crate::call_frame::CallFrameBackup;
20use crate::errors::InternalError;
21use crate::errors::VMError;
22use crate::precompiles::PrecompileMoves;
23use crate::utils::account_to_levm_account;
24use crate::utils::restore_cache_state;
25use crate::vm::VM;
26use ethrex_common::seeded_hash::{SeededHashMap, SeededHashSet};
27pub use ethrex_common::types::AccountUpdate;
28use rustc_hash::FxHashMap;
29use std::collections::hash_map::Entry;
30
31/// Accounts touched by execution, by address. Seeded: contracts choose which addresses
32/// they touch (see [`SeededHashMap`]).
33pub type CacheDB = SeededHashMap<Address, LevmAccount>;
34
35/// Per-tx BAL cursor for lazy on-read prefix materialization.
36/// `bal_index = tx_idx + 1`; cursor's effective max_idx is `bal_index - 1`,
37/// matching `seed_db_from_bal`'s `max_idx = tx_idx` semantics.
38#[derive(Clone)]
39pub struct LazyBalCursor {
40 pub bal: Arc<BlockAccessList>,
41 pub bal_index: u32,
42 pub index: Arc<BalAddressIndex>,
43}
44
45/// Apply balance, nonce, and code fields from BAL for a single account into `db`.
46///
47/// Returns `true` if any info field was applied; `false` if all field positions
48/// were 0 (no info changes for this account at indices <= max_idx).
49/// Does NOT touch `account.storage`.
50#[cfg(feature = "rayon")]
51pub fn seed_one_address_info_from_bal(
52 db: &mut GeneralizedDatabase,
53 bal: &BlockAccessList,
54 acct_idx: usize,
55 max_idx: u32,
56) -> Result<bool, InternalError> {
57 use ethrex_common::types::AccountInfo;
58
59 let acct_changes = bal
60 .accounts()
61 .get(acct_idx)
62 .ok_or(InternalError::AccountNotFound)?;
63 let addr = acct_changes.address;
64
65 let balance_pos = acct_changes
66 .balance_changes
67 .partition_point(|c| c.block_access_index <= max_idx);
68 let nonce_pos = acct_changes
69 .nonce_changes
70 .partition_point(|c| c.block_access_index <= max_idx);
71 let code_pos = acct_changes
72 .code_changes
73 .partition_point(|c| c.block_access_index <= max_idx);
74
75 if balance_pos == 0 && nonce_pos == 0 && code_pos == 0 {
76 return Ok(false);
77 }
78
79 // Compute code update before borrowing acc (borrow checker: can't access
80 // db.codes while acc holds a mutable borrow of db).
81 let code_update = if code_pos > 0 {
82 let entry = acct_changes
83 .code_changes
84 .get(code_pos.saturating_sub(1))
85 .ok_or(InternalError::AccountNotFound)?;
86 Some(code_from_bal(&entry.new_code))
87 } else {
88 None
89 };
90
91 // When BAL covers all account info fields (balance + nonce + code), insert
92 // a default LevmAccount directly to skip the store/shared_base lookup.
93 // For partial coverage, load from store to fill missing fields.
94 //
95 // Invariant: `account.storage` is left empty here. Storage is materialized
96 // lazily through `get_storage_value` (which also consults the cursor).
97 // Callers must NOT assume `account.storage` is fully populated after this
98 // path — iterate-all-keys / bulk-read patterns will see an empty map.
99 let has_all_info = balance_pos > 0 && nonce_pos > 0 && code_pos > 0;
100 if has_all_info {
101 use ethrex_common::constants::EMPTY_KECCAK_HASH;
102 let balance = acct_changes
103 .balance_changes
104 .get(balance_pos.saturating_sub(1))
105 .ok_or(InternalError::AccountNotFound)?
106 .post_balance;
107 let nonce = acct_changes
108 .nonce_changes
109 .get(nonce_pos.saturating_sub(1))
110 .ok_or(InternalError::AccountNotFound)?
111 .post_nonce;
112 let code_hash = code_update
113 .as_ref()
114 .map(|(h, _)| *h)
115 .unwrap_or(*EMPTY_KECCAK_HASH);
116 let acc = db
117 .current_accounts_state
118 .entry(addr)
119 .or_insert_with(|| LevmAccount {
120 info: AccountInfo::default(),
121 storage: Default::default(),
122 has_storage: false,
123 status: AccountStatus::Modified,
124 exists: true,
125 });
126 acc.info.balance = balance;
127 acc.info.nonce = nonce;
128 acc.info.code_hash = code_hash;
129 acc.mark_modified();
130 } else {
131 db.get_account(addr)
132 .map_err(|e| InternalError::Custom(format!("seed_db_from_bal load: {e}")))?;
133 let acc = db
134 .get_account_mut(addr)
135 .map_err(|e| InternalError::Custom(format!("seed bal: {e}")))?;
136
137 if balance_pos > 0
138 && let Some(entry) = acct_changes
139 .balance_changes
140 .get(balance_pos.saturating_sub(1))
141 {
142 acc.info.balance = entry.post_balance;
143 }
144 if nonce_pos > 0
145 && let Some(entry) = acct_changes.nonce_changes.get(nonce_pos.saturating_sub(1))
146 {
147 acc.info.nonce = entry.post_nonce;
148 }
149 if let Some((hash, _)) = &code_update {
150 acc.info.code_hash = *hash;
151 }
152 }
153
154 // Insert code object after acc borrow is released. The entry may already be there
155 // because a frame still running deployed the same bytes; record the hash either way, so
156 // that frame's revert keeps it. `code_from_bal` yields no code object only for empty
157 // code, which the store always serves.
158 if let Some((hash, Some(code_obj))) = code_update {
159 db.codes.entry(hash).or_insert(code_obj);
160 db.bal_seeded_code_hashes.insert(hash);
161 }
162
163 Ok(true)
164}
165
166/// Select the post-value of a single `SlotChange` up to `max_idx`.
167///
168/// Pure read; returns `Some(value)` if any `slot_changes` entry has
169/// `block_access_index <= max_idx`, `None` otherwise.
170#[cfg(feature = "rayon")]
171pub fn post_value_at_or_before(sc: &SlotChange, max_idx: u32) -> Option<U256> {
172 let pos = sc
173 .slot_changes
174 .partition_point(|c| c.block_access_index <= max_idx);
175 sc.slot_changes
176 .get(pos.saturating_sub(1))
177 .filter(|_| pos > 0)
178 .map(|c| c.post_value)
179}
180
181/// Read the post-value of a single storage slot from the BAL up to `max_idx`.
182///
183/// O(1) slot resolution via the precomputed `slot_idx_by_account` map in
184/// `BalAddressIndex`. Pure read; does not touch `db`.
185#[cfg(feature = "rayon")]
186pub fn seed_one_storage_slot_from_bal(
187 bal: &BlockAccessList,
188 index: &BalAddressIndex,
189 acct_idx: usize,
190 key: H256,
191 max_idx: u32,
192) -> Option<U256> {
193 let acct_changes = bal.accounts().get(acct_idx)?;
194 let slot_map = index.slot_idx_by_account.get(acct_idx)?;
195 let sc_idx = *slot_map.get(&key)?;
196 let sc = acct_changes.storage_changes.get(sc_idx)?;
197 post_value_at_or_before(sc, max_idx)
198}
199
200/// Compute code hash and optional `Code` object from raw bytecode in a BAL entry.
201#[cfg(feature = "rayon")]
202pub fn code_from_bal(new_code: &bytes::Bytes) -> (H256, Option<Code>) {
203 use ethrex_common::constants::EMPTY_KECCAK_HASH;
204 if new_code.is_empty() {
205 (*EMPTY_KECCAK_HASH, None)
206 } else {
207 let code_obj = Code::from_bytecode(new_code.clone(), ðrex_crypto::NativeCrypto);
208 let hash = code_obj.hash;
209 (hash, Some(code_obj))
210 }
211}
212
213#[derive(Clone)]
214pub struct GeneralizedDatabase {
215 pub store: Arc<dyn Database>,
216 pub current_accounts_state: CacheDB,
217 pub initial_accounts_state: CacheDB,
218 /// Shared read-only base state (pre-block snapshot of system-touched addresses for
219 /// parallel groups, captured from `initial_accounts_state` after `prepare_block`).
220 /// Checked on `load_account` AFTER the `lazy_bal` hook so the BAL overlay (which
221 /// includes system-call effects at idx 0) takes precedence for any address the BAL
222 /// covers. Accounts are cloned into `initial_accounts_state` on first access.
223 pub shared_base: Option<Arc<CacheDB>>,
224 /// Seeded: deployed code is called by hash, and its deployer can grind the hash.
225 pub codes: SeededHashMap<H256, Code>,
226 /// Hashes of the codes the block access list provided to `codes`. A frame revert keeps
227 /// these entries even when the frame inserted them (see [`Self::evict_reverted_code`]).
228 pub(crate) bal_seeded_code_hashes: SeededHashSet<H256>,
229 pub code_metadata: SeededHashMap<H256, CodeMetadata>,
230 pub tx_backup: Option<CallFrameBackup>,
231 /// Optional BAL recorder for EIP-7928 Block Access List recording.
232 pub bal_recorder: Option<BlockAccessListRecorder>,
233 /// When true, skip cloning accounts into `initial_accounts_state` on load.
234 /// Used for parallel per-tx DBs where `get_state_transitions_tx` is never called
235 /// (state transitions come from BAL instead).
236 skip_initial_tracking: bool,
237 /// Optional tracker for BAL validation: records addresses accessed via load_account.
238 /// Enabled only during parallel execution to detect extraneous BAL pure-access entries.
239 pub accessed_accounts: Option<SeededHashSet<Address>>,
240 /// Optional BAL cursor for lazy per-read prefix materialization.
241 /// When set, account loads and storage reads consult the BAL before hitting the store.
242 pub lazy_bal: Option<LazyBalCursor>,
243 /// Simulation-only precompile relocations (`movePrecompileToAddress`).
244 /// `None` on every consensus path, where dispatch is unchanged.
245 pub precompile_moves: Option<Arc<PrecompileMoves>>,
246}
247
248impl GeneralizedDatabase {
249 pub fn new(store: Arc<dyn Database>) -> Self {
250 Self {
251 store,
252 current_accounts_state: Default::default(),
253 initial_accounts_state: Default::default(),
254 shared_base: None,
255 tx_backup: None,
256 codes: Default::default(),
257 bal_seeded_code_hashes: Default::default(),
258 code_metadata: Default::default(),
259 bal_recorder: None,
260 skip_initial_tracking: false,
261 accessed_accounts: None,
262 lazy_bal: None,
263 precompile_moves: None,
264 }
265 }
266
267 /// Creates a new GeneralizedDatabase with a shared read-only base state.
268 /// Used for parallel execution groups that share post-system-call state.
269 /// Skips initial_accounts_state tracking since parallel per-tx DBs never
270 /// call get_state_transitions_tx (state comes from BAL instead).
271 pub fn new_with_shared_base(store: Arc<dyn Database>, shared_base: Arc<CacheDB>) -> Self {
272 Self::new_with_shared_base_and_capacity(store, shared_base, 0)
273 }
274
275 /// Like `new_with_shared_base` but pre-allocates account/code maps to
276 /// `capacity` entries, avoiding rehashing during BAL seeding.
277 pub fn new_with_shared_base_and_capacity(
278 store: Arc<dyn Database>,
279 shared_base: Arc<CacheDB>,
280 capacity: usize,
281 ) -> Self {
282 Self {
283 store,
284 current_accounts_state: CacheDB::with_capacity_and_hasher(capacity, Default::default()),
285 initial_accounts_state: Default::default(),
286 shared_base: Some(shared_base),
287 tx_backup: None,
288 codes: SeededHashMap::with_capacity_and_hasher(capacity / 4, Default::default()),
289 bal_seeded_code_hashes: Default::default(),
290 code_metadata: Default::default(),
291 bal_recorder: None,
292 skip_initial_tracking: true,
293 accessed_accounts: None,
294 lazy_bal: None,
295 precompile_moves: None,
296 }
297 }
298
299 /// Enables BAL recording for EIP-7928.
300 /// After enabling, state changes will be recorded during execution.
301 pub fn enable_bal_recording(&mut self) {
302 self.bal_recorder = Some(BlockAccessListRecorder::new());
303 }
304
305 /// Disables BAL recording.
306 pub fn disable_bal_recording(&mut self) {
307 self.bal_recorder = None;
308 }
309
310 /// Sets the current block access index for BAL recording per EIP-7928 spec (uint32).
311 /// Call this before each transaction or phase.
312 pub fn set_bal_index(&mut self, index: u32) {
313 if let Some(recorder) = &mut self.bal_recorder {
314 recorder.set_block_access_index(index);
315 }
316 }
317
318 /// Takes the BAL recorder and builds the final BlockAccessList.
319 /// Returns None if recording was not enabled.
320 pub fn take_bal(&mut self) -> Option<BlockAccessList> {
321 self.bal_recorder.take().map(|recorder| recorder.build())
322 }
323
324 /// Returns a mutable reference to the BAL recorder if enabled.
325 pub fn bal_recorder_mut(&mut self) -> Option<&mut BlockAccessListRecorder> {
326 self.bal_recorder.as_mut()
327 }
328
329 /// Only used within Levm Runner, where the accounts already have all the storage pre-loaded, not used in real case scenarios.
330 pub fn new_with_account_state(
331 store: Arc<dyn Database>,
332 current_accounts_state: FxHashMap<Address, Account>,
333 ) -> Self {
334 let mut codes: SeededHashMap<H256, Code> = Default::default();
335 let levm_accounts: CacheDB = current_accounts_state
336 .into_iter()
337 .map(|(address, account)| {
338 let (levm_account, code) = account_to_levm_account(account);
339 codes.insert(levm_account.info.code_hash, code);
340 (address, levm_account)
341 })
342 .collect();
343 Self {
344 store,
345 current_accounts_state: levm_accounts.clone(),
346 initial_accounts_state: levm_accounts,
347 shared_base: None,
348 tx_backup: None,
349 codes,
350 bal_seeded_code_hashes: Default::default(),
351 code_metadata: Default::default(),
352 bal_recorder: None,
353 skip_initial_tracking: false,
354 accessed_accounts: None,
355 lazy_bal: None,
356 precompile_moves: None,
357 }
358 }
359
360 // ================== Account related functions =====================
361 /// Loads account
362 /// If it's the first time it's loaded store it in `initial_accounts_state` and also cache it in `current_accounts_state` for making changes to it
363 fn load_account(&mut self, address: Address) -> Result<&mut LevmAccount, InternalError> {
364 if let Some(tracker) = &mut self.accessed_accounts {
365 tracker.insert(address);
366 }
367
368 // One lookup on the hot path (every account access of an executing tx lands here). The
369 // borrow checker rejects returning the `get_mut` borrow from one branch while the other
370 // branches keep using `self`, so the reference goes through a raw pointer. This is the
371 // known limitation on conditionally returned borrows (NLL problem case #3); once the
372 // Polonius borrow checker ships, the plain `if let` compiles and the `unsafe` can go.
373 if let Some(account) = self.current_accounts_state.get_mut(&address) {
374 let account: *mut LevmAccount = account;
375 // SAFETY: `account` comes from a live `&mut` into `current_accounts_state`, and
376 // nothing touches the map before this returns it with the lifetime of `&mut self`.
377 #[expect(unsafe_code, reason = "conditional return of a map borrow, see above")]
378 return Ok(unsafe { &mut *account });
379 }
380
381 // Initial-state fast path.
382 //
383 // Clone info/flags only, NOT the storage map. The streaming executor drains
384 // `current_accounts_state` into `initial_accounts_state` every few txs, so a hot account
385 // (token contracts, etc.) is re-faulted here repeatedly with an ever-growing storage map
386 // it barely reads. The touched slots are faulted back in lazily by `get_storage_value`,
387 // which resolves a `current` miss against `initial` (the committed baseline) before the
388 // store — so this stays correct and the diff invariant holds. See `clone_without_storage`.
389 //
390 // Exception: destroyed-and-recreated accounts must be full-cloned. `get_storage_value`
391 // early-returns 0 for `DestroyedModified` *before* the `initial` fallback (an unwritten
392 // slot of a destroyed account must read 0, never the stale value in `initial`). With an
393 // info-only clone, a committed slot written after recreation — folded into `initial`
394 // wholesale by the per-flush drain-back — would also read 0, since the lazy fallback is
395 // never reached. Carrying the storage on the clone keeps those committed slots in
396 // `current`, where the `account.storage` hit precedes the early-return.
397 if let Some(account) = self.initial_accounts_state.get(&address) {
398 let clone = match account.status {
399 AccountStatus::Destroyed | AccountStatus::DestroyedModified => account.clone(),
400 _ => account.clone_without_storage(),
401 };
402 return Ok(self.current_accounts_state.entry(address).or_insert(clone));
403 }
404
405 // Lazy-BAL hook: if the cursor finds this address, materialize info from the BAL
406 // before consulting `shared_base` or the store.
407 //
408 // Ordering matters: `shared_base` holds the pre-block snapshot of system-touched
409 // addresses, but the canonical pre-state for tx N is the BAL prefix up to its
410 // `bal_index` (= system-call effects at idx 0 plus all prior txs). If `shared_base`
411 // were consulted first for an address it covers, the BAL overlay would be skipped
412 // and tx N would observe stale balance/nonce/code (consensus bug for system-touched
413 // predeploys mutated by a prior tx in the same block).
414 //
415 // We `.take()` the cursor out of `self.lazy_bal` before calling
416 // `seed_one_address_info_from_bal`. For partial-coverage accounts (e.g. balance-only
417 // change with no nonce/code) the helper calls `db.get_account(addr)` internally to
418 // load the base state before overlaying. If `self.lazy_bal` were still `Some(...)`
419 // at that point, `get_account` → `load_account` would re-enter this same block and
420 // recurse infinitely. Taking the cursor out breaks the cycle: the inner call sees
421 // `lazy_bal = None` and falls through to `shared_base`/store. We restore the cursor
422 // unconditionally afterward (even on error) so the outer caller still sees it.
423 #[cfg(feature = "rayon")]
424 {
425 let cursor_opt = self.lazy_bal.take();
426 let helper_result = if let Some(cursor) = cursor_opt.as_ref() {
427 debug_assert!(
428 cursor.bal_index >= 1,
429 "LazyBalCursor bal_index must be >= 1"
430 );
431 let max_idx = cursor.bal_index.saturating_sub(1);
432 if let Some(&acct_idx) = cursor.index.addr_to_idx.get(&address) {
433 Some(
434 seed_one_address_info_from_bal(self, &cursor.bal, acct_idx, max_idx)
435 .map(|_| true),
436 )
437 } else {
438 None
439 }
440 } else {
441 None
442 };
443 // Restore the cursor before propagating any error or returning.
444 self.lazy_bal = cursor_opt;
445 if let Some(result) = helper_result {
446 result.map_err(|e| InternalError::Custom(format!("lazy_bal seed: {e}")))?;
447 if self.current_accounts_state.contains_key(&address) {
448 return self
449 .current_accounts_state
450 .get_mut(&address)
451 .ok_or(InternalError::AccountNotFound);
452 }
453 }
454 }
455
456 // Check shared_base (read-only pre-block snapshot) before hitting store.
457 if let Some(ref base) = self.shared_base
458 && let Some(account) = base.get(&address)
459 {
460 let account = account.clone();
461 if !self.skip_initial_tracking {
462 self.initial_accounts_state.insert(address, account.clone());
463 }
464 return Ok(self
465 .current_accounts_state
466 .entry(address)
467 .or_insert(account));
468 }
469
470 // Store fallback.
471 let state = self.store.get_account_state(address)?;
472 let account = LevmAccount::from(state);
473 if !self.skip_initial_tracking {
474 self.initial_accounts_state.insert(address, account.clone());
475 }
476 Ok(self
477 .current_accounts_state
478 .entry(address)
479 .or_insert(account))
480 }
481
482 /// Gets reference of an account
483 pub fn get_account(&mut self, address: Address) -> Result<&LevmAccount, InternalError> {
484 Ok(self.load_account(address)?)
485 }
486
487 /// Gets mutable reference of an account
488 /// Warning: Use directly only if outside of the EVM, otherwise use `vm.get_account_mut` because it contemplates call frame backups.
489 pub fn get_account_mut(&mut self, address: Address) -> Result<&mut LevmAccount, InternalError> {
490 let acc = self.load_account(address)?;
491 acc.mark_modified();
492 Ok(acc)
493 }
494
495 /// Evicts a code a reverted frame inserted into the by-hash cache, so a later read of the
496 /// same hash goes to the store and is recorded in an execution witness. A code the block
497 /// access list provided is kept: the store may not hold code deployed earlier in the block
498 /// yet, so the seeded account's reads rely on the cache entry. If the seed ran first, the
499 /// frame never tracked the hash, so keeping the entry makes both orderings leave the same
500 /// cache.
501 #[inline]
502 pub(crate) fn evict_reverted_code(&mut self, code_hash: &H256) {
503 if !self.bal_seeded_code_hashes.contains(code_hash) {
504 self.codes.remove(code_hash);
505 }
506 }
507
508 /// Gets code immutably given the code hash.
509 /// Use this only inside of the VM, when we don't surely know if the code is in the cache or not
510 /// But e.g. in `get_state_transitions` just do `db.codes.get(code_hash)` because we know for sure code is there.
511 pub fn get_code(&mut self, code_hash: H256) -> Result<&Code, InternalError> {
512 match self.codes.entry(code_hash) {
513 Entry::Occupied(entry) => Ok(entry.into_mut()),
514 Entry::Vacant(entry) => {
515 let code = self.store.get_account_code(code_hash)?;
516 Ok(entry.insert(code))
517 }
518 }
519 }
520
521 /// Shortcut for getting the code when we only have the address of an account and we don't need anything else.
522 pub fn get_account_code(&mut self, address: Address) -> Result<&Code, InternalError> {
523 let code_hash = self.get_account(address)?.info.code_hash;
524 self.get_code(code_hash)
525 }
526
527 /// Gets code metadata immutably given the code hash.
528 pub fn get_code_metadata(&mut self, code_hash: H256) -> Result<&CodeMetadata, InternalError> {
529 match self.code_metadata.entry(code_hash) {
530 Entry::Occupied(entry) => Ok(entry.into_mut()),
531 Entry::Vacant(entry) => {
532 // Answer from the size-only store lookup rather than the bytecode: a
533 // contract's code is up to 24KB and lives out-of-line, so materializing it
534 // to return a length is the dominant cost of EXTCODESIZE. Code already
535 // loaded for another reason answers for free.
536 #[expect(clippy::as_conversions, reason = "same sized types (on 64bit)")]
537 let length = match self.codes.get(&code_hash) {
538 Some(code) => code.len() as u64,
539 None => self.store.get_code_metadata(code_hash)?.length,
540 };
541
542 // Insert into cache and return reference
543 Ok(entry.insert(CodeMetadata { length }))
544 }
545 }
546 }
547
548 /// Convenience method to get code length by address (optimized for EXTCODESIZE).
549 pub fn get_code_length(&mut self, address: Address) -> Result<usize, InternalError> {
550 use ethrex_common::constants::EMPTY_KECCAK_HASH;
551
552 let code_hash = self.get_account(address)?.info.code_hash;
553 if code_hash == *EMPTY_KECCAK_HASH {
554 return Ok(0);
555 }
556 let metadata = self.get_code_metadata(code_hash)?;
557 #[expect(clippy::as_conversions, reason = "same sized types (on 64bit)")]
558 Ok(metadata.length as usize)
559 }
560
561 /// Gets storage slot from Database, storing in initial_accounts_state for efficiency when getting AccountUpdates.
562 fn get_value_from_database(
563 &mut self,
564 address: Address,
565 key: H256,
566 ) -> Result<U256, InternalError> {
567 let value = self.store.get_storage_value(address, key)?;
568 if self.skip_initial_tracking {
569 return Ok(value);
570 }
571 // Account must already be in initial_accounts_state
572 match self.initial_accounts_state.get_mut(&address) {
573 Some(account) => {
574 account.storage.insert(key, value);
575 }
576 None => {
577 // If we are fetching the storage of an account it means that we previously fetched the account from database before.
578 return Err(InternalError::msg(
579 "Account not found in InMemoryDB when fetching storage",
580 ));
581 }
582 }
583 Ok(value)
584 }
585
586 /// Gets the transaction backup, if it exists.
587 /// It only works if the `BackupHook` was enabled during the transaction execution.
588 pub fn get_tx_backup(&self) -> Result<CallFrameBackup, InternalError> {
589 self.tx_backup.clone().ok_or_else(|| {
590 InternalError::Custom(
591 "Transaction backup not found. Was BackupHook enabled?".to_string(),
592 )
593 })
594 }
595
596 /// Undoes the last transaction by restoring the cache state to the state before the transaction.
597 pub fn undo_last_transaction(&mut self) -> Result<(), VMError> {
598 let tx_backup = self.get_tx_backup()?;
599 restore_cache_state(self, tx_backup)?;
600 Ok(())
601 }
602
603 pub fn get_state_transitions(&mut self) -> Result<Vec<AccountUpdate>, VMError> {
604 // Upper bound: `current_accounts_state` holds every *read* account, while the loop
605 // emits only *modified* ones, so on read-heavy blocks this over-reserves. Still a
606 // single non-reallocating alloc (never empty — the sender is always modified), which
607 // beats the repeated growth of starting from `vec![]`.
608 let mut account_updates: Vec<AccountUpdate> =
609 Vec::with_capacity(self.current_accounts_state.len());
610 for (address, new_state_account) in self.current_accounts_state.iter() {
611 if new_state_account.is_unmodified() {
612 // Skip processing account that we know wasn't mutably accessed during execution
613 continue;
614 }
615 // In case the account is not in immutable_cache (rare) we search for it in the actual database.
616 let initial_state_account =
617 self.initial_accounts_state.get(address).ok_or_else(|| {
618 VMError::Internal(InternalError::Custom(format!(
619 "Failed to get account {address} from immutable cache",
620 )))
621 })?;
622
623 let mut acc_info_updated = false;
624 let mut storage_updated = false;
625
626 // 1. Account Info has been updated if balance, nonce or bytecode changed.
627 if initial_state_account.info.balance != new_state_account.info.balance {
628 acc_info_updated = true;
629 }
630
631 if initial_state_account.info.nonce != new_state_account.info.nonce {
632 acc_info_updated = true;
633 }
634
635 let code = if initial_state_account.info.code_hash != new_state_account.info.code_hash {
636 acc_info_updated = true;
637 // code should be in `codes`
638 Some(
639 self.codes
640 .get(&new_state_account.info.code_hash)
641 .ok_or_else(|| {
642 VMError::Internal(InternalError::Custom(format!(
643 "Failed to get code for account {address}"
644 )))
645 })?,
646 )
647 } else {
648 None
649 };
650
651 // Account will have only its storage removed if it was Destroyed and then modified
652 // Edge cases that can make this true:
653 // 1. Account was destroyed and created again afterwards.
654 // 2. Account was destroyed but then was sent ETH, so it's not going to be completely removed from the trie.
655 // A `Destroyed` account may hold slots too: a reverted re-creation puts back
656 // the zeros its writes replaced, and those have no old value either.
657 let was_destroyed = matches!(
658 new_state_account.status,
659 AccountStatus::Destroyed | AccountStatus::DestroyedModified
660 );
661 // Only emit removed_storage if the account actually had storage in the trie.
662 // If it didn't (e.g. account was created within the batch), there's nothing to
663 // remove, and emitting removed_storage=true would cause a spurious empty
664 // account to be inserted into the state trie.
665 let removed_storage = was_destroyed && initial_state_account.has_storage;
666
667 // 2. Storage has been updated if the current value is different from the one before execution.
668 let mut added_storage: SeededHashMap<_, _> = Default::default();
669
670 for (key, new_value) in &new_state_account.storage {
671 let old_value = if !was_destroyed {
672 initial_state_account.storage.get(key).ok_or_else(|| { VMError::Internal(InternalError::Custom(format!("Failed to get old value from account's initial storage for address: {address:?}. For key: {key:?}")))})?
673 } else {
674 // There's not an "old value" if the contract was destroyed and re-created.
675 &ZERO_U256
676 };
677
678 if new_value != old_value {
679 added_storage.insert(*key, *new_value);
680 storage_updated = true;
681 }
682 }
683
684 let info = if acc_info_updated {
685 Some(new_state_account.info.clone())
686 } else {
687 None
688 };
689
690 // "At the end of the transaction, any account touched by the execution of that transaction which is now empty SHALL instead become non-existent (i.e. deleted)."
691 // ethrex is a post-Merge client, empty accounts have already been pruned from the trie on Mainnet by the Merge (see EIP-161), so we won't have any empty accounts in the trie.
692 let was_empty = initial_state_account.is_empty();
693 let removed = new_state_account.is_empty() && !was_empty;
694
695 if !removed && !acc_info_updated && !storage_updated && !removed_storage {
696 // Account hasn't been updated
697 continue;
698 }
699
700 let account_update = AccountUpdate {
701 address: *address,
702 removed,
703 info,
704 code: code.cloned(),
705 added_storage,
706 removed_storage,
707 };
708
709 account_updates.push(account_update);
710 }
711 self.initial_accounts_state.clear();
712 self.current_accounts_state.clear();
713 self.codes.clear();
714 self.bal_seeded_code_hashes.clear();
715 self.code_metadata.clear();
716 Ok(account_updates)
717 }
718
719 pub fn get_state_transitions_tx(&mut self) -> Result<Vec<AccountUpdate>, VMError> {
720 // Exact upper bound: one update per modified account. Capture the length before draining.
721 let mut account_updates: Vec<AccountUpdate> =
722 Vec::with_capacity(self.current_accounts_state.len());
723 for (address, new_state_account) in self.current_accounts_state.drain() {
724 if new_state_account.is_unmodified() {
725 // Skip processing account that we know wasn't mutably accessed during execution
726 continue;
727 }
728 // [LIE] In case the account is not in immutable_cache (rare) we search for it in the actual database.
729 let initial_state_account =
730 self.initial_accounts_state.get(&address).ok_or_else(|| {
731 VMError::Internal(InternalError::Custom(format!(
732 "Failed to get account {address} from immutable cache",
733 )))
734 })?;
735
736 let mut acc_info_updated = false;
737 let mut storage_updated = false;
738
739 // 1. Account Info has been updated if balance, nonce or bytecode changed.
740 if initial_state_account.info.balance != new_state_account.info.balance {
741 acc_info_updated = true;
742 }
743
744 if initial_state_account.info.nonce != new_state_account.info.nonce {
745 acc_info_updated = true;
746 }
747
748 let code = if initial_state_account.info.code_hash != new_state_account.info.code_hash {
749 acc_info_updated = true;
750 // code should be in `codes`
751 Some(
752 self.codes
753 .get(&new_state_account.info.code_hash)
754 .cloned()
755 .ok_or_else(|| {
756 VMError::Internal(InternalError::Custom(format!(
757 "Failed to get code for account {address}"
758 )))
759 })?,
760 )
761 } else {
762 None
763 };
764
765 // Whether the diff baseline is already a post-destruction state: an earlier
766 // batch of this block destroyed the account, and the fold below carried the
767 // status over so reads of slots not written since keep returning zero instead
768 // of the stale storage still in the store. The baseline's storage then holds
769 // every slot committed since the destruction, and a slot absent from it is
770 // zero, so this batch diffs against those committed values, and a write of
771 // zero to a committed slot is a deletion.
772 let baseline_destroyed = matches!(
773 initial_state_account.status,
774 AccountStatus::Destroyed | AccountStatus::DestroyedModified
775 );
776 let currently_destroyed = matches!(
777 new_state_account.status,
778 AccountStatus::Destroyed | AccountStatus::DestroyedModified
779 );
780 // Destroyed within this batch: whatever storage it had, in the trie or
781 // committed by earlier batches, is gone, so every slot's old value is zero.
782 // Edge cases that make this true for an account still holding slots:
783 // 1. Account was destroyed and created again afterwards.
784 // 2. Account was destroyed but then was sent ETH, so it's not going to be completely removed from the trie.
785 // 3. A re-creation of a `Destroyed` account was reverted, which puts back
786 // the zeros its writes replaced.
787 let destroyed_this_batch = currently_destroyed && !baseline_destroyed;
788 // Only emit removed_storage if the account actually had storage in the trie.
789 // If it didn't (e.g. account was created within the batch), there's nothing to
790 // remove, and emitting removed_storage=true would cause a spurious empty
791 // account to be inserted into the state trie.
792 let removed_storage = destroyed_this_batch && initial_state_account.has_storage;
793
794 // 2. Storage has been updated if the current value is different from the one before execution.
795 let mut added_storage: SeededHashMap<_, _> = Default::default();
796
797 for (key, new_value) in &new_state_account.storage {
798 let old_value = if destroyed_this_batch {
799 // There's not an "old value" if the contract was destroyed and re-created.
800 ZERO_U256
801 } else if baseline_destroyed {
802 initial_state_account
803 .storage
804 .get(key)
805 .copied()
806 .unwrap_or(ZERO_U256)
807 } else {
808 *initial_state_account.storage.get(key).ok_or_else(|| { VMError::Internal(InternalError::Custom(format!("Failed to get old value from account's initial storage for address: {address}")))})?
809 };
810
811 if *new_value != old_value {
812 added_storage.insert(*key, *new_value);
813 storage_updated = true;
814 }
815 }
816
817 // The account is loaded with a full copy of a post-destruction baseline, so a
818 // slot the baseline committed that the account no longer holds was cleared by
819 // a destruction within this batch: delete it from the trie, where it is the
820 // only storage the account has left.
821 if baseline_destroyed && currently_destroyed {
822 for (key, old_value) in &initial_state_account.storage {
823 if !old_value.is_zero() && !new_state_account.storage.contains_key(key) {
824 added_storage.insert(*key, ZERO_U256);
825 storage_updated = true;
826 }
827 }
828 }
829
830 let info = acc_info_updated.then(|| new_state_account.info.clone());
831
832 // "At the end of the transaction, any account touched by the execution of that transaction which is now empty SHALL instead become non-existent (i.e. deleted)."
833 // ethrex is a post-Merge client, empty accounts have already been pruned from the trie on Mainnet by the Merge (see EIP-161), so we won't have any empty accounts in the trie.
834 let was_empty = initial_state_account.is_empty();
835 let removed = new_state_account.is_empty() && !was_empty;
836
837 if !removed && !acc_info_updated && !storage_updated && !removed_storage {
838 // Account hasn't been updated
839 continue;
840 }
841
842 // Fold this flush's committed state into the diff baseline. With the info-only clone
843 // in `load_account`, `new_state_account.storage` holds only the slots touched this
844 // batch, so we MERGE them into the existing baseline instead of replacing it: a plain
845 // replace would drop the committed values of slots written in an earlier batch but not
846 // re-touched here (the old full-storage clone preserved them implicitly, which is why
847 // a replace was correct before). On destroy the prior storage is invalid, so the
848 // drained account is authoritative and replaces it wholesale (old behavior).
849 match self.initial_accounts_state.get_mut(&address) {
850 Some(initial_account)
851 if !matches!(
852 new_state_account.status,
853 AccountStatus::Destroyed | AccountStatus::DestroyedModified
854 ) =>
855 {
856 // Move each field out of the about-to-be-dropped drained account.
857 initial_account.info = new_state_account.info;
858 initial_account.status = new_state_account.status;
859 initial_account.has_storage = new_state_account.has_storage;
860 initial_account.exists = new_state_account.exists;
861 // `extend` overwrites touched slots with their committed value and keeps
862 // untouched baseline slots from earlier batches.
863 initial_account.storage.extend(new_state_account.storage);
864 }
865 _ => {
866 self.initial_accounts_state
867 .insert(address, new_state_account);
868 }
869 }
870
871 let account_update = AccountUpdate {
872 address,
873 removed,
874 info,
875 code,
876 added_storage,
877 removed_storage,
878 };
879
880 account_updates.push(account_update);
881 }
882 Ok(account_updates)
883 }
884}
885
886impl<'a> VM<'a> {
887 // ================== Account related functions =====================
888
889 /*
890 Each callframe has a CallFrameBackup, which contains:
891
892 - A list with account infos of every account that was modified so far (balance, nonce, bytecode/code hash)
893 - A list with a tuple (address, storage) that contains, for every account whose storage was accessed, a hashmap
894 of the storage slots that were modified, with their original value.
895
896 On every call frame, at the end one of two things can happen:
897
898 - The transaction succeeds. In this case:
899 - The CallFrameBackup of the current callframe has to be merged with the backup of its parent, in the following way:
900 For every account that's present in the parent backup, do nothing (i.e. keep the one that's already there).
901 For every account that's NOT present in the parent backup but is on the child backup, add the child backup to it.
902 Do the same for every individual storage slot.
903 - The transaction reverts. In this case:
904 - Insert into the cache the value of every account on the CallFrameBackup.
905 - Insert into the cache the value of every storage slot in every account on the CallFrameBackup.
906
907 */
908 pub fn get_account_mut(&mut self, address: Address) -> Result<&mut LevmAccount, InternalError> {
909 // Backup must be taken before mark_modified flips `exists` to true.
910 let account = self.db.get_account(address)?;
911 self.current_call_frame
912 .call_frame_backup
913 .backup_account_info(address, account)?;
914
915 let account = self.db.get_account_mut(address)?;
916 Ok(account)
917 }
918
919 pub fn increase_account_balance(
920 &mut self,
921 address: Address,
922 increase: U256,
923 ) -> Result<(), InternalError> {
924 if increase.is_zero() {
925 return Ok(());
926 }
927 let account = self.get_account_mut(address)?;
928
929 // Get initial balance BEFORE modification (avoids duplicate lookup)
930 let initial_balance = account.info.balance;
931
932 // Modify balance
933 account.info.balance = account
934 .info
935 .balance
936 .checked_add(increase)
937 .ok_or(InternalError::Overflow)?;
938 let new_balance = account.info.balance;
939
940 // Record initial and changed balance for BAL
941 if let Some(recorder) = self.db.bal_recorder.as_mut() {
942 recorder.set_initial_balance(address, initial_balance);
943 recorder.record_balance_change(address, new_balance);
944 }
945
946 Ok(())
947 }
948
949 pub fn decrease_account_balance(
950 &mut self,
951 address: Address,
952 decrease: U256,
953 ) -> Result<(), InternalError> {
954 if decrease.is_zero() {
955 return Ok(());
956 }
957 let account = self.get_account_mut(address)?;
958
959 // Get initial balance BEFORE modification (avoids duplicate lookup)
960 let initial_balance = account.info.balance;
961
962 // Modify balance
963 account.info.balance = account
964 .info
965 .balance
966 .checked_sub(decrease)
967 .ok_or(InternalError::Underflow)?;
968 let new_balance = account.info.balance;
969
970 // Record initial and changed balance for BAL
971 if let Some(recorder) = self.db.bal_recorder.as_mut() {
972 recorder.set_initial_balance(address, initial_balance);
973 recorder.record_balance_change(address, new_balance);
974 }
975
976 Ok(())
977 }
978
979 pub fn transfer(
980 &mut self,
981 from: Address,
982 to: Address,
983 value: U256,
984 ) -> Result<(), InternalError> {
985 if value != U256::zero() {
986 self.decrease_account_balance(from, value)?;
987 self.increase_account_balance(to, value)?;
988 }
989
990 Ok(())
991 }
992
993 /// Updates bytecode of given account.
994 pub fn update_account_bytecode(
995 &mut self,
996 address: Address,
997 new_bytecode: Code,
998 ) -> Result<(), InternalError> {
999 // Record code change for BAL
1000 if let Some(recorder) = self.db.bal_recorder.as_mut() {
1001 // Capture initial code BEFORE recording the change.
1002 // This is needed for:
1003 // 1. Distinguishing CREATE empty code vs delegation clear
1004 // 2. Net-zero code change detection (e.g., delegate then reset in same tx)
1005 let current_code_bytes = self
1006 .db
1007 .current_accounts_state
1008 .get(&address)
1009 .and_then(|account| self.db.codes.get(&account.info.code_hash))
1010 .map(|c| c.code_bytes())
1011 .unwrap_or_default();
1012 let has_code = !current_code_bytes.is_empty();
1013 recorder.capture_initial_code_presence(address, has_code);
1014 recorder.set_initial_code(address, current_code_bytes);
1015 recorder.record_code_change(address, new_bytecode.code_bytes());
1016 }
1017
1018 let acc = self.get_account_mut(address)?;
1019 let code_hash = new_bytecode.hash;
1020 acc.info.code_hash = new_bytecode.hash;
1021 if let Entry::Vacant(entry) = self.db.codes.entry(code_hash) {
1022 entry.insert(new_bytecode);
1023 // Track the insertion so a frame revert evicts it: a stale entry
1024 // would serve a later read of the same hash from the cache,
1025 // hiding the store read from execution-witness recording.
1026 self.current_call_frame
1027 .call_frame_backup
1028 .inserted_code_hashes
1029 .push(code_hash);
1030 }
1031 Ok(())
1032 }
1033
1034 // =================== Nonce related functions ======================
1035 /// Increments the nonce of the given account.
1036 /// Per EIP-7928, nonce changes are recorded for:
1037 /// - EOA senders
1038 /// - Contracts performing CREATE/CREATE2
1039 /// - Deployed contracts
1040 /// - EIP-7702 authorities
1041 pub fn increment_account_nonce(&mut self, address: Address) -> Result<u64, InternalError> {
1042 let account = self.get_account_mut(address)?;
1043 account.info.nonce = account
1044 .info
1045 .nonce
1046 .checked_add(1)
1047 .ok_or(InternalError::Overflow)?;
1048 let new_nonce = account.info.nonce;
1049
1050 // Record nonce change for BAL
1051 if let Some(recorder) = self.db.bal_recorder.as_mut() {
1052 recorder.record_nonce_change(address, new_nonce);
1053 }
1054
1055 Ok(new_nonce)
1056 }
1057
1058 /// SSTORE-specialized storage access path that returns current and original values together.
1059 /// This keeps the SSTORE hot path tighter by avoiding extra method-level plumbing.
1060 #[inline(always)]
1061 pub fn access_storage_slot_for_sstore(
1062 &mut self,
1063 address: Address,
1064 key: H256,
1065 ) -> Result<(U256, U256, bool), InternalError> {
1066 let storage_slot_was_cold = self.substate.add_accessed_slot(address, key);
1067 // SSTORE pre-image flows transitively through get_storage_value, which consults lazy_bal.
1068 let current_value = self.get_storage_value(address, key)?;
1069 let original_value = match self
1070 .storage_original_values
1071 .entry(address)
1072 .or_default()
1073 .entry(key)
1074 {
1075 Entry::Occupied(entry) => *entry.get(),
1076 Entry::Vacant(entry) => *entry.insert(current_value),
1077 };
1078 Ok((current_value, original_value, storage_slot_was_cold))
1079 }
1080
1081 /// Records a storage slot read to BAL after gas checks have passed.
1082 /// Per EIP-7928: "If pre-state validation fails, the target is never accessed and must not appear in BAL."
1083 /// This function should be called AFTER the gas check succeeds.
1084 pub fn record_storage_slot_to_bal(&mut self, address: Address, key: U256) {
1085 if let Some(recorder) = self.db.bal_recorder.as_mut() {
1086 recorder.record_storage_read(address, key);
1087 }
1088 }
1089
1090 /// Gets storage value of an account, caching it if not already cached.
1091 #[inline(always)]
1092 pub fn get_storage_value(
1093 &mut self,
1094 address: Address,
1095 key: H256,
1096 ) -> Result<U256, InternalError> {
1097 if let Some(account) = self.db.current_accounts_state.get(&address) {
1098 if let Some(value) = account.storage.get(&key) {
1099 return Ok(*value);
1100 }
1101 // If the account was destroyed and then created then we cannot rely on the DB to obtain storage values
1102 if account.status == AccountStatus::DestroyedModified {
1103 return Ok(U256::zero());
1104 }
1105 } else {
1106 // When requesting storage of an account we should've previously requested and cached the account
1107 return Err(InternalError::AccountNotFound);
1108 }
1109
1110 // Lazy-BAL hook: copy result out BEFORE taking &mut on current_accounts_state
1111 // so the immutable borrow of lazy_bal is released before the mutable reborrow.
1112 #[cfg(feature = "rayon")]
1113 let bal_hit: Option<U256> = self.db.lazy_bal.as_ref().and_then(|cursor| {
1114 debug_assert!(
1115 cursor.bal_index >= 1,
1116 "LazyBalCursor bal_index must be >= 1"
1117 );
1118 let max_idx = cursor.bal_index.saturating_sub(1);
1119 let &acct_idx = cursor.index.addr_to_idx.get(&address)?;
1120 seed_one_storage_slot_from_bal(&cursor.bal, &cursor.index, acct_idx, key, max_idx)
1121 });
1122 #[cfg(feature = "rayon")]
1123 if let Some(value) = bal_hit {
1124 let account = self
1125 .db
1126 .current_accounts_state
1127 .get_mut(&address)
1128 .ok_or(InternalError::AccountNotFound)?;
1129 account.storage.insert(key, value);
1130 return Ok(value);
1131 }
1132
1133 // Resolve against `initial_accounts_state` before the store. With the info-only clone in
1134 // `load_account`, `current.storage` starts empty on a re-fault, but `initial` holds this
1135 // slot's committed in-block value (from the per-flush drain-back) — whereas `self.store`
1136 // only has the stale pre-block value (in-block writes go to the merkleizer, never back to
1137 // the store). Reading `initial` first returns the committed value and keeps the slot in
1138 // `initial` (the diff baseline), so the invariant "every key in `current.storage` is also
1139 // in `initial.storage`" is preserved. `.copied()` releases the immutable borrow before
1140 // the mutable one below.
1141 if let Some(value) = self
1142 .db
1143 .initial_accounts_state
1144 .get(&address)
1145 .and_then(|account| account.storage.get(&key))
1146 .copied()
1147 {
1148 let account = self
1149 .db
1150 .current_accounts_state
1151 .get_mut(&address)
1152 .ok_or(InternalError::AccountNotFound)?;
1153 account.storage.insert(key, value);
1154 return Ok(value);
1155 }
1156
1157 let value = self.db.get_value_from_database(address, key)?;
1158
1159 // Cache-fill only: this is a read-path miss, not a state mutation.
1160 let account = self
1161 .db
1162 .current_accounts_state
1163 .get_mut(&address)
1164 .ok_or(InternalError::AccountNotFound)?;
1165 account.storage.insert(key, value);
1166
1167 Ok(value)
1168 }
1169
1170 /// Updates storage of an account, caching it if not already cached.
1171 pub fn update_account_storage(
1172 &mut self,
1173 address: Address,
1174 key: H256,
1175 slot_key: U256,
1176 new_value: U256,
1177 current_value: U256,
1178 ) -> Result<(), InternalError> {
1179 self.backup_storage_slot(address, key, current_value)?;
1180
1181 // Record storage change for BAL (EIP-7928).
1182 // SSTORE that changes the value (new != current) → storage write.
1183 // SSTORE with same value (new == current) → storage read (no actual mutation).
1184 if let Some(recorder) = self.db.bal_recorder.as_mut() {
1185 if new_value != current_value {
1186 // Record original value before first write. If final value equals original
1187 // after all tx operations, the slot becomes a read per EIP-7928 net-zero filtering.
1188 // This captures the value BEFORE the first write in this transaction
1189 recorder.capture_pre_storage(address, slot_key, current_value);
1190 // Actual write
1191 recorder.record_storage_write(address, slot_key, new_value);
1192 } else {
1193 // No-op write (post == pre) - record as read per EIP-7928
1194 recorder.record_storage_read(address, slot_key);
1195 }
1196 }
1197
1198 let account = self.get_account_mut(address)?;
1199 account.storage.insert(key, new_value);
1200 Ok(())
1201 }
1202
1203 pub fn backup_storage_slot(
1204 &mut self,
1205 address: Address,
1206 key: H256,
1207 current_value: U256,
1208 ) -> Result<(), InternalError> {
1209 self.current_call_frame
1210 .call_frame_backup
1211 .original_account_storage_slots
1212 .entry(address)
1213 .or_default()
1214 .entry(key)
1215 .or_insert(current_value);
1216
1217 Ok(())
1218 }
1219}