rings-core 0.10.0

Chord DHT implementation with ICE
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Error of rings_core

/// A wrap `Result` contains custom errors.
pub type Result<T> = std::result::Result<T, Error>;

/// Errors collections in ring-core.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
    #[error("Serialize affine failed")]
    EccSerializeFailed,
    #[error("desrialize affine failed")]
    EccDeserializeFailed,
    #[error("Failed to initialize Curve hasher")]
    CurveHasherInitFailed,
    #[error("Failed to hash data into cruve")]
    CurveHasherFailed,

    #[error("Ed25519/EdDSA pubkey bad format")]
    EdDSAPublicKeyBadFormat,

    #[error("Secp256k1/ECDSA pubkey bad format")]
    ECDSAPublicKeyBadFormat,

    #[error("Failed to lift encoded plaintext into a secp256k1 point")]
    Secp256k1PointLiftFailed,

    #[error("E2E stream id mismatch: expected {expected}, actual {actual}")]
    E2eStreamIdMismatch {
        /// Stream ID expected by the decryptor.
        expected: uuid::Uuid,
        /// Stream ID carried by the frame.
        actual: uuid::Uuid,
    },

    #[error("E2E frame sequence mismatch: expected {expected}, actual {actual}")]
    E2eFrameSequenceMismatch {
        /// Sequence number expected by the decryptor.
        expected: u64,
        /// Sequence number carried by the frame.
        actual: u64,
    },

    #[error(
        "E2E frame sequence {actual} exceeds reorder window {window} from next sequence {next_sequence}"
    )]
    E2eFrameReorderWindowExceeded {
        /// Next contiguous sequence number expected by the decryptor.
        next_sequence: u64,
        /// Sequence number carried by the frame.
        actual: u64,
        /// Maximum accepted gap ahead of the next sequence.
        window: u64,
    },

    #[error("E2E frame sequence counter overflowed")]
    E2eFrameSequenceOverflow,

    #[error("E2E frame received after the authenticated final frame")]
    E2eFrameAfterFinal,

    #[error("E2E stream is missing the authenticated final frame")]
    E2eMissingFinalFrame,

    #[error("E2E public key resolves to {actual}, expected {expected}")]
    E2ePublicKeyDidMismatch {
        /// DID expected by the signed message context.
        expected: crate::dht::Did,
        /// DID derived from the supplied public key.
        actual: crate::dht::Did,
    },

    #[error("Secp256r1/ECDSA Error: {0}")]
    ECDSAError(#[from] ecdsa::Error),

    #[error("ECDSA or EdDSA pubkey bad format")]
    PublicKeyBadFormat,

    #[error("Failed to decode vector to bls affine")]
    BlsAffineDecodeFailed,

    #[error("private bad format")]
    PrivateKeyBadFormat,

    #[error("Invalid Transport")]
    InvalidTransport,

    #[error("InvalidPublicKey")]
    InvalidPublicKey,

    #[error("Entry kind not equal when overwriting")]
    EntryKindNotEqual,

    #[error("Did of Entry not equal")]
    EntryDidNotEqual,

    #[error("The type of Entry is not allowed to be overwritten")]
    EntryNotOverwritable,

    #[error("The type of Entry is not allowed to be appended")]
    EntryNotAppendable,

    #[error("The type of Entry is not allowed to be joined as a subring")]
    EntryNotJoinable,

    #[error("The type of Entry is not allowed to be tombstoned")]
    EntryNotTombstonable,

    #[error("Entry dot index {index} is out of bounds")]
    EntryDotIndexOutOfBounds {
        /// Dot index that could not be represented.
        index: usize,
    },

    #[error("Affine rotation scalar must be greater than zero")]
    InvalidAffineScalar,

    #[error("Storage redundancy mismatch: transport configured {configured}, storage request uses {requested}")]
    StorageRedundancyMismatch {
        /// Redundancy configured on swarm transport for repair.
        configured: u16,
        /// Redundancy requested by the storage API const generic.
        requested: u16,
    },

    #[error("Encode a byte vector into a base58-check string, adds 4 bytes checksum")]
    Encode,

    #[error("Decode base58-encoded with 4 bytes checksum string into a byte vector")]
    Decode,

    #[error("Couldn't decode data as UTF-8.")]
    Utf8Encoding(#[from] std::string::FromUtf8Error),

    #[error("IOError")]
    ServiceIOError(#[from] std::io::Error),

    #[error("Invalid hexadecimal id in directory cache")]
    BadHexInCache(#[from] hex::FromHexError),

    #[error("Invalid rustc hexadecimal id in directory cache")]
    BadCHexInCache,

    #[error("URL parse error")]
    URLParse(#[from] url::ParseError),

    #[error("Invalid hexadecimal id in directory cache")]
    BadArrayInCache(#[from] std::array::TryFromSliceError),

    #[error("JSON serialize toString error")]
    SerializeToString,

    #[error("Serialization error")]
    SerializeError,

    #[error("JSON serialization error")]
    Serialize(#[source] serde_json::Error),

    #[error("JSON deserialization error")]
    Deserialize(#[source] serde_json::Error),

    #[error("Bincode serialization error")]
    BincodeSerialize(#[source] bincode::Error),

    #[error("Bincode deserialization error")]
    BincodeDeserialize(#[source] bincode::Error),

    #[error("Unknown account")]
    UnknownAccount,

    #[error("Failed on verify message signature")]
    VerifySignatureFailed,

    #[error("ECDSA Invalid recover Id {0}")]
    InvalidRecoverId(u8),

    #[error("Gzip encode error.")]
    GzipEncode,

    #[error("Gzip decode error.")]
    GzipDecode,

    #[error("Failed on promise, state is not succeeded")]
    PromiseStateFailed,

    #[error("promise timeout, state is not succeeded")]
    PromiseStateTimeout,

    #[error("Ice server scheme {0} has not supported yet")]
    IceServerSchemeNotSupport(String),

    #[error("Ice server get url without host")]
    IceServerURLMissHost,

    #[error("Libsecp256k1 error")]
    Libsecp256k1Error(#[from] libsecp256k1::Error),

    #[error("Signature standard parse failed, {0}")]
    Libsecp256k1SignatureParseStandard(String),

    #[error("RecoverId parse failed, {0}")]
    Libsecp256k1RecoverIdParse(String),

    #[error("Libsecp256k1 recover failed")]
    Libsecp256k1Recover,

    #[error("Cannot find next node by local DHT")]
    MessageHandlerMissNextNode,

    #[error("Found existing transport when answer offer from remote node")]
    AlreadyConnected,

    #[error("You should not connect to yourself")]
    ShouldNotConnectSelf,

    #[error("Send message through channel failed")]
    ChannelSendMessageFailed,

    #[error("Recv message through channel failed {0}")]
    ChannelRecvMessageFailed(String),

    #[error("Invalid PeerRingAction")]
    PeerRingInvalidAction,

    #[error("Failed on read successors")]
    FailedToReadSuccessors,

    #[error("Successor index {index} is out of bounds for length {len}")]
    SuccessorIndexOutOfBounds {
        /// Requested successor index.
        index: usize,
        /// Current successor sequence length.
        len: usize,
    },

    #[error("Failed on write successors")]
    FailedToWriteSuccessors,

    #[error("Failed on TryInto Entry")]
    PeerRingInvalidEntry,

    #[error("Unexpected PeerRingAction, {0:?}")]
    PeerRingUnexpectedAction(Box<crate::dht::PeerRingAction>),

    #[error("PeerRing findsuccessor error, {0}")]
    PeerRingFindSuccessor(String),

    #[error("PeerRing cannot find closest preceding node")]
    PeerRingNotFindClosestNode,

    #[error("PeerRing RWLock unlock failed")]
    PeerRingUnlockFailed,

    #[error("Cannot seek did in swarm table, {0}")]
    SwarmMissDidInTable(crate::dht::Did),

    #[error("Cannot gather local candidate, {0}")]
    FailedOnGatherLocalCandidate(String),

    #[error("Node behaviour bad")]
    NodeBehaviourBad(crate::dht::Did),

    #[error("Cannot get transport from did: {0}")]
    SwarmMissTransport(crate::dht::Did),

    #[error("Load message failed with message: {0}")]
    SwarmLoadMessageRecvFailed(String),

    #[error("Default transport is not connected")]
    SwarmDefaultTransportNotConnected,

    #[error("call lock() failed")]
    SwarmPendingTransTryLockFailed,

    #[error("transport not found")]
    SwarmPendingTransNotFound,

    #[error("failed to close previous when registering, {0}")]
    SwarmToClosePrevTransport(String),

    #[error("call lock() failed")]
    SessionTryLockFailed,

    #[error("Invalid peer type")]
    InvalidPeerType,

    #[error("Invalid entry kind")]
    InvalidEntryKind,

    #[cfg(not(feature = "wasm"))]
    #[error("RTC new peer connection failed")]
    RTCPeerConnectionCreateFailed(#[source] webrtc::Error),

    #[error("RTC peer_connection not establish")]
    RTCPeerConnectionNotEstablish,

    #[cfg(not(feature = "wasm"))]
    #[error("RTC peer_connection fail to create offer")]
    RTCPeerConnectionCreateOfferFailed(#[source] webrtc::Error),

    #[cfg(feature = "wasm")]
    #[error("RTC peer_connection fail to create offer")]
    RTCPeerConnectionCreateOfferFailed(String),

    #[cfg(not(feature = "wasm"))]
    #[error("RTC peer_connection fail to create answer")]
    RTCPeerConnectionCreateAnswerFailed(#[source] webrtc::Error),

    #[cfg(feature = "wasm")]
    #[error("RTC peer_connection fail to create answer")]
    RTCPeerConnectionCreateAnswerFailed(String),

    #[error("DataChannel message size not match, {0} < {1}")]
    RTCDataChannelMessageIncomplete(usize, usize),

    #[cfg(not(feature = "wasm"))]
    #[error("DataChannel send text message failed")]
    RTCDataChannelSendTextFailed(#[source] webrtc::Error),

    #[cfg(feature = "wasm")]
    #[error("DataChannel send text message failed, {0}")]
    RTCDataChannelSendTextFailed(String),

    #[error("DataChannel not ready")]
    RTCDataChannelNotReady,

    #[error("DataChannel state not open")]
    RTCDataChannelStateNotOpen,

    #[cfg(not(feature = "wasm"))]
    #[error("RTC peer_connection add ice candidate error")]
    RTCPeerConnectionAddIceCandidateError(#[source] webrtc::Error),

    #[cfg(feature = "wasm")]
    #[error("RTC peer_connection add ice candidate error")]
    RTCPeerConnectionAddIceCandidateError(String),

    #[cfg(not(feature = "wasm"))]
    #[error("RTC peer_connection set local description failed")]
    RTCPeerConnectionSetLocalDescFailed(#[source] webrtc::Error),

    #[cfg(feature = "wasm")]
    #[error("RTC peer_connection set local description failed")]
    RTCPeerConnectionSetLocalDescFailed(String),

    #[cfg(not(feature = "wasm"))]
    #[error("RTC peer_connection set remote description failed")]
    RTCPeerConnectionSetRemoteDescFailed(#[source] webrtc::Error),

    #[cfg(feature = "wasm")]
    #[error("RTC peer_connection set remote description failed")]
    RTCPeerConnectionSetRemoteDescFailed(String),

    #[cfg(not(feature = "wasm"))]
    #[error("RTC peer_connection failed to close it")]
    RTCPeerConnectionCloseFailed(#[source] webrtc::Error),

    #[error("RTC unsupported sdp type")]
    RTCSdpTypeNotMatch,

    #[error("Connection not Found")]
    ConnectionNotFound,

    #[error("Invalid Transport Id")]
    InvalidTransportUuid,

    #[error("Unexpected encrypted data")]
    UnexpectedEncryptedData,

    #[error("Failed to decrypt data")]
    DecryptionError,

    #[error("Current node is not the next hop of message")]
    InvalidNextHop,

    #[error("Adjacent elements in path cannot be equal")]
    InvalidRelayPath,

    #[error("Suspected infinite looping in path")]
    InfiniteRelayPath,

    #[error("The destination of report message should always be the first element of path")]
    InvalidRelayDestination,

    #[error("Cannot infer next hop")]
    CannotInferNextHop,

    #[error("Cannot get next hop when sending message")]
    NoNextHop,

    #[error("To generate REPORT, you should provide SEND")]
    ReportNeedSend,

    #[error("Only SEND message can reset destination")]
    ResetDestinationNeedSend,

    #[cfg(feature = "wasm")]
    #[error("IndexedDB error, {0}")]
    IDBError(rexie::Error),

    #[error("Invalid capacity value")]
    InvalidCapacity,

    #[cfg(not(feature = "wasm"))]
    #[error("Sled error, {0}")]
    SledError(sled::Error),

    #[error("entry not found")]
    EntryNotFound,

    #[error("IO error: {0}")]
    IOError(std::io::Error),

    #[error("Failed to get dht from a sync lock")]
    DHTSyncLockError,

    #[error("Failed to lock callback of swarm")]
    CallbackSyncLockError,

    #[error("Failed to build swarm: {0}")]
    SwarmBuildFailed(String),

    #[error("Message invalid: {0}")]
    InvalidMessage(String),

    #[error("Message encryption failed")]
    MessageEncryptionFailed(String),

    #[error("Message decryption failed")]
    MessageDecryptionFailed(String),

    #[error("Message has {0} bytes which is too large")]
    MessageTooLarge(usize),

    #[error("Peer's negotiated max_message_size {0} is too small to carry even one chunk")]
    PeerMaxMessageSizeTooSmall(usize),

    #[cfg(feature = "wasm")]
    #[error("Cannot get property {0} from JsValue")]
    FailedOnGetProperty(String),

    #[cfg(feature = "wasm")]
    #[error("Cannot set property {0} from JsValue")]
    FailedOnSetProperty(String),

    #[cfg(feature = "wasm")]
    #[error("Error on ser/der JsValue")]
    SerdeWasmBindgenError(#[from] serde_wasm_bindgen::Error),

    #[cfg(feature = "wasm")]
    #[error("Error create RTC connection: {0}")]
    CreateConnectionError(String),

    #[error("Session is expired")]
    SessionExpired,

    #[error("Transport error: {0}")]
    Transport(#[from] rings_transport::error::Error),

    #[error("External Javascript error: {0}")]
    JsError(String),
}

impl Error {
    pub(crate) fn unexpected_peer_ring_action(action: crate::dht::PeerRingAction) -> Self {
        Self::PeerRingUnexpectedAction(Box::new(action))
    }
}

#[cfg(feature = "wasm")]
impl From<Error> for wasm_bindgen::JsValue {
    fn from(err: Error) -> Self {
        wasm_bindgen::JsValue::from_str(&err.to_string())
    }
}

#[cfg(feature = "wasm")]
impl From<js_sys::Error> for Error {
    fn from(err: js_sys::Error) -> Self {
        Error::JsError(err.to_string().into())
    }
}