/ algorithms / src / snark / varuna / data_structures / circuit_verifying_key.rs
circuit_verifying_key.rs
  1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
  2  // This file is part of the deltavm library.
  3  
  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  
  8  // http://www.apache.org/licenses/LICENSE-2.0
  9  
 10  // Unless required by applicable law or agreed to in writing, software
 11  // distributed under the License is distributed on an "AS IS" BASIS,
 12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  // See the License for the specific language governing permissions and
 14  // limitations under the License.
 15  
 16  use crate::{polycommit::sonic_pc, snark::varuna::ahp::indexer::*};
 17  use deltavm_curves::PairingEngine;
 18  use deltavm_utilities::{FromBytes, FromBytesDeserializer, ToBytes, ToBytesSerializer, into_io_error, serialize::*};
 19  
 20  use anyhow::Result;
 21  use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
 22  use std::{
 23      cmp::Ordering,
 24      fmt,
 25      io::{self, Read, Write},
 26      str::FromStr,
 27      string::String,
 28  };
 29  
 30  /// Verification key for a specific index (i.e., R1CS matrices).
 31  #[derive(Debug, Clone, PartialEq, Eq, CanonicalSerialize, CanonicalDeserialize)]
 32  pub struct CircuitVerifyingKey<E: PairingEngine> {
 33      /// Stores information about the size of the circuit, as well as its defined
 34      /// field.
 35      pub circuit_info: CircuitInfo,
 36      /// Commitments to the indexed polynomials.
 37      pub circuit_commitments: Vec<sonic_pc::Commitment<E>>,
 38      pub id: CircuitId,
 39  }
 40  
 41  impl<E: PairingEngine> FromBytes for CircuitVerifyingKey<E> {
 42      fn read_le<R: Read>(r: R) -> io::Result<Self> {
 43          Self::deserialize_compressed(r)
 44              .map_err(|err| into_io_error(anyhow::Error::from(err).context("could not deserialize CircuitVerifyingKey")))
 45      }
 46  
 47      fn read_le_unchecked<R: Read>(r: R) -> io::Result<Self> {
 48          Self::deserialize_compressed_unchecked(r)
 49              .map_err(|err| into_io_error(anyhow::Error::from(err).context("could not deserialize CircuitVerifyingKey")))
 50      }
 51  }
 52  
 53  impl<E: PairingEngine> ToBytes for CircuitVerifyingKey<E> {
 54      fn write_le<W: Write>(&self, w: W) -> io::Result<()> {
 55          self.serialize_compressed(w)
 56              .map_err(|err| into_io_error(anyhow::Error::from(err).context("could not serialize CircuitVerifyingKey")))
 57      }
 58  }
 59  
 60  impl<E: PairingEngine> CircuitVerifyingKey<E> {
 61      /// Iterate over the commitments to indexed polynomials in `self`.
 62      pub fn iter(&self) -> impl Iterator<Item = &sonic_pc::Commitment<E>> {
 63          self.circuit_commitments.iter()
 64      }
 65  }
 66  
 67  impl<E: PairingEngine> FromStr for CircuitVerifyingKey<E> {
 68      type Err = anyhow::Error;
 69  
 70      #[inline]
 71      fn from_str(vk_hex: &str) -> Result<Self, Self::Err> {
 72          Self::from_bytes_le(&hex::decode(vk_hex)?)
 73      }
 74  }
 75  
 76  impl<E: PairingEngine> fmt::Display for CircuitVerifyingKey<E> {
 77      #[inline]
 78      fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 79          let vk_hex = hex::encode(self.to_bytes_le().expect("Failed to convert verifying key to bytes"));
 80          write!(f, "{vk_hex}")
 81      }
 82  }
 83  
 84  impl<E: PairingEngine> Serialize for CircuitVerifyingKey<E> {
 85      #[inline]
 86      fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
 87          match serializer.is_human_readable() {
 88              true => serializer.collect_str(self),
 89              false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
 90          }
 91      }
 92  }
 93  
 94  impl<'de, E: PairingEngine> Deserialize<'de> for CircuitVerifyingKey<E> {
 95      #[inline]
 96      fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
 97          match deserializer.is_human_readable() {
 98              true => {
 99                  let s: String = Deserialize::deserialize(deserializer)?;
100                  FromStr::from_str(&s).map_err(de::Error::custom)
101              }
102              false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "verifying key"),
103          }
104      }
105  }
106  
107  impl<E: PairingEngine> Ord for CircuitVerifyingKey<E> {
108      fn cmp(&self, other: &Self) -> Ordering {
109          self.id.cmp(&other.id)
110      }
111  }
112  
113  impl<E: PairingEngine> PartialOrd for CircuitVerifyingKey<E> {
114      fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
115          Some(self.cmp(other))
116      }
117  }