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 mut accounts = HashMap::default();
260 let mut account_storage = HashMap::default();
261
262 for (addr, acc) in &self.cache.accounts {
263 account_storage.insert(*addr, acc.storage.clone());
264 let mut info = acc.info.clone();
265 info.code = self.cache.contracts.get(&info.code_hash).cloned();
266 accounts.insert(*addr, info);
267 }
268
269 let block_hashes = self.cache.block_hashes.clone();
270 StateSnapshot { accounts, storage: account_storage, block_hashes }
271 }
272
273 fn clear(&mut self) {
274 self.clear_into_state_snapshot();
275 }
276
277 fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot) {
278 let StateSnapshot { accounts, mut storage, block_hashes } = state_snapshot;
279
280 for (addr, mut acc) in accounts {
281 if let Some(code) = acc.code.take() {
282 self.cache.contracts.insert(acc.code_hash, code);
283 }
284 self.cache.accounts.insert(
285 addr,
286 DbAccount {
287 info: acc,
288 storage: storage.remove(&addr).unwrap_or_default(),
289 ..Default::default()
290 },
291 );
292 }
293 self.cache.block_hashes = block_hashes;
294 }
295}
296
297impl<T: DatabaseRef<Error = DatabaseError>> MaybeForkedDatabase for CacheDB<T> {
298 fn maybe_reset(&mut self, _url: Option<String>, _block_number: BlockId) -> Result<(), String> {
299 Err("not supported".to_string())
300 }
301
302 fn maybe_flush_cache(&self) -> Result<(), String> {
303 Err("not supported".to_string())
304 }
305
306 fn maybe_inner(&self) -> Result<&BlockchainDb, String> {
307 Err("not supported".to_string())
308 }
309}
310
311#[derive(Debug)]
313pub struct StateDb(pub(crate) Box<dyn MaybeFullDatabase + Send + Sync>);
314
315impl StateDb {
316 pub fn new(db: impl MaybeFullDatabase + Send + Sync + 'static) -> Self {
317 Self(Box::new(db))
318 }
319
320 pub fn serialize_state(&mut self) -> StateSnapshot {
321 self.read_as_state_snapshot()
324 }
325}
326
327impl DatabaseRef for StateDb {
328 type Error = DatabaseError;
329 fn basic_ref(&self, address: Address) -> DatabaseResult<Option<AccountInfo>> {
330 self.0.basic_ref(address)
331 }
332
333 fn code_by_hash_ref(&self, code_hash: B256) -> DatabaseResult<Bytecode> {
334 self.0.code_by_hash_ref(code_hash)
335 }
336
337 fn storage_ref(&self, address: Address, index: U256) -> DatabaseResult<U256> {
338 self.0.storage_ref(address, index)
339 }
340
341 fn block_hash_ref(&self, number: u64) -> DatabaseResult<B256> {
342 self.0.block_hash_ref(number)
343 }
344}
345
346impl MaybeFullDatabase for StateDb {
347 fn maybe_as_full_db(&self) -> Option<&HashMap<Address, DbAccount>> {
348 self.0.maybe_as_full_db()
349 }
350
351 fn clear_into_state_snapshot(&mut self) -> StateSnapshot {
352 self.0.clear_into_state_snapshot()
353 }
354
355 fn read_as_state_snapshot(&self) -> StateSnapshot {
356 self.0.read_as_state_snapshot()
357 }
358
359 fn clear(&mut self) {
360 self.0.clear()
361 }
362
363 fn init_from_state_snapshot(&mut self, state_snapshot: StateSnapshot) {
364 self.0.init_from_state_snapshot(state_snapshot)
365 }
366}
367
368#[derive(Debug, Deserialize)]
370#[serde(rename_all = "snake_case")]
371pub struct LegacyBlockEnv {
372 pub number: Option<StringOrU64>,
373 #[serde(alias = "coinbase")]
374 pub beneficiary: Option<Address>,
375 pub timestamp: Option<StringOrU64>,
376 pub gas_limit: Option<StringOrU64>,
377 pub basefee: Option<StringOrU64>,
378 pub difficulty: Option<StringOrU64>,
379 pub prevrandao: Option<B256>,
380 pub blob_excess_gas_and_price: Option<LegacyBlobExcessGasAndPrice>,
381}
382
383#[derive(Debug, Deserialize)]
385pub struct LegacyBlobExcessGasAndPrice {
386 pub excess_blob_gas: u64,
387 pub blob_gasprice: u64,
388}
389
390#[derive(Debug, Deserialize)]
392#[serde(untagged)]
393pub enum StringOrU64 {
394 Hex(String),
395 Dec(u64),
396}
397
398impl StringOrU64 {
399 pub fn to_u64(&self) -> Option<u64> {
400 match self {
401 Self::Dec(n) => Some(*n),
402 Self::Hex(s) => s.strip_prefix("0x").and_then(|s| u64::from_str_radix(s, 16).ok()),
403 }
404 }
405
406 pub fn to_u256(&self) -> Option<U256> {
407 match self {
408 Self::Dec(n) => Some(U256::from(*n)),
409 Self::Hex(s) => s.strip_prefix("0x").and_then(|s| U256::from_str_radix(s, 16).ok()),
410 }
411 }
412}
413
414impl TryFrom<LegacyBlockEnv> for BlockEnv {
416 type Error = &'static str;
417
418 fn try_from(legacy: LegacyBlockEnv) -> Result<Self, Self::Error> {
419 Ok(Self {
420 number: legacy.number.and_then(|v| v.to_u256()).unwrap_or(U256::ZERO),
421 beneficiary: legacy.beneficiary.unwrap_or(Address::ZERO),
422 timestamp: legacy.timestamp.and_then(|v| v.to_u256()).unwrap_or(U256::ONE),
423 gas_limit: legacy.gas_limit.and_then(|v| v.to_u64()).unwrap_or(u64::MAX),
424 basefee: legacy.basefee.and_then(|v| v.to_u64()).unwrap_or(0),
425 difficulty: legacy.difficulty.and_then(|v| v.to_u256()).unwrap_or(U256::ZERO),
426 prevrandao: legacy.prevrandao.or(Some(B256::ZERO)),
427 blob_excess_gas_and_price: legacy
428 .blob_excess_gas_and_price
429 .map(|v| BlobExcessGasAndPrice::new(v.excess_blob_gas, v.blob_gasprice))
430 .or_else(|| {
431 Some(BlobExcessGasAndPrice::new(0, BLOB_BASE_FEE_UPDATE_FRACTION_PRAGUE))
432 }),
433 })
434 }
435}
436
437fn deserialize_block_env_compat<'de, D>(deserializer: D) -> Result<Option<BlockEnv>, D::Error>
439where
440 D: Deserializer<'de>,
441{
442 let value: Option<Value> = Option::deserialize(deserializer)?;
443 let Some(value) = value else {
444 return Ok(None);
445 };
446
447 if let Ok(env) = BlockEnv::deserialize(&value) {
448 return Ok(Some(env));
449 }
450
451 let legacy: LegacyBlockEnv = serde_json::from_value(value).map_err(|e| {
452 D::Error::custom(format!("Legacy deserialization of `BlockEnv` failed: {e}"))
453 })?;
454
455 Ok(Some(BlockEnv::try_from(legacy).map_err(D::Error::custom)?))
456}
457
458fn deserialize_best_block_number_compat<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
460where
461 D: Deserializer<'de>,
462{
463 let value: Option<Value> = Option::deserialize(deserializer)?;
464 let Some(value) = value else {
465 return Ok(None);
466 };
467
468 let number = match value {
469 Value::Number(n) => n.as_u64(),
470 Value::String(s) => {
471 if let Some(s) = s.strip_prefix("0x") {
472 u64::from_str_radix(s, 16).ok()
473 } else {
474 s.parse().ok()
475 }
476 }
477 _ => None,
478 };
479
480 Ok(number)
481}
482
483#[derive(Clone, Debug, Default, Serialize, Deserialize)]
484pub struct SerializableState {
485 #[serde(deserialize_with = "deserialize_block_env_compat")]
489 pub block: Option<BlockEnv>,
490 pub accounts: BTreeMap<Address, SerializableAccountRecord>,
491 #[serde(deserialize_with = "deserialize_best_block_number_compat")]
493 pub best_block_number: Option<u64>,
494 #[serde(default)]
495 pub blocks: Vec<SerializableBlock>,
496 #[serde(default)]
497 pub transactions: Vec<SerializableTransaction>,
498 #[serde(default)]
502 pub historical_states: Option<SerializableHistoricalStates>,
503}
504
505impl SerializableState {
506 pub fn load(path: impl AsRef<Path>) -> Result<Self, FsPathError> {
508 let path = path.as_ref();
509 if path.is_dir() {
510 foundry_common::fs::read_json_file(&path.join("state.json"))
511 } else {
512 foundry_common::fs::read_json_file(path)
513 }
514 }
515
516 #[allow(dead_code)]
518 pub(crate) fn parse(path: &str) -> Result<Self, String> {
519 Self::load(path).map_err(|err| err.to_string())
520 }
521}
522
523#[derive(Clone, Debug, Serialize, Deserialize)]
524pub struct SerializableAccountRecord {
525 pub nonce: u64,
526 pub balance: U256,
527 pub code: Bytes,
528
529 #[serde(deserialize_with = "deserialize_btree")]
530 pub storage: BTreeMap<B256, B256>,
531}
532
533fn deserialize_btree<'de, D>(deserializer: D) -> Result<BTreeMap<B256, B256>, D::Error>
534where
535 D: Deserializer<'de>,
536{
537 struct BTreeVisitor;
538
539 impl<'de> Visitor<'de> for BTreeVisitor {
540 type Value = BTreeMap<B256, B256>;
541
542 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
543 formatter.write_str("a mapping of hex encoded storage slots to hex encoded state data")
544 }
545
546 fn visit_map<M>(self, mut mapping: M) -> Result<BTreeMap<B256, B256>, M::Error>
547 where
548 M: MapAccess<'de>,
549 {
550 let mut btree = BTreeMap::new();
551 while let Some((key, value)) = mapping.next_entry::<U256, U256>()? {
552 btree.insert(B256::from(key), B256::from(value));
553 }
554
555 Ok(btree)
556 }
557 }
558
559 deserializer.deserialize_map(BTreeVisitor)
560}
561
562#[derive(Clone, Debug, Serialize, Deserialize)]
570#[serde(untagged)]
571pub enum SerializableTransactionType {
572 TypedTransaction(TypedTransaction),
573 MaybeImpersonatedTransaction(MaybeImpersonatedTransaction),
574}
575
576#[derive(Clone, Debug, Serialize, Deserialize)]
577pub struct SerializableBlock {
578 pub header: Header,
579 pub transactions: Vec<SerializableTransactionType>,
580 pub ommers: Vec<Header>,
581}
582
583impl From<Block> for SerializableBlock {
584 fn from(block: Block) -> Self {
585 Self {
586 header: block.header,
587 transactions: block.transactions.into_iter().map(Into::into).collect(),
588 ommers: block.ommers.into_iter().collect(),
589 }
590 }
591}
592
593impl From<SerializableBlock> for Block {
594 fn from(block: SerializableBlock) -> Self {
595 Self {
596 header: block.header,
597 transactions: block.transactions.into_iter().map(Into::into).collect(),
598 ommers: block.ommers.into_iter().collect(),
599 }
600 }
601}
602
603impl From<MaybeImpersonatedTransaction> for SerializableTransactionType {
604 fn from(transaction: MaybeImpersonatedTransaction) -> Self {
605 Self::MaybeImpersonatedTransaction(transaction)
606 }
607}
608
609impl From<SerializableTransactionType> for MaybeImpersonatedTransaction {
610 fn from(transaction: SerializableTransactionType) -> Self {
611 match transaction {
612 SerializableTransactionType::TypedTransaction(tx) => Self::new(tx),
613 SerializableTransactionType::MaybeImpersonatedTransaction(tx) => tx,
614 }
615 }
616}
617
618#[derive(Clone, Debug, Serialize, Deserialize)]
619pub struct SerializableTransaction {
620 pub info: TransactionInfo,
621 pub receipt: TypedReceipt,
622 pub block_hash: B256,
623 pub block_number: u64,
624}
625
626impl From<MinedTransaction> for SerializableTransaction {
627 fn from(transaction: MinedTransaction) -> Self {
628 Self {
629 info: transaction.info,
630 receipt: transaction.receipt,
631 block_hash: transaction.block_hash,
632 block_number: transaction.block_number,
633 }
634 }
635}
636
637impl From<SerializableTransaction> for MinedTransaction {
638 fn from(transaction: SerializableTransaction) -> Self {
639 Self {
640 info: transaction.info,
641 receipt: transaction.receipt,
642 block_hash: transaction.block_hash,
643 block_number: transaction.block_number,
644 }
645 }
646}
647
648#[derive(Clone, Debug, Serialize, Deserialize, Default)]
649pub struct SerializableHistoricalStates(Vec<(B256, StateSnapshot)>);
650
651impl SerializableHistoricalStates {
652 pub const fn new(states: Vec<(B256, StateSnapshot)>) -> Self {
653 Self(states)
654 }
655}
656
657impl IntoIterator for SerializableHistoricalStates {
658 type Item = (B256, StateSnapshot);
659 type IntoIter = std::vec::IntoIter<Self::Item>;
660
661 fn into_iter(self) -> Self::IntoIter {
662 self.0.into_iter()
663 }
664}
665
666#[cfg(test)]
667mod test {
668 use super::*;
669
670 #[test]
671 fn test_deser_block() {
672 let block = r#"{
673 "header": {
674 "parentHash": "0xceb0fe420d6f14a8eeec4319515b89acbb0bb4861cad9983d529ab4b1e4af929",
675 "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
676 "miner": "0x0000000000000000000000000000000000000000",
677 "stateRoot": "0xe1423fd180478ab4fd05a7103277d64496b15eb914ecafe71eeec871b552efd1",
678 "transactionsRoot": "0x2b5598ef261e5f88e4303bb2b3986b3d5c0ebf4cd9977daebccae82a6469b988",
679 "receiptsRoot": "0xf78dfb743fbd92ade140711c8bbc542b5e307f0ab7984eff35d751969fe57efa",
680 "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
681 "difficulty": "0x0",
682 "number": "0x2",
683 "gasLimit": "0x1c9c380",
684 "gasUsed": "0x5208",
685 "timestamp": "0x66cdc823",
686 "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
687 "nonce": "0x0000000000000000",
688 "baseFeePerGas": "0x342a1c58",
689 "blobGasUsed": "0x0",
690 "excessBlobGas": "0x0",
691 "extraData": "0x"
692 },
693 "transactions": [
694 {
695 "EIP1559": {
696 "chainId": "0x7a69",
697 "nonce": "0x0",
698 "gas": "0x5209",
699 "maxFeePerGas": "0x77359401",
700 "maxPriorityFeePerGas": "0x1",
701 "to": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
702 "value": "0x0",
703 "accessList": [],
704 "input": "0x",
705 "r": "0x85c2794a580da137e24ccc823b45ae5cea99371ae23ee13860fcc6935f8305b0",
706 "s": "0x41de7fa4121dab284af4453d30928241208bafa90cdb701fe9bc7054759fe3cd",
707 "yParity": "0x0",
708 "hash": "0x8c9b68e8947ace33028dba167354fde369ed7bbe34911b772d09b3c64b861515"
709 }
710 }
711 ],
712 "ommers": []
713 }
714 "#;
715
716 let _block: SerializableBlock = serde_json::from_str(block).unwrap();
717 }
718}