arnaucube
arnaucube/NovaPublic Self-hosted repository
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 num_bigint::BigInt;
 14
 15/// Gets as input the little indian representation of a number and spits out the number
 16pub fn le_bits_to_num<Scalar, CS>(
 17  mut cs: CS,
 18  bits: Vec<AllocatedBit>,
 19) -> Result<AllocatedNum<Scalar>, SynthesisError>
 20where
 21  Scalar: PrimeField + PrimeFieldBits,
 22  CS: ConstraintSystem<Scalar>,
 23{
 24  // We loop over the input bits and construct the constraint
 25  // and the field element that corresponds to the result
 26  let mut lc = LinearCombination::zero();
 27  let mut coeff = Scalar::one();
 28  let mut fe = Some(Scalar::zero());
 29  for bit in bits.iter() {
 30    lc = lc + (coeff, bit.get_variable());
 31    fe = bit.get_value().map(|val| {
 32      if val {
 33        fe.unwrap() + coeff
 34      } else {
 35        fe.unwrap()
 36      }
 37    });
 38    coeff = coeff.double();
 39  }
 40  let num = AllocatedNum::alloc(cs.namespace(|| "Field element"), || {
 41    fe.ok_or(SynthesisError::AssignmentMissing)
 42  })?;
 43  lc = lc - num.get_variable();
 44  cs.enforce(|| "compute number from bits", |lc| lc, |lc| lc, |_| lc);
 45  Ok(num)
 46}
 47
 48/// Allocate a variable that is set to zero
 49pub fn alloc_zero<F: PrimeField, CS: ConstraintSystem<F>>(
 50  mut cs: CS,
 51) -> Result<AllocatedNum<F>, SynthesisError> {
 52  let zero = AllocatedNum::alloc(cs.namespace(|| "alloc"), || Ok(F::zero()))?;
 53  cs.enforce(
 54    || "check zero is valid",
 55    |lc| lc,
 56    |lc| lc,
 57    |lc| lc + zero.get_variable(),
 58  );
 59  Ok(zero)
 60}
 61
 62/// Allocate a variable that is set to one
 63pub fn alloc_one<F: PrimeField, CS: ConstraintSystem<F>>(
 64  mut cs: CS,
 65) -> Result<AllocatedNum<F>, SynthesisError> {
 66  let one = AllocatedNum::alloc(cs.namespace(|| "alloc"), || Ok(F::one()))?;
 67  cs.enforce(
 68    || "check one is valid",
 69    |lc| lc + CS::one(),
 70    |lc| lc + CS::one(),
 71    |lc| lc + one.get_variable(),
 72  );
 73
 74  Ok(one)
 75}
 76
 77/// Allocate a scalar as a base. Only to be used is the scalar fits in base!
 78pub fn alloc_scalar_as_base<G, CS>(
 79  mut cs: CS,
 80  input: Option<G::Scalar>,
 81) -> Result<AllocatedNum<G::Base>, SynthesisError>
 82where
 83  G: Group,
 84  <G as Group>::Scalar: PrimeFieldBits,
 85  CS: ConstraintSystem<<G as Group>::Base>,
 86{
 87  AllocatedNum::alloc(cs.namespace(|| "allocate scalar as base"), || {
 88    let input_bits = input.unwrap_or_else(G::Scalar::zero).clone().to_le_bits();
 89    let mut mult = G::Base::one();
 90    let mut val = G::Base::zero();
 91    for bit in input_bits {
 92      if bit {
 93        val += mult;
 94      }
 95      mult = mult + mult;
 96    }
 97    Ok(val)
 98  })
 99}
100
101/// interepret scalar as base
102pub fn scalar_as_base<G: Group>(input: G::Scalar) -> G::Base {
103  let input_bits = input.to_le_bits();
104  let mut mult = G::Base::one();
105  let mut val = G::Base::zero();
106  for bit in input_bits {
107    if bit {
108      val += mult;
109    }
110    mult = mult + mult;
111  }
112  val
113}
114
115/// Allocate bignat a constant
116pub fn alloc_bignat_constant<F: PrimeField, CS: ConstraintSystem<F>>(
117  mut cs: CS,
118  val: &BigInt,
119  limb_width: usize,
120  n_limbs: usize,
121) -> Result<BigNat<F>, SynthesisError> {
122  let limbs = nat_to_limbs(val, limb_width, n_limbs).unwrap();
123  let bignat = BigNat::alloc_from_limbs(
124    cs.namespace(|| "alloc bignat"),
125    || Ok(limbs.clone()),
126    None,
127    limb_width,
128    n_limbs,
129  )?;
130  // Now enforce that the limbs are all equal to the constants
131  #[allow(clippy::needless_range_loop)]
132  for i in 0..n_limbs {
133    cs.enforce(
134      || format!("check limb {}", i),
135      |lc| lc + &bignat.limbs[i],
136      |lc| lc + CS::one(),
137      |lc| lc + (limbs[i], CS::one()),
138    );
139  }
140  Ok(bignat)
141}
142
143/// Check that two numbers are equal and return a bit
144pub fn alloc_num_equals<F: PrimeField, CS: ConstraintSystem<F>>(
145  mut cs: CS,
146  a: &AllocatedNum<F>,
147  b: &AllocatedNum<F>,
148) -> Result<AllocatedBit, SynthesisError> {
149  // Allocate and constrain `r`: result boolean bit.
150  // It equals `true` if `a` equals `b`, `false` otherwise
151  let r_value = match (a.get_value(), b.get_value()) {
152    (Some(a), Some(b)) => Some(a == b),
153    _ => None,
154  };
155
156  let r = AllocatedBit::alloc(cs.namespace(|| "r"), r_value)?;
157
158  // Allocate t s.t. t=1 if z1 == z2 else 1/(z1 - z2)
159
160  let t = AllocatedNum::alloc(cs.namespace(|| "t"), || {
161    Ok(if *a.get_value().get()? == *b.get_value().get()? {
162      F::one()
163    } else {
164      (*a.get_value().get()? - *b.get_value().get()?)
165        .invert()
166        .unwrap()
167    })
168  })?;
169
170  cs.enforce(
171    || "t*(a - b) = 1 - r",
172    |lc| lc + t.get_variable(),
173    |lc| lc + a.get_variable() - b.get_variable(),
174    |lc| lc + CS::one() - r.get_variable(),
175  );
176
177  cs.enforce(
178    || "r*(a - b) = 0",
179    |lc| lc + r.get_variable(),
180    |lc| lc + a.get_variable() - b.get_variable(),
181    |lc| lc,
182  );
183
184  Ok(r)
185}
186
187/// If condition return a otherwise b
188pub fn conditionally_select<F: PrimeField, CS: ConstraintSystem<F>>(
189  mut cs: CS,
190  a: &AllocatedNum<F>,
191  b: &AllocatedNum<F>,
192  condition: &Boolean,
193) -> Result<AllocatedNum<F>, SynthesisError> {
194  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
195    if *condition.get_value().get()? {
196      Ok(*a.get_value().get()?)
197    } else {
198      Ok(*b.get_value().get()?)
199    }
200  })?;
201
202  // a * condition + b*(1-condition) = c ->
203  // a * condition - b*condition = c - b
204  cs.enforce(
205    || "conditional select constraint",
206    |lc| lc + a.get_variable() - b.get_variable(),
207    |_| condition.lc(CS::one(), F::one()),
208    |lc| lc + c.get_variable() - b.get_variable(),
209  );
210
211  Ok(c)
212}
213
214/// If condition return a otherwise b where a and b are BigNats
215pub fn conditionally_select_bignat<F: PrimeField, CS: ConstraintSystem<F>>(
216  mut cs: CS,
217  a: &BigNat<F>,
218  b: &BigNat<F>,
219  condition: &Boolean,
220) -> Result<BigNat<F>, SynthesisError> {
221  assert!(a.limbs.len() == b.limbs.len());
222  let c = BigNat::alloc_from_nat(
223    cs.namespace(|| "conditional select result"),
224    || {
225      if *condition.get_value().get()? {
226        Ok(a.value.get()?.clone())
227      } else {
228        Ok(b.value.get()?.clone())
229      }
230    },
231    a.params.limb_width,
232    a.params.n_limbs,
233  )?;
234
235  // a * condition + b*(1-condition) = c ->
236  // a * condition - b*condition = c - b
237  for i in 0..c.limbs.len() {
238    cs.enforce(
239      || format!("conditional select constraint {}", i),
240      |lc| lc + &a.limbs[i] - &b.limbs[i],
241      |_| condition.lc(CS::one(), F::one()),
242      |lc| lc + &c.limbs[i] - &b.limbs[i],
243    );
244  }
245  Ok(c)
246}
247
248/// Same as the above but Condition is an AllocatedNum that needs to be
249/// 0 or 1. 1 => True, 0 => False
250pub fn conditionally_select2<F: PrimeField, CS: ConstraintSystem<F>>(
251  mut cs: CS,
252  a: &AllocatedNum<F>,
253  b: &AllocatedNum<F>,
254  condition: &AllocatedNum<F>,
255) -> Result<AllocatedNum<F>, SynthesisError> {
256  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
257    if *condition.get_value().get()? == F::one() {
258      Ok(*a.get_value().get()?)
259    } else {
260      Ok(*b.get_value().get()?)
261    }
262  })?;
263
264  // a * condition + b*(1-condition) = c ->
265  // a * condition - b*condition = c - b
266  cs.enforce(
267    || "conditional select constraint",
268    |lc| lc + a.get_variable() - b.get_variable(),
269    |lc| lc + condition.get_variable(),
270    |lc| lc + c.get_variable() - b.get_variable(),
271  );
272
273  Ok(c)
274}
275
276/// If condition set to 0 otherwise a. Condition is an allocated num
277pub fn select_zero_or_num2<F: PrimeField, CS: ConstraintSystem<F>>(
278  mut cs: CS,
279  a: &AllocatedNum<F>,
280  condition: &AllocatedNum<F>,
281) -> Result<AllocatedNum<F>, SynthesisError> {
282  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
283    if *condition.get_value().get()? == F::one() {
284      Ok(F::zero())
285    } else {
286      Ok(*a.get_value().get()?)
287    }
288  })?;
289
290  // a * (1 - condition) = c
291  cs.enforce(
292    || "conditional select constraint",
293    |lc| lc + a.get_variable(),
294    |lc| lc + CS::one() - condition.get_variable(),
295    |lc| lc + c.get_variable(),
296  );
297
298  Ok(c)
299}
300
301/// If condition set to a otherwise 0. Condition is an allocated num
302pub fn select_num_or_zero2<F: PrimeField, CS: ConstraintSystem<F>>(
303  mut cs: CS,
304  a: &AllocatedNum<F>,
305  condition: &AllocatedNum<F>,
306) -> Result<AllocatedNum<F>, SynthesisError> {
307  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
308    if *condition.get_value().get()? == F::one() {
309      Ok(*a.get_value().get()?)
310    } else {
311      Ok(F::zero())
312    }
313  })?;
314
315  cs.enforce(
316    || "conditional select constraint",
317    |lc| lc + a.get_variable(),
318    |lc| lc + condition.get_variable(),
319    |lc| lc + c.get_variable(),
320  );
321
322  Ok(c)
323}
324
325/// If condition set to a otherwise 0
326pub fn select_num_or_zero<F: PrimeField, CS: ConstraintSystem<F>>(
327  mut cs: CS,
328  a: &AllocatedNum<F>,
329  condition: &Boolean,
330) -> Result<AllocatedNum<F>, SynthesisError> {
331  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
332    if *condition.get_value().get()? {
333      Ok(*a.get_value().get()?)
334    } else {
335      Ok(F::zero())
336    }
337  })?;
338
339  cs.enforce(
340    || "conditional select constraint",
341    |lc| lc + a.get_variable(),
342    |_| condition.lc(CS::one(), F::one()),
343    |lc| lc + c.get_variable(),
344  );
345
346  Ok(c)
347}
348
349/// If condition set to 1 otherwise a
350pub fn select_one_or_num2<F: PrimeField, CS: ConstraintSystem<F>>(
351  mut cs: CS,
352  a: &AllocatedNum<F>,
353  condition: &AllocatedNum<F>,
354) -> Result<AllocatedNum<F>, SynthesisError> {
355  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
356    if *condition.get_value().get()? == F::one() {
357      Ok(F::one())
358    } else {
359      Ok(*a.get_value().get()?)
360    }
361  })?;
362
363  cs.enforce(
364    || "conditional select constraint",
365    |lc| lc + CS::one() - a.get_variable(),
366    |lc| lc + condition.get_variable(),
367    |lc| lc + c.get_variable() - a.get_variable(),
368  );
369  Ok(c)
370}
371
372/// If condition set to 1 otherwise a - b
373pub fn select_one_or_diff2<F: PrimeField, CS: ConstraintSystem<F>>(
374  mut cs: CS,
375  a: &AllocatedNum<F>,
376  b: &AllocatedNum<F>,
377  condition: &AllocatedNum<F>,
378) -> Result<AllocatedNum<F>, SynthesisError> {
379  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
380    if *condition.get_value().get()? == F::one() {
381      Ok(F::one())
382    } else {
383      Ok(*a.get_value().get()? - *b.get_value().get()?)
384    }
385  })?;
386
387  cs.enforce(
388    || "conditional select constraint",
389    |lc| lc + CS::one() - a.get_variable() + b.get_variable(),
390    |lc| lc + condition.get_variable(),
391    |lc| lc + c.get_variable() - a.get_variable() + b.get_variable(),
392  );
393  Ok(c)
394}
395
396/// If condition set to a otherwise 1 for boolean conditions
397pub fn select_num_or_one<F: PrimeField, CS: ConstraintSystem<F>>(
398  mut cs: CS,
399  a: &AllocatedNum<F>,
400  condition: &Boolean,
401) -> Result<AllocatedNum<F>, SynthesisError> {
402  let c = AllocatedNum::alloc(cs.namespace(|| "conditional select result"), || {
403    if *condition.get_value().get()? {
404      Ok(*a.get_value().get()?)
405    } else {
406      Ok(F::one())
407    }
408  })?;
409
410  cs.enforce(
411    || "conditional select constraint",
412    |lc| lc + a.get_variable() - CS::one(),
413    |_| condition.lc(CS::one(), F::one()),
414    |lc| lc + c.get_variable() - CS::one(),
415  );
416
417  Ok(c)
418}