use std::path::PathBuf; use config::SideNodeConfig; use crate::{keys, utils}; pub(crate) mod config; pub(crate) fn init(home: PathBuf, config: SideNodeConfig) -> Result<(), std::io::Error> { ensure_side_directory_exists(&home)?; let (key_path, config_path) = utils::side_paths(home.clone()); println!("Writing key to: {:?}", key_path); keys::write(key_path)?; println!("Writing config to: {:?}", config_path); config::write(&config, &config_path).expect("unable to write config file"); Ok(()) } /// Ensures that the directory at side_dir exists, so we have a place /// to store our key file and config file. fn ensure_side_directory_exists(side_dir: &PathBuf) -> Result<(), std::io::Error> { if side_dir.exists() { return Ok(()); } println!( "Config directory doesn't exist, creating at: {:?}", side_dir ); std::fs::create_dir_all(side_dir) } #[cfg(test)] mod tests { use std::{fs, path::Path}; use fastcrypto::{ ed25519::Ed25519KeyPair, traits::{EncodeDecodeBase64, KeyPair, ToFromBytes}, }; use super::*; fn default_side_node_config() -> SideNodeConfig { SideNodeConfig { name: "alice".to_string(), } } #[test] fn creates_side_node_directory() { let mut test_home = PathBuf::new(); let side_dir = "/tmp/side"; // clean up any previous test runs fs::remove_dir_all(side_dir).expect("couldn't remove side directory during test"); test_home.push(side_dir); let node_dir = Path::new(&test_home).parent().unwrap().to_str().unwrap(); let _ = init(test_home.clone(), default_side_node_config()); assert!(std::path::Path::new(node_dir).exists()); } #[test] fn creates_key_file() { let mut file_path = PathBuf::new(); file_path.push("/tmp/side"); let side_dir = file_path.clone(); file_path.push(utils::KEY_FILE); let _ = init(side_dir.clone(), default_side_node_config()); assert!(file_path.exists()); // check that the pem is readable let data = fs::read_to_string(file_path).expect("couldn't read key file"); let keys = Ed25519KeyPair::decode_base64(&data).expect("couldn't load keypair from file"); assert_eq!(keys.public().as_bytes().len(), 32); } #[test] fn creates_config_file() { let mut file_path = PathBuf::new(); file_path.push("/tmp/side"); let side_dir = file_path.clone(); file_path.push(utils::CONFIG_FILE); let _ = init(side_dir.clone(), default_side_node_config()); assert!(file_path.exists()); } }