Merge pull request #202 from zcash/group-traits

Migrate to group traits
This commit is contained in:
ebfull 2021-02-22 13:37:02 -07:00 committed by GitHub
commit a7b9ca44f8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 348 additions and 341 deletions

View file

@ -43,6 +43,7 @@ backtrace = { version = "0.3", optional = true }
subtle = "2.3" subtle = "2.3"
crossbeam-utils = "0.8" crossbeam-utils = "0.8"
ff = "0.9" ff = "0.9"
group = "0.9"
metrics = "0.14.2" metrics = "0.14.2"
num_cpus = "1.13" num_cpus = "1.13"
rand = "0.8" rand = "0.8"

View file

@ -2,7 +2,7 @@
use criterion::{criterion_group, criterion_main, Criterion}; use criterion::{criterion_group, criterion_main, Criterion};
use halo2::arithmetic::Curve; use halo2::arithmetic::CurveExt;
use halo2::pasta::{pallas, vesta}; use halo2::pasta::{pallas, vesta};
fn criterion_benchmark(c: &mut Criterion) { fn criterion_benchmark(c: &mut Criterion) {

View file

@ -1,5 +1,6 @@
use group::Curve;
use halo2::{ use halo2::{
arithmetic::{Curve, FieldExt}, arithmetic::FieldExt,
model::ModelRecorder, model::ModelRecorder,
pasta::{EqAffine, Fp}, pasta::{EqAffine, Fp},
plonk::*, plonk::*,

View file

@ -3,6 +3,7 @@
use crossbeam_utils::thread; use crossbeam_utils::thread;
pub use ff::Field; pub use ff::Field;
use group::Group as _;
mod curves; mod curves;
mod fields; mod fields;
@ -68,7 +69,7 @@ where
} }
} }
fn multiexp_serial<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C], acc: &mut C::Projective) { fn multiexp_serial<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C], acc: &mut C::Curve) {
let coeffs: Vec<[u8; 32]> = coeffs.iter().map(|a| a.to_bytes()).collect(); let coeffs: Vec<[u8; 32]> = coeffs.iter().map(|a| a.to_bytes()).collect();
let c = if bases.len() < 4 { let c = if bases.len() < 4 {
@ -110,7 +111,7 @@ fn multiexp_serial<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C], acc: &mut
enum Bucket<C: CurveAffine> { enum Bucket<C: CurveAffine> {
None, None,
Affine(C), Affine(C),
Projective(C::Projective), Projective(C::Curve),
} }
impl<C: CurveAffine> Bucket<C> { impl<C: CurveAffine> Bucket<C> {
@ -125,7 +126,7 @@ fn multiexp_serial<C: CurveAffine>(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 { match self {
Bucket::None => other, Bucket::None => other,
Bucket::Affine(a) => { Bucket::Affine(a) => {
@ -150,7 +151,7 @@ fn multiexp_serial<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C], acc: &mut
// e.g. 3a + 2b + 1c = a + // e.g. 3a + 2b + 1c = a +
// (a) + b + // (a) + b +
// ((a) + b) + c // ((a) + b) + c
let mut running_sum = C::Projective::zero(); let mut running_sum = C::Curve::identity();
for exp in buckets.into_iter().rev() { for exp in buckets.into_iter().rev() {
running_sum = exp.add(running_sum); running_sum = exp.add(running_sum);
*acc = *acc + &running_sum; *acc = *acc + &running_sum;
@ -160,9 +161,9 @@ fn multiexp_serial<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C], acc: &mut
/// Performs a small multi-exponentiation operation. /// Performs a small multi-exponentiation operation.
/// Uses the double-and-add algorithm with doublings shared across points. /// Uses the double-and-add algorithm with doublings shared across points.
pub fn small_multiexp<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C]) -> C::Projective { pub fn small_multiexp<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C]) -> C::Curve {
let coeffs: Vec<[u8; 32]> = coeffs.iter().map(|a| a.to_bytes()).collect(); 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
for byte_idx in (0..32).rev() { for byte_idx in (0..32).rev() {
@ -187,14 +188,14 @@ pub fn small_multiexp<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C]) -> C::P
/// This function will panic if coeffs and bases have a different length. /// This function will panic if coeffs and bases have a different length.
/// ///
/// This will use multithreading if beneficial. /// This will use multithreading if beneficial.
pub fn best_multiexp<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C]) -> C::Projective { pub fn best_multiexp<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C]) -> C::Curve {
assert_eq!(coeffs.len(), bases.len()); assert_eq!(coeffs.len(), bases.len());
let num_cpus = num_cpus::get(); let num_cpus = num_cpus::get();
if coeffs.len() > num_cpus { if coeffs.len() > num_cpus {
let chunk = coeffs.len() / num_cpus; let chunk = coeffs.len() / num_cpus;
let num_chunks = coeffs.chunks(chunk).len(); 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| { thread::scope(|scope| {
let chunk = coeffs.len() / num_cpus; let chunk = coeffs.len() / num_cpus;
@ -209,9 +210,9 @@ pub fn best_multiexp<C: CurveAffine>(coeffs: &[C::Scalar], bases: &[C]) -> C::Pr
} }
}) })
.unwrap(); .unwrap();
results.iter().fold(C::Projective::zero(), |a, b| a + b) results.iter().fold(C::Curve::identity(), |a, b| a + b)
} else { } else {
let mut acc = C::Projective::zero(); let mut acc = C::Curve::identity();
multiexp_serial(coeffs, bases, &mut acc); multiexp_serial(coeffs, bases, &mut acc);
acc acc
} }

View file

@ -2,8 +2,8 @@
//! write code that generalizes over a pair of groups. //! write code that generalizes over a pair of groups.
use core::cmp; use core::cmp;
use core::fmt::Debug; use core::ops::{Add, Sub};
use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}; use group::prime::{PrimeCurve, PrimeCurveAffine};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption}; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use super::{FieldExt, Group}; 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 /// 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 /// curve group in a "projective" form, where that arithmetic is usually more
/// efficient. /// efficient.
pub trait Curve: pub trait CurveExt:
Sized PrimeCurve
+ group::Group<Scalar = <Self as CurveExt>::ScalarExt>
+ Default + Default
+ Copy
+ Clone
+ Send
+ Sync
+ 'static
+ Debug
+ Add<Output = Self>
+ Sub<Output = Self>
+ Mul<<Self as Curve>::Scalar, Output = Self>
+ Neg<Output = Self>
+ for<'a> Add<&'a Self, Output = Self>
+ for<'a> Sub<&'a Self, Output = Self>
+ MulAssign<<Self as Curve>::Scalar>
+ AddAssign
+ SubAssign
+ for<'a> AddAssign<&'a Self>
+ for<'a> SubAssign<&'a Self>
+ AddAssign<<Self as Curve>::Affine>
+ SubAssign<<Self as Curve>::Affine>
+ PartialEq + PartialEq
+ cmp::Eq + cmp::Eq
+ ConditionallySelectable + ConditionallySelectable
+ ConstantTimeEq + ConstantTimeEq
+ From<<Self as Curve>::Affine> + From<<Self as PrimeCurve>::Affine>
+ Group<Scalar = <Self as Curve>::Scalar> + Group<Scalar = <Self as group::Group>::Scalar>
{ {
/// The representation of a point on this curve in the affine coordinate space.
type Affine: CurveAffine<
Projective = Self,
Scalar = <Self as Curve>::Scalar,
Base = <Self as Curve>::Base,
> + Add<Output = Self>
+ Sub<Output = Self>
+ Mul<<Self as Curve>::Scalar, Output = Self>
+ Neg<Output = <Self as Curve>::Affine>
+ From<Self>;
/// The scalar field of this elliptic curve. /// The scalar field of this elliptic curve.
type Scalar: FieldExt; type ScalarExt: FieldExt;
/// The base field over which this elliptic curve is constructed. /// The base field over which this elliptic curve is constructed.
type Base: FieldExt; 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 /// Apply the curve endomorphism by multiplying the x-coordinate
/// by an element of multiplicative order 3. /// by an element of multiplicative order 3.
fn endo(&self) -> Self; fn endo(&self) -> Self;
/// Converts this element into its affine form.
fn to_affine(&self) -> Self::Affine;
/// Return the Jacobian coordinates of this point. /// Return the Jacobian coordinates of this point.
fn jacobian_coordinates(&self) -> (Self::Base, Self::Base, Self::Base); fn jacobian_coordinates(&self) -> (Self::Base, Self::Base, Self::Base);
@ -87,9 +44,12 @@ pub trait Curve:
/// # Example /// # Example
/// ///
/// ``` /// ```
/// use halo2::arithmetic::{Curve, CurveAffine}; /// use halo2::arithmetic::CurveExt;
/// fn pedersen_commitment<C: CurveAffine>(x: C::Scalar, r: C::Scalar) -> C { /// fn pedersen_commitment<C: CurveExt>(
/// let hasher = C::Projective::hash_to_curve("z.cash:example_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 g = hasher(b"g");
/// let h = hasher(b"h"); /// let h = hasher(b"h");
/// (g * x + &(h * r)).to_affine() /// (g * x + &(h * r)).to_affine()
@ -101,10 +61,6 @@ pub trait Curve:
/// always be true unless an "unchecked" API was used. /// always be true unless an "unchecked" API was used.
fn is_on_curve(&self) -> Choice; 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. /// Returns the curve constant a.
fn a() -> Self::Base; fn a() -> Self::Base;
@ -119,36 +75,16 @@ pub trait Curve:
/// This trait is the affine counterpart to `Curve` and is used for /// This trait is the affine counterpart to `Curve` and is used for
/// serialization, storage in memory, and inspection of $x$ and $y$ coordinates. /// serialization, storage in memory, and inspection of $x$ and $y$ coordinates.
pub trait CurveAffine: pub trait CurveAffine:
Sized PrimeCurveAffine<Scalar = <Self as CurveAffine>::ScalarExt>
+ Default + Default
+ Copy + Add<Output = <Self as PrimeCurveAffine>::Curve>
+ Clone + Sub<Output = <Self as PrimeCurveAffine>::Curve>
+ Send
+ Sync
+ 'static
+ Debug
+ Add<Output = <Self as CurveAffine>::Projective>
+ Sub<Output = <Self as CurveAffine>::Projective>
+ Mul<<Self as CurveAffine>::Scalar, Output = <Self as CurveAffine>::Projective>
+ Neg<Output = Self>
+ PartialEq
+ cmp::Eq
+ ConditionallySelectable + ConditionallySelectable
+ ConstantTimeEq + ConstantTimeEq
+ From<<Self as CurveAffine>::Projective> + From<<Self as PrimeCurveAffine>::Curve>
{ {
/// The representation of a point on this curve in the projective coordinate space.
type Projective: Curve<
Affine = Self,
Scalar = <Self as CurveAffine>::Scalar,
Base = <Self as CurveAffine>::Base,
> + Mul<<Self as CurveAffine>::Scalar, Output = <Self as CurveAffine>::Projective>
+ MulAssign<<Self as CurveAffine>::Scalar>
+ AddAssign<Self>
+ SubAssign<Self>
+ From<Self>;
/// The scalar field of this elliptic curve. /// The scalar field of this elliptic curve.
type Scalar: FieldExt; type ScalarExt: FieldExt;
/// The base field over which this elliptic curve is constructed. /// The base field over which this elliptic curve is constructed.
type Base: FieldExt; type Base: FieldExt;
@ -159,18 +95,6 @@ pub trait CurveAffine:
/// CURVE_ID used for hash-to-curve. /// CURVE_ID used for hash-to-curve.
const CURVE_ID: &'static str; 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. /// Gets the $(x, y)$ coordinates of this point.
fn get_xy(&self) -> CtOption<(Self::Base, Self::Base)>; 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. /// always be true unless an "unchecked" API was used.
fn is_on_curve(&self) -> Choice; 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<Self>;
/// Reads a compressed element from the buffer and attempts to parse it /// Reads a compressed element from the buffer and attempts to parse it
/// using `from_bytes`. /// using `from_bytes`.
fn read<R: Read>(reader: &mut R) -> io::Result<Self> { fn read<R: Read>(reader: &mut R) -> io::Result<Self> {
let mut compressed = [0u8; 32]; let mut compressed = Self::Repr::default();
reader.read_exact(&mut compressed[..])?; reader.read_exact(compressed.as_mut())?;
Option::from(Self::from_bytes(&compressed)) Option::from(Self::from_bytes(&compressed))
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "invalid point encoding in proof")) .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. /// Writes an element in compressed form to the buffer.
fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> { fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
let compressed = self.to_bytes(); 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 /// Attempts to obtain a group element from its uncompressed 64-byte little

View file

@ -15,10 +15,11 @@ pub use fields::*;
#[test] #[test]
fn test_endo_consistency() { 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()); 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()); assert_eq!(a * vesta::Scalar::ZETA, a.endo());
} }

View file

@ -3,15 +3,21 @@
use core::cmp; use core::cmp;
use core::fmt::Debug; use core::fmt::Debug;
use core::iter::Sum;
use core::ops::{Add, Mul, Neg, Sub}; use core::ops::{Add, Mul, Neg, Sub};
use ff::Field; use ff::Field;
use group::{
prime::{PrimeCurve, PrimeCurveAffine, PrimeGroup},
Curve as _, Group as _, GroupEncoding,
};
use rand::RngCore;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption}; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use super::{Fp, Fq}; use super::{Fp, Fq};
use crate::arithmetic::{Curve, CurveAffine, FieldExt, Group}; use crate::arithmetic::{CurveAffine, CurveExt, FieldExt, Group};
macro_rules! new_curve_impl { 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) => { $curve_id:literal, $a_raw:expr, $b_raw:expr, $curve_type:ident) => {
/// Represents a point in the projective coordinate space. /// Represents a point in the projective coordinate space.
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
@ -50,14 +56,25 @@ macro_rules! new_curve_impl {
} }
} }
impl Curve for $name { impl group::Group for $name {
type Affine = $name_affine;
type Scalar = $scalar; 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 { Self {
x: $base::zero(), x: $base::zero(),
y: $base::zero(), y: $base::zero(),
@ -65,26 +82,17 @@ macro_rules! new_curve_impl {
} }
} }
fn is_zero(&self) -> Choice { fn is_identity(&self) -> Choice {
self.z.ct_is_zero() 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::zero(), 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);
fn a() -> Self::Base { fn a() -> Self::Base {
$name::curve_constant_a() $name::curve_constant_a()
} }
@ -93,6 +101,11 @@ macro_rules! new_curve_impl {
$name::curve_constant_b() $name::curve_constant_b()
} }
fn new_jacobian(x: Self::Base, y: Self::Base, z: Self::Base) -> CtOption<Self> {
let p = $name { x, y, z };
CtOption::new(p, p.is_on_curve())
}
fn jacobian_coordinates(&self) -> ($base, $base, $base) { fn jacobian_coordinates(&self) -> ($base, $base, $base) {
(self.x, self.y, self.z) (self.x, self.y, self.z)
} }
@ -108,8 +121,12 @@ macro_rules! new_curve_impl {
.ct_eq(&(z6 * $name::curve_constant_b())) .ct_eq(&(z6 * $name::curve_constant_b()))
| self.z.ct_is_zero() | 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()); assert_eq!(p.len(), q.len());
let mut acc = $base::one(); let mut acc = $base::one();
@ -119,7 +136,7 @@ macro_rules! new_curve_impl {
q.x = acc; q.x = acc;
// We will end up skipping all identities in p // 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 // 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(); acc = acc.invert().unwrap();
for (p, q) in p.iter().rev().zip(q.iter_mut().rev()) { 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 // Compute tmp = 1/z
let tmp = q.x * acc; let tmp = q.x * acc;
@ -143,31 +160,65 @@ macro_rules! new_curve_impl {
q.y = p.y * tmp3; q.y = p.y * tmp3;
q.infinity = Choice::from(0u8); 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<Self> { fn to_affine(&self) -> Self::AffineRepr {
let p = $name { x, y, z }; let zinv = self.z.invert().unwrap_or($base::zero());
CtOption::new(p, p.is_on_curve()) 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<Self> {
$name_affine::from_bytes(bytes).map(Self::from)
}
fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
// 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 { impl<'a> From<&'a $name_affine> for $name {
fn from(p: &'a $name_affine) -> $name { fn from(p: &'a $name_affine) -> $name {
p.to_projective() p.to_curve()
} }
} }
impl From<$name_affine> for $name { impl From<$name_affine> for $name {
fn from(p: $name_affine) -> $name { fn from(p: $name_affine) -> $name {
p.to_projective() p.to_curve()
} }
} }
impl Default for $name { impl Default for $name {
fn default() -> $name { fn default() -> $name {
$name::zero() $name::identity()
} }
} }
@ -184,8 +235,8 @@ macro_rules! new_curve_impl {
let z = z * self.z; let z = z * self.z;
let y2 = other.y * z; let y2 = other.y * z;
let self_is_zero = self.is_zero(); let self_is_zero = self.is_identity();
let other_is_zero = other.is_zero(); let other_is_zero = other.is_identity();
(self_is_zero & other_is_zero) // Both point at infinity (self_is_zero & other_is_zero) // Both point at infinity
| ((!self_is_zero) & (!other_is_zero) & x1.ct_eq(&x2) & y1.ct_eq(&y2)) | ((!self_is_zero) & (!other_is_zero) & x1.ct_eq(&x2) & y1.ct_eq(&y2))
@ -231,13 +282,25 @@ macro_rules! new_curve_impl {
} }
} }
impl<T> Sum<T> for $name
where
T: core::borrow::Borrow<$name>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>,
{
iter.fold(Self::identity(), |acc, item| acc + item.borrow())
}
}
impl<'a, 'b> Add<&'a $name> for &'b $name { impl<'a, 'b> Add<&'a $name> for &'b $name {
type Output = $name; type Output = $name;
fn add(self, rhs: &'a $name) -> $name { fn add(self, rhs: &'a $name) -> $name {
if bool::from(self.is_zero()) { if bool::from(self.is_identity()) {
*rhs *rhs
} else if bool::from(rhs.is_zero()) { } else if bool::from(rhs.is_identity()) {
*self *self
} else { } else {
let z1z1 = self.z.square(); let z1z1 = self.z.square();
@ -251,7 +314,7 @@ macro_rules! new_curve_impl {
if s1 == s2 { if s1 == s2 {
self.double() self.double()
} else { } else {
$name::zero() $name::identity()
} }
} else { } else {
let h = u2 - u1; let h = u2 - u1;
@ -279,9 +342,9 @@ macro_rules! new_curve_impl {
type Output = $name; type Output = $name;
fn add(self, rhs: &'a $name_affine) -> $name { fn add(self, rhs: &'a $name_affine) -> $name {
if bool::from(self.is_zero()) { if bool::from(self.is_identity()) {
rhs.to_projective() rhs.to_curve()
} else if bool::from(rhs.is_zero()) { } else if bool::from(rhs.is_identity()) {
*self *self
} else { } else {
let z1z1 = self.z.square(); let z1z1 = self.z.square();
@ -292,7 +355,7 @@ macro_rules! new_curve_impl {
if self.y == s2 { if self.y == s2 {
self.double() self.double()
} else { } else {
$name::zero() $name::identity()
} }
} else { } else {
let h = u2 - self.x; let h = u2 - self.x;
@ -339,7 +402,7 @@ macro_rules! new_curve_impl {
fn mul(self, other: &'b $scalar) -> Self::Output { fn mul(self, other: &'b $scalar) -> Self::Output {
// TODO: make this faster // TODO: make this faster
let mut acc = $name::zero(); let mut acc = $name::identity();
// This is a simple double-and-add implementation of point // This is a simple double-and-add implementation of point
// multiplication, moving from most significant to least // multiplication, moving from most significant to least
@ -393,16 +456,16 @@ macro_rules! new_curve_impl {
type Output = $name; type Output = $name;
fn add(self, rhs: &'a $name_affine) -> $name { fn add(self, rhs: &'a $name_affine) -> $name {
if bool::from(self.is_zero()) { if bool::from(self.is_identity()) {
rhs.to_projective() rhs.to_curve()
} else if bool::from(rhs.is_zero()) { } else if bool::from(rhs.is_identity()) {
self.to_projective() self.to_curve()
} else { } else {
if self.x == rhs.x { if self.x == rhs.x {
if self.y == rhs.y { if self.y == rhs.y {
self.to_projective().double() self.to_curve().double()
} else { } else {
$name::zero() $name::identity()
} }
} else { } else {
let h = rhs.x - self.x; let h = rhs.x - self.x;
@ -449,7 +512,7 @@ macro_rules! new_curve_impl {
fn mul(self, other: &'b $scalar) -> Self::Output { fn mul(self, other: &'b $scalar) -> Self::Output {
// TODO: make this faster // TODO: make this faster
let mut acc = $name::zero(); let mut acc = $name::identity();
// This is a simple double-and-add implementation of point // This is a simple double-and-add implementation of point
// multiplication, moving from most significant to least // multiplication, moving from most significant to least
@ -471,17 +534,13 @@ macro_rules! new_curve_impl {
} }
} }
impl CurveAffine for $name_affine { impl PrimeCurveAffine for $name_affine {
type Projective = $name; type Curve = $name;
type Scalar = $scalar; 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); impl_affine_curve_specific!($name, $base, $curve_type);
fn zero() -> Self { fn identity() -> Self {
Self { Self {
x: $base::zero(), x: $base::zero(),
y: $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 self.infinity
} }
fn is_on_curve(&self) -> Choice { fn to_curve(&self) -> Self::Curve {
// 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 {
$name { $name {
x: self.x, x: self.x,
y: self.y, y: self.y,
z: $base::conditional_select(&$base::one(), &$base::zero(), self.infinity), 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<Self> { impl GroupEncoding for $name_affine {
let p = $name_affine { type Repr = [u8; 32];
x, y, infinity: 0u8.into()
};
CtOption::new(p, p.is_on_curve())
}
fn from_bytes(bytes: &[u8; 32]) -> CtOption<Self> { fn from_bytes(bytes: &[u8; 32]) -> CtOption<Self> {
let mut tmp = *bytes; let mut tmp = *bytes;
@ -524,7 +570,7 @@ macro_rules! new_curve_impl {
tmp[31] &= 0b0111_1111; tmp[31] &= 0b0111_1111;
$base::from_bytes(&tmp).and_then(|x| { $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; let x3 = x.square() * x;
(x3 + $name::curve_constant_b()).sqrt().and_then(|y| { (x3 + $name::curve_constant_b()).sqrt().and_then(|y| {
let sign = Choice::from(y.to_bytes()[0] & 1); 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<Self> {
// We can't avoid curve checks when parsing a compressed encoding.
Self::from_bytes(bytes)
}
fn to_bytes(&self) -> [u8; 32] { fn to_bytes(&self) -> [u8; 32] {
// TODO: not constant time // TODO: not constant time
if bool::from(self.is_zero()) { if bool::from(self.is_identity()) {
[0; 32] [0; 32]
} else { } else {
let (x, y) = (self.x, self.y); let (x, y) = (self.x, self.y);
@ -556,6 +607,31 @@ macro_rules! new_curve_impl {
xbytes 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<Self> {
let p = $name_affine {
x, y, infinity: 0u8.into()
};
CtOption::new(p, p.is_on_curve())
}
fn from_bytes_wide(bytes: &[u8; 64]) -> CtOption<Self> { fn from_bytes_wide(bytes: &[u8; 64]) -> CtOption<Self> {
let mut xbytes = [0u8; 32]; let mut xbytes = [0u8; 32];
@ -565,7 +641,7 @@ macro_rules! new_curve_impl {
$base::from_bytes(&xbytes).and_then(|x| { $base::from_bytes(&xbytes).and_then(|x| {
$base::from_bytes(&ybytes).and_then(|y| { $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 = let on_curve =
(x * x.square() + $name::curve_constant_b()).ct_eq(&y.square()); (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] { fn to_bytes_wide(&self) -> [u8; 64] {
// TODO: not constant time // TODO: not constant time
if bool::from(self.is_zero()) { if bool::from(self.is_identity()) {
[0; 64] [0; 64]
} else { } else {
let mut out = [0u8; 64]; let mut out = [0u8; 64];
@ -606,7 +682,7 @@ macro_rules! new_curve_impl {
impl Default for $name_affine { impl Default for $name_affine {
fn default() -> $name_affine { fn default() -> $name_affine {
$name_affine::zero() $name_affine::identity()
} }
} }
@ -660,7 +736,7 @@ macro_rules! new_curve_impl {
type Scalar = $scalar; type Scalar = $scalar;
fn group_zero() -> Self { fn group_zero() -> Self {
Self::zero() Self::identity()
} }
fn group_add(&mut self, rhs: &Self) { fn group_add(&mut self, rhs: &Self) {
*self = *self + *rhs; *self = *self + *rhs;
@ -676,33 +752,8 @@ macro_rules! new_curve_impl {
} }
macro_rules! impl_projective_curve_specific { macro_rules! impl_projective_curve_specific {
($name:ident, $name_affine:ident, $iso_affine:ident, $base:ident, special_a0_b5) => { ($name:ident, $base:ident, special_a0_b5) => {
fn hash_to_curve<'a>(domain_prefix: &'a str) -> Box<dyn Fn(&[u8]) -> Self + 'a> { fn generator() -> Self {
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 {
// NOTE: This is specific to b = 5 // NOTE: This is specific to b = 5
const NEGATIVE_ONE: $base = $base::neg(&$base::one()); 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 { fn double(&self) -> Self {
// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l // 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, 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) => { ($name:ident, $base:ident, general) => {
/// Unimplemented: hashing to this curve is not supported
fn hash_to_curve<'a>(_domain_prefix: &'a str) -> Box<dyn Fn(&[u8]) -> Self + 'a> {
unimplemented!()
}
/// Unimplemented: there is no standard generator for this curve. /// Unimplemented: there is no standard generator for this curve.
fn one() -> Self { fn generator() -> Self {
unimplemented!()
}
/// Unimplemented: no endomorphism is supported for this curve.
fn endo(&self) -> Self {
unimplemented!() unimplemented!()
} }
@ -796,14 +827,61 @@ macro_rules! impl_projective_curve_specific {
z: z3, 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<dyn Fn(&[u8]) -> 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<dyn Fn(&[u8]) -> Self + 'a> {
unimplemented!()
}
/// Unimplemented: no endomorphism is supported for this curve.
fn endo(&self) -> Self {
unimplemented!()
} }
}; };
} }
macro_rules! impl_affine_curve_specific { macro_rules! impl_affine_curve_specific {
($name:ident, $base:ident, special_a0_b5) => { ($name:ident, $base:ident, special_a0_b5) => {
fn one() -> Self { fn generator() -> Self {
// NOTE: This is specific to b = 5 // NOTE: This is specific to b = 5
const NEGATIVE_ONE: $base = $base::neg(&$base::from_raw([1, 0, 0, 0])); 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) => { ($name:ident, $base:ident, general) => {
/// Unimplemented: there is no standard generator for this curve. /// Unimplemented: there is no standard generator for this curve.
fn one() -> Self { fn generator() -> Self {
unimplemented!() unimplemented!()
} }
}; };
@ -828,7 +906,7 @@ new_curve_impl!(
(pub), (pub),
Ep, Ep,
EpAffine, EpAffine,
IsoEpAffine, IsoEp,
Fp, Fp,
Fq, Fq,
b"halo2_____pallas", b"halo2_____pallas",
@ -841,7 +919,7 @@ new_curve_impl!(
(pub), (pub),
Eq, Eq,
EqAffine, EqAffine,
IsoEqAffine, IsoEq,
Fq, Fq,
Fp, Fp,
b"halo2______vesta", b"halo2______vesta",
@ -854,7 +932,7 @@ new_curve_impl!(
(pub(crate)), (pub(crate)),
IsoEp, IsoEp,
IsoEpAffine, IsoEpAffine,
EpAffine, Ep,
Fp, Fp,
Fq, Fq,
b"halo2_iso_pallas", b"halo2_iso_pallas",
@ -872,7 +950,7 @@ new_curve_impl!(
(pub(crate)), (pub(crate)),
IsoEq, IsoEq,
IsoEqAffine, IsoEqAffine,
EqAffine, Eq,
Fq, Fq,
Fp, Fp,
b"halo2__iso_vesta", b"halo2__iso_vesta",

View file

@ -3,7 +3,7 @@
use subtle::ConstantTimeEq; 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`. /// Hashes over a message and writes the output to all of `buf`.
pub fn hash_to_field<F: FieldExt>( pub fn hash_to_field<F: FieldExt>(
@ -72,10 +72,10 @@ pub fn hash_to_field<F: FieldExt>(
} }
/// Implements a degree 3 isogeny map. /// Implements a degree 3 isogeny map.
pub fn iso_map<F: FieldExt, C: CurveAffine<Base = F>, I: CurveAffine<Base = F>>( pub fn iso_map<F: FieldExt, C: CurveExt<Base = F>, I: CurveExt<Base = F>>(
p: &I::Projective, p: &I,
iso: &[C::Base; 13], iso: &[C::Base; 13],
) -> C::Projective { ) -> C {
// The input and output are in Jacobian coordinates, using the method // The input and output are in Jacobian coordinates, using the method
// in "Avoiding inversions" [WB2019, section 4.3]. // in "Avoiding inversions" [WB2019, section 4.3].
@ -96,14 +96,14 @@ pub fn iso_map<F: FieldExt, C: CurveAffine<Base = F>, I: CurveAffine<Base = F>>(
let xo = num_x * div_y * zo; let xo = num_x * div_y * zo;
let yo = num_y * div_x * zo.square(); 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<F: FieldExt, C: CurveAffine<Base = F>, I: CurveAffine<Base = F>>( pub fn map_to_curve_simple_swu<F: FieldExt, C: CurveExt<Base = F>, I: CurveExt<Base = F>>(
u: &F, u: &F,
theta: F, theta: F,
z: F, z: F,
) -> I::Projective { ) -> I {
// 1. tv1 = inv0(Z^2 * u^4 + Z * u^2) // 1. tv1 = inv0(Z^2 * u^4 + Z * u^2)
// 2. x1 = (-B / A) * (1 + tv1) // 2. x1 = (-B / A) * (1 + tv1)
// 3. If tv1 == 0, set x1 = B / (Z * A) // 3. If tv1 == 0, set x1 = B / (Z * A)
@ -171,5 +171,5 @@ pub fn map_to_curve_simple_swu<F: FieldExt, C: CurveAffine<Base = F>, I: CurveAf
(u.get_lower_32() % 2).ct_eq(&(y.get_lower_32() % 2)), (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()
} }

View file

@ -16,7 +16,8 @@ pub type Affine = EpAffine;
#[test] #[test]
fn test_iso_map() { 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 // 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 // with domain prefix "z.cash:test", Shake128, and input b"hello"). We don't
@ -42,8 +43,7 @@ fn test_iso_map() {
]), ]),
) )
.unwrap(); .unwrap();
let p = let p = super::hashtocurve::iso_map::<_, Point, super::IsoEp>(&r, &Ep::ISOGENY_CONSTANTS);
super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r, &Ep::ISOGENY_CONSTANTS);
let (x, y, z) = p.jacobian_coordinates(); let (x, y, z) = p.jacobian_coordinates();
assert!( assert!(
format!("{:?}", x) == "0x318cc15f281662b3f26d0175cab97b924870c837879cac647e877be51a85e898" format!("{:?}", x) == "0x318cc15f281662b3f26d0175cab97b924870c837879cac647e877be51a85e898"
@ -58,15 +58,15 @@ fn test_iso_map() {
// check that iso_map([2] r) = [2] iso_map(r) // check that iso_map([2] r) = [2] iso_map(r)
let r2 = r.double(); let r2 = r.double();
assert!(bool::from(r2.is_on_curve())); assert!(bool::from(r2.is_on_curve()));
let p2 = let p2 = super::hashtocurve::iso_map::<_, Point, super::IsoEp>(&r2, &Ep::ISOGENY_CONSTANTS);
super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r2, &Ep::ISOGENY_CONSTANTS);
assert!(bool::from(p2.is_on_curve())); assert!(bool::from(p2.is_on_curve()));
assert!(p2 == p.double()); assert!(p2 == p.double());
} }
#[test] #[test]
fn test_iso_map_identity() { fn test_iso_map_identity() {
use crate::arithmetic::Curve; use crate::arithmetic::CurveExt;
use group::Group;
let r = super::IsoEp::new_jacobian( let r = super::IsoEp::new_jacobian(
Base::from_raw([ Base::from_raw([
@ -91,22 +91,20 @@ fn test_iso_map_identity() {
.unwrap(); .unwrap();
let r = (r * -Fq::one()) + r; let r = (r * -Fq::one()) + r;
assert!(bool::from(r.is_on_curve())); assert!(bool::from(r.is_on_curve()));
assert!(bool::from(r.is_zero())); assert!(bool::from(r.is_identity()));
let p = let p = super::hashtocurve::iso_map::<_, Point, super::IsoEp>(&r, &Ep::ISOGENY_CONSTANTS);
super::hashtocurve::iso_map::<_, Affine, super::IsoEpAffine>(&r, &Ep::ISOGENY_CONSTANTS);
assert!(bool::from(p.is_on_curve())); assert!(bool::from(p.is_on_curve()));
assert!(bool::from(p.is_zero())); assert!(bool::from(p.is_identity()));
} }
#[test] #[test]
fn test_map_to_curve_simple_swu() { fn test_map_to_curve_simple_swu() {
use crate::arithmetic::Curve; use crate::arithmetic::CurveExt;
use crate::pasta::curves::{IsoEp, IsoEpAffine}; use crate::pasta::curves::IsoEp;
use crate::pasta::hashtocurve::map_to_curve_simple_swu; use crate::pasta::hashtocurve::map_to_curve_simple_swu;
// The zero input is a special case. // The zero input is a special case.
let p: IsoEp = let p: IsoEp = map_to_curve_simple_swu::<Fp, Ep, IsoEp>(&Fp::zero(), Ep::THETA, Ep::Z);
map_to_curve_simple_swu::<Fp, EpAffine, IsoEpAffine>(&Fp::zero(), Ep::THETA, Ep::Z);
let (x, y, z) = p.jacobian_coordinates(); let (x, y, z) = p.jacobian_coordinates();
println!("{:?}", p); println!("{:?}", p);
assert!( assert!(
@ -119,8 +117,7 @@ fn test_map_to_curve_simple_swu() {
format!("{:?}", z) == "0x054b3ba10416dc104157b1318534a19d5d115472da7d746f8a5f250cd8cdef36" format!("{:?}", z) == "0x054b3ba10416dc104157b1318534a19d5d115472da7d746f8a5f250cd8cdef36"
); );
let p: IsoEp = let p: IsoEp = map_to_curve_simple_swu::<Fp, Ep, IsoEp>(&Fp::one(), Ep::THETA, Ep::Z);
map_to_curve_simple_swu::<Fp, EpAffine, IsoEpAffine>(&Fp::one(), Ep::THETA, Ep::Z);
let (x, y, z) = p.jacobian_coordinates(); let (x, y, z) = p.jacobian_coordinates();
println!("{:?}", p); println!("{:?}", p);
assert!( assert!(
@ -136,7 +133,8 @@ fn test_map_to_curve_simple_swu() {
#[test] #[test]
fn test_hash_to_curve() { 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 // 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). // "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; let p = (p * -Fq::one()) + p;
assert!(bool::from(p.is_on_curve())); assert!(bool::from(p.is_on_curve()));
assert!(bool::from(p.is_zero())); assert!(bool::from(p.is_identity()));
} }

View file

@ -16,13 +16,12 @@ pub type Affine = EqAffine;
#[test] #[test]
fn test_map_to_curve_simple_swu() { fn test_map_to_curve_simple_swu() {
use crate::arithmetic::Curve; use crate::arithmetic::CurveExt;
use crate::pasta::curves::{IsoEq, IsoEqAffine}; use crate::pasta::curves::IsoEq;
use crate::pasta::hashtocurve::map_to_curve_simple_swu; use crate::pasta::hashtocurve::map_to_curve_simple_swu;
// The zero input is a special case. // The zero input is a special case.
let p: IsoEq = let p: IsoEq = map_to_curve_simple_swu::<Fq, Eq, IsoEq>(&Fq::zero(), Eq::THETA, Eq::Z);
map_to_curve_simple_swu::<Fq, EqAffine, IsoEqAffine>(&Fq::zero(), Eq::THETA, Eq::Z);
let (x, y, z) = p.jacobian_coordinates(); let (x, y, z) = p.jacobian_coordinates();
println!("{:?}", p); println!("{:?}", p);
assert!( assert!(
@ -35,8 +34,7 @@ fn test_map_to_curve_simple_swu() {
format!("{:?}", z) == "0x0b851e9e579403a76df1100f556e1f226e5656bdf38f3bf8601d8a3a9a15890b" format!("{:?}", z) == "0x0b851e9e579403a76df1100f556e1f226e5656bdf38f3bf8601d8a3a9a15890b"
); );
let p: IsoEq = let p: IsoEq = map_to_curve_simple_swu::<Fq, Eq, IsoEq>(&Fq::one(), Eq::THETA, Eq::Z);
map_to_curve_simple_swu::<Fq, EqAffine, IsoEqAffine>(&Fq::one(), Eq::THETA, Eq::Z);
let (x, y, z) = p.jacobian_coordinates(); let (x, y, z) = p.jacobian_coordinates();
println!("{:?}", p); println!("{:?}", p);
assert!( assert!(
@ -52,7 +50,7 @@ fn test_map_to_curve_simple_swu() {
#[test] #[test]
fn test_hash_to_curve() { 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 // 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). // "branch" and the second takes the gx1 square "branch" (opposite to the Pallas test vector).

View file

@ -44,7 +44,7 @@ impl<C: CurveAffine> VerifyingKey<C> {
/// Writes a verifying key to a buffer. /// Writes a verifying key to a buffer.
pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> { pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
for commitment in &self.fixed_commitments { 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 { for permutation in &self.permutations {
permutation.write(writer)?; permutation.write(writer)?;
@ -190,7 +190,7 @@ type ChallengeX<F> = ChallengeScalar<F, X>;
#[test] #[test]
fn test_proving() { fn test_proving() {
use crate::arithmetic::{Curve, FieldExt}; use crate::arithmetic::FieldExt;
use crate::dev::MockProver; use crate::dev::MockProver;
use crate::pasta::{EqAffine, Fp}; use crate::pasta::{EqAffine, Fp};
use crate::poly::{ use crate::poly::{
@ -199,6 +199,7 @@ fn test_proving() {
}; };
use crate::transcript::{Blake2bRead, Blake2bWrite}; use crate::transcript::{Blake2bRead, Blake2bWrite};
use circuit::{Advice, Column, Fixed}; use circuit::{Advice, Column, Fixed};
use group::Curve;
use std::marker::PhantomData; use std::marker::PhantomData;
const K: u32 = 5; const K: u32 = 5;

View file

@ -1,10 +1,11 @@
use ff::Field; use ff::Field;
use group::Curve;
use super::{ use super::{
circuit::{Advice, Assignment, Circuit, Column, ConstraintSystem, Fixed}, circuit::{Advice, Assignment, Circuit, Column, ConstraintSystem, Fixed},
permutation, Error, LagrangeCoeff, Polynomial, ProvingKey, VerifyingKey, permutation, Error, LagrangeCoeff, Polynomial, ProvingKey, VerifyingKey,
}; };
use crate::arithmetic::{Curve, CurveAffine}; use crate::arithmetic::CurveAffine;
use crate::poly::{ use crate::poly::{
commitment::{Blind, Params}, commitment::{Blind, Params},
EvaluationDomain, Rotation, EvaluationDomain, Rotation,

View file

@ -4,7 +4,7 @@ use super::super::{
}; };
use super::Argument; use super::Argument;
use crate::{ use crate::{
arithmetic::{eval_polynomial, parallelize, BatchInvert, Curve, CurveAffine, FieldExt}, arithmetic::{eval_polynomial, parallelize, BatchInvert, CurveAffine, FieldExt},
poly::{ poly::{
commitment::{Blind, Params}, commitment::{Blind, Params},
multiopen::ProverQuery, multiopen::ProverQuery,
@ -13,6 +13,7 @@ use crate::{
transcript::TranscriptWrite, transcript::TranscriptWrite,
}; };
use ff::Field; use ff::Field;
use group::Curve;
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
iter, iter,
@ -86,8 +87,8 @@ impl<F: FieldExt> Argument<F> {
transcript: &mut T, transcript: &mut T,
) -> Result<Permuted<C>, Error> ) -> Result<Permuted<C>, Error>
where where
C: CurveAffine<Scalar = F>, C: CurveAffine<ScalarExt = F>,
C::Projective: Mul<F, Output = C::Projective> + MulAssign<F>, C::Curve: Mul<F, Output = C::Curve> + MulAssign<F>,
{ {
// Closure to get values of expressions and compress them // Closure to get values of expressions and compress them
let compress_expressions = |expressions: &[Expression<C::Scalar>]| { let compress_expressions = |expressions: &[Expression<C::Scalar>]| {

View file

@ -1,8 +1,9 @@
use ff::Field; use ff::Field;
use group::Curve;
use super::{Argument, ProvingKey, VerifyingKey}; use super::{Argument, ProvingKey, VerifyingKey};
use crate::{ use crate::{
arithmetic::{Curve, CurveAffine, FieldExt}, arithmetic::{CurveAffine, FieldExt},
plonk::{circuit::ConstraintSystem, Error}, plonk::{circuit::ConstraintSystem, Error},
poly::{ poly::{
commitment::{Blind, Params}, commitment::{Blind, Params},

View file

@ -1,10 +1,11 @@
use ff::Field; use ff::Field;
use group::Curve;
use std::iter; use std::iter;
use super::super::circuit::Any; use super::super::circuit::Any;
use super::{Argument, ProvingKey}; use super::{Argument, ProvingKey};
use crate::{ use crate::{
arithmetic::{eval_polynomial, parallelize, BatchInvert, Curve, CurveAffine, FieldExt}, arithmetic::{eval_polynomial, parallelize, BatchInvert, CurveAffine, FieldExt},
plonk::{self, ChallengeBeta, ChallengeGamma, ChallengeX, Error}, plonk::{self, ChallengeBeta, ChallengeGamma, ChallengeX, Error},
poly::{ poly::{
commitment::{Blind, Params}, commitment::{Blind, Params},

View file

@ -1,4 +1,5 @@
use ff::Field; use ff::Field;
use group::Curve;
use std::iter; use std::iter;
use super::{ use super::{
@ -6,7 +7,7 @@ use super::{
lookup, permutation, vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX, lookup, permutation, vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX,
ChallengeY, Error, ProvingKey, ChallengeY, Error, ProvingKey,
}; };
use crate::arithmetic::{eval_polynomial, Curve, CurveAffine, FieldExt}; use crate::arithmetic::{eval_polynomial, CurveAffine, FieldExt};
use crate::poly::{ use crate::poly::{
commitment::{Blind, Params}, commitment::{Blind, Params},
multiopen::{self, ProverQuery}, multiopen::{self, ProverQuery},
@ -52,11 +53,9 @@ pub fn create_proof<C: CurveAffine, T: TranscriptWrite<C>, ConcreteCircuit: Circ
.iter() .iter()
.map(|poly| params.commit_lagrange(poly, Blind::default())) .map(|poly| params.commit_lagrange(poly, Blind::default()))
.collect(); .collect();
let mut instance_commitments = vec![C::zero(); instance_commitments_projective.len()]; let mut instance_commitments =
C::Projective::batch_to_affine( vec![C::identity(); instance_commitments_projective.len()];
&instance_commitments_projective, C::Curve::batch_normalize(&instance_commitments_projective, &mut instance_commitments);
&mut instance_commitments,
);
let instance_commitments = instance_commitments; let instance_commitments = instance_commitments;
drop(instance_commitments_projective); drop(instance_commitments_projective);
metrics::counter!("instance_commitments", instance_commitments.len() as u64); metrics::counter!("instance_commitments", instance_commitments.len() as u64);
@ -206,8 +205,8 @@ pub fn create_proof<C: CurveAffine, T: TranscriptWrite<C>, ConcreteCircuit: Circ
.zip(advice_blinds.iter()) .zip(advice_blinds.iter())
.map(|(poly, blind)| params.commit_lagrange(poly, *blind)) .map(|(poly, blind)| params.commit_lagrange(poly, *blind))
.collect(); .collect();
let mut advice_commitments = vec![C::zero(); advice_commitments_projective.len()]; let mut advice_commitments = vec![C::identity(); advice_commitments_projective.len()];
C::Projective::batch_to_affine(&advice_commitments_projective, &mut advice_commitments); C::Curve::batch_normalize(&advice_commitments_projective, &mut advice_commitments);
let advice_commitments = advice_commitments; let advice_commitments = advice_commitments;
drop(advice_commitments_projective); drop(advice_commitments_projective);
metrics::counter!("advice_commitments", advice_commitments.len() as u64); metrics::counter!("advice_commitments", advice_commitments.len() as u64);

View file

@ -1,6 +1,8 @@
use group::Curve;
use super::Argument; use super::Argument;
use crate::{ use crate::{
arithmetic::{eval_polynomial, Curve, CurveAffine, FieldExt}, arithmetic::{eval_polynomial, CurveAffine, FieldExt},
plonk::{ChallengeX, ChallengeY, Error}, plonk::{ChallengeX, ChallengeY, Error},
poly::{ poly::{
commitment::{Blind, Params}, commitment::{Blind, Params},
@ -50,8 +52,8 @@ impl<C: CurveAffine> Argument<C> {
.zip(h_blinds.iter()) .zip(h_blinds.iter())
.map(|(h_piece, blind)| params.commit(&h_piece, *blind)) .map(|(h_piece, blind)| params.commit(&h_piece, *blind))
.collect(); .collect();
let mut h_commitments = vec![C::zero(); h_commitments_projective.len()]; let mut h_commitments = vec![C::identity(); h_commitments_projective.len()];
C::Projective::batch_to_affine(&h_commitments_projective, &mut h_commitments); C::Curve::batch_normalize(&h_commitments_projective, &mut h_commitments);
let h_commitments = h_commitments; let h_commitments = h_commitments;
// Hash each h(X) piece // Hash each h(X) piece

View file

@ -6,10 +6,10 @@
use blake2b_simd::{Params as Blake2bParams, State as Blake2bState}; use blake2b_simd::{Params as Blake2bParams, State as Blake2bState};
use super::{Coeff, LagrangeCoeff, Polynomial}; 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 ff::{Field, PrimeField};
use std::convert::TryInto; use group::{prime::PrimeCurveAffine, Curve};
use std::ops::{Add, AddAssign, Mul, MulAssign}; use std::ops::{Add, AddAssign, Mul, MulAssign};
mod msm; mod msm;
@ -36,7 +36,10 @@ pub struct Params<C: CurveAffine> {
impl<C: CurveAffine> Params<C> { impl<C: CurveAffine> Params<C> {
/// Initializes parameters for the curve, given a random oracle to draw /// Initializes parameters for the curve, given a random oracle to draw
/// points from. /// points from.
pub fn new(k: u32) -> Self { pub fn new(k: u32) -> Self
where
<C as PrimeCurveAffine>::Curve: Group,
{
// This is usually a limitation on the curve, but we also want 32-bit // This is usually a limitation on the curve, but we also want 32-bit
// architectures to be supported. // architectures to be supported.
assert!(k < 32); assert!(k < 32);
@ -50,7 +53,9 @@ impl<C: CurveAffine> Params<C> {
loop { loop {
let mut hasher = hasher.clone(); let mut hasher = hasher.clone();
hasher.update(&(trial.to_le_bytes())[..]); 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()) { if bool::from(p.is_some()) {
break p.unwrap(); break p.unwrap();
} }
@ -60,7 +65,7 @@ impl<C: CurveAffine> Params<C> {
let g = { let g = {
let mut g = Vec::with_capacity(n as usize); 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| { parallelize(&mut g, move |g, start| {
let mut hasher = Blake2bParams::new() let mut hasher = Blake2bParams::new()
@ -83,11 +88,11 @@ impl<C: CurveAffine> Params<C> {
// Let's evaluate all of the Lagrange basis polynomials // Let's evaluate all of the Lagrange basis polynomials
// using an inverse FFT. // using an inverse FFT.
let mut alpha_inv = C::Scalar::ROOT_OF_UNITY_INV; let mut alpha_inv = <<C as PrimeCurveAffine>::Curve as Group>::Scalar::ROOT_OF_UNITY_INV;
for _ in k..C::Scalar::S { for _ in k..C::Scalar::S {
alpha_inv = alpha_inv.square(); alpha_inv = alpha_inv.square();
} }
let mut g_lagrange_projective = g.iter().map(|g| g.to_projective()).collect::<Vec<_>>(); let mut g_lagrange_projective = g.iter().map(|g| g.to_curve()).collect::<Vec<_>>();
best_fft(&mut g_lagrange_projective, alpha_inv, k); best_fft(&mut g_lagrange_projective, alpha_inv, k);
let minv = C::Scalar::TWO_INV.pow_vartime(&[k as u64, 0, 0, 0]); let minv = C::Scalar::TWO_INV.pow_vartime(&[k as u64, 0, 0, 0]);
parallelize(&mut g_lagrange_projective, |g, _| { parallelize(&mut g_lagrange_projective, |g, _| {
@ -97,9 +102,9 @@ impl<C: CurveAffine> Params<C> {
}); });
let g_lagrange = { 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| { 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_projective[starts..(starts + g_lagrange.len())],
g_lagrange, g_lagrange,
); );
@ -141,11 +146,7 @@ impl<C: CurveAffine> Params<C> {
/// This computes a commitment to a polynomial described by the provided /// This computes a commitment to a polynomial described by the provided
/// slice of coefficients. The commitment will be blinded by the blinding /// slice of coefficients. The commitment will be blinded by the blinding
/// factor `r`. /// factor `r`.
pub fn commit( pub fn commit(&self, poly: &Polynomial<C::Scalar, Coeff>, r: Blind<C::Scalar>) -> C::Curve {
&self,
poly: &Polynomial<C::Scalar, Coeff>,
r: Blind<C::Scalar>,
) -> C::Projective {
metrics::increment_counter!("multiexp", "size" => format!("{}", poly.len() + 1), "fn" => "commit"); metrics::increment_counter!("multiexp", "size" => format!("{}", poly.len() + 1), "fn" => "commit");
let mut tmp_scalars = Vec::with_capacity(poly.len() + 1); let mut tmp_scalars = Vec::with_capacity(poly.len() + 1);
let mut tmp_bases = Vec::with_capacity(poly.len() + 1); let mut tmp_bases = Vec::with_capacity(poly.len() + 1);
@ -166,7 +167,7 @@ impl<C: CurveAffine> Params<C> {
&self, &self,
poly: &Polynomial<C::Scalar, LagrangeCoeff>, poly: &Polynomial<C::Scalar, LagrangeCoeff>,
r: Blind<C::Scalar>, r: Blind<C::Scalar>,
) -> C::Projective { ) -> C::Curve {
metrics::increment_counter!("multiexp", "size" => format!("{}", poly.len() + 1), "fn" => "commit_lagrange"); 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_scalars = Vec::with_capacity(poly.len() + 1);
let mut tmp_bases = Vec::with_capacity(poly.len() + 1); let mut tmp_bases = Vec::with_capacity(poly.len() + 1);
@ -195,13 +196,13 @@ impl<C: CurveAffine> Params<C> {
pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> { pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
writer.write_all(&self.k.to_le_bytes())?; writer.write_all(&self.k.to_le_bytes())?;
for g_element in &self.g { 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 { 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.h.to_bytes().as_ref())?;
writer.write_all(&self.u.to_bytes())?; writer.write_all(self.u.to_bytes().as_ref())?;
Ok(()) Ok(())
} }

View file

@ -1,6 +1,7 @@
use super::Params; use super::Params;
use crate::arithmetic::{best_multiexp, parallelize, Curve, CurveAffine}; use crate::arithmetic::{best_multiexp, parallelize, CurveAffine};
use ff::Field; use ff::Field;
use group::Group;
/// A multiscalar multiplication in the polynomial commitment scheme /// A multiscalar multiplication in the polynomial commitment scheme
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -144,6 +145,6 @@ impl<'a, C: CurveAffine> MSM<'a, C> {
assert_eq!(scalars.len(), len); assert_eq!(scalars.len(), len);
metrics::increment_counter!("multiexp", "size" => format!("{}", len), "fn" => "MSM::eval"); 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())
} }
} }

View file

@ -3,10 +3,11 @@ use ff::Field;
use super::super::{Coeff, Polynomial}; use super::super::{Coeff, Polynomial};
use super::{Blind, Params}; use super::{Blind, Params};
use crate::arithmetic::{ use crate::arithmetic::{
best_multiexp, compute_inner_product, eval_polynomial, parallelize, Curve, CurveAffine, best_multiexp, compute_inner_product, eval_polynomial, parallelize, CurveAffine, FieldExt,
FieldExt,
}; };
use crate::transcript::{Challenge, ChallengeScalar, TranscriptWrite}; use crate::transcript::{Challenge, ChallengeScalar, TranscriptWrite};
use group::Curve;
use std::io; use std::io;
/// Create a polynomial commitment opening proof for the polynomial defined /// Create a polynomial commitment opening proof for the polynomial defined
@ -152,8 +153,8 @@ fn parallel_generator_collapse<C: CurveAffine>(g: &mut [C], challenge: C::Scalar
let g_hi = &g_hi[start..]; let g_hi = &g_hi[start..];
let mut tmp = Vec::with_capacity(g_lo.len()); let mut tmp = Vec::with_capacity(g_lo.len());
for (g_lo, g_hi) in g_lo.iter().zip(g_hi.iter()) { 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);
}); });
} }

View file

@ -1,10 +1,11 @@
use ff::Field; use ff::Field;
use group::Curve;
use super::super::Error; use super::super::Error;
use super::{Params, MSM}; use super::{Params, MSM};
use crate::transcript::{Challenge, ChallengeScalar, TranscriptRead}; 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 /// A guard returned by the verifier
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View file

@ -206,8 +206,10 @@ where
#[test] #[test]
fn test_roundtrip() { fn test_roundtrip() {
use group::Curve;
use super::commitment::{Blind, Params}; use super::commitment::{Blind, Params};
use crate::arithmetic::{eval_polynomial, Curve, FieldExt}; use crate::arithmetic::{eval_polynomial, FieldExt};
use crate::pasta::{EqAffine, Fp}; use crate::pasta::{EqAffine, Fp};
const K: u32 = 4; const K: u32 = 4;

View file

@ -7,10 +7,11 @@ use super::{
Query, 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 crate::transcript::TranscriptWrite;
use ff::Field; use ff::Field;
use group::Curve;
use std::io; use std::io;
use std::marker::PhantomData; use std::marker::PhantomData;

View file

@ -69,8 +69,8 @@ impl<R: Read, C: CurveAffine> Blake2bRead<R, C> {
impl<R: Read, C: CurveAffine> TranscriptRead<C> for Blake2bRead<R, C> { impl<R: Read, C: CurveAffine> TranscriptRead<C> for Blake2bRead<R, C> {
fn read_point(&mut self) -> io::Result<C> { fn read_point(&mut self) -> io::Result<C> {
let mut compressed = [0u8; 32]; let mut compressed = C::Repr::default();
self.reader.read_exact(&mut compressed[..])?; self.reader.read_exact(compressed.as_mut())?;
let point: C = Option::from(C::from_bytes(&compressed)).ok_or_else(|| { let point: C = Option::from(C::from_bytes(&compressed)).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "invalid point encoding in proof") io::Error::new(io::ErrorKind::Other, "invalid point encoding in proof")
})?; })?;
@ -154,7 +154,7 @@ impl<W: Write, C: CurveAffine> TranscriptWrite<C> for Blake2bWrite<W, C> {
fn write_point(&mut self, point: C) -> io::Result<()> { fn write_point(&mut self, point: C) -> io::Result<()> {
self.common_point(point)?; self.common_point(point)?;
let compressed = point.to_bytes(); 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<()> { fn write_scalar(&mut self, scalar: C::Scalar) -> io::Result<()> {
self.common_scalar(scalar)?; self.common_scalar(scalar)?;