diff --git a/src/key.rs b/src/key.rs index 91ad39143..4d2c6a426 100644 --- a/src/key.rs +++ b/src/key.rs @@ -1053,13 +1053,18 @@ impl<'a> From<&'a KeyPair> for PublicKey { } } +#[cfg(feature = "alloc")] impl str::FromStr for KeyPair { type Err = Error; fn from_str(s: &str) -> Result { - let ctx = unsafe { - Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context) - }; + #[cfg(feature = "global-context")] + let ctx = SECP256K1; + + #[cfg(all(not(feature = "global-context"), feature = "alloc"))] + let ctx = Secp256k1::signing_only(); + + #[allow(clippy::needless_borrow)] KeyPair::from_seckey_str(&ctx, s) } } @@ -1082,7 +1087,7 @@ impl serde::Serialize for KeyPair { } } -#[cfg(feature = "serde")] +#[cfg(all(feature = "serde", feature = "alloc"))] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] impl<'de> serde::Deserialize<'de> for KeyPair { fn deserialize>(d: D) -> Result { @@ -1093,8 +1098,14 @@ impl<'de> serde::Deserialize<'de> for KeyPair { } else { let visitor = super::serde_util::Tuple32Visitor::new( "raw 32 bytes KeyPair", - |data| unsafe { - let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context); + |data| { + #[cfg(feature = "global-context")] + let ctx = SECP256K1; + + #[cfg(all(not(feature = "global-context"), feature = "alloc"))] + let ctx = Secp256k1::signing_only(); + + #[allow(clippy::needless_borrow)] KeyPair::from_seckey_slice(&ctx, data) } ); @@ -1630,6 +1641,7 @@ pub mod serde_keypair { #[cfg(test)] #[allow(unused_imports)] mod test { + use bitcoin_hashes::hex::ToHex; use super::*; use core::str::FromStr; @@ -2431,6 +2443,16 @@ mod test { assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]); assert_tokens(&pk.readable(), &[Token::String(PK_STR)]); } + + #[test] + #[cfg(feature = "global-context")] + fn test_keypair_from_str() { + let ctx = crate::Secp256k1::new(); + let keypair = KeyPair::new(&ctx, &mut thread_rng()); + let msg = keypair.secret_key().secret_bytes().to_hex(); + let parsed_key: KeyPair = msg.parse().unwrap(); + assert_eq!(parsed_key, keypair); + } } #[cfg(bench)]