Skip to main content

clm_rust_core/layer3/
discovery_engine.rs

1use std::collections::HashMap;
2use std::net::UdpSocket;
3use std::path::Path;
4use std::fs;
5use std::time::{Duration, Instant};
6use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo};
7use serde::{Serialize, Deserialize};
8use ed25519_dalek::{VerifyingKey, SigningKey, Verifier, Signature, Signer};
9use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};
10
11
12// Structure matching JavaScript peer export
13#[derive(Serialize, Deserialize, Clone, Debug)]
14pub struct PeerInfo {
15    pub name: String,
16    pub ip: String,
17    pub port: u16,
18    pub did: String,
19    pub capabilities: Vec<String>,
20    pub protocol: String,
21    #[serde(rename = "discoveredAt")]
22    pub discovered_at: String,
23    /// WireGuard public key (hex-encoded X25519 public key).
24    /// Present when the peer announces WireGuard support via mDNS.
25    /// `None` for peers that don't support WireGuard (backward compatible).
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub wg_public_key: Option<String>,
28}
29
30pub struct DiscoveryEngine {
31    pub service_type: String,
32}
33
34impl Default for DiscoveryEngine {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl DiscoveryEngine {
41    pub fn new() -> Self {
42        Self {
43            service_type: "_pkc._tcp.local.".to_string(),
44        }
45    }
46
47    pub fn get_local_ip() -> String {
48        if let Ok(socket) = UdpSocket::bind("0.0.0.0:0")
49            && socket.connect("8.8.8.8:80").is_ok()
50                && let Ok(addr) = socket.local_addr() {
51                    return addr.ip().to_string();
52                }
53        "127.0.0.1".to_string()
54    }
55
56    pub fn announce(&self, service_name: &str, did: &str, port: u16) -> Result<(), String> {
57        self.announce_with_wireguard(service_name, did, port, None)
58    }
59
60    /// Announce the PKC service with a WireGuard public key.
61    ///
62    /// In addition to the standard mDNS properties (did, version, capabilities, protocol),
63    /// this includes `wg_public_key` so peers can establish WireGuard-encrypted tunnels.
64    pub fn announce_with_wireguard(
65        &self,
66        service_name: &str,
67        did: &str,
68        port: u16,
69        wg_public_key: Option<&str>,
70    ) -> Result<(), String> {
71        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
72        let local_ip = Self::get_local_ip();
73
74        let host_name = format!("{}.local.", service_name);
75        let mut properties = HashMap::new();
76        properties.insert("did".to_string(), did.to_string());
77        properties.insert("version".to_string(), "1.0".to_string());
78        properties.insert("capabilities".to_string(), "s3_access,ipfs_access,webrtc_relay".to_string());
79        properties.insert("protocol".to_string(), "challenge-response".to_string());
80        if let Some(wg_key) = wg_public_key {
81            properties.insert("wg_public_key".to_string(), wg_key.to_string());
82        }
83
84        let service_info = ServiceInfo::new(
85            &self.service_type,
86            service_name,
87            &host_name,
88            &local_ip,
89            port,
90            properties,
91        )
92        .map_err(|e| format!("Failed to create ServiceInfo: {}", e))?
93        .enable_addr_auto();
94
95        mdns.register(service_info).map_err(|e| format!("Failed to register service: {}", e))?;
96
97        println!("[mDNS PKC] ✅ Announced service: {} on port {}", service_name, port);
98        println!("[mDNS PKC]    IPs: {}", local_ip);
99        println!("[mDNS PKC]    DID: {}", did);
100
101        // Keep running to maintain registration
102        loop {
103            std::thread::sleep(Duration::from_secs(10));
104        }
105    }
106
107    pub fn discover(&self, timeout: Duration) -> Result<Vec<PeerInfo>, String> {
108        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
109        let receiver = mdns.browse(&self.service_type).map_err(|e| format!("Failed to browse: {}", e))?;
110
111        println!("[mDNS PKC] 🔍 Discovering PKC peers on network...");
112
113        let start_time = Instant::now();
114        let mut discovered_peers: HashMap<String, PeerInfo> = HashMap::new();
115
116        while start_time.elapsed() < timeout {
117            let remaining = timeout.saturating_sub(start_time.elapsed());
118            if remaining.is_zero() {
119                break;
120            }
121
122            if let Ok(event) = receiver.recv_timeout(remaining)
123                && let ServiceEvent::ServiceResolved(info) = event {
124                    let name = info.get_fullname().to_string();
125                    let port = info.get_port();
126                    
127                    let props = info.get_properties();
128                    let did = props.get_property_val_str("did").unwrap_or("unknown").to_string();
129                    let capabilities = props.get_property_val_str("capabilities")
130                        .map(|s| s.split(',').map(|x| x.to_string()).collect())
131                        .unwrap_or_else(Vec::new);
132                    let protocol = props.get_property_val_str("protocol").unwrap_or("unknown").to_string();
133
134
135                    let wg_public_key = props.get_property_val_str("wg_public_key").map(|s| s.to_string());
136
137                    for ip_addr in info.get_addresses() {
138                        let ip = ip_addr.to_string();
139                        let peer_id = format!("{}:{}", ip, port);
140                        
141                        // Check skip self if we knew ours, but we just list all non-self or all discovered
142                        discovered_peers.insert(peer_id, PeerInfo {
143                            name: name.clone(),
144                            ip,
145                            port,
146                            did: did.clone(),
147                            capabilities: capabilities.clone(),
148                            protocol: protocol.clone(),
149                            discovered_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
150                            wg_public_key: wg_public_key.clone(),
151                        });
152                    }
153                }
154        }
155
156        let peers: Vec<PeerInfo> = discovered_peers.into_values().collect();
157        Ok(peers)
158    }
159
160    /// Announce the PKC service asynchronously with structured cancellation.
161    pub async fn announce_with_cancellation(
162        &self,
163        service_name: &str,
164        did: &str,
165        port: u16,
166        wg_public_key: Option<&str>,
167        token: tokio_util::sync::CancellationToken,
168    ) -> Result<(), String> {
169        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
170        let local_ip = Self::get_local_ip();
171
172        let host_name = format!("{}.local.", service_name);
173        let mut properties = HashMap::new();
174        properties.insert("did".to_string(), did.to_string());
175        properties.insert("version".to_string(), "1.0".to_string());
176        properties.insert("capabilities".to_string(), "s3_access,ipfs_access,webrtc_relay".to_string());
177        properties.insert("protocol".to_string(), "challenge-response".to_string());
178        if let Some(wg_key) = wg_public_key {
179            properties.insert("wg_public_key".to_string(), wg_key.to_string());
180        }
181
182        let service_info = ServiceInfo::new(
183            &self.service_type,
184            service_name,
185            &host_name,
186            &local_ip,
187            port,
188            properties,
189        )
190        .map_err(|e| format!("Failed to create ServiceInfo: {}", e))?
191        .enable_addr_auto();
192
193        mdns.register(service_info).map_err(|e| format!("Failed to register service: {}", e))?;
194
195        // Gracefully wait until token cancellation
196        tokio::select! {
197            _ = token.cancelled() => {
198                let _ = mdns.shutdown();
199                Ok(())
200            }
201        }
202    }
203
204    /// Discover PKC peers asynchronously with structured cancellation.
205    pub async fn discover_with_cancellation(
206        &self,
207        timeout: Duration,
208        token: tokio_util::sync::CancellationToken,
209    ) -> Result<Vec<PeerInfo>, String> {
210        let mdns = ServiceDaemon::new().map_err(|e| format!("Failed to create mDNS daemon: {}", e))?;
211        let receiver = mdns.browse(&self.service_type).map_err(|e| format!("Failed to browse: {}", e))?;
212
213        let start_time = Instant::now();
214        let mut discovered_peers: HashMap<String, PeerInfo> = HashMap::new();
215
216        while start_time.elapsed() < timeout && !token.is_cancelled() {
217            let remaining = timeout.saturating_sub(start_time.elapsed());
218            if remaining.is_zero() {
219                break;
220            }
221
222            let step = remaining.min(Duration::from_millis(50));
223            tokio::select! {
224                _ = token.cancelled() => break,
225                res = tokio::task::spawn_blocking({
226                    let receiver = receiver.clone();
227                    move || receiver.recv_timeout(step)
228                }) => {
229                    if let Ok(Ok(event)) = res
230                        && let ServiceEvent::ServiceResolved(info) = event {
231                            let name = info.get_fullname().to_string();
232                            let port = info.get_port();
233                            let props = info.get_properties();
234                            let did = props.get_property_val_str("did").unwrap_or("unknown").to_string();
235                            let capabilities = props.get_property_val_str("capabilities")
236                                .map(|s| s.split(',').map(|x| x.to_string()).collect())
237                                .unwrap_or_else(Vec::new);
238                            let protocol = props.get_property_val_str("protocol").unwrap_or("unknown").to_string();
239                            let wg_public_key = props.get_property_val_str("wg_public_key").map(|s| s.to_string());
240
241                            for ip_addr in info.get_addresses() {
242                                let ip = ip_addr.to_string();
243                                let peer_id = format!("{}:{}", ip, port);
244                                discovered_peers.insert(peer_id, PeerInfo {
245                                    name: name.clone(),
246                                    ip,
247                                    port,
248                                    did: did.clone(),
249                                    capabilities: capabilities.clone(),
250                                    protocol: protocol.clone(),
251                                    discovered_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
252                                    wg_public_key: wg_public_key.clone(),
253                                });
254                            }
255                        }
256                }
257            }
258        }
259
260        let _ = mdns.shutdown();
261        let peers: Vec<PeerInfo> = discovered_peers.into_values().collect();
262        Ok(peers)
263    }
264}
265
266// Helpers for Hex Encoding/Decoding
267pub fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
268    if !s.len().is_multiple_of(2) {
269        return Err("Hex string must have an even length".to_string());
270    }
271    (0..s.len())
272        .step_by(2)
273        .map(|i| {
274            u8::from_str_radix(&s[i..i + 2], 16)
275                .map_err(|e| format!("Invalid hex digit: {}", e))
276        })
277        .collect()
278}
279
280pub fn encode_hex(bytes: &[u8]) -> String {
281    bytes.iter().map(|b| format!("{:02x}", b)).collect()
282}
283
284// SQLite / Agent Card parser structs
285#[derive(Deserialize, Debug)]
286pub struct AgentCard {
287    pub public_key: String,
288    #[serde(default)]
289    pub capabilities: Vec<String>,
290}
291
292pub fn get_agent_card_from_db(db_path: &str, did: &str) -> Result<Option<AgentCard>, String> {
293    if !Path::new(db_path).exists() {
294        return Err(format!("Database file not found at: {}", db_path));
295    }
296    let conn = rusqlite::Connection::open(db_path)
297        .map_err(|e| format!("Failed to open agent identity DB: {}", e))?;
298    
299    let mut stmt = conn.prepare("SELECT content FROM card WHERE hash = ?")
300        .map_err(|e| format!("Prepare query failed: {}", e))?;
301    
302    let content_opt: Option<String> = stmt.query_row(rusqlite::params![did], |row| row.get(0))
303        .ok();
304
305    if let Some(content) = content_opt {
306        let card: AgentCard = serde_yaml::from_str(&content)
307            .map_err(|e| format!("Failed to parse YAML agent card: {}", e))?;
308        Ok(Some(card))
309    } else {
310        Ok(None)
311    }
312}
313
314
315#[path = "discovery_engine_handshake.rs"]
316mod discovery_engine_handshake;
317#[allow(unused_imports)]
318pub use discovery_engine_handshake::*;
319#[cfg(test)]
320#[path = "discovery_engine_tests.rs"]
321mod tests;
322