saorsa_core/bootstrap/
mod.rs

1// Copyright 2024 Saorsa Labs Limited
2//
3// This software is dual-licensed under:
4// - GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)
5// - Commercial License
6//
7// For AGPL-3.0 license, see LICENSE-AGPL-3.0
8// For commercial licensing, contact: saorsalabs@gmail.com
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under these licenses is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
14//! Bootstrap Cache System
15//!
16//! Provides decentralized peer discovery through local caching of known contacts.
17//! Eliminates dependency on central bootstrap servers by maintaining a high-quality
18//! cache of up to 30,000 peer contacts with automatic conflict resolution for
19//! multiple concurrent instances.
20
21pub mod cache;
22pub mod contact;
23pub mod discovery;
24pub mod merge;
25
26pub use cache::{BootstrapCache, CacheConfig, CacheError};
27pub use contact::{
28    ContactEntry, QualityCalculator, QualityMetrics, QuicConnectionType, QuicContactInfo,
29    QuicQualityMetrics,
30};
31pub use discovery::{BootstrapConfig, BootstrapDiscovery, ConfigurableBootstrapDiscovery};
32pub use merge::{MergeCoordinator, MergeResult};
33// Use real four-word-networking crate types behind a thin facade
34pub use four_word_networking as fourwords;
35use four_word_networking::FourWordAdaptiveEncoder;
36
37/// Minimal facade around external four-word types
38#[derive(Debug, Clone)]
39pub struct FourWordAddress(pub String);
40
41impl FourWordAddress {
42    pub fn from_string(s: &str) -> Result<Self> {
43        let parts: Vec<&str> = s.split(['.', '-']).collect();
44        if parts.len() != 4 {
45            return Err(P2PError::Bootstrap(
46                crate::error::BootstrapError::InvalidData(
47                    "Four-word address must have exactly 4 words"
48                        .to_string()
49                        .into(),
50                ),
51            ));
52        }
53        Ok(FourWordAddress(parts.join("-")))
54    }
55
56    pub fn validate(&self, _encoder: &WordEncoder) -> bool {
57        let parts: Vec<&str> = self.0.split(['.', '-']).collect();
58        parts.len() == 4 && parts.iter().all(|part| !part.is_empty())
59    }
60}
61
62#[derive(Debug, Clone)]
63pub struct WordDictionary;
64
65#[derive(Debug, Clone)]
66pub struct WordEncoder;
67
68impl Default for WordEncoder {
69    fn default() -> Self {
70        Self::new()
71    }
72}
73
74impl WordEncoder {
75    pub fn new() -> Self {
76        Self
77    }
78
79    pub fn encode_multiaddr_string(&self, multiaddr: &str) -> Result<FourWordAddress> {
80        // Map multiaddr to IPv4:port if possible, else hash deterministically
81        let socket_addr: std::net::SocketAddr = multiaddr.parse().map_err(|e| {
82            P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
83                format!("{e}").into(),
84            ))
85        })?;
86        self.encode_socket_addr(&socket_addr)
87    }
88
89    pub fn decode_to_socket_addr(&self, words: &FourWordAddress) -> Result<std::net::SocketAddr> {
90        let encoder = FourWordAdaptiveEncoder::new().map_err(|e| {
91            P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
92                format!("Encoder init failed: {e}").into(),
93            ))
94        })?;
95        // Accept hyphens, spaces or dots; normalize then call adaptive decoder
96        let normalized = words.0.replace(' ', "-");
97        let decoded = encoder.decode(&normalized).map_err(|e| {
98            P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
99                format!("Failed to decode four-word address: {e}").into(),
100            ))
101        })?;
102        decoded.parse::<std::net::SocketAddr>().map_err(|_| {
103            P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
104                "Decoded address missing port".to_string().into(),
105            ))
106        })
107    }
108
109    pub fn encode_socket_addr(&self, addr: &std::net::SocketAddr) -> Result<FourWordAddress> {
110        let encoder = FourWordAdaptiveEncoder::new().map_err(|e| {
111            P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
112                format!("Encoder init failed: {e}").into(),
113            ))
114        })?;
115        let encoded = encoder
116            .encode(&addr.to_string())
117            .map_err(|e| P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(format!("{e}").into())))?;
118        Ok(FourWordAddress(encoded.replace(' ', "-")))
119    }
120}
121
122use crate::error::BootstrapError;
123use crate::{P2PError, PeerId, Result};
124use std::path::PathBuf;
125use std::time::Duration;
126
127/// Default cache configuration
128pub const DEFAULT_MAX_CONTACTS: usize = 30_000;
129/// Default directory for storing bootstrap cache files
130pub const DEFAULT_CACHE_DIR: &str = ".cache/p2p_foundation";
131/// Default interval for merging instance cache files
132pub const DEFAULT_MERGE_INTERVAL: Duration = Duration::from_secs(30);
133/// Default interval for cleaning up stale contacts (1 hour)
134pub const DEFAULT_CLEANUP_INTERVAL: Duration = Duration::from_secs(3600);
135/// Default interval for updating contact quality scores (5 minutes)
136pub const DEFAULT_QUALITY_UPDATE_INTERVAL: Duration = Duration::from_secs(300);
137
138/// Bootstrap cache initialization and management
139pub struct BootstrapManager {
140    cache: BootstrapCache,
141    merge_coordinator: MergeCoordinator,
142    word_encoder: WordEncoder,
143}
144
145impl BootstrapManager {
146    /// Create a new bootstrap manager with default configuration
147    pub async fn new() -> Result<Self> {
148        let cache_dir = home_cache_dir()?;
149        let config = CacheConfig::default();
150
151        let cache = BootstrapCache::new(cache_dir.clone(), config).await?;
152        let merge_coordinator = MergeCoordinator::new(cache_dir)?;
153        let word_encoder = WordEncoder::new();
154
155        Ok(Self {
156            cache,
157            merge_coordinator,
158            word_encoder,
159        })
160    }
161
162    /// Create a new bootstrap manager with custom configuration
163    pub async fn with_config(config: CacheConfig) -> Result<Self> {
164        let cache_dir = home_cache_dir()?;
165
166        let cache = BootstrapCache::new(cache_dir.clone(), config).await?;
167        let merge_coordinator = MergeCoordinator::new(cache_dir)?;
168        let word_encoder = WordEncoder::new();
169
170        Ok(Self {
171            cache,
172            merge_coordinator,
173            word_encoder,
174        })
175    }
176
177    /// Get bootstrap peers for initial connection
178    pub async fn get_bootstrap_peers(&self, count: usize) -> Result<Vec<ContactEntry>> {
179        self.cache.get_bootstrap_peers(count).await
180    }
181
182    /// Add a discovered peer to the cache
183    pub async fn add_contact(&mut self, contact: ContactEntry) -> Result<()> {
184        self.cache.add_contact(contact).await
185    }
186
187    /// Update contact performance metrics
188    pub async fn update_contact_metrics(
189        &mut self,
190        peer_id: &PeerId,
191        metrics: QualityMetrics,
192    ) -> Result<()> {
193        self.cache.update_contact_metrics(peer_id, metrics).await
194    }
195
196    /// Start background maintenance tasks
197    pub async fn start_background_tasks(&mut self) -> Result<()> {
198        // Start periodic merge of instance caches
199        let cache_clone = self.cache.clone();
200        let merge_coordinator = self.merge_coordinator.clone();
201
202        tokio::spawn(async move {
203            let mut interval = tokio::time::interval(DEFAULT_MERGE_INTERVAL);
204            loop {
205                interval.tick().await;
206                if let Err(e) = merge_coordinator.merge_instance_caches(&cache_clone).await {
207                    tracing::warn!("Failed to merge instance caches: {}", e);
208                }
209            }
210        });
211
212        // Start quality score updates
213        let cache_clone = self.cache.clone();
214        tokio::spawn(async move {
215            let mut interval = tokio::time::interval(DEFAULT_QUALITY_UPDATE_INTERVAL);
216            loop {
217                interval.tick().await;
218                if let Err(e) = cache_clone.update_quality_scores().await {
219                    tracing::warn!("Failed to update quality scores: {}", e);
220                }
221            }
222        });
223
224        // Start cleanup task
225        let cache_clone = self.cache.clone();
226        tokio::spawn(async move {
227            let mut interval = tokio::time::interval(DEFAULT_CLEANUP_INTERVAL);
228            loop {
229                interval.tick().await;
230                if let Err(e) = cache_clone.cleanup_stale_entries().await {
231                    tracing::warn!("Failed to cleanup stale entries: {}", e);
232                }
233            }
234        });
235
236        Ok(())
237    }
238
239    /// Get cache statistics
240    pub async fn get_stats(&self) -> Result<CacheStats> {
241        self.cache.get_stats().await
242    }
243
244    /// Force a cache merge operation
245    pub async fn force_merge(&self) -> Result<MergeResult> {
246        self.merge_coordinator
247            .merge_instance_caches(&self.cache)
248            .await
249    }
250
251    /// Convert socket address to four-word address
252    pub fn encode_address(&self, socket_addr: &std::net::SocketAddr) -> Result<FourWordAddress> {
253        self.word_encoder
254            .encode_socket_addr(socket_addr)
255            .map_err(|e| {
256                crate::P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
257                    format!("Failed to encode socket address: {e}").into(),
258                ))
259            })
260    }
261
262    /// Convert four-word address to socket address
263    pub fn decode_address(&self, words: &FourWordAddress) -> Result<std::net::SocketAddr> {
264        self.word_encoder.decode_to_socket_addr(words).map_err(|e| {
265            crate::P2PError::Bootstrap(crate::error::BootstrapError::InvalidData(
266                format!("Failed to decode four-word address: {e}").into(),
267            ))
268        })
269    }
270
271    /// Validate four-word address format
272    pub fn validate_words(&self, words: &FourWordAddress) -> Result<()> {
273        if words.validate(&self.word_encoder) {
274            Ok(())
275        } else {
276            Err(crate::P2PError::Bootstrap(
277                crate::error::BootstrapError::InvalidData(
278                    "Invalid four-word address format".to_string().into(),
279                ),
280            ))
281        }
282    }
283
284    /// Get the word encoder for direct access
285    pub fn word_encoder(&self) -> &WordEncoder {
286        &self.word_encoder
287    }
288
289    /// Get well-known bootstrap addresses as four-word addresses
290    pub fn get_well_known_word_addresses(&self) -> Vec<(FourWordAddress, std::net::SocketAddr)> {
291        let well_known_addrs = vec![
292            // Primary bootstrap nodes with well-known addresses
293            std::net::SocketAddr::from(([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888], 9000)),
294            std::net::SocketAddr::from(([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8844], 9001)),
295            std::net::SocketAddr::from(([0x2606, 0x4700, 0x4700, 0, 0, 0, 0, 0x1111], 9002)),
296        ];
297
298        well_known_addrs
299            .into_iter()
300            .filter_map(|socket_addr| {
301                if let Ok(words) = self.encode_address(&socket_addr) {
302                    Some((words, socket_addr))
303                } else {
304                    None
305                }
306            })
307            .collect()
308    }
309}
310
311/// Cache statistics for monitoring
312#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
313pub struct CacheStats {
314    /// Total number of contacts in the cache
315    pub total_contacts: usize,
316    /// Number of contacts with high quality scores
317    pub high_quality_contacts: usize,
318    /// Number of contacts with verified IPv6 identity
319    pub verified_contacts: usize,
320    /// Timestamp of the last cache merge operation
321    pub last_merge: chrono::DateTime<chrono::Utc>,
322    /// Timestamp of the last cache cleanup operation
323    pub last_cleanup: chrono::DateTime<chrono::Utc>,
324    /// Cache hit rate for peer discovery operations
325    pub cache_hit_rate: f64,
326    /// Average quality score across all contacts
327    pub average_quality_score: f64,
328
329    // QUIC-specific statistics
330    /// Number of contacts with QUIC networking support
331    pub iroh_contacts: usize,
332    /// Number of contacts with successful NAT traversal (deprecated)
333    pub nat_traversal_contacts: usize,
334    /// Average QUIC connection setup time (milliseconds)
335    pub avg_iroh_setup_time_ms: f64,
336    /// Most successful QUIC connection type
337    pub preferred_iroh_connection_type: Option<String>,
338}
339
340/// Get the home cache directory
341fn home_cache_dir() -> Result<PathBuf> {
342    let home = std::env::var("HOME")
343        .or_else(|_| std::env::var("USERPROFILE"))
344        .map_err(|_| {
345            P2PError::Bootstrap(BootstrapError::CacheError(
346                "Unable to determine home directory".to_string().into(),
347            ))
348        })?;
349
350    let cache_dir = PathBuf::from(home).join(DEFAULT_CACHE_DIR);
351
352    // Ensure cache directory exists
353    std::fs::create_dir_all(&cache_dir).map_err(|e| {
354        P2PError::Bootstrap(BootstrapError::CacheError(
355            format!("Failed to create cache directory: {e}").into(),
356        ))
357    })?;
358
359    Ok(cache_dir)
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    use tempfile::TempDir;
366
367    #[tokio::test]
368    async fn test_bootstrap_manager_creation() {
369        let temp_dir = TempDir::new().unwrap();
370        let config = CacheConfig {
371            cache_dir: temp_dir.path().to_path_buf(),
372            max_contacts: 1000,
373            ..CacheConfig::default()
374        };
375
376        let manager = BootstrapManager::with_config(config).await;
377        assert!(manager.is_ok());
378    }
379
380    #[tokio::test]
381    async fn test_home_cache_dir() {
382        let result = home_cache_dir();
383        assert!(result.is_ok());
384
385        let path = result.unwrap();
386        assert!(path.exists());
387        assert!(path.is_dir());
388    }
389}