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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use crate::utils::interval;
use fnv::FnvHashMap;
use futures::prelude::*;
use libp2p::{
core::{
connection::{ConnectionId, ListenerId},
either::EitherOutput,
ConnectedPoint, PeerId, PublicKey,
},
identify::{Identify, IdentifyConfig, IdentifyEvent, IdentifyInfo},
ping::{Ping, PingConfig, PingEvent, PingSuccess},
swarm::{
IntoProtocolsHandler, IntoProtocolsHandlerSelect, NetworkBehaviour, NetworkBehaviourAction,
PollParameters, ProtocolsHandler,
},
Multiaddr,
};
use log::{debug, error, trace};
use smallvec::SmallVec;
use std::{
collections::hash_map::Entry,
error, io,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use wasm_timer::Instant;
const CACHE_EXPIRE: Duration = Duration::from_secs(10 * 60);
const GARBAGE_COLLECT_INTERVAL: Duration = Duration::from_secs(2 * 60);
pub struct PeerInfoBehaviour {
ping: Ping,
identify: Identify,
nodes_info: FnvHashMap<PeerId, NodeInfo>,
garbage_collect: Pin<Box<dyn Stream<Item = ()> + Send>>,
}
#[derive(Debug)]
struct NodeInfo {
info_expire: Option<Instant>,
endpoints: SmallVec<[ConnectedPoint; crate::MAX_CONNECTIONS_PER_PEER]>,
client_version: Option<String>,
latest_ping: Option<Duration>,
}
impl NodeInfo {
fn new(endpoint: ConnectedPoint) -> Self {
let mut endpoints = SmallVec::new();
endpoints.push(endpoint);
NodeInfo { info_expire: None, endpoints, client_version: None, latest_ping: None }
}
}
impl PeerInfoBehaviour {
pub fn new(user_agent: String, local_public_key: PublicKey) -> Self {
let identify = {
let cfg = IdentifyConfig::new("/substrate/1.0".to_string(), local_public_key)
.with_agent_version(user_agent);
Identify::new(cfg)
};
PeerInfoBehaviour {
ping: Ping::new(PingConfig::new()),
identify,
nodes_info: FnvHashMap::default(),
garbage_collect: Box::pin(interval(GARBAGE_COLLECT_INTERVAL)),
}
}
pub fn node(&self, peer_id: &PeerId) -> Option<Node> {
self.nodes_info.get(peer_id).map(Node)
}
fn handle_ping_report(&mut self, peer_id: &PeerId, ping_time: Duration) {
trace!(target: "sub-libp2p", "Ping time with {:?}: {:?}", peer_id, ping_time);
if let Some(entry) = self.nodes_info.get_mut(peer_id) {
entry.latest_ping = Some(ping_time);
} else {
error!(target: "sub-libp2p",
"Received ping from node we're not connected to {:?}", peer_id);
}
}
fn handle_identify_report(&mut self, peer_id: &PeerId, info: &IdentifyInfo) {
trace!(target: "sub-libp2p", "Identified {:?} => {:?}", peer_id, info);
if let Some(entry) = self.nodes_info.get_mut(peer_id) {
entry.client_version = Some(info.agent_version.clone());
} else {
error!(target: "sub-libp2p",
"Received pong from node we're not connected to {:?}", peer_id);
}
}
}
pub struct Node<'a>(&'a NodeInfo);
impl<'a> Node<'a> {
pub fn endpoint(&self) -> Option<&'a ConnectedPoint> {
self.0.endpoints.get(0)
}
pub fn client_version(&self) -> Option<&'a str> {
self.0.client_version.as_deref()
}
pub fn latest_ping(&self) -> Option<Duration> {
self.0.latest_ping
}
}
#[derive(Debug)]
pub enum PeerInfoEvent {
Identified {
peer_id: PeerId,
info: IdentifyInfo,
},
}
impl NetworkBehaviour for PeerInfoBehaviour {
type ProtocolsHandler = IntoProtocolsHandlerSelect<
<Ping as NetworkBehaviour>::ProtocolsHandler,
<Identify as NetworkBehaviour>::ProtocolsHandler,
>;
type OutEvent = PeerInfoEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler {
IntoProtocolsHandler::select(self.ping.new_handler(), self.identify.new_handler())
}
fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
let mut list = self.ping.addresses_of_peer(peer_id);
list.extend_from_slice(&self.identify.addresses_of_peer(peer_id));
list
}
fn inject_connected(&mut self, peer_id: &PeerId) {
self.ping.inject_connected(peer_id);
self.identify.inject_connected(peer_id);
}
fn inject_connection_established(
&mut self,
peer_id: &PeerId,
conn: &ConnectionId,
endpoint: &ConnectedPoint,
) {
self.ping.inject_connection_established(peer_id, conn, endpoint);
self.identify.inject_connection_established(peer_id, conn, endpoint);
match self.nodes_info.entry(peer_id.clone()) {
Entry::Vacant(e) => {
e.insert(NodeInfo::new(endpoint.clone()));
},
Entry::Occupied(e) => {
let e = e.into_mut();
if e.info_expire.as_ref().map(|exp| *exp < Instant::now()).unwrap_or(false) {
e.client_version = None;
e.latest_ping = None;
}
e.info_expire = None;
e.endpoints.push(endpoint.clone());
},
}
}
fn inject_connection_closed(
&mut self,
peer_id: &PeerId,
conn: &ConnectionId,
endpoint: &ConnectedPoint,
) {
self.ping.inject_connection_closed(peer_id, conn, endpoint);
self.identify.inject_connection_closed(peer_id, conn, endpoint);
if let Some(entry) = self.nodes_info.get_mut(peer_id) {
entry.endpoints.retain(|ep| ep != endpoint)
} else {
error!(target: "sub-libp2p",
"Unknown connection to {:?} closed: {:?}", peer_id, endpoint);
}
}
fn inject_disconnected(&mut self, peer_id: &PeerId) {
self.ping.inject_disconnected(peer_id);
self.identify.inject_disconnected(peer_id);
if let Some(entry) = self.nodes_info.get_mut(peer_id) {
entry.info_expire = Some(Instant::now() + CACHE_EXPIRE);
} else {
error!(target: "sub-libp2p",
"Disconnected from node we were not connected to {:?}", peer_id);
}
}
fn inject_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent,
) {
match event {
EitherOutput::First(event) => self.ping.inject_event(peer_id, connection, event),
EitherOutput::Second(event) => self.identify.inject_event(peer_id, connection, event),
}
}
fn inject_addr_reach_failure(
&mut self,
peer_id: Option<&PeerId>,
addr: &Multiaddr,
error: &dyn std::error::Error,
) {
self.ping.inject_addr_reach_failure(peer_id, addr, error);
self.identify.inject_addr_reach_failure(peer_id, addr, error);
}
fn inject_dial_failure(&mut self, peer_id: &PeerId) {
self.ping.inject_dial_failure(peer_id);
self.identify.inject_dial_failure(peer_id);
}
fn inject_new_listener(&mut self, id: ListenerId) {
self.ping.inject_new_listener(id);
self.identify.inject_new_listener(id);
}
fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
self.ping.inject_new_listen_addr(id, addr);
self.identify.inject_new_listen_addr(id, addr);
}
fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
self.ping.inject_expired_listen_addr(id, addr);
self.identify.inject_expired_listen_addr(id, addr);
}
fn inject_new_external_addr(&mut self, addr: &Multiaddr) {
self.ping.inject_new_external_addr(addr);
self.identify.inject_new_external_addr(addr);
}
fn inject_expired_external_addr(&mut self, addr: &Multiaddr) {
self.ping.inject_expired_external_addr(addr);
self.identify.inject_expired_external_addr(addr);
}
fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn error::Error + 'static)) {
self.ping.inject_listener_error(id, err);
self.identify.inject_listener_error(id, err);
}
fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &io::Error>) {
self.ping.inject_listener_closed(id, reason);
self.identify.inject_listener_closed(id, reason);
}
fn poll(
&mut self,
cx: &mut Context,
params: &mut impl PollParameters
) -> Poll<
NetworkBehaviourAction<
<<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent,
Self::OutEvent
>
>{
loop {
match self.ping.poll(cx, params) {
Poll::Pending => break,
Poll::Ready(NetworkBehaviourAction::GenerateEvent(ev)) => {
if let PingEvent { peer, result: Ok(PingSuccess::Ping { rtt }) } = ev {
self.handle_ping_report(&peer, rtt)
}
},
Poll::Ready(NetworkBehaviourAction::DialAddress { address }) =>
return Poll::Ready(NetworkBehaviourAction::DialAddress { address }),
Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }) =>
return Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }),
Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, handler, event }) =>
return Poll::Ready(NetworkBehaviourAction::NotifyHandler {
peer_id,
handler,
event: EitherOutput::First(event),
}),
Poll::Ready(NetworkBehaviourAction::ReportObservedAddr { address, score }) =>
return Poll::Ready(NetworkBehaviourAction::ReportObservedAddr {
address,
score,
}),
}
}
loop {
match self.identify.poll(cx, params) {
Poll::Pending => break,
Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)) => match event {
IdentifyEvent::Received { peer_id, info, .. } => {
self.handle_identify_report(&peer_id, &info);
let event = PeerInfoEvent::Identified { peer_id, info };
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event))
},
IdentifyEvent::Error { peer_id, error } =>
debug!(target: "sub-libp2p", "Identification with peer {:?} failed => {}", peer_id, error),
IdentifyEvent::Pushed { .. } => {},
IdentifyEvent::Sent { .. } => {},
},
Poll::Ready(NetworkBehaviourAction::DialAddress { address }) =>
return Poll::Ready(NetworkBehaviourAction::DialAddress { address }),
Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }) =>
return Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }),
Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, handler, event }) =>
return Poll::Ready(NetworkBehaviourAction::NotifyHandler {
peer_id,
handler,
event: EitherOutput::Second(event),
}),
Poll::Ready(NetworkBehaviourAction::ReportObservedAddr { address, score }) =>
return Poll::Ready(NetworkBehaviourAction::ReportObservedAddr {
address,
score,
}),
}
}
while let Poll::Ready(Some(())) = self.garbage_collect.poll_next_unpin(cx) {
self.nodes_info.retain(|_, node| {
node.info_expire.as_ref().map(|exp| *exp >= Instant::now()).unwrap_or(true)
});
}
Poll::Pending
}
}