1#![allow(clippy::enum_variant_names)]
23
24use crate::{
27 protocol::Direction,
28 transport::manager::limits::ConnectionLimitsError,
29 types::{protocol::ProtocolName, ConnectionId, SubstreamId},
30 PeerId,
31};
32
33type Multihash = multihash::Multihash<64>;
34
35use multiaddr::Multiaddr;
36use std::io::{self, ErrorKind};
37
38#[allow(clippy::large_enum_variant)]
41#[derive(Debug, thiserror::Error)]
42pub enum Error {
43 #[error("Peer `{0}` does not exist")]
44 PeerDoesntExist(PeerId),
45 #[error("Peer `{0}` already exists")]
46 PeerAlreadyExists(PeerId),
47 #[error("Protocol `{0}` not supported")]
48 ProtocolNotSupported(String),
49 #[error("Address error: `{0}`")]
50 AddressError(#[from] AddressError),
51 #[error("Parse error: `{0}`")]
52 ParseError(ParseError),
53 #[error("I/O error: `{0}`")]
54 IoError(ErrorKind),
55 #[error("Negotiation error: `{0}`")]
56 NegotiationError(#[from] NegotiationError),
57 #[error("Substream error: `{0}`")]
58 SubstreamError(#[from] SubstreamError),
59 #[error("Substream error: `{0}`")]
60 NotificationError(NotificationError),
61 #[error("Essential task closed")]
62 EssentialTaskClosed,
63 #[error("Unknown error occurred")]
64 Unknown,
65 #[error("Cannot dial self: `{0}`")]
66 CannotDialSelf(Multiaddr),
67 #[error("Transport not supported")]
68 TransportNotSupported(Multiaddr),
69 #[error("Yamux error for substream `{0:?}`: `{1}`")]
70 YamuxError(Direction, crate::yamux::ConnectionError),
71 #[error("Operation not supported: `{0}`")]
72 NotSupported(String),
73 #[error("Other error occurred: `{0}`")]
74 Other(String),
75 #[error("Protocol already exists: `{0:?}`")]
76 ProtocolAlreadyExists(ProtocolName),
77 #[error("Operation timed out")]
78 Timeout,
79 #[error("Invalid state transition")]
80 InvalidState,
81 #[error("DNS address resolution failed")]
82 DnsAddressResolutionFailed,
83 #[error("Transport error: `{0}`")]
84 TransportError(String),
85 #[cfg(feature = "quic")]
86 #[error("Failed to generate certificate: `{0}`")]
87 CertificateGeneration(#[from] crate::crypto::tls::certificate::GenError),
88 #[error("Invalid data")]
89 InvalidData,
90 #[error("Input rejected")]
91 InputRejected,
92 #[cfg(feature = "websocket")]
93 #[error("WebSocket error: `{0}`")]
94 WebSocket(#[from] tokio_tungstenite::tungstenite::error::Error),
95 #[error("Insufficient peers")]
96 InsufficientPeers,
97 #[error("Substream doens't exist")]
98 SubstreamDoesntExist,
99 #[cfg(feature = "webrtc")]
100 #[error("`str0m` error: `{0}`")]
101 WebRtc(#[from] str0m::RtcError),
102 #[error("Remote peer disconnected")]
103 Disconnected,
104 #[error("Channel does not exist")]
105 ChannelDoesntExist,
106 #[error("Tried to dial self")]
107 TriedToDialSelf,
108 #[error("Litep2p is already connected to the peer")]
109 AlreadyConnected,
110 #[error("No addres available for `{0}`")]
111 NoAddressAvailable(PeerId),
112 #[error("Connection closed")]
113 ConnectionClosed,
114 #[cfg(feature = "quic")]
115 #[error("Quinn error: `{0}`")]
116 Quinn(quinn::ConnectionError),
117 #[error("Invalid certificate")]
118 InvalidCertificate,
119 #[error("Peer ID mismatch: expected `{0}`, got `{1}`")]
120 PeerIdMismatch(PeerId, PeerId),
121 #[error("Channel is clogged")]
122 ChannelClogged,
123 #[error("Connection doesn't exist: `{0:?}`")]
124 ConnectionDoesntExist(ConnectionId),
125 #[error("Exceeded connection limits `{0:?}`")]
126 ConnectionLimit(ConnectionLimitsError),
127 #[error("Failed to dial peer immediately")]
128 ImmediateDialError(#[from] ImmediateDialError),
129 #[error("Cannot read system DNS config: `{0}`")]
130 CannotReadSystemDnsConfig(hickory_resolver::ResolveError),
131}
132
133#[derive(Debug, thiserror::Error)]
135pub enum AddressError {
136 #[error("Invalid address for protocol")]
141 InvalidProtocol,
142 #[error("Invalid URL")]
144 InvalidUrl,
145 #[error("`PeerId` missing from the address")]
147 PeerIdMissing,
148 #[error("Address not available")]
150 AddressNotAvailable,
151 #[error("Multihash does not contain a valid peer ID : `{0:?}`")]
153 InvalidPeerId(Multihash),
154}
155
156#[derive(Debug, thiserror::Error, PartialEq)]
157pub enum ParseError {
158 #[error("Failed to decode protobuf message: `{0:?}`")]
160 ProstDecodeError(#[from] prost::DecodeError),
161 #[error("Failed to encode protobuf message: `{0:?}`")]
163 ProstEncodeError(#[from] prost::EncodeError),
164 #[error("Unknown key type from protobuf message: `{0}`")]
170 UnknownKeyType(i32),
171 #[error("Invalid public key")]
178 InvalidPublicKey,
179 #[error("Invalid data")]
183 InvalidData,
184 #[error("Invalid reply length")]
186 InvalidReplyLength,
187}
188
189#[derive(Debug, thiserror::Error)]
190pub enum SubstreamError {
191 #[error("Connection closed")]
193 ConnectionClosed,
194 #[error("Connection channel clogged")]
195 ChannelClogged,
196 #[error("Connection to peer does not exist: `{0}`")]
197 PeerDoesNotExist(PeerId),
198 #[error("I/O error: `{0}`")]
199 IoError(ErrorKind),
200 #[error("yamux error: `{0}`")]
201 YamuxError(crate::yamux::ConnectionError, Direction),
202 #[error("Failed to read from substream, substream id `{0:?}`")]
203 ReadFailure(Option<SubstreamId>),
204 #[error("Failed to write to substream, substream id `{0:?}`")]
205 WriteFailure(Option<SubstreamId>),
206 #[error("Negotiation error: `{0:?}`")]
207 NegotiationError(#[from] NegotiationError),
208}
209
210impl PartialEq for SubstreamError {
212 fn eq(&self, other: &Self) -> bool {
213 match (self, other) {
214 (Self::ConnectionClosed, Self::ConnectionClosed) => true,
215 (Self::ChannelClogged, Self::ChannelClogged) => true,
216 (Self::PeerDoesNotExist(lhs), Self::PeerDoesNotExist(rhs)) => lhs == rhs,
217 (Self::IoError(lhs), Self::IoError(rhs)) => lhs == rhs,
218 (Self::YamuxError(lhs, lhs_1), Self::YamuxError(rhs, rhs_1)) => {
219 if lhs_1 != rhs_1 {
220 return false;
221 }
222
223 match (lhs, rhs) {
224 (
225 crate::yamux::ConnectionError::Io(lhs),
226 crate::yamux::ConnectionError::Io(rhs),
227 ) => lhs.kind() == rhs.kind(),
228 (
229 crate::yamux::ConnectionError::Decode(lhs),
230 crate::yamux::ConnectionError::Decode(rhs),
231 ) => match (lhs, rhs) {
232 (
233 crate::yamux::FrameDecodeError::Io(lhs),
234 crate::yamux::FrameDecodeError::Io(rhs),
235 ) => lhs.kind() == rhs.kind(),
236 (
237 crate::yamux::FrameDecodeError::FrameTooLarge(lhs),
238 crate::yamux::FrameDecodeError::FrameTooLarge(rhs),
239 ) => lhs == rhs,
240 (
241 crate::yamux::FrameDecodeError::Header(lhs),
242 crate::yamux::FrameDecodeError::Header(rhs),
243 ) => match (lhs, rhs) {
244 (
245 crate::yamux::HeaderDecodeError::Version(lhs),
246 crate::yamux::HeaderDecodeError::Version(rhs),
247 ) => lhs == rhs,
248 (
249 crate::yamux::HeaderDecodeError::Type(lhs),
250 crate::yamux::HeaderDecodeError::Type(rhs),
251 ) => lhs == rhs,
252 _ => false,
253 },
254 _ => false,
255 },
256 (
257 crate::yamux::ConnectionError::NoMoreStreamIds,
258 crate::yamux::ConnectionError::NoMoreStreamIds,
259 ) => true,
260 (
261 crate::yamux::ConnectionError::Closed,
262 crate::yamux::ConnectionError::Closed,
263 ) => true,
264 (
265 crate::yamux::ConnectionError::TooManyStreams,
266 crate::yamux::ConnectionError::TooManyStreams,
267 ) => true,
268 _ => false,
269 }
270 }
271
272 (Self::ReadFailure(lhs), Self::ReadFailure(rhs)) => lhs == rhs,
273 (Self::WriteFailure(lhs), Self::WriteFailure(rhs)) => lhs == rhs,
274 (Self::NegotiationError(lhs), Self::NegotiationError(rhs)) => lhs == rhs,
275 _ => false,
276 }
277 }
278}
279
280#[derive(Debug, thiserror::Error)]
282pub enum NegotiationError {
283 #[error("multistream-select error: `{0:?}`")]
285 MultistreamSelectError(#[from] crate::multistream_select::NegotiationError),
286 #[error("multistream-select error: `{0:?}`")]
288 SnowError(#[from] snow::Error),
289 #[error("`PeerId` missing from Noise handshake")]
291 PeerIdMissing,
292 #[error("The signature of the remote identity's public key does not verify")]
294 BadSignature,
295 #[error("Operation timed out")]
297 Timeout,
298 #[error("Parse error: `{0}`")]
300 ParseError(#[from] ParseError),
301 #[error("I/O error: `{0}`")]
303 IoError(ErrorKind),
304 #[error("Expected a different state")]
306 StateMismatch,
307 #[error("Peer ID mismatch: expected `{0}`, got `{1}`")]
310 PeerIdMismatch(PeerId, PeerId),
311 #[cfg(feature = "quic")]
313 #[error("QUIC error: `{0}`")]
314 Quic(#[from] QuicError),
315 #[cfg(feature = "websocket")]
317 #[error("WebSocket error: `{0}`")]
318 WebSocket(#[from] tokio_tungstenite::tungstenite::error::Error),
319}
320
321impl PartialEq for NegotiationError {
322 fn eq(&self, other: &Self) -> bool {
323 match (self, other) {
324 (Self::MultistreamSelectError(lhs), Self::MultistreamSelectError(rhs)) => lhs == rhs,
325 (Self::SnowError(lhs), Self::SnowError(rhs)) => lhs == rhs,
326 (Self::ParseError(lhs), Self::ParseError(rhs)) => lhs == rhs,
327 (Self::IoError(lhs), Self::IoError(rhs)) => lhs == rhs,
328 (Self::PeerIdMismatch(lhs, lhs_1), Self::PeerIdMismatch(rhs, rhs_1)) =>
329 lhs == rhs && lhs_1 == rhs_1,
330 #[cfg(feature = "quic")]
331 (Self::Quic(lhs), Self::Quic(rhs)) => lhs == rhs,
332 #[cfg(feature = "websocket")]
333 (Self::WebSocket(lhs), Self::WebSocket(rhs)) =>
334 core::mem::discriminant(lhs) == core::mem::discriminant(rhs),
335 _ => core::mem::discriminant(self) == core::mem::discriminant(other),
336 }
337 }
338}
339
340#[derive(Debug, thiserror::Error)]
341pub enum NotificationError {
342 #[error("Peer already exists")]
343 PeerAlreadyExists,
344 #[error("Peer is in invalid state")]
345 InvalidState,
346 #[error("Notifications clogged")]
347 NotificationsClogged,
348 #[error("Notification stream closed")]
349 NotificationStreamClosed(PeerId),
350}
351
352#[derive(Debug, thiserror::Error)]
357pub enum DialError {
358 #[error("Dial timed out")]
363 Timeout,
364 #[error("Address error: `{0}`")]
366 AddressError(#[from] AddressError),
367 #[error("DNS lookup error for `{0}`")]
372 DnsError(#[from] DnsError),
373 #[error("Negotiation error: `{0}`")]
375 NegotiationError(#[from] NegotiationError),
376}
377
378#[derive(Debug, thiserror::Error, Copy, Clone, Eq, PartialEq)]
380pub enum ImmediateDialError {
381 #[error("`PeerId` missing from the address")]
383 PeerIdMissing,
384 #[error("Tried to dial self")]
386 TriedToDialSelf,
387 #[error("Already connected to peer")]
389 AlreadyConnected,
390 #[error("No address available for peer")]
392 NoAddressAvailable,
393 #[error("TaskClosed")]
395 TaskClosed,
396 #[error("Connection channel clogged")]
398 ChannelClogged,
399}
400
401#[cfg(feature = "quic")]
403#[derive(Debug, thiserror::Error, PartialEq)]
404pub enum QuicError {
405 #[error("Invalid certificate")]
407 InvalidCertificate,
408 #[error("Failed to negotiate QUIC: `{0}`")]
410 ConnectionError(#[from] quinn::ConnectionError),
411 #[error("Failed to connect to peer: `{0}`")]
413 ConnectError(#[from] quinn::ConnectError),
414}
415
416#[derive(Debug, thiserror::Error, PartialEq)]
418pub enum DnsError {
419 #[error("DNS failed to resolve url `{0}`")]
421 ResolveError(String),
422 #[error("DNS type is different from the provided IP address")]
426 IpVersionMismatch,
427}
428
429impl From<Multihash> for Error {
430 fn from(hash: Multihash) -> Self {
431 Error::AddressError(AddressError::InvalidPeerId(hash))
432 }
433}
434
435impl From<io::Error> for Error {
436 fn from(error: io::Error) -> Error {
437 Error::IoError(error.kind())
438 }
439}
440
441impl From<io::Error> for SubstreamError {
442 fn from(error: io::Error) -> SubstreamError {
443 SubstreamError::IoError(error.kind())
444 }
445}
446
447impl From<io::Error> for DialError {
448 fn from(error: io::Error) -> Self {
449 DialError::NegotiationError(NegotiationError::IoError(error.kind()))
450 }
451}
452
453impl From<crate::multistream_select::NegotiationError> for Error {
454 fn from(error: crate::multistream_select::NegotiationError) -> Error {
455 Error::NegotiationError(NegotiationError::MultistreamSelectError(error))
456 }
457}
458
459impl From<snow::Error> for Error {
460 fn from(error: snow::Error) -> Self {
461 Error::NegotiationError(NegotiationError::SnowError(error))
462 }
463}
464
465impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error {
466 fn from(_: tokio::sync::mpsc::error::SendError<T>) -> Self {
467 Error::EssentialTaskClosed
468 }
469}
470
471impl From<tokio::sync::oneshot::error::RecvError> for Error {
472 fn from(_: tokio::sync::oneshot::error::RecvError) -> Self {
473 Error::EssentialTaskClosed
474 }
475}
476
477impl From<prost::DecodeError> for Error {
478 fn from(error: prost::DecodeError) -> Self {
479 Error::ParseError(ParseError::ProstDecodeError(error))
480 }
481}
482
483impl From<prost::EncodeError> for Error {
484 fn from(error: prost::EncodeError) -> Self {
485 Error::ParseError(ParseError::ProstEncodeError(error))
486 }
487}
488
489impl From<io::Error> for NegotiationError {
490 fn from(error: io::Error) -> Self {
491 NegotiationError::IoError(error.kind())
492 }
493}
494
495impl From<ParseError> for Error {
496 fn from(error: ParseError) -> Self {
497 Error::ParseError(error)
498 }
499}
500
501impl From<Multihash> for AddressError {
502 fn from(hash: Multihash) -> Self {
503 AddressError::InvalidPeerId(hash)
504 }
505}
506
507#[cfg(feature = "quic")]
508impl From<quinn::ConnectionError> for Error {
509 fn from(error: quinn::ConnectionError) -> Self {
510 match error {
511 quinn::ConnectionError::TimedOut => Error::Timeout,
512 error => Error::Quinn(error),
513 }
514 }
515}
516
517#[cfg(feature = "quic")]
518impl From<quinn::ConnectionError> for DialError {
519 fn from(error: quinn::ConnectionError) -> Self {
520 match error {
521 quinn::ConnectionError::TimedOut => DialError::Timeout,
522 error => DialError::NegotiationError(NegotiationError::Quic(error.into())),
523 }
524 }
525}
526
527#[cfg(feature = "quic")]
528impl From<quinn::ConnectError> for DialError {
529 fn from(error: quinn::ConnectError) -> Self {
530 DialError::NegotiationError(NegotiationError::Quic(error.into()))
531 }
532}
533
534impl From<ConnectionLimitsError> for Error {
535 fn from(error: ConnectionLimitsError) -> Self {
536 Error::ConnectionLimit(error)
537 }
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543 use tokio::sync::mpsc::{channel, Sender};
544
545 #[tokio::test]
546 async fn try_from_errors() {
547 let (tx, rx) = channel(1);
548 drop(rx);
549
550 async fn test(tx: Sender<()>) -> crate::Result<()> {
551 tx.send(()).await.map_err(From::from)
552 }
553
554 match test(tx).await.unwrap_err() {
555 Error::EssentialTaskClosed => {}
556 _ => panic!("invalid error"),
557 }
558 }
559}