Skip to main content

saorsa_core/dht/
mod.rs

1//! Distributed Hash Table implementations
2//!
3//! This module provides various DHT implementations including:
4//! - Trust-weighted Kademlia DHT with EigenTrust integration
5//! - Core DHT engine with replication and fault tolerance
6//! - Geographic routing and content addressing
7//! - Capacity signaling and telemetry
8
9pub mod capacity_signaling;
10pub mod core_engine;
11pub mod telemetry;
12pub mod trust_weighted_dht;
13pub mod trust_weighted_kademlia;
14
15// Re-export the main DHT trait and types
16pub use trust_weighted_dht::{
17    Contact, Dht, Key, Outcome, PutPolicy, PutReceipt, eigen_trust_epoch, record_interaction,
18};
19
20// Re-export PeerId from trust_weighted_dht
21pub use trust_weighted_dht::PeerId;
22
23// Re-export the trust-weighted implementation
24pub use trust_weighted_kademlia::TrustWeightedKademlia;
25
26// Re-export capacity signaling
27pub use capacity_signaling::{CapacityGossip, CapacityHistogram, CapacityManager, CapacityStats};
28
29// Re-export telemetry
30pub use telemetry::{DhtTelemetry, OperationStats, OperationType, TelemetryStats};
31
32// Re-export replication grace period types
33pub use replication_grace_period::{
34    EndpointRegistration, FailedNodeInfo, NodeFailureReason, ReplicationError,
35    ReplicationGracePeriodConfig,
36};
37
38// Re-export node failure tracker
39pub use node_failure_tracker::{DefaultNodeFailureTracker, DhtClient, NodeFailureTracker};
40
41// Re-export existing DHT components
42pub use core_engine::{
43    DhtCoreEngine, DhtKey, DhtRequestWrapper, DhtResponseWrapper, NodeCapacity,
44    NodeId as DhtNodeId, NodeInfo,
45};
46
47// Legacy type aliases for backward compatibility
48pub type DHT = DhtCoreEngine;
49pub type DHTNode = NodeInfo;
50pub type SerializableDHTNode = NodeInfo;
51
52// Re-export types from trust_weighted_dht
53pub use trust_weighted_dht::Key as DHT_Key;
54
55// Import additional types for compatibility
56use serde::{Deserialize, Serialize};
57use std::time::Duration;
58
59/// DHT configuration parameters
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct DHTConfig {
62    /// Replication parameter (k) - number of nodes to store each record
63    pub replication_factor: usize,
64    /// Maximum nodes per k-bucket
65    pub bucket_size: usize,
66    /// Concurrency parameter for parallel lookups
67    pub alpha: usize,
68    /// Record expiration time
69    pub record_ttl: Duration,
70    /// Refresh interval for buckets
71    pub bucket_refresh_interval: Duration,
72    /// Republish interval for stored records
73    pub republish_interval: Duration,
74    /// Maximum distance for considering nodes "close"
75    pub max_distance: u8,
76}
77
78impl Default for DHTConfig {
79    fn default() -> Self {
80        Self {
81            replication_factor: 8,
82            bucket_size: 20,
83            alpha: 3,
84            record_ttl: Duration::from_secs(3600),
85            bucket_refresh_interval: Duration::from_secs(3600),
86            republish_interval: Duration::from_secs(3600),
87            max_distance: 160,
88        }
89    }
90}
91
92/// DHT record containing key-value data with metadata
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct Record {
95    /// Record key
96    pub key: Key,
97    /// Record value
98    pub value: Vec<u8>,
99    /// Publisher peer ID
100    pub publisher: PeerId,
101    /// Record creation time
102    pub created_at: std::time::SystemTime,
103    /// Record expiration time
104    pub expires_at: std::time::SystemTime,
105    /// Signature for verification (optional)
106    pub signature: Option<Vec<u8>>,
107}
108
109impl Record {
110    /// Create a new record
111    pub fn new(key: Key, value: Vec<u8>, publisher: PeerId) -> Self {
112        let now = std::time::SystemTime::now();
113        Self {
114            key,
115            value,
116            publisher,
117            created_at: now,
118            expires_at: now + std::time::Duration::from_secs(3600), // 1 hour default TTL
119            signature: None,
120        }
121    }
122
123    /// Check if the record has expired
124    pub fn is_expired(&self) -> bool {
125        std::time::SystemTime::now() > self.expires_at
126    }
127}
128
129// Re-export other DHT modules
130pub mod content_addressing;
131pub mod enhanced_storage;
132pub mod geographic_network_integration;
133pub mod geographic_routing;
134pub mod geographic_routing_table;
135pub mod latency_aware_selection;
136pub mod network_integration;
137pub mod node_failure_tracker;
138pub mod optimized_storage;
139pub mod replication_grace_period;
140pub mod skademlia;
141// Witness/attestation modules removed.
142
143/// IPv6-based DHT identity for security parity
144pub mod ipv6_identity;
145
146/// IPv4-based DHT identity for security parity
147pub mod ipv4_identity;
148
149/// Cross-network replication for IPv4/IPv6 dual-stack redundancy
150pub mod cross_network_replication;
151
152/// Node age verification for anti-Sybil protection
153pub mod node_age_verifier;
154
155/// Witness collusion detection for Byzantine-robust consensus
156pub mod collusion_detector;
157
158/// Sybil attack detection for DHT protection
159pub mod sybil_detector;
160
161/// Authenticated sibling broadcast for eclipse attack prevention
162pub mod authenticated_sibling_broadcast;
163
164/// Routing table maintenance and node validation
165pub mod routing_maintenance;
166
167/// Comprehensive metrics for security, DHT health, trust, and placement
168pub mod metrics;
169
170/// Trust-aware peer selection combining XOR distance with EigenTrust scores
171#[cfg(feature = "adaptive-ml")]
172pub mod trust_peer_selector;
173
174// Re-export trust peer selector types
175#[cfg(feature = "adaptive-ml")]
176pub use trust_peer_selector::{
177    TrustAwarePeerSelector, TrustSelectionConfig, adaptive_id_to_dht_node, dht_node_to_adaptive_id,
178};
179
180// Re-export routing maintenance types for convenience
181pub use routing_maintenance::{
182    BucketRefreshManager, EvictionManager, EvictionReason, MaintenanceConfig, MaintenanceScheduler,
183    MaintenanceTask, NodeLivenessState, NodeValidationResult, RefreshTier, ValidationFailure,
184};
185
186// Re-export security coordinator types
187pub use routing_maintenance::{
188    CloseGroupEviction, CloseGroupEvictionTracker, EvictionRecord, SecurityCoordinator,
189    SecurityCoordinatorConfig,
190};
191
192// Re-export close group validator types
193pub use routing_maintenance::close_group_validator::{
194    AttackIndicators, CloseGroupFailure, CloseGroupHistory, CloseGroupResponse,
195    CloseGroupValidationResult, CloseGroupValidator, CloseGroupValidatorConfig,
196};
197
198// Re-export collusion detector types for witness validation
199pub use collusion_detector::{
200    CollusionDetector, CollusionDetectorConfig, CollusionEvidence, CollusionGroup, VotingPattern,
201    VotingRecord,
202};
203
204// Re-export sybil detector types for DHT protection
205pub use sybil_detector::{
206    BehaviorProfile, JoinRecord, SybilDetector, SybilDetectorConfig, SybilEvidence, SybilGroup,
207};
208
209// Re-export authenticated sibling broadcast types
210pub use authenticated_sibling_broadcast::{
211    AuthenticatedSiblingBroadcast, BroadcastValidationFailure, BroadcastValidationResult,
212    MembershipProof, MembershipProofType, SiblingBroadcastBuilder, SiblingBroadcastConfig,
213    SiblingBroadcastValidator, SignedSiblingEntry,
214};
215
216// Re-export comprehensive metrics types for security, DHT health, trust, and placement
217pub use metrics::{
218    DhtHealthMetrics, DhtMetricsAggregator, DhtMetricsCollector, MetricsSummary, PlacementMetrics,
219    PlacementMetricsCollector, SecurityMetrics, SecurityMetricsCollector, TrustMetrics,
220    TrustMetricsCollector,
221};
222
223#[cfg(test)]
224mod security_tests;