Skip to content

Commit ef9fd2a

Browse files
committed
Implemente TryFrom instead of From to avoid panics
1 parent 42d85f5 commit ef9fd2a

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ pub enum ParseError {
4545

4646
#[error("CBOR parse error: `{0}`")]
4747
CborFormat(#[from] serde_cbor::Error),
48+
49+
#[error("Invalid KES format")]
50+
KesFormat,
4851
}
4952

5053
/// Fields for a shelley formatted file (holds for vkeys, skeys or certs)
@@ -121,9 +124,11 @@ impl SerDeShelleyFileFormat for Sum6KesBytes {
121124
}
122125
}
123126

124-
impl<'a> From<&'a mut Sum6KesBytes> for Sum6Kes<'a> {
125-
fn from(value: &'a mut Sum6KesBytes) -> Self {
126-
Self::from_bytes(&mut value.0).expect("Invalid data format")
127+
impl<'a> TryFrom<&'a mut Sum6KesBytes> for Sum6Kes<'a> {
128+
type Error = ParseError;
129+
130+
fn try_from(value: &'a mut Sum6KesBytes) -> Result<Self, Self::Error> {
131+
Self::from_bytes(&mut value.0).map_err(|_| ParseError::KesFormat)
127132
}
128133
}
129134

@@ -154,6 +159,6 @@ mod test {
154159
let mut kes_sk_bytes =
155160
Sum6KesBytes::from_file(&sk_dir).expect("Failure parsing Shelley file format.");
156161

157-
let _kes_sk = Sum6Kes::from(&mut kes_sk_bytes); // Panics if data is incorrect
162+
assert!(Sum6Kes::try_from(&mut kes_sk_bytes).is_ok());
158163
}
159164
}

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,8 @@ impl StmInitializerWrapper {
125125
let stm_initializer = StmInitializer::setup(params, stake, rng);
126126
let kes_signature = if let Some(kes_sk_path) = kes_sk_path {
127127
let mut kes_sk_bytes = Sum6KesBytes::from_file(kes_sk_path)?;
128-
let mut kes_sk = Sum6Kes::from(&mut kes_sk_bytes);
128+
let mut kes_sk = Sum6Kes::try_from(&mut kes_sk_bytes)
129+
.map_err(ProtocolInitializerErrorWrapper::Codec)?;
129130
let kes_sk_period = kes_sk.get_period();
130131
let provided_period = kes_period.unwrap_or_default();
131132
if kes_sk_period > provided_period {

0 commit comments

Comments
 (0)