Skip to main content

rialo_s_random_seed/
lib.rs

1// Copyright (c) Subzero Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
5//! Random seed syscall for Solana programs.
6//!
7//! This module provides a safe wrapper around the `rlo_get_random_seed` syscall,
8//! which retrieves a random seed from the bank.
9
10#[cfg(not(target_os = "solana"))]
11use rand::Rng;
12use thiserror::Error;
13
14/// Errors that can be returned from the random seed syscall.
15#[derive(Debug, Clone, PartialEq, Eq, Error)]
16pub enum RandomSeedError {
17    /// Failed to retrieve random seed from the bank
18    #[error("Failed to retrieve random seed")]
19    RetrievalFailed,
20}
21
22impl From<u64> for RandomSeedError {
23    fn from(_: u64) -> RandomSeedError {
24        RandomSeedError::RetrievalFailed
25    }
26}
27
28#[cfg(target_os = "solana")]
29pub use rialo_s_define_syscall::definitions::rlo_get_random_seed;
30
31/// Retrieve a random seed from the bank.
32///
33/// This function provides a safe wrapper around the `rlo_get_random_seed` syscall.
34/// It retrieves a random 64-bit seed value that can be used for randomness in
35/// Solana programs.
36///
37/// # Returns
38///
39/// Returns `Ok(u64)` containing the random seed on success, or
40/// `Err(RandomSeedError::RetrievalFailed)` if the syscall fails.
41///
42/// # Examples
43///
44/// ```rust,no_run
45/// use rialo_s_random_seed::get_random_seed;
46///
47/// # fn example() -> Result<(), rialo_s_random_seed::RandomSeedError> {
48/// let seed = get_random_seed()?;
49/// println!("Random seed: {}", seed);
50/// # Ok(())
51/// # }
52/// ```
53///
54/// # Errors
55///
56/// Returns [`RandomSeedError::RetrievalFailed`] if the syscall fails to retrieve
57/// the random seed from the bank.
58pub fn get_random_seed() -> Result<u64, RandomSeedError> {
59    #[cfg(target_os = "solana")]
60    {
61        let mut seed: u64 = 0;
62        #[allow(unsafe_code)]
63        let result = unsafe { rlo_get_random_seed(&mut seed as *mut u64 as *mut u8) };
64
65        match result {
66            0 => Ok(seed),
67            error => Err(RandomSeedError::from(error)),
68        }
69    }
70
71    #[cfg(not(target_os = "solana"))]
72    {
73        // For off-chain testing, generate a random value using rand::thread_rng
74        let mut rng = rand::thread_rng();
75        Ok(rng.gen::<u64>())
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn test_get_random_seed_succeeds() {
85        // Test that get_random_seed returns a successful result
86        let result = get_random_seed();
87        assert!(result.is_ok());
88    }
89
90    #[test]
91    fn test_random_seed_error_from() {
92        // Test that error codes convert to RandomSeedError
93        let error = RandomSeedError::from(1u64);
94        assert_eq!(error, RandomSeedError::RetrievalFailed);
95
96        let error = RandomSeedError::from(42u64);
97        assert_eq!(error, RandomSeedError::RetrievalFailed);
98
99        let error = RandomSeedError::from(u64::MAX);
100        assert_eq!(error, RandomSeedError::RetrievalFailed);
101    }
102
103    #[test]
104    fn test_random_seed_error_display() {
105        // Test that the error displays correctly
106        let error = RandomSeedError::RetrievalFailed;
107        let error_string = format!("{}", error);
108        assert_eq!(error_string, "Failed to retrieve random seed");
109    }
110}