Skip to content

Commit ada3f98

Browse files
committed
Merge #313: Serde implementation for KeyPair type
de77518 Serde serialization for KeyPair (Dr Maxim Orlovsky) Pull request description: Serde implementation for `KeyPair` type (which hadn't it before). Based on #312 (includes all commits from that PR, will be rebased upon merge) ACKs for top commit: apoelstra: ACK de77518 Tree-SHA512: 1e75c4fc772dcba5ce7edb30235a58550342cf986c6a77b4affd81defeba456c9655e28b081e0040c1f8440da3f7ad2224485d35222c1921099567b4d1533794
2 parents 48683d8 + de77518 commit ada3f98

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/key.rs

+43
Original file line numberDiff line numberDiff line change
@@ -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)]
679722
pub struct XOnlyPublicKey(ffi::XOnlyPublicKey);

0 commit comments

Comments
 (0)