datex_core/runtime/
global_context.rs

1use crate::{crypto::crypto::CryptoTrait, utils::time::TimeTrait};
2use std::{cell::RefCell, sync::Arc}; // FIXME #106 no-std
3
4#[cfg(feature = "debug")]
5#[derive(Clone, Debug)]
6pub struct DebugFlags {
7    pub allow_unsigned_blocks: bool,
8    pub enable_deterministic_behavior: bool,
9}
10#[cfg(feature = "debug")]
11impl Default for DebugFlags {
12    fn default() -> Self {
13        DebugFlags {
14            allow_unsigned_blocks: true,
15            enable_deterministic_behavior: true,
16        }
17    }
18}
19
20#[derive(Clone)]
21pub struct GlobalContext {
22    pub crypto: Arc<dyn CryptoTrait>,
23    pub time: Arc<dyn TimeTrait>,
24
25    #[cfg(feature = "debug")]
26    pub debug_flags: DebugFlags,
27}
28
29impl GlobalContext {
30    pub fn new(
31        crypto: Arc<dyn CryptoTrait>,
32        time: Arc<dyn TimeTrait>,
33    ) -> GlobalContext {
34        GlobalContext {
35            crypto,
36            time,
37            #[cfg(feature = "debug")]
38            debug_flags: DebugFlags::default(),
39        }
40    }
41
42    #[cfg(all(feature = "native_crypto", feature = "native_time"))]
43    pub fn native() -> GlobalContext {
44        use crate::{
45            crypto::crypto_native::CryptoNative, utils::time_native::TimeNative,
46        };
47        GlobalContext {
48            crypto: Arc::new(CryptoNative),
49            time: Arc::new(TimeNative),
50            #[cfg(feature = "debug")]
51            debug_flags: DebugFlags::default(),
52        }
53    }
54}
55
56thread_local! {
57    pub static GLOBAL_CONTEXT: RefCell<Option<GlobalContext>> = const { RefCell::new(None) };
58}
59pub fn set_global_context(c: GlobalContext) {
60    GLOBAL_CONTEXT.replace(Some(c));
61}
62pub(crate) fn get_global_context() -> GlobalContext {
63    match GLOBAL_CONTEXT.with(|c| c.borrow().clone()) {
64        Some(c) => c,
65        None => panic!(
66            "Global context not initialized - call set_global_context first!"
67        ),
68    }
69}