Skip to content

Commit c08a974

Browse files
committed
Serde impl for KeyPair
1 parent 0d8afe6 commit c08a974

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/schnorrsig.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,48 @@ impl str::FromStr for Signature {
8080
pub struct KeyPair(ffi::KeyPair);
8181
impl_safe_debug!(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+
#[cfg(all(feature = "serde", feature = "serde-secrets"))]
95+
impl ::serde::Serialize for KeyPair {
96+
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
97+
if s.is_human_readable() {
98+
#[allow(deprecated)]
99+
s.serialize_str(&self.format_secret_key())
100+
} else {
101+
s.serialize_bytes(&self.0[..])
102+
}
103+
}
104+
}
105+
106+
#[cfg(feature = "serde")]
107+
impl<'de> ::serde::Deserialize<'de> for KeyPair {
108+
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
109+
if d.is_human_readable() {
110+
d.deserialize_str(super::serde_util::FromStrVisitor::new(
111+
"a hex string representing 32 byte KeyPair"
112+
))
113+
} else {
114+
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
115+
"raw 32 bytes KeyPair",
116+
|data| unsafe {
117+
let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context);
118+
KeyPair::from_seckey_slice(&ctx, data)
119+
}
120+
))
121+
}
122+
}
123+
}
124+
83125
/// A Schnorr public key, used for verification of Schnorr signatures
84126
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
85127
pub struct PublicKey(ffi::XOnlyPublicKey);

0 commit comments

Comments
 (0)