Skip to main content

snarkvm_synthesizer_snark/verifying_key/
parse.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 super::*;
17
18static VERIFYING_KEY: &str = "verifier";
19
20impl<N: Network> Parser for VerifyingKey<N> {
21    /// Parses a string into the verifying key.
22    #[inline]
23    fn parse(string: &str) -> ParserResult<Self> {
24        // Prepare a parser for the Aleo verifying key.
25        let parse_key = recognize(pair(
26            pair(tag(VERIFYING_KEY), tag("1")),
27            many1(terminated(one_of("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), many0(char('_')))),
28        ));
29
30        // Parse the verifying key from the string.
31        map_res(parse_key, |key: &str| -> Result<_, Error> { Self::from_str(&key.replace('_', "")) })(string)
32    }
33}
34
35impl<N: Network> FromStr for VerifyingKey<N> {
36    type Err = Error;
37
38    /// Reads in the verifying key string.
39    fn from_str(key: &str) -> Result<Self, Self::Err> {
40        // Decode the verifying key string from bech32m.
41        let (hrp, data, variant) = bech32::decode(key)?;
42        if hrp != VERIFYING_KEY {
43            bail!("Failed to decode verifying key: '{hrp}' is an invalid prefix")
44        } else if data.is_empty() {
45            bail!("Failed to decode verifying key: data field is empty")
46        } else if variant != bech32::Variant::Bech32m {
47            bail!("Found a verifying key that is not bech32m encoded: {key}");
48        }
49        // Decode the verifying key data from u5 to u8, and into the verifying key.
50        Ok(Self::read_le(&Vec::from_base32(&data)?[..])?)
51    }
52}
53
54impl<N: Network> Debug for VerifyingKey<N> {
55    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
56        Display::fmt(self, f)
57    }
58}
59
60impl<N: Network> Display for VerifyingKey<N> {
61    /// Writes the verifying key as a bech32m string.
62    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
63        // Convert the verifying key to bytes.
64        let bytes = self.to_bytes_le().map_err(|_| fmt::Error)?;
65        // Encode the bytes into bech32m.
66        let string =
67            bech32::encode(VERIFYING_KEY, bytes.to_base32(), bech32::Variant::Bech32m).map_err(|_| fmt::Error)?;
68        // Output the string.
69        Display::fmt(&string, f)
70    }
71}