signature/
error.rs

1//! Signature error types
2
3use core::fmt::{self, Debug, Display};
4
5#[cfg(feature = "std")]
6use std::boxed::Box;
7
8/// Result type.
9///
10/// A result with the `signature` crate's [`Error`] type.
11pub type Result<T> = core::result::Result<T, Error>;
12
13/// Signature errors.
14///
15/// This type is deliberately opaque as to avoid sidechannel leakage which
16/// could potentially be used recover signing private keys or forge signatures
17/// (e.g. [BB'06]).
18///
19/// When the `std` feature is enabled, it impls [`std::error::Error`] and
20/// supports an optional [`std::error::Error::source`], which can be used by
21/// things like remote signers (e.g. HSM, KMS) to report I/O or auth errors.
22///
23/// [BB'06]: https://en.wikipedia.org/wiki/Daniel_Bleichenbacher
24#[derive(Default)]
25pub struct Error {
26    /// Prevent from being instantiated as `Error {}` when the `std` feature
27    /// is disabled
28    _private: (),
29
30    /// Source of the error (if applicable).
31    #[cfg(feature = "std")]
32    source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
33}
34
35impl Error {
36    /// Create a new error with no associated source
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// Create a new error with an associated source.
42    ///
43    /// **NOTE:** The "source" should **NOT** be used to propagate cryptographic
44    /// errors e.g. signature parsing or verification errors. The intended use
45    /// cases are for propagating errors related to external signers, e.g.
46    /// communication/authentication errors with HSMs, KMS, etc.
47    #[cfg(feature = "std")]
48    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
49    pub fn from_source(
50        source: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
51    ) -> Self {
52        Self {
53            _private: (),
54            source: Some(source.into()),
55        }
56    }
57}
58
59impl Debug for Error {
60    #[cfg(not(feature = "std"))]
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str("signature::Error {}")
63    }
64
65    #[cfg(feature = "std")]
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str("signature::Error { source: ")?;
68
69        if let Some(source) = &self.source {
70            write!(f, "Some({})", source)?;
71        } else {
72            f.write_str("None")?;
73        }
74
75        f.write_str(" }")
76    }
77}
78
79impl Display for Error {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.write_str("signature error")?;
82
83        #[cfg(feature = "std")]
84        {
85            if let Some(source) = &self.source {
86                write!(f, ": {}", source)?;
87            }
88        }
89
90        Ok(())
91    }
92}
93
94#[cfg(feature = "std")]
95impl From<Box<dyn std::error::Error + Send + Sync + 'static>> for Error {
96    fn from(source: Box<dyn std::error::Error + Send + Sync + 'static>) -> Error {
97        Self::from_source(source)
98    }
99}
100
101#[cfg(feature = "std")]
102impl std::error::Error for Error {
103    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
104        self.source
105            .as_ref()
106            .map(|source| source.as_ref() as &(dyn std::error::Error + 'static))
107    }
108}