Skip to content

Commit 8ad0075

Browse files
committed
replace thiserror with anyhow
1 parent 5b35061 commit 8ad0075

File tree

10 files changed

+142
-142
lines changed

10 files changed

+142
-142
lines changed

rust/catalyst-voting/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ license.workspace = true
1111
workspace = true
1212

1313
[dependencies]
14-
thiserror = "1.0.64"
14+
anyhow = "1.0.89"
1515
rand_core = "0.6.4"
1616
curve25519-dalek = { version = "4.1.3", features = ["digest"] }
1717
blake2b_simd = "1.0.2"

rust/catalyst-voting/src/crypto/babystep_giantstep.rs

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
44
use std::collections::HashMap;
55

6+
use anyhow::{bail, ensure};
7+
68
use crate::crypto::group::{GroupElement, Scalar};
79

810
/// Default balance value.
@@ -22,16 +24,6 @@ pub struct BabyStepGiantStep {
2224
giant_step: GroupElement,
2325
}
2426

25-
#[derive(thiserror::Error, Debug)]
26-
pub enum BabyStepError {
27-
/// Invalid max value or balance
28-
#[error("Maximum value and balance must be greater than zero, provided max value: {0} and balance: {1}.")]
29-
InvalidMaxValueOrBalance(u64, u64),
30-
/// Max value exceeded
31-
#[error("Max log value exceeded. Means that the actual discrete log for the provided group element is higher than the provided `max_log_value`.")]
32-
MaxLogExceeded,
33-
}
34-
3527
impl BabyStepGiantStep {
3628
/// Creates a new setup for the baby-step giant-step algorithm.
3729
///
@@ -47,16 +39,15 @@ impl BabyStepGiantStep {
4739
/// `baby_step_giant_step` function for the same `max_value`.
4840
///
4941
/// # Errors
50-
/// - `BabyStepError`
51-
pub fn new(max_log_value: u64, balance: Option<u64>) -> Result<Self, BabyStepError> {
42+
/// - Maximum value and balance must be greater than zero.
43+
pub fn new(max_log_value: u64, balance: Option<u64>) -> anyhow::Result<Self> {
5244
let balance = balance.unwrap_or(DEFAULT_BALANCE);
5345

54-
if balance == 0 || max_log_value == 0 {
55-
return Err(BabyStepError::InvalidMaxValueOrBalance(
56-
max_log_value,
57-
balance,
58-
));
59-
}
46+
ensure!(
47+
balance != 0 && max_log_value != 0,
48+
"Maximum value and balance must be greater than zero,
49+
provided max value: {max_log_value} and balance: {balance}."
50+
);
6051

6152
#[allow(
6253
clippy::cast_possible_truncation,
@@ -85,18 +76,21 @@ impl BabyStepGiantStep {
8576
/// Solve the discrete log using baby step giant step algorithm.
8677
///
8778
/// # Errors
88-
/// - `BabyStepError`
89-
pub fn discrete_log(&self, mut point: GroupElement) -> Result<u64, BabyStepError> {
79+
/// - Max log value exceeded.
80+
pub fn discrete_log(&self, mut point: GroupElement) -> anyhow::Result<u64> {
9081
for baby_step in 0..=self.baby_step_size {
9182
if let Some(x) = self.table.get(&point) {
9283
let r = baby_step * self.baby_step_size + x;
9384
return Ok(r);
9485
}
9586
point = &point + &self.giant_step;
9687
}
88+
9789
// If we get here, the point is not in the table
9890
// So we exceeded the maximum value of the discrete log
99-
Err(BabyStepError::MaxLogExceeded)
91+
bail!("Max log value exceeded.
92+
Means that the actual discrete log for the provided group element is higher than the provided `max_log_value`."
93+
)
10094
}
10195
}
10296

rust/catalyst-voting/src/crypto/elgamal.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
use std::ops::{Add, Deref, Mul};
55

6+
use anyhow::anyhow;
67
use rand_core::CryptoRngCore;
78

89
use crate::crypto::group::{GroupElement, Scalar};
@@ -77,11 +78,16 @@ impl Ciphertext {
7778
}
7879

7980
/// Attempt to construct a `Scalar` from a compressed value byte representation.
81+
///
82+
/// # Errors
83+
/// - Cannot decode group element field.
8084
#[allow(clippy::unwrap_used)]
81-
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> Option<Self> {
82-
Some(Self(
83-
GroupElement::from_bytes(bytes[0..32].try_into().unwrap())?,
84-
GroupElement::from_bytes(bytes[32..64].try_into().unwrap())?,
85+
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> anyhow::Result<Self> {
86+
Ok(Self(
87+
GroupElement::from_bytes(bytes[0..32].try_into().unwrap())
88+
.map_err(|_| anyhow!("Cannot decode first group element field."))?,
89+
GroupElement::from_bytes(bytes[32..64].try_into().unwrap())
90+
.map_err(|_| anyhow!("Cannot decode second group element field."))?,
8591
))
8692
}
8793
}

rust/catalyst-voting/src/crypto/group/ristretto255.rs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use std::{
77
ops::{Add, Mul, Sub},
88
};
99

10+
use anyhow::anyhow;
1011
use curve25519_dalek::{
1112
constants::{RISTRETTO_BASEPOINT_POINT, RISTRETTO_BASEPOINT_TABLE},
1213
digest::{consts::U64, Digest},
@@ -78,8 +79,14 @@ impl Scalar {
7879
}
7980

8081
/// Attempt to construct a `Scalar` from a canonical byte representation.
81-
pub fn from_bytes(bytes: [u8; Self::BYTES_SIZE]) -> Option<Scalar> {
82-
IScalar::from_canonical_bytes(bytes).map(Scalar).into()
82+
///
83+
/// # Errors
84+
/// - Cannot decode scalar.
85+
pub fn from_bytes(bytes: [u8; Self::BYTES_SIZE]) -> anyhow::Result<Scalar> {
86+
IScalar::from_canonical_bytes(bytes)
87+
.map(Scalar)
88+
.into_option()
89+
.ok_or(anyhow!("Cannot decode scalar."))
8390
}
8491

8592
/// Generate a `Scalar` from a hash digest.
@@ -107,9 +114,14 @@ impl GroupElement {
107114
}
108115

109116
/// Attempt to construct a `Scalar` from a compressed value byte representation.
110-
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> Option<Self> {
111-
Some(GroupElement(
112-
CompressedRistretto::from_slice(bytes).ok()?.decompress()?,
117+
///
118+
/// # Errors
119+
/// - Cannot decode group element.
120+
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> anyhow::Result<Self> {
121+
Ok(GroupElement(
122+
CompressedRistretto::from_slice(bytes)?
123+
.decompress()
124+
.ok_or(anyhow!("Cannot decode group element."))?,
113125
))
114126
}
115127
}

rust/catalyst-voting/src/crypto/zk_unit_vector/mod.rs

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ mod utils;
1313

1414
use std::{io::Read, ops::Mul};
1515

16+
use anyhow::anyhow;
1617
use challenges::{calculate_first_challenge_hash, calculate_second_challenge_hash};
1718
use polynomial::{calculate_polynomial_val, generate_polynomial, Polynomial};
1819
use rand_core::CryptoRngCore;
@@ -35,34 +36,44 @@ pub struct UnitVectorProof(
3536

3637
impl UnitVectorProof {
3738
/// Decode `UnitVectorProof` from bytes.
38-
pub fn from_bytes(mut bytes: &[u8], size: usize) -> Option<Self> {
39+
///
40+
/// # Errors
41+
/// - Cannot decode announcement value.
42+
/// - Cannot decode ciphertext value.
43+
/// - Cannot decode response randomness value.
44+
/// - Cannot decode scalar value.
45+
pub fn from_bytes(mut bytes: &[u8], size: usize) -> anyhow::Result<Self> {
3946
let mut ann_buf = [0u8; Announcement::BYTES_SIZE];
4047
let mut dl_buf = [0u8; Ciphertext::BYTES_SIZE];
4148
let mut rr_buf = [0u8; ResponseRandomness::BYTES_SIZE];
4249

4350
let ann = (0..size)
44-
.map(|_| {
45-
bytes.read_exact(&mut ann_buf).ok()?;
51+
.map(|i| {
52+
bytes.read_exact(&mut ann_buf)?;
4653
Announcement::from_bytes(&ann_buf)
54+
.map_err(|e| anyhow!("Cannot decode announcement at {i}, error: {e}."))
4755
})
48-
.collect::<Option<_>>()?;
56+
.collect::<anyhow::Result<_>>()?;
4957
let dl = (0..size)
50-
.map(|_| {
51-
bytes.read_exact(&mut dl_buf).ok()?;
58+
.map(|i| {
59+
bytes.read_exact(&mut dl_buf)?;
5260
Ciphertext::from_bytes(&dl_buf)
61+
.map_err(|e| anyhow!("Cannot decode ciphertext at {i}, error: {e}."))
5362
})
54-
.collect::<Option<_>>()?;
63+
.collect::<anyhow::Result<_>>()?;
5564
let rr = (0..size)
56-
.map(|_| {
57-
bytes.read_exact(&mut rr_buf).ok()?;
65+
.map(|i| {
66+
bytes.read_exact(&mut rr_buf)?;
5867
ResponseRandomness::from_bytes(&rr_buf)
68+
.map_err(|e| anyhow!("Cannot decode response randomness at {i}, error: {e}."))
5969
})
60-
.collect::<Option<_>>()?;
70+
.collect::<anyhow::Result<_>>()?;
6171

6272
let mut scalar_buf = [0u8; Scalar::BYTES_SIZE];
63-
bytes.read_exact(&mut scalar_buf).ok()?;
64-
let scalar = Scalar::from_bytes(scalar_buf)?;
65-
Some(Self(ann, dl, rr, scalar))
73+
bytes.read_exact(&mut scalar_buf)?;
74+
let scalar =
75+
Scalar::from_bytes(scalar_buf).map_err(|_| anyhow!("Cannot decode scalar field."))?;
76+
Ok(Self(ann, dl, rr, scalar))
6677
}
6778

6879
/// Get a deserialized bytes size

rust/catalyst-voting/src/crypto/zk_unit_vector/randomness_announcements.rs

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use std::ops::Mul;
66

7+
use anyhow::anyhow;
78
use rand_core::CryptoRngCore;
89

910
use crate::crypto::group::{GroupElement, Scalar};
@@ -63,11 +64,14 @@ impl Announcement {
6364
/// # Errors
6465
/// - `AnnouncementDecodingError`
6566
#[allow(clippy::unwrap_used)]
66-
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> Option<Self> {
67-
let i = GroupElement::from_bytes(bytes[0..32].try_into().unwrap())?;
68-
let b = GroupElement::from_bytes(bytes[32..64].try_into().unwrap())?;
69-
let a = GroupElement::from_bytes(bytes[64..96].try_into().unwrap())?;
70-
Some(Self { i, b, a })
67+
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> anyhow::Result<Self> {
68+
let i = GroupElement::from_bytes(bytes[0..32].try_into().unwrap())
69+
.map_err(|_| anyhow!("Cannot decode `i` group element field."))?;
70+
let b = GroupElement::from_bytes(bytes[32..64].try_into().unwrap())
71+
.map_err(|_| anyhow!("Cannot decode `b` group element field."))?;
72+
let a = GroupElement::from_bytes(bytes[64..96].try_into().unwrap())
73+
.map_err(|_| anyhow!("Cannot decode `a` group element field."))?;
74+
Ok(Self { i, b, a })
7175
}
7276

7377
/// Encode `Announcement` tos bytes.
@@ -108,13 +112,16 @@ impl ResponseRandomness {
108112
/// Decode `ResponseRandomness` from bytes.
109113
///
110114
/// # Errors
111-
/// - `ResponseRandomnessDecodingError`
115+
/// - Cannot decode scalar field.
112116
#[allow(clippy::unwrap_used)]
113-
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> Option<Self> {
114-
let z = Scalar::from_bytes(bytes[0..32].try_into().unwrap())?;
115-
let w = Scalar::from_bytes(bytes[32..64].try_into().unwrap())?;
116-
let v = Scalar::from_bytes(bytes[64..96].try_into().unwrap())?;
117-
Some(Self { z, w, v })
117+
pub fn from_bytes(bytes: &[u8; Self::BYTES_SIZE]) -> anyhow::Result<Self> {
118+
let z = Scalar::from_bytes(bytes[0..32].try_into().unwrap())
119+
.map_err(|_| anyhow!("Cannot decode `z` scalar field."))?;
120+
let w = Scalar::from_bytes(bytes[32..64].try_into().unwrap())
121+
.map_err(|_| anyhow!("Cannot decode `w` scalar field."))?;
122+
let v = Scalar::from_bytes(bytes[64..96].try_into().unwrap())
123+
.map_err(|_| anyhow!("Cannot decode `v` scalar field."))?;
124+
Ok(Self { z, w, v })
118125
}
119126

120127
/// Encode `ResponseRandomness` tos bytes.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
//! A catalyst transaction objects implementation
22
33
mod utils;
4-
pub mod v1;
4+
// pub mod v1;

0 commit comments

Comments
 (0)