snarkvm_console_account/signature/
parse.rs

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