Skip to main content

kobe_btc/
error.rs

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