arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
ark-r1cs-std/r1cs-std/src/bits/uint8.rs
r1cs-std/src/bits/uint8.rsRaw
  1use algebra::Field;
  2use algebra::{FpParameters, PrimeField, ToConstraintField};
  3
  4use r1cs_core::{ConstraintSystemRef, Namespace, SynthesisError};
  5
  6use crate::{fields::fp::AllocatedFp, prelude::*, Assignment, Vec};
  7use core::borrow::Borrow;
  8
  9/// Represents an interpretation of 8 `Boolean` objects as an
 10/// unsigned integer.
 11#[derive(Clone, Debug)]
 12pub struct UInt8<F: Field> {
 13    /// Little-endian representation: least significant bit first
 14    pub(crate) bits: Vec<Boolean<F>>,
 15    /// Little-endian representation: least significant bit first
 16    pub(crate) value: Option<u8>,
 17}
 18
 19impl<F: Field> R1CSVar<F> for UInt8<F> {
 20    type Value = u8;
 21
 22    fn cs(&self) -> Option<ConstraintSystemRef<F>> {
 23        self.bits.as_slice().cs()
 24    }
 25
 26    fn value(&self) -> Result<Self::Value, SynthesisError> {
 27        let mut value = None;
 28        for (i, bit) in self.bits.iter().enumerate() {
 29            let b = u8::from(bit.value()?);
 30            value = match value {
 31                Some(value) => Some(value + (b << i)),
 32                None => Some(b << i),
 33            };
 34        }
 35        debug_assert_eq!(self.value, value);
 36        value.get()
 37    }
 38}
 39
 40impl<F: Field> UInt8<F> {
 41    /// Construct a constant vector of `UInt8` from a vector of `u8`
 42    pub fn constant_vec(values: &[u8]) -> Vec<Self> {
 43        let mut result = Vec::new();
 44        for value in values {
 45            result.push(UInt8::constant(*value));
 46        }
 47        result
 48    }
 49
 50    /// Construct a constant `UInt8` from a `u8`
 51    pub fn constant(value: u8) -> Self {
 52        let mut bits = Vec::with_capacity(8);
 53
 54        let mut tmp = value;
 55        for _ in 0..8 {
 56            // If last bit is one, push one.
 57            bits.push(Boolean::constant(tmp & 1 == 1));
 58            tmp >>= 1;
 59        }
 60
 61        Self {
 62            bits,
 63            value: Some(value),
 64        }
 65    }
 66
 67    pub fn new_witness_vec(
 68        cs: impl Into<Namespace<F>>,
 69        values: &[impl Into<Option<u8>> + Copy],
 70    ) -> Result<Vec<Self>, SynthesisError> {
 71        let ns = cs.into();
 72        let cs = ns.cs();
 73        let mut output_vec = Vec::with_capacity(values.len());
 74        for value in values {
 75            let byte: Option<u8> = Into::into(*value);
 76            output_vec.push(Self::new_witness(cs.clone(), || byte.get())?);
 77        }
 78        Ok(output_vec)
 79    }
 80
 81    /// Allocates a vector of `u8`'s by first converting (chunks of) them to
 82    /// `ConstraintF` elements, (thus reducing the number of input allocations),
 83    /// and then converts this list of `ConstraintF` gadgets back into
 84    /// bytes.
 85    pub fn new_input_vec(
 86        cs: impl Into<Namespace<F>>,
 87        values: &[u8],
 88    ) -> Result<Vec<Self>, SynthesisError>
 89    where
 90        F: PrimeField,
 91    {
 92        let ns = cs.into();
 93        let cs = ns.cs();
 94        let values_len = values.len();
 95        let field_elements: Vec<F> = ToConstraintField::<F>::to_field_elements(values).unwrap();
 96
 97        let max_size = 8 * (F::Params::CAPACITY / 8) as usize;
 98        let mut allocated_bits = Vec::new();
 99        for field_element in field_elements.into_iter() {
100            let fe = AllocatedFp::new_input(cs.clone(), || Ok(field_element))?;
101            let fe_bits = fe.to_bits_le()?;
102
103            // Remove the most significant bit, because we know it should be zero
104            // because `values.to_field_elements()` only
105            // packs field elements up to the penultimate bit.
106            // That is, the most significant bit (`ConstraintF::NUM_BITS`-th bit) is
107            // unset, so we can just pop it off.
108            allocated_bits.extend_from_slice(&fe_bits[0..max_size]);
109        }
110
111        // Chunk up slices of 8 bit into bytes.
112        Ok(allocated_bits[0..(8 * values_len)]
113            .chunks(8)
114            .map(Self::from_bits_le)
115            .collect())
116    }
117
118    /// Converts a little-endian byte order representation of bits into a
119    /// `UInt8`.
120    pub fn from_bits_le(bits: &[Boolean<F>]) -> Self {
121        assert_eq!(bits.len(), 8);
122
123        let bits = bits.to_vec();
124
125        let mut value = Some(0u8);
126        for (i, b) in bits.iter().enumerate() {
127            value = match b.value().ok() {
128                Some(b) => value.map(|v| v + (u8::from(b) << i)),
129                None => None,
130            }
131        }
132
133        Self { value, bits }
134    }
135
136    /// XOR this `UInt8` with another `UInt8`
137    pub fn xor(&self, other: &Self) -> Result<Self, SynthesisError> {
138        let new_value = match (self.value, other.value) {
139            (Some(a), Some(b)) => Some(a ^ b),
140            _ => None,
141        };
142
143        let bits = self
144            .bits
145            .iter()
146            .zip(other.bits.iter())
147            .map(|(a, b)| a.xor(b))
148            .collect::<Result<_, _>>()?;
149
150        Ok(Self {
151            bits,
152            value: new_value,
153        })
154    }
155}
156
157impl<ConstraintF: Field> EqGadget<ConstraintF> for UInt8<ConstraintF> {
158    fn is_eq(&self, other: &Self) -> Result<Boolean<ConstraintF>, SynthesisError> {
159        self.bits.as_slice().is_eq(&other.bits)
160    }
161
162    fn conditional_enforce_equal(
163        &self,
164        other: &Self,
165        condition: &Boolean<ConstraintF>,
166    ) -> Result<(), SynthesisError> {
167        self.bits.conditional_enforce_equal(&other.bits, condition)
168    }
169
170    fn conditional_enforce_not_equal(
171        &self,
172        other: &Self,
173        condition: &Boolean<ConstraintF>,
174    ) -> Result<(), SynthesisError> {
175        self.bits
176            .conditional_enforce_not_equal(&other.bits, condition)
177    }
178}
179
180impl<ConstraintF: Field> AllocVar<u8, ConstraintF> for UInt8<ConstraintF> {
181    fn new_variable<T: Borrow<u8>>(
182        cs: impl Into<Namespace<ConstraintF>>,
183        f: impl FnOnce() -> Result<T, SynthesisError>,
184        mode: AllocationMode,
185    ) -> Result<Self, SynthesisError> {
186        let ns = cs.into();
187        let cs = ns.cs();
188        let value = f().map(|f| *f.borrow());
189        let values = match value {
190            Ok(val) => (0..8).map(|i| Some((val >> i) & 1 == 1)).collect(),
191            _ => vec![None; 8],
192        };
193        let bits = values
194            .into_iter()
195            .map(|v| Boolean::new_variable(cs.clone(), || v.get(), mode))
196            .collect::<Result<Vec<_>, _>>()?;
197        Ok(Self {
198            bits,
199            value: value.ok(),
200        })
201    }
202}
203
204#[cfg(test)]
205mod test {
206    use super::UInt8;
207    use crate::{prelude::*, Vec};
208    use algebra::bls12_381::Fr;
209    use r1cs_core::{ConstraintSystem, SynthesisError};
210    use rand::{Rng, SeedableRng};
211    use rand_xorshift::XorShiftRng;
212
213    #[test]
214    fn test_uint8_from_bits_to_bits() -> Result<(), SynthesisError> {
215        let cs = ConstraintSystem::<Fr>::new_ref();
216        let byte_val = 0b01110001;
217        let byte = UInt8::new_witness(cs.ns("alloc value"), || Ok(byte_val)).unwrap();
218        let bits = byte.to_bits_le()?;
219        for (i, bit) in bits.iter().enumerate() {
220            assert_eq!(bit.value()?, (byte_val >> i) & 1 == 1)
221        }
222        Ok(())
223    }
224
225    #[test]
226    fn test_uint8_new_input_vec() -> Result<(), SynthesisError> {
227        let cs = ConstraintSystem::<Fr>::new_ref();
228        let byte_vals = (64u8..128u8).collect::<Vec<_>>();
229        let bytes = UInt8::new_input_vec(cs.ns("alloc value"), &byte_vals).unwrap();
230        dbg!(bytes.value())?;
231        for (native, variable) in byte_vals.into_iter().zip(bytes) {
232            let bits = variable.to_bits_le()?;
233            for (i, bit) in bits.iter().enumerate() {
234                assert_eq!(
235                    bit.value()?,
236                    (native >> i) & 1 == 1,
237                    "native value {}: bit {:?}",
238                    native,
239                    i
240                )
241            }
242        }
243        Ok(())
244    }
245
246    #[test]
247    fn test_uint8_from_bits() -> Result<(), SynthesisError> {
248        let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
249
250        for _ in 0..1000 {
251            let v = (0..8)
252                .map(|_| Boolean::<Fr>::Constant(rng.gen()))
253                .collect::<Vec<_>>();
254
255            let val = UInt8::from_bits_le(&v);
256
257            for (i, bit) in val.bits.iter().enumerate() {
258                match bit {
259                    Boolean::Constant(b) => assert!(*b == ((val.value()? >> i) & 1 == 1)),
260                    _ => unreachable!(),
261                }
262            }
263
264            let expected_to_be_same = val.to_bits_le()?;
265
266            for x in v.iter().zip(expected_to_be_same.iter()) {
267                match x {
268                    (&Boolean::Constant(true), &Boolean::Constant(true)) => {}
269                    (&Boolean::Constant(false), &Boolean::Constant(false)) => {}
270                    _ => unreachable!(),
271                }
272            }
273        }
274        Ok(())
275    }
276
277    #[test]
278    fn test_uint8_xor() -> Result<(), SynthesisError> {
279        let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
280
281        for _ in 0..1000 {
282            let cs = ConstraintSystem::<Fr>::new_ref();
283
284            let a: u8 = rng.gen();
285            let b: u8 = rng.gen();
286            let c: u8 = rng.gen();
287
288            let mut expected = a ^ b ^ c;
289
290            let a_bit = UInt8::new_witness(cs.ns("a_bit"), || Ok(a)).unwrap();
291            let b_bit = UInt8::constant(b);
292            let c_bit = UInt8::new_witness(cs.ns("c_bit"), || Ok(c)).unwrap();
293
294            let r = a_bit.xor(&b_bit).unwrap();
295            let r = r.xor(&c_bit).unwrap();
296
297            assert!(cs.is_satisfied().unwrap());
298
299            assert!(r.value == Some(expected));
300
301            for b in r.bits.iter() {
302                match b {
303                    Boolean::Is(b) => assert!(b.value()? == (expected & 1 == 1)),
304                    Boolean::Not(b) => assert!(!b.value()? == (expected & 1 == 1)),
305                    Boolean::Constant(b) => assert!(*b == (expected & 1 == 1)),
306                }
307
308                expected >>= 1;
309            }
310        }
311        Ok(())
312    }
313}