snarkvm_console_account/view_key/
string.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 VIEW_KEY_PREFIX: [u8; 7] = [14, 138, 223, 204, 247, 224, 122]; // AViewKey1
19
20impl<N: Network> FromStr for ViewKey<N> {
21    type Err = Error;
22
23    /// Reads in an account view key from a base58 string.
24    fn from_str(s: &str) -> Result<Self, Self::Err> {
25        // Encode the string into base58.
26        let data = bs58::decode(s).into_vec().map_err(|err| anyhow!("{:?}", err))?;
27        if data.len() != 39 {
28            bail!("Invalid account view key length: found {}, expected 39", data.len())
29        } else if data[0..7] != VIEW_KEY_PREFIX {
30            bail!("Invalid account view key prefix: found {:?}, expected {:?}", &data[0..7], VIEW_KEY_PREFIX)
31        }
32        // Output the view key.
33        Ok(Self::from_scalar(Scalar::new(FromBytes::read_le(&data[7..39])?)))
34    }
35}
36
37impl<N: Network> fmt::Display for ViewKey<N> {
38    /// Writes the account view key as a base58 string.
39    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40        // Write the view key bytes.
41        let mut view_key = [0u8; 39];
42        view_key[0..7].copy_from_slice(&VIEW_KEY_PREFIX);
43        self.0.write_le(&mut view_key[7..39]).map_err(|_| fmt::Error)?;
44        // Encode the view key into base58.
45        write!(f, "{}", bs58::encode(view_key).into_string())
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use snarkvm_console_network::MainnetV0;
53
54    type CurrentNetwork = MainnetV0;
55
56    const ITERATIONS: u64 = 1000;
57
58    #[test]
59    fn test_string() -> Result<()> {
60        let mut rng = TestRng::default();
61
62        for _ in 0..ITERATIONS {
63            // Sample a new view key.
64            let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
65            let expected = ViewKey::try_from(private_key)?;
66
67            // Check the string representation.
68            let candidate = format!("{expected}");
69            assert_eq!(expected, ViewKey::from_str(&candidate)?);
70            assert_eq!("AViewKey", candidate.split('1').next().unwrap());
71        }
72        Ok(())
73    }
74}