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::{
19    FromBytes,
20    FromBytesDeserializer,
21    ToBytes,
22    ToBytesSerializer,
23    error,
24    io::{self, Read, Write},
25    serialize::*,
26    string::String,
27};
28
29use anyhow::Result;
30use core::{fmt, str::FromStr};
31use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
32use std::cmp::Ordering;
33
34/// Verification key for a specific index (i.e., R1CS matrices).
35#[derive(Debug, Clone, PartialEq, Eq, CanonicalSerialize, CanonicalDeserialize)]
36pub struct CircuitVerifyingKey<E: PairingEngine> {
37    /// Stores information about the size of the circuit, as well as its defined
38    /// field.
39    pub circuit_info: CircuitInfo,
40    /// Commitments to the indexed polynomials.
41    pub circuit_commitments: Vec<sonic_pc::Commitment<E>>,
42    pub id: CircuitId,
43}
44
45impl<E: PairingEngine> FromBytes for CircuitVerifyingKey<E> {
46    fn read_le<R: Read>(r: R) -> io::Result<Self> {
47        Self::deserialize_compressed(r).map_err(|_| error("could not deserialize CircuitVerifyingKey"))
48    }
49}
50
51impl<E: PairingEngine> ToBytes for CircuitVerifyingKey<E> {
52    fn write_le<W: Write>(&self, w: W) -> io::Result<()> {
53        self.serialize_compressed(w).map_err(|_| error("could not serialize CircuitVerifyingKey"))
54    }
55}
56
57impl<E: PairingEngine> CircuitVerifyingKey<E> {
58    /// Iterate over the commitments to indexed polynomials in `self`.
59    pub fn iter(&self) -> impl Iterator<Item = &sonic_pc::Commitment<E>> {
60        self.circuit_commitments.iter()
61    }
62}
63
64impl<E: PairingEngine> FromStr for CircuitVerifyingKey<E> {
65    type Err = anyhow::Error;
66
67    #[inline]
68    fn from_str(vk_hex: &str) -> Result<Self, Self::Err> {
69        Self::from_bytes_le(&hex::decode(vk_hex)?)
70    }
71}
72
73impl<E: PairingEngine> fmt::Display for CircuitVerifyingKey<E> {
74    #[inline]
75    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76        let vk_hex = hex::encode(self.to_bytes_le().expect("Failed to convert verifying key to bytes"));
77        write!(f, "{vk_hex}")
78    }
79}
80
81impl<E: PairingEngine> Serialize for CircuitVerifyingKey<E> {
82    #[inline]
83    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
84        match serializer.is_human_readable() {
85            true => serializer.collect_str(self),
86            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
87        }
88    }
89}
90
91impl<'de, E: PairingEngine> Deserialize<'de> for CircuitVerifyingKey<E> {
92    #[inline]
93    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
94        match deserializer.is_human_readable() {
95            true => {
96                let s: String = Deserialize::deserialize(deserializer)?;
97                FromStr::from_str(&s).map_err(de::Error::custom)
98            }
99            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "verifying key"),
100        }
101    }
102}
103
104impl<E: PairingEngine> Ord for CircuitVerifyingKey<E> {
105    fn cmp(&self, other: &Self) -> Ordering {
106        self.id.cmp(&other.id)
107    }
108}
109
110impl<E: PairingEngine> PartialOrd for CircuitVerifyingKey<E> {
111    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
112        Some(self.cmp(other))
113    }
114}