Skip to main content

solana_sysvar/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
3//! Access to special accounts with dynamically-updated data.
4//!
5//! Sysvars are special accounts that contain dynamically-updated data about the
6//! network cluster, the blockchain history, and the executing transaction. Each
7//! sysvar is defined in its own submodule within this module. The [`clock`],
8//! [`epoch_schedule`], and [`rent`] sysvars are most useful to on-chain
9//! programs.
10//!
11//! Simple sysvars implement the [`Sysvar::get`] method, which loads a sysvar
12//! directly from the runtime, as in this example that logs the `clock` sysvar:
13//!
14//! ```
15//! use solana_account_info::AccountInfo;
16//! use solana_msg::msg;
17//! use solana_sysvar::Sysvar;
18//! use solana_program_error::ProgramResult;
19//! use solana_pubkey::Pubkey;
20//!
21//! fn process_instruction(
22//!     program_id: &Pubkey,
23//!     accounts: &[AccountInfo],
24//!     instruction_data: &[u8],
25//! ) -> ProgramResult {
26//!     let clock = solana_clock::Clock::get()?;
27//!     msg!("clock: {:#?}", clock);
28//!     Ok(())
29//! }
30//! ```
31//!
32//! Since Solana sysvars are accounts, if the `AccountInfo` is provided to the
33//! program, then the program can deserialize the sysvar with
34//! [`SysvarSerialize::from_account_info`] to access its data, as in this example that
35//! again logs the [`clock`] sysvar.
36//!
37//! ```
38//! use solana_account_info::{AccountInfo, next_account_info};
39//! use solana_msg::msg;
40//! use solana_sysvar::{Sysvar, SysvarSerialize};
41//! use solana_program_error::ProgramResult;
42//! use solana_pubkey::Pubkey;
43//!
44//! fn process_instruction(
45//!     program_id: &Pubkey,
46//!     accounts: &[AccountInfo],
47//!     instruction_data: &[u8],
48//! ) -> ProgramResult {
49//!     let account_info_iter = &mut accounts.iter();
50//!     let clock_account = next_account_info(account_info_iter)?;
51//!     let clock = solana_clock::Clock::from_account_info(&clock_account)?;
52//!     msg!("clock: {:#?}", clock);
53//!     Ok(())
54//! }
55//! ```
56//!
57//! When possible, programs should prefer to call `Sysvar::get` instead of
58//! deserializing with `Sysvar::from_account_info`, as the latter imposes extra
59//! overhead of deserialization while also requiring the sysvar account address
60//! be passed to the program, wasting the limited space available to
61//! transactions. Deserializing sysvars that can instead be retrieved with
62//! `Sysvar::get` should be only be considered for compatibility with older
63//! programs that pass around sysvar accounts.
64//!
65//! Some sysvars are too large to deserialize within a program, and
66//! `Sysvar::from_account_info` returns an error, or the serialization attempt
67//! will exhaust the program's compute budget. Some sysvars do not implement
68//! `Sysvar::get` and return an error. Some sysvars have custom deserializers
69//! that do not implement the `Sysvar` trait. These cases are documented in the
70//! modules for individual sysvars.
71//!
72//! All sysvar accounts are owned by the account identified by [`sysvar::ID`].
73//!
74//! [`sysvar::ID`]: https://docs.rs/solana-sdk-ids/latest/solana_sdk_ids/sysvar/constant.ID.html
75//!
76//! For more details see the Solana [documentation on sysvars][sysvardoc].
77//!
78//! [sysvardoc]: https://docs.solanalabs.com/runtime/sysvars
79
80pub use solana_get_sysvar::{get_sysvar, impl_get_sysvar as impl_sysvar_get, GetSysvar as Sysvar};
81#[cfg(feature = "bincode")]
82use solana_program_error::ProgramError;
83#[cfg(feature = "bincode")]
84use {solana_account_info::AccountInfo, solana_sysvar_id::SysvarId};
85
86pub mod clock;
87pub mod epoch_rewards;
88pub mod epoch_schedule;
89pub mod fees;
90pub mod last_restart_slot;
91pub mod program_stubs;
92pub mod recent_blockhashes;
93pub mod rent;
94pub mod rewards;
95pub mod slot_hashes;
96pub mod slot_history;
97pub mod stake_history;
98
99#[cfg(feature = "bincode")]
100/// A type that holds sysvar data.
101pub trait SysvarSerialize:
102    Default + Sysvar + SysvarId + serde::Serialize + serde::de::DeserializeOwned
103{
104    /// The size in bytes of the sysvar as serialized account data.
105    fn size_of() -> usize {
106        bincode::serialized_size(&Self::default()).unwrap() as usize
107    }
108
109    /// Deserializes the sysvar from its `AccountInfo`.
110    ///
111    /// # Errors
112    ///
113    /// If `account_info` does not have the same ID as the sysvar this function
114    /// returns [`ProgramError::InvalidArgument`].
115    fn from_account_info(account_info: &AccountInfo) -> Result<Self, ProgramError> {
116        if !Self::check_id(account_info.unsigned_key()) {
117            return Err(ProgramError::InvalidArgument);
118        }
119        bincode::deserialize(&account_info.data.borrow()).map_err(|_| ProgramError::InvalidArgument)
120    }
121
122    /// Serializes the sysvar to `AccountInfo`.
123    ///
124    /// # Errors
125    ///
126    /// Returns `None` if serialization failed.
127    fn to_account_info(&self, account_info: &mut AccountInfo) -> Option<()> {
128        bincode::serialize_into(&mut account_info.data.borrow_mut()[..], self).ok()
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use {
135        super::*,
136        serde_derive::{Deserialize, Serialize},
137        solana_program_error::ProgramError,
138        solana_pubkey::Pubkey,
139        std::{cell::RefCell, rc::Rc},
140    };
141
142    #[repr(C)]
143    #[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq)]
144    struct TestSysvar {
145        something: Pubkey,
146    }
147    solana_pubkey::declare_id!("TestSysvar111111111111111111111111111111111");
148    impl solana_sysvar_id::SysvarId for TestSysvar {
149        fn id() -> solana_pubkey::Pubkey {
150            id()
151        }
152
153        fn check_id(pubkey: &solana_pubkey::Pubkey) -> bool {
154            check_id(pubkey)
155        }
156    }
157    impl Sysvar for TestSysvar {}
158    impl SysvarSerialize for TestSysvar {}
159
160    #[test]
161    fn test_sysvar_account_info_to_from() {
162        let test_sysvar = TestSysvar::default();
163        let key = id();
164        let wrong_key = Pubkey::new_unique();
165        let owner = Pubkey::new_unique();
166        let mut lamports = 42;
167        let mut data = vec![0_u8; TestSysvar::size_of()];
168        let mut account_info =
169            AccountInfo::new(&key, false, true, &mut lamports, &mut data, &owner, false);
170
171        test_sysvar.to_account_info(&mut account_info).unwrap();
172        let new_test_sysvar = TestSysvar::from_account_info(&account_info).unwrap();
173        assert_eq!(test_sysvar, new_test_sysvar);
174
175        account_info.key = &wrong_key;
176        assert_eq!(
177            TestSysvar::from_account_info(&account_info),
178            Err(ProgramError::InvalidArgument)
179        );
180
181        let mut small_data = vec![];
182        account_info.data = Rc::new(RefCell::new(&mut small_data));
183        assert_eq!(test_sysvar.to_account_info(&mut account_info), None);
184    }
185}