Skip to content

Commit

Permalink
Add a global-context-less-secure feature which skips randomization
Browse files Browse the repository at this point in the history
This is useful for us downstream as we wish to target WASM with a
global context, and using rand in such a build doesn't seem like a
safe idea.
  • Loading branch information
TheBlueMatt committed Jun 8, 2021
1 parent cf8921a commit ce930ab
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ std = ["secp256k1-sys/std"]
rand-std = ["rand/std"]
recovery = ["secp256k1-sys/recovery"]
lowmemory = ["secp256k1-sys/lowmemory"]
global-context = ["std", "rand-std"]
global-context = ["std", "rand-std", "global-context-less-secure"]
global-context-less-secure = []

[dependencies]
secp256k1-sys = { version = "0.4.0", default-features = false, path = "./secp256k1-sys" }
Expand Down
12 changes: 10 additions & 2 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ use Secp256k1;
#[cfg(feature = "std")]
pub use self::std_only::*;

#[cfg(feature = "global-context")]
#[cfg(feature = "global-context-less-secure")]
/// Module implementing a singleton pattern for a global `Secp256k1` context
pub mod global {
#[cfg(feature = "global-context")]
use rand;

use std::ops::Deref;
use std::sync::Once;
use {Secp256k1, All};
Expand All @@ -22,6 +24,9 @@ pub mod global {
}

/// A global, static context to avoid repeatedly creating contexts where one can't be passed
///
/// If the global-context feature is enabled (and not just the global-context-less-secure),
/// this will have been randomized.
pub static SECP256K1: &GlobalContext = &GlobalContext { __private: () };

impl Deref for GlobalContext {
Expand All @@ -32,7 +37,10 @@ pub mod global {
static mut CONTEXT: Option<Secp256k1<All>> = None;
ONCE.call_once(|| unsafe {
let mut ctx = Secp256k1::new();
ctx.randomize(&mut rand::thread_rng());
#[cfg(feature = "global-context")]
{
ctx.randomize(&mut rand::thread_rng());
}
CONTEXT = Some(ctx);
});
unsafe { CONTEXT.as_ref().unwrap() }
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ use core::ops::Deref;
use core::mem;
use ffi::{CPtr, types::AlignedType};

#[cfg(feature = "global-context")]
#[cfg(feature = "global-context-less-secure")]
pub use context::global::SECP256K1;

#[cfg(feature = "bitcoin_hashes")]
Expand Down Expand Up @@ -1269,7 +1269,7 @@ mod tests {

}

#[cfg(feature = "global-context")]
#[cfg(feature = "global-context-less-secure")]
#[test]
fn test_global_context() {
use super::SECP256K1;
Expand Down

0 comments on commit ce930ab

Please sign in to comment.