From de77518d3a306b3755902e99a13eaaf38e738235 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Mon, 27 Sep 2021 13:28:53 +0200 Subject: [PATCH] Serde serialization for KeyPair --- src/key.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/key.rs b/src/key.rs index b5c5f3c..d00393e 100644 --- a/src/key.rs +++ b/src/key.rs @@ -674,6 +674,49 @@ impl<'a> From<&'a KeyPair> for PublicKey { } } +impl str::FromStr for KeyPair { + type Err = Error; + + fn from_str(s: &str) -> Result { + let ctx = unsafe { + Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context) + }; + KeyPair::from_seckey_str(&ctx, s) + } +} + +#[cfg(feature = "serde")] +impl ::serde::Serialize for KeyPair { + fn serialize(&self, s: S) -> Result { + if s.is_human_readable() { + let mut buf = [0u8; 64]; + s.serialize_str(::to_hex(&self.serialize_secret(), &mut buf) + .expect("fixed-size hex serialization")) + } else { + s.serialize_bytes(&self.0[..]) + } + } +} + +#[cfg(feature = "serde")] +impl<'de> ::serde::Deserialize<'de> for KeyPair { + fn deserialize>(d: D) -> Result { + if d.is_human_readable() { + d.deserialize_str(super::serde_util::FromStrVisitor::new( + "a hex string representing 32 byte KeyPair" + )) + } else { + d.deserialize_bytes(super::serde_util::BytesVisitor::new( + "raw 32 bytes KeyPair", + |data| unsafe { + let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context); + KeyPair::from_seckey_slice(&ctx, data) + } + )) + } + } +} + /// A x-only public key, used for verification of Schnorr signatures and serialized according to BIP-340. #[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)] pub struct XOnlyPublicKey(ffi::XOnlyPublicKey);