use futures::stream::{FuturesUnordered, StreamExt};
use std::net::SocketAddr;
use tracing::debug;
use super::super::lookup::{
iterative_get_item, iterative_get_item_for_publish, iterative_sample_infohashes, mark_node_bad,
};
use super::super::modern::{
MutableValue, SampleInfoHashesResponse, StoredItem, put_immutable_query, put_query,
};
use super::super::node::DhtNode;
use super::super::task_impl::PingTask;
use super::super::task_peer::PeerLookupTask;
use super::super::tracker::QueryType;
use super::{DhtEngine, DhtEngineState, FindPeersResult};
impl DhtEngine {
pub fn local_addr(&self) -> SocketAddr {
self.context.task_context.socket.local_addr()
}
pub async fn find_peers(&self, info_hash: &[u8; 20]) -> std::io::Result<FindPeersResult> {
self.run_peer_lookup(info_hash, 0, "DHT peer lookup task was cancelled")
.await
}
pub async fn find_peers_and_announce(
&self,
info_hash: &[u8; 20],
port: u16,
) -> std::io::Result<FindPeersResult> {
self.run_peer_lookup(info_hash, port, "DHT peer lookup task was cancelled")
.await
}
async fn run_peer_lookup(
&self,
info_hash: &[u8; 20],
announce_port: u16,
cancelled_message: &'static str,
) -> std::io::Result<FindPeersResult> {
let state = self.state().await;
if state != DhtEngineState::Running && state != DhtEngineState::Bootstrapping {
return Ok(FindPeersResult {
peers: vec![],
nodes_contacted: 0,
});
}
debug!(
info_hash = %hex::encode(info_hash),
announce_port,
"Starting DHT peer lookup"
);
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
let accepted = self
.task_queue
.add_immediate_task(Box::new(PeerLookupTask::new(
self.context.task_context.clone(),
*info_hash,
announce_port,
Some(result_tx),
)))
.await;
if !accepted {
return Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
cancelled_message,
));
}
let result = result_rx
.await
.map_err(|_| std::io::Error::new(std::io::ErrorKind::Interrupted, cancelled_message))?;
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<()> {
self.find_peers_and_announce(info_hash, port).await?;
Ok(())
}
pub async fn sample_infohashes(
&self,
target: &[u8; 20],
) -> std::io::Result<Option<SampleInfoHashesResponse>> {
if !matches!(
self.state().await,
DhtEngineState::Running | DhtEngineState::Bootstrapping
) {
return Ok(None);
}
Ok(iterative_sample_infohashes(
target,
&self.context.task_context.self_id,
&self.context.task_context.routing_table,
&self.context.task_context.socket,
&self.context.task_context.tracker,
self.context.task_context.query_timeout,
)
.await
.response)
}
pub async fn get_item(
&self,
target: &[u8; 20],
seq: Option<i64>,
) -> std::io::Result<Option<StoredItem>> {
Ok(iterative_get_item(
target,
seq,
&self.context.task_context.self_id,
&self.context.task_context.routing_table,
&self.context.task_context.socket,
&self.context.task_context.tracker,
self.context.task_context.query_timeout,
)
.await
.item
.filter(StoredItem::verify_target))
}
pub async fn put_immutable(
&self,
value: &crate::bittorrent::bencode::codec::BencodeValue,
) -> std::io::Result<bool> {
let target = StoredItem::immutable_target(value);
let lookup = iterative_get_item_for_publish(
&target,
None,
&self.context.task_context.self_id,
&self.context.task_context.routing_table,
&self.context.task_context.socket,
&self.context.task_context.tracker,
self.context.task_context.query_timeout,
)
.await;
self.publish_immutable_to_tokens(&lookup.token_nodes, value)
.await
}
pub async fn put_mutable(
&self,
item: &MutableValue,
cas: Option<i64>,
) -> std::io::Result<bool> {
if !item.verify_signature() {
return Ok(false);
}
let target = StoredItem::mutable_target(&item.public_key, item.salt.as_deref());
let lookup = iterative_get_item_for_publish(
&target,
None,
&self.context.task_context.self_id,
&self.context.task_context.routing_table,
&self.context.task_context.socket,
&self.context.task_context.tracker,
self.context.task_context.query_timeout,
)
.await;
self.publish_mutable_to_tokens(&lookup.token_nodes, item, cas)
.await
}
async fn publish_immutable_to_tokens(
&self,
token_nodes: &[(SocketAddr, [u8; 20], Vec<u8>)],
value: &crate::bittorrent::bencode::codec::BencodeValue,
) -> std::io::Result<bool> {
let mut sends = FuturesUnordered::new();
let task_context = &self.context.task_context;
for (addr, node_id, token) in token_nodes.iter().take(8) {
let (tx, wait) = task_context.tracker.allocate_wait(
QueryType::Put,
*addr,
task_context.query_timeout,
);
let message = put_immutable_query(tx, &task_context.self_id, token, value);
let encoded = message.encode();
let socket = task_context.socket.clone();
let addr = *addr;
let node_id = *node_id;
let routing_table = task_context.routing_table.clone();
sends.push(async move {
if socket.send_to(addr, &encoded).await.is_err() {
return false;
}
let response = wait.wait().await;
if response.is_none() {
mark_node_bad(&node_id, &routing_table).await;
}
response.is_some_and(|response| response.message.is_response())
});
}
let mut accepted = false;
while let Some(result) = sends.next().await {
accepted |= result;
}
Ok(accepted)
}
async fn publish_mutable_to_tokens(
&self,
token_nodes: &[(SocketAddr, [u8; 20], Vec<u8>)],
item: &MutableValue,
cas: Option<i64>,
) -> std::io::Result<bool> {
let mut sends = FuturesUnordered::new();
let task_context = &self.context.task_context;
for (addr, node_id, token) in token_nodes.iter().take(8) {
let (tx, wait) = task_context.tracker.allocate_wait(
QueryType::Put,
*addr,
task_context.query_timeout,
);
let message = put_query(tx, &task_context.self_id, token, item, cas);
let encoded = message.encode();
let socket = task_context.socket.clone();
let addr = *addr;
let node_id = *node_id;
let routing_table = task_context.routing_table.clone();
sends.push(async move {
if socket.send_to(addr, &encoded).await.is_err() {
return false;
}
let response = wait.wait().await;
if response.is_none() {
mark_node_bad(&node_id, &routing_table).await;
}
response.is_some_and(|response| response.message.is_response())
});
}
let mut accepted = false;
while let Some(result) = sends.next().await {
accepted |= result;
}
Ok(accepted)
}
pub async fn add_node(&self, addr: SocketAddr) {
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
let accepted = self
.task_queue
.add_immediate_task(Box::new(PingTask::new(
self.context.task_context.clone(),
DhtNode::new([0u8; 20], addr),
0,
Some(result_tx),
)))
.await;
if !accepted {
return;
}
if let Ok(Some(node)) = result_rx.await {
debug!(
addr = %addr,
id = %hex::encode(node.id),
"Added DHT node via add_node"
);
}
}
}