iroh_sync/store/
pubkeys.rs

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