diff --git a/substrate/core/network-libp2p/src/error.rs b/substrate/core/network-libp2p/src/error.rs
deleted file mode 100644
index b99c84d9ee..0000000000
--- a/substrate/core/network-libp2p/src/error.rs
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright 2015-2019 Parity Technologies (UK) Ltd.
-// This file is part of Substrate.
-
-// Substrate is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Substrate is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Substrate. If not, see .
-
-use error_chain::*;
-use std::{io, net, fmt};
-
-#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub enum DisconnectReason {
- DisconnectRequested,
- TCPError,
- BadProtocol,
- UselessPeer,
- TooManyPeers,
- DuplicatePeer,
- IncompatibleProtocol,
- NullIdentity,
- ClientQuit,
- UnexpectedIdentity,
- LocalIdentity,
- PingTimeout,
- Unknown,
-}
-
-impl DisconnectReason {
- pub fn from_u8(n: u8) -> DisconnectReason {
- match n {
- 0 => DisconnectReason::DisconnectRequested,
- 1 => DisconnectReason::TCPError,
- 2 => DisconnectReason::BadProtocol,
- 3 => DisconnectReason::UselessPeer,
- 4 => DisconnectReason::TooManyPeers,
- 5 => DisconnectReason::DuplicatePeer,
- 6 => DisconnectReason::IncompatibleProtocol,
- 7 => DisconnectReason::NullIdentity,
- 8 => DisconnectReason::ClientQuit,
- 9 => DisconnectReason::UnexpectedIdentity,
- 10 => DisconnectReason::LocalIdentity,
- 11 => DisconnectReason::PingTimeout,
- _ => DisconnectReason::Unknown,
- }
- }
-}
-
-impl fmt::Display for DisconnectReason {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use self::DisconnectReason::*;
-
- let msg = match *self {
- DisconnectRequested => "disconnect requested",
- TCPError => "TCP error",
- BadProtocol => "bad protocol",
- UselessPeer => "useless peer",
- TooManyPeers => "too many peers",
- DuplicatePeer => "duplicate peer",
- IncompatibleProtocol => "incompatible protocol",
- NullIdentity => "null identity",
- ClientQuit => "client quit",
- UnexpectedIdentity => "unexpected identity",
- LocalIdentity => "local identity",
- PingTimeout => "ping timeout",
- Unknown => "unknown",
- };
-
- f.write_str(msg)
- }
-}
-
-error_chain! {
- errors {
- #[doc = "Error concerning the network address parsing subsystem."]
- AddressParse {
- description("Failed to parse network address"),
- display("Failed to parse network address"),
- }
-
- #[doc = "Error concerning the network address resolution subsystem."]
- AddressResolve(err: Option) {
- description("Failed to resolve network address"),
- display("Failed to resolve network address {}", err.as_ref().map_or("".to_string(), |e| e.to_string())),
- }
-
- #[doc = "Authentication failure"]
- Auth {
- description("Authentication failure"),
- display("Authentication failure"),
- }
-
- #[doc = "Unrecognised protocol"]
- BadProtocol {
- description("Bad protocol"),
- display("Bad protocol"),
- }
-
- #[doc = "Expired message"]
- Expired {
- description("Expired message"),
- display("Expired message"),
- }
-
- #[doc = "Peer not found"]
- PeerNotFound {
- description("Peer not found"),
- display("Peer not found"),
- }
-
- #[doc = "Peer is disconnected"]
- Disconnect(reason: DisconnectReason) {
- description("Peer disconnected"),
- display("Peer disconnected: {}", reason),
- }
-
- #[doc = "Invalid node id"]
- InvalidNodeId {
- description("Invalid node id"),
- display("Invalid node id"),
- }
-
- #[doc = "Packet size is over the protocol limit"]
- OversizedPacket {
- description("Packet is too large"),
- display("Packet is too large"),
- }
-
- #[doc = "An unknown IO error occurred."]
- Io(err: io::Error) {
- description("IO Error"),
- display("Unexpected IO error: {}", err),
- }
- }
-}
-
-impl From for Error {
- fn from(err: io::Error) -> Self {
- Error::from_kind(ErrorKind::Io(err))
- }
-}
-
-impl From for Error {
- fn from(_err: net::AddrParseError) -> Self { ErrorKind::AddressParse.into() }
-}
-
-#[test]
-fn test_errors() {
- assert_eq!(DisconnectReason::ClientQuit, DisconnectReason::from_u8(8));
- let mut r = DisconnectReason::DisconnectRequested;
- for i in 0 .. 20 {
- r = DisconnectReason::from_u8(i);
- }
- assert_eq!(DisconnectReason::Unknown, r);
-}
diff --git a/substrate/core/network-libp2p/src/lib.rs b/substrate/core/network-libp2p/src/lib.rs
index 5d1f248451..a6336e4163 100644
--- a/substrate/core/network-libp2p/src/lib.rs
+++ b/substrate/core/network-libp2p/src/lib.rs
@@ -18,35 +18,72 @@
mod behaviour;
mod custom_proto;
-mod error;
mod secret;
mod service_task;
mod traits;
mod transport;
pub use crate::custom_proto::{CustomMessage, CustomMessageId, RegisteredProtocol};
-pub use crate::error::{Error, ErrorKind, DisconnectReason};
pub use crate::secret::obtain_private_key;
pub use crate::service_task::{start_service, Service, ServiceEvent};
pub use crate::traits::{NetworkConfiguration, NodeIndex, NodeId, NonReservedPeerMode};
pub use crate::traits::{ProtocolId, Secret, Severity};
-pub use libp2p::{Multiaddr, multiaddr::Protocol, build_multiaddr, PeerId, core::PublicKey};
+pub use libp2p::{Multiaddr, multiaddr::Error as MultiaddrError, multiaddr::Protocol, build_multiaddr, PeerId, core::PublicKey};
use libp2p::core::nodes::ConnectedPoint;
use serde_derive::Serialize;
-use std::{collections::{HashMap, HashSet}, time::Duration};
+use std::{collections::{HashMap, HashSet}, error, fmt, time::Duration};
/// Parses a string address and returns the component, if valid.
-pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), Error> {
- let mut addr: Multiaddr = addr_str.parse().map_err(|_| ErrorKind::AddressParse)?;
+pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> {
+ let mut addr: Multiaddr = addr_str.parse()?;
+
let who = match addr.pop() {
- Some(Protocol::P2p(key)) =>
- PeerId::from_multihash(key).map_err(|_| ErrorKind::AddressParse)?,
- _ => return Err(ErrorKind::AddressParse.into()),
+ Some(Protocol::P2p(key)) => PeerId::from_multihash(key)
+ .map_err(|_| ParseErr::InvalidPeerId)?,
+ _ => return Err(ParseErr::PeerIdMissing),
};
+
Ok((who, addr))
}
+/// Error that can be generated by `parse_str_addr`.
+#[derive(Debug)]
+pub enum ParseErr {
+ /// Error while parsing the multiaddress.
+ MultiaddrParse(MultiaddrError),
+ /// Multihash of the peer ID is invalid.
+ InvalidPeerId,
+ /// The peer ID is missing from the address.
+ PeerIdMissing,
+}
+
+impl fmt::Display for ParseErr {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ ParseErr::MultiaddrParse(err) => write!(f, "{}", err),
+ ParseErr::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"),
+ ParseErr::PeerIdMissing => write!(f, "Peer id is missing from the address"),
+ }
+ }
+}
+
+impl error::Error for ParseErr {
+ fn source(&self) -> Option<&(dyn error::Error + 'static)> {
+ match self {
+ ParseErr::MultiaddrParse(err) => Some(err),
+ ParseErr::InvalidPeerId => None,
+ ParseErr::PeerIdMissing => None,
+ }
+ }
+}
+
+impl From for ParseErr {
+ fn from(err: MultiaddrError) -> ParseErr {
+ ParseErr::MultiaddrParse(err)
+ }
+}
+
/// Returns general information about the networking.
///
/// Meant for general diagnostic purposes.
diff --git a/substrate/core/network-libp2p/src/service_task.rs b/substrate/core/network-libp2p/src/service_task.rs
index a9df000809..69181b90ee 100644
--- a/substrate/core/network-libp2p/src/service_task.rs
+++ b/substrate/core/network-libp2p/src/service_task.rs
@@ -19,7 +19,7 @@ use crate::{
transport, NetworkState, NetworkStatePeer, NetworkStateNotConnectedPeer
};
use crate::custom_proto::{CustomMessage, RegisteredProtocol, RegisteredProtocols};
-use crate::{Error, NetworkConfiguration, NodeIndex, ProtocolId, parse_str_addr};
+use crate::{NetworkConfiguration, NodeIndex, ProtocolId, parse_str_addr};
use fnv::FnvHashMap;
use futures::{prelude::*, Stream};
use libp2p::{multiaddr::Protocol, Multiaddr, PeerId, build_multiaddr};
@@ -41,7 +41,7 @@ use tokio_timer::Interval;
pub fn start_service(
config: NetworkConfiguration,
registered_custom: TProtos,
-) -> Result, Error>
+) -> Result, IoError>
where TProtos: IntoIterator- >,
TMessage: CustomMessage + Send + 'static {
diff --git a/substrate/core/network/src/error.rs b/substrate/core/network/src/error.rs
index b71209f470..bf687f9969 100644
--- a/substrate/core/network/src/error.rs
+++ b/substrate/core/network/src/error.rs
@@ -22,12 +22,10 @@
use error_chain::*;
use std::io::Error as IoError;
-use network_libp2p::Error as NetworkError;
use client;
error_chain! {
foreign_links {
- Network(NetworkError) #[doc = "Devp2p error."];
Io(IoError) #[doc = "IO error."];
}
diff --git a/substrate/core/network/src/service.rs b/substrate/core/network/src/service.rs
index c0085655e3..34f82d2ddc 100644
--- a/substrate/core/network/src/service.rs
+++ b/substrate/core/network/src/service.rs
@@ -21,7 +21,7 @@ use std::{io, thread};
use log::{warn, debug, error, trace, info};
use futures::{Async, Future, Stream, stream, sync::oneshot, sync::mpsc};
use parking_lot::{Mutex, RwLock};
-use network_libp2p::{ProtocolId, NetworkConfiguration, NodeIndex, ErrorKind, Severity};
+use network_libp2p::{ProtocolId, NetworkConfiguration, NodeIndex, Severity};
use network_libp2p::{start_service, parse_str_addr, Service as NetworkService, ServiceEvent as NetworkServiceEvent};
use network_libp2p::{Protocol as Libp2pProtocol, RegisteredProtocol, NetworkState};
use consensus::import_queue::{ImportQueue, Link};
@@ -469,11 +469,7 @@ fn start_thread(
let service = match start_service(config, Some(registered)) {
Ok(service) => Arc::new(Mutex::new(service)),
Err(err) => {
- match err.kind() {
- ErrorKind::Io(ref e) if e.kind() == io::ErrorKind::AddrInUse =>
- warn!("Network port is already in use, make sure that another instance of Substrate client is not running or change the port using the --port option."),
- _ => warn!("Error starting network: {}", err),
- };
+ warn!("Error starting network: {}", err);
return Err(err.into())
},
};