string.rs
1 // Copyright (c) 2019-2025 Alpha-Delta Network Inc. 2 // This file is part of the deltavm 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 16 use super::*; 17 18 static GRAPH_KEY_PREFIX: [u8; 9] = [42, 72, 193, 144, 65, 126, 212, 229, 211]; // AGraphKey1 19 20 impl<N: Network> FromStr for GraphKey<N> { 21 type Err = Error; 22 23 /// Reads in an account graph 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() != 41 { 28 bail!("Invalid account graph key length: found {}, expected 41", data.len()) 29 } else if data[0..9] != GRAPH_KEY_PREFIX { 30 bail!("Invalid account graph key prefix: found {:?}, expected {:?}", &data[0..9], GRAPH_KEY_PREFIX) 31 } 32 // Output the graph key. 33 Self::try_from(Field::read_le(&data[9..41])?) 34 } 35 } 36 37 impl<N: Network> fmt::Display for GraphKey<N> { 38 /// Writes the account graph key as a base58 string. 39 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 40 // Write the graph key bytes. 41 let mut graph_key = [0u8; 41]; 42 graph_key[0..9].copy_from_slice(&GRAPH_KEY_PREFIX); 43 self.sk_tag.write_le(&mut graph_key[9..41]).map_err(|_| fmt::Error)?; 44 // Encode the graph key into base58. 45 write!(f, "{}", bs58::encode(graph_key).into_string()) 46 } 47 } 48 49 #[cfg(test)] 50 mod tests { 51 use super::*; 52 use crate::PrivateKey; 53 use deltavm_console_network::MainnetV0; 54 55 type CurrentNetwork = MainnetV0; 56 57 const ITERATIONS: u64 = 10_000; 58 59 #[test] 60 fn test_string() -> Result<()> { 61 let mut rng = TestRng::default(); 62 63 for _ in 0..ITERATIONS { 64 // Sample a new graph key. 65 let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?; 66 let view_key = ViewKey::try_from(private_key)?; 67 let expected = GraphKey::try_from(view_key)?; 68 69 // Check the string representation. 70 let candidate = format!("{expected}"); 71 assert_eq!(expected, GraphKey::from_str(&candidate)?); 72 assert_eq!("AGraphKey", candidate.split('1').next().unwrap()); 73 } 74 Ok(()) 75 } 76 }