Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global context is randomized twice #759

Closed
DaniPopes opened this issue Nov 1, 2024 · 1 comment · Fixed by #760
Closed

Global context is randomized twice #759

DaniPopes opened this issue Nov 1, 2024 · 1 comment · Fixed by #760

Comments

@DaniPopes
Copy link
Contributor

In:

#[allow(unused_mut)] // Unused when `rand` + `std` is not enabled.
fn deref(&self) -> &Self::Target {
static ONCE: Once = Once::new();
static mut CONTEXT: Option<Secp256k1<All>> = None;
ONCE.call_once(|| unsafe {
let mut ctx = Secp256k1::new();
#[cfg(all(
not(target_arch = "wasm32"),
feature = "rand",
feature = "std",
not(feature = "global-context-less-secure")
))]
{
ctx.randomize(&mut rand::thread_rng());
}
CONTEXT = Some(ctx);
});
unsafe { CONTEXT.as_ref().unwrap() }
}
}

Secp256k1::new itself calls randomize with rand:

pub fn gen_new() -> Secp256k1<C> {
#[cfg(target_arch = "wasm32")]
ffi::types::sanity_checks_for_wasm();
let size = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
let layout = alloc::Layout::from_size_align(size, ALIGN_TO).unwrap();
let ptr = unsafe { alloc::alloc(layout) };
let ptr = NonNull::new(ptr as *mut c_void)
.unwrap_or_else(|| alloc::handle_alloc_error(layout));
#[allow(unused_mut)] // ctx is not mutated under some feature combinations.
let mut ctx = Secp256k1 {
ctx: unsafe { ffi::secp256k1_context_preallocated_create(ptr, C::FLAGS) },
phantom: PhantomData,
};
#[cfg(all(
not(target_arch = "wasm32"),
feature = "rand",
feature = "std",
not(feature = "global-context-less-secure")
))]
{
ctx.randomize(&mut rand::thread_rng());
}
#[allow(clippy::let_and_return)] // as for unusted_mut
ctx
}

Is this intended? If not, the call in deref should be dropped.

@apoelstra
Copy link
Member

Good catch. Yeah, let's drop the one in deref.

cc #388

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants