-
Notifications
You must be signed in to change notification settings - Fork 3
/
discovery.rs
323 lines (283 loc) · 10.9 KB
/
discovery.rs
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Copyright 2023 Alexandru Vasile
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use crate::utils::{build_swarm, is_public_address, Location, Locator};
use codec::Decode;
use futures::StreamExt;
use libp2p::{
identify::Info,
kad::{GetClosestPeersError, GetClosestPeersOk, KademliaEvent, QueryId, QueryResult},
multiaddr::Protocol,
swarm::SwarmEvent,
Multiaddr, PeerId, Swarm,
};
use std::time::Duration;
use std::{cmp::Reverse, error::Error};
use std::{
collections::{hash_map::Entry, HashMap, HashSet},
net::IpAddr,
};
use subp2p_explorer::{
notifications::{behavior::NotificationsToSwarm, messages::ProtocolRole},
peer_behavior::PeerInfoEvent,
Behaviour, BehaviourEvent,
};
use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts},
TokioAsyncResolver,
};
struct NetworkDiscovery {
/// Drive the network behavior.
swarm: Swarm<Behaviour>,
/// In flight kademlia queries.
queries: HashSet<QueryId>,
/// Discovered peers by kademlia queries.
discovered_with_addresses: HashMap<PeerId, HashSet<Multiaddr>>,
/// Peer details including protocols, multiaddress.
peer_details: HashMap<PeerId, Info>,
/// Peers that announced their role.
peer_role: HashMap<PeerId, ProtocolRole>,
/// Peers dialed.
dialed_peers: HashMap<PeerId, usize>,
}
impl NetworkDiscovery {
/// Constructs a new [`NetworkDiscovery`].
pub fn new(swarm: Swarm<Behaviour>) -> Self {
Self {
swarm,
queries: HashSet::with_capacity(1024),
discovered_with_addresses: HashMap::with_capacity(1024),
peer_details: HashMap::with_capacity(1024),
peer_role: HashMap::with_capacity(1024),
dialed_peers: HashMap::with_capacity(1024),
}
}
/// Insert a number of queries to randomly walk the DHT.
///
/// Performs a Kademlia query that returns a number of closest peers up to
/// the replication factor (k = 20 for substrate chains).
fn insert_queries(&mut self, num: usize) {
for _ in 0..num {
self.queries.insert(
self.swarm
.behaviour_mut()
.discovery
.get_closest_peers(PeerId::random()),
);
}
}
/// Track the dialed peers in response of an [`SwarmEvent::Dialing`] event.
fn dialed_peer(&mut self, peer_id: Option<PeerId>) {
// Record how many times have we dialed a peer.
let Some(peer_id) = peer_id else { return };
self.dialed_peers
.entry(peer_id)
.and_modify(|num| *num += 1)
.or_insert(0);
}
/// Drive the network behavior events.
pub async fn drive_events(&mut self) {
// Start by performing 128 queries.
self.insert_queries(128);
let mut old_log_time = std::time::Instant::now();
loop {
let event = self.swarm.select_next_some().await;
match event {
SwarmEvent::Dialing { peer_id, .. } => {
self.dialed_peer(peer_id);
}
SwarmEvent::Behaviour(BehaviourEvent::Discovery(event)) => match event {
KademliaEvent::OutboundQueryProgressed {
id,
result: QueryResult::GetClosestPeers(result),
..
} => {
self.queries.remove(&id);
// It might be possible that the query did not finish in 5 minutes.
// However we capture the provided peers.
// Peers are later reported by kademila events handled below.
let peers = match result {
Ok(GetClosestPeersOk { peers, .. }) => peers,
Err(GetClosestPeersError::Timeout { peers, .. }) => peers,
};
let num_discovered = peers.len();
let now = std::time::Instant::now();
if now.duration_since(old_log_time) > Duration::from_secs(10) {
old_log_time = now;
log::info!("...Discovery in progress last_query_num={num_discovered}");
}
if self.queries.is_empty() {
self.insert_queries(128);
}
}
KademliaEvent::RoutingUpdated {
peer, addresses, ..
} => {
match self.discovered_with_addresses.entry(peer) {
Entry::Occupied(mut occupied) => {
occupied.get_mut().extend(addresses.into_vec());
}
Entry::Vacant(vacant) => {
vacant.insert(addresses.iter().cloned().collect());
}
};
}
KademliaEvent::RoutablePeer { peer, address }
| KademliaEvent::PendingRoutablePeer { peer, address } => {
match self.discovered_with_addresses.entry(peer) {
Entry::Occupied(mut occupied) => {
occupied.get_mut().insert(address);
}
Entry::Vacant(vacant) => {
let mut set = HashSet::new();
set.insert(address);
vacant.insert(set);
}
};
}
_ => (),
},
SwarmEvent::Behaviour(BehaviourEvent::PeerInfo(info_event)) => match info_event {
PeerInfoEvent::Identified { peer_id, info } => {
log::debug!("Identified peer_id={:?} info={:?}", peer_id, info);
self.peer_details.insert(peer_id, info);
}
},
SwarmEvent::Behaviour(BehaviourEvent::Notifications(
NotificationsToSwarm::CustomProtocolOpen {
peer_id,
index,
received_handshake,
inbound,
..
},
)) => {
if let Ok(role) = ProtocolRole::decode(&mut &received_handshake[..]) {
log::debug!("Identified peer_id={:?} role={:?}", peer_id, role);
self.peer_role.insert(peer_id, role);
}
log::debug!(
"Protocol open peer={:?} index={:?} handshake={:?} inbound={:?}",
peer_id,
index,
received_handshake,
inbound
);
}
_ => (),
}
}
}
}
pub async fn discover_network(
genesis: String,
bootnodes: Vec<String>,
num_cities: Option<usize>,
raw_geolocation: bool,
only_authorities: bool,
timeout: std::time::Duration,
) -> Result<(), Box<dyn Error>> {
let swarm = build_swarm(genesis.clone(), bootnodes)?;
let mut network_discovery = NetworkDiscovery::new(swarm);
// Drive network events for a few minutes.
let _ = tokio::time::timeout(timeout, network_discovery.drive_events()).await;
println!("Dialed num={} peers", network_discovery.dialed_peers.len());
println!(
"Discovered num={} peers",
network_discovery.discovered_with_addresses.len()
);
let infos: HashMap<_, _> = network_discovery
.peer_details
.iter()
.filter(|(_peer, info)| {
info.protocols
.iter()
.any(|stream_proto| stream_proto.as_ref().contains(&genesis))
})
.collect();
println!(
"Peers with identity num={}",
network_discovery.peer_details.len()
);
println!("Peers that support our genesis hash {:?}", infos.len());
let peers_with_public_addr: HashMap<_, _> = infos
.iter()
.filter(|(_peer, info)| info.listen_addrs.iter().any(is_public_address))
.collect();
println!(
" Peers with public addresses {:?}",
peers_with_public_addr.len()
);
println!(
" Peers with private addresses {:?}",
infos.len() - peers_with_public_addr.len()
);
println!(
"Peers with role associated num={}",
network_discovery.peer_role.len()
);
if only_authorities {
let authorities = network_discovery
.peer_role
.iter()
.filter_map(|(peer, role)| {
if *role == ProtocolRole::Authority {
Some(peer)
} else {
None
}
});
for peer in authorities {
println!(
"authority={peer} version={:?}",
network_discovery
.peer_details
.get(peer)
.map(|info| info.agent_version.clone())
);
}
}
let locator = Locator::new();
let mut cities: HashMap<String, usize> = HashMap::new();
let mut geolocated_peers: HashMap<PeerId, Location> = HashMap::new();
// Resolver for DNS addresses.
let resolver = TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default());
for (peer, info) in infos {
for addr in &info.listen_addrs {
let located = match addr.iter().next() {
Some(Protocol::Ip4(ip)) => locator.locate(IpAddr::V4(ip)),
Some(Protocol::Ip6(ip)) => locator.locate(IpAddr::V6(ip)),
Some(Protocol::Dns(dns))
| Some(Protocol::Dns4(dns))
| Some(Protocol::Dns6(dns)) => {
let Ok(lookup) = resolver.lookup_ip(dns.to_string()).await else {
continue;
};
lookup.iter().find_map(|ip| locator.locate(ip))
}
_ => continue,
};
let Some(located) = located else { continue };
cities
.entry(located.city.clone())
.and_modify(|num| *num += 1)
.or_insert(1);
geolocated_peers.insert(peer.clone(), located);
break;
}
}
// Print top k cities.
let mut cities: Vec<_> = cities.iter().collect();
cities.sort_by_key(|data| Reverse(*data.1));
let iter = cities.iter().take(num_cities.unwrap_or(10));
for (city, count) in iter {
println!(" City={city} peers={count}");
}
if raw_geolocation {
println!();
for (peer, location) in geolocated_peers {
println!(" Peer {peer}: {location:?}");
}
}
Ok(())
}