Skip to main content

qualia_core_db/net/peer/host/
mod.rs

1//! Native peer host. Replaces libp2p `Swarm` + `NetworkBehaviour`.
2//!
3//! Discovery is QLink beacons (not mDNS). Lookup is QSR (not Kademlia).
4//! Streams are QSession (not Yamux). Session keys are `qpr-pq-1` (not Noise).
5//! Application send/receive requires a verified permit and packet protection.
6
7pub mod builder;
8mod discovery;
9pub mod driver;
10pub mod exchange;
11pub mod identity;
12mod path_cc;
13pub mod services;
14pub mod session_table;
15
16use crate::net::peer::cells::CellSlot;
17use crate::net::peer::runtime::{CancelEpoch, ReservationLedger};
18use crate::net::qdnf::bearer::IpcEndpoint;
19use crate::net::qdnf::errors::QdnfError;
20use crate::net::qdnf::link::{ChallengeTable, NeighborTable, PreAuthBudget};
21use crate::net::qdnf::resolve::qsr::{
22    lookup_exact, lookup_qsr_full as qsr_lookup_full, CoverInterval, HandoverStage, QsrOutcome,
23    QsrSnapshot, TokenStage,
24};
25use crate::net::qdnf::types::{Generation, LinkId, ObservedLocator, StrongDigest};
26
27pub use builder::{PeerBuilder, CELL_BYTES_DEFAULT};
28pub use driver::SealedFrame;
29pub use exchange::authorised_ipc_stream_exchange;
30pub use identity::ControllerIdentity;
31pub use services::ServiceId;
32pub use session_table::{SessionHandle, SessionTable, MAX_SESSIONS};
33
34pub struct NativePeer {
35    pub(crate) identity: ControllerIdentity,
36    pub(crate) local_link: LinkId,
37    pub(crate) neighbors: NeighborTable,
38    pub(crate) ledger: ReservationLedger,
39    pub(crate) sessions: session_table::SessionTable,
40    pub(crate) primary: Option<SessionHandle>,
41    pub(crate) bearer: IpcEndpoint,
42    pub(crate) cancel_epoch: CancelEpoch,
43    pub(crate) cancelled: bool,
44    pub(crate) cell_slot: Option<CellSlot>,
45    pub(crate) challenges: ChallengeTable,
46    pub(crate) preauth: PreAuthBudget,
47}
48
49impl NativePeer {
50    #[inline]
51    /// `NativePeer::identity`.
52    pub fn identity(&self) -> ControllerIdentity {
53        self.identity
54    }
55
56    #[inline]
57    /// Locator.
58    pub fn locator(&self) -> ObservedLocator {
59        self.bearer.locator()
60    }
61
62    #[inline]
63    /// `NativePeer::local_link`.
64    pub fn local_link(&self) -> LinkId {
65        self.local_link
66    }
67
68    /// Cover-interval membership only. Not authenticated existence.
69    /// Use [`Self::lookup_qsr_full`] for tokens and handover.
70    pub fn lookup_qsr(
71        key: &StrongDigest,
72        covers: &[CoverInterval],
73    ) -> Result<QsrOutcome, QdnfError> {
74        lookup_exact(key, covers)
75    }
76
77    /// Production QSR lookup: exact cover/snapshot, then tokens, then handover.
78    pub fn lookup_qsr_full(
79        key: &StrongDigest,
80        covers: &[CoverInterval],
81        snapshot: &QsrSnapshot,
82        required_generation: Generation,
83        token: Option<TokenStage<'_>>,
84        handover: Option<HandoverStage<'_>>,
85        out: &mut [StrongDigest],
86    ) -> Result<QsrOutcome, QdnfError> {
87        qsr_lookup_full(
88            key,
89            covers,
90            snapshot,
91            required_generation,
92            token,
93            handover,
94            out,
95        )
96    }
97
98    /// Service identifier alone cannot open an application session (E01/R01).
99    pub fn open_session(&mut self, _service: ServiceId) -> Result<(), QdnfError> {
100        Err(QdnfError::Unauthorized)
101    }
102
103    /// `NativePeer::remote_or_reject`.
104    pub(crate) fn remote_or_reject(&self) -> Result<LinkId, QdnfError> {
105        let mut want = LinkId::ZERO;
106        want.0[0] = if self.local_link.0[0] == 1 { 2 } else { 1 };
107        if self.neighbors.forwarding(want).is_some() {
108            Ok(want)
109        } else {
110            Err(QdnfError::NoRoute)
111        }
112    }
113
114    /// `neighbor` count.
115    pub fn neighbor_count(&self) -> usize {
116        self.neighbors.len()
117    }
118}
119
120/// Two-peer native stream without libp2p, IP, or DNS. Protected QPR path.
121pub fn native_ipc_stream_exchange(payload: &[u8]) -> Result<usize, QdnfError> {
122    authorised_ipc_stream_exchange(payload)
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::net::peer::cells::MAX_ORDINARY_CELL;
129    use crate::net::qdnf::authority::{
130        binding_for_controllers, AuthorityOwner, ContactState, InstalledSessionKeys,
131    };
132    use crate::net::qdnf::harness::oracles::wire::{plaintext_on_wire, ProtectedView};
133    use crate::net::qdnf::types::{Generation, ScopeEpoch};
134
135    fn activate(
136        peer: &mut NativePeer,
137        local: &[u8],
138        remote: &[u8],
139        tag: u8,
140        now: u64,
141    ) -> SessionHandle {
142        let mut owner = AuthorityOwner::new();
143        let binding = binding_for_controllers(local, remote, b"q42:QSync/1", &[b'o', tag]).unwrap();
144        let (_cred, _contact, handle) = owner
145            .install_grant(binding, now, now.saturating_add(3600), ContactState::Active)
146            .unwrap();
147        let permit = owner.issue_permit(handle, binding, now, 4096).unwrap();
148        let mut send = [tag.saturating_add(1); 32];
149        let mut recv = [tag.saturating_add(80); 32];
150        send[31] = 1;
151        recv[31] = 2;
152        let keys = InstalledSessionKeys::new(Generation(1), send, recv, true).unwrap();
153        peer.activate_protected(permit, keys, now).unwrap()
154    }
155
156    #[test]
157    fn native_peer_replaces_swarm_without_libp2p() {
158        let n = native_ipc_stream_exchange(b"hello-qpr").unwrap();
159        assert_eq!(n, 9);
160    }
161
162    #[test]
163    fn qsr_lookup_is_not_kademlia() {
164        let key = StrongDigest([7u8; 48]);
165        let covers = [CoverInterval { start: 0, end: 15 }];
166        assert_eq!(
167            NativePeer::lookup_qsr(&key, &covers).unwrap(),
168            QsrOutcome::NeedContinuation
169        );
170        let snap = QsrSnapshot::empty(Generation(1));
171        let mut out = [StrongDigest::ZERO; 1];
172        assert_eq!(
173            NativePeer::lookup_qsr_full(&key, &covers, &snap, Generation(1), None, None, &mut out,)
174                .unwrap(),
175            QsrOutcome::EmptyInSnapshot
176        );
177    }
178
179    #[test]
180    fn session_required_before_stream() {
181        let scope = ScopeEpoch { scope: 1, epoch: 1 };
182        let (mut a, b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
183        assert_eq!(
184            a.send_stream(&b.locator(), b"x"),
185            Err(QdnfError::Unauthorized)
186        );
187    }
188
189    #[test]
190    fn service_open_cannot_mint_active_allow() {
191        let scope = ScopeEpoch { scope: 1, epoch: 1 };
192        let (mut a, _b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
193        let service = ServiceId::from_iri(b"q42:QSync/1").unwrap();
194        assert_eq!(a.open_session(service), Err(QdnfError::Unauthorized));
195    }
196
197    #[test]
198    fn protected_exchange_is_not_plaintext_on_wire() {
199        let app = b"hello-qpr";
200        assert!(!plaintext_on_wire(ProtectedView {
201            wire_payload: &[0u8; 9],
202            application: app,
203        }));
204        let n = authorised_ipc_stream_exchange(app).unwrap();
205        assert_eq!(n, 9);
206    }
207
208    #[test]
209    fn rekey_without_protection_is_unauthorized() {
210        let scope = ScopeEpoch { scope: 1, epoch: 1 };
211        let (mut a, _b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
212        let mut table =
213            crate::net::qdnf::session::rekey::RekeyTable::from_keys([1u8; 32], [2u8; 32]).unwrap();
214        assert_eq!(a.rekey_protected(&mut table), Err(QdnfError::Unauthorized));
215    }
216
217    #[test]
218    fn builder_rejects_zero_and_oversize_cell_bytes() {
219        let link = LinkId::ZERO;
220        assert_eq!(
221            PeerBuilder::new(b"did:q42:a", link, 0).unwrap_err(),
222            QdnfError::Capacity
223        );
224        assert_eq!(
225            PeerBuilder::new(b"did:q42:a", link, MAX_ORDINARY_CELL + 1).unwrap_err(),
226            QdnfError::Capacity
227        );
228    }
229
230    #[test]
231    fn two_sessions_live_closing_one_keeps_the_other() {
232        let scope = ScopeEpoch { scope: 1, epoch: 1 };
233        let (mut a, _b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
234        let now = 1_700_000_000u64;
235        let h1 = activate(&mut a, b"did:q42:a", b"did:q42:b", 1, now);
236        let h2 = activate(&mut a, b"did:q42:a", b"did:q42:b", 2, now);
237        assert_eq!(a.live_session_count(), 2);
238        a.close_session(h1).unwrap();
239        assert_eq!(a.live_session_count(), 1);
240        assert_eq!(a.sessions.get_mut(h1).err(), Some(QdnfError::Closed));
241        assert!(a.sessions.get_mut(h2).is_ok());
242        assert_eq!(a.primary_session(), Some(h2));
243    }
244
245    #[test]
246    fn fifth_session_is_capacity() {
247        let scope = ScopeEpoch { scope: 1, epoch: 1 };
248        let (mut a, _b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
249        let now = 1_700_000_000u64;
250        for tag in 1u8..=4 {
251            let _ = activate(&mut a, b"did:q42:a", b"did:q42:b", tag, now);
252        }
253        assert_eq!(a.live_session_count(), 4);
254        let mut owner = AuthorityOwner::new();
255        let binding =
256            binding_for_controllers(b"did:q42:a", b"did:q42:b", b"q42:QSync/1", b"op-5").unwrap();
257        let (_c, _k, handle) = owner
258            .install_grant(binding, now, now.saturating_add(3600), ContactState::Active)
259            .unwrap();
260        let permit = owner.issue_permit(handle, binding, now, 4096).unwrap();
261        let keys = InstalledSessionKeys::new(Generation(1), [9u8; 32], [10u8; 32], true).unwrap();
262        assert_eq!(
263            a.activate_protected(permit, keys, now).unwrap_err(),
264            QdnfError::Capacity
265        );
266        assert_eq!(a.live_session_count(), 4);
267    }
268
269    #[test]
270    fn close_then_open_reconciles_reservation() {
271        let scope = ScopeEpoch { scope: 1, epoch: 1 };
272        let (mut a, _b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
273        let now = 1_700_000_000u64;
274        let before = a.remaining_host_bytes();
275        let h = activate(&mut a, b"did:q42:a", b"did:q42:b", 1, now);
276        let used = a.remaining_host_bytes();
277        assert!(used < before);
278        a.close_session(h).unwrap();
279        let after_close = a.remaining_host_bytes();
280        assert!(after_close > used);
281        assert_eq!(after_close, before);
282        let _ = activate(&mut a, b"did:q42:a", b"did:q42:b", 2, now);
283        assert_eq!(a.remaining_host_bytes(), used);
284    }
285
286    #[test]
287    fn poll_recv_before_deadline_is_would_block() {
288        let scope = ScopeEpoch { scope: 1, epoch: 1 };
289        let (mut a, mut b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
290        let now = 1_700_000_000u64;
291        a.announce(&b.locator(), now).unwrap();
292        let _ = b.accept_announce().unwrap();
293        b.announce(&a.locator(), now).unwrap();
294        let _ = a.accept_announce().unwrap();
295        let _ = activate(&mut a, b"did:q42:a", b"did:q42:b", 1, now);
296        let mut out = [0u8; 64];
297        assert_eq!(
298            a.poll_recv(now, now.saturating_add(60), &mut out),
299            Err(QdnfError::WouldBlock)
300        );
301        assert_eq!(
302            a.poll_recv(now.saturating_add(60), now.saturating_add(60), &mut out),
303            Err(QdnfError::Expired)
304        );
305    }
306
307    #[test]
308    fn r01_r02_unconfirmed_or_zero_keys_cannot_activate_protected_session() {
309        let scope = ScopeEpoch { scope: 1, epoch: 1 };
310        let (a, _b) = NativePeer::pair_ipc(b"did:q42:a", b"did:q42:b", scope, 1280).unwrap();
311        let now = 1_700_000_000u64;
312        let mut owner = AuthorityOwner::new();
313        let binding =
314            binding_for_controllers(b"did:q42:a", b"did:q42:b", b"q42:QSync/1", b"op-r01").unwrap();
315        let (_cred, _contact, handle) = owner
316            .install_grant(binding, now, now.saturating_add(3600), ContactState::Active)
317            .unwrap();
318        let permit = owner.issue_permit(handle, binding, now, 4096).unwrap();
319        // Zero or unconfirmed keys must fail before any session slot becomes Active.
320        assert!(InstalledSessionKeys::new(Generation(1), [0u8; 32], [2u8; 32], true).is_err());
321        assert!(InstalledSessionKeys::new(Generation(1), [1u8; 32], [2u8; 32], false).is_err());
322        let _ = (a.live_session_count(), permit);
323    }
324}