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

@@ -18,8 +18,8 @@ serde_with = "3.8.1"
sha256 = "1.5.0"
tokio = { version = "1.37.0", features = ["full"] }
websockets = "0.3.0"
pem = "3.0.4"
toml = "0.8.14"
fastcrypto = "0.1.8"
[features]
default = ["bft", "logging-list", "logging-json"]

View File

@@ -18,7 +18,7 @@ pub(crate) struct Args {
#[derive(Subcommand)]
pub(crate) enum Commands {
/// runs the Side Node
Run {},
Run { name: String },
/// initializes the Side Node with a new keypair
Init { name: String },

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());

27
side-node/src/keys.rs Normal file
View File

@@ -0,0 +1,27 @@
use std::{
fs::{self, File},
io::Write,
path::PathBuf,
};
use bft_json_crdt::keypair::{make_keypair, Ed25519KeyPair};
use fastcrypto::traits::EncodeDecodeBase64;
/// Writes a new Ed25519 keypair to the file at key_path.
pub(crate) fn write(key_path: PathBuf) -> Result<(), std::io::Error> {
let keys = make_keypair();
let mut file = File::create(key_path)?;
let out = keys.encode_base64();
file.write(out.as_bytes())?;
Ok(())
}
pub(crate) fn load_from_file(side_dir: PathBuf) -> Ed25519KeyPair {
let key_path = crate::utils::side_paths(side_dir.clone()).0;
let data = fs::read_to_string(key_path).expect("couldn't read key file");
println!("data: {:?}", data);
Ed25519KeyPair::decode_base64(&data).expect("couldn't load keypair from file")
}

View File

@@ -1,3 +1,5 @@
use std::path::PathBuf;
use bft_crdt_derive::add_crdt_fields;
use bft_json_crdt::{
@@ -10,6 +12,8 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use websockets::WebSocket;
use crate::keys;
#[add_crdt_fields]
#[derive(Clone, CrdtNode, Serialize, Deserialize)]
pub(crate) struct CrdtList {
@@ -25,8 +29,9 @@ pub(crate) struct Transaction {
amount: f64,
}
pub(crate) fn new() -> (BaseCrdt<CrdtList>, Ed25519KeyPair) {
let keys = make_keypair();
pub(crate) fn new(side_dir: PathBuf) -> (BaseCrdt<CrdtList>, Ed25519KeyPair) {
let keys = keys::load_from_file(side_dir);
// let keys = make_keypair();
let bft_crdt = BaseCrdt::<CrdtList>::new(&keys);
println!("Author is {}", keys.public().to_string());
(bft_crdt, keys)

View File

@@ -2,7 +2,9 @@ use cli::{parse_args, Commands};
pub(crate) mod cli;
pub(crate) mod init;
pub(crate) mod keys;
pub(crate) mod list_transaction_crdt;
pub(crate) mod utils;
pub(crate) mod websocket;
#[tokio::main]
@@ -17,8 +19,9 @@ async fn main() {
let _ = init::init(home(name), config);
}
Some(Commands::Run {}) => {
let (mut bft_crdt, keys) = list_transaction_crdt::new();
Some(Commands::Run { name }) => {
let side_dir = home(name);
let (mut bft_crdt, keys) = list_transaction_crdt::new(side_dir);
websocket::start(keys, &mut bft_crdt).await.unwrap();
}
None => println!("No command provided. Exiting. See --help for more information."),

15
side-node/src/utils.rs Normal file
View File

@@ -0,0 +1,15 @@
use std::path::PathBuf;
pub(crate) const KEY_FILE: &str = "keys.pem";
pub(crate) const CONFIG_FILE: &str = "config.toml";
/// Returns the path to the key file for this host OS.
pub(crate) 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)
}