cypheron_core/sig/dilithium/
errors.rs

1// Copyright 2025 Cypheron Labs, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use thiserror::Error;
16
17#[derive(Error, Debug, Clone, PartialEq, Eq)]
18pub enum DilithiumError {
19    #[error("Random number generation failed during key generation")]
20    KeyGenerationRngFailure,
21    #[error("An internal error occurred during key generation")]
22    KeyGenerationInternalError,
23    #[error("Random number generation failed during signing")]
24    SigningRngFailure,
25    #[error("An internal error occurred during signing")]
26    SigningInternalError,
27    #[error("Dilithium C library returned error code: {code}")]
28    CLibraryError { code: i32 },
29    #[error("Invalid input parameters provided to Dilithium function")]
30    InvalidInput,
31    #[error("Memory allocation failed in Dilithium operation")]
32    MemoryAllocationFailed,
33    #[error("Cryptographic operation failed - possible invalid key or signature")]
34    CryptographicFailure,
35}
36
37impl DilithiumError {
38    pub fn from_c_code(code: i32, operation: &str) -> Self {
39        match code {
40            0 => panic!("Should not map success code 0 to error"),
41            -1 => match operation {
42                "keypair" => DilithiumError::KeyGenerationInternalError,
43                "sign" => DilithiumError::SigningInternalError,
44                _ => DilithiumError::CryptographicFailure,
45            },
46            1 => DilithiumError::InvalidInput,
47            2 => DilithiumError::MemoryAllocationFailed,
48            3 => match operation {
49                "keypair" => DilithiumError::KeyGenerationRngFailure,
50                "sign" => DilithiumError::SigningRngFailure,
51                _ => DilithiumError::CryptographicFailure,
52            },
53            _ => DilithiumError::CLibraryError { code },
54        }
55    }
56}