Skip to content

Commit a2b461e

Browse files
committed
Add an optional global, static context
1 parent a5147bb commit a2b461e

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ rand-std = ["rand/std"]
2929
recovery = ["secp256k1-sys/recovery"]
3030
endomorphism = ["secp256k1-sys/endomorphism"]
3131
lowmemory = ["secp256k1-sys/lowmemory"]
32+
global-context = ["lazy_static"]
3233

3334
# Use this feature to not compile the bundled libsecp256k1 C symbols,
3435
# but use external ones. Use this only if you know what you are doing!
@@ -38,6 +39,7 @@ external-symbols = ["secp256k1-sys/external-symbols"]
3839
fuzztarget = ["secp256k1-sys/fuzztarget"]
3940

4041
[dependencies]
42+
lazy_static = { version = "1.4.0", optional = true }
4143
secp256k1-sys = { version = "0.1.1", default-features = false, path = "./secp256k1-sys" }
4244

4345
[dev-dependencies]

src/lib.rs

+17
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ pub use secp256k1_sys as ffi;
160160
#[cfg(all(test, feature = "serde"))] extern crate serde_test;
161161
#[cfg(any(test, feature = "rand"))] use rand::Rng;
162162
#[cfg(any(test, feature = "std"))] extern crate core;
163+
#[cfg(feature = "global-context")] #[macro_use] extern crate lazy_static;
163164

164165
use core::{fmt, ptr, str};
165166

@@ -179,6 +180,12 @@ use core::marker::PhantomData;
179180
use core::ops::Deref;
180181
use ffi::CPtr;
181182

183+
#[cfg(feature = "global-context")]
184+
lazy_static! {
185+
/// A global, static context to avoid repeatedly creating contexts where one can't be passed
186+
pub static ref SECP256K1: Secp256k1<All> = Secp256k1::new();
187+
}
188+
182189
#[cfg(feature = "bitcoin_hashes")]
183190
use bitcoin_hashes::Hash;
184191

@@ -1138,6 +1145,16 @@ mod tests {
11381145
assert_tokens(&sig.readable(), &[Token::BorrowedStr(SIG_STR)]);
11391146
}
11401147

1148+
#[cfg(feature = "global-context")]
1149+
#[test]
1150+
fn test_global_context() {
1151+
use super::SECP256K1;
1152+
1153+
let (sk, pk) = SECP256K1.generate_keypair(&mut thread_rng());
1154+
let pk_from_sk = PublicKey::from_secret_key(&SECP256K1, &sk);
1155+
assert_eq!(pk, pk_from_sk);
1156+
}
1157+
11411158
// For WASM, just run through our general tests in this file all at once.
11421159
#[cfg(target_arch = "wasm32")]
11431160
extern crate wasm_bindgen_test;

0 commit comments

Comments
 (0)