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, fmt};
24
25use crate::KeyType;
26
27/// An error during decoding of key material.
28#[derive(Debug)]
29pub struct DecodingError {
30    msg: String,
31    source: Option<Box<dyn Error + Send + Sync>>,
32}
33
34impl DecodingError {
35    #[allow(dead_code)]
36    pub(crate) fn missing_feature(feature_name: &'static str) -> Self {
37        Self {
38            msg: format!("cargo feature `{feature_name}` is not enabled"),
39            source: None,
40        }
41    }
42
43    #[cfg(any(
44        feature = "ecdsa",
45        feature = "secp256k1",
46        feature = "ed25519",
47        feature = "rsa"
48    ))]
49    pub(crate) fn failed_to_parse<E, S>(what: &'static str, source: S) -> Self
50    where
51        E: Error + Send + Sync + 'static,
52        S: Into<Option<E>>,
53    {
54        Self {
55            msg: format!("failed to parse {what}"),
56            source: match source.into() {
57                None => None,
58                Some(e) => Some(Box::new(e)),
59            },
60        }
61    }
62
63    #[cfg(any(
64        feature = "ecdsa",
65        feature = "secp256k1",
66        feature = "ed25519",
67        feature = "rsa"
68    ))]
69    pub(crate) fn bad_protobuf(
70        what: &'static str,
71        source: impl Error + Send + Sync + 'static,
72    ) -> Self {
73        Self {
74            msg: format!("failed to decode {what} from protobuf"),
75            source: Some(Box::new(source)),
76        }
77    }
78
79    #[cfg(any(
80        feature = "ecdsa",
81        feature = "secp256k1",
82        feature = "ed25519",
83        feature = "rsa"
84    ))]
85    pub(crate) fn unknown_key_type(key_type: i32) -> Self {
86        Self {
87            msg: format!("unknown key type {key_type}"),
88            source: None,
89        }
90    }
91
92    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
93    pub(crate) fn encoding_unsupported(key_type: &'static str) -> Self {
94        Self {
95            msg: format!("encoding {key_type} key to Protobuf is unsupported"),
96            source: None,
97        }
98    }
99}
100
101impl fmt::Display for DecodingError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "Key decoding error: {}", self.msg)
104    }
105}
106
107impl Error for DecodingError {
108    fn source(&self) -> Option<&(dyn Error + 'static)> {
109        self.source.as_ref().map(|s| &**s as &dyn Error)
110    }
111}
112
113/// An error during signing of a message.
114#[derive(Debug)]
115pub struct SigningError {
116    msg: String,
117    source: Option<Box<dyn Error + Send + Sync>>,
118}
119
120/// An error during encoding of key material.
121impl SigningError {
122    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
123    pub(crate) fn new<S: ToString>(msg: S) -> Self {
124        Self {
125            msg: msg.to_string(),
126            source: None,
127        }
128    }
129
130    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
131    pub(crate) fn source(self, source: impl Error + Send + Sync + 'static) -> Self {
132        Self {
133            source: Some(Box::new(source)),
134            ..self
135        }
136    }
137}
138
139impl fmt::Display for SigningError {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        write!(f, "Key signing error: {}", self.msg)
142    }
143}
144
145impl Error for SigningError {
146    fn source(&self) -> Option<&(dyn Error + 'static)> {
147        self.source.as_ref().map(|s| &**s as &dyn Error)
148    }
149}
150
151/// Error produced when failing to convert [`Keypair`](crate::Keypair) to a more concrete keypair.
152#[derive(Debug)]
153pub struct OtherVariantError {
154    actual: KeyType,
155}
156
157impl OtherVariantError {
158    #[allow(dead_code)] // This is used but the cfg is too complicated to write ..
159    pub(crate) fn new(actual: KeyType) -> OtherVariantError {
160        OtherVariantError { actual }
161    }
162}
163
164impl fmt::Display for OtherVariantError {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.write_str(&format!(
167            "Cannot convert to the given type, the actual key type inside is {}",
168            self.actual
169        ))
170    }
171}
172
173impl Error for OtherVariantError {}