libp2p_identity/
error.rs

1// Copyright 2019 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Errors during identity key operations.
22
23use std::error::Error;
24use std::fmt;
25
26use crate::KeyType;
27
28/// An error during decoding of key material.
29#[derive(Debug)]
30pub struct DecodingError {
31    msg: String,
32    source: Option<Box<dyn Error + Send + Sync>>,
33}
34
35impl DecodingError {
36    #[allow(dead_code)]
37    pub(crate) fn missing_feature(feature_name: &'static str) -> Self {
38        Self {
39            msg: format!("cargo feature `{feature_name}` is not enabled"),
40            source: None,
41        }
42    }
43
44    #[cfg(any(
45        feature = "ecdsa",
46        feature = "secp256k1",
47        feature = "ed25519",
48        feature = "rsa"
49    ))]
50    pub(crate) fn failed_to_parse<E, S>(what: &'static str, source: S) -> Self
51    where
52        E: Error + Send + Sync + 'static,
53        S: Into<Option<E>>,
54    {
55        Self {
56            msg: format!("failed to parse {what}"),
57            source: match source.into() {
58                None => None,
59                Some(e) => Some(Box::new(e)),
60            },
61        }
62    }
63
64    #[cfg(any(
65        feature = "ecdsa",
66        feature = "secp256k1",
67        feature = "ed25519",
68        feature = "rsa"
69    ))]
70    pub(crate) fn bad_protobuf(
71        what: &'static str,
72        source: impl Error + Send + Sync + 'static,
73    ) -> Self {
74        Self {
75            msg: format!("failed to decode {what} from protobuf"),
76            source: Some(Box::new(source)),
77        }
78    }
79
80    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
81    pub(crate) fn encoding_unsupported(key_type: &'static str) -> Self {
82        Self {
83            msg: format!("encoding {key_type} key to Protobuf is unsupported"),
84            source: None,
85        }
86    }
87}
88
89impl fmt::Display for DecodingError {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "Key decoding error: {}", self.msg)
92    }
93}
94
95impl Error for DecodingError {
96    fn source(&self) -> Option<&(dyn Error + 'static)> {
97        self.source.as_ref().map(|s| &**s as &dyn Error)
98    }
99}
100
101/// An error during signing of a message.
102#[derive(Debug)]
103pub struct SigningError {
104    msg: String,
105    source: Option<Box<dyn Error + Send + Sync>>,
106}
107
108/// An error during encoding of key material.
109impl SigningError {
110    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
111    pub(crate) fn new<S: ToString>(msg: S) -> Self {
112        Self {
113            msg: msg.to_string(),
114            source: None,
115        }
116    }
117
118    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
119    pub(crate) fn source(self, source: impl Error + Send + Sync + 'static) -> Self {
120        Self {
121            source: Some(Box::new(source)),
122            ..self
123        }
124    }
125}
126
127impl fmt::Display for SigningError {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        write!(f, "Key signing error: {}", self.msg)
130    }
131}
132
133impl Error for SigningError {
134    fn source(&self) -> Option<&(dyn Error + 'static)> {
135        self.source.as_ref().map(|s| &**s as &dyn Error)
136    }
137}
138
139/// Error produced when failing to convert [`Keypair`](crate::Keypair) to a more concrete keypair.
140#[derive(Debug)]
141pub struct OtherVariantError {
142    actual: KeyType,
143}
144
145impl OtherVariantError {
146    #[allow(dead_code)] // This is used but the cfg is too complicated to write ..
147    pub(crate) fn new(actual: KeyType) -> OtherVariantError {
148        OtherVariantError { actual }
149    }
150}
151
152impl fmt::Display for OtherVariantError {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.write_str(&format!(
155            "Cannot convert to the given type, the actual key type inside is {}",
156            self.actual
157        ))
158    }
159}
160
161impl Error for OtherVariantError {}