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 /// (Or it didn't respond before the request finished.)
108 ///
109 /// This error happens when the peer doesn't have any of the requested data,
110 /// so that the original request can be retried.
111 ///
112 /// This is a temporary error.
113 ///
114 /// Zebra can try different peers if the request is retried,
115 /// or peers can download and verify the missing data.
116 ///
117 /// If the peer has some of the data, the request returns an [`Ok`] response,
118 /// with any `notfound` data is marked as [`Missing`][1].
119 ///
120 /// [1]: crate::protocol::internal::InventoryResponse::Missing
121 #[error("Remote peer could not find any of the items: {0:?}")]
122 NotFoundResponse(Vec<InventoryHash>),
123
124 /// We requested data, but all our ready peers are marked as recently
125 /// [`Missing`][1] that data in our local inventory registry.
126 ///
127 /// This is a temporary error.
128 ///
129 /// Peers with the inventory can finish their requests and become ready, or
130 /// other peers can download and verify the missing data.
131 ///
132 /// # Correctness
133 ///
134 /// This error is produced using Zebra's local inventory registry, without
135 /// contacting any peers.
136 ///
137 /// Client responses containing this error must not be used to update the
138 /// inventory registry. This makes sure that we eventually expire our local
139 /// cache of missing inventory, and send requests to peers again.
140 ///
141 /// [1]: crate::protocol::internal::InventoryResponse::Missing
142 #[error("All ready peers are registered as recently missing these items: {0:?}")]
143 NotFoundRegistry(Vec<InventoryHash>),
144}
145
146impl PeerError {
147 /// Returns the Zebra internal handler type as a string.
148 pub fn kind(&self) -> Cow<'static, str> {
149 match self {
150 PeerError::ConnectionClosed => "ConnectionClosed".into(),
151 PeerError::ConnectionDropped => "ConnectionDropped".into(),
152 PeerError::ClientDropped => "ClientDropped".into(),
153 PeerError::ClientCancelledHeartbeatTask => "ClientCancelledHeartbeatTask".into(),
154 PeerError::HeartbeatTaskExited(_) => "HeartbeatTaskExited".into(),
155 PeerError::ConnectionTaskExited => "ConnectionTaskExited".into(),
156 PeerError::ConnectionSendTimeout => "ConnectionSendTimeout".into(),
157 PeerError::ConnectionReceiveTimeout => "ConnectionReceiveTimeout".into(),
158 // TODO: add error kinds or summaries to `SerializationError`
159 PeerError::Serialization(inner) => format!("Serialization({inner})").into(),
160 PeerError::DuplicateHandshake => "DuplicateHandshake".into(),
161 PeerError::Overloaded => "Overloaded".into(),
162 PeerError::NoReadyPeers => "NoReadyPeers".into(),
163 PeerError::AdvertRequiresDedicatedService => "AdvertRequiresDedicatedService".into(),
164 PeerError::AdvertAuthorizationRevoked => "AdvertAuthorizationRevoked".into(),
165 PeerError::InboundTimeout => "InboundTimeout".into(),
166 PeerError::ServiceShutdown => "ServiceShutdown".into(),
167 PeerError::NotFoundResponse(_) => "NotFoundResponse".into(),
168 PeerError::NotFoundRegistry(_) => "NotFoundRegistry".into(),
169 }
170 }
171}
172
173/// A shared error slot for peer errors.
174///
175/// # Correctness
176///
177/// Error slots are shared between sync and async code. In async code, the error
178/// mutex should be held for as short a time as possible. This avoids blocking
179/// the async task thread on acquiring the mutex.
180///
181/// > If the value behind the mutex is just data, it’s usually appropriate to use a blocking mutex
182/// > ...
183/// > wrap the `Arc<Mutex<...>>` in a struct
184/// > that provides non-async methods for performing operations on the data within,
185/// > and only lock the mutex inside these methods
186///
187/// <https://docs.rs/tokio/1.15.0/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use>
188#[derive(Default, Clone)]
189pub struct ErrorSlot(Arc<std::sync::Mutex<Option<SharedPeerError>>>);
190
191impl std::fmt::Debug for ErrorSlot {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 // don't hang if the mutex is locked
194 // show the panic if the mutex was poisoned
195 f.debug_struct("ErrorSlot")
196 .field("error", &self.0.try_lock())
197 .finish()
198 }
199}
200
201impl ErrorSlot {
202 /// Read the current error in the slot.
203 ///
204 /// Returns `None` if there is no error in the slot.
205 ///
206 /// # Correctness
207 ///
208 /// Briefly locks the error slot's threaded `std::sync::Mutex`, to get a
209 /// reference to the error in the slot.
210 #[allow(clippy::unwrap_in_result)]
211 pub fn try_get_error(&self) -> Option<SharedPeerError> {
212 self.0
213 .lock()
214 .expect("error mutex should be unpoisoned")
215 .as_ref()
216 .cloned()
217 }
218
219 /// Update the current error in the slot.
220 ///
221 /// Returns `Err(AlreadyErrored)` if there was already an error in the slot.
222 ///
223 /// # Correctness
224 ///
225 /// Briefly locks the error slot's threaded `std::sync::Mutex`, to check for
226 /// a previous error, then update the error in the slot.
227 #[allow(clippy::unwrap_in_result)]
228 pub fn try_update_error(&self, e: SharedPeerError) -> Result<(), AlreadyErrored> {
229 let mut guard = self.0.lock().expect("error mutex should be unpoisoned");
230
231 if let Some(original_error) = guard.clone() {
232 Err(AlreadyErrored { original_error })
233 } else {
234 *guard = Some(e);
235 Ok(())
236 }
237 }
238}
239
240/// Error returned when the [`ErrorSlot`] already contains an error.
241#[derive(Clone, Debug)]
242pub struct AlreadyErrored {
243 /// The original error in the error slot.
244 pub original_error: SharedPeerError,
245}
246
247/// An error during a handshake with a remote peer.
248#[derive(Error, Debug)]
249pub enum HandshakeError {
250 /// The remote peer sent an unexpected message during the handshake.
251 #[error("The remote peer sent an unexpected message: {0:?}")]
252 UnexpectedMessage(Box<crate::protocol::external::Message>),
253 /// The peer connector detected handshake nonce reuse, possibly indicating self-connection.
254 #[error("Detected nonce reuse, possible self-connection")]
255 RemoteNonceReuse,
256 /// The peer connector created a duplicate random nonce. This is very unlikely,
257 /// because the range of the data type is 2^64.
258 #[error("Unexpectedly created a duplicate random local nonce")]
259 LocalDuplicateNonce,
260 /// The remote peer closed the connection.
261 #[error("Peer closed connection")]
262 ConnectionClosed,
263 /// An error occurred while performing an IO operation.
264 #[error("Underlying IO error: {0}")]
265 Io(#[from] std::io::Error),
266 /// A serialization error occurred while reading or writing a message.
267 #[error("Serialization error: {0}")]
268 Serialization(#[from] SerializationError),
269 /// The remote peer offered a version older than our minimum version.
270 #[error("Peer offered obsolete version: {0:?}")]
271 ObsoleteVersion(crate::protocol::external::types::Version),
272 /// The remote peer is missing services that are required for outbound peers.
273 #[error("Peer is missing required services, advertised: {services:?}")]
274 MissingRequiredServices {
275 /// The services advertised by the remote peer in its `version` message.
276 services: crate::protocol::external::types::PeerServices,
277 },
278 /// Sending or receiving a message timed out.
279 #[error("Timeout when sending or receiving a message to peer")]
280 Timeout,
281}
282
283impl From<tokio::time::error::Elapsed> for HandshakeError {
284 fn from(_source: tokio::time::error::Elapsed) -> Self {
285 HandshakeError::Timeout
286 }
287}