1#[cfg(not(target_arch = "wasm32"))]
6pub mod swarm {
7 use crate::governance::coordination::compute_priority;
8 use crate::identifier::parse_did_q42;
9 #[cfg(not(target_arch = "wasm32"))]
10 use crate::q42_lexicon::{CborLdError, Q42CborLdParser, Q42Context};
11 #[cfg(not(target_arch = "wasm32"))]
12 use crate::q42_volume::Q42Volume;
13 use crate::NQuin;
14 use crate::QualiaSuperBlock;
15 use crossbeam_channel::{bounded, Receiver, Sender};
16 use std::collections::HashMap;
17
18 use std::net::IpAddr;
19 use std::process::Command;
20 use std::sync::{Arc, Mutex};
21 use std::thread;
22 use std::time::{SystemTime, UNIX_EPOCH};
23
24 #[derive(Debug, Clone, PartialEq, Eq)]
26 pub struct AgentComputeCandidate {
27 pub agent_did_hash: u64,
28 pub windowed_faults: u32,
29 pub usury_event: bool,
30 }
31
32 impl AgentComputeCandidate {
33 pub const fn new(agent_did_hash: u64, windowed_faults: u32, usury_event: bool) -> Self {
35 Self {
36 agent_did_hash,
37 windowed_faults,
38 usury_event,
39 }
40 }
41
42 #[inline]
44 pub fn priority(&self) -> u64 {
45 compute_priority(self.windowed_faults, self.usury_event)
46 }
47 }
48
49 const SPSC_BUFFER_CAPACITY: usize = 1024;
51
52 const DNSSEC_TXT_RECORD: u16 = 16;
54 const DNSSEC_CERT_RECORD: u16 = 37;
55
56 const WG_PUBKEY_LEN: usize = 32;
58
59 const CBOR_LD_MAX_SIZE: usize = 512;
61
62 const DNSSEC_CACHE_TTL_SECONDS: u64 = 300;
64
65 const DEFAULT_PEER_PORT: u16 = 51820;
67
68 #[cfg(target_arch = "x86_64")]
69 #[target_feature(enable = "avx2,fma")]
70 unsafe fn tensor_contraction_avx2_fma(
71 matrix_a: &[f32],
72 matrix_b: &[f32],
73 result: &mut [f32],
74 size: usize,
75 ) {
76 use core::arch::x86_64::*;
77
78 for i in 0..size {
79 for k in 0..size {
80 let a_ik = _mm256_broadcast_ss(&matrix_a[i * size + k]);
81 let mut j = 0;
82 while j + 8 <= size {
83 let b_kj = _mm256_loadu_ps(matrix_b.as_ptr().add(k * size + j));
84 let mut r_ij = _mm256_loadu_ps(result.as_ptr().add(i * size + j));
85 r_ij = _mm256_fmadd_ps(a_ik, b_kj, r_ij);
86 _mm256_storeu_ps(result.as_mut_ptr().add(i * size + j), r_ij);
87 j += 8;
88 }
89 while j < size {
90 result[i * size + j] += matrix_a[i * size + k] * matrix_b[k * size + j];
91 j += 1;
92 }
93 }
94 }
95 }
96
97 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub enum DaemonError {
100 ResolverNotInitialized,
102 DigUnavailable,
104 DnssecLookupFailed,
106 CborLdParsingFailed,
108 InvalidDomain,
110 PeerNotFound,
112 }
113
114 impl From<&'static str> for DaemonError {
115 fn from(msg: &'static str) -> Self {
116 match msg {
117 "DNSSEC resolver not initialized" => DaemonError::ResolverNotInitialized,
118 "DNSSEC lookup failed" | "DNSSEC query failed" => DaemonError::DigUnavailable,
119 "CBOR-LD payload not found in DNSSEC response" => DaemonError::DnssecLookupFailed,
120 "CBOR-LD payload too large" | "CBOR-LD parsing failed" => {
121 DaemonError::CborLdParsingFailed
122 }
123 _ => DaemonError::DnssecLookupFailed,
124 }
125 }
126 }
127
128 #[derive(Debug, Clone, PartialEq, Eq)]
130 pub struct PeerEndpoint {
131 pub address: IpAddr,
133 pub port: u16,
135 pub verified: bool,
137 pub timestamp: u64,
139 }
140
141 #[derive(Debug, Clone)]
143 pub struct CachedPeer {
144 pub endpoint: PeerEndpoint,
145 pub cached_at: u64,
146 pub ttl_seconds: u64,
147 }
148
149 impl CachedPeer {
150 pub fn is_fresh(&self, now: u64) -> bool {
152 now.saturating_sub(self.cached_at) < self.ttl_seconds
153 }
154 }
155
156 fn unix_now() -> u64 {
158 SystemTime::now()
159 .duration_since(UNIX_EPOCH)
160 .map(|d| d.as_secs())
161 .unwrap_or(0)
162 }
163
164 fn domain_to_ip(domain: &str, salt: u64) -> IpAddr {
171 let mut h = crate::q_hash(domain).wrapping_add(salt);
174 h = h.wrapping_mul(0x9E3779B97F4A7C15);
175 h ^= h >> 32;
176 h = h.wrapping_mul(0x9E3779B97F4A7C15);
177 h ^= h >> 32;
178 IpAddr::V4(std::net::Ipv4Addr::new(
179 10,
180 ((h >> 40) & 0xff) as u8,
181 ((h >> 32) & 0xff) as u8,
182 ((h >> 24) & 0xff) as u8,
183 ))
184 }
185
186 fn port_from_payload(payload: &DnssecSemanticPayload) -> u16 {
188 let raw = payload.did_q42 ^ payload.routing_mask;
189 let port = (raw & 0xffff) as u16;
190 if port == 0 {
191 DEFAULT_PEER_PORT
192 } else {
193 port
194 }
195 }
196
197 #[derive(Debug, Clone)]
199 pub struct DnssecSemanticPayload {
200 pub wireguard_pubkey: [u8; WG_PUBKEY_LEN],
201 pub did_q42: u64,
202 pub routing_mask: u64, pub semantic_handshake: String,
204 pub peer_capabilities: u16,
205 pub semantic_context: u64,
206 }
207
208 #[derive(Debug, Clone)]
210 pub struct SocialWebNetPeer {
211 pub peer_id: u64,
212 pub endpoint: IpAddr,
213 pub port: u16,
214 pub pubkey: [u8; WG_PUBKEY_LEN],
215 pub allowed_ips: Vec<String>,
216 pub routing_mask: u64,
217 }
218
219 pub struct DnssecResolver {
221 pub trusted_anchors: HashMap<String, [u8; 32]>,
222 pub cache: HashMap<String, DnssecSemanticPayload>,
223 pub validation_enabled: bool,
224 }
225
226 pub struct SocialWebNetInterface {
228 pub interface_name: String,
229 pub local_port: u16,
230 pub active_peers: HashMap<u64, SocialWebNetPeer>,
231 pub routing_table: HashMap<String, u64>,
232 }
233
234 pub struct WorkerCell {
237 pub cell_id: usize,
238 pub memory_boundary: usize, pub attached_blocks: Vec<QualiaSuperBlock>,
240 pub dnssec_resolver: Option<DnssecResolver>,
241 pub wireguard_interface: Option<SocialWebNetInterface>,
242 #[cfg(not(target_arch = "wasm32"))]
243 pub q42_context: Option<Arc<Q42Context>>,
244 #[cfg(not(target_arch = "wasm32"))]
245 pub cbor_ld_parser: Option<Arc<Q42CborLdParser>>,
246 pub dnssec_cache: HashMap<String, CachedPeer>,
248 pub peer_capabilities: HashMap<String, u64>,
250 pub semantic_contexts: HashMap<String, u64>,
252 pub local_permission: crate::webizen_server::CompiledPermission,
254 }
255
256 impl WorkerCell {
257 pub fn new(cell_id: usize) -> Self {
259 Self {
260 cell_id,
261 memory_boundary: 512 * 1024 * 1024,
262 attached_blocks: Vec::new(),
263 dnssec_resolver: None,
264 wireguard_interface: None,
265 #[cfg(not(target_arch = "wasm32"))]
266 q42_context: None,
267 #[cfg(not(target_arch = "wasm32"))]
268 cbor_ld_parser: None,
269 dnssec_cache: HashMap::new(),
270 peer_capabilities: HashMap::new(),
271 semantic_contexts: HashMap::new(),
272 local_permission: crate::webizen_server::CompiledPermission {
273 routing_mask: 0x01 << 61, semantic_handshake: "qualia:handshake:v1".to_string(),
275 is_permissive_commons: true,
276 },
277 }
278 }
279
280 pub fn init_dnssec_resolver(&mut self, trusted_anchors: HashMap<String, [u8; 32]>) {
282 self.dnssec_resolver = Some(DnssecResolver {
283 trusted_anchors,
284 cache: HashMap::new(),
285 validation_enabled: true,
286 });
287 }
288
289 pub fn init_wireguard_interface(&mut self, interface_name: String, local_port: u16) {
291 self.wireguard_interface = Some(SocialWebNetInterface {
292 interface_name,
293 local_port,
294 active_peers: HashMap::new(),
295 routing_table: HashMap::new(),
296 });
297 }
298
299 #[cfg(not(target_arch = "wasm32"))]
301 pub fn init_q42_lexicon(&mut self, volume: &Q42Volume) -> Result<(), CborLdError> {
302 let context =
303 Arc::new(Q42Context::from_volume(volume).map_err(|_| CborLdError::InvalidOffset)?);
304 let parser = Arc::new(
305 Q42CborLdParser::from_volume(volume).map_err(|_| CborLdError::InvalidOffset)?,
306 );
307
308 self.q42_context = Some(context);
309 self.cbor_ld_parser = Some(parser);
310 Ok(())
311 }
312
313 pub fn resolve_peer_dnssec_payload(
319 &mut self,
320 domain: &str,
321 ) -> Result<DnssecSemanticPayload, &'static str> {
322 if self.dnssec_resolver.is_none() {
324 return Err("DNSSEC resolver not initialized");
325 }
326
327 if let Some(cached_payload) = self
329 .dnssec_resolver
330 .as_ref()
331 .and_then(|r| r.cache.get(domain))
332 {
333 return Ok(cached_payload.clone());
334 }
335
336 let cbor_ld_payload = self.perform_dnssec_lookup(domain)?;
338
339 let semantic_payload = self.parse_cbor_ld_to_payload(&cbor_ld_payload)?;
341
342 if let Some(ref mut resolver) = self.dnssec_resolver {
344 resolver
345 .cache
346 .insert(domain.to_string(), semantic_payload.clone());
347 }
348
349 Ok(semantic_payload)
350 }
351
352 fn dnssec_rrtype_name(rrtype: u16) -> Option<&'static str> {
353 match rrtype {
354 DNSSEC_TXT_RECORD => Some("TXT"),
355 DNSSEC_CERT_RECORD => Some("CERT"),
356 _ => None,
357 }
358 }
359
360 fn perform_dnssec_lookup(&self, domain: &str) -> Result<Vec<u8>, &'static str> {
362 for rrtype in [DNSSEC_TXT_RECORD, DNSSEC_CERT_RECORD] {
363 if let Ok(cbor_bytes) = self.dig_dnssec_record(domain, rrtype) {
364 return Ok(cbor_bytes);
365 }
366 }
367 Err("DNSSEC query failed")
368 }
369
370 fn dig_dnssec_record(&self, domain: &str, rrtype: u16) -> Result<Vec<u8>, &'static str> {
371 let rrtype_name = Self::dnssec_rrtype_name(rrtype).ok_or("DNSSEC query failed")?;
372 let qname = format!("_qualia._dnssec.{}", domain);
373
374 let output = Command::new("dig")
375 .args([
376 "+dnssec",
377 "+short",
378 "+yaml",
379 &format!("+rrtype={rrtype_name}"),
380 qname.as_str(),
381 ])
382 .output()
383 .map_err(|_| "DNSSEC lookup failed")?;
384
385 if !output.status.success() {
386 return Err("DNSSEC query failed");
387 }
388
389 let response = String::from_utf8_lossy(&output.stdout);
390 let cbor_hex = self.extract_cbor_from_dnssec_response(&response, rrtype)?;
391 hex::decode(&cbor_hex).map_err(|_| "Invalid CBOR hex encoding")
392 }
393
394 fn extract_cbor_from_dnssec_response(
396 &self,
397 response: &str,
398 rrtype: u16,
399 ) -> Result<String, &'static str> {
400 let marker = match rrtype {
401 DNSSEC_TXT_RECORD => "cbor-ld:",
402 DNSSEC_CERT_RECORD => "cbor-cert:",
403 _ => return Err("CBOR-LD payload not found in DNSSEC response"),
404 };
405
406 for line in response.lines() {
407 if !line.contains(marker) {
408 continue;
409 }
410 let parts: Vec<&str> = line.split(':').collect();
411 if parts.len() >= 2 {
412 return Ok(parts[1].trim().to_string());
413 }
414 }
415 Err("CBOR-LD payload not found in DNSSEC response")
416 }
417
418 #[cfg(not(target_arch = "wasm32"))]
420 fn parse_cbor_ld_to_payload(
421 &self,
422 cbor_bytes: &[u8],
423 ) -> Result<DnssecSemanticPayload, &'static str> {
424 if cbor_bytes.len() > CBOR_LD_MAX_SIZE {
425 return Err("CBOR-LD payload too large");
426 }
427
428 if let Some(ref parser) = self.cbor_ld_parser {
430 let semantic_payload = parser
431 .parse_semantic_payload(cbor_bytes)
432 .map_err(|_| "CBOR-LD parsing failed")?;
433
434 let wireguard_pubkey = match semantic_payload.wireguard_pubkey {
437 Some(k) => {
438 let mut key = [0u8; 32];
439 if k.len() >= 32 {
440 key.copy_from_slice(&k.as_bytes()[0..32]);
441 }
442 key
443 }
444 None => [0u8; 32],
445 };
446
447 let did_q42 = match semantic_payload.did_q42 {
448 Some(d) => crate::q_hash(&d),
449 None => 0,
450 };
451
452 let routing_mask = if !semantic_payload.routing_constraints.is_empty() {
453 0x02 << 61 } else {
455 0x01 << 61 };
457
458 return Ok(DnssecSemanticPayload {
459 wireguard_pubkey,
460 did_q42,
461 routing_mask,
462 semantic_handshake: "Semantic Cryptographic Proof Template".to_string(),
463 peer_capabilities: 0, semantic_context: 0, });
466 }
467
468 self.parse_cbor_ld_to_quin_legacy(cbor_bytes)
470 }
471
472 #[cfg(not(target_arch = "wasm32"))]
478 pub fn parse_cbor_ld_to_quin(&self, cbor_data: &[u8]) -> Result<Vec<u64>, DaemonError> {
479 if cbor_data.is_empty() {
480 return Err(DaemonError::CborLdParsingFailed);
481 }
482 if cbor_data.len() > CBOR_LD_MAX_SIZE {
483 return Err(DaemonError::CborLdParsingFailed);
484 }
485
486 let parser = self
487 .cbor_ld_parser
488 .as_ref()
489 .ok_or(DaemonError::CborLdParsingFailed)?;
490
491 let semantic_payload = parser
492 .parse_semantic_payload(cbor_data)
493 .map_err(|_| DaemonError::CborLdParsingFailed)?;
494
495 let data = &semantic_payload.data;
499 let mut pointers = Vec::with_capacity((data.len() + 7) / 8);
500 let mut idx = 0;
501 while idx < data.len() {
502 let mut chunk = [0u8; 8];
503 let end = (idx + 8).min(data.len());
504 chunk[..end - idx].copy_from_slice(&data[idx..end]);
505 pointers.push(u64::from_le_bytes(chunk));
506 idx += 8;
507 }
508
509 if pointers.is_empty() {
512 pointers.push(0);
513 }
514
515 Ok(pointers)
516 }
517
518 pub fn resolve_peer_dnssec(&mut self, domain: &str) -> Result<PeerEndpoint, DaemonError> {
528 let now = unix_now();
529
530 if let Some(cached) = self.dnssec_cache.get(domain) {
532 if cached.is_fresh(now) {
533 return Ok(cached.endpoint.clone());
534 }
535 }
536
537 let endpoint = match self.perform_dnssec_lookup(domain) {
539 Ok(cbor_bytes) => {
540 let verified = self
544 .dnssec_resolver
545 .as_ref()
546 .map_or(false, |r| r.validation_enabled);
547 let payload = self.parse_cbor_ld_to_payload(&cbor_bytes);
548 let (address, port) = match payload {
549 Ok(p) => {
550 let id = u64::from_le_bytes(
551 p.wireguard_pubkey[..8].try_into().unwrap_or([0u8; 8]),
552 );
553 (domain_to_ip(domain, id), port_from_payload(&p))
554 }
555 Err(_) => (domain_to_ip(domain, 0), DEFAULT_PEER_PORT),
556 };
557 PeerEndpoint {
558 address,
559 port,
560 verified,
561 timestamp: now,
562 }
563 }
564 Err(_) => {
565 let address = domain_to_ip(domain, 0);
569 PeerEndpoint {
570 address,
571 port: DEFAULT_PEER_PORT,
572 verified: false,
573 timestamp: now,
574 }
575 }
576 };
577
578 self.dnssec_cache.insert(
580 domain.to_string(),
581 CachedPeer {
582 endpoint: endpoint.clone(),
583 cached_at: now,
584 ttl_seconds: DNSSEC_CACHE_TTL_SECONDS,
585 },
586 );
587
588 Ok(endpoint)
589 }
590
591 pub fn dnssec_cache_size(&self) -> usize {
593 self.dnssec_cache.len()
594 }
595
596 pub fn clear_dnssec_cache(&mut self) {
598 self.dnssec_cache.clear();
599 }
600
601 pub fn set_peer_capabilities(&mut self, peer_id: &str, capabilities: u64) {
603 self.peer_capabilities
604 .insert(peer_id.to_string(), capabilities);
605 }
606
607 pub fn set_semantic_context(&mut self, peer_id: &str, context: u64) {
609 self.semantic_contexts.insert(peer_id.to_string(), context);
610 }
611
612 pub fn get_peer_capabilities(&self, peer_id: &str) -> Option<u64> {
614 self.peer_capabilities.get(peer_id).copied()
615 }
616
617 pub fn get_semantic_context(&self, peer_id: &str) -> Option<u64> {
619 self.semantic_contexts.get(peer_id).copied()
620 }
621
622 pub fn compute_agent_priority(&self, windowed_faults: u32, usury_event: bool) -> u64 {
624 compute_priority(windowed_faults, usury_event)
625 }
626
627 pub fn route_agent_task(&self, candidates: &[AgentComputeCandidate]) -> Option<u64> {
629 DaemonOrchestrator::route_agent_task(candidates)
630 }
631
632 fn parse_cbor_ld_to_quin_legacy(
634 &self,
635 cbor_bytes: &[u8],
636 ) -> Result<DnssecSemanticPayload, &'static str> {
637 if cbor_bytes.len() > CBOR_LD_MAX_SIZE {
638 return Err("CBOR-LD payload too large");
639 }
640
641 let mut payload = DnssecSemanticPayload {
644 wireguard_pubkey: [0u8; WG_PUBKEY_LEN],
645 did_q42: 0,
646 routing_mask: 0,
647 semantic_handshake: "Legacy Proof".to_string(),
648 peer_capabilities: 0,
649 semantic_context: 0,
650 };
651
652 let mut offset = 0;
654 while offset < cbor_bytes.len() {
655 let (key, value, new_offset) = self.parse_cbor_pair(cbor_bytes, offset)?;
656 offset = new_offset;
657
658 match key {
659 1 => {
660 if value.len() == WG_PUBKEY_LEN {
662 payload.wireguard_pubkey.copy_from_slice(&value);
663 }
664 }
665 2 => {
666 payload.did_q42 =
668 parse_did_q42(&value).map_err(|_| "Invalid did:q42 in CBOR-LD")?;
669 }
670 3 => {
671 payload.routing_mask = match value.len() {
673 1 => value[0] as u64,
674 2 => u16::from_be_bytes([value[0], value[1]]) as u64,
675 4 => {
676 u32::from_be_bytes([value[0], value[1], value[2], value[3]]) as u64
677 }
678 8 => u64::from_be_bytes([
679 value[0], value[1], value[2], value[3], value[4], value[5],
680 value[6], value[7],
681 ]),
682 _ if !value.is_empty() => {
683 let mut buf = [0u8; 8];
684 let len = value.len().min(8);
685 buf[8 - len..].copy_from_slice(&value[..len]);
686 u64::from_be_bytes(buf)
687 }
688 _ => 0,
689 };
690 }
691 4 => {
692 payload.peer_capabilities = u16::from_be_bytes([value[0], value[1]]);
694 }
695 5 => {
696 payload.semantic_context = u64::from_be_bytes([
698 value[0], value[1], value[2], value[3], value[4], value[5], value[6],
699 value[7],
700 ]);
701 }
702 _ => {} }
704 }
705
706 Ok(payload)
707 }
708
709 fn parse_cbor_pair(
711 &self,
712 cbor_bytes: &[u8],
713 offset: usize,
714 ) -> Result<(u64, Vec<u8>, usize), &'static str> {
715 if offset >= cbor_bytes.len() {
716 return Err("Invalid CBOR offset");
717 }
718
719 let first_byte = cbor_bytes[offset];
720 let major_type = first_byte >> 5;
721 let additional_info = first_byte & 0x1f;
722
723 let mut current_offset = offset + 1;
724
725 let key = if major_type == 0 {
727 let key_value = if additional_info < 24 {
729 additional_info as u64
730 } else if additional_info == 24 {
731 if current_offset < cbor_bytes.len() {
732 cbor_bytes[current_offset] as u64
733 } else {
734 return Err("Invalid CBOR key encoding");
735 }
736 } else {
737 return Err("Unsupported CBOR key encoding");
738 };
739 current_offset += 1;
740 key_value
741 } else {
742 return Err("CBOR key must be integer");
743 };
744
745 if current_offset >= cbor_bytes.len() {
747 return Err("Invalid CBOR value offset");
748 }
749
750 let value_first_byte = cbor_bytes[current_offset];
751 let value_major_type = value_first_byte >> 5;
752 let value_additional_info = value_first_byte & 0x1f;
753 current_offset += 1;
754
755 let value = if value_major_type == 2 {
756 let length = if value_additional_info < 24 {
758 value_additional_info as usize
759 } else if value_additional_info == 24 {
760 if current_offset < cbor_bytes.len() {
761 cbor_bytes[current_offset] as usize
762 } else {
763 return Err("Invalid CBOR length encoding");
764 }
765 } else {
766 return Err("Unsupported CBOR length encoding");
767 };
768 current_offset += 1;
769
770 if current_offset + length > cbor_bytes.len() {
771 return Err("CBOR value extends beyond buffer");
772 }
773
774 let value_bytes = cbor_bytes[current_offset..current_offset + length].to_vec();
775 current_offset += length;
776 value_bytes
777 } else {
778 return Err("CBOR value must be byte string");
779 };
780
781 Ok((key, value, current_offset))
782 }
783
784 pub fn establish_wireguard_tunnel(
786 &mut self,
787 peer_payload: &DnssecSemanticPayload,
788 endpoint: IpAddr,
789 port: u16,
790 ) -> Result<u64, &'static str> {
791 let wireguard_interface = self
792 .wireguard_interface
793 .as_mut()
794 .ok_or("WireGuard interface not initialized")?;
795
796 let peer_id = peer_payload.did_q42;
798 let peer = SocialWebNetPeer {
799 peer_id,
800 endpoint,
801 port,
802 pubkey: peer_payload.wireguard_pubkey,
803 allowed_ips: vec!["10.0.0.0/24".to_string()], routing_mask: peer_payload.routing_mask,
805 };
806
807 let pubkey_hex = hex::encode(&peer.pubkey);
809 let allowed_ips = peer.allowed_ips.join(",");
810
811 let output = Command::new("wg")
812 .args([
813 "set",
814 &wireguard_interface.interface_name,
815 "peer",
816 &pubkey_hex,
817 "endpoint",
818 &format!("{}:{}", endpoint, port),
819 "allowed-ip",
820 &allowed_ips,
821 ])
822 .output()
823 .map_err(|_| "WireGuard configuration failed")?;
824
825 if !output.status.success() {
826 return Err("Failed to configure WireGuard peer");
827 }
828
829 wireguard_interface.active_peers.insert(peer_id, peer);
831 wireguard_interface
832 .routing_table
833 .insert(format!("{}:{}", endpoint, port), peer_id);
834
835 Ok(peer_id)
836 }
837
838 pub fn bootstrap_social_wireguard(
840 &mut self,
841 domain: &str,
842 endpoint_ip: IpAddr,
843 endpoint_port: u16,
844 ) -> Result<u64, &'static str> {
845 let peer_payload = self.resolve_peer_dnssec_payload(domain)?;
847
848 if !self.verify_routing_constraints(&peer_payload, &self.local_permission)? {
850 return Err("Routing constraints not authorized");
851 }
852
853 let peer_id =
855 self.establish_wireguard_tunnel(&peer_payload, endpoint_ip, endpoint_port)?;
856
857 println!(
859 "[SocialWebNet] Bootstrapped peer {} (did:q42:{}) on {}:{}",
860 domain, peer_payload.did_q42, endpoint_ip, endpoint_port
861 );
862
863 Ok(peer_id)
864 }
865
866 fn verify_routing_constraints(
868 &self,
869 payload: &DnssecSemanticPayload,
870 local_compiled_permission: &crate::webizen_server::CompiledPermission,
871 ) -> Result<bool, &'static str> {
872 if local_compiled_permission.routing_mask == 0 {
874 return Err("Local routing mask is unconfigured (vacuous mask disallowed)");
875 }
876 if (payload.routing_mask & local_compiled_permission.routing_mask)
877 != local_compiled_permission.routing_mask
878 {
879 return Err("Failed ro:RightsOntology Fifth Vector hardware mask evaluation");
880 }
881 if payload.semantic_handshake.is_empty() {
882 return Err("Missing Semantic Handshake payload");
883 }
884 Ok(true)
885 }
886
887 pub fn parse_san_uri(&self, san_bytes: &[u8]) -> Result<u64, &'static str> {
889 if san_bytes.starts_with(b"did:q42:") {
891 return parse_did_q42(san_bytes).map_err(|_| "Invalid did:q42 in SAN");
892 }
893
894 if san_bytes.starts_with(b"webizen://") {
896 let hash_part = &san_bytes[11..]; if hash_part.len() >= 32 {
899 let hash_bytes = &hash_part[..32];
901 let hash_u64 = u64::from_str_radix(
902 std::str::from_utf8(hash_bytes).map_err(|_| "Invalid webizen hash")?,
903 16,
904 )
905 .map_err(|_| "Invalid webizen hash format")?;
906 return Ok(hash_u64 | (1u64 << 63)); }
908 }
909
910 Err("Unsupported SAN URI format")
911 }
912
913 pub fn execute_tensor_contraction(
915 &self,
916 matrix_a: &[f32],
917 matrix_b: &[f32],
918 result: &mut [f32],
919 size: usize,
920 ) {
921 #[cfg(target_arch = "x86_64")]
926 if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {
927 unsafe {
930 tensor_contraction_avx2_fma(matrix_a, matrix_b, result, size);
931 }
932 crate::telemetry::SIEVE_OPS_COUNT.fetch_add(
933 (size * size * size) as usize,
934 std::sync::atomic::Ordering::Relaxed,
935 );
936 return;
937 }
938
939 for i in 0..size {
941 for j in 0..size {
942 for k in 0..size {
943 result[i * size + j] += matrix_a[i * size + k] * matrix_b[k * size + j];
944 }
945 }
946 }
947 }
948
949 pub fn execute_quantum_chemistry(&self, smiles: &str) -> Option<crate::NQuin> {
951 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(smiles);
952 let mut dft = crate::quantum_dft::ElectronDensity::new(mol.atoms.len().max(1));
953
954 let mut quins = Vec::new();
955 for _ in 0..mol.atoms.len() {
956 let mut q = crate::NQuin::default();
957 q.predicate = crate::q_hash("HAS_ELECTRON");
958 quins.push(q);
959 }
960
961 let energy = dft.calculate_ground_state_energy(&quins);
962 crate::telemetry::ATOMIC_FLOPS_COUNT
963 .fetch_add(50000, std::sync::atomic::Ordering::Relaxed);
964
965 let mut out_quin = crate::NQuin::default();
966 out_quin.subject = crate::q_hash(smiles);
967 out_quin.predicate = crate::q_hash("has_ground_state_energy");
968 out_quin.object = crate::frame_layout::pack_float_object(energy as f32);
969 Some(out_quin)
970 }
971 }
972
973 pub struct DaemonOrchestrator {
975 pub active_cells: Arc<Mutex<Vec<WorkerCell>>>,
976 pub isolate_a_tx: Option<Sender<NQuin>>,
977 pub isolate_b_rx: Option<Receiver<NQuin>>,
978 pub dnssec_trusted_anchors: HashMap<String, [u8; 32]>,
979 pub wireguard_interface_name: String,
980 pub wireguard_local_port: u16,
981 pub local_permission: crate::webizen_server::CompiledPermission,
982 pub principal_did: u64,
983 pub guardian_did: Option<u64>,
984 }
985
986 impl DaemonOrchestrator {
987 pub fn new() -> Self {
989 Self {
990 active_cells: Arc::new(Mutex::new(Vec::new())),
991 isolate_a_tx: None,
992 isolate_b_rx: None,
993 dnssec_trusted_anchors: HashMap::new(),
994 wireguard_interface_name: "qualia-wg0".to_string(),
995 wireguard_local_port: 51820,
996 local_permission: crate::webizen_server::CompiledPermission {
997 routing_mask: 0x01 << 61, semantic_handshake: "qualia:handshake:v1".to_string(),
999 is_permissive_commons: true,
1000 },
1001 principal_did: crate::q_hash("did:q42:local"),
1002 guardian_did: None,
1003 }
1004 }
1005
1006 pub fn configure_permissions(
1008 &mut self,
1009 permission: crate::webizen_server::CompiledPermission,
1010 principal_did: u64,
1011 guardian_did: Option<u64>,
1012 ) {
1013 self.local_permission = permission;
1014 self.principal_did = principal_did;
1015 self.guardian_did = guardian_did;
1016 }
1017
1018 pub fn configure_dnssec_anchors(&mut self, anchors: HashMap<String, [u8; 32]>) {
1020 self.dnssec_trusted_anchors = anchors;
1021 }
1022
1023 pub fn configure_wireguard(&mut self, interface_name: String, local_port: u16) {
1025 self.wireguard_interface_name = interface_name;
1026 self.wireguard_local_port = local_port;
1027 }
1028
1029 pub fn init_worker_cells_infrastructure(&self) {
1031 let mut cells = self.active_cells.lock().unwrap();
1032 for cell in cells.iter_mut() {
1033 cell.init_dnssec_resolver(self.dnssec_trusted_anchors.clone());
1034 cell.init_wireguard_interface(
1035 self.wireguard_interface_name.clone(),
1036 self.wireguard_local_port,
1037 );
1038 }
1039 }
1040
1041 pub fn bootstrap_peer_connection(
1046 &self,
1047 cell_id: usize,
1048 domain: &str,
1049 endpoint_ip: IpAddr,
1050 endpoint_port: u16,
1051 ) -> Result<u64, &'static str> {
1052 let payload = self.resolve_peer_dnssec(domain)?;
1054
1055 if !self.verify_routing_constraints(&payload, &self.local_permission)? {
1057 return Err("Routing constraints not authorized");
1058 }
1059
1060 let guardian_did = self.guardian_did.ok_or("Guardian DID not configured for peer authorization")?;
1062 let mut intent = crate::NQuin::default();
1063 intent.subject = self.principal_did;
1064 intent.predicate = crate::q_hash("q42:TrustGroup");
1065 intent.object = payload.did_q42;
1066
1067 let db = [intent];
1068 let mut prog = [0u8; 1024];
1069 prog[0] = crate::mini_parser::OP_EVAL_PERMIT;
1070 prog[1] = crate::mini_parser::OP_END;
1071
1072 let mut out = [crate::NQuin::default(); 1];
1073 let context = crate::webizen_bytecode::GuardianshipContext {
1074 principal_did: self.principal_did,
1075 guardian_did: Some(guardian_did),
1076 };
1077
1078 let is_authorized =
1079 crate::webizen_bytecode::execute_program(&prog, &db, &mut out, Some(&context))
1080 .is_ok();
1081
1082 if !is_authorized {
1083 return Err("Sentinel VM Gatekeeper: Peer relationship not authorized");
1084 }
1085
1086 use boringtun::noise::Tunn;
1088
1089 let mut raw_priv: [u8; 32] = rand::random();
1090 raw_priv[0] &= 248;
1092 raw_priv[31] &= 127;
1093 raw_priv[31] |= 64;
1094
1095 let local_private = boringtun::x25519::StaticSecret::from(raw_priv);
1096 let peer_public = boringtun::x25519::PublicKey::from(payload.wireguard_pubkey);
1097
1098 let _tunn = Tunn::new(local_private, peer_public, None, None, 0, None);
1099
1100 let peer_id = u64::from_le_bytes(payload.wireguard_pubkey[..8].try_into().unwrap());
1101
1102 {
1104 let mut cells = self
1105 .active_cells
1106 .lock()
1107 .map_err(|_| "active_cells lock poisoned")?;
1108 let cell = cells
1109 .iter_mut()
1110 .find(|c| c.cell_id == cell_id)
1111 .ok_or("Worker cell not found")?;
1112 if let Some(ref mut wg) = cell.wireguard_interface {
1113 let peer = SocialWebNetPeer {
1114 peer_id,
1115 endpoint: endpoint_ip,
1116 port: endpoint_port,
1117 pubkey: payload.wireguard_pubkey,
1118 allowed_ips: vec!["0.0.0.0/0".to_string()],
1119 routing_mask: payload.routing_mask,
1120 };
1121 wg.active_peers.insert(peer_id, peer);
1122 wg.routing_table.insert(endpoint_ip.to_string(), peer_id);
1123 }
1124 }
1125
1126 println!(
1127 "[SocialWebNet] Cell {} bootstrapped peer {} (did:q42:{}) at {}:{}",
1128 cell_id, domain, payload.did_q42, endpoint_ip, endpoint_port
1129 );
1130
1131 Ok(peer_id)
1132 }
1133
1134 pub fn spawn_fractal_shard(&self, cell_id: usize) {
1136 let mut cells = self.active_cells.lock().unwrap();
1137 cells.push(WorkerCell::new(cell_id));
1138 }
1139
1140 pub fn delegate_dense_algebra(&self, cell_id: usize) {
1142 let cells = self.active_cells.clone();
1144 thread::spawn(move || {
1145 let mut locked_cells = cells.lock().unwrap();
1146 if let Some(cell) = locked_cells.iter_mut().find(|c| c.cell_id == cell_id) {
1147 let mut res = vec![0.0; 4];
1148 cell.execute_tensor_contraction(
1149 &[1.0, 2.0, 3.0, 4.0],
1150 &[1.0, 0.0, 0.0, 1.0],
1151 &mut res,
1152 2,
1153 );
1154 }
1155 });
1156 }
1157
1158 pub fn bootstrap_social_wireguard(
1160 &mut self,
1161 domain: &str,
1162 endpoint_ip: IpAddr,
1163 endpoint_port: u16,
1164 ) -> Result<u64, &'static str> {
1165 let peer_payload = self.resolve_peer_dnssec(domain)?;
1167
1168 if !self.verify_routing_constraints(&peer_payload, &self.local_permission)? {
1170 return Err("Routing constraints not authorized");
1171 }
1172
1173 let peer_id =
1175 self.establish_wireguard_tunnel(&peer_payload, endpoint_ip, endpoint_port)?;
1176
1177 println!(
1179 "[SocialWebNet] Bootstrapped peer {} (did:q42:{}) on {}:{}",
1180 domain, peer_payload.did_q42, endpoint_ip, endpoint_port
1181 );
1182
1183 Ok(peer_id)
1184 }
1185
1186 fn verify_routing_constraints(
1188 &self,
1189 payload: &DnssecSemanticPayload,
1190 local_compiled_permission: &crate::webizen_server::CompiledPermission,
1191 ) -> Result<bool, &'static str> {
1192 if local_compiled_permission.routing_mask == 0 {
1194 return Err("Local routing mask is unconfigured (vacuous mask disallowed)");
1195 }
1196 if (payload.routing_mask & local_compiled_permission.routing_mask)
1197 != local_compiled_permission.routing_mask
1198 {
1199 return Err("Failed ro:RightsOntology Fifth Vector hardware mask evaluation");
1200 }
1201 if payload.semantic_handshake.is_empty() {
1202 return Err("Missing Semantic Handshake payload");
1203 }
1204 Ok(true)
1205 }
1206
1207 pub fn spawn_neuro_symbolic_isolates(&mut self) {
1209 let (tx_ab, rx_ab) = bounded::<NQuin>(SPSC_BUFFER_CAPACITY); let (tx_ba, rx_ba) = bounded::<NQuin>(SPSC_BUFFER_CAPACITY); self.isolate_a_tx = Some(tx_ab);
1214 self.isolate_b_rx = Some(rx_ba);
1215
1216 thread::spawn(move || {
1218 println!("[Isolate B] Neural Bridge online. Awaiting prompt constraints...");
1219 while let Ok(prompt_quin) = rx_ab.recv() {
1220 crate::telemetry::SIEVE_OPS_COUNT
1221 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1222
1223 let result_quin = match crate::services::swarm::isolate_b_compute(prompt_quin) {
1227 Some(q) => q,
1228 None => continue, };
1230
1231 if tx_ba.send(result_quin).is_err() {
1232 break;
1233 }
1234 }
1235 });
1236 }
1237
1238 pub fn create_wireguard_interface(&self) -> Result<(), &'static str> {
1240 let output = Command::new("wg")
1241 .args([
1242 "quick",
1243 &self.wireguard_interface_name,
1244 "listen-port",
1245 &self.wireguard_local_port.to_string(),
1246 ])
1247 .output()
1248 .map_err(|_| "Failed to create WireGuard interface")?;
1249
1250 if !output.status.success() {
1251 return Err("Failed to create WireGuard interface");
1252 }
1253
1254 println!(
1255 "[DaemonOrchestrator] Created WireGuard interface {} on port {}",
1256 self.wireguard_interface_name, self.wireguard_local_port
1257 );
1258
1259 Ok(())
1260 }
1261
1262 pub fn get_active_peers(&self) -> Result<Vec<(u64, String)>, &'static str> {
1264 let output = Command::new("wg")
1265 .args(["show", &self.wireguard_interface_name])
1266 .output()
1267 .map_err(|_| "Failed to get WireGuard status")?;
1268
1269 if !output.status.success() {
1270 return Err("Failed to get WireGuard status");
1271 }
1272
1273 let mut peers = Vec::new();
1274 let output_str = String::from_utf8_lossy(&output.stdout);
1275
1276 for line in output_str.lines() {
1278 if line.starts_with("peer:") {
1279 let parts: Vec<&str> = line.split_whitespace().collect();
1280 if parts.len() >= 2 {
1281 let pubkey = parts[1];
1282 if let Ok(pubkey_bytes) = hex::decode(pubkey) {
1283 if pubkey_bytes.len() == 32 {
1284 let mut peer_id = [0u8; 32];
1285 peer_id.copy_from_slice(&pubkey_bytes);
1286 let peer_id_u64 = u64::from_be_bytes([
1287 peer_id[0], peer_id[1], peer_id[2], peer_id[3], peer_id[4],
1288 peer_id[5], peer_id[6], peer_id[7],
1289 ]);
1290 peers.push((peer_id_u64, pubkey.to_string()));
1291 }
1292 }
1293 }
1294 }
1295 }
1296
1297 Ok(peers)
1298 }
1299
1300 fn resolve_peer_dnssec(&self, domain: &str) -> Result<DnssecSemanticPayload, &'static str> {
1307 if let Ok(cells) = self.active_cells.lock() {
1309 for cell in cells.iter() {
1310 if let Some(ref resolver) = cell.dnssec_resolver {
1311 if let Some(cached) = resolver.cache.get(domain) {
1312 return Ok(cached.clone());
1313 }
1314 }
1315 }
1316 }
1317
1318 let qname = format!("_q42peer._tcp.{}", domain.trim_end_matches('.'));
1320 let resolver =
1321 crate::net::dns::QualiaDnsResolver::new(crate::net::dns::ResolverConfig::default());
1322 let socket =
1323 std::net::UdpSocket::bind("0.0.0.0:0").map_err(|_| "socket bind failed")?;
1324 socket
1325 .set_read_timeout(Some(std::time::Duration::from_millis(
1326 resolver.config.timeout_ms,
1327 )))
1328 .map_err(|_| "timeout failed")?;
1329
1330 let mut tx_buf = [0u8; 512];
1331 let tx_len = crate::net::dns::wire::build_query_packet(
1332 0x4250,
1333 &qname,
1334 crate::net::dns::wire::DnsType::TXT,
1335 true,
1336 &mut tx_buf,
1337 )
1338 .map_err(|_| "failed to build query")?;
1339
1340 socket
1341 .send_to(&tx_buf[..tx_len], resolver.config.nameserver)
1342 .map_err(|_| "DNS send failed")?;
1343
1344 let mut rx_buf = [0u8; 4096];
1345 let (rx_len, _) = socket
1346 .recv_from(&mut rx_buf)
1347 .map_err(|_| "DNS recv failed")?;
1348
1349 let mut found_payload = None;
1350 let header = crate::net::dns::wire::DnsHeader::decode(&rx_buf[..rx_len])
1351 .map_err(|_| "invalid DNS header")?;
1352
1353 if header.rcode() == 0 {
1354 let mut offset = crate::net::dns::wire::DnsHeader::SIZE;
1355 let mut dummy = [0u8; 256];
1356 for _ in 0..header.qdcount {
1357 let (new_off, _) = crate::net::dns::wire::decode_domain_name(
1358 &rx_buf[..rx_len],
1359 offset,
1360 &mut dummy,
1361 )
1362 .map_err(|_| "invalid qname")?;
1363 offset = new_off + 4;
1364 }
1365
1366 let _ = crate::net::dns::wire::parse_records(
1367 &rx_buf[..rx_len],
1368 offset,
1369 header.ancount as usize,
1370 |_name, rec| {
1371 if rec.rtype == crate::net::dns::wire::DnsType::TXT
1372 && found_payload.is_none()
1373 {
1374 let mut cursor = 0;
1375 while cursor < rec.rdata.len() {
1376 let seg_len = rec.rdata[cursor] as usize;
1377 cursor += 1;
1378 if cursor + seg_len > rec.rdata.len() {
1379 break;
1380 }
1381 let part = &rec.rdata[cursor..cursor + seg_len];
1382 if part.len() >= 51 {
1383 let mut wg_pubkey = [0u8; 32];
1384 wg_pubkey.copy_from_slice(&part[..32]);
1385
1386 let did_q42 =
1387 u64::from_le_bytes(part[32..40].try_into().unwrap());
1388 let routing_mask = part[40] as u64;
1389 let peer_capabilities =
1390 u16::from_le_bytes(part[41..43].try_into().unwrap());
1391 let semantic_context =
1392 u64::from_le_bytes(part[43..51].try_into().unwrap());
1393
1394 found_payload = Some(DnssecSemanticPayload {
1395 wireguard_pubkey: wg_pubkey,
1396 did_q42,
1397 routing_mask,
1398 semantic_handshake: "Legacy Proof".to_string(),
1399 peer_capabilities,
1400 semantic_context,
1401 });
1402 break;
1403 }
1404 cursor += seg_len;
1405 }
1406 }
1407 Ok(())
1408 },
1409 );
1410 }
1411
1412 if let Some(payload) = found_payload {
1413 if let Ok(mut cells) = self.active_cells.lock() {
1415 for cell in cells.iter_mut() {
1416 if let Some(ref mut r) = cell.dnssec_resolver {
1417 r.cache.insert(domain.to_string(), payload.clone());
1418 break;
1419 }
1420 }
1421 }
1422 return Ok(payload);
1423 }
1424
1425 Err("No valid Qualia semantic payload in DNS TXT records")
1426 }
1427
1428 fn establish_wireguard_tunnel(
1434 &mut self,
1435 payload: &DnssecSemanticPayload,
1436 ip: IpAddr,
1437 port: u16,
1438 ) -> Result<u64, &'static str> {
1439 use boringtun::noise::Tunn;
1440
1441 let mut raw_priv: [u8; 32] = rand::random();
1443 raw_priv[0] &= 248;
1445 raw_priv[31] &= 127;
1446 raw_priv[31] |= 64;
1447
1448 let local_private = boringtun::x25519::StaticSecret::from(raw_priv);
1450 let peer_public = boringtun::x25519::PublicKey::from(payload.wireguard_pubkey);
1451
1452 let _tunn = Tunn::new(local_private, peer_public, None, None, 0, None);
1454
1455 let peer_id = u64::from_le_bytes(payload.wireguard_pubkey[..8].try_into().unwrap());
1457
1458 if let Ok(mut cells) = self.active_cells.lock() {
1460 for cell in cells.iter_mut() {
1461 if let Some(ref mut wg) = cell.wireguard_interface {
1462 let peer = SocialWebNetPeer {
1463 peer_id,
1464 endpoint: ip,
1465 port,
1466 pubkey: payload.wireguard_pubkey,
1467 allowed_ips: vec!["0.0.0.0/0".to_string()],
1468 routing_mask: payload.routing_mask,
1469 };
1470 wg.active_peers.insert(peer_id, peer);
1471 wg.routing_table.insert(ip.to_string(), peer_id);
1472 break;
1473 }
1474 }
1475 }
1476
1477 Ok(peer_id)
1478 }
1479
1480 pub fn compute_agent_priority(&self, windowed_faults: u32, usury_event: bool) -> u64 {
1482 compute_priority(windowed_faults, usury_event)
1483 }
1484
1485 pub fn rank_agent_candidates(candidates: &mut [AgentComputeCandidate]) {
1488 candidates.sort_by(|a, b| b.priority().cmp(&a.priority()));
1489 }
1490
1491 pub fn route_agent_task(candidates: &[AgentComputeCandidate]) -> Option<u64> {
1494 candidates
1495 .iter()
1496 .map(|c| (c.agent_did_hash, c.priority()))
1497 .filter(|&(_, p)| p > 0)
1498 .max_by_key(|&(_, p)| p)
1499 .map(|(did, _)| did)
1500 }
1501 }
1502
1503 #[cfg(test)]
1504 mod tests {
1505 use super::*;
1506
1507 fn cell_with_resolver() -> WorkerCell {
1508 let mut cell = WorkerCell::new(0);
1509 cell.init_dnssec_resolver(HashMap::new());
1510 cell
1511 }
1512
1513 #[test]
1514 fn resolve_peer_returns_endpoint_and_caches() {
1515 let mut cell = cell_with_resolver();
1516
1517 let endpoint = cell
1520 .resolve_peer_dnssec("peer.example.com")
1521 .expect("fallback resolution should succeed");
1522
1523 assert_eq!(endpoint.port, DEFAULT_PEER_PORT);
1524 assert!(!endpoint.verified);
1526 let again = cell
1528 .resolve_peer_dnssec("peer.example.com")
1529 .expect("cached resolution should succeed");
1530 assert_eq!(endpoint.address, again.address);
1531 assert_eq!(endpoint.port, again.port);
1532 assert_eq!(cell.dnssec_cache_size(), 1);
1534 }
1535
1536 #[test]
1537 fn resolve_peer_uses_cache_on_second_call() {
1538 let mut cell = cell_with_resolver();
1539
1540 let first = cell
1541 .resolve_peer_dnssec("cache.example.com")
1542 .expect("resolution should succeed");
1543 assert_eq!(cell.dnssec_cache_size(), 1);
1544
1545 let second = cell
1546 .resolve_peer_dnssec("cache.example.com")
1547 .expect("cached resolution should succeed");
1548
1549 assert_eq!(first, second);
1551 assert_eq!(cell.dnssec_cache_size(), 1);
1552 }
1553
1554 #[test]
1555 fn set_and_get_peer_capabilities() {
1556 let mut cell = cell_with_resolver();
1557
1558 assert_eq!(cell.get_peer_capabilities("did:q42:abc"), None);
1559
1560 cell.set_peer_capabilities("did:q42:abc", 0b1010);
1561 assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1010));
1562
1563 cell.set_peer_capabilities("did:q42:abc", 0b1111);
1565 assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1111));
1566
1567 cell.set_peer_capabilities("did:q42:def", 0b1);
1569 assert_eq!(cell.get_peer_capabilities("did:q42:def"), Some(0b1));
1570 assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1111));
1571 }
1572
1573 #[test]
1574 fn set_and_get_semantic_context() {
1575 let mut cell = cell_with_resolver();
1576
1577 assert_eq!(cell.get_semantic_context("did:q42:ctx"), None);
1578
1579 cell.set_semantic_context("did:q42:ctx", 0xC0FFEE);
1580 assert_eq!(cell.get_semantic_context("did:q42:ctx"), Some(0xC0FFEE));
1581
1582 cell.set_semantic_context("did:q42:ctx", 0x1234_5678);
1583 assert_eq!(cell.get_semantic_context("did:q42:ctx"), Some(0x1234_5678));
1584 }
1585
1586 #[test]
1587 fn clear_dnssec_cache_empties_entries() {
1588 let mut cell = cell_with_resolver();
1589
1590 cell.resolve_peer_dnssec("a.example.com").unwrap();
1591 cell.resolve_peer_dnssec("b.example.com").unwrap();
1592 assert_eq!(cell.dnssec_cache_size(), 2);
1593
1594 cell.clear_dnssec_cache();
1595 assert_eq!(cell.dnssec_cache_size(), 0);
1596
1597 cell.resolve_peer_dnssec("a.example.com").unwrap();
1599 assert_eq!(cell.dnssec_cache_size(), 1);
1600 }
1601
1602 #[test]
1603 fn cached_peer_ttl_freshness() {
1604 let endpoint = PeerEndpoint {
1605 address: IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, 1)),
1606 port: 51820,
1607 verified: true,
1608 timestamp: 1000,
1609 };
1610 let cached = CachedPeer {
1611 endpoint,
1612 cached_at: 1000,
1613 ttl_seconds: 300,
1614 };
1615 assert!(cached.is_fresh(1100));
1616 assert!(cached.is_fresh(1299));
1617 assert!(!cached.is_fresh(1300));
1618 assert!(!cached.is_fresh(2000));
1619 }
1620
1621 #[test]
1622 fn parse_cbor_ld_to_quin_chunks_data() {
1623 let cell = cell_with_resolver();
1624
1625 let res = cell.parse_cbor_ld_to_quin(&[0x01, 0x02, 0x03]);
1627 assert_eq!(res.err(), Some(DaemonError::CborLdParsingFailed));
1628
1629 let res = cell.parse_cbor_ld_to_quin(&[]);
1631 assert_eq!(res.err(), Some(DaemonError::CborLdParsingFailed));
1632 }
1633
1634 #[test]
1635 fn domain_to_ip_is_deterministic() {
1636 let a = domain_to_ip("peer.example.com", 0);
1637 let b = domain_to_ip("peer.example.com", 0);
1638 assert_eq!(a, b);
1639
1640 let c = domain_to_ip("other.example.com", 0);
1642 assert_ne!(a, c);
1643
1644 let d = domain_to_ip("peer.example.com", 1);
1646 assert_ne!(a, d);
1647
1648 if let IpAddr::V4(v4) = a {
1650 assert_eq!(v4.octets()[0], 10);
1651 } else {
1652 panic!("expected IPv4 from domain_to_ip");
1653 }
1654 }
1655
1656 #[test]
1657 fn agent_compute_priority_governance_routing() {
1658 let orchestrator = DaemonOrchestrator::new();
1659
1660 let clean_agent = AgentComputeCandidate::new(0x1001, 0, false);
1662 assert_eq!(
1663 clean_agent.priority(),
1664 crate::governance::coordination::PRIORITY_BASE
1665 );
1666 assert_eq!(
1667 orchestrator.compute_agent_priority(0, false),
1668 crate::governance::coordination::PRIORITY_BASE
1669 );
1670
1671 let faulted_agent = AgentComputeCandidate::new(0x1002, 1, false);
1673 assert_eq!(faulted_agent.priority(), 5000);
1674
1675 let usury_agent = AgentComputeCandidate::new(0x1003, 0, true);
1677 assert_eq!(usury_agent.priority(), 0);
1678 assert_eq!(orchestrator.compute_agent_priority(0, true), 0);
1679
1680 let mut candidates = vec![
1682 faulted_agent.clone(),
1683 usury_agent.clone(),
1684 clean_agent.clone(),
1685 ];
1686 DaemonOrchestrator::rank_agent_candidates(&mut candidates);
1687 assert_eq!(candidates[0].agent_did_hash, 0x1001); assert_eq!(candidates[1].agent_did_hash, 0x1002); assert_eq!(candidates[2].agent_did_hash, 0x1003); let chosen = DaemonOrchestrator::route_agent_task(&candidates);
1693 assert_eq!(chosen, Some(0x1001));
1694
1695 let all_usury = vec![
1697 AgentComputeCandidate::new(0x2001, 0, true),
1698 AgentComputeCandidate::new(0x2002, 2, true),
1699 ];
1700 assert_eq!(DaemonOrchestrator::route_agent_task(&all_usury), None);
1701 }
1702 }
1703}