1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum OnionQueueKind {
13 RelayControl,
15 CircuitData,
17}
18
19impl OnionQueueKind {
20 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub enum OnionQueueAdmissionReason {
33 GlobalFull,
35 PeerFull,
37 CounterOverflow,
39 LinkDown,
41}
42
43impl OnionQueueAdmissionReason {
44 pub const fn is_full(self) -> bool {
47 matches!(self, Self::GlobalFull | Self::PeerFull)
48 }
49}
50
51pub type Result<T> = std::result::Result<T, Error>;
53
54pub const INCOMPATIBLE_WIRE_VERSION_CODE: u32 = 210;
56
57#[derive(Debug, thiserror::Error)]
61#[non_exhaustive]
62#[repr(u32)]
63pub enum Error {
64 #[error("Connect remote rpc server failed: {0}.")]
66 RemoteRpcError(String) = 100,
67 #[error("Unknown rpc error.")]
69 UnknownRpcError = 101,
70 #[error("Internal rpc services error: {0}.")]
72 InternalRpcError(#[from] jsonrpc_core::Error) = 102,
73 #[error("Uuid error: {0}")]
75 UuidError(#[from] uuid::Error) = 103,
76 #[error("Connection not found.")]
78 ConnectionNotFound = 203,
79 #[error("Create connection error: {0}.")]
81 NewConnectionError(rings_core::error::Error) = 204,
82 #[error("Close connection error: {0}.")]
84 CloseConnectionError(rings_core::error::Error) = 205,
85 #[error("Invalid connection id.")]
87 InvalidConnectionId = 206,
88 #[error("Create offer info failed: {0}.")]
90 CreateOffer(rings_core::error::Error) = 207,
91 #[error("Answer offer info failed: {0}.")]
93 AnswerOffer(rings_core::error::Error) = 208,
94 #[error("Accept answer info failed: {0}.")]
96 AcceptAnswer(rings_core::error::Error) = 209,
97 #[error("Incompatible wire version: {0}.")]
100 IncompatibleWireVersion(WireVersionMismatch) = INCOMPATIBLE_WIRE_VERSION_CODE,
101 #[error("Decode error.")]
103 DecodeError = 300,
104 #[error("Encode error.")]
106 EncodeError = 301,
107 #[error("WASM compile error: {0}")]
109 WasmCompileError(String) = 400,
110 #[error("BackendMessage RwLock Error")]
112 WasmBackendMessageRwLockError = 401,
113 #[error("WASM instantiation error.")]
115 WasmInstantiationError = 402,
116 #[error("WASM export error.")]
118 WasmExportError = 403,
119 #[error("WASM runtime error: {0}")]
121 WasmRuntimeError(String) = 404,
122 #[error("WASM global memory mutex error.")]
124 WasmGlobalMemoryLockError = 405,
125 #[error("WASM failed to load file.")]
127 WasmFailedToLoadFile = 406,
128 #[error("Invalid did: {0}")]
130 InvalidDid(String) = 500,
131 #[error("Invalid method.")]
133 InvalidMethod = 501,
134 #[error("Internal error: {0}.")]
136 InternalError(rings_core::error::Error) = 502,
137 #[error("No Permission")]
139 NoPermission = 504,
140 #[error("Connect error, {0}")]
142 ConnectError(rings_core::error::Error) = 600,
143 #[error("Send message error: {0}")]
145 SendMessage(rings_core::error::Error) = 601,
146 #[error("entry action error: {0}")]
148 EntryError(rings_core::error::Error) = 603,
149 #[error("service register action error: {0}")]
151 ServiceRegisterError(rings_core::error::Error) = 604,
152 #[error("JsError: {0}")]
154 JsError(String) = 700,
155 #[error("Invalid message")]
157 InvalidMessage = 800,
158 #[error("Invalid http request: {0}")]
160 HttpRequestError(String) = 801,
161 #[error("Invalid data")]
163 InvalidData = 802,
164 #[error("Invalid service")]
166 InvalidService = 803,
167 #[error("Invalid address")]
169 InvalidAddress = 804,
170 #[error("Invalid auth data")]
172 InvalidAuthData = 805,
173 #[error("invalid headers")]
175 InvalidHeaders = 806,
176 #[error("Storage Error: {0}")]
178 Storage(rings_core::error::Error) = 807,
179 #[error("Swarm Error: {0}")]
181 Swarm(rings_core::error::Error) = 808,
182 #[error("Invalid logging level: {0}")]
184 InvalidLoggingLevel(String) = 809,
185 #[error("Invalid local UDP port range: {0}")]
187 InvalidUdpPortRange(#[from] rings_transport::network_config::UdpPortRangeError) = 810,
188 #[error("Both udp_port_min and udp_port_max must be set together: min={min:?}, max={max:?}")]
190 IncompleteUdpPortRange {
191 min: Option<u16>,
193 max: Option<u16>,
195 } = 811,
196 #[error("Invalid configuration: {0}")]
198 InvalidConfig(String) = 812,
199 #[error("this node's onion runtime cannot interpret the offered exit service {service:?}")]
202 UninterpretableOnionService {
203 service: crate::onion::OnionServiceName,
205 } = 813,
206 #[error("Open browser storage \"{name}\" failed: {source}")]
208 BrowserStorageOpen {
209 name: String,
211 source: rings_core::error::Error,
213 } = 814,
214 #[error("registration task stopped")]
216 RegistrationStopped = 815,
217 #[error("Measurement runtime error: {0}")]
219 MeasurementRuntime(#[from] crate::measure::MeasureRuntimeError) = 816,
220 #[cfg(rings_native)]
222 #[error("peer {peer} was not admitted within the handshake admission window")]
223 AdmissionTimedOut {
224 peer: Did,
226 } = 817,
227 #[error("handshake pinned to {expected} but the endpoint answered as {actual}")]
230 HandshakePeerMismatch {
231 expected: Did,
233 actual: Did,
235 } = 818,
236 #[error("a handshake with {peer} is already in flight")]
239 HandshakeInFlight {
240 peer: Did,
242 } = 819,
243 #[error(transparent)]
245 SeedPeer(#[from] crate::seed::SeedPeerError) = 820,
246 #[error("Parse config file {} failed", path.display())]
249 ConfigParse {
250 path: std::path::PathBuf,
252 source: Box<serde_saphyr::Error>,
255 } = 821,
256 #[error("Serialize config file {} failed", path.display())]
258 ConfigSerialize {
259 path: std::path::PathBuf,
261 source: serde_saphyr::ser::Error,
264 } = 822,
265 #[error("Browser storage \"{0}\" is held by another open node")]
269 BrowserStorageLocked(String) = 823,
270 #[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 #[error("Create File Error: {0}")]
279 CreateFileError(String) = 900,
280 #[error("Open File Error: {0}")]
282 OpenFileError(String) = 901,
283 #[error("Acquire lock failed")]
285 Lock = 902,
286 #[error("Cannot find home directory")]
288 HomeDirError = 903,
289 #[error("Cannot find parent directory")]
291 ParentDirError = 904,
292 #[error("Path is not valid UTF-8: {0}")]
294 PathUtf8Error(String) = 905,
295 #[error("Serde json error: {0}")]
297 SerdeJsonError(#[from] serde_json::Error) = 1000,
298 #[error("Serde yaml error: {0}")]
301 SerdeYamlError(Box<serde_saphyr::Error>) = 1001,
302 #[error("verify error: {0}")]
304 VerifyError(String) = 1002,
305 #[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 expires_at_ms: u128,
315 horizon_ms: u128,
317 } = 1003,
318 #[error("Core error: {0}")]
320 CoreError(#[from] rings_core::error::Error) = 1102,
321 #[error("External singer error: {0}")]
323 ExternalError(String) = 1202,
324 #[error("An error indicating that an interior nul byte was found: {0}")]
326 FFINulError(#[from] std::ffi::NulError) = 1203,
327 #[error("Failed to convert CStr to String: {0}")]
329 FFICStrError(#[from] std::str::Utf8Error) = 1204,
330 #[error("An error indicating that a ptr is null")]
332 FFINulPtrError = 1205,
333 #[error("Failed to convert bytes to String: {0}")]
335 FFIFromUtf8Error(#[from] std::string::FromUtf8Error) = 1206,
336 #[error("Extend Backend Error {0}")]
338 BackendError(String) = 1501,
339 #[error("Extension error: {0}")]
341 ExtensionError(String) = 1502,
342 #[error("Detached task failed: {0}")]
344 DetachedTask(#[from] rings_runtime::DetachedError) = 1503,
345 #[error(transparent)]
347 RuntimeUnavailable(#[from] rings_runtime::RuntimeUnavailable) = 1504,
348 #[error("Timer error: {0}")]
350 Timer(#[from] rings_runtime::TimerError) = 1505,
351 #[error(
355 "The node is closed but still shared: its stores are released when its last clone drops"
356 )]
357 ProviderStillShared {
358 released: crate::release::StoresReleased,
360 } = 1506,
361 #[error("Onion route error: {0}")]
363 OnionRouteError(OnionRouteError) = 1601,
364 #[error("Onion proxy IO error: {0}")]
366 OnionProxyIoError(String) = 1602,
367 #[error("Onion proxy request timed out")]
369 OnionProxyRequestTimedOut = 1603,
370 #[error("{queue:?} queue rejected peer {peer}: {reason:?}")]
372 OnionQueueAdmission {
373 queue: OnionQueueKind,
375 peer: Did,
377 reason: OnionQueueAdmissionReason,
379 } = 1604,
380 #[error("Invalid onion proxy target: {0}")]
382 OnionProxyTarget(#[from] OnionProxyTargetError) = 1605,
383 #[error("Failed to resolve onion target {authority:?}: {source}")]
385 OnionTargetResolve {
386 authority: String,
388 source: std::io::Error,
390 } = 1606,
391 #[error("Onion target {authority:?} resolved no addresses")]
393 OnionTargetResolvedEmpty {
394 authority: String,
396 } = 1607,
397 #[error("Unsafe remote RPC target: {0}")]
399 UnsafeRemoteRpcTarget(String) = 1608,
400}
401
402impl Error {
403 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 unsafe { *<*const _>::from(self).cast::<u32>() }
420 }
421
422 pub fn code(&self) -> u32 {
424 self.discriminant()
425 }
426
427 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 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 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 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 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}