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 51a70e8..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; @@ -68,7 +69,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 +111,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 +126,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 +151,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 +161,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 +188,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 +210,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..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,69 +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< - Projective = Self, - Scalar = ::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 zero() -> Self; - - /// Obtains the base point of the curve. - fn one() -> Self; - - /// Doubles this element. - fn double(&self) -> Self; - - /// Returns whether or not this element is the identity. - fn is_zero(&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); @@ -87,9 +44,12 @@ pub trait Curve: /// # Example /// /// ``` - /// 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"); + /// 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"); /// let h = hasher(b"h"); /// (g * x + &(h * r)).to_affine() @@ -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_to_affine(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::Projective> - + Sub::Projective> - + Mul<::Scalar, Output = ::Projective> - + Neg - + PartialEq - + cmp::Eq + + Add::Curve> + + Sub::Curve> + ConditionallySelectable + ConstantTimeEq - + From<::Projective> + + From<::Curve> { - /// The representation of a point on this curve in the projective coordinate space. - type Projective: Curve< - Affine = Self, - Scalar = ::Scalar, - Base = ::Base, - > + Mul<::Scalar, Output = ::Projective> - + 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 zero() -> Self; - - /// Obtains the base point of the curve. - fn one() -> Self; - - /// Returns whether or not this element is the identity. - fn is_zero(&self) -> Choice; - - /// Converts this element into its projective form. - fn to_projective(&self) -> Self::Projective; - /// 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 924ec13..4f170c6 100644 --- a/src/pasta.rs +++ b/src/pasta.rs @@ -15,10 +15,11 @@ 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::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 f22a65b..552944e 100644 --- a/src/pasta/curves.rs +++ b/src/pasta/curves.rs @@ -3,15 +3,21 @@ 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_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)] @@ -50,14 +56,25 @@ macro_rules! new_curve_impl { } } - impl Curve for $name { - type Affine = $name_affine; + impl group::Group for $name { type Scalar = $scalar; - type Base = $base; - impl_projective_curve_specific!($name, $name_affine, $iso_affine, $base, $curve_type); + 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(); + } + } + } + } - fn zero() -> Self { + impl_projective_curve_specific!($name, $base, $curve_type); + + fn identity() -> Self { Self { x: $base::zero(), y: $base::zero(), @@ -65,25 +82,16 @@ macro_rules! new_curve_impl { } } - fn is_zero(&self) -> Choice { + 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; + impl CurveExt for $name { + type ScalarExt = $scalar; + type Base = $base; - let tmp = $name_affine { - x, - y, - infinity: Choice::from(0u8), - }; - - $name_affine::conditional_select(&tmp, &$name_affine::zero(), zinv.ct_is_zero()) - } + impl_projective_curve_ext!($name, $name_affine, $iso, $base, $curve_type); fn a() -> Self::Base { $name::curve_constant_a() @@ -93,6 +101,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) } @@ -108,8 +121,12 @@ macro_rules! new_curve_impl { .ct_eq(&(z6 * $name::curve_constant_b())) | self.z.ct_is_zero() } + } - fn batch_to_affine(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(); @@ -119,7 +136,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 @@ -127,7 +144,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; @@ -143,31 +160,65 @@ 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); } } - 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 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 { 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() } } @@ -184,8 +235,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)) @@ -231,13 +282,25 @@ 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; 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(); @@ -251,7 +314,7 @@ macro_rules! new_curve_impl { if s1 == s2 { self.double() } else { - $name::zero() + $name::identity() } } else { let h = u2 - u1; @@ -279,9 +342,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(); @@ -292,7 +355,7 @@ macro_rules! new_curve_impl { if self.y == s2 { self.double() } else { - $name::zero() + $name::identity() } } else { let h = u2 - self.x; @@ -339,7 +402,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 @@ -393,16 +456,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; @@ -449,7 +512,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 @@ -471,17 +534,13 @@ macro_rules! new_curve_impl { } } - impl CurveAffine for $name_affine { - type Projective = $name; + 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); - fn zero() -> Self { + fn identity() -> Self { Self { x: $base::zero(), y: $base::zero(), @@ -489,34 +548,21 @@ macro_rules! new_curve_impl { } } - fn is_zero(&self) -> Choice { + fn is_identity(&self) -> Choice { 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_projective(&self) -> Self::Projective { + fn to_curve(&self) -> Self::Curve { $name { x: self.x, y: self.y, 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_zero()) - } - - 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; @@ -524,7 +570,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); @@ -544,9 +590,14 @@ 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_zero()) { + if bool::from(self.is_identity()) { [0; 32] } else { let (x, y) = (self.x, self.y); @@ -556,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]; @@ -565,7 +641,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()); @@ -584,7 +660,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]; @@ -606,7 +682,7 @@ macro_rules! new_curve_impl { impl Default for $name_affine { fn default() -> $name_affine { - $name_affine::zero() + $name_affine::identity() } } @@ -660,7 +736,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; @@ -676,33 +752,8 @@ 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, - ) - }) - } - - fn one() -> Self { + ($name:ident, $base:ident, special_a0_b5) => { + fn generator() -> Self { // NOTE: This is specific to b = 5 const NEGATIVE_ONE: $base = $base::neg(&$base::one()); @@ -715,16 +766,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 // @@ -753,22 +794,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, $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 { + fn generator() -> Self { unimplemented!() } @@ -796,14 +827,61 @@ 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()) + } + }; +} + +macro_rules! impl_projective_curve_ext { + ($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, $iso>( + &us[0], + $name::THETA, + $name::Z, + ); + 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, $iso>(&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: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 { + fn generator() -> Self { // NOTE: This is specific to b = 5 const NEGATIVE_ONE: $base = $base::neg(&$base::from_raw([1, 0, 0, 0])); @@ -818,7 +896,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!() } }; @@ -828,7 +906,7 @@ new_curve_impl!( (pub), Ep, EpAffine, - IsoEpAffine, + IsoEp, Fp, Fq, b"halo2_____pallas", @@ -841,7 +919,7 @@ new_curve_impl!( (pub), Eq, EqAffine, - IsoEqAffine, + IsoEq, Fq, Fp, b"halo2______vesta", @@ -854,7 +932,7 @@ new_curve_impl!( (pub(crate)), IsoEp, IsoEpAffine, - EpAffine, + Ep, Fp, Fq, b"halo2_iso_pallas", @@ -872,7 +950,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 2388c1e..3fae7b8 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::{CurveExt, 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::Projective, +pub fn iso_map, I: CurveExt>( + p: &I, iso: &[C::Base; 13], -) -> C::Projective { +) -> 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::Projective::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: CurveExt>( u: &F, theta: F, z: F, -) -> I::Projective { +) -> 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::Projective::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 06fd9c0..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 @@ -42,8 +43,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,15 +58,15 @@ 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()); } #[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([ @@ -91,22 +91,20 @@ 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())); - let p = - super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r, &Ep::ISOGENY_CONSTANTS); + assert!(bool::from(r.is_identity())); + 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_zero())); + assert!(bool::from(p.is_identity())); } #[test] fn test_map_to_curve_simple_swu() { - use crate::arithmetic::Curve; - use crate::pasta::curves::{IsoEp, IsoEpAffine}; + use crate::arithmetic::CurveExt; + 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 +117,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!( @@ -136,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). @@ -157,5 +155,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/pasta/vesta.rs b/src/pasta/vesta.rs index be387c2..c958804 100644 --- a/src/pasta/vesta.rs +++ b/src/pasta/vesta.rs @@ -16,13 +16,12 @@ pub type Affine = EqAffine; #[test] fn test_map_to_curve_simple_swu() { - use crate::arithmetic::Curve; - use crate::pasta::curves::{IsoEq, IsoEqAffine}; + use crate::arithmetic::CurveExt; + 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!( @@ -52,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 5abe772..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,8 +87,8 @@ impl Argument { transcript: &mut T, ) -> Result, Error> where - C: CurveAffine, - C::Projective: Mul + MulAssign, + C: CurveAffine, + C::Curve: Mul + MulAssign, { // Closure to get values of expressions and compress them let compress_expressions = |expressions: &[Expression]| { 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 8d1c055..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}, @@ -52,11 +53,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 +205,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..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}, @@ -50,8 +52,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..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(); } @@ -60,7 +65,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() @@ -83,11 +88,11 @@ 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(); } - 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 +102,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 +146,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 +167,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); @@ -195,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 75d7b25..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)] @@ -144,6 +145,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..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 @@ -152,8 +153,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); }); } 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)?;