Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 27d371e

Browse files
authored
libp2p-next (#5278)
* Adapt to rust-libp2p#1440. * Further adapt to libp2p/master. * Update to libp2p-0.17 * Finishing touches. * Remove stray TODO. * Incorporate review feedback. * Remove unused import.
1 parent 8c18580 commit 27d371e

File tree

26 files changed

+1045
-677
lines changed

26 files changed

+1045
-677
lines changed

Cargo.lock

+131-86
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -175,3 +175,4 @@ members = [
175175
[profile.release]
176176
# Substrate runtime requires unwinding.
177177
panic = "unwind"
178+

bin/utils/subkey/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ derive_more = { version = "0.99.2" }
2929
sc-rpc = { version = "2.0.0-alpha.5", path = "../../../client/rpc" }
3030
jsonrpc-core-client = { version = "14.0.3", features = ["http"] }
3131
hyper = "0.12.35"
32-
libp2p = "0.16.2"
32+
libp2p = "0.17.0"
3333
serde_json = "1.0"
3434

3535
[features]

client/authority-discovery/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ codec = { package = "parity-scale-codec", default-features = false, version = "1
1818
derive_more = "0.99.2"
1919
futures = "0.3.4"
2020
futures-timer = "3.0.1"
21-
libp2p = { version = "0.16.2", default-features = false, features = ["secp256k1", "libp2p-websocket"] }
21+
libp2p = { version = "0.17.0", default-features = false, features = ["secp256k1", "libp2p-websocket"] }
2222
log = "0.4.8"
2323
prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus", version = "0.8.0-alpha.5"}
2424
prost = "0.6.1"

client/authority-discovery/src/lib.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ where
300300
.map_err(Error::EncodingProto)?;
301301

302302
self.network.put_value(
303-
hash_authority_id(key.1.as_ref())?,
303+
hash_authority_id(key.1.as_ref()),
304304
signed_addresses,
305305
);
306306
}
@@ -323,7 +323,7 @@ where
323323

324324
for authority_id in authorities.iter() {
325325
self.network
326-
.get_value(&hash_authority_id(authority_id.as_ref())?);
326+
.get_value(&hash_authority_id(authority_id.as_ref()));
327327
}
328328

329329
Ok(())
@@ -408,8 +408,8 @@ where
408408
self.addr_cache.retain_ids(&authorities);
409409
authorities
410410
.into_iter()
411-
.map(|id| hash_authority_id(id.as_ref()).map(|h| (h, id)))
412-
.collect::<Result<HashMap<_, _>>>()?
411+
.map(|id| (hash_authority_id(id.as_ref()), id))
412+
.collect::<HashMap<_, _>>()
413413
};
414414

415415
// Check if the event origins from an authority in the current authority set.
@@ -586,10 +586,8 @@ where
586586
}
587587
}
588588

589-
fn hash_authority_id(id: &[u8]) -> Result<libp2p::kad::record::Key> {
590-
libp2p::multihash::encode(libp2p::multihash::Hash::SHA2256, id)
591-
.map(|k| libp2p::kad::record::Key::new(&k))
592-
.map_err(Error::HashingAuthorityId)
589+
fn hash_authority_id(id: &[u8]) -> libp2p::kad::record::Key {
590+
libp2p::kad::record::Key::new(&libp2p::multihash::Sha2_256::digest(id))
593591
}
594592

595593
fn interval_at(start: Instant, duration: Duration) -> Interval {

client/authority-discovery/src/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ fn handle_dht_events_with_value_found_should_call_set_priority_group() {
304304

305305
// Create sample dht event.
306306

307-
let authority_id_1 = hash_authority_id(key_pair.public().as_ref()).unwrap();
307+
let authority_id_1 = hash_authority_id(key_pair.public().as_ref());
308308
let address_1: Multiaddr = "/ip6/2001:db8::".parse().unwrap();
309309

310310
let mut serialized_addresses = vec![];

client/network-gossip/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ documentation = "https://docs.rs/sc-network-gossip"
1313
[dependencies]
1414
futures = "0.3.4"
1515
futures-timer = "3.0.1"
16-
libp2p = { version = "0.16.2", default-features = false, features = ["libp2p-websocket"] }
16+
libp2p = { version = "0.17.0", default-features = false, features = ["websocket"] }
1717
log = "0.4.8"
1818
lru = "0.4.3"
1919
sc-network = { version = "0.8.0-alpha.5", path = "../network" }

client/network/Cargo.toml

+6-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ futures = "0.3.4"
2626
futures_codec = "0.3.3"
2727
futures-timer = "3.0.1"
2828
wasm-timer = "0.2"
29-
libp2p = { version = "0.16.2", default-features = false, features = ["libp2p-websocket"] }
3029
linked-hash-map = "0.5.2"
3130
linked_hash_set = "0.1.3"
3231
log = "0.4.8"
@@ -59,10 +58,16 @@ unsigned-varint = { version = "0.3.1", features = ["futures", "futures-codec"] }
5958
void = "1.0.2"
6059
zeroize = "1.0.0"
6160

61+
[dependencies.libp2p]
62+
version = "0.17.0"
63+
default-features = false
64+
features = ["websocket", "kad", "mdns", "ping", "identify", "mplex", "yamux", "noise"]
65+
6266
[dev-dependencies]
6367
async-std = "1.5"
6468
assert_matches = "1.3"
6569
env_logger = "0.7.0"
70+
libp2p = { version = "0.17.0", default-features = false, features = ["secio"] }
6671
quickcheck = "0.9.0"
6772
rand = "0.7.2"
6873
sp-keyring = { version = "2.0.0-alpha.5", path = "../../primitives/keyring" }

client/network/src/debug_info.rs

+62-46
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,15 @@
1717
use fnv::FnvHashMap;
1818
use futures::prelude::*;
1919
use libp2p::Multiaddr;
20-
use libp2p::core::nodes::listeners::ListenerId;
20+
use libp2p::core::connection::{ConnectionId, ListenerId};
2121
use libp2p::core::{ConnectedPoint, either::EitherOutput, PeerId, PublicKey};
2222
use libp2p::swarm::{IntoProtocolsHandler, IntoProtocolsHandlerSelect, ProtocolsHandler};
2323
use libp2p::swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
2424
use libp2p::identify::{Identify, IdentifyEvent, IdentifyInfo};
2525
use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess};
2626
use log::{debug, trace, error};
27-
use std::error;
27+
use smallvec::SmallVec;
28+
use std::{error, io};
2829
use std::collections::hash_map::Entry;
2930
use std::pin::Pin;
3031
use std::task::{Context, Poll};
@@ -56,14 +57,27 @@ struct NodeInfo {
5657
/// When we will remove the entry about this node from the list, or `None` if we're connected
5758
/// to the node.
5859
info_expire: Option<Instant>,
59-
/// How we're connected to the node.
60-
endpoint: ConnectedPoint,
60+
/// Non-empty list of connected endpoints, one per connection.
61+
endpoints: SmallVec<[ConnectedPoint; crate::MAX_CONNECTIONS_PER_PEER]>,
6162
/// Version reported by the remote, or `None` if unknown.
6263
client_version: Option<String>,
6364
/// Latest ping time with this node.
6465
latest_ping: Option<Duration>,
6566
}
6667

68+
impl NodeInfo {
69+
fn new(endpoint: ConnectedPoint) -> Self {
70+
let mut endpoints = SmallVec::new();
71+
endpoints.push(endpoint);
72+
NodeInfo {
73+
info_expire: None,
74+
endpoints,
75+
client_version: None,
76+
latest_ping: None,
77+
}
78+
}
79+
}
80+
6781
impl DebugInfoBehaviour {
6882
/// Builds a new `DebugInfoBehaviour`.
6983
pub fn new(
@@ -121,9 +135,9 @@ impl DebugInfoBehaviour {
121135
pub struct Node<'a>(&'a NodeInfo);
122136

123137
impl<'a> Node<'a> {
124-
/// Returns the endpoint we are connected to or were last connected to.
138+
/// Returns the endpoint of an established connection to the peer.
125139
pub fn endpoint(&self) -> &'a ConnectedPoint {
126-
&self.0.endpoint
140+
&self.0.endpoints[0] // `endpoints` are non-empty by definition
127141
}
128142

129143
/// Returns the latest version information we know of.
@@ -168,18 +182,17 @@ impl NetworkBehaviour for DebugInfoBehaviour {
168182
list
169183
}
170184

171-
fn inject_connected(&mut self, peer_id: PeerId, endpoint: ConnectedPoint) {
172-
self.ping.inject_connected(peer_id.clone(), endpoint.clone());
173-
self.identify.inject_connected(peer_id.clone(), endpoint.clone());
185+
fn inject_connected(&mut self, peer_id: &PeerId) {
186+
self.ping.inject_connected(peer_id);
187+
self.identify.inject_connected(peer_id);
188+
}
174189

175-
match self.nodes_info.entry(peer_id) {
190+
fn inject_connection_established(&mut self, peer_id: &PeerId, conn: &ConnectionId, endpoint: &ConnectedPoint) {
191+
self.ping.inject_connection_established(peer_id, conn, endpoint);
192+
self.identify.inject_connection_established(peer_id, conn, endpoint);
193+
match self.nodes_info.entry(peer_id.clone()) {
176194
Entry::Vacant(e) => {
177-
e.insert(NodeInfo {
178-
info_expire: None,
179-
endpoint,
180-
client_version: None,
181-
latest_ping: None,
182-
});
195+
e.insert(NodeInfo::new(endpoint.clone()));
183196
}
184197
Entry::Occupied(e) => {
185198
let e = e.into_mut();
@@ -188,14 +201,26 @@ impl NetworkBehaviour for DebugInfoBehaviour {
188201
e.latest_ping = None;
189202
}
190203
e.info_expire = None;
191-
e.endpoint = endpoint;
204+
e.endpoints.push(endpoint.clone());
192205
}
193206
}
194207
}
195208

196-
fn inject_disconnected(&mut self, peer_id: &PeerId, endpoint: ConnectedPoint) {
197-
self.ping.inject_disconnected(peer_id, endpoint.clone());
198-
self.identify.inject_disconnected(peer_id, endpoint);
209+
fn inject_connection_closed(&mut self, peer_id: &PeerId, conn: &ConnectionId, endpoint: &ConnectedPoint) {
210+
self.ping.inject_connection_closed(peer_id, conn, endpoint);
211+
self.identify.inject_connection_closed(peer_id, conn, endpoint);
212+
213+
if let Some(entry) = self.nodes_info.get_mut(peer_id) {
214+
entry.endpoints.retain(|ep| ep != endpoint)
215+
} else {
216+
error!(target: "sub-libp2p",
217+
"Unknown connection to {:?} closed: {:?}", peer_id, endpoint);
218+
}
219+
}
220+
221+
fn inject_disconnected(&mut self, peer_id: &PeerId) {
222+
self.ping.inject_disconnected(peer_id);
223+
self.identify.inject_disconnected(peer_id);
199224

200225
if let Some(entry) = self.nodes_info.get_mut(peer_id) {
201226
entry.info_expire = Some(Instant::now() + CACHE_EXPIRE);
@@ -205,26 +230,15 @@ impl NetworkBehaviour for DebugInfoBehaviour {
205230
}
206231
}
207232

208-
fn inject_node_event(
233+
fn inject_event(
209234
&mut self,
210235
peer_id: PeerId,
236+
connection: ConnectionId,
211237
event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent
212238
) {
213239
match event {
214-
EitherOutput::First(event) => self.ping.inject_node_event(peer_id, event),
215-
EitherOutput::Second(event) => self.identify.inject_node_event(peer_id, event),
216-
}
217-
}
218-
219-
fn inject_replaced(&mut self, peer_id: PeerId, closed_endpoint: ConnectedPoint, new_endpoint: ConnectedPoint) {
220-
self.ping.inject_replaced(peer_id.clone(), closed_endpoint.clone(), new_endpoint.clone());
221-
self.identify.inject_replaced(peer_id.clone(), closed_endpoint, new_endpoint.clone());
222-
223-
if let Some(entry) = self.nodes_info.get_mut(&peer_id) {
224-
entry.endpoint = new_endpoint;
225-
} else {
226-
error!(target: "sub-libp2p",
227-
"Disconnected from node we were not connected to {:?}", peer_id);
240+
EitherOutput::First(event) => self.ping.inject_event(peer_id, connection, event),
241+
EitherOutput::Second(event) => self.identify.inject_event(peer_id, connection, event),
228242
}
229243
}
230244

@@ -258,9 +272,9 @@ impl NetworkBehaviour for DebugInfoBehaviour {
258272
self.identify.inject_listener_error(id, err);
259273
}
260274

261-
fn inject_listener_closed(&mut self, id: ListenerId) {
262-
self.ping.inject_listener_closed(id);
263-
self.identify.inject_listener_closed(id);
275+
fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &io::Error>) {
276+
self.ping.inject_listener_closed(id, reason);
277+
self.identify.inject_listener_closed(id, reason);
264278
}
265279

266280
fn poll(
@@ -283,11 +297,12 @@ impl NetworkBehaviour for DebugInfoBehaviour {
283297
},
284298
Poll::Ready(NetworkBehaviourAction::DialAddress { address }) =>
285299
return Poll::Ready(NetworkBehaviourAction::DialAddress { address }),
286-
Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id }) =>
287-
return Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id }),
288-
Poll::Ready(NetworkBehaviourAction::SendEvent { peer_id, event }) =>
289-
return Poll::Ready(NetworkBehaviourAction::SendEvent {
300+
Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }) =>
301+
return Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }),
302+
Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, handler, event }) =>
303+
return Poll::Ready(NetworkBehaviourAction::NotifyHandler {
290304
peer_id,
305+
handler,
291306
event: EitherOutput::First(event)
292307
}),
293308
Poll::Ready(NetworkBehaviourAction::ReportObservedAddr { address }) =>
@@ -312,11 +327,12 @@ impl NetworkBehaviour for DebugInfoBehaviour {
312327
},
313328
Poll::Ready(NetworkBehaviourAction::DialAddress { address }) =>
314329
return Poll::Ready(NetworkBehaviourAction::DialAddress { address }),
315-
Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id }) =>
316-
return Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id }),
317-
Poll::Ready(NetworkBehaviourAction::SendEvent { peer_id, event }) =>
318-
return Poll::Ready(NetworkBehaviourAction::SendEvent {
330+
Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }) =>
331+
return Poll::Ready(NetworkBehaviourAction::DialPeer { peer_id, condition }),
332+
Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, handler, event }) =>
333+
return Poll::Ready(NetworkBehaviourAction::NotifyHandler {
319334
peer_id,
335+
handler,
320336
event: EitherOutput::Second(event)
321337
}),
322338
Poll::Ready(NetworkBehaviourAction::ReportObservedAddr { address }) =>

0 commit comments

Comments
 (0)