midnight_zkir/ir.rs
1// This file is part of midnight-ledger.
2// Copyright (C) Midnight Foundation
3// SPDX-License-Identifier: Apache-2.0
4// Licensed under the Apache License, Version 2.0 (the "License");
5// You may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14use anyhow::Result;
15use base_crypto::fab::Alignment;
16use midnight_proofs::dev::cost_model::CircuitModel;
17#[cfg(feature = "proptest")]
18use proptest_derive::Arbitrary;
19use rand::{CryptoRng, Rng};
20use serde::{Deserialize, Serialize};
21#[cfg(feature = "proptest")]
22use serialize::randomised_serialization_test;
23use serialize::{Deserializable, Serializable, Tagged, tag_enforcement_test};
24use std::io::{self, Read};
25use std::sync::Arc;
26use transient_crypto::curve::Fr;
27use transient_crypto::proofs::{
28 ParamsProverProvider, Proof, ProofPreimage, ProverKey, ProvingError, TranscriptHash, Zkir,
29};
30
31use crate::ir_types::IrType;
32
33/// A low-level IR allowing the prover to populate circuit witnesses.
34#[cfg_attr(feature = "proptest", derive(Arbitrary))]
35#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize, Serializable)]
36#[tag = "ir-source[v3-generic]"]
37pub struct IrSource {
38 /// The minor version of this IR.
39 pub version: IrMinorVersion,
40 /// The list of input identifiers for this circuit
41 pub inputs: Vec<TypedIdentifier>,
42 /// The output types this circuit returns, positionally. The actual
43 /// values are produced by an `Instruction::Output` terminator whose
44 /// operand list is type-checked against this signature.
45 pub outputs: Vec<IrType>,
46 /// Whether this IR should compile a communications commitment
47 pub do_communications_commitment: bool,
48 /// The sequence of instructions to run in-circuit
49 pub instructions: Arc<Vec<Instruction>>,
50}
51tag_enforcement_test!(IrSource);
52tag_enforcement_test!(ProverKey<IrSource>);
53
54#[cfg_attr(feature = "proptest", derive(Arbitrary))]
55#[derive(
56 Clone,
57 Debug,
58 Default,
59 PartialEq,
60 serde_repr::Serialize_repr,
61 serde_repr::Deserialize_repr,
62 Serializable,
63)]
64#[tag = "ir-minor-version[v3]"]
65#[repr(u8)]
66#[non_exhaustive]
67pub enum IrMinorVersion {
68 V0,
69 V1,
70 #[default]
71 V2,
72}
73
74impl Zkir for IrSource {
75 type ProverKey = midnight_zk_stdlib::MidnightPK<IrSource>;
76
77 fn check(
78 &self,
79 preimage: &ProofPreimage,
80 ) -> std::result::Result<Vec<Option<usize>>, transient_crypto::proofs::ProvingError> {
81 Ok(self.preprocess(preimage)?.pi_skips)
82 }
83
84 async fn prove(
85 &self,
86 rng: impl Rng + CryptoRng,
87 params: &impl ParamsProverProvider,
88 pk: ProverKey<Self>,
89 preimage: &ProofPreimage,
90 ) -> Result<(Proof, Vec<Fr>, Vec<Option<usize>>), ProvingError> {
91 use midnight_zk_stdlib::prove;
92
93 let params_k = params.get_params(pk.init()?.k()).await?;
94 let preproc = self.preprocess(preimage)?;
95 let pis = preproc.pis.clone();
96 let pi_skips = preproc.pi_skips.clone();
97
98 let pk = pk
99 .init()
100 .map_err(|_| anyhow::anyhow!("Could not init pk"))?;
101
102 let proof = prove::<_, TranscriptHash>(params_k.as_ref(), &pk, self, &pis, preproc, rng)?;
103
104 Ok((Proof(proof), pis.into_iter().map(Fr).collect(), pi_skips))
105 }
106
107 fn k(&self) -> u8 {
108 midnight_zk_stdlib::optimal_k(self) as u8
109 }
110
111 async fn keygen_vk(
112 &self,
113 params: &impl ParamsProverProvider,
114 ) -> Result<transient_crypto::proofs::VerifierKey, anyhow::Error> {
115 use midnight_zk_stdlib::setup_vk;
116 Ok(transient_crypto::proofs::VerifierKey::from(setup_vk(
117 params.get_params(self.k()).await?.as_ref(),
118 self,
119 )))
120 }
121
122 async fn keygen(
123 &self,
124 params: &impl ParamsProverProvider,
125 ) -> Result<(ProverKey<Self>, transient_crypto::proofs::VerifierKey), anyhow::Error> {
126 use midnight_zk_stdlib::{setup_pk, setup_vk};
127 let vk = setup_vk(params.get_params(self.k()).await?.as_ref(), self);
128 let pk = setup_pk(self, &vk);
129 Ok((
130 ProverKey::from_raw(pk),
131 transient_crypto::proofs::VerifierKey::from(vk),
132 ))
133 }
134
135 fn load_ir_from_tagged(reader: impl Read + std::io::Seek) -> std::io::Result<Self> {
136 serialize::tagged_deserialize(reader)
137 }
138
139 fn load_prover_key_from_tagged(
140 reader: impl Read + std::io::Seek,
141 ) -> std::io::Result<ProverKey<Self>> {
142 serialize::tagged_deserialize(reader)
143 }
144
145 fn read_raw_pk(reader: impl Read) -> std::io::Result<Self::ProverKey> {
146 midnight_zk_stdlib::MidnightPK::<Self>::read(
147 &mut { reader },
148 midnight_proofs::utils::SerdeFormat::RawBytesUnchecked,
149 )
150 }
151
152 fn write_raw_pk(writer: impl std::io::Write, pk: &Self::ProverKey) -> std::io::Result<()> {
153 pk.write(
154 &mut { writer },
155 midnight_proofs::utils::SerdeFormat::RawBytesUnchecked,
156 )
157 }
158}
159
160/// An identifier for a variable in the circuit memory
161#[cfg_attr(feature = "proptest", derive(Arbitrary))]
162#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Serializable)]
163#[tag = "zkir-identifier[v1]"]
164pub struct Identifier(pub String);
165
166tag_enforcement_test!(Identifier);
167
168/// A typed identifier for a variable in the circuit memory
169#[cfg_attr(feature = "proptest", derive(Arbitrary))]
170#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Serializable)]
171#[tag = "zkir-typed-identifier[v1]"]
172pub struct TypedIdentifier {
173 pub(crate) name: Identifier,
174 #[serde(rename = "type")]
175 pub(crate) val_t: IrType,
176}
177
178tag_enforcement_test!(TypedIdentifier);
179
180/// An operand that can be either a variable reference or an immediate value
181#[cfg_attr(feature = "proptest", derive(Arbitrary))]
182#[derive(Clone, Debug, PartialEq)]
183pub enum Operand {
184 /// A reference to a variable in circuit memory
185 Variable(Identifier),
186 /// An immediate field element value
187 Immediate(Fr),
188}
189
190impl serde::Serialize for Operand {
191 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
192 match self {
193 Operand::Variable(id) => serde::Serialize::serialize(&id.0, serializer),
194 Operand::Immediate(imm) => {
195 let mut repr = imm.as_le_bytes();
196 while repr.last() == Some(&0) && repr.len() > 1 {
197 repr.pop();
198 }
199 serializer.serialize_str(&format!("0x{}", const_hex::encode(&repr)))
200 }
201 }
202 }
203}
204
205impl<'de> serde::Deserialize<'de> for Operand {
206 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
207 where
208 D: serde::Deserializer<'de>,
209 {
210 let s = <String as serde::Deserialize>::deserialize(deserializer)?;
211
212 // Check if this looks like a hex immediate (starts with "0x" or "-0x")
213 let mut repr = s.as_bytes();
214 let negate = if !repr.is_empty() && repr[0] == b'-' {
215 repr = &repr[1..];
216 true
217 } else {
218 false
219 };
220
221 if repr.starts_with(b"0x") || repr.starts_with(b"0X") {
222 let hex_str = &repr[2..];
223 if hex_str.is_empty() {
224 return Err(<D::Error as serde::de::Error>::custom(
225 "Invalid operand format: hex immediate must have at least one digit after '0x'",
226 ));
227 }
228
229 let bytes = const_hex::decode(hex_str)
230 .map_err(<D::Error as serde::de::Error>::custom)?
231 .into_iter()
232 .collect::<Vec<_>>();
233 let field = Fr::from_le_bytes(&bytes).ok_or_else(|| {
234 <D::Error as serde::de::Error>::custom("Out of range for field element")
235 })?;
236 Ok(Operand::Immediate(if negate { -field } else { field }))
237 } else {
238 // Variables must start with '%' in v3
239 if !s.starts_with('%') {
240 return Err(<D::Error as serde::de::Error>::custom(format!(
241 "Invalid operand format: '{}'. Variables must start with '%', immediates must start with '0x'",
242 s
243 )));
244 }
245 Ok(Operand::Variable(Identifier(s)))
246 }
247 }
248}
249
250impl Serializable for Operand {
251 fn serialize(&self, sink: &mut impl std::io::Write) -> Result<(), std::io::Error> {
252 match self {
253 Operand::Variable(id) => {
254 // Write variant tag 0 for Variable
255 Serializable::serialize(&0u8, sink)?;
256 Serializable::serialize(id, sink)
257 }
258 Operand::Immediate(imm) => {
259 // Write variant tag 1 for Immediate
260 Serializable::serialize(&1u8, sink)?;
261 let mut repr = imm.as_le_bytes();
262 while repr.last() == Some(&0) && repr.len() > 1 {
263 repr.pop();
264 }
265 let s = format!("0x{}", const_hex::encode(&repr));
266 Serializable::serialize(&s, sink)
267 }
268 }
269 }
270
271 fn serialized_size(&self) -> usize {
272 let variant_size = 1; // 1 byte for the variant tag
273 variant_size
274 + match self {
275 Operand::Variable(id) => id.serialized_size(),
276 Operand::Immediate(imm) => {
277 let mut repr = imm.as_le_bytes();
278 while repr.last() == Some(&0) && repr.len() > 1 {
279 repr.pop();
280 }
281 let s = format!("0x{}", const_hex::encode(&repr));
282 s.serialized_size()
283 }
284 }
285 }
286}
287
288impl Deserializable for Operand {
289 fn deserialize(source: &mut impl Read, _max_depth: u32) -> Result<Self, io::Error> {
290 // Read the variant tag
291 let variant_tag = <u8 as Deserializable>::deserialize(source, _max_depth)?;
292
293 match variant_tag {
294 0 => {
295 // Variable variant
296 let id = <Identifier as Deserializable>::deserialize(source, _max_depth)?;
297 Ok(Operand::Variable(id))
298 }
299 1 => {
300 // Immediate variant
301 let s: String = Deserializable::deserialize(source, _max_depth)?;
302
303 // Parse the hex string
304 let mut repr = s.as_bytes();
305 let negate = if !repr.is_empty() && repr[0] == b'-' {
306 repr = &repr[1..];
307 true
308 } else {
309 false
310 };
311
312 if !repr.starts_with(b"0x") && !repr.starts_with(b"0X") {
313 return Err(io::Error::new(
314 io::ErrorKind::InvalidData,
315 format!("Expected hex immediate to start with '0x', got: {}", s),
316 ));
317 }
318
319 let hex_str = &repr[2..];
320 if hex_str.is_empty() {
321 return Err(io::Error::new(
322 io::ErrorKind::InvalidData,
323 "Invalid operand format: hex immediate must have at least one digit after '0x'",
324 ));
325 }
326
327 let bytes = const_hex::decode(hex_str)
328 .map_err(|e| {
329 std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
330 })?
331 .into_iter()
332 .collect::<Vec<_>>();
333 let field = Fr::from_le_bytes(&bytes).ok_or_else(|| {
334 io::Error::new(io::ErrorKind::InvalidData, "Out of range for field element")
335 })?;
336 Ok(Operand::Immediate(if negate { -field } else { field }))
337 }
338 _ => Err(io::Error::new(
339 io::ErrorKind::InvalidData,
340 format!("Invalid Operand variant tag: {}", variant_tag),
341 )),
342 }
343 }
344}
345
346impl Tagged for Operand {
347 fn tag() -> std::borrow::Cow<'static, str> {
348 std::borrow::Cow::Borrowed("zkir-operand[v1]")
349 }
350
351 fn tag_unique_factor() -> String {
352 "[zkir-identifier,fr]".to_string()
353 }
354}
355tag_enforcement_test!(Operand);
356
357/// Serde helpers for the `Constant` instruction's `encoding` field. The
358/// encoding is stored as `Vec<Fr>` but (de)serialized as a list of hex
359/// immediates, reusing `Operand`'s immediate format (e.g. `["0x2a", "0x01"]`).
360mod constant_encoding {
361 use super::{Fr, Operand};
362 use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
363
364 pub(super) fn serialize<S: Serializer>(
365 values: &[Fr],
366 serializer: S,
367 ) -> Result<S::Ok, S::Error> {
368 let immediates: Vec<Operand> = values.iter().map(|f| Operand::Immediate(*f)).collect();
369 immediates.serialize(serializer)
370 }
371
372 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
373 deserializer: D,
374 ) -> Result<Vec<Fr>, D::Error> {
375 Vec::<Operand>::deserialize(deserializer)?
376 .into_iter()
377 .map(|op| match op {
378 Operand::Immediate(f) => Ok(f),
379 Operand::Variable(_) => Err(de::Error::custom(
380 "constant encoding entries must be hex immediates (0x..), not variables",
381 )),
382 })
383 .collect()
384 }
385}
386
387/// An individual ZK IR instruction
388//
389// The variant order defines the binary layout: new instructions must be
390// appended at the end, never inserted in the middle, and existing variants
391// must not be reordered.
392#[cfg_attr(feature = "proptest", derive(Arbitrary))]
393#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Serializable)]
394#[serde(rename_all = "snake_case", tag = "op")]
395#[tag = "ir-instruction[v3]"]
396pub enum Instruction {
397 /// Encodes the given value as a vector of raw Fr elements.
398 ///
399 /// This operation will result in an error if the number of outputs
400 /// is not the exact number of raw Fr elements required to represent a
401 /// value of the input type:
402 ///
403 /// - Native: 1 output
404 /// - Bytes32: 2 outputs (low 31 bytes, high byte)
405 /// - JubjubPoint: 2 outputs (x and y coordinates)
406 /// - JubjubScalar: 1 output
407 ///
408 /// Foreign-field elements encode as 2 limbs (midnight-circuits'
409 /// public-input encoding); points as x and y coordinates (2 limbs each)
410 /// followed, on Weierstrass curves only, by an is-identity flag:
411 ///
412 /// - Secp256k1Point: 5 outputs
413 /// - Secp256k1Base: 2 outputs
414 /// - Secp256k1Scalar: 2 outputs
415 ///
416 /// - Secp256r1Point: 5 outputs
417 /// - Secp256r1Base: 2 outputs
418 /// - Secp256r1Scalar: 2 outputs
419 ///
420 /// - Curve25519Point: 4 outputs
421 /// - Curve25519Base: 2 outputs
422 /// - Curve25519Scalar: 2 outputs
423 Encode {
424 /// The value to encode
425 input: Operand,
426 /// The output variable names
427 outputs: Vec<Identifier>,
428 },
429 /// Assert that `cond` has value `1`. UB if `cond` is not `0` or `1`.
430 ///
431 /// No outputs
432 Assert {
433 /// The boolean condition being asserted
434 cond: Operand,
435 },
436 /// Conditionally select a value. UB if `bit` is not `0` or `1`.
437 /// Supported on types:
438 /// - Native
439 /// - JubjubPoint
440 /// - JubjubScalar
441 /// - Secp256k1Point
442 /// - Secp256k1Base
443 /// - Secp256k1Scalar
444 /// - Secp256r1Point
445 /// - Secp256r1Base
446 /// - Secp256r1Scalar
447 /// - Curve25519Point
448 /// - Curve25519Base
449 /// - Curve25519Scalar
450 ///
451 /// Outputs one element, identical to `a` or `b`
452 CondSelect {
453 /// A boolean selector, if `1`, select `a`, else `b`
454 bit: Operand,
455 /// The value to select for `1`
456 a: Operand,
457 /// The value to select for `0`
458 b: Operand,
459 /// The output variable name
460 output: Identifier,
461 },
462 /// Constrains `val` to a set number of bits.
463 ///
464 /// No outputs
465 ConstrainBits {
466 /// The value to constrain
467 val: Operand,
468 /// The number of bits to constrain it to
469 bits: u32,
470 },
471 /// Constrains two values `a` and `b` to be equal.
472 /// Supported on types:
473 /// - Native
474 /// - JubjubPoint
475 /// - JubjubScalar
476 /// - Secp256k1Point
477 /// - Secp256k1Base
478 /// - Secp256k1Scalar
479 /// - Secp256r1Point
480 /// - Secp256r1Base
481 /// - Secp256r1Scalar
482 /// - Curve25519Point
483 /// - Curve25519Base
484 /// - Curve25519Scalar
485 ///
486 /// No outputs
487 ConstrainEq {
488 /// The first value to constrain
489 a: Operand,
490 /// The second value to constrain
491 b: Operand,
492 },
493 /// Constrains a value `val` to be a boolean (`0` or `1`).
494 ///
495 /// No outputs
496 ConstrainToBoolean {
497 /// The value to constrain
498 val: Operand,
499 },
500 /// Creates a copy of a value `val`. Superfluous, but potentially useful
501 /// in some settings, and does not extend the actual circuit.
502 ///
503 /// Outputs one element, identical to `val`
504 Copy {
505 /// The variable or immediate to copy
506 val: Operand,
507 /// The output variable name
508 output: Identifier,
509 },
510 /// Conditional impact instruction - declares multiple public inputs under a guard condition.
511 ///
512 /// No outputs, but adds the inputs as public inputs and activity information to
513 /// [`IrSource::prove`] and [`IrSource::check`].
514 ///
515 /// In-circuit, if `guard` is `false`, instead of adding the `inputs` as public inputs,
516 /// it will add `n` zeros as public inputs (where `n` is the number of `inputs`).
517 /// This is enforced with in-circuit constraints.
518 ///
519 /// NB: Currently, we require that all `inputs` be of type `Native`.
520 /// A runtime error will be raised otherwise.
521 Impact {
522 /// The boolean condition under which the public inputs are active
523 guard: Operand,
524 /// The sequence of values to declare as public inputs
525 inputs: Vec<Operand>,
526 },
527 /// Multiplies an elliptic curve point by a scalar.
528 /// Supported on types:
529 /// - `JubjubPoint x JubjubScalar`
530 /// - `Secp256k1Point x Secp256k1Scalar`
531 /// - `Secp256r1Point x Secp256r1Scalar`
532 /// - `Curve25519Point x Curve25519Scalar`
533 ///
534 /// This operation will result in an error if the input types are not
535 /// supported.
536 ///
537 /// Outputs 1 element, the product
538 EcMul {
539 /// The point to be multiplied
540 a: Operand,
541 /// The scalar to multiply by
542 scalar: Operand,
543 /// The result of multiplication
544 output: Identifier,
545 },
546 /// Multiplies the group generator by a scalar. The curve is determined by
547 /// the scalar type:
548 /// - `JubjubScalar` producing a `JubjubPoint`
549 /// - `Secp256k1Scalar` producing a `Secp256k1Point`
550 /// - `Secp256r1Scalar` producing a `Secp256r1Point`
551 /// - `Curve25519Scalar` producing a `Curve25519Point`
552 ///
553 /// This operation will result in an error if the operand given as `scalar`
554 /// is not one of the above types.
555 ///
556 /// Outputs 1 element, the product
557 EcMulGenerator {
558 /// The scalar to multiply by
559 scalar: Operand,
560 /// The result of multiplication
561 output: Identifier,
562 },
563 /// Hashes a sequence of field elements to a Jubjub point.
564 /// All inputs are required to be of type `Native`. Failure otherwise.
565 ///
566 /// Outputs 1 element, the point
567 HashToCurve {
568 /// The values to hash to a curve point
569 inputs: Vec<Operand>,
570 /// The resulting point
571 output: Identifier,
572 },
573 /// The affine coordinates of the given elliptic curve point.
574 /// On Weierstrass curves the identity has no affine coordinates, so
575 /// extracting them errors off-circuit and is unsatisfiable in-circuit.
576 ///
577 /// Supported on types:
578 /// * JubjubPoint
579 /// * Secp256k1Point
580 /// * Secp256r1Point
581 /// * Curve25519Point
582 ///
583 /// Outputs 2 elements, the coordinates (x, y)
584 IntoCoordinates {
585 /// The point whose coordinate are extracted
586 point: Operand,
587 /// The output variable names (x, y)
588 outputs: (Identifier, Identifier),
589 },
590 /// Reconstructs an elliptic curve point from the given affine coordinates.
591 ///
592 /// On Weierstrass curves the identity cannot be built with this instruction.
593 ///
594 /// Supported on types:
595 /// * (Native, Native): producing a JubjubPoint
596 /// * (Secp256k1Base, Secp256k1Base): producing a Secp256k1Point
597 /// * (Secp256r1Base, Secp256r1Base): producing a Secp256r1Point
598 /// * (Curve25519Base, Curve25519Base): producing a Curve25519Point
599 ///
600 /// Outputs 1 element, the point
601 FromCoordinates {
602 /// The affine coordinates (x, y)
603 inputs: (Operand, Operand),
604 /// The output variable names
605 output: Identifier,
606 },
607 /// ZKIR 3.0 version of `ToBytes` with a fixed-size 32-byte output.
608 ///
609 /// Supported on the prime-field types:
610 /// * Native
611 /// * JubjubScalar
612 /// * Secp256k1Base
613 /// * Secp256k1Scalar
614 /// * Secp256r1Base
615 /// * Secp256r1Scalar
616 /// * Curve25519Base
617 /// * Curve25519Scalar
618 ///
619 /// The output is a `Bytes(32)`: unlike `ToBytes`, this instruction errors
620 /// off-circuit (and fails synthesis in-circuit) if the byte encoding of the
621 /// input is not exactly 32 bytes long.
622 ///
623 /// **Deprecated:** this instruction is slated for removal and should not be
624 /// used in new circuits. Use `ToBytes` instead.
625 IntoBytes32 {
626 /// The element to be converted
627 input: Operand,
628 /// The output variable name
629 output: Identifier,
630 },
631 /// ZKIR 3.0 version of `FromBytes` with a fixed size 32-byte input.
632 ///
633 /// Supported on the prime-field types:
634 /// * Native
635 /// * JubjubScalar
636 /// * Secp256k1Base
637 /// * Secp256k1Scalar
638 /// * Secp256r1Base
639 /// * Secp256r1Scalar
640 /// * Curve25519Base
641 /// * Curve25519Scalar
642 ///
643 /// The input must be a `Bytes(32)`: unlike `FromBytes`, byte strings of any
644 /// other length are rejected.
645 ///
646 /// **Deprecated:** this instruction is slated for removal and should not be
647 /// used in new circuits. Use `FromBytes` instead.
648 FromBytes32 {
649 /// The input bytes
650 bytes: Operand,
651 /// The type to be converted into
652 #[serde(rename = "type")]
653 val_t: IrType,
654 /// The output variable name
655 output: Identifier,
656 },
657 /// ZKIR 3.0 name of `Reverse`, with the same behavior: the input must be
658 /// of type `Bytes(n)`, otherwise this operation fails.
659 ///
660 /// Outputs 1 element, the reversed bytes
661 ///
662 /// **Deprecated:** this instruction is slated for removal and should not be
663 /// used in new circuits. Use `Reverse` instead.
664 ReverseBytes {
665 /// The bytes to be reversed
666 bytes: Operand,
667 /// The output variable name
668 output: Identifier,
669 },
670 /// Decomposes a `Bytes32` value into two `Native` field elements.
671 ///
672 /// The first output (`low`) encodes the first 31 bytes of the input as a
673 /// little-endian native field element. The second output (`high`) encodes
674 /// the 32nd (most significant) byte as a native field element.
675 ///
676 /// This is the inverse of `Bytes32FromLowHigh`.
677 ///
678 /// This instruction imposes no off-circuit errors and no in-circuit constraints.
679 ///
680 /// # Note
681 ///
682 /// This instruction is a temporary bridge for Compact, which cannot yet deal with
683 /// `Bytes32` values directly. It is intended to be removed once Compact can handle
684 /// `Bytes32` (or `Bytes(n)`) without decomposing it into field elements.
685 ///
686 /// **Deprecated:** this instruction is slated for removal and should not be
687 /// used in new circuits. Use `BytesIntoNatives` instead.
688 Bytes32IntoLowHigh {
689 /// The input bytes
690 bytes: Operand,
691 /// The output variables: (low, high)
692 outputs: (Identifier, Identifier),
693 },
694 /// Constructs a `Bytes32` value from two `Native` field elements in low-high form.
695 ///
696 /// The first input (`low`) must encode at most 31 bytes, i.e. its value must be
697 /// less than 2^248. The second input (`high`) must encode a single byte, i.e. its
698 /// value must be less than 256. The result concatenates the first 31 bytes from `low`
699 /// with byte `high`.
700 ///
701 /// This is the inverse of `Bytes32IntoLowHigh`.
702 ///
703 /// # Errors and constraints
704 ///
705 /// Off-circuit: returns an error if `low >= 2^248` or `high >= 256`.
706 ///
707 /// In-circuit: the constraint `low < 2^248` is enforced by asserting that the
708 /// 32nd byte of the little-endian decomposition of `low` is zero, making the
709 /// circuit unsatisfiable if violated. The constraint `high < 256` is enforced
710 /// by a byte range check on `high`, also causing unsatisfiability if violated.
711 ///
712 /// # Note
713 ///
714 /// This instruction is a temporary bridge for Compact, which cannot yet deal with
715 /// `Bytes32` values directly. It is intended to be removed once Compact can handle
716 /// `Bytes32` (or `Bytes(n)`) without decomposing it into field elements.
717 ///
718 /// **Deprecated:** this instruction is slated for removal and should not be
719 /// used in new circuits. Use `BytesFromNatives` instead.
720 Bytes32FromLowHigh {
721 /// The inputs: (low, high)
722 inputs: (Operand, Operand),
723 /// The output variable name
724 output: Identifier,
725 },
726 /// Divides with remainder by a power of two (number of bits).
727 ///
728 /// Two outputs, `val >> bits`, and `val & ((1 << bits) - 1)`
729 ///
730 /// **Deprecated:** this instruction is slated for removal and should not be
731 /// used in new circuits.
732 DivModPowerOfTwo {
733 /// The variable to divide
734 val: Operand,
735 /// The number of bits to divide by
736 bits: u32,
737 /// The outputs: [division result, modulus result]
738 outputs: Vec<Identifier>,
739 },
740 /// Takes two inputs, `divisor` and `modulus`, and outputs
741 /// `divisor << bits | modulus`, guaranteeing that the result does not
742 /// overflow the field size, and that `modulus < (1 << bits)`. Inverse of
743 /// `DivModPowerOfTwo`.
744 ///
745 /// **Deprecated:** this instruction is slated for removal and should not be
746 /// used in new circuits.
747 ReconstituteField {
748 /// The divisor of the reconstituted field element
749 divisor: Operand,
750 /// The modulus of the reconstituted field element
751 modulus: Operand,
752 /// The number of bits for `modulus`
753 bits: u32,
754 /// The output variable name
755 output: Identifier,
756 },
757 /// Calls a circuit-friendly hash function on a sequence of items.
758 ///
759 /// One output, `H(inputs)`
760 TransientHash {
761 /// The values to hash
762 inputs: Vec<Operand>,
763 /// The output variable name
764 output: Identifier,
765 },
766 /// Calls a long-term hash function on a sequence of items with a given
767 /// alignment.
768 ///
769 /// Outputs a value of type Bytes32.
770 PersistentHash {
771 /// The alignment of the inputs being passed
772 alignment: Alignment,
773 /// The inputs to hash
774 inputs: Vec<Operand>,
775 /// The output variable names
776 output: Identifier,
777 },
778 /// Evaluates the Keccak-256 hash function on a sequence of items with
779 /// a given alignment.
780 ///
781 /// Outputs a value of type Bytes32.
782 Keccak256 {
783 /// The alignment of the inputs being passed
784 alignment: Alignment,
785 /// The inputs to hash
786 inputs: Vec<Operand>,
787 /// The output variable names
788 output: Identifier,
789 },
790 /// Tests if `a` and `b` are equal.
791 /// Supported on types:
792 /// - Native
793 /// - JubjubPoint
794 /// - JubjubScalar
795 /// - Secp256k1Point
796 /// - Secp256k1Base
797 /// - Secp256k1Scalar
798 /// - Secp256r1Point
799 /// - Secp256r1Base
800 /// - Secp256r1Scalar
801 /// - Curve25519Point
802 /// - Curve25519Base
803 /// - Curve25519Scalar
804 ///
805 /// One boolean output, `a == b`
806 TestEq {
807 /// The first value to check for equality
808 a: Operand,
809 /// The second value to check for equality
810 b: Operand,
811 /// The output variable name
812 output: Identifier,
813 },
814 /// Adds `a` and `b`.
815 /// Supported on types:
816 /// - Native
817 /// - JubjubPoint
818 /// - JubjubScalar
819 /// - Secp256k1Point
820 /// - Secp256k1Base
821 /// - Secp256k1Scalar
822 /// - Secp256r1Point
823 /// - Secp256r1Base
824 /// - Secp256r1Scalar
825 /// - Curve25519Point
826 /// - Curve25519Base
827 /// - Curve25519Scalar
828 ///
829 /// One output `a + b`
830 Add {
831 /// The first value to add
832 a: Operand,
833 /// The second value to add
834 b: Operand,
835 /// The output variable name
836 output: Identifier,
837 },
838 /// Multiplies `a` and `b`.
839 /// Supported on types:
840 /// - Native
841 /// - JubjubScalar
842 /// - Secp256k1Base
843 /// - Secp256k1Scalar
844 /// - Secp256r1Base
845 /// - Secp256r1Scalar
846 /// - Curve25519Base
847 /// - Curve25519Scalar
848 ///
849 /// One output `a * b`
850 Mul {
851 /// The first value to multiply
852 a: Operand,
853 /// The second value to multiply
854 b: Operand,
855 /// The output variable name
856 output: Identifier,
857 },
858 /// Negates `a`.
859 /// Supported on types:
860 /// - Native
861 /// - JubjubPoint
862 /// - JubjubScalar
863 /// - Secp256k1Point
864 /// - Secp256k1Base
865 /// - Secp256k1Scalar
866 /// - Secp256r1Point
867 /// - Secp256r1Base
868 /// - Secp256r1Scalar
869 /// - Curve25519Point
870 /// - Curve25519Base
871 /// - Curve25519Scalar
872 ///
873 /// One output `-a`
874 Neg {
875 /// The value to negate
876 a: Operand,
877 /// The output variable name
878 output: Identifier,
879 },
880 /// Inverts `a`, results in an error if `a` is zero.
881 /// Supported on types:
882 /// - Native
883 /// - JubjubScalar
884 /// - Secp256k1Base
885 /// - Secp256k1Scalar
886 /// - Secp256r1Base
887 /// - Secp256r1Scalar
888 /// - Curve25519Base
889 /// - Curve25519Scalar
890 ///
891 /// One output `a^(-1)`
892 Inv {
893 /// The value to invert
894 a: Operand,
895 /// The output variable name
896 output: Identifier,
897 },
898 /// Boolean not gate.
899 ///
900 /// One output `!a`
901 Not {
902 /// The value to negate
903 a: Operand,
904 /// The output variable name
905 output: Identifier,
906 },
907 /// Checks if `a` < `b`, interpreting both as `bits`-bit unsigned
908 /// integers. UB if `a` or `b` exceed `bits`.
909 ///
910 /// One boolean output `a < b`
911 LessThan {
912 /// The first value to compare
913 a: Operand,
914 /// The second value to compare
915 b: Operand,
916 /// The number of bits to compare
917 bits: u32,
918 /// The output variable name
919 output: Identifier,
920 },
921 /// Cast a Native value as a Jubjub scalar by reducing it modulo the Jubjub scalar
922 /// field order if necessary.
923 ///
924 /// NB: This instruction will be removed when the BigUint type becomes available.
925 JubjubScalarFromNative {
926 /// The native value to be converted.
927 native: Operand,
928 /// The output variable name.
929 output: Identifier,
930 },
931 /// Off-circuit (preprocessing):
932 /// Retrieves an input from the public transcript outputs.
933 /// Outputs one element, the next public transcript output, or a default value
934 /// if the `guard` fails.
935 ///
936 /// In-circuit:
937 /// Allows the prover to witness a free value, only constrained to respect
938 /// the type `val_t`. The `guard` DOES NOT participate in in-circuit constraints.
939 ///
940 /// NB: This instruction is essentially identical to `PrivateInput` except that
941 /// the `preprocessing` pass will consume the value from a different source
942 /// (the public transcript outputs in this case).
943 PublicInput {
944 /// An optional condition for retrieving the next public transcript
945 /// output
946 guard: Option<Operand>,
947 /// The type of this input
948 #[serde(rename = "type")]
949 val_t: IrType,
950 /// The output variable name
951 output: Identifier,
952 },
953
954 /// Off-circuit (preprocessing):
955 /// Retrieves an input from the private transcript outputs.
956 /// Outputs one element, the next private transcript output, or a default value
957 /// if the `guard` fails.
958 ///
959 /// In-circuit:
960 /// Allows the prover to witness a free value, only constrained to respect
961 /// the type `val_t`. The `guard` DOES NOT participate in in-circuit constraints.
962 ///
963 /// NB: This instruction is essentially identical to `PublicInput` except that
964 /// the `preprocessing` pass will consume the value from a different source
965 /// (the private transcript outputs in this case).
966 PrivateInput {
967 /// An optional condition for retrieving the next private transcript
968 /// output
969 guard: Option<Operand>,
970 /// The type of this input
971 #[serde(rename = "type")]
972 val_t: IrType,
973 /// The output variable name
974 output: Identifier,
975 },
976 /// Circuit terminator. Produces the circuit's return values, in
977 /// signature order, and ends execution. The operand list is type-checked
978 /// against `IrSource::outputs` (length and per-position type), then each
979 /// operand is encoded via `encode_offcircuit` / `encode_incircuit` and
980 /// pushed into the outputs accumulator.
981 Output {
982 /// The values returned, one per `IrSource::outputs[i]`.
983 vals: Vec<Operand>,
984 },
985 //
986 // ==================== END OF ZKIR 3.0 INSTRUCTIONS ====================
987 //
988 /// Extracts a contiguous sub-slice of a `Bytes(n)` value, returning a
989 /// `Bytes(len)`.
990 ///
991 /// `start` and `len` are compile-time constants; the slice covers positions
992 /// `start .. start + len`. `len` must be at least 1.
993 ///
994 /// # Errors
995 ///
996 /// Errors off-circuit (and fails synthesis in-circuit) if the input is not a
997 /// `Bytes(n)` value, if `len == 0`, or if `start + len > n`. Imposes no
998 /// in-circuit constraints: it selects a fixed range of wires.
999 Slice {
1000 /// The byte string to slice
1001 bytes: Operand,
1002 /// The (constant) start position of the slice
1003 start: u32,
1004 /// The (constant) length of the slice (`>= 1`)
1005 len: u32,
1006 /// The output variable name (a `Bytes(len)`)
1007 output: Identifier,
1008 },
1009 /// Extracts the byte at position `index` of a `Bytes(n)` value, returning a
1010 /// `Byte`.
1011 ///
1012 /// `index` is a compile-time constant that must lie in the range `0..n`,
1013 /// where `n` is the length of the input byte string.
1014 ///
1015 /// # Errors
1016 ///
1017 /// Errors off-circuit (and fails synthesis in-circuit) if the input is not a
1018 /// `Bytes(n)` value, or if `index >= n`. Imposes no in-circuit constraints:
1019 /// it simply selects a fixed wire.
1020 Nth {
1021 /// The byte string to index into
1022 bytes: Operand,
1023 /// The (constant) position of the byte to extract, in `0..n`
1024 index: u32,
1025 /// The output variable name (a `Byte`)
1026 output: Identifier,
1027 },
1028 /// Concatenates a non-empty sequence of `Byte` and/or `Bytes(m)` values into
1029 /// a single `Bytes(n)` value, where `n` is the sum of the input lengths (a
1030 /// `Byte` contributes 1, a `Bytes(m)` contributes `m`).
1031 ///
1032 /// # Errors
1033 ///
1034 /// Errors if `inputs` is empty, if any input is neither a `Byte` nor a
1035 /// `Bytes` value, or if the resulting length exceeds `MAX_BYTES_LEN`.
1036 Concat {
1037 /// The `Byte`/`Bytes` values to concatenate, in order
1038 inputs: Vec<Operand>,
1039 /// The output variable name (a `Bytes(n)`)
1040 output: Identifier,
1041 },
1042 /// Loads a fixed (constant) value of the given `type` into the circuit.
1043 ///
1044 /// `encoding` is the value's encoded form: the list of field elements that
1045 /// [`crate::ir_instructions::encode::encode_offcircuit`] would produce for
1046 /// it, written as hex immediates (e.g. `["0x2a"]`). Off-circuit the encoding
1047 /// is decoded into a typed value; in-circuit that value is baked in with
1048 /// `assign_fixed`.
1049 ///
1050 /// Supported on every `type`.
1051 ///
1052 /// # Errors
1053 ///
1054 /// Errors off-circuit (and fails synthesis in-circuit) if `encoding` is not
1055 /// a valid, canonical encoding of a value of `type` (wrong number of field
1056 /// elements, non-canonical field element, etc.).
1057 LoadConstant {
1058 /// The type of the constant
1059 #[serde(rename = "type")]
1060 val_t: IrType,
1061 /// The encoded value, as a list of field-element immediates
1062 #[serde(with = "constant_encoding")]
1063 encoding: Vec<Fr>,
1064 /// The output variable name
1065 output: Identifier,
1066 },
1067 /// Evaluates the SHA-512 hash function on a sequence of items with
1068 /// a given alignment.
1069 ///
1070 /// Outputs a value of type `Bytes<64>`.
1071 Sha512 {
1072 /// The alignment of the inputs being passed
1073 alignment: Alignment,
1074 /// The inputs to hash
1075 inputs: Vec<Operand>,
1076 /// The output variable name
1077 output: Identifier,
1078 },
1079 /// Boolean AND gate over a non-empty list of `Bool` values.
1080 ///
1081 /// All `inputs` must be of type `Bool`. Results in an error if the input
1082 /// list is empty or if any input is not a `Bool`.
1083 ///
1084 /// One `Bool` output, the conjunction of all `inputs`
1085 And {
1086 /// The boolean values to combine
1087 inputs: Vec<Operand>,
1088 /// The output variable name
1089 output: Identifier,
1090 },
1091 /// Boolean OR gate over a non-empty list of `Bool` values.
1092 ///
1093 /// All `inputs` must be of type `Bool`. Results in an error if the input
1094 /// list is empty or if any input is not a `Bool`.
1095 ///
1096 /// One `Bool` output, the disjunction of all `inputs`
1097 Or {
1098 /// The boolean values to combine
1099 inputs: Vec<Operand>,
1100 /// The output variable name
1101 output: Identifier,
1102 },
1103 /// Boolean XOR gate over a non-empty list of `Bool` values.
1104 ///
1105 /// All `inputs` must be of type `Bool`. Results in an error if the input
1106 /// list is empty or if any input is not a `Bool`.
1107 ///
1108 /// One `Bool` output, the exclusive-or (parity) of all `inputs`
1109 Xor {
1110 /// The boolean values to combine
1111 inputs: Vec<Operand>,
1112 /// The output variable name
1113 output: Identifier,
1114 },
1115 /// Transforms the given value into its fixed-size byte representation.
1116 ///
1117 /// Supported on the prime-field types, with a `Bytes(32)` output:
1118 /// * Native
1119 /// * JubjubScalar
1120 /// * Secp256k1Base
1121 /// * Secp256k1Scalar
1122 /// * Secp256r1Base
1123 /// * Secp256r1Scalar
1124 /// * Curve25519Base
1125 /// * Curve25519Scalar
1126 ///
1127 /// In all the above prime fields, the byte representation is the
1128 /// little-endian byte encoding of the underlying (canonical) integer.
1129 ///
1130 /// Also supported on points, which are encoded in compressed form:
1131 /// * Curve25519Point -> Bytes(32), ed25519 (RFC 8032) encoding
1132 /// * JubjubPoint -> Bytes(32), same layout as Curve25519Point: the
1133 /// little-endian `y` coordinate, with the least significant bit of `x`
1134 /// in the most significant bit of the last byte
1135 /// * Secp256k1Point, Secp256r1Point -> Bytes(33), SEC1 compressed encoding,
1136 /// with the identity encoded as 33 zero bytes (SEC1's `0x00`, zero-padded)
1137 ToBytes {
1138 /// The element to be converted
1139 input: Operand,
1140 /// The output variable name
1141 output: Identifier,
1142 },
1143 /// Constructs an element of the given type from a `Bytes(n)` of any
1144 /// length, interpreted as a little-endian integer and reduced modulo the
1145 /// field order.
1146 ///
1147 /// Supported on the prime-field types:
1148 /// * Native
1149 /// * JubjubScalar
1150 /// * Secp256k1Base
1151 /// * Secp256k1Scalar
1152 /// * Secp256r1Base
1153 /// * Secp256r1Scalar
1154 /// * Curve25519Base
1155 /// * Curve25519Scalar
1156 ///
1157 /// The modular reduction in particular allows reducing the 64-byte output
1158 /// of a 512-bit hash into a `Curve25519Scalar`, as required by ed25519.
1159 /// For inputs representing an integer below the field order, `ToBytes`
1160 /// inverts `FromBytes` up to zero-padding to 32 bytes.
1161 ///
1162 /// Non-canonical field elements (integers not below the field order) are
1163 /// therefore accepted and reduced.
1164 ///
1165 /// Also supported on the point types listed in `ToBytes`, as its inverse.
1166 /// Unlike field elements, non-canonical encodings of points are rejected:
1167 /// this instruction fails off-circuit, and is unsatisfiable in-circuit,
1168 /// unless the input is exactly the compressed encoding of a point.
1169 FromBytes {
1170 /// The input bytes
1171 bytes: Operand,
1172 /// The type to be converted into
1173 #[serde(rename = "type")]
1174 val_t: IrType,
1175 /// The output variable name
1176 output: Identifier,
1177 },
1178 /// Reverses the byte order of a `Bytes(n)` value.
1179 ///
1180 /// The input must be of type `Bytes(n)`, otherwise this operation fails. The
1181 /// output is a `Bytes(n)` whose bytes are those of the input in reverse
1182 /// order, i.e. the first byte becomes the last and vice versa.
1183 ///
1184 /// Outputs 1 element, the reversed bytes
1185 Reverse {
1186 /// The bytes to be reversed
1187 bytes: Operand,
1188 /// The output variable name
1189 output: Identifier,
1190 },
1191 /// Packs a `Bytes(n)` value into `ceil(n / 31)` `Native` field elements.
1192 ///
1193 /// The input bytes are split into consecutive chunks of 31 bytes (the last
1194 /// chunk being shorter when `n` is not a multiple of 31), and every chunk is
1195 /// interpreted as a little-endian native field element. This is the packing
1196 /// that [`Instruction::Encode`] applies to a `Bytes(n)` value; for `n = 32`
1197 /// it yields the first 31 bytes as one field element and the 32nd (most
1198 /// significant) byte as another.
1199 ///
1200 /// The chunk size is not a constant of the IR but of the native field: 31 is
1201 /// the number of whole bytes that always fit below its modulus, currently
1202 /// the BLS12-381 scalar field at ~254 bits. It is parametrized as
1203 /// `BYTES_PER_FIELD_ELEMENT` in `crate::ir_types`, and a different native
1204 /// field would give a different number.
1205 ///
1206 /// This is the inverse of `BytesFromNatives`.
1207 ///
1208 /// # Errors and constraints
1209 ///
1210 /// Errors off-circuit (and fails synthesis in-circuit) if the input is not a
1211 /// `Bytes(n)` value, or if the number of outputs is not `ceil(n / 31)`.
1212 ///
1213 /// Imposes no in-circuit range checks: a chunk of at most 31 bytes always
1214 /// fits in a field element.
1215 ///
1216 /// # Note
1217 ///
1218 /// This instruction is a temporary bridge for Compact, which cannot yet deal with
1219 /// `Bytes(n)` values directly. It is intended to be removed once Compact can handle
1220 /// `Bytes(n)` without decomposing it into field elements.
1221 BytesIntoNatives {
1222 /// The input bytes
1223 bytes: Operand,
1224 /// The output variable names, `ceil(n / 31)` of them, ordered from the
1225 /// chunk holding the first bytes of the input to the chunk holding the
1226 /// last ones
1227 outputs: Vec<Identifier>,
1228 },
1229 /// Unpacks `ceil(len / 31)` `Native` field elements into a `Bytes(len)` value.
1230 ///
1231 /// Every input encodes 31 bytes of the result in little-endian form, except
1232 /// the last one, which encodes the remaining `len - 31 * (k - 1)` bytes,
1233 /// where `k` is the number of inputs. Each input must therefore be less than
1234 /// `2^(8 * r)`, `r` being the number of bytes it contributes.
1235 ///
1236 /// As in `BytesIntoNatives`, 31 is `BYTES_PER_FIELD_ELEMENT` (see
1237 /// `crate::ir_types`), which follows from the native field in use.
1238 ///
1239 /// This is the inverse of `BytesIntoNatives`.
1240 ///
1241 /// # Errors and constraints
1242 ///
1243 /// Errors off-circuit (and fails synthesis in-circuit) if `len` is not in
1244 /// `1..=MAX_BYTES_LEN`, or if the number of inputs is not `ceil(len / 31)`.
1245 ///
1246 /// Off-circuit: returns an error if an input is not less than `2^(8 * r)`,
1247 /// `r` being the number of bytes it contributes.
1248 ///
1249 /// In-circuit: each input is decomposed into exactly the `r` bytes it
1250 /// contributes, which enforces `input < 2^(8 * r)`, making the circuit
1251 /// unsatisfiable if violated.
1252 ///
1253 /// # Note
1254 ///
1255 /// This instruction is a temporary bridge for Compact, which cannot yet deal with
1256 /// `Bytes(n)` values directly. It is intended to be removed once Compact can handle
1257 /// `Bytes(n)` without decomposing it into field elements.
1258 BytesFromNatives {
1259 /// The inputs, `ceil(len / 31)` of them, ordered from the chunk holding
1260 /// the first bytes of the output to the chunk holding the last ones
1261 inputs: Vec<Operand>,
1262 /// The (constant) length in bytes of the output
1263 len: u32,
1264 /// The output variable name (a `Bytes(len)`)
1265 output: Identifier,
1266 },
1267 //
1268 // ==================== END OF ZKIR 3.1 INSTRUCTIONS ====================
1269 //
1270}
1271tag_enforcement_test!(Instruction);
1272
1273#[derive(Deserialize)]
1274struct SerdeVersion {
1275 major: u8,
1276 minor: u8,
1277}
1278
1279#[derive(Debug)]
1280/// A model containing data about a specific constructed circuit
1281pub struct Model {
1282 model: CircuitModel,
1283}
1284
1285impl Model {
1286 /// The minimum value of `k` needed for this circuit
1287 pub fn k(&self) -> u8 {
1288 self.model.k as u8
1289 }
1290
1291 /// The number of rows needed by this circuit, not counting custom gates and lookups
1292 pub fn rows(&self) -> usize {
1293 self.model.rows
1294 }
1295}
1296
1297impl IrSource {
1298 /// Retrieves a model representation of this circuit.
1299 pub fn model(&self) -> Model {
1300 Model {
1301 model: midnight_zk_stdlib::cost_model(self, None),
1302 }
1303 }
1304
1305 /// Attempts to parse an arbitrary input as IR.
1306 pub fn load<R: Read>(reader: R) -> io::Result<Self> {
1307 let value: serde_json::Value = serde_json::from_reader(reader)?;
1308 match value {
1309 serde_json::Value::Object(mut obj) => {
1310 let ver = serde_json::from_value(
1311 obj.get("version")
1312 .ok_or_else(|| {
1313 io::Error::new(io::ErrorKind::InvalidData, "Expected a version entry")
1314 })?
1315 .clone(),
1316 )?;
1317 match ver {
1318 SerdeVersion {
1319 major: 3,
1320 minor: 0..=2,
1321 } => {
1322 obj.insert(
1323 "version".into(),
1324 serde_json::Value::Number(ver.minor.into()),
1325 );
1326 Ok(serde_json::from_value(serde_json::Value::Object(obj))?)
1327 }
1328 SerdeVersion { major, minor } => Err(io::Error::new(
1329 io::ErrorKind::InvalidData,
1330 format!("Unhandled version: {major}.{minor}"),
1331 )),
1332 }
1333 }
1334 _ => Err(io::Error::new(
1335 io::ErrorKind::InvalidData,
1336 "Expected a JSON object",
1337 )),
1338 }
1339 }
1340
1341 /// Intended for testing only. This method enables fully controlling the inputs passed to
1342 /// proving, to test malicious prover behavior.
1343 pub async fn prove_unchecked<R: Rng + CryptoRng>(
1344 &self,
1345 rng: R,
1346 params: &impl ParamsProverProvider,
1347 pk: ProverKey<IrSource>,
1348 preproc: super::ir_vm::Preprocessed,
1349 ) -> Result<Proof> {
1350 use midnight_zk_stdlib::prove;
1351
1352 let params_k = params.get_params(pk.init()?.k()).await?;
1353 let pis = preproc.pis.clone();
1354
1355 let pk = pk
1356 .init()
1357 .map_err(|_| anyhow::anyhow!("Could not init pk"))?;
1358
1359 let proof = prove::<_, TranscriptHash>(params_k.as_ref(), &pk, self, &pis, preproc, rng)?;
1360
1361 Ok(Proof(proof))
1362 }
1363}
1364
1365#[cfg(feature = "proptest")]
1366randomised_serialization_test!(IrSource);
1367
1368#[cfg(feature = "proptest")]
1369randomised_serialization_test!(Instruction);