snarkvm_synthesizer_snark/proof/
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 PROOF_PREFIX: &str = "proof";
19
20impl<N: Network> Parser for Proof<N> {
21    /// Parses a string into an proof.
22    #[inline]
23    fn parse(string: &str) -> ParserResult<Self> {
24        // Prepare a parser for the Aleo proof.
25        let parse_proof = recognize(pair(
26            pair(tag(PROOF_PREFIX), tag("1")),
27            many1(terminated(one_of("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), many0(char('_')))),
28        ));
29
30        // Parse the proof from the string.
31        map_res(parse_proof, |proof: &str| -> Result<_, Error> { Self::from_str(&proof.replace('_', "")) })(string)
32    }
33}
34
35impl<N: Network> FromStr for Proof<N> {
36    type Err = Error;
37
38    /// Reads in the proof string.
39    fn from_str(proof: &str) -> Result<Self, Self::Err> {
40        // Decode the proof string from bech32m.
41        let (hrp, data, variant) = bech32::decode(proof)?;
42        if hrp != PROOF_PREFIX {
43            bail!("Failed to decode proof: '{hrp}' is an invalid prefix")
44        } else if data.is_empty() {
45            bail!("Failed to decode proof: data field is empty")
46        } else if variant != bech32::Variant::Bech32m {
47            bail!("Found an proof that is not bech32m encoded: {proof}");
48        }
49        // Decode the proof data from u5 to u8, and into the proof.
50        Ok(Self::read_le(&Vec::from_base32(&data)?[..])?)
51    }
52}
53
54impl<N: Network> Debug for Proof<N> {
55    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
56        Display::fmt(self, f)
57    }
58}
59
60impl<N: Network> Display for Proof<N> {
61    /// Writes the proof as a bech32m string.
62    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
63        // Convert the proof 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(PROOF_PREFIX, bytes.to_base32(), bech32::Variant::Bech32m).map_err(|_| fmt::Error)?;
68        // Output the string.
69        Display::fmt(&string, f)
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use console::network::MainnetV0;
77
78    type CurrentNetwork = MainnetV0;
79
80    #[test]
81    fn test_parse() -> Result<()> {
82        // Ensure type and empty value fails.
83        assert!(Proof::<CurrentNetwork>::parse(&format!("{PROOF_PREFIX}1")).is_err());
84        assert!(Proof::<CurrentNetwork>::parse("").is_err());
85
86        // Sample the proof.
87        let proof = crate::test_helpers::sample_proof();
88
89        // Check the proof parsing.
90        let expected = format!("{proof}");
91        let (remainder, candidate) = Proof::<CurrentNetwork>::parse(&expected).unwrap();
92        assert_eq!(format!("{expected}"), candidate.to_string());
93        assert_eq!(PROOF_PREFIX, candidate.to_string().split('1').next().unwrap());
94        assert_eq!("", remainder);
95        Ok(())
96    }
97
98    #[test]
99    fn test_string() -> Result<()> {
100        // Sample the proof.
101        let expected = crate::test_helpers::sample_proof();
102
103        // Check the string representation.
104        let candidate = format!("{expected}");
105        assert_eq!(expected, Proof::from_str(&candidate)?);
106        assert_eq!(PROOF_PREFIX, candidate.split('1').next().unwrap());
107
108        Ok(())
109    }
110
111    #[test]
112    fn test_display() -> Result<()> {
113        // Sample the proof.
114        let expected = crate::test_helpers::sample_proof();
115
116        let candidate = expected.to_string();
117        assert_eq!(format!("{expected}"), candidate);
118        assert_eq!(PROOF_PREFIX, candidate.split('1').next().unwrap());
119
120        let candidate_recovered = Proof::<CurrentNetwork>::from_str(&candidate)?;
121        assert_eq!(expected, candidate_recovered);
122
123        Ok(())
124    }
125}