hpsvm 0.1.3

A fast and lightweight Solana VM simulator for testing solana programs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#[cfg(not(feature = "hashbrown"))]
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

#[cfg(feature = "hashbrown")]
use hashbrown::{HashMap, HashSet};
use solana_account::{AccountSharedData, ReadableAccount, state_traits::StateMut};
use solana_address::Address;
use solana_address_lookup_table_interface::{error::AddressLookupError, state::AddressLookupTable};
use solana_builtins::BUILTINS;
use solana_clock::Clock;
use solana_instruction::error::InstructionError;
use solana_loader_v3_interface::state::UpgradeableLoaderState;
use solana_loader_v4_interface::state::LoaderV4State;
use solana_message::{
    AddressLoader,
    v0::{LoadedAddresses, MessageAddressTableLookup},
};
use solana_program_runtime::{
    loaded_programs::{
        LoadProgramMetrics, ProgramCacheEntry, ProgramCacheEntryOwner, ProgramCacheEntryType,
        ProgramCacheForTxBatch, ProgramRuntimeEnvironments,
    },
    sysvar_cache::SysvarCache,
};
use solana_sdk_ids::{
    bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, loader_v4, native_loader,
    sysvar::{
        clock::ID as CLOCK_ID, epoch_rewards::ID as EPOCH_REWARDS_ID,
        epoch_schedule::ID as EPOCH_SCHEDULE_ID, last_restart_slot::ID as LAST_RESTART_SLOT_ID,
        rent::ID as RENT_ID, slot_hashes::ID as SLOT_HASHES_ID,
        stake_history::ID as STAKE_HISTORY_ID,
    },
};
use solana_transaction_error::AddressLoaderError;

use crate::{
    account_source::{AccountSource, AccountSourceError, EmptyAccountSource},
    error::{HPSVMError, InvalidSysvarDataError},
};

const FEES_ID: Address = Address::from_str_const("SysvarFees111111111111111111111111111111111");
const RECENT_BLOCKHASHES_ID: Address =
    Address::from_str_const("SysvarRecentB1ockHashes11111111111111111111");

fn is_cached_program_account(pubkey: &Address, account: &AccountSharedData) -> bool {
    account.executable() && *pubkey != Address::default() && account.owner() != &native_loader::ID
}

const fn is_managed_sysvar_account(pubkey: &Address) -> bool {
    matches!(
        *pubkey,
        CLOCK_ID |
            EPOCH_REWARDS_ID |
            EPOCH_SCHEDULE_ID |
            FEES_ID |
            LAST_RESTART_SLOT_ID |
            RECENT_BLOCKHASHES_ID |
            RENT_ID |
            SLOT_HASHES_ID |
            STAKE_HISTORY_ID
    )
}

fn validate_sysvar_account(
    pubkey: Address,
    account: &AccountSharedData,
) -> Result<(), InvalidSysvarDataError> {
    use InvalidSysvarDataError::{
        Clock as ClockError, EpochRewards, EpochSchedule, Fees, LastRestartSlot, RecentBlockhashes,
        Rent, SlotHashes, StakeHistory,
    };

    match pubkey {
        CLOCK_ID => {
            let _: Clock = account.deserialize_data().map_err(|_| ClockError)?;
        }
        EPOCH_REWARDS_ID => {
            let _: solana_epoch_rewards::EpochRewards =
                account.deserialize_data().map_err(|_| EpochRewards)?;
        }
        EPOCH_SCHEDULE_ID => {
            let _: solana_epoch_schedule::EpochSchedule =
                account.deserialize_data().map_err(|_| EpochSchedule)?;
        }
        FEES_ID => {
            #[expect(deprecated)]
            let _: solana_sysvar::fees::Fees = account.deserialize_data().map_err(|_| Fees)?;
        }
        LAST_RESTART_SLOT_ID => {
            let _: solana_sysvar::last_restart_slot::LastRestartSlot =
                account.deserialize_data().map_err(|_| LastRestartSlot)?;
        }
        RECENT_BLOCKHASHES_ID => {
            #[expect(deprecated)]
            let _: solana_sysvar::recent_blockhashes::RecentBlockhashes =
                account.deserialize_data().map_err(|_| RecentBlockhashes)?;
        }
        RENT_ID => {
            let _: solana_rent::Rent = account.deserialize_data().map_err(|_| Rent)?;
        }
        SLOT_HASHES_ID => {
            let _: solana_slot_hashes::SlotHashes =
                account.deserialize_data().map_err(|_| SlotHashes)?;
        }
        STAKE_HISTORY_ID => {
            let _: solana_stake_interface::stake_history::StakeHistory =
                account.deserialize_data().map_err(|_| StakeHistory)?;
        }
        _ => {}
    }

    Ok(())
}

pub(crate) struct AccountsDb {
    source: Arc<dyn AccountSource>,
    inner: HashMap<Address, AccountSharedData>,
    removed: HashSet<Address>,
    programs_cache: ProgramCacheForTxBatch,
    sysvar_cache: SysvarCache,
    environments: ProgramRuntimeEnvironments,
}

impl Clone for AccountsDb {
    fn clone(&self) -> Self {
        Self {
            source: self.source.clone(),
            inner: self.inner.clone(),
            removed: self.removed.clone(),
            programs_cache: self.programs_cache.clone(),
            sysvar_cache: self.sysvar_cache.clone(),
            environments: self.environments.clone(),
        }
    }
}

impl Default for AccountsDb {
    fn default() -> Self {
        Self {
            source: Arc::new(EmptyAccountSource),
            inner: HashMap::default(),
            removed: HashSet::default(),
            programs_cache: ProgramCacheForTxBatch::default(),
            sysvar_cache: SysvarCache::default(),
            environments: ProgramRuntimeEnvironments::default(),
        }
    }
}

impl std::fmt::Debug for AccountsDb {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AccountsDb")
            .field("source", &"dyn AccountSource")
            .field("inner", &self.inner)
            .field("removed", &self.removed)
            .field("programs_cache", &self.programs_cache)
            .field("sysvar_cache", &self.sysvar_cache)
            .field("environments", &self.environments)
            .finish()
    }
}

/// Read-only facade over the VM accounts database.
#[derive(Clone, Copy, Debug)]
pub struct AccountsView<'a> {
    accounts_db: &'a AccountsDb,
}

impl<'a> AccountsView<'a> {
    pub(crate) const fn new(accounts_db: &'a AccountsDb) -> Self {
        Self { accounts_db }
    }

    /// Returns a borrowed account for the provided address.
    pub fn get_account_ref(&self, pubkey: &Address) -> Option<&'a AccountSharedData> {
        self.accounts_db.get_account_ref(pubkey)
    }

    /// Returns a cloned account for the provided address.
    pub fn get_account(&self, pubkey: &Address) -> Option<AccountSharedData> {
        self.accounts_db.get_account(pubkey)
    }

    /// Returns a borrowed slice of ELF bytes for the provided program account.
    pub fn try_program_elf_bytes(
        &self,
        program_key: &Address,
    ) -> std::result::Result<&'a [u8], InstructionError> {
        self.accounts_db.try_program_elf_bytes(program_key)
    }
}

impl AccountsDb {
    pub(crate) fn set_account_source(&mut self, source: Arc<dyn AccountSource>) {
        self.source = source;
    }

    pub(crate) fn replace_account_source(
        &mut self,
        source: Arc<dyn AccountSource>,
    ) -> Arc<dyn AccountSource> {
        std::mem::replace(&mut self.source, source)
    }

    pub fn get_account_ref(&self, pubkey: &Address) -> Option<&AccountSharedData> {
        self.inner.get(pubkey)
    }

    pub fn try_get_account(
        &self,
        pubkey: &Address,
    ) -> Result<Option<AccountSharedData>, AccountSourceError> {
        if let Some(account) = self.get_account_ref(pubkey) {
            return Ok(Some(account.clone()));
        }

        if self.removed.contains(pubkey) {
            return Ok(None);
        }

        self.source.get_account(pubkey)
    }

    pub fn get_account(&self, pubkey: &Address) -> Option<AccountSharedData> {
        self.try_get_account(pubkey).unwrap_or_else(|error| {
            tracing::error!(?pubkey, %error, "failed to load account from source");
            None
        })
    }

    pub(crate) fn remove_account(&mut self, pubkey: &Address) {
        self.inner.remove(pubkey);
        self.removed.insert(*pubkey);
    }

    pub(crate) fn minimum_balance_for_rent_exemption(&self, data_len: usize) -> u64 {
        1.max(self.sysvar_cache.get_rent().unwrap_or_default().minimum_balance(data_len))
    }

    pub(crate) fn current_slot(&self) -> u64 {
        self.sysvar_cache.get_clock().unwrap_or_default().slot
    }

    pub(crate) fn replenish_program_cache(
        &mut self,
        program_id: Address,
        program: Arc<ProgramCacheEntry>,
    ) {
        self.programs_cache.replenish(program_id, program);
    }

    pub(crate) fn cloned_programs_cache(&self) -> ProgramCacheForTxBatch {
        self.programs_cache.clone()
    }

    pub(crate) fn has_program_cache_entry(&self, program_id: &Address) -> bool {
        self.programs_cache.find(program_id).is_some()
    }

    pub(crate) const fn runtime_environments(&self) -> &ProgramRuntimeEnvironments {
        &self.environments
    }

    pub(crate) fn runtime_environments_mut(&mut self) -> &mut ProgramRuntimeEnvironments {
        &mut self.environments
    }

    pub(crate) const fn sysvar_cache(&self) -> &SysvarCache {
        &self.sysvar_cache
    }

    /// We should only use this when we know we're not touching any executable or sysvar accounts,
    /// or have already handled such cases.
    pub(crate) fn add_account_no_checks(&mut self, pubkey: Address, account: AccountSharedData) {
        self.removed.remove(&pubkey);
        self.inner.insert(pubkey, account);
    }

    pub(crate) fn add_account(
        &mut self,
        pubkey: Address,
        account: AccountSharedData,
    ) -> Result<(), HPSVMError> {
        let had_cached_program = self
            .inner
            .get(&pubkey)
            .is_some_and(|existing| is_cached_program_account(&pubkey, existing));

        if is_managed_sysvar_account(&pubkey) && account.lamports() != 0 {
            validate_sysvar_account(pubkey, &account)?;
        }

        if account.lamports() == 0 {
            self.inner.remove(&pubkey);
            self.removed.insert(pubkey);
        } else {
            self.add_account_no_checks(pubkey, account.clone());
        }

        if is_managed_sysvar_account(&pubkey) {
            self.rebuild_sysvar_cache();
        }

        let has_cached_program =
            account.lamports() != 0 && is_cached_program_account(&pubkey, &account);
        if has_cached_program {
            let loaded_program = self.load_program(
                self.get_account_ref(&pubkey)
                    .expect("program account just inserted - this should never fail"),
            )?;
            self.programs_cache.replenish(pubkey, Arc::new(loaded_program));
        } else if had_cached_program {
            self.rebuild_program_cache()?;
        }

        Ok(())
    }

    pub(crate) fn rebuild_sysvar_cache(&mut self) {
        self.sysvar_cache.reset();
        self.sysvar_cache.fill_missing_entries(|pubkey, set_sysvar| {
            if let Some(acc) = self.inner.get(pubkey) {
                set_sysvar(acc.data());
            }
        });
        let slot = self.sysvar_cache.get_clock().unwrap_or_default().slot;
        self.programs_cache.set_slot_for_tests(slot);
    }

    pub(crate) fn rebuild_program_cache(&mut self) -> Result<(), InstructionError> {
        let slot = self.sysvar_cache.get_clock().unwrap_or_default().slot;
        let mut cache = ProgramCacheForTxBatch::new(slot);

        BUILTINS.iter().filter(|builtin| self.inner.contains_key(&builtin.program_id)).for_each(
            |builtin| {
                let loaded_program =
                    ProgramCacheEntry::new_builtin(0, builtin.name.len(), builtin.entrypoint);
                cache.replenish(builtin.program_id, Arc::new(loaded_program));
            },
        );

        let program_keys = self
            .inner
            .iter()
            .filter_map(|(pubkey, account)| {
                is_cached_program_account(pubkey, account).then_some(*pubkey)
            })
            .collect::<Vec<_>>();

        for pubkey in program_keys {
            let loaded_program = self.load_program(
                self.get_account_ref(&pubkey).expect("program account should exist during rebuild - this indicates an internal inconsistency"),
            )?;
            cache.replenish(pubkey, Arc::new(loaded_program));
        }

        self.programs_cache = cache;
        Ok(())
    }

    /// Skip the executable() checks for builtin accounts
    pub(crate) fn add_builtin_account(&mut self, address: Address, data: AccountSharedData) {
        self.removed.remove(&address);
        self.inner.insert(address, data);
    }

    pub(crate) fn sync_accounts(
        &mut self,
        mut accounts: Vec<(Address, AccountSharedData)>,
    ) -> Result<(), HPSVMError> {
        // need to add programdata accounts first if there are any
        itertools::partition(&mut accounts, |x| {
            x.1.owner() == &bpf_loader_upgradeable::id() &&
                x.1.data().first().is_some_and(|byte| *byte == 3)
        });
        for (address, acc) in accounts {
            self.add_account(address, acc)?;
        }
        Ok(())
    }

    fn load_program(
        &self,
        program_account: &AccountSharedData,
    ) -> Result<ProgramCacheEntry, InstructionError> {
        let metrics = &mut LoadProgramMetrics::default();

        let owner = program_account.owner();
        let program_runtime_v1 = self.environments.program_runtime_v1.clone();
        let slot =
            self.sysvar_cache.get_clock().expect("clock sysvar should always be available").slot;

        if bpf_loader::check_id(owner) || bpf_loader_deprecated::check_id(owner) {
            ProgramCacheEntry::new(
                owner,
                program_runtime_v1,
                slot,
                slot,
                program_account.data(),
                program_account.data().len(),
                metrics,
            )
            .map_err(|e| {
                tracing::error!("Failed to load program: {e:?}");
                InstructionError::InvalidAccountData
            })
        } else if bpf_loader_upgradeable::check_id(owner) {
            let Ok(UpgradeableLoaderState::Program { programdata_address }) =
                program_account.state()
            else {
                tracing::error!(
                    "Program account data does not deserialize to UpgradeableLoaderState::Program"
                );
                return Err(InstructionError::InvalidAccountData);
            };
            let Some(programdata_account) = self.get_account(&programdata_address) else {
                return Ok(ProgramCacheEntry::new_tombstone(
                    slot,
                    ProgramCacheEntryOwner::LoaderV3,
                    ProgramCacheEntryType::Closed,
                ));
            };
            let program_data = programdata_account.data();
            if let Some(programdata) =
                program_data.get(UpgradeableLoaderState::size_of_programdata_metadata()..)
            {
                ProgramCacheEntry::new(
                    owner,
                    program_runtime_v1,
                    slot,
                    slot,
                    programdata,
                    program_account
                        .data()
                        .len()
                        .saturating_add(program_data.len()),
                    metrics).map_err(|e| {
                        tracing::error!("Error encountered when calling ProgramCacheEntry::new() for bpf_loader_upgradeable: {e:?}");
                        InstructionError::InvalidAccountData
                    })
            } else {
                tracing::error!("Index out of bounds using bpf_loader_upgradeable.");
                Err(InstructionError::InvalidAccountData)
            }
        } else if loader_v4::check_id(owner) {
            if let Some(elf_bytes) =
                program_account.data().get(LoaderV4State::program_data_offset()..)
            {
                ProgramCacheEntry::new(
                    &loader_v4::id(),
                    program_runtime_v1,
                    slot,
                    slot,
                    elf_bytes,
                    program_account.data().len(),
                    metrics,
                )
                .map_err(|_| {
                    tracing::error!(
                        "Error encountered when calling LoadedProgram::new() for loader_v4."
                    );
                    InstructionError::InvalidAccountData
                })
            } else {
                tracing::error!("Index out of bounds using loader_v4.");
                Err(InstructionError::InvalidAccountData)
            }
        } else {
            tracing::error!("Owner does not match any expected loader.");
            Err(InstructionError::IncorrectProgramId)
        }
    }

    fn load_lookup_table_addresses(
        &self,
        address_table_lookup: &MessageAddressTableLookup,
    ) -> std::result::Result<LoadedAddresses, AddressLookupError> {
        let table_account = self
            .get_account(&address_table_lookup.account_key)
            .ok_or(AddressLookupError::LookupTableAccountNotFound)?;

        if table_account.owner() == &solana_sdk_ids::address_lookup_table::id() {
            let slot_hashes = self
                .sysvar_cache
                .get_slot_hashes()
                .expect("slot hashes sysvar should always be available");
            let current_slot = self
                .sysvar_cache
                .get_clock()
                .expect("clock sysvar should always be available")
                .slot;
            let lookup_table = AddressLookupTable::deserialize(table_account.data())
                .map_err(|_ix_err| AddressLookupError::InvalidAccountData)?;

            Ok(LoadedAddresses {
                writable: lookup_table.lookup(
                    current_slot,
                    &address_table_lookup.writable_indexes,
                    &slot_hashes,
                )?,
                readonly: lookup_table.lookup(
                    current_slot,
                    &address_table_lookup.readonly_indexes,
                    &slot_hashes,
                )?,
            })
        } else {
            Err(AddressLookupError::InvalidAccountOwner)
        }
    }

    /// Returns a borrowed slice of ELF bytes for this account.
    /// Fails if the account is not a program account.
    pub fn try_program_elf_bytes<'a>(
        &'a self,
        program_key: &Address,
    ) -> std::result::Result<&'a [u8], InstructionError> {
        let program_account =
            self.get_account_ref(program_key).ok_or(InstructionError::MissingAccount)?;
        let owner = program_account.owner();

        if bpf_loader::check_id(owner) || bpf_loader_deprecated::check_id(owner) {
            Ok(program_account.data())
        } else if bpf_loader_upgradeable::check_id(owner) {
            let Ok(UpgradeableLoaderState::Program { programdata_address }) =
                program_account.state()
            else {
                return Err(InstructionError::InvalidAccountData);
            };
            let programdata_account =
                self.get_account_ref(&programdata_address).ok_or_else(|| {
                    tracing::error!("Program data account {programdata_address} not found");
                    InstructionError::MissingAccount
                })?;
            let program_data = programdata_account.data();
            if let Some(programdata) =
                program_data.get(UpgradeableLoaderState::size_of_programdata_metadata()..)
            {
                Ok(programdata)
            } else {
                tracing::error!("Index out of bounds using bpf_loader_upgradeable.");
                Err(InstructionError::InvalidAccountData)
            }
        } else if loader_v4::check_id(owner) {
            if let Some(elf_bytes) =
                program_account.data().get(LoaderV4State::program_data_offset()..)
            {
                Ok(elf_bytes)
            } else {
                tracing::error!("Index out of bounds using loader_v4.");
                Err(InstructionError::InvalidAccountData)
            }
        } else {
            tracing::error!("Owner does not match any expected loader.");
            Err(InstructionError::IncorrectProgramId)
        }
    }
}

const fn into_address_loader_error(err: AddressLookupError) -> AddressLoaderError {
    match err {
        AddressLookupError::LookupTableAccountNotFound => {
            AddressLoaderError::LookupTableAccountNotFound
        }
        AddressLookupError::InvalidAccountOwner => AddressLoaderError::InvalidAccountOwner,
        AddressLookupError::InvalidAccountData => AddressLoaderError::InvalidAccountData,
        AddressLookupError::InvalidLookupIndex => AddressLoaderError::InvalidLookupIndex,
    }
}

impl AddressLoader for &AccountsDb {
    fn load_addresses(
        self,
        lookups: &[MessageAddressTableLookup],
    ) -> Result<LoadedAddresses, AddressLoaderError> {
        lookups
            .iter()
            .map(|lookup| {
                self.load_lookup_table_addresses(lookup).map_err(into_address_loader_error)
            })
            .collect()
    }
}