use std::borrow::Borrow; use std::marker::PhantomData; use pairing::{CurveAffine, CurveProjective, EncodedPoint, Engine}; use super::{DecryptionShare, PublicKey, Signature}; use serde::de::Error as DeserializeError; use serde::{Deserialize, Deserializer, Serialize, Serializer}; const ERR_LEN: &str = "wrong length of deserialized group element"; const ERR_CODE: &str = "deserialized bytes don't encode a group element"; /// A wrapper type to facilitate serialization and deserialization of group elements. struct CurveWrap(B, PhantomData); impl CurveWrap { fn new(c: B) -> Self { CurveWrap(c, PhantomData) } } impl> Serialize for CurveWrap { fn serialize(&self, s: S) -> Result { serialize_projective(self.0.borrow(), s) } } impl<'de, C: CurveProjective> Deserialize<'de> for CurveWrap { fn deserialize>(d: D) -> Result { Ok(CurveWrap::new(deserialize_projective(d)?)) } } impl Serialize for PublicKey { fn serialize(&self, s: S) -> Result { serialize_projective(&self.0, s) } } impl<'de, E: Engine> Deserialize<'de> for PublicKey { fn deserialize>(d: D) -> Result { Ok(PublicKey(deserialize_projective(d)?)) } } impl Serialize for Signature { fn serialize(&self, s: S) -> Result { serialize_projective(&self.0, s) } } impl<'de, E: Engine> Deserialize<'de> for Signature { fn deserialize>(d: D) -> Result { Ok(Signature(deserialize_projective(d)?)) } } impl Serialize for DecryptionShare { fn serialize(&self, s: S) -> Result { serialize_projective(&self.0, s) } } impl<'de, E: Engine> Deserialize<'de> for DecryptionShare { fn deserialize>(d: D) -> Result { Ok(DecryptionShare(deserialize_projective(d)?)) } } /// Serializes the compressed representation of a group element. fn serialize_projective(c: &C, s: S) -> Result where S: Serializer, C: CurveProjective, { c.into_affine().into_compressed().as_ref().serialize(s) } /// Deserializes the compressed representation of a group element. fn deserialize_projective<'de, D, C>(d: D) -> Result where D: Deserializer<'de>, C: CurveProjective, { let bytes = >::deserialize(d)?; if bytes.len() != ::Compressed::size() { return Err(D::Error::custom(ERR_LEN)); } let mut compressed = ::Compressed::empty(); compressed.as_mut().copy_from_slice(&bytes); let to_err = |_| D::Error::custom(ERR_CODE); Ok(compressed.into_affine().map_err(to_err)?.into_projective()) } /// Serialization and deserialization of vectors of projective curve elements. pub mod projective_vec { use super::CurveWrap; use pairing::CurveProjective; use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub fn serialize(vec: &[C], s: S) -> Result where S: Serializer, C: CurveProjective, { let wrap_vec: Vec> = vec.iter().map(CurveWrap::new).collect(); wrap_vec.serialize(s) } pub fn deserialize<'de, D, C>(d: D) -> Result, D::Error> where D: Deserializer<'de>, C: CurveProjective, { let wrap_vec = >>::deserialize(d)?; Ok(wrap_vec.into_iter().map(|CurveWrap(c, _)| c).collect()) } }