snarkvm_algorithms/snark/varuna/data_structures/
circuit_verifying_key.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM 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
16use crate::{polycommit::sonic_pc, snark::varuna::ahp::indexer::*};
17use snarkvm_curves::PairingEngine;
18use snarkvm_utilities::{FromBytes, FromBytesDeserializer, ToBytes, ToBytesSerializer, into_io_error, serialize::*};
19
20use anyhow::Result;
21use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
22use 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)]
32pub 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
41impl<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
48impl<E: PairingEngine> ToBytes for CircuitVerifyingKey<E> {
49    fn write_le<W: Write>(&self, w: W) -> io::Result<()> {
50        self.serialize_compressed(w)
51            .map_err(|err| into_io_error(anyhow::Error::from(err).context("could not serialize CircuitVerifyingKey")))
52    }
53}
54
55impl<E: PairingEngine> CircuitVerifyingKey<E> {
56    /// Iterate over the commitments to indexed polynomials in `self`.
57    pub fn iter(&self) -> impl Iterator<Item = &sonic_pc::Commitment<E>> {
58        self.circuit_commitments.iter()
59    }
60}
61
62impl<E: PairingEngine> FromStr for CircuitVerifyingKey<E> {
63    type Err = anyhow::Error;
64
65    #[inline]
66    fn from_str(vk_hex: &str) -> Result<Self, Self::Err> {
67        Self::from_bytes_le(&hex::decode(vk_hex)?)
68    }
69}
70
71impl<E: PairingEngine> fmt::Display for CircuitVerifyingKey<E> {
72    #[inline]
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        let vk_hex = hex::encode(self.to_bytes_le().expect("Failed to convert verifying key to bytes"));
75        write!(f, "{vk_hex}")
76    }
77}
78
79impl<E: PairingEngine> Serialize for CircuitVerifyingKey<E> {
80    #[inline]
81    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
82        match serializer.is_human_readable() {
83            true => serializer.collect_str(self),
84            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
85        }
86    }
87}
88
89impl<'de, E: PairingEngine> Deserialize<'de> for CircuitVerifyingKey<E> {
90    #[inline]
91    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
92        match deserializer.is_human_readable() {
93            true => {
94                let s: String = Deserialize::deserialize(deserializer)?;
95                FromStr::from_str(&s).map_err(de::Error::custom)
96            }
97            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "verifying key"),
98        }
99    }
100}
101
102impl<E: PairingEngine> Ord for CircuitVerifyingKey<E> {
103    fn cmp(&self, other: &Self) -> Ordering {
104        self.id.cmp(&other.id)
105    }
106}
107
108impl<E: PairingEngine> PartialOrd for CircuitVerifyingKey<E> {
109    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
110        Some(self.cmp(other))
111    }
112}