Skip to content

Commit f6bfdf9

Browse files
committed
Fix broken serde::Deserialize and FromStr impl of keyPair
Fixes #491
1 parent 5e1e012 commit f6bfdf9

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/key.rs

+23-5
Original file line numberDiff line numberDiff line change
@@ -1057,9 +1057,12 @@ impl str::FromStr for KeyPair {
10571057
type Err = Error;
10581058

10591059
fn from_str(s: &str) -> Result<Self, Self::Err> {
1060-
let ctx = unsafe {
1061-
Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context)
1062-
};
1060+
#[cfg(feature = "global-context")]
1061+
let ctx = SECP256K1;
1062+
1063+
#[cfg(not(feature = "global-context"))]
1064+
let ctx = Secp256k1::signing_only();
1065+
10631066
KeyPair::from_seckey_str(&ctx, s)
10641067
}
10651068
}
@@ -1093,8 +1096,12 @@ impl<'de> serde::Deserialize<'de> for KeyPair {
10931096
} else {
10941097
let visitor = super::serde_util::Tuple32Visitor::new(
10951098
"raw 32 bytes KeyPair",
1096-
|data| unsafe {
1097-
let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context);
1099+
|data| {
1100+
#[cfg(feature = "global-context")]
1101+
let ctx = SECP256K1;
1102+
1103+
#[cfg(not(feature = "global-context"))]
1104+
let ctx = Secp256k1::signing_only();
10981105
KeyPair::from_seckey_slice(&ctx, data)
10991106
}
11001107
);
@@ -1630,6 +1637,7 @@ pub mod serde_keypair {
16301637
#[cfg(test)]
16311638
#[allow(unused_imports)]
16321639
mod test {
1640+
use bitcoin_hashes::hex::ToHex;
16331641
use super::*;
16341642

16351643
use core::str::FromStr;
@@ -2431,6 +2439,16 @@ mod test {
24312439
assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
24322440
assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
24332441
}
2442+
2443+
#[test]
2444+
#[cfg(feature = "global-context")]
2445+
fn test_keypair_from_str() {
2446+
let ctx = crate::Secp256k1::new();
2447+
let keypair = KeyPair::new(&ctx, &mut thread_rng());
2448+
let msg = keypair.secret_key().secret_bytes().to_hex();
2449+
let parsed_key: KeyPair = msg.parse().unwrap();
2450+
assert_eq!(parsed_key, keypair);
2451+
}
24342452
}
24352453

24362454
#[cfg(bench)]

0 commit comments

Comments
 (0)