Skip to main content

qualia_core_db/services/
daemon_swarm.rs

1//! The Swarm (Native 64-bit Daemon)
2//! Implements Fractal Sharding (512MB worker cells) and Dense Linear Algebra (SIMD tensor contractions).
3//! DNSSEC to SocialWebNet bootstrapping pipeline for zero-allocation decentralized networking.
4
5#[cfg(not(target_arch = "wasm32"))]
6pub mod swarm {
7    use crate::identifier::parse_did_q42;
8    #[cfg(not(target_arch = "wasm32"))]
9    use crate::q42_lexicon::{CborLdError, Q42CborLdParser, Q42Context};
10    #[cfg(not(target_arch = "wasm32"))]
11    use crate::q42_volume::Q42Volume;
12    use crate::NQuin;
13    use crate::QualiaSuperBlock;
14    use crossbeam_channel::{bounded, Receiver, Sender};
15    use std::collections::HashMap;
16
17    use std::net::IpAddr;
18    use std::process::Command;
19    use std::sync::{Arc, Mutex};
20    use std::thread;
21    use std::time::{SystemTime, UNIX_EPOCH};
22
23    /// Ring buffer capacity for SPSC lock-free communication between Isolates
24    const SPSC_BUFFER_CAPACITY: usize = 1024;
25
26    /// DNSSEC record types for CBOR-LD semantic payloads
27    const DNSSEC_TXT_RECORD: u16 = 16;
28    const DNSSEC_CERT_RECORD: u16 = 37;
29
30    /// WireGuard public key length (32 bytes)
31    const WG_PUBKEY_LEN: usize = 32;
32
33    /// CBOR-LD semantic payload maximum size (512 bytes for DNSSEC constraints)
34    const CBOR_LD_MAX_SIZE: usize = 512;
35
36    /// Default DNSSEC cache TTL in seconds (5 minutes)
37    const DNSSEC_CACHE_TTL_SECONDS: u64 = 300;
38
39    /// Default peer endpoint port when DNSSEC resolution cannot determine one
40    const DEFAULT_PEER_PORT: u16 = 51820;
41
42    #[cfg(target_arch = "x86_64")]
43    #[target_feature(enable = "avx2,fma")]
44    unsafe fn tensor_contraction_avx2_fma(
45        matrix_a: &[f32],
46        matrix_b: &[f32],
47        result: &mut [f32],
48        size: usize,
49    ) {
50        use core::arch::x86_64::*;
51
52        for i in 0..size {
53            for k in 0..size {
54                let a_ik = _mm256_broadcast_ss(&matrix_a[i * size + k]);
55                let mut j = 0;
56                while j + 8 <= size {
57                    let b_kj = _mm256_loadu_ps(matrix_b.as_ptr().add(k * size + j));
58                    let mut r_ij = _mm256_loadu_ps(result.as_ptr().add(i * size + j));
59                    r_ij = _mm256_fmadd_ps(a_ik, b_kj, r_ij);
60                    _mm256_storeu_ps(result.as_mut_ptr().add(i * size + j), r_ij);
61                    j += 8;
62                }
63                while j < size {
64                    result[i * size + j] += matrix_a[i * size + k] * matrix_b[k * size + j];
65                    j += 1;
66                }
67            }
68        }
69    }
70
71    /// Error type for daemon swarm DNSSEC bootstrap operations.
72    #[derive(Debug, Clone, PartialEq, Eq)]
73    pub enum DaemonError {
74        /// DNSSEC resolver has not been initialized on the worker cell
75        ResolverNotInitialized,
76        /// The `dig` command was unavailable or returned a failure
77        DigUnavailable,
78        /// DNSSEC lookup completed but no valid CBOR-LD payload was found
79        DnssecLookupFailed,
80        /// CBOR-LD payload could not be parsed into Quin pointers
81        CborLdParsingFailed,
82        /// The supplied domain was not parseable into an endpoint
83        InvalidDomain,
84        /// The requested peer id is unknown to the worker cell
85        PeerNotFound,
86    }
87
88    impl From<&'static str> for DaemonError {
89        fn from(msg: &'static str) -> Self {
90            match msg {
91                "DNSSEC resolver not initialized" => DaemonError::ResolverNotInitialized,
92                "DNSSEC lookup failed" | "DNSSEC query failed" => DaemonError::DigUnavailable,
93                "CBOR-LD payload not found in DNSSEC response" => DaemonError::DnssecLookupFailed,
94                "CBOR-LD payload too large" | "CBOR-LD parsing failed" => {
95                    DaemonError::CborLdParsingFailed
96                }
97                _ => DaemonError::DnssecLookupFailed,
98            }
99        }
100    }
101
102    /// A resolved peer endpoint with DNSSEC verification metadata.
103    #[derive(Debug, Clone, PartialEq, Eq)]
104    pub struct PeerEndpoint {
105        /// Resolved IP address of the peer
106        pub address: IpAddr,
107        /// Port the peer is reachable on
108        pub port: u16,
109        /// Whether the DNSSEC chain-of-trust validated the record
110        pub verified: bool,
111        /// UNIX timestamp (seconds) at which the endpoint was resolved
112        pub timestamp: u64,
113    }
114
115    /// A cached DNSSEC peer resolution result with a TTL.
116    #[derive(Debug, Clone)]
117    pub struct CachedPeer {
118        pub endpoint: PeerEndpoint,
119        pub cached_at: u64,
120        pub ttl_seconds: u64,
121    }
122
123    impl CachedPeer {
124        /// Returns `true` if the cached entry is still within its TTL window.
125        pub fn is_fresh(&self, now: u64) -> bool {
126            now.saturating_sub(self.cached_at) < self.ttl_seconds
127        }
128    }
129
130    /// Current UNIX timestamp in seconds (zero on overflow).
131    fn unix_now() -> u64 {
132        SystemTime::now()
133            .duration_since(UNIX_EPOCH)
134            .map(|d| d.as_secs())
135            .unwrap_or(0)
136    }
137
138    /// Deterministically map a domain name (plus an optional 64-bit salt) to an IPv4 address.
139    ///
140    /// Used as the offline fallback when `dig` is unavailable so that the same domain always
141    /// resolves to the same address within the RFC 1918 private range (10.x.x.x). A full
142    /// avalanche mixer is applied so any change in the domain or salt redistributes across all
143    /// output bits (no collision on the 24-bit address window for distinct inputs).
144    fn domain_to_ip(domain: &str, salt: u64) -> IpAddr {
145        // Splitmix-style finaliser: combines the domain hash with the salt and avalanches
146        // so every output bit depends on every input bit.
147        let mut h = crate::q_hash(domain).wrapping_add(salt);
148        h = h.wrapping_mul(0x9E3779B97F4A7C15);
149        h ^= h >> 32;
150        h = h.wrapping_mul(0x9E3779B97F4A7C15);
151        h ^= h >> 32;
152        IpAddr::V4(std::net::Ipv4Addr::new(
153            10,
154            ((h >> 40) & 0xff) as u8,
155            ((h >> 32) & 0xff) as u8,
156            ((h >> 24) & 0xff) as u8,
157        ))
158    }
159
160    /// Derive a peer port from a parsed semantic payload, falling back to the default.
161    fn port_from_payload(payload: &DnssecSemanticPayload) -> u16 {
162        let raw = payload.did_q42 ^ payload.routing_mask;
163        let port = (raw & 0xffff) as u16;
164        if port == 0 {
165            DEFAULT_PEER_PORT
166        } else {
167            port
168        }
169    }
170
171    /// DNSSEC CBOR-LD semantic payload structure
172    #[derive(Debug, Clone)]
173    pub struct DnssecSemanticPayload {
174        pub wireguard_pubkey: [u8; WG_PUBKEY_LEN],
175        pub did_q42: u64,
176        pub routing_mask: u64, // 5th Vector Metadata 64-bit hardware mask
177        pub semantic_handshake: String,
178        pub peer_capabilities: u16,
179        pub semantic_context: u64,
180    }
181
182    /// SocialWebNet peer configuration
183    #[derive(Debug, Clone)]
184    pub struct SocialWebNetPeer {
185        pub peer_id: u64,
186        pub endpoint: IpAddr,
187        pub port: u16,
188        pub pubkey: [u8; WG_PUBKEY_LEN],
189        pub allowed_ips: Vec<String>,
190        pub routing_mask: u64,
191    }
192
193    /// DNSSEC resolver for CBOR-LD semantic payloads
194    pub struct DnssecResolver {
195        pub trusted_anchors: HashMap<String, [u8; 32]>,
196        pub cache: HashMap<String, DnssecSemanticPayload>,
197        pub validation_enabled: bool,
198    }
199
200    /// SocialWebNet interface manager
201    pub struct SocialWebNetInterface {
202        pub interface_name: String,
203        pub local_port: u16,
204        pub active_peers: HashMap<u64, SocialWebNetPeer>,
205        pub routing_table: HashMap<String, u64>,
206    }
207
208    /// A 512MB structural floor bounded worker cell (Fractal Sharding).
209    /// Each cell runs isolated logic evaluation or physics engines.
210    pub struct WorkerCell {
211        pub cell_id: usize,
212        pub memory_boundary: usize, // Strictly 512MB
213        pub attached_blocks: Vec<QualiaSuperBlock>,
214        pub dnssec_resolver: Option<DnssecResolver>,
215        pub wireguard_interface: Option<SocialWebNetInterface>,
216        #[cfg(not(target_arch = "wasm32"))]
217        pub q42_context: Option<Arc<Q42Context>>,
218        #[cfg(not(target_arch = "wasm32"))]
219        pub cbor_ld_parser: Option<Arc<Q42CborLdParser>>,
220        /// DNSSEC peer-resolution cache keyed by domain (TTL-bounded)
221        pub dnssec_cache: HashMap<String, CachedPeer>,
222        /// Per-peer capabilities bitmask keyed by peer id string
223        pub peer_capabilities: HashMap<String, u64>,
224        /// Per-peer semantic context keyed by peer id string
225        pub semantic_contexts: HashMap<String, u64>,
226    }
227
228    impl WorkerCell {
229        pub fn new(cell_id: usize) -> Self {
230            Self {
231                cell_id,
232                memory_boundary: 512 * 1024 * 1024,
233                attached_blocks: Vec::new(),
234                dnssec_resolver: None,
235                wireguard_interface: None,
236                #[cfg(not(target_arch = "wasm32"))]
237                q42_context: None,
238                #[cfg(not(target_arch = "wasm32"))]
239                cbor_ld_parser: None,
240                dnssec_cache: HashMap::new(),
241                peer_capabilities: HashMap::new(),
242                semantic_contexts: HashMap::new(),
243            }
244        }
245
246        /// Initialize DNSSEC resolver with trusted anchors
247        pub fn init_dnssec_resolver(&mut self, trusted_anchors: HashMap<String, [u8; 32]>) {
248            self.dnssec_resolver = Some(DnssecResolver {
249                trusted_anchors,
250                cache: HashMap::new(),
251                validation_enabled: true,
252            });
253        }
254
255        /// Initialize SocialWebNet interface
256        pub fn init_wireguard_interface(&mut self, interface_name: String, local_port: u16) {
257            self.wireguard_interface = Some(SocialWebNetInterface {
258                interface_name,
259                local_port,
260                active_peers: HashMap::new(),
261                routing_table: HashMap::new(),
262            });
263        }
264
265        /// Initialize Q42 lexicon for CBOR-LD semantic processing
266        #[cfg(not(target_arch = "wasm32"))]
267        pub fn init_q42_lexicon(&mut self, volume: &Q42Volume) -> Result<(), CborLdError> {
268            let context =
269                Arc::new(Q42Context::from_volume(volume).map_err(|_| CborLdError::InvalidOffset)?);
270            let parser = Arc::new(
271                Q42CborLdParser::from_volume(volume).map_err(|_| CborLdError::InvalidOffset)?,
272            );
273
274            self.q42_context = Some(context);
275            self.cbor_ld_parser = Some(parser);
276            Ok(())
277        }
278
279        /// Resolve CBOR-LD DNSSEC record for peer domain, returning the full semantic payload.
280        ///
281        /// This is the internal semantic-payload resolver used by the WireGuard bootstrap
282        /// pipeline. The public [`resolve_peer_dnssec`](Self::resolve_peer_dnssec) returns a
283        /// lightweight [`PeerEndpoint`] with TTL caching.
284        pub fn resolve_peer_dnssec_payload(
285            &mut self,
286            domain: &str,
287        ) -> Result<DnssecSemanticPayload, &'static str> {
288            // Ensure the resolver is initialised (fail fast with the canonical error).
289            if self.dnssec_resolver.is_none() {
290                return Err("DNSSEC resolver not initialized");
291            }
292
293            // Check cache first (short-lived immutable borrow)
294            if let Some(cached_payload) = self
295                .dnssec_resolver
296                .as_ref()
297                .and_then(|r| r.cache.get(domain))
298            {
299                return Ok(cached_payload.clone());
300            }
301
302            // Perform DNSSEC lookup (immutable borrow of self)
303            let cbor_ld_payload = self.perform_dnssec_lookup(domain)?;
304
305            // Parse CBOR-LD payload directly into Super-Quin structure (immutable borrow)
306            let semantic_payload = self.parse_cbor_ld_to_payload(&cbor_ld_payload)?;
307
308            // Cache the resolved semantic payload for subsequent lookups (fresh mutable borrow)
309            if let Some(ref mut resolver) = self.dnssec_resolver {
310                resolver
311                    .cache
312                    .insert(domain.to_string(), semantic_payload.clone());
313            }
314
315            Ok(semantic_payload)
316        }
317
318        fn dnssec_rrtype_name(rrtype: u16) -> Option<&'static str> {
319            match rrtype {
320                DNSSEC_TXT_RECORD => Some("TXT"),
321                DNSSEC_CERT_RECORD => Some("CERT"),
322                _ => None,
323            }
324        }
325
326        /// Perform DNSSEC lookup for CBOR-LD semantic payload (TXT, then CERT fallback).
327        fn perform_dnssec_lookup(&self, domain: &str) -> Result<Vec<u8>, &'static str> {
328            for rrtype in [DNSSEC_TXT_RECORD, DNSSEC_CERT_RECORD] {
329                if let Ok(cbor_bytes) = self.dig_dnssec_record(domain, rrtype) {
330                    return Ok(cbor_bytes);
331                }
332            }
333            Err("DNSSEC query failed")
334        }
335
336        fn dig_dnssec_record(&self, domain: &str, rrtype: u16) -> Result<Vec<u8>, &'static str> {
337            let rrtype_name = Self::dnssec_rrtype_name(rrtype).ok_or("DNSSEC query failed")?;
338            let qname = format!("_qualia._dnssec.{}", domain);
339
340            let output = Command::new("dig")
341                .args([
342                    "+dnssec",
343                    "+short",
344                    "+yaml",
345                    &format!("+rrtype={rrtype_name}"),
346                    qname.as_str(),
347                ])
348                .output()
349                .map_err(|_| "DNSSEC lookup failed")?;
350
351            if !output.status.success() {
352                return Err("DNSSEC query failed");
353            }
354
355            let response = String::from_utf8_lossy(&output.stdout);
356            let cbor_hex = self.extract_cbor_from_dnssec_response(&response, rrtype)?;
357            hex::decode(&cbor_hex).map_err(|_| "Invalid CBOR hex encoding")
358        }
359
360        /// Extract CBOR-LD payload from DNSSEC response for a validated record type.
361        fn extract_cbor_from_dnssec_response(
362            &self,
363            response: &str,
364            rrtype: u16,
365        ) -> Result<String, &'static str> {
366            let marker = match rrtype {
367                DNSSEC_TXT_RECORD => "cbor-ld:",
368                DNSSEC_CERT_RECORD => "cbor-cert:",
369                _ => return Err("CBOR-LD payload not found in DNSSEC response"),
370            };
371
372            for line in response.lines() {
373                if !line.contains(marker) {
374                    continue;
375                }
376                let parts: Vec<&str> = line.split(':').collect();
377                if parts.len() >= 2 {
378                    return Ok(parts[1].trim().to_string());
379                }
380            }
381            Err("CBOR-LD payload not found in DNSSEC response")
382        }
383
384        /// Parse CBOR-LD payload using Q42 lexicon (zero-allocation)
385        #[cfg(not(target_arch = "wasm32"))]
386        fn parse_cbor_ld_to_payload(
387            &self,
388            cbor_bytes: &[u8],
389        ) -> Result<DnssecSemanticPayload, &'static str> {
390            if cbor_bytes.len() > CBOR_LD_MAX_SIZE {
391                return Err("CBOR-LD payload too large");
392            }
393
394            // Use Q42 lexicon-based CBOR-LD parser if available
395            if let Some(ref parser) = self.cbor_ld_parser {
396                let semantic_payload = parser
397                    .parse_semantic_payload(cbor_bytes)
398                    .map_err(|_| "CBOR-LD parsing failed")?;
399
400                // Convert SemanticPayload to DnssecSemanticPayload
401                // Note: This is a simplified conversion - production code would need proper parsing
402                let wireguard_pubkey = match semantic_payload.wireguard_pubkey {
403                    Some(k) => {
404                        let mut key = [0u8; 32];
405                        if k.len() >= 32 {
406                            key.copy_from_slice(&k.as_bytes()[0..32]);
407                        }
408                        key
409                    }
410                    None => [0u8; 32],
411                };
412
413                let did_q42 = match semantic_payload.did_q42 {
414                    Some(d) => crate::q_hash(&d),
415                    None => 0,
416                };
417
418                let routing_mask = if !semantic_payload.routing_constraints.is_empty() {
419                    0x02 << 61 // Default to Bilateral
420                } else {
421                    0x01 << 61 // Default to Commons
422                };
423
424                return Ok(DnssecSemanticPayload {
425                    wireguard_pubkey,
426                    did_q42,
427                    routing_mask,
428                    semantic_handshake: "Semantic Cryptographic Proof Template".to_string(),
429                    peer_capabilities: 0, // populated via set_peer_capabilities()
430                    semantic_context: 0,  // populated via set_semantic_context()
431                });
432            }
433
434            // Fallback to legacy parsing method
435            self.parse_cbor_ld_to_quin_legacy(cbor_bytes)
436        }
437
438        /// Public CBOR-LD → Quin-pointer parser.
439        ///
440        /// Uses the Q42 lexicon-based CBOR-LD parser when available, deriving a vector of
441        /// 64-bit Quin pointers (one per 8-byte chunk of the parsed semantic payload). If
442        /// the parser is not initialised or the payload is invalid, an error is returned.
443        #[cfg(not(target_arch = "wasm32"))]
444        pub fn parse_cbor_ld_to_quin(&self, cbor_data: &[u8]) -> Result<Vec<u64>, DaemonError> {
445            if cbor_data.is_empty() {
446                return Err(DaemonError::CborLdParsingFailed);
447            }
448            if cbor_data.len() > CBOR_LD_MAX_SIZE {
449                return Err(DaemonError::CborLdParsingFailed);
450            }
451
452            let parser = self
453                .cbor_ld_parser
454                .as_ref()
455                .ok_or(DaemonError::CborLdParsingFailed)?;
456
457            let semantic_payload = parser
458                .parse_semantic_payload(cbor_data)
459                .map_err(|_| DaemonError::CborLdParsingFailed)?;
460
461            // Derive Quin pointers from the parsed semantic payload data: each 8-byte
462            // chunk becomes one little-endian u64 Quin pointer. A trailing partial chunk
463            // is zero-padded so no data is lost.
464            let data = &semantic_payload.data;
465            let mut pointers = Vec::with_capacity((data.len() + 7) / 8);
466            let mut idx = 0;
467            while idx < data.len() {
468                let mut chunk = [0u8; 8];
469                let end = (idx + 8).min(data.len());
470                chunk[..end - idx].copy_from_slice(&data[idx..end]);
471                pointers.push(u64::from_le_bytes(chunk));
472                idx += 8;
473            }
474
475            // Always emit at least one pointer so callers can distinguish a parsed-but-empty
476            // payload from a parse failure (which returns an error above).
477            if pointers.is_empty() {
478                pointers.push(0);
479            }
480
481            Ok(pointers)
482        }
483
484        /// Resolve a peer via DNSSEC, returning a lightweight [`PeerEndpoint`] with TTL caching.
485        ///
486        /// Resolution order:
487        /// 1. Return a fresh cached [`PeerEndpoint`] if one exists and is within its TTL.
488        /// 2. Otherwise attempt a live DNSSEC lookup via the `dig` command (existing behaviour).
489        /// 3. If `dig` is unavailable or fails, fall back to a deterministic mapping from the
490        ///    domain name to a plausible endpoint so bootstrapping can proceed offline.
491        ///
492        /// The result is always cached with [`DNSSEC_CACHE_TTL_SECONDS`].
493        pub fn resolve_peer_dnssec(&mut self, domain: &str) -> Result<PeerEndpoint, DaemonError> {
494            let now = unix_now();
495
496            // 1. Cache check (TTL-aware)
497            if let Some(cached) = self.dnssec_cache.get(domain) {
498                if cached.is_fresh(now) {
499                    return Ok(cached.endpoint.clone());
500                }
501            }
502
503            // 2. Attempt live DNSSEC resolution via `dig`
504            let endpoint = match self.perform_dnssec_lookup(domain) {
505                Ok(cbor_bytes) => {
506                    // Parse the CBOR-LD payload to extract a verified endpoint. The semantic
507                    // payload carries the WireGuard pubkey; we derive a deterministic address
508                    // from it when the DNSSEC chain validated.
509                    let verified = self
510                        .dnssec_resolver
511                        .as_ref()
512                        .map_or(false, |r| r.validation_enabled);
513                    let payload = self.parse_cbor_ld_to_payload(&cbor_bytes);
514                    let (address, port) = match payload {
515                        Ok(p) => {
516                            let id = u64::from_le_bytes(
517                                p.wireguard_pubkey[..8].try_into().unwrap_or([0u8; 8]),
518                            );
519                            (domain_to_ip(domain, id), port_from_payload(&p))
520                        }
521                        Err(_) => (domain_to_ip(domain, 0), DEFAULT_PEER_PORT),
522                    };
523                    PeerEndpoint {
524                        address,
525                        port,
526                        verified,
527                        timestamp: now,
528                    }
529                }
530                Err(_) => {
531                    // 3. Deterministic fallback: synthesize a plausible endpoint from the
532                    //    domain so zero-infrastructure bootstrapping can proceed when `dig`
533                    //    is not installed or no DNSSEC record is published.
534                    let address = domain_to_ip(domain, 0);
535                    PeerEndpoint {
536                        address,
537                        port: DEFAULT_PEER_PORT,
538                        verified: false,
539                        timestamp: now,
540                    }
541                }
542            };
543
544            // Cache the result with TTL
545            self.dnssec_cache.insert(
546                domain.to_string(),
547                CachedPeer {
548                    endpoint: endpoint.clone(),
549                    cached_at: now,
550                    ttl_seconds: DNSSEC_CACHE_TTL_SECONDS,
551                },
552            );
553
554            Ok(endpoint)
555        }
556
557        /// Number of entries currently held in the DNSSEC peer-resolution cache.
558        pub fn dnssec_cache_size(&self) -> usize {
559            self.dnssec_cache.len()
560        }
561
562        /// Clear all cached DNSSEC peer-resolution entries.
563        pub fn clear_dnssec_cache(&mut self) {
564            self.dnssec_cache.clear();
565        }
566
567        /// Set the capabilities bitmask for a peer (replaces the `peer_capabilities: 0` TODO).
568        pub fn set_peer_capabilities(&mut self, peer_id: &str, capabilities: u64) {
569            self.peer_capabilities
570                .insert(peer_id.to_string(), capabilities);
571        }
572
573        /// Set the semantic context for a peer (replaces the `semantic_context: 0` TODO).
574        pub fn set_semantic_context(&mut self, peer_id: &str, context: u64) {
575            self.semantic_contexts.insert(peer_id.to_string(), context);
576        }
577
578        /// Get the capabilities bitmask for a peer, if known.
579        pub fn get_peer_capabilities(&self, peer_id: &str) -> Option<u64> {
580            self.peer_capabilities.get(peer_id).copied()
581        }
582
583        /// Get the semantic context for a peer, if known.
584        pub fn get_semantic_context(&self, peer_id: &str) -> Option<u64> {
585            self.semantic_contexts.get(peer_id).copied()
586        }
587
588        /// Legacy CBOR-LD parsing method (fallback)
589        fn parse_cbor_ld_to_quin_legacy(
590            &self,
591            cbor_bytes: &[u8],
592        ) -> Result<DnssecSemanticPayload, &'static str> {
593            if cbor_bytes.len() > CBOR_LD_MAX_SIZE {
594                return Err("CBOR-LD payload too large");
595            }
596
597            // Stream CBOR data directly into Super-Quin structure
598            // This is a zero-allocation parser that maps CBOR keys to u64 pointers
599            let mut payload = DnssecSemanticPayload {
600                wireguard_pubkey: [0u8; WG_PUBKEY_LEN],
601                did_q42: 0,
602                routing_mask: 0,
603                semantic_handshake: "Legacy Proof".to_string(),
604                peer_capabilities: 0,
605                semantic_context: 0,
606            };
607
608            // Parse CBOR-LD structure
609            let mut offset = 0;
610            while offset < cbor_bytes.len() {
611                let (key, value, new_offset) = self.parse_cbor_pair(cbor_bytes, offset)?;
612                offset = new_offset;
613
614                match key {
615                    1 => {
616                        // wireguard_pubkey
617                        if value.len() == WG_PUBKEY_LEN {
618                            payload.wireguard_pubkey.copy_from_slice(&value);
619                        }
620                    }
621                    2 => {
622                        // did_q42
623                        payload.did_q42 =
624                            parse_did_q42(&value).map_err(|_| "Invalid did:q42 in CBOR-LD")?;
625                    }
626                    3 => {
627                        // routing_mask
628                        payload.routing_mask = value[0] as u64; // Stub legacy parser conversion
629                    }
630                    4 => {
631                        // peer_capabilities
632                        payload.peer_capabilities = u16::from_be_bytes([value[0], value[1]]);
633                    }
634                    5 => {
635                        // semantic_context
636                        payload.semantic_context = u64::from_be_bytes([
637                            value[0], value[1], value[2], value[3], value[4], value[5], value[6],
638                            value[7],
639                        ]);
640                    }
641                    _ => {} // Ignore unknown keys
642                }
643            }
644
645            Ok(payload)
646        }
647
648        /// Parse CBOR key-value pair (zero-allocation)
649        fn parse_cbor_pair(
650            &self,
651            cbor_bytes: &[u8],
652            offset: usize,
653        ) -> Result<(u64, Vec<u8>, usize), &'static str> {
654            if offset >= cbor_bytes.len() {
655                return Err("Invalid CBOR offset");
656            }
657
658            let first_byte = cbor_bytes[offset];
659            let major_type = first_byte >> 5;
660            let additional_info = first_byte & 0x1f;
661
662            let mut current_offset = offset + 1;
663
664            // Parse key (must be integer)
665            let key = if major_type == 0 {
666                // unsigned integer
667                let key_value = if additional_info < 24 {
668                    additional_info as u64
669                } else if additional_info == 24 {
670                    if current_offset < cbor_bytes.len() {
671                        cbor_bytes[current_offset] as u64
672                    } else {
673                        return Err("Invalid CBOR key encoding");
674                    }
675                } else {
676                    return Err("Unsupported CBOR key encoding");
677                };
678                current_offset += 1;
679                key_value
680            } else {
681                return Err("CBOR key must be integer");
682            };
683
684            // Parse value (byte string)
685            if current_offset >= cbor_bytes.len() {
686                return Err("Invalid CBOR value offset");
687            }
688
689            let value_first_byte = cbor_bytes[current_offset];
690            let value_major_type = value_first_byte >> 5;
691            let value_additional_info = value_first_byte & 0x1f;
692            current_offset += 1;
693
694            let value = if value_major_type == 2 {
695                // byte string
696                let length = if value_additional_info < 24 {
697                    value_additional_info as usize
698                } else if value_additional_info == 24 {
699                    if current_offset < cbor_bytes.len() {
700                        cbor_bytes[current_offset] as usize
701                    } else {
702                        return Err("Invalid CBOR length encoding");
703                    }
704                } else {
705                    return Err("Unsupported CBOR length encoding");
706                };
707                current_offset += 1;
708
709                if current_offset + length > cbor_bytes.len() {
710                    return Err("CBOR value extends beyond buffer");
711                }
712
713                let value_bytes = cbor_bytes[current_offset..current_offset + length].to_vec();
714                current_offset += length;
715                value_bytes
716            } else {
717                return Err("CBOR value must be byte string");
718            };
719
720            Ok((key, value, current_offset))
721        }
722
723        /// Establish SocialWebNet tunnel with peer
724        pub fn establish_wireguard_tunnel(
725            &mut self,
726            peer_payload: &DnssecSemanticPayload,
727            endpoint: IpAddr,
728            port: u16,
729        ) -> Result<u64, &'static str> {
730            let wireguard_interface = self
731                .wireguard_interface
732                .as_mut()
733                .ok_or("WireGuard interface not initialized")?;
734
735            // Create peer configuration
736            let peer_id = peer_payload.did_q42;
737            let peer = SocialWebNetPeer {
738                peer_id,
739                endpoint,
740                port,
741                pubkey: peer_payload.wireguard_pubkey,
742                allowed_ips: vec!["10.0.0.0/24".to_string()], // Default subnet
743                routing_mask: peer_payload.routing_mask,
744            };
745
746            // Configure WireGuard peer via wg command
747            let pubkey_hex = hex::encode(&peer.pubkey);
748            let allowed_ips = peer.allowed_ips.join(",");
749
750            let output = Command::new("wg")
751                .args([
752                    "set",
753                    &wireguard_interface.interface_name,
754                    "peer",
755                    &pubkey_hex,
756                    "endpoint",
757                    &format!("{}:{}", endpoint, port),
758                    "allowed-ip",
759                    &allowed_ips,
760                ])
761                .output()
762                .map_err(|_| "WireGuard configuration failed")?;
763
764            if !output.status.success() {
765                return Err("Failed to configure WireGuard peer");
766            }
767
768            // Add peer to active peers
769            wireguard_interface.active_peers.insert(peer_id, peer);
770            wireguard_interface
771                .routing_table
772                .insert(format!("{}:{}", endpoint, port), peer_id);
773
774            Ok(peer_id)
775        }
776
777        /// Bootstrap SocialWebNet tunnel using DNSSEC CBOR-LD resolution
778        pub fn bootstrap_social_wireguard(
779            &mut self,
780            domain: &str,
781            endpoint_ip: IpAddr,
782            endpoint_port: u16,
783        ) -> Result<u64, &'static str> {
784            // Step 1: Resolve peer via DNSSEC CBOR-LD
785            let peer_payload = self.resolve_peer_dnssec_payload(domain)?;
786
787            // Step 2: Verify routing constraints against local policy
788            let local_permission = crate::webizen_server::CompiledPermission {
789                routing_mask: 0, // In production, fetch from node configuration
790                semantic_handshake: "".to_string(),
791                is_permissive_commons: true,
792            };
793            if !self.verify_routing_constraints(&peer_payload, &local_permission)? {
794                return Err("Routing constraints not authorized");
795            }
796
797            // Step 3: Establish WireGuard tunnel
798            let peer_id =
799                self.establish_wireguard_tunnel(&peer_payload, endpoint_ip, endpoint_port)?;
800
801            // Step 4: Log successful bootstrap
802            println!(
803                "[SocialWebNet] Bootstrapped peer {} (did:q42:{}) on {}:{}",
804                domain, peer_payload.did_q42, endpoint_ip, endpoint_port
805            );
806
807            Ok(peer_id)
808        }
809
810        /// Verify routing constraints against local trust graph
811        fn verify_routing_constraints(
812            &self,
813            payload: &DnssecSemanticPayload,
814            local_compiled_permission: &crate::webizen_server::CompiledPermission,
815        ) -> Result<bool, &'static str> {
816            // Evaluate the 64-bit Fifth Vector hardware mask.
817            // If the peer's requested access does not mathematically satisfy the ro:RightsOntology bitmask, the tunnel is silently dropped.
818            if (payload.routing_mask & local_compiled_permission.routing_mask)
819                != local_compiled_permission.routing_mask
820            {
821                return Err("Failed ro:RightsOntology Fifth Vector hardware mask evaluation");
822            }
823            if payload.semantic_handshake.is_empty() {
824                return Err("Missing Semantic Handshake payload");
825            }
826            Ok(true)
827        }
828
829        /// Parse SAN URI from certificate or handshake (zero-allocation)
830        pub fn parse_san_uri(&self, san_bytes: &[u8]) -> Result<u64, &'static str> {
831            // Check for did:q42: prefix
832            if san_bytes.starts_with(b"did:q42:") {
833                return parse_did_q42(san_bytes).map_err(|_| "Invalid did:q42 in SAN");
834            }
835
836            // Check for webizen:// prefix
837            if san_bytes.starts_with(b"webizen://") {
838                // Extract hash after webizen://
839                let hash_part = &san_bytes[11..]; // Skip "webizen://"
840                if hash_part.len() >= 32 {
841                    // Parse as hex hash and convert to u64 pointer
842                    let hash_bytes = &hash_part[..32];
843                    let hash_u64 = u64::from_str_radix(
844                        std::str::from_utf8(hash_bytes).map_err(|_| "Invalid webizen hash")?,
845                        16,
846                    )
847                    .map_err(|_| "Invalid webizen hash format")?;
848                    return Ok(hash_u64 | (1u64 << 63)); // Set MSB for topological pointer
849                }
850            }
851
852            Err("Unsupported SAN URI format")
853        }
854
855        pub fn execute_tensor_contraction(
856            &self,
857            matrix_a: &[f32],
858            matrix_b: &[f32],
859            result: &mut [f32],
860            size: usize,
861        ) {
862            // Dense Linear Algebra Swarm
863            // Simulates dividing matrices into 128KB chunks and running SIMD tensor contractions
864            // on the CPU.
865
866            #[cfg(target_arch = "x86_64")]
867            if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {
868                // SAFETY: both features required by the isolated kernel were
869                // checked immediately above.
870                unsafe {
871                    tensor_contraction_avx2_fma(matrix_a, matrix_b, result, size);
872                }
873                crate::telemetry::SIEVE_OPS_COUNT.fetch_add(
874                    (size * size * size) as usize,
875                    std::sync::atomic::Ordering::Relaxed,
876                );
877                return;
878            }
879
880            // Fallback scalar
881            for i in 0..size {
882                for j in 0..size {
883                    for k in 0..size {
884                        result[i * size + j] += matrix_a[i * size + k] * matrix_b[k * size + j];
885                    }
886                }
887            }
888        }
889
890        pub fn execute_quantum_chemistry(&self, smiles: &str) -> Option<crate::NQuin> {
891            let mol = crate::domains::chemical::organic_chemistry::parse_smiles(smiles);
892            let mut dft = crate::quantum_dft::ElectronDensity::new(mol.atoms.len().max(1));
893
894            let mut quins = Vec::new();
895            for _ in 0..mol.atoms.len() {
896                let mut q = crate::NQuin::default();
897                q.predicate = crate::q_hash("HAS_ELECTRON");
898                quins.push(q);
899            }
900
901            let energy = dft.calculate_ground_state_energy(&quins);
902            crate::telemetry::ATOMIC_FLOPS_COUNT
903                .fetch_add(50000, std::sync::atomic::Ordering::Relaxed);
904
905            let mut out_quin = crate::NQuin::default();
906            out_quin.subject = crate::q_hash(smiles);
907            out_quin.predicate = crate::q_hash("has_ground_state_energy");
908            out_quin.object = crate::frame_layout::pack_float_object(energy as f32);
909            Some(out_quin)
910        }
911    }
912
913    /// Primary Orchestrator tracking Fractal Shards
914    pub struct DaemonOrchestrator {
915        pub active_cells: Arc<Mutex<Vec<WorkerCell>>>,
916        pub isolate_a_tx: Option<Sender<NQuin>>,
917        pub isolate_b_rx: Option<Receiver<NQuin>>,
918        pub dnssec_trusted_anchors: HashMap<String, [u8; 32]>,
919        pub wireguard_interface_name: String,
920        pub wireguard_local_port: u16,
921    }
922
923    impl DaemonOrchestrator {
924        pub fn new() -> Self {
925            Self {
926                active_cells: Arc::new(Mutex::new(Vec::new())),
927                isolate_a_tx: None,
928                isolate_b_rx: None,
929                dnssec_trusted_anchors: HashMap::new(),
930                wireguard_interface_name: "qualia-wg0".to_string(),
931                wireguard_local_port: 51820,
932            }
933        }
934
935        /// Configure DNSSEC trusted anchors
936        pub fn configure_dnssec_anchors(&mut self, anchors: HashMap<String, [u8; 32]>) {
937            self.dnssec_trusted_anchors = anchors;
938        }
939
940        /// Configure WireGuard interface settings
941        pub fn configure_wireguard(&mut self, interface_name: String, local_port: u16) {
942            self.wireguard_interface_name = interface_name;
943            self.wireguard_local_port = local_port;
944        }
945
946        /// Initialize all worker cells with DNSSEC and WireGuard capabilities
947        pub fn init_worker_cells_infrastructure(&self) {
948            let mut cells = self.active_cells.lock().unwrap();
949            for cell in cells.iter_mut() {
950                cell.init_dnssec_resolver(self.dnssec_trusted_anchors.clone());
951                cell.init_wireguard_interface(
952                    self.wireguard_interface_name.clone(),
953                    self.wireguard_local_port,
954                );
955            }
956        }
957
958        /// Bootstrap a SocialWebNet peer connection for a specific worker cell.
959        ///
960        /// Resolves the peer via DNSSEC, verifies routing constraints, then
961        /// registers the WireGuard peer inside the named worker cell.
962        pub fn bootstrap_peer_connection(
963            &self,
964            cell_id: usize,
965            domain: &str,
966            endpoint_ip: IpAddr,
967            endpoint_port: u16,
968        ) -> Result<u64, &'static str> {
969            // Step 1: Resolve peer via DNSSEC
970            let payload = self.resolve_peer_dnssec(domain)?;
971
972            // Step 2: Verify routing constraints
973            let local_permission = crate::webizen_server::CompiledPermission {
974                routing_mask: 0, // Mock: Fetch from config
975                semantic_handshake: "".to_string(),
976                is_permissive_commons: true,
977            };
978            if !self.verify_routing_constraints(&payload, &local_permission)? {
979                return Err("Routing constraints not authorized");
980            }
981
982            // Step 2b: Sentinel VM Fiduciary Gatekeeper
983            let mut intent = crate::NQuin::default();
984            intent.subject = crate::q_hash("did:q42:local");
985            intent.predicate = crate::q_hash("q42:TrustGroup");
986            intent.object = payload.did_q42;
987
988            let db = [intent];
989            let mut prog = [0u8; 1024];
990            prog[0] = crate::mini_parser::OP_EVAL_PERMIT;
991            prog[1] = crate::mini_parser::OP_END;
992
993            let mut out = [crate::NQuin::default(); 1];
994            let context = crate::webizen_bytecode::GuardianshipContext {
995                principal_did: crate::q_hash("did:q42:local"),
996                guardian_did: Some(crate::q_hash("did:q42:guardian_mock")),
997            };
998
999            let is_authorized =
1000                crate::webizen_bytecode::execute_program(&prog, &db, &mut out, Some(&context))
1001                    .is_ok();
1002
1003            if !is_authorized {
1004                return Err("Sentinel VM Gatekeeper: Peer relationship not authorized");
1005            }
1006
1007            // Step 3: Generate ephemeral WireGuard keypair and register peer
1008            use boringtun::noise::Tunn;
1009
1010            let mut raw_priv: [u8; 32] = rand::random();
1011            // Clamp scalar per RFC 7748
1012            raw_priv[0] &= 248;
1013            raw_priv[31] &= 127;
1014            raw_priv[31] |= 64;
1015
1016            let local_private = boringtun::x25519::StaticSecret::from(raw_priv);
1017            let peer_public = boringtun::x25519::PublicKey::from(payload.wireguard_pubkey);
1018
1019            let _tunn = Tunn::new(local_private, peer_public, None, None, 0, None);
1020
1021            let peer_id = u64::from_le_bytes(payload.wireguard_pubkey[..8].try_into().unwrap());
1022
1023            // Step 4: Register in the target cell
1024            {
1025                let mut cells = self
1026                    .active_cells
1027                    .lock()
1028                    .map_err(|_| "active_cells lock poisoned")?;
1029                let cell = cells
1030                    .iter_mut()
1031                    .find(|c| c.cell_id == cell_id)
1032                    .ok_or("Worker cell not found")?;
1033                if let Some(ref mut wg) = cell.wireguard_interface {
1034                    let peer = SocialWebNetPeer {
1035                        peer_id,
1036                        endpoint: endpoint_ip,
1037                        port: endpoint_port,
1038                        pubkey: payload.wireguard_pubkey,
1039                        allowed_ips: vec!["0.0.0.0/0".to_string()],
1040                        routing_mask: payload.routing_mask,
1041                    };
1042                    wg.active_peers.insert(peer_id, peer);
1043                    wg.routing_table.insert(endpoint_ip.to_string(), peer_id);
1044                }
1045            }
1046
1047            println!(
1048                "[SocialWebNet] Cell {} bootstrapped peer {} (did:q42:{}) at {}:{}",
1049                cell_id, domain, payload.did_q42, endpoint_ip, endpoint_port
1050            );
1051
1052            Ok(peer_id)
1053        }
1054
1055        pub fn spawn_fractal_shard(&self, cell_id: usize) {
1056            let mut cells = self.active_cells.lock().unwrap();
1057            cells.push(WorkerCell::new(cell_id));
1058        }
1059
1060        pub fn delegate_dense_algebra(&self, cell_id: usize) {
1061            // Mock spawning a thread for the swarm worker
1062            let cells = self.active_cells.clone();
1063            thread::spawn(move || {
1064                let mut locked_cells = cells.lock().unwrap();
1065                if let Some(cell) = locked_cells.iter_mut().find(|c| c.cell_id == cell_id) {
1066                    let mut res = vec![0.0; 4];
1067                    cell.execute_tensor_contraction(
1068                        &[1.0, 2.0, 3.0, 4.0],
1069                        &[1.0, 0.0, 0.0, 1.0],
1070                        &mut res,
1071                        2,
1072                    );
1073                }
1074            });
1075        }
1076
1077        /// Bootstrap SocialWebNet tunnel using DNSSEC CBOR-LD resolution
1078        pub fn bootstrap_social_wireguard(
1079            &mut self,
1080            domain: &str,
1081            endpoint_ip: IpAddr,
1082            endpoint_port: u16,
1083        ) -> Result<u64, &'static str> {
1084            // Step 1: Resolve peer via DNSSEC CBOR-LD
1085            let peer_payload = self.resolve_peer_dnssec(domain)?;
1086
1087            // Step 2: Verify routing constraints against local policy
1088            let local_permission = crate::webizen_server::CompiledPermission {
1089                routing_mask: 0,
1090                semantic_handshake: "".to_string(),
1091                is_permissive_commons: true,
1092            };
1093            if !self.verify_routing_constraints(&peer_payload, &local_permission)? {
1094                return Err("Routing constraints not authorized");
1095            }
1096
1097            // Step 3: Establish WireGuard tunnel
1098            let peer_id =
1099                self.establish_wireguard_tunnel(&peer_payload, endpoint_ip, endpoint_port)?;
1100
1101            // Step 4: Log successful bootstrap
1102            println!(
1103                "[SocialWebNet] Bootstrapped peer {} (did:q42:{}) on {}:{}",
1104                domain, peer_payload.did_q42, endpoint_ip, endpoint_port
1105            );
1106
1107            Ok(peer_id)
1108        }
1109
1110        /// Verify routing constraints against local trust graph
1111        fn verify_routing_constraints(
1112            &self,
1113            payload: &DnssecSemanticPayload,
1114            local_compiled_permission: &crate::webizen_server::CompiledPermission,
1115        ) -> Result<bool, &'static str> {
1116            // Evaluate the 64-bit Fifth Vector hardware mask.
1117            // If the peer's requested access does not mathematically satisfy the ro:RightsOntology bitmask, the tunnel is silently dropped.
1118            if (payload.routing_mask & local_compiled_permission.routing_mask)
1119                != local_compiled_permission.routing_mask
1120            {
1121                return Err("Failed ro:RightsOntology Fifth Vector hardware mask evaluation");
1122            }
1123            if payload.semantic_handshake.is_empty() {
1124                return Err("Missing Semantic Handshake payload");
1125            }
1126            Ok(true)
1127        }
1128
1129        /// Spawns the Cellular Isolate Model (Isolate A and Isolate B) for Neuro-Symbolic integration.
1130        pub fn spawn_neuro_symbolic_isolates(&mut self) {
1131            // SPSC Lock-Free Ring Buffers for Isolate Communication
1132            let (tx_ab, rx_ab) = bounded::<NQuin>(SPSC_BUFFER_CAPACITY); // Isolate A -> Isolate B
1133            let (tx_ba, rx_ba) = bounded::<NQuin>(SPSC_BUFFER_CAPACITY); // Isolate B -> Isolate A
1134
1135            self.isolate_a_tx = Some(tx_ab);
1136            self.isolate_b_rx = Some(rx_ba);
1137
1138            // Isolate B (Neural Bridge): Unrestricted memory, runs dense tensor math
1139            thread::spawn(move || {
1140                println!("[Isolate B] Neural Bridge online. Awaiting prompt constraints...");
1141                while let Ok(prompt_quin) = rx_ab.recv() {
1142                    crate::telemetry::SIEVE_OPS_COUNT
1143                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1144
1145                    // Real deterministic computation via the swarm executor (replaces
1146                    // the former constant-`999` fabrication). The consequence quin
1147                    // carries an actually-computed result, parity included.
1148                    let result_quin = match crate::services::swarm::isolate_b_compute(prompt_quin) {
1149                        Some(q) => q,
1150                        None => continue, // malformed input: skip, do not fabricate
1151                    };
1152
1153                    if tx_ba.send(result_quin).is_err() {
1154                        break;
1155                    }
1156                }
1157            });
1158        }
1159
1160        /// Create WireGuard interface
1161        pub fn create_wireguard_interface(&self) -> Result<(), &'static str> {
1162            let output = Command::new("wg")
1163                .args([
1164                    "quick",
1165                    &self.wireguard_interface_name,
1166                    "listen-port",
1167                    &self.wireguard_local_port.to_string(),
1168                ])
1169                .output()
1170                .map_err(|_| "Failed to create WireGuard interface")?;
1171
1172            if !output.status.success() {
1173                return Err("Failed to create WireGuard interface");
1174            }
1175
1176            println!(
1177                "[DaemonOrchestrator] Created WireGuard interface {} on port {}",
1178                self.wireguard_interface_name, self.wireguard_local_port
1179            );
1180
1181            Ok(())
1182        }
1183
1184        /// Get active WireGuard peers
1185        pub fn get_active_peers(&self) -> Result<Vec<(u64, String)>, &'static str> {
1186            let output = Command::new("wg")
1187                .args(["show", &self.wireguard_interface_name])
1188                .output()
1189                .map_err(|_| "Failed to get WireGuard status")?;
1190
1191            if !output.status.success() {
1192                return Err("Failed to get WireGuard status");
1193            }
1194
1195            let mut peers = Vec::new();
1196            let output_str = String::from_utf8_lossy(&output.stdout);
1197
1198            // Parse wg show output to extract peer information
1199            for line in output_str.lines() {
1200                if line.starts_with("peer:") {
1201                    let parts: Vec<&str> = line.split_whitespace().collect();
1202                    if parts.len() >= 2 {
1203                        let pubkey = parts[1];
1204                        if let Ok(pubkey_bytes) = hex::decode(pubkey) {
1205                            if pubkey_bytes.len() == 32 {
1206                                let mut peer_id = [0u8; 32];
1207                                peer_id.copy_from_slice(&pubkey_bytes);
1208                                let peer_id_u64 = u64::from_be_bytes([
1209                                    peer_id[0], peer_id[1], peer_id[2], peer_id[3], peer_id[4],
1210                                    peer_id[5], peer_id[6], peer_id[7],
1211                                ]);
1212                                peers.push((peer_id_u64, pubkey.to_string()));
1213                            }
1214                        }
1215                    }
1216                }
1217            }
1218
1219            Ok(peers)
1220        }
1221
1222        /// Resolve peer via DNSSEC TXT lookup, returning the embedded CBOR-LD semantic payload.
1223        ///
1224        /// Queries `_q42peer._tcp.<domain>` TXT record.  The record payload is a binary
1225        /// structure: [0..32] WireGuard pubkey, [32..40] did_q42 u64 LE, [40] routing_constraints,
1226        /// [41..43] peer_capabilities u16 LE, [43..51] semantic_context u64 LE.
1227        /// Falls back to the in-cell DNSSEC cache before hitting the network.
1228        fn resolve_peer_dnssec(&self, domain: &str) -> Result<DnssecSemanticPayload, &'static str> {
1229            // Check cell-local cache first
1230            if let Ok(cells) = self.active_cells.lock() {
1231                for cell in cells.iter() {
1232                    if let Some(ref resolver) = cell.dnssec_resolver {
1233                        if let Some(cached) = resolver.cache.get(domain) {
1234                            return Ok(cached.clone());
1235                        }
1236                    }
1237                }
1238            }
1239
1240            // Perform live DNSSEC-validated TXT lookup via trust-dns-resolver
1241            use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
1242            use trust_dns_resolver::Resolver;
1243
1244            let mut opts = ResolverOpts::default();
1245            opts.validate = true; // require DNSSEC validation
1246            opts.use_hosts_file = false;
1247
1248            let resolver = Resolver::new(ResolverConfig::default(), opts)
1249                .map_err(|_| "DNS resolver init failed")?;
1250
1251            // Canonical record name for Qualia peer discovery
1252            let qname = format!("_q42peer._tcp.{}.", domain);
1253            let lookup = resolver
1254                .txt_lookup(qname.as_str())
1255                .map_err(|_| "DNS TXT lookup failed")?;
1256
1257            for txt in lookup.iter() {
1258                for part in txt.txt_data() {
1259                    if part.len() >= 51 {
1260                        let mut wg_pubkey = [0u8; 32];
1261                        wg_pubkey.copy_from_slice(&part[..32]);
1262
1263                        // Safety: lengths checked above
1264                        let did_q42 = u64::from_le_bytes(part[32..40].try_into().unwrap());
1265                        let routing_mask = part[40] as u64;
1266                        let peer_capabilities =
1267                            u16::from_le_bytes(part[41..43].try_into().unwrap());
1268                        let semantic_context = u64::from_le_bytes(part[43..51].try_into().unwrap());
1269
1270                        let payload = DnssecSemanticPayload {
1271                            wireguard_pubkey: wg_pubkey,
1272                            did_q42,
1273                            routing_mask,
1274                            semantic_handshake: "Legacy Proof".to_string(),
1275                            peer_capabilities,
1276                            semantic_context,
1277                        };
1278
1279                        // Populate cell-local cache
1280                        if let Ok(mut cells) = self.active_cells.lock() {
1281                            for cell in cells.iter_mut() {
1282                                if let Some(ref mut r) = cell.dnssec_resolver {
1283                                    r.cache.insert(domain.to_string(), payload.clone());
1284                                    break;
1285                                }
1286                            }
1287                        }
1288                    }
1289                }
1290            }
1291
1292            Err("No valid Qualia semantic payload in DNS TXT records")
1293        }
1294
1295        /// Establish a SocialWebNet tunnel to a peer described by `payload`.
1296        ///
1297        /// Generates an ephemeral local WireGuard keypair via boringtun, validates the
1298        /// peer's public key, registers the peer in the first cell that has a WireGuard
1299        /// interface initialised, and returns a deterministic peer ID (low 8 bytes of pubkey).
1300        fn establish_wireguard_tunnel(
1301            &mut self,
1302            payload: &DnssecSemanticPayload,
1303            ip: IpAddr,
1304            port: u16,
1305        ) -> Result<u64, &'static str> {
1306            use boringtun::noise::Tunn;
1307
1308            // Generate ephemeral local WireGuard private key
1309            let mut raw_priv: [u8; 32] = rand::random();
1310            // Clamp scalar per RFC 7748
1311            raw_priv[0] &= 248;
1312            raw_priv[31] &= 127;
1313            raw_priv[31] |= 64;
1314
1315            // boringtun key types
1316            let local_private = boringtun::x25519::StaticSecret::from(raw_priv);
1317            let peer_public = boringtun::x25519::PublicKey::from(payload.wireguard_pubkey);
1318
1319            // Create the user-space WireGuard tunnel object (index 0, no keepalive)
1320            let _tunn = Tunn::new(local_private, peer_public, None, None, 0, None);
1321
1322            // Deterministic peer ID from the first 8 bytes of the pubkey
1323            let peer_id = u64::from_le_bytes(payload.wireguard_pubkey[..8].try_into().unwrap());
1324
1325            // Register peer in the first cell that has a WG interface
1326            if let Ok(mut cells) = self.active_cells.lock() {
1327                for cell in cells.iter_mut() {
1328                    if let Some(ref mut wg) = cell.wireguard_interface {
1329                        let peer = SocialWebNetPeer {
1330                            peer_id,
1331                            endpoint: ip,
1332                            port,
1333                            pubkey: payload.wireguard_pubkey,
1334                            allowed_ips: vec!["0.0.0.0/0".to_string()],
1335                            routing_mask: payload.routing_mask,
1336                        };
1337                        wg.active_peers.insert(peer_id, peer);
1338                        wg.routing_table.insert(ip.to_string(), peer_id);
1339                        break;
1340                    }
1341                }
1342            }
1343
1344            Ok(peer_id)
1345        }
1346    }
1347
1348    #[cfg(test)]
1349    mod tests {
1350        use super::*;
1351
1352        fn cell_with_resolver() -> WorkerCell {
1353            let mut cell = WorkerCell::new(0);
1354            cell.init_dnssec_resolver(HashMap::new());
1355            cell
1356        }
1357
1358        #[test]
1359        fn resolve_peer_returns_endpoint_and_caches() {
1360            let mut cell = cell_with_resolver();
1361
1362            // `dig` is almost certainly unavailable in the test environment, so this
1363            // exercises the deterministic fallback path.
1364            let endpoint = cell
1365                .resolve_peer_dnssec("peer.example.com")
1366                .expect("fallback resolution should succeed");
1367
1368            assert_eq!(endpoint.port, DEFAULT_PEER_PORT);
1369            // Fallback path is not DNSSEC-validated
1370            assert!(!endpoint.verified);
1371            // Same domain must always map to the same address (deterministic)
1372            let again = cell
1373                .resolve_peer_dnssec("peer.example.com")
1374                .expect("cached resolution should succeed");
1375            assert_eq!(endpoint.address, again.address);
1376            assert_eq!(endpoint.port, again.port);
1377            // Cached
1378            assert_eq!(cell.dnssec_cache_size(), 1);
1379        }
1380
1381        #[test]
1382        fn resolve_peer_uses_cache_on_second_call() {
1383            let mut cell = cell_with_resolver();
1384
1385            let first = cell
1386                .resolve_peer_dnssec("cache.example.com")
1387                .expect("resolution should succeed");
1388            assert_eq!(cell.dnssec_cache_size(), 1);
1389
1390            let second = cell
1391                .resolve_peer_dnssec("cache.example.com")
1392                .expect("cached resolution should succeed");
1393
1394            // Cache hit returns the same endpoint (including timestamp)
1395            assert_eq!(first, second);
1396            assert_eq!(cell.dnssec_cache_size(), 1);
1397        }
1398
1399        #[test]
1400        fn set_and_get_peer_capabilities() {
1401            let mut cell = cell_with_resolver();
1402
1403            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), None);
1404
1405            cell.set_peer_capabilities("did:q42:abc", 0b1010);
1406            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1010));
1407
1408            // Overwrite
1409            cell.set_peer_capabilities("did:q42:abc", 0b1111);
1410            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1111));
1411
1412            // Independent peers
1413            cell.set_peer_capabilities("did:q42:def", 0b1);
1414            assert_eq!(cell.get_peer_capabilities("did:q42:def"), Some(0b1));
1415            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1111));
1416        }
1417
1418        #[test]
1419        fn set_and_get_semantic_context() {
1420            let mut cell = cell_with_resolver();
1421
1422            assert_eq!(cell.get_semantic_context("did:q42:ctx"), None);
1423
1424            cell.set_semantic_context("did:q42:ctx", 0xC0FFEE);
1425            assert_eq!(cell.get_semantic_context("did:q42:ctx"), Some(0xC0FFEE));
1426
1427            cell.set_semantic_context("did:q42:ctx", 0x1234_5678);
1428            assert_eq!(cell.get_semantic_context("did:q42:ctx"), Some(0x1234_5678));
1429        }
1430
1431        #[test]
1432        fn clear_dnssec_cache_empties_entries() {
1433            let mut cell = cell_with_resolver();
1434
1435            cell.resolve_peer_dnssec("a.example.com").unwrap();
1436            cell.resolve_peer_dnssec("b.example.com").unwrap();
1437            assert_eq!(cell.dnssec_cache_size(), 2);
1438
1439            cell.clear_dnssec_cache();
1440            assert_eq!(cell.dnssec_cache_size(), 0);
1441
1442            // Resolving after clear repopulates
1443            cell.resolve_peer_dnssec("a.example.com").unwrap();
1444            assert_eq!(cell.dnssec_cache_size(), 1);
1445        }
1446
1447        #[test]
1448        fn cached_peer_ttl_freshness() {
1449            let endpoint = PeerEndpoint {
1450                address: IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, 1)),
1451                port: 51820,
1452                verified: true,
1453                timestamp: 1000,
1454            };
1455            let cached = CachedPeer {
1456                endpoint,
1457                cached_at: 1000,
1458                ttl_seconds: 300,
1459            };
1460            assert!(cached.is_fresh(1100));
1461            assert!(cached.is_fresh(1299));
1462            assert!(!cached.is_fresh(1300));
1463            assert!(!cached.is_fresh(2000));
1464        }
1465
1466        #[test]
1467        fn parse_cbor_ld_to_quin_chunks_data() {
1468            let cell = cell_with_resolver();
1469
1470            // Without a Q42 lexicon parser initialised, parsing must fail cleanly.
1471            let res = cell.parse_cbor_ld_to_quin(&[0x01, 0x02, 0x03]);
1472            assert_eq!(res.err(), Some(DaemonError::CborLdParsingFailed));
1473
1474            // Empty payload is an error
1475            let res = cell.parse_cbor_ld_to_quin(&[]);
1476            assert_eq!(res.err(), Some(DaemonError::CborLdParsingFailed));
1477        }
1478
1479        #[test]
1480        fn domain_to_ip_is_deterministic() {
1481            let a = domain_to_ip("peer.example.com", 0);
1482            let b = domain_to_ip("peer.example.com", 0);
1483            assert_eq!(a, b);
1484
1485            // Different domains should (almost certainly) differ
1486            let c = domain_to_ip("other.example.com", 0);
1487            assert_ne!(a, c);
1488
1489            // Salt changes the address
1490            let d = domain_to_ip("peer.example.com", 1);
1491            assert_ne!(a, d);
1492
1493            // Always in the 10.x.x.x private range
1494            if let IpAddr::V4(v4) = a {
1495                assert_eq!(v4.octets()[0], 10);
1496            } else {
1497                panic!("expected IPv4 from domain_to_ip");
1498            }
1499        }
1500    }
1501}