use group::{
ff::{BatchInvert, Field},
Curve,
};
use rand_core::RngCore;
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},
plonk::{self, Error},
poly::{
self,
commitment::{Blind, Params},
multiopen::ProverQuery,
Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation,
},
transcript::{EncodedChallenge, TranscriptWrite},
};
pub struct CommittedSet<C: CurveAffine, Ev> {
permutation_product_poly: Polynomial<C::Scalar, Coeff>,
permutation_product_coset: poly::AstLeaf<Ev, ExtendedLagrangeCoeff>,
permutation_product_blind: Blind<C::Scalar>,
}
pub(crate) struct Committed<C: CurveAffine, Ev> {
sets: Vec<CommittedSet<C, Ev>>,
}
pub struct ConstructedSet<C: CurveAffine> {
permutation_product_poly: Polynomial<C::Scalar, Coeff>,
permutation_product_blind: Blind<C::Scalar>,
}
pub(crate) struct Constructed<C: CurveAffine> {
sets: Vec<ConstructedSet<C>>,
}
pub(crate) struct Evaluated<C: CurveAffine> {
constructed: Constructed<C>,
}
impl Argument {
pub(in crate::plonk) fn commit<
C: CurveAffine,
E: EncodedChallenge<C>,
Ev: Copy + Send + Sync,
R: RngCore,
T: TranscriptWrite<C, E>,
>(
&self,
params: &Params<C>,
pk: &plonk::ProvingKey<C>,
pkey: &ProvingKey<C>,
advice: &[Polynomial<C::Scalar, LagrangeCoeff>],
fixed: &[Polynomial<C::Scalar, LagrangeCoeff>],
instance: &[Polynomial<C::Scalar, LagrangeCoeff>],
beta: ChallengeBeta<C>,
gamma: ChallengeGamma<C>,
evaluator: &mut poly::Evaluator<Ev, C::Scalar, ExtendedLagrangeCoeff>,
mut rng: R,
transcript: &mut T,
) -> Result<Committed<C, Ev>, Error> {
let domain = &pk.vk.domain;
assert!(pk.vk.cs.degree() >= 3);
let chunk_len = pk.vk.cs.degree() - 2;
let blinding_factors = pk.vk.cs.blinding_factors();
let mut deltaomega = C::Scalar::one();
let mut last_z = C::Scalar::one();
let mut sets = vec![];
for (columns, permutations) in self
.columns
.chunks(chunk_len)
.zip(pkey.permutations.chunks(chunk_len))
{
let mut modified_values = vec![C::Scalar::one(); params.n as usize];
for (&column, permuted_column_values) in columns.iter().zip(permutations.iter()) {
let values = match column.column_type() {
Any::Advice => advice,
Any::Fixed => fixed,
Any::Instance => instance,
};
parallelize(&mut modified_values, |modified_values, start| {
for ((modified_values, value), permuted_value) in modified_values
.iter_mut()
.zip(values[column.index()][start..].iter())
.zip(permuted_column_values[start..].iter())
{
*modified_values *= &(*beta * permuted_value + &*gamma + value);
}
});
}
modified_values.batch_invert();
for &column in columns.iter() {
let omega = domain.get_omega();
let values = match column.column_type() {
Any::Advice => advice,
Any::Fixed => fixed,
Any::Instance => instance,
};
parallelize(&mut modified_values, |modified_values, start| {
let mut deltaomega = deltaomega * &omega.pow_vartime(&[start as u64, 0, 0, 0]);
for (modified_values, value) in modified_values
.iter_mut()
.zip(values[column.index()][start..].iter())
{
*modified_values *= &(deltaomega * &*beta + &*gamma + value);
deltaomega *= ω
}
});
deltaomega *= &C::Scalar::DELTA;
}
let mut z = vec![last_z];
for row in 1..(params.n as usize) {
let mut tmp = z[row - 1];
tmp *= &modified_values[row - 1];
z.push(tmp);
}
let mut z = domain.lagrange_from_vec(z);
for z in &mut z[params.n as usize - blinding_factors..] {
*z = C::Scalar::random(&mut rng);
}
last_z = z[params.n as usize - (blinding_factors + 1)];
let blind = Blind(C::Scalar::random(&mut rng));
let permutation_product_commitment_projective = params.commit_lagrange(&z, blind);
let permutation_product_blind = blind;
let z = domain.lagrange_to_coeff(z);
let permutation_product_poly = z.clone();
let permutation_product_coset =
evaluator.register_poly(domain.coeff_to_extended(z.clone()));
let permutation_product_commitment =
permutation_product_commitment_projective.to_affine();
transcript.write_point(permutation_product_commitment)?;
sets.push(CommittedSet {
permutation_product_poly,
permutation_product_coset,
permutation_product_blind,
});
}
Ok(Committed { sets })
}
}
impl<C: CurveAffine, Ev: Copy + Send + Sync> Committed<C, Ev> {
pub(in crate::plonk) fn construct<'a>(
self,
pk: &'a plonk::ProvingKey<C>,
p: &'a Argument,
advice_cosets: &'a [poly::AstLeaf<Ev, ExtendedLagrangeCoeff>],
fixed_cosets: &'a [poly::AstLeaf<Ev, ExtendedLagrangeCoeff>],
instance_cosets: &'a [poly::AstLeaf<Ev, ExtendedLagrangeCoeff>],
permutation_cosets: &'a [poly::AstLeaf<Ev, ExtendedLagrangeCoeff>],
l0: poly::AstLeaf<Ev, ExtendedLagrangeCoeff>,
l_blind: poly::AstLeaf<Ev, ExtendedLagrangeCoeff>,
l_last: poly::AstLeaf<Ev, ExtendedLagrangeCoeff>,
beta: ChallengeBeta<C>,
gamma: ChallengeGamma<C>,
) -> (
Constructed<C>,
impl Iterator<Item = poly::Ast<Ev, C::Scalar, ExtendedLagrangeCoeff>> + 'a,
) {
let chunk_len = pk.vk.cs.degree() - 2;
let blinding_factors = pk.vk.cs.blinding_factors();
let last_rotation = Rotation(-((blinding_factors + 1) as i32));
let constructed = Constructed {
sets: self
.sets
.iter()
.map(|set| ConstructedSet {
permutation_product_poly: set.permutation_product_poly.clone(),
permutation_product_blind: set.permutation_product_blind,
})
.collect(),
};
let expressions = iter::empty()
.chain(
self.sets
.first()
.map(|first_set| (poly::Ast::one() - first_set.permutation_product_coset) * l0),
)
.chain(self.sets.last().map(|last_set| {
((poly::Ast::from(last_set.permutation_product_coset)
* last_set.permutation_product_coset)
- last_set.permutation_product_coset)
* l_last
}))
.chain(
self.sets
.iter()
.skip(1)
.zip(self.sets.iter())
.map(|(set, last_set)| {
(poly::Ast::from(set.permutation_product_coset)
- last_set
.permutation_product_coset
.with_rotation(last_rotation))
* l0
})
.collect::<Vec<_>>(),
)
.chain(
self.sets
.into_iter()
.zip(p.columns.chunks(chunk_len))
.zip(permutation_cosets.chunks(chunk_len))
.enumerate()
.map(move |(chunk_index, ((set, columns), cosets))| {
let mut left = poly::Ast::<_, C::Scalar, _>::from(
set.permutation_product_coset
.with_rotation(Rotation::next()),
);
for (values, permutation) in columns
.iter()
.map(|&column| match column.column_type() {
Any::Advice => &advice_cosets[column.index()],
Any::Fixed => &fixed_cosets[column.index()],
Any::Instance => &instance_cosets[column.index()],
})
.zip(cosets.iter())
{
left *= poly::Ast::<_, C::Scalar, _>::from(*values)
+ (poly::Ast::ConstantTerm(*beta) * poly::Ast::from(*permutation))
+ poly::Ast::ConstantTerm(*gamma);
}
let mut right = poly::Ast::from(set.permutation_product_coset);
let mut current_delta = *beta
* &(C::Scalar::DELTA.pow_vartime(&[(chunk_index * chunk_len) as u64]));
for values in columns.iter().map(|&column| match column.column_type() {
Any::Advice => &advice_cosets[column.index()],
Any::Fixed => &fixed_cosets[column.index()],
Any::Instance => &instance_cosets[column.index()],
}) {
right *= poly::Ast::from(*values)
+ poly::Ast::LinearTerm(current_delta)
+ poly::Ast::ConstantTerm(*gamma);
current_delta *= &C::Scalar::DELTA;
}
(left - right) * (poly::Ast::one() - (poly::Ast::from(l_last) + l_blind))
}),
);
(constructed, expressions)
}
}
impl<C: CurveAffine> super::ProvingKey<C> {
pub(in crate::plonk) fn open(
&self,
x: ChallengeX<C>,
) -> impl Iterator<Item = ProverQuery<'_, C>> + Clone {
self.polys.iter().map(move |poly| ProverQuery {
point: *x,
poly,
blind: Blind::default(),
})
}
pub(in crate::plonk) fn evaluate<E: EncodedChallenge<C>, T: TranscriptWrite<C, E>>(
&self,
x: ChallengeX<C>,
transcript: &mut T,
) -> Result<(), Error> {
for eval in self.polys.iter().map(|poly| eval_polynomial(poly, *x)) {
transcript.write_scalar(eval)?;
}
Ok(())
}
}
impl<C: CurveAffine> Constructed<C> {
pub(in crate::plonk) fn evaluate<E: EncodedChallenge<C>, T: TranscriptWrite<C, E>>(
self,
pk: &plonk::ProvingKey<C>,
x: ChallengeX<C>,
transcript: &mut T,
) -> Result<Evaluated<C>, Error> {
let domain = &pk.vk.domain;
let blinding_factors = pk.vk.cs.blinding_factors();
{
let mut sets = self.sets.iter();
while let Some(set) = sets.next() {
let permutation_product_eval = eval_polynomial(&set.permutation_product_poly, *x);
let permutation_product_next_eval = eval_polynomial(
&set.permutation_product_poly,
domain.rotate_omega(*x, Rotation::next()),
);
for eval in iter::empty()
.chain(Some(&permutation_product_eval))
.chain(Some(&permutation_product_next_eval))
{
transcript.write_scalar(*eval)?;
}
if sets.len() > 0 {
let permutation_product_last_eval = eval_polynomial(
&set.permutation_product_poly,
domain.rotate_omega(*x, Rotation(-((blinding_factors + 1) as i32))),
);
transcript.write_scalar(permutation_product_last_eval)?;
}
}
}
Ok(Evaluated { constructed: self })
}
}
impl<C: CurveAffine> Evaluated<C> {
pub(in crate::plonk) fn open<'a>(
&'a self,
pk: &'a plonk::ProvingKey<C>,
x: ChallengeX<C>,
) -> impl Iterator<Item = ProverQuery<'a, C>> + Clone {
let blinding_factors = pk.vk.cs.blinding_factors();
let x_next = pk.vk.domain.rotate_omega(*x, Rotation::next());
let x_last = pk
.vk
.domain
.rotate_omega(*x, Rotation(-((blinding_factors + 1) as i32)));
iter::empty()
.chain(self.constructed.sets.iter().flat_map(move |set| {
iter::empty()
.chain(Some(ProverQuery {
point: *x,
poly: &set.permutation_product_poly,
blind: set.permutation_product_blind,
}))
.chain(Some(ProverQuery {
point: x_next,
poly: &set.permutation_product_poly,
blind: set.permutation_product_blind,
}))
}))
.chain(
self.constructed
.sets
.iter()
.rev()
.skip(1)
.flat_map(move |set| {
Some(ProverQuery {
point: x_last,
poly: &set.permutation_product_poly,
blind: set.permutation_product_blind,
})
}),
)
}
}