Skip to main content

second_brain_sync/keyring/
status.rs

1use anyhow::Result;
2use second_brain_core::keys::{Epoch, PeerView};
3use serde::Serialize;
4
5use super::Keyring;
6use crate::protocol::HandshakeKeys;
7
8/// This device's standing in its sync identity, as the store shows it.
9#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
10pub struct IdentityStatus {
11    pub identity: Option<String>,
12    /// Numbers of the epochs this device holds an envelope for.
13    pub epochs: Vec<u32>,
14    /// A revocation this device holds reaches it.
15    pub removed: bool,
16    /// Removed, or a peer that holds this device's row has an epoch it did
17    /// not wrap to this device.
18    pub possibly_revoked: bool,
19    /// Whether any peer's last hello listed this device's row; None until
20    /// a hello from a device still in the identity was taken.
21    pub row_accepted: Option<bool>,
22    pub peers: Vec<PeerStanding>,
23    /// Recovery phrases retired under this identity: none of them opens an
24    /// epoch minted after its retirement.
25    pub retired_recovery: Vec<RetiredPhrase>,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
29pub struct RetiredPhrase {
30    pub fingerprint: String,
31    /// None when only an epoch's cause named it, so no device here could
32    /// verify who retired it.
33    pub retired_by: Option<String>,
34    pub at_micros: Option<i64>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
38pub struct PeerStanding {
39    pub peer: String,
40    pub heard_at_micros: i64,
41    pub holds_own_row: bool,
42    /// Epochs the peer holds that this device cannot open.
43    pub lacking: Vec<u32>,
44}
45
46impl Keyring<'_> {
47    pub fn status(&self) -> Result<IdentityStatus> {
48        let Some(tag) = &self.identity else {
49            return Ok(IdentityStatus::default());
50        };
51        let removed = self.is_removed()?;
52        let mut peers = Vec::new();
53        for view in self.store.peer_views(tag)? {
54            if self.active_row(&view.peer)?.is_none() {
55                continue;
56            }
57            peers.push(PeerStanding {
58                peer: view.peer,
59                heard_at_micros: view.heard_at_micros,
60                holds_own_row: view.holds_own_row,
61                lacking: view.lacking.iter().map(|e| e.number).collect(),
62            });
63        }
64        let row_accepted = (!peers.is_empty()).then(|| peers.iter().any(|p| p.holds_own_row));
65        let possibly_revoked = removed
66            || peers
67                .iter()
68                .any(|p| p.holds_own_row && !p.lacking.is_empty());
69        let mut epochs: Vec<u32> = self.stored_epochs()?.iter().map(|e| e.number).collect();
70        epochs.sort_unstable();
71        epochs.dedup();
72        let retired_recovery = self
73            .store
74            .retired_under(tag)?
75            .into_iter()
76            .map(|(fingerprint, signed)| RetiredPhrase {
77                retired_by: signed
78                    .as_ref()
79                    .map(|s| self.device_name(&s.retirement.retirer)),
80                at_micros: signed.as_ref().map(|s| s.retirement.created_at_micros),
81                fingerprint,
82            })
83            .collect();
84        Ok(IdentityStatus {
85            identity: Some(tag.as_str().to_string()),
86            epochs,
87            removed,
88            possibly_revoked,
89            row_accepted,
90            peers,
91            retired_recovery,
92        })
93    }
94
95    /// Run after a peer's hello was taken, so `lacking` names only the
96    /// epochs it held back from this device.
97    pub(super) fn record_peer_view(
98        &self,
99        peer: &str,
100        keys: &HandshakeKeys,
101        now_micros: i64,
102    ) -> Result<()> {
103        let Some(tag) = &self.identity else {
104            return Ok(());
105        };
106        if peer == self.own() {
107            return Ok(());
108        }
109        let own_key = self.device.verifying_key();
110        let holds_own_row = keys.devices.iter().any(|row| {
111            row.record.machine_id == self.own()
112                && row.record.identity_tag == tag.as_str()
113                && row
114                    .record
115                    .signing_public_key()
116                    .is_ok_and(|key| key == own_key)
117        });
118        let held = self.stored_epochs()?;
119        let lacking = keys
120            .epochs
121            .iter()
122            .filter(|epoch| !held.contains(epoch))
123            .copied()
124            .collect();
125        self.store.record_peer_view(
126            tag,
127            &PeerView {
128                peer: peer.to_string(),
129                heard_at_micros: now_micros,
130                holds_own_row,
131                lacking,
132            },
133        )
134    }
135
136    fn stored_epochs(&self) -> Result<Vec<Epoch>> {
137        let recipient = self.device.age_recipient().to_string();
138        Ok(self
139            .store
140            .own_identity_envelopes(&recipient)?
141            .map(|(_, envelopes)| envelopes.into_iter().map(|e| e.epoch).collect())
142            .unwrap_or_default())
143    }
144}