ic_agent/agent/
nonce.rs

1use rand::{rngs::OsRng, Rng};
2use std::sync::{
3    atomic::{AtomicU64, Ordering},
4    Arc, Mutex,
5};
6
7/// A Factory for nonce blobs.
8#[derive(Clone)]
9pub struct NonceFactory {
10    inner: Arc<dyn NonceGenerator>,
11}
12
13impl NonceFactory {
14    /// Creates a nonce factory from an iterator over blobs. The iterator is not assumed to be fused.
15    pub fn from_iterator(iter: Box<dyn Iterator<Item = Vec<u8>> + Send>) -> Self {
16        Self {
17            inner: Arc::new(Iter::from(iter)),
18        }
19    }
20
21    /// Creates a nonce factory that generates random blobs using `getrandom`.
22    pub fn random() -> NonceFactory {
23        Self {
24            inner: Arc::new(RandomBlob {}),
25        }
26    }
27
28    /// Creates a nonce factory that returns None every time.
29    pub fn empty() -> NonceFactory {
30        Self {
31            inner: Arc::new(Empty),
32        }
33    }
34
35    /// Creates a nonce factory that generates incrementing blobs.
36    pub fn incrementing() -> NonceFactory {
37        Self {
38            inner: Arc::new(Incrementing::default()),
39        }
40    }
41
42    /// Generates a nonce, if one is available. Otherwise, returns None.
43    pub fn generate(&self) -> Option<Vec<u8>> {
44        NonceGenerator::generate(self)
45    }
46}
47
48impl NonceGenerator for NonceFactory {
49    fn generate(&self) -> Option<Vec<u8>> {
50        self.inner.generate()
51    }
52}
53
54/// An interface for generating nonces.
55pub trait NonceGenerator: Send + Sync {
56    /// Generates a nonce, if one is available. Otherwise, returns None.
57    fn generate(&self) -> Option<Vec<u8>>;
58}
59
60#[expect(unused)]
61pub(crate) struct Func<T>(pub T);
62impl<T: Send + Sync + Fn() -> Option<Vec<u8>>> NonceGenerator for Func<T> {
63    fn generate(&self) -> Option<Vec<u8>> {
64        (self.0)()
65    }
66}
67
68pub(crate) struct Iter<T>(Mutex<T>);
69impl<T: Send + Iterator<Item = Vec<u8>>> From<T> for Iter<T> {
70    fn from(val: T) -> Iter<T> {
71        Iter(Mutex::new(val))
72    }
73}
74impl<T: Send + Iterator<Item = Vec<u8>>> NonceGenerator for Iter<T> {
75    fn generate(&self) -> Option<Vec<u8>> {
76        self.0.lock().unwrap().next()
77    }
78}
79
80#[derive(Default)]
81pub(crate) struct RandomBlob {}
82impl NonceGenerator for RandomBlob {
83    fn generate(&self) -> Option<Vec<u8>> {
84        Some(OsRng.gen::<[u8; 16]>().to_vec())
85    }
86}
87
88#[derive(Default)]
89pub(crate) struct Empty;
90impl NonceGenerator for Empty {
91    fn generate(&self) -> Option<Vec<u8>> {
92        None
93    }
94}
95
96#[derive(Default)]
97pub(crate) struct Incrementing {
98    next: AtomicU64,
99}
100impl From<u64> for Incrementing {
101    fn from(val: u64) -> Incrementing {
102        Incrementing {
103            next: AtomicU64::new(val),
104        }
105    }
106}
107impl NonceGenerator for Incrementing {
108    fn generate(&self) -> Option<Vec<u8>> {
109        let val = self.next.fetch_add(1, Ordering::Relaxed);
110        Some(val.to_le_bytes().to_vec())
111    }
112}
113
114impl<N: NonceGenerator + ?Sized> NonceGenerator for Box<N> {
115    fn generate(&self) -> Option<Vec<u8>> {
116        (**self).generate()
117    }
118}
119impl<N: NonceGenerator + ?Sized> NonceGenerator for Arc<N> {
120    fn generate(&self) -> Option<Vec<u8>> {
121        (**self).generate()
122    }
123}