litecoinlib/
error.rs

1//! Contains error types and other error handling tools.
2
3use core::fmt;
4
5use bitcoin_internals::write_err;
6
7use crate::consensus::encode;
8pub use crate::parse::ParseIntError;
9
10/// A general error code, other errors should implement conversions to/from this
11/// if appropriate.
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum Error {
15    /// Encoding error
16    Encode(encode::Error),
17    /// The header hash is not below the target
18    BlockBadProofOfWork,
19    /// The `target` field of a block header did not match the expected difficulty
20    BlockBadTarget,
21}
22
23impl fmt::Display for Error {
24    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25        match *self {
26            Error::Encode(ref e) => write_err!(f, "encoding error"; e),
27            Error::BlockBadProofOfWork => f.write_str("block target correct but not attained"),
28            Error::BlockBadTarget => f.write_str("block target incorrect"),
29        }
30    }
31}
32
33#[cfg(feature = "std")]
34#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
35impl std::error::Error for Error {
36    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
37        use self::Error::*;
38
39        match self {
40            Encode(e) => Some(e),
41            BlockBadProofOfWork | BlockBadTarget => None,
42        }
43    }
44}
45
46#[doc(hidden)]
47impl From<encode::Error> for Error {
48    fn from(e: encode::Error) -> Error { Error::Encode(e) }
49}
50
51/// Impls std::error::Error for the specified type with appropriate attributes, possibly returning
52/// source.
53macro_rules! impl_std_error {
54    // No source available
55    ($type:ty) => {
56        #[cfg(feature = "std")]
57        #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
58        impl std::error::Error for $type {}
59    };
60    // Struct with $field as source
61    ($type:ty, $field:ident) => {
62        #[cfg(feature = "std")]
63        #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
64        impl std::error::Error for $type {
65            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.$field) }
66        }
67    };
68}
69pub(crate) use impl_std_error;