Skip to main content

ave_identity/
error.rs

1//! Error types for cryptographic operations
2//!
3//! This module defines all error types that can occur during cryptographic
4//! operations in the identity crate.
5//!
6//! ## Error Handling Examples
7//!
8//! ### Handling Signature Verification Errors
9//!
10//! ```rust
11//! use ave_identity::keys::{KeyPair, KeyPairAlgorithm};
12//! use ave_identity::error::CryptoError;
13//!
14//! let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
15//! let message = b"Hello, World!";
16//! let signature = keypair.sign(message).unwrap();
17//! let public_key = keypair.public_key();
18//!
19//! // Verify signature
20//! match public_key.verify(message, &signature) {
21//!     Ok(()) => println!("Signature is valid"),
22//!     Err(CryptoError::SignatureVerificationFailed) => {
23//!         eprintln!("Invalid signature or tampered data");
24//!     }
25//!     Err(CryptoError::InvalidSignatureFormat(msg)) => {
26//!         eprintln!("Malformed signature: {}", msg);
27//!     }
28//!     Err(e) => eprintln!("Unexpected error: {}", e),
29//! }
30//! ```
31//!
32//! ### Handling Key Parsing Errors
33//!
34//! ```rust
35//! use ave_identity::keys::PublicKey;
36//! use ave_identity::error::CryptoError;
37//!
38//! let key_str = "EInvalidData";
39//!
40//! match key_str.parse::<PublicKey>() {
41//!     Ok(key) => println!("Successfully parsed public key"),
42//!     Err(CryptoError::Base64DecodeError(msg)) => {
43//!         eprintln!("Invalid encoding: {}", msg);
44//!     }
45//!     Err(CryptoError::UnknownAlgorithm(id)) => {
46//!         eprintln!("Unknown algorithm identifier: {}", id);
47//!     }
48//!     Err(CryptoError::InvalidPublicKey(msg)) => {
49//!         eprintln!("Invalid public key: {}", msg);
50//!     }
51//!     Err(e) => eprintln!("Unexpected error: {}", e),
52//! }
53//! ```
54//!
55//! ### Handling Hash Parsing Errors
56//!
57//! ```rust
58//! use ave_identity::hash::DigestIdentifier;
59//! use ave_identity::error::CryptoError;
60//!
61//! let hash_str = "BInvalidHashData";
62//!
63//! match hash_str.parse::<DigestIdentifier>() {
64//!     Ok(hash) => println!("Successfully parsed hash"),
65//!     Err(CryptoError::Base64DecodeError(msg)) => {
66//!         eprintln!("Invalid encoding: {}", msg);
67//!     }
68//!     Err(CryptoError::UnknownAlgorithm(id)) => {
69//!         eprintln!("Unknown hash algorithm: {}", id);
70//!     }
71//!     Err(CryptoError::InvalidHashFormat(msg)) => {
72//!         eprintln!("Invalid hash format: {}", msg);
73//!     }
74//!     Err(e) => eprintln!("Unexpected error: {}", e),
75//! }
76//! ```
77//!
78//! ### Handling Serialization Errors
79//!
80//! ```rust
81//! use ave_identity::{hash_borsh, BLAKE3_HASHER};
82//! use ave_identity::error::CryptoError;
83//! use borsh::BorshSerialize;
84//!
85//! #[derive(BorshSerialize)]
86//! struct MyData {
87//!     value: u64,
88//! }
89//!
90//! let data = MyData { value: 42 };
91//!
92//! match hash_borsh(&BLAKE3_HASHER, &data) {
93//!     Ok(hash) => println!("Hash: {}", hash),
94//!     Err(CryptoError::SerializationError(msg)) => {
95//!         eprintln!("Failed to serialize data: {}", msg);
96//!     }
97//!     Err(e) => eprintln!("Unexpected error: {}", e),
98//! }
99//! ```
100
101use thiserror::Error;
102
103/// Errors that can occur during cryptographic operations
104#[derive(Error, Debug, Clone)]
105pub enum CryptoError {
106    /// Returned when an unrecognized algorithm identifier is encountered.
107    ///
108    /// This typically occurs when parsing Base64-encoded data with an unknown
109    /// algorithm prefix (e.g., not 'B' for Blake3 or 'E' for Ed25519).
110    #[error("Unknown algorithm identifier: {0}")]
111    UnknownAlgorithm(String),
112
113    /// Returned when hash data is malformed or has incorrect structure.
114    ///
115    /// Common causes:
116    /// - Missing algorithm identifier
117    /// - Incorrect data length for the algorithm
118    /// - Corrupted Base64 encoding
119    #[error("Invalid hash format: {0}")]
120    InvalidHashFormat(String),
121
122    /// Returned when signature data is malformed or has incorrect structure.
123    ///
124    /// Common causes:
125    /// - Missing algorithm identifier
126    /// - Incorrect signature length for the algorithm
127    /// - Corrupted Base64 encoding
128    #[error("Invalid signature format: {0}")]
129    InvalidSignatureFormat(String),
130
131    /// Returned when cryptographic signature verification fails.
132    ///
133    /// This indicates that either:
134    /// - The signature was not created by the claimed signer
135    /// - The signed data has been modified
136    /// - The signature is invalid or corrupted
137    #[error("Signature verification failed")]
138    SignatureVerificationFailed,
139
140    /// Returned when a public key is invalid or malformed.
141    ///
142    /// Common causes:
143    /// - Incorrect key length
144    /// - Invalid key format for the algorithm
145    /// - Corrupted key data
146    #[error("Invalid public key: {0}")]
147    InvalidPublicKey(String),
148
149    /// Returned when a secret key is invalid or malformed.
150    ///
151    /// Common causes:
152    /// - Incorrect key length
153    /// - Invalid key format
154    /// - Decryption failure from secure storage
155    #[error("Invalid secret key: {0}")]
156    InvalidSecretKey(String),
157
158    /// Returned when attempting signing operations on a verification-only instance.
159    ///
160    /// This occurs when a signer is created from a public key only (using
161    /// `from_public_key()`) and then used to sign data. Such instances can
162    /// only verify signatures, not create them.
163    #[error("No secret key available for signing (verification-only instance)")]
164    MissingSecretKey,
165
166    /// Returned when Base64 decoding fails.
167    #[error("Base64 decode error: {0}")]
168    Base64DecodeError(String),
169
170    /// Returned when data has an unexpected length.
171    ///
172    /// This is a validation error that occurs when the actual data size
173    /// doesn't match the expected size for a specific algorithm or operation.
174    #[error("Invalid data length: expected {expected}, got {actual}")]
175    InvalidDataLength { expected: usize, actual: usize },
176
177    /// Returned when Borsh serialization/deserialization fails.
178    #[error("Serialization error: {0}")]
179    SerializationError(String),
180
181    /// Returned when hash computation or verification fails.
182    #[error("Hash computation failed: {0}")]
183    HashError(String),
184
185    /// Returned when a signing operation fails.
186    #[error("Signing failed: {0}")]
187    SigningError(String),
188
189    /// Returned when an algorithm is not supported by this implementation.
190    ///
191    /// This occurs when attempting to use a cryptographic algorithm that
192    /// is recognized but not implemented in the current version.
193    #[error("Unsupported algorithm: {0}")]
194    UnsupportedAlgorithm(String),
195
196    /// Returned when PKCS#8 DER parsing fails.
197    #[error("Invalid PKCS#8 DER format: {0}")]
198    InvalidDerFormat(String),
199}