use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};
use super::handler::DhtQueryHandler;
use super::lookup::{announce_to_token_nodes, iterative_get_peers};
use super::message::{DhtMessage, DhtMessageBuilder};
use super::node::DhtNode;
use super::peer_storage::DhtPeerStorage;
use super::routing_table::RoutingTable;
use super::socket::DhtSocket;
use super::token_tracker::TokenTracker;
use super::tracker::TransactionTracker;
#[derive(Debug, Clone)]
pub struct DhtEngineConfig {
pub port: u16,
pub port_range: Option<Vec<u16>>,
pub self_id: [u8; 20],
pub dht_file_path: Option<PathBuf>,
pub refresh_check_interval: Duration,
pub query_timeout: Duration,
pub token_rotation_interval: Duration,
pub node_contact_interval: Duration,
pub max_concurrent_lookups: usize,
pub bootstrap_on_start: bool,
pub bootstrap_timeout: Duration,
}
impl Default for DhtEngineConfig {
fn default() -> Self {
Self {
port: 6881,
port_range: None,
self_id: [0u8; 20],
dht_file_path: None,
refresh_check_interval: Duration::from_secs(300), query_timeout: Duration::from_secs(10),
token_rotation_interval: Duration::from_secs(600), node_contact_interval: Duration::from_secs(900), max_concurrent_lookups: 16,
bootstrap_on_start: true,
bootstrap_timeout: Duration::from_secs(60),
}
}
}
impl DhtEngineConfig {
pub fn local() -> Self {
Self {
port: 0,
bootstrap_on_start: false,
..Default::default()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum DhtEngineState {
Stopped = 0,
Bootstrapping = 1,
Running = 2,
ShuttingDown = 3,
}
#[derive(Debug, Clone)]
pub struct DhtEngineStats {
pub total_nodes: usize,
pub good_nodes: usize,
pub pending_transactions: usize,
pub state: DhtEngineState,
}
#[derive(Debug, Clone)]
pub struct FindPeersResult {
pub peers: Vec<SocketAddr>,
pub nodes_contacted: usize,
}
#[derive(Debug)]
pub enum DhtEngineEvent {
BucketRefreshNeeded,
PeerLookupCompleted {
info_hash: [u8; 20],
peers: Vec<SocketAddr>,
},
NodeLookupCompleted {
target: [u8; 20],
nodes: Vec<SocketAddr>,
},
TokenRotationNeeded,
BootstrapCompleted,
}
pub(super) struct DhtEngineInner {
pub(super) state: DhtEngineState,
pub(super) routing_table: RoutingTable,
pub(super) self_id: [u8; 20],
}
pub struct DhtEngine {
pub(super) inner: Arc<RwLock<DhtEngineInner>>,
pub(super) config: DhtEngineConfig,
pub(super) socket: DhtSocket,
pub(super) token_tracker: Arc<std::sync::Mutex<TokenTracker>>,
pub(super) peer_storage: Arc<DhtPeerStorage>,
pub(super) tracker: Arc<TransactionTracker>,
pub(super) handler: DhtQueryHandler,
pub(super) shutdown_tx: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
}
impl DhtEngine {
pub async fn start(config: DhtEngineConfig) -> std::io::Result<Arc<Self>> {
let self_id = if config.self_id == [0u8; 20] {
let mut id = [0u8; 20];
use rand::{RngCore, SeedableRng};
rand::rngs::StdRng::from_entropy().fill_bytes(&mut id);
id
} else {
config.self_id
};
info!(
id = %hex::encode(self_id),
port = config.port,
"Starting DHT engine"
);
let socket = if let Some(ports) = config.port_range.as_deref() {
let mut last_error = None;
let mut bound = None;
for port in ports {
match DhtSocket::bind(*port).await {
Ok(socket) => {
bound = Some(socket);
break;
}
Err(error) => last_error = Some(error),
}
}
bound.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::AddrInUse,
last_error.unwrap_or_else(|| "DHT port range is empty".to_string()),
)
})?
} else {
DhtSocket::bind(config.port)
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::AddrInUse, e))?
};
let actual_port = socket.local_addr().port();
info!(port = actual_port, "DHT socket bound");
let mut routing_table = RoutingTable::new(self_id);
if let Some(ref path) = config.dht_file_path
&& path.exists()
{
match super::persistence::DhtPersistence::load_from_file_sync(path) {
Ok(data) => {
info!(
count = data.nodes.len(),
"Loaded DHT routing table from disk"
);
for pnode in data.nodes {
let node = DhtNode::new(pnode.id, pnode.addr);
routing_table.insert(node);
}
}
Err(e) => {
warn!("Failed to load DHT routing table: {}", e);
}
}
}
let inner = Arc::new(RwLock::new(DhtEngineInner {
state: DhtEngineState::Bootstrapping,
routing_table,
self_id,
}));
let token_tracker = Arc::new(std::sync::Mutex::new(TokenTracker::new()));
let peer_storage = Arc::new(DhtPeerStorage::new());
let tracker = Arc::new(TransactionTracker::new());
let handler = DhtQueryHandler::new(self_id);
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
let engine = Arc::new(Self {
inner,
config: config.clone(),
socket,
token_tracker,
peer_storage,
tracker,
handler,
shutdown_tx: std::sync::Mutex::new(Some(shutdown_tx)),
});
engine.spawn_receive_loop(shutdown_rx);
engine.spawn_periodic_tasks();
if config.bootstrap_on_start {
engine.spawn_bootstrap();
} else {
engine.inner.write().await.state = DhtEngineState::Running;
}
Ok(engine)
}
pub fn spawn_bootstrap(self: &Arc<Self>) {
let engine = Arc::clone(self);
let limit = self.config.bootstrap_timeout;
tokio::spawn(async move {
if tokio::time::timeout(limit, engine.bootstrap())
.await
.is_err()
{
warn!(
timeout = ?limit,
"DHT bootstrap timed out; continuing without entry-point nodes"
);
engine.inner.write().await.state = DhtEngineState::Running;
}
});
}
pub async fn state(&self) -> DhtEngineState {
let inner = self.inner.read().await;
inner.state
}
pub async fn find_peers(&self, info_hash: &[u8; 20]) -> std::io::Result<FindPeersResult> {
let state = self.state().await;
if state != DhtEngineState::Running && state != DhtEngineState::Bootstrapping {
return Ok(FindPeersResult {
peers: vec![],
nodes_contacted: 0,
});
}
let rt = Arc::new(RwLock::new(self.inner.read().await.routing_table.clone()));
let self_id = self.inner.read().await.self_id;
debug!(info_hash = %hex::encode(info_hash), "Starting DHT get_peers lookup");
let result =
iterative_get_peers(info_hash, &self_id, &rt, &self.socket, &self.tracker).await;
{
let mut inner = self.inner.write().await;
let discovered_rt = rt.read().await;
for node in discovered_rt.all_nodes() {
inner.routing_table.insert(node.clone());
}
}
Ok(FindPeersResult {
peers: result.peers,
nodes_contacted: result.nodes_contacted,
})
}
pub async fn announce_peer(&self, info_hash: &[u8; 20], port: u16) -> std::io::Result<()> {
let state = self.state().await;
if state != DhtEngineState::Running && state != DhtEngineState::Bootstrapping {
return Ok(());
}
let rt = Arc::new(RwLock::new(self.inner.read().await.routing_table.clone()));
let self_id = self.inner.read().await.self_id;
debug!(
info_hash = %hex::encode(info_hash),
port,
"Starting DHT announce_peer"
);
let result =
iterative_get_peers(info_hash, &self_id, &rt, &self.socket, &self.tracker).await;
{
let mut inner = self.inner.write().await;
let discovered_rt = rt.read().await;
for node in discovered_rt.all_nodes() {
inner.routing_table.insert(node.clone());
}
}
if !result.token_nodes.is_empty() {
announce_to_token_nodes(
info_hash,
&self_id,
port,
&result.token_nodes,
&self.socket,
&self.tracker,
)
.await;
}
Ok(())
}
pub async fn add_node(&self, addr: SocketAddr) {
let self_id = self.inner.read().await.self_id;
let msg = DhtMessageBuilder::ping(0, &self_id);
let encoded = match msg.encode() {
Ok(e) => e,
Err(e) => {
debug!("Failed to encode ping for add_node: {}", e);
return;
}
};
if let Err(e) = self.socket.send_to(addr, &encoded).await {
debug!(addr = %addr, "Failed to send ping: {}", e);
return;
}
let mut buf = [0u8; 4096];
if let Ok((len, _from)) = self
.socket
.recv_with_timeout(&mut buf, self.config.query_timeout)
.await
&& len > 0
&& let Ok(response) = DhtMessage::decode(&buf[..len])
&& response.is_response()
{
if let Some(r) = &response.r
&& let Some(id_bytes) = r.dict_get(b"id").and_then(|v| v.as_bytes())
&& id_bytes.len() == 20
{
let mut node_id = [0u8; 20];
node_id.copy_from_slice(id_bytes);
let node = DhtNode::new(node_id, addr);
let mut inner = self.inner.write().await;
inner.routing_table.insert(node);
debug!(addr = %addr, id = %hex::encode(node_id), "Added DHT node via add_node");
}
}
}
pub fn start_maintenance_loop(&self) {
info!("DHT maintenance loop already running (spawned at start)");
}
pub fn shutdown(&self) {
let mut tx = self.shutdown_tx.lock().unwrap_or_else(|e| e.into_inner());
if let Some(sender) = tx.take() {
let _ = sender.send(());
}
if let Ok(_inner) = self.inner.try_write() {
}
info!("DHT shutdown signal sent");
}
pub async fn shutdown_async(&self) {
self.shutdown();
tokio::time::sleep(Duration::from_millis(100)).await;
if let Some(ref path) = self.config.dht_file_path {
let inner = self.inner.read().await;
let self_id = inner.self_id;
let nodes: Vec<DhtNode> = inner.routing_table.collect_good_nodes();
drop(inner);
match super::persistence::DhtPersistence::save_to_file_sync(path, &self_id, &nodes) {
Ok(_) => {
info!(path = %path.display(), count = nodes.len(), "Saved DHT routing table")
}
Err(e) => warn!("Failed to save DHT routing table: {}", e),
}
}
info!("DHT engine shutdown complete");
}
pub async fn stats(&self) -> DhtEngineStats {
let inner = self.inner.read().await;
DhtEngineStats {
total_nodes: inner.routing_table.total_node_count(),
good_nodes: inner.routing_table.good_node_count(),
pending_transactions: self.tracker.pending_count(),
state: inner.state,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dht_engine_config_default() {
let config = DhtEngineConfig::default();
assert_eq!(config.refresh_check_interval, Duration::from_secs(300));
assert_eq!(config.max_concurrent_lookups, 16);
assert_eq!(config.port, 6881);
}
#[test]
fn test_dht_engine_state_ordering() {
assert!(DhtEngineState::Stopped < DhtEngineState::Bootstrapping);
assert!(DhtEngineState::Bootstrapping < DhtEngineState::Running);
assert!(DhtEngineState::Running < DhtEngineState::ShuttingDown);
}
#[tokio::test]
async fn test_dht_engine_start_shutdown() {
let config = DhtEngineConfig {
dht_file_path: None,
..DhtEngineConfig::local()
};
let engine = DhtEngine::start(config)
.await
.expect("start should succeed");
assert_eq!(engine.state().await, DhtEngineState::Running);
engine.shutdown_async().await;
}
#[tokio::test]
async fn test_dht_engine_tries_next_port_when_first_is_occupied() {
let occupied = tokio::net::UdpSocket::bind("0.0.0.0:0")
.await
.expect("occupied UDP socket");
let first_port = occupied.local_addr().unwrap().port();
let candidate = tokio::net::UdpSocket::bind("0.0.0.0:0")
.await
.expect("candidate UDP socket");
let second_port = candidate.local_addr().unwrap().port();
drop(candidate);
let config = DhtEngineConfig {
port: first_port,
port_range: Some(vec![first_port, second_port]),
dht_file_path: None,
..DhtEngineConfig::local()
};
let engine = DhtEngine::start(config)
.await
.expect("DHT should fall back to the next available port");
assert_eq!(engine.socket.local_addr().port(), second_port);
drop(occupied);
engine.shutdown_async().await;
}
#[tokio::test]
async fn test_dht_engine_stats() {
let config = DhtEngineConfig {
dht_file_path: None,
..DhtEngineConfig::local()
};
let engine = DhtEngine::start(config)
.await
.expect("start should succeed");
let stats = engine.stats().await;
assert_eq!(stats.state, DhtEngineState::Running);
engine.shutdown_async().await;
}
#[tokio::test]
async fn test_find_peers_when_stopped() {
let config = DhtEngineConfig {
dht_file_path: None,
..DhtEngineConfig::local()
};
let engine = DhtEngine::start(config)
.await
.expect("start should succeed");
engine.shutdown();
tokio::time::sleep(Duration::from_millis(200)).await;
let result = engine.find_peers(&[0u8; 20]).await;
assert!(result.is_ok());
}
}