1use crate::ir_instructions::add::{add_incircuit, add_offcircuit};
15use crate::ir_instructions::assign::assign_incircuit;
16use crate::ir_instructions::assign_constant::assign_constant_incircuit;
17use crate::ir_instructions::constrain_eq::{constrain_eq_incircuit, constrain_eq_offcircuit};
18use crate::ir_instructions::ec_mul::{ec_mul_incircuit, ec_mul_offcircuit};
19use crate::ir_instructions::encode::{
20 decode_offcircuit, encode_incircuit, encode_offcircuit, jubjub_scalar_from_biguint,
21 native_to_jubjub_scalar,
22};
23use crate::ir_instructions::eq::{test_eq_incircuit, test_eq_offcircuit};
24use crate::ir_instructions::from_bytes::{from_bytes_incircuit, from_bytes_offcircuit};
25use crate::ir_instructions::from_coordinates::{
26 from_coordinates_incircuit, from_coordinates_offcircuit,
27};
28use crate::ir_instructions::into_coordinates::{
29 into_coordinates_incircuit, into_coordinates_offcircuit,
30};
31use crate::ir_instructions::inv::{inv_incircuit, inv_offcircuit};
32use crate::ir_instructions::mul::{mul_incircuit, mul_offcircuit};
33use crate::ir_instructions::neg::{neg_incircuit, neg_offcircuit};
34use crate::ir_instructions::select::{select_incircuit, select_offcircuit};
35use crate::ir_instructions::to_bytes::{to_bytes_incircuit, to_bytes_offcircuit};
36use crate::ir_types::{BYTES_PER_FIELD_ELEMENT, CircuitValue, IrType, IrValue, MAX_BYTES_LEN};
37
38use super::ir::{Identifier, Instruction as I, IrSource, Operand};
39use anyhow::{anyhow, bail};
40use base_crypto::fab::{Alignment, AlignmentAtom, AlignmentSegment};
41use base_crypto::repr::BinaryHashRepr;
42use group::Group;
43use midnight_circuits::instructions::{
44 ArithInstructions, AssertionInstructions, AssignmentInstructions, BinaryInstructions,
45 ControlFlowInstructions, ConversionInstructions, DecompositionInstructions,
46 PublicInputInstructions, ZeroInstructions,
47};
48use midnight_circuits::types::{AssignedBit, AssignedByte, AssignedNative, InnerValue};
49use midnight_curves::{JubjubSubgroup, curve25519, k256, p256};
50use midnight_proofs::{
51 circuit::{Layouter, Value},
52 plonk::Error,
53};
54use midnight_zk_stdlib::{Relation, ZkStdLib, ZkStdLibArch};
55use serialize::{Deserializable, Serializable, VecExt, tagged_deserialize, tagged_serialize};
56use sha2::{Sha256, Sha512};
57use sha3::{Digest, Keccak256};
58use std::cmp::Ordering;
59use std::collections::HashMap;
60use transient_crypto::curve::outer;
61use transient_crypto::curve::{FR_BITS, FR_BYTES_STORED, Fr};
62use transient_crypto::fab::{AlignmentExt, ValueReprAlignedValue};
63use transient_crypto::hash::{hash_to_curve, transient_commit, transient_hash};
64use transient_crypto::proofs::{ProofPreimage, ProvingError};
65
66#[derive(Clone, Debug)]
70#[allow(missing_docs)]
71pub struct Preprocessed {
72 pub memory: HashMap<Identifier, IrValue>,
73 pub pis: Vec<outer::Scalar>,
74 pub pi_skips: Vec<Option<usize>>,
75 pub binding_input: outer::Scalar,
76 pub comm_comm: Option<(outer::Scalar, outer::Scalar)>,
77}
78
79fn ir_value_to_bytes32(value: IrValue) -> Result<[u8; 32], anyhow::Error> {
83 let bytes: Vec<u8> = value.try_into()?;
84 let len = bytes.len();
85 bytes
86 .try_into()
87 .map_err(|_| anyhow!("expected a Bytes<32> value, got Bytes<{len}>"))
88}
89
90fn circuit_value_to_bytes32(
94 value: CircuitValue,
95) -> Result<[AssignedByte<outer::Scalar>; 32], Error> {
96 let bytes: Vec<AssignedByte<outer::Scalar>> = value.try_into()?;
97 let len = bytes.len();
98 bytes
99 .try_into()
100 .map_err(|_| Error::Synthesis(format!("expected a Bytes<32> value, got Bytes<{len}>")))
101}
102
103fn bytes_from_natives_nb_limbs(len: u32, nb_inputs: usize) -> Result<usize, String> {
108 if len == 0 || len > MAX_BYTES_LEN {
109 return Err(format!(
110 "BytesFromNatives: output length {len} is not in 1..={MAX_BYTES_LEN}"
111 ));
112 }
113 let nb_limbs = (len as usize).div_ceil(BYTES_PER_FIELD_ELEMENT);
114 if nb_inputs != nb_limbs {
115 return Err(format!(
116 "BytesFromNatives: a Bytes<{len}> unpacks from {nb_limbs} field elements but the \
117 instruction has {nb_inputs} inputs"
118 ));
119 }
120 Ok(nb_limbs)
121}
122
123fn fab_decode_to_bytes(
124 std: &ZkStdLib,
125 layouter: &mut impl Layouter<outer::Scalar>,
126 align: &Alignment,
127 mut inputs: &[AssignedNative<outer::Scalar>],
128) -> Result<Vec<AssignedByte<outer::Scalar>>, Error> {
129 let mut res = Vec::with_bounded_capacity(align.bin_len());
130 let _ = fab_decode_to_bytes_inner(std, layouter, align, &mut inputs, &mut res)?;
131 let mut debug_values: Vec<u8> = Vec::new();
132 for value in res.iter() {
133 value.value().assert_if_known(|v| {
134 debug_values.push(*v);
135 true
136 })
137 }
138 if !debug_values.is_empty() {
139 trace!(bytes = ?debug_values, len = debug_values.len(), "bytes decoded in-circuit");
140 }
141 Ok(res)
142}
143
144fn fab_decode_to_bytes_inner(
145 std: &ZkStdLib,
146 layouter: &mut impl Layouter<outer::Scalar>,
147 align: &Alignment,
148 inputs: &mut &[AssignedNative<outer::Scalar>],
149 res: &mut Vec<AssignedByte<outer::Scalar>>,
150) -> Result<AssignedNative<outer::Scalar>, Error> {
151 let mut acc = std.assign_fixed(layouter, 0.into())?;
152 for segment in align.0.iter() {
153 match segment {
154 AlignmentSegment::Atom(atom) => {
155 fab_decode_to_bytes_atom(std, layouter, atom, inputs, res)?;
156 acc = std.add_constant(layouter, &acc, 1.into())?;
157 }
158 AlignmentSegment::Option(_) => {
159 error!("in-circuit decoding of alignment options is not yet implemented!");
160 return Err(Error::Synthesis(
161 "in-circuit decoding of alignment options is not yet implemented!".into(),
162 ));
163 }
164 }
165 }
166 Ok(acc)
167}
168
169fn fab_decode_to_bytes_atom(
170 std: &ZkStdLib,
171 layouter: &mut impl Layouter<outer::Scalar>,
172 align: &AlignmentAtom,
173 inputs: &mut &[AssignedNative<outer::Scalar>],
174 res: &mut Vec<AssignedByte<outer::Scalar>>,
175) -> Result<(), Error> {
176 match align {
177 AlignmentAtom::Field => {
178 if inputs.is_empty() {
179 return Err(Error::Synthesis(
180 "cannot decode field element from no data".into(),
181 ));
182 }
183 let value = &inputs[0];
184 *inputs = &inputs[1..];
185 res.extend(std.assigned_to_le_bytes(layouter, value, None)?);
186 Ok(())
187 }
188 AlignmentAtom::Bytes { length } => {
189 let stray = *length as usize % FR_BYTES_STORED;
190 let chunks = *length as usize / FR_BYTES_STORED;
191 let expected_size = chunks + (stray != 0) as usize;
192 let mut bytes_from =
193 |slice: &mut Vec<AssignedByte<outer::Scalar>>,
194 k,
195 f: AssignedNative<outer::Scalar>| {
196 let repr = std.assigned_to_le_bytes(layouter, &f, Some(k))?;
197 slice.extend(repr[..k].iter().cloned());
198 Ok::<_, Error>(())
199 };
200 if inputs.len() < expected_size {
201 return Err(Error::Synthesis(
202 "cannot decode bytes from to little data".into(),
203 ));
204 }
205 let mut res_vec = Vec::with_bounded_capacity(*length as usize - stray);
206 if stray > 0 {
207 bytes_from(&mut res_vec, stray, inputs[0].clone())?;
208 *inputs = &inputs[1..];
209 }
210 for i in 0..chunks {
211 bytes_from(res, FR_BYTES_STORED, inputs[chunks - 1 - i].clone())?;
212 }
213 *inputs = &inputs[chunks..];
214 res.extend(res_vec);
215 Ok(())
216 }
217 AlignmentAtom::Compress => {
218 error!("Cannot decode compressed value from field elements");
219 Err(Error::Synthesis(
220 "Cannot decode compressed value from field elements".into(),
221 ))
222 }
223 }
224}
225
226impl IrSource {
227 pub(crate) fn preprocess(
230 &self,
231 preimage: &ProofPreimage,
232 ) -> Result<Preprocessed, ProvingError> {
233 let mut memory: HashMap<Identifier, IrValue> = HashMap::new();
234
235 let mut idx = 0;
236 for input_id in self.inputs.iter() {
237 let w = input_id.val_t.encoded_len();
238 if idx + w > preimage.inputs.len() {
239 bail!(
240 "Not enough raw inputs: ran out at index {} while decoding {:?}",
241 idx,
242 input_id.name
243 );
244 }
245 let value = decode_offcircuit(&preimage.inputs[idx..idx + w], &input_id.val_t)?;
246 memory.insert(input_id.name.clone(), value);
247 idx += w;
248 }
249 if idx != preimage.inputs.len() {
250 bail!(
251 "Expected {} raw inputs, received {}",
252 idx,
253 preimage.inputs.len()
254 );
255 }
256
257 let mut pis = vec![preimage.binding_input];
258 if self.do_communications_commitment {
259 pis.push(
260 preimage
261 .communications_commitment
262 .ok_or_else(|| anyhow!("Expected communications commitment"))?
263 .0,
264 );
265 }
266 let mut pi_skips = Vec::new();
267 let mut public_transcript_inputs_idx: usize = 0;
268 let mut public_transcript_outputs_idx: usize = 0;
269 let mut private_transcript_outputs_idx: usize = 0;
270 let mut outputs = Vec::new();
271 let idx = |memory: &HashMap<Identifier, IrValue>, id: &Identifier| {
272 let res = memory
273 .get(id)
274 .cloned()
275 .ok_or_else(|| anyhow!("variable not found: {:?}", id));
276 trace!(?res, "retrieved from {:?}", id);
277 res
278 };
279 let resolve_operand =
280 |memory: &HashMap<Identifier, IrValue>, operand: &Operand| match operand {
281 Operand::Variable(id) => idx(memory, id),
282 Operand::Immediate(imm) => Ok(IrValue::Native(*imm)),
283 };
284 let resolve_operand_bool = |memory: &HashMap<Identifier, IrValue>, operand: &Operand| {
285 resolve_operand(memory, operand).and_then(|val| {
286 let val: Fr = val.try_into()?;
287 if val == 0.into() {
288 Ok(false)
289 } else if val == 1.into() {
290 Ok(true)
291 } else {
292 bail!("Expected boolean, found: {val:?}");
293 }
294 })
295 };
296
297 let resolve_bool_list = |memory: &HashMap<Identifier, IrValue>,
298 operands: &[Operand]|
299 -> Result<Vec<bool>, anyhow::Error> {
300 if operands.is_empty() {
301 bail!("Boolean gate requires at least one input");
302 }
303 operands
304 .iter()
305 .map(|op| {
306 let val = resolve_operand(memory, op)?;
307 let t = val.get_type();
308 bool::try_from(val)
309 .map_err(|_| anyhow!("Boolean gate expects Bool inputs, found {t:?}"))
310 })
311 .collect()
312 };
313
314 let resolve_operand_bits =
315 |memory: &HashMap<Identifier, IrValue>, operand: &Operand, constrain: Option<u32>| {
316 resolve_operand(memory, operand).and_then(|val| {
317 let val: Fr = val.try_into()?;
318 let mut bits = val
319 .0
320 .to_bytes_le()
321 .into_iter()
322 .flat_map(|byte| {
323 [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]
324 .into_iter()
325 .map(move |mask| byte & mask != 0)
326 })
327 .collect::<Vec<_>>();
328 if let Some(n) = constrain {
329 if n as usize >= FR_BITS {
330 bail!("Excessive bit bound");
331 }
332 if bits[n as usize..].iter().any(|b| *b) {
333 bail!("Bit bound failed: {val:?} is not {n}-bit");
334 }
335 bits.truncate(n as usize);
336 }
337 Ok(bits)
338 })
339 };
340
341 fn from_bits<I: DoubleEndedIterator<Item = bool>>(bits: I) -> Fr {
342 bits.rev()
343 .fold(0.into(), |acc, bit| acc * 2.into() + bit.into())
344 }
345 for ins in self.instructions.iter() {
346 trace!(?ins, "preprocess gate");
347 match ins {
348 I::Encode { input, outputs } => {
349 let val = resolve_operand(&memory, input)?;
350 let encoded = encode_offcircuit(&val);
351 if encoded.len() != outputs.len() {
352 return Err(anyhow::Error::msg(format!(
353 "Unexpected output length of encode instruction: {:?}",
354 val.get_type()
355 )));
356 }
357 for (out_id, enc_val) in outputs.iter().zip(encoded) {
358 memory.insert(out_id.clone(), enc_val);
359 }
360 }
361 I::Add { a, b, output } => {
362 let a = resolve_operand(&memory, a)?;
363 let b = resolve_operand(&memory, b)?;
364 let result = add_offcircuit(&a, &b)?;
365 memory.insert(output.clone(), result);
366 }
367 I::Mul { a, b, output } => {
368 let a = resolve_operand(&memory, a)?;
369 let b = resolve_operand(&memory, b)?;
370 let result = mul_offcircuit(&a, &b)?;
371 memory.insert(output.clone(), result);
372 }
373 I::Neg { a, output } => {
374 let a = resolve_operand(&memory, a)?;
375 let result = neg_offcircuit(&a)?;
376 memory.insert(output.clone(), result);
377 }
378 I::Inv { a, output } => {
379 let a = resolve_operand(&memory, a)?;
380 let result = inv_offcircuit(&a)?;
381 memory.insert(output.clone(), result);
382 }
383 I::Not { a, output } => {
384 let result = IrValue::Native((!resolve_operand_bool(&memory, a)?).into());
385 memory.insert(output.clone(), result);
386 }
387 I::And { inputs, output } => {
388 let result = resolve_bool_list(&memory, inputs)?.into_iter().all(|b| b);
389 memory.insert(output.clone(), IrValue::Bool(result));
390 }
391 I::Or { inputs, output } => {
392 let result = resolve_bool_list(&memory, inputs)?.into_iter().any(|b| b);
393 memory.insert(output.clone(), IrValue::Bool(result));
394 }
395 I::Xor { inputs, output } => {
396 let result = resolve_bool_list(&memory, inputs)?
397 .into_iter()
398 .fold(false, |acc, b| acc ^ b);
399 memory.insert(output.clone(), IrValue::Bool(result));
400 }
401 I::ConstrainEq { a, b } => {
402 let a = resolve_operand(&memory, a)?;
403 let b = resolve_operand(&memory, b)?;
404 constrain_eq_offcircuit(&a, &b)?;
405 }
406 I::CondSelect { bit, a, b, output } => {
407 let bit_val = resolve_operand_bool(&memory, bit)?;
408 let a_val = resolve_operand(&memory, a)?;
409 let b_val = resolve_operand(&memory, b)?;
410 memory.insert(output.clone(), select_offcircuit(bit_val, &a_val, &b_val)?);
411 }
412 I::Assert { cond } => {
413 if !resolve_operand_bool(&memory, cond)? {
414 bail!("Failed direct assertion");
415 }
416 }
417 I::TestEq { a, b, output } => {
418 let a = resolve_operand(&memory, a)?;
419 let b = resolve_operand(&memory, b)?;
420 let result = test_eq_offcircuit(&a, &b)?;
421 memory.insert(output.clone(), IrValue::Native(result.into()));
422 }
423 I::PublicInput {
424 guard,
425 val_t,
426 output,
427 } => {
428 let val = match guard {
429 Some(guard) if !resolve_operand_bool(&memory, guard)? => {
430 IrValue::default(val_t)
431 }
432 _ => {
433 let w = val_t.encoded_len();
434 let raw_outputs = &preimage.public_transcript_outputs
435 [public_transcript_outputs_idx..public_transcript_outputs_idx + w];
436 public_transcript_outputs_idx += w;
437 decode_offcircuit(raw_outputs, val_t)?
438 }
439 };
440 memory.insert(output.clone(), val);
441 }
442 I::PrivateInput {
443 guard,
444 val_t,
445 output,
446 } => {
447 let val = match guard {
448 Some(guard) if !resolve_operand_bool(&memory, guard)? => {
449 IrValue::default(val_t)
450 }
451 _ => {
452 let w = val_t.encoded_len();
453 let raw_outputs = &preimage.private_transcript
454 [private_transcript_outputs_idx
455 ..private_transcript_outputs_idx + w];
456 private_transcript_outputs_idx += w;
457 decode_offcircuit(raw_outputs, val_t)?
458 }
459 };
460 memory.insert(output.clone(), val);
461 }
462 I::Copy { val, output } => {
463 let val = resolve_operand(&memory, val)?;
464 memory.insert(output.clone(), val);
465 }
466 I::ConstrainToBoolean { val } => drop(resolve_operand_bool(&memory, val)?),
467 I::ConstrainBits { val, bits } => {
468 drop(resolve_operand_bits(&memory, val, Some(*bits))?)
469 }
470 I::DivModPowerOfTwo { val, bits, outputs } => {
471 if outputs.len() != 2 {
472 bail!("DivModPowerOfTwo requires exactly 2 outputs");
473 }
474 if *bits as usize > FR_BYTES_STORED * 8 {
475 bail!("Excessive bit count");
476 }
477 let val_bits = resolve_operand_bits(&memory, val, None)?;
478 memory.insert(
479 outputs[0].clone(),
480 IrValue::Native(from_bits(val_bits[*bits as usize..].iter().copied())),
481 );
482 memory.insert(
483 outputs[1].clone(),
484 IrValue::Native(from_bits(val_bits[..*bits as usize].iter().copied())),
485 );
486 }
487 I::ReconstituteField {
488 divisor,
489 modulus,
490 bits,
491 output,
492 } => {
493 if *bits as usize > FR_BYTES_STORED * 8 {
494 bail!("Excessive bit count");
495 }
496 let fr_max = Fr::from(-1);
497 let max_bits: Vec<bool> = fr_max
498 .0
499 .to_bytes_le()
500 .into_iter()
501 .flat_map(|byte| {
502 [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]
503 .into_iter()
504 .map(move |mask| byte & mask != 0)
505 })
506 .collect();
507 let modulus_bits = resolve_operand_bits(&memory, modulus, Some(*bits))?;
508 let divisor_bits =
509 resolve_operand_bits(&memory, divisor, Some(FR_BITS as u32 - *bits))?;
510 let cmp = modulus_bits
511 .iter()
512 .chain(divisor_bits.iter())
513 .rev()
514 .zip(max_bits[..FR_BITS].iter().rev())
515 .map(|(ab, max)| ab.cmp(max))
516 .fold(
517 Ordering::Equal,
518 |prefix, local| if prefix.is_eq() { local } else { prefix },
519 );
520 if cmp.is_gt() {
521 bail!("Reconstituted element overflows field");
522 }
523 let power = (0..*bits).fold(Fr::from(1), |acc, _| Fr::from(2) * acc);
524 let modulus: Fr = resolve_operand(&memory, modulus)?.try_into()?;
525 let divisor: Fr = resolve_operand(&memory, divisor)?.try_into()?;
526 let result = IrValue::Native(power * divisor + modulus);
527 memory.insert(output.clone(), result);
528 }
529 I::LessThan { a, b, bits, output } => {
530 let result =
531 (from_bits(resolve_operand_bits(&memory, a, Some(*bits))?.into_iter())
532 < from_bits(
533 resolve_operand_bits(&memory, b, Some(*bits))?.into_iter(),
534 ))
535 .into();
536 memory.insert(output.clone(), IrValue::Native(result));
537 }
538 I::JubjubScalarFromNative { native, output } => {
539 let x: Fr = resolve_operand(&memory, native)?.try_into()?;
540 let s = native_to_jubjub_scalar(&x);
541 memory.insert(output.clone(), IrValue::JubjubScalar(s));
542 }
543 I::TransientHash { inputs, output } => {
544 let result = transient_hash(
545 &inputs
546 .iter()
547 .map(|i| resolve_operand(&memory, i))
548 .map(|r| r.and_then(|v| v.try_into()))
549 .collect::<Result<Vec<Fr>, _>>()?,
550 );
551 memory.insert(output.clone(), IrValue::Native(result));
552 }
553 I::PersistentHash {
554 alignment,
555 inputs,
556 output,
557 }
558 | I::Keccak256 {
559 alignment,
560 inputs,
561 output,
562 }
563 | I::Sha512 {
564 alignment,
565 inputs,
566 output,
567 } => {
568 let inputs = inputs
569 .iter()
570 .map(|i| resolve_operand(&memory, i))
571 .map(|r| r.and_then(|v| v.try_into()))
572 .collect::<Result<Vec<_>, _>>()?;
573 let value = alignment.parse_field_repr(&inputs).ok_or_else(|| {
574 error!("Inputs did not match alignment (inputs: {inputs:?}, alignment: {alignment:?})");
575 anyhow!("Inputs did not match alignment (inputs: {inputs:?}, alignment: {alignment:?})")
576 })?;
577 let mut repr = Vec::new();
578 ValueReprAlignedValue(value).binary_repr(&mut repr);
579 trace!(bytes = ?repr, "bytes decoded out-of-circuit");
580 let hash_output: Vec<u8> = match ins {
581 I::PersistentHash { .. } => Sha256::digest(&repr).to_vec(),
582 I::Keccak256 { .. } => Keccak256::digest(&repr).to_vec(),
583 I::Sha512 { .. } => Sha512::digest(&repr).to_vec(),
584 _ => unreachable!(),
585 };
586 memory.insert(output.clone(), IrValue::Bytes(hash_output));
587 }
588 I::Impact { guard, inputs } => {
589 let count = inputs.len();
590 if !resolve_operand_bool(&memory, guard)? {
591 for _ in inputs {
595 pis.push(0.into());
596 }
597 pi_skips.push(Some(count));
598 } else {
599 for input in inputs {
600 let x: Fr = resolve_operand(&memory, input)?.try_into()?;
601 pis.push(x);
602 public_transcript_inputs_idx += 1;
603 }
604 pi_skips.push(None);
605 for i in 0..count {
606 let idx = public_transcript_inputs_idx - count + i;
607 let expected = preimage.public_transcript_inputs.get(idx).copied();
608 let computed = Some(pis[pis.len() - count + i]);
609 if expected != computed {
610 error!(
611 ?idx,
612 ?expected,
613 ?computed,
614 ?memory,
615 ?pis,
616 "Public transcript input mismatch"
617 );
618 bail!(
619 "Public transcript input mismatch for input {idx}; expected: {expected:?}, computed: {computed:?}"
620 );
621 }
622 }
623 }
624 }
625 I::HashToCurve { inputs, output } => {
626 let inputs = inputs
627 .iter()
628 .map(|var| resolve_operand(&memory, var))
629 .map(|r| r.and_then(|v| v.try_into()))
630 .collect::<Result<Vec<Fr>, _>>()?;
631 let point = hash_to_curve(&inputs);
632 memory.insert(output.clone(), IrValue::JubjubPoint(point.0));
633 }
634 I::EcMul { a, scalar, output } => {
635 let p = resolve_operand(&memory, a)?;
636 let s = resolve_operand(&memory, scalar)?;
637 let r = ec_mul_offcircuit(&p, &s)?;
638 memory.insert(output.clone(), r);
639 }
640 I::EcMulGenerator { scalar, output } => {
641 let s = resolve_operand(&memory, scalar)?;
642 let p = match s.get_type() {
643 IrType::JubjubScalar => IrValue::JubjubPoint(JubjubSubgroup::generator()),
644 IrType::Secp256k1Scalar => IrValue::Secp256k1Point(k256::K256::generator()),
645 IrType::Secp256r1Scalar => IrValue::Secp256r1Point(p256::P256::generator()),
646 IrType::Curve25519Scalar => IrValue::Curve25519Point(
647 curve25519::Curve25519Subgroup::generator(),
648 ),
649 t => bail!("Unsupported EcMulGenerator for scalar of type {t:?}"),
650 };
651 let r = ec_mul_offcircuit(&p, &s)?;
652 memory.insert(output.clone(), r);
653 }
654 I::IntoCoordinates { point, outputs } => {
655 let p = resolve_operand(&memory, point)?;
656 let coordinates = into_coordinates_offcircuit(&p)?;
657 memory.insert(outputs.0.clone(), coordinates.0);
658 memory.insert(outputs.1.clone(), coordinates.1);
659 }
660 I::FromCoordinates { inputs, output } => {
661 let x = resolve_operand(&memory, &inputs.0)?;
662 let y = resolve_operand(&memory, &inputs.1)?;
663 let p = from_coordinates_offcircuit(&x, &y)?;
664 memory.insert(output.clone(), p);
665 }
666 I::ToBytes { input, output } => {
667 let x = resolve_operand(&memory, input)?;
668 let bytes = to_bytes_offcircuit(&x)?;
669 memory.insert(output.clone(), bytes);
670 }
671 I::IntoBytes32 { input, output } => {
672 let x = resolve_operand(&memory, input)?;
675 let bytes = ir_value_to_bytes32(to_bytes_offcircuit(&x)?)?;
676 memory.insert(output.clone(), IrValue::Bytes(bytes.to_vec()));
677 }
678 I::FromBytes {
679 val_t,
680 bytes,
681 output,
682 } => {
683 let bytes: Vec<u8> = resolve_operand(&memory, bytes)?.try_into()?;
684 let x = from_bytes_offcircuit(val_t, &bytes)?;
685 memory.insert(output.clone(), x);
686 }
687 I::FromBytes32 {
688 val_t,
689 bytes,
690 output,
691 } => {
692 let bytes = ir_value_to_bytes32(resolve_operand(&memory, bytes)?)?;
695 let x = from_bytes_offcircuit(val_t, &bytes)?;
696 memory.insert(output.clone(), x);
697 }
698 I::Reverse { bytes, output } | I::ReverseBytes { bytes, output } => {
699 let bytes = resolve_operand(&memory, bytes)?;
702 let mut bytes: Vec<u8> = bytes.try_into()?;
703 bytes.reverse();
704 memory.insert(output.clone(), IrValue::Bytes(bytes));
705 }
706 I::Slice {
707 bytes,
708 start,
709 len,
710 output,
711 } => {
712 let bs: Vec<u8> = resolve_operand(&memory, bytes)?.try_into()?;
713 let (s, l) = (*start as usize, *len as usize);
714 if l == 0 {
715 bail!("slice length must be at least 1");
716 }
717 let end = s
718 .checked_add(l)
719 .filter(|end| *end <= bs.len())
720 .ok_or_else(|| {
721 anyhow!("slice out of bounds: {s}..{s}+{l} into Bytes<{}>", bs.len())
722 })?;
723 memory.insert(output.clone(), IrValue::Bytes(bs[s..end].to_vec()));
724 }
725 I::BytesIntoNatives { bytes, outputs } => {
726 let value = resolve_operand(&memory, bytes)?;
727 if !matches!(value, IrValue::Bytes(_)) {
728 bail!(
729 "BytesIntoNatives expects a Bytes input, found {:?}",
730 value.get_type()
731 );
732 }
733 let encoded = encode_offcircuit(&value);
734 if encoded.len() != outputs.len() {
735 bail!(
736 "BytesIntoNatives: {:?} packs into {} field elements but the instruction has {} outputs",
737 value.get_type(),
738 encoded.len(),
739 outputs.len()
740 );
741 }
742 for (out_id, enc_val) in outputs.iter().zip(encoded) {
743 memory.insert(out_id.clone(), enc_val);
744 }
745 }
746 I::BytesFromNatives {
747 inputs,
748 len,
749 output,
750 } => {
751 let nb_limbs = bytes_from_natives_nb_limbs(*len, inputs.len())
752 .map_err(anyhow::Error::msg)?;
753 let encoded = inputs
754 .iter()
755 .map(|op| Fr::try_from(resolve_operand(&memory, op)?))
756 .collect::<Result<Vec<_>, _>>()?;
757 let value =
758 decode_offcircuit(&encoded, &IrType::Bytes(*len)).map_err(|_| {
759 anyhow!(
760 "BytesFromNatives: every input must fit in the number of bytes it \
761 contributes to the output ({BYTES_PER_FIELD_ELEMENT} bytes, \
762 except the last one, which contributes {})",
763 *len as usize - BYTES_PER_FIELD_ELEMENT * (nb_limbs - 1)
764 )
765 })?;
766 memory.insert(output.clone(), value);
767 }
768 I::Bytes32IntoLowHigh { bytes, outputs } => {
769 let bytes = resolve_operand(&memory, bytes)?;
770 let mut bytes = ir_value_to_bytes32(bytes)?;
771 let high = IrValue::Native(Fr::from(bytes[31]));
772 bytes[31] = 0;
773 let low = from_bytes_offcircuit(&IrType::Native, &bytes)?;
774 memory.insert(outputs.0.clone(), low);
775 memory.insert(outputs.1.clone(), high);
776 }
777 I::Bytes32FromLowHigh { inputs, output } => {
778 let low = resolve_operand(&memory, &inputs.0)?;
779 let high = resolve_operand(&memory, &inputs.1)?;
780 let bytes_low = ir_value_to_bytes32(to_bytes_offcircuit(&low)?)?;
781 let bytes_high = ir_value_to_bytes32(to_bytes_offcircuit(&high)?)?;
782 if bytes_low[31] != 0 || bytes_high[1..].iter().any(|b| *b != 0) {
783 bail!(
784 "Bytes32FromLowHigh: low operand must fit in 31 bytes (be less than 2^248) and high operand must fit in a single byte (be less than 256)"
785 );
786 }
787 let mut out_bytes = bytes_low;
788 out_bytes[31] = bytes_high[0];
789 memory.insert(output.clone(), IrValue::Bytes(out_bytes.to_vec()));
790 }
791 I::Nth {
792 bytes,
793 index,
794 output,
795 } => {
796 let bs: Vec<u8> = resolve_operand(&memory, bytes)?.try_into()?;
797 let k = *index as usize;
798 if k >= bs.len() {
799 bail!("nth out of bounds: index {k} into Bytes<{}>", bs.len());
800 }
801 memory.insert(output.clone(), IrValue::Byte(bs[k]));
802 }
803 I::Concat { inputs, output } => {
804 let mut bytes = vec![];
805 for op in inputs {
806 match resolve_operand(&memory, op)? {
807 IrValue::Byte(b) => bytes.push(b),
808 IrValue::Bytes(bs) => bytes.extend(bs),
809 other => bail!(
810 "Concat expects Byte or Bytes inputs, found {:?}",
811 other.get_type()
812 ),
813 }
814 }
815 if bytes.is_empty() {
816 bail!("Concat requires at least one byte of input");
817 }
818 if bytes.len() > MAX_BYTES_LEN as usize {
819 bail!(
820 "Concat result length {} exceeds MAX_BYTES_LEN ({MAX_BYTES_LEN})",
821 bytes.len()
822 );
823 }
824 memory.insert(output.clone(), IrValue::Bytes(bytes));
825 }
826 I::LoadConstant {
827 val_t,
828 encoding,
829 output,
830 } => {
831 let value = decode_offcircuit(encoding, val_t)?;
832 memory.insert(output.clone(), value);
833 }
834 I::Output { vals } => {
835 if vals.len() != self.outputs.len() {
836 bail!(
837 "Output: signature declares {} return values but instruction has {}",
838 self.outputs.len(),
839 vals.len()
840 );
841 }
842 for (i, (val, expected_t)) in vals.iter().zip(self.outputs.iter()).enumerate() {
843 let value = resolve_operand(&memory, val)?;
844 if value.get_type() != *expected_t {
845 bail!(
846 "Output position {i}: signature declares {:?} but operand has runtime type {:?}",
847 expected_t,
848 value.get_type()
849 );
850 }
851 outputs.push(value);
852 }
853 }
854 }
855 }
856 trace!(?outputs, "Finished instructions with output");
857 if preimage.public_transcript_inputs.len() != public_transcript_inputs_idx
858 || preimage.public_transcript_outputs.len() != public_transcript_outputs_idx
859 || preimage.private_transcript.len() != private_transcript_outputs_idx
860 {
861 error!(
862 public_transcript_inputs = ?preimage.public_transcript_inputs,
863 public_transcript_outputs = ?preimage.public_transcript_outputs,
864 private_transcript_outputs = ?preimage.private_transcript,
865 ?public_transcript_inputs_idx,
866 ?public_transcript_outputs_idx,
867 ?private_transcript_outputs_idx,
868 "Transcripts not fully consumed");
869 bail!("Transcripts not fully consumed");
870 }
871 if self.do_communications_commitment {
872 let comm_comm = preimage
873 .communications_commitment
874 .ok_or_else(|| anyhow!("Expected communications randomness"))?;
875 let mut comm_comm_inputs: Vec<Fr> = Vec::new();
876 comm_comm_inputs.extend(preimage.inputs.iter());
877 for value in outputs.iter() {
878 for ir_val in encode_offcircuit(value) {
879 comm_comm_inputs.push(ir_val.try_into()?);
880 }
881 }
882 if comm_comm.0 != transient_commit(&comm_comm_inputs[..], comm_comm.1) {
883 error!(
884 ?comm_comm,
885 ?comm_comm_inputs,
886 "Communications commitment mismatch"
887 );
888 bail!("Communications commitment mismatch");
889 }
890 }
891 if cfg!(debug_assertions) {
893 let (types, _) = self
894 .types_pass()
895 .expect("types pass failed on a valid circuit");
896 for (id, value) in memory.iter() {
897 assert_eq!(
898 types.get(id),
899 Some(&value.get_type()),
900 "types pass disagrees with preprocess on {id:?}"
901 );
902 }
903 }
904 Ok(Preprocessed {
905 memory,
906 pis: pis.into_iter().map(|x| x.0).collect(),
907 pi_skips,
908 binding_input: preimage.binding_input.0,
909 comm_comm: preimage
910 .communications_commitment
911 .map(|(comm, rand)| (comm.0, rand.0)),
912 })
913 }
914}
915
916impl Relation for IrSource {
917 type Instance = Vec<outer::Scalar>;
918 type Witness = Preprocessed;
919 type Error = midnight_proofs::plonk::Error;
920
921 fn format_instance(
922 instance: &Self::Instance,
923 ) -> Result<Vec<outer::Scalar>, midnight_proofs::plonk::Error> {
924 Ok(instance.clone())
925 }
926
927 fn circuit(
928 &self,
929 std: &ZkStdLib,
930 layouter: &mut impl Layouter<outer::Scalar>,
931 _instance: Value<Self::Instance>,
932 witness: Value<Self::Witness>,
933 ) -> Result<(), Error> {
934 let mut input_values = Vec::new();
935 for id in &self.inputs {
936 let value = witness.as_ref().map(|preproc| {
937 preproc
938 .memory
939 .get(&id.name)
940 .cloned()
941 .unwrap_or_else(|| IrValue::Native(0.into()))
942 });
943 input_values.push(value);
944 }
945
946 let binding_input_value = witness.as_ref().map(|preproc| preproc.binding_input);
947 let comm_comm_value = witness.as_ref().map(|preproc| preproc.comm_comm);
948
949 let mut memory: HashMap<Identifier, CircuitValue> = HashMap::new();
950
951 for (id, value) in self.inputs.iter().zip(input_values) {
952 let assigned = assign_incircuit(std, layouter, &id.val_t, &[value])?[0].clone();
953 memory.insert(id.name.clone(), assigned);
954 }
955
956 let binding_input = std.assign(layouter, binding_input_value)?;
957
958 let mut outputs = Vec::new();
959
960 fn idx<'a>(
961 memory: &'a HashMap<Identifier, CircuitValue>,
962 id: &Identifier,
963 ) -> Result<&'a CircuitValue, Error> {
964 memory
965 .get(id)
966 .ok_or_else(|| Error::Synthesis(format!("value {id:?} not in memory")))
967 }
968
969 fn resolve_operand<'a>(
970 std: &ZkStdLib,
971 layouter: &mut impl Layouter<outer::Scalar>,
972 memory: &'a HashMap<Identifier, CircuitValue>,
973 operand: &'a Operand,
974 ) -> Result<CircuitValue, Error> {
975 match operand {
976 Operand::Variable(id) => idx(memory, id).cloned(),
977 Operand::Immediate(imm) => {
978 std.assign_fixed(layouter, imm.0).map(CircuitValue::Native)
979 }
980 }
981 }
982
983 fn resolve_bit_list(
984 std: &ZkStdLib,
985 layouter: &mut impl Layouter<outer::Scalar>,
986 memory: &HashMap<Identifier, CircuitValue>,
987 operands: &[Operand],
988 ) -> Result<Vec<AssignedBit<outer::Scalar>>, Error> {
989 if operands.is_empty() {
990 return Err(Error::Synthesis(
991 "Boolean gate requires at least one input".into(),
992 ));
993 }
994 operands
995 .iter()
996 .map(|op| {
997 let val = resolve_operand(std, layouter, memory, op)?;
998 AssignedBit::try_from(val)
999 })
1000 .collect()
1001 }
1002
1003 let mem_insert = |id: Identifier,
1004 cell: CircuitValue,
1005 mem: &mut HashMap<Identifier, CircuitValue>|
1006 -> Result<(), Error> {
1007 witness.as_ref()
1012 .zip(cell.value())
1013 .error_if_known_and(|(preproc, v)| {
1014 if let Some(expected) = preproc.memory.get(&id) && *expected != *v {
1015 error!(id = ?id, expected = ?expected, actual = ?v, "Misalignment between `prepare` and `synthesize` runs. This is a bug.");
1016 return true;
1017 }
1018 false
1019 })?;
1020
1021 mem.insert(id, cell);
1022 Ok(())
1023 };
1024
1025 let pi_push = |cell: AssignedNative<outer::Scalar>,
1026 pis: &mut Vec<AssignedNative<outer::Scalar>>|
1027 -> Result<(), Error> {
1028 let idx = pis.len();
1029 witness.as_ref()
1030 .zip(cell.value())
1031 .error_if_known_and(|(preproc, v)| {
1032 if idx < preproc.pis.len() && preproc.pis[idx] != **v {
1033 error!(prepare = ?preproc.pis, ?idx, ?v, "Misalignment between `prepare` and `synthesize` runs. This is a bug.");
1034 true
1035 } else {
1036 false
1037 }
1038 })?;
1039 pis.push(cell);
1040 Ok(())
1041 };
1042
1043 let mut public_inputs = vec![];
1044 pi_push(binding_input, &mut public_inputs)?;
1045
1046 if self.do_communications_commitment {
1047 let comm_comm_value = comm_comm_value.map(|c| {
1048 c.ok_or_else(|| {
1049 error!("Communication commitment not present despite preproc. This is a bug.");
1050 Error::Synthesis("Communication commitment not present despite preproc.".into())
1051 })
1052 .unwrap()
1053 .0
1054 });
1055 let comm_comm = std.assign(layouter, comm_comm_value)?;
1056 pi_push(comm_comm, &mut public_inputs)?;
1057 }
1058 for ins in self.instructions.iter() {
1059 match ins {
1060 I::Encode { input, outputs } => {
1061 let val = resolve_operand(std, layouter, &memory, input)?;
1062 let encoded = encode_incircuit(std, layouter, &val)?;
1063 if encoded.len() != outputs.len() {
1064 return Err(Error::Synthesis(
1065 "Unexpected output length of encode instruction".into(),
1066 ));
1067 }
1068 for (out_id, enc_val) in outputs.iter().zip(encoded) {
1069 mem_insert(out_id.clone(), enc_val, &mut memory)?;
1070 }
1071 }
1072 I::Assert { cond } => {
1073 let cond_val = resolve_operand(std, layouter, &memory, cond)?;
1074 let cond: AssignedNative<_> = cond_val.try_into()?;
1075 std.assert_non_zero(layouter, &cond)?;
1076 }
1077 I::CondSelect { bit, a, b, output } => {
1078 let bit_val = resolve_operand(std, layouter, &memory, bit)?;
1079 let bit: AssignedNative<_> = bit_val.try_into()?;
1080 let bit: AssignedBit<outer::Scalar> = std.convert(layouter, &bit)?;
1081 let a_val = resolve_operand(std, layouter, &memory, a)?;
1082 let b_val = resolve_operand(std, layouter, &memory, b)?;
1083 let result = select_incircuit(std, layouter, &bit, &a_val, &b_val)?;
1084 mem_insert(output.clone(), result, &mut memory)?;
1085 }
1086 I::ConstrainBits { val, bits } => {
1087 let val_assigned = resolve_operand(std, layouter, &memory, val)?;
1088 let x: AssignedNative<_> = val_assigned.try_into()?;
1089 drop(std.assigned_to_le_bits(
1090 layouter,
1091 &x,
1092 Some(*bits as usize),
1093 *bits as usize >= FR_BITS,
1094 )?);
1095 }
1096 I::ConstrainEq { a, b } => {
1097 let a_val = resolve_operand(std, layouter, &memory, a)?;
1098 let b_val = resolve_operand(std, layouter, &memory, b)?;
1099 constrain_eq_incircuit(std, layouter, &a_val, &b_val)?;
1100 }
1101 I::ConstrainToBoolean { val } => {
1102 let val_assigned = resolve_operand(std, layouter, &memory, val)?;
1104 let x: AssignedNative<_> = val_assigned.try_into()?;
1105 let _: AssignedBit<_> = std.convert(layouter, &x)?;
1106 }
1107 I::Copy { val, output } => {
1108 let val = resolve_operand(std, layouter, &memory, val)?;
1109 mem_insert(output.clone(), val, &mut memory)?;
1110 }
1111 I::Impact { guard, inputs } => {
1112 let zero = std.assign_fixed(layouter, outer::Scalar::from(0))?;
1113 let guard: AssignedBit<_> = {
1114 let guard = resolve_operand(std, layouter, &memory, guard)?;
1115 let guard: AssignedNative<_> = guard.try_into()?;
1116 std.convert(layouter, &guard)?
1117 };
1118 for input in inputs {
1119 let val_assigned = resolve_operand(std, layouter, &memory, input)?;
1120 let x: AssignedNative<_> = val_assigned.try_into()?;
1121 let guarded_x = std.select(layouter, &guard, &x, &zero)?;
1122 pi_push(guarded_x, &mut public_inputs)?;
1123 }
1124 }
1125 I::TransientHash { inputs, output } => {
1126 let mut resolved_inputs = Vec::new();
1127 for inp in inputs {
1128 let x = resolve_operand(std, layouter, &memory, inp)?;
1129 let x: AssignedNative<_> = x.try_into()?;
1130 resolved_inputs.push(x);
1131 }
1132 let result = CircuitValue::Native(std.poseidon(layouter, &resolved_inputs)?);
1133 mem_insert(output.clone(), result, &mut memory)?;
1134 }
1135 I::PersistentHash {
1136 alignment,
1137 inputs,
1138 output,
1139 }
1140 | I::Keccak256 {
1141 alignment,
1142 inputs,
1143 output,
1144 }
1145 | I::Sha512 {
1146 alignment,
1147 inputs,
1148 output,
1149 } => {
1150 let mut resolved_inputs = Vec::new();
1151 for inp in inputs {
1152 let x = resolve_operand(std, layouter, &memory, inp)?;
1153 let x: AssignedNative<_> = x.try_into()?;
1154 resolved_inputs.push(x);
1155 }
1156 let inputs = resolved_inputs;
1157 let bytes = fab_decode_to_bytes(std, layouter, alignment, &inputs)?;
1158 let hash_output = match ins {
1159 I::PersistentHash { .. } => std.sha2_256(layouter, &bytes)?.to_vec(),
1160 I::Keccak256 { .. } => std.keccak_256(layouter, &bytes)?.to_vec(),
1161 I::Sha512 { .. } => std.sha2_512(layouter, &bytes)?.to_vec(),
1162 _ => unreachable!(),
1163 };
1164 mem_insert(
1165 output.clone(),
1166 CircuitValue::Bytes(hash_output),
1167 &mut memory,
1168 )?;
1169 }
1170 I::TestEq { a, b, output } => {
1171 let a_val = resolve_operand(std, layouter, &memory, a)?;
1172 let b_val = resolve_operand(std, layouter, &memory, b)?;
1173 let bit = test_eq_incircuit(std, layouter, &a_val, &b_val)?;
1174 let result = CircuitValue::Native(std.convert(layouter, &bit)?);
1175 mem_insert(output.clone(), result, &mut memory)?;
1176 }
1177 I::Add { a, b, output } => {
1178 let a_val = resolve_operand(std, layouter, &memory, a)?;
1179 let b_val = resolve_operand(std, layouter, &memory, b)?;
1180 let result = add_incircuit(std, layouter, &a_val, &b_val)?;
1181 mem_insert(output.clone(), result, &mut memory)?;
1182 }
1183 I::Mul { a, b, output } => {
1184 let a_val = resolve_operand(std, layouter, &memory, a)?;
1185 let b_val = resolve_operand(std, layouter, &memory, b)?;
1186 let result = mul_incircuit(std, layouter, &a_val, &b_val)?;
1187 mem_insert(output.clone(), result, &mut memory)?;
1188 }
1189 I::Neg { a, output } => {
1190 let a_val = resolve_operand(std, layouter, &memory, a)?;
1191 let result = neg_incircuit(std, layouter, &a_val)?;
1192 mem_insert(output.clone(), result, &mut memory)?;
1193 }
1194 I::Inv { a, output } => {
1195 let a_val = resolve_operand(std, layouter, &memory, a)?;
1196 let result = inv_incircuit(std, layouter, &a_val)?;
1197 mem_insert(output.clone(), result, &mut memory)?;
1198 }
1199 I::Not { a, output } => {
1200 let a_val = resolve_operand(std, layouter, &memory, a)?;
1201 let a: AssignedNative<_> = a_val.try_into()?;
1202 let bit: AssignedBit<_> = std.convert(layouter, &a)?;
1203 let neg_bit = std.not(layouter, &bit)?;
1204 let result = CircuitValue::Native(std.convert(layouter, &neg_bit)?);
1205 mem_insert(output.clone(), result, &mut memory)?;
1206 }
1207 I::And { inputs, output } => {
1208 let bits = resolve_bit_list(std, layouter, &memory, inputs)?;
1209 let result = CircuitValue::Bool(std.and(layouter, &bits)?);
1210 mem_insert(output.clone(), result, &mut memory)?;
1211 }
1212 I::Or { inputs, output } => {
1213 let bits = resolve_bit_list(std, layouter, &memory, inputs)?;
1214 let result = CircuitValue::Bool(std.or(layouter, &bits)?);
1215 mem_insert(output.clone(), result, &mut memory)?;
1216 }
1217 I::Xor { inputs, output } => {
1218 let bits = resolve_bit_list(std, layouter, &memory, inputs)?;
1219 let result = CircuitValue::Bool(std.xor(layouter, &bits)?);
1220 mem_insert(output.clone(), result, &mut memory)?;
1221 }
1222 I::LessThan { a, b, bits, output } => {
1223 let a_val = resolve_operand(std, layouter, &memory, a)?;
1226 let b_val = resolve_operand(std, layouter, &memory, b)?;
1227 let a: AssignedNative<_> = a_val.try_into()?;
1228 let b: AssignedNative<_> = b_val.try_into()?;
1229 let bit = std.lower_than(layouter, &a, &b, u32::max(*bits + *bits % 2, 4))?;
1230 let result = CircuitValue::Native(std.convert(layouter, &bit)?);
1231 mem_insert(output.clone(), result, &mut memory)?;
1232 }
1233 I::JubjubScalarFromNative { native, output } => {
1234 let x: AssignedNative<_> =
1235 resolve_operand(std, layouter, &memory, native)?.try_into()?;
1236 let x_bytes = std.assigned_to_le_bytes(layouter, &x, None)?;
1237 let x_big = std.biguint().from_le_bytes(layouter, &x_bytes)?;
1238 let s = jubjub_scalar_from_biguint(std, layouter, x_big)?;
1239 mem_insert(output.clone(), CircuitValue::JubjubScalar(s), &mut memory)?;
1240 }
1241 I::PublicInput {
1242 guard: _,
1243 val_t,
1244 output,
1245 }
1246 | I::PrivateInput {
1247 guard: _,
1248 val_t,
1249 output,
1250 } => {
1251 let value = witness.as_ref().map_with_result(|preproc| {
1252 preproc.memory.get(output).cloned().ok_or_else(|| {
1253 Error::Synthesis(format!(
1254 "Output {:?} not found in witness memory",
1255 output
1256 ))
1257 })
1258 })?;
1259
1260 mem_insert(
1261 output.clone(),
1262 assign_incircuit(std, layouter, val_t, &[value])?[0].clone(),
1263 &mut memory,
1264 )?;
1265 }
1266 I::DivModPowerOfTwo { val, bits, outputs } => {
1267 if outputs.len() != 2 {
1268 return Err(Error::Synthesis(
1269 "Unexpected output length of DivModPowerOfTwo instruction".into(),
1270 ));
1271 }
1272 let val = resolve_operand(std, layouter, &memory, val)?;
1273 let val: AssignedNative<_> = val.try_into()?;
1274 let val_bits = std.assigned_to_le_bits(layouter, &val, None, true)?;
1275 let modulus = CircuitValue::Native(
1276 std.assigned_from_le_bits(layouter, &val_bits[..*bits as usize])?,
1277 );
1278
1279 let divisor = CircuitValue::Native(
1280 std.assigned_from_le_bits(layouter, &val_bits[*bits as usize..])?,
1281 );
1282
1283 mem_insert(outputs[0].clone(), divisor, &mut memory)?;
1284 mem_insert(outputs[1].clone(), modulus, &mut memory)?;
1285 }
1286 I::ReconstituteField {
1287 divisor,
1288 modulus,
1289 bits,
1290 output,
1291 } => {
1292 let divisor_val = resolve_operand(std, layouter, &memory, divisor)?;
1293 let modulus_val = resolve_operand(std, layouter, &memory, modulus)?;
1294 let divisor: AssignedNative<_> = divisor_val.try_into()?;
1295 let modulus: AssignedNative<_> = modulus_val.try_into()?;
1296
1297 use group::ff::Field;
1298 let result_val = divisor.value().zip(modulus.value()).map(|(d, m)| {
1299 let two_pow_bits = outer::Scalar::from(2).pow([*bits as u64]);
1300 *d * two_pow_bits + *m
1301 });
1302 let result = std.assign(layouter, result_val)?;
1303
1304 let result_bits = std.assigned_to_le_bits(layouter, &result, None, true)?;
1309 let (modulus_bits, divisor_bits) = result_bits.split_at(*bits as usize);
1310 let modulus_check = std.assigned_from_le_bits(layouter, modulus_bits)?;
1311 let divisor_check = std.assigned_from_le_bits(layouter, divisor_bits)?;
1312 std.assert_equal(layouter, &modulus_check, &modulus)?;
1313 std.assert_equal(layouter, &divisor_check, &divisor)?;
1314
1315 mem_insert(output.clone(), CircuitValue::Native(result), &mut memory)?;
1316 }
1317 I::EcMul { a, scalar, output } => {
1318 let p = resolve_operand(std, layouter, &memory, a)?;
1319 let s = resolve_operand(std, layouter, &memory, scalar)?;
1320 let r = ec_mul_incircuit(std, layouter, &p, &s)?;
1321 mem_insert(output.clone(), r, &mut memory)?;
1322 }
1323 I::EcMulGenerator { scalar, output } => {
1324 let s = resolve_operand(std, layouter, &memory, scalar)?;
1325 let p = match s.get_type() {
1326 IrType::JubjubScalar => CircuitValue::JubjubPoint(
1327 std.jubjub()
1328 .assign_fixed(layouter, JubjubSubgroup::generator())?,
1329 ),
1330 IrType::Secp256k1Scalar => CircuitValue::Secp256k1Point(
1331 std.secp256k1()
1332 .assign_fixed(layouter, k256::K256::generator())?,
1333 ),
1334 IrType::Secp256r1Scalar => CircuitValue::Secp256r1Point(
1335 std.p256().assign_fixed(layouter, p256::P256::generator())?,
1336 ),
1337 IrType::Curve25519Scalar => CircuitValue::Curve25519Point(
1338 std.curve25519().assign_fixed(
1339 layouter,
1340 curve25519::Curve25519Subgroup::generator(),
1341 )?,
1342 ),
1343 t => {
1344 return Err(Error::Synthesis(format!(
1345 "Unsupported EcMulGenerator for scalar of type {t:?}"
1346 )));
1347 }
1348 };
1349 let r = ec_mul_incircuit(std, layouter, &p, &s)?;
1350 mem_insert(output.clone(), r, &mut memory)?;
1351 }
1352 I::HashToCurve { inputs, output } => {
1353 let mut resolved_inputs = Vec::new();
1354 for inp in inputs {
1355 let x = resolve_operand(std, layouter, &memory, inp)?;
1356 let x: AssignedNative<_> = x.try_into()?;
1357 resolved_inputs.push(x);
1358 }
1359 let point = std.hash_to_curve(layouter, &resolved_inputs)?;
1360 mem_insert(
1361 output.clone(),
1362 CircuitValue::JubjubPoint(point),
1363 &mut memory,
1364 )?;
1365 }
1366 I::IntoCoordinates { point, outputs } => {
1367 let p = resolve_operand(std, layouter, &memory, point)?;
1368 let coordinates = into_coordinates_incircuit(std, layouter, &p)?;
1369 mem_insert(outputs.0.clone(), coordinates.0, &mut memory)?;
1370 mem_insert(outputs.1.clone(), coordinates.1, &mut memory)?;
1371 }
1372 I::FromCoordinates { inputs, output } => {
1373 let x = resolve_operand(std, layouter, &memory, &inputs.0)?;
1374 let y = resolve_operand(std, layouter, &memory, &inputs.1)?;
1375 let p = from_coordinates_incircuit(std, layouter, &x, &y)?;
1376 mem_insert(output.clone(), p, &mut memory)?;
1377 }
1378 I::ToBytes { input, output } => {
1379 let x = resolve_operand(std, layouter, &memory, input)?;
1380 let bytes = to_bytes_incircuit(std, layouter, &x)?;
1381 mem_insert(output.clone(), bytes, &mut memory)?;
1382 }
1383 I::IntoBytes32 { input, output } => {
1384 let x = resolve_operand(std, layouter, &memory, input)?;
1387 let bytes = circuit_value_to_bytes32(to_bytes_incircuit(std, layouter, &x)?)?;
1388 mem_insert(
1389 output.clone(),
1390 CircuitValue::Bytes(bytes.to_vec()),
1391 &mut memory,
1392 )?;
1393 }
1394 I::FromBytes {
1395 val_t,
1396 bytes,
1397 output,
1398 } => {
1399 let bytes: Vec<AssignedByte<outer::Scalar>> =
1400 resolve_operand(std, layouter, &memory, bytes)?.try_into()?;
1401 let x = from_bytes_incircuit(std, layouter, val_t, &bytes)?;
1402 memory.insert(output.clone(), x);
1403 }
1404 I::FromBytes32 {
1405 val_t,
1406 bytes,
1407 output,
1408 } => {
1409 let bytes =
1412 circuit_value_to_bytes32(resolve_operand(std, layouter, &memory, bytes)?)?;
1413 let x = from_bytes_incircuit(std, layouter, val_t, &bytes)?;
1414 memory.insert(output.clone(), x);
1415 }
1416 I::Reverse { bytes, output } | I::ReverseBytes { bytes, output } => {
1417 let bytes = resolve_operand(std, layouter, &memory, bytes)?;
1420 let mut bytes: Vec<AssignedByte<outer::Scalar>> = bytes.try_into()?;
1421 bytes.reverse();
1422 memory.insert(output.clone(), CircuitValue::Bytes(bytes));
1423 }
1424 I::Slice {
1425 bytes,
1426 start,
1427 len,
1428 output,
1429 } => {
1430 let bs: Vec<AssignedByte<outer::Scalar>> =
1431 resolve_operand(std, layouter, &memory, bytes)?.try_into()?;
1432 let (s, l) = (*start as usize, *len as usize);
1433 if l == 0 {
1434 return Err(Error::Synthesis("slice length must be at least 1".into()));
1435 }
1436 let end = s
1437 .checked_add(l)
1438 .filter(|end| *end <= bs.len())
1439 .ok_or_else(|| {
1440 Error::Synthesis(format!(
1441 "slice out of bounds: {s}..{s}+{l} into Bytes<{}>",
1442 bs.len()
1443 ))
1444 })?;
1445 mem_insert(
1446 output.clone(),
1447 CircuitValue::Bytes(bs[s..end].to_vec()),
1448 &mut memory,
1449 )?;
1450 }
1451 I::BytesIntoNatives { bytes, outputs } => {
1452 let value = resolve_operand(std, layouter, &memory, bytes)?;
1453 if !matches!(value, CircuitValue::Bytes(_)) {
1454 return Err(Error::Synthesis(format!(
1455 "BytesIntoNatives expects a Bytes input, found {:?}",
1456 value.get_type()
1457 )));
1458 }
1459 let encoded = encode_incircuit(std, layouter, &value)?;
1460 if encoded.len() != outputs.len() {
1461 return Err(Error::Synthesis(format!(
1462 "BytesIntoNatives: {:?} packs into {} field elements but the instruction has {} outputs",
1463 value.get_type(),
1464 encoded.len(),
1465 outputs.len()
1466 )));
1467 }
1468 for (out_id, enc_val) in outputs.iter().zip(encoded) {
1469 mem_insert(out_id.clone(), enc_val, &mut memory)?;
1470 }
1471 }
1472 I::BytesFromNatives {
1473 inputs,
1474 len,
1475 output,
1476 } => {
1477 bytes_from_natives_nb_limbs(*len, inputs.len()).map_err(Error::Synthesis)?;
1478 let mut bytes = Vec::with_capacity(*len as usize);
1479 for (i, op) in inputs.iter().enumerate() {
1480 let limb: AssignedNative<_> =
1481 resolve_operand(std, layouter, &memory, op)?.try_into()?;
1482 let nb_bytes = (*len as usize - BYTES_PER_FIELD_ELEMENT * i)
1486 .min(BYTES_PER_FIELD_ELEMENT);
1487 bytes.extend(std.assigned_to_le_bytes(layouter, &limb, Some(nb_bytes))?);
1488 }
1489 mem_insert(output.clone(), CircuitValue::Bytes(bytes), &mut memory)?;
1490 }
1491 I::Bytes32IntoLowHigh { bytes, outputs } => {
1492 let bytes = resolve_operand(std, layouter, &memory, bytes)?;
1493 let mut bytes = circuit_value_to_bytes32(bytes)?;
1494 let high = CircuitValue::Native(std.convert(layouter, &bytes[31])?);
1495 bytes[31] = std.assign_fixed(layouter, 0u8)?;
1496 let low = from_bytes_incircuit(std, layouter, &IrType::Native, &bytes)?;
1497 memory.insert(outputs.0.clone(), low);
1498 memory.insert(outputs.1.clone(), high);
1499 }
1500 I::Bytes32FromLowHigh { inputs, output } => {
1501 let low = resolve_operand(std, layouter, &memory, &inputs.0)?;
1502 let high: AssignedNative<_> =
1503 resolve_operand(std, layouter, &memory, &inputs.1)?.try_into()?;
1504 let bytes_low =
1505 circuit_value_to_bytes32(to_bytes_incircuit(std, layouter, &low)?)?;
1506 std.assert_equal_to_fixed(layouter, &bytes_low[31], 0u8)?;
1507 let mut out_bytes = bytes_low;
1508 out_bytes[31] = std.convert(layouter, &high)?;
1509 memory.insert(output.clone(), CircuitValue::Bytes(out_bytes.to_vec()));
1510 }
1511 I::Nth {
1512 bytes,
1513 index,
1514 output,
1515 } => {
1516 let bs: Vec<AssignedByte<outer::Scalar>> =
1517 resolve_operand(std, layouter, &memory, bytes)?.try_into()?;
1518 let k = *index as usize;
1519 if k >= bs.len() {
1520 return Err(Error::Synthesis(format!(
1521 "nth out of bounds: index {k} into Bytes<{}>",
1522 bs.len()
1523 )));
1524 }
1525 mem_insert(
1526 output.clone(),
1527 CircuitValue::Byte(bs[k].clone()),
1528 &mut memory,
1529 )?;
1530 }
1531 I::Concat { inputs, output } => {
1532 let mut bytes = vec![];
1533 for op in inputs {
1534 match resolve_operand(std, layouter, &memory, op)? {
1535 CircuitValue::Byte(b) => bytes.push(b),
1536 CircuitValue::Bytes(bs) => bytes.extend(bs),
1537 other => {
1538 return Err(Error::Synthesis(format!(
1539 "Concat expects Byte or Bytes inputs, found {:?}",
1540 other.get_type()
1541 )));
1542 }
1543 }
1544 }
1545 if bytes.is_empty() {
1546 return Err(Error::Synthesis(
1547 "Concat requires at least one byte of input".into(),
1548 ));
1549 }
1550 if bytes.len() > MAX_BYTES_LEN as usize {
1551 return Err(Error::Synthesis(format!(
1552 "Concat result length {} exceeds MAX_BYTES_LEN ({MAX_BYTES_LEN})",
1553 bytes.len()
1554 )));
1555 }
1556 mem_insert(output.clone(), CircuitValue::Bytes(bytes), &mut memory)?;
1557 }
1558 I::LoadConstant {
1559 val_t,
1560 encoding,
1561 output,
1562 } => {
1563 let value = decode_offcircuit(encoding, val_t)
1564 .map_err(|e| Error::Synthesis(e.to_string()))?;
1565 let assigned = assign_constant_incircuit(std, layouter, &value)?;
1566 mem_insert(output.clone(), assigned, &mut memory)?;
1567 }
1568 I::Output { vals } => {
1569 if vals.len() != self.outputs.len() {
1570 return Err(Error::Synthesis(format!(
1571 "Output: signature declares {} return values but instruction has {}",
1572 self.outputs.len(),
1573 vals.len()
1574 )));
1575 }
1576 for (i, (val, expected_t)) in vals.iter().zip(self.outputs.iter()).enumerate() {
1577 let value = resolve_operand(std, layouter, &memory, val)?;
1578 if value.get_type() != *expected_t {
1579 return Err(Error::Synthesis(format!(
1580 "Output position {i}: signature declares {:?} but operand has runtime type {:?}",
1581 expected_t,
1582 value.get_type()
1583 )));
1584 }
1585 outputs.push(value);
1586 }
1587 }
1588 }
1589 }
1590 if self.do_communications_commitment {
1591 let comm_comm_rand_value = comm_comm_value.map(|c| {
1592 c.ok_or_else(|| {
1593 error!("Communication commitment not present despite preproc. This is a bug.");
1594 Error::Synthesis("Communication commitment not present despite preproc.".into())
1595 })
1596 .unwrap()
1597 .1
1598 });
1599 let comm_comm_rand = std.assign(layouter, comm_comm_rand_value)?;
1600
1601 let mut preimage = vec![comm_comm_rand];
1602 for id in &self.inputs {
1603 if let Some(val) = memory.get(&id.name) {
1604 for cv in encode_incircuit(std, layouter, val)? {
1605 let x: AssignedNative<_> = cv.try_into()?;
1606 preimage.push(x);
1607 }
1608 }
1609 }
1610
1611 for value in &outputs {
1612 for cv in encode_incircuit(std, layouter, value)? {
1613 let x: AssignedNative<_> = cv.try_into()?;
1614 preimage.push(x);
1615 }
1616 }
1617
1618 let comm_comm = std.poseidon(layouter, &preimage)?;
1619 std.assert_equal(layouter, &comm_comm, &public_inputs[1])?;
1622 }
1623
1624 public_inputs
1625 .iter()
1626 .try_for_each(|x| std.constrain_as_public_input(layouter, x))
1627 }
1628
1629 fn used_chips(&self) -> ZkStdLibArch {
1630 self.types_pass()
1633 .map(|(_, arch)| arch)
1634 .unwrap_or_else(|err| {
1635 error!("Ill-typed circuit: {err}");
1636 ZkStdLibArch {
1637 nr_pow2range_cols: 4,
1638 ..ZkStdLibArch::default()
1639 }
1640 })
1641 }
1642
1643 fn write_relation<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
1644 let mut raw = Vec::new();
1645 tagged_serialize(&self, &mut raw)?;
1646 raw.serialize(writer)
1647 }
1648
1649 fn read_relation<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
1650 let raw: Vec<u8> = Deserializable::deserialize(reader, 0)?;
1651 tagged_deserialize(&mut &raw[..])
1652 }
1653}