Skip to main content

ruvector_dag/qudag/crypto/
keystore.rs

1//! Secure Keystore with Zeroization
2
3use super::identity::QuDagIdentity;
4use std::collections::HashMap;
5use zeroize::Zeroize;
6
7pub struct SecureKeystore {
8    identities: HashMap<String, QuDagIdentity>,
9    master_key: Option<[u8; 32]>,
10}
11
12impl SecureKeystore {
13    pub fn new() -> Self {
14        Self {
15            identities: HashMap::new(),
16            master_key: None,
17        }
18    }
19
20    pub fn with_master_key(key: [u8; 32]) -> Self {
21        Self {
22            identities: HashMap::new(),
23            master_key: Some(key),
24        }
25    }
26
27    pub fn add_identity(&mut self, identity: QuDagIdentity) {
28        let id = identity.node_id.clone();
29        self.identities.insert(id, identity);
30    }
31
32    pub fn get_identity(&self, node_id: &str) -> Option<&QuDagIdentity> {
33        self.identities.get(node_id)
34    }
35
36    pub fn remove_identity(&mut self, node_id: &str) -> Option<QuDagIdentity> {
37        self.identities.remove(node_id)
38    }
39
40    pub fn list_identities(&self) -> Vec<&str> {
41        self.identities.keys().map(|s| s.as_str()).collect()
42    }
43
44    pub fn clear(&mut self) {
45        self.identities.clear();
46        if let Some(ref mut key) = self.master_key {
47            key.zeroize();
48        }
49        self.master_key = None;
50    }
51}
52
53impl Drop for SecureKeystore {
54    fn drop(&mut self) {
55        self.clear();
56    }
57}
58
59impl Default for SecureKeystore {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65#[derive(Debug, thiserror::Error)]
66pub enum KeystoreError {
67    #[error("Identity not found")]
68    IdentityNotFound,
69    #[error("Keystore locked")]
70    Locked,
71    #[error("Storage error: {0}")]
72    StorageError(String),
73}