From 81a7936d99a91a68b114e1da5c71d3aae8cfd771 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 22 Feb 2021 18:33:53 +0000 Subject: [PATCH 1/5] pasta: Split halo2-specific curve-specific logic into a separate macro --- src/pasta/curves.rs | 103 +++++++++++++++++++++++--------------------- 1 file changed, 55 insertions(+), 48 deletions(-) diff --git a/src/pasta/curves.rs b/src/pasta/curves.rs index f22a65b..74bb236 100644 --- a/src/pasta/curves.rs +++ b/src/pasta/curves.rs @@ -55,7 +55,7 @@ macro_rules! new_curve_impl { type Scalar = $scalar; type Base = $base; - impl_projective_curve_specific!($name, $name_affine, $iso_affine, $base, $curve_type); + impl_projective_curve_specific!($name, $base, $curve_type); fn zero() -> Self { Self { @@ -85,6 +85,8 @@ macro_rules! new_curve_impl { $name_affine::conditional_select(&tmp, &$name_affine::zero(), zinv.ct_is_zero()) } + impl_projective_curve_ext!($name, $name_affine, $iso_affine, $base, $curve_type); + fn a() -> Self::Base { $name::curve_constant_a() } @@ -676,32 +678,7 @@ macro_rules! new_curve_impl { } macro_rules! impl_projective_curve_specific { - ($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, special_a0_b5) => { - fn hash_to_curve<'a>(domain_prefix: &'a str) -> Box Self + 'a> { - use super::hashtocurve; - - Box::new(move |message| { - let mut us = [Field::zero(); 2]; - hashtocurve::hash_to_field($name_affine::CURVE_ID, domain_prefix, message, &mut us); - let q0 = hashtocurve::map_to_curve_simple_swu::<$base, $name_affine, $iso_affine>( - &us[0], - $name::THETA, - $name::Z, - ); - let q1 = hashtocurve::map_to_curve_simple_swu::<$base, $name_affine, $iso_affine>( - &us[1], - $name::THETA, - $name::Z, - ); - let r = q0 + &q1; - debug_assert!(bool::from(r.is_on_curve())); - hashtocurve::iso_map::<$base, $name_affine, $iso_affine>( - &r, - &$name::ISOGENY_CONSTANTS, - ) - }) - } - + ($name:ident, $base:ident, special_a0_b5) => { fn one() -> Self { // NOTE: This is specific to b = 5 @@ -715,16 +692,6 @@ macro_rules! impl_projective_curve_specific { } } - /// Apply the curve endomorphism by multiplying the x-coordinate - /// by an element of multiplicative order 3. - fn endo(&self) -> Self { - $name { - x: self.x * $base::ZETA, - y: self.y, - z: self.z, - } - } - fn double(&self) -> Self { // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l // @@ -756,22 +723,12 @@ macro_rules! impl_projective_curve_specific { $name::conditional_select(&tmp, &$name::zero(), self.is_zero()) } }; - ($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, general) => { - /// Unimplemented: hashing to this curve is not supported - fn hash_to_curve<'a>(_domain_prefix: &'a str) -> Box Self + 'a> { - unimplemented!() - } - + ($name:ident, $base:ident, general) => { /// Unimplemented: there is no standard generator for this curve. fn one() -> Self { unimplemented!() } - /// Unimplemented: no endomorphism is supported for this curve. - fn endo(&self) -> Self { - unimplemented!() - } - fn double(&self) -> Self { // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl // @@ -801,6 +758,56 @@ macro_rules! impl_projective_curve_specific { }; } +macro_rules! impl_projective_curve_ext { + ($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, special_a0_b5) => { + fn hash_to_curve<'a>(domain_prefix: &'a str) -> Box Self + 'a> { + use super::hashtocurve; + + Box::new(move |message| { + let mut us = [Field::zero(); 2]; + hashtocurve::hash_to_field($name_affine::CURVE_ID, domain_prefix, message, &mut us); + let q0 = hashtocurve::map_to_curve_simple_swu::<$base, $name_affine, $iso_affine>( + &us[0], + $name::THETA, + $name::Z, + ); + let q1 = hashtocurve::map_to_curve_simple_swu::<$base, $name_affine, $iso_affine>( + &us[1], + $name::THETA, + $name::Z, + ); + let r = q0 + &q1; + debug_assert!(bool::from(r.is_on_curve())); + hashtocurve::iso_map::<$base, $name_affine, $iso_affine>( + &r, + &$name::ISOGENY_CONSTANTS, + ) + }) + } + + /// Apply the curve endomorphism by multiplying the x-coordinate + /// by an element of multiplicative order 3. + fn endo(&self) -> Self { + $name { + x: self.x * $base::ZETA, + y: self.y, + z: self.z, + } + } + }; + ($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, general) => { + /// Unimplemented: hashing to this curve is not supported + fn hash_to_curve<'a>(_domain_prefix: &'a str) -> Box Self + 'a> { + unimplemented!() + } + + /// Unimplemented: no endomorphism is supported for this curve. + fn endo(&self) -> Self { + unimplemented!() + } + }; +} + macro_rules! impl_affine_curve_specific { ($name:ident, $base:ident, special_a0_b5) => { fn one() -> Self { From 7037d55320078cc3a1b3c08906deb53fab23e51f Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 22 Feb 2021 18:39:14 +0000 Subject: [PATCH 2/5] Rename Curve and CurveAffine properties to match group traits --- src/arithmetic.rs | 20 ++++---- src/arithmetic/curves.rs | 37 +++++++-------- src/pasta.rs | 4 +- src/pasta/curves.rs | 88 +++++++++++++++++------------------ src/pasta/hashtocurve.rs | 10 ++-- src/pasta/pallas.rs | 6 +-- src/plonk/lookup/prover.rs | 2 +- src/plonk/prover.rs | 12 ++--- src/plonk/vanishing/prover.rs | 4 +- src/poly/commitment.rs | 16 +++---- src/poly/commitment/msm.rs | 2 +- src/poly/commitment/prover.rs | 4 +- 12 files changed, 98 insertions(+), 107 deletions(-) diff --git a/src/arithmetic.rs b/src/arithmetic.rs index 51a70e8..bee2b04 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -68,7 +68,7 @@ where } } -fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut C::Projective) { +fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut C::Curve) { let coeffs: Vec<[u8; 32]> = coeffs.iter().map(|a| a.to_bytes()).collect(); let c = if bases.len() < 4 { @@ -110,7 +110,7 @@ fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut enum Bucket { None, Affine(C), - Projective(C::Projective), + Projective(C::Curve), } impl Bucket { @@ -125,7 +125,7 @@ fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut } } - fn add(self, mut other: C::Projective) -> C::Projective { + fn add(self, mut other: C::Curve) -> C::Curve { match self { Bucket::None => other, Bucket::Affine(a) => { @@ -150,7 +150,7 @@ fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut // e.g. 3a + 2b + 1c = a + // (a) + b + // ((a) + b) + c - let mut running_sum = C::Projective::zero(); + let mut running_sum = C::Curve::identity(); for exp in buckets.into_iter().rev() { running_sum = exp.add(running_sum); *acc = *acc + &running_sum; @@ -160,9 +160,9 @@ fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut /// Performs a small multi-exponentiation operation. /// Uses the double-and-add algorithm with doublings shared across points. -pub fn small_multiexp(coeffs: &[C::Scalar], bases: &[C]) -> C::Projective { +pub fn small_multiexp(coeffs: &[C::Scalar], bases: &[C]) -> C::Curve { let coeffs: Vec<[u8; 32]> = coeffs.iter().map(|a| a.to_bytes()).collect(); - let mut acc = C::Projective::zero(); + let mut acc = C::Curve::identity(); // for byte idx for byte_idx in (0..32).rev() { @@ -187,14 +187,14 @@ pub fn small_multiexp(coeffs: &[C::Scalar], bases: &[C]) -> C::P /// This function will panic if coeffs and bases have a different length. /// /// This will use multithreading if beneficial. -pub fn best_multiexp(coeffs: &[C::Scalar], bases: &[C]) -> C::Projective { +pub fn best_multiexp(coeffs: &[C::Scalar], bases: &[C]) -> C::Curve { assert_eq!(coeffs.len(), bases.len()); let num_cpus = num_cpus::get(); if coeffs.len() > num_cpus { let chunk = coeffs.len() / num_cpus; let num_chunks = coeffs.chunks(chunk).len(); - let mut results = vec![C::Projective::zero(); num_chunks]; + let mut results = vec![C::Curve::identity(); num_chunks]; thread::scope(|scope| { let chunk = coeffs.len() / num_cpus; @@ -209,9 +209,9 @@ pub fn best_multiexp(coeffs: &[C::Scalar], bases: &[C]) -> C::Pr } }) .unwrap(); - results.iter().fold(C::Projective::zero(), |a, b| a + b) + results.iter().fold(C::Curve::identity(), |a, b| a + b) } else { - let mut acc = C::Projective::zero(); + let mut acc = C::Curve::identity(); multiexp_serial(coeffs, bases, &mut acc); acc } diff --git a/src/arithmetic/curves.rs b/src/arithmetic/curves.rs index 4a633d9..ef1ba4f 100644 --- a/src/arithmetic/curves.rs +++ b/src/arithmetic/curves.rs @@ -43,11 +43,8 @@ pub trait Curve: + Group::Scalar> { /// The representation of a point on this curve in the affine coordinate space. - type Affine: CurveAffine< - Projective = Self, - Scalar = ::Scalar, - Base = ::Base, - > + Add + type Affine: CurveAffine::Scalar, Base = ::Base> + + Add + Sub + Mul<::Scalar, Output = Self> + Neg::Affine> @@ -58,16 +55,16 @@ pub trait Curve: type Base: FieldExt; /// Obtains the additive identity. - fn zero() -> Self; + fn identity() -> Self; /// Obtains the base point of the curve. - fn one() -> Self; + fn generator() -> Self; /// Doubles this element. fn double(&self) -> Self; /// Returns whether or not this element is the identity. - fn is_zero(&self) -> Choice; + fn is_identity(&self) -> Choice; /// Apply the curve endomorphism by multiplying the x-coordinate /// by an element of multiplicative order 3. @@ -89,7 +86,7 @@ pub trait Curve: /// ``` /// use halo2::arithmetic::{Curve, CurveAffine}; /// fn pedersen_commitment(x: C::Scalar, r: C::Scalar) -> C { - /// let hasher = C::Projective::hash_to_curve("z.cash:example_pedersen_commitment"); + /// let hasher = C::Curve::hash_to_curve("z.cash:example_pedersen_commitment"); /// let g = hasher(b"g"); /// let h = hasher(b"h"); /// (g * x + &(h * r)).to_affine() @@ -103,7 +100,7 @@ pub trait Curve: /// Converts many elements into their affine form. Panics if the /// sizes of the slices are different. - fn batch_to_affine(v: &[Self], target: &mut [Self::Affine]); + fn batch_normalize(v: &[Self], target: &mut [Self::Affine]); /// Returns the curve constant a. fn a() -> Self::Base; @@ -127,22 +124,22 @@ pub trait CurveAffine: + Sync + 'static + Debug - + Add::Projective> - + Sub::Projective> - + Mul<::Scalar, Output = ::Projective> + + Add::Curve> + + Sub::Curve> + + Mul<::Scalar, Output = ::Curve> + Neg + PartialEq + cmp::Eq + ConditionallySelectable + ConstantTimeEq - + From<::Projective> + + From<::Curve> { /// The representation of a point on this curve in the projective coordinate space. - type Projective: Curve< + type Curve: Curve< Affine = Self, Scalar = ::Scalar, Base = ::Base, - > + Mul<::Scalar, Output = ::Projective> + > + Mul<::Scalar, Output = ::Curve> + MulAssign<::Scalar> + AddAssign + SubAssign @@ -160,16 +157,16 @@ pub trait CurveAffine: const CURVE_ID: &'static str; /// Obtains the additive identity. - fn zero() -> Self; + fn identity() -> Self; /// Obtains the base point of the curve. - fn one() -> Self; + fn generator() -> Self; /// Returns whether or not this element is the identity. - fn is_zero(&self) -> Choice; + fn is_identity(&self) -> Choice; /// Converts this element into its projective form. - fn to_projective(&self) -> Self::Projective; + fn to_curve(&self) -> Self::Curve; /// Gets the $(x, y)$ coordinates of this point. fn get_xy(&self) -> CtOption<(Self::Base, Self::Base)>; diff --git a/src/pasta.rs b/src/pasta.rs index 924ec13..3046bf4 100644 --- a/src/pasta.rs +++ b/src/pasta.rs @@ -17,8 +17,8 @@ pub use fields::*; fn test_endo_consistency() { use crate::arithmetic::{Curve, FieldExt}; - let a = pallas::Point::one(); + let a = pallas::Point::generator(); assert_eq!(a * pallas::Scalar::ZETA, a.endo()); - let a = vesta::Point::one(); + let a = vesta::Point::generator(); assert_eq!(a * vesta::Scalar::ZETA, a.endo()); } diff --git a/src/pasta/curves.rs b/src/pasta/curves.rs index 74bb236..72eaa05 100644 --- a/src/pasta/curves.rs +++ b/src/pasta/curves.rs @@ -57,7 +57,7 @@ macro_rules! new_curve_impl { impl_projective_curve_specific!($name, $base, $curve_type); - fn zero() -> Self { + fn identity() -> Self { Self { x: $base::zero(), y: $base::zero(), @@ -65,7 +65,7 @@ macro_rules! new_curve_impl { } } - fn is_zero(&self) -> Choice { + fn is_identity(&self) -> Choice { self.z.ct_is_zero() } @@ -82,7 +82,7 @@ macro_rules! new_curve_impl { infinity: Choice::from(0u8), }; - $name_affine::conditional_select(&tmp, &$name_affine::zero(), zinv.ct_is_zero()) + $name_affine::conditional_select(&tmp, &$name_affine::identity(), zinv.ct_is_zero()) } impl_projective_curve_ext!($name, $name_affine, $iso_affine, $base, $curve_type); @@ -111,7 +111,7 @@ macro_rules! new_curve_impl { | self.z.ct_is_zero() } - fn batch_to_affine(p: &[Self], q: &mut [Self::Affine]) { + fn batch_normalize(p: &[Self], q: &mut [Self::Affine]) { assert_eq!(p.len(), q.len()); let mut acc = $base::one(); @@ -121,7 +121,7 @@ macro_rules! new_curve_impl { q.x = acc; // We will end up skipping all identities in p - acc = $base::conditional_select(&(acc * p.z), &acc, p.is_zero()); + acc = $base::conditional_select(&(acc * p.z), &acc, p.is_identity()); } // This is the inverse, as all z-coordinates are nonzero and the ones @@ -129,7 +129,7 @@ macro_rules! new_curve_impl { acc = acc.invert().unwrap(); for (p, q) in p.iter().rev().zip(q.iter_mut().rev()) { - let skip = p.is_zero(); + let skip = p.is_identity(); // Compute tmp = 1/z let tmp = q.x * acc; @@ -145,7 +145,7 @@ macro_rules! new_curve_impl { q.y = p.y * tmp3; q.infinity = Choice::from(0u8); - *q = $name_affine::conditional_select(&q, &$name_affine::zero(), skip); + *q = $name_affine::conditional_select(&q, &$name_affine::identity(), skip); } } @@ -157,19 +157,19 @@ macro_rules! new_curve_impl { impl<'a> From<&'a $name_affine> for $name { fn from(p: &'a $name_affine) -> $name { - p.to_projective() + p.to_curve() } } impl From<$name_affine> for $name { fn from(p: $name_affine) -> $name { - p.to_projective() + p.to_curve() } } impl Default for $name { fn default() -> $name { - $name::zero() + $name::identity() } } @@ -186,8 +186,8 @@ macro_rules! new_curve_impl { let z = z * self.z; let y2 = other.y * z; - let self_is_zero = self.is_zero(); - let other_is_zero = other.is_zero(); + let self_is_zero = self.is_identity(); + let other_is_zero = other.is_identity(); (self_is_zero & other_is_zero) // Both point at infinity | ((!self_is_zero) & (!other_is_zero) & x1.ct_eq(&x2) & y1.ct_eq(&y2)) @@ -237,9 +237,9 @@ macro_rules! new_curve_impl { type Output = $name; fn add(self, rhs: &'a $name) -> $name { - if bool::from(self.is_zero()) { + if bool::from(self.is_identity()) { *rhs - } else if bool::from(rhs.is_zero()) { + } else if bool::from(rhs.is_identity()) { *self } else { let z1z1 = self.z.square(); @@ -253,7 +253,7 @@ macro_rules! new_curve_impl { if s1 == s2 { self.double() } else { - $name::zero() + $name::identity() } } else { let h = u2 - u1; @@ -281,9 +281,9 @@ macro_rules! new_curve_impl { type Output = $name; fn add(self, rhs: &'a $name_affine) -> $name { - if bool::from(self.is_zero()) { - rhs.to_projective() - } else if bool::from(rhs.is_zero()) { + if bool::from(self.is_identity()) { + rhs.to_curve() + } else if bool::from(rhs.is_identity()) { *self } else { let z1z1 = self.z.square(); @@ -294,7 +294,7 @@ macro_rules! new_curve_impl { if self.y == s2 { self.double() } else { - $name::zero() + $name::identity() } } else { let h = u2 - self.x; @@ -341,7 +341,7 @@ macro_rules! new_curve_impl { fn mul(self, other: &'b $scalar) -> Self::Output { // TODO: make this faster - let mut acc = $name::zero(); + let mut acc = $name::identity(); // This is a simple double-and-add implementation of point // multiplication, moving from most significant to least @@ -395,16 +395,16 @@ macro_rules! new_curve_impl { type Output = $name; fn add(self, rhs: &'a $name_affine) -> $name { - if bool::from(self.is_zero()) { - rhs.to_projective() - } else if bool::from(rhs.is_zero()) { - self.to_projective() + if bool::from(self.is_identity()) { + rhs.to_curve() + } else if bool::from(rhs.is_identity()) { + self.to_curve() } else { if self.x == rhs.x { if self.y == rhs.y { - self.to_projective().double() + self.to_curve().double() } else { - $name::zero() + $name::identity() } } else { let h = rhs.x - self.x; @@ -451,7 +451,7 @@ macro_rules! new_curve_impl { fn mul(self, other: &'b $scalar) -> Self::Output { // TODO: make this faster - let mut acc = $name::zero(); + let mut acc = $name::identity(); // This is a simple double-and-add implementation of point // multiplication, moving from most significant to least @@ -474,7 +474,7 @@ macro_rules! new_curve_impl { } impl CurveAffine for $name_affine { - type Projective = $name; + type Curve = $name; type Scalar = $scalar; type Base = $base; @@ -483,7 +483,7 @@ macro_rules! new_curve_impl { impl_affine_curve_specific!($name, $base, $curve_type); - fn zero() -> Self { + fn identity() -> Self { Self { x: $base::zero(), y: $base::zero(), @@ -491,7 +491,7 @@ macro_rules! new_curve_impl { } } - fn is_zero(&self) -> Choice { + fn is_identity(&self) -> Choice { self.infinity } @@ -501,7 +501,7 @@ macro_rules! new_curve_impl { | self.infinity } - fn to_projective(&self) -> Self::Projective { + fn to_curve(&self) -> Self::Curve { $name { x: self.x, y: self.y, @@ -510,7 +510,7 @@ macro_rules! new_curve_impl { } fn get_xy(&self) -> CtOption<(Self::Base, Self::Base)> { - CtOption::new((self.x, self.y), !self.is_zero()) + CtOption::new((self.x, self.y), !self.is_identity()) } fn from_xy(x: Self::Base, y: Self::Base) -> CtOption { @@ -526,7 +526,7 @@ macro_rules! new_curve_impl { tmp[31] &= 0b0111_1111; $base::from_bytes(&tmp).and_then(|x| { - CtOption::new(Self::zero(), x.ct_is_zero() & (!ysign)).or_else(|| { + CtOption::new(Self::identity(), x.ct_is_zero() & (!ysign)).or_else(|| { let x3 = x.square() * x; (x3 + $name::curve_constant_b()).sqrt().and_then(|y| { let sign = Choice::from(y.to_bytes()[0] & 1); @@ -548,7 +548,7 @@ macro_rules! new_curve_impl { fn to_bytes(&self) -> [u8; 32] { // TODO: not constant time - if bool::from(self.is_zero()) { + if bool::from(self.is_identity()) { [0; 32] } else { let (x, y) = (self.x, self.y); @@ -567,7 +567,7 @@ macro_rules! new_curve_impl { $base::from_bytes(&xbytes).and_then(|x| { $base::from_bytes(&ybytes).and_then(|y| { - CtOption::new(Self::zero(), x.ct_is_zero() & y.ct_is_zero()).or_else(|| { + CtOption::new(Self::identity(), x.ct_is_zero() & y.ct_is_zero()).or_else(|| { let on_curve = (x * x.square() + $name::curve_constant_b()).ct_eq(&y.square()); @@ -586,7 +586,7 @@ macro_rules! new_curve_impl { fn to_bytes_wide(&self) -> [u8; 64] { // TODO: not constant time - if bool::from(self.is_zero()) { + if bool::from(self.is_identity()) { [0; 64] } else { let mut out = [0u8; 64]; @@ -608,7 +608,7 @@ macro_rules! new_curve_impl { impl Default for $name_affine { fn default() -> $name_affine { - $name_affine::zero() + $name_affine::identity() } } @@ -662,7 +662,7 @@ macro_rules! new_curve_impl { type Scalar = $scalar; fn group_zero() -> Self { - Self::zero() + Self::identity() } fn group_add(&mut self, rhs: &Self) { *self = *self + *rhs; @@ -679,7 +679,7 @@ macro_rules! new_curve_impl { macro_rules! impl_projective_curve_specific { ($name:ident, $base:ident, special_a0_b5) => { - fn one() -> Self { + fn generator() -> Self { // NOTE: This is specific to b = 5 const NEGATIVE_ONE: $base = $base::neg(&$base::one()); @@ -720,12 +720,12 @@ macro_rules! impl_projective_curve_specific { z: z3, }; - $name::conditional_select(&tmp, &$name::zero(), self.is_zero()) + $name::conditional_select(&tmp, &$name::identity(), self.is_identity()) } }; ($name:ident, $base:ident, general) => { /// Unimplemented: there is no standard generator for this curve. - fn one() -> Self { + fn generator() -> Self { unimplemented!() } @@ -753,7 +753,7 @@ macro_rules! impl_projective_curve_specific { z: z3, }; - $name::conditional_select(&tmp, &$name::zero(), self.is_zero()) + $name::conditional_select(&tmp, &$name::identity(), self.is_identity()) } }; } @@ -810,7 +810,7 @@ macro_rules! impl_projective_curve_ext { macro_rules! impl_affine_curve_specific { ($name:ident, $base:ident, special_a0_b5) => { - fn one() -> Self { + fn generator() -> Self { // NOTE: This is specific to b = 5 const NEGATIVE_ONE: $base = $base::neg(&$base::from_raw([1, 0, 0, 0])); @@ -825,7 +825,7 @@ macro_rules! impl_affine_curve_specific { }; ($name:ident, $base:ident, general) => { /// Unimplemented: there is no standard generator for this curve. - fn one() -> Self { + fn generator() -> Self { unimplemented!() } }; diff --git a/src/pasta/hashtocurve.rs b/src/pasta/hashtocurve.rs index 2388c1e..c315455 100644 --- a/src/pasta/hashtocurve.rs +++ b/src/pasta/hashtocurve.rs @@ -73,9 +73,9 @@ pub fn hash_to_field( /// Implements a degree 3 isogeny map. pub fn iso_map, I: CurveAffine>( - p: &I::Projective, + p: &I::Curve, iso: &[C::Base; 13], -) -> C::Projective { +) -> C::Curve { // The input and output are in Jacobian coordinates, using the method // in "Avoiding inversions" [WB2019, section 4.3]. @@ -96,14 +96,14 @@ pub fn iso_map, I: CurveAffine>( let xo = num_x * div_y * zo; let yo = num_y * div_x * zo.square(); - C::Projective::new_jacobian(xo, yo, zo).unwrap() + C::Curve::new_jacobian(xo, yo, zo).unwrap() } pub fn map_to_curve_simple_swu, I: CurveAffine>( u: &F, theta: F, z: F, -) -> I::Projective { +) -> I::Curve { // 1. tv1 = inv0(Z^2 * u^4 + Z * u^2) // 2. x1 = (-B / A) * (1 + tv1) // 3. If tv1 == 0, set x1 = B / (Z * A) @@ -171,5 +171,5 @@ pub fn map_to_curve_simple_swu, I: CurveAf (u.get_lower_32() % 2).ct_eq(&(y.get_lower_32() % 2)), ); - I::Projective::new_jacobian(num_x * div, y * div3, div).unwrap() + I::Curve::new_jacobian(num_x * div, y * div3, div).unwrap() } diff --git a/src/pasta/pallas.rs b/src/pasta/pallas.rs index 06fd9c0..ea5de3f 100644 --- a/src/pasta/pallas.rs +++ b/src/pasta/pallas.rs @@ -91,11 +91,11 @@ fn test_iso_map_identity() { .unwrap(); let r = (r * -Fq::one()) + r; assert!(bool::from(r.is_on_curve())); - assert!(bool::from(r.is_zero())); + assert!(bool::from(r.is_identity())); let p = super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r, &Ep::ISOGENY_CONSTANTS); assert!(bool::from(p.is_on_curve())); - assert!(bool::from(p.is_zero())); + assert!(bool::from(p.is_identity())); } #[test] @@ -157,5 +157,5 @@ fn test_hash_to_curve() { let p = (p * -Fq::one()) + p; assert!(bool::from(p.is_on_curve())); - assert!(bool::from(p.is_zero())); + assert!(bool::from(p.is_identity())); } diff --git a/src/plonk/lookup/prover.rs b/src/plonk/lookup/prover.rs index 5abe772..1eee099 100644 --- a/src/plonk/lookup/prover.rs +++ b/src/plonk/lookup/prover.rs @@ -87,7 +87,7 @@ impl Argument { ) -> Result, Error> where C: CurveAffine, - C::Projective: Mul + MulAssign, + C::Curve: Mul + MulAssign, { // Closure to get values of expressions and compress them let compress_expressions = |expressions: &[Expression]| { diff --git a/src/plonk/prover.rs b/src/plonk/prover.rs index 8d1c055..f9f1e3a 100644 --- a/src/plonk/prover.rs +++ b/src/plonk/prover.rs @@ -52,11 +52,9 @@ pub fn create_proof, ConcreteCircuit: Circ .iter() .map(|poly| params.commit_lagrange(poly, Blind::default())) .collect(); - let mut instance_commitments = vec![C::zero(); instance_commitments_projective.len()]; - C::Projective::batch_to_affine( - &instance_commitments_projective, - &mut instance_commitments, - ); + let mut instance_commitments = + vec![C::identity(); instance_commitments_projective.len()]; + C::Curve::batch_normalize(&instance_commitments_projective, &mut instance_commitments); let instance_commitments = instance_commitments; drop(instance_commitments_projective); metrics::counter!("instance_commitments", instance_commitments.len() as u64); @@ -206,8 +204,8 @@ pub fn create_proof, ConcreteCircuit: Circ .zip(advice_blinds.iter()) .map(|(poly, blind)| params.commit_lagrange(poly, *blind)) .collect(); - let mut advice_commitments = vec![C::zero(); advice_commitments_projective.len()]; - C::Projective::batch_to_affine(&advice_commitments_projective, &mut advice_commitments); + let mut advice_commitments = vec![C::identity(); advice_commitments_projective.len()]; + C::Curve::batch_normalize(&advice_commitments_projective, &mut advice_commitments); let advice_commitments = advice_commitments; drop(advice_commitments_projective); metrics::counter!("advice_commitments", advice_commitments.len() as u64); diff --git a/src/plonk/vanishing/prover.rs b/src/plonk/vanishing/prover.rs index 2e0eccc..bf8094e 100644 --- a/src/plonk/vanishing/prover.rs +++ b/src/plonk/vanishing/prover.rs @@ -50,8 +50,8 @@ impl Argument { .zip(h_blinds.iter()) .map(|(h_piece, blind)| params.commit(&h_piece, *blind)) .collect(); - let mut h_commitments = vec![C::zero(); h_commitments_projective.len()]; - C::Projective::batch_to_affine(&h_commitments_projective, &mut h_commitments); + let mut h_commitments = vec![C::identity(); h_commitments_projective.len()]; + C::Curve::batch_normalize(&h_commitments_projective, &mut h_commitments); let h_commitments = h_commitments; // Hash each h(X) piece diff --git a/src/poly/commitment.rs b/src/poly/commitment.rs index c827219..5bbc350 100644 --- a/src/poly/commitment.rs +++ b/src/poly/commitment.rs @@ -60,7 +60,7 @@ impl Params { let g = { let mut g = Vec::with_capacity(n as usize); - g.resize(n as usize, C::zero()); + g.resize(n as usize, C::identity()); parallelize(&mut g, move |g, start| { let mut hasher = Blake2bParams::new() @@ -87,7 +87,7 @@ impl Params { for _ in k..C::Scalar::S { alpha_inv = alpha_inv.square(); } - let mut g_lagrange_projective = g.iter().map(|g| g.to_projective()).collect::>(); + let mut g_lagrange_projective = g.iter().map(|g| g.to_curve()).collect::>(); best_fft(&mut g_lagrange_projective, alpha_inv, k); let minv = C::Scalar::TWO_INV.pow_vartime(&[k as u64, 0, 0, 0]); parallelize(&mut g_lagrange_projective, |g, _| { @@ -97,9 +97,9 @@ impl Params { }); let g_lagrange = { - let mut g_lagrange = vec![C::zero(); n as usize]; + let mut g_lagrange = vec![C::identity(); n as usize]; parallelize(&mut g_lagrange, |g_lagrange, starts| { - C::Projective::batch_to_affine( + C::Curve::batch_normalize( &g_lagrange_projective[starts..(starts + g_lagrange.len())], g_lagrange, ); @@ -141,11 +141,7 @@ impl Params { /// This computes a commitment to a polynomial described by the provided /// slice of coefficients. The commitment will be blinded by the blinding /// factor `r`. - pub fn commit( - &self, - poly: &Polynomial, - r: Blind, - ) -> C::Projective { + pub fn commit(&self, poly: &Polynomial, r: Blind) -> C::Curve { metrics::increment_counter!("multiexp", "size" => format!("{}", poly.len() + 1), "fn" => "commit"); let mut tmp_scalars = Vec::with_capacity(poly.len() + 1); let mut tmp_bases = Vec::with_capacity(poly.len() + 1); @@ -166,7 +162,7 @@ impl Params { &self, poly: &Polynomial, r: Blind, - ) -> C::Projective { + ) -> C::Curve { metrics::increment_counter!("multiexp", "size" => format!("{}", poly.len() + 1), "fn" => "commit_lagrange"); let mut tmp_scalars = Vec::with_capacity(poly.len() + 1); let mut tmp_bases = Vec::with_capacity(poly.len() + 1); diff --git a/src/poly/commitment/msm.rs b/src/poly/commitment/msm.rs index 75d7b25..090fbb9 100644 --- a/src/poly/commitment/msm.rs +++ b/src/poly/commitment/msm.rs @@ -144,6 +144,6 @@ impl<'a, C: CurveAffine> MSM<'a, C> { assert_eq!(scalars.len(), len); metrics::increment_counter!("multiexp", "size" => format!("{}", len), "fn" => "MSM::eval"); - bool::from(best_multiexp(&scalars, &bases).is_zero()) + bool::from(best_multiexp(&scalars, &bases).is_identity()) } } diff --git a/src/poly/commitment/prover.rs b/src/poly/commitment/prover.rs index 4710821..71995b5 100644 --- a/src/poly/commitment/prover.rs +++ b/src/poly/commitment/prover.rs @@ -152,8 +152,8 @@ fn parallel_generator_collapse(g: &mut [C], challenge: C::Scalar let g_hi = &g_hi[start..]; let mut tmp = Vec::with_capacity(g_lo.len()); for (g_lo, g_hi) in g_lo.iter().zip(g_hi.iter()) { - tmp.push(g_lo.to_projective() + &(*g_hi * challenge)); + tmp.push(g_lo.to_curve() + &(*g_hi * challenge)); } - C::Projective::batch_to_affine(&tmp, g_lo); + C::Curve::batch_normalize(&tmp, g_lo); }); } From 082d66d6e7e9e20757efdb1d519f85783fcab699 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 22 Feb 2021 18:41:41 +0000 Subject: [PATCH 3/5] pasta: Reorganize the curve macro This will make the migration to group easier to review. --- src/pasta/curves.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pasta/curves.rs b/src/pasta/curves.rs index 72eaa05..9a2b9db 100644 --- a/src/pasta/curves.rs +++ b/src/pasta/curves.rs @@ -95,6 +95,11 @@ macro_rules! new_curve_impl { $name::curve_constant_b() } + fn new_jacobian(x: Self::Base, y: Self::Base, z: Self::Base) -> CtOption { + let p = $name { x, y, z }; + CtOption::new(p, p.is_on_curve()) + } + fn jacobian_coordinates(&self) -> ($base, $base, $base) { (self.x, self.y, self.z) } @@ -148,11 +153,6 @@ macro_rules! new_curve_impl { *q = $name_affine::conditional_select(&q, &$name_affine::identity(), skip); } } - - fn new_jacobian(x: Self::Base, y: Self::Base, z: Self::Base) -> CtOption { - let p = $name { x, y, z }; - CtOption::new(p, p.is_on_curve()) - } } impl<'a> From<&'a $name_affine> for $name { From 55fb581f1769bc11c9d000b028474ed6a2a06cd9 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 22 Feb 2021 18:58:50 +0000 Subject: [PATCH 4/5] Define hash-to-curve over Curve, not CurveAffine This removes an unnecessary layer of indirection from the type system, and ensures that these APIs depend on the halo2-specific trait with the extensions we require. --- src/arithmetic/curves.rs | 9 ++++++--- src/pasta/curves.rs | 25 +++++++++++-------------- src/pasta/hashtocurve.rs | 16 ++++++++-------- src/pasta/pallas.rs | 17 ++++++----------- src/pasta/vesta.rs | 8 +++----- 5 files changed, 34 insertions(+), 41 deletions(-) diff --git a/src/arithmetic/curves.rs b/src/arithmetic/curves.rs index ef1ba4f..21da4f7 100644 --- a/src/arithmetic/curves.rs +++ b/src/arithmetic/curves.rs @@ -84,9 +84,12 @@ pub trait Curve: /// # Example /// /// ``` - /// use halo2::arithmetic::{Curve, CurveAffine}; - /// fn pedersen_commitment(x: C::Scalar, r: C::Scalar) -> C { - /// let hasher = C::Curve::hash_to_curve("z.cash:example_pedersen_commitment"); + /// use halo2::arithmetic::Curve; + /// fn pedersen_commitment( + /// x: ::Scalar, + /// r: ::Scalar, + /// ) -> C::Affine { + /// let hasher = C::hash_to_curve("z.cash:example_pedersen_commitment"); /// let g = hasher(b"g"); /// let h = hasher(b"h"); /// (g * x + &(h * r)).to_affine() diff --git a/src/pasta/curves.rs b/src/pasta/curves.rs index 9a2b9db..fe266cc 100644 --- a/src/pasta/curves.rs +++ b/src/pasta/curves.rs @@ -11,7 +11,7 @@ use super::{Fp, Fq}; use crate::arithmetic::{Curve, CurveAffine, FieldExt, Group}; macro_rules! new_curve_impl { - (($($privacy:tt)*), $name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, $scalar:ident, $blake2b_personalization:literal, + (($($privacy:tt)*), $name:ident, $name_affine:ident, $iso:ident, $base:ident, $scalar:ident, $blake2b_personalization:literal, $curve_id:literal, $a_raw:expr, $b_raw:expr, $curve_type:ident) => { /// Represents a point in the projective coordinate space. #[derive(Copy, Clone, Debug)] @@ -85,7 +85,7 @@ macro_rules! new_curve_impl { $name_affine::conditional_select(&tmp, &$name_affine::identity(), zinv.ct_is_zero()) } - impl_projective_curve_ext!($name, $name_affine, $iso_affine, $base, $curve_type); + impl_projective_curve_ext!($name, $name_affine, $iso, $base, $curve_type); fn a() -> Self::Base { $name::curve_constant_a() @@ -759,29 +759,26 @@ macro_rules! impl_projective_curve_specific { } macro_rules! impl_projective_curve_ext { - ($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, special_a0_b5) => { + ($name:ident, $name_affine:ident, $iso:ident, $base:ident, special_a0_b5) => { fn hash_to_curve<'a>(domain_prefix: &'a str) -> Box Self + 'a> { use super::hashtocurve; Box::new(move |message| { let mut us = [Field::zero(); 2]; hashtocurve::hash_to_field($name_affine::CURVE_ID, domain_prefix, message, &mut us); - let q0 = hashtocurve::map_to_curve_simple_swu::<$base, $name_affine, $iso_affine>( + let q0 = hashtocurve::map_to_curve_simple_swu::<$base, $name, $iso>( &us[0], $name::THETA, $name::Z, ); - let q1 = hashtocurve::map_to_curve_simple_swu::<$base, $name_affine, $iso_affine>( + let q1 = hashtocurve::map_to_curve_simple_swu::<$base, $name, $iso>( &us[1], $name::THETA, $name::Z, ); let r = q0 + &q1; debug_assert!(bool::from(r.is_on_curve())); - hashtocurve::iso_map::<$base, $name_affine, $iso_affine>( - &r, - &$name::ISOGENY_CONSTANTS, - ) + hashtocurve::iso_map::<$base, $name, $iso>(&r, &$name::ISOGENY_CONSTANTS) }) } @@ -795,7 +792,7 @@ macro_rules! impl_projective_curve_ext { } } }; - ($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, general) => { + ($name:ident, $name_affine:ident, $iso:ident, $base:ident, general) => { /// Unimplemented: hashing to this curve is not supported fn hash_to_curve<'a>(_domain_prefix: &'a str) -> Box Self + 'a> { unimplemented!() @@ -835,7 +832,7 @@ new_curve_impl!( (pub), Ep, EpAffine, - IsoEpAffine, + IsoEp, Fp, Fq, b"halo2_____pallas", @@ -848,7 +845,7 @@ new_curve_impl!( (pub), Eq, EqAffine, - IsoEqAffine, + IsoEq, Fq, Fp, b"halo2______vesta", @@ -861,7 +858,7 @@ new_curve_impl!( (pub(crate)), IsoEp, IsoEpAffine, - EpAffine, + Ep, Fp, Fq, b"halo2_iso_pallas", @@ -879,7 +876,7 @@ new_curve_impl!( (pub(crate)), IsoEq, IsoEqAffine, - EqAffine, + Eq, Fq, Fp, b"halo2__iso_vesta", diff --git a/src/pasta/hashtocurve.rs b/src/pasta/hashtocurve.rs index c315455..d3acfe8 100644 --- a/src/pasta/hashtocurve.rs +++ b/src/pasta/hashtocurve.rs @@ -3,7 +3,7 @@ use subtle::ConstantTimeEq; -use crate::arithmetic::{Curve, CurveAffine, FieldExt}; +use crate::arithmetic::{Curve, FieldExt}; /// Hashes over a message and writes the output to all of `buf`. pub fn hash_to_field( @@ -72,10 +72,10 @@ pub fn hash_to_field( } /// Implements a degree 3 isogeny map. -pub fn iso_map, I: CurveAffine>( - p: &I::Curve, +pub fn iso_map, I: Curve>( + p: &I, iso: &[C::Base; 13], -) -> C::Curve { +) -> C { // The input and output are in Jacobian coordinates, using the method // in "Avoiding inversions" [WB2019, section 4.3]. @@ -96,14 +96,14 @@ pub fn iso_map, I: CurveAffine>( let xo = num_x * div_y * zo; let yo = num_y * div_x * zo.square(); - C::Curve::new_jacobian(xo, yo, zo).unwrap() + C::new_jacobian(xo, yo, zo).unwrap() } -pub fn map_to_curve_simple_swu, I: CurveAffine>( +pub fn map_to_curve_simple_swu, I: Curve>( u: &F, theta: F, z: F, -) -> I::Curve { +) -> I { // 1. tv1 = inv0(Z^2 * u^4 + Z * u^2) // 2. x1 = (-B / A) * (1 + tv1) // 3. If tv1 == 0, set x1 = B / (Z * A) @@ -171,5 +171,5 @@ pub fn map_to_curve_simple_swu, I: CurveAf (u.get_lower_32() % 2).ct_eq(&(y.get_lower_32() % 2)), ); - I::Curve::new_jacobian(num_x * div, y * div3, div).unwrap() + I::new_jacobian(num_x * div, y * div3, div).unwrap() } diff --git a/src/pasta/pallas.rs b/src/pasta/pallas.rs index ea5de3f..729b264 100644 --- a/src/pasta/pallas.rs +++ b/src/pasta/pallas.rs @@ -42,8 +42,7 @@ fn test_iso_map() { ]), ) .unwrap(); - let p = - super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r, &Ep::ISOGENY_CONSTANTS); + let p = super::hashtocurve::iso_map::<_, Point, super::IsoEp>(&r, &Ep::ISOGENY_CONSTANTS); let (x, y, z) = p.jacobian_coordinates(); assert!( format!("{:?}", x) == "0x318cc15f281662b3f26d0175cab97b924870c837879cac647e877be51a85e898" @@ -58,8 +57,7 @@ fn test_iso_map() { // check that iso_map([2] r) = [2] iso_map(r) let r2 = r.double(); assert!(bool::from(r2.is_on_curve())); - let p2 = - super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r2, &Ep::ISOGENY_CONSTANTS); + let p2 = super::hashtocurve::iso_map::<_, Point, super::IsoEp>(&r2, &Ep::ISOGENY_CONSTANTS); assert!(bool::from(p2.is_on_curve())); assert!(p2 == p.double()); } @@ -92,8 +90,7 @@ fn test_iso_map_identity() { let r = (r * -Fq::one()) + r; assert!(bool::from(r.is_on_curve())); assert!(bool::from(r.is_identity())); - let p = - super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r, &Ep::ISOGENY_CONSTANTS); + let p = super::hashtocurve::iso_map::<_, Point, super::IsoEp>(&r, &Ep::ISOGENY_CONSTANTS); assert!(bool::from(p.is_on_curve())); assert!(bool::from(p.is_identity())); } @@ -101,12 +98,11 @@ fn test_iso_map_identity() { #[test] fn test_map_to_curve_simple_swu() { use crate::arithmetic::Curve; - use crate::pasta::curves::{IsoEp, IsoEpAffine}; + use crate::pasta::curves::IsoEp; use crate::pasta::hashtocurve::map_to_curve_simple_swu; // The zero input is a special case. - let p: IsoEp = - map_to_curve_simple_swu::(&Fp::zero(), Ep::THETA, Ep::Z); + let p: IsoEp = map_to_curve_simple_swu::(&Fp::zero(), Ep::THETA, Ep::Z); let (x, y, z) = p.jacobian_coordinates(); println!("{:?}", p); assert!( @@ -119,8 +115,7 @@ fn test_map_to_curve_simple_swu() { format!("{:?}", z) == "0x054b3ba10416dc104157b1318534a19d5d115472da7d746f8a5f250cd8cdef36" ); - let p: IsoEp = - map_to_curve_simple_swu::(&Fp::one(), Ep::THETA, Ep::Z); + let p: IsoEp = map_to_curve_simple_swu::(&Fp::one(), Ep::THETA, Ep::Z); let (x, y, z) = p.jacobian_coordinates(); println!("{:?}", p); assert!( diff --git a/src/pasta/vesta.rs b/src/pasta/vesta.rs index be387c2..d41d60f 100644 --- a/src/pasta/vesta.rs +++ b/src/pasta/vesta.rs @@ -17,12 +17,11 @@ pub type Affine = EqAffine; #[test] fn test_map_to_curve_simple_swu() { use crate::arithmetic::Curve; - use crate::pasta::curves::{IsoEq, IsoEqAffine}; + use crate::pasta::curves::IsoEq; use crate::pasta::hashtocurve::map_to_curve_simple_swu; // The zero input is a special case. - let p: IsoEq = - map_to_curve_simple_swu::(&Fq::zero(), Eq::THETA, Eq::Z); + let p: IsoEq = map_to_curve_simple_swu::(&Fq::zero(), Eq::THETA, Eq::Z); let (x, y, z) = p.jacobian_coordinates(); println!("{:?}", p); assert!( @@ -35,8 +34,7 @@ fn test_map_to_curve_simple_swu() { format!("{:?}", z) == "0x0b851e9e579403a76df1100f556e1f226e5656bdf38f3bf8601d8a3a9a15890b" ); - let p: IsoEq = - map_to_curve_simple_swu::(&Fq::one(), Eq::THETA, Eq::Z); + let p: IsoEq = map_to_curve_simple_swu::(&Fq::one(), Eq::THETA, Eq::Z); let (x, y, z) = p.jacobian_coordinates(); println!("{:?}", p); assert!( From b4ed5295feb7ee28696fbb3ab772d5b1dcedfc0f Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 22 Feb 2021 19:02:53 +0000 Subject: [PATCH 5/5] Migrate to group traits The `Curve` trait is now `CurveExt: group::prime::PrimeCurve`, and `CurveAffine` is now `CurveAffine: group::prime::PrimeCurveAffine`. There is no `CurveAffine` trait in `group`, and it's a widely-used trait in this crate, so we don't rename it to `CurveAffineExt`. --- Cargo.toml | 1 + benches/hashtocurve.rs | 2 +- examples/performance_model.rs | 3 +- src/arithmetic.rs | 1 + src/arithmetic/curves.rs | 124 ++++--------------------- src/pasta.rs | 3 +- src/pasta/curves.rs | 156 +++++++++++++++++++++++--------- src/pasta/hashtocurve.rs | 6 +- src/pasta/pallas.rs | 11 ++- src/pasta/vesta.rs | 4 +- src/plonk.rs | 5 +- src/plonk/keygen.rs | 3 +- src/plonk/lookup/prover.rs | 5 +- src/plonk/permutation/keygen.rs | 3 +- src/plonk/permutation/prover.rs | 3 +- src/plonk/prover.rs | 3 +- src/plonk/vanishing/prover.rs | 4 +- src/poly/commitment.rs | 23 +++-- src/poly/commitment/msm.rs | 3 +- src/poly/commitment/prover.rs | 5 +- src/poly/commitment/verifier.rs | 3 +- src/poly/multiopen.rs | 4 +- src/poly/multiopen/prover.rs | 3 +- src/transcript.rs | 6 +- 24 files changed, 200 insertions(+), 184 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7cd9d62..d60b76c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ backtrace = { version = "0.3", optional = true } subtle = "2.3" crossbeam-utils = "0.8" ff = "0.9" +group = "0.9" metrics = "0.14.2" num_cpus = "1.13" rand = "0.8" diff --git a/benches/hashtocurve.rs b/benches/hashtocurve.rs index cd3e987..7e6af30 100644 --- a/benches/hashtocurve.rs +++ b/benches/hashtocurve.rs @@ -2,7 +2,7 @@ use criterion::{criterion_group, criterion_main, Criterion}; -use halo2::arithmetic::Curve; +use halo2::arithmetic::CurveExt; use halo2::pasta::{pallas, vesta}; fn criterion_benchmark(c: &mut Criterion) { diff --git a/examples/performance_model.rs b/examples/performance_model.rs index 5f03efb..8cd9c53 100644 --- a/examples/performance_model.rs +++ b/examples/performance_model.rs @@ -1,5 +1,6 @@ +use group::Curve; use halo2::{ - arithmetic::{Curve, FieldExt}, + arithmetic::FieldExt, model::ModelRecorder, pasta::{EqAffine, Fp}, plonk::*, diff --git a/src/arithmetic.rs b/src/arithmetic.rs index bee2b04..31c972b 100644 --- a/src/arithmetic.rs +++ b/src/arithmetic.rs @@ -3,6 +3,7 @@ use crossbeam_utils::thread; pub use ff::Field; +use group::Group as _; mod curves; mod fields; diff --git a/src/arithmetic/curves.rs b/src/arithmetic/curves.rs index 21da4f7..97a9527 100644 --- a/src/arithmetic/curves.rs +++ b/src/arithmetic/curves.rs @@ -2,8 +2,8 @@ //! write code that generalizes over a pair of groups. use core::cmp; -use core::fmt::Debug; -use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; +use core::ops::{Add, Sub}; +use group::prime::{PrimeCurve, PrimeCurveAffine}; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption}; use super::{FieldExt, Group}; @@ -13,66 +13,26 @@ use std::io::{self, Read, Write}; /// This trait is a common interface for dealing with elements of an elliptic /// curve group in a "projective" form, where that arithmetic is usually more /// efficient. -pub trait Curve: - Sized +pub trait CurveExt: + PrimeCurve + + group::Group::ScalarExt> + Default - + Copy - + Clone - + Send - + Sync - + 'static - + Debug - + Add - + Sub - + Mul<::Scalar, Output = Self> - + Neg - + for<'a> Add<&'a Self, Output = Self> - + for<'a> Sub<&'a Self, Output = Self> - + MulAssign<::Scalar> - + AddAssign - + SubAssign - + for<'a> AddAssign<&'a Self> - + for<'a> SubAssign<&'a Self> - + AddAssign<::Affine> - + SubAssign<::Affine> + PartialEq + cmp::Eq + ConditionallySelectable + ConstantTimeEq - + From<::Affine> - + Group::Scalar> + + From<::Affine> + + Group::Scalar> { - /// The representation of a point on this curve in the affine coordinate space. - type Affine: CurveAffine::Scalar, Base = ::Base> - + Add - + Sub - + Mul<::Scalar, Output = Self> - + Neg::Affine> - + From; /// The scalar field of this elliptic curve. - type Scalar: FieldExt; + type ScalarExt: FieldExt; /// The base field over which this elliptic curve is constructed. type Base: FieldExt; - /// Obtains the additive identity. - fn identity() -> Self; - - /// Obtains the base point of the curve. - fn generator() -> Self; - - /// Doubles this element. - fn double(&self) -> Self; - - /// Returns whether or not this element is the identity. - fn is_identity(&self) -> Choice; - /// Apply the curve endomorphism by multiplying the x-coordinate /// by an element of multiplicative order 3. fn endo(&self) -> Self; - /// Converts this element into its affine form. - fn to_affine(&self) -> Self::Affine; - /// Return the Jacobian coordinates of this point. fn jacobian_coordinates(&self) -> (Self::Base, Self::Base, Self::Base); @@ -84,10 +44,10 @@ pub trait Curve: /// # Example /// /// ``` - /// use halo2::arithmetic::Curve; - /// fn pedersen_commitment( - /// x: ::Scalar, - /// r: ::Scalar, + /// use halo2::arithmetic::CurveExt; + /// fn pedersen_commitment( + /// x: C::ScalarExt, + /// r: C::ScalarExt, /// ) -> C::Affine { /// let hasher = C::hash_to_curve("z.cash:example_pedersen_commitment"); /// let g = hasher(b"g"); @@ -101,10 +61,6 @@ pub trait Curve: /// always be true unless an "unchecked" API was used. fn is_on_curve(&self) -> Choice; - /// Converts many elements into their affine form. Panics if the - /// sizes of the slices are different. - fn batch_normalize(v: &[Self], target: &mut [Self::Affine]); - /// Returns the curve constant a. fn a() -> Self::Base; @@ -119,36 +75,16 @@ pub trait Curve: /// This trait is the affine counterpart to `Curve` and is used for /// serialization, storage in memory, and inspection of $x$ and $y$ coordinates. pub trait CurveAffine: - Sized + PrimeCurveAffine::ScalarExt> + Default - + Copy - + Clone - + Send - + Sync - + 'static - + Debug - + Add::Curve> - + Sub::Curve> - + Mul<::Scalar, Output = ::Curve> - + Neg - + PartialEq - + cmp::Eq + + Add::Curve> + + Sub::Curve> + ConditionallySelectable + ConstantTimeEq - + From<::Curve> + + From<::Curve> { - /// The representation of a point on this curve in the projective coordinate space. - type Curve: Curve< - Affine = Self, - Scalar = ::Scalar, - Base = ::Base, - > + Mul<::Scalar, Output = ::Curve> - + MulAssign<::Scalar> - + AddAssign - + SubAssign - + From; /// The scalar field of this elliptic curve. - type Scalar: FieldExt; + type ScalarExt: FieldExt; /// The base field over which this elliptic curve is constructed. type Base: FieldExt; @@ -159,18 +95,6 @@ pub trait CurveAffine: /// CURVE_ID used for hash-to-curve. const CURVE_ID: &'static str; - /// Obtains the additive identity. - fn identity() -> Self; - - /// Obtains the base point of the curve. - fn generator() -> Self; - - /// Returns whether or not this element is the identity. - fn is_identity(&self) -> Choice; - - /// Converts this element into its projective form. - fn to_curve(&self) -> Self::Curve; - /// Gets the $(x, y)$ coordinates of this point. fn get_xy(&self) -> CtOption<(Self::Base, Self::Base)>; @@ -182,27 +106,19 @@ pub trait CurveAffine: /// always be true unless an "unchecked" API was used. fn is_on_curve(&self) -> Choice; - /// Attempts to obtain a group element from its compressed 32-byte little - /// endian representation. - fn from_bytes(bytes: &[u8; 32]) -> CtOption; - /// Reads a compressed element from the buffer and attempts to parse it /// using `from_bytes`. fn read(reader: &mut R) -> io::Result { - let mut compressed = [0u8; 32]; - reader.read_exact(&mut compressed[..])?; + let mut compressed = Self::Repr::default(); + reader.read_exact(compressed.as_mut())?; Option::from(Self::from_bytes(&compressed)) .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "invalid point encoding in proof")) } - /// Obtains the compressed, 32-byte little endian representation of this - /// element. - fn to_bytes(&self) -> [u8; 32]; - /// Writes an element in compressed form to the buffer. fn write(&self, writer: &mut W) -> io::Result<()> { let compressed = self.to_bytes(); - writer.write_all(&compressed[..]) + writer.write_all(compressed.as_ref()) } /// Attempts to obtain a group element from its uncompressed 64-byte little diff --git a/src/pasta.rs b/src/pasta.rs index 3046bf4..4f170c6 100644 --- a/src/pasta.rs +++ b/src/pasta.rs @@ -15,7 +15,8 @@ pub use fields::*; #[test] fn test_endo_consistency() { - use crate::arithmetic::{Curve, FieldExt}; + use crate::arithmetic::{CurveExt, FieldExt}; + use group::Group; let a = pallas::Point::generator(); assert_eq!(a * pallas::Scalar::ZETA, a.endo()); diff --git a/src/pasta/curves.rs b/src/pasta/curves.rs index fe266cc..552944e 100644 --- a/src/pasta/curves.rs +++ b/src/pasta/curves.rs @@ -3,12 +3,18 @@ use core::cmp; use core::fmt::Debug; +use core::iter::Sum; use core::ops::{Add, Mul, Neg, Sub}; use ff::Field; +use group::{ + prime::{PrimeCurve, PrimeCurveAffine, PrimeGroup}, + Curve as _, Group as _, GroupEncoding, +}; +use rand::RngCore; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption}; use super::{Fp, Fq}; -use crate::arithmetic::{Curve, CurveAffine, FieldExt, Group}; +use crate::arithmetic::{CurveAffine, CurveExt, FieldExt, Group}; macro_rules! new_curve_impl { (($($privacy:tt)*), $name:ident, $name_affine:ident, $iso:ident, $base:ident, $scalar:ident, $blake2b_personalization:literal, @@ -50,10 +56,21 @@ macro_rules! new_curve_impl { } } - impl Curve for $name { - type Affine = $name_affine; + impl group::Group for $name { type Scalar = $scalar; - type Base = $base; + + fn random(mut rng: impl RngCore) -> Self { + loop { + let mut buf = [0; 64]; + rng.fill_bytes(&mut buf); + let p: Option<$name_affine> = $name_affine::from_bytes_wide(&buf).into(); + if let Some(p) = p { + if !bool::from(p.is_identity()) { + break p.to_curve(); + } + } + } + } impl_projective_curve_specific!($name, $base, $curve_type); @@ -68,22 +85,11 @@ macro_rules! new_curve_impl { fn is_identity(&self) -> Choice { self.z.ct_is_zero() } + } - fn to_affine(&self) -> Self::Affine { - let zinv = self.z.invert().unwrap_or($base::zero()); - let zinv2 = zinv.square(); - let x = self.x * zinv2; - let zinv3 = zinv2 * zinv; - let y = self.y * zinv3; - - let tmp = $name_affine { - x, - y, - infinity: Choice::from(0u8), - }; - - $name_affine::conditional_select(&tmp, &$name_affine::identity(), zinv.ct_is_zero()) - } + impl CurveExt for $name { + type ScalarExt = $scalar; + type Base = $base; impl_projective_curve_ext!($name, $name_affine, $iso, $base, $curve_type); @@ -115,8 +121,12 @@ macro_rules! new_curve_impl { .ct_eq(&(z6 * $name::curve_constant_b())) | self.z.ct_is_zero() } + } - fn batch_normalize(p: &[Self], q: &mut [Self::Affine]) { + impl group::Curve for $name { + type AffineRepr = $name_affine; + + fn batch_normalize(p: &[Self], q: &mut [Self::AffineRepr]) { assert_eq!(p.len(), q.len()); let mut acc = $base::one(); @@ -153,6 +163,45 @@ macro_rules! new_curve_impl { *q = $name_affine::conditional_select(&q, &$name_affine::identity(), skip); } } + + fn to_affine(&self) -> Self::AffineRepr { + let zinv = self.z.invert().unwrap_or($base::zero()); + let zinv2 = zinv.square(); + let x = self.x * zinv2; + let zinv3 = zinv2 * zinv; + let y = self.y * zinv3; + + let tmp = $name_affine { + x, + y, + infinity: Choice::from(0u8), + }; + + $name_affine::conditional_select(&tmp, &$name_affine::identity(), zinv.ct_is_zero()) + } + } + + impl PrimeGroup for $name {} + + impl PrimeCurve for $name { + type Affine = $name_affine; + } + + impl GroupEncoding for $name { + type Repr = [u8; 32]; + + fn from_bytes(bytes: &Self::Repr) -> CtOption { + $name_affine::from_bytes(bytes).map(Self::from) + } + + fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption { + // We can't avoid curve checks when parsing a compressed encoding. + $name_affine::from_bytes(bytes).map(Self::from) + } + + fn to_bytes(&self) -> Self::Repr { + $name_affine::from(self).to_bytes() + } } impl<'a> From<&'a $name_affine> for $name { @@ -233,6 +282,18 @@ macro_rules! new_curve_impl { } } + impl Sum for $name + where + T: core::borrow::Borrow<$name>, + { + fn sum(iter: I) -> Self + where + I: Iterator, + { + iter.fold(Self::identity(), |acc, item| acc + item.borrow()) + } + } + impl<'a, 'b> Add<&'a $name> for &'b $name { type Output = $name; @@ -473,13 +534,9 @@ macro_rules! new_curve_impl { } } - impl CurveAffine for $name_affine { + impl PrimeCurveAffine for $name_affine { type Curve = $name; type Scalar = $scalar; - type Base = $base; - - const BLAKE2B_PERSONALIZATION: &'static [u8; 16] = $blake2b_personalization; - const CURVE_ID: &'static str = $curve_id; impl_affine_curve_specific!($name, $base, $curve_type); @@ -495,12 +552,6 @@ macro_rules! new_curve_impl { self.infinity } - fn is_on_curve(&self) -> Choice { - // y^2 - x^3 - ax ?= b - (self.y.square() - (self.x.square() + &$name::curve_constant_a()) * self.x).ct_eq(&$name::curve_constant_b()) - | self.infinity - } - fn to_curve(&self) -> Self::Curve { $name { x: self.x, @@ -508,17 +559,10 @@ macro_rules! new_curve_impl { z: $base::conditional_select(&$base::one(), &$base::zero(), self.infinity), } } + } - fn get_xy(&self) -> CtOption<(Self::Base, Self::Base)> { - CtOption::new((self.x, self.y), !self.is_identity()) - } - - fn from_xy(x: Self::Base, y: Self::Base) -> CtOption { - let p = $name_affine { - x, y, infinity: 0u8.into() - }; - CtOption::new(p, p.is_on_curve()) - } + impl GroupEncoding for $name_affine { + type Repr = [u8; 32]; fn from_bytes(bytes: &[u8; 32]) -> CtOption { let mut tmp = *bytes; @@ -546,6 +590,11 @@ macro_rules! new_curve_impl { }) } + fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption { + // We can't avoid curve checks when parsing a compressed encoding. + Self::from_bytes(bytes) + } + fn to_bytes(&self) -> [u8; 32] { // TODO: not constant time if bool::from(self.is_identity()) { @@ -558,6 +607,31 @@ macro_rules! new_curve_impl { xbytes } } + } + + impl CurveAffine for $name_affine { + type ScalarExt = $scalar; + type Base = $base; + + const BLAKE2B_PERSONALIZATION: &'static [u8; 16] = $blake2b_personalization; + const CURVE_ID: &'static str = $curve_id; + + fn is_on_curve(&self) -> Choice { + // y^2 - x^3 - ax ?= b + (self.y.square() - (self.x.square() + &$name::curve_constant_a()) * self.x).ct_eq(&$name::curve_constant_b()) + | self.infinity + } + + fn get_xy(&self) -> CtOption<(Self::Base, Self::Base)> { + CtOption::new((self.x, self.y), !self.is_identity()) + } + + fn from_xy(x: Self::Base, y: Self::Base) -> CtOption { + let p = $name_affine { + x, y, infinity: 0u8.into() + }; + CtOption::new(p, p.is_on_curve()) + } fn from_bytes_wide(bytes: &[u8; 64]) -> CtOption { let mut xbytes = [0u8; 32]; diff --git a/src/pasta/hashtocurve.rs b/src/pasta/hashtocurve.rs index d3acfe8..3fae7b8 100644 --- a/src/pasta/hashtocurve.rs +++ b/src/pasta/hashtocurve.rs @@ -3,7 +3,7 @@ use subtle::ConstantTimeEq; -use crate::arithmetic::{Curve, FieldExt}; +use crate::arithmetic::{CurveExt, FieldExt}; /// Hashes over a message and writes the output to all of `buf`. pub fn hash_to_field( @@ -72,7 +72,7 @@ pub fn hash_to_field( } /// Implements a degree 3 isogeny map. -pub fn iso_map, I: Curve>( +pub fn iso_map, I: CurveExt>( p: &I, iso: &[C::Base; 13], ) -> C { @@ -99,7 +99,7 @@ pub fn iso_map, I: Curve>( C::new_jacobian(xo, yo, zo).unwrap() } -pub fn map_to_curve_simple_swu, I: Curve>( +pub fn map_to_curve_simple_swu, I: CurveExt>( u: &F, theta: F, z: F, diff --git a/src/pasta/pallas.rs b/src/pasta/pallas.rs index 729b264..c3094ef 100644 --- a/src/pasta/pallas.rs +++ b/src/pasta/pallas.rs @@ -16,7 +16,8 @@ pub type Affine = EpAffine; #[test] fn test_iso_map() { - use crate::arithmetic::Curve; + use crate::arithmetic::CurveExt; + use group::Group; // This is a regression test (it's the same input to iso_map as for hash_to_curve // with domain prefix "z.cash:test", Shake128, and input b"hello"). We don't @@ -64,7 +65,8 @@ fn test_iso_map() { #[test] fn test_iso_map_identity() { - use crate::arithmetic::Curve; + use crate::arithmetic::CurveExt; + use group::Group; let r = super::IsoEp::new_jacobian( Base::from_raw([ @@ -97,7 +99,7 @@ fn test_iso_map_identity() { #[test] fn test_map_to_curve_simple_swu() { - use crate::arithmetic::Curve; + use crate::arithmetic::CurveExt; use crate::pasta::curves::IsoEp; use crate::pasta::hashtocurve::map_to_curve_simple_swu; @@ -131,7 +133,8 @@ fn test_map_to_curve_simple_swu() { #[test] fn test_hash_to_curve() { - use crate::arithmetic::Curve; + use crate::arithmetic::CurveExt; + use group::Group; // This test vector is chosen so that the first map_to_curve_simple_swu takes the gx1 square // "branch" and the second takes the gx1 non-square "branch" (opposite to the Vesta test vector). diff --git a/src/pasta/vesta.rs b/src/pasta/vesta.rs index d41d60f..c958804 100644 --- a/src/pasta/vesta.rs +++ b/src/pasta/vesta.rs @@ -16,7 +16,7 @@ pub type Affine = EqAffine; #[test] fn test_map_to_curve_simple_swu() { - use crate::arithmetic::Curve; + use crate::arithmetic::CurveExt; use crate::pasta::curves::IsoEq; use crate::pasta::hashtocurve::map_to_curve_simple_swu; @@ -50,7 +50,7 @@ fn test_map_to_curve_simple_swu() { #[test] fn test_hash_to_curve() { - use crate::arithmetic::Curve; + use crate::arithmetic::CurveExt; // This test vector is chosen so that the first map_to_curve_simple_swu takes the gx1 non-square // "branch" and the second takes the gx1 square "branch" (opposite to the Pallas test vector). diff --git a/src/plonk.rs b/src/plonk.rs index bb9fd31..95719c4 100644 --- a/src/plonk.rs +++ b/src/plonk.rs @@ -44,7 +44,7 @@ impl VerifyingKey { /// Writes a verifying key to a buffer. pub fn write(&self, writer: &mut W) -> io::Result<()> { for commitment in &self.fixed_commitments { - writer.write_all(&commitment.to_bytes())?; + writer.write_all(commitment.to_bytes().as_ref())?; } for permutation in &self.permutations { permutation.write(writer)?; @@ -190,7 +190,7 @@ type ChallengeX = ChallengeScalar; #[test] fn test_proving() { - use crate::arithmetic::{Curve, FieldExt}; + use crate::arithmetic::FieldExt; use crate::dev::MockProver; use crate::pasta::{EqAffine, Fp}; use crate::poly::{ @@ -199,6 +199,7 @@ fn test_proving() { }; use crate::transcript::{Blake2bRead, Blake2bWrite}; use circuit::{Advice, Column, Fixed}; + use group::Curve; use std::marker::PhantomData; const K: u32 = 5; diff --git a/src/plonk/keygen.rs b/src/plonk/keygen.rs index a206913..18cbafb 100644 --- a/src/plonk/keygen.rs +++ b/src/plonk/keygen.rs @@ -1,10 +1,11 @@ use ff::Field; +use group::Curve; use super::{ circuit::{Advice, Assignment, Circuit, Column, ConstraintSystem, Fixed}, permutation, Error, LagrangeCoeff, Polynomial, ProvingKey, VerifyingKey, }; -use crate::arithmetic::{Curve, CurveAffine}; +use crate::arithmetic::CurveAffine; use crate::poly::{ commitment::{Blind, Params}, EvaluationDomain, Rotation, diff --git a/src/plonk/lookup/prover.rs b/src/plonk/lookup/prover.rs index 1eee099..76693dc 100644 --- a/src/plonk/lookup/prover.rs +++ b/src/plonk/lookup/prover.rs @@ -4,7 +4,7 @@ use super::super::{ }; use super::Argument; use crate::{ - arithmetic::{eval_polynomial, parallelize, BatchInvert, Curve, CurveAffine, FieldExt}, + arithmetic::{eval_polynomial, parallelize, BatchInvert, CurveAffine, FieldExt}, poly::{ commitment::{Blind, Params}, multiopen::ProverQuery, @@ -13,6 +13,7 @@ use crate::{ transcript::TranscriptWrite, }; use ff::Field; +use group::Curve; use std::{ collections::BTreeMap, iter, @@ -86,7 +87,7 @@ impl Argument { transcript: &mut T, ) -> Result, Error> where - C: CurveAffine, + C: CurveAffine, C::Curve: Mul + MulAssign, { // Closure to get values of expressions and compress them diff --git a/src/plonk/permutation/keygen.rs b/src/plonk/permutation/keygen.rs index 072f6c5..dfc1f55 100644 --- a/src/plonk/permutation/keygen.rs +++ b/src/plonk/permutation/keygen.rs @@ -1,8 +1,9 @@ use ff::Field; +use group::Curve; use super::{Argument, ProvingKey, VerifyingKey}; use crate::{ - arithmetic::{Curve, CurveAffine, FieldExt}, + arithmetic::{CurveAffine, FieldExt}, plonk::{circuit::ConstraintSystem, Error}, poly::{ commitment::{Blind, Params}, diff --git a/src/plonk/permutation/prover.rs b/src/plonk/permutation/prover.rs index b0a3f30..eca39a2 100644 --- a/src/plonk/permutation/prover.rs +++ b/src/plonk/permutation/prover.rs @@ -1,10 +1,11 @@ use ff::Field; +use group::Curve; use std::iter; use super::super::circuit::Any; use super::{Argument, ProvingKey}; use crate::{ - arithmetic::{eval_polynomial, parallelize, BatchInvert, Curve, CurveAffine, FieldExt}, + arithmetic::{eval_polynomial, parallelize, BatchInvert, CurveAffine, FieldExt}, plonk::{self, ChallengeBeta, ChallengeGamma, ChallengeX, Error}, poly::{ commitment::{Blind, Params}, diff --git a/src/plonk/prover.rs b/src/plonk/prover.rs index f9f1e3a..e919fd9 100644 --- a/src/plonk/prover.rs +++ b/src/plonk/prover.rs @@ -1,4 +1,5 @@ use ff::Field; +use group::Curve; use std::iter; use super::{ @@ -6,7 +7,7 @@ use super::{ lookup, permutation, vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX, ChallengeY, Error, ProvingKey, }; -use crate::arithmetic::{eval_polynomial, Curve, CurveAffine, FieldExt}; +use crate::arithmetic::{eval_polynomial, CurveAffine, FieldExt}; use crate::poly::{ commitment::{Blind, Params}, multiopen::{self, ProverQuery}, diff --git a/src/plonk/vanishing/prover.rs b/src/plonk/vanishing/prover.rs index bf8094e..441615e 100644 --- a/src/plonk/vanishing/prover.rs +++ b/src/plonk/vanishing/prover.rs @@ -1,6 +1,8 @@ +use group::Curve; + use super::Argument; use crate::{ - arithmetic::{eval_polynomial, Curve, CurveAffine, FieldExt}, + arithmetic::{eval_polynomial, CurveAffine, FieldExt}, plonk::{ChallengeX, ChallengeY, Error}, poly::{ commitment::{Blind, Params}, diff --git a/src/poly/commitment.rs b/src/poly/commitment.rs index 5bbc350..7ed1ac3 100644 --- a/src/poly/commitment.rs +++ b/src/poly/commitment.rs @@ -6,10 +6,10 @@ use blake2b_simd::{Params as Blake2bParams, State as Blake2bState}; use super::{Coeff, LagrangeCoeff, Polynomial}; -use crate::arithmetic::{best_fft, best_multiexp, parallelize, Curve, CurveAffine, FieldExt}; +use crate::arithmetic::{best_fft, best_multiexp, parallelize, CurveAffine, FieldExt, Group}; use ff::{Field, PrimeField}; -use std::convert::TryInto; +use group::{prime::PrimeCurveAffine, Curve}; use std::ops::{Add, AddAssign, Mul, MulAssign}; mod msm; @@ -36,7 +36,10 @@ pub struct Params { impl Params { /// Initializes parameters for the curve, given a random oracle to draw /// points from. - pub fn new(k: u32) -> Self { + pub fn new(k: u32) -> Self + where + ::Curve: Group, + { // This is usually a limitation on the curve, but we also want 32-bit // architectures to be supported. assert!(k < 32); @@ -50,7 +53,9 @@ impl Params { loop { let mut hasher = hasher.clone(); hasher.update(&(trial.to_le_bytes())[..]); - let p = C::from_bytes(&hasher.finalize().as_bytes().try_into().unwrap()); + let mut repr = C::Repr::default(); + repr.as_mut().copy_from_slice(hasher.finalize().as_bytes()); + let p = C::from_bytes(&repr); if bool::from(p.is_some()) { break p.unwrap(); } @@ -83,7 +88,7 @@ impl Params { // Let's evaluate all of the Lagrange basis polynomials // using an inverse FFT. - let mut alpha_inv = C::Scalar::ROOT_OF_UNITY_INV; + let mut alpha_inv = <::Curve as Group>::Scalar::ROOT_OF_UNITY_INV; for _ in k..C::Scalar::S { alpha_inv = alpha_inv.square(); } @@ -191,13 +196,13 @@ impl Params { pub fn write(&self, writer: &mut W) -> io::Result<()> { writer.write_all(&self.k.to_le_bytes())?; for g_element in &self.g { - writer.write_all(&g_element.to_bytes())?; + writer.write_all(g_element.to_bytes().as_ref())?; } for g_lagrange_element in &self.g_lagrange { - writer.write_all(&g_lagrange_element.to_bytes())?; + writer.write_all(g_lagrange_element.to_bytes().as_ref())?; } - writer.write_all(&self.h.to_bytes())?; - writer.write_all(&self.u.to_bytes())?; + writer.write_all(self.h.to_bytes().as_ref())?; + writer.write_all(self.u.to_bytes().as_ref())?; Ok(()) } diff --git a/src/poly/commitment/msm.rs b/src/poly/commitment/msm.rs index 090fbb9..91184a1 100644 --- a/src/poly/commitment/msm.rs +++ b/src/poly/commitment/msm.rs @@ -1,6 +1,7 @@ use super::Params; -use crate::arithmetic::{best_multiexp, parallelize, Curve, CurveAffine}; +use crate::arithmetic::{best_multiexp, parallelize, CurveAffine}; use ff::Field; +use group::Group; /// A multiscalar multiplication in the polynomial commitment scheme #[derive(Debug, Clone)] diff --git a/src/poly/commitment/prover.rs b/src/poly/commitment/prover.rs index 71995b5..db3e97c 100644 --- a/src/poly/commitment/prover.rs +++ b/src/poly/commitment/prover.rs @@ -3,10 +3,11 @@ use ff::Field; use super::super::{Coeff, Polynomial}; use super::{Blind, Params}; use crate::arithmetic::{ - best_multiexp, compute_inner_product, eval_polynomial, parallelize, Curve, CurveAffine, - FieldExt, + best_multiexp, compute_inner_product, eval_polynomial, parallelize, CurveAffine, FieldExt, }; use crate::transcript::{Challenge, ChallengeScalar, TranscriptWrite}; + +use group::Curve; use std::io; /// Create a polynomial commitment opening proof for the polynomial defined diff --git a/src/poly/commitment/verifier.rs b/src/poly/commitment/verifier.rs index da057fd..2665223 100644 --- a/src/poly/commitment/verifier.rs +++ b/src/poly/commitment/verifier.rs @@ -1,10 +1,11 @@ use ff::Field; +use group::Curve; use super::super::Error; use super::{Params, MSM}; use crate::transcript::{Challenge, ChallengeScalar, TranscriptRead}; -use crate::arithmetic::{best_multiexp, BatchInvert, Curve, CurveAffine}; +use crate::arithmetic::{best_multiexp, BatchInvert, CurveAffine}; /// A guard returned by the verifier #[derive(Debug, Clone)] diff --git a/src/poly/multiopen.rs b/src/poly/multiopen.rs index c5937e4..2ed4ee7 100644 --- a/src/poly/multiopen.rs +++ b/src/poly/multiopen.rs @@ -206,8 +206,10 @@ where #[test] fn test_roundtrip() { + use group::Curve; + use super::commitment::{Blind, Params}; - use crate::arithmetic::{eval_polynomial, Curve, FieldExt}; + use crate::arithmetic::{eval_polynomial, FieldExt}; use crate::pasta::{EqAffine, Fp}; const K: u32 = 4; diff --git a/src/poly/multiopen/prover.rs b/src/poly/multiopen/prover.rs index 7cf4703..9dbb647 100644 --- a/src/poly/multiopen/prover.rs +++ b/src/poly/multiopen/prover.rs @@ -7,10 +7,11 @@ use super::{ Query, }; -use crate::arithmetic::{eval_polynomial, kate_division, Curve, CurveAffine, FieldExt}; +use crate::arithmetic::{eval_polynomial, kate_division, CurveAffine, FieldExt}; use crate::transcript::TranscriptWrite; use ff::Field; +use group::Curve; use std::io; use std::marker::PhantomData; diff --git a/src/transcript.rs b/src/transcript.rs index 86052b6..c3da9a9 100644 --- a/src/transcript.rs +++ b/src/transcript.rs @@ -69,8 +69,8 @@ impl Blake2bRead { impl TranscriptRead for Blake2bRead { fn read_point(&mut self) -> io::Result { - let mut compressed = [0u8; 32]; - self.reader.read_exact(&mut compressed[..])?; + let mut compressed = C::Repr::default(); + self.reader.read_exact(compressed.as_mut())?; let point: C = Option::from(C::from_bytes(&compressed)).ok_or_else(|| { io::Error::new(io::ErrorKind::Other, "invalid point encoding in proof") })?; @@ -154,7 +154,7 @@ impl TranscriptWrite for Blake2bWrite { fn write_point(&mut self, point: C) -> io::Result<()> { self.common_point(point)?; let compressed = point.to_bytes(); - self.writer.write_all(&compressed[..]) + self.writer.write_all(compressed.as_ref()) } fn write_scalar(&mut self, scalar: C::Scalar) -> io::Result<()> { self.common_scalar(scalar)?;