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("Serialization error: {0}")]
13    SerializationError(#[from] SerializationError),
14    #[error("Verification Error: {0}")]
15    VerificationError(#[from] VerificationError),
16    #[error("Size Error: expected {0} elements, got {1}")]
17    SizeError(usize, usize),
18    #[error("Invalid Parameters: {0}")]
19    InvalidParameters(String),
20    #[error("Wrong peer index: {0} ∉ [0, {1}].")]
21    WrongPeerIndex(PeerIndex, PeerIndex),
22    #[error("Rustls error: {0}")]
23    RustlsError(String),
24    #[error("Zero value sampled for type {0}")]
25    ZeroValueSampled(String),
26    #[error("{0} <| State: {1} |>")]
27    WithState(String, String),
28}
29
30impl From<quinn::rustls::Error> for PrimitiveError {
31    fn from(err: quinn::rustls::Error) -> Self {
32        PrimitiveError::RustlsError(err.to_string())
33    }
34}
35
36impl PrimitiveError {
37    /// Blames another peer for this error.
38    pub(crate) fn blame(self, peer_to_blame: PeerIndex) -> PrimitiveError {
39        if let PrimitiveError::VerificationError(VerificationError::InvalidMACFor(
40            _,
41            expect,
42            receiver,
43        )) = self
44        {
45            PrimitiveError::VerificationError(InvalidMACFor(peer_to_blame, expect, receiver))
46        } else {
47            self
48        }
49    }
50
51    /// Adds a serializable state to the error.
52    /// TODO: Generalise to all errors?
53    pub(crate) fn add_state(self, state: impl Serialize) -> PrimitiveError {
54        PrimitiveError::WithState(self.to_string(), serde_json::to_string(&state).unwrap())
55    }
56}