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 wincode to access
34//! its data, as in this example that again logs the [`clock`] sysvar.
35//!
36//! ```
37//! use solana_account_info::{AccountInfo, next_account_info};
38//! use solana_clock::Clock;
39//! use solana_msg::msg;
40//! use solana_program_error::{ProgramError, ProgramResult};
41//! use solana_pubkey::Pubkey;
42//! use solana_sdk_ids::sysvar::clock;
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//! if !clock::check_id(clock_account.key) {
52//! return Err(ProgramError::InvalidArgument);
53//! }
54//! let clock: Clock = wincode::deserialize(&clock_account.data.borrow())
55//! .map_err(|_| ProgramError::InvalidArgument)?;
56//! msg!("clock: {:#?}", clock);
57//! Ok(())
58//! }
59//! ```
60//!
61//! When possible, programs should prefer to call `Sysvar::get` instead of
62//! deserializing with wincode, as the latter imposes extra
63//! overhead of deserialization while also requiring the sysvar account address
64//! be passed to the program, wasting the limited space available to
65//! transactions. Deserializing sysvars that can instead be retrieved with
66//! `Sysvar::get` should be only be considered for compatibility with older
67//! programs that pass around sysvar accounts.
68//!
69//! Some sysvars are too large to deserialize within a program, and
70//! deserializing them may exhaust the program's compute budget. Some sysvars do
71//! not implement `Sysvar::get` and return an error. Some sysvars have custom deserializers
72//! that do not implement the `Sysvar` trait. These cases are documented in the
73//! modules for individual sysvars.
74//!
75//! All sysvar accounts are owned by the account identified by [`sysvar::ID`].
76//!
77//! [`sysvar::ID`]: https://docs.rs/solana-sdk-ids/latest/solana_sdk_ids/sysvar/constant.ID.html
78//!
79//! For more details see the Solana [documentation on sysvars][sysvardoc].
80//!
81//! [sysvardoc]: https://docs.solanalabs.com/runtime/sysvars
82
83pub use solana_get_sysvar::{get_sysvar, impl_get_sysvar as impl_sysvar_get, GetSysvar as Sysvar};
84#[cfg(feature = "bincode")]
85use solana_program_error::ProgramError;
86#[cfg(feature = "bincode")]
87use {solana_account_info::AccountInfo, solana_sysvar_id::SysvarId};
88
89pub mod clock;
90pub mod epoch_rewards;
91pub mod epoch_schedule;
92pub mod fees;
93pub mod last_restart_slot;
94pub mod program_stubs;
95pub mod recent_blockhashes;
96pub mod rent;
97pub mod rewards;
98pub mod slot_hashes;
99pub mod slot_history;
100pub mod stake_history;
101
102#[cfg(feature = "bincode")]
103/// A type that holds sysvar data.
104#[deprecated(
105 since = "4.3.0",
106 note = "Use `wincode::deserialize` and check the sysvar account address"
107)]
108pub trait SysvarSerialize:
109 Default + Sysvar + SysvarId + serde::Serialize + serde::de::DeserializeOwned
110{
111 /// The size in bytes of the sysvar as serialized account data.
112 #[deprecated(
113 since = "4.3.0",
114 note = "Use the sysvar crate's `SIZE` constant or `wincode::serialized_size`"
115 )]
116 fn size_of() -> usize {
117 bincode::serialized_size(&Self::default()).unwrap() as usize
118 }
119
120 /// Deserializes the sysvar from its `AccountInfo`.
121 ///
122 /// # Errors
123 ///
124 /// If `account_info` does not have the same ID as the sysvar this function
125 /// returns [`ProgramError::InvalidArgument`].
126 #[deprecated(
127 since = "4.3.0",
128 note = "Use `wincode::deserialize` and check the account address"
129 )]
130 fn from_account_info(account_info: &AccountInfo) -> Result<Self, ProgramError> {
131 if !Self::check_id(account_info.unsigned_key()) {
132 return Err(ProgramError::InvalidArgument);
133 }
134 bincode::deserialize(&account_info.data.borrow()).map_err(|_| ProgramError::InvalidArgument)
135 }
136
137 /// Serializes the sysvar to `AccountInfo`.
138 ///
139 /// # Errors
140 ///
141 /// Returns `None` if serialization failed.
142 #[deprecated(since = "4.3.0", note = "Use `wincode::serialize_into`")]
143 fn to_account_info(&self, account_info: &mut AccountInfo) -> Option<()> {
144 bincode::serialize_into(&mut account_info.data.borrow_mut()[..], self).ok()
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use {
151 super::*,
152 serde_derive::{Deserialize, Serialize},
153 solana_program_error::ProgramError,
154 solana_pubkey::Pubkey,
155 std::{cell::RefCell, rc::Rc},
156 };
157
158 #[repr(C)]
159 #[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq)]
160 struct TestSysvar {
161 something: Pubkey,
162 }
163 solana_pubkey::declare_id!("TestSysvar111111111111111111111111111111111");
164 impl solana_sysvar_id::SysvarId for TestSysvar {
165 fn id() -> solana_pubkey::Pubkey {
166 id()
167 }
168
169 fn check_id(pubkey: &solana_pubkey::Pubkey) -> bool {
170 check_id(pubkey)
171 }
172 }
173 impl Sysvar for TestSysvar {}
174 #[allow(deprecated)]
175 impl SysvarSerialize for TestSysvar {}
176
177 #[test]
178 #[allow(deprecated)]
179 fn test_sysvar_account_info_to_from() {
180 let test_sysvar = TestSysvar::default();
181 let key = id();
182 let wrong_key = Pubkey::new_unique();
183 let owner = Pubkey::new_unique();
184 let mut lamports = 42;
185 let mut data = vec![0_u8; TestSysvar::size_of()];
186 let mut account_info =
187 AccountInfo::new(&key, false, true, &mut lamports, &mut data, &owner, false);
188
189 test_sysvar.to_account_info(&mut account_info).unwrap();
190 let new_test_sysvar = TestSysvar::from_account_info(&account_info).unwrap();
191 assert_eq!(test_sysvar, new_test_sysvar);
192
193 account_info.key = &wrong_key;
194 assert_eq!(
195 TestSysvar::from_account_info(&account_info),
196 Err(ProgramError::InvalidArgument)
197 );
198
199 let mut small_data = vec![];
200 account_info.data = Rc::new(RefCell::new(&mut small_data));
201 assert_eq!(test_sysvar.to_account_info(&mut account_info), None);
202 }
203}