1use crate::bencode;
2use crate::dht::krpc::ErrorMessage;
3use std::{io, result};
4use thiserror::Error;
5
6pub type Result<T> = result::Result<T, Error>;
8
9#[derive(Debug, Error)]
11pub enum Error {
12 #[error("krpc message is invalid, {0}")]
13 InvalidMessage(String),
14 #[error("transaction id is invalid")]
15 InvalidTransactionId,
16 #[error("invalid node id")]
17 InvalidNodeId,
18 #[error("address is invalid")]
19 InvalidAddr,
20 #[error("token is invalid")]
21 InvalidToken,
22 #[error("signature is invalid")]
23 InvalidSignature,
24 #[error("sequence number is less than current")]
25 InvalidSequenceNr,
26 #[error("item already exists")]
27 AlreadyExists,
28 #[error("missing crypto provider")]
29 MissingCryptoProvider,
30 #[error("response error code {0}, {1}")]
31 Response(u16, String),
32 #[error("timed-out while waiting for a response from the node")]
33 Timeout,
34 #[error("method is unsupported")]
35 Unsupported,
36 #[error("failed to parse message, {0}")]
37 Parse(String),
38 #[error("an io error occurred, {0}")]
39 Io(io::Error),
40 #[error("node server has been stopped")]
41 Closed,
42}
43
44impl From<ErrorMessage> for Error {
45 fn from(value: ErrorMessage) -> Self {
46 Self::Response(value.code(), value.description().to_string())
47 }
48}
49
50impl From<bencode::Error> for Error {
51 fn from(e: bencode::Error) -> Self {
52 Self::Parse(e.to_string())
53 }
54}
55
56impl From<io::Error> for Error {
57 fn from(value: io::Error) -> Self {
58 Self::Io(value)
59 }
60}
61
62impl PartialEq for Error {
63 fn eq(&self, other: &Self) -> bool {
64 match (self, other) {
65 (Self::InvalidMessage(_), Self::InvalidMessage(_)) => true,
66 (Self::InvalidTransactionId, Self::InvalidTransactionId) => true,
67 (Self::InvalidNodeId, Self::InvalidNodeId) => true,
68 (Self::InvalidAddr, Self::InvalidAddr) => true,
69 (Self::InvalidToken, Self::InvalidToken) => true,
70 (Self::InvalidSignature, Self::InvalidSignature) => true,
71 (Self::AlreadyExists, Self::AlreadyExists) => true,
72 (Self::MissingCryptoProvider, Self::MissingCryptoProvider) => true,
73 (Self::Response(code, _), Self::Response(other_code, _)) => code == other_code,
74 (Self::Timeout, Self::Timeout) => true,
75 (Self::Unsupported, Self::Unsupported) => true,
76 (Self::Parse(_), Self::Parse(_)) => true,
77 (Self::Io(_), Self::Io(_)) => true,
78 (Self::Closed, Self::Closed) => true,
79 _ => false,
80 }
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn test_from_error_message() {
90 let msg = "A Generic error occurred";
91 let error = ErrorMessage::Generic(msg.to_string());
92 let expected_result = Error::Response(201, msg.to_string());
93
94 let result = Error::from(error);
95
96 assert_eq!(expected_result, result);
97 }
98}