interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-core / src / key_cache.rs

76 lines · 3292 bytes Raw Blame History
1//! Bounded per-thread cache of decoded Ed25519 verifying keys (issue #93).
2//!
3//! `VerifyingKey::from_bytes` decompresses the curve point on every call. One accepted
4//! submit verifies the changeset envelope (author key, [`crate::ChangesetEnvelope::validate`]),
5//! the grant (authority key) and the request (agent key, both in `synapse-auth`), and these
6//! keys repeat across requests, so the decoded key is cached here, keyed by the exact 32 key
7//! bytes. The cache lives in this crate so the envelope check and `synapse-auth` share it.
8//! Only the decode is cached: every signature is still verified in full, with the same
9//! `verify` or `verify_strict` call as before, by the existing `ed25519-dalek` crate.
10//!
11//! Bounds and refusals:
12//! - Only keys that decode are cached. Bytes that do not decode are refused on every call,
13//! exactly as before (the caller maps the error to its refusal code), and never enter
14//! the cache, so churn of invalid keys cannot grow it.
15//! - At most [`KEY_CACHE_CAPACITY`] keys per thread; the oldest insertion is evicted first.
16//! Churn of valid keys (each new key one decode) therefore keeps the cache at the cap.
17//! - Per thread: no lock on the verify path and nothing shared between threads.
18
19use ed25519_dalek::{SignatureError, VerifyingKey};
20use std::cell::RefCell;
21use std::collections::{HashMap, VecDeque};
22
23/// Most decoded keys one thread keeps.
24pub const KEY_CACHE_CAPACITY: usize = 64;
25
26#[derive(Default)]
27struct KeyCache {
28 keys: HashMap<[u8; 32], VerifyingKey>,
29 /// Insertion order, oldest first; always the same key set as `keys`.
30 order: VecDeque<[u8; 32]>,
31 /// Point decodes performed (cache misses that reached `VerifyingKey::from_bytes`).
32 decodes: u64,
33}
34
35thread_local! {
36 static CACHE: RefCell<KeyCache> = RefCell::new(KeyCache::default());
37}
38
39/// The decoded verifying key for `bytes`: from this thread's cache, or decoded with
40/// `VerifyingKey::from_bytes` (and cached when it decodes). Same result and same error as
41/// calling `VerifyingKey::from_bytes(bytes)` directly.
42pub fn cached_verifying_key(bytes: &[u8; 32]) -> Result<VerifyingKey, SignatureError> {
43 CACHE
44 .try_with(|cell| {
45 let mut cache = cell.borrow_mut();
46 if let Some(key) = cache.keys.get(bytes) {
47 return Ok(*key);
48 }
49 cache.decodes += 1;
50 let key = VerifyingKey::from_bytes(bytes)?;
51 if cache.keys.len() >= KEY_CACHE_CAPACITY {
52 if let Some(oldest) = cache.order.pop_front() {
53 cache.keys.remove(&oldest);
54 }
55 }
56 cache.keys.insert(*bytes, key);
57 cache.order.push_back(*bytes);
58 Ok(key)
59 })
60 // Thread-local storage already torn down (thread exit): decode without caching.
61 .unwrap_or_else(|_| VerifyingKey::from_bytes(bytes))
62}
63
64/// `(cached keys, point decodes)` for the calling thread. Diagnostic only: tests use it to
65/// count decodes; it changes nothing.
66#[doc(hidden)]
67pub fn key_cache_stats() -> (usize, u64) {
68 CACHE.with(|cell| {
69 let cache = cell.borrow();
70 debug_assert_eq!(cache.keys.len(), cache.order.len());
71 (cache.keys.len(), cache.decodes)
72 })
73}
74
75#[cfg(test)]
76mod tests;