ark-r1cs-std/src/poly/domain/vanishing_poly.rs
src/poly/domain/vanishing_poly.rsRaw
1use crate::fields::{fp::FpVar, FieldVar};
2use ark_ff::{Field, PrimeField};
3use ark_relations::r1cs::SynthesisError;
4use ark_std::ops::Sub;
5
6/// Struct describing vanishing polynomial for a multiplicative coset H where
7/// |H| is a power of 2. As H is a coset, every element can be described as
8/// h*g^i and therefore has vanishing polynomial Z_H(x) = x^|H| - h^|H|
9#[derive(Clone)]
10pub struct VanishingPolynomial<F: Field> {
11 /// h^|H|
12 pub constant_term: F,
13 /// log_2(|H|)
14 pub dim_h: u64,
15 /// |H|
16 pub order_h: u64,
17}
18
19impl<F: PrimeField> VanishingPolynomial<F> {
20 /// returns a VanishingPolynomial of coset `H = h<g>`.
21 pub fn new(offset: F, dim_h: u64) -> Self {
22 let order_h = 1 << dim_h;
23 let vp = VanishingPolynomial {
24 constant_term: offset.pow([order_h]),
25 dim_h,
26 order_h,
27 };
28 vp
29 }
30
31 /// Evaluates the vanishing polynomial without generating the constraints.
32 pub fn evaluate(&self, x: &F) -> F {
33 let mut result = x.pow([self.order_h]);
34 result -= &self.constant_term;
35 result
36 }
37
38 /// Evaluates the constraints and just gives you the gadget for the result.
39 /// Caution for use in holographic lincheck: The output has 2 entries in one
40 /// 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::{
59 alloc::AllocVar, fields::fp::FpVar, poly::domain::vanishing_poly::VanishingPolynomial,
60 R1CSVar,
61 };
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}