clm-kernel 0.0.2

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Reticulum AutoInterface Discovery Engine for CLM Layer 3 Mesh.
//! Canonical Path: kernel/clm_rust_core/src/mesh/reticulum_discovery.rs
//!
//! Provides Tokio-based UDP socket listener and broadcaster for Reticulum
//! announce packets on port 29716 (or custom test port).

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::UdpSocket;
use tokio::sync::{broadcast, RwLock};
use tokio_util::sync::CancellationToken;

use crate::mesh::reticulum_codec::{
    encode_announce_packet, parse_and_verify_peer, sign_announce_data,
    DecodedPkcPeer, PkcAnnouncePayload, ReticulumAnnounceData,
};
use ed25519_dalek::SigningKey;

pub const RETICULUM_AUTOINTERFACE_PORT: u16 = 29716;

#[derive(Debug, Clone)]
pub struct DiscoveryConfig {
    pub bind_addr: String,
    pub broadcast_addr: String,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            bind_addr: format!("0.0.0.0:{}", RETICULUM_AUTOINTERFACE_PORT),
            broadcast_addr: format!("255.255.255.255:{}", RETICULUM_AUTOINTERFACE_PORT),
        }
    }
}

pub struct ReticulumDiscoveryEngine {
    socket: Arc<UdpSocket>,
    peers: Arc<RwLock<HashMap<String, DecodedPkcPeer>>>,
    peer_tx: broadcast::Sender<DecodedPkcPeer>,
    cancel_token: CancellationToken,
}

impl ReticulumDiscoveryEngine {
    /// Initializes and binds the discovery engine to the specified address.
    pub async fn bind(config: DiscoveryConfig) -> std::io::Result<Self> {
        let socket = UdpSocket::bind(&config.bind_addr).await?;
        socket.set_broadcast(true)?;

        let (peer_tx, _) = broadcast::channel(128);

        Ok(Self {
            socket: Arc::new(socket),
            peers: Arc::new(RwLock::new(HashMap::new())),
            peer_tx,
            cancel_token: CancellationToken::new(),
        })
    }

    /// Local socket address bound by the engine.
    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
        self.socket.local_addr()
    }

    /// Starts the background listener loop.
    pub fn start(&self) -> tokio::task::JoinHandle<()> {
        let socket = Arc::clone(&self.socket);
        let peers = Arc::clone(&self.peers);
        let peer_tx = self.peer_tx.clone();
        let cancel = self.cancel_token.clone();

        tokio::spawn(async move {
            let mut buf = [0u8; 4096];
            loop {
                tokio::select! {
                    _ = cancel.cancelled() => {
                        break;
                    }
                    result = socket.recv_from(&mut buf) => {
                        match result {
                            Ok((len, _addr)) => {
                                if let Ok(peer) = parse_and_verify_peer(&buf[..len]) {
                                    {
                                        let mut map = peers.write().await;
                                        map.insert(peer.destination_hex.clone(), peer.clone());
                                    }
                                    let _ = peer_tx.send(peer);
                                }
                            }
                            Err(_) => {
                                // Socket closed or transient error
                                break;
                            }
                        }
                    }
                }
            }
        })
    }

    /// Broadcasts or sends an announce packet to the given destination socket address.
    pub async fn send_announce(
        &self,
        dest_addr: &str,
        dest_hash: [u8; 16],
        signing_key: &SigningKey,
        payload: &PkcAnnouncePayload,
    ) -> Result<DecodedPkcPeer, Box<dyn std::error::Error + Send + Sync>> {
        let pub_bytes = signing_key.verifying_key().to_bytes();
        let app_data = serde_json::to_vec(payload)?;
        let signature = sign_announce_data(&dest_hash, &pub_bytes, &app_data, signing_key);

        let announce = ReticulumAnnounceData {
            destination_hash: dest_hash,
            public_key: pub_bytes,
            app_data,
            signature,
        };

        let frame = encode_announce_packet(&announce);
        self.socket.send_to(&frame, dest_addr).await?;

        Ok(DecodedPkcPeer {
            destination_hex: hex::encode(dest_hash),
            identity_public_key_hex: hex::encode(pub_bytes),
            payload: payload.clone(),
            verified: true,
        })
    }

    /// Subscribes to discovered peer events.
    pub fn subscribe(&self) -> broadcast::Receiver<DecodedPkcPeer> {
        self.peer_tx.subscribe()
    }

    /// Returns a snapshot of all discovered peers.
    pub async fn get_discovered_peers(&self) -> Vec<DecodedPkcPeer> {
        let map = self.peers.read().await;
        map.values().cloned().collect()
    }

    /// Stops the discovery engine and cancels listener tasks.
    pub fn stop(&self) {
        self.cancel_token.cancel();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::OsRng;

    #[tokio::test]
    async fn test_discovery_engine_loopback() {
        // Bind engine A and engine B on ephemeral ports
        let config_a = DiscoveryConfig {
            bind_addr: "127.0.0.1:0".into(),
            broadcast_addr: "127.0.0.1:0".into(),
        };
        let engine_a = ReticulumDiscoveryEngine::bind(config_a).await.unwrap();
        let _addr_a = engine_a.local_addr().unwrap();

        let config_b = DiscoveryConfig {
            bind_addr: "127.0.0.1:0".into(),
            broadcast_addr: "127.0.0.1:0".into(),
        };
        let engine_b = ReticulumDiscoveryEngine::bind(config_b).await.unwrap();
        let addr_b = engine_b.local_addr().unwrap();

        let mut sub_b = engine_b.subscribe();
        engine_b.start();

        let mut rng = OsRng;
        let key_a = SigningKey::generate(&mut rng);
        let dest_hash = [0x55u8; 16];
        let payload = PkcAnnouncePayload {
            did: "did:clm:peer_a".into(),
            capabilities: vec!["mcard:text".into(), "satori:dialogue".into()],
            namespaces: vec!["clm:pkc/alice".into()],
            timestamp: 1726501000.0,
            extra: serde_json::Map::new(),
        };

        engine_a
            .send_announce(&addr_b.to_string(), dest_hash, &key_a, &payload)
            .await
            .unwrap();

        let discovered = tokio::time::timeout(std::time::Duration::from_secs(2), sub_b.recv())
            .await
            .expect("Timeout waiting for announce")
            .expect("Receive error");

        assert_eq!(discovered.payload.did, "did:clm:peer_a");
        assert_eq!(discovered.destination_hex, hex::encode(dest_hash));
        assert!(discovered.verified);

        let peers = engine_b.get_discovered_peers().await;
        assert_eq!(peers.len(), 1);
        assert_eq!(peers[0].payload.did, "did:clm:peer_a");

        engine_a.stop();
        engine_b.stop();
    }
}