Skip to content

Commit 670a48b

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

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/key.rs

+26-5
Original file line numberDiff line numberDiff line change
@@ -1057,9 +1057,13 @@ 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+
1066+
#[allow(clippy::needless_borrow)]
10631067
KeyPair::from_seckey_str(&ctx, s)
10641068
}
10651069
}
@@ -1093,8 +1097,14 @@ impl<'de> serde::Deserialize<'de> for KeyPair {
10931097
} else {
10941098
let visitor = super::serde_util::Tuple32Visitor::new(
10951099
"raw 32 bytes KeyPair",
1096-
|data| unsafe {
1097-
let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context);
1100+
|data| {
1101+
#[cfg(feature = "global-context")]
1102+
let ctx = SECP256K1;
1103+
1104+
#[cfg(not(feature = "global-context"))]
1105+
let ctx = Secp256k1::signing_only();
1106+
1107+
#[allow(clippy::needless_borrow)]
10981108
KeyPair::from_seckey_slice(&ctx, data)
10991109
}
11001110
);
@@ -1630,6 +1640,7 @@ pub mod serde_keypair {
16301640
#[cfg(test)]
16311641
#[allow(unused_imports)]
16321642
mod test {
1643+
use bitcoin_hashes::hex::ToHex;
16331644
use super::*;
16341645

16351646
use core::str::FromStr;
@@ -2431,6 +2442,16 @@ mod test {
24312442
assert_tokens(&pk.readable(), &[Token::Str(PK_STR)]);
24322443
assert_tokens(&pk.readable(), &[Token::String(PK_STR)]);
24332444
}
2445+
2446+
#[test]
2447+
#[cfg(feature = "global-context")]
2448+
fn test_keypair_from_str() {
2449+
let ctx = crate::Secp256k1::new();
2450+
let keypair = KeyPair::new(&ctx, &mut thread_rng());
2451+
let msg = keypair.secret_key().secret_bytes().to_hex();
2452+
let parsed_key: KeyPair = msg.parse().unwrap();
2453+
assert_eq!(parsed_key, keypair);
2454+
}
24342455
}
24352456

24362457
#[cfg(bench)]

0 commit comments

Comments
 (0)