Skip to main content

qualia_core_db/net/qdnf/link/
adjacency.rs

1//! QLink adjacency state machine. Link possession is not controller authority.
2
3use crate::crypto::network::digest::sha384;
4use crate::net::qdnf::errors::QdnfError;
5use crate::net::qdnf::types::{LinkId, ObservedLocator, StrongDigest};
6
7#[repr(u8)]
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum AdjacencyState {
10    Undiscovered = 0,
11    BeaconSeen = 1,
12    ChallengeSent = 2,
13    ChallengeReceived = 3,
14    EphemeralProofVerified = 4,
15    LinkKeysDerived = 5,
16    Adjacent = 6,
17    Rekeying = 7,
18    Draining = 8,
19    Closed = 9,
20}
21
22#[repr(C)]
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct Adjacency {
25    pub local: LinkId,
26    pub remote: LinkId,
27    pub observed_peer: ObservedLocator,
28    pub state: AdjacencyState,
29    pub generation: u64,
30    pub mtu: u16,
31}
32
33impl Adjacency {
34    /// Activates the adjacency.
35    pub fn activate(&mut self) -> Result<(), QdnfError> {
36        if self.state != AdjacencyState::LinkKeysDerived
37            && self.state != AdjacencyState::EphemeralProofVerified
38        {
39            return Err(QdnfError::Unauthorized);
40        }
41        self.state = AdjacencyState::Adjacent;
42        Ok(())
43    }
44
45    /// `true` when `forwarding`.
46    pub fn is_forwarding(&self) -> bool {
47        self.state == AdjacencyState::Adjacent
48    }
49}
50
51/// Link ID derived from the key.
52pub fn link_id_from_key(public: &[u8], bearer_scope: &[u8], epoch: u64) -> LinkId {
53    let mut buf = [0u8; 80];
54    let label = b"qdnf:link:v1";
55    buf[..label.len()].copy_from_slice(label);
56    let mut off = label.len();
57    let copy = public.len().min(32);
58    buf[off..off + copy].copy_from_slice(&public[..copy]);
59    off += copy;
60    buf[off..off + 8].copy_from_slice(&epoch.to_be_bytes());
61    off += 8;
62    let scope_n = bearer_scope.len().min(16);
63    buf[off..off + scope_n].copy_from_slice(&bearer_scope[..scope_n]);
64    let digest: StrongDigest = sha384(&buf);
65    let mut id = LinkId::ZERO;
66    id.0.copy_from_slice(&digest.0[..16]);
67    id
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn unconfirmed_neighbor_is_not_forwarding() {
76        let adj = Adjacency {
77            local: LinkId::ZERO,
78            remote: LinkId::ZERO,
79            observed_peer: ObservedLocator::EMPTY,
80            state: AdjacencyState::ChallengeSent,
81            generation: 1,
82            mtu: 1280,
83        };
84        assert!(!adj.is_forwarding());
85    }
86}