Skip to main content

coven_crypto/custody/
memory.rs

1//! Custody for one session only (E1).
2
3use coven_foundation::locks::lock_unpoisoned;
4use std::sync::Mutex;
5
6/// In-memory custody for `StoreKeyring` or `MemberIdentity`, erased with the session.
7pub struct InMemoryCustody<T> {
8    secret: Mutex<Option<T>>,
9}
10
11impl<T: Clone> InMemoryCustody<T> {
12    /// Start without keys; bootstrap fills custody only after opening sealed keys.
13    pub fn empty() -> Self {
14        Self { secret: Mutex::new(None) }
15    }
16
17    /// Retain the supplied keys for this session (E1).
18    pub fn new(secret: T) -> Self {
19        Self { secret: Mutex::new(Some(secret)) }
20    }
21
22    pub(crate) fn read(&self) -> Option<T> {
23        // The custody traits return owned keys while custody keeps its copy.
24        lock_unpoisoned(&self.secret).clone()
25    }
26
27    pub(crate) fn write(&self, secret: &T) {
28        *lock_unpoisoned(&self.secret) = Some(secret.clone());
29    }
30
31    pub(crate) fn remove(&self) {
32        *lock_unpoisoned(&self.secret) = None;
33    }
34}
35
36impl<T> std::fmt::Debug for InMemoryCustody<T> {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.write_str("InMemoryCustody([REDACTED])")
39    }
40}
41
42#[cfg(test)]
43#[path = "memory_tests.rs"]
44mod tests;