1use 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
55pub trait ParamsProverProvider {
57 #[allow(async_fn_in_trait)]
59 async fn get_params(&self, k: u8) -> io::Result<ParamsProver>;
61}
62
63pub 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#[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 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
103pub const VERIFIER_MAX_DEGREE: u8 = 14;
108
109#[derive(Clone)]
111pub struct ParamsVerifier(Arc<ParamsVerifierKZG<Bls12>>);
112
113impl ParamsVerifier {
114 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 pub static ref PARAMS_VERIFIER: ParamsVerifier = ParamsVerifier::read(PARAMS_VERIFIER_RAW).expect("Static verifier parameters should be valid.");
128}
129
130#[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#[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#[allow(async_fn_in_trait)]
152pub trait Zkir: Relation + Any + Send + Sync + Debug {
153 fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, ProvingError>;
171 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 fn k(&self) -> u8 {
183 MidnightCircuit::from_relation(self).min_k() as u8
184 }
185
186 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 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 fn load_ir_from_tagged(reader: impl Read + Seek) -> io::Result<Self>;
213
214 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 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 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#[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)] #[allow(clippy::large_enum_variant)]
413pub(crate) enum InnerVerifierKey {
414 Uninitialized(Vec<u8>),
415 Invalid(Vec<u8>),
416 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
454impl 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 pub fn init(&self) -> Result<(), VerifyingError> {
526 self.force_init()?;
527 Ok(())
528 }
529
530 #[allow(dead_code)] 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 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 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 ¶ms.0, &vk, &pi, None, &proof.0,
577 )
578 .map_err(|_| anyhow::anyhow!("Invalid proof"))
579 }
580
581 #[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 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>(¶ms.0, &vks, &pis, &proofs)
615 .map_err(|_| anyhow::anyhow!("Invalid proof"))
616 }
617
618 #[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#[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"]
666pub struct WrappedIr(pub Vec<u8>);
668tag_enforcement_test!(WrappedIr);
669
670#[derive(Clone, Serializable)]
671#[tag = "proving-data"]
672pub struct ProvingKeyMaterial {
674 pub prover_key: Vec<u8>,
676 pub verifier_key: Vec<u8>,
678 pub ir_source: Vec<u8>,
680}
681tag_enforcement_test!(ProvingKeyMaterial);
682
683pub trait Resolver {
685 #[allow(async_fn_in_trait)]
688 async fn resolve_key(&self, key: KeyLocation) -> io::Result<Option<ProvingKeyMaterial>>;
689}
690
691#[allow(async_fn_in_trait)]
695pub trait ProvingProvider {
696 async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error>;
698 async fn prove(
700 self,
701 preimage: &ProofPreimage,
702 overwrite_binding_input: Option<Fr>,
703 ) -> Result<Proof, anyhow::Error>;
704 fn split(&mut self) -> Self;
707}
708
709#[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 pub inputs: Vec<Fr>,
729 pub private_transcript: Vec<Fr>,
731 pub public_transcript_inputs: Vec<Fr>,
733 pub public_transcript_outputs: Vec<Fr>,
735 pub binding_input: Fr,
737 pub communications_commitment: Option<(Fr, Fr)>,
740 pub key_location: KeyLocation,
742}
743tag_enforcement_test!(ProofPreimage);
744
745impl ProofPreimage {
746 #[allow(unused_variables)]
749 pub fn check(&self, ir: &impl Zkir) -> Result<Vec<Option<usize>>, ProvingError> {
750 ir.check(self)
751 }
752
753 #[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 ¶ms.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
818pub type ProvingError = anyhow::Error;
822pub type VerifyingError = anyhow::Error;