Skip to content

Commit

Permalink
Add NonceRng implementations for RefCell and Mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
LLFourn committed Dec 12, 2022
1 parent 53aad8a commit 250b6e8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- Replace `.mark` system with methods for changing each marker type.
- Make `From<u32>` for `Scalar` regardless of secrecy
- Merge `AddTag` and `Tagged` into one trait `Tag`
- Add `NonceRng` impls for `RefCell` and `Mutex`

## 0.7.1

Expand Down
32 changes: 25 additions & 7 deletions secp256kfun/src/nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,19 @@ use rand_core::RngCore;

/// A helper trait over RNGs that handle internal mutablility.
///
/// [`RngCore`] requires `self` to be mutable which is annoying in our context.
/// This trait requires the rng be able to create randomness without being
/// mutable. The most strightforward way of doing this is to use transient rngs
/// instances like [`ThreadRng`] that have a `Default` implementation. For this
/// reason, this trait is implemented for `PhantomData<ThreadRng>` (any Rng that
/// implements `Default`). If you want to BYO rng you have to implement this
/// trait yourself and handle mutability internally.
/// Used by the [`Synthetic`] nonce generator.
///
/// [`RngCore`] requires `self` to be mutable which is annoying in our context. This trait requires
/// the rng be able to create randomness without being mutable. The most strightforward way of doing
/// this is to use rngs instances like [`ThreadRng`] that have a `Default` implementation are and
/// seeded from the system. See [`GlobalRng`].
///
/// If you want to BYO rng you have to either implement this trait or wrap the `RngCore` in a
/// [`RefCell`] or [`Mutex`].
///
/// [`RngCore`]: rand_core::RngCore
/// [`RefCell`]: core::cell::RefCell
/// [`Mutex`]: std::sync::Mutex
/// [`ThreadRng`]: https://docs.rs/rand/latest/rand/rngs/struct.ThreadRng.html
pub trait NonceRng {
/// Fill `bytes` with random data.
Expand All @@ -46,6 +50,20 @@ impl<R: RngCore + Default> NonceRng for GlobalRng<R> {
}
}

impl<R: RngCore> NonceRng for core::cell::RefCell<R> {
fn fill_bytes(&self, bytes: &mut [u8]) {
self.borrow_mut().fill_bytes(bytes)
}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<R: RngCore> NonceRng for std::sync::Mutex<R> {
fn fill_bytes(&self, bytes: &mut [u8]) {
self.lock().unwrap().fill_bytes(bytes)
}
}

/// A nonce generator that uses an RNG to mix in real randomness into the nonce
/// generation.
///
Expand Down

0 comments on commit 250b6e8

Please sign in to comment.