Skip to main content

midnight_zk_stdlib/
lib.rs

1// This file is part of MIDNIGHT-ZK.
2// Copyright (C) 2025 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
14#![doc = include_str!("../README.md")]
15//!
16//! ## Implementation Details
17//!
18//! This library uses a fixed configuration, meaning that regardless of what one
19//! uses, it will always consist of the same columns, lookups, permutation
20//! enabled columns, or gates. The motivation for this is twofold:
21//!
22//! * It facilitates recursion (we always aggregate circuits that have the same
23//!   verification logic).
24//!
25//! * We could optimise the verifier, who can store part of the circuit
26//!   description in memory and does not need to reproduce it everytime it
27//!   receives a new proof.
28
29pub mod utils;
30
31use std::{cell::RefCell, cmp::max, convert::TryInto, fmt::Debug, io, rc::Rc};
32
33use bincode::{config::standard, Decode, Encode};
34use blake2b::blake2b::{
35    blake2b_chip::{Blake2bChip, Blake2bConfig},
36    NB_BLAKE2B_ADVICE_COLS,
37};
38use ff::PrimeField;
39use group::{prime::PrimeCurveAffine, Group};
40use keccak_sha3::packed_chip::{PackedChip, PackedConfig, PACKED_ADVICE_COLS, PACKED_FIXED_COLS};
41use midnight_circuits::{
42    biguint::biguint_gadget::BigUintGadget,
43    ecc::{
44        foreign::{nb_foreign_ecc_chip_columns, ForeignEccChip, ForeignEccConfig},
45        hash_to_curve::HashToCurveGadget,
46        native::{EccChip, EccConfig, NB_EDWARDS_COLS},
47    },
48    external::{blake2b::Blake2bWrapper, keccak_sha3::KeccakSha3Wrapper},
49    field::{
50        decomposition::{
51            chip::{P2RDecompositionChip, P2RDecompositionConfig},
52            pow2range::Pow2RangeChip,
53        },
54        foreign::{
55            nb_field_chip_columns, params::MultiEmulationParams as MEP, FieldChip, FieldChipConfig,
56        },
57        native::{NB_ARITH_COLS, NB_ARITH_FIXED_COLS},
58        NativeChip, NativeConfig, NativeGadget,
59    },
60    hash::{
61        poseidon::{PoseidonChip, PoseidonConfig, NB_POSEIDON_ADVICE_COLS, NB_POSEIDON_FIXED_COLS},
62        sha256::{Sha256Chip, Sha256Config, NB_SHA256_ADVICE_COLS, NB_SHA256_FIXED_COLS},
63        sha512::{Sha512Chip, Sha512Config, NB_SHA512_ADVICE_COLS, NB_SHA512_FIXED_COLS},
64    },
65    instructions::{public_input::CommittedInstanceInstructions, *},
66    map::map_gadget::MapGadget,
67    parsing::{
68        self,
69        automaton_chip::{AutomatonChip, AutomatonConfig, NB_AUTOMATA_COLS},
70        Base64Chip, Base64Config, ParserGadget, StdLibParser, NB_BASE64_ADVICE_COLS,
71    },
72    types::{
73        AssignedBit, AssignedByte, AssignedNative, AssignedNativePoint, ComposableChip, InnerValue,
74        Instantiable,
75    },
76    vec::{vector_gadget::VectorGadget, AssignedVector, Vectorizable},
77};
78use midnight_curves::{
79    secp256k1::{self, Secp256k1},
80    Fq, G1Affine, G1Projective,
81};
82use midnight_proofs::{
83    circuit::{Layouter, SimpleFloorPlanner, Value},
84    dev::cost_model::{circuit_model, CircuitModel},
85    plonk::{k_from_circuit, prepare, Circuit, ConstraintSystem, Error, ProvingKey, VerifyingKey},
86    poly::{
87        commitment::{Guard, Params},
88        kzg::{
89            params::{ParamsKZG, ParamsVerifierKZG},
90            KZGCommitmentScheme,
91        },
92    },
93    transcript::{CircuitTranscript, Hashable, Sampleable, Transcript, TranscriptHash},
94    utils::SerdeFormat,
95};
96use num_bigint::BigUint;
97use rand::{rngs::OsRng, CryptoRng, RngCore};
98
99use crate::utils::plonk_api::BlstPLONK;
100
101type C = midnight_curves::JubjubExtended;
102type F = midnight_curves::Fq;
103
104// Type aliases, for readability.
105type NG = NativeGadget<F, P2RDecompositionChip<F>, NativeChip<F>>;
106type Secp256k1BaseChip = FieldChip<F, secp256k1::Fp, MEP, NG>;
107type Secp256k1ScalarChip = FieldChip<F, secp256k1::Fq, MEP, NG>;
108type Secp256k1Chip = ForeignEccChip<F, Secp256k1, MEP, Secp256k1ScalarChip, NG>;
109type Bls12381BaseChip = FieldChip<F, midnight_curves::Fp, MEP, NG>;
110type Bls12381Chip = ForeignEccChip<F, midnight_curves::G1Projective, MEP, NG, NG>;
111
112const ZKSTD_VERSION: u32 = 1;
113
114/// Architecture of the standard library. Specifies what chips need to be
115/// configured.
116#[derive(Clone, Copy, Debug, Eq, PartialEq, Encode, Decode)]
117pub struct ZkStdLibArch {
118    /// Enable the Jubjub chip?
119    pub jubjub: bool,
120
121    /// Enable the Poseidon chip?
122    pub poseidon: bool,
123
124    /// Enable the SHA256 chip?
125    pub sha2_256: bool,
126
127    /// Enable the SHA512 chip?
128    pub sha2_512: bool,
129
130    /// Enable the Keccak chip? (third-party implementation)
131    ///
132    /// Note: is configured using the same columns and tables as sha3_256,
133    /// meaning enabling either of the two, or both, requires the same
134    /// configuration resources.
135    pub keccak_256: bool,
136
137    /// Enable the Sha3 chip? (third-party implementation)
138    ///
139    /// Note: is configured using the same columns and tables as keccak_256,
140    /// meaning enabling either of the two, or both, requires the same
141    /// configuration resources.
142    pub sha3_256: bool,
143
144    /// Enable the Blake2b chip? (third-party implementation)
145    pub blake2b: bool,
146
147    /// Enable the Secp256k1 chip?
148    pub secp256k1: bool,
149
150    /// Enable BLS12-381 chip?
151    pub bls12_381: bool,
152
153    /// Enable base64 chip?
154    pub base64: bool,
155
156    /// Enable automaton?
157    pub automaton: bool,
158
159    /// Number of parallel lookups for range checks.
160    pub nr_pow2range_cols: u8,
161}
162
163impl Default for ZkStdLibArch {
164    fn default() -> Self {
165        ZkStdLibArch {
166            jubjub: false,
167            poseidon: false,
168            sha2_256: false,
169            sha2_512: false,
170            sha3_256: false,
171            keccak_256: false,
172            blake2b: false,
173            secp256k1: false,
174            bls12_381: false,
175            base64: false,
176            automaton: false,
177            nr_pow2range_cols: 1,
178        }
179    }
180}
181
182impl ZkStdLibArch {
183    /// Writes the ZKStd architecture to a buffer.
184    pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
185        writer.write_all(&ZKSTD_VERSION.to_le_bytes())?;
186        bincode::encode_into_std_write(self, writer, standard())
187            .map(|_| ())
188            .map_err(io::Error::other)
189    }
190
191    /// Reads the ZkStd architecture from a buffer.
192    pub fn read<R: io::Read>(reader: &mut R) -> io::Result<Self> {
193        let mut version = [0u8; 4];
194        reader.read_exact(&mut version)?;
195        let version = u32::from_le_bytes(version);
196        match version {
197            1 => bincode::decode_from_std_read(reader, standard())
198                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)),
199            _ => Err(io::Error::new(
200                io::ErrorKind::InvalidData,
201                format!("Unsupported ZKStd version: {}", version),
202            )),
203        }
204    }
205
206    /// Reads the ZkStdArchitecture from a buffer where a MidnightVK was
207    /// serialized. This enables the reader to know the architecture without
208    /// the need of deserializing the full verifying key.
209    pub fn read_from_serialized_vk<R: io::Read>(reader: &mut R) -> io::Result<Self> {
210        // The current serialization of the verifying key places the architecture at
211        // the beginning.
212        Self::read(reader)
213    }
214
215    /// Returns a tuple `(points_in_proof, points_in_vk, points_in_final_msm)`
216    /// where:
217    ///
218    /// * `points_in_proof`: total number of EC points deserialized when reading
219    ///   a proof for this relation.
220    /// * `points_in_vk`: total number of EC points deserialized when reading
221    ///   the verifying key.
222    /// * `points_in_final_msm`: number of EC points involved in the final MSM
223    ///   operation during verification.
224    pub fn nb_points(&self) -> (usize, usize, usize) {
225        let mut cs = ConstraintSystem::default();
226        let _config = ZkStdLib::configure(&mut cs, *self);
227
228        let nb_perm_chunks =
229            (cs.permutation().columns.len().saturating_sub(1) / cs.degree().saturating_sub(2)) + 1;
230
231        let points_in_proof = cs.num_advice_columns() +
232            cs.lookups().len() * 3 +
233            nb_perm_chunks +
234            cs.degree() + // chunks of the vanishing
235            2; // points in multiopen argument
236
237        let points_in_vk =
238            cs.num_fixed_columns() + cs.num_selectors() + cs.permutation().columns.len();
239
240        let points_in_final_msm = points_in_proof + points_in_vk + 1; // + 1 comes from the the generator in the final check
241
242        (points_in_proof, points_in_vk, points_in_final_msm)
243    }
244}
245
246#[derive(Debug, Clone)]
247/// Configured chips for [ZkStdLib].
248pub struct ZkStdLibConfig {
249    native_config: NativeConfig,
250    core_decomposition_config: P2RDecompositionConfig,
251    jubjub_config: Option<EccConfig>,
252    sha2_256_config: Option<Sha256Config>,
253    sha2_512_config: Option<Sha512Config>,
254    poseidon_config: Option<PoseidonConfig<midnight_curves::Fq>>,
255    secp256k1_scalar_config: Option<FieldChipConfig>,
256    secp256k1_config: Option<ForeignEccConfig<Secp256k1>>,
257    bls12_381_config: Option<ForeignEccConfig<midnight_curves::G1Projective>>,
258    base64_config: Option<Base64Config>,
259    automaton_config: Option<AutomatonConfig<StdLibParser, midnight_curves::Fq>>,
260
261    // Configuration of external libraries.
262    keccak_sha3_config: Option<PackedConfig>,
263    blake2b_config: Option<Blake2bConfig>,
264}
265
266/// The `ZkStdLib` exposes all tools that are used in circuit generation.
267#[derive(Clone, Debug)]
268#[allow(clippy::type_complexity)]
269pub struct ZkStdLib {
270    // Internal chips and gadgets.
271    native_gadget: NG,
272    core_decomposition_chip: P2RDecompositionChip<F>,
273    jubjub_chip: Option<EccChip<C>>,
274    sha2_256_chip: Option<Sha256Chip<F>>,
275    sha2_512_chip: Option<Sha512Chip<F>>,
276    poseidon_gadget: Option<PoseidonChip<F>>,
277    htc_gadget: Option<HashToCurveGadget<F, C, AssignedNative<F>, PoseidonChip<F>, EccChip<C>>>,
278    map_gadget: Option<MapGadget<F, NG, PoseidonChip<F>>>,
279    biguint_gadget: BigUintGadget<F, NG>,
280    secp256k1_scalar_chip: Option<Secp256k1ScalarChip>,
281    secp256k1_curve_chip: Option<Secp256k1Chip>,
282    bls12_381_curve_chip: Option<Bls12381Chip>,
283    base64_chip: Option<Base64Chip<F>>,
284    parser_gadget: ParserGadget<F, NG>,
285    vector_gadget: VectorGadget<F>,
286    automaton_chip: Option<AutomatonChip<StdLibParser, F>>,
287
288    // Third-party chips.
289    keccak_sha3_chip: Option<KeccakSha3Wrapper<F>>,
290    blake2b_chip: Option<Blake2bWrapper<F>>,
291
292    // Flags that indicate if certain chips have been used. This way we can load the tables only
293    // when necessary (thus reducing the min_k in some cases).
294    // Such a usage flag has to be added and updated correctly for each new chip using tables.
295    used_sha2_256: Rc<RefCell<bool>>,
296    used_sha2_512: Rc<RefCell<bool>>,
297    used_secp256k1_scalar: Rc<RefCell<bool>>,
298    used_secp256k1_curve: Rc<RefCell<bool>>,
299    used_bls12_381_curve: Rc<RefCell<bool>>,
300    used_base64: Rc<RefCell<bool>>,
301    used_automaton: Rc<RefCell<bool>>,
302    used_keccak_or_sha3: Rc<RefCell<bool>>,
303    used_blake2b: Rc<RefCell<bool>>,
304}
305
306impl ZkStdLib {
307    /// Creates a new [ZkStdLib] given its config.
308    pub fn new(config: &ZkStdLibConfig, max_bit_len: usize) -> Self {
309        let native_chip = NativeChip::new(&config.native_config, &());
310        let core_decomposition_chip =
311            P2RDecompositionChip::new(&config.core_decomposition_config, &max_bit_len);
312        let native_gadget = NativeGadget::new(core_decomposition_chip.clone(), native_chip.clone());
313        let jubjub_chip = (config.jubjub_config.as_ref())
314            .map(|jubjub_config| EccChip::new(jubjub_config, &native_gadget));
315        let sha2_256_chip = (config.sha2_256_config.as_ref())
316            .map(|sha256_config| Sha256Chip::new(sha256_config, &native_gadget));
317        let sha2_512_chip = (config.sha2_512_config.as_ref())
318            .map(|sha512_config| Sha512Chip::new(sha512_config, &native_gadget));
319        let poseidon_gadget = (config.poseidon_config.as_ref())
320            .map(|poseidon_config| PoseidonChip::new(poseidon_config, &native_chip));
321        let htc_gadget = (jubjub_chip.as_ref())
322            .zip(poseidon_gadget.as_ref())
323            .map(|(ecc_chip, poseidon_gadget)| HashToCurveGadget::new(poseidon_gadget, ecc_chip));
324        let biguint_gadget = BigUintGadget::new(&native_gadget);
325        let map_gadget = poseidon_gadget
326            .as_ref()
327            .map(|poseidon_gadget| MapGadget::new(&native_gadget, poseidon_gadget));
328        let secp256k1_scalar_chip = (config.secp256k1_scalar_config.as_ref())
329            .map(|scalar_config| FieldChip::new(scalar_config, &native_gadget));
330        let secp256k1_curve_chip = (config.secp256k1_config.as_ref())
331            .zip(secp256k1_scalar_chip.as_ref())
332            .map(|(curve_config, scalar_chip)| {
333                ForeignEccChip::new(curve_config, &native_gadget, scalar_chip, OsRng)
334            });
335        let bls12_381_curve_chip = (config.bls12_381_config.as_ref()).map(|curve_config| {
336            ForeignEccChip::new(curve_config, &native_gadget, &native_gadget, OsRng)
337        });
338
339        let base64_chip = (config.base64_config.as_ref())
340            .map(|base64_config| Base64Chip::new(base64_config, &native_gadget));
341
342        let parser_gadget = ParserGadget::new(&native_gadget);
343        let vector_gadget = VectorGadget::new(&native_gadget);
344        let automaton_chip =
345            config.automaton_config.as_ref().map(|c| AutomatonChip::new(c, &native_gadget));
346        let keccak_sha3_chip = config
347            .keccak_sha3_config
348            .as_ref()
349            .map(|sha3_config| KeccakSha3Wrapper::new(sha3_config, &native_gadget));
350        let blake2b_chip = config
351            .blake2b_config
352            .as_ref()
353            .map(|blake2b_config| Blake2bWrapper::new(blake2b_config, &native_gadget));
354
355        Self {
356            native_gadget,
357            core_decomposition_chip,
358            jubjub_chip,
359            sha2_256_chip,
360            sha2_512_chip,
361            poseidon_gadget,
362            map_gadget,
363            htc_gadget,
364            biguint_gadget,
365            secp256k1_scalar_chip,
366            secp256k1_curve_chip,
367            bls12_381_curve_chip,
368            base64_chip,
369            parser_gadget,
370            vector_gadget,
371            automaton_chip,
372            keccak_sha3_chip,
373            blake2b_chip,
374            used_sha2_256: Rc::new(RefCell::new(false)),
375            used_sha2_512: Rc::new(RefCell::new(false)),
376            used_secp256k1_scalar: Rc::new(RefCell::new(false)),
377            used_secp256k1_curve: Rc::new(RefCell::new(false)),
378            used_bls12_381_curve: Rc::new(RefCell::new(false)),
379            used_base64: Rc::new(RefCell::new(false)),
380            used_automaton: Rc::new(RefCell::new(false)),
381            used_keccak_or_sha3: Rc::new(RefCell::new(false)),
382            used_blake2b: Rc::new(RefCell::new(false)),
383        }
384    }
385
386    /// Configure [ZkStdLib] from scratch.
387    pub fn configure(meta: &mut ConstraintSystem<F>, arch: ZkStdLibArch) -> ZkStdLibConfig {
388        let nb_advice_cols = [
389            NB_ARITH_COLS,
390            arch.nr_pow2range_cols as usize,
391            arch.jubjub as usize * NB_EDWARDS_COLS,
392            arch.poseidon as usize * NB_POSEIDON_ADVICE_COLS,
393            arch.sha2_256 as usize * NB_SHA256_ADVICE_COLS,
394            arch.sha2_512 as usize * NB_SHA512_ADVICE_COLS,
395            arch.secp256k1 as usize
396                * max(
397                    nb_field_chip_columns::<F, secp256k1::Fq, MEP>(),
398                    nb_foreign_ecc_chip_columns::<F, Secp256k1, MEP, secp256k1::Fq>(),
399                ),
400            arch.bls12_381 as usize
401                * max(
402                    nb_field_chip_columns::<F, midnight_curves::Fp, MEP>(),
403                    nb_foreign_ecc_chip_columns::<
404                        F,
405                        midnight_curves::G1Projective,
406                        MEP,
407                        midnight_curves::Fp,
408                    >(),
409                ),
410            arch.base64 as usize * NB_BASE64_ADVICE_COLS,
411            arch.automaton as usize * NB_AUTOMATA_COLS,
412            (arch.keccak_256 || arch.sha3_256) as usize * PACKED_ADVICE_COLS,
413            arch.blake2b as usize * NB_BLAKE2B_ADVICE_COLS,
414        ]
415        .into_iter()
416        .max()
417        .unwrap_or(0);
418
419        let nb_fixed_cols = [
420            NB_ARITH_FIXED_COLS,
421            arch.poseidon as usize * NB_POSEIDON_FIXED_COLS,
422            arch.sha2_256 as usize * NB_SHA256_FIXED_COLS,
423            arch.sha2_512 as usize * NB_SHA512_FIXED_COLS,
424            (arch.keccak_256 || arch.sha3_256) as usize * PACKED_FIXED_COLS,
425        ]
426        .into_iter()
427        .max()
428        .unwrap_or(0);
429
430        let advice_columns = (0..nb_advice_cols).map(|_| meta.advice_column()).collect::<Vec<_>>();
431        let fixed_columns = (0..nb_fixed_cols).map(|_| meta.fixed_column()).collect::<Vec<_>>();
432        let committed_instance_column = meta.instance_column();
433        let instance_column = meta.instance_column();
434
435        let native_config = NativeChip::configure(
436            meta,
437            &(
438                advice_columns[..NB_ARITH_COLS].try_into().unwrap(),
439                fixed_columns[..NB_ARITH_FIXED_COLS].try_into().unwrap(),
440                [committed_instance_column, instance_column],
441            ),
442        );
443
444        let pow2range_config =
445            Pow2RangeChip::configure(meta, &advice_columns[1..=arch.nr_pow2range_cols as usize]);
446
447        let core_decomposition_config =
448            P2RDecompositionChip::configure(meta, &(native_config.clone(), pow2range_config));
449
450        let jubjub_config = arch.jubjub.then(|| {
451            EccChip::<C>::configure(meta, &advice_columns[..NB_EDWARDS_COLS].try_into().unwrap())
452        });
453
454        let sha2_256_config = arch.sha2_256.then(|| {
455            Sha256Chip::configure(
456                meta,
457                &(
458                    advice_columns[..NB_SHA256_ADVICE_COLS].try_into().unwrap(),
459                    fixed_columns[..NB_SHA256_FIXED_COLS].try_into().unwrap(),
460                ),
461            )
462        });
463
464        let sha2_512_config = arch.sha2_512.then(|| {
465            Sha512Chip::configure(
466                meta,
467                &(
468                    advice_columns[..NB_SHA512_ADVICE_COLS].try_into().unwrap(),
469                    fixed_columns[..NB_SHA512_FIXED_COLS].try_into().unwrap(),
470                ),
471            )
472        });
473
474        let poseidon_config = arch.poseidon.then(|| {
475            PoseidonChip::configure(
476                meta,
477                &(
478                    advice_columns[..NB_POSEIDON_ADVICE_COLS].try_into().unwrap(),
479                    fixed_columns[..NB_POSEIDON_FIXED_COLS].try_into().unwrap(),
480                ),
481            )
482        });
483
484        let secp256k1_scalar_config =
485            arch.secp256k1.then(|| Secp256k1ScalarChip::configure(meta, &advice_columns));
486
487        let secp256k1_config = arch.secp256k1.then(|| {
488            let base_config = Secp256k1BaseChip::configure(meta, &advice_columns);
489            Secp256k1Chip::configure(meta, &base_config, &advice_columns)
490        });
491
492        let bls12_381_config = arch.bls12_381.then(|| {
493            let base_config = Bls12381BaseChip::configure(meta, &advice_columns);
494            Bls12381Chip::configure(meta, &base_config, &advice_columns)
495        });
496
497        let base64_config = arch.base64.then(|| {
498            Base64Chip::configure(
499                meta,
500                advice_columns[..NB_BASE64_ADVICE_COLS].try_into().unwrap(),
501            )
502        });
503
504        let automaton_config = arch.automaton.then(|| {
505            AutomatonChip::configure(
506                meta,
507                &(
508                    advice_columns[..NB_AUTOMATA_COLS].try_into().unwrap(),
509                    parsing::spec_library(),
510                ),
511            )
512        });
513
514        let constant_column =
515            (arch.keccak_256 || arch.sha3_256 || arch.blake2b).then(|| meta.fixed_column());
516
517        let keccak_sha3_config = (arch.keccak_256 || arch.sha3_256).then(|| {
518            PackedChip::configure(
519                meta,
520                constant_column.unwrap(),
521                advice_columns[..PACKED_ADVICE_COLS].try_into().unwrap(),
522                fixed_columns[..PACKED_FIXED_COLS].try_into().unwrap(),
523            )
524        });
525
526        let blake2b_config = arch.blake2b.then(|| {
527            Blake2bChip::configure(
528                meta,
529                constant_column.unwrap(),
530                advice_columns[0],
531                advice_columns[1..NB_BLAKE2B_ADVICE_COLS].try_into().unwrap(),
532            )
533        });
534
535        ZkStdLibConfig {
536            native_config,
537            core_decomposition_config,
538            jubjub_config,
539            sha2_256_config,
540            sha2_512_config,
541            poseidon_config,
542            secp256k1_scalar_config,
543            secp256k1_config,
544            bls12_381_config,
545            base64_config,
546            automaton_config,
547            keccak_sha3_config,
548            blake2b_config,
549        }
550    }
551}
552
553impl ZkStdLib {
554    /// Native EccChip.
555    pub fn jubjub(&self) -> &EccChip<C> {
556        self.jubjub_chip.as_ref().expect("ZkStdLibArch must enable jubjub")
557    }
558
559    /// Gadget for performing in-circuit big-unsigned integer operations.
560    pub fn biguint(&self) -> &BigUintGadget<F, NG> {
561        &self.biguint_gadget
562    }
563
564    /// Gadget for performing map and non-map checks
565    pub fn map_gadget(&self) -> &MapGadget<F, NG, PoseidonChip<F>> {
566        self.map_gadget
567            .as_ref()
568            .unwrap_or_else(|| panic!("ZkStdLibArch must enable poseidon"))
569    }
570
571    /// Chip for performing in-circuit operations over the Secp256k1 scalar
572    /// field.
573    pub fn secp256k1_scalar(&self) -> &Secp256k1ScalarChip {
574        *self.used_secp256k1_scalar.borrow_mut() = true;
575        self.secp256k1_scalar_chip
576            .as_ref()
577            .unwrap_or_else(|| panic!("ZkStdLibArch must enable secp256k1"))
578    }
579
580    /// Chip for performing in-circuit operations over the Secp256k1 curve.
581    pub fn secp256k1_curve(&self) -> &Secp256k1Chip {
582        *self.used_secp256k1_curve.borrow_mut() = true;
583        self.secp256k1_curve_chip
584            .as_ref()
585            .unwrap_or_else(|| panic!("ZkStdLibArch must enable secp256k1"))
586    }
587
588    /// Chip for performing in-circuit operations over the BLS12-381 curve.
589    /// Note that this is the whole BLS curve (whose order is a 381-bits
590    /// integer). If you need to work over the BLS subgroup, you may want to
591    /// use [Bls12381Chip::assert_in_bls12_381_subgroup].
592    pub fn bls12_381_curve(&self) -> &Bls12381Chip {
593        *self.used_bls12_381_curve.borrow_mut() = true;
594        self.bls12_381_curve_chip
595            .as_ref()
596            .unwrap_or_else(|| panic!("ZkStdLibArch must enable bls12_381"))
597    }
598
599    /// Chip for performing in-circuit base64 decoding.
600    pub fn base64(&self) -> &Base64Chip<F> {
601        *self.used_base64.borrow_mut() = true;
602        self.base64_chip
603            .as_ref()
604            .unwrap_or_else(|| panic!("ZkStdLibArch must enable base64"))
605    }
606
607    /// Gadget for parsing properties of a JSON object.
608    pub fn parser(&self) -> &ParserGadget<F, NG> {
609        &self.parser_gadget
610    }
611
612    /// Chip for performing automaton-based parsing.
613    pub fn automaton(&self) -> &AutomatonChip<StdLibParser, F> {
614        *self.used_automaton.borrow_mut() = true;
615        (self.automaton_chip.as_ref())
616            .unwrap_or_else(|| panic!("ZkStdLibArch must enable automaton"))
617    }
618
619    /// Assert that a given assigned bit is true.
620    ///
621    /// ```
622    /// # midnight_zk_stdlib::run_test_stdlib!(chip, layouter, 13, {
623    /// let input: AssignedBit<F> = chip.assign_fixed(layouter, true)?;
624    /// chip.assert_true(layouter, &input)?;
625    /// # });
626    /// ```
627    pub fn assert_true(
628        &self,
629        layouter: &mut impl Layouter<F>,
630        input: &AssignedBit<F>,
631    ) -> Result<(), Error> {
632        self.native_gadget.assert_equal_to_fixed(layouter, input, true)
633    }
634
635    /// Assert that a given assigned bit is false
636    pub fn assert_false(
637        &self,
638        layouter: &mut impl Layouter<F>,
639        input: &AssignedBit<F>,
640    ) -> Result<(), Error> {
641        self.native_gadget.assert_equal_to_fixed(layouter, input, false)
642    }
643
644    /// Returns `1` iff `x < y`.
645    ///
646    /// ```
647    /// # midnight_zk_stdlib::run_test_stdlib!(chip, layouter, 13, {
648    /// let x: AssignedNative<F> = chip.assign_fixed(layouter, F::from(127))?;
649    /// let y: AssignedNative<F> = chip.assign_fixed(layouter, F::from(212))?;
650    /// let condition = chip.lower_than(layouter, &x, &y, 8)?;
651    ///
652    /// chip.assert_true(layouter, &condition)?;
653    /// # });
654    /// ```
655    ///
656    /// # Unsatisfiable Circuit
657    ///
658    /// If `x` or `y` are not in the range `[0, 2^n)`.
659    ///
660    /// ```should_panic
661    /// # midnight_zk_stdlib::run_test_stdlib!(chip, layouter, 13, {
662    /// let x: AssignedNative<F> = chip.assign_fixed(layouter, F::from(127))?;
663    /// let y: AssignedNative<F> = chip.assign_fixed(layouter, F::from(212))?;
664    /// let _condition = chip.lower_than(layouter, &x, &y, 7)?;
665    /// # });
666    /// ```
667    ///
668    /// Setting `n > (F::NUM_BITS - 1) / 2` will result in a compile-time
669    /// error.
670    pub fn lower_than(
671        &self,
672        layouter: &mut impl Layouter<F>,
673        x: &AssignedNative<F>,
674        y: &AssignedNative<F>,
675        n: u32,
676    ) -> Result<AssignedBit<F>, Error> {
677        let bounded_x = self.native_gadget.bounded_of_element(layouter, n as usize, x)?;
678        let bounded_y = self.native_gadget.bounded_of_element(layouter, n as usize, y)?;
679        self.native_gadget.lower_than(layouter, &bounded_x, &bounded_y)
680    }
681
682    /// Poseidon hash from a slice of native values into a native value.
683    ///
684    /// ```
685    /// # midnight_zk_stdlib::run_test_stdlib!(chip, layouter, 13, {
686    /// let x: AssignedNative<F> = chip.assign_fixed(layouter, F::from(127))?;
687    /// let y: AssignedNative<F> = chip.assign_fixed(layouter, F::from(212))?;
688    ///
689    /// let _hash = chip.poseidon(layouter, &[x, y])?;
690    /// # });
691    /// ```
692    pub fn poseidon(
693        &self,
694        layouter: &mut impl Layouter<F>,
695        input: &[AssignedNative<F>],
696    ) -> Result<AssignedNative<F>, Error> {
697        self.poseidon_gadget
698            .as_ref()
699            .unwrap_or_else(|| panic!("ZkStdLibArch must enable poseidon"))
700            .hash(layouter, input)
701    }
702
703    /// Hashes a slice of assigned values into `(x, y)` coordinates which are
704    /// guaranteed to be in the curve `C`. For usage, see [HashToCurveGadget].
705    pub fn hash_to_curve(
706        &self,
707        layouter: &mut impl Layouter<F>,
708        inputs: &[AssignedNative<F>],
709    ) -> Result<AssignedNativePoint<C>, Error> {
710        self.htc_gadget
711            .as_ref()
712            .unwrap_or_else(|| panic!("ZkStdLibArch must enable poseidon and jubjub"))
713            .hash_to_curve(layouter, inputs)
714    }
715
716    /// Sha2_256.
717    /// Takes as input a slice of assigned bytes and returns the assigned
718    /// input/output in bytes.
719    /// We assume the field uses little endian encoding.
720    /// ```
721    /// # midnight_zk_stdlib::run_test_stdlib!(chip, layouter, 13, {
722    /// let input = chip.assign_many(
723    ///     layouter,
724    ///     &[
725    ///         Value::known(13),
726    ///         Value::known(226),
727    ///         Value::known(119),
728    ///         Value::known(5),
729    ///     ],
730    /// )?;
731    ///
732    /// let _hash = chip.sha2_256(layouter, &input)?;
733    /// # });
734    /// ```
735    pub fn sha2_256(
736        &self,
737        layouter: &mut impl Layouter<F>,
738        input: &[AssignedByte<F>], // F -> decompose_bytes -> hash
739    ) -> Result<[AssignedByte<F>; 32], Error> {
740        *self.used_sha2_256.borrow_mut() = true;
741        self.sha2_256_chip
742            .as_ref()
743            .expect("ZkStdLibArch must enable sha256")
744            .hash(layouter, input)
745    }
746
747    /// Sha2_512 hash.
748    pub fn sha2_512(
749        &self,
750        layouter: &mut impl Layouter<F>,
751        input: &[AssignedByte<F>], // F -> decompose_bytes -> hash
752    ) -> Result<[AssignedByte<F>; 64], Error> {
753        *self.used_sha2_512.borrow_mut() = true;
754        self.sha2_512_chip
755            .as_ref()
756            .expect("ZkStdLibArch must enable sha512")
757            .hash(layouter, input)
758    }
759
760    /// Sha3_256 hash (third-party implementation).
761    pub fn sha3_256(
762        &self,
763        layouter: &mut impl Layouter<F>,
764        input: &[AssignedByte<F>],
765    ) -> Result<[AssignedByte<Fq>; 32], Error> {
766        *self.used_keccak_or_sha3.borrow_mut() = true;
767        let chip = self
768            .keccak_sha3_chip
769            .as_ref()
770            .expect("ZkStdLibArch must enable sha3 (or keccak)");
771        chip.sha3_256_digest(layouter, input)
772    }
773
774    /// keccak_256 hash (third-party implementation).
775    pub fn keccak_256(
776        &self,
777        layouter: &mut impl Layouter<F>,
778        input: &[AssignedByte<F>],
779    ) -> Result<[AssignedByte<Fq>; 32], Error> {
780        *self.used_keccak_or_sha3.borrow_mut() = true;
781        let chip = self
782            .keccak_sha3_chip
783            .as_ref()
784            .expect("ZkStdLibArch must enable keccak (or sha3)");
785        chip.keccak_256_digest(layouter, input)
786    }
787
788    /// Blake2b hash with a 256-bit output, unkeyed (third-party
789    /// implementation).
790    pub fn blake2b_256(
791        &self,
792        layouter: &mut impl Layouter<F>,
793        input: &[AssignedByte<F>],
794    ) -> Result<[AssignedByte<F>; 32], Error> {
795        *self.used_blake2b.borrow_mut() = true;
796        let chip = self.blake2b_chip.as_ref().expect("ZkStdLibArch must enable blake2b");
797        chip.blake2b_256_digest(layouter, input)
798    }
799
800    /// Blake2b hash with a 512-bit output, unkeyed (third-party
801    /// implementation).
802    pub fn blake2b_512(
803        &self,
804        layouter: &mut impl Layouter<F>,
805        input: &[AssignedByte<F>],
806    ) -> Result<[AssignedByte<F>; 64], Error> {
807        *self.used_blake2b.borrow_mut() = true;
808        let chip = self.blake2b_chip.as_ref().expect("ZkStdLibArch must enable blake2b");
809        chip.blake2b_512_digest(layouter, input)
810    }
811}
812
813impl<T> AssignmentInstructions<F, T> for ZkStdLib
814where
815    T: InnerValue,
816    T::Element: Clone,
817    NG: AssignmentInstructions<F, T>,
818{
819    fn assign(
820        &self,
821        layouter: &mut impl Layouter<F>,
822        value: Value<T::Element>,
823    ) -> Result<T, Error> {
824        self.native_gadget.assign(layouter, value)
825    }
826
827    fn assign_fixed(
828        &self,
829        layouter: &mut impl Layouter<F>,
830        constant: T::Element,
831    ) -> Result<T, Error> {
832        self.native_gadget.assign_fixed(layouter, constant)
833    }
834
835    fn assign_many(
836        &self,
837        layouter: &mut impl Layouter<F>,
838        values: &[Value<T::Element>],
839    ) -> Result<Vec<T>, Error> {
840        self.native_gadget.assign_many(layouter, values)
841    }
842}
843
844impl<T> PublicInputInstructions<F, T> for ZkStdLib
845where
846    T: Instantiable<F>,
847    T::Element: Clone,
848    NG: PublicInputInstructions<F, T>,
849{
850    fn as_public_input(
851        &self,
852        layouter: &mut impl Layouter<F>,
853        assigned: &T,
854    ) -> Result<Vec<AssignedNative<F>>, Error> {
855        self.native_gadget.as_public_input(layouter, assigned)
856    }
857
858    fn constrain_as_public_input(
859        &self,
860        layouter: &mut impl Layouter<F>,
861        assigned: &T,
862    ) -> Result<(), Error> {
863        self.native_gadget.constrain_as_public_input(layouter, assigned)
864    }
865
866    fn assign_as_public_input(
867        &self,
868        layouter: &mut impl Layouter<F>,
869        value: Value<<T>::Element>,
870    ) -> Result<T, Error> {
871        self.native_gadget.assign_as_public_input(layouter, value)
872    }
873}
874
875impl<T> CommittedInstanceInstructions<F, T> for ZkStdLib
876where
877    F: PrimeField,
878    T: Instantiable<F>,
879    NG: CommittedInstanceInstructions<F, T>,
880{
881    fn constrain_as_committed_public_input(
882        &self,
883        layouter: &mut impl Layouter<F>,
884        assigned: &T,
885    ) -> Result<(), Error> {
886        self.native_gadget.constrain_as_committed_public_input(layouter, assigned)
887    }
888}
889
890impl<T> AssertionInstructions<F, T> for ZkStdLib
891where
892    T: InnerValue,
893    NG: AssertionInstructions<F, T>,
894{
895    fn assert_equal(&self, layouter: &mut impl Layouter<F>, x: &T, y: &T) -> Result<(), Error> {
896        self.native_gadget.assert_equal(layouter, x, y)
897    }
898
899    fn assert_not_equal(&self, layouter: &mut impl Layouter<F>, x: &T, y: &T) -> Result<(), Error> {
900        self.native_gadget.assert_not_equal(layouter, x, y)
901    }
902
903    fn assert_equal_to_fixed(
904        &self,
905        layouter: &mut impl Layouter<F>,
906        x: &T,
907        constant: T::Element,
908    ) -> Result<(), Error> {
909        self.native_gadget.assert_equal_to_fixed(layouter, x, constant)
910    }
911
912    fn assert_not_equal_to_fixed(
913        &self,
914        layouter: &mut impl Layouter<F>,
915        x: &T,
916        constant: T::Element,
917    ) -> Result<(), Error> {
918        self.native_gadget.assert_not_equal_to_fixed(layouter, x, constant)
919    }
920}
921
922impl<T> EqualityInstructions<F, T> for ZkStdLib
923where
924    T: InnerValue,
925    NG: EqualityInstructions<F, T>,
926{
927    fn is_equal(
928        &self,
929        layouter: &mut impl Layouter<F>,
930        x: &T,
931        y: &T,
932    ) -> Result<AssignedBit<F>, Error> {
933        self.native_gadget.is_equal(layouter, x, y)
934    }
935
936    fn is_not_equal(
937        &self,
938        layouter: &mut impl Layouter<F>,
939        x: &T,
940        y: &T,
941    ) -> Result<AssignedBit<F>, Error> {
942        self.native_gadget.is_not_equal(layouter, x, y)
943    }
944
945    fn is_equal_to_fixed(
946        &self,
947        layouter: &mut impl Layouter<F>,
948        x: &T,
949        constant: T::Element,
950    ) -> Result<AssignedBit<F>, Error> {
951        self.native_gadget.is_equal_to_fixed(layouter, x, constant)
952    }
953
954    fn is_not_equal_to_fixed(
955        &self,
956        layouter: &mut impl Layouter<F>,
957        x: &T,
958        constant: T::Element,
959    ) -> Result<AssignedBit<F>, Error> {
960        self.native_gadget.is_not_equal_to_fixed(layouter, x, constant)
961    }
962}
963
964impl<T1, T2> ConversionInstructions<F, T1, T2> for ZkStdLib
965where
966    T1: InnerValue,
967    T2: InnerValue,
968    NG: ConversionInstructions<F, T1, T2>,
969{
970    fn convert_value(&self, x: &T1::Element) -> Option<T2::Element> {
971        ConversionInstructions::<_, T1, T2>::convert_value(&self.native_gadget, x)
972    }
973
974    fn convert(&self, layouter: &mut impl Layouter<F>, x: &T1) -> Result<T2, Error> {
975        self.native_gadget.convert(layouter, x)
976    }
977}
978
979impl CanonicityInstructions<F, AssignedNative<F>> for ZkStdLib {
980    fn le_bits_lower_than(
981        &self,
982        layouter: &mut impl Layouter<F>,
983        bits: &[AssignedBit<F>],
984        bound: BigUint,
985    ) -> Result<AssignedBit<F>, Error> {
986        self.native_gadget.le_bits_lower_than(layouter, bits, bound)
987    }
988
989    fn le_bits_geq_than(
990        &self,
991        layouter: &mut impl Layouter<F>,
992        bits: &[AssignedBit<F>],
993        bound: BigUint,
994    ) -> Result<AssignedBit<F>, Error> {
995        self.native_gadget.le_bits_geq_than(layouter, bits, bound)
996    }
997}
998
999impl DecompositionInstructions<F, AssignedNative<F>> for ZkStdLib {
1000    fn assigned_to_le_bits(
1001        &self,
1002        layouter: &mut impl Layouter<F>,
1003        x: &AssignedNative<F>,
1004        nb_bits: Option<usize>,
1005        enforce_canonical: bool,
1006    ) -> Result<Vec<AssignedBit<F>>, Error> {
1007        self.native_gadget.assigned_to_le_bits(layouter, x, nb_bits, enforce_canonical)
1008    }
1009
1010    fn assigned_to_le_bytes(
1011        &self,
1012        layouter: &mut impl Layouter<F>,
1013        x: &AssignedNative<F>,
1014        nb_bytes: Option<usize>,
1015    ) -> Result<Vec<AssignedByte<F>>, Error> {
1016        self.native_gadget.assigned_to_le_bytes(layouter, x, nb_bytes)
1017    }
1018
1019    fn assigned_to_le_chunks(
1020        &self,
1021        layouter: &mut impl Layouter<F>,
1022        x: &AssignedNative<F>,
1023        nb_bits_per_chunk: usize,
1024        nb_chunks: Option<usize>,
1025    ) -> Result<Vec<AssignedNative<F>>, Error> {
1026        self.native_gadget
1027            .assigned_to_le_chunks(layouter, x, nb_bits_per_chunk, nb_chunks)
1028    }
1029
1030    fn sgn0(
1031        &self,
1032        layouter: &mut impl Layouter<F>,
1033        x: &AssignedNative<F>,
1034    ) -> Result<AssignedBit<F>, Error> {
1035        self.native_gadget.sgn0(layouter, x)
1036    }
1037}
1038
1039impl ArithInstructions<F, AssignedNative<F>> for ZkStdLib {
1040    fn linear_combination(
1041        &self,
1042        layouter: &mut impl Layouter<F>,
1043        terms: &[(F, AssignedNative<F>)],
1044        constant: F,
1045    ) -> Result<AssignedNative<F>, Error> {
1046        self.native_gadget.linear_combination(layouter, terms, constant)
1047    }
1048
1049    fn mul(
1050        &self,
1051        layouter: &mut impl Layouter<F>,
1052        x: &AssignedNative<F>,
1053        y: &AssignedNative<F>,
1054        multiplying_constant: Option<F>,
1055    ) -> Result<AssignedNative<F>, Error> {
1056        self.native_gadget.mul(layouter, x, y, multiplying_constant)
1057    }
1058
1059    fn div(
1060        &self,
1061        layouter: &mut impl Layouter<F>,
1062        x: &AssignedNative<F>,
1063        y: &AssignedNative<F>,
1064    ) -> Result<AssignedNative<F>, Error> {
1065        self.native_gadget.div(layouter, x, y)
1066    }
1067
1068    fn inv(
1069        &self,
1070        layouter: &mut impl Layouter<F>,
1071        x: &AssignedNative<F>,
1072    ) -> Result<AssignedNative<F>, Error> {
1073        self.native_gadget.inv(layouter, x)
1074    }
1075
1076    fn inv0(
1077        &self,
1078        layouter: &mut impl Layouter<F>,
1079        x: &AssignedNative<F>,
1080    ) -> Result<AssignedNative<F>, Error> {
1081        self.native_gadget.inv0(layouter, x)
1082    }
1083}
1084
1085impl ZeroInstructions<F, AssignedNative<F>> for ZkStdLib {}
1086
1087impl<Assigned> ControlFlowInstructions<F, Assigned> for ZkStdLib
1088where
1089    Assigned: InnerValue,
1090    NG: ControlFlowInstructions<F, Assigned>,
1091{
1092    fn select(
1093        &self,
1094        layouter: &mut impl Layouter<F>,
1095        cond: &AssignedBit<F>,
1096        x: &Assigned,
1097        y: &Assigned,
1098    ) -> Result<Assigned, Error> {
1099        self.native_gadget.select(layouter, cond, x, y)
1100    }
1101
1102    fn cond_swap(
1103        &self,
1104        layouter: &mut impl Layouter<F>,
1105        cond: &AssignedBit<F>,
1106        x: &Assigned,
1107        y: &Assigned,
1108    ) -> Result<(Assigned, Assigned), Error> {
1109        self.native_gadget.cond_swap(layouter, cond, x, y)
1110    }
1111}
1112
1113impl FieldInstructions<F, AssignedNative<F>> for ZkStdLib {
1114    fn order(&self) -> BigUint {
1115        self.native_gadget.order()
1116    }
1117}
1118
1119impl RangeCheckInstructions<F, AssignedNative<F>> for ZkStdLib {
1120    fn assign_lower_than_fixed(
1121        &self,
1122        layouter: &mut impl Layouter<F>,
1123        value: Value<F>,
1124        bound: &BigUint,
1125    ) -> Result<AssignedNative<F>, Error> {
1126        self.native_gadget.assign_lower_than_fixed(layouter, value, bound)
1127    }
1128
1129    fn assert_lower_than_fixed(
1130        &self,
1131        layouter: &mut impl Layouter<F>,
1132        x: &AssignedNative<F>,
1133        bound: &BigUint,
1134    ) -> Result<(), Error> {
1135        self.native_gadget.assert_lower_than_fixed(layouter, x, bound)
1136    }
1137}
1138
1139impl DivisionInstructions<F, AssignedNative<F>> for ZkStdLib {}
1140
1141impl BinaryInstructions<F> for ZkStdLib {
1142    fn and(
1143        &self,
1144        layouter: &mut impl Layouter<F>,
1145        bits: &[AssignedBit<F>],
1146    ) -> Result<AssignedBit<F>, Error> {
1147        self.native_gadget.and(layouter, bits)
1148    }
1149
1150    fn or(
1151        &self,
1152        layouter: &mut impl Layouter<F>,
1153        bits: &[AssignedBit<F>],
1154    ) -> Result<AssignedBit<F>, Error> {
1155        self.native_gadget.or(layouter, bits)
1156    }
1157
1158    fn xor(
1159        &self,
1160        layouter: &mut impl Layouter<F>,
1161        bits: &[AssignedBit<F>],
1162    ) -> Result<AssignedBit<F>, Error> {
1163        self.native_gadget.xor(layouter, bits)
1164    }
1165
1166    fn not(
1167        &self,
1168        layouter: &mut impl Layouter<F>,
1169        bit: &AssignedBit<F>,
1170    ) -> Result<AssignedBit<F>, Error> {
1171        self.native_gadget.not(layouter, bit)
1172    }
1173}
1174
1175impl BitwiseInstructions<F, AssignedNative<F>> for ZkStdLib {}
1176
1177impl<const M: usize, const A: usize, T> VectorInstructions<F, T, M, A> for ZkStdLib
1178where
1179    T: Vectorizable,
1180    T::Element: Copy,
1181    NG: AssignmentInstructions<F, T> + ControlFlowInstructions<F, T>,
1182{
1183    fn trim_beginning(
1184        &self,
1185        layouter: &mut impl Layouter<F>,
1186        input: &AssignedVector<F, T, M, A>,
1187        n_elems: usize,
1188    ) -> Result<AssignedVector<F, T, M, A>, Error> {
1189        self.vector_gadget.trim_beginning(layouter, input, n_elems)
1190    }
1191
1192    fn padding_flag(
1193        &self,
1194        layouter: &mut impl Layouter<F>,
1195        input: &AssignedVector<F, T, M, A>,
1196    ) -> Result<[AssignedBit<F>; M], Error> {
1197        self.vector_gadget.padding_flag(layouter, input)
1198    }
1199
1200    fn get_limits(
1201        &self,
1202        layouter: &mut impl Layouter<F>,
1203        input: &AssignedVector<F, T, M, A>,
1204    ) -> Result<(AssignedNative<F>, AssignedNative<F>), Error> {
1205        self.vector_gadget.get_limits(layouter, input)
1206    }
1207
1208    fn resize<const L: usize>(
1209        &self,
1210        layouter: &mut impl Layouter<F>,
1211        input: AssignedVector<F, T, M, A>,
1212    ) -> Result<AssignedVector<F, T, L, A>, Error> {
1213        self.vector_gadget.resize(layouter, input)
1214    }
1215
1216    fn assign_with_filler(
1217        &self,
1218        layouter: &mut impl Layouter<F>,
1219        value: Value<Vec<<T>::Element>>,
1220        filler: Option<<T>::Element>,
1221    ) -> Result<AssignedVector<F, T, M, A>, Error> {
1222        self.vector_gadget.assign_with_filler(layouter, value, filler)
1223    }
1224}
1225
1226/// Circuit structure which is used to create any circuit that can be compiled
1227/// into keys using the ZK standard library.
1228#[derive(Clone, Debug)]
1229pub struct MidnightCircuit<'a, R: Relation> {
1230    relation: &'a R,
1231    max_bit_len: u8,
1232    instance: Value<R::Instance>,
1233    witness: Value<R::Witness>,
1234    nb_public_inputs: Rc<RefCell<Option<usize>>>,
1235}
1236
1237impl<'a, R: Relation> MidnightCircuit<'a, R> {
1238    /// A MidnightCircuit with unknown instance-witness for the given relation.
1239    pub fn from_relation(relation: &'a R) -> Self {
1240        MidnightCircuit::new(relation, Value::unknown(), Value::unknown(), None)
1241    }
1242
1243    /// Creates a new MidnightCircuit for the given relation. If not provided,
1244    /// this function selects the optimal max_bit_len for the pow2range table.
1245    pub fn new(
1246        relation: &'a R,
1247        instance: Value<R::Instance>,
1248        witness: Value<R::Witness>,
1249        max_bit_len_opt: Option<u8>,
1250    ) -> Self {
1251        if let Some(max_bit_len) = max_bit_len_opt {
1252            return MidnightCircuit {
1253                relation,
1254                max_bit_len,
1255                instance,
1256                witness,
1257                nb_public_inputs: Rc::new(RefCell::new(None)),
1258            };
1259        }
1260
1261        let model_with_max_bit_len = |max_bit_len: u8| -> CircuitModel {
1262            circuit_model::<_, 48, 32>(&MidnightCircuit {
1263                relation,
1264                max_bit_len,
1265                instance: Value::unknown(),
1266                witness: Value::unknown(),
1267                nb_public_inputs: Rc::new(RefCell::new(None)),
1268            })
1269        };
1270
1271        let mut best_k = u32::MAX;
1272        let mut best_max_bit_len = 8;
1273
1274        // Loop for finding the optimal `max_bit_len`.
1275        for max_bit_len in 8..25 {
1276            let model = model_with_max_bit_len(max_bit_len);
1277
1278            if model.k < best_k {
1279                best_k = model.k;
1280                best_max_bit_len = max_bit_len;
1281            }
1282
1283            // Stop when the table becomes the bottleneck.
1284            if model.rows < (1 << (max_bit_len + 1)) {
1285                break;
1286            }
1287        }
1288
1289        MidnightCircuit {
1290            relation,
1291            max_bit_len: best_max_bit_len,
1292            instance,
1293            witness,
1294            nb_public_inputs: Rc::new(RefCell::new(None)),
1295        }
1296    }
1297
1298    /// The minimum `k` necessary to implement this circuit.
1299    pub fn min_k(&self) -> u32 {
1300        k_from_circuit(self)
1301    }
1302}
1303
1304/// A verifier key of a Midnight circuit.
1305#[derive(Clone, Debug)]
1306pub struct MidnightVK {
1307    architecture: ZkStdLibArch,
1308    max_bit_len: u8,
1309    nb_public_inputs: usize,
1310    vk: VerifyingKey<midnight_curves::Fq, KZGCommitmentScheme<midnight_curves::Bls12>>,
1311}
1312
1313impl MidnightVK {
1314    /// Writes a verifying key to a buffer.
1315    ///
1316    /// Depending on the `format`:
1317    /// - `Processed`: Takes less space, but more time to read.
1318    /// - `RawBytes`: Takes more space, but faster to read.
1319    ///
1320    /// Using `RawBytesUnchecked` will have the same effect as `RawBytes`,
1321    /// but it is not recommended.
1322    pub fn write<W: io::Write>(&self, writer: &mut W, format: SerdeFormat) -> io::Result<()> {
1323        self.architecture.write(writer)?;
1324
1325        writer.write_all(&[self.max_bit_len])?;
1326
1327        writer.write_all(&(self.nb_public_inputs as u32).to_le_bytes())?;
1328
1329        self.vk.write(writer, format)
1330    }
1331
1332    /// Reads a verification key from a buffer.
1333    ///
1334    /// The `format` must match the one that was used when writing the key.
1335    /// If the key was written with `RawBytes`, it can be read with `RawBytes`
1336    /// or `RawBytesUnchecked` (which is faster).
1337    ///
1338    /// # WARNING
1339    /// Use `RawBytesUnchecked` only if you trust the party who wrote the key.
1340    pub fn read<R: io::Read>(reader: &mut R, format: SerdeFormat) -> io::Result<Self> {
1341        let architecture = ZkStdLibArch::read(reader)?;
1342
1343        let mut byte = [0u8; 1];
1344        reader.read_exact(&mut byte)?;
1345        let max_bit_len = byte[0];
1346
1347        let mut bytes = [0u8; 4];
1348        reader.read_exact(&mut bytes)?;
1349        let nb_public_inputs = u32::from_le_bytes(bytes) as usize;
1350
1351        let mut cs = ConstraintSystem::default();
1352        let _config = ZkStdLib::configure(&mut cs, architecture);
1353
1354        let vk = VerifyingKey::read_from_cs::<R>(reader, format, cs)?;
1355
1356        Ok(MidnightVK {
1357            architecture,
1358            max_bit_len,
1359            nb_public_inputs,
1360            vk,
1361        })
1362    }
1363
1364    /// The size of the domain associated to this verifying key.
1365    pub fn k(&self) -> u8 {
1366        self.vk.get_domain().k() as u8
1367    }
1368
1369    /// The underlying midnight-proofs verifying key.
1370    pub fn vk(
1371        &self,
1372    ) -> &VerifyingKey<midnight_curves::Fq, KZGCommitmentScheme<midnight_curves::Bls12>> {
1373        &self.vk
1374    }
1375}
1376
1377/// A proving key of a Midnight circuit.
1378#[derive(Clone, Debug)]
1379pub struct MidnightPK<R: Relation> {
1380    max_bit_len: u8,
1381    k: u8,
1382    relation: R,
1383    pk: ProvingKey<midnight_curves::Fq, KZGCommitmentScheme<midnight_curves::Bls12>>,
1384}
1385
1386impl<Rel: Relation> MidnightPK<Rel> {
1387    /// Writes a proving key to a buffer.
1388    ///
1389    /// Depending on the `format`:
1390    /// - `Processed`: Takes less space, but more time to read.
1391    /// - `RawBytes`: Takes more space, but faster to read.
1392    ///
1393    /// Using `RawBytesUnchecked` will have the same effect as `RawBytes`,
1394    /// but it is not recommended.
1395    pub fn write<W: io::Write>(&self, writer: &mut W, format: SerdeFormat) -> io::Result<()> {
1396        writer.write_all(&[self.max_bit_len])?;
1397        writer.write_all(&[self.k])?;
1398
1399        Rel::write_relation(&self.relation, writer)?;
1400
1401        self.pk.write(writer, format)
1402    }
1403
1404    /// Reads a proving key from a buffer.
1405    ///
1406    /// The `format` must match the one that was used when writing the key.
1407    /// If the key was written with `RawBytes`, it can be read with `RawBytes`
1408    /// or `RawBytesUnchecked` (which is faster).
1409    ///
1410    /// # WARNING
1411    /// Use `RawBytesUnchecked` only if you trust the party who wrote the key.
1412    pub fn read<R: io::Read>(reader: &mut R, format: SerdeFormat) -> io::Result<Self> {
1413        let mut byte = [0u8; 1];
1414
1415        reader.read_exact(&mut byte)?;
1416        let max_bit_len = byte[0];
1417
1418        reader.read_exact(&mut byte)?;
1419        let k = byte[0];
1420
1421        let relation = Rel::read_relation(reader)?;
1422
1423        let pk = ProvingKey::read::<R, MidnightCircuit<Rel>>(
1424            reader,
1425            format,
1426            MidnightCircuit::new(
1427                &relation,
1428                Value::unknown(),
1429                Value::unknown(),
1430                Some(max_bit_len),
1431            )
1432            .params(),
1433        )?;
1434
1435        Ok(MidnightPK {
1436            max_bit_len,
1437            k,
1438            relation,
1439            pk,
1440        })
1441    }
1442
1443    /// The size of the domain associated to this proving key.
1444    pub fn k(&self) -> u8 {
1445        self.k
1446    }
1447
1448    /// The underlying midnight-proofs proving key.
1449    pub fn pk(
1450        &self,
1451    ) -> &ProvingKey<midnight_curves::Fq, KZGCommitmentScheme<midnight_curves::Bls12>> {
1452        &self.pk
1453    }
1454}
1455
1456/// Helper trait, used to abstract the circuit developer from Halo2's
1457/// boilerplate.
1458///
1459/// `Relation` has a default implementation for loading only the tables
1460/// needed for the requested chips. The developer needs to implement the
1461/// function [Relation::circuit], which essentially contains the
1462/// statement of the proof we are creating.
1463///
1464/// # Important note
1465///
1466/// The API provided here guarantees that the number of public inputs
1467/// used during verification matches the number of public inputs (as raw
1468/// scalars) declared in [Relation::circuit] through the
1469/// [PublicInputInstructions] interface. Proof verification will fail if
1470/// this requirement is not met.
1471///
1472/// # Example
1473///
1474/// ```
1475/// # use midnight_circuits::{
1476/// #     instructions::{AssignmentInstructions, PublicInputInstructions},
1477/// #     types::{AssignedByte, Instantiable},
1478/// # };
1479/// # use midnight_zk_stdlib::{utils::plonk_api::filecoin_srs, Relation, ZkStdLib, ZkStdLibArch};
1480/// # use midnight_proofs::{
1481/// #     circuit::{Layouter, Value},
1482/// #     plonk::Error,
1483/// # };
1484/// # use rand::{rngs::OsRng, Rng, SeedableRng};
1485/// # use rand_chacha::ChaCha8Rng;
1486/// # use sha2::Digest;
1487/// #
1488/// type F = midnight_curves::Fq;
1489///
1490/// #[derive(Clone, Default)]
1491/// struct ShaPreImageCircuit;
1492///
1493/// impl Relation for ShaPreImageCircuit {
1494///     // When defining a circuit, one must clearly state the instance and the witness
1495///     // of the underlying NP-relation.
1496///     type Instance = [u8; 32];
1497///     type Witness = [u8; 24]; // 192 = 24 * 8
1498///
1499///     // We must specify how the instance is converted into raw field elements to
1500///     // be process by the prover/verifier. The order here must be consistent with
1501///     // the order in which public inputs are constrained/assigned in [circuit].
1502///     fn format_instance(instance: &Self::Instance) -> Result<Vec<F>, Error> {
1503///         Ok(instance.iter().flat_map(AssignedByte::<F>::as_public_input).collect())
1504///     }
1505///
1506///     // Define the logic of the NP-relation being proved.
1507///     fn circuit(
1508///         &self,
1509///         std_lib: &ZkStdLib,
1510///         layouter: &mut impl Layouter<F>,
1511///         _instance: Value<Self::Instance>,
1512///         witness: Value<Self::Witness>,
1513///     ) -> Result<(), Error> {
1514///         let assigned_input = std_lib.assign_many(layouter, &witness.transpose_array())?;
1515///         let output = std_lib.sha2_256(layouter, &assigned_input)?;
1516///         output.iter().try_for_each(|b| std_lib.constrain_as_public_input(layouter, b))
1517///     }
1518///
1519///     fn used_chips(&self) -> ZkStdLibArch {
1520///         ZkStdLibArch {
1521///             sha2_256: true,
1522///             ..ZkStdLibArch::default()
1523///         }
1524///     }
1525///
1526///     fn write_relation<W: std::io::Write>(&self, _writer: &mut W) -> std::io::Result<()> {
1527///         Ok(())
1528///     }
1529///
1530///     fn read_relation<R: std::io::Read>(_reader: &mut R) -> std::io::Result<Self> {
1531///         Ok(ShaPreImageCircuit)
1532///     }
1533/// }
1534///
1535/// const K: u32 = 13;
1536/// let mut srs = filecoin_srs(K);
1537///
1538/// let relation = ShaPreImageCircuit;
1539///
1540/// let vk = midnight_zk_stdlib::setup_vk(&srs, &relation);
1541/// let pk = midnight_zk_stdlib::setup_pk(&relation, &vk);
1542///
1543/// let mut rng = ChaCha8Rng::from_entropy();
1544/// let witness: [u8; 24] = core::array::from_fn(|_| rng.gen());
1545/// let instance = sha2::Sha256::digest(witness).into();
1546///
1547/// let proof = midnight_zk_stdlib::prove::<ShaPreImageCircuit, blake2b_simd::State>(
1548///     &srs, &pk, &relation, &instance, witness, OsRng,
1549/// )
1550/// .expect("Proof generation should not fail");
1551///
1552/// assert!(
1553///     midnight_zk_stdlib::verify::<ShaPreImageCircuit, blake2b_simd::State>(
1554///         &srs.verifier_params(),
1555///         &vk,
1556///         &instance,
1557///         None,
1558///         &proof
1559///     )
1560///     .is_ok()
1561/// )
1562/// ```
1563pub trait Relation: Clone {
1564    /// The instance of the NP-relation described by this circuit.
1565    type Instance: Clone;
1566
1567    /// The witness of the NP-relation described by this circuit.
1568    type Witness: Clone;
1569
1570    /// Produces a vector of field elements in PLONK format representing the
1571    /// given [Self::Instance].
1572    fn format_instance(instance: &Self::Instance) -> Result<Vec<F>, Error>;
1573
1574    /// Produces a vector of field elements in PLONK format representing the
1575    /// data inside the committed instance.
1576    fn format_committed_instances(_witness: &Self::Witness) -> Vec<F> {
1577        vec![]
1578    }
1579
1580    /// Defines the circuit's logic.
1581    fn circuit(
1582        &self,
1583        std_lib: &ZkStdLib,
1584        layouter: &mut impl Layouter<F>,
1585        instance: Value<Self::Instance>,
1586        witness: Value<Self::Witness>,
1587    ) -> Result<(), Error>;
1588
1589    /// Specifies what chips are enabled in the standard library. A chip needs
1590    /// to be enabled if it is used in [Self::circuit], but it can also be
1591    /// enabled even if it is not used (possibly to share the same architecture
1592    /// with other circuits).
1593    ///
1594    /// The blanket implementation enables none of them.
1595    fn used_chips(&self) -> ZkStdLibArch {
1596        ZkStdLibArch::default()
1597    }
1598
1599    /// Writes a relation to a buffer.
1600    fn write_relation<W: io::Write>(&self, writer: &mut W) -> io::Result<()>;
1601
1602    /// Reads a relation from a buffer.
1603    fn read_relation<R: io::Read>(reader: &mut R) -> io::Result<Self>;
1604}
1605
1606impl<R: Relation> Circuit<F> for MidnightCircuit<'_, R> {
1607    type Config = ZkStdLibConfig;
1608
1609    // FIXME: this could be parametrised by MidnightCircuit.
1610    type FloorPlanner = SimpleFloorPlanner;
1611
1612    type Params = ZkStdLibArch;
1613
1614    fn without_witnesses(&self) -> Self {
1615        unreachable!()
1616    }
1617
1618    fn params(&self) -> Self::Params {
1619        self.relation.used_chips()
1620    }
1621
1622    fn configure_with_params(meta: &mut ConstraintSystem<F>, arch: ZkStdLibArch) -> Self::Config {
1623        ZkStdLib::configure(meta, arch)
1624    }
1625
1626    fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
1627        ZkStdLib::configure(meta, ZkStdLibArch::default())
1628    }
1629
1630    fn synthesize(
1631        &self,
1632        config: Self::Config,
1633        mut layouter: impl Layouter<F>,
1634    ) -> Result<(), Error> {
1635        let zk_std_lib = ZkStdLib::new(&config, self.max_bit_len as usize);
1636
1637        self.relation.circuit(
1638            &zk_std_lib,
1639            &mut layouter.namespace(|| "Running logic circuit"),
1640            self.instance.clone(),
1641            self.witness.clone(),
1642        )?;
1643
1644        // After the circuit function has been called, we can update the expected
1645        // number of raw public inputs in [Self] (via a RefCell). This number will
1646        // be stored in the MidnightVK so that we can make sure it matches the number of
1647        // public inputs provided during verification.
1648        *self.nb_public_inputs.borrow_mut() =
1649            Some(zk_std_lib.native_gadget.native_chip.nb_public_inputs());
1650
1651        // We load the tables at the end, once we have figured out what chips/gadgets
1652        // were actually used.
1653        zk_std_lib.core_decomposition_chip.load(&mut layouter)?;
1654
1655        if let Some(sha256_chip) = zk_std_lib.sha2_256_chip {
1656            if *zk_std_lib.used_sha2_256.borrow() {
1657                sha256_chip.load(&mut layouter)?;
1658            }
1659        }
1660
1661        if let Some(sha512_chip) = zk_std_lib.sha2_512_chip {
1662            if *zk_std_lib.used_sha2_512.borrow() {
1663                sha512_chip.load(&mut layouter)?;
1664            }
1665        }
1666
1667        if let Some(b64_chip) = zk_std_lib.base64_chip {
1668            if *zk_std_lib.used_base64.borrow() {
1669                b64_chip.load(&mut layouter)?;
1670            }
1671        }
1672
1673        if let Some(automaton_chip) = zk_std_lib.automaton_chip {
1674            if *zk_std_lib.used_automaton.borrow() {
1675                automaton_chip.load(&mut layouter)?;
1676            }
1677        }
1678
1679        if let Some(keccak_sha3_chip) = zk_std_lib.keccak_sha3_chip {
1680            if *zk_std_lib.used_keccak_or_sha3.borrow() {
1681                keccak_sha3_chip.load(&mut layouter)?;
1682            }
1683        }
1684
1685        if let Some(blake2b_chip) = zk_std_lib.blake2b_chip {
1686            if *zk_std_lib.used_blake2b.borrow() {
1687                blake2b_chip.load(&mut layouter)?;
1688            }
1689        }
1690
1691        Ok(())
1692    }
1693}
1694
1695/// Downsizes the given SRS to the size required by the given circuit (which is
1696/// computed automatically). This step does not need to be done if you know that
1697/// the SRS already has the correct size.
1698pub fn downsize_srs_for_relation<R: Relation>(
1699    srs: &mut ParamsKZG<midnight_curves::Bls12>,
1700    relation: &R,
1701) {
1702    srs.downsize_from_circuit(&MidnightCircuit::from_relation(relation))
1703}
1704
1705/// Generates a verifying key for a `MidnightCircuit<R>` circuit. Downsizes the
1706/// parameters to match the size of the Relation.
1707pub fn setup_vk<R: Relation>(
1708    params: &ParamsKZG<midnight_curves::Bls12>,
1709    relation: &R,
1710) -> MidnightVK {
1711    let circuit = MidnightCircuit::from_relation(relation);
1712    let vk = BlstPLONK::<MidnightCircuit<R>>::setup_vk(params, &circuit);
1713
1714    // During the call to [setup_vk] the circuit RefCell on public inputs has been
1715    // mutated with the correct value. The following [unwrap] is safe here.
1716    let nb_public_inputs = circuit.nb_public_inputs.clone().borrow().unwrap();
1717
1718    MidnightVK {
1719        architecture: relation.used_chips(),
1720        max_bit_len: circuit.max_bit_len,
1721        nb_public_inputs,
1722        vk,
1723    }
1724}
1725
1726/// Generates a proving key for a `MidnightCircuit<R>` circuit.
1727pub fn setup_pk<R: Relation>(relation: &R, vk: &MidnightVK) -> MidnightPK<R> {
1728    let circuit = MidnightCircuit::new(
1729        relation,
1730        Value::unknown(),
1731        Value::unknown(),
1732        Some(vk.max_bit_len),
1733    );
1734    let pk = BlstPLONK::<MidnightCircuit<R>>::setup_pk(&circuit, &vk.vk);
1735    MidnightPK {
1736        max_bit_len: vk.max_bit_len,
1737        k: vk.vk.get_domain().k() as u8,
1738        relation: relation.clone(),
1739        pk,
1740    }
1741}
1742
1743/// Produces a proof of relation `R` for the given instance (using the given
1744/// proving key and witness).
1745pub fn prove<R: Relation, H: TranscriptHash>(
1746    params: &ParamsKZG<midnight_curves::Bls12>,
1747    pk: &MidnightPK<R>,
1748    relation: &R,
1749    instance: &R::Instance,
1750    witness: R::Witness,
1751    rng: impl RngCore + CryptoRng,
1752) -> Result<Vec<u8>, Error>
1753where
1754    G1Projective: Hashable<H>,
1755    F: Hashable<H> + Sampleable<H>,
1756{
1757    let pi = R::format_instance(instance)?;
1758    let com_inst = R::format_committed_instances(&witness);
1759    let circuit = MidnightCircuit::new(
1760        relation,
1761        Value::known(instance.clone()),
1762        Value::known(witness),
1763        Some(pk.max_bit_len),
1764    );
1765    BlstPLONK::<MidnightCircuit<R>>::prove::<H>(
1766        params,
1767        &pk.pk,
1768        &circuit,
1769        1,
1770        &[com_inst.as_slice(), &pi],
1771        rng,
1772    )
1773}
1774
1775/// Verifies the given proof of relation `R` with respect to the given instance.
1776/// Returns `Ok(())` if the proof is valid.
1777pub fn verify<R: Relation, H: TranscriptHash>(
1778    params_verifier: &ParamsVerifierKZG<midnight_curves::Bls12>,
1779    vk: &MidnightVK,
1780    instance: &R::Instance,
1781    committed_instance: Option<G1Affine>,
1782    proof: &[u8],
1783) -> Result<(), Error>
1784where
1785    G1Projective: Hashable<H>,
1786    F: Hashable<H> + Sampleable<H>,
1787{
1788    let pi = R::format_instance(instance)?;
1789    let committed_pi = committed_instance.unwrap_or(G1Affine::identity());
1790    if pi.len() != vk.nb_public_inputs {
1791        return Err(Error::InvalidInstances);
1792    }
1793    BlstPLONK::<MidnightCircuit<R>>::verify::<H>(
1794        params_verifier,
1795        &vk.vk,
1796        &[committed_pi],
1797        &[&pi],
1798        proof,
1799    )
1800}
1801
1802/// Verifies a batch of proofs with respect to their corresponding vk.
1803/// This method does not need to know the `Relation` the proofs are associated
1804/// to and, indeed, it can verify proofs from different `Relation`s.
1805/// For that, this function does not take `instance`s, but public inputs
1806/// in raw format (`Vec<F>`).
1807///
1808/// Returns `Ok(())` if all proofs are valid.
1809pub fn batch_verify<H: TranscriptHash + Send + Sync>(
1810    params_verifier: &ParamsVerifierKZG<midnight_curves::Bls12>,
1811    vks: &[MidnightVK],
1812    pis: &[Vec<F>],
1813    proofs: &[Vec<u8>],
1814) -> Result<(), Error>
1815where
1816    G1Projective: Hashable<H>,
1817    F: Hashable<H> + Sampleable<H>,
1818{
1819    use rayon::prelude::*;
1820
1821    // TODO: For the moment, committed instances are not supported.
1822    let n = vks.len();
1823    if pis.len() != n || proofs.len() != n {
1824        // TODO: have richer types in halo2
1825        return Err(Error::InvalidInstances);
1826    }
1827
1828    let prepared: Vec<(_, F)> = vks
1829        .par_iter()
1830        .zip(pis.par_iter())
1831        .zip(proofs.par_iter())
1832        .map(|((vk, pi), proof)| {
1833            if pi.len() != vk.nb_public_inputs {
1834                return Err(Error::InvalidInstances);
1835            }
1836
1837            let mut transcript = CircuitTranscript::init_from_bytes(proof);
1838            let dual_msm = prepare::<
1839                midnight_curves::Fq,
1840                KZGCommitmentScheme<midnight_curves::Bls12>,
1841                CircuitTranscript<H>,
1842            >(
1843                &vk.vk,
1844                &[&[midnight_curves::G1Projective::identity()]],
1845                // TODO: We could batch here proofs with the same vk.
1846                &[&[pi]],
1847                &mut transcript,
1848            )?;
1849            let summary: F = transcript.squeeze_challenge();
1850            transcript.assert_empty().map_err(|_| Error::Opening)?;
1851            Ok((dual_msm, summary))
1852        })
1853        .collect::<Result<Vec<_>, Error>>()?;
1854
1855    let mut r_transcript = CircuitTranscript::init();
1856    let mut guards = Vec::with_capacity(n);
1857    for (guard, summary) in prepared {
1858        r_transcript.common(&summary)?;
1859        guards.push(guard);
1860    }
1861    let r: F = r_transcript.squeeze_challenge();
1862
1863    let powers: Vec<F> = std::iter::successors(Some(<F as ff::Field>::ONE), |p| Some(*p * r))
1864        .take(guards.len())
1865        .collect();
1866    guards.par_iter_mut().enumerate().for_each(|(i, guard)| guard.scale(powers[i]));
1867
1868    let Some(mut acc_guard) = guards.pop() else {
1869        return Ok(());
1870    };
1871    for guard in guards {
1872        acc_guard.add_msm(guard);
1873    }
1874    // TODO: Have richer error types
1875    acc_guard.verify(params_verifier).map_err(|_| Error::Opening)
1876}
1877
1878/// Cost model of the given relation.
1879pub fn cost_model<R: Relation>(relation: &R) -> CircuitModel {
1880    let circuit = MidnightCircuit::from_relation(relation);
1881    circuit_model::<_, 48, 32>(&circuit)
1882}