Преглед на файлове

utils: use bincode for serialization

Lennart Braun преди 2 години
родител
ревизия
197f2d62cd
променени са 3 файла, в които са добавени 14 реда и са изтрити 73 реда
  1. 1 0
      utils/Cargo.toml
  2. 6 39
      utils/src/field.rs
  3. 7 34
      utils/src/permutation.rs

+ 1 - 0
utils/Cargo.toml

@@ -7,6 +7,7 @@ edition = "2021"
 
 [dependencies]
 communicator = { path = "../communicator" }
+bincode = "2.0.0-rc.2"
 aes = "0.8.2"
 blake3 = "1.3.3"
 ff = { version = "0.13.0", features = ["derive"] }

+ 6 - 39
utils/src/field.rs

@@ -1,6 +1,6 @@
 use crate::fixed_key_aes::FixedKeyAes;
+use bincode;
 use blake3;
-use communicator::{traits::Serializable, Error};
 use ff::{Field, PrimeField};
 use num;
 use rand::{thread_rng, Rng};
@@ -10,7 +10,7 @@ pub const p: u128 = 340282366920938462946865773367900766209;
 
 /// Prime field with modulus
 /// p = 340282366920938462946865773367900766209.
-#[derive(PrimeField)]
+#[derive(PrimeField, bincode::Encode, bincode::Decode)]
 #[PrimeFieldModulus = "340282366920938462946865773367900766209"]
 #[PrimeFieldGenerator = "7"]
 #[PrimeFieldReprEndianness = "little"]
@@ -208,40 +208,6 @@ impl FromHash for Fp {
     }
 }
 
-impl Serializable for Fp {
-    fn bytes_required() -> usize {
-        16
-    }
-
-    fn to_bytes(&self) -> Vec<u8> {
-        let mut buf = vec![0u8; 16];
-        self.into_bytes(&mut buf).unwrap();
-        buf
-    }
-
-    fn into_bytes(&self, buf: &mut [u8]) -> Result<(), Error> {
-        if buf.len() != 16 {
-            return Err(Error::SerializationError("wrong buffer size".to_owned()));
-        }
-        buf.chunks_mut(8).enumerate().for_each(|(i, c)| {
-            c.copy_from_slice(&self.0[i].to_be_bytes());
-        });
-        Ok(())
-    }
-
-    fn from_bytes(buf: &[u8]) -> Result<Self, Error> {
-        if buf.len() != 16 {
-            return Err(Error::DeserializationError("wrong buffer size".to_owned()));
-        }
-
-        let mut output = Self::ZERO;
-        buf.chunks(8).enumerate().for_each(|(i, c)| {
-            output.0[i] = u64::from_be_bytes(c.try_into().unwrap());
-        });
-        Ok(output)
-    }
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -300,11 +266,12 @@ mod tests {
 
     #[test]
     fn test_serialization() {
-        assert_eq!(Fp::bytes_required(), 16);
         for _ in 0..100 {
             let x = Fp::random(thread_rng());
-            let x_bytes = x.to_bytes();
-            let y = Fp::from_bytes(&x_bytes).unwrap();
+            let x_bytes = bincode::encode_to_vec(x, bincode::config::standard()).unwrap();
+            let (y, bytes_read): (Fp, usize) =
+                bincode::decode_from_slice(&x_bytes, bincode::config::standard()).unwrap();
+            assert_eq!(bytes_read, x_bytes.len());
             assert_eq!(y, x);
         }
     }

+ 7 - 34
utils/src/permutation.rs

@@ -1,4 +1,4 @@
-use communicator::{traits::Serializable, Error as CommError};
+use bincode;
 use rand::{thread_rng, Rng, SeedableRng};
 use rand_chacha::ChaCha20Rng;
 
@@ -15,41 +15,12 @@ pub trait Permutation {
     // fn permuted_vector() -> Vec<usize>;
 }
 
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, bincode::Encode, bincode::Decode)]
 pub struct FisherYatesPermutationKey {
     log_domain_size: u32,
     prg_seed: [u8; 32],
 }
 
-impl Serializable for FisherYatesPermutationKey {
-    fn bytes_required() -> usize {
-        36
-    }
-
-    fn into_bytes(&self, buf: &mut [u8]) -> Result<(), CommError> {
-        if buf.len() != Self::bytes_required() {
-            return Err(CommError::SerializationError(
-                "buffer has wrong size".to_owned(),
-            ));
-        }
-        buf[..4].copy_from_slice(&self.log_domain_size.to_be_bytes());
-        buf[4..36].copy_from_slice(&self.prg_seed);
-        Ok(())
-    }
-
-    fn from_bytes(buf: &[u8]) -> Result<Self, CommError> {
-        if buf.len() != Self::bytes_required() {
-            return Err(CommError::DeserializationError(
-                "buffer has wrong size".to_owned(),
-            ));
-        }
-        Ok(Self {
-            log_domain_size: u32::from_be_bytes(buf[..4].try_into().unwrap()),
-            prg_seed: buf[4..36].try_into().unwrap(),
-        })
-    }
-}
-
 /// Random permutation based on a Fisher-Yates shuffle of [0, N) with a seeded PRG.
 #[derive(Clone, Debug)]
 pub struct FisherYatesPermutation {
@@ -128,9 +99,11 @@ mod tests {
         for _ in 0..100 {
             let log_domain_size = thread_rng().gen_range(1..30);
             let key = FisherYatesPermutation::sample(log_domain_size);
-            let bytes = key.to_bytes();
-            assert_eq!(bytes.len(), FisherYatesPermutationKey::bytes_required());
-            assert_eq!(FisherYatesPermutationKey::from_bytes(&bytes).unwrap(), key);
+            let bytes = bincode::encode_to_vec(key, bincode::config::standard()).unwrap();
+            let (new_key, bytes_read): (FisherYatesPermutationKey, usize) =
+                bincode::decode_from_slice(&bytes, bincode::config::standard()).unwrap();
+            assert_eq!(bytes_read, bytes.len());
+            assert_eq!(new_key, key);
         }
     }
 }