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::from(1)));
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 = <MemDb as DatabaseRef>::Error;
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 = <MemDb as Database>::Error;
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::from(1)));
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::from(1)));
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 maybe_state_root(&self) -> Option<B256> {
486 Some(self.state_root.lock().root(&self.inner.inner.cache.accounts))
487 }
488
489 fn current_state(&self) -> StateDb {
490 StateDb::new(self.history.lock().snapshot(&self.inner))
491 }
492}
493
494impl MaybeFullDatabase for StateRootDb {
495 fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
496 MaybeFullDatabase::maybe_as_full_db(&self.inner)
497 }
498
499 fn maybe_full_db(&self) -> Option<AddressMap<DbAccount>> {
500 MaybeFullDatabase::maybe_full_db(&self.inner)
501 }
502
503 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
504 self.state_root.get_mut().invalidate();
505 self.history.get_mut().invalidate();
506 self.block_hash_head = None;
507 MaybeFullDatabase::clear_into_state_snapshot(&mut self.inner)
508 }
509
510 fn read_as_state_snapshot(&self) -> StateSnapshot {
511 MaybeFullDatabase::read_as_state_snapshot(&self.inner)
512 }
513
514 fn clear(&mut self) {
515 self.state_root.get_mut().invalidate();
516 self.history.get_mut().invalidate();
517 self.block_hash_head = None;
518 MaybeFullDatabase::clear(&mut self.inner)
519 }
520
521 fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
522 MaybeFullDatabase::init_from_state_snapshot(&mut self.inner, snapshot);
523 self.state_root.get_mut().invalidate();
524 self.history.get_mut().invalidate();
525 self.normalize_block_hashes();
526 }
527}
528
529impl MaybeForkedDatabase for StateRootDb {
530 fn maybe_reset(&mut self, urls: Vec<String>, block_number: BlockId) -> Result<(), String> {
531 self.inner.maybe_reset(urls, block_number)
532 }
533
534 fn maybe_flush_cache(&self) -> Result<(), String> {
535 self.inner.maybe_flush_cache()
536 }
537
538 fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
539 self.inner.maybe_inner()
540 }
541}
542
543impl Db for MemDb {
544 fn insert_account(&mut self, address: Address, account: AccountInfo) {
545 self.inner.insert_account_info(address, account)
546 }
547
548 fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
549 self.inner.insert_account_storage(address, slot.into(), val.into())
550 }
551
552 fn insert_block_hash(&mut self, number: U256, hash: B256) {
553 cache_block_hash(&mut self.inner.cache.block_hashes, number, hash);
554 }
555
556 fn set_block_hashes(&mut self, block_hashes: Vec<(U256, B256)>) {
557 self.inner.cache.block_hashes = block_hashes.into_iter().collect();
558 }
559
560 fn dump_state(
561 &self,
562 at: BlockEnv,
563 best_number: u64,
564 blocks: Vec<SerializableBlock>,
565 transactions: Vec<SerializableTransaction>,
566 historical_states: Option<SerializableHistoricalStates>,
567 ) -> DatabaseResult<Option<SerializableState>> {
568 let accounts = self
569 .inner
570 .cache
571 .accounts
572 .clone()
573 .into_iter()
574 .map(|(k, v)| -> DatabaseResult<_> {
575 let code = if let Some(code) = v.info.code {
576 code
577 } else {
578 self.inner.code_by_hash_ref(v.info.code_hash)?
579 };
580 Ok((
581 k,
582 SerializableAccountRecord {
583 nonce: v.info.nonce,
584 balance: v.info.balance,
585 code: code.original_bytes(),
586 storage: v.storage.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
587 },
588 ))
589 })
590 .collect::<Result<_, _>>()?;
591
592 Ok(Some(SerializableState {
593 block: Some(at),
594 accounts,
595 best_block_number: Some(best_number),
596 blocks,
597 transactions,
598 historical_states,
599 }))
600 }
601
602 fn snapshot_state(&mut self) -> U256 {
604 let id = self.state_snapshots.insert(self.inner.clone());
605 trace!(target: "backend::memdb", "Created new state snapshot {}", id);
606 id
607 }
608
609 fn revert_state(&mut self, id: U256, action: RevertStateSnapshotAction) -> bool {
610 if let Some(state_snapshot) = self.state_snapshots.remove(id) {
611 if action.is_keep() {
612 self.state_snapshots.insert_at(state_snapshot.clone(), id);
613 }
614 self.inner = state_snapshot;
615 trace!(target: "backend::memdb", "Reverted state snapshot {}", id);
616 true
617 } else {
618 warn!(target: "backend::memdb", "No state snapshot to revert for {}", id);
619 false
620 }
621 }
622
623 fn maybe_state_root(&self) -> Option<B256> {
624 Some(state_root(&self.inner.cache.accounts))
625 }
626
627 fn current_state(&self) -> StateDb {
628 StateDb::new(Self { inner: self.inner.clone(), ..Default::default() })
629 }
630}
631
632impl MaybeFullDatabase for MemDb {
633 fn maybe_as_full_db(&self) -> Option<&AddressMap<DbAccount>> {
634 Some(&self.inner.cache.accounts)
635 }
636
637 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
638 self.inner.clear_into_state_snapshot()
639 }
640
641 fn read_as_state_snapshot(&self) -> StateSnapshot {
642 self.inner.read_as_state_snapshot()
643 }
644
645 fn clear(&mut self) {
646 self.inner.clear();
647 }
648
649 fn init_from_state_snapshot(&mut self, snapshot: StateSnapshot) {
650 self.inner.init_from_state_snapshot(snapshot)
651 }
652}
653
654impl MaybeForkedDatabase for MemDb {
655 fn maybe_reset(&mut self, _urls: Vec<String>, _block_number: BlockId) -> Result<(), String> {
656 Err("not supported".to_string())
657 }
658
659 fn maybe_flush_cache(&self) -> Result<(), String> {
660 Err("not supported".to_string())
661 }
662
663 fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
664 Err("not supported".to_string())
665 }
666}
667
668#[cfg(test)]
669mod tests {
670 use super::*;
671 use alloy_primitives::{Bytes, address};
672 use revm::primitives::KECCAK_EMPTY;
673 use std::collections::BTreeMap;
674
675 #[test]
678 fn test_dump_reload_cycle() {
679 let test_addr: Address = address!("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
680
681 let mut dump_db = MemDb::default();
682
683 let contract_code = Bytecode::new_raw(Bytes::from("fake contract code"));
684 dump_db.insert_account(
685 test_addr,
686 AccountInfo {
687 balance: U256::from(123456),
688 code_hash: KECCAK_EMPTY,
689 code: Some(contract_code.clone()),
690 nonce: 1234,
691 account_id: None,
692 },
693 );
694 dump_db
695 .set_storage_at(test_addr, U256::from(1234567).into(), U256::from(1).into())
696 .unwrap();
697
698 let state = dump_db
700 .dump_state(Default::default(), 0, Vec::new(), Vec::new(), Default::default())
701 .unwrap()
702 .unwrap();
703
704 let mut load_db = MemDb::default();
705
706 load_db.load_state(state).unwrap();
707
708 let loaded_account = load_db.basic_ref(test_addr).unwrap().unwrap();
709
710 assert_eq!(loaded_account.balance, U256::from(123456));
711 assert_eq!(load_db.code_by_hash_ref(loaded_account.code_hash).unwrap(), contract_code);
712 assert_eq!(loaded_account.nonce, 1234);
713 assert_eq!(load_db.storage_ref(test_addr, U256::from(1234567)).unwrap(), U256::from(1));
714 }
715
716 #[test]
719 fn test_load_state_merge() {
720 let test_addr: Address = address!("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
721 let test_addr2: Address = address!("0x70997970c51812dc3a010c7d01b50e0d17dc79c8");
722
723 let contract_code = Bytecode::new_raw(Bytes::from("fake contract code"));
724
725 let mut db = MemDb::default();
726
727 db.insert_account(
728 test_addr,
729 AccountInfo {
730 balance: U256::from(123456),
731 code_hash: KECCAK_EMPTY,
732 code: Some(contract_code.clone()),
733 nonce: 1234,
734 account_id: None,
735 },
736 );
737
738 db.set_storage_at(test_addr, U256::from(1234567).into(), U256::from(1).into()).unwrap();
739 db.set_storage_at(test_addr, U256::from(1234568).into(), U256::from(2).into()).unwrap();
740
741 let mut new_state = SerializableState::default();
742
743 new_state.accounts.insert(
744 test_addr2,
745 SerializableAccountRecord {
746 balance: Default::default(),
747 code: Default::default(),
748 nonce: 1,
749 storage: Default::default(),
750 },
751 );
752
753 let mut new_storage = BTreeMap::default();
754 new_storage.insert(U256::from(1234568).into(), U256::from(5).into());
755
756 new_state.accounts.insert(
757 test_addr,
758 SerializableAccountRecord {
759 balance: U256::from(100100),
760 code: contract_code.bytes()[..contract_code.len()].to_vec().into(),
761 nonce: 100,
762 storage: new_storage,
763 },
764 );
765
766 db.load_state(new_state).unwrap();
767
768 let loaded_account = db.basic_ref(test_addr).unwrap().unwrap();
769 let loaded_account2 = db.basic_ref(test_addr2).unwrap().unwrap();
770
771 assert_eq!(loaded_account2.nonce, 1);
772
773 assert_eq!(loaded_account.balance, U256::from(100100));
774 assert_eq!(db.code_by_hash_ref(loaded_account.code_hash).unwrap(), contract_code);
775 assert_eq!(loaded_account.nonce, 1234);
776 assert_eq!(db.storage_ref(test_addr, U256::from(1234567)).unwrap(), U256::from(1));
777 assert_eq!(db.storage_ref(test_addr, U256::from(1234568)).unwrap(), U256::from(5));
778 }
779
780 #[test]
781 fn incremental_state_root_matches_full_rebuild() {
782 let address = address!("0000000000000000000000000000000000002935");
783 let deleted = Address::with_last_byte(1);
784 let mut db = StateRootDb::default();
785 db.insert_account(address, AccountInfo::default());
786 db.insert_account(deleted, AccountInfo::from_balance(U256::from(1)));
787
788 assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
789
790 for slot in 0..1_024 {
792 db.set_storage_at(address, U256::from(slot).into(), B256::from(U256::from(slot + 1)))
793 .unwrap();
794 let _ = db.maybe_state_root().unwrap();
795 }
796
797 db.set_balance(address, U256::from(42)).unwrap();
798 db.set_storage_at(address, U256::from(7).into(), B256::ZERO).unwrap();
799 db.set_storage_at(address, U256::from(8).into(), B256::from(U256::from(2_048))).unwrap();
800 db.inner.inner.cache.accounts.get_mut(&deleted).unwrap().account_state =
801 AccountState::NotExisting;
802 db.state_root.get_mut().record_account(deleted);
803 assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
804
805 let snapshot = db.snapshot_state();
806 db.set_balance(address, U256::from(43)).unwrap();
807 assert!(db.revert_state(snapshot, RevertStateSnapshotAction::RevertRemove));
808 assert_eq!(db.maybe_state_root(), Some(state_root(&db.inner.inner.cache.accounts)));
809 }
810
811 #[test]
812 fn evm_block_hash_cache_is_bounded() {
813 let mut db = StateRootDb::default();
814 for number in 0..1_024 {
815 db.insert_block_hash(U256::from(number), B256::from(U256::from(number)));
816 }
817
818 let block_hashes = &db.inner.inner.cache.block_hashes;
819 assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
820 assert!(!block_hashes.contains_key(&U256::from(766)));
821 assert!(block_hashes.contains_key(&U256::from(767)));
822 assert!(block_hashes.contains_key(&U256::from(768)));
823 assert!(block_hashes.contains_key(&U256::from(1_023)));
824
825 let snapshot = db.snapshot_state();
826 db.insert_block_hash(U256::from(1_024), B256::from(U256::from(1_024)));
827 assert!(db.revert_state(snapshot, RevertStateSnapshotAction::RevertRemove));
828 db.insert_block_hash(U256::from(1_024), B256::from(U256::from(1_024)));
829
830 let block_hashes = &db.inner.inner.cache.block_hashes;
831 assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
832 assert!(!block_hashes.contains_key(&U256::from(767)));
833 assert!(block_hashes.contains_key(&U256::from(768)));
834 assert!(block_hashes.contains_key(&U256::from(1_024)));
835 }
836
837 #[test]
838 fn oversized_seeded_block_hash_caches_are_normalized() {
839 let block_hashes = (0..=1_000)
840 .map(|number| (U256::from(number), B256::from(U256::from(number))))
841 .collect::<Vec<_>>();
842
843 let mut db = StateRootDb::default();
844 db.set_block_hashes(block_hashes.clone());
845 assert_block_hash_window(&db, 744, 1_000);
846 db.insert_block_hash(U256::from(1_001), B256::from(U256::from(1_001)));
847 assert_block_hash_window(&db, 745, 1_001);
848
849 let mut snapshot_source = MemDb::default();
850 snapshot_source.set_block_hashes(block_hashes);
851 let snapshot = snapshot_source.read_as_state_snapshot();
852 let mut restored = StateRootDb::default();
853 restored.init_from_state_snapshot(snapshot);
854 assert_block_hash_window(&restored, 744, 1_000);
855 restored.insert_block_hash(U256::from(1_001), B256::from(U256::from(1_001)));
856 assert_block_hash_window(&restored, 745, 1_001);
857 }
858
859 fn assert_block_hash_window(db: &StateRootDb, min: u64, head: u64) {
860 let block_hashes = &db.inner.inner.cache.block_hashes;
861 assert_eq!(block_hashes.len(), BLOCKHASH_HISTORY as usize + 1);
862 assert!(
863 block_hashes
864 .keys()
865 .all(|number| *number >= U256::from(min) && *number <= U256::from(head))
866 );
867 assert!(block_hashes.contains_key(&U256::from(min)));
868 assert!(block_hashes.contains_key(&U256::from(head)));
869 }
870
871 #[test]
872 fn evm_block_hash_cache_is_bounded_across_block_number_jumps() {
873 let mut db = StateRootDb::default();
874 db.current_state();
876
877 for number in [0, 516, 400] {
878 db.insert_block_hash(U256::from(number), B256::from(U256::from(number)));
879 }
880
881 let block_hashes = &db.inner.inner.cache.block_hashes;
883 assert_eq!(block_hashes.len(), 2);
884 assert!(block_hashes.contains_key(&U256::from(400)));
885 assert!(block_hashes.contains_key(&U256::from(516)));
886
887 db.insert_block_hash(U256::from(774), B256::from(U256::from(774)));
888
889 let block_hashes = &db.inner.inner.cache.block_hashes;
890 assert_eq!(block_hashes.len(), 1);
891 assert!(block_hashes.contains_key(&U256::from(774)));
892
893 let historical = db.history.get_mut().state.as_ref().unwrap();
894 assert_eq!(historical.block_hashes.len(), 1);
895 assert!(historical.block_hashes.contains_key(&U256::from(774)));
896 }
897
898 #[test]
899 fn historical_states_are_persistent_and_isolated() {
900 let address = address!("0000000000000000000000000000000000002935");
901 let slot = U256::from(1);
902 let mut db = StateRootDb::default();
903 db.insert_account(address, AccountInfo::from_balance(U256::from(1)));
904
905 let first = db.current_state();
906 assert!(first.is_persistent());
907
908 db.set_balance(address, U256::from(2)).unwrap();
909 db.set_storage_at(address, slot.into(), B256::from(U256::from(3))).unwrap();
910 let second = db.current_state();
911
912 assert_eq!(first.basic_ref(address).unwrap().unwrap().balance, U256::from(1));
913 assert_eq!(first.storage_ref(address, slot).unwrap(), U256::ZERO);
914 assert_eq!(second.basic_ref(address).unwrap().unwrap().balance, U256::from(2));
915 assert_eq!(second.storage_ref(address, slot).unwrap(), U256::from(3));
916 }
917
918 #[test]
919 fn historical_missing_accounts_match_live_state() {
920 let missing = Address::with_last_byte(1);
921 let deleted = Address::with_last_byte(2);
922 let mut db = StateRootDb::default();
923 let historical = db.current_state();
924
925 let live_account = db.basic_ref(missing).unwrap();
926 assert_eq!(live_account, Some(AccountInfo::default()));
927 assert_eq!(historical.basic_ref(missing).unwrap(), live_account);
928
929 db.insert_account(deleted, AccountInfo::from_balance(U256::from(1)));
930 db.inner.inner.cache.accounts.get_mut(&deleted).unwrap().account_state =
931 AccountState::NotExisting;
932 db.history.get_mut().record_account(deleted);
933 let historical = db.current_state();
934 assert_eq!(historical.basic_ref(deleted).unwrap(), None);
935 assert!(!historical.maybe_as_full_db().unwrap().contains_key(&deleted));
936 assert!(!historical.read_as_state_snapshot().accounts.contains_key(&deleted));
937
938 let mut fresh = StateRootDb::default();
939 fresh.insert_account(deleted, AccountInfo::from_balance(U256::from(1)));
940 fresh.inner.inner.cache.accounts.get_mut(&deleted).unwrap().account_state =
941 AccountState::NotExisting;
942 let historical = fresh.current_state();
943 assert_eq!(historical.basic_ref(deleted).unwrap(), None);
944 assert!(!historical.maybe_as_full_db().unwrap().contains_key(&deleted));
945 }
946
947 #[test]
948 fn disabled_history_tracking_records_nothing() {
949 let address = address!("0000000000000000000000000000000000002935");
950 let slot = U256::from(1);
951 let mut db = StateRootDb::new(false);
952
953 db.insert_account(address, AccountInfo::from_balance(U256::from(1)));
954 db.set_storage_at(address, slot.into(), B256::from(U256::from(2))).unwrap();
955 db.basic(address).unwrap();
956 db.storage(address, slot).unwrap();
957 db.maybe_state_root().unwrap();
958
959 assert!(db.history.get_mut().dirty.is_empty());
960 assert!(db.history.get_mut().state.is_none());
961
962 let historical = db.current_state();
964 assert_eq!(historical.basic_ref(address).unwrap().unwrap().balance, U256::from(1));
965 assert_eq!(historical.storage_ref(address, slot).unwrap(), U256::from(2));
966 assert!(db.history.get_mut().state.is_none());
967 }
968}