newton-core 0.4.16

newton protocol core sdk
//! Error types for key management operations

use std::fmt;

/// Result type for key operations
pub type KeyResult<T> = Result<T, KeyError>;

/// Errors that can occur during key operations
#[derive(Debug)]
pub enum KeyError {
    /// Failed to create keys directory
    DirectoryCreation(std::io::Error),
    /// Failed to read or write key file
    FileOperation(std::io::Error),
    /// Failed to parse hex-encoded private key
    HexDecode(hex::FromHexError),
    /// Failed to create ECDSA signer from private key
    EcdsaSigner(eyre::Error),
    /// Failed to create BLS keypair from private key
    BlsKeypair(eyre::Error),
    /// Failed to generate random key
    KeyGeneration(String),
    /// Key file not found
    KeyNotFound(String),
    /// Invalid key format
    InvalidKey(String),
}

impl fmt::Display for KeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyError::DirectoryCreation(e) => write!(f, "Failed to create keys directory: {}", e),
            KeyError::FileOperation(e) => write!(f, "File operation failed: {}", e),
            KeyError::HexDecode(e) => write!(f, "Failed to decode hex key: {}", e),
            KeyError::EcdsaSigner(e) => write!(f, "Failed to create ECDSA signer: {}", e),
            KeyError::BlsKeypair(e) => write!(f, "Failed to create BLS keypair: {}", e),
            KeyError::KeyGeneration(msg) => write!(f, "Key generation failed: {}", msg),
            KeyError::KeyNotFound(name) => write!(f, "Key not found: {}", name),
            KeyError::InvalidKey(msg) => write!(f, "Invalid key: {}", msg),
        }
    }
}

impl std::error::Error for KeyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            KeyError::DirectoryCreation(e) => Some(e),
            KeyError::FileOperation(e) => Some(e),
            KeyError::HexDecode(e) => Some(e),
            KeyError::EcdsaSigner(e) => Some(e.as_ref()),
            KeyError::BlsKeypair(e) => Some(e.as_ref()),
            _ => None,
        }
    }
}