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
// Copyright 2018-2020 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::error::Error;
use std::fmt;

use crate::circuit;
use crate::consensus::error::ProposalManagerError;
use crate::orchestrator::InitializeServiceError;
use crate::service::error::{ServiceError, ServiceSendError};
use crate::signing;

use protobuf::error;

#[derive(Debug)]
pub enum AdminServiceError {
    ServiceError(ServiceError),

    GeneralError {
        context: String,
        source: Option<Box<dyn Error + Send>>,
    },
}

impl AdminServiceError {
    pub fn general_error(context: &str) -> Self {
        AdminServiceError::GeneralError {
            context: context.into(),
            source: None,
        }
    }

    pub fn general_error_with_source(context: &str, err: Box<dyn Error + Send>) -> Self {
        AdminServiceError::GeneralError {
            context: context.into(),
            source: Some(err),
        }
    }
}

impl Error for AdminServiceError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            AdminServiceError::ServiceError(err) => Some(err),
            AdminServiceError::GeneralError { source, .. } => {
                if let Some(ref err) = source {
                    Some(&**err)
                } else {
                    None
                }
            }
        }
    }
}

impl fmt::Display for AdminServiceError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AdminServiceError::ServiceError(err) => f.write_str(&err.to_string()),
            AdminServiceError::GeneralError { context, source } => {
                if let Some(ref err) = source {
                    write!(f, "{}: {}", context, err)
                } else {
                    f.write_str(&context)
                }
            }
        }
    }
}

impl From<ServiceError> for AdminServiceError {
    fn from(err: ServiceError) -> Self {
        AdminServiceError::ServiceError(err)
    }
}

#[derive(Debug)]
pub enum AdminSubscriberError {
    UnableToHandleEvent(String),
    Unsubscribe,
}

impl Error for AdminSubscriberError {}

impl fmt::Display for AdminSubscriberError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AdminSubscriberError::UnableToHandleEvent(msg) => {
                write!(f, "Unable to handle event: {}", msg)
            }
            AdminSubscriberError::Unsubscribe => f.write_str("Unsubscribe"),
        }
    }
}

#[derive(Debug)]
pub struct AdminKeyVerifierError {
    context: String,
    source: Option<Box<dyn Error + Send>>,
}

impl AdminKeyVerifierError {
    pub fn new(context: &str) -> Self {
        Self {
            context: context.into(),
            source: None,
        }
    }

    pub fn new_with_source(context: &str, err: Box<dyn Error + Send>) -> Self {
        Self {
            context: context.into(),
            source: Some(err),
        }
    }
}

impl Error for AdminKeyVerifierError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        if let Some(ref err) = self.source {
            Some(&**err)
        } else {
            None
        }
    }
}

impl fmt::Display for AdminKeyVerifierError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref err) = self.source {
            write!(f, "{}: {}", self.context, err)
        } else {
            f.write_str(&self.context)
        }
    }
}

impl From<ServiceError> for ProposalManagerError {
    fn from(err: ServiceError) -> Self {
        ProposalManagerError::Internal(Box::new(err))
    }
}

#[derive(Debug)]
pub enum AdminSharedError {
    SplinterStateError(circuit::SplinterStateError),
    HashError(Sha256Error),
    InvalidMessageFormat(MarshallingError),
    NoPendingChanges,
    ServiceInitializationFailed {
        context: String,
        source: Option<InitializeServiceError>,
    },
    ServiceSendError(ServiceSendError),
    UnknownAction(String),
    ValidationFailed(String),

    /// An error occurred while trying to add an admin service event subscriber to the service.
    UnableToAddSubscriber(String),

    /// An error occured while attempting to verify a payload's signature
    SignerError(signing::error::Error),

    // Returned if a circuit cannot be added to splinter state
    CommitError(String),
    UpdateProposalsError(OpenProposalError),
    // An error occured while trying to negotiated protocol versions
    ServiceProtocolError(String),
}

impl Error for AdminSharedError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            AdminSharedError::SplinterStateError(err) => Some(err),
            AdminSharedError::HashError(err) => Some(err),
            AdminSharedError::InvalidMessageFormat(err) => Some(err),
            AdminSharedError::NoPendingChanges => None,
            AdminSharedError::ServiceInitializationFailed { source, .. } => {
                if let Some(ref err) = source {
                    Some(err)
                } else {
                    None
                }
            }
            AdminSharedError::ServiceSendError(err) => Some(err),
            AdminSharedError::UnknownAction(_) => None,
            AdminSharedError::ValidationFailed(_) => None,
            AdminSharedError::SignerError(_) => None,
            AdminSharedError::CommitError(_) => None,
            AdminSharedError::UpdateProposalsError(err) => Some(err),
            AdminSharedError::UnableToAddSubscriber(_) => None,
            AdminSharedError::ServiceProtocolError(_) => None,
        }
    }
}

impl fmt::Display for AdminSharedError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AdminSharedError::SplinterStateError(err) => write!(f, "{}", err),
            AdminSharedError::HashError(err) => write!(f, "received error while hashing: {}", err),
            AdminSharedError::InvalidMessageFormat(err) => {
                write!(f, "invalid message format: {}", err)
            }
            AdminSharedError::NoPendingChanges => {
                write!(f, "tried to commit without pending changes")
            }
            AdminSharedError::ServiceInitializationFailed { context, source } => {
                if let Some(ref err) = source {
                    write!(f, "{}: {}", context, err)
                } else {
                    f.write_str(&context)
                }
            }
            AdminSharedError::ServiceSendError(err) => {
                write!(f, "failed to send service message: {}", err)
            }
            AdminSharedError::UnknownAction(msg) => {
                write!(f, "received message with unknown action: {}", msg)
            }
            AdminSharedError::ValidationFailed(msg) => write!(f, "validation failed: {}", msg),
            AdminSharedError::SignerError(ref msg) => write!(f, "Signing error: {}", msg),
            AdminSharedError::CommitError(msg) => write!(f, "unable to commit circuit: {}", msg),
            AdminSharedError::UpdateProposalsError(err) => {
                write!(f, "received error while update open proposal: {}", err)
            }
            AdminSharedError::UnableToAddSubscriber(msg) => {
                write!(f, "unable to add admin service event subscriber: {}", msg)
            }
            AdminSharedError::ServiceProtocolError(msg) => write!(
                f,
                "error occured while trying to agree on protocol: {}",
                msg
            ),
        }
    }
}

impl From<ServiceSendError> for AdminSharedError {
    fn from(err: ServiceSendError) -> Self {
        AdminSharedError::ServiceSendError(err)
    }
}

impl From<signing::error::Error> for AdminSharedError {
    fn from(err: signing::error::Error) -> Self {
        AdminSharedError::SignerError(err)
    }
}

impl From<MarshallingError> for AdminSharedError {
    fn from(err: MarshallingError) -> Self {
        AdminSharedError::InvalidMessageFormat(err)
    }
}

impl From<OpenProposalError> for AdminSharedError {
    fn from(err: OpenProposalError) -> Self {
        AdminSharedError::UpdateProposalsError(err)
    }
}

impl From<circuit::SplinterStateError> for AdminSharedError {
    fn from(err: circuit::SplinterStateError) -> Self {
        AdminSharedError::SplinterStateError(err)
    }
}

impl From<AdminKeyVerifierError> for AdminSharedError {
    fn from(err: AdminKeyVerifierError) -> Self {
        AdminSharedError::ValidationFailed(format!("unable to verify key permissions: {}", err))
    }
}

#[derive(Debug)]
pub struct AdminConsensusManagerError(pub Box<dyn Error + Send>);

impl Error for AdminConsensusManagerError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&*self.0)
    }
}

impl std::fmt::Display for AdminConsensusManagerError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "admin consensus manager failed: {}", self.0)
    }
}

#[derive(Debug)]
pub enum AdminError {
    ConsensusFailed(AdminConsensusManagerError),
    MessageTypeUnset,
}

impl Error for AdminError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            AdminError::ConsensusFailed(err) => Some(err),
            AdminError::MessageTypeUnset => None,
        }
    }
}

impl std::fmt::Display for AdminError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            AdminError::ConsensusFailed(err) => write!(f, "admin consensus failed: {}", err),
            AdminError::MessageTypeUnset => write!(f, "received message with unset type"),
        }
    }
}

impl From<AdminConsensusManagerError> for AdminError {
    fn from(err: AdminConsensusManagerError) -> Self {
        AdminError::ConsensusFailed(err)
    }
}

#[derive(Debug)]
pub struct Sha256Error(pub Box<dyn Error + Send>);

impl Error for Sha256Error {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&*self.0)
    }
}

impl std::fmt::Display for Sha256Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "unable to get sha256 hash: {}", self.0)
    }
}

impl From<Sha256Error> for AdminSharedError {
    fn from(err: Sha256Error) -> Self {
        AdminSharedError::HashError(err)
    }
}

#[derive(Debug)]
pub enum MarshallingError {
    UnsetField(String),
    ProtobufError(error::ProtobufError),
}

impl std::error::Error for MarshallingError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            MarshallingError::UnsetField(_) => None,
            MarshallingError::ProtobufError(err) => Some(err),
        }
    }
}

impl std::fmt::Display for MarshallingError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            MarshallingError::UnsetField(_) => write!(f, "Invalid enumerated type"),
            MarshallingError::ProtobufError(err) => write!(f, "Protobuf Error: {}", err),
        }
    }
}

impl From<error::ProtobufError> for MarshallingError {
    fn from(err: error::ProtobufError) -> Self {
        MarshallingError::ProtobufError(err)
    }
}

#[derive(Debug)]
pub enum OpenProposalError {
    WriteError(String),
    InvalidMessageFormat(MarshallingError),
}

impl std::error::Error for OpenProposalError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            OpenProposalError::WriteError(_) => None,
            OpenProposalError::InvalidMessageFormat(err) => Some(err),
        }
    }
}

impl std::fmt::Display for OpenProposalError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            OpenProposalError::WriteError(msg) => {
                write!(f, "Unable to write to persisted storage: {}", msg)
            }
            OpenProposalError::InvalidMessageFormat(err) => {
                write!(f, "Unable to convert circuit proposal: {}", err)
            }
        }
    }
}

impl From<MarshallingError> for OpenProposalError {
    fn from(err: MarshallingError) -> Self {
        OpenProposalError::InvalidMessageFormat(err)
    }
}