Skip to main content

kobe_btc/
error.rs

1//! Error types for Bitcoin wallet operations.
2
3#[cfg(feature = "alloc")]
4use alloc::string::String;
5
6use core::fmt;
7
8/// Errors that can occur during Bitcoin wallet operations.
9#[derive(Debug)]
10pub enum Error {
11    /// Invalid mnemonic phrase.
12    Mnemonic(bip39::Error),
13    /// BIP32 derivation error.
14    Bip32(bitcoin::bip32::Error),
15    /// Invalid word count for mnemonic.
16    InvalidWordCount(usize),
17    /// Invalid derivation path.
18    #[cfg(feature = "alloc")]
19    InvalidDerivationPath(String),
20    /// Invalid WIF (Wallet Import Format) private key.
21    InvalidWif,
22    /// Secp256k1 error.
23    Secp256k1(bitcoin::secp256k1::Error),
24}
25
26impl fmt::Display for Error {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::Mnemonic(e) => write!(f, "mnemonic error: {e}"),
30            Self::Bip32(e) => write!(f, "BIP32 derivation error: {e}"),
31            Self::InvalidWordCount(n) => {
32                write!(f, "invalid word count {n}, must be 12, 15, 18, 21, or 24")
33            }
34            #[cfg(feature = "alloc")]
35            Self::InvalidDerivationPath(p) => write!(f, "invalid derivation path: {p}"),
36            Self::InvalidWif => write!(f, "invalid WIF format"),
37            Self::Secp256k1(e) => write!(f, "secp256k1 error: {e}"),
38        }
39    }
40}
41
42#[cfg(feature = "std")]
43impl std::error::Error for Error {
44    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45        match self {
46            Self::Mnemonic(e) => Some(e),
47            Self::Bip32(e) => Some(e),
48            Self::Secp256k1(e) => Some(e),
49            Self::InvalidWordCount(_) | Self::InvalidWif => None,
50            #[cfg(feature = "alloc")]
51            Self::InvalidDerivationPath(_) => None,
52        }
53    }
54}
55
56impl From<bip39::Error> for Error {
57    fn from(err: bip39::Error) -> Self {
58        Self::Mnemonic(err)
59    }
60}
61
62impl From<bitcoin::bip32::Error> for Error {
63    fn from(err: bitcoin::bip32::Error) -> Self {
64        Self::Bip32(err)
65    }
66}
67
68impl From<bitcoin::secp256k1::Error> for Error {
69    fn from(err: bitcoin::secp256k1::Error) -> Self {
70        Self::Secp256k1(err)
71    }
72}