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    pub fn new() -> Self {
12        Self {
13            trusted_groups: Arc::new(DashMap::new()),
14        }
15    }
16
17    /// Hydrates trusted groups from the `.q42` database slice using the zero-allocation VM.
18    pub fn hydrate_from_db(&self, db: &[crate::NQuin]) {
19        let mut program = [0u8; 1024];
20        // Compile a query for all Quins declaring a TrustGroup
21        if crate::mini_parser::compile_ntriples_to_bytecode(
22            b"?group <q42:isTrustedGroup> ?key .",
23            &mut program,
24        )
25        .is_ok()
26        {
27            let mut out = vec![crate::NQuin::default(); 128]; // Stack allocation alternative for demo, bounded
28            if let Ok((match_count, _)) =
29                crate::webizen_bytecode::execute_program(&program, db, &mut out, None)
30            {
31                for quin in &out[..match_count] {
32                    let group_hash = quin.subject.to_le_bytes();
33                    // Derive a dummy 32-byte VerifyingKey from the object hash since NQuin is 64-bit bounded
34                    // In full production, this would resolve via `did:q42` hardware pointer to the 32-byte blob.
35                    let mut key_bytes = [0u8; 32];
36                    key_bytes[0..8].copy_from_slice(&quin.object.to_le_bytes());
37                    if let Ok(public_key) = VerifyingKey::from_bytes(&key_bytes) {
38                        self.add_trusted_group(group_hash, public_key);
39                    }
40                }
41            }
42        }
43    }
44
45    /// Add a trusted Group DID to the memory cache
46    pub fn add_trusted_group(&self, group_hash: [u8; 8], public_key: VerifyingKey) {
47        self.trusted_groups.insert(group_hash, public_key);
48    }
49
50    /// Verifies if a semantic route is authorized by a Trusted Group Verifiable Credential.
51    /// Operates in O(1) memory lookup time. Instantly drops if group is unknown.
52    pub fn is_authorized(
53        &self,
54        group_hash: &[u8; 8],
55        quin_bytes: &[u8],
56        signature_bytes: &[u8; 64],
57    ) -> bool {
58        if let Some(public_key) = self.trusted_groups.get(group_hash) {
59            // Fast-path cryptographic verification
60            if let Ok(sig) = Signature::from_slice(signature_bytes) {
61                return public_key.verify(quin_bytes, &sig).is_ok();
62            }
63        }
64        false
65    }
66}