solana_program_fork_cleon_00/sysvar/mod.rs
1//! Access to special accounts with dynamically-updated data.
2//!
3//! Sysvars are special accounts that contain dynamically-updated data about the
4//! network cluster, the blockchain history, and the executing transaction. Each
5//! sysvar is defined in its own submodule within this module. The [`clock`],
6//! [`epoch_schedule`], [`instructions`], and [`rent`] sysvars are most useful
7//! to on-chain programs.
8//!
9//! Simple sysvars implement the [`Sysvar::get`] method, which loads a sysvar
10//! directly from the runtime, as in this example that logs the `clock` sysvar:
11//!
12//! ```
13//! use solana_program::{
14//! account_info::AccountInfo,
15//! clock,
16//! entrypoint::ProgramResult,
17//! msg,
18//! pubkey::Pubkey,
19//! sysvar::Sysvar,
20//! };
21//!
22//! fn process_instruction(
23//! program_id: &Pubkey,
24//! accounts: &[AccountInfo],
25//! instruction_data: &[u8],
26//! ) -> ProgramResult {
27//! let clock = clock::Clock::get()?;
28//! msg!("clock: {:#?}", clock);
29//! Ok(())
30//! }
31//! ```
32//!
33//! Since Solana sysvars are accounts, if the `AccountInfo` is provided to the
34//! program, then the program can deserialize the sysvar with
35//! [`Sysvar::from_account_info`] to access its data, as in this example that
36//! again logs the [`clock`] sysvar.
37//!
38//! ```
39//! use solana_program::{
40//! account_info::{next_account_info, AccountInfo},
41//! clock,
42//! entrypoint::ProgramResult,
43//! msg,
44//! pubkey::Pubkey,
45//! sysvar::Sysvar,
46//! };
47//!
48//! fn process_instruction(
49//! program_id: &Pubkey,
50//! accounts: &[AccountInfo],
51//! instruction_data: &[u8],
52//! ) -> ProgramResult {
53//! let account_info_iter = &mut accounts.iter();
54//! let clock_account = next_account_info(account_info_iter)?;
55//! let clock = clock::Clock::from_account_info(&clock_account)?;
56//! msg!("clock: {:#?}", clock);
57//! Ok(())
58//! }
59//! ```
60//!
61//! When possible, programs should prefer to call `Sysvar::get` instead of
62//! deserializing with `Sysvar::from_account_info`, 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//! `Sysvar::from_account_info` returns an error, or the serialization attempt
71//! will exhaust the program's compute budget. Some sysvars do not implement
72//! `Sysvar::get` and return an error. Some sysvars have custom deserializers
73//! that do not implement the `Sysvar` trait. These cases are documented in the
74//! modules for individual sysvars.
75//!
76//! All sysvar accounts are owned by the account identified by [`sysvar::ID`].
77//!
78//! [`sysvar::ID`]: crate::sysvar::ID
79//!
80//! For more details see the Solana [documentation on sysvars][sysvardoc].
81//!
82//! [sysvardoc]: https://docs.solanalabs.com/runtime/sysvars
83
84use {
85 crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey},
86 lazy_static::lazy_static,
87};
88
89pub mod clock;
90pub mod epoch_rewards;
91pub mod epoch_schedule;
92pub mod fees;
93pub mod instructions;
94pub mod last_restart_slot;
95pub mod recent_blockhashes;
96pub mod rent;
97pub mod rewards;
98pub mod slot_hashes;
99pub mod slot_history;
100pub mod stake_history;
101
102lazy_static! {
103 // This will be deprecated and so this list shouldn't be modified
104 pub static ref ALL_IDS: Vec<Pubkey> = vec![
105 clock::id(),
106 epoch_schedule::id(),
107 #[allow(deprecated)]
108 fees::id(),
109 #[allow(deprecated)]
110 recent_blockhashes::id(),
111 rent::id(),
112 rewards::id(),
113 slot_hashes::id(),
114 slot_history::id(),
115 stake_history::id(),
116 instructions::id(),
117 ];
118}
119
120/// Returns `true` of the given `Pubkey` is a sysvar account.
121pub fn is_sysvar_id(id: &Pubkey) -> bool {
122 ALL_IDS.iter().any(|key| key == id)
123}
124
125/// Declares an ID that implements [`SysvarId`].
126#[macro_export]
127macro_rules! declare_sysvar_id(
128 ($name:expr, $type:ty) => (
129 $crate::declare_id!($name);
130
131 impl $crate::sysvar::SysvarId for $type {
132 fn id() -> $crate::pubkey::Pubkey {
133 id()
134 }
135
136 fn check_id(pubkey: &$crate::pubkey::Pubkey) -> bool {
137 check_id(pubkey)
138 }
139 }
140 )
141);
142
143/// Same as [`declare_sysvar_id`] except that it reports that this ID has been deprecated.
144#[macro_export]
145macro_rules! declare_deprecated_sysvar_id(
146 ($name:expr, $type:ty) => (
147 $crate::declare_deprecated_id!($name);
148
149 impl $crate::sysvar::SysvarId for $type {
150 fn id() -> $crate::pubkey::Pubkey {
151 #[allow(deprecated)]
152 id()
153 }
154
155 fn check_id(pubkey: &$crate::pubkey::Pubkey) -> bool {
156 #[allow(deprecated)]
157 check_id(pubkey)
158 }
159 }
160 )
161);
162
163// Owner pubkey for sysvar accounts
164crate::declare_id!("Sysvar1111111111111111111111111111111111111");
165
166/// A type that holds sysvar data and has an associated sysvar `Pubkey`.
167pub trait SysvarId {
168 /// The `Pubkey` of the sysvar.
169 fn id() -> Pubkey;
170
171 /// Returns `true` if the given pubkey is the program ID.
172 fn check_id(pubkey: &Pubkey) -> bool;
173}
174
175/// A type that holds sysvar data.
176pub trait Sysvar:
177 SysvarId + Default + Sized + serde::Serialize + serde::de::DeserializeOwned
178{
179 /// The size in bytes of the sysvar as serialized account data.
180 fn size_of() -> usize {
181 bincode::serialized_size(&Self::default()).unwrap() as usize
182 }
183
184 /// Deserializes the sysvar from its `AccountInfo`.
185 ///
186 /// # Errors
187 ///
188 /// If `account_info` does not have the same ID as the sysvar this function
189 /// returns [`ProgramError::InvalidArgument`].
190 fn from_account_info(account_info: &AccountInfo) -> Result<Self, ProgramError> {
191 if !Self::check_id(account_info.unsigned_key()) {
192 return Err(ProgramError::InvalidArgument);
193 }
194 bincode::deserialize(&account_info.data.borrow()).map_err(|_| ProgramError::InvalidArgument)
195 }
196
197 /// Serializes the sysvar to `AccountInfo`.
198 ///
199 /// # Errors
200 ///
201 /// Returns `None` if serialization failed.
202 fn to_account_info(&self, account_info: &mut AccountInfo) -> Option<()> {
203 bincode::serialize_into(&mut account_info.data.borrow_mut()[..], self).ok()
204 }
205
206 /// Load the sysvar directly from the runtime.
207 ///
208 /// This is the preferred way to load a sysvar. Calling this method does not
209 /// incur any deserialization overhead, and does not require the sysvar
210 /// account to be passed to the program.
211 ///
212 /// Not all sysvars support this method. If not, it returns
213 /// [`ProgramError::UnsupportedSysvar`].
214 fn get() -> Result<Self, ProgramError> {
215 Err(ProgramError::UnsupportedSysvar)
216 }
217}
218
219/// Implements the [`Sysvar::get`] method for both SBF and host targets.
220#[macro_export]
221macro_rules! impl_sysvar_get {
222 ($syscall_name:ident) => {
223 fn get() -> Result<Self, ProgramError> {
224 let mut var = Self::default();
225 let var_addr = &mut var as *mut _ as *mut u8;
226
227 #[cfg(target_os = "solana")]
228 let result = unsafe { $crate::syscalls::$syscall_name(var_addr) };
229
230 #[cfg(not(target_os = "solana"))]
231 let result = $crate::program_stubs::$syscall_name(var_addr);
232
233 match result {
234 $crate::entrypoint::SUCCESS => Ok(var),
235 e => Err(e.into()),
236 }
237 }
238 };
239}
240
241#[cfg(test)]
242mod tests {
243 use {
244 super::*,
245 crate::{clock::Epoch, program_error::ProgramError, pubkey::Pubkey},
246 std::{cell::RefCell, rc::Rc},
247 };
248
249 #[repr(C)]
250 #[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq)]
251 struct TestSysvar {
252 something: Pubkey,
253 }
254 crate::declare_id!("TestSysvar111111111111111111111111111111111");
255 impl crate::sysvar::SysvarId for TestSysvar {
256 fn id() -> crate::pubkey::Pubkey {
257 id()
258 }
259
260 fn check_id(pubkey: &crate::pubkey::Pubkey) -> bool {
261 check_id(pubkey)
262 }
263 }
264 impl Sysvar for TestSysvar {}
265
266 #[test]
267 fn test_sysvar_account_info_to_from() {
268 let test_sysvar = TestSysvar::default();
269 let key = crate::sysvar::tests::id();
270 let wrong_key = Pubkey::new_unique();
271 let owner = Pubkey::new_unique();
272 let mut lamports = 42;
273 let mut data = vec![0_u8; TestSysvar::size_of()];
274 let mut account_info = AccountInfo::new(
275 &key,
276 false,
277 true,
278 &mut lamports,
279 &mut data,
280 &owner,
281 false,
282 Epoch::default(),
283 );
284
285 test_sysvar.to_account_info(&mut account_info).unwrap();
286 let new_test_sysvar = TestSysvar::from_account_info(&account_info).unwrap();
287 assert_eq!(test_sysvar, new_test_sysvar);
288
289 account_info.key = &wrong_key;
290 assert_eq!(
291 TestSysvar::from_account_info(&account_info),
292 Err(ProgramError::InvalidArgument)
293 );
294
295 let mut small_data = vec![];
296 account_info.data = Rc::new(RefCell::new(&mut small_data));
297 assert_eq!(test_sysvar.to_account_info(&mut account_info), None);
298 }
299}