@@ -674,6 +674,49 @@ impl<'a> From<&'a KeyPair> for PublicKey {
674674 }
675675}
676676
677+ impl str:: FromStr for KeyPair {
678+ type Err = Error ;
679+
680+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
681+ let ctx = unsafe {
682+ Secp256k1 :: from_raw_all ( ffi:: secp256k1_context_no_precomp as * mut ffi:: Context )
683+ } ;
684+ KeyPair :: from_seckey_str ( & ctx, s)
685+ }
686+ }
687+
688+ #[ cfg( feature = "serde" ) ]
689+ impl :: serde:: Serialize for KeyPair {
690+ fn serialize < S : :: serde:: Serializer > ( & self , s : S ) -> Result < S :: Ok , S :: Error > {
691+ if s. is_human_readable ( ) {
692+ let mut buf = [ 0u8 ; 64 ] ;
693+ s. serialize_str ( :: to_hex ( & self . serialize_secret ( ) , & mut buf)
694+ . expect ( "fixed-size hex serialization" ) )
695+ } else {
696+ s. serialize_bytes ( & self . 0 [ ..] )
697+ }
698+ }
699+ }
700+
701+ #[ cfg( feature = "serde" ) ]
702+ impl < ' de > :: serde:: Deserialize < ' de > for KeyPair {
703+ fn deserialize < D : :: serde:: Deserializer < ' de > > ( d : D ) -> Result < Self , D :: Error > {
704+ if d. is_human_readable ( ) {
705+ d. deserialize_str ( super :: serde_util:: FromStrVisitor :: new (
706+ "a hex string representing 32 byte KeyPair"
707+ ) )
708+ } else {
709+ d. deserialize_bytes ( super :: serde_util:: BytesVisitor :: new (
710+ "raw 32 bytes KeyPair" ,
711+ |data| unsafe {
712+ let ctx = Secp256k1 :: from_raw_all ( ffi:: secp256k1_context_no_precomp as * mut ffi:: Context ) ;
713+ KeyPair :: from_seckey_slice ( & ctx, data)
714+ }
715+ ) )
716+ }
717+ }
718+ }
719+
677720/// A x-only public key, used for verification of Schnorr signatures and serialized according to BIP-340.
678721#[ derive( Copy , Clone , PartialEq , Eq , Debug , PartialOrd , Ord , Hash ) ]
679722pub struct XOnlyPublicKey ( ffi:: XOnlyPublicKey ) ;
0 commit comments