web3utilities/
errors.rs

1use borsh::{BorshDeserialize, BorshSerialize};
2
3/// This data structure  implements From <T> for error types of the
4/// dependencies of this crate
5pub type UtilitiesResult<T> = Result<T, UtilitiesError>;
6
7/// Common Errors
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, BorshSerialize, BorshDeserialize)]
9pub enum UtilitiesError {
10    /// The byte length is less than 12 bytes
11    LengthLessThan12Bytes,
12    /// The byte length is greater than 12 bytes
13    LengthGreaterThan12Bytes,
14    /// The byte length is less than 16 bytes
15    LengthLessThan16Bytes,
16    /// The byte length is greater than 16 bytes
17    LengthGreaterThan16Bytes,
18    /// The byte length is less than 24 bytes
19    LengthLessThan24Bytes,
20    /// The byte length is greater than 12 bytes
21    LengthGreaterThan24Bytes,
22    /// The byte length is less than 32 bytes
23    LengthLessThan32Bytes,
24    /// The byte length is greater than 12 bytes
25    LengthGreaterThan32Bytes,
26    /// The byte length is less than 64 bytes
27    LengthLessThan64Bytes,
28    /// The byte length is greater than 64 bytes
29    LengthGreaterThan64Bytes,
30    /// The byte length is less than 128 bytes
31    LengthLessThan128Bytes,
32    /// The byte length is greater than 128 bytes
33    LengthGreaterThan128Bytes,
34    /// The bytes provided for the Ed25519 Keypair are invalid
35    InvalidBytesForEd25519Keypair,
36    /// The bytes provided for the Ed25519 Public Key are invalid
37    InvalidBytesForEd25519PublicKey,
38    /// The bytes provided for the Ed25519 Signature are invalid
39    InvalidBytesForEd25519Signature,
40    /// The bytes provided for the SR25519 Keypair are invalid
41    InvalidBytesForSr25519Keypair,
42    /// The bytes provided for the SR25519 Public Key are invalid
43    InvalidBytesForSr25519PublicKey,
44    /// The bytes provided for the Sr25519 Signature are invalid
45    InvalidBytesForSr25519Signature,
46    /// An invalid character was found. Valid ones are: `0...9`, `a...f`
47    /// or `A...F`.
48    HexInvalidHexCharacter {
49        /// The invalid hex character
50        c: String,
51        /// The index of the invalid hex character
52        index: usize,
53    },
54
55    /// A hex string's length needs to be even, as two digits correspond to
56    /// one byte.
57    HexOddLength,
58
59    /// If the hex string is decoded into a fixed sized container, such as an
60    /// array, the hex string's length * 2 has to match the container's
61    /// length.
62    HexInvalidStringLength,
63    /// Buffer
64    Base58BufferTooSmall,
65    /// Mirros the error for `bs58` crate
66    Base58InvalidCharacter {
67        /// The invalid Base58 character
68        character: String,
69        /// The index of the invalid character
70        index: usize,
71    },
72    /// Mirros the error for `bs58` crate
73    Base58NonAsciiCharacter {
74        /// The index of the non ASCII character
75        index: usize,
76    },
77    /// Base58 error encountered is not supported
78    #[cfg(feature = "base58")]
79    UnsupportedBase58Error,
80    #[cfg(feature = "tai64")]
81    /// Occurs when trying to compare an error duration
82    /// with the current duration. The current duration shoud
83    /// always be later than the earlier duration.
84    /// Utilizes std::time
85    SystemtimeInvalidEarlierDuaration,
86    #[cfg(feature = "tai64")]
87    /// Mirros Errors for Tai64 crate
88    Tai64LengthInvalid,
89    /// Mirros Errors for Tai64 crate
90    #[cfg(feature = "tai64")]
91    Tai64NanosInvalid,
92    /// Mirros Errors for Tai64 crate
93    #[cfg(feature = "tai64")]
94    /// The duration provided is smaller than the UNIX_EPOCH.
95    /// This operation is currently not supported
96    Tai64InvalidEarlierDuaration,
97    /// The public key did not sign the provided signature
98    InvalidEd25519Signature,
99    /// The bytes provided could not be encrypted
100    XChaCha8Poly1305EncryptionError,
101    /// The encrypted bytes provided could not be decrypted
102    XChaCha8Poly1305DecryptionError,
103    /// The bytes provided for the `ed25519_dalek::Keypair` are invalid
104    InvalidBytesForKeyPair,
105    /// The bytes provided for the `ed25519_dalek::PublicKey` are invalid
106    InvalidBytesForPublicKey,
107    /// The bytes provided for the `ed25519_dalek::SecretKey` are invalid
108    InvalidBytesForSecretKey,
109    /// Could not sign the message. The actual error is opaque
110    /// to prevent side-channel attacks
111    SigningError,
112    /// The memory occupied by `ed25519_dalek::Keypair` stored in `Ed25519Vault`
113    /// could not be wiped
114    MemoryCouldNotbeZeroized,
115    /// `std::io::ErrorKind` conversion
116    Io(IoErrorKind),
117}
118
119#[cfg(feature = "tai64")]
120impl From<tai64::Error> for UtilitiesError {
121    fn from(error: tai64::Error) -> Self {
122        match error {
123            tai64::Error::LengthInvalid => UtilitiesError::Tai64LengthInvalid,
124            tai64::Error::NanosInvalid => UtilitiesError::Tai64NanosInvalid,
125        }
126    }
127}
128
129#[cfg(feature = "base58")]
130impl From<bs58::decode::Error> for UtilitiesError {
131    fn from(error: bs58::decode::Error) -> Self {
132        use bs58::decode::Error as Bs58Error;
133
134        match error {
135            Bs58Error::BufferTooSmall => UtilitiesError::Base58BufferTooSmall,
136            Bs58Error::InvalidCharacter { character, index } => {
137                UtilitiesError::Base58InvalidCharacter {
138                    character: character.to_string(),
139                    index,
140                }
141            }
142            Bs58Error::NonAsciiCharacter { index } => {
143                UtilitiesError::Base58NonAsciiCharacter { index }
144            }
145            _ => UtilitiesError::UnsupportedBase58Error,
146        }
147    }
148}
149
150#[cfg(feature = "base58")]
151impl From<bs58::encode::Error> for UtilitiesError {
152    fn from(error: bs58::encode::Error) -> Self {
153        use bs58::encode::Error as Bs58Error;
154
155        match error {
156            Bs58Error::BufferTooSmall => UtilitiesError::Base58BufferTooSmall,
157            _ => UtilitiesError::UnsupportedBase58Error,
158        }
159    }
160}
161
162#[cfg(feature = "hex")]
163impl From<hex::FromHexError> for UtilitiesError {
164    fn from(error: hex::FromHexError) -> Self {
165        match error {
166            hex::FromHexError::OddLength => UtilitiesError::HexOddLength,
167            hex::FromHexError::InvalidStringLength => UtilitiesError::HexInvalidStringLength,
168            hex::FromHexError::InvalidHexCharacter { c, index } => {
169                UtilitiesError::HexInvalidHexCharacter {
170                    c: c.to_string(),
171                    index,
172                }
173            }
174        }
175    }
176}
177
178impl From<std::io::Error> for UtilitiesError {
179    fn from(error: std::io::Error) -> Self {
180        use std::io::ErrorKind;
181
182        match error.kind() {
183            ErrorKind::NotFound => UtilitiesError::Io(IoErrorKind::NotFound),
184            ErrorKind::PermissionDenied => UtilitiesError::Io(IoErrorKind::PermissionDenied),
185            ErrorKind::ConnectionRefused => UtilitiesError::Io(IoErrorKind::ConnectionRefused),
186            ErrorKind::ConnectionReset => UtilitiesError::Io(IoErrorKind::ConnectionReset),
187            ErrorKind::ConnectionAborted => UtilitiesError::Io(IoErrorKind::ConnectionAborted),
188            ErrorKind::NotConnected => UtilitiesError::Io(IoErrorKind::NotConnected),
189            ErrorKind::AddrInUse => UtilitiesError::Io(IoErrorKind::AddrInUse),
190            ErrorKind::AddrNotAvailable => UtilitiesError::Io(IoErrorKind::AddrNotAvailable),
191            ErrorKind::BrokenPipe => UtilitiesError::Io(IoErrorKind::BrokenPipe),
192            ErrorKind::AlreadyExists => UtilitiesError::Io(IoErrorKind::AlreadyExists),
193            ErrorKind::WouldBlock => UtilitiesError::Io(IoErrorKind::WouldBlock),
194            ErrorKind::InvalidInput => UtilitiesError::Io(IoErrorKind::InvalidInput),
195            ErrorKind::InvalidData => UtilitiesError::Io(IoErrorKind::InvalidData),
196            ErrorKind::TimedOut => UtilitiesError::Io(IoErrorKind::TimedOut),
197            ErrorKind::WriteZero => UtilitiesError::Io(IoErrorKind::WriteZero),
198            ErrorKind::Interrupted => UtilitiesError::Io(IoErrorKind::Interrupted),
199            ErrorKind::UnexpectedEof => UtilitiesError::Io(IoErrorKind::UnexpectedEof),
200            ErrorKind::OutOfMemory => UtilitiesError::Io(IoErrorKind::OutOfMemory),
201            ErrorKind::Other => UtilitiesError::Io(IoErrorKind::Other),
202            _ => UtilitiesError::Io(IoErrorKind::UnsupportedErrorKind),
203        }
204    }
205}
206
207/// Implemetation for `From<std::io::ErrorKind>` for this crate
208#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, BorshSerialize, BorshDeserialize)]
209pub enum IoErrorKind {
210    /// An entity was not found, often a file.
211    NotFound,
212    /// The operation lacked the necessary privileges to complete.
213    PermissionDenied,
214    /// The connection was refused by the remote server.
215    ConnectionRefused,
216    /// The connection was reset by the remote server.
217    ConnectionReset,
218    /// The connection was aborted (terminated) by the remote server.
219    ConnectionAborted,
220    ///The network operation failed because it was not connected yet.
221    NotConnected,
222    /// A socket address could not be bound because the address is already in use elsewhere.
223    AddrInUse,
224    /// A nonexistent interface was requested or the requested address was not local.
225    AddrNotAvailable,
226    /// The operation failed because a pipe was closed.
227    BrokenPipe,
228    /// An entity already exists, often a file.
229    AlreadyExists,
230    /// The operation needs to block to complete, but the blocking operation was requested to not occur.
231    WouldBlock,
232    /// A parameter was incorrect.
233    InvalidInput,
234    /// Data not valid for the operation were encountered.
235    /// Unlike InvalidInput, this typically means that the operation parameters were valid, however the error was caused by malformed input data.
236    ///
237    /// For example, a function that reads a file into a string will error with InvalidData if the file's
238    /// contents are not valid UTF-8.
239    InvalidData,
240    /// The I/O operation's timeout expired, causing it to be canceled.
241    TimedOut,
242    /// An error returned when an operation could not be completed because a call to write returned Ok(0).
243    WriteZero,
244    /// An error returned when an operation could not be completed because a call to write returned Ok(0).
245    ///
246    /// This typically means that an operation could only succeed if it wrote a particular number of bytes but only a smaller number of bytes could be written.
247    Interrupted,
248    /// Any I/O error not part of this list.
249    ///
250    /// Errors that are Other now may move to a different or a new ErrorKind variant in the future. It is not recommended to match an error against Other and to expect any additional characteristics, e.g., a specific Error::raw_os_error return value.
251    Other,
252    /// An error returned when an operation could not be completed because an "end of file" was reached prematurely.
253    ///
254    /// This typically means that an operation could only succeed if it read a particular number of bytes but only a smaller number of bytes could be read.
255    UnexpectedEof,
256    /// An operation could not be completed, because it failed to allocate enough memory.
257    OutOfMemory,
258    /// `ErrorKind` encountered is not yet supported
259    UnsupportedErrorKind,
260}