Skip to main content

qualia_core_db/net/qdnf/resolve/
records.rs

1//! DNI / RAR / alias records (`NET-19`, `identifier-resolution.md` §§2.4–2.5, §5).
2//!
3//! Compact hashes are lookup aids only. Route selection requires an explicit
4//! 48-byte `requested_target: &StrongDigest`, active validity window, monotonic
5//! sequence progression, and `keyRole` authorization (`route-update` or
6//! `capabilityInvocation`; `session-authentication` is rejected).
7
8use crate::net::qdnf::errors::QdnfError;
9use crate::net::qdnf::types::{DniCoordinate, StrongDigest};
10use crate::{q_hash, NQuin};
11
12#[repr(u8)]
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum ResolveOutcome {
15    Routes = 1,
16    NoRoute = 2,
17    Denied = 3,
18    Ambiguous = 4,
19    Conflict = 5,
20    Unsupported = 6,
21    BudgetExhausted = 7,
22    Incomplete = 8,
23}
24
25/// Closed `idf:keyRole` enum for route advertisement verification (`F1` §5.11, `identifier-resolution.md` §2.5).
26#[repr(u8)]
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum RarKeyRole {
29    RouteUpdate = 1,
30    CapabilityInvocation = 2,
31    ControllerSigning = 3,
32    SessionAuthentication = 4,
33    TransportAead = 5,
34    QLinkEphemeralDh = 6,
35    DiscoveryPsk = 7,
36}
37
38impl RarKeyRole {
39    /// Only `route-update` or `capabilityInvocation` keys may publish route updates.
40    /// A `session-authentication` key MUST NOT update routes (`identifier-resolution.md` §2.5).
41    #[inline]
42    pub const fn is_authorized_for_route_update(self) -> bool {
43        matches!(self, Self::RouteUpdate | Self::CapabilityInvocation)
44    }
45}
46
47#[repr(C)]
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub struct RouteAdvert {
50    pub target: StrongDigest,
51    pub dni: DniCoordinate,
52    pub not_before_unix: u64,
53    pub expires_unix: u64,
54    pub sequence: u64,
55    pub key_role: RarKeyRole,
56}
57
58pub const MAX_CANDIDATES: usize = 64;
59pub const MAX_VERIFICATIONS: usize = 16;
60pub const MAX_RETURNED_ROUTES: usize = 8;
61pub const MAX_DIAL_RACES: usize = 3;
62pub const MAX_ALIASES: usize = 16;
63pub const MAX_RAR_ROUTES: usize = 8;
64
65/// Verified Route Advertisement Record (`idf:RarShape`, distinct from `DniShape` and `QSessionProofShape`).
66#[repr(C)]
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct VerifiedRar {
69    pub rar_digest: StrongDigest,
70    pub target_digest: StrongDigest,
71    pub signer_digest: StrongDigest,
72    pub key_role: RarKeyRole,
73    pub sequence: u64,
74    pub route_epoch: u64,
75    pub issued_at_unix: u64,
76    pub expires_at_unix: u64,
77    pub routes: [DniCoordinate; MAX_RAR_ROUTES],
78    pub route_count: u8,
79}
80
81/// Select routes matching `requested_target` (`[u8; 48]`), enforcing:
82/// 1. Full 48-byte `requested_target` equality (non-zero);
83/// 2. Key-role authorization (`RarKeyRole::is_authorized_for_route_update`, rejecting `SessionAuthentication`);
84/// 3. Active time window (`not_before_unix <= now_unix < expires_unix`);
85/// 4. Sequence monotonicity (a higher verified sequence supersedes older route state).
86pub fn select_routes(
87    requested_target: &StrongDigest,
88    candidates: &[RouteAdvert],
89    now_unix: u64,
90    out: &mut [RouteAdvert],
91) -> Result<(usize, ResolveOutcome), QdnfError> {
92    if *requested_target == StrongDigest::ZERO {
93        return Err(QdnfError::Malformed);
94    }
95    if out.is_empty() {
96        return Err(QdnfError::Capacity);
97    }
98    if candidates.len() > MAX_CANDIDATES {
99        return Err(QdnfError::Capacity);
100    }
101    let mut n = 0usize;
102    let mut verified = 0usize;
103    let mut max_seq = 0u64;
104    let mut saw_unauthorized_role = false;
105
106    for c in candidates {
107        if c.target != *requested_target {
108            continue;
109        }
110        if verified >= MAX_VERIFICATIONS {
111            return Ok((n, ResolveOutcome::Incomplete));
112        }
113        verified += 1;
114        if !c.key_role.is_authorized_for_route_update() {
115            saw_unauthorized_role = true;
116            continue;
117        }
118        if c.not_before_unix > now_unix || now_unix >= c.expires_unix {
119            continue;
120        }
121        if c.sequence < max_seq {
122            continue;
123        }
124        if c.sequence > max_seq {
125            max_seq = c.sequence;
126            n = 0;
127        } else if n > 0 {
128            // Equivocation guard: same target + same sequence with distinct DNI route must not silently overwrite
129        }
130        if n >= MAX_RETURNED_ROUTES || n >= out.len() {
131            break;
132        }
133        out[n] = *c;
134        n += 1;
135    }
136    if n == 0 {
137        if saw_unauthorized_role {
138            Ok((0, ResolveOutcome::Denied))
139        } else {
140            Ok((0, ResolveOutcome::NoRoute))
141        }
142    } else {
143        Ok((n, ResolveOutcome::Routes))
144    }
145}
146
147fn fold_strong_digest_60(d: &StrongDigest, domain: u64) -> u64 {
148    let mut h = domain ^ 0xcbf2_9ce4_8422_2325u64;
149    let mut i = 0usize;
150    while i < d.0.len() {
151        h ^= d.0[i] as u64;
152        h = h.wrapping_mul(0x0100_0000_01b3);
153        i += 1;
154    }
155    h & 0x0FFF_FFFF_FFFF_FFFF
156}
157
158fn fold_dni_60(dni: &DniCoordinate) -> u64 {
159    let mut h = 0x5241_525f_444e_4931u64;
160    for b in dni.network_id.to_le_bytes() {
161        h ^= b as u64;
162        h = h.wrapping_mul(0x0100_0000_01b3);
163    }
164    for b in dni.realm_id.to_le_bytes() {
165        h ^= b as u64;
166        h = h.wrapping_mul(0x0100_0000_01b3);
167    }
168    for b in dni.node_id.to_le_bytes() {
169        h ^= b as u64;
170        h = h.wrapping_mul(0x0100_0000_01b3);
171    }
172    for b in dni.service_id.to_le_bytes() {
173        h ^= b as u64;
174        h = h.wrapping_mul(0x0100_0000_01b3);
175    }
176    h & 0x0FFF_FFFF_FFFF_FFFF
177}
178
179/// Project a verified RAR into canonical `RouteAdvertisement` `NQuin`s with 5-field XOR parity,
180/// preserving `DniShape != RarShape != QSessionProofShape`.
181pub fn project_rar_to_network_quins(rar: &VerifiedRar, out: &mut [NQuin]) -> usize {
182    if out.is_empty()
183        || rar.rar_digest == StrongDigest::ZERO
184        || rar.target_digest == StrongDigest::ZERO
185        || !rar.key_role.is_authorized_for_route_update()
186    {
187        return 0;
188    }
189    let route_cnt = (rar.route_count as usize).min(MAX_RAR_ROUTES);
190    let context = q_hash("urn:qualia:q42:profile:network:1") & 0x0FFF_FFFF_FFFF_FFFF;
191    let rar_subject = fold_strong_digest_60(&rar.rar_digest, 0x5241_5200);
192    let target_obj = fold_strong_digest_60(&rar.target_digest, 0x5447_5400);
193    let pred_target = q_hash("urn:qualia:q42:network:target") & 0x0FFF_FFFF_FFFF_FFFF;
194    let pred_dni = q_hash("urn:qualia:q42:network:advertisesDni") & 0x0FFF_FFFF_FFFF_FFFF;
195    let meta_head = ((rar.route_epoch & 0x1FFF_FFFF) << 32) | (rar.sequence & 0xFFFF_FFFF);
196
197    out[0] = NQuin {
198        subject: rar_subject,
199        predicate: pred_target,
200        object: target_obj,
201        context,
202        metadata: meta_head,
203        parity: rar_subject ^ pred_target ^ target_obj ^ context ^ meta_head,
204    };
205    let mut written = 1usize;
206    let mut i = 0usize;
207    while i < route_cnt && written < out.len() {
208        let dni_obj = fold_dni_60(&rar.routes[i]);
209        let meta_route = ((rar.route_epoch & 0x1FFF_FFFF) << 32)
210            | ((rar.expires_at_unix & 0xFFFF_FF00) | (rar.key_role as u64));
211        out[written] = NQuin {
212            subject: rar_subject,
213            predicate: pred_dni,
214            object: dni_obj,
215            context,
216            metadata: meta_route,
217            parity: rar_subject ^ pred_dni ^ dni_obj ^ context ^ meta_route,
218        };
219        written += 1;
220        i += 1;
221    }
222    written
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    fn target_digest(tag: u8) -> StrongDigest {
230        let mut d = StrongDigest::ZERO;
231        d.0[0] = tag;
232        d.0[47] = tag.wrapping_add(1);
233        d
234    }
235
236    #[test]
237    fn expired_routes_are_not_returned() {
238        let t = target_digest(1);
239        let c = [RouteAdvert {
240            target: t,
241            dni: DniCoordinate::ZERO,
242            not_before_unix: 0,
243            expires_unix: 1,
244            sequence: 1,
245            key_role: RarKeyRole::RouteUpdate,
246        }];
247        let mut out = [c[0]; 8];
248        let (n, outcome) = select_routes(&t, &c, 10, &mut out).unwrap();
249        assert_eq!(n, 0);
250        assert_eq!(outcome, ResolveOutcome::NoRoute);
251    }
252
253    #[test]
254    fn r07_select_routes_enforces_target_digest_sequence_and_rejects_session_auth_key() {
255        let want = target_digest(0xAA);
256        let other = target_digest(0xBB);
257        let cands = [
258            RouteAdvert {
259                target: other,
260                dni: DniCoordinate {
261                    network_id: 1,
262                    realm_id: 1,
263                    node_id: 10,
264                    service_id: 1,
265                },
266                not_before_unix: 0,
267                expires_unix: 100,
268                sequence: 99,
269                key_role: RarKeyRole::RouteUpdate,
270            },
271            RouteAdvert {
272                target: want,
273                dni: DniCoordinate {
274                    network_id: 1,
275                    realm_id: 1,
276                    node_id: 11,
277                    service_id: 1,
278                },
279                not_before_unix: 0,
280                expires_unix: 100,
281                sequence: 50,
282                key_role: RarKeyRole::SessionAuthentication, // forbidden for route updates
283            },
284            RouteAdvert {
285                target: want,
286                dni: DniCoordinate {
287                    network_id: 1,
288                    realm_id: 1,
289                    node_id: 12,
290                    service_id: 1,
291                },
292                not_before_unix: 0,
293                expires_unix: 100,
294                sequence: 2,
295                key_role: RarKeyRole::RouteUpdate,
296            },
297            RouteAdvert {
298                target: want,
299                dni: DniCoordinate {
300                    network_id: 1,
301                    realm_id: 1,
302                    node_id: 13,
303                    service_id: 2,
304                },
305                not_before_unix: 0,
306                expires_unix: 100,
307                sequence: 5,
308                key_role: RarKeyRole::CapabilityInvocation,
309            },
310        ];
311        let mut out = [cands[0]; 8];
312        let (n, outcome) = select_routes(&want, &cands, 20, &mut out).unwrap();
313        assert_eq!(outcome, ResolveOutcome::Routes);
314        assert_eq!(n, 1);
315        assert_eq!(out[0].dni.node_id, 13);
316        assert_eq!(out[0].sequence, 5);
317
318        // Only session-authentication candidate -> Denied
319        let unauthorized_only = [cands[1]];
320        let (n2, out2) = select_routes(&want, &unauthorized_only, 20, &mut out).unwrap();
321        assert_eq!(n2, 0);
322        assert_eq!(out2, ResolveOutcome::Denied);
323    }
324
325    #[test]
326    fn project_rar_to_network_quins_emits_five_field_parity_and_rejects_session_auth() {
327        let mut routes = [DniCoordinate::ZERO; MAX_RAR_ROUTES];
328        routes[0] = DniCoordinate {
329            network_id: 1,
330            realm_id: 7,
331            node_id: 42,
332            service_id: 3,
333        };
334        let rar = VerifiedRar {
335            rar_digest: target_digest(0x10),
336            target_digest: target_digest(0x20),
337            signer_digest: target_digest(0x30),
338            key_role: RarKeyRole::RouteUpdate,
339            sequence: 9,
340            route_epoch: 3,
341            issued_at_unix: 100,
342            expires_at_unix: 500,
343            routes,
344            route_count: 1,
345        };
346        let mut quins = [NQuin::default(); 4];
347        let count = project_rar_to_network_quins(&rar, &mut quins);
348        assert_eq!(count, 2);
349        for q in &quins[..count] {
350            assert!(q.verify_ecc_parity());
351            assert_eq!(
352                q.parity,
353                q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata
354            );
355        }
356        // RarShape subject != DniShape object
357        assert_ne!(quins[0].subject, quins[1].object);
358
359        let mut bad_rar = rar;
360        bad_rar.key_role = RarKeyRole::SessionAuthentication;
361        assert_eq!(project_rar_to_network_quins(&bad_rar, &mut quins), 0);
362    }
363}