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