Skip to main content

rings_node/
error.rs

1//! A bunch of wrap errors.
2use rings_core::dht::Did;
3use rings_core::message::PeerWireVersion;
4use rings_core::message::WireVersionMismatch;
5
6use crate::onion::OnionProxyTargetError;
7use crate::onion::OnionRouteError;
8use crate::prelude::rings_core;
9
10/// Bounded onion/relay queue whose admission failed.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum OnionQueueKind {
13    /// Terminal relay-control sends.
14    RelayControl,
15    /// Onion data-plane sends.
16    CircuitData,
17}
18
19impl OnionQueueKind {
20    /// Build the closed admission error for this queue kind.
21    pub(crate) const fn admission(self, peer: Did, reason: OnionQueueAdmissionReason) -> Error {
22        Error::OnionQueueAdmission {
23            queue: self,
24            peer,
25            reason,
26        }
27    }
28}
29
30/// Algebraic reason a bounded onion/relay queue rejected one item.
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub enum OnionQueueAdmissionReason {
33    /// The queue-wide bound was reached.
34    GlobalFull,
35    /// One peer reached its isolated share.
36    PeerFull,
37    /// A resource counter could not represent its successor.
38    CounterOverflow,
39    /// The peer has no up link, so nothing may be queued for it.
40    LinkDown,
41}
42
43impl OnionQueueAdmissionReason {
44    /// Whether the refusal is a bound, which a later completion lifts: `GlobalFull` or
45    /// `PeerFull`.
46    pub const fn is_full(self) -> bool {
47        matches!(self, Self::GlobalFull | Self::PeerFull)
48    }
49}
50
51/// A wrap `Result` contains custom errors.
52pub type Result<T> = std::result::Result<T, Error>;
53
54/// The stable JSON-RPC code of [`Error::IncompatibleWireVersion`], which a client matches.
55pub const INCOMPATIBLE_WIRE_VERSION_CODE: u32 = 210;
56
57/// Errors enum mapping global custom errors.
58/// The error type can be expressed in decimal, where the high decs represent
59/// the error category and the low decs represent the error type.
60#[derive(Debug, thiserror::Error)]
61#[non_exhaustive]
62#[repr(u32)]
63pub enum Error {
64    /// Connecting to a remote JSON-RPC server failed.
65    #[error("Connect remote rpc server failed: {0}.")]
66    RemoteRpcError(String) = 100,
67    /// A remote JSON-RPC error did not match a known local variant.
68    #[error("Unknown rpc error.")]
69    UnknownRpcError = 101,
70    /// The internal JSON-RPC dispatcher returned an error.
71    #[error("Internal rpc services error: {0}.")]
72    InternalRpcError(#[from] jsonrpc_core::Error) = 102,
73    /// UUID parsing or formatting failed.
74    #[error("Uuid error: {0}")]
75    UuidError(#[from] uuid::Error) = 103,
76    /// The requested connection does not exist in the local swarm.
77    #[error("Connection not found.")]
78    ConnectionNotFound = 203,
79    /// Opening a new connection through the core swarm failed.
80    #[error("Create connection error: {0}.")]
81    NewConnectionError(rings_core::error::Error) = 204,
82    /// Closing an existing connection through the core swarm failed.
83    #[error("Close connection error: {0}.")]
84    CloseConnectionError(rings_core::error::Error) = 205,
85    /// The supplied connection identifier is malformed or unknown.
86    #[error("Invalid connection id.")]
87    InvalidConnectionId = 206,
88    /// Creating WebRTC offer data failed.
89    #[error("Create offer info failed: {0}.")]
90    CreateOffer(rings_core::error::Error) = 207,
91    /// Creating WebRTC answer data failed.
92    #[error("Answer offer info failed: {0}.")]
93    AnswerOffer(rings_core::error::Error) = 208,
94    /// Accepting WebRTC answer data failed.
95    #[error("Accept answer info failed: {0}.")]
96    AcceptAnswer(rings_core::error::Error) = 209,
97    /// A handshake met a node of another wire version (#1104); over JSON-RPC its data is
98    /// `{"ours": n, "theirs": m}`, with `theirs` null for a peer before wire versioning.
99    #[error("Incompatible wire version: {0}.")]
100    IncompatibleWireVersion(WireVersionMismatch) = INCOMPATIBLE_WIRE_VERSION_CODE,
101    /// Decoding structured data failed.
102    #[error("Decode error.")]
103    DecodeError = 300,
104    /// Encoding structured data failed.
105    #[error("Encode error.")]
106    EncodeError = 301,
107    /// Compiling a WASM artifact failed.
108    #[error("WASM compile error: {0}")]
109    WasmCompileError(String) = 400,
110    /// Acquiring the WASM backend-message lock failed.
111    #[error("BackendMessage RwLock Error")]
112    WasmBackendMessageRwLockError = 401,
113    /// Instantiating a WASM module failed.
114    #[error("WASM instantiation error.")]
115    WasmInstantiationError = 402,
116    /// Resolving a required WASM export failed.
117    #[error("WASM export error.")]
118    WasmExportError = 403,
119    /// Executing WASM code returned a runtime error.
120    #[error("WASM runtime error: {0}")]
121    WasmRuntimeError(String) = 404,
122    /// Acquiring the WASM global memory lock failed.
123    #[error("WASM global memory mutex error.")]
124    WasmGlobalMemoryLockError = 405,
125    /// Loading a WASM input file failed.
126    #[error("WASM failed to load file.")]
127    WasmFailedToLoadFile = 406,
128    /// Parsing or validating a DID failed.
129    #[error("Invalid did: {0}")]
130    InvalidDid(String) = 500,
131    /// The requested JSON-RPC method is not supported.
132    #[error("Invalid method.")]
133    InvalidMethod = 501,
134    /// A core internal operation failed.
135    #[error("Internal error: {0}.")]
136    InternalError(rings_core::error::Error) = 502,
137    /// The caller is not authorized to perform the requested action.
138    #[error("No Permission")]
139    NoPermission = 504,
140    /// Connecting to a peer failed.
141    #[error("Connect error, {0}")]
142    ConnectError(rings_core::error::Error) = 600,
143    /// Sending a peer message failed.
144    #[error("Send message error: {0}")]
145    SendMessage(rings_core::error::Error) = 601,
146    /// Applying a DHT entry action failed.
147    #[error("entry action error: {0}")]
148    EntryError(rings_core::error::Error) = 603,
149    /// Registering a service descriptor failed.
150    #[error("service register action error: {0}")]
151    ServiceRegisterError(rings_core::error::Error) = 604,
152    /// JavaScript host code returned an error.
153    #[error("JsError: {0}")]
154    JsError(String) = 700,
155    /// A protocol message failed validation.
156    #[error("Invalid message")]
157    InvalidMessage = 800,
158    /// An HTTP proxy request failed validation.
159    #[error("Invalid http request: {0}")]
160    HttpRequestError(String) = 801,
161    /// Input data failed semantic validation.
162    #[error("Invalid data")]
163    InvalidData = 802,
164    /// A service name or service descriptor is invalid.
165    #[error("Invalid service")]
166    InvalidService = 803,
167    /// A network address is invalid.
168    #[error("Invalid address")]
169    InvalidAddress = 804,
170    /// Authentication payload data is invalid.
171    #[error("Invalid auth data")]
172    InvalidAuthData = 805,
173    /// Request headers are missing required values or contain invalid values.
174    #[error("invalid headers")]
175    InvalidHeaders = 806,
176    /// Persistent or cache storage returned an error.
177    #[error("Storage Error: {0}")]
178    Storage(rings_core::error::Error) = 807,
179    /// Swarm state management returned an error.
180    #[error("Swarm Error: {0}")]
181    Swarm(rings_core::error::Error) = 808,
182    /// The requested logging level is not supported.
183    #[error("Invalid logging level: {0}")]
184    InvalidLoggingLevel(String) = 809,
185    /// The configured local UDP port range is invalid.
186    #[error("Invalid local UDP port range: {0}")]
187    InvalidUdpPortRange(#[from] rings_transport::network_config::UdpPortRangeError) = 810,
188    /// Only one side of the local UDP port range was configured.
189    #[error("Both udp_port_min and udp_port_max must be set together: min={min:?}, max={max:?}")]
190    IncompleteUdpPortRange {
191        /// Configured lower UDP port bound.
192        min: Option<u16>,
193        /// Configured upper UDP port bound.
194        max: Option<u16>,
195    } = 811,
196    /// The node configuration is structurally invalid.
197    #[error("Invalid configuration: {0}")]
198    InvalidConfig(String) = 812,
199    /// An onion exit offers a service this node's runtime cannot interpret: a browser runtime
200    /// has `fetch` but no sockets, so it interprets `https` only.
201    #[error("this node's onion runtime cannot interpret the offered exit service {service:?}")]
202    UninterpretableOnionService {
203        /// The first offered service the runtime cannot interpret.
204        service: crate::onion::OnionServiceName,
205    } = 813,
206    /// Opening browser IndexedDB-backed provider storage failed.
207    #[error("Open browser storage \"{name}\" failed: {source}")]
208    BrowserStorageOpen {
209        /// IndexedDB database and object-store name requested by the browser provider.
210        name: String,
211        /// Storage backend error returned while opening the database.
212        source: rings_core::error::Error,
213    } = 814,
214    /// A periodic registration task observed a cooperative stop request.
215    #[error("registration task stopped")]
216    RegistrationStopped = 815,
217    /// Loading or explicitly flushing local peer measurements failed.
218    #[error("Measurement runtime error: {0}")]
219    MeasurementRuntime(#[from] crate::measure::MeasureRuntimeError) = 816,
220    /// A handshake was accepted but the swarm did not admit the peer within the dial's window.
221    #[cfg(rings_native)]
222    #[error("peer {peer} was not admitted within the handshake admission window")]
223    AdmissionTimedOut {
224        /// Peer the handshake was accepted with.
225        peer: Did,
226    } = 817,
227    /// The endpoint answered as a DID other than the one the handshake was pinned to; no offer
228    /// was created.
229    #[error("handshake pinned to {expected} but the endpoint answered as {actual}")]
230    HandshakePeerMismatch {
231        /// DID the handshake was pinned to.
232        expected: Did,
233        /// DID the endpoint answered as.
234        actual: Did,
235    } = 818,
236    /// A handshake was refused because the peer's slot is owned by another attempt: a handshake
237    /// in flight, whichever side started it.
238    #[error("a handshake with {peer} is already in flight")]
239    HandshakeInFlight {
240        /// The peer whose slot is owned.
241        peer: Did,
242    } = 819,
243    /// A seed entry failed validation.
244    #[error(transparent)]
245    SeedPeer(#[from] crate::seed::SeedPeerError) = 820,
246    /// The node configuration file is not a valid config document: malformed YAML, a missing
247    /// or unknown key, or a value of the wrong type.
248    #[error("Parse config file {} failed", path.display())]
249    ConfigParse {
250        /// Config file that was read.
251        path: std::path::PathBuf,
252        /// The parser's error, with the key and source location, reported as this error's
253        /// source rather than in its message. Boxed as in [`Error::SerdeYamlError`].
254        source: Box<serde_saphyr::Error>,
255    } = 821,
256    /// Writing the node configuration to its file failed while serializing it.
257    #[error("Serialize config file {} failed", path.display())]
258    ConfigSerialize {
259        /// Config file that was written.
260        path: std::path::PathBuf,
261        /// The serializer's error, including any I/O error of the write, reported as this
262        /// error's source.
263        source: serde_saphyr::ser::Error,
264    } = 822,
265    /// Another open browser node holds the exclusive Web Lock for this storage namespace (#1055):
266    /// one storage namespace has one writer in the origin, so this open refuses before opening
267    /// any IndexedDB database instead of interleaving with it.
268    #[error("Browser storage \"{0}\" is held by another open node")]
269    BrowserStorageLocked(String) = 823,
270    /// A browser `storage_name` is empty or contains path separators or control characters, which
271    /// could alias another namespace's sub-store Web Lock (`rings-node/<storage_name>/<substore>`).
272    #[error(
273        "Invalid browser storage name \"{0}\": must be a non-empty single namespace segment \
274         without '/', '\\', or control characters"
275    )]
276    InvalidBrowserStorageName(String) = 824,
277    /// Creating a file on disk failed.
278    #[error("Create File Error: {0}")]
279    CreateFileError(String) = 900,
280    /// Opening a file on disk failed.
281    #[error("Open File Error: {0}")]
282    OpenFileError(String) = 901,
283    /// Acquiring a synchronization lock failed.
284    #[error("Acquire lock failed")]
285    Lock = 902,
286    /// The process home directory could not be resolved.
287    #[error("Cannot find home directory")]
288    HomeDirError = 903,
289    /// The parent directory of a path could not be resolved.
290    #[error("Cannot find parent directory")]
291    ParentDirError = 904,
292    /// A filesystem path cannot be represented as UTF-8.
293    #[error("Path is not valid UTF-8: {0}")]
294    PathUtf8Error(String) = 905,
295    /// JSON serialization or deserialization failed.
296    #[error("Serde json error: {0}")]
297    SerdeJsonError(#[from] serde_json::Error) = 1000,
298    /// YAML deserialization failed. Boxed: the parser's error carries its source location and
299    /// snippet, and would otherwise make every `Result` of this crate as large.
300    #[error("Serde yaml error: {0}")]
301    SerdeYamlError(Box<serde_saphyr::Error>) = 1001,
302    /// Cryptographic verification failed.
303    #[error("verify error: {0}")]
304    VerifyError(String) = 1002,
305    /// The node's own delegation is past its signing horizon (#1063): it expires at
306    /// `expires_at_ms`, and every frame that carries it is refused from `horizon_ms` on, so the
307    /// node can send nothing until it restarts with a fresh delegatee key.
308    #[error(
309        "the node's delegation reached its signing horizon at {horizon_ms} ms (it expires at \
310         {expires_at_ms} ms): the node can send nothing; restart it with a fresh delegatee key"
311    )]
312    DelegationHorizonReached {
313        /// The delegation's expiry, in Unix epoch milliseconds.
314        expires_at_ms: u128,
315        /// The first instant at which no frame leaves, in Unix epoch milliseconds.
316        horizon_ms: u128,
317    } = 1003,
318    /// A rings-core operation returned an error.
319    #[error("Core error: {0}")]
320    CoreError(#[from] rings_core::error::Error) = 1102,
321    /// An external signer returned an error.
322    #[error("External singer error: {0}")]
323    ExternalError(String) = 1202,
324    /// An FFI string contained an interior nul byte.
325    #[error("An error indicating that an interior nul byte was found: {0}")]
326    FFINulError(#[from] std::ffi::NulError) = 1203,
327    /// Converting an FFI C string to UTF-8 failed.
328    #[error("Failed to convert CStr to String: {0}")]
329    FFICStrError(#[from] std::str::Utf8Error) = 1204,
330    /// An FFI pointer argument was null.
331    #[error("An error indicating that a ptr is null")]
332    FFINulPtrError = 1205,
333    /// Converting owned FFI bytes to UTF-8 failed.
334    #[error("Failed to convert bytes to String: {0}")]
335    FFIFromUtf8Error(#[from] std::string::FromUtf8Error) = 1206,
336    /// A protocol backend returned an error.
337    #[error("Extend Backend Error {0}")]
338    BackendError(String) = 1501,
339    /// An extension runtime returned an error.
340    #[error("Extension error: {0}")]
341    ExtensionError(String) = 1502,
342    /// Owned detached work produced no result: it never started or ended without publishing.
343    #[error("Detached task failed: {0}")]
344    DetachedTask(#[from] rings_runtime::DetachedError) = 1503,
345    /// Work could not be scheduled because no async runtime is current.
346    #[error(transparent)]
347    RuntimeUnavailable(#[from] rings_runtime::RuntimeUnavailable) = 1504,
348    /// The runtime could not run a timer.
349    #[error("Timer error: {0}")]
350    Timer(#[from] rings_runtime::TimerError) = 1505,
351    /// A closed node is still shared, so its stores are not yet released
352    /// ([`Provider::close`](crate::provider::Provider::close)): they are once its last clone
353    /// drops, which `released` witnesses.
354    #[error(
355        "The node is closed but still shared: its stores are released when its last clone drops"
356    )]
357    ProviderStillShared {
358        /// Resolves once every store of the node is released.
359        released: crate::release::StoresReleased,
360    } = 1506,
361    /// Onion route construction or validation failed.
362    #[error("Onion route error: {0}")]
363    OnionRouteError(OnionRouteError) = 1601,
364    /// Onion proxy I/O failed.
365    #[error("Onion proxy IO error: {0}")]
366    OnionProxyIoError(String) = 1602,
367    /// A local onion proxy request did not complete before its deadline.
368    #[error("Onion proxy request timed out")]
369    OnionProxyRequestTimedOut = 1603,
370    /// A bounded onion or relay send queue rejected one item.
371    #[error("{queue:?} queue rejected peer {peer}: {reason:?}")]
372    OnionQueueAdmission {
373        /// Queue whose bound was reached.
374        queue: OnionQueueKind,
375        /// Peer whose item was rejected.
376        peer: Did,
377        /// Exact admission relation that failed.
378        reason: OnionQueueAdmissionReason,
379    } = 1604,
380    /// An onion proxy authority failed closed parsing.
381    #[error("Invalid onion proxy target: {0}")]
382    OnionProxyTarget(#[from] OnionProxyTargetError) = 1605,
383    /// Runtime DNS resolution of an admitted onion target failed.
384    #[error("Failed to resolve onion target {authority:?}: {source}")]
385    OnionTargetResolve {
386        /// Canonical target authority.
387        authority: String,
388        /// Resolver I/O failure.
389        source: std::io::Error,
390    } = 1606,
391    /// Runtime DNS resolution returned no addresses.
392    #[error("Onion target {authority:?} resolved no addresses")]
393    OnionTargetResolvedEmpty {
394        /// Canonical target authority.
395        authority: String,
396    } = 1607,
397    /// A remote JSON-RPC URL failed the public-network egress policy.
398    #[error("Unsafe remote RPC target: {0}")]
399    UnsafeRemoteRpcTarget(String) = 1608,
400}
401
402impl Error {
403    /// Whether this is an overlay send refused before any of its frames could be accepted, so
404    /// sending the payload again cannot duplicate it (`rings_core::error::Error::is_refused_before_acceptance`).
405    pub(crate) fn is_send_refused_before_acceptance(&self) -> bool {
406        matches!(self, Self::SendMessage(error) if error.is_refused_before_acceptance())
407    }
408
409    fn discriminant(&self) -> u32 {
410        // SAFETY: Because `Self` is marked `repr(u32)`, its layout is a `repr(C)` `union`
411        // between `repr(C)` structs, each of which has the `u32` discriminant as its first
412        // field, so we can read the discriminant without offsetting the pointer.
413        // This code is copy from
414        // ref: https://doc.rust-lang.org/std/mem/fn.discriminant.html
415        // And we modify it from [u8] to [u32], this is work because
416        // repr(C) is equivalent to one of repr(u*) (see the next section) for
417        // fieldless enums.
418        // ref: https://doc.rust-lang.org/nomicon/other-reprs.html
419        unsafe { *<*const _>::from(self).cast::<u32>() }
420    }
421
422    /// Returns the stable numeric error code for JSON-RPC error conversion.
423    pub fn code(&self) -> u32 {
424        self.discriminant()
425    }
426
427    /// The structured data a JSON-RPC caller matches beside the code: both wire versions of an
428    /// [`Self::IncompatibleWireVersion`], none for any other error.
429    fn data(&self) -> Option<serde_json::Value> {
430        match self {
431            Self::IncompatibleWireVersion(mismatch) => Some(serde_json::json!({
432                "ours": mismatch.ours,
433                "theirs": mismatch.theirs.number(),
434            })),
435            _ => None,
436        }
437    }
438
439    /// `error` as this layer reports it: the core's refusal of a peer of another wire version
440    /// as [`Self::IncompatibleWireVersion`], any other error through `otherwise`.
441    pub(crate) fn from_core_or(
442        error: rings_core::error::Error,
443        otherwise: impl FnOnce(rings_core::error::Error) -> Self,
444    ) -> Self {
445        match error {
446            rings_core::error::Error::IncompatibleWireVersion(mismatch) => {
447                Self::IncompatibleWireVersion(mismatch)
448            }
449            error => otherwise(error),
450        }
451    }
452
453    /// The refusal a remote node returned for this node's wire version, as this node states it:
454    /// the remote's `ours` is this node's `theirs`. `None` for any other remote error.
455    fn remote_wire_refusal(error: &jsonrpc_core::Error) -> Option<Self> {
456        let code = jsonrpc_core::ErrorCode::ServerError(INCOMPATIBLE_WIRE_VERSION_CODE.into());
457        if error.code != code {
458            return None;
459        }
460        let theirs = error.data.as_ref()?.get("ours")?.as_u64()?;
461        let theirs = u16::try_from(theirs).ok()?;
462        Some(Self::IncompatibleWireVersion(
463            PeerWireVersion::Versioned(theirs).mismatch(),
464        ))
465    }
466}
467
468impl From<Error> for jsonrpc_core::Error {
469    fn from(e: Error) -> Self {
470        Self {
471            code: jsonrpc_core::ErrorCode::ServerError(e.code().into()),
472            message: e.to_string(),
473            data: e.data(),
474        }
475    }
476}
477
478impl From<serde_saphyr::Error> for Error {
479    /// Box the parser's error into [`Error::SerdeYamlError`].
480    fn from(error: serde_saphyr::Error) -> Self {
481        Error::SerdeYamlError(Box::new(error))
482    }
483}
484
485impl From<rings_rpc::jsonrpc::RpcError> for Error {
486    /// A remote node's JSON-RPC call failed: transport, decoding or an error the node returned.
487    /// The remote's refusal of this node's wire version is that refusal, as this node states it
488    /// ([`Error::IncompatibleWireVersion`]).
489    fn from(error: rings_rpc::jsonrpc::RpcError) -> Self {
490        if let rings_rpc::jsonrpc::RpcError::JsonClientError(remote) = &error {
491            if let Some(refusal) = Error::remote_wire_refusal(remote) {
492                return refusal;
493            }
494        }
495        Error::RemoteRpcError(error.to_string())
496    }
497}
498
499impl From<rings_rpc::error::Error> for Error {
500    fn from(e: rings_rpc::error::Error) -> Self {
501        match e {
502            rings_rpc::error::Error::InvalidMethod => Error::InvalidMethod,
503            rings_rpc::error::Error::RpcError(v) => Error::RemoteRpcError(v.to_string()),
504            rings_rpc::error::Error::InvalidSignature => Error::InvalidData,
505            rings_rpc::error::Error::InvalidHeaders => Error::InvalidHeaders,
506            _ => Error::UnknownRpcError,
507        }
508    }
509}
510
511#[cfg(all(feature = "browser", target_family = "wasm"))]
512impl From<Error> for wasm_bindgen::JsValue {
513    fn from(err: Error) -> Self {
514        wasm_bindgen::JsValue::from_str(&err.to_string())
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521    #[test]
522    fn test_error_code() {
523        let err = Error::RemoteRpcError("Test".to_string());
524        assert_eq!(err.code(), 100);
525    }
526
527    #[test]
528    fn test_browser_storage_locked_error_code() {
529        let err = Error::BrowserStorageLocked("rings-node".to_string());
530        assert_eq!(err.code(), 823);
531        assert_eq!(
532            err.to_string(),
533            "Browser storage \"rings-node\" is held by another open node"
534        );
535    }
536}