Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SDK: Slot Hashes: Add queries using sol_get_sysvar #1622

Merged
merged 10 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions sdk/program/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ array-bytes = { workspace = true }
assert_matches = { workspace = true }
serde_json = { workspace = true }
static_assertions = { workspace = true }
test-case = { workspace = true }

[build-dependencies]
rustc_version = { workspace = true }
Expand Down
64 changes: 63 additions & 1 deletion sdk/program/src/sysvar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,12 @@
//!
//! [sysvardoc]: https://docs.solanalabs.com/runtime/sysvars

use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey};
#[allow(deprecated)]
pub use sysvar_ids::ALL_IDS;
use {
crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey},
std::alloc::{alloc, Layout},
};

pub mod clock;
pub mod epoch_rewards;
Expand Down Expand Up @@ -249,12 +252,44 @@ macro_rules! impl_sysvar_get {
};
}

/// Handler for retrieving a slice of sysvar data from the `sol_get_sysvar`
/// syscall.
fn get_sysvar<'a>(sysvar_id: &Pubkey, offset: u64, length: u64) -> Result<&'a [u8], ProgramError> {
let sysvar_id = sysvar_id as *const _ as *const u8;

// Allocate the memory region for the sysvar data to be written to.
let var = unsafe {
let length = length as usize;
let layout = Layout::from_size_align(length, std::mem::align_of::<u8>())
.map_err(|_| ProgramError::InvalidArgument)?;
let ptr = alloc(layout);
if ptr.is_null() {
return Err(ProgramError::InvalidArgument);
}
std::slice::from_raw_parts_mut(ptr, length)
};
joncinque marked this conversation as resolved.
Show resolved Hide resolved

let var_addr = var as *mut _ as *mut u8;

#[cfg(target_os = "solana")]
let result = unsafe { crate::syscalls::sol_get_sysvar(sysvar_id, var_addr, offset, length) };

#[cfg(not(target_os = "solana"))]
let result = crate::program_stubs::sol_get_sysvar(sysvar_id, var_addr, offset, length);

match result {
crate::entrypoint::SUCCESS => Ok(var),
e => Err(e.into()),
}
}

#[cfg(test)]
mod tests {
use {
super::*,
crate::{clock::Epoch, program_error::ProgramError, pubkey::Pubkey},
std::{cell::RefCell, rc::Rc},
test_case::test_case,
};

#[repr(C)]
Expand Down Expand Up @@ -307,4 +342,31 @@ mod tests {
account_info.data = Rc::new(RefCell::new(&mut small_data));
assert_eq!(test_sysvar.to_account_info(&mut account_info), None);
}

#[allow(deprecated)]
#[test_case(0)]
#[test_case(clock::Clock::size_of() as u64)]
#[test_case(epoch_rewards::EpochRewards::size_of() as u64)]
#[test_case(epoch_schedule::EpochSchedule::size_of() as u64)]
#[test_case(fees::Fees::size_of() as u64)]
#[test_case(last_restart_slot::LastRestartSlot::size_of() as u64)]
#[test_case(rent::Rent::size_of() as u64)]
#[test_case(slot_hashes::SlotHashes::size_of() as u64)]
#[test_case(slot_history::SlotHistory::size_of() as u64)]
#[test_case(stake_history::StakeHistory::size_of() as u64)]
fn test_get_sysvar_alloc(length: u64) {
// As long as we use a test sysvar ID and we're _not_ testing from a BPF
// context, the `sol_get_sysvar` syscall will always return
// `ProgramError::UnsupportedSysvar`, since the ID will not match any
// sysvars in the Sysvar Cache.
// Under this condition, we can test the pointer allocation by ensuring
// the allocation routes to `ProgramError::UnsupportedSysvar` and does
// not throw a panic or `ProgramError::InvalidArgument`.
// Also, `offset` is only used in the syscall, _not_ the pointer
// allocation.
assert_eq!(
get_sysvar(&crate::sysvar::tests::id(), 0, length).unwrap_err(),
ProgramError::UnsupportedSysvar,
);
}
buffalojoec marked this conversation as resolved.
Show resolved Hide resolved
}
71 changes: 70 additions & 1 deletion sdk/program/src/sysvar/slot_hashes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,14 @@
//! ```

pub use crate::slot_hashes::SlotHashes;
use crate::{account_info::AccountInfo, program_error::ProgramError, sysvar::Sysvar};
use crate::{
account_info::AccountInfo,
clock::Slot,
hash::{Hash, HASH_BYTES},
program_error::ProgramError,
slot_hashes::{SlotHash, MAX_ENTRIES},
sysvar::{get_sysvar, Sysvar, SysvarId},
};

crate::declare_sysvar_id!("SysvarS1otHashes111111111111111111111111111", SlotHashes);

Expand All @@ -62,6 +69,68 @@ impl Sysvar for SlotHashes {
}
}

/// Trait for querying the `SlotHashes` sysvar.
pub trait SlotHashesSysvar {
buffalojoec marked this conversation as resolved.
Show resolved Hide resolved
/// Get a value from the sysvar entries by its key.
/// Returns `None` if the key is not found.
fn get(key: &Slot) -> Result<Option<Hash>, ProgramError> {
get_slot_hash_bytes_with_position(key)
.map(|result| result.map(|(_, bytes)| Hash::new(&bytes[8..8 + HASH_BYTES])))
}

/// Get the position of an entry in the sysvar by its key.
/// Returns `None` if the key is not found.
fn position(key: &Slot) -> Result<Option<usize>, ProgramError> {
get_slot_hash_bytes_with_position(key).map(|result| result.map(|(position, _)| position))
}
}

impl SlotHashesSysvar for SlotHashes {}

fn get_slot_hash_bytes_with_position<'a>(
slot: &Slot,
) -> Result<Option<(usize, &'a [u8])>, ProgramError> {
// Slot hashes is sorted largest -> smallest slot, so we can leverage
// this to perform the search.
//
// `SlotHashes` can have skipped slots, so we'll have to implement a
// binary search over data from `sol_get_sysvar`.
let key = slot.to_le_bytes();

// Rust's `serde::Serialize` will serialize a `usize` as a `u64` on 64-bit
// systems for vector length prefixes.
let start_offset = std::mem::size_of::<u64>();
let length = SlotHashes::size_of().saturating_sub(start_offset);
let entry_size = std::mem::size_of::<SlotHash>();

let data = get_sysvar(&SlotHashes::id(), start_offset as u64, length as u64)?;
buffalojoec marked this conversation as resolved.
Show resolved Hide resolved

let mut low: usize = 0;
let mut high: usize = MAX_ENTRIES.saturating_sub(1);
while low <= high {
let mid = low.saturating_add(high).div_euclid(2);
let offset = mid.saturating_mul(entry_size);
let end = offset.saturating_add(entry_size);

let entry_data = &data[offset..end];
let key_data = &entry_data[..8];

match key_data.cmp(&key) {
std::cmp::Ordering::Equal => {
return Ok(Some((mid, entry_data)));
}
std::cmp::Ordering::Greater => {
low = mid.saturating_add(1);
}
std::cmp::Ordering::Less => {
high = mid;
}
}
}

Ok(None)
}

#[cfg(test)]
mod tests {
use {
Expand Down