solana_svm/
account_overrides.rs

1use {
2    solana_account::AccountSharedData, solana_pubkey::Pubkey, solana_sdk_ids::sysvar,
3    std::collections::HashMap,
4};
5
6/// Encapsulates overridden accounts, typically used for transaction
7/// simulations. Account overrides are currently not used when loading the
8/// durable nonce account or when constructing the instructions sysvar account.
9#[derive(Default)]
10pub struct AccountOverrides {
11    accounts: HashMap<Pubkey, AccountSharedData>,
12}
13
14impl AccountOverrides {
15    /// Insert or remove an account with a given pubkey to/from the list of overrides.
16    fn set_account(&mut self, pubkey: &Pubkey, account: Option<AccountSharedData>) {
17        match account {
18            Some(account) => self.accounts.insert(*pubkey, account),
19            None => self.accounts.remove(pubkey),
20        };
21    }
22
23    /// Sets in the slot history
24    ///
25    /// Note: no checks are performed on the correctness of the contained data
26    pub fn set_slot_history(&mut self, slot_history: Option<AccountSharedData>) {
27        self.set_account(&sysvar::slot_history::id(), slot_history);
28    }
29
30    /// Gets the account if it's found in the list of overrides
31    pub(crate) fn get(&self, pubkey: &Pubkey) -> Option<&AccountSharedData> {
32        self.accounts.get(pubkey)
33    }
34}
35
36#[cfg(test)]
37mod test {
38    use {
39        crate::account_overrides::AccountOverrides, solana_account::AccountSharedData,
40        solana_pubkey::Pubkey, solana_sdk_ids::sysvar,
41    };
42
43    #[test]
44    fn test_set_account() {
45        let mut accounts = AccountOverrides::default();
46        let data = AccountSharedData::default();
47        let key = Pubkey::new_unique();
48        accounts.set_account(&key, Some(data.clone()));
49        assert_eq!(accounts.get(&key), Some(&data));
50
51        accounts.set_account(&key, None);
52        assert!(accounts.get(&key).is_none());
53    }
54
55    #[test]
56    fn test_slot_history() {
57        let mut accounts = AccountOverrides::default();
58        let data = AccountSharedData::default();
59
60        assert_eq!(accounts.get(&sysvar::slot_history::id()), None);
61        accounts.set_slot_history(Some(data.clone()));
62
63        assert_eq!(accounts.get(&sysvar::slot_history::id()), Some(&data));
64    }
65}