Skip to content

Commit f8d7f4a

Browse files
committed
Randomize signing contexts
Randomize signing contexts on creation if `rand-std` feature is enabled.
1 parent 5c2b80e commit f8d7f4a

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

src/context.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,9 @@ mod alloc_only {
115115
#[cfg(not(feature = "std"))]
116116
use alloc::alloc;
117117

118+
#[cfg(feature = "rand-std")]
119+
use rand;
120+
118121
impl private::Sealed for SignOnly {}
119122
impl private::Sealed for All {}
120123
impl private::Sealed for VerifyOnly {}
@@ -174,38 +177,54 @@ mod alloc_only {
174177
}
175178

176179
impl<C: Context> Secp256k1<C> {
177-
/// Lets you create a context in a generic manner(sign/verify/all)
180+
/// Lets you create a context in a generic manner (sign/verify/all).
181+
///
182+
/// If `rand-std` feature is enabled, context will have been randomized using `thread_rng`.
183+
#[allow(unused_mut)] // Unused when `rand-std` is not enabled.
178184
pub fn gen_new() -> Secp256k1<C> {
179185
#[cfg(target_arch = "wasm32")]
180186
ffi::types::sanity_checks_for_wasm();
181187

182188
let size = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
183189
let layout = alloc::Layout::from_size_align(size, ALIGN_TO).unwrap();
184190
let ptr = unsafe {alloc::alloc(layout)};
185-
Secp256k1 {
191+
let mut ctx = Secp256k1 {
186192
ctx: unsafe { ffi::secp256k1_context_preallocated_create(ptr as *mut c_void, C::FLAGS) },
187193
phantom: PhantomData,
188194
size,
195+
};
196+
197+
#[cfg(feature = "rand-std")]
198+
{
199+
ctx.randomize(&mut rand::thread_rng());
189200
}
201+
202+
ctx
190203
}
191204
}
192205

193206
impl Secp256k1<All> {
194-
/// Creates a new Secp256k1 context with all capabilities
207+
/// Creates a new Secp256k1 context with all capabilities.
208+
///
209+
/// If `rand-std` feature is enabled, context will have been randomized using `thread_rng`.
195210
pub fn new() -> Secp256k1<All> {
196211
Secp256k1::gen_new()
197212
}
198213
}
199214

200215
impl Secp256k1<SignOnly> {
201-
/// Creates a new Secp256k1 context that can only be used for signing
216+
/// Creates a new Secp256k1 context that can only be used for signing.
217+
///
218+
/// If `rand-std` feature is enabled, context will have been randomized using `thread_rng`.
202219
pub fn signing_only() -> Secp256k1<SignOnly> {
203220
Secp256k1::gen_new()
204221
}
205222
}
206223

207224
impl Secp256k1<VerifyOnly> {
208-
/// Creates a new Secp256k1 context that can only be used for verification
225+
/// Creates a new Secp256k1 context that can only be used for verification.
226+
///
227+
/// If `rand-std` feature is enabled, context will have been randomized using `thread_rng`.
209228
pub fn verification_only() -> Secp256k1<VerifyOnly> {
210229
Secp256k1::gen_new()
211230
}

0 commit comments

Comments
 (0)