ark-r1cs-std/crypto-primitives/src/prf/blake2s/constraints.rs
crypto-primitives/src/prf/blake2s/constraints.rsRaw
1use algebra::PrimeField;
2use r1cs_core::{ConstraintSystem, SynthesisError};
3
4use crate::prf::PRFGadget;
5use r1cs_std::prelude::*;
6
7use std::borrow::Borrow;
8
9// 2.1. Parameters
10// The following table summarizes various parameters and their ranges:
11// | BLAKE2b | BLAKE2s |
12// --------------+------------------+------------------+
13// Bits in word | w = 64 | w = 32 |
14// Rounds in F | r = 12 | r = 10 |
15// Block bytes | bb = 128 | bb = 64 |
16// Hash bytes | 1 <= nn <= 64 | 1 <= nn <= 32 |
17// Key bytes | 0 <= kk <= 64 | 0 <= kk <= 32 |
18// Input bytes | 0 <= ll < 2**128 | 0 <= ll < 2**64 |
19// --------------+------------------+------------------+
20// G Rotation | (R1, R2, R3, R4) | (R1, R2, R3, R4) |
21// constants = | (32, 24, 16, 63) | (16, 12, 8, 7) |
22// --------------+------------------+------------------+
23//
24
25const R1: usize = 16;
26const R2: usize = 12;
27const R3: usize = 8;
28const R4: usize = 7;
29
30// Round | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
31// ----------+-------------------------------------------------+
32// SIGMA[0] | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
33// SIGMA[1] | 14 10 4 8 9 15 13 6 1 12 0 2 11 7 5 3 |
34// SIGMA[2] | 11 8 12 0 5 2 15 13 10 14 3 6 7 1 9 4 |
35// SIGMA[3] | 7 9 3 1 13 12 11 14 2 6 5 10 4 0 15 8 |
36// SIGMA[4] | 9 0 5 7 2 4 10 15 14 1 11 12 6 8 3 13 |
37// SIGMA[5] | 2 12 6 10 0 11 8 3 4 13 7 5 15 14 1 9 |
38// SIGMA[6] | 12 5 1 15 14 13 4 10 0 7 6 3 9 2 8 11 |
39// SIGMA[7] | 13 11 7 14 12 1 3 9 5 0 15 4 8 6 2 10 |
40// SIGMA[8] | 6 15 14 9 11 3 0 8 12 2 13 7 1 4 10 5 |
41// SIGMA[9] | 10 2 8 4 7 6 1 5 15 11 9 14 3 12 13 0 |
42// ----------+-------------------------------------------------+
43//
44
45const SIGMA: [[usize; 16]; 10] = [
46 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
47 [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
48 [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
49 [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
50 [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
51 [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
52 [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
53 [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
54 [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
55 [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
56];
57
58// 3.1. Mixing Function G
59// The G primitive function mixes two input words, "x" and "y", into
60// four words indexed by "a", "b", "c", and "d" in the working vector
61// v[0..15]. The full modified vector is returned. The rotation
62// constants (R1, R2, R3, R4) are given in Section 2.1.
63// FUNCTION G( v[0..15], a, b, c, d, x, y )
64// |
65// | v[a] := (v[a] + v[b] + x) mod 2**w
66// | v[d] := (v[d] ^ v[a]) >>> R1
67// | v[c] := (v[c] + v[d]) mod 2**w
68// | v[b] := (v[b] ^ v[c]) >>> R2
69// | v[a] := (v[a] + v[b] + y) mod 2**w
70// | v[d] := (v[d] ^ v[a]) >>> R3
71// | v[c] := (v[c] + v[d]) mod 2**w
72// | v[b] := (v[b] ^ v[c]) >>> R4
73// |
74// | RETURN v[0..15]
75// |
76// END FUNCTION.
77//
78
79fn mixing_g<ConstraintF: PrimeField, CS: ConstraintSystem<ConstraintF>>(
80 mut cs: CS,
81 v: &mut [UInt32],
82 a: usize,
83 b: usize,
84 c: usize,
85 d: usize,
86 x: &UInt32,
87 y: &UInt32,
88) -> Result<(), SynthesisError> {
89 v[a] = UInt32::addmany(
90 cs.ns(|| "mixing step 1"),
91 &[v[a].clone(), v[b].clone(), x.clone()],
92 )?;
93 v[d] = v[d].xor(cs.ns(|| "mixing step 2"), &v[a])?.rotr(R1);
94 v[c] = UInt32::addmany(cs.ns(|| "mixing step 3"), &[v[c].clone(), v[d].clone()])?;
95 v[b] = v[b].xor(cs.ns(|| "mixing step 4"), &v[c])?.rotr(R2);
96 v[a] = UInt32::addmany(
97 cs.ns(|| "mixing step 5"),
98 &[v[a].clone(), v[b].clone(), y.clone()],
99 )?;
100 v[d] = v[d].xor(cs.ns(|| "mixing step 6"), &v[a])?.rotr(R3);
101 v[c] = UInt32::addmany(cs.ns(|| "mixing step 7"), &[v[c].clone(), v[d].clone()])?;
102 v[b] = v[b].xor(cs.ns(|| "mixing step 8"), &v[c])?.rotr(R4);
103
104 Ok(())
105}
106
107// 3.2. Compression Function F
108// Compression function F takes as an argument the state vector "h",
109// message block vector "m" (last block is padded with zeros to full
110// block size, if required), 2w-bit_gadget offset counter "t", and final block
111// indicator flag "f". Local vector v[0..15] is used in processing. F
112// returns a new state vector. The number of rounds, "r", is 12 for
113// BLAKE2b and 10 for BLAKE2s. Rounds are numbered from 0 to r - 1.
114// FUNCTION F( h[0..7], m[0..15], t, f )
115// |
116// | // Initialize local work vector v[0..15]
117// | v[0..7] := h[0..7] // First half from state.
118// | v[8..15] := IV[0..7] // Second half from IV.
119// |
120// | v[12] := v[12] ^ (t mod 2**w) // Low word of the offset.
121// | v[13] := v[13] ^ (t >> w) // High word.
122// |
123// | IF f = TRUE THEN // last block flag?
124// | | v[14] := v[14] ^ 0xFF..FF // Invert all bits.
125// | END IF.
126// |
127// | // Cryptographic mixing
128// | FOR i = 0 TO r - 1 DO // Ten or twelve rounds.
129// | |
130// | | // Message word selection permutation for this round.
131// | | s[0..15] := SIGMA[i mod 10][0..15]
132// | |
133// | | v := G( v, 0, 4, 8, 12, m[s[ 0]], m[s[ 1]] )
134// | | v := G( v, 1, 5, 9, 13, m[s[ 2]], m[s[ 3]] )
135// | | v := G( v, 2, 6, 10, 14, m[s[ 4]], m[s[ 5]] )
136// | | v := G( v, 3, 7, 11, 15, m[s[ 6]], m[s[ 7]] )
137// | |
138// | | v := G( v, 0, 5, 10, 15, m[s[ 8]], m[s[ 9]] )
139// | | v := G( v, 1, 6, 11, 12, m[s[10]], m[s[11]] )
140// | | v := G( v, 2, 7, 8, 13, m[s[12]], m[s[13]] )
141// | | v := G( v, 3, 4, 9, 14, m[s[14]], m[s[15]] )
142// | |
143// | END FOR
144// |
145// | FOR i = 0 TO 7 DO // XOR the two halves.
146// | | h[i] := h[i] ^ v[i] ^ v[i + 8]
147// | END FOR.
148// |
149// | RETURN h[0..7] // New state.
150// |
151// END FUNCTION.
152//
153
154fn blake2s_compression<ConstraintF: PrimeField, CS: ConstraintSystem<ConstraintF>>(
155 mut cs: CS,
156 h: &mut [UInt32],
157 m: &[UInt32],
158 t: u64,
159 f: bool,
160) -> Result<(), SynthesisError> {
161 assert_eq!(h.len(), 8);
162 assert_eq!(m.len(), 16);
163
164 // static const uint32_t blake2s_iv[8] =
165 // {
166 // 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
167 // 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
168 // };
169 //
170
171 let mut v = Vec::with_capacity(16);
172 v.extend_from_slice(h);
173 v.push(UInt32::constant(0x6A09E667));
174 v.push(UInt32::constant(0xBB67AE85));
175 v.push(UInt32::constant(0x3C6EF372));
176 v.push(UInt32::constant(0xA54FF53A));
177 v.push(UInt32::constant(0x510E527F));
178 v.push(UInt32::constant(0x9B05688C));
179 v.push(UInt32::constant(0x1F83D9AB));
180 v.push(UInt32::constant(0x5BE0CD19));
181
182 assert_eq!(v.len(), 16);
183
184 v[12] = v[12].xor(cs.ns(|| "first xor"), &UInt32::constant(t as u32))?;
185 v[13] = v[13].xor(cs.ns(|| "second xor"), &UInt32::constant((t >> 32) as u32))?;
186
187 if f {
188 v[14] = v[14].xor(cs.ns(|| "third xor"), &UInt32::constant(u32::max_value()))?;
189 }
190
191 for i in 0..10 {
192 let mut cs = cs.ns(|| format!("round {}", i));
193
194 let s = SIGMA[i % 10];
195
196 mixing_g(
197 cs.ns(|| "mixing invocation 1"),
198 &mut v,
199 0,
200 4,
201 8,
202 12,
203 &m[s[0]],
204 &m[s[1]],
205 )?;
206 mixing_g(
207 cs.ns(|| "mixing invocation 2"),
208 &mut v,
209 1,
210 5,
211 9,
212 13,
213 &m[s[2]],
214 &m[s[3]],
215 )?;
216 mixing_g(
217 cs.ns(|| "mixing invocation 3"),
218 &mut v,
219 2,
220 6,
221 10,
222 14,
223 &m[s[4]],
224 &m[s[5]],
225 )?;
226 mixing_g(
227 cs.ns(|| "mixing invocation 4"),
228 &mut v,
229 3,
230 7,
231 11,
232 15,
233 &m[s[6]],
234 &m[s[7]],
235 )?;
236
237 mixing_g(
238 cs.ns(|| "mixing invocation 5"),
239 &mut v,
240 0,
241 5,
242 10,
243 15,
244 &m[s[8]],
245 &m[s[9]],
246 )?;
247 mixing_g(
248 cs.ns(|| "mixing invocation 6"),
249 &mut v,
250 1,
251 6,
252 11,
253 12,
254 &m[s[10]],
255 &m[s[11]],
256 )?;
257 mixing_g(
258 cs.ns(|| "mixing invocation 7"),
259 &mut v,
260 2,
261 7,
262 8,
263 13,
264 &m[s[12]],
265 &m[s[13]],
266 )?;
267 mixing_g(
268 cs.ns(|| "mixing invocation 8"),
269 &mut v,
270 3,
271 4,
272 9,
273 14,
274 &m[s[14]],
275 &m[s[15]],
276 )?;
277 }
278
279 for i in 0..8 {
280 let mut cs = cs.ns(|| format!("h[{i}] ^ v[{i}] ^ v[{i} + 8]", i = i));
281
282 h[i] = h[i].xor(cs.ns(|| "first xor"), &v[i])?;
283 h[i] = h[i].xor(cs.ns(|| "second xor"), &v[i + 8])?;
284 }
285
286 Ok(())
287}
288
289// FUNCTION BLAKE2( d[0..dd-1], ll, kk, nn )
290// |
291// | h[0..7] := IV[0..7] // Initialization Vector.
292// |
293// | // Parameter block p[0]
294// | h[0] := h[0] ^ 0x01010000 ^ (kk << 8) ^ nn
295// |
296// | // Process padded key and data blocks
297// | IF dd > 1 THEN
298// | | FOR i = 0 TO dd - 2 DO
299// | | | h := F( h, d[i], (i + 1) * bb, FALSE )
300// | | END FOR.
301// | END IF.
302// |
303// | // Final block.
304// | IF kk = 0 THEN
305// | | h := F( h, d[dd - 1], ll, TRUE )
306// | ELSE
307// | | h := F( h, d[dd - 1], ll + bb, TRUE )
308// | END IF.
309// |
310// | RETURN first "nn" bytes from little-endian word array h[].
311// |
312// END FUNCTION.
313//
314
315pub fn blake2s_gadget<ConstraintF: PrimeField, CS: ConstraintSystem<ConstraintF>>(
316 mut cs: CS,
317 input: &[Boolean],
318) -> Result<Vec<UInt32>, SynthesisError> {
319 assert!(input.len() % 8 == 0);
320
321 let mut h = Vec::with_capacity(8);
322 h.push(UInt32::constant(0x6A09E667 ^ 0x01010000 ^ 32));
323 h.push(UInt32::constant(0xBB67AE85));
324 h.push(UInt32::constant(0x3C6EF372));
325 h.push(UInt32::constant(0xA54FF53A));
326 h.push(UInt32::constant(0x510E527F));
327 h.push(UInt32::constant(0x9B05688C));
328 h.push(UInt32::constant(0x1F83D9AB));
329 h.push(UInt32::constant(0x5BE0CD19));
330
331 let mut blocks: Vec<Vec<UInt32>> = vec![];
332
333 for block in input.chunks(512) {
334 let mut this_block = Vec::with_capacity(16);
335 for word in block.chunks(32) {
336 let mut tmp = word.to_vec();
337 while tmp.len() < 32 {
338 tmp.push(Boolean::constant(false));
339 }
340 this_block.push(UInt32::from_bits_le(&tmp));
341 }
342 while this_block.len() < 16 {
343 this_block.push(UInt32::constant(0));
344 }
345 blocks.push(this_block);
346 }
347
348 if blocks.is_empty() {
349 blocks.push((0..16).map(|_| UInt32::constant(0)).collect());
350 }
351
352 for (i, block) in blocks[0..blocks.len() - 1].iter().enumerate() {
353 let cs = cs.ns(|| format!("block {}", i));
354
355 blake2s_compression(cs, &mut h, block, ((i as u64) + 1) * 64, false)?;
356 }
357
358 {
359 let cs = cs.ns(|| "final block");
360
361 blake2s_compression(
362 cs,
363 &mut h,
364 &blocks[blocks.len() - 1],
365 (input.len() / 8) as u64,
366 true,
367 )?;
368 }
369
370 Ok(h)
371}
372
373use crate::prf::Blake2s;
374
375pub struct Blake2sGadget;
376#[derive(Clone, Debug)]
377pub struct Blake2sOutputGadget(pub Vec<UInt8>);
378
379impl PartialEq for Blake2sOutputGadget {
380 fn eq(&self, other: &Self) -> bool {
381 self.0 == other.0
382 }
383}
384
385impl Eq for Blake2sOutputGadget {}
386
387impl<ConstraintF: PrimeField> EqGadget<ConstraintF> for Blake2sOutputGadget {}
388
389impl<ConstraintF: PrimeField> ConditionalEqGadget<ConstraintF> for Blake2sOutputGadget {
390 #[inline]
391 fn conditional_enforce_equal<CS: ConstraintSystem<ConstraintF>>(
392 &self,
393 mut cs: CS,
394 other: &Self,
395 condition: &Boolean,
396 ) -> Result<(), SynthesisError> {
397 for (i, (a, b)) in self.0.iter().zip(other.0.iter()).enumerate() {
398 a.conditional_enforce_equal(
399 &mut cs.ns(|| format!("blake2s_equal_{}", i)),
400 b,
401 condition,
402 )?;
403 }
404 Ok(())
405 }
406
407 fn cost() -> usize {
408 32 * <UInt8 as ConditionalEqGadget<ConstraintF>>::cost()
409 }
410}
411
412impl<ConstraintF: PrimeField> ToBytesGadget<ConstraintF> for Blake2sOutputGadget {
413 #[inline]
414 fn to_bytes<CS: ConstraintSystem<ConstraintF>>(&self, _cs: CS) -> Result<Vec<UInt8>, SynthesisError> {
415 Ok(self.0.clone())
416 }
417
418 #[inline]
419 fn to_bytes_strict<CS: ConstraintSystem<ConstraintF>>(
420 &self,
421 cs: CS,
422 ) -> Result<Vec<UInt8>, SynthesisError> {
423 self.to_bytes(cs)
424 }
425}
426
427impl<ConstraintF: PrimeField> AllocGadget<[u8; 32], ConstraintF> for Blake2sOutputGadget {
428 #[inline]
429 fn alloc<F, T, CS: ConstraintSystem<ConstraintF>>(cs: CS, value_gen: F) -> Result<Self, SynthesisError>
430 where
431 F: FnOnce() -> Result<T, SynthesisError>,
432 T: Borrow<[u8; 32]>,
433 {
434 let zeros = [0u8; 32];
435 let value = match value_gen() {
436 Ok(val) => *(val.borrow()),
437 Err(_) => zeros,
438 };
439 let bytes = <UInt8>::alloc_vec(cs, &value)?;
440
441 Ok(Blake2sOutputGadget(bytes))
442 }
443
444 #[inline]
445 fn alloc_input<F, T, CS: ConstraintSystem<ConstraintF>>(
446 cs: CS,
447 value_gen: F,
448 ) -> Result<Self, SynthesisError>
449 where
450 F: FnOnce() -> Result<T, SynthesisError>,
451 T: Borrow<[u8; 32]>,
452 {
453 let zeros = [0u8; 32];
454 let value = match value_gen() {
455 Ok(val) => *(val.borrow()),
456 Err(_) => zeros,
457 };
458 let bytes = <UInt8>::alloc_input_vec(cs, &value)?;
459
460 Ok(Blake2sOutputGadget(bytes))
461 }
462}
463
464impl<ConstraintF: PrimeField> PRFGadget<Blake2s, ConstraintF> for Blake2sGadget {
465 type OutputGadget = Blake2sOutputGadget;
466
467 fn new_seed<CS: ConstraintSystem<ConstraintF>>(mut cs: CS, seed: &[u8; 32]) -> Vec<UInt8> {
468 UInt8::alloc_vec(&mut cs.ns(|| "alloc_seed"), seed).unwrap()
469 }
470
471 fn check_evaluation_gadget<CS: ConstraintSystem<ConstraintF>>(
472 mut cs: CS,
473 seed: &[UInt8],
474 input: &[UInt8],
475 ) -> Result<Self::OutputGadget, SynthesisError> {
476 assert_eq!(seed.len(), 32);
477 // assert_eq!(input.len(), 32);
478 let mut gadget_input = Vec::with_capacity(512);
479 for byte in seed.into_iter().chain(input) {
480 gadget_input.extend_from_slice(&byte.into_bits_le());
481 }
482 let mut result = Vec::new();
483 for (i, int) in blake2s_gadget(cs.ns(|| "Blake2s Eval"), &gadget_input)?
484 .into_iter()
485 .enumerate()
486 {
487 let chunk = int.to_bytes(&mut cs.ns(|| format!("Result ToBytes {}", i)))?;
488 result.extend_from_slice(&chunk);
489 }
490 Ok(Blake2sOutputGadget(result))
491 }
492}
493
494#[cfg(test)]
495mod test {
496 use algebra::fields::bls12_377::fr::Fr;
497 use digest::{FixedOutput, Input};
498 use rand::{Rng, SeedableRng};
499 use rand_xorshift::XorShiftRng;
500
501 use crate::prf::blake2s::{Blake2s as B2SPRF, constraints::blake2s_gadget};
502 use blake2::Blake2s;
503 use r1cs_core::ConstraintSystem;
504
505 use super::Blake2sGadget;
506 use r1cs_std::{prelude::*, boolean::AllocatedBit, test_constraint_system::TestConstraintSystem};
507
508 #[test]
509 fn test_blake2s_constraints() {
510 let mut cs = TestConstraintSystem::<Fr>::new();
511 let input_bits: Vec<_> = (0..512)
512 .map(|i| {
513 AllocatedBit::alloc(cs.ns(|| format!("input bit_gadget {}", i)), || Ok(true))
514 .unwrap()
515 .into()
516 })
517 .collect();
518 blake2s_gadget(&mut cs, &input_bits).unwrap();
519 assert!(cs.is_satisfied());
520 assert_eq!(cs.num_constraints(), 21792);
521 }
522
523 #[test]
524 fn test_blake2s_prf() {
525 use crate::prf::{PRF, PRFGadget};
526 use rand::Rng;
527
528 let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
529 let mut cs = TestConstraintSystem::<Fr>::new();
530
531 let mut seed = [0u8; 32];
532 rng.fill(&mut seed);
533
534 let mut input = [0u8; 32];
535 rng.fill(&mut input);
536
537 let seed_gadget = Blake2sGadget::new_seed(&mut cs.ns(|| "declare_seed"), &seed);
538 let input_gadget = UInt8::alloc_vec(&mut cs.ns(|| "declare_input"), &input).unwrap();
539 let out = B2SPRF::evaluate(&seed, &input).unwrap();
540 let actual_out_gadget = <Blake2sGadget as PRFGadget<_, Fr>>::OutputGadget::alloc(
541 &mut cs.ns(|| "declare_output"),
542 || Ok(out),
543 )
544 .unwrap();
545
546 let output_gadget = Blake2sGadget::check_evaluation_gadget(
547 &mut cs.ns(|| "eval_blake2s"),
548 &seed_gadget,
549 &input_gadget,
550 )
551 .unwrap();
552 output_gadget
553 .enforce_equal(&mut cs, &actual_out_gadget)
554 .unwrap();
555
556 if !cs.is_satisfied() {
557 println!(
558 "which is unsatisfied: {:?}",
559 cs.which_is_unsatisfied().unwrap()
560 );
561 }
562 assert!(cs.is_satisfied());
563 }
564
565 #[test]
566 fn test_blake2s_precomp_constraints() {
567 // Test that 512 fixed leading bits (constants)
568 // doesn't result in more constraints.
569
570 let mut cs = TestConstraintSystem::<Fr>::new();
571 let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
572 let input_bits: Vec<_> = (0..512)
573 .map(|_| Boolean::constant(rng.gen()))
574 .chain((0..512).map(|i| {
575 AllocatedBit::alloc(cs.ns(|| format!("input bit_gadget {}", i)), || Ok(true))
576 .unwrap()
577 .into()
578 }))
579 .collect();
580 blake2s_gadget(&mut cs, &input_bits).unwrap();
581 assert!(cs.is_satisfied());
582 assert_eq!(cs.num_constraints(), 21792);
583 }
584
585 #[test]
586 fn test_blake2s_constant_constraints() {
587 let mut cs = TestConstraintSystem::<Fr>::new();
588 let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
589 let input_bits: Vec<_> = (0..512).map(|_| Boolean::constant(rng.gen())).collect();
590 blake2s_gadget(&mut cs, &input_bits).unwrap();
591 assert_eq!(cs.num_constraints(), 0);
592 }
593
594 #[test]
595 fn test_blake2s() {
596 let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
597
598 for input_len in (0..32).chain((32..256).filter(|a| a % 8 == 0)) {
599 let mut h = Blake2s::new_keyed(&[], 32);
600
601 let data: Vec<u8> = (0..input_len).map(|_| rng.gen()).collect();
602
603 h.process(&data);
604
605 let hash_result = h.fixed_result();
606
607 let mut cs = TestConstraintSystem::<Fr>::new();
608
609 let mut input_bits = vec![];
610
611 for (byte_i, input_byte) in data.into_iter().enumerate() {
612 for bit_i in 0..8 {
613 let cs = cs.ns(|| format!("input bit_gadget {} {}", byte_i, bit_i));
614
615 input_bits.push(
616 AllocatedBit::alloc(cs, || Ok((input_byte >> bit_i) & 1u8 == 1u8))
617 .unwrap()
618 .into(),
619 );
620 }
621 }
622
623 let r = blake2s_gadget(&mut cs, &input_bits).unwrap();
624
625 assert!(cs.is_satisfied());
626
627 let mut s = hash_result
628 .as_ref()
629 .iter()
630 .flat_map(|&byte| (0..8).map(move |i| (byte >> i) & 1u8 == 1u8));
631
632 for chunk in r {
633 for b in chunk.to_bits_le() {
634 match b {
635 Boolean::Is(b) => {
636 assert!(s.next().unwrap() == b.get_value().unwrap());
637 },
638 Boolean::Not(b) => {
639 assert!(s.next().unwrap() != b.get_value().unwrap());
640 },
641 Boolean::Constant(b) => {
642 assert!(input_len == 0);
643 assert!(s.next().unwrap() == b);
644 },
645 }
646 }
647 }
648 }
649 }
650}