From 863dab030b3a6dd2ba4766826e9f5f580777312c Mon Sep 17 00:00:00 2001 From: Damien LACHAUME / PALO-IT Date: Thu, 31 Aug 2023 10:44:30 +0200 Subject: [PATCH] Add `CodecError` common error --- mithril-common/src/crypto_helper/codec.rs | 40 +++++++++++++++---- .../src/crypto_helper/types/protocol_key.rs | 30 ++++++-------- mithril-common/src/test_utils/fake_keys.rs | 4 +- mithril-signer/src/single_signer.rs | 17 +++----- 4 files changed, 55 insertions(+), 36 deletions(-) diff --git a/mithril-common/src/crypto_helper/codec.rs b/mithril-common/src/crypto_helper/codec.rs index ee149701032..07716eeb280 100644 --- a/mithril-common/src/crypto_helper/codec.rs +++ b/mithril-common/src/crypto_helper/codec.rs @@ -3,29 +3,55 @@ use crate::entities::{HexEncodedKey, HexEncodedKeySlice}; use hex::{FromHex, ToHex}; use serde::de::DeserializeOwned; use serde::Serialize; +use thiserror::Error; + +/// Error raised when the encoding or decoding fails +#[derive(Error, Debug)] +#[error("Codec error: {msg}")] +pub struct CodecError { + msg: String, + #[source] + source: anyhow::Error, +} + +impl CodecError { + /// [CodecError] factory. + pub fn new(msg: &str, source: anyhow::Error) -> Self { + Self { + msg: msg.to_string(), + source, + } + } +} /// Encode key to hex helper -pub fn key_encode_hex(from: T) -> Result +pub fn key_encode_hex(from: T) -> Result where T: Serialize, { Ok(serde_json::to_string(&from) - .map_err(|e| format!("can't convert to hex: {e}"))? + .map_err(|e| CodecError::new("Key encode hex: can not convert to hex", e.into()))? .encode_hex::()) } /// Decode key from hex helper -pub fn key_decode_hex(from: HexEncodedKeySlice) -> Result +pub fn key_decode_hex(from: HexEncodedKeySlice) -> Result where T: DeserializeOwned, { let from_vec = Vec::from_hex(from).map_err(|e| { - format!("Key decode hex: can not turn hexadecimal value into bytes, error: {e}") + CodecError::new( + "Key decode hex: can not turn hexadecimal value into bytes", + e.into(), + ) })?; serde_json::from_slice(from_vec.as_slice()).map_err(|e| { - format!( - "Key decode hex: can not deserialize to type '{}' from binary JSON: error {e}", - std::any::type_name::() + CodecError::new( + &format!( + "Key decode hex: can not deserialize to type '{}' from binary JSON", + std::any::type_name::() + ), + e.into(), ) }) } diff --git a/mithril-common/src/crypto_helper/types/protocol_key.rs b/mithril-common/src/crypto_helper/types/protocol_key.rs index 39a62a0230d..fee547856e0 100644 --- a/mithril-common/src/crypto_helper/types/protocol_key.rs +++ b/mithril-common/src/crypto_helper/types/protocol_key.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, Context}; +use anyhow::Context; use serde::{de::DeserializeOwned, Deserialize, Serialize, Serializer}; use std::any::type_name; use std::ops::Deref; @@ -44,14 +44,12 @@ where /// Create an instance from a JSON hex representation pub fn from_json_hex(hex_string: &str) -> StdResult { - let key = key_decode_hex::(hex_string) - .map_err(|e| anyhow!(e)) - .with_context(|| { - format!( - "Could not deserialize a ProtocolKey from JSON hex string. Inner key type: {}", - type_name::() - ) - })?; + let key = key_decode_hex::(hex_string).with_context(|| { + format!( + "Could not deserialize a ProtocolKey from JSON hex string. Inner key type: {}", + type_name::() + ) + })?; Ok(Self { key }) } @@ -63,14 +61,12 @@ where /// Create a JSON hash representation of the given key pub fn key_to_json_hex(key: &T) -> StdResult { - key_encode_hex(key) - .map_err(|e| anyhow!(e)) - .with_context(|| { - format!( - "Could not serialize a ProtocolKey to JSON hex key string. Inner key type: {}", - type_name::() - ) - }) + key_encode_hex(key).with_context(|| { + format!( + "Could not serialize a ProtocolKey to JSON hex key string. Inner key type: {}", + type_name::() + ) + }) } } diff --git a/mithril-common/src/test_utils/fake_keys.rs b/mithril-common/src/test_utils/fake_keys.rs index 5c51bd975f4..47a5f8a4350 100644 --- a/mithril-common/src/test_utils/fake_keys.rs +++ b/mithril-common/src/test_utils/fake_keys.rs @@ -394,7 +394,9 @@ mod test { encoded_types: &[&str], ) { assert_decode_all(encoded_types, |encoded_type| { - key_decode_hex::(encoded_type).map(|_| ()) + key_decode_hex::(encoded_type) + .map(|_| ()) + .map_err(|e| format!("{e:?}")) }) } diff --git a/mithril-signer/src/single_signer.rs b/mithril-signer/src/single_signer.rs index 24be0c5818c..4edaf658c1d 100644 --- a/mithril-signer/src/single_signer.rs +++ b/mithril-signer/src/single_signer.rs @@ -8,7 +8,7 @@ use mithril_common::entities::{ PartyId, ProtocolMessage, ProtocolParameters, SignerWithStake, SingleSignatures, Stake, }; use mithril_common::protocol::SignerBuilder; -use mithril_common::StdError; +use mithril_common::{StdError, StdResult}; #[cfg(test)] use mockall::automock; @@ -46,14 +46,14 @@ pub trait SingleSigner: Sync + Send { protocol_message: &ProtocolMessage, signers_with_stake: &[SignerWithStake], protocol_initializer: &ProtocolInitializer, - ) -> Result, SingleSignerError>; + ) -> StdResult>; /// Compute aggregate verification key from stake distribution fn compute_aggregate_verification_key( &self, signers_with_stake: &[SignerWithStake], protocol_initializer: &ProtocolInitializer, - ) -> Result, SingleSignerError>; + ) -> StdResult>; /// Get party id fn get_party_id(&self) -> PartyId; @@ -66,10 +66,6 @@ pub enum SingleSignerError { #[error("the protocol signer creation failed: `{0}`")] ProtocolSignerCreationFailure(String), - /// Encoding / Decoding error. - #[error("codec error: '{0:?}'")] - Codec(StdError), - /// Signature Error #[error("Signature Error: {0:?}")] SignatureFailed(StdError), @@ -97,7 +93,7 @@ impl SingleSigner for MithrilSingleSigner { protocol_message: &ProtocolMessage, signers_with_stake: &[SignerWithStake], protocol_initializer: &ProtocolInitializer, - ) -> Result, SingleSignerError> { + ) -> StdResult> { let builder = SignerBuilder::new( signers_with_stake, &protocol_initializer.get_protocol_parameters().into(), @@ -131,7 +127,7 @@ impl SingleSigner for MithrilSingleSigner { &self, signers_with_stake: &[SignerWithStake], protocol_initializer: &ProtocolInitializer, - ) -> Result, SingleSignerError> { + ) -> StdResult> { let signer_builder = SignerBuilder::new( signers_with_stake, &protocol_initializer.get_protocol_parameters().into(), @@ -140,8 +136,7 @@ impl SingleSigner for MithrilSingleSigner { let encoded_avk = signer_builder .compute_aggregate_verification_key() - .to_json_hex() - .map_err(SingleSignerError::Codec)?; + .to_json_hex()?; Ok(Some(encoded_avk)) }