arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
ark-r1cs-std/r1cs-std/src/bits/uint.rs
r1cs-std/src/bits/uint.rsRaw
  1macro_rules! make_uint {
  2    ($name:ident, $size:expr, $native:ident, $mod_name:ident, $native_doc_name:expr) => {
  3        #[doc = "This module contains a `UInt"]
  4        #[doc = $native_doc_name]
  5        #[doc = "`, a R1CS equivalent of the `u"]
  6        #[doc = $native_doc_name]
  7        #[doc = "`type."]
  8        pub mod $mod_name {
  9            use algebra::{Field, FpParameters, PrimeField};
 10            use core::borrow::Borrow;
 11            use core::convert::TryFrom;
 12
 13            use r1cs_core::{
 14                lc, ConstraintSystemRef, LinearCombination, Namespace, SynthesisError, Variable,
 15            };
 16
 17            use crate::{
 18                boolean::{AllocatedBit, Boolean},
 19                prelude::*,
 20                Assignment, Vec,
 21            };
 22
 23            #[doc = "This struct represent an unsigned"]
 24            #[doc = $native_doc_name]
 25            #[doc = "-bit integer as a sequence of "]
 26            #[doc = $native_doc_name]
 27            #[doc = " `Boolean`s\n"]
 28            #[doc = "This is the R1CS equivalent of the native `u"]
 29            #[doc = $native_doc_name]
 30            #[doc = "` unsigned integer type."]
 31            #[derive(Clone, Debug)]
 32            pub struct $name<F: Field> {
 33                // Least significant bit first
 34                bits: Vec<Boolean<F>>,
 35                value: Option<$native>,
 36            }
 37
 38            impl<F: Field> R1CSVar<F> for $name<F> {
 39                type Value = $native;
 40
 41                fn cs(&self) -> Option<ConstraintSystemRef<F>> {
 42                    self.bits.as_slice().cs()
 43                }
 44
 45                fn value(&self) -> Result<Self::Value, SynthesisError> {
 46                    let mut value = None;
 47                    for (i, bit) in self.bits.iter().enumerate() {
 48                        let b = $native::from(bit.value()?);
 49                        value = match value {
 50                            Some(value) => Some(value + (b << i)),
 51                            None => Some(b << i),
 52                        };
 53                    }
 54                    debug_assert_eq!(self.value, value);
 55                    value.get()
 56                }
 57            }
 58
 59            impl<F: Field> $name<F> {
 60                #[doc = "Construct a constant `UInt"]
 61                #[doc = $native_doc_name]
 62                #[doc = "` from the native `u"]
 63                #[doc = $native_doc_name]
 64                #[doc = "` type."]
 65                pub fn constant(value: $native) -> Self {
 66                    let mut bits = Vec::with_capacity($size);
 67
 68                    let mut tmp = value;
 69                    for _ in 0..$size {
 70                        if tmp & 1 == 1 {
 71                            bits.push(Boolean::constant(true))
 72                        } else {
 73                            bits.push(Boolean::constant(false))
 74                        }
 75
 76                        tmp >>= 1;
 77                    }
 78
 79                    $name {
 80                        bits,
 81                        value: Some(value),
 82                    }
 83                }
 84
 85                /// Turns `self` into the underlying little-endian bits.
 86                pub fn to_bits_le(&self) -> Vec<Boolean<F>> {
 87                    self.bits.clone()
 88                }
 89
 90                /// Construct `Self` from a slice of `Boolean`s.
 91                ///
 92                /// # Panics
 93                ///
 94                /// This method panics if `bits.len() != u
 95                #[doc($native_doc_name)]
 96                #[doc("`.")]
 97                pub fn from_bits_le(bits: &[Boolean<F>]) -> Self {
 98                    assert_eq!(bits.len(), $size);
 99
100                    let bits = bits.to_vec();
101
102                    let mut value = Some(0);
103                    for b in bits.iter().rev() {
104                        value.as_mut().map(|v| *v <<= 1);
105
106                        match b {
107                            &Boolean::Constant(b) => {
108                                value.as_mut().map(|v| *v |= $native::from(b));
109                            }
110                            &Boolean::Is(ref b) => match b.value() {
111                                Ok(b) => {
112                                    value.as_mut().map(|v| *v |= $native::from(b));
113                                }
114                                Err(_) => value = None,
115                            },
116                            &Boolean::Not(ref b) => match b.value() {
117                                Ok(b) => {
118                                    value.as_mut().map(|v| *v |= $native::from(!b));
119                                }
120                                Err(_) => value = None,
121                            },
122                        }
123                    }
124
125                    Self { value, bits }
126                }
127
128                /// Rotates `self` to the right by `by` steps, wrapping around.
129                #[tracing::instrument(target = "r1cs", skip(self))]
130                pub fn rotr(&self, by: usize) -> Self {
131                    let by = by % $size;
132
133                    let new_bits = self
134                        .bits
135                        .iter()
136                        .skip(by)
137                        .chain(self.bits.iter())
138                        .take($size)
139                        .cloned()
140                        .collect();
141
142                    $name {
143                        bits: new_bits,
144                        value: self
145                            .value
146                            .map(|v| v.rotate_right(u32::try_from(by).unwrap())),
147                    }
148                }
149
150                /// Outputs `self ^ other`.
151                ///
152                /// If at least one of `self` and `other` are constants, then this method
153                /// *does not* create any constraints or variables.
154                #[tracing::instrument(target = "r1cs", skip(self, other))]
155                pub fn xor(&self, other: &Self) -> Result<Self, SynthesisError> {
156                    let new_value = match (self.value, other.value) {
157                        (Some(a), Some(b)) => Some(a ^ b),
158                        _ => None,
159                    };
160
161                    let bits = self
162                        .bits
163                        .iter()
164                        .zip(other.bits.iter())
165                        .map(|(a, b)| a.xor(b))
166                        .collect::<Result<_, _>>()?;
167
168                    Ok($name {
169                        bits,
170                        value: new_value,
171                    })
172                }
173
174                /// Perform modular addition of `operands`.
175                ///
176                /// The user must ensure that overflow does not occur.
177                #[tracing::instrument(target = "r1cs", skip(operands))]
178                pub fn addmany(operands: &[Self]) -> Result<Self, SynthesisError>
179                where
180                    F: PrimeField,
181                {
182                    // Make some arbitrary bounds for ourselves to avoid overflows
183                    // in the scalar field
184                    assert!(F::Params::MODULUS_BITS >= 2 * $size);
185
186                    assert!(operands.len() >= 1);
187                    assert!($size * operands.len() <= F::Params::MODULUS_BITS as usize);
188
189                    if operands.len() == 1 {
190                        return Ok(operands[0].clone());
191                    }
192
193                    // Compute the maximum value of the sum so we allocate enough bits for
194                    // the result
195                    let mut max_value = (operands.len() as u128) * u128::from($native::max_value());
196
197                    // Keep track of the resulting value
198                    let mut result_value = Some(0u128);
199
200                    // This is a linear combination that we will enforce to be "zero"
201                    let mut lc = LinearCombination::zero();
202
203                    let mut all_constants = true;
204
205                    // Iterate over the operands
206                    for op in operands {
207                        // Accumulate the value
208                        match op.value {
209                            Some(val) => {
210                                result_value.as_mut().map(|v| *v += u128::from(val));
211                            }
212
213                            None => {
214                                // If any of our operands have unknown value, we won't
215                                // know the value of the result
216                                result_value = None;
217                            }
218                        }
219
220                        // Iterate over each bit_gadget of the operand and add the operand to
221                        // the linear combination
222                        let mut coeff = F::one();
223                        for bit in &op.bits {
224                            match *bit {
225                                Boolean::Is(ref bit) => {
226                                    all_constants = false;
227
228                                    // Add coeff * bit_gadget
229                                    lc += (coeff, bit.variable());
230                                }
231                                Boolean::Not(ref bit) => {
232                                    all_constants = false;
233
234                                    // Add coeff * (1 - bit_gadget) = coeff * ONE - coeff * bit_gadget
235                                    lc = lc + (coeff, Variable::One) - (coeff, bit.variable());
236                                }
237                                Boolean::Constant(bit) => {
238                                    if bit {
239                                        lc += (coeff, Variable::One);
240                                    }
241                                }
242                            }
243
244                            coeff.double_in_place();
245                        }
246                    }
247
248                    // The value of the actual result is modulo 2^$size
249                    let modular_value = result_value.map(|v| v as $native);
250
251                    if all_constants && modular_value.is_some() {
252                        // We can just return a constant, rather than
253                        // unpacking the result into allocated bits.
254
255                        return Ok($name::constant(modular_value.unwrap()));
256                    }
257                    let cs = operands.cs().unwrap();
258
259                    // Storage area for the resulting bits
260                    let mut result_bits = vec![];
261
262                    // Allocate each bit_gadget of the result
263                    let mut coeff = F::one();
264                    let mut i = 0;
265                    while max_value != 0 {
266                        // Allocate the bit_gadget
267                        let b = AllocatedBit::new_witness(cs.clone(), || {
268                            result_value.map(|v| (v >> i) & 1 == 1).get()
269                        })?;
270
271                        // Subtract this bit_gadget from the linear combination to ensure the sums
272                        // balance out
273                        lc = lc - (coeff, b.variable());
274
275                        result_bits.push(b.into());
276
277                        max_value >>= 1;
278                        i += 1;
279                        coeff.double_in_place();
280                    }
281
282                    // Enforce that the linear combination equals zero
283                    cs.enforce_constraint(lc!(), lc!(), lc)?;
284
285                    // Discard carry bits that we don't care about
286                    result_bits.truncate($size);
287
288                    Ok($name {
289                        bits: result_bits,
290                        value: modular_value,
291                    })
292                }
293            }
294
295            impl<ConstraintF: Field> ToBytesGadget<ConstraintF> for $name<ConstraintF> {
296                #[tracing::instrument(target = "r1cs", skip(self))]
297                fn to_bytes(&self) -> Result<Vec<UInt8<ConstraintF>>, SynthesisError> {
298                    Ok(self
299                        .to_bits_le()
300                        .chunks(8)
301                        .map(UInt8::from_bits_le)
302                        .collect())
303                }
304            }
305
306            impl<ConstraintF: Field> EqGadget<ConstraintF> for $name<ConstraintF> {
307                #[tracing::instrument(target = "r1cs", skip(self))]
308                fn is_eq(&self, other: &Self) -> Result<Boolean<ConstraintF>, SynthesisError> {
309                    self.bits.as_slice().is_eq(&other.bits)
310                }
311
312                #[tracing::instrument(target = "r1cs", skip(self))]
313                fn conditional_enforce_equal(
314                    &self,
315                    other: &Self,
316                    condition: &Boolean<ConstraintF>,
317                ) -> Result<(), SynthesisError> {
318                    self.bits.conditional_enforce_equal(&other.bits, condition)
319                }
320
321                #[tracing::instrument(target = "r1cs", skip(self))]
322                fn conditional_enforce_not_equal(
323                    &self,
324                    other: &Self,
325                    condition: &Boolean<ConstraintF>,
326                ) -> Result<(), SynthesisError> {
327                    self.bits
328                        .conditional_enforce_not_equal(&other.bits, condition)
329                }
330            }
331
332            impl<ConstraintF: Field> AllocVar<$native, ConstraintF> for $name<ConstraintF> {
333                fn new_variable<T: Borrow<$native>>(
334                    cs: impl Into<Namespace<ConstraintF>>,
335                    f: impl FnOnce() -> Result<T, SynthesisError>,
336                    mode: AllocationMode,
337                ) -> Result<Self, SynthesisError> {
338                    let ns = cs.into();
339                    let cs = ns.cs();
340                    let value = f().map(|f| *f.borrow());
341                    let values = match value {
342                        Ok(val) => (0..$size).map(|i| Some((val >> i) & 1 == 1)).collect(),
343                        _ => vec![None; $size],
344                    };
345                    let bits = values
346                        .into_iter()
347                        .map(|v| Boolean::new_variable(cs.clone(), || v.get(), mode))
348                        .collect::<Result<Vec<_>, _>>()?;
349                    Ok(Self {
350                        bits,
351                        value: value.ok(),
352                    })
353                }
354            }
355
356            #[cfg(test)]
357            mod test {
358                use super::$name;
359                use crate::{bits::boolean::Boolean, prelude::*, Vec};
360                use algebra::bls12_381::Fr;
361                use r1cs_core::{ConstraintSystem, SynthesisError};
362                use rand::{Rng, SeedableRng};
363                use rand_xorshift::XorShiftRng;
364
365                #[test]
366                fn test_from_bits() -> Result<(), SynthesisError> {
367                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
368
369                    for _ in 0..1000 {
370                        let v = (0..$size)
371                            .map(|_| Boolean::constant(rng.gen()))
372                            .collect::<Vec<Boolean<Fr>>>();
373
374                        let b = $name::from_bits_le(&v);
375
376                        for (i, bit) in b.bits.iter().enumerate() {
377                            match bit {
378                                &Boolean::Constant(bit) => {
379                                    assert_eq!(bit, ((b.value()? >> i) & 1 == 1));
380                                }
381                                _ => unreachable!(),
382                            }
383                        }
384
385                        let expected_to_be_same = b.to_bits_le();
386
387                        for x in v.iter().zip(expected_to_be_same.iter()) {
388                            match x {
389                                (&Boolean::Constant(true), &Boolean::Constant(true)) => {}
390                                (&Boolean::Constant(false), &Boolean::Constant(false)) => {}
391                                _ => unreachable!(),
392                            }
393                        }
394                    }
395                    Ok(())
396                }
397
398                #[test]
399                fn test_xor() -> Result<(), SynthesisError> {
400                    use Boolean::*;
401                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
402
403                    for _ in 0..1000 {
404                        let cs = ConstraintSystem::<Fr>::new_ref();
405
406                        let a: $native = rng.gen();
407                        let b: $native = rng.gen();
408                        let c: $native = rng.gen();
409
410                        let mut expected = a ^ b ^ c;
411
412                        let a_bit = $name::new_witness(cs.clone(), || Ok(a))?;
413                        let b_bit = $name::constant(b);
414                        let c_bit = $name::new_witness(cs.clone(), || Ok(c))?;
415
416                        let r = a_bit.xor(&b_bit).unwrap();
417                        let r = r.xor(&c_bit).unwrap();
418
419                        assert!(cs.is_satisfied().unwrap());
420
421                        assert!(r.value == Some(expected));
422
423                        for b in r.bits.iter() {
424                            match b {
425                                Is(b) => assert_eq!(b.value()?, (expected & 1 == 1)),
426                                Not(b) => assert_eq!(!b.value()?, (expected & 1 == 1)),
427                                Constant(b) => assert_eq!(*b, (expected & 1 == 1)),
428                            }
429
430                            expected >>= 1;
431                        }
432                    }
433                    Ok(())
434                }
435
436                #[test]
437                fn test_addmany_constants() -> Result<(), SynthesisError> {
438                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
439
440                    for _ in 0..1000 {
441                        let cs = ConstraintSystem::<Fr>::new_ref();
442
443                        let a: $native = rng.gen();
444                        let b: $native = rng.gen();
445                        let c: $native = rng.gen();
446
447                        let a_bit = $name::new_constant(cs.clone(), a)?;
448                        let b_bit = $name::new_constant(cs.clone(), b)?;
449                        let c_bit = $name::new_constant(cs.clone(), c)?;
450
451                        let mut expected = a.wrapping_add(b).wrapping_add(c);
452
453                        let r = $name::addmany(&[a_bit, b_bit, c_bit]).unwrap();
454
455                        assert!(r.value == Some(expected));
456
457                        for b in r.bits.iter() {
458                            match b {
459                                Boolean::Is(_) => unreachable!(),
460                                Boolean::Not(_) => unreachable!(),
461                                Boolean::Constant(b) => assert_eq!(*b, (expected & 1 == 1)),
462                            }
463
464                            expected >>= 1;
465                        }
466                    }
467                    Ok(())
468                }
469
470                #[test]
471                fn test_addmany() -> Result<(), SynthesisError> {
472                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
473
474                    for _ in 0..1000 {
475                        let cs = ConstraintSystem::<Fr>::new_ref();
476
477                        let a: $native = rng.gen();
478                        let b: $native = rng.gen();
479                        let c: $native = rng.gen();
480                        let d: $native = rng.gen();
481
482                        let mut expected = (a ^ b).wrapping_add(c).wrapping_add(d);
483
484                        let a_bit = $name::new_witness(r1cs_core::ns!(cs, "a_bit"), || Ok(a))?;
485                        let b_bit = $name::constant(b);
486                        let c_bit = $name::constant(c);
487                        let d_bit = $name::new_witness(r1cs_core::ns!(cs, "d_bit"), || Ok(d))?;
488
489                        let r = a_bit.xor(&b_bit).unwrap();
490                        let r = $name::addmany(&[r, c_bit, d_bit]).unwrap();
491
492                        assert!(cs.is_satisfied().unwrap());
493
494                        assert!(r.value == Some(expected));
495
496                        for b in r.bits.iter() {
497                            match b {
498                                Boolean::Is(b) => assert_eq!(b.value()?, (expected & 1 == 1)),
499                                Boolean::Not(b) => assert_eq!(!b.value()?, (expected & 1 == 1)),
500                                Boolean::Constant(_) => unreachable!(),
501                            }
502
503                            expected >>= 1;
504                        }
505                    }
506                    Ok(())
507                }
508
509                #[test]
510                fn test_rotr() -> Result<(), SynthesisError> {
511                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
512
513                    let mut num = rng.gen();
514
515                    let a: $name<Fr> = $name::constant(num);
516
517                    for i in 0..$size {
518                        let b = a.rotr(i);
519
520                        assert!(b.value.unwrap() == num);
521
522                        let mut tmp = num;
523                        for b in &b.bits {
524                            match b {
525                                Boolean::Constant(b) => assert_eq!(*b, tmp & 1 == 1),
526                                _ => unreachable!(),
527                            }
528
529                            tmp >>= 1;
530                        }
531
532                        num = num.rotate_right(1);
533                    }
534                    Ok(())
535                }
536            }
537        }
538    };
539}