Skip to main content

lb_rs/model/
entropy.rs

1#[cfg(feature = "test-seed")]
2use std::sync::{Arc, Mutex};
3
4use libsecp256k1::SecretKey;
5use rand::RngCore;
6use rand::rngs::OsRng;
7#[cfg(feature = "test-seed")]
8use rand::{SeedableRng, rngs::StdRng};
9use uuid::Uuid;
10
11use crate::model::core_config::Config;
12use crate::model::crypto::AESKey;
13
14/// Where an instance draws the ids and keys of the files and accounts it creates: the OS, or a
15/// config's seed with the `test-seed` feature, so a test that takes the same steps creates the same
16/// ids and keys. Seeded keys are guessable, so only test builds can seed one.
17#[derive(Clone, Default)]
18pub struct Entropy {
19    #[cfg(feature = "test-seed")]
20    seeded: Option<Arc<Mutex<StdRng>>>,
21}
22
23impl Entropy {
24    pub fn new(#[allow(unused_variables)] config: &Config) -> Self {
25        Self {
26            #[cfg(feature = "test-seed")]
27            seeded: config
28                .seed
29                .map(|seed| Arc::new(Mutex::new(StdRng::seed_from_u64(seed)))),
30        }
31    }
32
33    pub fn id(&self) -> Uuid {
34        let mut bytes = [0u8; 16];
35        self.fill(&mut bytes);
36        uuid::Builder::from_random_bytes(bytes).into_uuid()
37    }
38
39    pub fn key(&self) -> AESKey {
40        let mut key = [0u8; 32];
41        self.fill(&mut key);
42        key
43    }
44
45    pub fn secret_key(&self) -> SecretKey {
46        #[cfg(feature = "test-seed")]
47        if let Some(rng) = &self.seeded {
48            return SecretKey::random(&mut *rng.lock().unwrap());
49        }
50        SecretKey::random(&mut OsRng)
51    }
52
53    fn fill(&self, bytes: &mut [u8]) {
54        #[cfg(feature = "test-seed")]
55        if let Some(rng) = &self.seeded {
56            return rng.lock().unwrap().fill_bytes(bytes);
57        }
58        OsRng.fill_bytes(bytes)
59    }
60}