Merge pull request #697 from zcash/fieldext-finale

Migrate to `ff` revision without `FieldExt`
This commit is contained in:
str4d 2022-12-05 19:27:06 +00:00 committed by GitHub
commit 677866d653
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
61 changed files with 370 additions and 354 deletions

View File

@ -4,3 +4,7 @@ members = [
"halo2_gadgets",
"halo2_proofs",
]
[patch.crates-io]
ff = { git = "https://github.com/zkcrypto/ff.git", rev = "c555625ab4e6e26560ec5323fd99fef6eba18365" }
pasta_curves = { git = "https://github.com/zcash/pasta_curves.git", rev = "825cb944decfab4b1a64380d15a43eb93899dfad" }

View File

@ -1,10 +1,13 @@
use super::EccPoint;
use group::ff::PrimeField;
use halo2_proofs::{
circuit::Region,
plonk::{Advice, Assigned, Column, ConstraintSystem, Constraints, Error, Expression, Selector},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use std::collections::HashSet;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]

View File

@ -6,10 +6,7 @@ use group::{
Curve,
};
use halo2_proofs::arithmetic::lagrange_interpolate;
use pasta_curves::{
arithmetic::{CurveAffine, FieldExt},
pallas,
};
use pasta_curves::{arithmetic::CurveAffine, pallas};
/// Window size for fixed-base scalar multiplication
pub const FIXED_BASE_WINDOW_SIZE: usize = 3;
@ -64,7 +61,7 @@ fn compute_window_table<C: CurveAffine>(base: C, num_windows: usize) -> Vec<[C;
// Generate window table entries for the last window, w = `num_windows - 1`.
// For the last window, we compute [k * (2^3)^w - sum]B, where sum is defined
// as sum = \sum_{j = 0}^{`num_windows - 2`} 2^{3j+1}
let sum = (0..(num_windows - 1)).fold(C::Scalar::zero(), |acc, j| {
let sum = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, j| {
acc + C::Scalar::from(2).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * j as u64 + 1, 0, 0, 0])
});
window_table.push(
@ -184,7 +181,7 @@ pub fn test_lagrange_coeffs<C: CurveAffine>(base: C, num_windows: usize) {
.rev()
.cloned()
.reduce(|acc, coeff| acc * x + coeff)
.unwrap_or_else(C::Base::zero)
.unwrap_or(C::Base::ZERO)
}
let lagrange_coeffs = compute_lagrange_coeffs(base, num_windows);
@ -216,7 +213,7 @@ pub fn test_lagrange_coeffs<C: CurveAffine>(base: C, num_windows: usize) {
// Compute the actual x-coordinate of the multiple [k * (8^84) - offset]B,
// where offset = \sum_{j = 0}^{83} 2^{3j+1}
let offset = (0..(num_windows - 1)).fold(C::Scalar::zero(), |acc, w| {
let offset = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, w| {
acc + C::Scalar::from(2).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0])
});
let scalar = C::Scalar::from(bits as u64)
@ -232,11 +229,9 @@ pub fn test_lagrange_coeffs<C: CurveAffine>(base: C, num_windows: usize) {
#[cfg(test)]
mod tests {
use ff::FromUniformBytes;
use group::{ff::Field, Curve, Group};
use pasta_curves::{
arithmetic::{CurveAffine, FieldExt},
pallas,
};
use pasta_curves::{arithmetic::CurveAffine, pallas};
use proptest::prelude::*;
use super::{compute_window_table, find_zs_and_us, test_lagrange_coeffs, H, NUM_WINDOWS};
@ -247,7 +242,7 @@ mod tests {
// Instead of rejecting out-of-range bytes, let's reduce them.
let mut buf = [0; 64];
buf[..32].copy_from_slice(&bytes);
let scalar = pallas::Scalar::from_bytes_wide(&buf);
let scalar = pallas::Scalar::from_uniform_bytes(&buf);
pallas::Point::generator() * scalar
}
}

View File

@ -1,6 +1,8 @@
use super::super::NonIdentityEccPoint;
use super::{X, Y, Z};
use crate::utilities::bool_check;
use group::ff::PrimeField;
use halo2_proofs::{
circuit::{Region, Value},
plonk::{
@ -8,8 +10,7 @@ use halo2_proofs::{
},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
/// A helper struct for implementing single-row double-and-add using incomplete addition.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]

View File

@ -3,14 +3,14 @@ use crate::{
sinsemilla::primitives as sinsemilla, utilities::lookup_range_check::LookupRangeCheckConfig,
};
use group::ff::PrimeField;
use halo2_proofs::circuit::AssignedCell;
use halo2_proofs::{
circuit::Layouter,
plonk::{Advice, Assigned, Column, ConstraintSystem, Constraints, Error, Expression, Selector},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use std::iter;

View File

@ -7,7 +7,7 @@ use crate::utilities::decompose_running_sum::RunningSumConfig;
use std::marker::PhantomData;
use group::{
ff::{PrimeField, PrimeFieldBits},
ff::{Field, PrimeField, PrimeFieldBits},
Curve,
};
use halo2_proofs::{
@ -19,10 +19,7 @@ use halo2_proofs::{
poly::Rotation,
};
use lazy_static::lazy_static;
use pasta_curves::{
arithmetic::{CurveAffine, FieldExt},
pallas,
};
use pasta_curves::{arithmetic::CurveAffine, pallas};
pub mod base_field_elem;
pub mod full_width;

View File

@ -13,7 +13,7 @@ use halo2_proofs::{
plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Expression, Selector},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use std::convert::TryInto;

View File

@ -251,7 +251,7 @@ pub mod tests {
circuit::{AssignedCell, Chip, Layouter, Value},
plonk::{Any, Error},
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use crate::{
ecc::{

View File

@ -4,9 +4,8 @@ use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use group::ff::Field;
use group::ff::{Field, PrimeField};
use halo2_proofs::{
arithmetic::FieldExt,
circuit::{AssignedCell, Chip, Layouter},
plonk::Error,
};
@ -267,7 +266,7 @@ impl<
}
impl<
F: FieldExt,
F: PrimeField,
PoseidonChip: PoseidonSpongeInstructions<F, S, ConstantLength<L>, T, RATE>,
S: Spec<F, T, RATE>,
const T: usize,

View File

@ -3,7 +3,6 @@ use std::iter;
use group::ff::Field;
use halo2_proofs::{
arithmetic::FieldExt,
circuit::{AssignedCell, Cell, Chip, Layouter, Region, Value},
plonk::{
Advice, Any, Column, ConstraintSystem, Constraints, Error, Expression, Fixed, Selector,
@ -221,7 +220,7 @@ impl<F: Field, const WIDTH: usize, const RATE: usize> Chip<F> for Pow5Chip<F, WI
}
}
impl<F: FieldExt, S: Spec<F, WIDTH, RATE>, const WIDTH: usize, const RATE: usize>
impl<F: Field, S: Spec<F, WIDTH, RATE>, const WIDTH: usize, const RATE: usize>
PoseidonInstructions<F, S, WIDTH, RATE> for Pow5Chip<F, WIDTH, RATE>
{
type Word = StateWord<F>;
@ -272,7 +271,7 @@ impl<F: FieldExt, S: Spec<F, WIDTH, RATE>, const WIDTH: usize, const RATE: usize
}
impl<
F: FieldExt,
F: Field,
S: Spec<F, WIDTH, RATE>,
D: Domain<F, RATE>,
const WIDTH: usize,
@ -301,7 +300,7 @@ impl<
};
for i in 0..RATE {
load_state_word(i, F::zero())?;
load_state_word(i, F::ZERO)?;
}
load_state_word(RATE, D::initial_capacity_element())?;
@ -371,7 +370,7 @@ impl<
.get(i)
.map(|word| word.0.value().cloned())
// The capacity element is never altered by the input.
.unwrap_or_else(|| Value::known(F::zero()));
.unwrap_or_else(|| Value::known(F::ZERO));
region
.assign_advice(
|| format!("load output_{}", i),
@ -429,7 +428,7 @@ impl<F: Field> Var<F> for StateWord<F> {
#[derive(Debug)]
struct Pow5State<F: Field, const WIDTH: usize>([StateWord<F>; WIDTH]);
impl<F: FieldExt, const WIDTH: usize> Pow5State<F, WIDTH> {
impl<F: Field, const WIDTH: usize> Pow5State<F, WIDTH> {
fn full_round<const RATE: usize>(
self,
region: &mut Region<F>,
@ -449,7 +448,7 @@ impl<F: FieldExt, const WIDTH: usize> Pow5State<F, WIDTH> {
r.as_ref().map(|r| {
r.iter()
.enumerate()
.fold(F::zero(), |acc, (j, r_j)| acc + m_i[j] * r_j)
.fold(F::ZERO, |acc, (j, r_j)| acc + m_i[j] * r_j)
})
});
@ -490,7 +489,7 @@ impl<F: FieldExt, const WIDTH: usize> Pow5State<F, WIDTH> {
r.as_ref().map(|r| {
m_i.iter()
.zip(r.iter())
.fold(F::zero(), |acc, (m_ij, r_j)| acc + *m_ij * r_j)
.fold(F::ZERO, |acc, (m_ij, r_j)| acc + *m_ij * r_j)
})
})
.collect();
@ -523,7 +522,7 @@ impl<F: FieldExt, const WIDTH: usize> Pow5State<F, WIDTH> {
r_mid.as_ref().map(|r| {
m_i.iter()
.zip(r.iter())
.fold(F::zero(), |acc, (m_ij, r_j)| acc + *m_ij * r_j)
.fold(F::ZERO, |acc, (m_ij, r_j)| acc + *m_ij * r_j)
})
})
.collect();

View File

@ -5,8 +5,7 @@ use std::fmt;
use std::iter;
use std::marker::PhantomData;
use group::ff::Field;
use halo2_proofs::arithmetic::FieldExt;
use group::ff::{Field, FromUniformBytes, PrimeField};
pub(crate) mod fp;
pub(crate) mod fq;
@ -55,8 +54,12 @@ pub trait Spec<F: Field, const T: usize, const RATE: usize>: fmt::Debug {
}
/// Generates `(round_constants, mds, mds^-1)` corresponding to this specification.
pub fn generate_constants<F: FieldExt, S: Spec<F, T, RATE>, const T: usize, const RATE: usize>(
) -> (Vec<[F; T]>, Mds<F, T>, Mds<F, T>) {
pub fn generate_constants<
F: FromUniformBytes<64> + Ord,
S: Spec<F, T, RATE>,
const T: usize,
const RATE: usize,
>() -> (Vec<[F; T]>, Mds<F, T>, Mds<F, T>) {
let r_f = S::full_rounds();
let r_p = S::partial_rounds();
@ -64,7 +67,7 @@ pub fn generate_constants<F: FieldExt, S: Spec<F, T, RATE>, const T: usize, cons
let round_constants = (0..(r_f + r_p))
.map(|_| {
let mut rc_row = [F::zero(); T];
let mut rc_row = [F::ZERO; T];
for (rc, value) in rc_row
.iter_mut()
.zip((0..T).map(|_| grain.next_field_element()))
@ -90,7 +93,7 @@ pub(crate) fn permute<F: Field, S: Spec<F, T, RATE>, const T: usize, const RATE:
let r_p = S::partial_rounds();
let apply_mds = |state: &mut State<F, T>| {
let mut new_state = [F::zero(); T];
let mut new_state = [F::ZERO; T];
// Matrix multiplication
#[allow(clippy::needless_range_loop)]
for i in 0..T {
@ -206,7 +209,7 @@ impl<F: Field, S: Spec<F, T, RATE>, const T: usize, const RATE: usize>
let (round_constants, mds_matrix, _) = S::constants();
let mode = Absorbing([None; RATE]);
let mut state = [F::zero(); T];
let mut state = [F::ZERO; T];
state[RATE] = initial_capacity_element;
Sponge {
@ -300,7 +303,7 @@ pub trait Domain<F: Field, const RATE: usize> {
#[derive(Clone, Copy, Debug)]
pub struct ConstantLength<const L: usize>;
impl<F: FieldExt, const RATE: usize, const L: usize> Domain<F, RATE> for ConstantLength<L> {
impl<F: PrimeField, const RATE: usize, const L: usize> Domain<F, RATE> for ConstantLength<L> {
type Padding = iter::Take<iter::Repeat<F>>;
fn name() -> String {
@ -320,7 +323,7 @@ impl<F: FieldExt, const RATE: usize, const L: usize> Domain<F, RATE> for Constan
// Poseidon authors encode the constant length into the capacity element, ensuring
// that inputs of different lengths do not share the same permutation.
let k = (L + RATE - 1) / RATE;
iter::repeat(F::zero()).take(k * RATE - L)
iter::repeat(F::ZERO).take(k * RATE - L)
}
}
@ -362,7 +365,7 @@ impl<F: Field, S: Spec<F, T, RATE>, D: Domain<F, RATE>, const T: usize, const RA
}
}
impl<F: FieldExt, S: Spec<F, T, RATE>, const T: usize, const RATE: usize, const L: usize>
impl<F: PrimeField, S: Spec<F, T, RATE>, const T: usize, const RATE: usize, const L: usize>
Hash<F, S, ConstantLength<L>, T, RATE>
{
/// Hashes the given input.
@ -379,7 +382,7 @@ impl<F: FieldExt, S: Spec<F, T, RATE>, const T: usize, const RATE: usize, const
#[cfg(test)]
mod tests {
use halo2_proofs::arithmetic::FieldExt;
use group::ff::PrimeField;
use pasta_curves::pallas;
use super::{permute, ConstantLength, Hash, P128Pow5T3 as OrchardNullifier, Spec};

View File

@ -3,8 +3,7 @@
use std::marker::PhantomData;
use bitvec::prelude::*;
use group::ff::{Field, PrimeField};
use halo2_proofs::arithmetic::FieldExt;
use group::ff::{Field, FromUniformBytes, PrimeField};
const STATE: usize = 80;
@ -138,7 +137,7 @@ impl<F: PrimeField> Grain<F> {
}
}
impl<F: FieldExt> Grain<F> {
impl<F: FromUniformBytes<64>> Grain<F> {
/// Returns the next field element from this Grain instantiation, without using
/// rejection sampling.
pub(super) fn next_field_element_without_rejection(&mut self) -> F {
@ -164,7 +163,7 @@ impl<F: FieldExt> Grain<F> {
view[i / 8] |= if bit { 1 << (i % 8) } else { 0 };
}
F::from_bytes_wide(&bytes)
F::from_uniform_bytes(&bytes)
}
}

View File

@ -1,8 +1,8 @@
use halo2_proofs::arithmetic::FieldExt;
use ff::FromUniformBytes;
use super::{grain::Grain, Mds};
pub(super) fn generate_mds<F: FieldExt, const T: usize>(
pub(super) fn generate_mds<F: FromUniformBytes<64> + Ord, const T: usize>(
grain: &mut Grain<F>,
mut select: usize,
) -> (Mds<F, T>, Mds<F, T>) {
@ -48,7 +48,7 @@ pub(super) fn generate_mds<F: FieldExt, const T: usize>(
// However, the Poseidon paper and reference impl use the positive formulation,
// and we want to rely on the reference impl for MDS security, so we use the same
// formulation.
let mut mds = [[F::zero(); T]; T];
let mut mds = [[F::ZERO; T]; T];
#[allow(clippy::needless_range_loop)]
for i in 0..T {
for j in 0..T {
@ -74,10 +74,10 @@ pub(super) fn generate_mds<F: FieldExt, const T: usize>(
// where A_i(x) and B_i(x) are the Lagrange polynomials for xs and ys respectively.
//
// We adapt this to the positive Cauchy formulation by negating ys.
let mut mds_inv = [[F::zero(); T]; T];
let mut mds_inv = [[F::ZERO; T]; T];
let l = |xs: &[F], j, x: F| {
let x_j = xs[j];
xs.iter().enumerate().fold(F::one(), |acc, (m, x_m)| {
xs.iter().enumerate().fold(F::ONE, |acc, (m, x_m)| {
if m == j {
acc
} else {
@ -98,6 +98,7 @@ pub(super) fn generate_mds<F: FieldExt, const T: usize>(
#[cfg(test)]
mod tests {
use group::ff::Field;
use pasta_curves::Fp;
use super::{generate_mds, Grain};
@ -112,9 +113,9 @@ mod tests {
#[allow(clippy::needless_range_loop)]
for i in 0..T {
for j in 0..T {
let expected = if i == j { Fp::one() } else { Fp::zero() };
let expected = if i == j { Fp::ONE } else { Fp::ZERO };
assert_eq!(
(0..T).fold(Fp::zero(), |acc, k| acc + (mds[i][k] * mds_inv[k][j])),
(0..T).fold(Fp::ZERO, |acc, k| acc + (mds[i][k] * mds_inv[k][j])),
expected
);
}

View File

@ -66,11 +66,9 @@ impl Spec<Fq, 3, 2> for P128Pow5T3 {
#[cfg(test)]
mod tests {
use ff::{Field, PrimeField};
use ff::{Field, FromUniformBytes, PrimeField};
use std::marker::PhantomData;
use pasta_curves::arithmetic::FieldExt;
use super::{
super::{fp, fq},
Fp, Fq,
@ -91,7 +89,9 @@ mod tests {
}
}
impl<F: FieldExt, const SECURE_MDS: usize> Spec<F, 3, 2> for P128Pow5T3Gen<F, SECURE_MDS> {
impl<F: FromUniformBytes<64> + Ord, const SECURE_MDS: usize> Spec<F, 3, 2>
for P128Pow5T3Gen<F, SECURE_MDS>
{
fn full_rounds() -> usize {
8
}
@ -115,7 +115,7 @@ mod tests {
#[test]
fn verify_constants() {
fn verify_constants_helper<F: FieldExt>(
fn verify_constants_helper<F: FromUniformBytes<64> + Ord>(
expected_round_constants: [[F; 3]; 64],
expected_mds: [[F; 3]; 3],
expected_mds_inv: [[F; 3]; 3],

View File

@ -8,7 +8,7 @@ pub struct CompressionGate<F: Field>(PhantomData<F>);
impl<F: PrimeField> CompressionGate<F> {
fn ones() -> Expression<F> {
Expression::Constant(F::one())
Expression::Constant(F::ONE)
}
// Decompose `A,B,C,D` words
@ -58,16 +58,16 @@ impl<F: PrimeField> CompressionGate<F> {
+ c_mid * F::from(1 << 16)
+ c_hi * F::from(1 << 19)
+ d * F::from(1 << 22)
+ word_lo * (-F::one())
+ word_hi * F::from(1 << 16) * (-F::one());
+ word_lo * (-F::ONE)
+ word_hi * F::from(1 << 16) * (-F::ONE);
let spread_check = spread_a
+ spread_b * F::from(1 << 4)
+ spread_c_lo * F::from(1 << 26)
+ spread_c_mid * F::from(1 << 32)
+ spread_c_hi * F::from(1 << 38)
+ spread_d * F::from(1 << 44)
+ spread_word_lo * (-F::one())
+ spread_word_hi * F::from(1 << 32) * (-F::one());
+ spread_word_lo * (-F::ONE)
+ spread_word_hi * F::from(1 << 32) * (-F::ONE);
Constraints::with_selector(
s_decompose_abcd,
@ -129,16 +129,16 @@ impl<F: PrimeField> CompressionGate<F> {
+ b_hi * F::from(1 << 8)
+ c * F::from(1 << 11)
+ d * F::from(1 << 25)
+ word_lo * (-F::one())
+ word_hi * F::from(1 << 16) * (-F::one());
+ word_lo * (-F::ONE)
+ word_hi * F::from(1 << 16) * (-F::ONE);
let spread_check = spread_a_lo
+ spread_a_hi * F::from(1 << 6)
+ spread_b_lo * F::from(1 << 12)
+ spread_b_hi * F::from(1 << 16)
+ spread_c * F::from(1 << 22)
+ spread_d * F::from(1 << 50)
+ spread_word_lo * (-F::one())
+ spread_word_hi * F::from(1 << 32) * (-F::one());
+ spread_word_lo * (-F::ONE)
+ spread_word_hi * F::from(1 << 32) * (-F::ONE);
Constraints::with_selector(
s_decompose_efgh,
@ -188,7 +188,7 @@ impl<F: PrimeField> CompressionGate<F> {
+ spread_c_mid * F::from(1 << 52)
+ spread_c_hi * F::from(1 << 58);
let xor = xor_0 + xor_1 + xor_2;
let check = spread_witness + (xor * -F::one());
let check = spread_witness + (xor * -F::ONE);
Some(("s_upper_sigma_0", s_upper_sigma_0 * check))
}
@ -232,7 +232,7 @@ impl<F: PrimeField> CompressionGate<F> {
+ spread_b_hi * F::from(1 << 30)
+ spread_c * F::from(1 << 36);
let xor = xor_0 + xor_1 + xor_2;
let check = spread_witness + (xor * -F::one());
let check = spread_witness + (xor * -F::ONE);
Some(("s_upper_sigma_1", s_upper_sigma_1 * check))
}
@ -258,7 +258,7 @@ impl<F: PrimeField> CompressionGate<F> {
let rhs_odd = spread_p0_odd + spread_p1_odd * F::from(1 << 32);
let rhs = rhs_even + rhs_odd * F::from(2);
let check = lhs + rhs * -F::one();
let check = lhs + rhs * -F::ONE;
Some(("s_ch", s_ch * check))
}
@ -285,9 +285,9 @@ impl<F: PrimeField> CompressionGate<F> {
let neg_check = {
let evens = Self::ones() * F::from(MASK_EVEN_32 as u64);
// evens - spread_e_lo = spread_e_neg_lo
let lo_check = spread_e_neg_lo.clone() + spread_e_lo + (evens.clone() * (-F::one()));
let lo_check = spread_e_neg_lo.clone() + spread_e_lo + (evens.clone() * (-F::ONE));
// evens - spread_e_hi = spread_e_neg_hi
let hi_check = spread_e_neg_hi.clone() + spread_e_hi + (evens * (-F::one()));
let hi_check = spread_e_neg_hi.clone() + spread_e_hi + (evens * (-F::ONE));
std::iter::empty()
.chain(Some(("lo_check", lo_check)))

View File

@ -5,7 +5,7 @@ pub struct Gate<F: PrimeField>(pub Expression<F>);
impl<F: PrimeField> Gate<F> {
fn ones() -> Expression<F> {
Expression::Constant(F::one())
Expression::Constant(F::ONE)
}
// Helper gates
@ -33,7 +33,7 @@ impl<F: PrimeField> Gate<F> {
for i in 0..deg {
let i = i as u64;
if i != idx {
expr = expr * (Self::ones() * (-F::one()) * F::from(i) + var.clone());
expr = expr * (Self::ones() * (-F::ONE) * F::from(i) + var.clone());
}
}
expr * F::from(u64::from(eval))
@ -47,13 +47,13 @@ impl<F: PrimeField> Gate<F> {
}
}
if denom < 0 {
-F::one() * F::from(factor / (-denom as u64))
-F::ONE * F::from(factor / (-denom as u64))
} else {
F::from(factor / (denom as u64))
}
};
let mut expr = Self::ones() * F::zero();
let mut expr = Self::ones() * F::ZERO;
for ((idx, _), eval) in points.iter().enumerate().zip(evals.iter()) {
expr = expr + numerator(var.clone(), *eval, idx as u64) * denominator(idx as i32)
}
@ -64,7 +64,7 @@ impl<F: PrimeField> Gate<F> {
pub fn range_check(value: Expression<F>, lower_range: u64, upper_range: u64) -> Expression<F> {
let mut expr = Self::ones();
for i in lower_range..(upper_range + 1) {
expr = expr * (Self::ones() * (-F::one()) * F::from(i) + value.clone())
expr = expr * (Self::ones() * (-F::ONE) * F::from(i) + value.clone())
}
expr
}

View File

@ -27,8 +27,8 @@ impl<F: PrimeField> ScheduleGate<F> {
let word_check = lo
+ hi * F::from(1 << 16)
+ (carry.clone() * F::from(1 << 32) * (-F::one()))
+ (word * (-F::one()));
+ (carry.clone() * F::from(1 << 32) * (-F::ONE))
+ (word * (-F::ONE));
let carry_check = Gate::range_check(carry, 0, 3);
[("word_check", word_check), ("carry_check", carry_check)]
@ -60,11 +60,8 @@ impl<F: PrimeField> ScheduleGate<F> {
tag_d: Expression<F>,
word: Expression<F>,
) -> impl Iterator<Item = (&'static str, Expression<F>)> {
let decompose_check = a
+ b * F::from(1 << 3)
+ c * F::from(1 << 7)
+ d * F::from(1 << 18)
+ word * (-F::one());
let decompose_check =
a + b * F::from(1 << 3) + c * F::from(1 << 7) + d * F::from(1 << 18) + word * (-F::ONE);
let range_check_tag_c = Gate::range_check(tag_c, 0, 2);
let range_check_tag_d = Gate::range_check(tag_d, 0, 4);
@ -101,7 +98,7 @@ impl<F: PrimeField> ScheduleGate<F> {
+ e * F::from(1 << 17)
+ f * F::from(1 << 18)
+ g * F::from(1 << 19)
+ word * (-F::one());
+ word * (-F::ONE);
let range_check_tag_d = Gate::range_check(tag_d, 0, 0);
let range_check_tag_g = Gate::range_check(tag_g, 0, 3);
@ -131,7 +128,7 @@ impl<F: PrimeField> ScheduleGate<F> {
+ b * F::from(1 << 10)
+ c * F::from(1 << 17)
+ d * F::from(1 << 19)
+ word * (-F::one());
+ word * (-F::ONE);
let range_check_tag_a = Gate::range_check(tag_a, 0, 1);
let range_check_tag_d = Gate::range_check(tag_d, 0, 3);

View File

@ -260,34 +260,31 @@ impl<F: PrimeField> SpreadTableChip<F> {
impl SpreadTableConfig {
fn generate<F: PrimeField>() -> impl Iterator<Item = (F, F, F)> {
(1..=(1 << 16)).scan(
(F::zero(), F::zero(), F::zero()),
|(tag, dense, spread), i| {
// We computed this table row in the previous iteration.
let res = (*tag, *dense, *spread);
(1..=(1 << 16)).scan((F::ZERO, F::ZERO, F::ZERO), |(tag, dense, spread), i| {
// We computed this table row in the previous iteration.
let res = (*tag, *dense, *spread);
// i holds the zero-indexed row number for the next table row.
match i {
BITS_7 | BITS_10 | BITS_11 | BITS_13 | BITS_14 => *tag += F::one(),
_ => (),
}
*dense += F::one();
if i & 1 == 0 {
// On even-numbered rows we recompute the spread.
*spread = F::zero();
for b in 0..16 {
if (i >> b) & 1 != 0 {
*spread += F::from(1 << (2 * b));
}
// i holds the zero-indexed row number for the next table row.
match i {
BITS_7 | BITS_10 | BITS_11 | BITS_13 | BITS_14 => *tag += F::ONE,
_ => (),
}
*dense += F::ONE;
if i & 1 == 0 {
// On even-numbered rows we recompute the spread.
*spread = F::ZERO;
for b in 0..16 {
if (i >> b) & 1 != 0 {
*spread += F::from(1 << (2 * b));
}
} else {
// On odd-numbered rows we add one.
*spread += F::one();
}
} else {
// On odd-numbered rows we add one.
*spread += F::ONE;
}
Some(res)
},
)
Some(res)
})
}
}
@ -363,20 +360,20 @@ mod tests {
};
// Test the first few small values.
add_row(F::zero(), F::from(0b000), F::from(0b000000))?;
add_row(F::zero(), F::from(0b001), F::from(0b000001))?;
add_row(F::zero(), F::from(0b010), F::from(0b000100))?;
add_row(F::zero(), F::from(0b011), F::from(0b000101))?;
add_row(F::zero(), F::from(0b100), F::from(0b010000))?;
add_row(F::zero(), F::from(0b101), F::from(0b010001))?;
add_row(F::ZERO, F::from(0b000), F::from(0b000000))?;
add_row(F::ZERO, F::from(0b001), F::from(0b000001))?;
add_row(F::ZERO, F::from(0b010), F::from(0b000100))?;
add_row(F::ZERO, F::from(0b011), F::from(0b000101))?;
add_row(F::ZERO, F::from(0b100), F::from(0b010000))?;
add_row(F::ZERO, F::from(0b101), F::from(0b010001))?;
// Test the tag boundaries:
// 7-bit
add_row(F::zero(), F::from(0b1111111), F::from(0b01010101010101))?;
add_row(F::one(), F::from(0b10000000), F::from(0b0100000000000000))?;
add_row(F::ZERO, F::from(0b1111111), F::from(0b01010101010101))?;
add_row(F::ONE, F::from(0b10000000), F::from(0b0100000000000000))?;
// - 10-bit
add_row(
F::one(),
F::ONE,
F::from(0b1111111111),
F::from(0b01010101010101010101),
)?;

View File

@ -204,9 +204,9 @@ where
let to_base_field = |bits: &[Value<bool>]| -> Value<C::Base> {
let bits: Value<Vec<bool>> = bits.iter().cloned().collect();
bits.map(|bits| {
bits.into_iter().rev().fold(C::Base::zero(), |acc, bit| {
bits.into_iter().rev().fold(C::Base::ZERO, |acc, bit| {
if bit {
acc.double() + C::Base::one()
acc.double() + C::Base::ONE
} else {
acc.double()
}
@ -244,7 +244,7 @@ where
subpieces: impl IntoIterator<Item = RangeConstrained<C::Base, Value<C::Base>>>,
) -> Result<Self, Error> {
let (field_elem, total_bits) = subpieces.into_iter().fold(
(Value::known(C::Base::zero()), 0),
(Value::known(C::Base::ZERO), 0),
|(acc, bits), subpiece| {
assert!(bits < 64);
let subpiece_shifted = subpiece

View File

@ -1,3 +1,4 @@
use group::ff::PrimeField;
use halo2_proofs::{
circuit::{Layouter, Value},
plonk::{ConstraintSystem, Error, Expression, TableColumn},
@ -6,7 +7,7 @@ use halo2_proofs::{
use super::{CommitDomains, FixedPoints, HashDomains};
use crate::sinsemilla::primitives::{self as sinsemilla, SINSEMILLA_S};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
/// Table containing independent generators S[0..2^k]
#[derive(Eq, PartialEq, Copy, Clone, Debug)]

View File

@ -5,12 +5,13 @@ use crate::{
sinsemilla::primitives::{self as sinsemilla, lebs2ip_k, INV_TWO_POW_K, SINSEMILLA_S},
};
use ff::Field;
use halo2_proofs::{
circuit::{AssignedCell, Chip, Region, Value},
plonk::{Assigned, Error},
};
use group::ff::{Field, PrimeField, PrimeFieldBits};
use group::ff::{PrimeField, PrimeFieldBits};
use pasta_curves::{arithmetic::CurveAffine, pallas};
use std::ops::Deref;

View File

@ -5,7 +5,7 @@ use halo2_proofs::{
plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use super::MerkleInstructions;

View File

@ -1,7 +1,6 @@
//! Gadget and chips for the Sinsemilla hash function.
use ff::{Field, PrimeFieldBits};
use halo2_proofs::circuit::{AssignedCell, Cell, Value};
use std::fmt::Debug;
/// A [`Message`] composed of several [`MessagePiece`]s.

View File

@ -138,7 +138,7 @@ pub fn bool_check<F: PrimeField>(value: Expression<F>) -> Expression<F> {
///
/// `a` must be a boolean-constrained expression.
pub fn ternary<F: Field>(a: Expression<F>, b: Expression<F>, c: Expression<F>) -> Expression<F> {
let one_minus_a = Expression::Constant(F::one()) - a.clone();
let one_minus_a = Expression::Constant(F::ONE) - a.clone();
a * b + one_minus_a * c
}
@ -156,9 +156,9 @@ pub fn bitrange_subset<F: PrimeFieldBits>(field_elem: &F, bitrange: Range<usize>
.skip(bitrange.start)
.take(bitrange.end - bitrange.start)
.rev()
.fold(F::zero(), |acc, bit| {
.fold(F::ZERO, |acc, bit| {
if bit {
acc.double() + F::one()
acc.double() + F::ONE
} else {
acc.double()
}
@ -240,14 +240,14 @@ pub fn i2lebsp<const NUM_BITS: usize>(int: u64) -> [bool; NUM_BITS] {
#[cfg(test)]
mod tests {
use super::*;
use group::ff::{Field, PrimeField};
use group::ff::{Field, FromUniformBytes, PrimeField};
use halo2_proofs::{
circuit::{Layouter, SimpleFloorPlanner},
dev::{FailureLocation, MockProver, VerifyFailure},
plonk::{Any, Circuit, ConstraintSystem, Constraints, Error, Selector},
poly::Rotation,
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use proptest::prelude::*;
use rand::rngs::OsRng;
use std::convert::TryInto;
@ -358,7 +358,7 @@ mod tests {
let field_elem = pallas::Base::random(rng);
let bitrange = 0..0;
let subset = bitrange_subset(&field_elem, bitrange);
assert_eq!(pallas::Base::zero(), subset);
assert_eq!(pallas::Base::ZERO, subset);
}
// Closure to decompose field element into pieces using consecutive ranges,
@ -420,7 +420,7 @@ mod tests {
// Instead of rejecting out-of-range bytes, let's reduce them.
let mut buf = [0; 64];
buf[..32].copy_from_slice(&bytes);
pallas::Scalar::from_bytes_wide(&buf)
pallas::Scalar::from_uniform_bytes(&buf)
}
}

View File

@ -8,7 +8,6 @@ use halo2_proofs::{
plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector},
poly::Rotation,
};
use std::marker::PhantomData;
/// Instructions for a conditional swap gadget.

View File

@ -198,7 +198,7 @@ impl<F: PrimeFieldBits, const WINDOW_NUM_BITS: usize> RunningSumConfig<F, WINDOW
if strict {
// Constrain the final running sum output to be zero.
region.constrain_constant(zs.last().unwrap().cell(), F::zero())?;
region.constrain_constant(zs.last().unwrap().cell(), F::ZERO)?;
}
Ok(RunningSum(zs))
@ -214,7 +214,7 @@ mod tests {
dev::{FailureLocation, MockProver, VerifyFailure},
plonk::{Any, Circuit, ConstraintSystem, Error},
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use pasta_curves::pallas;
use rand::rngs::OsRng;
use crate::ecc::chip::{

View File

@ -118,7 +118,7 @@ impl<F: PrimeFieldBits, const K: usize> LookupRangeCheckConfig<F, K> {
// In the short range check, the word is directly witnessed.
let short_lookup = {
let short_word = z_cur;
let q_short = Expression::Constant(F::one()) - q_running;
let q_short = Expression::Constant(F::ONE) - q_running;
q_short * short_word
};
@ -285,7 +285,7 @@ impl<F: PrimeFieldBits, const K: usize> LookupRangeCheckConfig<F, K> {
if strict {
// Constrain the final `z` to be zero.
region.constrain_constant(zs.last().unwrap().cell(), F::zero())?;
region.constrain_constant(zs.last().unwrap().cell(), F::ZERO)?;
}
Ok(RunningSum(zs))
@ -434,8 +434,8 @@ mod tests {
// Lookup constraining element to be no longer than num_words * K bits.
let elements_and_expected_final_zs = [
(F::from((1 << (self.num_words * K)) - 1), F::zero(), true), // a word that is within self.num_words * K bits long
(F::from(1 << (self.num_words * K)), F::one(), false), // a word that is just over self.num_words * K bits long
(F::from((1 << (self.num_words * K)) - 1), F::ZERO, true), // a word that is within self.num_words * K bits long
(F::from(1 << (self.num_words * K)), F::ONE, false), // a word that is just over self.num_words * K bits long
];
fn expected_zs<F: PrimeFieldBits, const K: usize>(
@ -545,7 +545,7 @@ mod tests {
// Edge case: zero bits
{
let circuit: MyCircuit<pallas::Base> = MyCircuit {
element: Value::known(pallas::Base::zero()),
element: Value::known(pallas::Base::ZERO),
num_bits: 0,
};
let prover = MockProver::<pallas::Base>::run(11, &circuit, vec![]).unwrap();

View File

@ -6,6 +6,7 @@ and this project adheres to Rust's notion of
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- The following structs now derive the `Eq` trait:
- `halo2_proofs::dev`:
- `failure::FailureLocation`
@ -14,14 +15,13 @@ and this project adheres to Rust's notion of
- `metadata::Constraint`
- `metadata::Region`
- `halo2_proofs::poly::Rotation`
### Added
- `halo2_proofs::arithmetic::FftGroup`
- `halo2_proofs::circuit::layouter`:
- `RegionLayouter::instance_value` method added to provide access to
instance values within a region.
### Changed
- Migrated to `ff 0.13`.
- APIs with `F: pasta_curves::arithmetic::FieldExt` bounds have been changed to
use `ff` traits directly.
- `halo2_proofs::arithmetic`:

View File

@ -42,7 +42,7 @@ fn criterion_benchmark(c: &mut Criterion) {
meta.lookup(|meta| {
let selector = meta.query_selector(config.selector);
let not_selector = Expression::Constant(F::one()) - selector.clone();
let not_selector = Expression::Constant(F::ONE) - selector.clone();
let advice = meta.query_advice(config.advice, Rotation::cur());
vec![(selector * advice + not_selector, config.table)]
});

View File

@ -103,15 +103,10 @@ fn criterion_benchmark(c: &mut Criterion) {
|| value.unwrap().map(|v| v.2),
)?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?;
region.assign_fixed(
|| "a * b",
self.config.sm,
0,
|| Value::known(FF::one()),
)?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ZERO))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ZERO))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ONE))?;
Ok((lhs.cell(), rhs.cell(), out.cell()))
},
)
@ -150,14 +145,14 @@ fn criterion_benchmark(c: &mut Criterion) {
|| value.unwrap().map(|v| v.2),
)?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?;
region.assign_fixed(
|| "a * b",
self.config.sm,
0,
|| Value::known(FF::zero()),
|| Value::known(FF::ZERO),
)?;
Ok((lhs.cell(), rhs.cell(), out.cell()))
},

View File

@ -93,10 +93,10 @@ impl<FF: Field> StandardCs<FF> for StandardPlonk<FF> {
let out =
region.assign_advice(|| "out", self.config.c, 0, || value.unwrap().map(|v| v.2))?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ZERO))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ZERO))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ONE))?;
Ok((lhs.cell(), rhs.cell(), out.cell()))
}
fn raw_add<F>(&self, region: &mut Region<FF>, mut f: F) -> Result<(Cell, Cell, Cell), Error>
@ -130,10 +130,10 @@ impl<FF: Field> StandardCs<FF> for StandardPlonk<FF> {
let out =
region.assign_advice(|| "out", self.config.c, 0, || value.unwrap().map(|v| v.2))?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ZERO))?;
Ok((lhs.cell(), rhs.cell(), out.cell()))
}
fn copy(&self, region: &mut Region<FF>, left: Cell, right: Cell) -> Result<(), Error> {
@ -274,7 +274,7 @@ fn main() {
// Prepare the circuit you want to render.
// You don't need to include any witness variables.
let a = Fp::random(OsRng);
let instance = Fp::one() + Fp::one();
let instance = Fp::ONE + Fp::ONE;
let lookup_table = vec![instance, a, a, Fp::zero()];
let circuit: MyCircuit<Fp> = MyCircuit {
a: Value::unknown(),

View File

@ -207,7 +207,7 @@ pub fn best_fft<Scalar: Field, G: FftGroup<Scalar>>(a: &mut [G], omega: Scalar,
// precompute twiddle factors
let twiddles: Vec<_> = (0..(n / 2))
.scan(Scalar::one(), |w, _| {
.scan(Scalar::ONE, |w, _| {
let tw = *w;
*w *= &omega;
Some(tw)
@ -293,7 +293,7 @@ pub fn eval_polynomial<F: Field>(poly: &[F], point: F) -> F {
// TODO: parallelize?
poly.iter()
.rev()
.fold(F::zero(), |acc, coeff| acc * point + coeff)
.fold(F::ZERO, |acc, coeff| acc * point + coeff)
}
/// This computes the inner product of two vectors `a` and `b`.
@ -303,7 +303,7 @@ pub fn compute_inner_product<F: Field>(a: &[F], b: &[F]) -> F {
// TODO: parallelize?
assert_eq!(a.len(), b.len());
let mut acc = F::zero();
let mut acc = F::ZERO;
for (a, b) in a.iter().zip(b.iter()) {
acc += (*a) * (*b);
}
@ -320,9 +320,9 @@ where
b = -b;
let a = a.into_iter();
let mut q = vec![F::zero(); a.len() - 1];
let mut q = vec![F::ZERO; a.len() - 1];
let mut tmp = F::zero();
let mut tmp = F::ZERO;
for (q, r) in q.iter_mut().rev().zip(a.rev()) {
let mut lead_coeff = *r;
lead_coeff.sub_assign(&tmp);
@ -392,11 +392,11 @@ pub fn lagrange_interpolate<F: Field>(points: &[F], evals: &[F]) -> Vec<F> {
// Compute (x_j - x_k)^(-1) for each j != i
denoms.iter_mut().flat_map(|v| v.iter_mut()).batch_invert();
let mut final_poly = vec![F::zero(); points.len()];
let mut final_poly = vec![F::ZERO; points.len()];
for (j, (denoms, eval)) in denoms.into_iter().zip(evals.iter()).enumerate() {
let mut tmp: Vec<F> = Vec::with_capacity(points.len());
let mut product = Vec::with_capacity(points.len() - 1);
tmp.push(F::one());
tmp.push(F::ONE);
for (x_k, denom) in points
.iter()
.enumerate()
@ -404,11 +404,11 @@ pub fn lagrange_interpolate<F: Field>(points: &[F], evals: &[F]) -> Vec<F> {
.map(|a| a.1)
.zip(denoms.into_iter())
{
product.resize(tmp.len() + 1, F::zero());
product.resize(tmp.len() + 1, F::ZERO);
for ((a, b), product) in tmp
.iter()
.chain(std::iter::once(&F::zero()))
.zip(std::iter::once(&F::zero()).chain(tmp.iter()))
.chain(std::iter::once(&F::ZERO))
.zip(std::iter::once(&F::ZERO).chain(tmp.iter()))
.zip(product.iter_mut())
{
*product = *a * (-denom * x_k) + *b * denom;

View File

@ -9,7 +9,6 @@ use ff::Field;
use crate::plonk::Assigned;
use crate::{
arithmetic::FieldExt,
circuit,
plonk::{
permutation, Advice, Any, Assignment, Circuit, Column, ConstraintSystem, Error, Expression,
@ -92,7 +91,7 @@ impl<F: Field> From<CellValue<F>> for Value<F> {
fn from(value: CellValue<F>) -> Self {
match value {
// Cells that haven't been explicitly assigned to, default to zero.
CellValue::Unassigned => Value::Real(F::zero()),
CellValue::Unassigned => Value::Real(F::ZERO),
CellValue::Assigned(v) => Value::Real(v),
CellValue::Poison(_) => Value::Poison,
}
@ -132,7 +131,7 @@ impl<F: Field> Mul for Value<F> {
(Value::Real(x), Value::Poison) | (Value::Poison, Value::Real(x))
if x.is_zero_vartime() =>
{
Value::Real(F::zero())
Value::Real(F::ZERO)
}
_ => Value::Poison,
}
@ -147,7 +146,7 @@ impl<F: Field> Mul<F> for Value<F> {
Value::Real(lhs) => Value::Real(lhs * rhs),
// If poison is multiplied by zero, then we treat the poison as unconstrained
// and we don't propagate it.
Value::Poison if rhs.is_zero_vartime() => Value::Real(F::zero()),
Value::Poison if rhs.is_zero_vartime() => Value::Real(F::ZERO),
_ => Value::Poison,
}
}
@ -164,8 +163,8 @@ impl<F: Field> Mul<F> for Value<F> {
/// # Examples
///
/// ```
/// use group::ff::PrimeField;
/// use halo2_proofs::{
/// arithmetic::FieldExt,
/// circuit::{Layouter, SimpleFloorPlanner, Value},
/// dev::{FailureLocation, MockProver, VerifyFailure},
/// pasta::Fp,
@ -188,7 +187,7 @@ impl<F: Field> Mul<F> for Value<F> {
/// b: Value<u64>,
/// }
///
/// impl<F: FieldExt> Circuit<F> for MyCircuit {
/// impl<F: PrimeField> Circuit<F> for MyCircuit {
/// type Config = MyConfig;
/// type FloorPlanner = SimpleFloorPlanner;
///
@ -303,7 +302,7 @@ impl<F: Field> InstanceValue<F> {
fn value(&self) -> F {
match self {
InstanceValue::Assigned(v) => *v,
InstanceValue::Padding => F::zero(),
InstanceValue::Padding => F::ZERO,
}
}
}
@ -477,7 +476,7 @@ impl<F: Field> Assignment<F> for MockProver<F> {
}
}
impl<F: FieldExt> MockProver<F> {
impl<F: Field + Ord> MockProver<F> {
/// Runs a synthetic keygen-and-prove operation on the given circuit, collecting data
/// about the constraints and their assignments.
pub fn run<ConcreteCircuit: Circuit<F>>(
@ -918,6 +917,7 @@ impl<F: FieldExt> MockProver<F> {
#[cfg(test)]
mod tests {
use group::ff::Field;
use pasta_curves::Fp;
use super::{FailureLocation, MockProver, VerifyFailure};
@ -979,7 +979,7 @@ mod tests {
config.q.enable(&mut region, 1)?;
// Assign a = 0.
region.assign_advice(|| "a", config.a, 0, || Value::known(Fp::zero()))?;
region.assign_advice(|| "a", config.a, 0, || Value::known(Fp::ZERO))?;
// BUG: Forget to assign b = 0! This could go unnoticed during
// development, because cell values default to zero, which in this

View File

@ -58,9 +58,9 @@ impl From<InstanceQuery> for AnyQuery {
pub(super) fn format_value<F: Field>(v: F) -> String {
if v.is_zero_vartime() {
"0".into()
} else if v == F::one() {
} else if v == F::ONE {
"1".into()
} else if v == -F::one() {
} else if v == -F::ONE {
"-1".into()
} else {
// Format value as hex.

View File

@ -6,9 +6,9 @@
//! [plonk]: https://eprint.iacr.org/2019/953
use blake2b_simd::Params as Blake2bParams;
use group::ff::Field;
use group::ff::{Field, FromUniformBytes, PrimeField};
use crate::arithmetic::{CurveAffine, FieldExt};
use crate::arithmetic::CurveAffine;
use crate::poly::{
Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, PinnedEvaluationDomain,
Polynomial,
@ -49,7 +49,10 @@ pub struct VerifyingKey<C: CurveAffine> {
transcript_repr: C::Scalar,
}
impl<C: CurveAffine> VerifyingKey<C> {
impl<C: CurveAffine> VerifyingKey<C>
where
C::Scalar: FromUniformBytes<64>,
{
fn from_parts(
domain: EvaluationDomain<C::Scalar>,
fixed_commitments: Vec<C>,
@ -66,7 +69,7 @@ impl<C: CurveAffine> VerifyingKey<C> {
cs,
cs_degree,
// Temporary, this is not pinned.
transcript_repr: C::Scalar::zero(),
transcript_repr: C::Scalar::ZERO,
};
let mut hasher = Blake2bParams::new()
@ -80,11 +83,13 @@ impl<C: CurveAffine> VerifyingKey<C> {
hasher.update(s.as_bytes());
// Hash in final Blake2bState
vk.transcript_repr = C::Scalar::from_bytes_wide(hasher.finalize().as_array());
vk.transcript_repr = C::Scalar::from_uniform_bytes(hasher.finalize().as_array());
vk
}
}
impl<C: CurveAffine> VerifyingKey<C> {
/// Hashes a verification key into a transcript.
pub fn hash_into<E: EncodedChallenge<C>, T: Transcript<C, E>>(
&self,

View File

@ -280,7 +280,7 @@ impl<F: Field> Assigned<F> {
/// Returns the numerator.
pub fn numerator(&self) -> F {
match self {
Self::Zero => F::zero(),
Self::Zero => F::ZERO,
Self::Trivial(x) => *x,
Self::Rational(numerator, _) => *numerator,
}
@ -341,7 +341,7 @@ impl<F: Field> Assigned<F> {
pub fn invert(&self) -> Self {
match self {
Self::Zero => Self::Zero,
Self::Trivial(x) => Self::Rational(F::one(), *x),
Self::Trivial(x) => Self::Rational(F::ONE, *x),
Self::Rational(numerator, denominator) => Self::Rational(*denominator, *numerator),
}
}
@ -352,13 +352,13 @@ impl<F: Field> Assigned<F> {
/// If the denominator is zero, this returns zero.
pub fn evaluate(self) -> F {
match self {
Self::Zero => F::zero(),
Self::Zero => F::ZERO,
Self::Trivial(x) => x,
Self::Rational(numerator, denominator) => {
if denominator == F::one() {
if denominator == F::ONE {
numerator
} else {
numerator * denominator.invert().unwrap_or(F::zero())
numerator * denominator.invert().unwrap_or(F::ZERO)
}
}
}
@ -367,6 +367,7 @@ impl<F: Field> Assigned<F> {
#[cfg(test)]
mod tests {
use group::ff::Field;
use pasta_curves::Fp;
use super::Assigned;
@ -376,7 +377,7 @@ mod tests {
// a = 2
// b = (1,0)
let a = Assigned::Trivial(Fp::from(2));
let b = Assigned::Rational(Fp::one(), Fp::zero());
let b = Assigned::Rational(Fp::ONE, Fp::ZERO);
// 2 + (1,0) = 2 + 0 = 2
// This fails if addition is implemented using normal rules for rationals.
@ -388,8 +389,8 @@ mod tests {
fn add_rational_to_inv0_rational() {
// a = (1,2)
// b = (1,0)
let a = Assigned::Rational(Fp::one(), Fp::from(2));
let b = Assigned::Rational(Fp::one(), Fp::zero());
let a = Assigned::Rational(Fp::ONE, Fp::from(2));
let b = Assigned::Rational(Fp::ONE, Fp::ZERO);
// (1,2) + (1,0) = (1,2) + 0 = (1,2)
// This fails if addition is implemented using normal rules for rationals.
@ -402,7 +403,7 @@ mod tests {
// a = 2
// b = (1,0)
let a = Assigned::Trivial(Fp::from(2));
let b = Assigned::Rational(Fp::one(), Fp::zero());
let b = Assigned::Rational(Fp::ONE, Fp::ZERO);
// (1,0) - 2 = 0 - 2 = -2
// This fails if subtraction is implemented using normal rules for rationals.
@ -416,8 +417,8 @@ mod tests {
fn sub_rational_from_inv0_rational() {
// a = (1,2)
// b = (1,0)
let a = Assigned::Rational(Fp::one(), Fp::from(2));
let b = Assigned::Rational(Fp::one(), Fp::zero());
let a = Assigned::Rational(Fp::ONE, Fp::from(2));
let b = Assigned::Rational(Fp::ONE, Fp::ZERO);
// (1,0) - (1,2) = 0 - (1,2) = -(1,2)
// This fails if subtraction is implemented using normal rules for rationals.
@ -431,14 +432,14 @@ mod tests {
fn mul_rational_by_inv0_rational() {
// a = (1,2)
// b = (1,0)
let a = Assigned::Rational(Fp::one(), Fp::from(2));
let b = Assigned::Rational(Fp::one(), Fp::zero());
let a = Assigned::Rational(Fp::ONE, Fp::from(2));
let b = Assigned::Rational(Fp::ONE, Fp::ZERO);
// (1,2) * (1,0) = (1,2) * 0 = 0
assert_eq!((a * b).evaluate(), Fp::zero());
assert_eq!((a * b).evaluate(), Fp::ZERO);
// (1,0) * (1,2) = 0 * (1,2) = 0
assert_eq!((b * a).evaluate(), Fp::zero());
assert_eq!((b * a).evaluate(), Fp::ZERO);
}
}
@ -476,7 +477,7 @@ mod proptests {
}
fn inv0(&self) -> Self {
self.invert().unwrap_or(F::zero())
self.invert().unwrap_or(F::ZERO)
}
}
@ -578,7 +579,7 @@ mod proptests {
fn arb_rational()(
numerator in arb_element(),
denominator in prop_oneof![
1 => Just(Fp::zero()),
1 => Just(Fp::ZERO),
2 => arb_element(),
],
) -> Assigned<Fp> {

View File

@ -228,12 +228,11 @@ impl TryFrom<Column<Any>> for Column<Instance> {
/// Selectors are disabled on all rows by default, and must be explicitly enabled on each
/// row when required:
/// ```
/// use group::ff::Field;
/// use halo2_proofs::{
/// arithmetic::FieldExt,
/// circuit::{Chip, Layouter, Value},
/// plonk::{Advice, Column, Error, Selector},
/// };
/// # use ff::Field;
/// # use halo2_proofs::plonk::Fixed;
///
/// struct Config {
@ -242,12 +241,12 @@ impl TryFrom<Column<Any>> for Column<Instance> {
/// s: Selector,
/// }
///
/// fn circuit_logic<F: FieldExt, C: Chip<F>>(chip: C, mut layouter: impl Layouter<F>) -> Result<(), Error> {
/// fn circuit_logic<F: Field, C: Chip<F>>(chip: C, mut layouter: impl Layouter<F>) -> Result<(), Error> {
/// let config = chip.config();
/// # let config: Config = todo!();
/// layouter.assign_region(|| "bar", |mut region| {
/// region.assign_advice(|| "a", config.a, 0, || Value::known(F::one()))?;
/// region.assign_advice(|| "a", config.b, 1, || Value::known(F::one()))?;
/// region.assign_advice(|| "a", config.a, 0, || Value::known(F::ONE))?;
/// region.assign_advice(|| "a", config.b, 1, || Value::known(F::ONE))?;
/// config.s.enable(&mut region, 1)
/// })?;
/// Ok(())
@ -816,6 +815,7 @@ impl<F: Field> From<Expression<F>> for Vec<Constraint<F>> {
/// A set of polynomial constraints with a common selector.
///
/// ```
/// use group::ff::Field;
/// use halo2_proofs::{pasta::Fp, plonk::{Constraints, Expression}, poly::Rotation};
/// # use halo2_proofs::plonk::ConstraintSystem;
///
@ -832,7 +832,7 @@ impl<F: Field> From<Expression<F>> for Vec<Constraint<F>> {
/// let c = meta.query_advice(c, Rotation::cur());
/// let s_ternary = meta.query_selector(s);
///
/// let one_minus_a = Expression::Constant(Fp::one()) - a.clone();
/// let one_minus_a = Expression::Constant(Fp::ONE) - a.clone();
///
/// Constraints::with_selector(
/// s_ternary,

View File

@ -79,7 +79,7 @@ where
let combination_assignment = selector
.activations
.iter()
.map(|b| if *b { F::one() } else { F::zero() })
.map(|b| if *b { F::ONE } else { F::ZERO })
.collect::<Vec<_>>();
let combination_index = combination_assignments.len();
combination_assignments.push(combination_assignment);
@ -177,12 +177,12 @@ where
}
// Now, compute the selector and combination assignments.
let mut combination_assignment = vec![F::zero(); n];
let mut combination_assignment = vec![F::ZERO; n];
let combination_len = combination.len();
let combination_index = combination_assignments.len();
let query = allocate_fixed_column();
let mut assigned_root = F::one();
let mut assigned_root = F::ONE;
selector_assignments.extend(combination.into_iter().map(|selector| {
// Compute the expression for substitution. This produces an expression of the
// form
@ -192,12 +192,12 @@ where
// `assigned_root`. In particular, rows set to 0 correspond to all selectors
// being disabled.
let mut expression = query.clone();
let mut root = F::one();
let mut root = F::ONE;
for _ in 0..combination_len {
if root != assigned_root {
expression = expression * (Expression::Constant(root) - query.clone());
}
root += F::one();
root += F::ONE;
}
// Update the combination assignment
@ -212,7 +212,7 @@ where
}
}
assigned_root += F::one();
assigned_root += F::ONE;
SelectorAssignment {
selector: selector.selector,

View File

@ -2,7 +2,7 @@
use std::ops::Range;
use ff::Field;
use ff::{Field, FromUniformBytes};
use group::Curve;
use super::{
@ -192,6 +192,7 @@ pub fn keygen_vk<C, ConcreteCircuit>(
) -> Result<VerifyingKey<C>, Error>
where
C: CurveAffine,
C::Scalar: FromUniformBytes<64>,
ConcreteCircuit: Circuit<C::Scalar>,
{
let (domain, cs, config) = create_domain::<C, ConcreteCircuit>(params);
@ -303,7 +304,7 @@ where
// Compute l_0(X)
// TODO: this can be done more efficiently
let mut l0 = vk.domain.empty_lagrange();
l0[0] = C::Scalar::one();
l0[0] = C::Scalar::ONE;
let l0 = vk.domain.lagrange_to_coeff(l0);
let l0 = vk.domain.coeff_to_extended(l0);
@ -311,7 +312,7 @@ where
// and 0 otherwise over the domain.
let mut l_blind = vk.domain.empty_lagrange();
for evaluation in l_blind[..].iter_mut().rev().take(cs.blinding_factors()) {
*evaluation = C::Scalar::one();
*evaluation = C::Scalar::ONE;
}
let l_blind = vk.domain.lagrange_to_coeff(l_blind);
let l_blind = vk.domain.coeff_to_extended(l_blind);
@ -319,7 +320,7 @@ where
// Compute l_last(X) which evaluates to 1 on the first inactive row (just
// before the blinding factors) and 0 otherwise over the domain
let mut l_last = vk.domain.empty_lagrange();
l_last[params.n as usize - cs.blinding_factors() - 1] = C::Scalar::one();
l_last[params.n as usize - cs.blinding_factors() - 1] = C::Scalar::ONE;
let l_last = vk.domain.lagrange_to_coeff(l_last);
let l_last = vk.domain.coeff_to_extended(l_last);

View File

@ -4,7 +4,7 @@ use super::super::{
};
use super::Argument;
use crate::{
arithmetic::{eval_polynomial, parallelize, CurveAffine, FieldExt},
arithmetic::{eval_polynomial, parallelize, CurveAffine},
poly::{
self,
commitment::{Blind, Params},
@ -13,6 +13,7 @@ use crate::{
},
transcript::{EncodedChallenge, TranscriptWrite},
};
use ff::WithSmallOrderMulGroup;
use group::{
ff::{BatchInvert, Field},
Curve,
@ -61,7 +62,7 @@ pub(in crate::plonk) struct Evaluated<C: CurveAffine> {
constructed: Constructed<C>,
}
impl<F: FieldExt> Argument<F> {
impl<F: WithSmallOrderMulGroup<3>> Argument<F> {
/// Given a Lookup with input expressions [A_0, A_1, ..., A_{m-1}] and table expressions
/// [S_0, S_1, ..., S_{m-1}], this method
/// - constructs A_compressed = \theta^{m-1} A_0 + theta^{m-2} A_1 + ... + \theta A_{m-2} + A_{m-1}
@ -164,13 +165,13 @@ impl<F: FieldExt> Argument<F> {
// Compressed version of expressions
let compressed_expression = unpermuted_expressions.iter().fold(
poly::Ast::ConstantTerm(C::Scalar::zero()),
poly::Ast::ConstantTerm(C::Scalar::ZERO),
|acc, expression| &(acc * *theta) + expression,
);
// Compressed version of cosets
let compressed_coset = unpermuted_cosets.iter().fold(
poly::Ast::<_, _, ExtendedLagrangeCoeff>::ConstantTerm(C::Scalar::zero()),
poly::Ast::<_, _, ExtendedLagrangeCoeff>::ConstantTerm(C::Scalar::ZERO),
|acc, eval| acc * poly::Ast::ConstantTerm(*theta) + eval.clone(),
);
@ -275,7 +276,7 @@ impl<C: CurveAffine, Ev: Copy + Send + Sync> Permuted<C, Ev> {
// s_j(X) is the jth table expression in this lookup,
// s'(X) is the compression of the permuted table expressions,
// and i is the ith row of the expression.
let mut lookup_product = vec![C::Scalar::zero(); params.n as usize];
let mut lookup_product = vec![C::Scalar::ZERO; params.n as usize];
// Denominator uses the permuted input expression and permuted table expression
parallelize(&mut lookup_product, |lookup_product, start| {
for ((lookup_product, permuted_input_value), permuted_table_value) in lookup_product
@ -320,9 +321,9 @@ impl<C: CurveAffine, Ev: Copy + Send + Sync> Permuted<C, Ev> {
// Compute the evaluations of the lookup product polynomial
// over our domain, starting with z[0] = 1
let z = iter::once(C::Scalar::one())
let z = iter::once(C::Scalar::ONE)
.chain(lookup_product)
.scan(C::Scalar::one(), |state, cur| {
.scan(C::Scalar::ONE, |state, cur| {
*state *= &cur;
Some(*state)
})
@ -343,7 +344,7 @@ impl<C: CurveAffine, Ev: Copy + Send + Sync> Permuted<C, Ev> {
let u = (params.n as usize) - (blinding_factors + 1);
// l_0(X) * (1 - z(X)) = 0
assert_eq!(z[0], C::Scalar::one());
assert_eq!(z[0], C::Scalar::ONE);
// z(\omega X) (a'(X) + \beta) (s'(X) + \gamma)
// - z(X) (\theta^{m-1} a_0(X) + ... + a_{m-1}(X) + \beta) (\theta^{m-1} s_0(X) + ... + s_{m-1}(X) + \gamma)
@ -371,7 +372,7 @@ impl<C: CurveAffine, Ev: Copy + Send + Sync> Permuted<C, Ev> {
// l_last(X) * (z(X)^2 - z(X)) = 0
// Assertion will fail only when soundness is broken, in which
// case this z[u] value will be zero. (bad!)
assert_eq!(z[u], C::Scalar::one());
assert_eq!(z[u], C::Scalar::ONE);
}
let product_blind = Blind(C::Scalar::random(rng));
@ -584,7 +585,7 @@ fn permute_expression_pair<C: CurveAffine, R: RngCore>(
*acc.entry(*coeff).or_insert(0) += 1;
acc
});
let mut permuted_table_coeffs = vec![C::Scalar::zero(); usable_rows];
let mut permuted_table_coeffs = vec![C::Scalar::ZERO; usable_rows];
let mut repeated_input_rows = permuted_input_expression
.iter()

View File

@ -104,7 +104,7 @@ impl<C: CurveAffine> Evaluated<C> {
fixed_evals: &[C::Scalar],
instance_evals: &[C::Scalar],
) -> impl Iterator<Item = C::Scalar> + 'a {
let active_rows = C::Scalar::one() - (l_last + l_blind);
let active_rows = C::Scalar::ONE - (l_last + l_blind);
let product_expression = || {
// z(\omega X) (a'(X) + \beta) (s'(X) + \gamma)
@ -129,7 +129,7 @@ impl<C: CurveAffine> Evaluated<C> {
&|a, scalar| a * &scalar,
)
})
.fold(C::Scalar::zero(), |acc, eval| acc * &*theta + &eval)
.fold(C::Scalar::ZERO, |acc, eval| acc * &*theta + &eval)
};
let right = self.product_eval
* &(compress_expressions(&argument.input_expressions) + &*beta)
@ -141,7 +141,7 @@ impl<C: CurveAffine> Evaluated<C> {
std::iter::empty()
.chain(
// l_0(X) * (1 - z(X)) = 0
Some(l_0 * &(C::Scalar::one() - &self.product_eval)),
Some(l_0 * &(C::Scalar::ONE - &self.product_eval)),
)
.chain(
// l_last(X) * (z(X)^2 - z(X)) = 0

View File

@ -1,9 +1,11 @@
use ff::Field;
use group::Curve;
use group::{
ff::{Field, PrimeField},
Curve,
};
use super::{Argument, ProvingKey, VerifyingKey};
use crate::{
arithmetic::{CurveAffine, FieldExt},
arithmetic::CurveAffine,
plonk::{Any, Column, Error},
poly::{
commitment::{Blind, Params},
@ -106,7 +108,7 @@ impl Assembly {
// Compute [omega^0, omega^1, ..., omega^{params.n - 1}]
let mut omega_powers = Vec::with_capacity(params.n as usize);
{
let mut cur = C::Scalar::one();
let mut cur = C::Scalar::ONE;
for _ in 0..params.n {
omega_powers.push(cur);
cur *= &domain.get_omega();
@ -116,7 +118,7 @@ impl Assembly {
// Compute [omega_powers * \delta^0, omega_powers * \delta^1, ..., omega_powers * \delta^m]
let mut deltaomega = Vec::with_capacity(p.columns.len());
{
let mut cur = C::Scalar::one();
let mut cur = C::Scalar::ONE;
for _ in 0..p.columns.len() {
let mut omega_powers = omega_powers.clone();
for o in &mut omega_powers {
@ -159,7 +161,7 @@ impl Assembly {
// Compute [omega^0, omega^1, ..., omega^{params.n - 1}]
let mut omega_powers = Vec::with_capacity(params.n as usize);
{
let mut cur = C::Scalar::one();
let mut cur = C::Scalar::ONE;
for _ in 0..params.n {
omega_powers.push(cur);
cur *= &domain.get_omega();
@ -169,7 +171,7 @@ impl Assembly {
// Compute [omega_powers * \delta^0, omega_powers * \delta^1, ..., omega_powers * \delta^m]
let mut deltaomega = Vec::with_capacity(p.columns.len());
{
let mut cur = C::Scalar::one();
let mut cur = C::Scalar::ONE;
for _ in 0..p.columns.len() {
let mut omega_powers = omega_powers.clone();
for o in &mut omega_powers {

View File

@ -1,5 +1,5 @@
use group::{
ff::{BatchInvert, Field},
ff::{BatchInvert, Field, PrimeField},
Curve,
};
use rand_core::RngCore;
@ -8,7 +8,7 @@ use std::iter::{self, ExactSizeIterator};
use super::super::{circuit::Any, ChallengeBeta, ChallengeGamma, ChallengeX};
use super::{Argument, ProvingKey};
use crate::{
arithmetic::{eval_polynomial, parallelize, CurveAffine, FieldExt},
arithmetic::{eval_polynomial, parallelize, CurveAffine},
plonk::{self, Error},
poly::{
self,
@ -75,10 +75,10 @@ impl Argument {
let blinding_factors = pk.vk.cs.blinding_factors();
// Each column gets its own delta power.
let mut deltaomega = C::Scalar::one();
let mut deltaomega = C::Scalar::ONE;
// Track the "last" value from the previous column set
let mut last_z = C::Scalar::one();
let mut last_z = C::Scalar::ONE;
let mut sets = vec![];
@ -95,7 +95,7 @@ impl Argument {
// where p_j(X) is the jth column in this permutation,
// and i is the ith row of the column.
let mut modified_values = vec![C::Scalar::one(); params.n as usize];
let mut modified_values = vec![C::Scalar::ONE; params.n as usize];
// Iterate over each column of the permutation
for (&column, permuted_column_values) in columns.iter().zip(permutations.iter()) {

View File

@ -1,10 +1,11 @@
use ff::Field;
use group::ff::{Field, PrimeField};
use std::iter;
use super::super::{circuit::Any, ChallengeBeta, ChallengeGamma, ChallengeX};
use super::{Argument, VerifyingKey};
use crate::{
arithmetic::{CurveAffine, FieldExt},
arithmetic::CurveAffine,
plonk::{self, Error},
poly::{multiopen::VerifierQuery, Rotation},
transcript::{EncodedChallenge, TranscriptRead},
@ -120,9 +121,9 @@ impl<C: CurveAffine> Evaluated<C> {
// Enforce only for the first set.
// l_0(X) * (1 - z_0(X)) = 0
.chain(
self.sets.first().map(|first_set| {
l_0 * &(C::Scalar::one() - &first_set.permutation_product_eval)
}),
self.sets
.first()
.map(|first_set| l_0 * &(C::Scalar::ONE - &first_set.permutation_product_eval)),
)
// Enforce only for the last set.
// l_last(X) * (z_l(X)^2 - z_l(X)) = 0
@ -195,7 +196,7 @@ impl<C: CurveAffine> Evaluated<C> {
current_delta *= &C::Scalar::DELTA;
}
(left - &right) * (C::Scalar::one() - &(l_last + &l_blind))
(left - &right) * (C::Scalar::ONE - &(l_last + &l_blind))
}),
)
}

View File

@ -13,7 +13,7 @@ use super::{
ChallengeY, Error, ProvingKey,
};
use crate::{
arithmetic::{eval_polynomial, CurveAffine, FieldExt},
arithmetic::{eval_polynomial, CurveAffine},
circuit::Value,
plonk::Assigned,
poly::{

View File

@ -139,9 +139,7 @@ impl<C: CurveAffine> Constructed<C> {
.h_blinds
.iter()
.rev()
.fold(Blind(C::Scalar::zero()), |acc, eval| {
acc * Blind(xn) + *eval
});
.fold(Blind(C::Scalar::ZERO), |acc, eval| acc * Blind(xn) + *eval);
let random_eval = eval_polynomial(&self.committed.random_poly, *x);
transcript.write_scalar(random_eval)?;

View File

@ -94,8 +94,8 @@ impl<C: CurveAffine> PartiallyEvaluated<C> {
y: ChallengeY<C>,
xn: C::Scalar,
) -> Evaluated<C> {
let expected_h_eval = expressions.fold(C::Scalar::zero(), |h_eval, v| h_eval * &*y + &v);
let expected_h_eval = expected_h_eval * ((xn - C::Scalar::one()).invert().unwrap());
let expected_h_eval = expressions.fold(C::Scalar::ZERO, |h_eval, v| h_eval * &*y + &v);
let expected_h_eval = expected_h_eval * ((xn - C::Scalar::ONE).invert().unwrap());
let h_commitment =
self.h_commitments
@ -103,7 +103,7 @@ impl<C: CurveAffine> PartiallyEvaluated<C> {
.rev()
.fold(params.empty_msm(), |mut acc, commitment| {
acc.scale(xn);
acc.append_term(C::Scalar::one(), *commitment);
acc.append_term(C::Scalar::ONE, *commitment);
acc
});

View File

@ -6,7 +6,7 @@ use super::{
vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX, ChallengeY, Error,
VerifyingKey,
};
use crate::arithmetic::{CurveAffine, FieldExt};
use crate::arithmetic::CurveAffine;
use crate::poly::{
commitment::{Blind, Guard, Params, MSM},
multiopen::{self, VerifierQuery},
@ -94,7 +94,7 @@ pub fn verify_proof<
return Err(Error::InstanceTooLarge);
}
let mut poly = instance.to_vec();
poly.resize(params.n as usize, C::Scalar::zero());
poly.resize(params.n as usize, C::Scalar::ZERO);
let poly = vk.domain.lagrange_from_vec(poly);
Ok(params.commit_lagrange(&poly, Blind::default()).to_affine())
@ -213,7 +213,7 @@ pub fn verify_proof<
let l_last = l_evals[0];
let l_blind: C::Scalar = l_evals[1..(1 + blinding_factors)]
.iter()
.fold(C::Scalar::zero(), |acc, eval| acc + eval);
.fold(C::Scalar::ZERO, |acc, eval| acc + eval);
let l_0 = l_evals[1 + blinding_factors];
// Compute the expected value of h(x)

View File

@ -1,4 +1,4 @@
use group::ff::Field;
use group::ff::{Field, FromUniformBytes};
use pasta_curves::arithmetic::CurveAffine;
use rand_core::OsRng;
@ -61,7 +61,12 @@ impl<C: CurveAffine> BatchVerifier<C> {
pub fn add_proof(&mut self, instances: Vec<Vec<Vec<C::Scalar>>>, proof: Vec<u8>) {
self.items.push(BatchItem { instances, proof })
}
}
impl<C: CurveAffine> BatchVerifier<C>
where
C::Scalar: FromUniformBytes<64>,
{
/// Finalizes the batch and checks its validity.
///
/// Returns `false` if *some* proof was invalid. If the caller needs to identify

View File

@ -157,9 +157,7 @@ pub(crate) fn batch_invert_assigned<F: Field>(
assigned
.iter()
.zip(assigned_denominators.into_iter())
.map(|(poly, inv_denoms)| {
poly.invert(inv_denoms.into_iter().map(|d| d.unwrap_or_else(F::one)))
})
.map(|(poly, inv_denoms)| poly.invert(inv_denoms.into_iter().map(|d| d.unwrap_or(F::ONE))))
.collect()
}

View File

@ -4,13 +4,11 @@
//! [halo]: https://eprint.iacr.org/2019/1021
use super::{Coeff, LagrangeCoeff, Polynomial};
use crate::arithmetic::{
best_fft, best_multiexp, parallelize, CurveAffine, CurveExt, FieldExt, Group,
};
use crate::arithmetic::{best_fft, best_multiexp, parallelize, CurveAffine, CurveExt};
use crate::helpers::CurveRead;
use ff::{Field, PrimeField};
use group::{prime::PrimeCurveAffine, Curve, Group as _};
use group::{prime::PrimeCurveAffine, Curve, Group};
use std::ops::{Add, AddAssign, Mul, MulAssign};
mod msm;
@ -208,7 +206,7 @@ pub struct Blind<F>(pub F);
impl<F: Field> Default for Blind<F> {
fn default() -> Self {
Blind(F::one())
Blind(F::ONE)
}
}
@ -357,7 +355,7 @@ fn test_opening_proof() {
assert_eq!(v, v_prime);
let mut commitment_msm = params.empty_msm();
commitment_msm.append_term(Field::one(), p);
commitment_msm.append_term(Field::ONE, p);
let guard = verify_proof(&params, commitment_msm, &mut transcript, *x, v).unwrap();
let ch_verifier = transcript.squeeze_challenge();
assert_eq!(*ch_prover, *ch_verifier);

View File

@ -88,7 +88,7 @@ impl<'a, C: CurveAffine> MSM<'a, C> {
if let Some(g_scalars) = self.g_scalars.as_mut() {
g_scalars[0] += &constant;
} else {
let mut g_scalars = vec![C::Scalar::zero(); self.params.n as usize];
let mut g_scalars = vec![C::Scalar::ZERO; self.params.n as usize];
g_scalars[0] += &constant;
self.g_scalars = Some(g_scalars);
}

View File

@ -85,7 +85,7 @@ pub fn create_proof<
// `p_prime` and `b` is the evaluation of the polynomial at `x_3`.
let mut b = Vec::with_capacity(1 << params.k);
{
let mut cur = C::Scalar::one();
let mut cur = C::Scalar::ONE;
for _ in 0..(1 << params.k) {
b.push(cur);
cur *= &x_3;

View File

@ -54,7 +54,7 @@ impl<'a, C: CurveAffine, E: EncodedChallenge<C>> Guard<'a, C, E> {
/// Computes G = ⟨s, params.g⟩
pub fn compute_g(&self) -> C {
let s = compute_s(&self.u, C::Scalar::one());
let s = compute_s(&self.u, C::Scalar::ONE);
best_multiexp(&s, &self.msm.params.g).to_affine()
}
@ -143,10 +143,10 @@ pub fn verify_proof<'a, C: CurveAffine, E: EncodedChallenge<C>, T: TranscriptRea
/// Computes $\prod\limits_{i=0}^{k-1} (1 + u_{k - 1 - i} x^{2^i})$.
fn compute_b<F: Field>(x: F, u: &[F]) -> F {
let mut tmp = F::one();
let mut tmp = F::ONE;
let mut cur = x;
for u_j in u.iter().rev() {
tmp *= F::one() + &(*u_j * &cur);
tmp *= F::ONE + &(*u_j * &cur);
cur *= cur;
}
tmp
@ -155,7 +155,7 @@ fn compute_b<F: Field>(x: F, u: &[F]) -> F {
/// Computes the coefficients of $g(X) = \prod\limits_{i=0}^{k-1} (1 + u_{k - 1 - i} X^{2^i})$.
fn compute_s<F: Field>(u: &[F], init: F) -> Vec<F> {
assert!(!u.is_empty());
let mut v = vec![F::zero(); 1 << u.len()];
let mut v = vec![F::ZERO; 1 << u.len()];
v[0] = init;
for (len, u_j) in u.iter().rev().enumerate().map(|(i, u_j)| (1 << i, u_j)) {

View File

@ -2,12 +2,13 @@
//! domain that is of a suitable size for the application.
use crate::{
arithmetic::{best_fft, parallelize, FieldExt},
arithmetic::{best_fft, parallelize},
plonk::Assigned,
};
use super::{Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation};
use ff::WithSmallOrderMulGroup;
use group::ff::{BatchInvert, Field};
use std::marker::PhantomData;
@ -33,7 +34,7 @@ pub struct EvaluationDomain<F: Field> {
barycentric_weight: F,
}
impl<F: FieldExt> EvaluationDomain<F> {
impl<F: WithSmallOrderMulGroup<3>> EvaluationDomain<F> {
/// This constructs a new evaluation domain object based on the provided
/// values $j, k$.
pub fn new(j: u32, k: u32) -> Self {
@ -51,7 +52,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
extended_k += 1;
}
let mut extended_omega = F::root_of_unity();
let mut extended_omega = F::ROOT_OF_UNITY;
// Get extended_omega, the 2^{extended_k}'th root of unity
// The loop computes extended_omega = omega^{2 ^ (S - extended_k)}
@ -99,7 +100,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
// Subtract 1 from each to give us t_evaluations[i] = t(zeta * extended_omega^i)
for coeff in &mut t_evaluations {
*coeff -= &F::one();
*coeff -= &F::ONE;
}
// Invert, because we're dividing by this polynomial.
@ -168,7 +169,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
/// Returns an empty (zero) polynomial in the coefficient basis
pub fn empty_coeff(&self) -> Polynomial<F, Coeff> {
Polynomial {
values: vec![F::zero(); self.n as usize],
values: vec![F::ZERO; self.n as usize],
_marker: PhantomData,
}
}
@ -176,7 +177,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
/// Returns an empty (zero) polynomial in the Lagrange coefficient basis
pub fn empty_lagrange(&self) -> Polynomial<F, LagrangeCoeff> {
Polynomial {
values: vec![F::zero(); self.n as usize],
values: vec![F::ZERO; self.n as usize],
_marker: PhantomData,
}
}
@ -185,7 +186,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
/// deferred inversions.
pub(crate) fn empty_lagrange_assigned(&self) -> Polynomial<Assigned<F>, LagrangeCoeff> {
Polynomial {
values: vec![F::zero().into(); self.n as usize],
values: vec![F::ZERO.into(); self.n as usize],
_marker: PhantomData,
}
}
@ -202,7 +203,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
/// basis
pub fn empty_extended(&self) -> Polynomial<F, ExtendedLagrangeCoeff> {
Polynomial {
values: vec![F::zero(); self.extended_len()],
values: vec![F::ZERO; self.extended_len()],
_marker: PhantomData,
}
}
@ -241,7 +242,7 @@ impl<F: FieldExt> EvaluationDomain<F> {
assert_eq!(a.values.len(), 1 << self.k);
self.distribute_powers_zeta(&mut a.values, true);
a.values.resize(self.extended_len(), F::zero());
a.values.resize(self.extended_len(), F::ZERO);
best_fft(&mut a.values, self.extended_omega, self.extended_k);
Polynomial {
@ -452,13 +453,13 @@ impl<F: FieldExt> EvaluationDomain<F> {
results = Vec::with_capacity(rotations.size_hint().1.unwrap_or(0));
for rotation in rotations {
let rotation = Rotation(rotation);
let result = x - self.rotate_omega(F::one(), rotation);
let result = x - self.rotate_omega(F::ONE, rotation);
results.push(result);
}
results.iter_mut().batch_invert();
}
let common = (xn - F::one()) * self.barycentric_weight;
let common = (xn - F::ONE) * self.barycentric_weight;
for (rotation, result) in rotations.into_iter().zip(results.iter_mut()) {
let rotation = Rotation(rotation);
*result = self.rotate_omega(*result * common, rotation);
@ -549,7 +550,7 @@ fn test_l_i() {
}
for i in 0..8 {
let mut l_i = vec![Scalar::zero(); 8];
l_i[i] = Scalar::one();
l_i[i] = Scalar::ONE;
let l_i = lagrange_interpolate(&points[..], &l_i[..]);
l.push(l_i);
}

View File

@ -6,8 +6,8 @@ use std::{
sync::Arc,
};
use ff::WithSmallOrderMulGroup;
use group::ff::Field;
use pasta_curves::arithmetic::FieldExt;
use super::{
Basis, Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation,
@ -133,7 +133,7 @@ impl<E, F: Field, B: Basis> Evaluator<E, F, B> {
) -> Polynomial<F, B>
where
E: Copy + Send + Sync,
F: FieldExt,
F: WithSmallOrderMulGroup<3>,
B: BasisOps,
{
// We're working in a single basis, so all polynomials are the same length.
@ -148,7 +148,7 @@ impl<E, F: Field, B: Basis> Evaluator<E, F, B> {
polys: &'a [Polynomial<F, B>],
}
fn recurse<E, F: FieldExt, B: BasisOps>(
fn recurse<E, F: WithSmallOrderMulGroup<3>, B: BasisOps>(
ast: &Ast<E, F, B>,
ctx: &AstContext<'_, F, B>,
) -> Vec<F> {
@ -184,7 +184,7 @@ impl<E, F: Field, B: Basis> Evaluator<E, F, B> {
lhs
}
Ast::DistributePowers(terms, base) => terms.iter().fold(
B::constant_term(ctx.poly_len, ctx.chunk_size, ctx.chunk_index, F::zero()),
B::constant_term(ctx.poly_len, ctx.chunk_size, ctx.chunk_index, F::ZERO),
|mut acc, term| {
let term = recurse(term, ctx);
for (acc, term) in acc.iter_mut().zip(term) {
@ -299,7 +299,7 @@ impl<E, F: Field, B: Basis> From<AstLeaf<E, B>> for Ast<E, F, B> {
impl<E, F: Field, B: Basis> Ast<E, F, B> {
pub(crate) fn one() -> Self {
Self::ConstantTerm(F::one())
Self::ConstantTerm(F::ONE)
}
}
@ -307,7 +307,7 @@ impl<E, F: Field, B: Basis> Neg for Ast<E, F, B> {
type Output = Ast<E, F, B>;
fn neg(self) -> Self::Output {
Ast::Scale(Arc::new(self), -F::one())
Ast::Scale(Arc::new(self), -F::ONE)
}
}
@ -441,21 +441,23 @@ impl<E: Clone, F: Field> MulAssign for Ast<E, F, ExtendedLagrangeCoeff> {
/// Operations which can be performed over a given basis.
pub(crate) trait BasisOps: Basis {
fn empty_poly<F: FieldExt>(domain: &EvaluationDomain<F>) -> Polynomial<F, Self>;
fn empty_poly<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
) -> Polynomial<F, Self>;
fn constant_term<F: Field>(
poly_len: usize,
chunk_size: usize,
chunk_index: usize,
scalar: F,
) -> Vec<F>;
fn linear_term<F: FieldExt>(
fn linear_term<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
poly_len: usize,
chunk_size: usize,
chunk_index: usize,
scalar: F,
) -> Vec<F>;
fn get_chunk_of_rotated<F: FieldExt>(
fn get_chunk_of_rotated<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
chunk_size: usize,
chunk_index: usize,
@ -465,7 +467,9 @@ pub(crate) trait BasisOps: Basis {
}
impl BasisOps for Coeff {
fn empty_poly<F: FieldExt>(domain: &EvaluationDomain<F>) -> Polynomial<F, Self> {
fn empty_poly<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
) -> Polynomial<F, Self> {
domain.empty_coeff()
}
@ -475,21 +479,21 @@ impl BasisOps for Coeff {
chunk_index: usize,
scalar: F,
) -> Vec<F> {
let mut chunk = vec![F::zero(); cmp::min(chunk_size, poly_len - chunk_size * chunk_index)];
let mut chunk = vec![F::ZERO; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)];
if chunk_index == 0 {
chunk[0] = scalar;
}
chunk
}
fn linear_term<F: FieldExt>(
fn linear_term<F: WithSmallOrderMulGroup<3>>(
_: &EvaluationDomain<F>,
poly_len: usize,
chunk_size: usize,
chunk_index: usize,
scalar: F,
) -> Vec<F> {
let mut chunk = vec![F::zero(); cmp::min(chunk_size, poly_len - chunk_size * chunk_index)];
let mut chunk = vec![F::ZERO; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)];
// If the chunk size is 1 (e.g. if we have a small k and many threads), then the
// linear coefficient is the second chunk. Otherwise, the chunk size is greater
// than one, and the linear coefficient is the second element of the first chunk.
@ -504,7 +508,7 @@ impl BasisOps for Coeff {
chunk
}
fn get_chunk_of_rotated<F: FieldExt>(
fn get_chunk_of_rotated<F: WithSmallOrderMulGroup<3>>(
_: &EvaluationDomain<F>,
_: usize,
_: usize,
@ -516,7 +520,9 @@ impl BasisOps for Coeff {
}
impl BasisOps for LagrangeCoeff {
fn empty_poly<F: FieldExt>(domain: &EvaluationDomain<F>) -> Polynomial<F, Self> {
fn empty_poly<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
) -> Polynomial<F, Self> {
domain.empty_lagrange()
}
@ -529,7 +535,7 @@ impl BasisOps for LagrangeCoeff {
vec![scalar; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]
}
fn linear_term<F: FieldExt>(
fn linear_term<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
poly_len: usize,
chunk_size: usize,
@ -548,7 +554,7 @@ impl BasisOps for LagrangeCoeff {
.collect()
}
fn get_chunk_of_rotated<F: FieldExt>(
fn get_chunk_of_rotated<F: WithSmallOrderMulGroup<3>>(
_: &EvaluationDomain<F>,
chunk_size: usize,
chunk_index: usize,
@ -560,7 +566,9 @@ impl BasisOps for LagrangeCoeff {
}
impl BasisOps for ExtendedLagrangeCoeff {
fn empty_poly<F: FieldExt>(domain: &EvaluationDomain<F>) -> Polynomial<F, Self> {
fn empty_poly<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
) -> Polynomial<F, Self> {
domain.empty_extended()
}
@ -573,7 +581,7 @@ impl BasisOps for ExtendedLagrangeCoeff {
vec![scalar; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]
}
fn linear_term<F: FieldExt>(
fn linear_term<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
poly_len: usize,
chunk_size: usize,
@ -595,7 +603,7 @@ impl BasisOps for ExtendedLagrangeCoeff {
.collect()
}
fn get_chunk_of_rotated<F: FieldExt>(
fn get_chunk_of_rotated<F: WithSmallOrderMulGroup<3>>(
domain: &EvaluationDomain<F>,
chunk_size: usize,
chunk_index: usize,
@ -608,6 +616,7 @@ impl BasisOps for ExtendedLagrangeCoeff {
#[cfg(test)]
mod tests {
use group::ff::Field;
use pasta_curves::pallas;
use super::{get_chunk_params, new_evaluator, Ast, BasisOps, Evaluator};
@ -643,8 +652,8 @@ mod tests {
evaluator.register_poly(B::empty_poly(&domain));
// With the bug present, these will panic.
let _ = evaluator.evaluate(&Ast::ConstantTerm(pallas::Base::zero()), &domain);
let _ = evaluator.evaluate(&Ast::LinearTerm(pallas::Base::zero()), &domain);
let _ = evaluator.evaluate(&Ast::ConstantTerm(pallas::Base::ZERO), &domain);
let _ = evaluator.evaluate(&Ast::LinearTerm(pallas::Base::ZERO), &domain);
}
test_case(k, new_evaluator::<_, _, Coeff>(|| {}));

View File

@ -386,10 +386,11 @@ mod tests {
#[cfg(test)]
mod proptests {
use group::ff::FromUniformBytes;
use proptest::{collection::vec, prelude::*, sample::select};
use super::construct_intermediate_sets;
use pasta_curves::{arithmetic::FieldExt, Fp};
use pasta_curves::Fp;
use std::convert::TryFrom;
@ -421,7 +422,7 @@ mod proptests {
fn arb_point()(
bytes in vec(any::<u8>(), 64)
) -> Fp {
Fp::from_bytes_wide(&<[u8; 64]>::try_from(bytes).unwrap())
Fp::from_uniform_bytes(&<[u8; 64]>::try_from(bytes).unwrap())
}
}

View File

@ -41,7 +41,7 @@ where
// Collapse openings at same point sets together into single openings using
// x_1 challenge.
let mut q_polys: Vec<Option<Polynomial<C::Scalar, Coeff>>> = vec![None; point_sets.len()];
let mut q_blinds = vec![Blind(C::Scalar::zero()); point_sets.len()];
let mut q_blinds = vec![Blind(C::Scalar::ZERO); point_sets.len()];
{
let mut accumulate =
@ -73,7 +73,7 @@ where
.fold(poly.clone().unwrap().values, |poly, point| {
kate_division(&poly, *point)
});
poly.resize(params.n as usize, C::Scalar::zero());
poly.resize(params.n as usize, C::Scalar::ZERO);
let poly = Polynomial {
values: poly,
_marker: PhantomData,

View File

@ -40,14 +40,14 @@ where
// Compress the commitments and expected evaluations at x together.
// using the challenge x_1
let mut q_commitments: Vec<_> = vec![
(params.empty_msm(), C::Scalar::one()); // (accumulator, next x_1 power).
(params.empty_msm(), C::Scalar::ONE); // (accumulator, next x_1 power).
point_sets.len()];
// A vec of vecs of evals. The outer vec corresponds to the point set,
// while the inner vec corresponds to the points in a particular set.
let mut q_eval_sets = Vec::with_capacity(point_sets.len());
for point_set in point_sets.iter() {
q_eval_sets.push(vec![C::Scalar::zero(); point_set.len()]);
q_eval_sets.push(vec![C::Scalar::ZERO; point_set.len()]);
}
{
@ -102,7 +102,7 @@ where
.zip(q_eval_sets.iter())
.zip(u.iter())
.fold(
C::Scalar::zero(),
C::Scalar::ZERO,
|msm_eval, ((points, evals), proof_eval)| {
let r_poly = lagrange_interpolate(points, evals);
let r_eval = eval_polynomial(&r_poly, *x_3);
@ -118,7 +118,7 @@ where
let x_4: ChallengeX4<_> = transcript.squeeze_challenge_scalar();
// Compute the final commitment that has to be opened
msm.append_term(C::Scalar::one(), q_prime_commitment);
msm.append_term(C::Scalar::ONE, q_prime_commitment);
let (msm, v) = q_commitments.into_iter().zip(u.iter()).fold(
(msm, msm_eval),
|(mut msm, msm_eval), ((q_commitment, _), q_eval)| {

View File

@ -2,10 +2,10 @@
//! transcripts.
use blake2b_simd::{Params as Blake2bParams, State as Blake2bState};
use group::ff::PrimeField;
use group::ff::{FromUniformBytes, PrimeField};
use std::convert::TryInto;
use crate::arithmetic::{Coordinates, CurveAffine, FieldExt};
use crate::arithmetic::{Coordinates, CurveAffine};
use std::io::{self, Read, Write};
use std::marker::PhantomData;
@ -85,6 +85,8 @@ impl<R: Read, C: CurveAffine, E: EncodedChallenge<C>> Blake2bRead<R, C, E> {
impl<R: Read, C: CurveAffine> TranscriptRead<C, Challenge255<C>>
for Blake2bRead<R, C, Challenge255<C>>
where
C::Scalar: FromUniformBytes<64>,
{
fn read_point(&mut self) -> io::Result<C> {
let mut compressed = C::Repr::default();
@ -112,8 +114,9 @@ impl<R: Read, C: CurveAffine> TranscriptRead<C, Challenge255<C>>
}
}
impl<R: Read, C: CurveAffine> Transcript<C, Challenge255<C>>
for Blake2bRead<R, C, Challenge255<C>>
impl<R: Read, C: CurveAffine> Transcript<C, Challenge255<C>> for Blake2bRead<R, C, Challenge255<C>>
where
C::Scalar: FromUniformBytes<64>,
{
fn squeeze_challenge(&mut self) -> Challenge255<C> {
self.state.update(&[BLAKE2B_PREFIX_CHALLENGE]);
@ -174,6 +177,8 @@ impl<W: Write, C: CurveAffine, E: EncodedChallenge<C>> Blake2bWrite<W, C, E> {
impl<W: Write, C: CurveAffine> TranscriptWrite<C, Challenge255<C>>
for Blake2bWrite<W, C, Challenge255<C>>
where
C::Scalar: FromUniformBytes<64>,
{
fn write_point(&mut self, point: C) -> io::Result<()> {
self.common_point(point)?;
@ -189,6 +194,8 @@ impl<W: Write, C: CurveAffine> TranscriptWrite<C, Challenge255<C>>
impl<W: Write, C: CurveAffine> Transcript<C, Challenge255<C>>
for Blake2bWrite<W, C, Challenge255<C>>
where
C::Scalar: FromUniformBytes<64>,
{
fn squeeze_challenge(&mut self) -> Challenge255<C> {
self.state.update(&[BLAKE2B_PREFIX_CHALLENGE]);
@ -273,12 +280,15 @@ impl<C: CurveAffine> std::ops::Deref for Challenge255<C> {
}
}
impl<C: CurveAffine> EncodedChallenge<C> for Challenge255<C> {
impl<C: CurveAffine> EncodedChallenge<C> for Challenge255<C>
where
C::Scalar: FromUniformBytes<64>,
{
type Input = [u8; 64];
fn new(challenge_input: &[u8; 64]) -> Self {
Challenge255(
C::Scalar::from_bytes_wide(challenge_input)
C::Scalar::from_uniform_bytes(challenge_input)
.to_repr()
.as_ref()
.try_into()

View File

@ -2,8 +2,8 @@
#![allow(clippy::op_ref)]
use assert_matches::assert_matches;
use group::ff::Field;
use halo2_proofs::arithmetic::{CurveAffine, FieldExt};
use group::ff::{Field, WithSmallOrderMulGroup};
use halo2_proofs::arithmetic::CurveAffine;
use halo2_proofs::circuit::{Cell, Layouter, SimpleFloorPlanner, Value};
use halo2_proofs::dev::MockProver;
use halo2_proofs::pasta::{Eq, EqAffine, Fp};
@ -138,15 +138,10 @@ fn plonk_api() {
|| value.unwrap().map(|v| v.2),
)?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::zero()))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?;
region.assign_fixed(
|| "a * b",
self.config.sm,
0,
|| Value::known(FF::one()),
)?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ZERO))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ZERO))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ONE))?;
Ok((lhs.cell(), rhs.cell(), out.cell()))
},
)
@ -197,14 +192,14 @@ fn plonk_api() {
|| value.unwrap().map(|v| v.2),
)?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?;
region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ONE))?;
region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?;
region.assign_fixed(
|| "a * b",
self.config.sm,
0,
|| Value::known(FF::zero()),
|| Value::known(FF::ZERO),
)?;
Ok((lhs.cell(), rhs.cell(), out.cell()))
},
@ -236,7 +231,7 @@ fn plonk_api() {
|| "public",
self.config.sp,
0,
|| Value::known(FF::one()),
|| Value::known(FF::ONE),
)?;
Ok(value.cell())
@ -374,7 +369,7 @@ fn plonk_api() {
) -> Result<(), Error> {
let cs = StandardPlonk::new(config);
let _ = cs.public_input(&mut layouter, || Value::known(F::one() + F::one()))?;
let _ = cs.public_input(&mut layouter, || Value::known(F::ONE + F::ONE))?;
for _ in 0..10 {
let a: Value<Assigned<_>> = self.a.into();
@ -400,8 +395,8 @@ fn plonk_api() {
}
let a = Fp::from(2834758237) * Fp::ZETA;
let instance = Fp::one() + Fp::one();
let lookup_table = vec![instance, a, a, Fp::zero()];
let instance = Fp::ONE + Fp::ONE;
let lookup_table = vec![instance, a, a, Fp::ZERO];
let empty_circuit: MyCircuit<Fp> = MyCircuit {
a: Value::unknown(),