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