primitives/errors/
mod.rs

1use serde::{Deserialize, Serialize};
2pub use serialization_error::SerializationError;
3pub use verification_error::VerificationError;
4
5use crate::{errors::VerificationError::InvalidMACFor, types::PeerIndex};
6
7pub mod serialization_error;
8pub mod verification_error;
9
10#[derive(thiserror::Error, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11pub enum PrimitiveError {
12    #[error("Verification Error: {0}")]
13    VerificationError(#[from] VerificationError),
14    #[error("Size Error: expected {0} elements, got {1}")]
15    SizeError(usize, usize),
16    #[error("Invalid Parameters: {0}")]
17    InvalidParameters(String),
18    #[error("Serialization error: {0}")]
19    SerializationError(#[from] SerializationError),
20    #[error("Rustls error: {0}")]
21    RustlsError(String),
22    #[error("Zero value sampled for type {0}")]
23    ZeroValueSampled(String),
24    #[error("{0} <| State: {1} |>")]
25    WithState(String, String),
26}
27
28impl From<quinn::rustls::Error> for PrimitiveError {
29    fn from(err: quinn::rustls::Error) -> Self {
30        PrimitiveError::RustlsError(err.to_string())
31    }
32}
33
34impl PrimitiveError {
35    /// Blames another peer for this error.
36    pub(crate) fn blame(self, peer_to_blame: PeerIndex) -> PrimitiveError {
37        if let PrimitiveError::VerificationError(VerificationError::InvalidMACFor(
38            _,
39            expect,
40            receiver,
41        )) = self
42        {
43            PrimitiveError::VerificationError(InvalidMACFor(peer_to_blame, expect, receiver))
44        } else {
45            self
46        }
47    }
48
49    /// Adds a serializable state to the error.
50    /// TODO: Generalise to all errors?
51    pub(crate) fn add_state(self, state: impl Serialize) -> PrimitiveError {
52        PrimitiveError::WithState(self.to_string(), serde_json::to_string(&state).unwrap())
53    }
54}