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
use core::convert::Infallible;

/// Crypto error variants
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Error {
    /// Invalid secp256k1 secret key
    InvalidSecretKey,

    /// Invalid secp256k1 public key
    InvalidPublicKey,

    /// Invalid secp256k1 signature message
    InvalidMessage,

    /// Invalid secp256k1 signature
    InvalidSignature,

    /// Coudln't sign the message
    FailedToSign,

    /// The provided key wasn't found
    KeyNotFound,

    /// The keystore isn't available or is corrupted
    KeystoreNotAvailable,

    /// Out of preallocated memory
    NotEnoughMemory,

    /// Invalid mnemonic phrase
    InvalidMnemonic,

    /// Bip32-related error
    Bip32Error,
}

impl From<Error> for Infallible {
    fn from(_: Error) -> Infallible {
        unreachable!()
    }
}

impl From<Infallible> for Error {
    fn from(_: Infallible) -> Error {
        unreachable!()
    }
}

#[cfg(feature = "std")]
mod use_std {
    use super::*;
    use coins_bip39::MnemonicError;
    use std::{
        error,
        fmt,
        io,
    };

    impl From<MnemonicError> for Error {
        fn from(_: MnemonicError) -> Self {
            Self::InvalidMnemonic
        }
    }

    impl From<coins_bip32::Bip32Error> for Error {
        fn from(_: coins_bip32::Bip32Error) -> Self {
            Self::Bip32Error
        }
    }

    impl fmt::Display for Error {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{self:?}")
        }
    }

    impl error::Error for Error {
        fn source(&self) -> Option<&(dyn error::Error + 'static)> {
            None
        }
    }

    impl From<Error> for io::Error {
        fn from(e: Error) -> io::Error {
            io::Error::new(io::ErrorKind::Other, e)
        }
    }
}