Skip to content

Commit cd90352

Browse files
committed
Add serializer for Option<secp::key::Pubkey>
Adds serde mod for an optional public key. Useful for atomic swap transaction flow
1 parent 4155555 commit cd90352

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

core/src/libtx/secp_ser.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,51 @@ pub mod pubkey_serde {
5151
}
5252
}
5353

54+
/// Serializes an Option<secp::key::PublicKey> to and from hex
55+
pub mod option_pubkey_serde {
56+
use serde::de::Error;
57+
use serde::{Deserialize, Deserializer, Serializer};
58+
use util::secp::key::PublicKey;
59+
use util::{from_hex, static_secp_instance, ToHex};
60+
61+
///
62+
pub fn serialize<S>(key: &Option<PublicKey>, serializer: S) -> Result<S::Ok, S::Error>
63+
where
64+
S: Serializer,
65+
{
66+
match key {
67+
Some(k) => {
68+
let static_secp = static_secp_instance();
69+
let static_secp = static_secp.lock();
70+
serializer.serialize_str(&k.serialize_vec(&static_secp, true).to_hex())
71+
}
72+
None => serializer.serialize_none(),
73+
}
74+
}
75+
76+
///
77+
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<PublicKey>, D::Error>
78+
where
79+
D: Deserializer<'de>,
80+
{
81+
Option::<String>::deserialize(deserializer).and_then(|res| match res {
82+
Some(string) => {
83+
let static_secp = static_secp_instance();
84+
let static_secp = static_secp.lock();
85+
86+
from_hex(&string)
87+
.map_err(Error::custom)
88+
.and_then(|bytes: Vec<u8>| {
89+
Ok(Some(
90+
PublicKey::from_slice(&static_secp, &bytes).map_err(Error::custom)?,
91+
))
92+
})
93+
}
94+
None => Ok(None),
95+
})
96+
}
97+
}
98+
5499
/// Serializes an Option<secp::Signature> to and from hex
55100
pub mod option_sig_serde {
56101
use serde::de::Error;

0 commit comments

Comments
 (0)