use std::{ fs::File, io::Write, path::{Path, PathBuf}, }; use pem::Pem; use bft_json_crdt::keypair::{make_keypair, KeyPair}; const KEY_FILE: &str = ".side/node/keys.pem"; pub(crate) fn init() -> Result<(), std::io::Error> { println!("Initializing Side Node"); let home = std::env::var("HOME").expect("couldn't read home directory env variable"); let key_path = key_path(home); ensure_directory_exists(&key_path)?; let pem = create_pem(); write(key_path, pem)?; Ok(()) } fn ensure_directory_exists(key_path: &PathBuf) -> Result<(), std::io::Error> { Ok(if let Some(parent_dir) = key_path.parent() { println!("Creating parent directory: {:?}", parent_dir); std::fs::create_dir_all(parent_dir)?; }) } /// Writes a PEM-encoded string to a file at key_path. fn write(key_path: PathBuf, pem: String) -> Result<(), std::io::Error> { let mut file = File::create(key_path)?; file.write(pem.to_string().as_bytes())?; Ok(()) } /// Makes an Ed25519 keypair and returns the public and private keys as a PEM-encoded string. fn create_pem() -> String { let keys = make_keypair(); let public_pem = Pem::new("PUBLIC", keys.public().to_string()); let private_pem = Pem::new("PRIVATE", keys.private().to_string()); pem::encode_many(&[public_pem, private_pem]) } /// Returns the path to the key file for this host OS. fn key_path(home: String) -> PathBuf { let key_path = format!("{home}/.{KEY_FILE}"); let path = Path::new(&key_path).to_owned(); path } #[cfg(test)] mod tests { use super::*; #[test] fn creates_side_node_directory() { let node_dir = Path::new(KEY_FILE).parent().unwrap().to_str().unwrap(); let _ = init(); assert!(std::path::Path::new(node_dir).exists()); } #[test] fn creates_key_file() { let _ = init(); assert!(std::path::Path::new(KEY_FILE).exists()); } // #[test] // fn creates_config_file() {} }