Skip to main content

qualia_core_db/net/qdnf/session/
contact.rs

1//! Protected contact states and reserved help (NET-05.17 / NET-05.20).
2//!
3//! Request → Consent → Active. Request cannot skip Consent. Blocked and
4//! Suspended deny even when a current grant would Allow and the peer paid.
5//! Mandate revoke uses the current generation, then Blocked. Two help slots
6//! stay independent of the 16 contact slots. Packages remain open.
7
8use crate::net::qdnf::authority::{admit_service, ContactState, PolicyOutcome, TemporalGrant};
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::session::policy::gate_channel;
11use crate::net::qdnf::types::StrongDigest;
12
13/// Occupied contact slots. A 17th distinct peer is [`QdnfError::Capacity`].
14pub const CONTACT_SLOTS: usize = 16;
15/// Revocation / help capacity. Bulk contact fill must not consume these.
16pub const REVOKED_HELP_SLOTS: usize = 2;
17
18/// One protected-person contact. `paid` is observational only.
19#[repr(C)]
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct ContactSlot {
22    pub peer: StrongDigest,
23    pub state: ContactState,
24    /// Zero means no mandate is recorded.
25    pub mandate_generation: u64,
26    pub purpose: StrongDigest,
27    pub paid: bool,
28    pub revoked: bool,
29}
30
31/// Sixteen contact slots plus two reserved help/revocation slots.
32pub struct ContactTable {
33    contacts: [Option<ContactSlot>; CONTACT_SLOTS],
34    help: [Option<StrongDigest>; REVOKED_HELP_SLOTS],
35}
36
37impl ContactTable {
38    /// Creates a default `ContactTable`.
39    pub const fn new() -> Self {
40        Self {
41            contacts: [None; CONTACT_SLOTS],
42            help: [None; REVOKED_HELP_SLOTS],
43        }
44    }
45
46    /// `true` when the contact slot is occupied.
47    pub fn contact_occupied(&self) -> usize {
48        let mut n = 0usize;
49        let mut i = 0usize;
50        while i < CONTACT_SLOTS {
51            if self.contacts[i].is_some() {
52                n += 1;
53            }
54            i += 1;
55        }
56        n
57    }
58
59    /// `true` when the help slot is occupied.
60    pub fn help_occupied(&self) -> usize {
61        let mut n = 0usize;
62        let mut i = 0usize;
63        while i < REVOKED_HELP_SLOTS {
64            if self.help[i].is_some() {
65                n += 1;
66            }
67            i += 1;
68        }
69        n
70    }
71
72    fn index_of(&self, peer: StrongDigest) -> Result<usize, QdnfError> {
73        let mut i = 0usize;
74        while i < CONTACT_SLOTS {
75            if let Some(slot) = self.contacts[i] {
76                if slot.peer == peer {
77                    return Ok(i);
78                }
79            }
80            i += 1;
81        }
82        Err(QdnfError::Unauthorized)
83    }
84
85    /// Fetches an entry by key; `None` when absent.
86    pub fn get(&self, peer: StrongDigest) -> Result<ContactSlot, QdnfError> {
87        let i = self.index_of(peer)?;
88        self.contacts[i].ok_or(QdnfError::Unauthorized)
89    }
90
91    /// Occupy a Request slot. Distinct 17th peer → Capacity.
92    pub fn insert_request(
93        &mut self,
94        peer: StrongDigest,
95        purpose: StrongDigest,
96        paid: bool,
97        mandate_generation: u64,
98    ) -> Result<(), QdnfError> {
99        if peer == StrongDigest::ZERO {
100            return Err(QdnfError::Malformed);
101        }
102        let mut free = None;
103        let mut i = 0usize;
104        while i < CONTACT_SLOTS {
105            match self.contacts[i] {
106                Some(slot) if slot.peer == peer => return Err(QdnfError::Conflict),
107                Some(_) => {}
108                None => {
109                    if free.is_none() {
110                        free = Some(i);
111                    }
112                }
113            }
114            i += 1;
115        }
116        let idx = free.ok_or(QdnfError::Capacity)?;
117        self.contacts[idx] = Some(ContactSlot {
118            peer,
119            state: ContactState::Request,
120            mandate_generation,
121            purpose,
122            paid,
123            revoked: false,
124        });
125        Ok(())
126    }
127
128    /// Request → Consent. Already Consent/Active is idempotent.
129    pub fn consent(&mut self, peer: StrongDigest) -> Result<(), QdnfError> {
130        let i = self.index_of(peer)?;
131        let slot = self.contacts[i].as_mut().ok_or(QdnfError::Unauthorized)?;
132        match slot.state {
133            ContactState::Request | ContactState::Consent => {
134                slot.state = ContactState::Consent;
135                Ok(())
136            }
137            ContactState::Active => Ok(()),
138            ContactState::Suspended | ContactState::Blocked => Err(QdnfError::Denied),
139        }
140    }
141
142    /// Consent → Active. Request cannot skip Consent.
143    pub fn activate(&mut self, peer: StrongDigest) -> Result<(), QdnfError> {
144        let i = self.index_of(peer)?;
145        let slot = self.contacts[i].as_mut().ok_or(QdnfError::Unauthorized)?;
146        match slot.state {
147            ContactState::Request => Err(QdnfError::Unauthorized),
148            ContactState::Consent | ContactState::Active => {
149                slot.state = ContactState::Active;
150                Ok(())
151            }
152            ContactState::Suspended | ContactState::Blocked => Err(QdnfError::Denied),
153        }
154    }
155
156    /// Active → Suspended.
157    pub fn suspend(&mut self, peer: StrongDigest) -> Result<(), QdnfError> {
158        let i = self.index_of(peer)?;
159        let slot = self.contacts[i].as_mut().ok_or(QdnfError::Unauthorized)?;
160        match slot.state {
161            ContactState::Active | ContactState::Suspended => {
162                slot.state = ContactState::Suspended;
163                Ok(())
164            }
165            ContactState::Blocked => Err(QdnfError::Denied),
166            ContactState::Request | ContactState::Consent => Err(QdnfError::Unauthorized),
167        }
168    }
169
170    /// Any live slot → Blocked. Payment on the slot is left observational.
171    pub fn block(&mut self, peer: StrongDigest) -> Result<(), QdnfError> {
172        let i = self.index_of(peer)?;
173        let slot = self.contacts[i].as_mut().ok_or(QdnfError::Unauthorized)?;
174        slot.state = ContactState::Blocked;
175        Ok(())
176    }
177}
178
179impl Default for ContactTable {
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185/// Payment never unblocks, unsuspends, or un-revokes.
186#[inline]
187pub fn payment_bypasses_block() -> bool {
188    false
189}
190
191/// Group membership is not private-message consent (NET-05.19 claim only).
192#[inline]
193pub fn group_membership_is_private_consent() -> bool {
194    false
195}
196
197/// Admit service for a contact using the current operation-specific grant.
198///
199/// `paid` is ignored for Blocked, Suspended, and Revoked. Purpose on the
200/// grant must match `purpose` and the stored slot purpose.
201pub fn admit_contact(
202    table: &ContactTable,
203    peer: StrongDigest,
204    purpose: StrongDigest,
205    paid: bool,
206    now: u64,
207    grant: &TemporalGrant,
208) -> Result<(), QdnfError> {
209    let _ = paid;
210    debug_assert!(!payment_bypasses_block());
211    let slot = table.get(peer)?;
212    if slot.revoked {
213        return Err(QdnfError::Revoked);
214    }
215    if matches!(slot.state, ContactState::Blocked | ContactState::Suspended) {
216        return gate_channel(PolicyOutcome::Allow, true, slot.state);
217    }
218    if grant.purpose_digest != purpose || slot.purpose != purpose {
219        return Err(QdnfError::Unauthorized);
220    }
221    if slot.state != ContactState::Active {
222        return Err(QdnfError::Unauthorized);
223    }
224    let current = match grant.current_at(now) {
225        Ok(()) => true,
226        Err(QdnfError::Expired) => false,
227        Err(e) => return Err(e),
228    };
229    gate_channel(PolicyOutcome::Allow, current, slot.state)?;
230    admit_service(PolicyOutcome::Allow, current)
231}
232
233/// Intermediary path: any Blocked or Suspended hop is Denied.
234/// A later hop cannot authorize the path by paying.
235pub fn admit_path(states: &[ContactState]) -> Result<(), QdnfError> {
236    if states.is_empty() {
237        return Err(QdnfError::Unauthorized);
238    }
239    let mut i = 0usize;
240    while i < states.len() {
241        match states[i] {
242            ContactState::Blocked | ContactState::Suspended => return Err(QdnfError::Denied),
243            ContactState::Request | ContactState::Consent | ContactState::Active => {}
244        }
245        i += 1;
246    }
247    Ok(())
248}
249
250/// Guardian / organizational mandate revoke. Stale generation is unchanged.
251/// Current generation sets Blocked (guardian revoke) and marks revoked.
252pub fn revoke_mandate(
253    table: &mut ContactTable,
254    peer: StrongDigest,
255    generation: u64,
256) -> Result<(), QdnfError> {
257    let i = table.index_of(peer)?;
258    let slot = table.contacts[i].as_mut().ok_or(QdnfError::Unauthorized)?;
259    if slot.mandate_generation == 0 || slot.mandate_generation != generation {
260        return Err(QdnfError::StaleGeneration);
261    }
262    slot.state = ContactState::Blocked;
263    slot.revoked = true;
264    Ok(())
265}
266
267/// Reserved help/revocation admit. Independent of the 16 contact slots.
268/// Does not grant private-message consent.
269pub fn admit_help(table: &mut ContactTable, peer: StrongDigest) -> Result<(), QdnfError> {
270    if peer == StrongDigest::ZERO {
271        return Err(QdnfError::Malformed);
272    }
273    debug_assert!(!group_membership_is_private_consent());
274    let mut free = None;
275    let mut i = 0usize;
276    while i < REVOKED_HELP_SLOTS {
277        match table.help[i] {
278            Some(existing) if existing == peer => return Ok(()),
279            Some(_) => {}
280            None => {
281                if free.is_none() {
282                    free = Some(i);
283                }
284            }
285        }
286        i += 1;
287    }
288    let idx = free.ok_or(QdnfError::Capacity)?;
289    table.help[idx] = Some(peer);
290    Ok(())
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate::net::qdnf::types::ProfileId;
297
298    fn digest(tag: u8) -> StrongDigest {
299        let mut d = StrongDigest::ZERO;
300        d.0[0] = tag;
301        d
302    }
303
304    fn grant(purpose: StrongDigest, expires_unix: u64) -> TemporalGrant {
305        TemporalGrant {
306            purpose_digest: purpose,
307            audience_digest: StrongDigest::ZERO,
308            authority_generation: 1,
309            not_before_unix: 0,
310            expires_unix,
311            profile: ProfileId::QDNF_CRYPTO_1,
312        }
313    }
314
315    fn active_peer(table: &mut ContactTable, tag: u8, mandate: u64, paid: bool) -> StrongDigest {
316        let peer = digest(tag);
317        let purpose = digest(200);
318        table
319            .insert_request(peer, purpose, paid, mandate)
320            .expect("request");
321        table.consent(peer).expect("consent");
322        table.activate(peer).expect("active");
323        peer
324    }
325
326    #[test]
327    fn request_cannot_activate_without_consent() {
328        let mut table = ContactTable::new();
329        let peer = digest(1);
330        let purpose = digest(200);
331        table
332            .insert_request(peer, purpose, false, 0)
333            .expect("request");
334        assert_eq!(table.activate(peer), Err(QdnfError::Unauthorized));
335        assert_eq!(table.get(peer).unwrap().state, ContactState::Request);
336        table.consent(peer).expect("consent");
337        table.activate(peer).expect("after consent");
338        assert_eq!(table.get(peer).unwrap().state, ContactState::Active);
339    }
340
341    #[test]
342    fn blocked_paid_allow_is_denied() {
343        let mut table = ContactTable::new();
344        let peer = active_peer(&mut table, 2, 0, true);
345        table.block(peer).expect("block");
346        let purpose = digest(200);
347        let g = grant(purpose, 1_000);
348        assert_eq!(
349            admit_contact(&table, peer, purpose, true, 10, &g),
350            Err(QdnfError::Denied)
351        );
352        assert!(!payment_bypasses_block());
353    }
354
355    #[test]
356    fn suspended_paid_is_denied() {
357        let mut table = ContactTable::new();
358        let peer = active_peer(&mut table, 3, 0, true);
359        table.suspend(peer).expect("suspend");
360        let purpose = digest(200);
361        let g = grant(purpose, 1_000);
362        assert_eq!(
363            admit_contact(&table, peer, purpose, true, 10, &g),
364            Err(QdnfError::Denied)
365        );
366    }
367
368    #[test]
369    fn active_current_grant_allow_admits() {
370        let mut table = ContactTable::new();
371        let peer = active_peer(&mut table, 4, 0, false);
372        let purpose = digest(200);
373        let g = grant(purpose, 1_000);
374        assert!(admit_contact(&table, peer, purpose, false, 10, &g).is_ok());
375    }
376
377    #[test]
378    fn expired_grant_is_expired_when_active() {
379        let mut table = ContactTable::new();
380        let peer = active_peer(&mut table, 5, 0, false);
381        let purpose = digest(200);
382        let g = grant(purpose, 50);
383        assert_eq!(
384            admit_contact(&table, peer, purpose, false, 50, &g),
385            Err(QdnfError::Expired)
386        );
387        assert_eq!(
388            admit_contact(&table, peer, purpose, true, 80, &g),
389            Err(QdnfError::Expired)
390        );
391    }
392
393    #[test]
394    fn path_with_blocked_intermediary_is_denied() {
395        let blocked = [
396            ContactState::Active,
397            ContactState::Blocked,
398            ContactState::Active,
399        ];
400        assert_eq!(admit_path(&blocked), Err(QdnfError::Denied));
401        let suspended = [ContactState::Active, ContactState::Suspended];
402        assert_eq!(admit_path(&suspended), Err(QdnfError::Denied));
403        let ok = [ContactState::Active, ContactState::Active];
404        assert!(admit_path(&ok).is_ok());
405    }
406
407    #[test]
408    fn mandate_revoke_then_admit_is_revoked() {
409        let mut table = ContactTable::new();
410        let peer = active_peer(&mut table, 6, 7, false);
411        revoke_mandate(&mut table, peer, 7).expect("revoke");
412        assert_eq!(table.get(peer).unwrap().state, ContactState::Blocked);
413        let purpose = digest(200);
414        let g = grant(purpose, 1_000);
415        assert_eq!(
416            admit_contact(&table, peer, purpose, true, 10, &g),
417            Err(QdnfError::Revoked)
418        );
419    }
420
421    #[test]
422    fn stale_mandate_generation_is_stale() {
423        let mut table = ContactTable::new();
424        let peer = active_peer(&mut table, 7, 9, false);
425        assert_eq!(
426            revoke_mandate(&mut table, peer, 8),
427            Err(QdnfError::StaleGeneration)
428        );
429        assert_eq!(table.get(peer).unwrap().state, ContactState::Active);
430        let purpose = digest(200);
431        let g = grant(purpose, 1_000);
432        assert!(admit_contact(&table, peer, purpose, false, 10, &g).is_ok());
433    }
434
435    #[test]
436    fn seventeenth_contact_is_capacity_help_still_admits() {
437        let mut table = ContactTable::new();
438        let purpose = digest(200);
439        let mut tag = 1u8;
440        while tag <= CONTACT_SLOTS as u8 {
441            table
442                .insert_request(digest(tag), purpose, false, 0)
443                .expect("fill");
444            tag += 1;
445        }
446        assert_eq!(table.contact_occupied(), CONTACT_SLOTS);
447        assert_eq!(table.help_occupied(), 0);
448        assert_eq!(
449            table.insert_request(digest(17), purpose, false, 0),
450            Err(QdnfError::Capacity)
451        );
452        assert_eq!(table.contact_occupied(), CONTACT_SLOTS);
453        assert!(admit_help(&mut table, digest(100)).is_ok());
454        assert_eq!(table.help_occupied(), 1);
455        assert_eq!(table.contact_occupied(), CONTACT_SLOTS);
456    }
457
458    #[test]
459    fn payment_does_not_bypass_block() {
460        assert!(!payment_bypasses_block());
461        assert!(!group_membership_is_private_consent());
462    }
463}