Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add serde to Field #506

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion ec/src/models/short_weierstrass/affine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ impl<P: SWCurveConfig> From<Projective<P>> for Affine<P> {
}
}

impl<P: SWCurveConfig> CanonicalSerialize for Affine<P> {
impl<P: SWCurveConfig> CanonicalSerializeInner for Affine<P> {
#[inline]
fn serialize_with_mode<W: Write>(
&self,
Expand All @@ -359,6 +359,8 @@ impl<P: SWCurveConfig> CanonicalSerialize for Affine<P> {
}
}

impl<P: SWCurveConfig> CanonicalSerialize for Affine<P> {}

impl<P: SWCurveConfig> Valid for Affine<P> {
fn check(&self) -> Result<(), SerializationError> {
if self.is_on_curve() && self.is_in_correct_subgroup_assuming_on_curve() {
Expand Down
4 changes: 3 additions & 1 deletion ec/src/models/short_weierstrass/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ impl<P: SWCurveConfig> From<Affine<P>> for Projective<P> {
}
}

impl<P: SWCurveConfig> CanonicalSerialize for Projective<P> {
impl<P: SWCurveConfig> CanonicalSerializeInner for Projective<P> {
#[inline]
fn serialize_with_mode<W: Write>(
&self,
Expand All @@ -588,6 +588,8 @@ impl<P: SWCurveConfig> CanonicalSerialize for Projective<P> {
}
}

impl<P: SWCurveConfig> CanonicalSerialize for Projective<P> {}

impl<P: SWCurveConfig> Valid for Projective<P> {
fn check(&self) -> Result<(), SerializationError> {
self.into_affine().check()
Expand Down
4 changes: 3 additions & 1 deletion ec/src/models/twisted_edwards/affine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ impl<P: TECurveConfig> From<Projective<P>> for Affine<P> {
}
}
}
impl<P: TECurveConfig> CanonicalSerialize for Affine<P> {
impl<P: TECurveConfig> CanonicalSerializeInner for Affine<P> {
#[inline]
fn serialize_with_mode<W: Write>(
&self,
Expand All @@ -316,6 +316,8 @@ impl<P: TECurveConfig> CanonicalSerialize for Affine<P> {
}
}

impl<P: TECurveConfig> CanonicalSerialize for Affine<P> {}

impl<P: TECurveConfig> Valid for Affine<P> {
fn check(&self) -> Result<(), SerializationError> {
if self.is_on_curve() && self.is_in_correct_subgroup_assuming_on_curve() {
Expand Down
4 changes: 3 additions & 1 deletion ec/src/models/twisted_edwards/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ impl<P: MontCurveConfig> MontgomeryAffine<P> {
}
}

impl<P: TECurveConfig> CanonicalSerialize for Projective<P> {
impl<P: TECurveConfig> CanonicalSerializeInner for Projective<P> {
#[allow(unused_qualifications)]
#[inline]
fn serialize_with_mode<W: Write>(
Expand All @@ -440,6 +440,8 @@ impl<P: TECurveConfig> CanonicalSerialize for Projective<P> {
}
}

impl<P: TECurveConfig> CanonicalSerialize for Projective<P> {}

impl<P: TECurveConfig> Valid for Projective<P> {
fn check(&self) -> Result<(), SerializationError> {
self.into_affine().check()
Expand Down
4 changes: 3 additions & 1 deletion ec/src/pairing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ pub trait Pairing: Sized + 'static + Copy + Debug + Sync + Send + Eq {
#[must_use]
pub struct PairingOutput<P: Pairing>(pub P::TargetField);

impl<P: Pairing> CanonicalSerialize for PairingOutput<P> {
impl<P: Pairing> CanonicalSerializeInner for PairingOutput<P> {
#[allow(unused_qualifications)]
#[inline]
fn serialize_with_mode<W: Write>(
Expand All @@ -150,6 +150,8 @@ impl<P: Pairing> CanonicalSerialize for PairingOutput<P> {
}
}

impl<P: Pairing> CanonicalSerialize for PairingOutput<P> {}

impl<P: Pairing> Valid for PairingOutput<P> {
fn check(&self) -> Result<(), SerializationError> {
if self.0.pow(&P::ScalarField::characteristic()).is_one() {
Expand Down
3 changes: 2 additions & 1 deletion ff/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ derivative = { version = "2", features = ["use_core"] }
num-traits = { version = "0.2", default-features = false }
paste = "1.0"
rayon = { version = "1", optional = true }
serde = { version = "1.0", optional = true, features = ["derive"] }
zeroize = { version = "1", default-features = false, features = ["zeroize_derive"] }
num-bigint = { version = "0.4", default-features = false }
digest = { version = "0.10", default-features = false, features = ["alloc"] }
Expand All @@ -46,7 +47,7 @@ default = []
std = [ "ark-std/std", "ark-serialize/std", "itertools/use_std" ]
parallel = [ "std", "rayon", "ark-std/parallel" ]
asm = []

serde = [ "dep:serde", "ark-serialize/serde" ]

[package.metadata.docs.rs]
rustdoc-args = ["--html-in-header", "../doc/katex-header.html"]
74 changes: 71 additions & 3 deletions ff/src/biginteger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use crate::{
#[allow(unused)]
use ark_ff_macros::unroll_for_loops;
use ark_serialize::{
CanonicalDeserialize, CanonicalSerialize, Compress, SerializationError, Valid, Validate,
CanonicalDeserialize, CanonicalSerialize, CanonicalSerializeInner, Compress,
SerializationError, Valid, Validate,
};
use ark_std::{
convert::TryFrom,
Expand All @@ -23,16 +24,81 @@ use zeroize::Zeroize;
#[macro_use]
pub mod arithmetic;

/// This is a hack to make serialization of BigInt work below.
#[cfg(feature = "serde")]
mod arrays {
use ark_std::vec::Vec;
use ark_std::{convert::TryInto, marker::PhantomData};

use serde::{
de::{SeqAccess, Visitor},
ser::SerializeTuple,
Deserialize, Deserializer, Serialize, Serializer,
};
pub fn serialize<S: Serializer, T: Serialize, const N: usize>(
data: &[T; N],
ser: S,
) -> Result<S::Ok, S::Error> {
let mut s = ser.serialize_tuple(N)?;
for item in data {
s.serialize_element(item)?;
}
s.end()
}

struct ArrayVisitor<T, const N: usize>(PhantomData<T>);

impl<'de, T, const N: usize> Visitor<'de> for ArrayVisitor<T, N>
where
T: Deserialize<'de>,
{
type Value = [T; N];

fn expecting(&self, formatter: &mut ark_std::fmt::Formatter<'_>) -> ark_std::fmt::Result {
formatter.write_str(&format!("an array of length {}", N))
}

#[inline]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
// can be optimized using MaybeUninit
let mut data = Vec::with_capacity(N);
for _ in 0..N {
match (seq.next_element())? {
Some(val) => data.push(val),
None => return Err(serde::de::Error::invalid_length(N, &self)),
}
}
match data.try_into() {
Ok(arr) => Ok(arr),
Err(_) => unreachable!(),
}
}
}
pub fn deserialize<'de, D, T, const N: usize>(deserializer: D) -> Result<[T; N], D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
deserializer.deserialize_tuple(N, ArrayVisitor::<T, N>(PhantomData))
}
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Zeroize)]
pub struct BigInt<const N: usize>(pub [u64; N]);
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BigInt<const N: usize>(
#[cfg_attr(feature = "serde", serde(with = "arrays"))] pub [u64; N],
);

impl<const N: usize> Default for BigInt<N> {
fn default() -> Self {
Self([0u64; N])
}
}

impl<const N: usize> CanonicalSerialize for BigInt<N> {
impl<const N: usize> CanonicalSerializeInner for BigInt<N> {
fn serialize_with_mode<W: Write>(
&self,
writer: W,
Expand All @@ -46,6 +112,8 @@ impl<const N: usize> CanonicalSerialize for BigInt<N> {
}
}

impl<const N: usize> CanonicalSerialize for BigInt<N> {}

impl<const N: usize> Valid for BigInt<N> {
fn check(&self) -> Result<(), SerializationError> {
self.0.check()
Expand Down
8 changes: 6 additions & 2 deletions ff/src/fields/models/cubic_extension.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use ark_serialize::{
CanonicalDeserialize, CanonicalDeserializeWithFlags, CanonicalSerialize,
CanonicalSerializeWithFlags, Compress, EmptyFlags, Flags, SerializationError, Valid, Validate,
CanonicalSerializeInner, CanonicalSerializeWithFlags, Compress, EmptyFlags, Flags,
SerializationError, Valid, Validate,
};
use ark_std::{
cmp::{Ord, Ordering, PartialOrd},
Expand Down Expand Up @@ -78,6 +79,7 @@ pub trait CubicExtConfig: 'static + Send + Sync + Sized {

/// An element of a cubic extension field F_p\[X\]/(X^3 - P::NONRESIDUE) is
/// represented as c0 + c1 * X + c2 * X^2, for c0, c1, c2 in `P::BaseField`.
#[cfg_attr(feature = "serde", serde::Serialize, serde::Deserialize)]
#[derive(Derivative)]
#[derivative(
Default(bound = "P: CubicExtConfig"),
Expand Down Expand Up @@ -624,7 +626,7 @@ impl<P: CubicExtConfig> CanonicalSerializeWithFlags for CubicExtField<P> {
}
}

impl<P: CubicExtConfig> CanonicalSerialize for CubicExtField<P> {
impl<P: CubicExtConfig> CanonicalSerializeInner for CubicExtField<P> {
#[inline]
fn serialize_with_mode<W: Write>(
&self,
Expand All @@ -640,6 +642,8 @@ impl<P: CubicExtConfig> CanonicalSerialize for CubicExtField<P> {
}
}

impl<P: CubicExtConfig> CanonicalSerialize for CubicExtField<P> {}

impl<P: CubicExtConfig> CanonicalDeserializeWithFlags for CubicExtField<P> {
#[inline]
fn deserialize_with_flags<R: Read, F: Flags>(
Expand Down
8 changes: 6 additions & 2 deletions ff/src/fields/models/fp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use core::iter;

use ark_serialize::{
buffer_byte_size, CanonicalDeserialize, CanonicalDeserializeWithFlags, CanonicalSerialize,
CanonicalSerializeWithFlags, Compress, EmptyFlags, Flags, SerializationError, Valid, Validate,
CanonicalSerializeInner, CanonicalSerializeWithFlags, Compress, EmptyFlags, Flags,
SerializationError, Valid, Validate,
};
use ark_std::{
cmp::{Ord, Ordering, PartialOrd},
Expand Down Expand Up @@ -100,6 +101,7 @@ pub trait FpConfig<const N: usize>: Send + Sync + 'static + Sized {

/// Represents an element of the prime field F_p, where `p == P::MODULUS`.
/// This type can represent elements in any field of size at most N * 64 bits.
#[cfg_attr(feature = "serde", serde::Serialize, serde::Deserialize)]
#[derive(Derivative)]
#[derivative(
Default(bound = ""),
Expand Down Expand Up @@ -567,7 +569,7 @@ impl<P: FpConfig<N>, const N: usize> CanonicalSerializeWithFlags for Fp<P, N> {
}
}

impl<P: FpConfig<N>, const N: usize> CanonicalSerialize for Fp<P, N> {
impl<P: FpConfig<N>, const N: usize> CanonicalSerializeInner for Fp<P, N> {
#[inline]
fn serialize_with_mode<W: ark_std::io::Write>(
&self,
Expand All @@ -583,6 +585,8 @@ impl<P: FpConfig<N>, const N: usize> CanonicalSerialize for Fp<P, N> {
}
}

impl<P: FpConfig<N>, const N: usize> CanonicalSerialize for Fp<P, N> {}

impl<P: FpConfig<N>, const N: usize> CanonicalDeserializeWithFlags for Fp<P, N> {
fn deserialize_with_flags<R: ark_std::io::Read, F: Flags>(
reader: R,
Expand Down
8 changes: 6 additions & 2 deletions ff/src/fields/models/quadratic_extension.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use ark_serialize::{
CanonicalDeserialize, CanonicalDeserializeWithFlags, CanonicalSerialize,
CanonicalSerializeWithFlags, Compress, EmptyFlags, Flags, SerializationError, Valid, Validate,
CanonicalSerializeInner, CanonicalSerializeWithFlags, Compress, EmptyFlags, Flags,
SerializationError, Valid, Validate,
};
use ark_std::{
cmp::{Ord, Ordering, PartialOrd},
Expand Down Expand Up @@ -93,6 +94,7 @@ pub trait QuadExtConfig: 'static + Send + Sync + Sized {

/// An element of a quadratic extension field F_p\[X\]/(X^2 - P::NONRESIDUE) is
/// represented as c0 + c1 * X, for c0, c1 in `P::BaseField`.
#[cfg_attr(feature = "serde", serde::Serialize, serde::Deserialize)]
#[derive(Derivative)]
#[derivative(
Default(bound = "P: QuadExtConfig"),
Expand Down Expand Up @@ -702,7 +704,7 @@ impl<P: QuadExtConfig> CanonicalSerializeWithFlags for QuadExtField<P> {
}
}

impl<P: QuadExtConfig> CanonicalSerialize for QuadExtField<P> {
impl<P: QuadExtConfig> CanonicalSerializeInner for QuadExtField<P> {
#[inline]
fn serialize_with_mode<W: Write>(
&self,
Expand All @@ -718,6 +720,8 @@ impl<P: QuadExtConfig> CanonicalSerialize for QuadExtField<P> {
}
}

impl<P: QuadExtConfig> CanonicalSerialize for QuadExtField<P> {}

impl<P: QuadExtConfig> CanonicalDeserializeWithFlags for QuadExtField<P> {
#[inline]
fn deserialize_with_flags<R: Read, F: Flags>(
Expand Down
7 changes: 5 additions & 2 deletions poly/src/domain/general.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use crate::domain::{
};
use ark_ff::FftField;
use ark_serialize::{
CanonicalDeserialize, CanonicalSerialize, Compress, SerializationError, Valid, Validate,
CanonicalDeserialize, CanonicalSerialize, CanonicalSerializeInner, Compress,
SerializationError, Valid, Validate,
};
use ark_std::{
io::{Read, Write},
Expand All @@ -39,7 +40,7 @@ macro_rules! map {
}
}

impl<F: FftField> CanonicalSerialize for GeneralEvaluationDomain<F> {
impl<F: FftField> CanonicalSerializeInner for GeneralEvaluationDomain<F> {
fn serialize_with_mode<W: Write>(
&self,
mut writer: W,
Expand Down Expand Up @@ -75,6 +76,8 @@ impl<F: FftField> CanonicalSerialize for GeneralEvaluationDomain<F> {
}
}

impl<F: FftField> CanonicalSerialize for GeneralEvaluationDomain<F> {}

impl<F: FftField> Valid for GeneralEvaluationDomain<F> {
fn check(&self) -> Result<(), SerializationError> {
Ok(())
Expand Down
9 changes: 6 additions & 3 deletions serialize-derive/src/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub(super) fn impl_canonical_serialize(ast: &syn::DeriveInput) -> TokenStream {
data_struct.fields.len()
} else {
panic!(
"`CanonicalSerialize` can only be derived for structs, {} is not a struct",
"`CanonicalSerializeInner` can only be derived for structs, {} is not a struct",
name
);
};
Expand Down Expand Up @@ -90,7 +90,7 @@ pub(super) fn impl_canonical_serialize(ast: &syn::DeriveInput) -> TokenStream {
};

let gen = quote! {
impl #impl_generics ark_serialize::CanonicalSerialize for #name #ty_generics #where_clause {
impl #impl_generics ark_serialize::CanonicalSerializeInner for #name #ty_generics #where_clause {
#[allow(unused_mut, unused_variables)]
fn serialize_with_mode<W: ark_serialize::Write>(&self, mut writer: W, compress: ark_serialize::Compress) -> Result<(), ark_serialize::SerializationError> {
#(#serialize_body)*
Expand All @@ -104,5 +104,8 @@ pub(super) fn impl_canonical_serialize(ast: &syn::DeriveInput) -> TokenStream {
}
}
};
gen

let gen2 = quote! { impl #impl_generics ark_serialize::CanonicalSerialize for #name #ty_generics #where_clause {} };

quote! { #gen #gen2 }
}
2 changes: 2 additions & 0 deletions serialize/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ rust-version = "1.56"
ark-serialize-derive = { version = "^0.3.0", path = "../serialize-derive", optional = true }
ark-std = { version = "^0.3.0", default-features = false }
digest = { version = "0.10", default-features = false }
serde = { version = "1.0", optional = true, features = ["derive"] }

[dev-dependencies]
sha2 = { version = "0.10", default-features = false}
Expand All @@ -27,3 +28,4 @@ blake2 = { version = "0.10", default-features = false}
default = []
std = [ "ark-std/std", ]
derive = [ "ark-serialize-derive" ]
serde = [ "dep:serde" ]
Loading