snarkvm_console_account/private_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 PRIVATE_KEY_PREFIX: [u8; 11] = [127, 134, 189, 116, 210, 221, 210, 137, 145, 18, 253]; // APrivateKey1
19
20impl<N: Network> FromStr for PrivateKey<N> {
21    type Err = Error;
22
23    /// Reads in an account private 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() != 43 {
28            bail!("Invalid account private key length: found {}, expected 43", data.len())
29        } else if data[0..11] != PRIVATE_KEY_PREFIX {
30            bail!("Invalid account private key prefix: found {:?}, expected {:?}", &data[0..11], PRIVATE_KEY_PREFIX)
31        }
32        // Output the private key.
33        Ok(Self::try_from(Field::new(FromBytes::read_le(&data[11..43])?)).map_err(|e| error(format!("{e}")))?)
34    }
35}
36
37impl<N: Network> fmt::Display for PrivateKey<N> {
38    /// Writes the account private key as a base58 string.
39    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40        // Write the private key bytes.
41        let mut private_key = [0u8; 43];
42        private_key[0..11].copy_from_slice(&PRIVATE_KEY_PREFIX);
43        self.seed.write_le(&mut private_key[11..43]).map_err(|_| fmt::Error)?;
44        // Encode the private key into base58.
45        write!(f, "{}", bs58::encode(private_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 private key.
64            let expected = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
65
66            // Check the string representation.
67            let candidate = format!("{expected}");
68            assert_eq!(expected, PrivateKey::from_str(&candidate)?);
69            assert_eq!("APrivateKey", candidate.split('1').next().unwrap());
70        }
71        Ok(())
72    }
73}