Skip to main content

qualia_core_db/p2p/
routing.rs

1use dashmap::DashMap;
2use ed25519_dalek::{Signature, Verifier, VerifyingKey};
3use std::sync::Arc;
4
5pub struct CivicsRoutingTable {
6    // Maps the 8-byte hash of the Group DID to its 32-byte Ed25519 Public Key
7    trusted_groups: Arc<DashMap<[u8; 8], VerifyingKey>>,
8}
9
10impl CivicsRoutingTable {
11    /// Creates a default `CivicsRoutingTable`.
12    pub fn new() -> Self {
13        Self {
14            trusted_groups: Arc::new(DashMap::new()),
15        }
16    }
17
18    /// Hydrates trusted groups from the `.q42` database slice using the zero-allocation VM.
19    pub fn hydrate_from_db(&self, db: &[crate::NQuin]) {
20        let mut program = [0u8; 1024];
21        // Compile a query for all Quins declaring a TrustGroup
22        if crate::mini_parser::compile_ntriples_to_bytecode(
23            b"?group <q42:isTrustedGroup> ?key .",
24            &mut program,
25        )
26        .is_ok()
27        {
28            let mut out = vec![crate::NQuin::default(); 128]; // Stack allocation alternative for demo, bounded
29            if let Ok((match_count, _)) =
30                crate::webizen_bytecode::execute_program(&program, db, &mut out, None)
31            {
32                for quin in &out[..match_count] {
33                    let group_hash = quin.subject.to_le_bytes();
34                    let mut key_bytes = [0u8; 32];
35                    let mut found_chunks = false;
36
37                    // Look for 4 sequential 8-byte key chunks in DB for this subject
38                    let chunk0_pred = crate::q_hash("q42:keyChunk0");
39                    let chunk1_pred = crate::q_hash("q42:keyChunk1");
40                    let chunk2_pred = crate::q_hash("q42:keyChunk2");
41                    let chunk3_pred = crate::q_hash("q42:keyChunk3");
42
43                    let mut c0 = None;
44                    let mut c1 = None;
45                    let mut c2 = None;
46                    let mut c3 = None;
47
48                    for q in db {
49                        if q.subject == quin.subject {
50                            if q.predicate == chunk0_pred { c0 = Some(q.object.to_le_bytes()); }
51                            else if q.predicate == chunk1_pred { c1 = Some(q.object.to_le_bytes()); }
52                            else if q.predicate == chunk2_pred { c2 = Some(q.object.to_le_bytes()); }
53                            else if q.predicate == chunk3_pred { c3 = Some(q.object.to_le_bytes()); }
54                        }
55                    }
56
57                    if let (Some(b0), Some(b1), Some(b2), Some(b3)) = (c0, c1, c2, c3) {
58                        key_bytes[0..8].copy_from_slice(&b0);
59                        key_bytes[8..16].copy_from_slice(&b1);
60                        key_bytes[16..24].copy_from_slice(&b2);
61                        key_bytes[24..32].copy_from_slice(&b3);
62                        found_chunks = true;
63                    }
64
65                    if found_chunks {
66                        if let Ok(public_key) = VerifyingKey::from_bytes(&key_bytes) {
67                            self.add_trusted_group(group_hash, public_key);
68                        } else {
69                            log::warn!("Invalid 32-byte Ed25519 key for trusted group {:x?}", group_hash);
70                        }
71                    } else {
72                        // Fail closed: do not fabricate a 32-byte key with zero-padding
73                        log::debug!("Trusted group {:x?} has no complete 32-byte public key chunks", group_hash);
74                    }
75                }
76            }
77        }
78    }
79
80    /// Add a trusted Group DID to the memory cache
81    pub fn add_trusted_group(&self, group_hash: [u8; 8], public_key: VerifyingKey) {
82        self.trusted_groups.insert(group_hash, public_key);
83    }
84
85    /// Verifies if a semantic route is authorized by a Trusted Group Verifiable Credential.
86    /// Operates in O(1) memory lookup time. Instantly drops if group is unknown.
87    pub fn is_authorized(
88        &self,
89        group_hash: &[u8; 8],
90        quin_bytes: &[u8],
91        signature_bytes: &[u8; 64],
92    ) -> bool {
93        if let Some(public_key) = self.trusted_groups.get(group_hash) {
94            // Fast-path cryptographic verification
95            if let Ok(sig) = Signature::from_slice(signature_bytes) {
96                return public_key.verify(quin_bytes, &sig).is_ok();
97            }
98        }
99        false
100    }
101}