Key generation, saving and loading works.

This commit is contained in:
Dave Hrycyszyn
2024-06-06 18:52:39 +01:00
parent 6d6c544dd5
commit cda6dd2901
9 changed files with 67 additions and 58 deletions

View File

@@ -1,20 +0,0 @@
use std::{fs::File, io::Write, path::PathBuf};
use bft_json_crdt::keypair::{make_keypair, KeyPair};
use pem::Pem;
/// Makes an Ed25519 keypair and returns the public and private keys as a PEM-encoded string.
pub(crate) fn setup() -> 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])
}
/// Writes a PEM-encoded string to a file at key_path.
pub(crate) 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(())
}

View File

@@ -2,19 +2,16 @@ use std::path::PathBuf;
use config::SideNodeConfig;
pub(crate) mod config;
mod keys;
use crate::{keys, utils};
const KEY_FILE: &str = "keys.pem";
const CONFIG_FILE: &str = "config.toml";
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) = side_paths(home.clone());
let (key_path, config_path) = utils::side_paths(home.clone());
println!("Writing key to: {:?}", key_path);
let pem = keys::setup();
keys::write(key_path, pem)?;
keys::write(key_path)?;
println!("Writing config to: {:?}", config_path);
config::write(&config, &config_path).expect("unable to write config file");
@@ -28,21 +25,13 @@ fn ensure_side_directory_exists(side_dir: &PathBuf) -> Result<(), std::io::Error
if side_dir.exists() {
return Ok(());
}
println!("Creating side config directory: {:?}", side_dir);
println!(
"Config directory doesn't exist, creating at: {:?}",
side_dir
);
std::fs::create_dir_all(side_dir)
}
/// Returns the path to the key file for this host OS.
fn side_paths(prefix: PathBuf) -> (PathBuf, PathBuf) {
let mut key_path = prefix.clone();
key_path.push(KEY_FILE);
let mut config_path = prefix.clone();
config_path.push(CONFIG_FILE);
(key_path, config_path)
}
#[cfg(test)]
mod tests {
use std::{fs, path::Path};
@@ -74,7 +63,7 @@ mod tests {
let mut file_path = PathBuf::new();
file_path.push("/tmp/side");
let side_dir = file_path.clone();
file_path.push(KEY_FILE);
file_path.push(utils::KEY_FILE);
let _ = init(side_dir.clone(), default_side_node_config());
assert!(file_path.exists());
@@ -89,7 +78,7 @@ mod tests {
let mut file_path = PathBuf::new();
file_path.push("/tmp/side");
let side_dir = file_path.clone();
file_path.push(CONFIG_FILE);
file_path.push(utils::CONFIG_FILE);
let _ = init(side_dir.clone(), default_side_node_config());
assert!(file_path.exists());