Skip to main content

rings_core/
error.rs

1//! Error of rings_core
2
3/// A wrap `Result` contains custom errors.
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// Errors collections in ring-core.
7#[derive(thiserror::Error, Debug)]
8#[non_exhaustive]
9pub enum Error {
10    #[error("Serialize affine failed")]
11    EccSerializeFailed,
12    #[error("desrialize affine failed")]
13    EccDeserializeFailed,
14    #[error("Failed to initialize Curve hasher")]
15    CurveHasherInitFailed,
16    #[error("Failed to hash data into cruve")]
17    CurveHasherFailed,
18
19    #[error("Ed25519/EdDSA pubkey bad format")]
20    EdDSAPublicKeyBadFormat,
21
22    #[error("Secp256k1/ECDSA pubkey bad format")]
23    ECDSAPublicKeyBadFormat,
24
25    #[error("Failed to lift encoded plaintext into a secp256k1 point")]
26    Secp256k1PointLiftFailed,
27
28    #[error("E2E stream id mismatch: expected {expected}, actual {actual}")]
29    E2eStreamIdMismatch {
30        /// Stream ID expected by the decryptor.
31        expected: uuid::Uuid,
32        /// Stream ID carried by the frame.
33        actual: uuid::Uuid,
34    },
35
36    #[error("E2E frame sequence mismatch: expected {expected}, actual {actual}")]
37    E2eFrameSequenceMismatch {
38        /// Sequence number expected by the decryptor.
39        expected: u64,
40        /// Sequence number carried by the frame.
41        actual: u64,
42    },
43
44    #[error(
45        "E2E frame sequence {actual} exceeds reorder window {window} from next sequence {next_sequence}"
46    )]
47    E2eFrameReorderWindowExceeded {
48        /// Next contiguous sequence number expected by the decryptor.
49        next_sequence: u64,
50        /// Sequence number carried by the frame.
51        actual: u64,
52        /// Maximum accepted gap ahead of the next sequence.
53        window: u64,
54    },
55
56    #[error("E2E frame sequence counter overflowed")]
57    E2eFrameSequenceOverflow,
58
59    #[error("E2E frame received after the authenticated final frame")]
60    E2eFrameAfterFinal,
61
62    #[error("E2E stream is missing the authenticated final frame")]
63    E2eMissingFinalFrame,
64
65    #[error("E2E public key resolves to {actual}, expected {expected}")]
66    E2ePublicKeyDidMismatch {
67        /// DID expected by the signed message context.
68        expected: crate::dht::Did,
69        /// DID derived from the supplied public key.
70        actual: crate::dht::Did,
71    },
72
73    #[error("Secp256r1/ECDSA Error: {0}")]
74    ECDSAError(#[from] ecdsa::Error),
75
76    #[error("ECDSA or EdDSA pubkey bad format")]
77    PublicKeyBadFormat,
78
79    #[error("Failed to decode vector to bls affine")]
80    BlsAffineDecodeFailed,
81
82    #[error("private bad format")]
83    PrivateKeyBadFormat,
84
85    #[error("Invalid Transport")]
86    InvalidTransport,
87
88    #[error("InvalidPublicKey")]
89    InvalidPublicKey,
90
91    #[error("Entry kind not equal when overwriting")]
92    EntryKindNotEqual,
93
94    #[error("Did of Entry not equal")]
95    EntryDidNotEqual,
96
97    #[error("The type of Entry is not allowed to be overwritten")]
98    EntryNotOverwritable,
99
100    #[error("The type of Entry is not allowed to be appended")]
101    EntryNotAppendable,
102
103    #[error("The type of Entry is not allowed to be joined as a subring")]
104    EntryNotJoinable,
105
106    #[error("The type of Entry is not allowed to be tombstoned")]
107    EntryNotTombstonable,
108
109    #[error("Entry dot index {index} is out of bounds")]
110    EntryDotIndexOutOfBounds {
111        /// Dot index that could not be represented.
112        index: usize,
113    },
114
115    #[error("Affine rotation scalar must be greater than zero")]
116    InvalidAffineScalar,
117
118    #[error("Storage redundancy mismatch: transport configured {configured}, storage request uses {requested}")]
119    StorageRedundancyMismatch {
120        /// Redundancy configured on swarm transport for repair.
121        configured: u16,
122        /// Redundancy requested by the storage API const generic.
123        requested: u16,
124    },
125
126    #[error("Encode a byte vector into a base58-check string, adds 4 bytes checksum")]
127    Encode,
128
129    #[error("Decode base58-encoded with 4 bytes checksum string into a byte vector")]
130    Decode,
131
132    #[error("Couldn't decode data as UTF-8.")]
133    Utf8Encoding(#[from] std::string::FromUtf8Error),
134
135    #[error("IOError")]
136    ServiceIOError(#[from] std::io::Error),
137
138    #[error("Invalid hexadecimal id in directory cache")]
139    BadHexInCache(#[from] hex::FromHexError),
140
141    #[error("Invalid rustc hexadecimal id in directory cache")]
142    BadCHexInCache,
143
144    #[error("URL parse error")]
145    URLParse(#[from] url::ParseError),
146
147    #[error("Invalid hexadecimal id in directory cache")]
148    BadArrayInCache(#[from] std::array::TryFromSliceError),
149
150    #[error("JSON serialize toString error")]
151    SerializeToString,
152
153    #[error("Serialization error")]
154    SerializeError,
155
156    #[error("JSON serialization error")]
157    Serialize(#[source] serde_json::Error),
158
159    #[error("JSON deserialization error")]
160    Deserialize(#[source] serde_json::Error),
161
162    #[error("Bincode serialization error")]
163    BincodeSerialize(#[source] bincode::Error),
164
165    #[error("Bincode deserialization error")]
166    BincodeDeserialize(#[source] bincode::Error),
167
168    #[error("Unknown account")]
169    UnknownAccount,
170
171    #[error("Failed on verify message signature")]
172    VerifySignatureFailed,
173
174    #[error("ECDSA Invalid recover Id {0}")]
175    InvalidRecoverId(u8),
176
177    #[error("Gzip encode error.")]
178    GzipEncode,
179
180    #[error("Gzip decode error.")]
181    GzipDecode,
182
183    #[error("Failed on promise, state is not succeeded")]
184    PromiseStateFailed,
185
186    #[error("promise timeout, state is not succeeded")]
187    PromiseStateTimeout,
188
189    #[error("Ice server scheme {0} has not supported yet")]
190    IceServerSchemeNotSupport(String),
191
192    #[error("Ice server get url without host")]
193    IceServerURLMissHost,
194
195    #[error("Libsecp256k1 error")]
196    Libsecp256k1Error(#[from] libsecp256k1::Error),
197
198    #[error("Signature standard parse failed, {0}")]
199    Libsecp256k1SignatureParseStandard(String),
200
201    #[error("RecoverId parse failed, {0}")]
202    Libsecp256k1RecoverIdParse(String),
203
204    #[error("Libsecp256k1 recover failed")]
205    Libsecp256k1Recover,
206
207    #[error("Cannot find next node by local DHT")]
208    MessageHandlerMissNextNode,
209
210    #[error("Found existing transport when answer offer from remote node")]
211    AlreadyConnected,
212
213    #[error("You should not connect to yourself")]
214    ShouldNotConnectSelf,
215
216    #[error("Send message through channel failed")]
217    ChannelSendMessageFailed,
218
219    #[error("Recv message through channel failed {0}")]
220    ChannelRecvMessageFailed(String),
221
222    #[error("Invalid PeerRingAction")]
223    PeerRingInvalidAction,
224
225    #[error("Failed on read successors")]
226    FailedToReadSuccessors,
227
228    #[error("Successor index {index} is out of bounds for length {len}")]
229    SuccessorIndexOutOfBounds {
230        /// Requested successor index.
231        index: usize,
232        /// Current successor sequence length.
233        len: usize,
234    },
235
236    #[error("Failed on write successors")]
237    FailedToWriteSuccessors,
238
239    #[error("Failed on TryInto Entry")]
240    PeerRingInvalidEntry,
241
242    #[error("Unexpected PeerRingAction, {0:?}")]
243    PeerRingUnexpectedAction(Box<crate::dht::PeerRingAction>),
244
245    #[error("PeerRing findsuccessor error, {0}")]
246    PeerRingFindSuccessor(String),
247
248    #[error("PeerRing cannot find closest preceding node")]
249    PeerRingNotFindClosestNode,
250
251    #[error("PeerRing RWLock unlock failed")]
252    PeerRingUnlockFailed,
253
254    #[error("Cannot seek did in swarm table, {0}")]
255    SwarmMissDidInTable(crate::dht::Did),
256
257    #[error("Cannot gather local candidate, {0}")]
258    FailedOnGatherLocalCandidate(String),
259
260    #[error("Node behaviour bad")]
261    NodeBehaviourBad(crate::dht::Did),
262
263    #[error("Cannot get transport from did: {0}")]
264    SwarmMissTransport(crate::dht::Did),
265
266    #[error("Load message failed with message: {0}")]
267    SwarmLoadMessageRecvFailed(String),
268
269    #[error("Default transport is not connected")]
270    SwarmDefaultTransportNotConnected,
271
272    #[error("call lock() failed")]
273    SwarmPendingTransTryLockFailed,
274
275    #[error("transport not found")]
276    SwarmPendingTransNotFound,
277
278    #[error("failed to close previous when registering, {0}")]
279    SwarmToClosePrevTransport(String),
280
281    #[error("call lock() failed")]
282    SessionTryLockFailed,
283
284    #[error("Invalid peer type")]
285    InvalidPeerType,
286
287    #[error("Invalid entry kind")]
288    InvalidEntryKind,
289
290    #[cfg(not(feature = "wasm"))]
291    #[error("RTC new peer connection failed")]
292    RTCPeerConnectionCreateFailed(#[source] webrtc::Error),
293
294    #[error("RTC peer_connection not establish")]
295    RTCPeerConnectionNotEstablish,
296
297    #[cfg(not(feature = "wasm"))]
298    #[error("RTC peer_connection fail to create offer")]
299    RTCPeerConnectionCreateOfferFailed(#[source] webrtc::Error),
300
301    #[cfg(feature = "wasm")]
302    #[error("RTC peer_connection fail to create offer")]
303    RTCPeerConnectionCreateOfferFailed(String),
304
305    #[cfg(not(feature = "wasm"))]
306    #[error("RTC peer_connection fail to create answer")]
307    RTCPeerConnectionCreateAnswerFailed(#[source] webrtc::Error),
308
309    #[cfg(feature = "wasm")]
310    #[error("RTC peer_connection fail to create answer")]
311    RTCPeerConnectionCreateAnswerFailed(String),
312
313    #[error("DataChannel message size not match, {0} < {1}")]
314    RTCDataChannelMessageIncomplete(usize, usize),
315
316    #[cfg(not(feature = "wasm"))]
317    #[error("DataChannel send text message failed")]
318    RTCDataChannelSendTextFailed(#[source] webrtc::Error),
319
320    #[cfg(feature = "wasm")]
321    #[error("DataChannel send text message failed, {0}")]
322    RTCDataChannelSendTextFailed(String),
323
324    #[error("DataChannel not ready")]
325    RTCDataChannelNotReady,
326
327    #[error("DataChannel state not open")]
328    RTCDataChannelStateNotOpen,
329
330    #[cfg(not(feature = "wasm"))]
331    #[error("RTC peer_connection add ice candidate error")]
332    RTCPeerConnectionAddIceCandidateError(#[source] webrtc::Error),
333
334    #[cfg(feature = "wasm")]
335    #[error("RTC peer_connection add ice candidate error")]
336    RTCPeerConnectionAddIceCandidateError(String),
337
338    #[cfg(not(feature = "wasm"))]
339    #[error("RTC peer_connection set local description failed")]
340    RTCPeerConnectionSetLocalDescFailed(#[source] webrtc::Error),
341
342    #[cfg(feature = "wasm")]
343    #[error("RTC peer_connection set local description failed")]
344    RTCPeerConnectionSetLocalDescFailed(String),
345
346    #[cfg(not(feature = "wasm"))]
347    #[error("RTC peer_connection set remote description failed")]
348    RTCPeerConnectionSetRemoteDescFailed(#[source] webrtc::Error),
349
350    #[cfg(feature = "wasm")]
351    #[error("RTC peer_connection set remote description failed")]
352    RTCPeerConnectionSetRemoteDescFailed(String),
353
354    #[cfg(not(feature = "wasm"))]
355    #[error("RTC peer_connection failed to close it")]
356    RTCPeerConnectionCloseFailed(#[source] webrtc::Error),
357
358    #[error("RTC unsupported sdp type")]
359    RTCSdpTypeNotMatch,
360
361    #[error("Connection not Found")]
362    ConnectionNotFound,
363
364    #[error("Invalid Transport Id")]
365    InvalidTransportUuid,
366
367    #[error("Unexpected encrypted data")]
368    UnexpectedEncryptedData,
369
370    #[error("Failed to decrypt data")]
371    DecryptionError,
372
373    #[error("Current node is not the next hop of message")]
374    InvalidNextHop,
375
376    #[error("Adjacent elements in path cannot be equal")]
377    InvalidRelayPath,
378
379    #[error("Suspected infinite looping in path")]
380    InfiniteRelayPath,
381
382    #[error("The destination of report message should always be the first element of path")]
383    InvalidRelayDestination,
384
385    #[error("Cannot infer next hop")]
386    CannotInferNextHop,
387
388    #[error("Cannot get next hop when sending message")]
389    NoNextHop,
390
391    #[error("To generate REPORT, you should provide SEND")]
392    ReportNeedSend,
393
394    #[error("Only SEND message can reset destination")]
395    ResetDestinationNeedSend,
396
397    #[cfg(feature = "wasm")]
398    #[error("IndexedDB error, {0}")]
399    IDBError(rexie::Error),
400
401    #[error("Invalid capacity value")]
402    InvalidCapacity,
403
404    #[cfg(not(feature = "wasm"))]
405    #[error("Sled error, {0}")]
406    SledError(sled::Error),
407
408    #[error("entry not found")]
409    EntryNotFound,
410
411    #[error("IO error: {0}")]
412    IOError(std::io::Error),
413
414    #[error("Failed to get dht from a sync lock")]
415    DHTSyncLockError,
416
417    #[error("Failed to lock callback of swarm")]
418    CallbackSyncLockError,
419
420    #[error("Failed to build swarm: {0}")]
421    SwarmBuildFailed(String),
422
423    #[error("Message invalid: {0}")]
424    InvalidMessage(String),
425
426    #[error("Message encryption failed")]
427    MessageEncryptionFailed(String),
428
429    #[error("Message decryption failed")]
430    MessageDecryptionFailed(String),
431
432    #[error("Message has {0} bytes which is too large")]
433    MessageTooLarge(usize),
434
435    #[error("Peer's negotiated max_message_size {0} is too small to carry even one chunk")]
436    PeerMaxMessageSizeTooSmall(usize),
437
438    #[cfg(feature = "wasm")]
439    #[error("Cannot get property {0} from JsValue")]
440    FailedOnGetProperty(String),
441
442    #[cfg(feature = "wasm")]
443    #[error("Cannot set property {0} from JsValue")]
444    FailedOnSetProperty(String),
445
446    #[cfg(feature = "wasm")]
447    #[error("Error on ser/der JsValue")]
448    SerdeWasmBindgenError(#[from] serde_wasm_bindgen::Error),
449
450    #[cfg(feature = "wasm")]
451    #[error("Error create RTC connection: {0}")]
452    CreateConnectionError(String),
453
454    #[error("Session is expired")]
455    SessionExpired,
456
457    #[error("Transport error: {0}")]
458    Transport(#[from] rings_transport::error::Error),
459
460    #[error("External Javascript error: {0}")]
461    JsError(String),
462}
463
464impl Error {
465    pub(crate) fn unexpected_peer_ring_action(action: crate::dht::PeerRingAction) -> Self {
466        Self::PeerRingUnexpectedAction(Box::new(action))
467    }
468}
469
470#[cfg(feature = "wasm")]
471impl From<Error> for wasm_bindgen::JsValue {
472    fn from(err: Error) -> Self {
473        wasm_bindgen::JsValue::from_str(&err.to_string())
474    }
475}
476
477#[cfg(feature = "wasm")]
478impl From<js_sys::Error> for Error {
479    fn from(err: js_sys::Error) -> Self {
480        Error::JsError(err.to_string().into())
481    }
482}