Skip to content

Commit

Permalink
Fix broken serde::Deserialize and FromStr impl of keyPair
Browse files Browse the repository at this point in the history
  • Loading branch information
elsirion committed Oct 22, 2022
1 parent 5e1e012 commit 9d5e477
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions src/key.rs
Expand Up @@ -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<Self, Self::Err> {
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)
}
}
Expand All @@ -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: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Expand All @@ -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)
}
);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)]
Expand Down

0 comments on commit 9d5e477

Please sign in to comment.