Skip to content

Commit 4a76e13

Browse files
committed
Serde serialization for KeyPair
1 parent 1f5d6da commit 4a76e13

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/schnorrsig.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,46 @@ impl str::FromStr for Signature {
8080
pub struct KeyPair(ffi::KeyPair);
8181
impl_display_secret!(KeyPair);
8282

83+
impl ::core::str::FromStr for KeyPair {
84+
type Err = Error;
85+
86+
fn from_str(s: &str) -> Result<Self, Self::Err> {
87+
let ctx = unsafe {
88+
Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context)
89+
};
90+
KeyPair::from_seckey_str(&ctx, s)
91+
}
92+
}
93+
94+
impl ::serde::Serialize for KeyPair {
95+
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
96+
if s.is_human_readable() {
97+
s.serialize_str(&self.display_secret().to_string())
98+
} else {
99+
s.serialize_bytes(&self.0[..])
100+
}
101+
}
102+
}
103+
104+
#[cfg(feature = "serde")]
105+
impl<'de> ::serde::Deserialize<'de> for KeyPair {
106+
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
107+
if d.is_human_readable() {
108+
d.deserialize_str(super::serde_util::FromStrVisitor::new(
109+
"a hex string representing 32 byte KeyPair"
110+
))
111+
} else {
112+
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
113+
"raw 32 bytes KeyPair",
114+
|data| unsafe {
115+
let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context);
116+
KeyPair::from_seckey_slice(&ctx, data)
117+
}
118+
))
119+
}
120+
}
121+
}
122+
83123
/// A Schnorr public key, used for verification of Schnorr signatures
84124
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
85125
pub struct PublicKey(ffi::XOnlyPublicKey);

0 commit comments

Comments
 (0)