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
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement.  This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.

use futures::sync::mpsc::SendError;
use maidsafe_utilities::serialisation::SerialisationError;
use routing::{ClientError, InterfaceError, RoutingError};
use routing::messaging;
use self_encryption::SelfEncryptionError;
use self_encryption_storage::SelfEncryptionStorageError;
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::sync::mpsc;

/// Client Errors
#[cfg_attr(feature = "cargo-clippy", allow(large_enum_variant))]
pub enum CoreError {
    /// Could not Serialise or Deserialise
    EncodeDecodeError(SerialisationError),
    /// Asymmetric Key Decryption Failed
    AsymmetricDecipherFailure,
    /// Symmetric Key Decryption Failed
    SymmetricDecipherFailure,
    /// Received unexpected data
    ReceivedUnexpectedData,
    /// Received unexpected event
    ReceivedUnexpectedEvent,
    /// No such data found in local version cache
    VersionCacheMiss,
    /// Cannot overwrite a root directory if it already exists
    RootDirectoryExists,
    /// Unable to obtain generator for random data
    RandomDataGenerationFailure,
    /// Forbidden operation
    OperationForbidden,
    /// Unexpected - Probably a Logic error
    Unexpected(String),
    /// Routing Error
    RoutingError(RoutingError),
    /// Interface Error
    RoutingInterfaceError(InterfaceError),
    /// Routing Client Error
    RoutingClientError(ClientError),
    /// Unable to pack into or operate with size of Salt
    UnsupportedSaltSizeForPwHash,
    /// Unable to complete computation for password hashing - usually because
    /// OS refused to
    /// allocate amount of requested memory
    UnsuccessfulPwHash,
    /// Blocking operation was cancelled
    OperationAborted,
    /// MpidMessaging Error
    MpidMessagingError(messaging::Error),
    /// Error while self-encrypting data
    SelfEncryption(SelfEncryptionError<SelfEncryptionStorageError>),
    /// The request has timed out
    RequestTimeout,
}

impl<'a> From<&'a str> for CoreError {
    fn from(error: &'a str) -> CoreError {
        CoreError::Unexpected(error.to_string())
    }
}

impl From<String> for CoreError {
    fn from(error: String) -> CoreError {
        CoreError::Unexpected(error)
    }
}

impl<T> From<SendError<T>> for CoreError {
    fn from(error: SendError<T>) -> CoreError {
        CoreError::from(format!("Couldn't send message to the channel: {}", error))
    }
}

impl From<SerialisationError> for CoreError {
    fn from(error: SerialisationError) -> CoreError {
        CoreError::EncodeDecodeError(error)
    }
}

impl From<RoutingError> for CoreError {
    fn from(error: RoutingError) -> CoreError {
        CoreError::RoutingError(error)
    }
}

impl From<InterfaceError> for CoreError {
    fn from(error: InterfaceError) -> CoreError {
        CoreError::RoutingInterfaceError(error)
    }
}

impl From<ClientError> for CoreError {
    fn from(error: ClientError) -> CoreError {
        CoreError::RoutingClientError(error)
    }
}

impl From<mpsc::RecvError> for CoreError {
    fn from(_: mpsc::RecvError) -> CoreError {
        CoreError::OperationAborted
    }
}

impl From<messaging::Error> for CoreError {
    fn from(error: messaging::Error) -> CoreError {
        CoreError::MpidMessagingError(error)
    }
}

impl From<SelfEncryptionError<SelfEncryptionStorageError>> for CoreError {
    fn from(error: SelfEncryptionError<SelfEncryptionStorageError>) -> CoreError {
        CoreError::SelfEncryption(error)
    }
}

impl Debug for CoreError {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        write!(formatter, "{} - ", self.description())?;
        match *self {
            CoreError::EncodeDecodeError(ref error) => {
                write!(formatter, "CoreError::EncodeDecodeError -> {:?}", error)
            }
            CoreError::AsymmetricDecipherFailure => {
                write!(formatter, "CoreError::AsymmetricDecipherFailure")
            }
            CoreError::SymmetricDecipherFailure => {
                write!(formatter, "CoreError::SymmetricDecipherFailure")
            }
            CoreError::ReceivedUnexpectedData => {
                write!(formatter, "CoreError::ReceivedUnexpectedData")
            }
            CoreError::ReceivedUnexpectedEvent => {
                write!(formatter, "CoreError::ReceivedUnexpectedEvent")
            }
            CoreError::VersionCacheMiss => write!(formatter, "CoreError::VersionCacheMiss"),
            CoreError::RootDirectoryExists => write!(formatter, "CoreError::RootDirectoryExists"),
            CoreError::RandomDataGenerationFailure => {
                write!(formatter, "CoreError::RandomDataGenerationFailure")
            }
            CoreError::OperationForbidden => write!(formatter, "CoreError::OperationForbidden"),
            CoreError::Unexpected(ref error) => {
                write!(formatter, "CoreError::Unexpected::{{{:?}}}", error)
            }
            CoreError::RoutingError(ref error) => {
                write!(formatter, "CoreError::RoutingError -> {:?}", error)
            }
            CoreError::RoutingInterfaceError(ref error) => {
                write!(formatter, "CoreError::RoutingInterfaceError -> {:?}", error)
            }
            CoreError::RoutingClientError(ref error) => {
                write!(formatter, "CoreError::RoutingClientError -> {:?}", error)
            }
            CoreError::UnsupportedSaltSizeForPwHash => {
                write!(formatter, "CoreError::UnsupportedSaltSizeForPwHash")
            }
            CoreError::UnsuccessfulPwHash => write!(formatter, "CoreError::UnsuccessfulPwHash"),
            CoreError::OperationAborted => write!(formatter, "CoreError::OperationAborted"),
            CoreError::MpidMessagingError(ref error) => {
                write!(formatter, "CoreError::MpidMessagingError -> {:?}", error)
            }
            CoreError::SelfEncryption(ref error) => {
                write!(formatter, "CoreError::SelfEncryption -> {:?}", error)
            }
            CoreError::RequestTimeout => write!(formatter, "CoreError::RequestTimeout"),
        }
    }
}

impl Display for CoreError {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        match *self {
            CoreError::EncodeDecodeError(ref error) => {
                write!(
                    formatter,
                    "Error while serialising/deserialising: {}",
                    error
                )
            }
            CoreError::AsymmetricDecipherFailure => {
                write!(formatter, "Asymmetric decryption failed")
            }
            CoreError::SymmetricDecipherFailure => write!(formatter, "Symmetric decryption failed"),
            CoreError::ReceivedUnexpectedData => write!(formatter, "Received unexpected data"),
            CoreError::ReceivedUnexpectedEvent => write!(formatter, "Received unexpected event"),
            CoreError::VersionCacheMiss => {
                write!(formatter, "No such data found in local version cache")
            }
            CoreError::RootDirectoryExists => {
                write!(
                    formatter,
                    "Cannot overwrite a root directory if it already exists"
                )
            }
            CoreError::RandomDataGenerationFailure => {
                write!(formatter, "Unable to obtain generator for random data")
            }
            CoreError::OperationForbidden => write!(formatter, "Forbidden operation requested"),
            CoreError::Unexpected(ref error) => write!(formatter, "Unexpected: {}", error),
            CoreError::RoutingError(ref error) => {
                // TODO - use `{}` once `RoutingError` implements `std::error::Error`.
                write!(formatter, "Routing internal error: {:?}", error)
            }
            CoreError::RoutingInterfaceError(ref error) => {
                // TODO - use `{}` once `InterfaceError` implements `std::error::Error`.
                write!(formatter, "Routing interface error -> {:?}", error)
            }
            CoreError::RoutingClientError(ref error) => {
                write!(formatter, "Routing client error -> {}", error)
            }
            CoreError::UnsupportedSaltSizeForPwHash => {
                write!(
                    formatter,
                    "Unable to pack into or operate with size of Salt"
                )
            }
            CoreError::UnsuccessfulPwHash => {
                write!(
                    formatter,
                    "Unable to complete computation for password hashing"
                )
            }
            CoreError::OperationAborted => write!(formatter, "Blocking operation was cancelled"),
            CoreError::MpidMessagingError(ref error) => {
                write!(formatter, "Mpid messaging error: {}", error)
            }
            CoreError::SelfEncryption(ref error) => {
                write!(formatter, "Self-encryption error: {}", error)
            }
            CoreError::RequestTimeout => write!(formatter, "CoreError::RequestTimeout"),
        }
    }
}

impl Error for CoreError {
    fn description(&self) -> &str {
        match *self {
            CoreError::EncodeDecodeError(_) => "Serialisation error",
            CoreError::AsymmetricDecipherFailure => "Asymmetric decryption failure",
            CoreError::SymmetricDecipherFailure => "Symmetric decryption failure",
            CoreError::ReceivedUnexpectedData => "Received unexpected data",
            CoreError::ReceivedUnexpectedEvent => "Received unexpected event",
            CoreError::VersionCacheMiss => "Version cache miss",
            CoreError::RootDirectoryExists => "Root directory already exists",
            CoreError::RandomDataGenerationFailure => "Cannot obtain RNG",
            CoreError::OperationForbidden => "Operation forbidden",
            CoreError::Unexpected(_) => "Unexpected error",
            // TODO - use `error.description()` once `RoutingError` implements `std::error::Error`.
            CoreError::RoutingError(_) => "Routing internal error",
            // TODO - use `error.description()` once `InterfaceError` implements `std::error::Error`
            CoreError::RoutingClientError(ref error) => error.description(),
            CoreError::RoutingInterfaceError(_) => "Routing interface error",
            CoreError::UnsupportedSaltSizeForPwHash => "Unsupported size of salt",
            CoreError::UnsuccessfulPwHash => "Failed while password hashing",
            CoreError::OperationAborted => "Operation aborted",
            CoreError::MpidMessagingError(_) => "Mpid messaging error",
            CoreError::SelfEncryption(ref error) => error.description(),
            CoreError::RequestTimeout => "Request has timed out",
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            CoreError::EncodeDecodeError(ref err) => Some(err),
            CoreError::MpidMessagingError(ref err) => Some(err),
            // CoreError::RoutingError(ref err) => Some(err),
            // CoreError::RoutingInterfaceError(ref err) => Some(err),
            CoreError::RoutingClientError(ref err) => Some(err),
            CoreError::SelfEncryption(ref err) => Some(err),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    /*
    use core::SelfEncryptionStorageError;
    use rand;
    use routing::{ClientError, DataIdentifier};
    use self_encryption::SelfEncryptionError;
    use super::*;

    #[test]
    fn self_encryption_error() {
        let id = rand::random();
        let core_err_0 = CoreError::MutationFailure {
            data_id: DataIdentifier::Structured(id, 10000),
            reason: MutationError::LowBalance,
        };
        let core_err_1 = CoreError::MutationFailure {
            data_id: DataIdentifier::Structured(id, 10000),
            reason: MutationError::LowBalance,
        };

        let se_err = SelfEncryptionError::Storage(SelfEncryptionStorageError(Box::new(core_err_0)));
        let core_from_se_err = CoreError::from(se_err);

        assert_eq!(Into::<i32>::into(core_err_1),
                   Into::<i32>::into(core_from_se_err));
    }
    */
}