3
2
Prechádzať zdrojové kódy

Merge serialization code for scalars and points

Removing some unnecessary code duplication
Ian Goldberg 6 mesiacov pred
rodič
commit
662b45327c
3 zmenil súbory, kde vykonal 28 pridanie a 146 odobranie
  1. 23 3
      src/group_serde.rs
  2. 5 7
      src/lib.rs
  3. 0 136
      src/primefield_serde.rs

+ 23 - 3
src/group_serde.rs

@@ -1,4 +1,4 @@
-//! serde adaptors for Group + GroupEncoding
+//! serde adaptors for Group + GroupEncoding and for PrimeField
 //!
 //! Adapted from elliptic_curve_tools v0.1.2 by Michael Lodder:
 //! https://crates.io/crates/elliptic-curve-tools
@@ -36,6 +36,7 @@ use core::{
     fmt::{self, Formatter},
     marker::PhantomData,
 };
+use ff::PrimeField;
 use group::{Group, GroupEncoding};
 use serde::{
     self,
@@ -44,7 +45,7 @@ use serde::{
 };
 
 /// Serialize a group element.
-pub fn serialize<G, S>(g: &G, s: S) -> Result<S::Ok, S::Error>
+pub fn serialize_point<G, S>(g: &G, s: S) -> Result<S::Ok, S::Error>
 where
     S: Serializer,
     G: Group + GroupEncoding,
@@ -53,7 +54,7 @@ where
 }
 
 /// Deserialize a group element.
-pub fn deserialize<'de, G, D>(d: D) -> Result<G, D::Error>
+pub fn deserialize_point<'de, G, D>(d: D) -> Result<G, D::Error>
 where
     D: Deserializer<'de>,
     G: Group + GroupEncoding,
@@ -62,6 +63,25 @@ where
     Option::from(G::from_bytes(&bytes)).ok_or(DError::custom("invalid group element"))
 }
 
+/// Serialize a prime field element.
+pub fn serialize_scalar<F, S>(f: &F, s: S) -> Result<S::Ok, S::Error>
+where
+    S: Serializer,
+    F: PrimeField,
+{
+    serialize_(f.to_repr(), s)
+}
+
+/// Deserialize a prime field element.
+pub fn deserialize_scalar<'de, F, D>(d: D) -> Result<F, D::Error>
+where
+    D: Deserializer<'de>,
+    F: PrimeField,
+{
+    let repr = deserialize_(d)?;
+    Option::from(F::from_repr(repr)).ok_or(DError::custom("invalid prime field element"))
+}
+
 fn serialize_<B, S>(bytes: B, s: S) -> Result<S::Ok, S::Error>
 where
     S: Serializer,

+ 5 - 7
src/lib.rs

@@ -18,7 +18,7 @@ pub use serde_with::{serde_as, DeserializeAs, SerializeAs};
 //
 // Pattern from https://docs.rs/serde_with/3.12.0/serde_with/guide/serde_as/index.html
 
-mod primefield_serde;
+mod group_serde;
 
 pub struct SerdeScalar;
 
@@ -27,7 +27,7 @@ impl<F: PrimeField> SerializeAs<F> for SerdeScalar {
     where
         S: Serializer,
     {
-        primefield_serde::serialize(value, serializer)
+        group_serde::serialize_scalar(value, serializer)
     }
 }
 
@@ -36,12 +36,10 @@ impl<'de, F: PrimeField> DeserializeAs<'de, F> for SerdeScalar {
     where
         D: Deserializer<'de>,
     {
-        primefield_serde::deserialize(deserializer)
+        group_serde::deserialize_scalar(deserializer)
     }
 }
 
-mod group_serde;
-
 pub struct SerdePoint;
 
 impl<G: Group + GroupEncoding> SerializeAs<G> for SerdePoint {
@@ -49,7 +47,7 @@ impl<G: Group + GroupEncoding> SerializeAs<G> for SerdePoint {
     where
         S: Serializer,
     {
-        group_serde::serialize(value, serializer)
+        group_serde::serialize_point(value, serializer)
     }
 }
 
@@ -58,7 +56,7 @@ impl<'de, G: Group + GroupEncoding> DeserializeAs<'de, G> for SerdePoint {
     where
         D: Deserializer<'de>,
     {
-        group_serde::deserialize(deserializer)
+        group_serde::deserialize_point(deserializer)
     }
 }
 

+ 0 - 136
src/primefield_serde.rs

@@ -1,136 +0,0 @@
-//! serde adaptors for PrimeField
-//!
-//! Adapted from elliptic_curve_tools v0.1.2 by Michael Lodder:
-//! https://crates.io/crates/elliptic-curve-tools
-//!
-//! Lodder's original can be adapted under the terms of the MIT license:
-//!
-//! [No explicit copyright line was present in that package's
-//! LICENSE-MIT file.]
-//!
-//! Permission is hereby granted, free of charge, to any
-//! person obtaining a copy of this software and associated
-//! documentation files (the "Software"), to deal in the
-//! Software without restriction, including without
-//! limitation the rights to use, copy, modify, merge,
-//! publish, distribute, sublicense, and/or sell copies of
-//! the Software, and to permit persons to whom the Software
-//! is furnished to do so, subject to the following
-//! conditions:
-//!
-//! The above copyright notice and this permission notice
-//! shall be included in all copies or substantial portions
-//! of the Software.
-//!
-//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
-//! ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
-//! TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-//! PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-//! SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-//! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-//! OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
-//! IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-//! DEALINGS IN THE SOFTWARE.
-
-use core::{
-    fmt::{self, Formatter},
-    marker::PhantomData,
-};
-use ff::PrimeField;
-use serde::{
-    self,
-    de::{Error as DError, Visitor},
-    Deserializer, Serializer,
-};
-
-/// Serialize a prime field element.
-pub fn serialize<F, S>(f: &F, s: S) -> Result<S::Ok, S::Error>
-where
-    S: Serializer,
-    F: PrimeField,
-{
-    serialize_(f.to_repr(), s)
-}
-
-/// Deserialize a prime field element.
-pub fn deserialize<'de, F, D>(d: D) -> Result<F, D::Error>
-where
-    D: Deserializer<'de>,
-    F: PrimeField,
-{
-    let repr = deserialize_(d)?;
-    Option::from(F::from_repr(repr)).ok_or(DError::custom("invalid prime field element"))
-}
-
-fn serialize_<B, S>(bytes: B, s: S) -> Result<S::Ok, S::Error>
-where
-    S: Serializer,
-    B: AsRef<[u8]> + AsMut<[u8]> + Default,
-{
-    if s.is_human_readable() {
-        s.serialize_str(&hex::encode(bytes.as_ref()))
-    } else {
-        s.serialize_bytes(bytes.as_ref())
-    }
-}
-
-fn deserialize_<'de, B: AsRef<[u8]> + AsMut<[u8]> + Default, D: Deserializer<'de>>(
-    d: D,
-) -> Result<B, D::Error> {
-    if d.is_human_readable() {
-        struct StrVisitor<B: AsRef<[u8]> + AsMut<[u8]> + Default>(PhantomData<B>);
-
-        impl<'de, B> Visitor<'de> for StrVisitor<B>
-        where
-            B: AsRef<[u8]> + AsMut<[u8]> + Default,
-        {
-            type Value = B;
-
-            fn expecting(&self, f: &mut Formatter) -> fmt::Result {
-                write!(f, "a {} length hex string", B::default().as_ref().len() * 2)
-            }
-
-            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
-            where
-                E: DError,
-            {
-                let mut repr = B::default();
-                let length = repr.as_ref().len();
-                if v.len() != length * 2 {
-                    return Err(DError::custom("invalid length"));
-                }
-                hex::decode_to_slice(v, repr.as_mut())
-                    .map_err(|_| DError::custom("invalid input"))?;
-                Ok(repr)
-            }
-        }
-        d.deserialize_str(StrVisitor(PhantomData))
-    } else {
-        struct ByteVisitor<B: AsRef<[u8]> + AsMut<[u8]> + Default>(PhantomData<B>);
-
-        impl<'de, B> Visitor<'de> for ByteVisitor<B>
-        where
-            B: AsRef<[u8]> + AsMut<[u8]> + Default,
-        {
-            type Value = B;
-
-            fn expecting(&self, f: &mut Formatter) -> fmt::Result {
-                write!(f, "a {} byte", B::default().as_ref().len())
-            }
-
-            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
-            where
-                E: serde::de::Error,
-            {
-                let mut repr = B::default();
-                if v.len() != repr.as_ref().len() {
-                    return Err(serde::de::Error::custom("invalid length"));
-                }
-                repr.as_mut().copy_from_slice(v);
-                Ok(repr)
-            }
-        }
-
-        d.deserialize_bytes(ByteVisitor(PhantomData))
-    }
-}