moved old functions into new impl

This commit is contained in:
ghe0 2024-08-18 05:07:52 +03:00
parent 4f2cec3fa7
commit 95b2f6455a

@ -1,6 +1,5 @@
#![allow(dead_code)] #![allow(dead_code)]
use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
use once_cell::sync::Lazy;
use rand::rngs::OsRng; use rand::rngs::OsRng;
use std::collections::HashMap; use std::collections::HashMap;
use std::time::Duration; use std::time::Duration;
@ -8,8 +7,6 @@ use std::time::SystemTime;
use tabled::{Table, Tabled}; use tabled::{Table, Tabled};
use tokio::sync::Mutex; use tokio::sync::Mutex;
type IP = String;
#[derive(Clone)] #[derive(Clone)]
pub struct NodeInfo { pub struct NodeInfo {
pub pubkey: VerifyingKey, pub pubkey: VerifyingKey,
@ -22,6 +19,40 @@ pub struct Store {
nodes: Mutex<HashMap<IP, NodeInfo>>, nodes: Mutex<HashMap<IP, NodeInfo>>,
keys: Mutex<HashMap<VerifyingKey, SigningKey>>, keys: Mutex<HashMap<VerifyingKey, SigningKey>>,
} }
pub enum SigningError {
CorruptedKey,
KeyNotFound,
}
impl From<hex::FromHexError> for SigningError {
fn from(_: hex::FromHexError) -> Self {
Self::CorruptedKey
}
}
impl From<ed25519_dalek::ed25519::Error> for SigningError {
fn from(_: ed25519_dalek::ed25519::Error) -> Self {
Self::CorruptedKey
}
}
impl From<std::array::TryFromSliceError> 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 { impl Store {
pub fn init() -> Self { pub fn init() -> Self {
@ -34,21 +65,12 @@ impl Store {
pub async fn add_mock_node(&self, ip: String) { pub async fn add_mock_node(&self, ip: String) {
let mut csprng = OsRng; let mut csprng = OsRng;
let privkey = ed25519_dalek::SigningKey::generate(&mut csprng); let privkey = ed25519_dalek::SigningKey::generate(&mut csprng);
{ self.add_node(ip, NodeInfo {
let mut nodes = self.nodes.lock().await;
nodes.insert(
ip,
NodeInfo {
pubkey: privkey.verifying_key(), pubkey: privkey.verifying_key(),
updated_at: std::time::SystemTime::now(), updated_at: std::time::SystemTime::now(),
online: true, online: true,
}, }).await;
); self.add_key(privkey.verifying_key(), privkey).await;
}
{
let mut keys = self.keys.lock().await;
keys.insert(privkey.verifying_key(), privkey);
}
} }
pub async fn tabled_node_list(&self) -> String { pub async fn tabled_node_list(&self) -> String {
@ -90,129 +112,50 @@ impl Store {
Ok(signature) Ok(signature)
} }
}
static NODES: Lazy<Mutex<HashMap<String, NodeInfo>>> = 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<Mutex<HashMap<VerifyingKey, SigningKey>>> = pub async fn remove_key(&self, pubkey: &VerifyingKey) {
Lazy::new(|| Mutex::new(HashMap::new())); let mut keys = self.keys.lock().await;
keys.remove(pubkey);
}
pub enum SigningError { async fn get_privkey(&self, pubkey: &VerifyingKey) -> Option<SigningKey> {
CorruptedKey, let keys = self.keys.lock().await;
KeyNotFound, keys.get(pubkey).cloned()
} }
impl std::fmt::Display for SigningError { pub async fn add_node(&self, ip: String, info: NodeInfo) {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut nodes = self.nodes.lock().await;
let error_message = match self { nodes.insert(ip, info);
SigningError::CorruptedKey => "The public key is corrupted", }
SigningError::KeyNotFound => "Did not find the public key",
}; pub async fn remove_node(&self, ip: &str) {
write!(f, "{}", error_message) let mut nodes = self.nodes.lock().await;
nodes.remove(ip);
}
pub async fn get_pubkey(&self, ip: &str) -> Option<NodeInfo> {
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<hex::FromHexError> for SigningError {
fn from(_: hex::FromHexError) -> Self {
Self::CorruptedKey
}
}
impl From<ed25519_dalek::ed25519::Error> for SigningError {
fn from(_: ed25519_dalek::ed25519::Error) -> Self {
Self::CorruptedKey
}
}
impl From<std::array::TryFromSliceError> 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<SigningKey> {
let keys = KEYS.lock().await;
keys.get(pubkey).cloned()
}
pub async fn sign_message_with_key(pubkey: &str, message: &str) -> Result<String, SigningError> {
// 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<NodeInfo> {
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));
// }
// });
// }