Skip to main content

signature/
error.rs

1//! Signature error types
2
3use core::fmt::{self, Debug, Display};
4
5#[cfg(feature = "alloc")]
6use alloc::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 `alloc` feature is enabled, it supports an optional [`core::error::Error::source`],
20/// which can be used by things like remote signers (e.g. HSM, KMS) to report I/O or auth errors.
21///
22/// [BB'06]: https://en.wikipedia.org/wiki/Daniel_Bleichenbacher
23#[derive(Default)]
24#[non_exhaustive]
25pub struct Error {
26    /// Source of the error (if applicable).
27    #[cfg(feature = "alloc")]
28    source: Option<Box<dyn core::error::Error + Send + Sync + 'static>>,
29}
30
31impl Error {
32    /// Create a new error with no associated source
33    #[must_use]
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// Create a new error with an associated source.
39    ///
40    /// **NOTE:** The "source" should **NOT** be used to propagate cryptographic
41    /// errors e.g. signature parsing or verification errors. The intended use
42    /// cases are for propagating errors related to external signers, e.g.
43    /// communication/authentication errors with HSMs, KMS, etc.
44    #[cfg(feature = "alloc")]
45    pub fn from_source(
46        source: impl Into<Box<dyn core::error::Error + Send + Sync + 'static>>,
47    ) -> Self {
48        Self {
49            source: Some(source.into()),
50        }
51    }
52}
53
54impl Debug for Error {
55    #[cfg(not(feature = "alloc"))]
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str("signature::Error {}")
58    }
59
60    #[cfg(feature = "alloc")]
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str("signature::Error { source: ")?;
63
64        if let Some(source) = &self.source {
65            write!(f, "Some({source})")?;
66        } else {
67            f.write_str("None")?;
68        }
69
70        f.write_str(" }")
71    }
72}
73
74impl Display for Error {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.write_str("signature error")
77    }
78}
79
80#[cfg(feature = "alloc")]
81impl From<Box<dyn core::error::Error + Send + Sync + 'static>> for Error {
82    fn from(source: Box<dyn core::error::Error + Send + Sync + 'static>) -> Error {
83        Self::from_source(source)
84    }
85}
86
87impl core::error::Error for Error {
88    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
89        #[cfg(not(feature = "alloc"))]
90        {
91            None
92        }
93        #[cfg(feature = "alloc")]
94        #[allow(trivial_casts)]
95        {
96            self.source
97                .as_ref()
98                .map(|source| source.as_ref() as &(dyn core::error::Error + 'static))
99        }
100    }
101}