arnaucube
arnaucube/hyperplonkPublic Self-hosted repository
hyperplonk/poly-iop/src/prod_check/mod.rs
poly-iop/src/prod_check/mod.rsRaw
  1//! Main module for the Product Check protocol
  2
  3use crate::{
  4    errors::PolyIOPErrors,
  5    prod_check::util::{compute_product_poly, prove_zero_check},
  6    PolyIOP, ZeroCheck,
  7};
  8use arithmetic::VPAuxInfo;
  9use ark_ec::PairingEngine;
 10use ark_ff::{One, PrimeField, Zero};
 11use ark_poly::DenseMultilinearExtension;
 12use ark_std::{end_timer, start_timer};
 13use pcs::prelude::PolynomialCommitmentScheme;
 14use std::{marker::PhantomData, rc::Rc};
 15use transcript::IOPTranscript;
 16
 17mod util;
 18
 19/// A product-check proves that two n-variate multilinear polynomials `f(x),
 20/// g(x)` satisfy:
 21/// \prod_{x \in {0,1}^n} f(x) = \prod_{x \in {0,1}^n} g(x)
 22///
 23/// A ProductCheck is derived from ZeroCheck.
 24///
 25/// Prover steps:
 26/// 1. build `prod(x0, ..., x_n)` from f and g,
 27///    such that `prod(0, x1, ..., xn)` equals `f/g` over domain {0,1}^n
 28/// 2. push commitments of `prod(x)` to the transcript,
 29///    and `generate_challenge` from current transcript (generate alpha)
 30/// 3. generate the zerocheck proof for the virtual polynomial
 31///    prod(1, x) - prod(x, 0) * prod(x, 1) + alpha * (f(x) - prod(0, x) * g(x))
 32///
 33/// Verifier steps:
 34/// 1. Extract commitments of `prod(x)` from the proof, push
 35/// them to the transcript
 36/// 2. `generate_challenge` from current transcript (generate alpha)
 37/// 3. `verify` to verify the zerocheck proof and generate the subclaim for
 38/// polynomial evaluations
 39pub trait ProductCheck<E, PCS>: ZeroCheck<E::Fr>
 40where
 41    E: PairingEngine,
 42    PCS: PolynomialCommitmentScheme<E>,
 43{
 44    type ProductCheckSubClaim;
 45    type ProductProof;
 46    type Polynomial;
 47
 48    /// Initialize the system with a transcript
 49    ///
 50    /// This function is optional -- in the case where a ProductCheck is
 51    /// an building block for a more complex protocol, the transcript
 52    /// may be initialized by this complex protocol, and passed to the
 53    /// ProductCheck prover/verifier.
 54    fn init_transcript() -> Self::Transcript;
 55
 56    /// Generate a proof for product check, showing that witness multilinear
 57    /// polynomials f(x), g(x) satisfy `\prod_{x \in {0,1}^n} f(x) =
 58    /// \prod_{x \in {0,1}^n} g(x)`
 59    ///
 60    /// Inputs:
 61    /// - fx: the numerator multilinear polynomial
 62    /// - gx: the denominator multilinear polynomial
 63    /// - transcript: the IOP transcript
 64    /// - pk: PCS committing key
 65    ///
 66    /// Outputs
 67    /// - the product check proof
 68    /// - the product polynomial (used for testing)
 69    ///
 70    /// Cost: O(N)
 71    fn prove(
 72        fx: &Self::Polynomial,
 73        gx: &Self::Polynomial,
 74        transcript: &mut IOPTranscript<E::Fr>,
 75        pk: &PCS::ProverParam,
 76    ) -> Result<(Self::ProductProof, Self::Polynomial), PolyIOPErrors>;
 77
 78    /// Verify that for witness multilinear polynomials f(x), g(x)
 79    /// it holds that `\prod_{x \in {0,1}^n} f(x) = \prod_{x \in {0,1}^n} g(x)`
 80    fn verify(
 81        proof: &Self::ProductProof,
 82        num_vars: usize,
 83        transcript: &mut Self::Transcript,
 84    ) -> Result<Self::ProductCheckSubClaim, PolyIOPErrors>;
 85}
 86
 87/// A product check subclaim consists of
 88/// - A zero check IOP subclaim for
 89/// `Q(x) = prod(1, x) - prod(x, 0) * prod(x, 1) + challenge * (f(x) - prod(0,
 90/// x) * g(x))` is 0, consists of the following:
 91///   - the SubClaim from the SumCheck
 92///   - the initial challenge r which is used to build eq(x, r) in ZeroCheck
 93/// - The challenge `challenge`
 94/// - A final query for `prod(1, ..., 1, 0) = claimed_product`.
 95// Note that this final query is in fact a constant that
 96// is independent from the proof. So we should avoid
 97// (de)serialize it.
 98#[derive(Clone, Debug, Default, PartialEq)]
 99pub struct ProductCheckSubClaim<F: PrimeField, ZC: ZeroCheck<F>> {
100    // the SubClaim from the ZeroCheck
101    zero_check_sub_claim: ZC::ZeroCheckSubClaim,
102    // final query which consists of
103    // - the vector `(1, ..., 1, 0)` (needs to be reversed because Arkwork's MLE uses big-endian
104    //   format for points)
105    // The expected final query evaluation is 1
106    final_query: (Vec<F>, F),
107    challenge: F,
108}
109
110/// A product check proof consists of
111/// - a zerocheck proof
112/// - a product polynomial commitment
113#[derive(Clone, Debug, Default, PartialEq)]
114pub struct ProductProof<E: PairingEngine, PCS: PolynomialCommitmentScheme<E>, ZC: ZeroCheck<E::Fr>>
115{
116    zero_check_proof: ZC::ZeroCheckProof,
117    prod_x_comm: PCS::Commitment,
118}
119
120impl<E, PCS> ProductCheck<E, PCS> for PolyIOP<E::Fr>
121where
122    E: PairingEngine,
123    PCS: PolynomialCommitmentScheme<E, Polynomial = Rc<DenseMultilinearExtension<E::Fr>>>,
124{
125    type ProductCheckSubClaim = ProductCheckSubClaim<E::Fr, Self>;
126    type ProductProof = ProductProof<E, PCS, Self>;
127    type Polynomial = Rc<DenseMultilinearExtension<E::Fr>>;
128
129    fn init_transcript() -> Self::Transcript {
130        IOPTranscript::<E::Fr>::new(b"Initializing ProductCheck transcript")
131    }
132
133    fn prove(
134        fx: &Self::Polynomial,
135        gx: &Self::Polynomial,
136        transcript: &mut IOPTranscript<E::Fr>,
137        pk: &PCS::ProverParam,
138    ) -> Result<(Self::ProductProof, Self::Polynomial), PolyIOPErrors> {
139        let start = start_timer!(|| "prod_check prove");
140
141        if fx.num_vars != gx.num_vars {
142            return Err(PolyIOPErrors::InvalidParameters(
143                "fx and gx have different number of variables".to_string(),
144            ));
145        }
146
147        // compute the product polynomial
148        let prod_x = compute_product_poly(fx, gx)?;
149
150        // generate challenge
151        let prod_x_comm = PCS::commit(pk, &Rc::new(prod_x.clone()))?;
152        transcript.append_serializable_element(b"prod(x)", &prod_x_comm)?;
153        let alpha = transcript.get_and_append_challenge(b"alpha")?;
154
155        // build the zero-check proof
156        let (zero_check_proof, _) = prove_zero_check(fx, gx, &prod_x, &alpha, transcript)?;
157
158        end_timer!(start);
159
160        Ok((
161            ProductProof {
162                zero_check_proof,
163                prod_x_comm,
164            },
165            Rc::new(prod_x.clone()),
166        ))
167    }
168
169    fn verify(
170        proof: &Self::ProductProof,
171        num_vars: usize,
172        transcript: &mut Self::Transcript,
173    ) -> Result<Self::ProductCheckSubClaim, PolyIOPErrors> {
174        let start = start_timer!(|| "prod_check verify");
175
176        // update transcript and generate challenge
177        transcript.append_serializable_element(b"prod(x)", &proof.prod_x_comm)?;
178        let alpha = transcript.get_and_append_challenge(b"alpha")?;
179
180        // invoke the zero check on the iop_proof
181        // the virtual poly info for Q(x)
182        let aux_info = VPAuxInfo {
183            max_degree: 2,
184            num_variables: num_vars,
185            phantom: PhantomData::default(),
186        };
187        let zero_check_sub_claim =
188            <Self as ZeroCheck<E::Fr>>::verify(&proof.zero_check_proof, &aux_info, transcript)?;
189
190        // the final query is on prod_x, hence has length `num_vars` + 1
191        let mut final_query = vec![E::Fr::one(); aux_info.num_variables + 1];
192        // the point has to be reversed because Arkworks uses big-endian.
193        final_query[0] = E::Fr::zero();
194        let final_eval = E::Fr::one();
195
196        end_timer!(start);
197
198        Ok(ProductCheckSubClaim {
199            zero_check_sub_claim,
200            final_query: (final_query, final_eval),
201            challenge: alpha,
202        })
203    }
204}
205
206#[cfg(test)]
207mod test {
208    use super::ProductCheck;
209    use crate::{errors::PolyIOPErrors, PolyIOP};
210    use ark_bls12_381::{Bls12_381, Fr};
211    use ark_ec::PairingEngine;
212    use ark_poly::{DenseMultilinearExtension, MultilinearExtension};
213    use ark_std::test_rng;
214    use pcs::{prelude::KZGMultilinearPCS, PolynomialCommitmentScheme};
215    use std::rc::Rc;
216
217    // f and g are guaranteed to have the same product
218    fn test_product_check_helper<E, PCS>(
219        f: &DenseMultilinearExtension<E::Fr>,
220        g: &DenseMultilinearExtension<E::Fr>,
221        pk: &PCS::ProverParam,
222    ) -> Result<(), PolyIOPErrors>
223    where
224        E: PairingEngine,
225        PCS: PolynomialCommitmentScheme<E, Polynomial = Rc<DenseMultilinearExtension<E::Fr>>>,
226    {
227        let mut transcript = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::init_transcript();
228        transcript.append_message(b"testing", b"initializing transcript for testing")?;
229
230        let (proof, prod_x) = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::prove(
231            &Rc::new(f.clone()),
232            &Rc::new(g.clone()),
233            &mut transcript,
234            pk,
235        )?;
236
237        let mut transcript = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::init_transcript();
238        transcript.append_message(b"testing", b"initializing transcript for testing")?;
239
240        let subclaim =
241            <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::verify(&proof, f.num_vars, &mut transcript)?;
242        assert_eq!(
243            prod_x.evaluate(&subclaim.final_query.0).unwrap(),
244            subclaim.final_query.1,
245            "different product"
246        );
247
248        // bad path
249        let mut transcript = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::init_transcript();
250        transcript.append_message(b"testing", b"initializing transcript for testing")?;
251
252        let h = f + g;
253        let (bad_proof, prod_x_bad) = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::prove(
254            &Rc::new(f.clone()),
255            &Rc::new(h.clone()),
256            &mut transcript,
257            pk,
258        )?;
259
260        let mut transcript = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::init_transcript();
261        transcript.append_message(b"testing", b"initializing transcript for testing")?;
262        let bad_subclaim = <PolyIOP<E::Fr> as ProductCheck<E, PCS>>::verify(
263            &bad_proof,
264            f.num_vars,
265            &mut transcript,
266        )?;
267        assert_ne!(
268            prod_x_bad.evaluate(&bad_subclaim.final_query.0).unwrap(),
269            bad_subclaim.final_query.1,
270            "can't detect wrong proof"
271        );
272
273        Ok(())
274    }
275
276    fn test_product_check(nv: usize) -> Result<(), PolyIOPErrors> {
277        let mut rng = test_rng();
278
279        let f: DenseMultilinearExtension<Fr> = DenseMultilinearExtension::rand(nv, &mut rng);
280        let mut g = f.clone();
281        g.evaluations.reverse();
282
283        let srs = KZGMultilinearPCS::<Bls12_381>::gen_srs_for_testing(&mut rng, nv + 1)?;
284        let (pk, _) = KZGMultilinearPCS::<Bls12_381>::trim(&srs, nv + 1, Some(nv + 1))?;
285
286        test_product_check_helper::<Bls12_381, KZGMultilinearPCS<Bls12_381>>(&f, &g, &pk)?;
287
288        Ok(())
289    }
290
291    #[test]
292    fn test_trivial_polynomial() -> Result<(), PolyIOPErrors> {
293        test_product_check(1)
294    }
295    #[test]
296    fn test_normal_polynomial() -> Result<(), PolyIOPErrors> {
297        test_product_check(10)
298    }
299}