1use std::{
4 collections::BTreeMap,
5 fmt::{self, Debug},
6 path::Path,
7};
8
9use alloy_consensus::Header;
10use alloy_primitives::{Address, B256, Bytes, U256, keccak256, map::HashMap};
11use alloy_rpc_types::BlockId;
12use anvil_core::eth::{
13 block::Block,
14 transaction::{MaybeImpersonatedTransaction, TransactionInfo, TypedReceipt, TypedTransaction},
15};
16use foundry_common::errors::FsPathError;
17use foundry_evm::backend::{
18 BlockchainDb, DatabaseError, DatabaseResult, MemDb, RevertStateSnapshotAction, StateSnapshot,
19};
20use revm::{
21 Database, DatabaseCommit,
22 bytecode::Bytecode,
23 context::BlockEnv,
24 context_interface::block::BlobExcessGasAndPrice,
25 database::{CacheDB, DatabaseRef, DbAccount},
26 primitives::{KECCAK_EMPTY, eip4844::BLOB_BASE_FEE_UPDATE_FRACTION_PRAGUE},
27 state::AccountInfo,
28};
29use serde::{
30 Deserialize, Deserializer, Serialize,
31 de::{Error as DeError, MapAccess, Visitor},
32};
33use serde_json::Value;
34
35use crate::mem::storage::MinedTransaction;
36
37pub trait MaybeFullDatabase: DatabaseRef<Error = DatabaseError> + Debug {
39 fn maybe_as_full_db(&self) -> Option<&HashMap<Address, DbAccount>> {
40 None
41 }
42
43 fn clear_into_state_snapshot(&mut self) -> StateSnapshot;
45
46 fn read_as_state_snapshot(&self) -> StateSnapshot;
50
51 fn clear(&mut self);
53
54 fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot);
56}
57
58impl<'a, T: 'a + MaybeFullDatabase + ?Sized> MaybeFullDatabase for &'a T
59where
60 &'a T: DatabaseRef<Error = DatabaseError>,
61{
62 fn maybe_as_full_db(&self) -> Option<&HashMap<Address, DbAccount>> {
63 T::maybe_as_full_db(self)
64 }
65
66 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
67 unreachable!("never called for DatabaseRef")
68 }
69
70 fn read_as_state_snapshot(&self) -> StateSnapshot {
71 unreachable!("never called for DatabaseRef")
72 }
73
74 fn clear(&mut self) {}
75
76 fn init_from_state_snapshot(&mut self, _state_snapshot: StateSnapshot) {}
77}
78
79pub trait MaybeForkedDatabase {
81 fn maybe_reset(&mut self, _url: Option<String>, block_number: BlockId) -> Result<(), String>;
82
83 fn maybe_flush_cache(&self) -> Result<(), String>;
84
85 fn maybe_inner(&self) -> Result<&BlockchainDb, String>;
86}
87
88pub trait Db:
90 DatabaseRef<Error = DatabaseError>
91 + Database<Error = DatabaseError>
92 + DatabaseCommit
93 + MaybeFullDatabase
94 + MaybeForkedDatabase
95 + fmt::Debug
96 + Send
97 + Sync
98{
99 fn insert_account(&mut self, address: Address, account: AccountInfo);
101
102 fn set_nonce(&mut self, address: Address, nonce: u64) -> DatabaseResult<()> {
104 let mut info = self.basic(address)?.unwrap_or_default();
105 info.nonce = nonce;
106 self.insert_account(address, info);
107 Ok(())
108 }
109
110 fn set_balance(&mut self, address: Address, balance: U256) -> DatabaseResult<()> {
112 let mut info = self.basic(address)?.unwrap_or_default();
113 info.balance = balance;
114 self.insert_account(address, info);
115 Ok(())
116 }
117
118 fn set_code(&mut self, address: Address, code: Bytes) -> DatabaseResult<()> {
120 let mut info = self.basic(address)?.unwrap_or_default();
121 let code_hash = if code.as_ref().is_empty() {
122 KECCAK_EMPTY
123 } else {
124 B256::from_slice(&keccak256(code.as_ref())[..])
125 };
126 info.code_hash = code_hash;
127 info.code = Some(Bytecode::new_raw(alloy_primitives::Bytes(code.0)));
128 self.insert_account(address, info);
129 Ok(())
130 }
131
132 fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()>;
134
135 fn insert_block_hash(&mut self, number: U256, hash: B256);
137
138 fn dump_state(
140 &self,
141 at: BlockEnv,
142 best_number: u64,
143 blocks: Vec<SerializableBlock>,
144 transactions: Vec<SerializableTransaction>,
145 historical_states: Option<SerializableHistoricalStates>,
146 ) -> DatabaseResult<Option<SerializableState>>;
147
148 fn load_state(&mut self, state: SerializableState) -> DatabaseResult<bool> {
150 for (addr, account) in state.accounts.into_iter() {
151 let old_account_nonce = DatabaseRef::basic_ref(self, addr)
152 .ok()
153 .and_then(|acc| acc.map(|acc| acc.nonce))
154 .unwrap_or_default();
155 let nonce = std::cmp::max(old_account_nonce, account.nonce);
158
159 self.insert_account(
160 addr,
161 AccountInfo {
162 balance: account.balance,
163 code_hash: KECCAK_EMPTY, code: if account.code.0.is_empty() {
165 None
166 } else {
167 Some(Bytecode::new_raw(alloy_primitives::Bytes(account.code.0)))
168 },
169 nonce,
170 },
171 );
172
173 for (k, v) in account.storage.into_iter() {
174 self.set_storage_at(addr, k, v)?;
175 }
176 }
177 Ok(true)
178 }
179
180 fn snapshot_state(&mut self) -> U256;
182
183 fn revert_state(&mut self, state_snapshot: U256, action: RevertStateSnapshotAction) -> bool;
187
188 fn maybe_state_root(&self) -> Option<B256> {
190 None
191 }
192
193 fn current_state(&self) -> StateDb;
195}
196
197impl<T: DatabaseRef<Error = DatabaseError> + Send + Sync + Clone + fmt::Debug> Db for CacheDB<T> {
202 fn insert_account(&mut self, address: Address, account: AccountInfo) {
203 self.insert_account_info(address, account)
204 }
205
206 fn set_storage_at(&mut self, address: Address, slot: B256, val: B256) -> DatabaseResult<()> {
207 self.insert_account_storage(address, slot.into(), val.into())
208 }
209
210 fn insert_block_hash(&mut self, number: U256, hash: B256) {
211 self.cache.block_hashes.insert(number, hash);
212 }
213
214 fn dump_state(
215 &self,
216 _at: BlockEnv,
217 _best_number: u64,
218 _blocks: Vec<SerializableBlock>,
219 _transaction: Vec<SerializableTransaction>,
220 _historical_states: Option<SerializableHistoricalStates>,
221 ) -> DatabaseResult<Option<SerializableState>> {
222 Ok(None)
223 }
224
225 fn snapshot_state(&mut self) -> U256 {
226 U256::ZERO
227 }
228
229 fn revert_state(&mut self, _state_snapshot: U256, _action: RevertStateSnapshotAction) -> bool {
230 false
231 }
232
233 fn current_state(&self) -> StateDb {
234 StateDb::new(MemDb::default())
235 }
236}
237
238impl<T: DatabaseRef<Error = DatabaseError> + Debug> MaybeFullDatabase for CacheDB<T> {
239 fn maybe_as_full_db(&self) -> Option<&HashMap<Address, DbAccount>> {
240 Some(&self.cache.accounts)
241 }
242
243 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
244 let db_accounts = std::mem::take(&mut self.cache.accounts);
245 let mut accounts = HashMap::default();
246 let mut account_storage = HashMap::default();
247
248 for (addr, mut acc) in db_accounts {
249 account_storage.insert(addr, std::mem::take(&mut acc.storage));
250 let mut info = acc.info;
251 info.code = self.cache.contracts.remove(&info.code_hash);
252 accounts.insert(addr, info);
253 }
254 let block_hashes = std::mem::take(&mut self.cache.block_hashes);
255 StateSnapshot { accounts, storage: account_storage, block_hashes }
256 }
257
258 fn read_as_state_snapshot(&self) -> StateSnapshot {
259 let db_accounts = self.cache.accounts.clone();
260 let mut accounts = HashMap::default();
261 let mut account_storage = HashMap::default();
262
263 for (addr, acc) in db_accounts {
264 account_storage.insert(addr, acc.storage.clone());
265 let mut info = acc.info;
266 info.code = self.cache.contracts.get(&info.code_hash).cloned();
267 accounts.insert(addr, info);
268 }
269
270 let block_hashes = self.cache.block_hashes.clone();
271 StateSnapshot { accounts, storage: account_storage, block_hashes }
272 }
273
274 fn clear(&mut self) {
275 self.clear_into_state_snapshot();
276 }
277
278 fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot) {
279 let StateSnapshot { accounts, mut storage, block_hashes } = state_snapshot;
280
281 for (addr, mut acc) in accounts {
282 if let Some(code) = acc.code.take() {
283 self.cache.contracts.insert(acc.code_hash, code);
284 }
285 self.cache.accounts.insert(
286 addr,
287 DbAccount {
288 info: acc,
289 storage: storage.remove(&addr).unwrap_or_default(),
290 ..Default::default()
291 },
292 );
293 }
294 self.cache.block_hashes = block_hashes;
295 }
296}
297
298impl<T: DatabaseRef<Error = DatabaseError>> MaybeForkedDatabase for CacheDB<T> {
299 fn maybe_reset(&mut self, _url: Option<String>, _block_number: BlockId) -> Result<(), String> {
300 Err("not supported".to_string())
301 }
302
303 fn maybe_flush_cache(&self) -> Result<(), String> {
304 Err("not supported".to_string())
305 }
306
307 fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
308 Err("not supported".to_string())
309 }
310}
311
312#[derive(Debug)]
314pub struct StateDb(pub(crate) Box<dyn MaybeFullDatabase + Send + Sync>);
315
316impl StateDb {
317 pub fn new(db: impl MaybeFullDatabase + Send + Sync + 'static) -> Self {
318 Self(Box::new(db))
319 }
320
321 pub fn serialize_state(&mut self) -> StateSnapshot {
322 self.read_as_state_snapshot()
325 }
326}
327
328impl DatabaseRef for StateDb {
329 type Error = DatabaseError;
330 fn basic_ref(&self, address: Address) -> DatabaseResult<Option<AccountInfo>> {
331 self.0.basic_ref(address)
332 }
333
334 fn code_by_hash_ref(&self, code_hash: B256) -> DatabaseResult<Bytecode> {
335 self.0.code_by_hash_ref(code_hash)
336 }
337
338 fn storage_ref(&self, address: Address, index: U256) -> DatabaseResult<U256> {
339 self.0.storage_ref(address, index)
340 }
341
342 fn block_hash_ref(&self, number: u64) -> DatabaseResult<B256> {
343 self.0.block_hash_ref(number)
344 }
345}
346
347impl MaybeFullDatabase for StateDb {
348 fn maybe_as_full_db(&self) -> Option<&HashMap<Address, DbAccount>> {
349 self.0.maybe_as_full_db()
350 }
351
352 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
353 self.0.clear_into_state_snapshot()
354 }
355
356 fn read_as_state_snapshot(&self) -> StateSnapshot {
357 self.0.read_as_state_snapshot()
358 }
359
360 fn clear(&mut self) {
361 self.0.clear()
362 }
363
364 fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot) {
365 self.0.init_from_state_snapshot(state_snapshot)
366 }
367}
368
369#[derive(Debug, Deserialize)]
371#[serde(rename_all = "snake_case")]
372pub struct LegacyBlockEnv {
373 pub number: Option<StringOrU64>,
374 #[serde(alias = "coinbase")]
375 pub beneficiary: Option<Address>,
376 pub timestamp: Option<StringOrU64>,
377 pub gas_limit: Option<StringOrU64>,
378 pub basefee: Option<StringOrU64>,
379 pub difficulty: Option<StringOrU64>,
380 pub prevrandao: Option<B256>,
381 pub blob_excess_gas_and_price: Option<LegacyBlobExcessGasAndPrice>,
382}
383
384#[derive(Debug, Deserialize)]
386pub struct LegacyBlobExcessGasAndPrice {
387 pub excess_blob_gas: u64,
388 pub blob_gasprice: u64,
389}
390
391#[derive(Debug, Deserialize)]
393#[serde(untagged)]
394pub enum StringOrU64 {
395 Hex(String),
396 Dec(u64),
397}
398
399impl StringOrU64 {
400 pub fn to_u64(&self) -> Option<u64> {
401 match self {
402 Self::Dec(n) => Some(*n),
403 Self::Hex(s) => s.strip_prefix("0x").and_then(|s| u64::from_str_radix(s, 16).ok()),
404 }
405 }
406
407 pub fn to_u256(&self) -> Option<U256> {
408 match self {
409 Self::Dec(n) => Some(U256::from(*n)),
410 Self::Hex(s) => s.strip_prefix("0x").and_then(|s| U256::from_str_radix(s, 16).ok()),
411 }
412 }
413}
414
415impl TryFrom<LegacyBlockEnv> for BlockEnv {
417 type Error = &'static str;
418
419 fn try_from(legacy: LegacyBlockEnv) -> Result<Self, Self::Error> {
420 Ok(Self {
421 number: legacy.number.and_then(|v| v.to_u256()).unwrap_or(U256::ZERO),
422 beneficiary: legacy.beneficiary.unwrap_or(Address::ZERO),
423 timestamp: legacy.timestamp.and_then(|v| v.to_u256()).unwrap_or(U256::ONE),
424 gas_limit: legacy.gas_limit.and_then(|v| v.to_u64()).unwrap_or(u64::MAX),
425 basefee: legacy.basefee.and_then(|v| v.to_u64()).unwrap_or(0),
426 difficulty: legacy.difficulty.and_then(|v| v.to_u256()).unwrap_or(U256::ZERO),
427 prevrandao: legacy.prevrandao.or(Some(B256::ZERO)),
428 blob_excess_gas_and_price: legacy
429 .blob_excess_gas_and_price
430 .map(|v| BlobExcessGasAndPrice::new(v.excess_blob_gas, v.blob_gasprice))
431 .or_else(|| {
432 Some(BlobExcessGasAndPrice::new(0, BLOB_BASE_FEE_UPDATE_FRACTION_PRAGUE))
433 }),
434 })
435 }
436}
437
438fn deserialize_block_env_compat<'de, D>(deserializer: D) -> Result<Option<BlockEnv>, D::Error>
440where
441 D: Deserializer<'de>,
442{
443 let value: Option<Value> = Option::deserialize(deserializer)?;
444 let Some(value) = value else {
445 return Ok(None);
446 };
447
448 if let Ok(env) = BlockEnv::deserialize(&value) {
449 return Ok(Some(env));
450 }
451
452 let legacy: LegacyBlockEnv = serde_json::from_value(value).map_err(|e| {
453 D::Error::custom(format!("Legacy deserialization of `BlockEnv` failed: {e}"))
454 })?;
455
456 Ok(Some(BlockEnv::try_from(legacy).map_err(D::Error::custom)?))
457}
458
459fn deserialize_best_block_number_compat<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
461where
462 D: Deserializer<'de>,
463{
464 let value: Option<Value> = Option::deserialize(deserializer)?;
465 let Some(value) = value else {
466 return Ok(None);
467 };
468
469 let number = match value {
470 Value::Number(n) => n.as_u64(),
471 Value::String(s) => {
472 if let Some(s) = s.strip_prefix("0x") {
473 u64::from_str_radix(s, 16).ok()
474 } else {
475 s.parse().ok()
476 }
477 }
478 _ => None,
479 };
480
481 Ok(number)
482}
483
484#[derive(Clone, Debug, Default, Serialize, Deserialize)]
485pub struct SerializableState {
486 #[serde(deserialize_with = "deserialize_block_env_compat")]
490 pub block: Option<BlockEnv>,
491 pub accounts: BTreeMap<Address, SerializableAccountRecord>,
492 #[serde(deserialize_with = "deserialize_best_block_number_compat")]
494 pub best_block_number: Option<u64>,
495 #[serde(default)]
496 pub blocks: Vec<SerializableBlock>,
497 #[serde(default)]
498 pub transactions: Vec<SerializableTransaction>,
499 #[serde(default)]
503 pub historical_states: Option<SerializableHistoricalStates>,
504}
505
506impl SerializableState {
507 pub fn load(path: impl AsRef<Path>) -> Result<Self, FsPathError> {
509 let path = path.as_ref();
510 if path.is_dir() {
511 foundry_common::fs::read_json_file(&path.join("state.json"))
512 } else {
513 foundry_common::fs::read_json_file(path)
514 }
515 }
516
517 #[allow(dead_code)]
519 pub(crate) fn parse(path: &str) -> Result<Self, String> {
520 Self::load(path).map_err(|err| err.to_string())
521 }
522}
523
524#[derive(Clone, Debug, Serialize, Deserialize)]
525pub struct SerializableAccountRecord {
526 pub nonce: u64,
527 pub balance: U256,
528 pub code: Bytes,
529
530 #[serde(deserialize_with = "deserialize_btree")]
531 pub storage: BTreeMap<B256, B256>,
532}
533
534fn deserialize_btree<'de, D>(deserializer: D) -> Result<BTreeMap<B256, B256>, D::Error>
535where
536 D: Deserializer<'de>,
537{
538 struct BTreeVisitor;
539
540 impl<'de> Visitor<'de> for BTreeVisitor {
541 type Value = BTreeMap<B256, B256>;
542
543 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
544 formatter.write_str("a mapping of hex encoded storage slots to hex encoded state data")
545 }
546
547 fn visit_map<M>(self, mut mapping: M) -> Result<BTreeMap<B256, B256>, M::Error>
548 where
549 M: MapAccess<'de>,
550 {
551 let mut btree = BTreeMap::new();
552 while let Some((key, value)) = mapping.next_entry::<U256, U256>()? {
553 btree.insert(B256::from(key), B256::from(value));
554 }
555
556 Ok(btree)
557 }
558 }
559
560 deserializer.deserialize_map(BTreeVisitor)
561}
562
563#[derive(Clone, Debug, Serialize, Deserialize)]
571#[serde(untagged)]
572pub enum SerializableTransactionType {
573 TypedTransaction(TypedTransaction),
574 MaybeImpersonatedTransaction(MaybeImpersonatedTransaction),
575}
576
577#[derive(Clone, Debug, Serialize, Deserialize)]
578pub struct SerializableBlock {
579 pub header: Header,
580 pub transactions: Vec<SerializableTransactionType>,
581 pub ommers: Vec<Header>,
582}
583
584impl From<Block> for SerializableBlock {
585 fn from(block: Block) -> Self {
586 Self {
587 header: block.header,
588 transactions: block.transactions.into_iter().map(Into::into).collect(),
589 ommers: block.ommers.into_iter().collect(),
590 }
591 }
592}
593
594impl From<SerializableBlock> for Block {
595 fn from(block: SerializableBlock) -> Self {
596 Self {
597 header: block.header,
598 transactions: block.transactions.into_iter().map(Into::into).collect(),
599 ommers: block.ommers.into_iter().collect(),
600 }
601 }
602}
603
604impl From<MaybeImpersonatedTransaction> for SerializableTransactionType {
605 fn from(transaction: MaybeImpersonatedTransaction) -> Self {
606 Self::MaybeImpersonatedTransaction(transaction)
607 }
608}
609
610impl From<SerializableTransactionType> for MaybeImpersonatedTransaction {
611 fn from(transaction: SerializableTransactionType) -> Self {
612 match transaction {
613 SerializableTransactionType::TypedTransaction(tx) => Self::new(tx),
614 SerializableTransactionType::MaybeImpersonatedTransaction(tx) => tx,
615 }
616 }
617}
618
619#[derive(Clone, Debug, Serialize, Deserialize)]
620pub struct SerializableTransaction {
621 pub info: TransactionInfo,
622 pub receipt: TypedReceipt,
623 pub block_hash: B256,
624 pub block_number: u64,
625}
626
627impl From<MinedTransaction> for SerializableTransaction {
628 fn from(transaction: MinedTransaction) -> Self {
629 Self {
630 info: transaction.info,
631 receipt: transaction.receipt,
632 block_hash: transaction.block_hash,
633 block_number: transaction.block_number,
634 }
635 }
636}
637
638impl From<SerializableTransaction> for MinedTransaction {
639 fn from(transaction: SerializableTransaction) -> Self {
640 Self {
641 info: transaction.info,
642 receipt: transaction.receipt,
643 block_hash: transaction.block_hash,
644 block_number: transaction.block_number,
645 }
646 }
647}
648
649#[derive(Clone, Debug, Serialize, Deserialize, Default)]
650pub struct SerializableHistoricalStates(Vec<(B256, StateSnapshot)>);
651
652impl SerializableHistoricalStates {
653 pub const fn new(states: Vec<(B256, StateSnapshot)>) -> Self {
654 Self(states)
655 }
656}
657
658impl IntoIterator for SerializableHistoricalStates {
659 type Item = (B256, StateSnapshot);
660 type IntoIter = std::vec::IntoIter<Self::Item>;
661
662 fn into_iter(self) -> Self::IntoIter {
663 self.0.into_iter()
664 }
665}
666
667#[cfg(test)]
668mod test {
669 use super::*;
670
671 #[test]
672 fn test_deser_block() {
673 let block = r#"{
674 "header": {
675 "parentHash": "0xceb0fe420d6f14a8eeec4319515b89acbb0bb4861cad9983d529ab4b1e4af929",
676 "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
677 "miner": "0x0000000000000000000000000000000000000000",
678 "stateRoot": "0xe1423fd180478ab4fd05a7103277d64496b15eb914ecafe71eeec871b552efd1",
679 "transactionsRoot": "0x2b5598ef261e5f88e4303bb2b3986b3d5c0ebf4cd9977daebccae82a6469b988",
680 "receiptsRoot": "0xf78dfb743fbd92ade140711c8bbc542b5e307f0ab7984eff35d751969fe57efa",
681 "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
682 "difficulty": "0x0",
683 "number": "0x2",
684 "gasLimit": "0x1c9c380",
685 "gasUsed": "0x5208",
686 "timestamp": "0x66cdc823",
687 "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
688 "nonce": "0x0000000000000000",
689 "baseFeePerGas": "0x342a1c58",
690 "blobGasUsed": "0x0",
691 "excessBlobGas": "0x0",
692 "extraData": "0x"
693 },
694 "transactions": [
695 {
696 "EIP1559": {
697 "chainId": "0x7a69",
698 "nonce": "0x0",
699 "gas": "0x5209",
700 "maxFeePerGas": "0x77359401",
701 "maxPriorityFeePerGas": "0x1",
702 "to": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
703 "value": "0x0",
704 "accessList": [],
705 "input": "0x",
706 "r": "0x85c2794a580da137e24ccc823b45ae5cea99371ae23ee13860fcc6935f8305b0",
707 "s": "0x41de7fa4121dab284af4453d30928241208bafa90cdb701fe9bc7054759fe3cd",
708 "yParity": "0x0",
709 "hash": "0x8c9b68e8947ace33028dba167354fde369ed7bbe34911b772d09b3c64b861515"
710 }
711 }
712 ],
713 "ommers": []
714 }
715 "#;
716
717 let _block: SerializableBlock = serde_json::from_str(block).unwrap();
718 }
719}