arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
ark-r1cs-std/src/bits/uint.rs
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 ark_ff::{Field, FpParameters, PrimeField};
 10            use core::borrow::Borrow;
 11            use core::convert::TryFrom;
 12
 13            use ark_relations::r1cs::{
 14                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) -> 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();
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> CondSelectGadget<ConstraintF> for $name<ConstraintF> {
333                #[tracing::instrument(target = "r1cs", skip(cond, true_value, false_value))]
334                fn conditionally_select(
335                    cond: &Boolean<ConstraintF>,
336                    true_value: &Self,
337                    false_value: &Self,
338                ) -> Result<Self, SynthesisError> {
339                    let selected_bits = true_value
340                    	.bits
341                    	.iter()
342                    	.zip(&false_value.bits)
343                        .map(|(t, f)| cond.select(t, f))
344                        .collect::<Result<Vec<_>, SynthesisError>>()?;
345                    let selected_value = cond.value().ok().and_then(|cond| {
346                    	if cond {
347                    		true_value.value().ok()
348                    	} else {
349                    		false_value.value().ok()
350                    	}
351                    });
352                    Ok(Self {
353                        bits: selected_bits,
354                        value: selected_value,
355                    })
356                }
357            }
358
359            impl<ConstraintF: Field> AllocVar<$native, ConstraintF> for $name<ConstraintF> {
360                fn new_variable<T: Borrow<$native>>(
361                    cs: impl Into<Namespace<ConstraintF>>,
362                    f: impl FnOnce() -> Result<T, SynthesisError>,
363                    mode: AllocationMode,
364                ) -> Result<Self, SynthesisError> {
365                    let ns = cs.into();
366                    let cs = ns.cs();
367                    let value = f().map(|f| *f.borrow());
368                    let values = match value {
369                        Ok(val) => (0..$size).map(|i| Some((val >> i) & 1 == 1)).collect(),
370                        _ => vec![None; $size],
371                    };
372                    let bits = values
373                        .into_iter()
374                        .map(|v| Boolean::new_variable(cs.clone(), || v.get(), mode))
375                        .collect::<Result<Vec<_>, _>>()?;
376                    Ok(Self {
377                        bits,
378                        value: value.ok(),
379                    })
380                }
381            }
382
383            #[cfg(test)]
384            mod test {
385                use super::$name;
386                use crate::{bits::boolean::Boolean, prelude::*, Vec};
387                use ark_test_curves::bls12_381::Fr;
388                use ark_relations::r1cs::{ConstraintSystem, SynthesisError};
389                use rand::{Rng, SeedableRng};
390                use rand_xorshift::XorShiftRng;
391
392                #[test]
393                fn test_from_bits() -> Result<(), SynthesisError> {
394                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
395
396                    for _ in 0..1000 {
397                        let v = (0..$size)
398                            .map(|_| Boolean::constant(rng.gen()))
399                            .collect::<Vec<Boolean<Fr>>>();
400
401                        let b = $name::from_bits_le(&v);
402
403                        for (i, bit) in b.bits.iter().enumerate() {
404                            match bit {
405                                &Boolean::Constant(bit) => {
406                                    assert_eq!(bit, ((b.value()? >> i) & 1 == 1));
407                                }
408                                _ => unreachable!(),
409                            }
410                        }
411
412                        let expected_to_be_same = b.to_bits_le();
413
414                        for x in v.iter().zip(expected_to_be_same.iter()) {
415                            match x {
416                                (&Boolean::Constant(true), &Boolean::Constant(true)) => {}
417                                (&Boolean::Constant(false), &Boolean::Constant(false)) => {}
418                                _ => unreachable!(),
419                            }
420                        }
421                    }
422                    Ok(())
423                }
424
425                #[test]
426                fn test_xor() -> Result<(), SynthesisError> {
427                    use Boolean::*;
428                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
429
430                    for _ in 0..1000 {
431                        let cs = ConstraintSystem::<Fr>::new_ref();
432
433                        let a: $native = rng.gen();
434                        let b: $native = rng.gen();
435                        let c: $native = rng.gen();
436
437                        let mut expected = a ^ b ^ c;
438
439                        let a_bit = $name::new_witness(cs.clone(), || Ok(a))?;
440                        let b_bit = $name::constant(b);
441                        let c_bit = $name::new_witness(cs.clone(), || Ok(c))?;
442
443                        let r = a_bit.xor(&b_bit).unwrap();
444                        let r = r.xor(&c_bit).unwrap();
445
446                        assert!(cs.is_satisfied().unwrap());
447
448                        assert!(r.value == Some(expected));
449
450                        for b in r.bits.iter() {
451                            match b {
452                                Is(b) => assert_eq!(b.value()?, (expected & 1 == 1)),
453                                Not(b) => assert_eq!(!b.value()?, (expected & 1 == 1)),
454                                Constant(b) => assert_eq!(*b, (expected & 1 == 1)),
455                            }
456
457                            expected >>= 1;
458                        }
459                    }
460                    Ok(())
461                }
462
463                #[test]
464                fn test_addmany_constants() -> Result<(), SynthesisError> {
465                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
466
467                    for _ in 0..1000 {
468                        let cs = ConstraintSystem::<Fr>::new_ref();
469
470                        let a: $native = rng.gen();
471                        let b: $native = rng.gen();
472                        let c: $native = rng.gen();
473
474                        let a_bit = $name::new_constant(cs.clone(), a)?;
475                        let b_bit = $name::new_constant(cs.clone(), b)?;
476                        let c_bit = $name::new_constant(cs.clone(), c)?;
477
478                        let mut expected = a.wrapping_add(b).wrapping_add(c);
479
480                        let r = $name::addmany(&[a_bit, b_bit, c_bit]).unwrap();
481
482                        assert!(r.value == Some(expected));
483
484                        for b in r.bits.iter() {
485                            match b {
486                                Boolean::Is(_) => unreachable!(),
487                                Boolean::Not(_) => unreachable!(),
488                                Boolean::Constant(b) => assert_eq!(*b, (expected & 1 == 1)),
489                            }
490
491                            expected >>= 1;
492                        }
493                    }
494                    Ok(())
495                }
496
497                #[test]
498                fn test_addmany() -> Result<(), SynthesisError> {
499                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
500
501                    for _ in 0..1000 {
502                        let cs = ConstraintSystem::<Fr>::new_ref();
503
504                        let a: $native = rng.gen();
505                        let b: $native = rng.gen();
506                        let c: $native = rng.gen();
507                        let d: $native = rng.gen();
508
509                        let mut expected = (a ^ b).wrapping_add(c).wrapping_add(d);
510
511                        let a_bit = $name::new_witness(ark_relations::ns!(cs, "a_bit"), || Ok(a))?;
512                        let b_bit = $name::constant(b);
513                        let c_bit = $name::constant(c);
514                        let d_bit = $name::new_witness(ark_relations::ns!(cs, "d_bit"), || Ok(d))?;
515
516                        let r = a_bit.xor(&b_bit).unwrap();
517                        let r = $name::addmany(&[r, c_bit, d_bit]).unwrap();
518
519                        assert!(cs.is_satisfied().unwrap());
520
521                        assert!(r.value == Some(expected));
522
523                        for b in r.bits.iter() {
524                            match b {
525                                Boolean::Is(b) => assert_eq!(b.value()?, (expected & 1 == 1)),
526                                Boolean::Not(b) => assert_eq!(!b.value()?, (expected & 1 == 1)),
527                                Boolean::Constant(_) => unreachable!(),
528                            }
529
530                            expected >>= 1;
531                        }
532                    }
533                    Ok(())
534                }
535
536                #[test]
537                fn test_rotr() -> Result<(), SynthesisError> {
538                    let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
539
540                    let mut num = rng.gen();
541
542                    let a: $name<Fr> = $name::constant(num);
543
544                    for i in 0..$size {
545                        let b = a.rotr(i);
546
547                        assert!(b.value.unwrap() == num);
548
549                        let mut tmp = num;
550                        for b in &b.bits {
551                            match b {
552                                Boolean::Constant(b) => assert_eq!(*b, tmp & 1 == 1),
553                                _ => unreachable!(),
554                            }
555
556                            tmp >>= 1;
557                        }
558
559                        num = num.rotate_right(1);
560                    }
561                    Ok(())
562                }
563            }
564        }
565    };
566}