@@ -1053,13 +1053,18 @@ impl<'a> From<&'a KeyPair> for PublicKey {
1053
1053
}
1054
1054
}
1055
1055
1056
+ #[ cfg( feature = "alloc" ) ]
1056
1057
impl str:: FromStr for KeyPair {
1057
1058
type Err = Error ;
1058
1059
1059
1060
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
- } ;
1061
+ #[ cfg( feature = "global-context" ) ]
1062
+ let ctx = SECP256K1 ;
1063
+
1064
+ #[ cfg( all( not( feature = "global-context" ) , feature = "alloc" ) ) ]
1065
+ let ctx = Secp256k1 :: signing_only ( ) ;
1066
+
1067
+ #[ allow( clippy:: needless_borrow) ]
1063
1068
KeyPair :: from_seckey_str ( & ctx, s)
1064
1069
}
1065
1070
}
@@ -1082,7 +1087,7 @@ impl serde::Serialize for KeyPair {
1082
1087
}
1083
1088
}
1084
1089
1085
- #[ cfg( feature = "serde" ) ]
1090
+ #[ cfg( all ( feature = "serde" , feature = "alloc" ) ) ]
1086
1091
#[ cfg_attr( docsrs, doc( cfg( feature = "serde" ) ) ) ]
1087
1092
impl < ' de > serde:: Deserialize < ' de > for KeyPair {
1088
1093
fn deserialize < D : serde:: Deserializer < ' de > > ( d : D ) -> Result < Self , D :: Error > {
@@ -1093,8 +1098,14 @@ impl<'de> serde::Deserialize<'de> for KeyPair {
1093
1098
} else {
1094
1099
let visitor = super :: serde_util:: Tuple32Visitor :: new (
1095
1100
"raw 32 bytes KeyPair" ,
1096
- |data| unsafe {
1097
- let ctx = Secp256k1 :: from_raw_all ( ffi:: secp256k1_context_no_precomp as * mut ffi:: Context ) ;
1101
+ |data| {
1102
+ #[ cfg( feature = "global-context" ) ]
1103
+ let ctx = SECP256K1 ;
1104
+
1105
+ #[ cfg( all( not( feature = "global-context" ) , feature = "alloc" ) ) ]
1106
+ let ctx = Secp256k1 :: signing_only ( ) ;
1107
+
1108
+ #[ allow( clippy:: needless_borrow) ]
1098
1109
KeyPair :: from_seckey_slice ( & ctx, data)
1099
1110
}
1100
1111
) ;
@@ -1630,6 +1641,7 @@ pub mod serde_keypair {
1630
1641
#[ cfg( test) ]
1631
1642
#[ allow( unused_imports) ]
1632
1643
mod test {
1644
+ use bitcoin_hashes:: hex:: ToHex ;
1633
1645
use super :: * ;
1634
1646
1635
1647
use core:: str:: FromStr ;
@@ -2431,6 +2443,16 @@ mod test {
2431
2443
assert_tokens ( & pk. readable ( ) , & [ Token :: Str ( PK_STR ) ] ) ;
2432
2444
assert_tokens ( & pk. readable ( ) , & [ Token :: String ( PK_STR ) ] ) ;
2433
2445
}
2446
+
2447
+ #[ test]
2448
+ #[ cfg( feature = "global-context" ) ]
2449
+ fn test_keypair_from_str ( ) {
2450
+ let ctx = crate :: Secp256k1 :: new ( ) ;
2451
+ let keypair = KeyPair :: new ( & ctx, & mut thread_rng ( ) ) ;
2452
+ let msg = keypair. secret_key ( ) . secret_bytes ( ) . to_hex ( ) ;
2453
+ let parsed_key: KeyPair = msg. parse ( ) . unwrap ( ) ;
2454
+ assert_eq ! ( parsed_key, keypair) ;
2455
+ }
2434
2456
}
2435
2457
2436
2458
#[ cfg( bench) ]
0 commit comments