arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
ark-r1cs-std/src/poly/domain/vanishing_poly.rs
src/poly/domain/vanishing_poly.rsRaw
 1use crate::fields::fp::FpVar;
 2use crate::fields::FieldVar;
 3use ark_ff::{Field, PrimeField};
 4use ark_relations::r1cs::SynthesisError;
 5use ark_std::ops::Sub;
 6
 7/// Struct describing vanishing polynomial for a multiplicative coset H where |H| is a power of 2.
 8/// As H is a coset, every element can be described as h*g^i and therefore
 9/// has vanishing polynomial Z_H(x) = x^|H| - h^|H|
10#[derive(Clone)]
11pub struct VanishingPolynomial<F: Field> {
12    /// h^|H|
13    pub constant_term: F,
14    /// log_2(|H|)
15    pub dim_h: u64,
16    /// |H|
17    pub order_h: u64,
18}
19
20impl<F: PrimeField> VanishingPolynomial<F> {
21    /// returns a VanishingPolynomial of coset `H = h<g>`.
22    pub fn new(offset: F, dim_h: u64) -> Self {
23        let order_h = 1 << dim_h;
24        let vp = VanishingPolynomial {
25            constant_term: offset.pow([order_h]),
26            dim_h,
27            order_h,
28        };
29        vp
30    }
31
32    /// Evaluates the vanishing polynomial without generating the constraints.
33    pub fn evaluate(&self, x: &F) -> F {
34        let mut result = x.pow([self.order_h]);
35        result -= &self.constant_term;
36        result
37    }
38
39    /// Evaluates the constraints and just gives you the gadget for the result.
40    /// Caution for use in holographic lincheck: The output has 2 entries in one matrix
41    pub fn evaluate_constraints(&self, x: &FpVar<F>) -> Result<FpVar<F>, SynthesisError> {
42        if self.dim_h == 1 {
43            let result = x.sub(x);
44            return Ok(result);
45        }
46
47        let mut cur = x.square()?;
48        for _ in 1..self.dim_h {
49            cur.square_in_place()?;
50        }
51        cur -= &FpVar::Constant(self.constant_term);
52        Ok(cur)
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use crate::alloc::AllocVar;
59    use crate::fields::fp::FpVar;
60    use crate::poly::domain::vanishing_poly::VanishingPolynomial;
61    use crate::R1CSVar;
62    use ark_relations::r1cs::ConstraintSystem;
63    use ark_std::{test_rng, UniformRand};
64    use ark_test_curves::bls12_381::Fr;
65
66    #[test]
67    fn constraints_test() {
68        let mut rng = test_rng();
69        let offset = Fr::rand(&mut rng);
70        let cs = ConstraintSystem::new_ref();
71        let x = Fr::rand(&mut rng);
72        let x_var = FpVar::new_witness(ns!(cs, "x_var"), || Ok(x)).unwrap();
73        let vp = VanishingPolynomial::new(offset, 12);
74        let native = vp.evaluate(&x);
75        let result_var = vp.evaluate_constraints(&x_var).unwrap();
76        assert!(cs.is_satisfied().unwrap());
77        assert_eq!(result_var.value().unwrap(), native);
78    }
79}