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