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