Skip to content

Commit

Permalink
Use custom error type instead of anomaly::BoxError
Browse files Browse the repository at this point in the history
  • Loading branch information
romac committed Jan 22, 2021
1 parent f337b26 commit 8a5820b
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 18 deletions.
8 changes: 6 additions & 2 deletions tendermint/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,14 @@ impl TryFrom<RawBlock> for Block {
// return Err(Kind::InvalidFirstBlock.context("last_commit is not null on first
// height").into());
//}

let data = value.data.ok_or(Kind::MissingData)?.into();
let evidence = value.evidence.ok_or(Kind::MissingEvidence)?.try_into()?;

Ok(Block {
header,
data: value.data.ok_or(Kind::MissingData)?.try_into()?,
evidence: value.evidence.ok_or(Kind::MissingEvidence)?.try_into()?,
data,
evidence,
last_commit,
})
}
Expand Down
17 changes: 14 additions & 3 deletions tendermint/src/block/commit_sig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,15 @@ impl TryFrom<RawCommitSig> for CommitSig {
return Err(Kind::InvalidValidatorAddress.into());
}
return Ok(CommitSig::BlockIDFlagCommit {
validator_address: value.validator_address.try_into()?,
timestamp: value.timestamp.ok_or(Kind::NoTimestamp)?.try_into()?,
validator_address: value
.validator_address
.try_into()
.map_err(|e| Kind::InvalidValidatorAddress.context(e))?,
timestamp: value
.timestamp
.ok_or(Kind::NoTimestamp)?
.try_into()
.map_err(|e| Kind::InvalidTimestamp.context(e))?,
signature: value.signature.try_into()?,
});
}
Expand All @@ -110,7 +117,11 @@ impl TryFrom<RawCommitSig> for CommitSig {
}
return Ok(CommitSig::BlockIDFlagNil {
validator_address: value.validator_address.try_into()?,
timestamp: value.timestamp.ok_or(Kind::NoTimestamp)?.try_into()?,
timestamp: value
.timestamp
.ok_or(Kind::NoTimestamp)?
.try_into()
.map_err(|e| Kind::InvalidTimestamp.context(e))?,
signature: value.signature.try_into()?,
});
}
Expand Down
2 changes: 1 addition & 1 deletion tendermint/src/block/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ pub struct Version {
impl Protobuf<RawConsensusVersion> for Version {}

impl TryFrom<RawConsensusVersion> for Version {
type Error = anomaly::BoxError;
type Error = Error;

fn try_from(value: RawConsensusVersion) -> Result<Self, Self::Error> {
Ok(Version {
Expand Down
7 changes: 5 additions & 2 deletions tendermint/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub struct TendermintConfig {
impl TendermintConfig {
/// Parse Tendermint `config.toml`
pub fn parse_toml<T: AsRef<str>>(toml_string: T) -> Result<Self, Error> {
Ok(toml::from_str(toml_string.as_ref())?)
Ok(toml::from_str(toml_string.as_ref()).map_err(|e| Kind::InvalidToml.context(e))?)
}

/// Load `config.toml` from a file
Expand All @@ -131,7 +131,10 @@ impl TendermintConfig {
let genesis_json = fs::read_to_string(&path)
.map_err(|e| format_err!(Kind::Parse, "couldn't open {}: {}", path.display(), e))?;

Ok(serde_json::from_str(genesis_json.as_ref())?)
Ok(
serde_json::from_str(genesis_json.as_ref())
.map_err(|e| Kind::InvalidJson.context(e))?,
)
}

/// Load `node_key.json` file from the configured location
Expand Down
2 changes: 1 addition & 1 deletion tendermint/src/config/node_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub struct NodeKey {
impl NodeKey {
/// Parse `node_key.json`
pub fn parse_json<T: AsRef<str>>(json_string: T) -> Result<Self, Error> {
Ok(serde_json::from_str(json_string.as_ref())?)
Ok(serde_json::from_str(json_string.as_ref()).map_err(|e| Kind::InvalidJson.context(e))?)
}

/// Load `node_key.json` from a file
Expand Down
3 changes: 2 additions & 1 deletion tendermint/src/config/priv_validator_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ pub struct PrivValidatorKey {
impl PrivValidatorKey {
/// Parse `priv_validator_key.json`
pub fn parse_json<T: AsRef<str>>(json_string: T) -> Result<Self, Error> {
let result = serde_json::from_str::<Self>(json_string.as_ref())?;
let result = serde_json::from_str::<Self>(json_string.as_ref())
.map_err(|e| Kind::InvalidJson.context(e))?;

// Validate that the parsed key type is usable as a consensus key
TendermintKey::new_consensus_key(result.priv_key.public_key())?;
Expand Down
21 changes: 19 additions & 2 deletions tendermint/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
//! Error types

use anomaly::{BoxError, Context};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::account;
use crate::vote;

/// Error type
pub type Error = BoxError;
pub type Error = anomaly::Error<Kind>;

/// Kinds of errors
#[derive(Clone, Eq, PartialEq, Debug, Error)]
#[derive(Clone, Eq, PartialEq, Debug, Error, Serialize, Deserialize)]
pub enum Kind {
/// Cryptographic operation failed
#[error("cryptographic error")]
Expand Down Expand Up @@ -196,6 +197,22 @@ pub enum Kind {
/// Proposer not found in validator set
#[error("proposer with address '{}' not found in validator set", _0)]
ProposerNotFound(account::Id),

/// Invalid TOML
#[error("invalid TOML")]
InvalidToml,

/// Invalid JSON
#[error("invalid JSON")]
InvalidJson,

/// Invalid date
#[error("invalid date")]
InvalidDate,

/// Invalid hex-encoded string
#[error("invalid hex-encoded string")]
InvalidHex,
}

impl Kind {
Expand Down
10 changes: 8 additions & 2 deletions tendermint/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,11 @@ impl Hash {
match alg {
Algorithm::Sha256 => {
let mut h = [0u8; SHA256_HASH_SIZE];
Hex::upper_case().decode_to_slice(s.as_bytes(), &mut h)?;

Hex::upper_case()
.decode_to_slice(s.as_bytes(), &mut h)
.map_err(|e| Kind::InvalidHex.context(e))?;

Ok(Hash::Sha256(h))
}
}
Expand Down Expand Up @@ -217,7 +221,9 @@ impl AppHash {
return Err(Kind::InvalidAppHashLength.into());
}
let mut h = vec![0; s.len() / 2];
Hex::upper_case().decode_to_slice(s.as_bytes(), &mut h)?;
Hex::upper_case()
.decode_to_slice(s.as_bytes(), &mut h)
.map_err(|e| Kind::InvalidHex.context(e))?;
Ok(AppHash(h))
}
}
Expand Down
10 changes: 7 additions & 3 deletions tendermint/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::error::{Error, Kind};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use std::convert::{Infallible, TryFrom};
use std::convert::TryFrom;
use std::fmt;
use std::ops::{Add, Sub};
use std::str::FromStr;
Expand All @@ -23,7 +23,7 @@ pub struct Time(DateTime<Utc>);
impl Protobuf<Timestamp> for Time {}

impl TryFrom<Timestamp> for Time {
type Error = Infallible;
type Error = Error;

fn try_from(value: Timestamp) -> Result<Self, Self::Error> {
// prost_types::Timestamp has a SystemTime converter but
Expand Down Expand Up @@ -71,7 +71,11 @@ impl Time {

/// Parse [`Time`] from an RFC 3339 date
pub fn parse_from_rfc3339(s: &str) -> Result<Time, Error> {
Ok(Time(DateTime::parse_from_rfc3339(s)?.with_timezone(&Utc)))
Ok(Time(
DateTime::parse_from_rfc3339(s)
.map_err(|e| Kind::InvalidDate.context(e))?
.with_timezone(&Utc),
))
}

/// Return an RFC 3339 and ISO 8601 date and time string with 6 subseconds digits and Z.
Expand Down
2 changes: 1 addition & 1 deletion tendermint/src/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl TryFrom<RawValidator> for Info {
address: value.address.try_into()?,
pub_key: value.pub_key.ok_or(Kind::MissingPublicKey)?.try_into()?,
voting_power: value.voting_power.try_into()?,
proposer_priority: value.proposer_priority.try_into()?,
proposer_priority: value.proposer_priority.into(),
})
}
}
Expand Down

0 comments on commit 8a5820b

Please sign in to comment.