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
extern crate serde_json;
extern crate log;

use ffi::ErrorCode;

use std::fmt;
use std::cell::RefCell;
use std::ptr;
use std::ffi::CString;

use failure::{Backtrace, Context, Fail};
use libc::c_char;

use utils::ctypes;

pub mod prelude {
    pub use super::{err_msg, IndyCryptoError, IndyCryptoErrorExt, IndyCryptoErrorKind, IndyCryptoResult, set_current_error, get_current_error_c_json};
}

#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum IndyCryptoErrorKind {
    // Common errors
    #[fail(display = "Invalid library state")]
    InvalidState,
    #[fail(display = "Invalid structure")]
    InvalidStructure,
    #[fail(display = "Invalid parameter {}", 0)]
    InvalidParam(u32),
    #[fail(display = "IO error")]
    IOError,
    // CL errors
    #[fail(display = "Proof rejected")]
    ProofRejected,
    #[fail(display = "Revocation accumulator is full")]
    RevocationAccumulatorIsFull,
    #[fail(display = "Invalid revocation id")]
    InvalidRevocationAccumulatorIndex,
    #[fail(display = "Credential revoked")]
    CredentialRevoked,
}

#[derive(Debug)]
pub struct IndyCryptoError {
    inner: Context<IndyCryptoErrorKind>
}

impl Fail for IndyCryptoError {
    fn cause(&self) -> Option<&Fail> {
        self.inner.cause()
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}

impl IndyCryptoError {
    pub fn from_msg<D>(kind: IndyCryptoErrorKind, msg: D) -> IndyCryptoError
        where D: fmt::Display + fmt::Debug + Send + Sync + 'static {
        IndyCryptoError { inner: Context::new(msg).context(kind) }
    }

    pub fn kind(&self) -> IndyCryptoErrorKind {
        *self.inner.get_context()
    }
}

impl fmt::Display for IndyCryptoError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut first = true;

        for cause in Fail::iter_chain(&self.inner) {
            if first {
                first = false;
                writeln!(f, "Error: {}", cause)?;
            } else {
                writeln!(f, "Caused by: {}", cause)?;
            }
        }

        Ok(())
    }
}

pub fn err_msg<D>(kind: IndyCryptoErrorKind, msg: D) -> IndyCryptoError
    where D: fmt::Display + fmt::Debug + Send + Sync + 'static {
    IndyCryptoError::from_msg(kind, msg)
}

impl From<Context<IndyCryptoErrorKind>> for IndyCryptoError {
    fn from(inner: Context<IndyCryptoErrorKind>) -> IndyCryptoError {
        IndyCryptoError { inner }
    }
}

impl From<log::SetLoggerError> for IndyCryptoError {
    fn from(err: log::SetLoggerError) -> IndyCryptoError {
        err.context(IndyCryptoErrorKind::InvalidState).into()
    }
}

impl From<IndyCryptoErrorKind> for ErrorCode {
    fn from(code: IndyCryptoErrorKind) -> ErrorCode {
        match code {
            IndyCryptoErrorKind::InvalidState => ErrorCode::CommonInvalidState,
            IndyCryptoErrorKind::InvalidStructure => ErrorCode::CommonInvalidStructure,
            IndyCryptoErrorKind::InvalidParam(num) =>
                match num {
                    1 => ErrorCode::CommonInvalidParam1,
                    2 => ErrorCode::CommonInvalidParam2,
                    3 => ErrorCode::CommonInvalidParam3,
                    4 => ErrorCode::CommonInvalidParam4,
                    5 => ErrorCode::CommonInvalidParam5,
                    6 => ErrorCode::CommonInvalidParam6,
                    7 => ErrorCode::CommonInvalidParam7,
                    8 => ErrorCode::CommonInvalidParam8,
                    9 => ErrorCode::CommonInvalidParam9,
                    10 => ErrorCode::CommonInvalidParam10,
                    11 => ErrorCode::CommonInvalidParam11,
                    12 => ErrorCode::CommonInvalidParam12,
                    _ => ErrorCode::CommonInvalidState
                },
            IndyCryptoErrorKind::IOError => ErrorCode::CommonIOError,
            IndyCryptoErrorKind::ProofRejected => ErrorCode::AnoncredsProofRejected,
            IndyCryptoErrorKind::RevocationAccumulatorIsFull => ErrorCode::AnoncredsRevocationAccumulatorIsFull,
            IndyCryptoErrorKind::InvalidRevocationAccumulatorIndex => ErrorCode::AnoncredsInvalidRevocationAccumulatorIndex,
            IndyCryptoErrorKind::CredentialRevoked => ErrorCode::AnoncredsCredentialRevoked,
        }
    }
}

impl From<ErrorCode> for IndyCryptoErrorKind {
    fn from(err: ErrorCode) -> IndyCryptoErrorKind {
        match err {
            ErrorCode::CommonInvalidState => IndyCryptoErrorKind::InvalidState,
            ErrorCode::CommonInvalidStructure => IndyCryptoErrorKind::InvalidStructure,
            ErrorCode::CommonInvalidParam1 => IndyCryptoErrorKind::InvalidParam(1),
            ErrorCode::CommonInvalidParam2 => IndyCryptoErrorKind::InvalidParam(2),
            ErrorCode::CommonInvalidParam3 => IndyCryptoErrorKind::InvalidParam(3),
            ErrorCode::CommonInvalidParam4 => IndyCryptoErrorKind::InvalidParam(4),
            ErrorCode::CommonInvalidParam5 => IndyCryptoErrorKind::InvalidParam(5),
            ErrorCode::CommonInvalidParam6 => IndyCryptoErrorKind::InvalidParam(6),
            ErrorCode::CommonInvalidParam7 => IndyCryptoErrorKind::InvalidParam(7),
            ErrorCode::CommonInvalidParam8 => IndyCryptoErrorKind::InvalidParam(8),
            ErrorCode::CommonInvalidParam9 => IndyCryptoErrorKind::InvalidParam(9),
            ErrorCode::CommonInvalidParam10 => IndyCryptoErrorKind::InvalidParam(10),
            ErrorCode::CommonInvalidParam11 => IndyCryptoErrorKind::InvalidParam(11),
            ErrorCode::CommonInvalidParam12 => IndyCryptoErrorKind::InvalidParam(12),
            ErrorCode::CommonIOError => IndyCryptoErrorKind::IOError,
            ErrorCode::AnoncredsProofRejected => IndyCryptoErrorKind::ProofRejected,
            ErrorCode::AnoncredsRevocationAccumulatorIsFull => IndyCryptoErrorKind::RevocationAccumulatorIsFull,
            ErrorCode::AnoncredsInvalidRevocationAccumulatorIndex => IndyCryptoErrorKind::InvalidRevocationAccumulatorIndex,
            ErrorCode::AnoncredsCredentialRevoked => IndyCryptoErrorKind::CredentialRevoked,
            _code => IndyCryptoErrorKind::InvalidState
        }
    }
}

impl From<IndyCryptoError> for ErrorCode {
    fn from(err: IndyCryptoError) -> ErrorCode {
        set_current_error(&err);
        err.kind().into()
    }
}

pub type IndyCryptoResult<T> = Result<T, IndyCryptoError>;

/// Extension methods for `Error`.
pub trait IndyCryptoErrorExt {
    fn to_indy<D>(self, kind: IndyCryptoErrorKind, msg: D) -> IndyCryptoError where D: fmt::Display + Send + Sync + 'static;
}

impl<E> IndyCryptoErrorExt for E where E: Fail
{
    fn to_indy<D>(self, kind: IndyCryptoErrorKind, msg: D) -> IndyCryptoError where D: fmt::Display + Send + Sync + 'static {
        self.context(msg).context(kind).into()
    }
}

thread_local! {
    pub static CURRENT_ERROR_C_JSON: RefCell<Option<CString>> = RefCell::new(None);
}

pub fn set_current_error(err: &IndyCryptoError) {
    CURRENT_ERROR_C_JSON.with(|error| {
        let error_json = json!({
            "message": err.to_string(),
            "backtrace": err.backtrace().map(|bt| bt.to_string())
        }).to_string();
        error.replace(Some(ctypes::string_to_cstring(error_json)));
    });
}

pub fn get_current_error_c_json() -> *const c_char {
    let mut value = ptr::null();

    CURRENT_ERROR_C_JSON.with(|err|
        err.borrow().as_ref().map(|err| value = err.as_ptr())
    );

    value
}