Skip to content

Commit

Permalink
Add CodecError common error
Browse files Browse the repository at this point in the history
  • Loading branch information
dlachaume committed Aug 31, 2023
1 parent 3673209 commit 863dab0
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 36 deletions.
40 changes: 33 additions & 7 deletions mithril-common/src/crypto_helper/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(from: T) -> Result<HexEncodedKey, String>
pub fn key_encode_hex<T>(from: T) -> Result<HexEncodedKey, CodecError>
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::<String>())
}

/// Decode key from hex helper
pub fn key_decode_hex<T>(from: HexEncodedKeySlice) -> Result<T, String>
pub fn key_decode_hex<T>(from: HexEncodedKeySlice) -> Result<T, CodecError>
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::<T>()
CodecError::new(
&format!(
"Key decode hex: can not deserialize to type '{}' from binary JSON",
std::any::type_name::<T>()
),
e.into(),
)
})
}
Expand Down
30 changes: 13 additions & 17 deletions mithril-common/src/crypto_helper/types/protocol_key.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -44,14 +44,12 @@ where

/// Create an instance from a JSON hex representation
pub fn from_json_hex(hex_string: &str) -> StdResult<Self> {
let key = key_decode_hex::<T>(hex_string)
.map_err(|e| anyhow!(e))
.with_context(|| {
format!(
"Could not deserialize a ProtocolKey from JSON hex string. Inner key type: {}",
type_name::<T>()
)
})?;
let key = key_decode_hex::<T>(hex_string).with_context(|| {
format!(
"Could not deserialize a ProtocolKey from JSON hex string. Inner key type: {}",
type_name::<T>()
)
})?;

Ok(Self { key })
}
Expand All @@ -63,14 +61,12 @@ where

/// Create a JSON hash representation of the given key
pub fn key_to_json_hex(key: &T) -> StdResult<String> {
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::<T>()
)
})
key_encode_hex(key).with_context(|| {
format!(
"Could not serialize a ProtocolKey to JSON hex key string. Inner key type: {}",
type_name::<T>()
)
})
}
}

Expand Down
4 changes: 3 additions & 1 deletion mithril-common/src/test_utils/fake_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,9 @@ mod test {
encoded_types: &[&str],
) {
assert_decode_all(encoded_types, |encoded_type| {
key_decode_hex::<T>(encoded_type).map(|_| ())
key_decode_hex::<T>(encoded_type)
.map(|_| ())
.map_err(|e| format!("{e:?}"))
})
}

Expand Down
17 changes: 6 additions & 11 deletions mithril-signer/src/single_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -46,14 +46,14 @@ pub trait SingleSigner: Sync + Send {
protocol_message: &ProtocolMessage,
signers_with_stake: &[SignerWithStake],
protocol_initializer: &ProtocolInitializer,
) -> Result<Option<SingleSignatures>, SingleSignerError>;
) -> StdResult<Option<SingleSignatures>>;

/// Compute aggregate verification key from stake distribution
fn compute_aggregate_verification_key(
&self,
signers_with_stake: &[SignerWithStake],
protocol_initializer: &ProtocolInitializer,
) -> Result<Option<String>, SingleSignerError>;
) -> StdResult<Option<String>>;

/// Get party id
fn get_party_id(&self) -> PartyId;
Expand All @@ -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),
Expand Down Expand Up @@ -97,7 +93,7 @@ impl SingleSigner for MithrilSingleSigner {
protocol_message: &ProtocolMessage,
signers_with_stake: &[SignerWithStake],
protocol_initializer: &ProtocolInitializer,
) -> Result<Option<SingleSignatures>, SingleSignerError> {
) -> StdResult<Option<SingleSignatures>> {
let builder = SignerBuilder::new(
signers_with_stake,
&protocol_initializer.get_protocol_parameters().into(),
Expand Down Expand Up @@ -131,7 +127,7 @@ impl SingleSigner for MithrilSingleSigner {
&self,
signers_with_stake: &[SignerWithStake],
protocol_initializer: &ProtocolInitializer,
) -> Result<Option<String>, SingleSignerError> {
) -> StdResult<Option<String>> {
let signer_builder = SignerBuilder::new(
signers_with_stake,
&protocol_initializer.get_protocol_parameters().into(),
Expand All @@ -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))
}
Expand Down

0 comments on commit 863dab0

Please sign in to comment.