Skip to content

Commit 817c062

Browse files
committed
Use anyhow in cardano codec crypto helper
1 parent ed098f1 commit 817c062

File tree

2 files changed

+62
-44
lines changed

2 files changed

+62
-44
lines changed

mithril-common/src/crypto_helper/cardano/codec.rs

Lines changed: 48 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
//! The trait `SerDeShelleyFileFormat` can be implemented for any structure that implements
1212
//! `Serialize` and `Deserialize`.
1313
14+
use anyhow::{anyhow, Context};
1415
use hex::FromHex;
1516
use kes_summed_ed25519::kes::Sum6Kes;
1617
use kes_summed_ed25519::traits::KesSk;
@@ -22,6 +23,8 @@ use std::io::Write;
2223
use std::path::Path;
2324
use thiserror::Error;
2425

26+
use crate::StdError;
27+
2528
/// We need to create this struct because the design of Sum6Kes takes
2629
/// a reference to a mutable pointer. It is therefore not possible to
2730
/// implement Ser/Deser using serde.
@@ -33,22 +36,8 @@ pub struct Sum6KesBytes(#[serde(with = "As::<Bytes>")] pub [u8; 612]);
3336

3437
/// Parse error
3538
#[derive(Error, Debug)]
36-
pub enum ParseError {
37-
#[error("io error: `{0}`")]
38-
IO(#[from] std::io::Error),
39-
40-
#[error("JSON parse error: `{0}`")]
41-
JsonFormat(#[from] serde_json::Error),
42-
43-
#[error("CBOR hex codec error: `{0}`")]
44-
CborHex(#[from] hex::FromHexError),
45-
46-
#[error("CBOR parse error: `{0}`")]
47-
CborFormat(#[from] serde_cbor::Error),
48-
49-
#[error("Invalid KES format")]
50-
KesFormat,
51-
}
39+
#[error("Codec parse error: `{0:?}`")]
40+
pub struct CodecParseError(StdError);
5241

5342
/// Fields for a shelley formatted file (holds for vkeys, skeys or certs)
5443
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -71,30 +60,48 @@ pub trait SerDeShelleyFileFormat: Serialize + DeserializeOwned {
7160

7261
/// Deserialize a type `T: Serialize + DeserializeOwned` from file following Cardano
7362
/// Shelley file format.
74-
fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ParseError> {
75-
let data = fs::read_to_string(path)?;
76-
let file: ShelleyFileFormat = serde_json::from_str(&data)?;
77-
let hex_vector = Vec::from_hex(file.cbor_hex)?;
63+
fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, CodecParseError> {
64+
let data = fs::read_to_string(path)
65+
.with_context(|| "SerDeShelleyFileFormat can not read data from file {}")
66+
.map_err(|e| CodecParseError(anyhow!(e)))?;
67+
let file: ShelleyFileFormat = serde_json::from_str(&data)
68+
.with_context(|| "SerDeShelleyFileFormat can not unserialize json data")
69+
.map_err(|e| CodecParseError(anyhow!(e)))?;
70+
let hex_vector = Vec::from_hex(file.cbor_hex)
71+
.with_context(|| "SerDeShelleyFileFormat can not unserialize hex data")
72+
.map_err(|e| CodecParseError(anyhow!(e)))?;
73+
let a: Self = serde_cbor::from_slice(&hex_vector)
74+
.with_context(|| "SerDeShelleyFileFormat can not unserialize cbor data")
75+
.map_err(|e| CodecParseError(anyhow!(e)))?;
7876

79-
let a: Self = serde_cbor::from_slice(&hex_vector)?;
8077
Ok(a)
8178
}
8279

8380
/// Serialize a type `T: Serialize + DeserializeOwned` to file following Cardano
8481
/// Shelley file format.
85-
fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), ParseError> {
86-
let cbor_string = hex::encode(serde_cbor::to_vec(&self)?);
82+
fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), CodecParseError> {
83+
let cbor_string = hex::encode(
84+
serde_cbor::to_vec(&self)
85+
.with_context(|| "SerDeShelleyFileFormat can not serialize data to cbor")
86+
.map_err(|e| CodecParseError(anyhow!(e)))?,
87+
);
8788

8889
let file_format = ShelleyFileFormat {
8990
file_type: Self::TYPE.to_string(),
9091
description: Self::DESCRIPTION.to_string(),
9192
cbor_hex: cbor_string,
9293
};
9394

94-
let mut file = fs::File::create(path)?;
95-
let json_str = serde_json::to_string(&file_format)?;
95+
let mut file = fs::File::create(path)
96+
.with_context(|| "SerDeShelleyFileFormat can not create file")
97+
.map_err(|e| CodecParseError(anyhow!(e)))?;
98+
let json_str = serde_json::to_string(&file_format)
99+
.with_context(|| "SerDeShelleyFileFormat can not serialize data to json")
100+
.map_err(|e| CodecParseError(anyhow!(e)))?;
96101

97-
write!(file, "{json_str}")?;
102+
write!(file, "{json_str}")
103+
.with_context(|| "SerDeShelleyFileFormat can not write data to file")
104+
.map_err(|e| CodecParseError(anyhow!(e)))?;
98105
Ok(())
99106
}
100107
}
@@ -106,10 +113,16 @@ impl SerDeShelleyFileFormat for Sum6KesBytes {
106113
/// Deserialize a Cardano key from file. Cardano KES key Shelley format does not
107114
/// contain the period (it is always zero). Therefore we need to include it in the
108115
/// deserialisation.
109-
fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ParseError> {
110-
let data = fs::read_to_string(path)?;
111-
let file: ShelleyFileFormat = serde_json::from_str(&data)?;
112-
let mut hex_vector = Vec::from_hex(file.cbor_hex)?;
116+
fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, CodecParseError> {
117+
let data = fs::read_to_string(path)
118+
.with_context(|| "Sum6KesBytes can not read data from file")
119+
.map_err(|e| CodecParseError(anyhow!(e)))?;
120+
let file: ShelleyFileFormat = serde_json::from_str(&data)
121+
.with_context(|| "Sum6KesBytes can not unserialize json data")
122+
.map_err(|e| CodecParseError(anyhow!(e)))?;
123+
let mut hex_vector = Vec::from_hex(file.cbor_hex)
124+
.with_context(|| "Sum6KesBytes can not unserialize hex data")
125+
.map_err(|e| CodecParseError(anyhow!(e)))?;
113126

114127
// We check whether the serialisation was performed by the haskell library or the rust library
115128
if (hex_vector[2] & 4u8) == 0 {
@@ -119,16 +132,18 @@ impl SerDeShelleyFileFormat for Sum6KesBytes {
119132
hex_vector.extend_from_slice(&[0u8; 4]);
120133
}
121134

122-
let a: Self = serde_cbor::from_slice(&hex_vector)?;
135+
let a: Self = serde_cbor::from_slice(&hex_vector)
136+
.with_context(|| "Sum6KesBytes can not unserialize cbor data")
137+
.map_err(|e| CodecParseError(anyhow!(e)))?;
123138
Ok(a)
124139
}
125140
}
126141

127142
impl<'a> TryFrom<&'a mut Sum6KesBytes> for Sum6Kes<'a> {
128-
type Error = ParseError;
143+
type Error = CodecParseError;
129144

130145
fn try_from(value: &'a mut Sum6KesBytes) -> Result<Self, Self::Error> {
131-
Self::from_bytes(&mut value.0).map_err(|_| ParseError::KesFormat)
146+
Self::from_bytes(&mut value.0).map_err(|e| CodecParseError(anyhow!(format!("{e:?}"))))
132147
}
133148
}
134149

mithril-signer/src/runtime/runner.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -164,17 +164,20 @@ impl Runner for SignerRunner {
164164
let stake = stake_distribution
165165
.get(&self.services.single_signer.get_party_id())
166166
.ok_or_else(RunnerError::NoStakeForSelf)?;
167-
let (operational_certificate, protocol_operational_certificate) =
168-
match &self.config.operational_certificate_path {
169-
Some(operational_certificate_path) => {
170-
let opcert: OpCert =
171-
OpCert::from_file(operational_certificate_path).map_err(|_| {
172-
RunnerError::FileParse("operational_certificate_path".to_string())
173-
})?;
174-
(Some(opcert.clone()), Some(ProtocolOpCert::new(opcert)))
175-
}
176-
_ => (None, None),
177-
};
167+
let (operational_certificate, protocol_operational_certificate) = match &self
168+
.config
169+
.operational_certificate_path
170+
{
171+
Some(operational_certificate_path) => {
172+
let opcert: OpCert = OpCert::from_file(operational_certificate_path)
173+
.map_err(|_| RunnerError::FileParse("operational_certificate_path".to_string()))
174+
.with_context(|| {
175+
"register_signer_to_aggregator can not decode OpCert from file"
176+
})?;
177+
(Some(opcert.clone()), Some(ProtocolOpCert::new(opcert)))
178+
}
179+
_ => (None, None),
180+
};
178181

179182
let kes_period = match operational_certificate {
180183
Some(operational_certificate) => Some(

0 commit comments

Comments
 (0)