Skip to content

Commit 656b26a

Browse files
committed
Serde serialization for KeyPair
1 parent 6810c2b commit 656b26a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/schnorrsig.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,49 @@ 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+
#[cfg(feature = "serde")]
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+
let mut buf = [0u8; 64];
99+
s.serialize_str(::to_hex(&self.serialize_secret(), &mut buf)
100+
.expect("fixed-size hex serialization"))
101+
} else {
102+
s.serialize_bytes(&self.0[..])
103+
}
104+
}
105+
}
106+
107+
#[cfg(feature = "serde")]
108+
impl<'de> ::serde::Deserialize<'de> for KeyPair {
109+
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
110+
if d.is_human_readable() {
111+
d.deserialize_str(super::serde_util::FromStrVisitor::new(
112+
"a hex string representing 32 byte KeyPair"
113+
))
114+
} else {
115+
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
116+
"raw 32 bytes KeyPair",
117+
|data| unsafe {
118+
let ctx = Secp256k1::from_raw_all(ffi::secp256k1_context_no_precomp as *mut ffi::Context);
119+
KeyPair::from_seckey_slice(&ctx, data)
120+
}
121+
))
122+
}
123+
}
124+
}
125+
83126
/// A Schnorr public key, used for verification of Schnorr signatures
84127
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
85128
pub struct PublicKey(ffi::XOnlyPublicKey);

0 commit comments

Comments
 (0)