Skip to main content

lexe_common/
rng.rs

1//! Lexe [`Crng`] compatibility hacks to support LDK's [`EntropySource`].
2//!
3//! [`Crng`]: lexe_crypto::rng::Crng
4//! [`EntropySource`]: lightning::sign::EntropySource
5//
6// These types live in `lexe-common` to avoid including any `lightning`
7// dependencies in our low-level, foundational crates, as `lightning` takes a
8// long time to compile.
9
10#[cfg(any(test, feature = "test-utils"))]
11use lexe_crypto::rng::FastRng;
12use lexe_crypto::rng::{RngExt, SysRng};
13use lightning::sign::EntropySource;
14
15/// Dumb hack so we can pass `SysRng` as an LDK [`EntropySource`] without
16/// wrapping in an Arc/Box.
17#[repr(transparent)]
18pub struct SysRngDerefHack(InnerSysrng);
19
20impl SysRngDerefHack {
21    pub fn new() -> Self {
22        Self(InnerSysrng)
23    }
24}
25
26impl std::ops::Deref for SysRngDerefHack {
27    type Target = InnerSysrng;
28    fn deref(&self) -> &Self::Target {
29        &self.0
30    }
31}
32
33#[doc(hidden)] // needs to be `pub` for `Deref<Target = InnerSysrng>`
34pub struct InnerSysrng;
35
36impl EntropySource for InnerSysrng {
37    fn get_secure_random_bytes(&self) -> [u8; 32] {
38        SysRng::new().gen_bytes()
39    }
40}
41
42/// Dumb hack so we can use a `FastRng` as an [`EntropySource`].
43///
44/// Note that because LDK requires `&self` for [`EntropySource`], this will
45/// return the same randomness for every `get_secure_random_bytes` call after
46/// creation.
47#[cfg(any(test, feature = "test-utils"))]
48#[repr(transparent)]
49pub struct FastRngDerefHack(InnerFastRng);
50
51#[cfg(any(test, feature = "test-utils"))]
52impl FastRngDerefHack {
53    pub fn from_u64(seed: u64) -> Self {
54        Self(InnerFastRng(FastRng::from_u64(seed)))
55    }
56
57    pub fn from_rng(rng: &mut FastRng) -> Self {
58        let rng = FastRng::from_u64(rng.gen_u64());
59        Self(InnerFastRng(rng))
60    }
61}
62
63#[cfg(any(test, feature = "test-utils"))]
64impl std::ops::Deref for FastRngDerefHack {
65    type Target = InnerFastRng;
66    fn deref(&self) -> &Self::Target {
67        &self.0
68    }
69}
70
71#[cfg(any(test, feature = "test-utils"))]
72#[doc(hidden)] // needs to be `pub` for `Deref<Target = InnerFastRng>`
73pub struct InnerFastRng(FastRng);
74
75#[cfg(any(test, feature = "test-utils"))]
76impl EntropySource for InnerFastRng {
77    fn get_secure_random_bytes(&self) -> [u8; 32] {
78        self.0.clone().gen_bytes()
79    }
80}