Nova/src/gadgets/utils.rs
src/gadgets/utils.rsRaw
1//! This module implements various low-level gadgets
2use crate::traits::Group;
3use bellperson::{
4 gadgets::{
5 boolean::{AllocatedBit, Boolean},
6 num::AllocatedNum,
7 Assignment,
8 },
9 ConstraintSystem, LinearCombination, SynthesisError,
10};
11use bellperson_nonnative::mp::bignat::{nat_to_limbs, BigNat};
12use ff::{Field, PrimeField, PrimeFieldBits};
13use rug::Integer;
14
15/// Gets as input the little indian representation of a number and spits out the number
16#[allow(dead_code)]
17pub fn le_bits_to_num<Scalar, CS>(
18 mut cs: CS,
19 bits: Vec<AllocatedBit>,
20) -> Result<AllocatedNum<Scalar>, SynthesisError>
21where
22 Scalar: PrimeField + PrimeFieldBits,
23 CS: ConstraintSystem<Scalar>,
24{
25 // We loop over the input bits and construct the constraint
26 // and the field element that corresponds to the result
27 let mut lc = LinearCombination::zero();
28 let mut coeff = Scalar::one();
29 let mut fe = Some(Scalar::zero());
30 for bit in bits.iter() {
31 lc = lc + (coeff, bit.get_variable());
32 fe = bit.get_value().map(|val| {
33 if val {
34 fe.unwrap() + coeff
35 } else {
36 fe.unwrap()
37 }
38 });
39 coeff = coeff.double();
40 }
41 let num = AllocatedNum::alloc(cs.namespace(|| "Field element"), || {
42 fe.ok_or(SynthesisError::AssignmentMissing)
43 })?;
44 lc = lc - num.get_variable();
45 cs.enforce(|| "compute number from bits", |lc| lc, |lc| lc, |_| lc);
46 Ok(num)
47}
48
49/// Allocate a variable that is set to zero
50pub fn alloc_zero<F: PrimeField, CS: ConstraintSystem<F>>(
51 mut cs: CS,
52) -> Result<AllocatedNum<F>, SynthesisError> {
53 let zero = AllocatedNum::alloc(cs.namespace(|| "alloc"), || Ok(F::zero()))?;
54 cs.enforce(
55 || "check zero is valid",
56 |lc| lc,
57 |lc| lc,
58 |lc| lc + zero.get_variable(),
59 );
60 Ok(zero)
61}
62
63/// Allocate a variable that is set to one
64pub fn alloc_one<F: PrimeField, CS: ConstraintSystem<F>>(
65 mut cs: CS,
66) -> Result<AllocatedNum<F>, SynthesisError> {
67 let one = AllocatedNum::alloc(cs.namespace(|| "alloc"), || Ok(F::one()))?;
68 cs.enforce(
69 || "check one is valid",
70 |lc| lc + CS::one(),
71 |lc| lc + CS::one(),
72 |lc| lc + one.get_variable(),
73 );
74
75 Ok(one)
76}
77
78/// Allocate a scalar as a base. Only to be used is the scalar fits in base!
79pub fn alloc_scalar_as_base<G, CS>(
80 mut cs: CS,
81 input: Option<G::Scalar>,
82) -> Result<AllocatedNum<G::Base>, SynthesisError>
83where
84 G: Group,
85 <G as Group>::Scalar: PrimeFieldBits,
86 CS: ConstraintSystem<<G as Group>::Base>,
87{
88 AllocatedNum::alloc(cs.namespace(|| "allocate scalar as base"), || {
89 let input_bits = input.get()?.clone().to_le_bits();
90 let mut mult = G::Base::one();
91 let mut val = G::Base::zero();
92 for bit in input_bits {
93 if bit {
94 val += mult;
95 }
96 mult = mult + mult;
97 }
98 Ok(val)
99 })
100}
101
102/// Allocate bignat a constant
103pub fn alloc_bignat_constant<F: PrimeField, CS: ConstraintSystem<F>>(
104 mut cs: CS,
105 val: &Integer,
106 limb_width: usize,
107 n_limbs: usize,
108) -> Result<BigNat<F>, SynthesisError> {
109 let limbs = nat_to_limbs(val, limb_width, n_limbs).unwrap();
110 let bignat = BigNat::alloc_from_limbs(
111 cs.namespace(|| "alloc bignat"),
112 || Ok(limbs.clone()),
113 None,
114 limb_width,
115 n_limbs,
116 )?;
117 // Now enforce that the limbs are all equal to the constants
118 #[allow(clippy::needless_range_loop)]
119 for i in 0..n_limbs {
120 cs.enforce(
121 || format!("check limb {}", i),
122 |lc| lc + &bignat.limbs[i],
123 |lc| lc + CS::one(),
124 |lc| lc + (limbs[i], CS::one()),
125 );
126 }
127 Ok(bignat)
128}
129
130/// Check that two numbers are equal and return a bit
131pub fn alloc_num_equals<F: PrimeField, CS: ConstraintSystem<F>>(
132 mut cs: CS,
133 a: AllocatedNum<F>,
134 b: AllocatedNum<F>,
135) -> Result<AllocatedBit, SynthesisError> {
136 // Allocate and constrain `r`: result boolean bit.
137 // It equals `true` if `a` equals `b`, `false` otherwise
138 let r_value = match (a.get_value(), b.get_value()) {
139 (Some(a), Some(b)) => Some(a == b),
140 _ => None,
141 };
142
143 let r = AllocatedBit::alloc(cs.namespace(|| "r"), r_value)?;
144
145 let delta = AllocatedNum::alloc(cs.namespace(|| "delta"), || {
146 let a_value = *a.get_value().get()?;
147 let b_value = *b.get_value().get()?;
148
149 let mut delta = a_value;
150 delta.sub_assign(&b_value);
151
152 Ok(delta)
153 })?;
154
155 cs.enforce(
156 || "delta = (a - b)",
157 |lc| lc + a.get_variable() - b.get_variable(),
158 |lc| lc + CS::one(),
159 |lc| lc + delta.get_variable(),
160 );
161
162 let delta_inv = AllocatedNum::alloc(cs.namespace(|| "delta_inv"), || {
163 let delta = *delta.get_value().get()?;
164
165 if delta.is_zero().unwrap_u8() == 1 {
166 Ok(F::one()) // we can return any number here, it doesn't matter
167 } else {
168 Ok(delta.invert().unwrap())
169 }
170 })?;
171
172 // Allocate `t = delta * delta_inv`
173 // If `delta` is non-zero (a != b), `t` will equal 1
174 // If `delta` is zero (a == b), `t` cannot equal 1
175 let t = AllocatedNum::alloc(cs.namespace(|| "t"), || {
176 let mut tmp = *delta.get_value().get()?;
177 tmp.mul_assign(&(*delta_inv.get_value().get()?));
178
179 Ok(tmp)
180 })?;
181
182 // Constrain allocation:
183 // t = (a - b) * delta_inv
184 cs.enforce(
185 || "t = (a - b) * delta_inv",
186 |lc| lc + a.get_variable() - b.get_variable(),
187 |lc| lc + delta_inv.get_variable(),
188 |lc| lc + t.get_variable(),
189 );
190
191 // Constrain:
192 // (a - b) * (t - 1) == 0
193 // This enforces that correct `delta_inv` was provided,
194 // and thus `t` is 1 if `(a - b)` is non zero (a != b )
195 cs.enforce(
196 || "(a - b) * (t - 1) == 0",
197 |lc| lc + a.get_variable() - b.get_variable(),
198 |lc| lc + t.get_variable() - CS::one(),
199 |lc| lc,
200 );
201
202 // Constrain:
203 // (a - b) * r == 0
204 // This enforces that `r` is zero if `(a - b)` is non-zero (a != b)
205 cs.enforce(
206 || "(a - b) * r == 0",
207 |lc| lc + a.get_variable() - b.get_variable(),
208 |lc| lc + r.get_variable(),
209 |lc| lc,
210 );
211
212 // Constrain:
213 // (t - 1) * (r - 1) == 0
214 // This enforces that `r` is one if `t` is not one (a == b)
215 cs.enforce(
216 || "(t - 1) * (r - 1) == 0",
217 |lc| lc + t.get_variable() - CS::one(),
218 |lc| lc + r.get_variable() - CS::one(),
219 |lc| lc,
220 );
221
222 Ok(r)
223}
224
225/// If condition return a otherwise b
226pub fn conditionally_select<F: PrimeField, CS: ConstraintSystem<F>>(
227 mut cs: CS,
228 a: &AllocatedNum<F>,
229 b: &AllocatedNum<F>,
230 condition: &Boolean,
231) -> Result<AllocatedNum<F>, SynthesisError> {
232 let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
233 if *condition.get_value().get()? {
234 Ok(*a.get_value().get()?)
235 } else {
236 Ok(*b.get_value().get()?)
237 }
238 })?;
239
240 // a * condition + b*(1-condition) = c ->
241 // a * condition - b*condition = c - b
242 cs.enforce(
243 || "conditional select constraint",
244 |lc| lc + a.get_variable() - b.get_variable(),
245 |_| condition.lc(CS::one(), F::one()),
246 |lc| lc + c.get_variable() - b.get_variable(),
247 );
248
249 Ok(c)
250}
251
252/// If condition return a otherwise b where a and b are BigNats
253pub fn conditionally_select_bignat<F: PrimeField, CS: ConstraintSystem<F>>(
254 mut cs: CS,
255 a: &BigNat<F>,
256 b: &BigNat<F>,
257 condition: &Boolean,
258) -> Result<BigNat<F>, SynthesisError> {
259 assert!(a.limbs.len() == b.limbs.len());
260 let c = BigNat::alloc_from_nat(
261 cs.namespace(|| "conditional select result"),
262 || {
263 if *condition.get_value().get()? {
264 Ok(a.value.get()?.clone())
265 } else {
266 Ok(b.value.get()?.clone())
267 }
268 },
269 a.params.limb_width,
270 a.params.n_limbs,
271 )?;
272
273 // a * condition + b*(1-condition) = c ->
274 // a * condition - b*condition = c - b
275 for i in 0..c.limbs.len() {
276 cs.enforce(
277 || format!("conditional select constraint {}", i),
278 |lc| lc + &a.limbs[i] - &b.limbs[i],
279 |_| condition.lc(CS::one(), F::one()),
280 |lc| lc + &c.limbs[i] - &b.limbs[i],
281 );
282 }
283 Ok(c)
284}
285
286/// Same as the above but Condition is an AllocatedNum that needs to be
287/// 0 or 1. 1 => True, 0 => False
288pub fn conditionally_select2<F: PrimeField, CS: ConstraintSystem<F>>(
289 mut cs: CS,
290 a: &AllocatedNum<F>,
291 b: &AllocatedNum<F>,
292 condition: &AllocatedNum<F>,
293) -> Result<AllocatedNum<F>, SynthesisError> {
294 let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
295 if *condition.get_value().get()? == F::one() {
296 Ok(*a.get_value().get()?)
297 } else {
298 Ok(*b.get_value().get()?)
299 }
300 })?;
301
302 // a * condition + b*(1-condition) = c ->
303 // a * condition - b*condition = c - b
304 cs.enforce(
305 || "conditional select constraint",
306 |lc| lc + a.get_variable() - b.get_variable(),
307 |lc| lc + condition.get_variable(),
308 |lc| lc + c.get_variable() - b.get_variable(),
309 );
310
311 Ok(c)
312}
313
314/// If condition set to 0 otherwise a
315pub fn select_zero_or<F: PrimeField, CS: ConstraintSystem<F>>(
316 mut cs: CS,
317 a: &AllocatedNum<F>,
318 condition: &AllocatedNum<F>,
319) -> Result<AllocatedNum<F>, SynthesisError> {
320 let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
321 if *condition.get_value().get()? == F::one() {
322 Ok(F::zero())
323 } else {
324 Ok(*a.get_value().get()?)
325 }
326 })?;
327
328 // a * (1 - condition) = c
329 cs.enforce(
330 || "conditional select constraint",
331 |lc| lc + a.get_variable(),
332 |lc| lc + CS::one() - condition.get_variable(),
333 |lc| lc + c.get_variable(),
334 );
335
336 Ok(c)
337}
338
339/// If condition set to 1 otherwise a
340pub fn select_one_or<F: PrimeField, CS: ConstraintSystem<F>>(
341 mut cs: CS,
342 a: &AllocatedNum<F>,
343 condition: &AllocatedNum<F>,
344) -> Result<AllocatedNum<F>, SynthesisError> {
345 let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
346 if *condition.get_value().get()? == F::one() {
347 Ok(F::one())
348 } else {
349 Ok(*a.get_value().get()?)
350 }
351 })?;
352
353 cs.enforce(
354 || "conditional select constraint",
355 |lc| lc + CS::one() - a.get_variable(),
356 |lc| lc + condition.get_variable(),
357 |lc| lc + c.get_variable() - a.get_variable(),
358 );
359 Ok(c)
360}