1use std::collections::HashMap;
6
7use secrecy::{ExposeSecret, SecretBox};
8use zeroize::Zeroizing;
9
10use crate::error::{KeepError, Result};
11use crate::keys::{KeyType, NostrKeypair};
12
13pub const MAX_KEYS: usize = 64;
15
16pub struct KeySlot {
18 pub pubkey: [u8; 32],
20 secret: SecretBox<[u8; 32]>,
21 pub key_type: KeyType,
23 pub name: String,
25 pub session_sign_count: u64,
27}
28
29impl KeySlot {
30 pub fn new(pubkey: [u8; 32], secret: [u8; 32], key_type: KeyType, name: String) -> Self {
32 Self {
33 pubkey,
34 secret: SecretBox::new(Box::new(secret)),
35 key_type,
36 name,
37 session_sign_count: 0,
38 }
39 }
40
41 pub fn expose_secret(&self) -> &[u8; 32] {
43 self.secret.expose_secret()
44 }
45
46 pub fn to_nostr_keypair(&self) -> Result<NostrKeypair> {
48 let mut secret_copy = Zeroizing::new(*self.secret.expose_secret());
49 NostrKeypair::from_secret_bytes(&mut secret_copy)
50 }
51}
52
53pub struct Keyring {
55 slots: HashMap<[u8; 32], KeySlot>,
56 primary: Option<[u8; 32]>,
57}
58
59impl Keyring {
60 pub fn new() -> Self {
62 Self {
63 slots: HashMap::new(),
64 primary: None,
65 }
66 }
67
68 pub fn load_key(
70 &mut self,
71 pubkey: [u8; 32],
72 secret: [u8; 32],
73 key_type: KeyType,
74 name: String,
75 ) -> Result<()> {
76 if self.slots.len() >= MAX_KEYS {
77 return Err(KeepError::KeyringFull(MAX_KEYS));
78 }
79
80 if self.slots.contains_key(&pubkey) {
81 return Err(KeepError::KeyAlreadyExists(hex::encode(pubkey)));
82 }
83
84 let slot = KeySlot::new(pubkey, secret, key_type, name);
85 self.slots.insert(pubkey, slot);
86
87 if self.primary.is_none() {
88 self.primary = Some(pubkey);
89 }
90
91 Ok(())
92 }
93
94 pub fn get(&self, pubkey: &[u8; 32]) -> Option<&KeySlot> {
96 self.slots.get(pubkey)
97 }
98
99 pub fn get_mut(&mut self, pubkey: &[u8; 32]) -> Option<&mut KeySlot> {
101 self.slots.get_mut(pubkey)
102 }
103
104 pub fn get_by_name(&self, name: &str) -> Option<&KeySlot> {
106 self.slots.values().find(|slot| slot.name == name)
107 }
108
109 pub fn get_primary(&self) -> Option<&KeySlot> {
111 self.primary.and_then(|pk| self.slots.get(&pk))
112 }
113
114 pub fn get_primary_mut(&mut self) -> Option<&mut KeySlot> {
116 if let Some(pk) = self.primary {
117 self.slots.get_mut(&pk)
118 } else {
119 None
120 }
121 }
122
123 pub fn set_primary(&mut self, pubkey: [u8; 32]) -> Result<()> {
125 if !self.slots.contains_key(&pubkey) {
126 return Err(KeepError::KeyNotFound(hex::encode(pubkey)));
127 }
128 self.primary = Some(pubkey);
129 Ok(())
130 }
131
132 pub fn remove(&mut self, pubkey: &[u8; 32]) -> Result<()> {
134 if self.slots.remove(pubkey).is_none() {
135 return Err(KeepError::KeyNotFound(hex::encode(pubkey)));
136 }
137
138 if self.primary == Some(*pubkey) {
139 self.primary = self.slots.keys().next().copied();
140 }
141
142 Ok(())
143 }
144
145 pub fn list(&self) -> impl Iterator<Item = &KeySlot> {
147 self.slots.values()
148 }
149
150 pub fn len(&self) -> usize {
152 self.slots.len()
153 }
154
155 pub fn is_empty(&self) -> bool {
157 self.slots.is_empty()
158 }
159
160 pub fn clear(&mut self) {
162 self.slots.clear();
163 self.primary = None;
164 }
165}
166
167impl Default for Keyring {
168 fn default() -> Self {
169 Self::new()
170 }
171}
172
173impl Drop for Keyring {
174 fn drop(&mut self) {
175 self.clear();
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use crate::crypto;
183
184 #[test]
185 fn test_keyring_basic() {
186 let mut kr = Keyring::new();
187
188 let pubkey: [u8; 32] = crypto::random_bytes();
189 let secret: [u8; 32] = crypto::random_bytes();
190
191 kr.load_key(pubkey, secret, KeyType::Nostr, "test".into())
192 .unwrap();
193
194 assert_eq!(kr.len(), 1);
195 assert!(kr.get(&pubkey).is_some());
196 assert!(kr.get_primary().is_some());
197 }
198
199 #[test]
200 fn test_keyring_max_keys() {
201 let mut kr = Keyring::new();
202
203 for i in 0..MAX_KEYS {
204 let mut pubkey: [u8; 32] = [0; 32];
205 pubkey[0] = i as u8;
206 let secret: [u8; 32] = crypto::random_bytes();
207
208 kr.load_key(pubkey, secret, KeyType::Nostr, format!("key{i}"))
209 .unwrap();
210 }
211
212 let pubkey: [u8; 32] = crypto::random_bytes();
213 let secret: [u8; 32] = crypto::random_bytes();
214 let result = kr.load_key(pubkey, secret, KeyType::Nostr, "overflow".into());
215
216 assert!(matches!(result, Err(KeepError::KeyringFull(_))));
217 }
218}