1use crate::{
4 eth::backend::db::{
5 BLOCKHASH_HISTORY, Db, MaybeForkedDatabase, MaybeFullDatabase, SerializableAccountRecord,
6 SerializableBlock, SerializableHistoricalStates, SerializableState,
7 SerializableTransaction, StateDb, cache_block_hash,
8 },
9 mem::state::{StateRootCache, state_root},
10};
11use alloy_primitives::{
12 Address, B256, U256,
13 map::{AddressMap, B256Map, HashSet},
14};
15use alloy_rpc_types::BlockId;
16use foundry_evm::backend::{BlockchainDb, DatabaseError, DatabaseResult, StateSnapshot};
17use imbl::HashMap as PersistentMap;
18use parking_lot::Mutex;
19use revm::{
20 Database, DatabaseCommit,
21 bytecode::Bytecode,
22 context::BlockEnv,
23 database::{AccountState, DatabaseRef, DbAccount},
24 state::{Account, AccountInfo},
25};
26use std::sync::OnceLock;
27
28pub use foundry_evm::backend::MemDb;
30use foundry_evm::backend::RevertStateSnapshotAction;
31
32#[derive(Debug, Default)]
34pub struct StateRootDb {
35 inner: MemDb,
36 state_root: Mutex<StateRootCache>,
37 history: Mutex<HistoricalStateCache>,
38 block_hash_head: Option<U256>,
40}
41
42impl StateRootDb {
43 pub fn new(track_history: bool) -> Self {
50 Self {
51 history: Mutex::new(HistoricalStateCache {
52 disabled: !track_history,
53 ..Default::default()
54 }),
55 ..Default::default()
56 }
57 }
58
59 fn normalize_block_hashes(&mut self) {
60 let block_hashes = &mut self.inner.inner.cache.block_hashes;
61 let Some(head) = block_hashes.keys().copied().max() else {
62 self.block_hash_head = None;
63 return;
64 };
65 let min_number = head.saturating_sub(U256::from(BLOCKHASH_HISTORY));
66 block_hashes.retain(|cached, _| *cached >= min_number && *cached <= head);
67 self.block_hash_head = Some(head);
68 }
69}
70
71#[derive(Debug, Default)]
73struct HistoricalStateCache {
74 state: Option<PersistentStateDb>,
75 dirty: AddressMap<DirtyHistoricalAccount>,
76 disabled: bool,
78}
79
80#[derive(Debug, Default)]
81struct DirtyHistoricalAccount {
82 storage: HashSet<U256>,
83 reset_storage: bool,
84}
85
86impl HistoricalStateCache {
87 fn record_changes(&mut self, changes: &AddressMap<Account>) {
88 if self.disabled {
89 return;
90 }
91 for (address, account) in changes {
92 if !account.is_touched() {
93 continue;
94 }
95
96 let dirty = self.dirty.entry(*address).or_default();
97 dirty.reset_storage |= account.is_created() || account.is_selfdestructed();
98 dirty.storage.extend(account.changed_storage_slots().map(|(slot, _)| *slot));
99 }
100 }
101
102 fn record_account(&mut self, address: Address) {
103 if self.disabled {
104 return;
105 }
106 self.dirty.entry(address).or_default();
107 }
108
109 fn record_storage(&mut self, address: Address, slot: U256) {
110 if self.disabled {
111 return;
112 }
113 self.dirty.entry(address).or_default().storage.insert(slot);
114 }
115
116 fn record_block_hash(&mut self, number: U256, hash: B256, is_next: bool) {
117 if self.disabled {
118 return;
119 }
120 let Some(state) = &mut self.state else { return };
121 if is_next {
122 let min_number = number.saturating_sub(U256::from(BLOCKHASH_HISTORY));
123 if min_number > U256::ZERO {
124 state.block_hashes.remove(&(min_number - U256::ONE));
125 }
126 state.block_hashes.insert(number, hash);
127 return;
128 }
129
130 let head = state.block_hashes.keys().copied().max().map_or(number, |head| head.max(number));
131 let min_number = head.saturating_sub(U256::from(BLOCKHASH_HISTORY));
132 state.block_hashes.retain(|cached, _| *cached >= min_number && *cached <= head);
133 if number >= min_number {
134 state.block_hashes.insert(number, hash);
135 }
136 }
137
138 fn invalidate(&mut self) {
139 self.state = None;
140 self.dirty.clear();
141 }
142
143 fn snapshot(&mut self, db: &MemDb) -> PersistentStateDb {
144 if self.disabled {
145 return PersistentStateDb::from_mem_db(db);
146 }
147 let Some(state) = &mut self.state else {
148 let state = PersistentStateDb::from_mem_db(db);
149 self.state = Some(state.clone());
150 self.dirty.clear();
151 return state;
152 };
153
154 for (address, dirty) in std::mem::take(&mut self.dirty) {
155 let Some(account) = db.inner.cache.accounts.get(&address) else {
156 state.accounts.remove(&address);
157 continue;
158 };
159
160 let mut storage = if dirty.reset_storage {
161 account.storage.iter().map(|(slot, value)| (*slot, *value)).collect()
162 } else {
163 state
164 .accounts
165 .get(&address)
166 .map(|account| account.storage.clone())
167 .unwrap_or_default()
168 };
169 if !dirty.reset_storage {
170 for slot in dirty.storage {
171 if let Some(value) = account.storage.get(&slot) {
172 storage.insert(slot, *value);
173 } else {
174 storage.remove(&slot);
175 }
176 }
177 }
178
179 let info = account_info_with_code(&account.info, &db.inner.cache.contracts);
180 if let Some(code) = &info.code {
181 state.contracts.insert(info.code_hash(), code.clone());
182 }
183 state.accounts.insert(
184 address,
185 PersistentAccount { info, account_state: account.account_state.clone(), storage },
186 );
187 }
188
189 state.full = OnceLock::new();
190 state.clone()
191 }
192}
193
194#[derive(Clone, Debug, Default)]
195struct PersistentAccount {
196 info: AccountInfo,
197 account_state: AccountState,
198 storage: PersistentMap<U256, U256>,
199}
200
201#[derive(Clone, Debug, Default)]
203struct PersistentStateDb {
204 accounts: PersistentMap<Address, PersistentAccount>,
205 contracts: PersistentMap<B256, Bytecode>,
206 block_hashes: PersistentMap<U256, B256>,
207 #[allow(clippy::type_complexity)]
208 full: OnceLock<AddressMap<DbAccount>>,
209}
210
211impl PersistentStateDb {
212 fn from_mem_db(db: &MemDb) -> Self {
213 let contracts = db
214 .inner
215 .cache
216 .contracts
217 .iter()
218 .map(|(hash, code)| (*hash, code.clone()))
219 .collect::<PersistentMap<_, _>>();
220 let accounts = db
221 .inner
222 .cache
223 .accounts
224 .iter()
225 .map(|(address, account)| {
226 (
227 *address,
228 PersistentAccount {
229 info: account_info_with_code(&account.info, &db.inner.cache.contracts),
230 account_state: account.account_state.clone(),
231 storage: account
232 .storage
233 .iter()
234 .map(|(slot, value)| (*slot, *value))
235 .collect(),
236 },
237 )
238 })
239 .collect();
240 let block_hashes =
241 db.inner.cache.block_hashes.iter().map(|(number, hash)| (*number, *hash)).collect();
242 Self { accounts, contracts, block_hashes, full: OnceLock::new() }
243 }
244
245 fn state_snapshot(&self) -> StateSnapshot {
246 StateSnapshot {
247 accounts: self
248 .accounts
249 .iter()
250 .filter(|(_, account)| account.account_state != AccountState::NotExisting)
251 .map(|(address, account)| (*address, account.info.clone()))
252 .collect(),
253 storage: self
254 .accounts
255 .iter()
256 .filter(|(_, account)| account.account_state != AccountState::NotExisting)
257 .map(|(address, account)| {
258 (
259 *address,
260 account.storage.iter().map(|(slot, value)| (*slot, *value)).collect(),
261 )
262 })
263 .collect(),
264 block_hashes: self.block_hashes.iter().map(|(number, hash)| (*number, *hash)).collect(),
265 }
266 }
267
268 fn full_db(&self) -> AddressMap<DbAccount> {
269 self.accounts
270 .iter()
271 .filter(|(_, account)| account.account_state != AccountState::NotExisting)
272 .map(|(address, account)| {
273 (
274 *address,
275 DbAccount {
276 info: account.info.clone(),
277 account_state: account.account_state.clone(),
278 storage: account
279 .storage
280 .iter()
281 .map(|(slot, value)| (*slot, *value))
282 .collect(),
283 },
284 )
285 })
286 .collect()
287 }
288}
289
290fn account_info_with_code(info: &AccountInfo, contracts: &B256Map<Bytecode>) -> AccountInfo {
291 let mut info = info.clone();
292 if info.code.is_none() {
293 info.code = contracts.get(&info.code_hash()).cloned();
294 }
295 info
296}
297
298impl DatabaseRef for PersistentStateDb {
299 type Error = DatabaseError;
300
301 fn basic_ref(&self, address: Address) -> DatabaseResult<Option<AccountInfo>> {
302 Ok(match self.accounts.get(&address) {
303 Some(account) if account.account_state == AccountState::NotExisting => None,
304 Some(account) => Some(account.info.clone()),
305 None => Some(AccountInfo::default()),
306 })
307 }
308
309 fn code_by_hash_ref(&self, code_hash: B256) -> DatabaseResult<Bytecode> {
310 Ok(self.contracts.get(&code_hash).cloned().unwrap_or_default())
311 }
312
313 fn storage_ref(&self, address: Address, index: U256) -> DatabaseResult<U256> {
314 Ok(self
315 .accounts
316 .get(&address)
317 .and_then(|account| account.storage.get(&index).copied())
318 .unwrap_or_default())
319 }
320
321 fn block_hash_ref(&self, number: u64) -> DatabaseResult<B256> {
322 Ok(self.block_hashes.get(&U256::from(number)).copied().unwrap_or_default())
323 }
324}
325
326impl MaybeFullDatabase for PersistentStateDb {
327 fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
328 Some(self.full.get_or_init(|| self.full_db()))
329 }
330
331 fn is_persistent(&self) -> bool {
332 true
333 }
334
335 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
336 let snapshot = self.state_snapshot();
337 self.clear();
338 snapshot
339 }
340
341 fn read_as_state_snapshot(&self) -> StateSnapshot {
342 self.state_snapshot()
343 }
344
345 fn clear(&mut self) {
346 *self = Self::default();
347 }
348
349 fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
350 let StateSnapshot { accounts, mut storage, block_hashes } = snapshot;
351 let mut contracts = PersistentMap::new();
352 let accounts = accounts
353 .into_iter()
354 .map(|(address, info)| {
355 if let Some(code) = &info.code {
356 contracts.insert(info.code_hash(), code.clone());
357 }
358 let storage = storage
359 .remove(&address)
360 .unwrap_or_default()
361 .into_iter()
362 .collect::<PersistentMap<_, _>>();
363 (address, PersistentAccount { info, account_state: AccountState::None, storage })
364 })
365 .collect();
366 let block_hashes = block_hashes.into_iter().collect();
367 *self = Self { accounts, contracts, block_hashes, full: OnceLock::new() };
368 }
369}
370
371impl DatabaseRef for StateRootDb {
372 type Error = DatabaseError;
373
374 fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
375 self.inner.basic_ref(address)
376 }
377
378 fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
379 self.inner.code_by_hash_ref(code_hash)
380 }
381
382 fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
383 self.inner.storage_ref(address, index)
384 }
385
386 fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
387 self.inner.block_hash_ref(number)
388 }
389}
390
391impl Database for StateRootDb {
392 type Error = DatabaseError;
393
394 fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
395 self.state_root.get_mut().record_account(address);
396 self.history.get_mut().record_account(address);
397 self.inner.basic(address)
398 }
399
400 fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
401 self.inner.code_by_hash(code_hash)
402 }
403
404 fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error> {
405 self.state_root.get_mut().record_storage(address, index);
406 self.history.get_mut().record_storage(address, index);
407 self.inner.storage(address, index)
408 }
409
410 fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
411 self.inner.block_hash(number)
412 }
413}
414
415impl DatabaseCommit for StateRootDb {
416 fn commit(&mut self, changes: revm::state::EvmState) {
417 self.state_root.get_mut().record_changes(&changes);
418 self.history.get_mut().record_changes(&changes);
419 self.inner.commit(changes);
420 }
421}
422
423impl Db for StateRootDb {
424 fn insert_account(&mut self, address: Address, account: AccountInfo) {
425 self.state_root.get_mut().record_account(address);
426 self.history.get_mut().record_account(address);
427 Db::insert_account(&mut self.inner, address, account);
428 }
429
430 fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
431 let storage_slot = slot.into();
432 self.state_root.get_mut().record_storage(address, storage_slot);
433 self.history.get_mut().record_storage(address, storage_slot);
434 Db::set_storage_at(&mut self.inner, address, slot, val)
435 }
436
437 fn insert_block_hash(&mut self, number: U256, hash: B256) {
438 let is_next =
439 self.block_hash_head.is_some_and(|head| number == head.saturating_add(U256::ONE));
440 if is_next {
441 let min_number = number.saturating_sub(U256::from(BLOCKHASH_HISTORY));
442 if min_number > U256::ZERO {
443 self.inner.inner.cache.block_hashes.remove(&(min_number - U256::ONE));
444 }
445 self.inner.inner.cache.block_hashes.insert(number, hash);
446 self.block_hash_head = Some(number);
447 } else {
448 self.block_hash_head =
449 Some(cache_block_hash(&mut self.inner.inner.cache.block_hashes, number, hash));
450 }
451 self.history.get_mut().record_block_hash(number, hash, is_next);
452 }
453
454 fn set_block_hashes(&mut self, block_hashes: Vec<(U256, B256)>) {
455 Db::set_block_hashes(&mut self.inner, block_hashes);
456 self.normalize_block_hashes();
457 self.history.get_mut().invalidate();
458 }
459
460 fn dump_state(
461 &self,
462 at: BlockEnv,
463 best_number: u64,
464 blocks: Vec<SerializableBlock>,
465 transactions: Vec<SerializableTransaction>,
466 historical_states: Option<SerializableHistoricalStates>,
467 ) -> DatabaseResult<Option<SerializableState>> {
468 Db::dump_state(&self.inner, at, best_number, blocks, transactions, historical_states)
469 }
470
471 fn snapshot_state(&mut self) -> U256 {
472 Db::snapshot_state(&mut self.inner)
473 }
474
475 fn revert_state(&mut self, id: U256, action: RevertStateSnapshotAction) -> bool {
476 let reverted = Db::revert_state(&mut self.inner, id, action);
477 if reverted {
478 self.state_root.get_mut().invalidate();
479 self.history.get_mut().invalidate();
480 self.block_hash_head = self.inner.inner.cache.block_hashes.keys().copied().max();
481 }
482 reverted
483 }
484
485 fn delete_state_snapshot(&mut self, id: U256) -> bool {
486 Db::delete_state_snapshot(&mut self.inner, id)
487 }
488
489 fn maybe_state_root(&self) -> Option<B256> {
490 Some(self.state_root.lock().root(&self.inner.inner.cache.accounts))
491 }
492
493 fn current_state(&self) -> StateDb {
494 StateDb::new(self.history.lock().snapshot(&self.inner))
495 }
496}
497
498impl MaybeFullDatabase for StateRootDb {
499 fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
500 MaybeFullDatabase::maybe_as_full_db(&self.inner)
501 }
502
503 fn maybe_full_db(&self) -> Option<AddressMap<DbAccount>> {
504 MaybeFullDatabase::maybe_full_db(&self.inner)
505 }
506
507 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
508 self.state_root.get_mut().invalidate();
509 self.history.get_mut().invalidate();
510 self.block_hash_head = None;
511 MaybeFullDatabase::clear_into_state_snapshot(&mut self.inner)
512 }
513
514 fn read_as_state_snapshot(&self) -> StateSnapshot {
515 MaybeFullDatabase::read_as_state_snapshot(&self.inner)
516 }
517
518 fn clear(&mut self) {
519 self.state_root.get_mut().invalidate();
520 self.history.get_mut().invalidate();
521 self.block_hash_head = None;
522 MaybeFullDatabase::clear(&mut self.inner)
523 }
524
525 fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
526 MaybeFullDatabase::init_from_state_snapshot(&mut self.inner, snapshot);
527 self.state_root.get_mut().invalidate();
528 self.history.get_mut().invalidate();
529 self.normalize_block_hashes();
530 }
531}
532
533impl MaybeForkedDatabase for StateRootDb {
534 fn maybe_reset(&mut self, urls: Vec<String>, block_number: BlockId) -> Result<(), String> {
535 self.inner.maybe_reset(urls, block_number)
536 }
537
538 fn maybe_flush_cache(&self) -> Result<(), String> {
539 self.inner.maybe_flush_cache()
540 }
541
542 fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
543 self.inner.maybe_inner()
544 }
545}
546
547impl Db for MemDb {
548 fn insert_account(&mut self, address: Address, account: AccountInfo) {
549 self.inner.insert_account_info(address, account)
550 }
551
552 fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
553 self.inner.insert_account_storage(address, slot.into(), val.into())
554 }
555
556 fn insert_block_hash(&mut self, number: U256, hash: B256) {
557 cache_block_hash(&mut self.inner.cache.block_hashes, number, hash);
558 }
559
560 fn set_block_hashes(&mut self, block_hashes: Vec<(U256, B256)>) {
561 self.inner.cache.block_hashes = block_hashes.into_iter().collect();
562 }
563
564 fn dump_state(
565 &self,
566 at: BlockEnv,
567 best_number: u64,
568 blocks: Vec<SerializableBlock>,
569 transactions: Vec<SerializableTransaction>,
570 historical_states: Option<SerializableHistoricalStates>,
571 ) -> DatabaseResult<Option<SerializableState>> {
572 let accounts = self
573 .inner
574 .cache
575 .accounts
576 .clone()
577 .into_iter()
578 .map(|(k, v)| -> DatabaseResult<_> {
579 let code = if let Some(code) = v.info.code {
580 code
581 } else {
582 self.inner.code_by_hash_ref(v.info.code_hash())?
583 };
584 Ok((
585 k,
586 SerializableAccountRecord {
587 nonce: v.info.nonce,
588 balance: v.info.balance,
589 code: code.original_bytes(),
590 storage: v.storage.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
591 },
592 ))
593 })
594 .collect::<Result<_, _>>()?;
595
596 Ok(Some(SerializableState {
597 block: Some(at),
598 accounts,
599 best_block_number: Some(best_number),
600 blocks,
601 transactions,
602 #[cfg(feature = "monad")]
603 monad_block_participants: Default::default(),
604 #[cfg(feature = "monad")]
605 monad_block_replay_profiles: Default::default(),
606 historical_states,
607 }))
608 }
609
610 fn snapshot_state(&mut self) -> U256 {
612 let id = self.state_snapshots.insert(self.inner.clone());
613 trace!(target: "backend::memdb", "Created new state snapshot {}", id);
614 id
615 }
616
617 fn revert_state(&mut self, id: U256, action: RevertStateSnapshotAction) -> bool {
618 if let Some(state_snapshot) = self.state_snapshots.remove(id) {
619 if action.is_keep() {
620 self.state_snapshots.insert_at(state_snapshot.clone(), id);
621 }
622 self.inner = state_snapshot;
623 trace!(target: "backend::memdb", "Reverted state snapshot {}", id);
624 true
625 } else {
626 warn!(target: "backend::memdb", "No state snapshot to revert for {}", id);
627 false
628 }
629 }
630
631 fn delete_state_snapshot(&mut self, id: U256) -> bool {
632 self.state_snapshots.remove_at(id).is_some()
633 }
634
635 fn maybe_state_root(&self) -> Option<B256> {
636 Some(state_root(&self.inner.cache.accounts))
637 }
638
639 fn current_state(&self) -> StateDb {
640 StateDb::new(Self { inner: self.inner.clone(), ..Default::default() })
641 }
642}
643
644impl MaybeFullDatabase for MemDb {
645 fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
646 Some(&self.inner.cache.accounts)
647 }
648
649 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
650 self.inner.clear_into_state_snapshot()
651 }
652
653 fn read_as_state_snapshot(&self) -> StateSnapshot {
654 self.inner.read_as_state_snapshot()
655 }
656
657 fn clear(&mut self) {
658 self.inner.clear();
659 }
660
661 fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
662 self.inner.init_from_state_snapshot(snapshot)
663 }
664}
665
666impl MaybeForkedDatabase for MemDb {
667 fn maybe_reset(&mut self, _urls: Vec<String>, _block_number: BlockId) -> Result<(), String> {
668 Err("not supported".to_string())
669 }
670
671 fn maybe_flush_cache(&self) -> Result<(), String> {
672 Err("not supported".to_string())
673 }
674
675 fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
676 Err("not supported".to_string())
677 }
678}
679
680#[cfg(test)]
681mod tests {
682 use super::*;
683 use alloy_primitives::{Bytes, address};
684 use revm::primitives::KECCAK_EMPTY;
685 use std::collections::BTreeMap;
686
687 #[test]
690 fn test_dump_reload_cycle() {
691 let test_addr: Address = address!("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
692
693 let mut dump_db = MemDb::default();
694
695 let contract_code = Bytecode::new_raw(Bytes::from("fake contract code"));
696 dump_db.insert_account(
697 test_addr,
698 AccountInfo {
699 balance: U256::from(123456),
700 code_hash: KECCAK_EMPTY,
701 code: Some(contract_code.clone()),
702 nonce: 1234,
703 account_id: None,
704 },
705 );
706 dump_db.set_storage_at(test_addr, U256::from(1234567).into(), U256::ONE.into()).unwrap();
707
708 let state = dump_db
710 .dump_state(Default::default(), 0, Vec::new(), Vec::new(), Default::default())
711 .unwrap()
712 .unwrap();
713
714 let mut load_db = MemDb::default();
715
716 load_db.load_state(state).unwrap();
717
718 let loaded_account = load_db.basic_ref(test_addr).unwrap().unwrap();
719
720 assert_eq!(loaded_account.balance, U256::from(123456));
721 assert_eq!(load_db.code_by_hash_ref(loaded_account.code_hash()).unwrap(), contract_code);
722 assert_eq!(loaded_account.nonce, 1234);
723 assert_eq!(load_db.storage_ref(test_addr, U256::from(1234567)).unwrap(), U256::ONE);
724 }
725
726 #[test]
729 fn test_load_state_merge() {
730 let test_addr: Address = address!("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
731 let test_addr2: Address = address!("0x70997970c51812dc3a010c7d01b50e0d17dc79c8");
732
733 let contract_code = Bytecode::new_raw(Bytes::from("fake contract code"));
734
735 let mut db = MemDb::default();
736
737 db.insert_account(
738 test_addr,
739 AccountInfo {
740 balance: U256::from(123456),
741 code_hash: KECCAK_EMPTY,
742 code: Some(contract_code.clone()),
743 nonce: 1234,
744 account_id: None,
745 },
746 );
747
748 db.set_storage_at(test_addr, U256::from(1234567).into(), U256::ONE.into()).unwrap();
749 db.set_storage_at(test_addr, U256::from(1234568).into(), U256::from(2).into()).unwrap();
750
751 let mut new_state = SerializableState::default();
752
753 new_state.accounts.insert(
754 test_addr2,
755 SerializableAccountRecord {
756 balance: Default::default(),
757 code: Default::default(),
758 nonce: 1,
759 storage: Default::default(),
760 },
761 );
762
763 let mut new_storage = BTreeMap::default();
764 new_storage.insert(U256::from(1234568).into(), U256::from(5).into());
765
766 new_state.accounts.insert(
767 test_addr,
768 SerializableAccountRecord {
769 balance: U256::from(100100),
770 code: contract_code.original_bytes(),
771 nonce: 100,
772 storage: new_storage,
773 },
774 );
775
776 db.load_state(new_state).unwrap();
777
778 let loaded_account = db.basic_ref(test_addr).unwrap().unwrap();
779 let loaded_account2 = db.basic_ref(test_addr2).unwrap().unwrap();
780
781 assert_eq!(loaded_account2.nonce, 1);
782
783 assert_eq!(loaded_account.balance, U256::from(100100));
784 assert_eq!(db.code_by_hash_ref(loaded_account.code_hash()).unwrap(), contract_code);
785 assert_eq!(loaded_account.nonce, 1234);
786 assert_eq!(db.storage_ref(test_addr, U256::from(1234567)).unwrap(), U256::ONE);
787 assert_eq!(db.storage_ref(test_addr, U256::from(1234568)).unwrap(), U256::from(5));
788 }
789
790 #[test]
791 fn incremental_state_root_matches_full_rebuild() {
792 let address = address!("0000000000000000000000000000000000002935");
793 let deleted = Address::with_last_byte(1);
794 let mut db = StateRootDb::default();
795 db.insert_account(address, AccountInfo::default());
796 db.insert_account(deleted, AccountInfo::from_balance(U256::ONE));
797
798 assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
799
800 for slot in 0..1_024 {
802 db.set_storage_at(address, U256::from(slot).into(), B256::from(U256::from(slot + 1)))
803 .unwrap();
804 let _ = db.maybe_state_root().unwrap();
805 }
806
807 db.set_balance(address, U256::from(42)).unwrap();
808 db.set_storage_at(address, U256::from(7).into(), B256::ZERO).unwrap();
809 db.set_storage_at(address, U256::from(8).into(), B256::from(U256::from(2_048))).unwrap();
810 db.inner.inner.cache.accounts.get_mut(&deleted).unwrap().account_state =
811 AccountState::NotExisting;
812 db.state_root.get_mut().record_account(deleted);
813 assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
814
815 let snapshot = db.snapshot_state();
816 db.set_balance(address, U256::from(43)).unwrap();
817 assert!(db.revert_state(snapshot, RevertStateSnapshotAction::RevertRemove));
818 assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
819 }
820
821 #[test]
822 fn evm_block_hash_cache_is_bounded() {
823 let mut db = StateRootDb::default();
824 for number in 0..1_024 {
825 db.insert_block_hash(U256::from(number), B256::from(U256::from(number)));
826 }
827
828 let block_hashes = &db.inner.inner.cache.block_hashes;
829 assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
830 assert!(!block_hashes.contains_key(&U256::from(766)));
831 assert!(block_hashes.contains_key(&U256::from(767)));
832 assert!(block_hashes.contains_key(&U256::from(768)));
833 assert!(block_hashes.contains_key(&U256::from(1_023)));
834
835 let snapshot = db.snapshot_state();
836 db.insert_block_hash(U256::from(1_024), B256::from(U256::from(1_024)));
837 assert!(db.revert_state(snapshot, RevertStateSnapshotAction::RevertRemove));
838 db.insert_block_hash(U256::from(1_024), B256::from(U256::from(1_024)));
839
840 let block_hashes = &db.inner.inner.cache.block_hashes;
841 assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
842 assert!(!block_hashes.contains_key(&U256::from(767)));
843 assert!(block_hashes.contains_key(&U256::from(768)));
844 assert!(block_hashes.contains_key(&U256::from(1_024)));
845 }
846
847 #[test]
848 fn oversized_seeded_block_hash_caches_are_normalized() {
849 let block_hashes = (0..=1_000)
850 .map(|number| (U256::from(number), B256::from(U256::from(number))))
851 .collect::<Vec<_>>();
852
853 let mut db = StateRootDb::default();
854 db.set_block_hashes(block_hashes.clone());
855 assert_block_hash_window(&db, 744, 1_000);
856 db.insert_block_hash(U256::from(1_001), B256::from(U256::from(1_001)));
857 assert_block_hash_window(&db, 745, 1_001);
858
859 let mut snapshot_source = MemDb::default();
860 snapshot_source.set_block_hashes(block_hashes);
861 let snapshot = snapshot_source.read_as_state_snapshot();
862 let mut restored = StateRootDb::default();
863 restored.init_from_state_snapshot(snapshot);
864 assert_block_hash_window(&restored, 744, 1_000);
865 restored.insert_block_hash(U256::from(1_001), B256::from(U256::from(1_001)));
866 assert_block_hash_window(&restored, 745, 1_001);
867 }
868
869 fn assert_block_hash_window(db: &StateRootDb, min: u64, head: u64) {
870 let block_hashes = &db.inner.inner.cache.block_hashes;
871 assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
872 assert!(
873 block_hashes
874 .keys()
875 .all(|number| *number >= U256::from(min) && *number <= U256::from(head))
876 );
877 assert!(block_hashes.contains_key(&U256::from(min)));
878 assert!(block_hashes.contains_key(&U256::from(head)));
879 }
880
881 #[test]
882 fn evm_block_hash_cache_is_bounded_across_block_number_jumps() {
883 let mut db = StateRootDb::default();
884 db.current_state();
886
887 for number in [0, 516, 400] {
888 db.insert_block_hash(U256::from(number), B256::from(U256::from(number)));
889 }
890
891 let block_hashes = &db.inner.inner.cache.block_hashes;
893 assert_eq!(block_hashes.len(), 2);
894 assert!(block_hashes.contains_key(&U256::from(400)));
895 assert!(block_hashes.contains_key(&U256::from(516)));
896
897 db.insert_block_hash(U256::from(774), B256::from(U256::from(774)));
898
899 let block_hashes = &db.inner.inner.cache.block_hashes;
900 assert_eq!(block_hashes.len(), 1);
901 assert!(block_hashes.contains_key(&U256::from(774)));
902
903 let historical = db.history.get_mut().state.as_ref().unwrap();
904 assert_eq!(historical.block_hashes.len(), 1);
905 assert!(historical.block_hashes.contains_key(&U256::from(774)));
906 }
907
908 #[test]
909 fn historical_states_are_persistent_and_isolated() {
910 let address = address!("0000000000000000000000000000000000002935");
911 let slot = U256::ONE;
912 let mut db = StateRootDb::default();
913 db.insert_account(address, AccountInfo::from_balance(U256::ONE));
914
915 let first = db.current_state();
916 assert!(first.is_persistent());
917
918 db.set_balance(address, U256::from(2)).unwrap();
919 db.set_storage_at(address, slot.into(), B256::with_last_byte(3)).unwrap();
920 let second = db.current_state();
921
922 assert_eq!(first.basic_ref(address).unwrap().unwrap().balance, U256::ONE);
923 assert_eq!(first.storage_ref(address, slot).unwrap(), U256::ZERO);
924 assert_eq!(second.basic_ref(address).unwrap().unwrap().balance, U256::from(2));
925 assert_eq!(second.storage_ref(address, slot).unwrap(), U256::from(3));
926 }
927
928 #[test]
929 fn historical_missing_accounts_match_live_state() {
930 let missing = Address::with_last_byte(1);
931 let deleted = Address::with_last_byte(2);
932 let mut db = StateRootDb::default();
933 let historical = db.current_state();
934
935 let live_account = db.basic_ref(missing).unwrap();
936 assert_eq!(live_account, Some(AccountInfo::default()));
937 assert_eq!(historical.basic_ref(missing).unwrap(), live_account);
938
939 db.insert_account(deleted, AccountInfo::from_balance(U256::ONE));
940 db.inner.inner.cache.accounts.get_mut(&deleted).unwrap().account_state =
941 AccountState::NotExisting;
942 db.history.get_mut().record_account(deleted);
943 let historical = db.current_state();
944 assert_eq!(historical.basic_ref(deleted).unwrap(), None);
945 assert!(!historical.maybe_as_full_db().unwrap().contains_key(&deleted));
946 assert!(!historical.read_as_state_snapshot().accounts.contains_key(&deleted));
947
948 let mut fresh = StateRootDb::default();
949 fresh.insert_account(deleted, AccountInfo::from_balance(U256::ONE));
950 fresh.inner.inner.cache.accounts.get_mut(&deleted).unwrap().account_state =
951 AccountState::NotExisting;
952 let historical = fresh.current_state();
953 assert_eq!(historical.basic_ref(deleted).unwrap(), None);
954 assert!(!historical.maybe_as_full_db().unwrap().contains_key(&deleted));
955 }
956
957 #[test]
958 fn disabled_history_tracking_records_nothing() {
959 let address = address!("0000000000000000000000000000000000002935");
960 let slot = U256::ONE;
961 let mut db = StateRootDb::new(false);
962
963 db.insert_account(address, AccountInfo::from_balance(U256::ONE));
964 db.set_storage_at(address, slot.into(), B256::with_last_byte(2)).unwrap();
965 db.basic(address).unwrap();
966 db.storage(address, slot).unwrap();
967 db.maybe_state_root().unwrap();
968
969 assert!(db.history.get_mut().dirty.is_empty());
970 assert!(db.history.get_mut().state.is_none());
971
972 let historical = db.current_state();
974 assert_eq!(historical.basic_ref(address).unwrap().unwrap().balance, U256::ONE);
975 assert_eq!(historical.storage_ref(address, slot).unwrap(), U256::from(2));
976 assert!(db.history.get_mut().state.is_none());
977 }
978}