Skip to main content

alloy_primitives/signature/
error.rs

1use core::{convert::Infallible, fmt};
2
3/// Errors in signature parsing or verification.
4#[derive(Debug)]
5#[cfg_attr(not(feature = "k256"), derive(Copy, Clone))]
6pub enum SignatureError {
7    /// Error converting from bytes.
8    FromBytes(&'static str),
9
10    /// Error converting hex to bytes.
11    FromHex(hex::FromHexError),
12
13    /// Invalid parity.
14    InvalidParity(u64),
15
16    /// k256 error
17    #[cfg(feature = "k256")]
18    K256(k256::ecdsa::Error),
19
20    /// secp256k1 error
21    #[cfg(feature = "secp256k1")]
22    Secp256k1(secp256k1::Error),
23}
24
25#[cfg(feature = "k256")]
26impl From<k256::ecdsa::Error> for SignatureError {
27    fn from(err: k256::ecdsa::Error) -> Self {
28        Self::K256(err)
29    }
30}
31
32#[cfg(feature = "secp256k1")]
33impl From<secp256k1::Error> for SignatureError {
34    fn from(err: secp256k1::Error) -> Self {
35        Self::Secp256k1(err)
36    }
37}
38
39impl From<hex::FromHexError> for SignatureError {
40    fn from(err: hex::FromHexError) -> Self {
41        Self::FromHex(err)
42    }
43}
44
45impl core::error::Error for SignatureError {
46    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
47        match self {
48            #[cfg(all(feature = "k256", feature = "std"))]
49            Self::K256(e) => Some(e),
50            #[cfg(all(feature = "secp256k1", feature = "std"))]
51            Self::Secp256k1(e) => Some(e),
52            #[cfg(any(feature = "std", not(feature = "hex-compat")))]
53            Self::FromHex(e) => Some(e),
54            _ => None,
55        }
56    }
57}
58
59impl fmt::Display for SignatureError {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            #[cfg(feature = "k256")]
63            Self::K256(e) => e.fmt(f),
64            #[cfg(feature = "secp256k1")]
65            Self::Secp256k1(e) => e.fmt(f),
66            Self::FromBytes(e) => f.write_str(e),
67            Self::FromHex(e) => e.fmt(f),
68            Self::InvalidParity(v) => write!(f, "invalid parity: {v}"),
69        }
70    }
71}
72
73impl From<Infallible> for SignatureError {
74    fn from(_: Infallible) -> Self {
75        unreachable!()
76    }
77}