Skip to content

Commit 4f0f542

Browse files
committed
Merge #392: Add global context API
eb453b8 Add global context API (Tobin Harding) 3ecb5e4 Refactor from_secret_key definition (Tobin Harding) e2d47a2 Remove unnecessary import statement (Tobin Harding) d79989b Remove erroneous duplicate feature (Tobin Harding) Pull request description: Our API often involves a `Secp256k1` parameter, when users enable the `global-context` feature they must then pass `SECP256K1` into these functions. This is kind of clunky since the global is by definition available everywhere. Make the API more ergonomic for `global-context` builds by adding various API functions/methods that use the global context implicitly. The first 3 patches are clean up. Resolves: #330 ACKs for top commit: apoelstra: ACK eb453b8 Tree-SHA512: 21d89a6688c24a7920d48ea92d923889bec2bbe9dc5ed5e33639405be45a50f50022a28dc1f235b8bea850ac39013c7dd24b5aed086ed40f5b259dd44c06433d
2 parents ecb6261 + eb453b8 commit 4f0f542

File tree

5 files changed

+106
-6
lines changed

5 files changed

+106
-6
lines changed

src/ecdsa/mod.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ mod recovery;
1212
#[cfg_attr(docsrs, doc(cfg(feature = "recovery")))]
1313
pub use self::recovery::{RecoveryId, RecoverableSignature};
1414

15+
#[cfg(feature = "global-context")]
16+
use SECP256K1;
17+
1518
/// An ECDSA signature
1619
#[derive(Copy, Clone, PartialEq, Eq)]
1720
pub struct Signature(pub(crate) ffi::Signature);
@@ -269,6 +272,14 @@ impl Signature {
269272
}
270273
ret
271274
}
275+
276+
/// Verifies an ECDSA signature for `msg` using `pk` and the global [`SECP256K1`] context.
277+
#[inline]
278+
#[cfg(feature = "global-context")]
279+
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
280+
pub fn verify(&self, msg: &Message, pk: &PublicKey) -> Result<(), Error> {
281+
SECP256K1.verify_ecdsa(msg, self, pk)
282+
}
272283
}
273284

274285
impl CPtr for Signature {

src/ecdsa/recovery.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,15 @@ impl RecoverableSignature {
121121
Signature(ret)
122122
}
123123
}
124+
125+
/// Determines the public key for which this [`Signature`] is valid for `msg`. Requires a
126+
/// verify-capable context.
127+
#[inline]
128+
#[cfg(feature = "global-context")]
129+
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
130+
pub fn recover(&self, msg: &Message) -> Result<key::PublicKey, Error> {
131+
SECP256K1.recover_ecdsa(msg, self)
132+
}
124133
}
125134

126135

src/key.rs

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ use Verification;
2828
use constants;
2929
use ffi::{self, CPtr};
3030

31+
#[cfg(feature = "global-context")]
32+
use {Message, ecdsa, SECP256K1};
33+
#[cfg(all(feature = "global-context", feature = "rand-std"))]
34+
use schnorr;
35+
3136
/// Secret 256-bit key used as `x` in an ECDSA signature.
3237
///
3338
/// # Examples
@@ -279,6 +284,14 @@ impl SecretKey {
279284
}
280285
}
281286
}
287+
288+
/// Constructs an ECDSA signature for `msg` using the global [`SECP256K1`] context.
289+
#[inline]
290+
#[cfg(feature = "global-context")]
291+
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
292+
pub fn sign_ecdsa(&self, msg: Message) -> ecdsa::Signature {
293+
SECP256K1.sign_ecdsa(&msg, self)
294+
}
282295
}
283296

284297
#[cfg(feature = "serde")]
@@ -338,9 +351,7 @@ impl PublicKey {
338351
/// # }
339352
/// ```
340353
#[inline]
341-
pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>,
342-
sk: &SecretKey)
343-
-> PublicKey {
354+
pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>,sk: &SecretKey) -> PublicKey {
344355
unsafe {
345356
let mut pk = ffi::PublicKey::new();
346357
// We can assume the return value because it's not possible to construct
@@ -351,6 +362,14 @@ impl PublicKey {
351362
}
352363
}
353364

365+
/// Creates a new public key from a [`SecretKey`] and the global [`SECP256K1`] context.
366+
#[inline]
367+
#[cfg(feature = "global-context")]
368+
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
369+
pub fn from_secret_key_global(sk: &SecretKey) -> PublicKey {
370+
PublicKey::from_secret_key(&SECP256K1, sk)
371+
}
372+
354373
/// Creates a public key directly from a slice.
355374
#[inline]
356375
pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
@@ -740,6 +759,18 @@ impl KeyPair {
740759
}
741760
}
742761

762+
/// Creates a Schnorr [`KeyPair`] directly from a secret key string and the global [`SECP256K1`] context.
763+
///
764+
/// # Errors
765+
///
766+
/// [`Error::InvalidSecretKey`] if corresponding public key for the provided secret key is not even.
767+
#[inline]
768+
#[cfg(feature = "global-context")]
769+
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
770+
pub fn from_seckey_str_global(s: &str) -> Result<KeyPair, Error> {
771+
KeyPair::from_seckey_str(SECP256K1, s)
772+
}
773+
743774
/// Generates a new random secret key.
744775
/// # Examples
745776
///
@@ -770,6 +801,14 @@ impl KeyPair {
770801
}
771802
}
772803

804+
/// Generates a new random secret key using the global [`SECP256K1`] context.
805+
#[inline]
806+
#[cfg(all(feature = "global-context", feature = "rand"))]
807+
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "rand"))))]
808+
pub fn new_global<R: ::rand::Rng + ?Sized>(rng: &mut R) -> KeyPair {
809+
KeyPair::new(SECP256K1, rng)
810+
}
811+
773812
/// Serializes the key pair as a secret key byte value.
774813
#[inline]
775814
pub fn serialize_secret(&self) -> [u8; constants::SECRET_KEY_SIZE] {
@@ -832,6 +871,14 @@ impl KeyPair {
832871
pub fn public_key(&self) -> XOnlyPublicKey {
833872
XOnlyPublicKey::from_keypair(self)
834873
}
874+
875+
/// Constructs an schnorr signature for `msg` using the global [`SECP256K1`] context.
876+
#[inline]
877+
#[cfg(all(feature = "global-context", feature = "rand-std"))]
878+
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "rand-std"))))]
879+
pub fn sign_schnorr(&self, msg: Message) -> schnorr::Signature {
880+
SECP256K1.sign_schnorr(&msg, self)
881+
}
835882
}
836883

837884
impl From<KeyPair> for SecretKey {

src/lib.rs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,22 @@
5757
//! # }
5858
//! ```
5959
//!
60+
//! If the "global-context" feature is enabled you have access to an alternate API.
61+
//!
62+
//! ```rust
63+
//! # #[cfg(all(feature="global-context", feature = "std", feature="rand-std", features = "bitcoin_hashes"))] {
64+
//! use secp256k1::rand::thread_rng;
65+
//! use secp256k1::{generate_keypair, Message};
66+
//! use secp256k1::hashes::sha256;
67+
//!
68+
//! let (secret_key, public_key) = generate_keypair(&mut thread_rng());
69+
//! let message = Message::from_hashed_data::<sha256::Hash>("Hello World!".as_bytes());
70+
//!
71+
//! let sig = secret_key.sign_ecdsa(&message, &secret_key);
72+
//! assert!(sig.verify(&message, &public_key).is_ok());
73+
//! # }
74+
//! ```
75+
//!
6076
//! The above code requires `rust-secp256k1` to be compiled with the `rand-std` and `bitcoin_hashes`
6177
//! feature enabled, to get access to [`generate_keypair`](struct.Secp256k1.html#method.generate_keypair)
6278
//! Alternately, keys and messages can be parsed from slices, like
@@ -198,7 +214,7 @@ use core::{mem, fmt, str};
198214
use ffi::{CPtr, types::AlignedType};
199215

200216
#[cfg(feature = "global-context")]
201-
#[cfg_attr(docsrs, doc(cfg(any(feature = "global-context", feature = "global-context"))))]
217+
#[cfg_attr(docsrs, doc(cfg(feature = "global-context")))]
202218
pub use context::global::SECP256K1;
203219

204220
#[cfg(feature = "bitcoin_hashes")]
@@ -458,6 +474,14 @@ impl<C: Signing> Secp256k1<C> {
458474
}
459475
}
460476

477+
/// Generates a random keypair using the global [`SECP256K1`] context.
478+
#[inline]
479+
#[cfg(all(feature = "global-context", feature = "rand"))]
480+
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "rand"))))]
481+
pub fn generate_keypair<R: Rng + ?Sized>(rng: &mut R) -> (key::SecretKey, key::PublicKey) {
482+
SECP256K1.generate_keypair(rng)
483+
}
484+
461485
/// Utility function used to parse hex into a target u8 buffer. Returns
462486
/// the number of bytes converted or an error if it encounters an invalid
463487
/// character or unexpected end of string.
@@ -960,8 +984,6 @@ mod tests {
960984
#[cfg(feature = "global-context")]
961985
#[test]
962986
fn test_global_context() {
963-
use super::SECP256K1;
964-
965987
let sk_data = hex!("e6dd32f8761625f105c39a39f19370b3521d845a12456d60ce44debd0a362641");
966988
let sk = SecretKey::from_slice(&sk_data).unwrap();
967989
let msg_data = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d");

src/schnorr.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ use ffi::{self, CPtr};
1313
use {constants, Secp256k1};
1414
use {Message, Signing, Verification, KeyPair, XOnlyPublicKey};
1515

16+
#[cfg(all(feature = "global-context", feature = "rand-std"))]
17+
use SECP256K1;
18+
1619
/// Represents a Schnorr signature.
1720
pub struct Signature([u8; constants::SCHNORRSIG_SIGNATURE_SIZE]);
1821
impl_array_newtype!(Signature, u8, constants::SCHNORRSIG_SIGNATURE_SIZE);
@@ -88,6 +91,14 @@ impl Signature {
8891
_ => Err(Error::InvalidSignature),
8992
}
9093
}
94+
95+
/// Verifies a schnorr signature for `msg` using `pk` and the global [`SECP256K1`] context.
96+
#[inline]
97+
#[cfg(all(feature = "global-context", feature = "rand-std"))]
98+
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "rand-std"))))]
99+
pub fn verify(&self, msg: &Message, pk: &XOnlyPublicKey) -> Result<(), Error> {
100+
SECP256K1.verify_schnorr(self, msg, pk)
101+
}
91102
}
92103

93104
impl<C: Signing> Secp256k1<C> {

0 commit comments

Comments
 (0)