iroh_sync/store/
pubkeys.rs1use std::sync::RwLock;
2use std::{collections::HashMap, sync::Arc};
3
4use ed25519_dalek::{SignatureError, VerifyingKey};
5
6use crate::{AuthorId, AuthorPublicKey, NamespaceId, NamespacePublicKey};
7
8pub trait PublicKeyStore {
14 fn public_key(&self, id: &[u8; 32]) -> Result<VerifyingKey, SignatureError>;
18
19 fn namespace_key(&self, bytes: &NamespaceId) -> Result<NamespacePublicKey, SignatureError> {
23 self.public_key(bytes.as_bytes()).map(Into::into)
24 }
25
26 fn author_key(&self, bytes: &AuthorId) -> Result<AuthorPublicKey, SignatureError> {
30 self.public_key(bytes.as_bytes()).map(Into::into)
31 }
32}
33
34impl<T: PublicKeyStore> PublicKeyStore for &T {
35 fn public_key(&self, id: &[u8; 32]) -> Result<VerifyingKey, SignatureError> {
36 (*self).public_key(id)
37 }
38}
39
40impl<T: PublicKeyStore> PublicKeyStore for &mut T {
41 fn public_key(&self, id: &[u8; 32]) -> Result<VerifyingKey, SignatureError> {
42 PublicKeyStore::public_key(*self, id)
43 }
44}
45
46impl PublicKeyStore for () {
47 fn public_key(&self, id: &[u8; 32]) -> Result<VerifyingKey, SignatureError> {
48 VerifyingKey::from_bytes(id)
49 }
50}
51
52#[derive(Debug, Clone, Default)]
55pub struct MemPublicKeyStore {
56 keys: Arc<RwLock<HashMap<[u8; 32], VerifyingKey>>>,
57}
58
59impl PublicKeyStore for MemPublicKeyStore {
60 fn public_key(&self, bytes: &[u8; 32]) -> Result<VerifyingKey, SignatureError> {
61 if let Some(id) = self.keys.read().unwrap().get(bytes) {
62 return Ok(*id);
63 }
64 let id = VerifyingKey::from_bytes(bytes)?;
65 self.keys.write().unwrap().insert(*bytes, id);
66 Ok(id)
67 }
68}