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
// Copyright 2020 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Module specific errors.

use crate::error::SymmError;
use std::{error::Error as StdError, fmt, result};

/// Module specific errors
#[derive(Debug)]
pub enum Error {
	/// secp256k1 enc error
	Secp(secp256k1::Error),
	/// Invalid secret key
	InvalidSecretKey,
	/// Invalid public key
	InvalidPublicKey,
	/// Invalid address
	InvalidAddress,
	/// Invalid EC signature
	InvalidSignature,
	/// Invalid AES message
	InvalidMessage,
	/// IO Error
	Io(std::io::Error),
	/// Symmetric encryption error
	Symm(SymmError),
	/// Custom
	Custom(String),
}

impl StdError for Error {
	fn source(&self) -> Option<&(dyn StdError + 'static)> {
		match self {
			Error::Secp(secp_err) => Some(secp_err),
			Error::Io(err) => Some(err),
			Error::Symm(symm_err) => Some(symm_err),
			_ => None,
		}
	}
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
		match self {
			Error::Secp(err) => write!(f, "secp error: {}", err),
			Error::InvalidSecretKey => write!(f, "invalid secret key"),
			Error::InvalidPublicKey => write!(f, "invalid public key"),
			Error::InvalidAddress => write!(f, "invalid address"),
			Error::InvalidSignature => write!(f, "invalid EC signature"),
			Error::InvalidMessage => write!(f, "invalid AES message"),
			Error::Io(err) => write!(f, "I/O error: {}", err),
			Error::Symm(err) => write!(f, "symmetric encryption error: {}", err),
			Error::Custom(err) => write!(f, "custom crypto error: {}", err),
		}
	}
}

impl Into<String> for Error {
	fn into(self) -> String {
		format!("{}", self)
	}
}

impl From<std::io::Error> for Error {
	fn from(err: std::io::Error) -> Error {
		Error::Io(err)
	}
}

impl From<SymmError> for Error {
	fn from(err: SymmError) -> Error {
		Error::Symm(err)
	}
}

impl From<secp256k1::Error> for Error {
	fn from(e: secp256k1::Error) -> Error {
		match e {
			secp256k1::Error::InvalidMessage => Error::InvalidMessage,
			secp256k1::Error::InvalidPublicKey => Error::InvalidPublicKey,
			secp256k1::Error::InvalidSecretKey => Error::InvalidSecretKey,
			_ => Error::InvalidSignature,
		}
	}
}