iroh_docs/store/
pubkeys.rs

1use std::{
2    collections::HashMap,
3    sync::{Arc, RwLock},
4};
5
6use ed25519_dalek::{SignatureError, VerifyingKey};
7
8use crate::{AuthorId, AuthorPublicKey, NamespaceId, NamespacePublicKey};
9
10/// Store trait for expanded public keys for authors and namespaces.
11///
12/// Used to cache [`ed25519_dalek::VerifyingKey`].
13///
14/// This trait is implemented for the unit type [`()`], where no caching is used.
15pub trait PublicKeyStore {
16    /// Convert a byte array into a  [`VerifyingKey`].
17    ///
18    /// New keys are inserted into the [`PublicKeyStore ] and reused on subsequent calls.
19    fn public_key(&self, id: &[u8; 32]) -> Result<VerifyingKey, SignatureError>;
20
21    /// Convert a [`NamespaceId`] into a [`NamespacePublicKey`].
22    ///
23    /// New keys are inserted into the [`PublicKeyStore ] and reused on subsequent calls.
24    fn namespace_key(&self, bytes: &NamespaceId) -> Result<NamespacePublicKey, SignatureError> {
25        self.public_key(bytes.as_bytes()).map(Into::into)
26    }
27
28    /// Convert a [`AuthorId`] into a [`AuthorPublicKey`].
29    ///
30    /// New keys are inserted into the [`PublicKeyStore ] and reused on subsequent calls.
31    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/// In-memory key storage
55// TODO: Make max number of keys stored configurable.
56#[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}