zebra_network/peer/error.rs
1//! Peer-related errors.
2
3use std::{borrow::Cow, sync::Arc};
4
5use thiserror::Error;
6
7use tracing_error::TracedError;
8use zebra_chain::serialization::SerializationError;
9
10use crate::protocol::external::InventoryHash;
11
12/// A wrapper around `Arc<PeerError>` that implements `Error`.
13#[derive(Error, Debug, Clone)]
14#[error(transparent)]
15pub struct SharedPeerError(Arc<TracedError<PeerError>>);
16
17impl<E> From<E> for SharedPeerError
18where
19 PeerError: From<E>,
20{
21 fn from(source: E) -> Self {
22 Self(Arc::new(TracedError::from(PeerError::from(source))))
23 }
24}
25
26impl SharedPeerError {
27 /// Returns a debug-formatted string describing the inner [`PeerError`].
28 ///
29 /// Unfortunately, [`TracedError`] makes it impossible to get a reference to the original error.
30 pub fn inner_debug(&self) -> String {
31 format!("{:?}", self.0.as_ref())
32 }
33}
34
35/// An error related to peer connection handling.
36#[derive(Error, Debug)]
37#[allow(dead_code)]
38pub enum PeerError {
39 /// The remote peer closed the connection.
40 #[error("Peer closed connection")]
41 ConnectionClosed,
42
43 /// Zebra dropped the [`Connection`](crate::peer::Connection).
44 #[error("Internal connection dropped")]
45 ConnectionDropped,
46
47 /// Zebra dropped the [`Client`](crate::peer::Client).
48 #[error("Internal client dropped")]
49 ClientDropped,
50
51 /// A [`Client`](crate::peer::Client)'s internal connection task exited.
52 #[error("Internal peer connection task exited")]
53 ConnectionTaskExited,
54
55 /// Zebra's [`Client`](crate::peer::Client) cancelled its heartbeat task.
56 #[error("Internal client cancelled its heartbeat task")]
57 ClientCancelledHeartbeatTask,
58
59 /// Zebra's internal heartbeat task exited.
60 #[error("Internal heartbeat task exited with message: {0:?}")]
61 HeartbeatTaskExited(String),
62
63 /// Sending a message to a remote peer took too long.
64 #[error("Sending Client request timed out")]
65 ConnectionSendTimeout,
66
67 /// Receiving a response to a [`Client`](crate::peer::Client) request took too long.
68 #[error("Receiving client response timed out")]
69 ConnectionReceiveTimeout,
70
71 /// A serialization error occurred while reading or writing a message.
72 #[error("Serialization error: {0}")]
73 Serialization(#[from] SerializationError),
74
75 /// A badly-behaved remote peer sent a handshake message after the handshake was
76 /// already complete.
77 #[error("Remote peer sent handshake messages after handshake")]
78 DuplicateHandshake,
79
80 /// This node's internal services were overloaded, so the connection was dropped
81 /// to shed load.
82 #[error("Internal services over capacity")]
83 Overloaded,
84
85 /// There are no ready remote peers.
86 #[error("No ready peers available")]
87 NoReadyPeers,
88
89 /// Block inventory must use the separately bounded advertiser.
90 #[error("block adverts require the dedicated advertiser")]
91 AdvertRequiresDedicatedService,
92
93 /// A queued advert lost authorization before its local write started.
94 #[error("peer authorization was revoked before advert delivery")]
95 AdvertAuthorizationRevoked,
96
97 /// This peer request's caused an internal service timeout, so the connection was dropped
98 /// to shed load or prevent attacks.
99 #[error("Internal services timed out")]
100 InboundTimeout,
101
102 /// This node's internal services are no longer able to service requests.
103 #[error("Internal services have failed or shutdown")]
104 ServiceShutdown,
105
106 /// We requested data, but the peer replied with a `notfound` message.
107 ///
108 /// This error happens when the peer doesn't have any of the requested data,
109 /// so that the original request can be retried.
110 ///
111 /// This is a temporary error.
112 ///
113 /// Zebra can try different peers if the request is retried,
114 /// or peers can download and verify the missing data.
115 ///
116 /// If the peer has some of the data, the request returns an [`Ok`] response,
117 /// with any `notfound` data is marked as [`Missing`][1].
118 ///
119 /// [1]: crate::protocol::internal::InventoryResponse::Missing
120 #[error("Remote peer could not find any of the items: {0:?}")]
121 NotFoundResponse(Vec<InventoryHash>),
122
123 /// We requested data, but all our ready peers are marked as recently
124 /// [`Missing`][1] that data in our local inventory registry.
125 ///
126 /// This is a temporary error.
127 ///
128 /// Peers with the inventory can finish their requests and become ready, or
129 /// other peers can download and verify the missing data.
130 ///
131 /// # Correctness
132 ///
133 /// This error is produced using Zebra's local inventory registry, without
134 /// contacting any peers.
135 ///
136 /// Client responses containing this error must not be used to update the
137 /// inventory registry. This makes sure that we eventually expire our local
138 /// cache of missing inventory, and send requests to peers again.
139 ///
140 /// [1]: crate::protocol::internal::InventoryResponse::Missing
141 #[error("All ready peers are registered as recently missing these items: {0:?}")]
142 NotFoundRegistry(Vec<InventoryHash>),
143}
144
145impl PeerError {
146 /// Returns the Zebra internal handler type as a string.
147 pub fn kind(&self) -> Cow<'static, str> {
148 match self {
149 PeerError::ConnectionClosed => "ConnectionClosed".into(),
150 PeerError::ConnectionDropped => "ConnectionDropped".into(),
151 PeerError::ClientDropped => "ClientDropped".into(),
152 PeerError::ClientCancelledHeartbeatTask => "ClientCancelledHeartbeatTask".into(),
153 PeerError::HeartbeatTaskExited(_) => "HeartbeatTaskExited".into(),
154 PeerError::ConnectionTaskExited => "ConnectionTaskExited".into(),
155 PeerError::ConnectionSendTimeout => "ConnectionSendTimeout".into(),
156 PeerError::ConnectionReceiveTimeout => "ConnectionReceiveTimeout".into(),
157 // TODO: add error kinds or summaries to `SerializationError`
158 PeerError::Serialization(inner) => format!("Serialization({inner})").into(),
159 PeerError::DuplicateHandshake => "DuplicateHandshake".into(),
160 PeerError::Overloaded => "Overloaded".into(),
161 PeerError::NoReadyPeers => "NoReadyPeers".into(),
162 PeerError::AdvertRequiresDedicatedService => "AdvertRequiresDedicatedService".into(),
163 PeerError::AdvertAuthorizationRevoked => "AdvertAuthorizationRevoked".into(),
164 PeerError::InboundTimeout => "InboundTimeout".into(),
165 PeerError::ServiceShutdown => "ServiceShutdown".into(),
166 PeerError::NotFoundResponse(_) => "NotFoundResponse".into(),
167 PeerError::NotFoundRegistry(_) => "NotFoundRegistry".into(),
168 }
169 }
170}
171
172/// A shared error slot for peer errors.
173///
174/// # Correctness
175///
176/// Error slots are shared between sync and async code. In async code, the error
177/// mutex should be held for as short a time as possible. This avoids blocking
178/// the async task thread on acquiring the mutex.
179///
180/// > If the value behind the mutex is just data, it’s usually appropriate to use a blocking mutex
181/// > ...
182/// > wrap the `Arc<Mutex<...>>` in a struct
183/// > that provides non-async methods for performing operations on the data within,
184/// > and only lock the mutex inside these methods
185///
186/// <https://docs.rs/tokio/1.15.0/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use>
187#[derive(Default, Clone)]
188pub struct ErrorSlot(Arc<std::sync::Mutex<Option<SharedPeerError>>>);
189
190impl std::fmt::Debug for ErrorSlot {
191 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192 // don't hang if the mutex is locked
193 // show the panic if the mutex was poisoned
194 f.debug_struct("ErrorSlot")
195 .field("error", &self.0.try_lock())
196 .finish()
197 }
198}
199
200impl ErrorSlot {
201 /// Read the current error in the slot.
202 ///
203 /// Returns `None` if there is no error in the slot.
204 ///
205 /// # Correctness
206 ///
207 /// Briefly locks the error slot's threaded `std::sync::Mutex`, to get a
208 /// reference to the error in the slot.
209 #[allow(clippy::unwrap_in_result)]
210 pub fn try_get_error(&self) -> Option<SharedPeerError> {
211 self.0
212 .lock()
213 .expect("error mutex should be unpoisoned")
214 .as_ref()
215 .cloned()
216 }
217
218 /// Update the current error in the slot.
219 ///
220 /// Returns `Err(AlreadyErrored)` if there was already an error in the slot.
221 ///
222 /// # Correctness
223 ///
224 /// Briefly locks the error slot's threaded `std::sync::Mutex`, to check for
225 /// a previous error, then update the error in the slot.
226 #[allow(clippy::unwrap_in_result)]
227 pub fn try_update_error(&self, e: SharedPeerError) -> Result<(), AlreadyErrored> {
228 let mut guard = self.0.lock().expect("error mutex should be unpoisoned");
229
230 if let Some(original_error) = guard.clone() {
231 Err(AlreadyErrored { original_error })
232 } else {
233 *guard = Some(e);
234 Ok(())
235 }
236 }
237}
238
239/// Error returned when the [`ErrorSlot`] already contains an error.
240#[derive(Clone, Debug)]
241pub struct AlreadyErrored {
242 /// The original error in the error slot.
243 pub original_error: SharedPeerError,
244}
245
246/// An error during a handshake with a remote peer.
247#[derive(Error, Debug)]
248pub enum HandshakeError {
249 /// The remote peer sent an unexpected message during the handshake.
250 #[error("The remote peer sent an unexpected message: {0:?}")]
251 UnexpectedMessage(Box<crate::protocol::external::Message>),
252 /// The peer connector detected handshake nonce reuse, possibly indicating self-connection.
253 #[error("Detected nonce reuse, possible self-connection")]
254 RemoteNonceReuse,
255 /// The peer connector created a duplicate random nonce. This is very unlikely,
256 /// because the range of the data type is 2^64.
257 #[error("Unexpectedly created a duplicate random local nonce")]
258 LocalDuplicateNonce,
259 /// The remote peer closed the connection.
260 #[error("Peer closed connection")]
261 ConnectionClosed,
262 /// An error occurred while performing an IO operation.
263 #[error("Underlying IO error: {0}")]
264 Io(#[from] std::io::Error),
265 /// A serialization error occurred while reading or writing a message.
266 #[error("Serialization error: {0}")]
267 Serialization(#[from] SerializationError),
268 /// The remote peer offered a version older than our minimum version.
269 #[error("Peer offered obsolete version: {0:?}")]
270 ObsoleteVersion(crate::protocol::external::types::Version),
271 /// The remote peer is missing services that are required for outbound peers.
272 #[error("Peer is missing required services, advertised: {services:?}")]
273 MissingRequiredServices {
274 /// The services advertised by the remote peer in its `version` message.
275 services: crate::protocol::external::types::PeerServices,
276 },
277 /// Sending or receiving a message timed out.
278 #[error("Timeout when sending or receiving a message to peer")]
279 Timeout,
280}
281
282impl From<tokio::time::error::Elapsed> for HandshakeError {
283 fn from(_source: tokio::time::error::Elapsed) -> Self {
284 HandshakeError::Timeout
285 }
286}