Skip to content

Commit ee8bef9

Browse files
authored
Merge pull request #2765 from input-output-hk/curiecrypt/refactor-stm-error-handling
Stm error handling with anyhow
2 parents 57e1490 + 6425660 commit ee8bef9

File tree

33 files changed

+448
-492
lines changed

33 files changed

+448
-492
lines changed

Cargo.lock

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mithril-aggregator/src/multi_signer.rs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -130,17 +130,19 @@ impl MultiSigner for MultiSignerImpl {
130130
self.aggregate_signature_type,
131131
) {
132132
Ok(multi_signature) => Ok(Some(multi_signature)),
133-
Err(ProtocolAggregationError::NotEnoughSignatures(actual, expected)) => {
134-
warn!(
135-
self.logger,
136-
"Could not compute multi-signature: Not enough signatures. Got only {actual} out of {expected}."
137-
);
138-
Ok(None)
139-
}
140-
Err(err) => Err(anyhow!(err).context(format!(
141-
"Multi Signer can not create multi-signature for entity type '{:?}'",
142-
open_message.signed_entity_type
143-
))),
133+
Err(err) => match err.downcast_ref::<ProtocolAggregationError>() {
134+
Some(ProtocolAggregationError::NotEnoughSignatures(actual, expected)) => {
135+
warn!(
136+
self.logger,
137+
"Could not compute multi-signature: Not enough signatures. Got only {actual} out of {expected}."
138+
);
139+
Ok(None)
140+
}
141+
_ => Err(anyhow!(err).context(format!(
142+
"Multi Signer can not create multi-signature for entity type '{:?}'",
143+
open_message.signed_entity_type
144+
))),
145+
},
144146
}
145147
}
146148
}

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

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
66
use std::{collections::HashMap, sync::Arc};
77

8+
use anyhow::anyhow;
89
use blake2::{
910
Blake2b, Digest,
1011
digest::{FixedOutput, consts::U32},
@@ -173,13 +174,8 @@ impl StmInitializerWrapper {
173174
/// * the current total stake (according to the registration service)
174175
/// # Error
175176
/// This function fails if the initializer is not registered.
176-
pub fn new_signer(
177-
self,
178-
closed_reg: ClosedKeyRegistration<D>,
179-
) -> Result<Signer<D>, ProtocolRegistrationErrorWrapper> {
180-
self.stm_initializer
181-
.create_signer(closed_reg)
182-
.map_err(ProtocolRegistrationErrorWrapper::CoreRegister)
177+
pub fn new_signer(self, closed_reg: ClosedKeyRegistration<D>) -> StdResult<Signer<D>> {
178+
self.stm_initializer.create_signer(closed_reg)
183179
}
184180

185181
/// Convert to bytes
@@ -199,7 +195,7 @@ impl StmInitializerWrapper {
199195
/// Convert a slice of bytes to an `StmInitializerWrapper`
200196
/// # Error
201197
/// The function fails if the given string of bytes is not of required size.
202-
pub fn from_bytes(bytes: &[u8]) -> Result<Self, RegisterError> {
198+
pub fn from_bytes(bytes: &[u8]) -> StdResult<Self> {
203199
let stm_initializer =
204200
Initializer::from_bytes(bytes.get(..256).ok_or(RegisterError::SerializationError)?)?;
205201
let bytes = bytes.get(256..).ok_or(RegisterError::SerializationError)?;
@@ -250,7 +246,7 @@ impl KeyRegWrapper {
250246
kes_sig: Option<ProtocolSignerVerificationKeySignature>, // Used for only for testing when SPO pool id is not certified
251247
kes_period: Option<KesPeriod>,
252248
pk: ProtocolSignerVerificationKey,
253-
) -> Result<ProtocolPartyId, ProtocolRegistrationErrorWrapper> {
249+
) -> StdResult<ProtocolPartyId> {
254250
let pool_id_bech32: ProtocolPartyId = if let Some(opcert) = opcert {
255251
let signature = kes_sig.ok_or(ProtocolRegistrationErrorWrapper::KesSignatureMissing)?;
256252
let kes_period =
@@ -264,9 +260,11 @@ impl KeyRegWrapper {
264260
.compute_protocol_party_id()
265261
.map_err(|_| ProtocolRegistrationErrorWrapper::PoolAddressEncoding)?
266262
} else {
267-
return Err(ProtocolRegistrationErrorWrapper::KesSignatureInvalid(
268-
kes_period,
269-
opcert.get_start_kes_period(),
263+
return Err(anyhow!(
264+
ProtocolRegistrationErrorWrapper::KesSignatureInvalid(
265+
kes_period,
266+
opcert.get_start_kes_period(),
267+
)
270268
));
271269
}
272270
} else {
@@ -277,12 +275,12 @@ impl KeyRegWrapper {
277275
};
278276

279277
if let Some(&stake) = self.stake_distribution.get(&pool_id_bech32) {
280-
self.stm_key_reg
281-
.register(stake, pk.into())
282-
.map_err(ProtocolRegistrationErrorWrapper::CoreRegister)?;
278+
self.stm_key_reg.register(stake, pk.into())?;
283279
return Ok(pool_id_bech32);
284280
}
285-
Err(ProtocolRegistrationErrorWrapper::PartyIdNonExisting)
281+
Err(anyhow!(
282+
ProtocolRegistrationErrorWrapper::PartyIdNonExisting
283+
))
286284
}
287285

288286
/// Finalize the key registration.

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ mod binary_mithril_stm {
6161

6262
impl TryFromBytes for SingleSignature {
6363
fn try_from_bytes(bytes: &[u8]) -> StdResult<Self> {
64-
Self::from_bytes::<D>(bytes).map_err(|e| e.into())
64+
Self::from_bytes::<D>(bytes)
6565
}
6666
}
6767

@@ -73,7 +73,7 @@ mod binary_mithril_stm {
7373

7474
impl TryFromBytes for SingleSignatureWithRegisteredParty {
7575
fn try_from_bytes(bytes: &[u8]) -> StdResult<Self> {
76-
Self::from_bytes::<D>(bytes).map_err(|e| e.into())
76+
Self::from_bytes::<D>(bytes)
7777
}
7878
}
7979

@@ -97,7 +97,7 @@ mod binary_mithril_stm {
9797

9898
impl TryFromBytes for VerificationKey {
9999
fn try_from_bytes(bytes: &[u8]) -> StdResult<Self> {
100-
Self::from_bytes(bytes).map_err(|e| e.into())
100+
Self::from_bytes(bytes)
101101
}
102102
}
103103

@@ -109,7 +109,7 @@ mod binary_mithril_stm {
109109

110110
impl TryFromBytes for VerificationKeyProofOfPossession {
111111
fn try_from_bytes(bytes: &[u8]) -> StdResult<Self> {
112-
Self::from_bytes(bytes).map_err(|e| e.into())
112+
Self::from_bytes(bytes)
113113
}
114114
}
115115

@@ -139,7 +139,7 @@ mod binary_mithril_stm {
139139

140140
impl TryFromBytes for Initializer {
141141
fn try_from_bytes(bytes: &[u8]) -> StdResult<Self> {
142-
Self::from_bytes(bytes).map_err(|e| e.into())
142+
Self::from_bytes(bytes)
143143
}
144144
}
145145
}

mithril-common/src/protocol/multi_signer.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@ use mithril_stm::{AggregateSignatureType, Parameters};
33

44
use crate::{
55
StdResult,
6-
crypto_helper::{
7-
ProtocolAggregateVerificationKey, ProtocolAggregationError, ProtocolClerk,
8-
ProtocolMultiSignature,
9-
},
6+
crypto_helper::{ProtocolAggregateVerificationKey, ProtocolClerk, ProtocolMultiSignature},
107
entities::SingleSignature,
118
protocol::ToMessage,
129
};
@@ -31,7 +28,7 @@ impl MultiSigner {
3128
single_signatures: &[SingleSignature],
3229
message: &T,
3330
aggregate_signature_type: AggregateSignatureType,
34-
) -> Result<ProtocolMultiSignature, ProtocolAggregationError> {
31+
) -> StdResult<ProtocolMultiSignature> {
3532
let protocol_signatures: Vec<_> = single_signatures
3633
.iter()
3734
.map(|single_signature| single_signature.to_protocol_signature())
@@ -94,9 +91,10 @@ impl MultiSigner {
9491

9592
#[cfg(test)]
9693
mod test {
97-
use mithril_stm::StmSignatureError;
94+
use mithril_stm::MultiSignatureError;
9895

9996
use crate::{
97+
crypto_helper::ProtocolAggregationError,
10098
entities::{ProtocolMessage, ProtocolMessagePartKey, ProtocolParameters},
10199
protocol::SignerBuilder,
102100
test::{
@@ -129,7 +127,10 @@ mod test {
129127
);
130128

131129
assert!(
132-
matches!(error, ProtocolAggregationError::NotEnoughSignatures(_, _)),
130+
matches!(
131+
error.downcast_ref::<ProtocolAggregationError>(),
132+
Some(ProtocolAggregationError::NotEnoughSignatures(_, _))
133+
),
133134
"Expected ProtocolAggregationError::NotEnoughSignatures, got: {error:?}"
134135
)
135136
}
@@ -194,8 +195,8 @@ mod test {
194195
"Verify single signature should fail if the signer isn't in the registered parties",
195196
);
196197

197-
match error.downcast_ref::<StmSignatureError>() {
198-
Some(StmSignatureError::SignatureInvalid(_)) => (),
198+
match error.downcast_ref::<MultiSignatureError>() {
199+
Some(MultiSignatureError::SignatureInvalid(_)) => (),
199200
_ => panic!("Expected an SignatureInvalid error, got: {error:?}"),
200201
}
201202
}
@@ -220,8 +221,8 @@ mod test {
220221
.verify_single_signature(&ProtocolMessage::default(), &single_signature)
221222
.expect_err("Verify single signature should fail");
222223

223-
match error.downcast_ref::<StmSignatureError>() {
224-
Some(StmSignatureError::SignatureInvalid(_)) => (),
224+
match error.downcast_ref::<MultiSignatureError>() {
225+
Some(MultiSignatureError::SignatureInvalid(_)) => (),
225226
_ => panic!("Expected an SignatureInvalid error, got: {error:?}"),
226227
}
227228
}

mithril-common/src/protocol/signer_builder.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ mod test {
177177
use mithril_stm::RegisterError;
178178

179179
use crate::{
180-
crypto_helper::{KesSignerStandard, ProtocolRegistrationErrorWrapper},
180+
crypto_helper::KesSignerStandard,
181181
test::{builder::MithrilFixtureBuilder, double::fake_data},
182182
};
183183

@@ -220,8 +220,8 @@ mod test {
220220
"We should not be able to construct a signer builder if a signer registration fail",
221221
);
222222

223-
match error.downcast_ref::<ProtocolRegistrationErrorWrapper>() {
224-
Some(ProtocolRegistrationErrorWrapper::CoreRegister(_)) => (),
223+
match error.downcast_ref::<RegisterError>() {
224+
Some(RegisterError::KeyRegistered { .. }) => (),
225225
_ => panic!("Expected an CoreRegister error, got: {error:?}"),
226226
}
227227
}
@@ -264,10 +264,8 @@ mod test {
264264
"We should not be able to construct a single signer from a not registered party",
265265
);
266266

267-
match error.downcast_ref::<ProtocolRegistrationErrorWrapper>() {
268-
Some(ProtocolRegistrationErrorWrapper::CoreRegister(
269-
RegisterError::UnregisteredInitializer,
270-
)) => (),
267+
match error.downcast_ref::<RegisterError>() {
268+
Some(RegisterError::UnregisteredInitializer) => (),
271269
_ => panic!(
272270
"Expected an ProtocolRegistrationErrorWrapper::CoreRegister error, got: {error:?}"
273271
),

mithril-stm/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## 0.6.0 (11-19-2025)
9+
10+
### Changed
11+
12+
- Stm error handling is done with `anyhow`.
13+
814
## 0.5.5 (10-13-2025)
915

1016
### Fixed

mithril-stm/Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "mithril-stm"
3-
version = "0.5.5"
3+
version = "0.6.0"
44
edition = { workspace = true }
55
authors = { workspace = true }
66
homepage = { workspace = true }
@@ -21,6 +21,7 @@ benchmark-internals = [] # For benchmarking multi_sig
2121
future_proof_system = [] # For activating future proof systems
2222

2323
[dependencies]
24+
anyhow = { workspace = true }
2425
blake2 = "0.10.6"
2526
# Enforce blst portable feature for runtime detection of Intel ADX instruction set.
2627
blst = { version = "0.3.16", features = ["portable"] }

mithril-stm/README.md

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -136,16 +136,19 @@ match msig {
136136
println!("Aggregate ok");
137137
assert!(aggr.verify(&msg, &clerk.compute_aggregate_verification_key(), &params).is_ok());
138138
}
139-
Err(AggregationError::NotEnoughSignatures(n, k)) => {
140-
println!("Not enough signatures");
141-
assert!(n < params.k && k == params.k)
142-
}
143-
Err(AggregationError::UsizeConversionInvalid) => {
144-
println!("Invalid usize conversion");
145-
}
146-
Err(AggregationError::UnsupportedProofSystem(aggregate_signature_type)) => {
147-
println!("Unsupported proof system: {:?}", aggregate_signature_type);
148-
}
139+
Err(error) => match error.downcast_ref::<AggregationError>() {
140+
Some(AggregationError::NotEnoughSignatures(n, k)) => {
141+
println!("Not enough signatures");
142+
assert!(n < &params.k && k == &params.k)
143+
},
144+
145+
Some(AggregationError::UnsupportedProofSystem(aggregate_signature_type)) => {
146+
println!("Unsupported proof system: {:?}", aggregate_signature_type);
147+
},
148+
_ => {
149+
println!("Unexpected error during aggregation: {:?}", error);
150+
}
151+
},
149152
}
150153
```
151154

0 commit comments

Comments
 (0)