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(all(feature = "rsa", not(target_arch = "wasm32")))]
80    pub(crate) fn encoding_unsupported(key_type: &'static str) -> Self {
81        Self {
82            msg: format!("encoding {key_type} key to Protobuf is unsupported"),
83            source: None,
84        }
85    }
86}
87
88impl fmt::Display for DecodingError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        write!(f, "Key decoding error: {}", self.msg)
91    }
92}
93
94impl Error for DecodingError {
95    fn source(&self) -> Option<&(dyn Error + 'static)> {
96        self.source.as_ref().map(|s| &**s as &dyn Error)
97    }
98}
99
100/// An error during signing of a message.
101#[derive(Debug)]
102pub struct SigningError {
103    msg: String,
104    source: Option<Box<dyn Error + Send + Sync>>,
105}
106
107/// An error during encoding of key material.
108impl SigningError {
109    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
110    pub(crate) fn new<S: ToString>(msg: S) -> Self {
111        Self {
112            msg: msg.to_string(),
113            source: None,
114        }
115    }
116
117    #[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
118    pub(crate) fn source(self, source: impl Error + Send + Sync + 'static) -> Self {
119        Self {
120            source: Some(Box::new(source)),
121            ..self
122        }
123    }
124}
125
126impl fmt::Display for SigningError {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(f, "Key signing error: {}", self.msg)
129    }
130}
131
132impl Error for SigningError {
133    fn source(&self) -> Option<&(dyn Error + 'static)> {
134        self.source.as_ref().map(|s| &**s as &dyn Error)
135    }
136}
137
138/// Error produced when failing to convert [`Keypair`](crate::Keypair) to a more concrete keypair.
139#[derive(Debug)]
140pub struct OtherVariantError {
141    actual: KeyType,
142}
143
144impl OtherVariantError {
145    #[allow(dead_code)] // This is used but the cfg is too complicated to write ..
146    pub(crate) fn new(actual: KeyType) -> OtherVariantError {
147        OtherVariantError { actual }
148    }
149}
150
151impl fmt::Display for OtherVariantError {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.write_str(&format!(
154            "Cannot convert to the given type, the actual key type inside is {}",
155            self.actual
156        ))
157    }
158}
159
160impl Error for OtherVariantError {}