From 95b2f6455a3b19fa3db2eddd27e06c293c081ea5 Mon Sep 17 00:00:00 2001 From: ghe0 Date: Sun, 18 Aug 2024 05:07:52 +0300 Subject: [PATCH] moved old functions into new impl --- src/datastore.rs | 213 +++++++++++++++++------------------------------ 1 file changed, 78 insertions(+), 135 deletions(-) diff --git a/src/datastore.rs b/src/datastore.rs index 5889fae..506e657 100644 --- a/src/datastore.rs +++ b/src/datastore.rs @@ -1,6 +1,5 @@ #![allow(dead_code)] use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; -use once_cell::sync::Lazy; use rand::rngs::OsRng; use std::collections::HashMap; use std::time::Duration; @@ -8,8 +7,6 @@ use std::time::SystemTime; use tabled::{Table, Tabled}; use tokio::sync::Mutex; -type IP = String; - #[derive(Clone)] pub struct NodeInfo { pub pubkey: VerifyingKey, @@ -22,6 +19,40 @@ pub struct Store { nodes: Mutex>, keys: Mutex>, } +pub enum SigningError { + CorruptedKey, + KeyNotFound, +} + +impl From for SigningError { + fn from(_: hex::FromHexError) -> Self { + Self::CorruptedKey + } +} + +impl From for SigningError { + fn from(_: ed25519_dalek::ed25519::Error) -> Self { + Self::CorruptedKey + } +} + +impl From for SigningError { + fn from(_: std::array::TryFromSliceError) -> Self { + Self::CorruptedKey + } +} + +type IP = String; + +impl std::fmt::Display for SigningError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let error_message = match self { + SigningError::CorruptedKey => "The public key is corrupted", + SigningError::KeyNotFound => "Did not find the public key", + }; + write!(f, "{}", error_message) + } +} impl Store { pub fn init() -> Self { @@ -34,21 +65,12 @@ impl Store { pub async fn add_mock_node(&self, ip: String) { let mut csprng = OsRng; let privkey = ed25519_dalek::SigningKey::generate(&mut csprng); - { - let mut nodes = self.nodes.lock().await; - nodes.insert( - ip, - NodeInfo { + self.add_node(ip, NodeInfo { pubkey: privkey.verifying_key(), updated_at: std::time::SystemTime::now(), online: true, - }, - ); - } - { - let mut keys = self.keys.lock().await; - keys.insert(privkey.verifying_key(), privkey); - } + }).await; + self.add_key(privkey.verifying_key(), privkey).await; } pub async fn tabled_node_list(&self) -> String { @@ -90,129 +112,50 @@ impl Store { Ok(signature) } -} -static NODES: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); + pub async fn add_key(&self, pubkey: VerifyingKey, privkey: SigningKey) { + let mut keys = self.keys.lock().await; + keys.insert(pubkey, privkey); + } -static KEYS: Lazy>> = - Lazy::new(|| Mutex::new(HashMap::new())); + pub async fn remove_key(&self, pubkey: &VerifyingKey) { + let mut keys = self.keys.lock().await; + keys.remove(pubkey); + } -pub enum SigningError { - CorruptedKey, - KeyNotFound, -} + async fn get_privkey(&self, pubkey: &VerifyingKey) -> Option { + let keys = self.keys.lock().await; + keys.get(pubkey).cloned() + } -impl std::fmt::Display for SigningError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let error_message = match self { - SigningError::CorruptedKey => "The public key is corrupted", - SigningError::KeyNotFound => "Did not find the public key", - }; - write!(f, "{}", error_message) + pub async fn add_node(&self, ip: String, info: NodeInfo) { + let mut nodes = self.nodes.lock().await; + nodes.insert(ip, info); + } + + pub async fn remove_node(&self, ip: &str) { + let mut nodes = self.nodes.lock().await; + nodes.remove(ip); + } + + pub async fn get_pubkey(&self, ip: &str) -> Option { + let nodes = self.nodes.lock().await; + nodes.get(ip).cloned() + } + + pub async fn cycle_self_key(&self) { + let mut csprng = OsRng; + // TODO: save old private key to disk using SGX Sealing + let privkey = ed25519_dalek::SigningKey::generate(&mut csprng); + self.add_node( + "localhost".to_string(), + NodeInfo { + pubkey: privkey.verifying_key(), + updated_at: std::time::SystemTime::now(), + online: true, + }, + ) + .await; + self.add_key(privkey.verifying_key(), privkey).await; } } - -impl From for SigningError { - fn from(_: hex::FromHexError) -> Self { - Self::CorruptedKey - } -} - -impl From for SigningError { - fn from(_: ed25519_dalek::ed25519::Error) -> Self { - Self::CorruptedKey - } -} - -impl From for SigningError { - fn from(_: std::array::TryFromSliceError) -> Self { - Self::CorruptedKey - } -} - -pub async fn add_key(pubkey: VerifyingKey, privkey: SigningKey) { - let mut keys = KEYS.lock().await; - keys.insert(pubkey, privkey); -} - -pub async fn remove_key(pubkey: &VerifyingKey) { - let mut keys = KEYS.lock().await; - keys.remove(pubkey); -} - -async fn get_privkey(pubkey: &VerifyingKey) -> Option { - let keys = KEYS.lock().await; - keys.get(pubkey).cloned() -} - -pub async fn sign_message_with_key(pubkey: &str, message: &str) -> Result { - // Parse the hex string into a VerifyingKey - let key_bytes = hex::decode(pubkey)?; - let pubkey = VerifyingKey::from_bytes(&key_bytes.as_slice().try_into()?)?; - - // Lock the hashmap and try to get the SigningKey - let key_store = KEYS.lock().await; - let signing_key = match key_store.get(&pubkey) { - Some(k) => k, - None => return Err(SigningError::KeyNotFound), - }; - - // TODO: check if to_bytes returns the signature in a format that people can verify from bash - let signature = hex::encode(signing_key.sign(message.as_bytes()).to_bytes()); - - Ok(signature) -} - -pub async fn add_node(ip: String, info: NodeInfo) { - let mut nodes = NODES.lock().await; - nodes.insert(ip, info); -} - -pub async fn remove_node(ip: &str) { - let mut nodes = NODES.lock().await; - nodes.remove(ip); -} - -pub async fn get_pubkey(ip: &str) -> Option { - let nodes = NODES.lock().await; - nodes.get(ip).cloned() -} - -pub async fn get_nodes_as_html_tabe() -> String { - #[derive(Tabled)] - struct OutputRow { - ip: String, - pubkey: String, - age: u64, - } - let mut output = vec![]; - for (ip, node_info) in NODES.lock().await.iter() { - let ip = ip.clone(); - let pubkey = hex::encode(node_info.pubkey.as_bytes()); - let age = std::time::SystemTime::now() - .duration_since(node_info.updated_at) - .unwrap_or(Duration::ZERO) - .as_secs(); - output.push(OutputRow { ip, pubkey, age }); - } - Table::new(output).to_string() -} - -// pub fn cycle_keys() { -// thread::spawn(|| { -// let mut csprng = OsRng; -// loop { -// // TODO: save old private key to disk using SGX Sealing -// let privkey = ed25519_dalek::SigningKey::generate(&mut csprng); -// add_node( -// "localhost".to_string(), -// NodeInfo { -// pubkey: privkey.verifying_key(), -// updated_at: std::time::SystemTime::now(), -// }, -// ); -// add_key(privkey.verifying_key(), privkey); -// thread::sleep(Duration::from_secs(60)); -// } -// }); -// }