1use std::{
2 collections::HashMap,
3 sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
4};
5
6use alloy::primitives::{Address, Bytes as AlloyBytes, B256, U256};
7use revm::{
8 context::DBErrorMarker,
9 primitives::KECCAK_EMPTY,
10 state::{AccountInfo, Bytecode},
11 DatabaseRef,
12};
13use thiserror::Error;
14use tracing::{debug, error, instrument, warn};
15use tycho_client::feed::BlockHeader;
16
17use crate::evm::{
18 account_storage::{AccountStorage, StateUpdate},
19 engine_db::engine_db_interface::EngineDatabaseInterface,
20 tycho_models::{AccountUpdate, ChangeType},
21};
22
23#[derive(Error, Debug)]
24pub enum TychoClientError {
25 #[error("Failed to parse URI: {0}. Error: {1}")]
26 UriParsing(String, String),
27 #[error("Failed to format request: {0}")]
28 FormatRequest(String),
29 #[error("Unexpected HTTP client error: {0}")]
30 HttpClient(String),
31 #[error("Failed to parse response: {0}")]
32 ParseResponse(String),
33}
34
35#[derive(Error, Debug)]
36pub enum PreCachedDBError {
37 #[error("Account {0} not found")]
38 MissingAccount(Address),
39 #[error("Bad account update: {0} - {1:?}")]
40 BadUpdate(String, Box<AccountUpdate>),
41 #[error("Block needs to be set")]
42 BlockNotSet(),
43 #[error("Tycho Client error: {0}")]
44 TychoClientError(#[from] TychoClientError),
45 #[error("{0}")]
46 Fatal(String),
47}
48
49impl DBErrorMarker for PreCachedDBError {}
50
51#[derive(Clone, Debug)]
52pub struct PreCachedDBInner {
53 accounts: AccountStorage,
55 block: Option<BlockHeader>,
57}
58
59#[derive(Clone, Debug)]
60pub struct PreCachedDB {
61 pub inner: Arc<RwLock<PreCachedDBInner>>,
67}
68
69impl PreCachedDB {
70 #[expect(
72 clippy::unnecessary_wraps,
73 reason = "public API; changing the signature is a breaking change"
74 )]
75 pub fn new() -> Result<Self, PreCachedDBError> {
76 Ok(PreCachedDB {
77 inner: Arc::new(RwLock::new(PreCachedDBInner {
78 accounts: AccountStorage::new(),
79 block: None,
80 })),
81 })
82 }
83
84 #[instrument(skip_all)]
94 pub fn update(
95 &self,
96 account_updates: Vec<AccountUpdate>,
97 block: Option<BlockHeader>,
98 ) -> Result<(), PreCachedDBError> {
99 let mut write_guard = self.write_inner()?;
102
103 write_guard.block = block;
104
105 for update in account_updates {
106 match update.change {
107 ChangeType::Update => {
108 debug!(%update.address, "Updating account");
109
110 write_guard.accounts.update_account(
113 &update.address,
114 &StateUpdate {
115 storage: Some(update.slots.clone()),
116 balance: update.balance,
117 },
118 );
119 }
120 ChangeType::Deletion => {
121 debug!(%update.address, "Deleting account");
122
123 warn!(%update.address, "Deletion not implemented");
124 }
125 ChangeType::Creation => {
126 debug!(%update.address, "Creating account");
127
128 let code = Bytecode::new_raw(AlloyBytes::from(
130 update.code.clone().ok_or_else(|| {
131 error!(%update.address, "MissingCode");
132 PreCachedDBError::BadUpdate(
133 "MissingCode".into(),
134 Box::new(update.clone()),
135 )
136 })?,
137 ));
138 let balance = update.balance.unwrap_or(U256::ZERO);
140
141 write_guard.accounts.overwrite_account(
144 update.address,
145 AccountInfo::new(balance, 0, code.hash_slow(), code),
146 Some(update.slots),
147 true, );
150 }
151 ChangeType::Unspecified => {
152 warn!(%update.address, "Unspecified change type");
153 }
154 }
155 }
156 Ok(())
157 }
158
159 pub fn force_update_accounts(
163 &self,
164 account_updates: Vec<AccountUpdate>,
165 ) -> Result<(), PreCachedDBError> {
166 let mut write_guard = self.write_inner()?;
167
168 for update in account_updates {
169 if matches!(update.change, ChangeType::Creation) {
170 let code =
171 Bytecode::new_raw(AlloyBytes::from(update.code.clone().ok_or_else(|| {
172 error!(%update.address, "MissingCode");
173 PreCachedDBError::BadUpdate("MissingCode".into(), Box::new(update.clone()))
174 })?));
175 let balance = update.balance.unwrap_or(U256::ZERO);
176
177 write_guard.accounts.overwrite_account(
178 update.address,
179 AccountInfo::new(balance, 0, code.hash_slow(), code),
180 Some(update.slots),
181 true,
182 );
183 } else {
184 warn!(%update.address, "force_update_accounts called with non-Creation update; ignoring");
185 }
186 }
187 Ok(())
188 }
189
190 pub fn get_storage(&self, address: &Address, index: &U256) -> Option<U256> {
206 self.inner
207 .read()
208 .unwrap()
209 .accounts
210 .get_storage(address, index)
211 }
212
213 #[expect(
223 clippy::needless_pass_by_ref_mut,
224 reason = "public API; changing the signature is a breaking change"
225 )]
226 pub fn update_state(
227 &mut self,
228 updates: &HashMap<Address, StateUpdate>,
229 block: BlockHeader,
230 ) -> Result<HashMap<Address, StateUpdate>, PreCachedDBError> {
231 let mut write_guard = self.write_inner()?;
234
235 let mut revert_updates = HashMap::new();
236 write_guard.block = Some(block);
237
238 for (address, update_info) in updates.iter() {
239 let mut revert_entry = StateUpdate::default();
240
241 if let Some(current_account) = write_guard
242 .accounts
243 .get_account_info(address)
244 {
245 revert_entry.balance = Some(current_account.balance);
246 }
247
248 if let Some(storage) = &update_info.storage {
249 let mut revert_storage = HashMap::default();
250 for index in storage.keys() {
251 if let Some(s) = write_guard
252 .accounts
253 .get_storage(address, index)
254 {
255 revert_storage.insert(*index, s);
256 }
257 }
258 revert_entry.storage = Some(revert_storage);
259 }
260 revert_updates.insert(*address, revert_entry);
261 write_guard
262 .accounts
263 .update_account(address, update_info);
264 }
265
266 Ok(revert_updates)
267 }
268
269 #[cfg(test)]
270 pub fn get_account_storage(&self) -> Result<AccountStorage, PreCachedDBError> {
271 self.read_inner()
272 .map(|guard| guard.accounts.clone())
273 }
274
275 pub fn block_number(&self) -> Result<Option<u64>, PreCachedDBError> {
277 self.read_inner().map(|guard| {
278 guard
279 .block
280 .as_ref()
281 .map(|header| header.number)
282 })
283 }
284
285 pub fn clear(&self) -> Result<(), PreCachedDBError> {
287 let mut write_guard = self.write_inner()?;
288 write_guard.accounts.clear();
289 write_guard.block = None;
290 Ok(())
291 }
292
293 fn read_inner(&self) -> Result<RwLockReadGuard<'_, PreCachedDBInner>, PreCachedDBError> {
294 self.inner.read().map_err(|_poisoned| {
295 PreCachedDBError::Fatal("Tycho state db lock poisoned".to_string())
296 })
297 }
298
299 fn write_inner(&self) -> Result<RwLockWriteGuard<'_, PreCachedDBInner>, PreCachedDBError> {
300 self.inner.write().map_err(|_poisoned| {
301 PreCachedDBError::Fatal("Tycho state db lock poisoned".to_string())
302 })
303 }
304}
305
306impl EngineDatabaseInterface for PreCachedDB {
307 type Error = PreCachedDBError;
308
309 fn init_account(
320 &self,
321 address: Address,
322 account: AccountInfo,
323 permanent_storage: Option<HashMap<U256, U256>>,
324 _mocked: bool,
325 ) -> Result<(), <Self as EngineDatabaseInterface>::Error> {
326 if account.code.is_none() && account.code_hash != KECCAK_EMPTY {
327 warn!("Code is None for account {address} but code hash is not KECCAK_EMPTY");
328 } else if account.code.is_some() && account.code_hash == KECCAK_EMPTY {
329 warn!("Code is Some for account {address} but code hash is KECCAK_EMPTY");
330 }
331
332 self.write_inner()?
333 .accounts
334 .init_account(address, account, permanent_storage, true);
335
336 Ok(())
337 }
338
339 fn clear_temp_storage(&mut self) -> Result<(), <Self as EngineDatabaseInterface>::Error> {
341 debug!("Temp storage in TychoDB is never set, nothing to clear");
342
343 Ok(())
344 }
345
346 fn get_current_block(&self) -> Option<BlockHeader> {
347 self.inner.read().unwrap().block.clone()
348 }
349}
350
351impl DatabaseRef for PreCachedDB {
352 type Error = PreCachedDBError;
353 fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
366 self.read_inner()?
367 .accounts
368 .get_account_info(&address)
369 .map(|acc| Some(acc.clone()))
370 .ok_or(PreCachedDBError::MissingAccount(address))
371 }
372
373 fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
374 Err(PreCachedDBError::Fatal(format!("Code by hash not supported: {code_hash}")))
375 }
376
377 fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
392 debug!(%address, %index, "Requested storage of account");
393 let read_guard = self.read_inner()?;
394 if let Some(storage_value) = read_guard
395 .accounts
396 .get_storage(&address, &index)
397 {
398 debug!(%address, %index, %storage_value, "Got value locally");
399 Ok(storage_value)
400 } else {
401 if read_guard
403 .accounts
404 .account_present(&address)
405 {
406 debug!(%address, %index, "Account found, but slot is zero");
409 Ok(U256::ZERO)
410 } else {
411 debug!(%address, %index, "Account not found");
413 Err(PreCachedDBError::MissingAccount(address))
414 }
415 }
416 }
417
418 fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
420 let block = self.read_inner()?.block.clone();
421 match block {
422 Some(header) => Ok(B256::from_slice(&header.hash)),
423 None => Ok(B256::default()),
424 }
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use std::{error::Error, str::FromStr};
431
432 use revm::primitives::U256;
433 use rstest::{fixture, rstest};
434 use tycho_common::Bytes;
435
436 use super::*;
437 use crate::evm::tycho_models::{AccountUpdate, Chain, ChangeType};
438
439 #[fixture]
440 pub fn mock_db() -> PreCachedDB {
441 PreCachedDB {
442 inner: Arc::new(RwLock::new(PreCachedDBInner {
443 accounts: AccountStorage::new(),
444 block: None,
445 })),
446 }
447 }
448
449 #[rstest]
450 #[tokio::test]
451 async fn test_account_get_acc_info(mock_db: PreCachedDB) -> Result<(), Box<dyn Error>> {
452 let mock_acc_address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc")?;
455 mock_db
456 .init_account(mock_acc_address, AccountInfo::default(), None, false)
457 .expect("Account init should succeed");
458
459 let acc_info = mock_db
460 .basic_ref(mock_acc_address)
461 .unwrap()
462 .unwrap();
463
464 assert_eq!(
465 mock_db
466 .basic_ref(mock_acc_address)
467 .unwrap()
468 .unwrap(),
469 acc_info
470 );
471 Ok(())
472 }
473
474 #[rstest]
475 fn test_account_storage(mock_db: PreCachedDB) {
476 let mock_acc_address =
477 Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").expect("valid address");
478 let storage_address = U256::from(1);
479 let mut permanent_storage: HashMap<U256, U256> = HashMap::new();
480 permanent_storage.insert(storage_address, U256::from(10));
481 mock_db
482 .init_account(mock_acc_address, AccountInfo::default(), Some(permanent_storage), false)
483 .expect("Account init should succeed");
484
485 let storage = mock_db
486 .storage_ref(mock_acc_address, storage_address)
487 .unwrap();
488
489 assert_eq!(storage, U256::from(10));
490 }
491
492 #[rstest]
493 fn test_account_storage_zero(mock_db: PreCachedDB) {
494 let mock_acc_address =
495 Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").expect("valid address");
496 let storage_address = U256::from(1);
497 mock_db
498 .init_account(mock_acc_address, AccountInfo::default(), None, false)
499 .expect("Account init should succeed");
500
501 let storage = mock_db
502 .storage_ref(mock_acc_address, storage_address)
503 .unwrap();
504
505 assert_eq!(storage, U256::ZERO);
506 }
507
508 #[rstest]
509 #[should_panic(
510 expected = "called `Result::unwrap()` on an `Err` value: MissingAccount(0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc)"
511 )]
512 fn test_account_storage_missing(mock_db: PreCachedDB) {
513 let mock_acc_address =
514 Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
515 let storage_address = U256::from(1);
516
517 mock_db
519 .storage_ref(mock_acc_address, storage_address)
520 .unwrap();
521 }
522
523 fn header(number: u64) -> BlockHeader {
524 BlockHeader { number, ..Default::default() }
525 }
526
527 fn snapshot(address: Address, slots: &[(u64, u64)], balance: u64) -> AccountUpdate {
528 AccountUpdate {
529 address,
530 chain: Chain::Ethereum,
531 slots: slots
532 .iter()
533 .map(|(k, v)| (U256::from(*k), U256::from(*v)))
534 .collect(),
535 balance: Some(U256::from(balance)),
536 code: Some(vec![0x60, 0x00]),
537 change: ChangeType::Creation,
538 }
539 }
540
541 #[rstest]
547 fn test_creation_reapply_overwrites_existing_account(mock_db: PreCachedDB) {
548 let address =
549 Address::from_str("0xd51a44d3fae010294c616388b506acda1bfaae46").expect("valid address");
550 let slot = U256::from(1);
551
552 mock_db
553 .update(vec![snapshot(address, &[(1, 100)], 10)], Some(header(1)))
554 .expect("initial snapshot update succeeds");
555 mock_db
557 .update(vec![snapshot(address, &[(1, 999), (2, 42)], 20)], Some(header(2)))
558 .expect("snapshot reapply succeeds");
559
560 assert_eq!(
561 mock_db.get_storage(&address, &slot),
562 Some(U256::from(999)),
563 "re-applied snapshot must overwrite a stale slot on an existing account"
564 );
565 assert_eq!(
566 mock_db.get_storage(&address, &U256::from(2)),
567 Some(U256::from(42)),
568 "slots first seen in the re-applied snapshot must be present"
569 );
570 assert_eq!(
571 mock_db
572 .basic_ref(address)
573 .unwrap()
574 .map(|acc| acc.balance),
575 Some(U256::from(20)),
576 "re-applied snapshot must refresh the native balance"
577 );
578 }
579
580 #[rstest]
583 fn test_delta_update_refreshes_existing_slot(mock_db: PreCachedDB) {
584 let address =
585 Address::from_str("0xd51a44d3fae010294c616388b506acda1bfaae46").expect("valid address");
586 let slot = U256::from(1);
587
588 mock_db
589 .update(vec![snapshot(address, &[(1, 100)], 10)], Some(header(1)))
590 .expect("initial snapshot update succeeds");
591 let delta = AccountUpdate {
592 address,
593 chain: Chain::Ethereum,
594 slots: HashMap::from([(slot, U256::from(200))]),
595 balance: None,
596 code: None,
597 change: ChangeType::Update,
598 };
599 mock_db
600 .update(vec![delta], Some(header(2)))
601 .expect("delta update succeeds");
602
603 assert_eq!(
604 mock_db.get_storage(&address, &slot),
605 Some(U256::from(200)),
606 "delta updates must refresh slots on existing accounts"
607 );
608 }
609
610 #[rstest]
611 #[tokio::test]
612 async fn test_update_state(mut mock_db: PreCachedDB) -> Result<(), Box<dyn Error>> {
613 let address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc")?;
614 mock_db
615 .init_account(address, AccountInfo::default(), None, false)
616 .expect("Account init should succeed");
617
618 let mut new_storage = HashMap::default();
619 let new_storage_value_index = U256::from_limbs_slice(&[123]);
620 new_storage.insert(new_storage_value_index, new_storage_value_index);
621 let new_balance = U256::from_limbs_slice(&[500]);
622 let update = StateUpdate { storage: Some(new_storage), balance: Some(new_balance) };
623 let new_block = BlockHeader {
624 number: 1,
625 hash: Bytes::from_str(
626 "0xc6b994ec855fb2b31013c7ae65074406fac46679b5b963469104e0bfeddd66d9",
627 )
628 .unwrap(),
629 timestamp: 123,
630 ..Default::default()
631 };
632 let mut updates = HashMap::default();
633 updates.insert(address, update);
634
635 mock_db
636 .update_state(&updates, new_block)
637 .expect("State update should succeed");
638
639 assert_eq!(
640 mock_db
641 .get_storage(&address, &new_storage_value_index)
642 .unwrap(),
643 new_storage_value_index
644 );
645 let account_info = mock_db
646 .basic_ref(address)
647 .unwrap()
648 .unwrap();
649 assert_eq!(account_info.balance, new_balance);
650 let block = mock_db
651 .inner
652 .read()
653 .unwrap()
654 .block
655 .clone()
656 .expect("block is Some");
657 assert_eq!(block.number, 1);
658
659 Ok(())
660 }
661
662 #[rstest]
663 #[tokio::test]
664 async fn test_block_number_getter(mut mock_db: PreCachedDB) -> Result<(), Box<dyn Error>> {
665 let address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc")?;
666 mock_db
667 .init_account(address, AccountInfo::default(), None, false)
668 .expect("Account init should succeed");
669
670 let new_block = BlockHeader {
671 number: 1,
672 hash: Bytes::from_str(
673 "0xc6b994ec855fb2b31013c7ae65074406fac46679b5b963469104e0bfeddd66d9",
674 )
675 .unwrap(),
676 timestamp: 123,
677 ..Default::default()
678 };
679 let updates = HashMap::default();
680
681 mock_db
682 .update_state(&updates, new_block)
683 .expect("State update should succeed");
684
685 let block_number = mock_db.block_number();
686 assert_eq!(block_number.unwrap().unwrap(), 1);
687
688 Ok(())
689 }
690
691 #[rstest]
692 #[tokio::test]
693 async fn test_update() {
694 let mock_db = PreCachedDB {
695 inner: Arc::new(RwLock::new(PreCachedDBInner {
696 accounts: AccountStorage::new(),
697 block: None,
698 })),
699 };
700
701 let account_update = AccountUpdate::new(
702 Address::from_str("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D").unwrap(),
703 Chain::Ethereum,
704 HashMap::new(),
705 Some(U256::from(500)),
706 Some(Vec::<u8>::new()),
707 ChangeType::Creation,
708 );
709
710 let new_block = BlockHeader {
711 number: 1,
712 hash: Bytes::from_str(
713 "0xc6b994ec855fb2b31013c7ae65074406fac46679b5b963469104e0bfeddd66d9",
714 )
715 .unwrap(),
716 timestamp: 123,
717 ..Default::default()
718 };
719
720 mock_db
721 .update(vec![account_update], Some(new_block))
722 .unwrap();
723
724 let account_info = mock_db
725 .basic_ref(Address::from_str("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D").unwrap())
726 .unwrap()
727 .unwrap();
728
729 assert_eq!(
730 account_info,
731 AccountInfo {
732 nonce: 0,
733 balance: U256::from(500),
734 code_hash: B256::from_str(
735 "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
736 )
737 .unwrap(),
738 code: Some(Bytecode::default()),
739 }
740 );
741
742 assert_eq!(
743 mock_db
744 .inner
745 .read()
746 .unwrap()
747 .block
748 .clone()
749 .expect("block is Some")
750 .number,
751 1
752 );
753 }
754
755 #[rstest]
756 fn test_force_update_accounts_overwrites_existing(mock_db: PreCachedDB) {
757 let address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
758
759 mock_db
761 .init_account(address, AccountInfo::default(), None, true)
762 .expect("placeholder init should succeed");
763
764 let storage_slot = U256::from(1);
766 let storage_value = U256::from(42);
767 let mut slots = HashMap::new();
768 slots.insert(storage_slot, storage_value);
769 let update = AccountUpdate::new(
770 address,
771 Chain::Ethereum,
772 slots,
773 Some(U256::from(100)),
774 Some(Vec::<u8>::new()),
775 ChangeType::Creation,
776 );
777 mock_db
778 .force_update_accounts(vec![update])
779 .expect("force update should succeed");
780
781 let info = mock_db
782 .basic_ref(address)
783 .unwrap()
784 .unwrap();
785 assert_eq!(info.balance, U256::from(100));
786 assert_eq!(
787 mock_db
788 .get_storage(&address, &storage_slot)
789 .unwrap(),
790 storage_value
791 );
792 }
793
794 #[rstest]
795 fn test_force_update_accounts_non_creation_ignored(mock_db: PreCachedDB) {
796 let address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
797 let original_balance = U256::from(10);
798
799 mock_db
800 .init_account(
801 address,
802 AccountInfo { balance: original_balance, ..Default::default() },
803 None,
804 true,
805 )
806 .expect("init should succeed");
807
808 let update = AccountUpdate::new(
810 address,
811 Chain::Ethereum,
812 HashMap::new(),
813 Some(U256::from(999)),
814 None,
815 ChangeType::Update,
816 );
817 mock_db
818 .force_update_accounts(vec![update])
819 .expect("force update should succeed");
820
821 let info = mock_db
823 .basic_ref(address)
824 .unwrap()
825 .unwrap();
826 assert_eq!(info.balance, original_balance);
827 }
828
829 #[ignore = "requires a running TychoDB instance"]
845 #[rstest]
846 fn test_tycho_db_connection() {
847 tracing_subscriber::fmt()
848 .with_env_filter("debug")
849 .init();
850
851 let ambient_contract =
852 Address::from_str("0xaaaaaaaaa24eeeb8d57d431224f73832bc34f688").unwrap();
853
854 let db = PreCachedDB::new().expect("db should initialize");
855
856 let acc_info = db
857 .basic_ref(ambient_contract)
858 .unwrap()
859 .unwrap();
860
861 debug!(?acc_info, "Account info");
862 }
863}