ysbell/gadgets/
multieq.rs1use ff::{Field, PrimeField, ScalarEngine};
2
3use crate::{ConstraintSystem, LinearCombination, SynthesisError, Variable};
4
5pub struct MultiEq<E: ScalarEngine, CS: ConstraintSystem<E>> {
6 cs: CS,
7 ops: usize,
8 bits_used: usize,
9 lhs: LinearCombination<E>,
10 rhs: LinearCombination<E>,
11}
12
13impl<E: ScalarEngine, CS: ConstraintSystem<E>> MultiEq<E, CS> {
14 pub fn new(cs: CS) -> Self {
15 MultiEq {
16 cs,
17 ops: 0,
18 bits_used: 0,
19 lhs: LinearCombination::zero(),
20 rhs: LinearCombination::zero(),
21 }
22 }
23
24 fn accumulate(&mut self) {
25 let ops = self.ops;
26 let lhs = self.lhs.clone();
27 let rhs = self.rhs.clone();
28 self.cs.enforce(
29 || format!("multieq {}", ops),
30 |_| lhs,
31 |lc| lc + CS::one(),
32 |_| rhs,
33 );
34 self.lhs = LinearCombination::zero();
35 self.rhs = LinearCombination::zero();
36 self.bits_used = 0;
37 self.ops += 1;
38 }
39
40 pub fn enforce_equal(
41 &mut self,
42 num_bits: usize,
43 lhs: &LinearCombination<E>,
44 rhs: &LinearCombination<E>,
45 ) {
46 if (E::Fr::CAPACITY as usize) <= (self.bits_used + num_bits) {
48 self.accumulate();
49 }
50
51 assert!((E::Fr::CAPACITY as usize) > (self.bits_used + num_bits));
52
53 let coeff = E::Fr::from_str("2").unwrap().pow(&[self.bits_used as u64]);
54 self.lhs = self.lhs.clone() + (coeff, lhs);
55 self.rhs = self.rhs.clone() + (coeff, rhs);
56 self.bits_used += num_bits;
57 }
58}
59
60impl<E: ScalarEngine, CS: ConstraintSystem<E>> Drop for MultiEq<E, CS> {
61 fn drop(&mut self) {
62 if self.bits_used > 0 {
63 self.accumulate();
64 }
65 }
66}
67
68impl<E: ScalarEngine, CS: ConstraintSystem<E>> ConstraintSystem<E> for MultiEq<E, CS> {
69 type Root = Self;
70
71 fn one() -> Variable {
72 CS::one()
73 }
74
75 fn alloc<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
76 where
77 F: FnOnce() -> Result<E::Fr, SynthesisError>,
78 A: FnOnce() -> AR,
79 AR: Into<String>,
80 {
81 self.cs.alloc(annotation, f)
82 }
83
84 fn alloc_input<F, A, AR>(&mut self, annotation: A, f: F) -> Result<Variable, SynthesisError>
85 where
86 F: FnOnce() -> Result<E::Fr, SynthesisError>,
87 A: FnOnce() -> AR,
88 AR: Into<String>,
89 {
90 self.cs.alloc_input(annotation, f)
91 }
92
93 fn enforce<A, AR, LA, LB, LC>(&mut self, annotation: A, a: LA, b: LB, c: LC)
94 where
95 A: FnOnce() -> AR,
96 AR: Into<String>,
97 LA: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
98 LB: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
99 LC: FnOnce(LinearCombination<E>) -> LinearCombination<E>,
100 {
101 self.cs.enforce(annotation, a, b, c)
102 }
103
104 fn push_namespace<NR, N>(&mut self, name_fn: N)
105 where
106 NR: Into<String>,
107 N: FnOnce() -> NR,
108 {
109 self.cs.get_root().push_namespace(name_fn)
110 }
111
112 fn pop_namespace(&mut self) {
113 self.cs.get_root().pop_namespace()
114 }
115
116 fn get_root(&mut self) -> &mut Self::Root {
117 self
118 }
119}