1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//! DHT bootstrap — resolves entry point hostnames and seeds the routing table.
//!
//! The C++ implementation uses `DHTEntryPointNameResolveCommand` with c-ares
//! for async DNS resolution of bootstrap node hostnames like
//! `router.bittorrent.com`. This Rust version uses tokio's built-in DNS
//! resolver (which delegates to the OS resolver) via `tokio::net::lookup_host`.
use super::node::DhtNode;
use super::routing_table::RoutingTable;
use std::net::SocketAddr;
/// Well-known DHT bootstrap nodes (hostname + port).
///
/// These hostnames MUST be resolved via DNS before use — they are NOT
/// IP addresses and cannot be parsed as `SocketAddr` directly.
const BOOTSTRAP_NODES: &[(&str, u16)] = &[
("router.bittorrent.com", 6881),
("dht.transmissionbt.com", 6881),
("router.utorrent.com", 6881),
("dht.aelitis.com", 6881),
];
pub struct DhtBootstrap;
impl DhtBootstrap {
/// Create provisional routing-table nodes for configured bootstrap endpoints.
///
/// Their IDs are placeholders until the remote node responds, matching the
/// original client's random-ID bootstrap node construction.
pub(crate) fn nodes_from_addresses(
addresses: impl IntoIterator<Item = SocketAddr>,
) -> Vec<DhtNode> {
use rand::SeedableRng;
let mut rng = {
let mut seed_rng = rand::rng();
rand::rngs::StdRng::from_rng(&mut seed_rng)
};
addresses
.into_iter()
.map(|addr| DhtNode::unverified(random_node_id(&mut rng), addr))
.collect()
}
/// Resolve all bootstrap node hostnames to socket addresses asynchronously.
///
/// For each hostname, performs DNS resolution via `tokio::net::lookup_host`.
/// Takes the first resolved address for each hostname. If resolution fails,
/// logs a warning and skips that node (rather than falling back to `0.0.0.0:0`
/// which would be useless).
///
/// This is the equivalent of C++ `DHTEntryPointNameResolveCommand` which
/// uses c-ares for async DNS resolution of entry point hostnames.
pub async fn resolve_bootstrap_nodes() -> Vec<DhtNode> {
Self::resolve_bootstrap_nodes_with_family(None).await
}
/// Resolve bootstrap nodes for the address family used by the UDP socket.
pub(crate) async fn resolve_bootstrap_nodes_for_family(use_ipv6: bool) -> Vec<DhtNode> {
Self::resolve_bootstrap_nodes_with_family(Some(use_ipv6)).await
}
async fn resolve_bootstrap_nodes_with_family(family: Option<bool>) -> Vec<DhtNode> {
use rand::SeedableRng;
// StdRng is Send across the async DNS lookups below.
let mut rng = {
let mut seed_rng = rand::rng();
rand::rngs::StdRng::from_rng(&mut seed_rng)
};
let mut nodes = Vec::new();
for (host, port) in BOOTSTRAP_NODES {
// Generate a random placeholder ID for the bootstrap node.
let id = random_node_id(&mut rng);
// Resolve hostname via async DNS (C++ uses c-ares here).
match tokio::net::lookup_host(format!("{}:{}", host, port)).await {
Ok(addrs) => {
if let Some(addr) = select_bootstrap_address(addrs, family) {
tracing::debug!(
"Resolved DHT bootstrap node {}:{} -> {}",
host,
port,
addr
);
nodes.push(DhtNode::unverified(id, addr));
} else {
tracing::warn!(
"DNS resolution returned no matching addresses for {}:{}",
host,
port
);
}
}
Err(e) => {
tracing::warn!(
"Failed to resolve DHT bootstrap node {}:{}: {}",
host,
port,
e
);
}
}
}
tracing::info!(
resolved = nodes.len(),
total = BOOTSTRAP_NODES.len(),
"DHT bootstrap node DNS resolution complete"
);
nodes
}
/// Resolve bootstrap nodes and add them to the routing table.
///
/// Returns the number of nodes successfully added.
pub async fn add_bootstrap_nodes_to_table(routing_table: &mut RoutingTable) -> usize {
let nodes = Self::resolve_bootstrap_nodes().await;
let count_before = routing_table.total_node_count();
for node in nodes {
routing_table.insert(node);
}
routing_table.total_node_count() - count_before
}
/// Return the list of bootstrap node hostnames as "host:port" strings.
pub fn bootstrap_node_list() -> Vec<String> {
BOOTSTRAP_NODES
.iter()
.map(|(host, port)| format!("{}:{}", host, port))
.collect()
}
}
fn random_node_id(rng: &mut impl rand::RngExt) -> [u8; 20] {
let mut id = [0u8; 20];
for byte in &mut id {
*byte = rng.random();
}
id
}
fn select_bootstrap_address(
addrs: impl IntoIterator<Item = std::net::SocketAddr>,
family: Option<bool>,
) -> Option<std::net::SocketAddr> {
addrs
.into_iter()
.find(|address| family.is_none_or(|use_ipv6| address.is_ipv6() == use_ipv6))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bootstrap_nodes_defined() {
assert!(!BOOTSTRAP_NODES.is_empty());
for (host, port) in BOOTSTRAP_NODES {
assert!(!host.is_empty());
assert!(*port > 0);
}
}
#[test]
fn bootstrap_resolution_selects_the_bound_ip_family() {
let ipv6 = "[2001:db8::1]:6881"
.parse::<std::net::SocketAddr>()
.unwrap();
let ipv4 = "192.0.2.1:6881".parse::<std::net::SocketAddr>().unwrap();
let resolver_order = [ipv6, ipv4];
assert_eq!(
super::select_bootstrap_address(resolver_order, Some(false)),
Some(ipv4)
);
assert_eq!(
super::select_bootstrap_address(resolver_order, Some(true)),
Some(ipv6)
);
assert_eq!(
super::select_bootstrap_address(resolver_order, None),
Some(ipv6)
);
}
#[tokio::test]
async fn test_resolve_bootstrap_nodes() {
// This test may fail in offline environments, so we just verify
// the function completes without panicking.
let nodes = DhtBootstrap::resolve_bootstrap_nodes().await;
// In a networked environment, at least some should resolve.
// In an offline environment, all may fail gracefully.
for node in &nodes {
assert_eq!(node.id.len(), 20);
// Resolved nodes should NOT be 0.0.0.0:0
assert_ne!(
node.addr,
"0.0.0.0:0".parse::<std::net::SocketAddr>().unwrap()
);
}
}
#[test]
fn test_bootstrap_list_strings() {
let list = DhtBootstrap::bootstrap_node_list();
assert!(!list.is_empty());
for entry in &list {
assert!(entry.contains(':'));
}
}
}