1use 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
56pub trait ParamsProverProvider {
58 #[allow(async_fn_in_trait)]
60 async fn get_params(&self, k: u8) -> io::Result<ParamsProver>;
62}
63
64pub 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#[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 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
104pub const VERIFIER_MAX_DEGREE: u8 = 14;
109
110#[derive(Clone)]
112pub struct ParamsVerifier(Arc<ParamsVerifierKZG<Bls12>>);
113
114impl ParamsVerifier {
115 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 pub static ref PARAMS_VERIFIER: ParamsVerifier = ParamsVerifier::read(PARAMS_VERIFIER_RAW).expect("Static verifier parameters should be valid.");
129}
130
131#[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#[derive(Clone)]
141#[derive_where(Debug; T::ProverKey)]
142pub struct ProverKey<T: Zkir>(Arc<Mutex<InnerProverKey<T>>>);
143
144#[allow(async_fn_in_trait)]
146pub trait Zkir: Any + Send + Sync + Debug + Sized {
147 type ProverKey: Send + Sync;
149
150 fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, ProvingError>;
168 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 fn k(&self) -> u8;
180
181 async fn keygen_vk(
183 &self,
184 params: &impl ParamsProverProvider,
185 ) -> Result<VerifierKey, anyhow::Error>;
186
187 async fn keygen(
190 &self,
191 params: &impl ParamsProverProvider,
192 ) -> Result<(ProverKey<Self>, VerifierKey), anyhow::Error>;
193
194 fn load_ir_from_tagged(reader: impl Read + Seek) -> io::Result<Self>;
197
198 fn load_prover_key_from_tagged(reader: impl Read + Seek) -> io::Result<ProverKey<Self>>;
201
202 fn read_raw_pk(reader: impl Read) -> io::Result<Self::ProverKey>;
204 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 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 pub fn from_raw(raw: T::ProverKey) -> Self {
274 ProverKey(Arc::new(Mutex::new(InnerProverKey::Initialized(Arc::new(
275 raw,
276 )))))
277 }
278
279 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#[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)] #[allow(clippy::large_enum_variant)]
401pub(crate) enum InnerVerifierKey {
402 Uninitialized(Vec<u8>),
403 Invalid(Vec<u8>),
404 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
442impl 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 pub fn init(&self) -> Result<(), VerifyingError> {
515 self.force_init()?;
516 Ok(())
517 }
518
519 #[allow(dead_code)] 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 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 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 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 ¶ms.0, &vk, &pi, None, &proof.0,
574 )
575 .map_err(|_| anyhow::anyhow!("Invalid proof"))
576 }
577
578 #[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 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>(¶ms.0, &vks, &pis, &proofs)
612 .map_err(|_| anyhow::anyhow!("Invalid proof"))
613 }
614
615 #[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#[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"]
663pub struct WrappedIr(pub Vec<u8>);
665tag_enforcement_test!(WrappedIr);
666
667#[derive(Clone, Serializable)]
668#[tag = "proving-data"]
669pub struct ProvingKeyMaterial {
671 pub prover_key: Vec<u8>,
673 pub verifier_key: Vec<u8>,
675 pub ir_source: Vec<u8>,
677}
678tag_enforcement_test!(ProvingKeyMaterial);
679
680pub trait Resolver {
682 #[allow(async_fn_in_trait)]
685 async fn resolve_key(&self, key: KeyLocation) -> io::Result<Option<ProvingKeyMaterial>>;
686}
687
688#[allow(async_fn_in_trait)]
692pub trait ProvingProvider {
693 async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error>;
695 async fn prove(
697 self,
698 preimage: &ProofPreimage,
699 overwrite_binding_input: Option<Fr>,
700 ) -> Result<Proof, anyhow::Error>;
701 fn split(&mut self) -> Self;
704 fn resolver(&self) -> &impl Resolver;
706}
707
708#[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 pub inputs: Vec<Fr>,
728 pub private_transcript: Vec<Fr>,
730 pub public_transcript_inputs: Vec<Fr>,
732 pub public_transcript_outputs: Vec<Fr>,
734 pub binding_input: Fr,
736 pub communications_commitment: Option<(Fr, Fr)>,
739 pub key_location: KeyLocation,
741}
742tag_enforcement_test!(ProofPreimage);
743
744impl ProofPreimage {
745 #[allow(unused_variables)]
748 pub fn check(&self, ir: &impl Zkir) -> Result<Vec<Option<usize>>, ProvingError> {
749 ir.check(self)
750 }
751
752 #[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 ¶ms.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
817pub type ProvingError = anyhow::Error;
821pub type VerifyingError = anyhow::Error;