clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::collections::HashMap;
use std::net::UdpSocket;
use std::path::Path;
use std::fs;
use std::time::{Duration, Instant};
use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo};
use serde::{Serialize, Deserialize};
use ed25519_dalek::{VerifyingKey, SigningKey, Verifier, Signature, Signer};
use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};


// Structure matching JavaScript peer export
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PeerInfo {
    pub name: String,
    pub ip: String,
    pub port: u16,
    pub did: String,
    pub capabilities: Vec<String>,
    pub protocol: String,
    #[serde(rename = "discoveredAt")]
    pub discovered_at: String,
    /// WireGuard public key (hex-encoded X25519 public key).
    /// Present when the peer announces WireGuard support via mDNS.
    /// `None` for peers that don't support WireGuard (backward compatible).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wg_public_key: Option<String>,
}

pub struct DiscoveryEngine {
    pub service_type: String,
}

impl Default for DiscoveryEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl DiscoveryEngine {
    pub fn new() -> Self {
        Self {
            service_type: "_pkc._tcp.local.".to_string(),
        }
    }

    pub fn get_local_ip() -> String {
        if let Ok(socket) = UdpSocket::bind("0.0.0.0:0")
            && socket.connect("8.8.8.8:80").is_ok()
                && let Ok(addr) = socket.local_addr() {
                    return addr.ip().to_string();
                }
        "127.0.0.1".to_string()
    }

    pub fn announce(&self, service_name: &str, did: &str, port: u16) -> Result<(), String> {
        self.announce_with_wireguard(service_name, did, port, None)
    }

    /// Announce the PKC service with a WireGuard public key.
    ///
    /// In addition to the standard mDNS properties (did, version, capabilities, protocol),
    /// this includes `wg_public_key` so peers can establish WireGuard-encrypted tunnels.
    pub fn announce_with_wireguard(
        &self,
        service_name: &str,
        did: &str,
        port: u16,
        wg_public_key: Option<&str>,
    ) -> Result<(), String> {
        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
        let local_ip = Self::get_local_ip();

        let host_name = format!("{}.local.", service_name);
        let mut properties = HashMap::new();
        properties.insert("did".to_string(), did.to_string());
        properties.insert("version".to_string(), "1.0".to_string());
        properties.insert("capabilities".to_string(), "s3_access,ipfs_access,webrtc_relay".to_string());
        properties.insert("protocol".to_string(), "challenge-response".to_string());
        if let Some(wg_key) = wg_public_key {
            properties.insert("wg_public_key".to_string(), wg_key.to_string());
        }

        let service_info = ServiceInfo::new(
            &self.service_type,
            service_name,
            &host_name,
            &local_ip,
            port,
            properties,
        )
        .map_err(|e| format!("Failed to create ServiceInfo: {}", e))?
        .enable_addr_auto();

        mdns.register(service_info).map_err(|e| format!("Failed to register service: {}", e))?;

        println!("[mDNS PKC] ✅ Announced service: {} on port {}", service_name, port);
        println!("[mDNS PKC]    IPs: {}", local_ip);
        println!("[mDNS PKC]    DID: {}", did);

        // Keep running to maintain registration
        loop {
            std::thread::sleep(Duration::from_secs(10));
        }
    }

    pub fn discover(&self, timeout: Duration) -> Result<Vec<PeerInfo>, String> {
        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
        let receiver = mdns.browse(&self.service_type).map_err(|e| format!("Failed to browse: {}", e))?;

        println!("[mDNS PKC] 🔍 Discovering PKC peers on network...");

        let start_time = Instant::now();
        let mut discovered_peers: HashMap<String, PeerInfo> = HashMap::new();

        while start_time.elapsed() < timeout {
            let remaining = timeout.saturating_sub(start_time.elapsed());
            if remaining.is_zero() {
                break;
            }

            if let Ok(event) = receiver.recv_timeout(remaining)
                && let ServiceEvent::ServiceResolved(info) = event {
                    let name = info.get_fullname().to_string();
                    let port = info.get_port();
                    
                    let props = info.get_properties();
                    let did = props.get_property_val_str("did").unwrap_or("unknown").to_string();
                    let capabilities = props.get_property_val_str("capabilities")
                        .map(|s| s.split(',').map(|x| x.to_string()).collect())
                        .unwrap_or_else(Vec::new);
                    let protocol = props.get_property_val_str("protocol").unwrap_or("unknown").to_string();


                    let wg_public_key = props.get_property_val_str("wg_public_key").map(|s| s.to_string());

                    for ip_addr in info.get_addresses() {
                        let ip = ip_addr.to_string();
                        let peer_id = format!("{}:{}", ip, port);
                        
                        // Check skip self if we knew ours, but we just list all non-self or all discovered
                        discovered_peers.insert(peer_id, PeerInfo {
                            name: name.clone(),
                            ip,
                            port,
                            did: did.clone(),
                            capabilities: capabilities.clone(),
                            protocol: protocol.clone(),
                            discovered_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
                            wg_public_key: wg_public_key.clone(),
                        });
                    }
                }
        }

        let peers: Vec<PeerInfo> = discovered_peers.into_values().collect();
        Ok(peers)
    }

    /// Announce the PKC service asynchronously with structured cancellation.
    pub async fn announce_with_cancellation(
        &self,
        service_name: &str,
        did: &str,
        port: u16,
        wg_public_key: Option<&str>,
        token: tokio_util::sync::CancellationToken,
    ) -> Result<(), String> {
        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
        let local_ip = Self::get_local_ip();

        let host_name = format!("{}.local.", service_name);
        let mut properties = HashMap::new();
        properties.insert("did".to_string(), did.to_string());
        properties.insert("version".to_string(), "1.0".to_string());
        properties.insert("capabilities".to_string(), "s3_access,ipfs_access,webrtc_relay".to_string());
        properties.insert("protocol".to_string(), "challenge-response".to_string());
        if let Some(wg_key) = wg_public_key {
            properties.insert("wg_public_key".to_string(), wg_key.to_string());
        }

        let service_info = ServiceInfo::new(
            &self.service_type,
            service_name,
            &host_name,
            &local_ip,
            port,
            properties,
        )
        .map_err(|e| format!("Failed to create ServiceInfo: {}", e))?
        .enable_addr_auto();

        mdns.register(service_info).map_err(|e| format!("Failed to register service: {}", e))?;

        // Gracefully wait until token cancellation
        tokio::select! {
            _ = token.cancelled() => {
                let _ = mdns.shutdown();
                Ok(())
            }
        }
    }

    /// Discover PKC peers asynchronously with structured cancellation.
    pub async fn discover_with_cancellation(
        &self,
        timeout: Duration,
        token: tokio_util::sync::CancellationToken,
    ) -> Result<Vec<PeerInfo>, String> {
        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
        let receiver = mdns.browse(&self.service_type).map_err(|e| format!("Failed to browse: {}", e))?;

        let start_time = Instant::now();
        let mut discovered_peers: HashMap<String, PeerInfo> = HashMap::new();

        while start_time.elapsed() < timeout && !token.is_cancelled() {
            let remaining = timeout.saturating_sub(start_time.elapsed());
            if remaining.is_zero() {
                break;
            }

            let step = remaining.min(Duration::from_millis(50));
            tokio::select! {
                _ = token.cancelled() => break,
                res = tokio::task::spawn_blocking({
                    let receiver = receiver.clone();
                    move || receiver.recv_timeout(step)
                }) => {
                    if let Ok(Ok(event)) = res
                        && let ServiceEvent::ServiceResolved(info) = event {
                            let name = info.get_fullname().to_string();
                            let port = info.get_port();
                            let props = info.get_properties();
                            let did = props.get_property_val_str("did").unwrap_or("unknown").to_string();
                            let capabilities = props.get_property_val_str("capabilities")
                                .map(|s| s.split(',').map(|x| x.to_string()).collect())
                                .unwrap_or_else(Vec::new);
                            let protocol = props.get_property_val_str("protocol").unwrap_or("unknown").to_string();
                            let wg_public_key = props.get_property_val_str("wg_public_key").map(|s| s.to_string());

                            for ip_addr in info.get_addresses() {
                                let ip = ip_addr.to_string();
                                let peer_id = format!("{}:{}", ip, port);
                                discovered_peers.insert(peer_id, PeerInfo {
                                    name: name.clone(),
                                    ip,
                                    port,
                                    did: did.clone(),
                                    capabilities: capabilities.clone(),
                                    protocol: protocol.clone(),
                                    discovered_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
                                    wg_public_key: wg_public_key.clone(),
                                });
                            }
                        }
                }
            }
        }

        let _ = mdns.shutdown();
        let peers: Vec<PeerInfo> = discovered_peers.into_values().collect();
        Ok(peers)
    }
}

// Helpers for Hex Encoding/Decoding
pub fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
    if !s.len().is_multiple_of(2) {
        return Err("Hex string must have an even length".to_string());
    }
    (0..s.len())
        .step_by(2)
        .map(|i| {
            u8::from_str_radix(&s[i..i + 2], 16)
                .map_err(|e| format!("Invalid hex digit: {}", e))
        })
        .collect()
}

pub fn encode_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

// SQLite / Agent Card parser structs
#[derive(Deserialize, Debug)]
pub struct AgentCard {
    pub public_key: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
}

pub fn get_agent_card_from_db(db_path: &str, did: &str) -> Result<Option<AgentCard>, String> {
    if !Path::new(db_path).exists() {
        return Err(format!("Database file not found at: {}", db_path));
    }
    let conn = rusqlite::Connection::open(db_path)
        .map_err(|e| format!("Failed to open agent identity DB: {}", e))?;
    
    let content_opt = crate::layer2::record_store::read_handle_text(&conn, did)
        .map_err(|error| error.to_string())?;

    if let Some(content) = content_opt {
        let card: AgentCard = serde_yaml::from_str(&content)
            .map_err(|e| format!("Failed to parse YAML agent card: {}", e))?;
        Ok(Some(card))
    } else {
        Ok(None)
    }
}


#[path = "discovery_engine_handshake.rs"]
mod discovery_engine_handshake;
#[allow(unused_imports)]
pub use discovery_engine_handshake::*;
#[cfg(test)]
#[path = "discovery_engine_tests.rs"]
mod tests;