Skip to main content

midnight_transient_crypto/
proofs.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
14//! This module provides access to creating, and verifying zero-knowledge
15//! proofs. It assumes that keys and IR are generated externally, which is the
16//! focus of [Compact](https://github.com/input-output-hk/compactc).
17
18use crate::curve::{Fr, outer};
19use base_crypto::hash::{HashOutput, persistent_hash};
20use lazy_static::lazy_static;
21use lru::LruCache;
22use midnight_curves::Bls12;
23use midnight_proofs::{
24    poly::kzg::params::{ParamsKZG, ParamsVerifierKZG},
25    utils::SerdeFormat,
26};
27use midnight_zk_stdlib::{MidnightCircuit, MidnightPK, MidnightVK, Relation};
28#[cfg(feature = "proptest")]
29use proptest::arbitrary::Arbitrary;
30#[cfg(feature = "proptest")]
31use proptest_derive::Arbitrary;
32use rand::distributions::{Distribution, Standard};
33use rand::{CryptoRng, Rng};
34use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::Error as SerError};
35use serialize::{
36    Deserializable, Serializable, Tagged, VecExt, tag_enforcement_test, tagged_deserialize,
37};
38#[cfg(feature = "proptest")]
39use serialize::{NoStrategy, simple_arbitrary};
40use std::hash::{Hash, Hasher};
41use std::io::Write;
42use std::io::{self, Read};
43#[cfg(feature = "proptest")]
44use std::marker::PhantomData;
45use std::sync::{Arc, Mutex};
46use std::{any::Any, cmp::Ordering};
47use std::{borrow::Cow, num::NonZeroUsize};
48use std::{fmt::Debug, io::Seek};
49use storage_core::Storable;
50use storage_core::arena::ArenaKey;
51use storage_core::db::DB;
52use storage_core::storable::Loader;
53use zeroize::{Zeroize, ZeroizeOnDrop};
54
55/// A provider of prover parameters.
56pub trait ParamsProverProvider {
57    // Allowed because we don't care about auto traits here.
58    #[allow(async_fn_in_trait)]
59    /// Retrieve the parameters for a given `k` value
60    async fn get_params(&self, k: u8) -> io::Result<ParamsProver>;
61}
62
63/// The hash used during proof transcript processing
64pub type TranscriptHash = blake2b_simd::State;
65
66impl ParamsProverProvider for base_crypto::data_provider::MidnightDataProvider {
67    async fn get_params(&self, k: u8) -> io::Result<ParamsProver> {
68        let name = Self::name_k(k);
69        let reader = self
70            .get_file(
71                &name,
72                &format!("public parameters for k={k} not found in cache"),
73            )
74            .await?;
75        ParamsProver::read(reader)
76    }
77}
78
79/// A specific instance of the prover parameters.
80#[derive(Clone)]
81pub struct ParamsProver(pub Arc<ParamsKZG<Bls12>>);
82
83impl AsRef<ParamsKZG<Bls12>> for ParamsProver {
84    fn as_ref(&self) -> &ParamsKZG<Bls12> {
85        &self.0
86    }
87}
88
89impl ParamsProver {
90    /// Reads the prover parameters from a data stream
91    pub fn read<R: Read>(mut reader: R) -> io::Result<Self> {
92        Ok(ParamsProver(Arc::new(ParamsKZG::read_custom(
93            &mut reader,
94            SerdeFormat::RawBytesUnchecked,
95        )?)))
96    }
97
98    pub(crate) fn as_verifier(&self) -> ParamsVerifier {
99        ParamsVerifier(Arc::new(self.0.verifier_params()))
100    }
101}
102
103/**
104 * The maximum degree supported by the standard verifier key.
105 * This limits the number of public inputs usable.
106 */
107pub const VERIFIER_MAX_DEGREE: u8 = 14;
108
109/// Parameters used for verifying with the `KZG` commitment scheme
110#[derive(Clone)]
111pub struct ParamsVerifier(Arc<ParamsVerifierKZG<Bls12>>);
112
113impl ParamsVerifier {
114    /// Reads in verifier parameters
115    pub fn read<R: Read>(reader: R) -> io::Result<Self> {
116        Ok(ParamsProver::read(reader)?.as_verifier())
117    }
118}
119
120const PARAMS_VERIFIER_RAW: &[u8] = include_bytes!("../static/bls_midnight_2p14");
121
122lazy_static! {
123    /// The midnight verifier parameters, up to [`VERIFIER_MAX_DEGREE`].
124    ///
125    /// Note that using this *will* embed these into the binary at compile time, if that's not what
126    /// you want, please use `ParamsVerifier::read` instead.
127    pub static ref PARAMS_VERIFIER: ParamsVerifier = ParamsVerifier::read(PARAMS_VERIFIER_RAW).expect("Static verifier parameters should be valid.");
128}
129
130/// A zero-knowledge proof.
131#[cfg_attr(feature = "proptest", derive(Arbitrary))]
132#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serializable, Storable)]
133#[storable(base)]
134#[tag = "proof[v5]"]
135pub struct Proof(pub Vec<u8>);
136tag_enforcement_test!(Proof);
137
138/// A prover key, used for creating proofs.
139#[derive(Debug, Clone)]
140pub struct ProverKey<T: Zkir>(Arc<Mutex<InnerProverKey<T>>>);
141
142impl<T: Zkir> From<MidnightPK<T>> for ProverKey<T> {
143    fn from(pk: MidnightPK<T>) -> Self {
144        ProverKey(Arc::new(Mutex::new(InnerProverKey::Initialized(Arc::new(
145            pk,
146        )))))
147    }
148}
149
150/// An intermediate representation for Midnight's circuits.
151#[allow(async_fn_in_trait)]
152pub trait Zkir: Relation + Any + Send + Sync + Debug {
153    /// Check that a proof preimage satisfies the circuit
154    ///
155    /// Returns which outputs were skipped in the proof preimage, and how many
156    /// zero element to buffer them with. Specifically, because our circuits
157    /// compile to JavaScript, and there do not evaluate untaken branches, this
158    /// leads to the output of the JavaScript circuit targets omitting public
159    /// inputs that occurred in an untaken branch. This information still needs
160    /// to be included in the statement vectors, where it is padded with zero
161    /// elements.
162    ///
163    /// Currently, we handle this by grouping the statement vector into 'blocks'
164    /// of public inputs, with each block corresponding to exactly one VM
165    /// instruction, and running `check` to figure out which blocks were
166    /// omitted due to untaken branches, and how many zeros to pad them with.
167    ///
168    /// Long-term, we probably want to move to make this obsolete, by having the
169    /// computer target gather information about untaken branches at run-time.
170    fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, ProvingError>;
171    /// Proves a circuit.
172    /// Returns the proof, the statement vector, and the skips from `check`.
173    async fn prove(
174        &self,
175        rng: impl Rng + CryptoRng,
176        params: &impl ParamsProverProvider,
177        pk: ProverKey<Self>,
178        preimage: &ProofPreimage,
179    ) -> Result<(Proof, Vec<Fr>, Vec<Option<usize>>), ProvingError>;
180
181    /// Returns the k value for this circuit
182    fn k(&self) -> u8 {
183        MidnightCircuit::from_relation(self).min_k() as u8
184    }
185
186    /// Performs key generation on this circuit, outputting the verifier key
187    async fn keygen_vk(
188        &self,
189        params: &impl ParamsProverProvider,
190    ) -> Result<VerifierKey, anyhow::Error> {
191        use midnight_zk_stdlib::setup_vk;
192        let vk = VerifierKey::from(setup_vk(params.get_params(self.k()).await?.as_ref(), self));
193
194        Ok(vk)
195    }
196
197    /// Performs key generation on this circuit, outputting the prover/verifier
198    /// key pair
199    async fn keygen(
200        &self,
201        params: &impl ParamsProverProvider,
202    ) -> Result<(ProverKey<Self>, VerifierKey), anyhow::Error> {
203        use midnight_zk_stdlib::{setup_pk, setup_vk};
204        let vk = setup_vk(params.get_params(self.k()).await?.as_ref(), self);
205        let pk = setup_pk(self, &vk);
206
207        Ok((ProverKey::from(pk), VerifierKey::from(vk)))
208    }
209
210    /// Loads IR from a tagged serialization. Separated from `Deserializable` to allow for
211    /// backwards-compatible deserialization of old variants.
212    fn load_ir_from_tagged(reader: impl Read + Seek) -> io::Result<Self>;
213
214    /// Loads a prover key from a tagged serialization. Separated from `Deserializable` to allow
215    /// for backwards-compatible deserialization of old variants.
216    fn load_prover_key_from_tagged(reader: impl Read + Seek) -> io::Result<ProverKey<Self>>;
217}
218
219impl<T: Zkir> PartialEq for ProverKey<T> {
220    fn eq(&self, other: &Self) -> bool {
221        let mut self_ser = Vec::new();
222        let mut other_ser = Vec::new();
223        Serializable::serialize(self, &mut self_ser).expect("In-memory serialization must succeed");
224        Serializable::serialize(other, &mut other_ser)
225            .expect("In-memory serialization must succeed");
226        self_ser == other_ser
227    }
228}
229
230impl<T: Zkir> Eq for ProverKey<T> {}
231
232impl<T: Zkir> Distribution<ProverKey<T>> for Standard {
233    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ProverKey<T> {
234        let size: u8 = rng.gen_range(0..32);
235        let mut bytes = Vec::with_bounded_capacity(size as usize);
236        rng.fill_bytes(&mut bytes);
237        ProverKey(Arc::new(Mutex::new(InnerProverKey::Uninitialized(bytes))))
238    }
239}
240
241#[derive(Debug, Clone)]
242pub(crate) enum InnerProverKey<T: Zkir> {
243    Uninitialized(Vec<u8>),
244    Invalid(Vec<u8>),
245    Initialized(Arc<MidnightPK<T>>),
246}
247
248impl<T: Zkir + Tagged> Tagged for ProverKey<T> {
249    fn tag() -> Cow<'static, str> {
250        Cow::Owned(format!("prover-key[v7]({})", T::tag()))
251    }
252    fn tag_unique_factor() -> String {
253        format!("prover-key[v7]({})", T::tag())
254    }
255}
256
257const PK_COMPRESSION_LEVEL: u32 = 6;
258const PK_CACHE_SIZE: usize = 5;
259
260lazy_static! {
261    // forall<T> Arc<MidnightPK<T>>
262    static ref PK_CACHE: Mutex<LruCache<HashOutput, Arc<dyn Any + Send + Sync>>> =
263        Mutex::new(LruCache::new(NonZeroUsize::new(PK_CACHE_SIZE).unwrap()));
264}
265
266impl<T: Zkir> InnerProverKey<T> {
267    fn try_cache(&mut self) {
268        let hash = match self {
269            InnerProverKey::Uninitialized(data) => persistent_hash(&data[..]),
270            _ => return,
271        };
272        if let Some(pk) = PK_CACHE
273            .lock()
274            .ok()
275            .and_then(|mut c| c.get(&hash).cloned())
276            .and_then(|ptr| ptr.downcast().ok())
277        {
278            *self = InnerProverKey::Initialized(pk);
279        }
280    }
281}
282
283impl<T: Zkir> ProverKey<T> {
284    /// Initializes the lazy prover key
285    pub fn init(&self) -> Result<Arc<MidnightPK<T>>, ProvingError> {
286        let mut mutex = self.0.lock().expect("mutex is not poisoned");
287        mutex.try_cache();
288        let data = match &*mutex {
289            InnerProverKey::Initialized(key) => {
290                return Ok(key.clone());
291            }
292            InnerProverKey::Invalid(_) => {
293                return Err(anyhow::anyhow!("known invalid verifier key"));
294            }
295            InnerProverKey::Uninitialized(data) => data.clone(),
296        };
297        let inner_reader = &mut &data[..];
298        let mut reader = flate2::read::GzDecoder::new(inner_reader);
299        let read_inner = |reader| {
300            let pk = MidnightPK::<T>::read(reader, SerdeFormat::RawBytesUnchecked)?;
301            Ok(pk)
302        };
303        let res: Result<_, ProvingError> = read_inner(&mut reader);
304        match res {
305            Ok(pk) => {
306                let key = Arc::new(pk);
307                PK_CACHE
308                    .lock()
309                    .ok()
310                    .and_then(|mut c| c.put(persistent_hash(&data), key.clone()));
311                *mutex = InnerProverKey::Initialized(key.clone());
312                Ok(key)
313            }
314            Err(e) => {
315                *mutex = InnerProverKey::Invalid(data);
316                Err(e)
317            }
318        }
319    }
320
321    fn inner_serialize<W: std::io::Write>(&self, mut writer: W) -> std::io::Result<()> {
322        match &*self.0.lock().expect("mutex is not poisoned") {
323            InnerProverKey::Uninitialized(data) | InnerProverKey::Invalid(data) => {
324                writer.write_all(data)?;
325                Ok(())
326            }
327            InnerProverKey::Initialized(key) => {
328                let mut writer = flate2::write::GzEncoder::new(
329                    writer,
330                    flate2::Compression::new(PK_COMPRESSION_LEVEL),
331                );
332                key.write(&mut writer, SerdeFormat::RawBytesUnchecked)
333            }
334        }
335    }
336}
337
338struct Count(usize);
339
340impl std::io::Write for Count {
341    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
342        self.0 += buf.len();
343        Ok(buf.len())
344    }
345    fn flush(&mut self) -> std::io::Result<()> {
346        Ok(())
347    }
348}
349
350impl<T: Zkir> Serializable for ProverKey<T> {
351    fn serialize(&self, writer: &mut impl Write) -> std::io::Result<()> {
352        let mut count = Count(0);
353        self.inner_serialize(&mut count).ok();
354        Serializable::serialize(&(count.0 as u64), writer)?;
355        self.inner_serialize(writer)
356    }
357
358    fn serialized_size(&self) -> usize {
359        let mut writer = Count(0);
360        self.inner_serialize(&mut writer).ok();
361        (writer.0 as u64).serialized_size() + writer.0
362    }
363}
364
365impl<T: Zkir> Deserializable for ProverKey<T> {
366    fn deserialize(reader: &mut impl Read, recursion_depth: u32) -> Result<Self, std::io::Error> {
367        let buf = <Vec<u8> as Deserializable>::deserialize(reader, recursion_depth)?;
368        let mut pk = InnerProverKey::Uninitialized(buf);
369        pk.try_cache();
370        Ok(Self(Arc::new(Mutex::new(pk))))
371    }
372}
373
374/// A verifier key, used for checking proofs.
375#[derive(Debug, Storable)]
376#[storable(base)]
377pub struct VerifierKey(Arc<Mutex<InnerVerifierKey>>);
378
379#[cfg(feature = "proptest")]
380simple_arbitrary!(VerifierKey);
381
382impl Tagged for VerifierKey {
383    fn tag() -> Cow<'static, str> {
384        Cow::Borrowed("verifier-key[v6]")
385    }
386    fn tag_unique_factor() -> String {
387        "verifier-key[v6]".into()
388    }
389}
390tag_enforcement_test!(VerifierKey);
391
392impl Distribution<VerifierKey> for Standard {
393    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> VerifierKey {
394        let size: u8 = rng.r#gen();
395        let mut bytes = Vec::with_bounded_capacity(size as usize);
396        rng.fill_bytes(&mut bytes);
397        VerifierKey(Arc::new(Mutex::new(InnerVerifierKey::Uninitialized(bytes))))
398    }
399}
400
401impl From<MidnightVK> for VerifierKey {
402    fn from(vk: MidnightVK) -> Self {
403        let mut raw = Vec::new();
404        vk.write(&mut raw, SerdeFormat::Processed)
405            .expect("in-memory serialization does not fail");
406        VerifierKey(Arc::new(Mutex::new(InnerVerifierKey::Initialized(vk, raw))))
407    }
408}
409
410#[derive(Debug, Clone)]
411#[allow(dead_code)] // Some features don't try to initialize
412#[allow(clippy::large_enum_variant)]
413pub(crate) enum InnerVerifierKey {
414    Uninitialized(Vec<u8>),
415    Invalid(Vec<u8>),
416    /// Parsed key alongside the original bytes it was decoded from, so that
417    /// serialization stays a function of the value and does not change when a
418    /// key is initialized in place (initialization is shared across clones via
419    /// the `Arc<Mutex>`).
420    Initialized(MidnightVK, Vec<u8>),
421}
422
423impl Clone for VerifierKey {
424    fn clone(&self) -> Self {
425        Self(self.0.clone())
426    }
427}
428
429impl Deserializable for VerifierKey {
430    fn deserialize(
431        reader: &mut impl std::io::Read,
432        recursion_depth: u32,
433    ) -> Result<Self, std::io::Error> {
434        const MAX_EXPECTED_SIZE: usize = 50_000;
435        let buf = <Vec<u8> as Deserializable>::deserialize(reader, recursion_depth)?;
436        if buf.len() > MAX_EXPECTED_SIZE {
437            return Err(std::io::Error::new(
438                std::io::ErrorKind::InvalidData,
439                format!(
440                    "Declared vk size {} exceeded permitted limit of {MAX_EXPECTED_SIZE}",
441                    buf.len()
442                ),
443            ));
444        }
445        Ok(Self(Arc::new(Mutex::new(InnerVerifierKey::Uninitialized(
446            buf,
447        )))))
448    }
449}
450
451#[derive(Clone)]
452struct DummyRelation;
453
454// TODO: This is a temporary workaround for verifier key deserialization.
455// Longer-term, we'll need to store information about the circuit architecture
456// in the verifier key, and use that for deserializing, but those API endpoints
457// do not currently exist in midnight-circuits.
458impl Relation for DummyRelation {
459    type Instance = Vec<outer::Scalar>;
460    type Witness = ();
461    fn format_instance(
462        instance: &Self::Instance,
463    ) -> Result<Vec<outer::Scalar>, midnight_proofs::plonk::Error> {
464        Ok(instance.clone())
465    }
466    fn circuit(
467        &self,
468        _std_lib: &midnight_zk_stdlib::ZkStdLib,
469        _layouter: &mut impl midnight_proofs::circuit::Layouter<outer::Scalar>,
470        _instance: midnight_proofs::circuit::Value<Self::Instance>,
471        _witness: midnight_proofs::circuit::Value<Self::Witness>,
472    ) -> Result<(), midnight_proofs::plonk::Error> {
473        unimplemented!("should not attempt to execute dummy relation")
474    }
475    fn read_relation<R: io::Read>(_reader: &mut R) -> io::Result<Self> {
476        unimplemented!("should not attempt to read dummy relation")
477    }
478    fn write_relation<W: io::Write>(&self, _writer: &mut W) -> io::Result<()> {
479        unimplemented!("should not attempt to write dummy relation")
480    }
481}
482
483impl Serialize for VerifierKey {
484    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
485        let mut vec = Vec::new();
486        <VerifierKey as Serializable>::serialize(self, &mut vec).map_err(S::Error::custom)?;
487        ser.serialize_bytes(&vec)
488    }
489}
490
491impl<'de> Deserialize<'de> for VerifierKey {
492    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
493        let bytes = serde_bytes::ByteBuf::deserialize(deserializer)?;
494        <VerifierKey as Deserializable>::deserialize(&mut &bytes[..], 0)
495            .map_err(serde::de::Error::custom)
496    }
497}
498
499#[allow(clippy::derived_hash_with_manual_eq)]
500impl Hash for VerifierKey {
501    fn hash<H: Hasher>(&self, state: &mut H) {
502        let mut data = Vec::new();
503        Serializable::serialize(&self, &mut data).ok();
504        state.write(&data);
505    }
506}
507
508impl Serializable for VerifierKey {
509    fn serialize(&self, writer: &mut impl Write) -> Result<(), std::io::Error> {
510        let mut count = Count(0);
511        self.inner_serialize(&mut count).ok();
512        Serializable::serialize(&(count.0 as u64), writer)?;
513        self.inner_serialize(writer)
514    }
515
516    fn serialized_size(&self) -> usize {
517        let mut writer = Count(0);
518        self.inner_serialize(&mut writer).ok();
519        (writer.0 as u64).serialized_size() + writer.0
520    }
521}
522
523impl VerifierKey {
524    /// Initializes the lazy verifier key
525    pub fn init(&self) -> Result<(), VerifyingError> {
526        self.force_init()?;
527        Ok(())
528    }
529
530    // warning! This grabs the lock! Make sure to drop the result before re-running!
531    #[allow(dead_code)] // Some features don't try to initialize
532    pub(crate) fn force_init(&self) -> Result<MidnightVK, VerifyingError> {
533        let mut mutex = self.0.lock().expect("mutex is not poisoned");
534        let data = match &*mutex {
535            InnerVerifierKey::Initialized(key, _) => {
536                return Ok(key.clone());
537            }
538            InnerVerifierKey::Invalid(_) => {
539                return Err(anyhow::anyhow!("known invalid verifier key"));
540            }
541            InnerVerifierKey::Uninitialized(data) => data.clone(),
542        };
543        let mut slice: &[u8] = &data;
544        let vk = MidnightVK::read(&mut slice, SerdeFormat::Processed)
545            .map_err(|_| anyhow::anyhow!("problem reading the verifier key"))?;
546        // Reject keys with unconsumed trailing bytes: two encodings must not map
547        // to the same key, and the trailing bytes would otherwise survive in the
548        // preserved-original serialization.
549        if !slice.is_empty() {
550            return Err(anyhow::anyhow!("trailing bytes after verifier key"));
551        }
552        *mutex = InnerVerifierKey::Initialized(vk.clone(), data);
553        Ok(vk)
554    }
555
556    fn inner_serialize<W: std::io::Write>(&self, mut writer: W) -> std::io::Result<()> {
557        match &*self.0.lock().expect("mutex is not poisoned") {
558            InnerVerifierKey::Uninitialized(data) | InnerVerifierKey::Invalid(data) => {
559                writer.write_all(data)
560            }
561            InnerVerifierKey::Initialized(_, original) => writer.write_all(original),
562        }
563    }
564
565    /// Checks a proof against a statement.
566    pub fn verify<F: Iterator<Item = Fr>>(
567        &self,
568        params: &ParamsVerifier,
569        proof: &Proof,
570        statement: F,
571    ) -> Result<(), VerifyingError> {
572        let vk = self.force_init()?;
573        let pi = statement.map(|f| f.0).collect::<Vec<_>>();
574        trace!(statement = ?pi, "verifying proof against statement");
575        midnight_zk_stdlib::verify::<DummyRelation, TranscriptHash>(
576            &params.0, &vk, &pi, None, &proof.0,
577        )
578        .map_err(|_| anyhow::anyhow!("Invalid proof"))
579    }
580
581    /// Mocks the checking of a proof against a statement
582    ///
583    /// We do this by running a number of CPU burn cycles calculated to be approximately
584    /// equivalent in time-taken to real proof verification
585    #[cfg(feature = "mock-verify")]
586    pub fn mock_verify<F: Iterator<Item = Fr>>(&self, statement: F) -> Result<(), VerifyingError> {
587        let pi_len = statement.count();
588        crate::mock_verify::mock_verify_for(pi_len)
589    }
590
591    /// Checks a sequence of proofs against their corresponding statements and verifier keys
592    pub fn batch_verify<
593        'a,
594        F: Iterator<Item = Fr>,
595        V: Iterator<Item = (&'a VerifierKey, &'a Proof, F)>,
596    >(
597        params: &ParamsVerifier,
598        parts: V,
599    ) -> Result<(), VerifyingError> {
600        use midnight_zk_stdlib::batch_verify;
601
602        let mut vks = vec![];
603        let mut pis = vec![];
604        let mut proofs = vec![];
605
606        for (vk, proof, stmt) in parts.into_iter() {
607            let pi = stmt.map(|f| f.0).collect::<Vec<_>>();
608            let vk = vk.force_init()?;
609            vks.push(vk);
610            pis.push(pi);
611            proofs.push(proof.0.clone());
612        }
613
614        batch_verify::<TranscriptHash>(&params.0, &vks, &pis, &proofs)
615            .map_err(|_| anyhow::anyhow!("Invalid proof"))
616    }
617
618    /// Mocks the checking of a sequence of proofs against a statement
619    ///
620    /// This is simulated by sequentially mocking each individual verification,
621    /// it doesn't currently benefit from any performance benefits one should associate
622    /// with batching
623    #[cfg(feature = "mock-verify")]
624    pub fn mock_batch_verify<
625        'a,
626        F: Iterator<Item = Fr>,
627        V: Iterator<Item = (&'a VerifierKey, &'a Proof, F)>,
628    >(
629        parts: V,
630    ) -> Result<(), VerifyingError> {
631        for (vk, _proof, stmt) in parts {
632            vk.mock_verify(stmt)?;
633        }
634        Ok(())
635    }
636}
637
638/// A hint on where keys for a circuit can be found.
639///
640/// Circuit keys are associated with a string name, and are resolved at proving
641/// time against a hash table of provided keys.
642#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serializable)]
643#[cfg_attr(feature = "proptest", derive(Arbitrary))]
644pub struct KeyLocation(pub Cow<'static, str>);
645
646impl Zeroize for KeyLocation {
647    fn zeroize(&mut self) {
648        if let Cow::Owned(s) = &mut self.0 {
649            s.zeroize();
650        }
651        self.0 = Cow::Borrowed("");
652    }
653}
654
655impl Tagged for KeyLocation {
656    fn tag() -> Cow<'static, str> {
657        Cow::Borrowed("string")
658    }
659    fn tag_unique_factor() -> String {
660        "string".into()
661    }
662}
663
664#[derive(Serializable)]
665#[tag = "wrapped-ir"]
666/// A container for just the IR part of [`ProofData`].
667pub struct WrappedIr(pub Vec<u8>);
668tag_enforcement_test!(WrappedIr);
669
670#[derive(Clone, Serializable)]
671#[tag = "proving-data"]
672/// A container for the parts required for proving
673pub struct ProvingKeyMaterial {
674    /// The prover key
675    pub prover_key: Vec<u8>,
676    /// The verifier key
677    pub verifier_key: Vec<u8>,
678    /// The IR source
679    pub ir_source: Vec<u8>,
680}
681tag_enforcement_test!(ProvingKeyMaterial);
682
683/// A mechanism to retrieve / resolve zero-knowledge key material from a short location string.
684pub trait Resolver {
685    /// Resolves the given key to the key material it represents, if available.
686    // Allowed as we do not need auto traits here
687    #[allow(async_fn_in_trait)]
688    async fn resolve_key(&self, key: KeyLocation) -> io::Result<Option<ProvingKeyMaterial>>;
689}
690
691/// A tool that provides proving against opaque/serialized proof preimages
692/// It is assumed (though not strictly required) that this also implements
693/// `Resolver` to resolve keys.
694#[allow(async_fn_in_trait)]
695pub trait ProvingProvider {
696    /// Check the proof preimage is valid, and if so returns the pi skip sequence
697    async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error>;
698    /// Produces the proof, optionally modifying the binding input in the proof preimage first.
699    async fn prove(
700        self,
701        preimage: &ProofPreimage,
702        overwrite_binding_input: Option<Fr>,
703    ) -> Result<Proof, anyhow::Error>;
704    /// Creates a copy of this provider. As providers often include an RNG, this
705    /// may mutate the provider itself.
706    fn split(&mut self) -> Self;
707}
708
709/// Everything necessary to produce a proof.
710#[derive(
711    Clone,
712    Debug,
713    PartialEq,
714    Eq,
715    PartialOrd,
716    Ord,
717    Serializable,
718    Hash,
719    Storable,
720    Zeroize,
721    ZeroizeOnDrop,
722)]
723#[storable(base)]
724#[tag = "proof-preimage"]
725#[cfg_attr(feature = "proptest", derive(Arbitrary))]
726pub struct ProofPreimage {
727    /// The inputs to be directly handed to the IR.
728    pub inputs: Vec<Fr>,
729    /// A private witness vector consumed by active witness calls in the IR.
730    pub private_transcript: Vec<Fr>,
731    /// A public statement vector encoding statement call information in the IR.
732    pub public_transcript_inputs: Vec<Fr>,
733    /// A public statement vector encoding statement call results in the IR.
734    pub public_transcript_outputs: Vec<Fr>,
735    /// An arbitrary input to be bound to in the proof.
736    pub binding_input: Fr,
737    /// The communications commitment that will be checked, and its randomness.
738    /// May be [None], in which case inputs and outputs are not committed to.
739    pub communications_commitment: Option<(Fr, Fr)>,
740    /// Where the keys for carrying out the proving can be found.
741    pub key_location: KeyLocation,
742}
743tag_enforcement_test!(ProofPreimage);
744
745impl ProofPreimage {
746    /// Runs witness generation and checks for correctness without generating a
747    /// proof
748    #[allow(unused_variables)]
749    pub fn check(&self, ir: &impl Zkir) -> Result<Vec<Option<usize>>, ProvingError> {
750        ir.check(self)
751    }
752
753    /// Carries out the actual proving of the proof preimage.
754    #[allow(unreachable_code, unused_variables)]
755    pub async fn prove<Z: Zkir>(
756        &self,
757        rng: impl Rng + CryptoRng,
758        params: &impl ParamsProverProvider,
759        resolver: &impl Resolver,
760    ) -> Result<(Proof, Vec<Option<usize>>), ProvingError> {
761        let proof_data = resolver
762            .resolve_key(self.key_location.clone())
763            .await?
764            .ok_or(anyhow::Error::msg(format!(
765                "failed to find proving key for '{}'",
766                self.key_location.0
767            )))?;
768        let ir = Z::load_ir_from_tagged(io::Cursor::new(&proof_data.ir_source[..]))?;
769        let verifier_key = tagged_deserialize::<VerifierKey>(&mut &proof_data.verifier_key[..])?;
770        let prover_key =
771            Z::load_prover_key_from_tagged(io::Cursor::new(&proof_data.prover_key[..]))?;
772        let (proof, pis, pi_skips) = ir.prove(rng, params, prover_key, self).await?;
773        debug!("proof created; verifying to make sure");
774        let k = verifier_key.force_init()?.k();
775        if let Err(e) = verifier_key.verify(
776            &params.get_params(k).await?.as_verifier(),
777            &proof,
778            pis.iter().copied(),
779        ) {
780            error!(error = ?e, ?pis, ?ir, "self-verification failed! This may be a bug, check that your keys match!");
781            return Err(e);
782        }
783        debug!("proof ok");
784        Ok((proof, pi_skips))
785    }
786}
787
788impl PartialEq for VerifierKey {
789    fn eq(&self, other: &Self) -> bool {
790        let mut self_ser = Vec::new();
791        let mut other_ser = Vec::new();
792        Serializable::serialize(self, &mut self_ser).expect("In-memory serialization must succeed");
793        Serializable::serialize(other, &mut other_ser)
794            .expect("In-memory serialization must succeed");
795        self_ser == other_ser
796    }
797}
798
799impl Eq for VerifierKey {}
800
801impl PartialOrd for VerifierKey {
802    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
803        Some(self.cmp(other))
804    }
805}
806
807impl Ord for VerifierKey {
808    fn cmp(&self, other: &Self) -> Ordering {
809        let mut self_ser = Vec::new();
810        let mut other_ser = Vec::new();
811        Serializable::serialize(self, &mut self_ser).expect("In-memory serialization must succeed");
812        Serializable::serialize(other, &mut other_ser)
813            .expect("In-memory serialization must succeed");
814        self_ser.cmp(&other_ser)
815    }
816}
817
818/// An error during proving. The type of this should not be considered part of
819/// the public API, although it may be assumed to be [`Debug`]` +
820/// `[`Display`](std::fmt::Display).
821pub type ProvingError = anyhow::Error;
822/// An error during verifying. The type of this should not be considered part of
823/// the public API, although it may be assumed to be [`Debug`]` +
824/// `[`Display`](std::fmt::Display).
825pub type VerifyingError = anyhow::Error;