Skip to content

Commit

Permalink
Merge pull request #42 from huitseeker/failure_to_anyhow
Browse files Browse the repository at this point in the history
fix: convert failure to anyhow
  • Loading branch information
huitseeker authored Dec 9, 2021
2 parents 7db00b8 + 593a82b commit 20b313d
Show file tree
Hide file tree
Showing 10 changed files with 75 additions and 76 deletions.
2 changes: 1 addition & 1 deletion fastpay/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ publish = false
edition = "2018"

[dependencies]
anyhow = "1.0"
bytes = "0.5.6"
clap = "2.33.3"
env_logger = "0.7.1"
failure = "0.1.8"
futures = "0.3.5"
log = "0.4.11"
net2 = "0.2.34"
Expand Down
4 changes: 2 additions & 2 deletions fastpay/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,15 +202,15 @@ pub struct InitialStateConfig {
}

impl InitialStateConfig {
pub fn read(path: &str) -> Result<Self, failure::Error> {
pub fn read(path: &str) -> Result<Self, anyhow::Error> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut accounts = Vec::new();
for line in reader.lines() {
let line = line?;
let elements = line.split(':').collect::<Vec<_>>();
if elements.len() != 2 {
failure::bail!("expecting two columns separated with ':'")
anyhow::bail!("expecting two columns separated with ':'")
}
let address = decode_address(elements[0])?;
let object_id = ObjectID::from_hex_literal(elements[1])?;
Expand Down
1 change: 1 addition & 0 deletions fastpay_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ publish = false
edition = "2018"

[dependencies]
anyhow = "1.0"
failure = "0.1.8"
futures = "0.3.5"
rand = "0.7.3"
Expand Down
30 changes: 15 additions & 15 deletions fastpay_core/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use crate::downloader::*;
use failure::{bail, ensure};
use anyhow::{bail, ensure};
use fastx_types::{
base_types::*, committee::Committee, error::FastPayError, fp_ensure, messages::*,
};
Expand Down Expand Up @@ -69,21 +69,21 @@ pub trait Client {
object_id: ObjectID,
recipient: FastPayAddress,
user_data: UserData,
) -> AsyncResult<'_, CertifiedOrder, failure::Error>;
) -> AsyncResult<'_, CertifiedOrder, anyhow::Error>;

/// Send money to a Primary account.
fn transfer_to_primary(
&mut self,
object_id: ObjectID,
recipient: PrimaryAddress,
user_data: UserData,
) -> AsyncResult<'_, CertifiedOrder, failure::Error>;
) -> AsyncResult<'_, CertifiedOrder, anyhow::Error>;

/// Receive money from FastPay.
fn receive_from_fastpay(
&mut self,
certificate: CertifiedOrder,
) -> AsyncResult<'_, (), failure::Error>;
) -> AsyncResult<'_, (), anyhow::Error>;

/// Send money to a FastPay account.
/// Do not check balance. (This may block the client)
Expand All @@ -94,12 +94,12 @@ pub trait Client {
recipient: FastPayAddress,
object_id: ObjectID,
user_data: UserData,
) -> AsyncResult<'_, CertifiedOrder, failure::Error>;
) -> AsyncResult<'_, CertifiedOrder, anyhow::Error>;

/// Find how much money we can spend.
/// TODO: Currently, this value only reflects received transfers that were
/// locally processed by `receive_from_fastpay`.
fn get_spendable_amount(&mut self) -> AsyncResult<'_, Amount, failure::Error>;
fn get_spendable_amount(&mut self) -> AsyncResult<'_, Amount, anyhow::Error>;
}

impl<A> ClientState<A> {
Expand Down Expand Up @@ -308,7 +308,7 @@ where
async fn communicate_with_quorum<'a, V, F>(
&'a mut self,
execute: F,
) -> Result<Vec<V>, failure::Error>
) -> Result<Vec<V>, anyhow::Error>
where
F: Fn(AuthorityName, &'a mut A) -> AsyncResult<'a, V, FastPayError> + Clone,
{
Expand Down Expand Up @@ -361,7 +361,7 @@ where
object_id: ObjectID,
known_certificates: Vec<CertifiedOrder>,
action: CommunicateAction,
) -> Result<Vec<CertifiedOrder>, failure::Error> {
) -> Result<Vec<CertifiedOrder>, anyhow::Error> {
let target_sequence_number = match &action {
CommunicateAction::SendOrder(order) => order.sequence_number(),
CommunicateAction::SynchronizeNextSequenceNumber(seq) => *seq,
Expand Down Expand Up @@ -515,7 +515,7 @@ where
object_id: ObjectID,
recipient: Address,
user_data: UserData,
) -> Result<CertifiedOrder, failure::Error> {
) -> Result<CertifiedOrder, anyhow::Error> {
let transfer = Transfer {
object_id,
sender: self.address,
Expand Down Expand Up @@ -566,7 +566,7 @@ where
&mut self,
order: Order,
with_confirmation: bool,
) -> Result<CertifiedOrder, failure::Error> {
) -> Result<CertifiedOrder, anyhow::Error> {
ensure!(
self.pending_transfer == None || self.pending_transfer.as_ref() == Some(&order),
"Client state has a different pending transfer",
Expand Down Expand Up @@ -613,7 +613,7 @@ where
object_id: ObjectID,
recipient: FastPayAddress,
user_data: UserData,
) -> AsyncResult<'_, CertifiedOrder, failure::Error> {
) -> AsyncResult<'_, CertifiedOrder, anyhow::Error> {
Box::pin(self.transfer(object_id, Address::FastPay(recipient), user_data))
}

Expand All @@ -622,11 +622,11 @@ where
object_id: ObjectID,
recipient: PrimaryAddress,
user_data: UserData,
) -> AsyncResult<'_, CertifiedOrder, failure::Error> {
) -> AsyncResult<'_, CertifiedOrder, anyhow::Error> {
Box::pin(self.transfer(object_id, Address::Primary(recipient), user_data))
}

fn get_spendable_amount(&mut self) -> AsyncResult<'_, Amount, failure::Error> {
fn get_spendable_amount(&mut self) -> AsyncResult<'_, Amount, anyhow::Error> {
Box::pin(async move {
if let Some(order) = self.pending_transfer.clone() {
// Finish executing the previous transfer.
Expand All @@ -650,7 +650,7 @@ where
fn receive_from_fastpay(
&mut self,
certificate: CertifiedOrder,
) -> AsyncResult<'_, (), failure::Error> {
) -> AsyncResult<'_, (), anyhow::Error> {
Box::pin(async move {
certificate.check(&self.committee)?;
match &certificate.order.kind {
Expand Down Expand Up @@ -690,7 +690,7 @@ where
recipient: FastPayAddress,
object_id: ObjectID,
user_data: UserData,
) -> AsyncResult<'_, CertifiedOrder, failure::Error> {
) -> AsyncResult<'_, CertifiedOrder, anyhow::Error> {
Box::pin(async move {
let transfer = Transfer {
object_id,
Expand Down
4 changes: 2 additions & 2 deletions fastpay_core/src/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ enum DownloadStatus<V> {

impl<K, V> DownloadHandle<K, V> {
/// Allow to make new download queries and wait for the result.
pub async fn query(&mut self, key: K) -> Result<V, failure::Error> {
pub async fn query(&mut self, key: K) -> Result<V, anyhow::Error> {
let (callback, receiver) = oneshot::channel();
self.0.send(DownloadCommand::Request(key, callback)).await?;
let value = receiver.await?;
Ok(value)
}

/// Shut down the main handler.
pub async fn stop(&mut self) -> Result<(), failure::Error> {
pub async fn stop(&mut self) -> Result<(), anyhow::Error> {
self.0.send(DownloadCommand::Quit).await?;
Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions fastpay_core/src/fastpay_smart_contract.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Facebook, Inc. and its affiliates.
// SPDX-License-Identifier: Apache-2.0

use failure::ensure;
use anyhow::ensure;
use fastx_types::{base_types::*, committee::Committee, messages::*};
use std::collections::BTreeMap;

Expand Down Expand Up @@ -36,21 +36,21 @@ pub trait FastPaySmartContract {
fn handle_funding_transaction(
&mut self,
transaction: FundingTransaction,
) -> Result<(), failure::Error>;
) -> Result<(), anyhow::Error>;

/// Finalize a transfer from FastPay to Primary.
fn handle_redeem_transaction(
&mut self,
transaction: RedeemTransaction,
) -> Result<(), failure::Error>;
) -> Result<(), anyhow::Error>;
}

impl FastPaySmartContract for FastPaySmartContractState {
/// Initiate a transfer to FastPay.
fn handle_funding_transaction(
&mut self,
transaction: FundingTransaction,
) -> Result<(), failure::Error> {
) -> Result<(), anyhow::Error> {
// TODO: Authentication by Primary sender
let amount = transaction.primary_coins;
ensure!(
Expand All @@ -68,7 +68,7 @@ impl FastPaySmartContract for FastPaySmartContractState {
fn handle_redeem_transaction(
&mut self,
transaction: RedeemTransaction,
) -> Result<(), failure::Error> {
) -> Result<(), anyhow::Error> {
transaction.certificate.check(&self.committee)?;
let order = transaction.certificate.order;

Expand Down
2 changes: 2 additions & 0 deletions fastx_types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ publish = false
edition = "2018"

[dependencies]
anyhow = "1.0"
base64 = "0.12.3"
bcs = "0.1.3"
bincode = "1.3.1"
Expand All @@ -18,6 +19,7 @@ ed25519 = { version = "1.0.1"}
ed25519-dalek = { version = "1.0.1", features = ["batch", "serde"] }
serde-name = "0.1.2"
structopt = "0.3.21"
thiserror = "1.0"

move-binary-format = { git = "https://github.com/diem/diem", rev="661a2d1367a64a02027e4ed8f4b18f0a37cfaa17" }
move-core-types = { git = "https://github.com/diem/diem", rev="661a2d1367a64a02027e4ed8f4b18f0a37cfaa17" }
2 changes: 1 addition & 1 deletion fastx_types/src/base_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub fn encode_address(key: &PublicKeyBytes) -> String {
base64::encode(&key.0[..])
}

pub fn decode_address(s: &str) -> Result<PublicKeyBytes, failure::Error> {
pub fn decode_address(s: &str) -> Result<PublicKeyBytes, anyhow::Error> {
let value = base64::decode(s)?;
let mut address = [0u8; dalek::PUBLIC_KEY_LENGTH];
address.copy_from_slice(&value[..dalek::PUBLIC_KEY_LENGTH]);
Expand Down
84 changes: 40 additions & 44 deletions fastx_types/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// Copyright (c) Facebook, Inc. and its affiliates.
// SPDX-License-Identifier: Apache-2.0

use thiserror::Error;

use crate::{base_types::*, messages::*};
use failure::Fail;
use serde::{Deserialize, Serialize};

#[macro_export]
Expand All @@ -21,100 +22,95 @@ macro_rules! fp_ensure {
};
}

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Fail, Hash)]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash)]
/// Custom error type for FastPay.
#[allow(clippy::large_enum_variant)]
pub enum FastPayError {
// Signature verification
#[fail(display = "Signature is not valid: {}", error)]
#[error("Signature is not valid: {}", error)]
InvalidSignature { error: String },
#[fail(display = "Value was not signed by the correct sender")]
#[error("Value was not signed by the correct sender")]
IncorrectSigner,
#[fail(display = "Value was not signed by a known authority")]
#[error("Value was not signed by a known authority")]
UnknownSigner,
// Certificate verification
#[fail(display = "Signatures in a certificate must form a quorum")]
#[error("Signatures in a certificate must form a quorum")]
CertificateRequiresQuorum,
// Transfer processing
#[fail(display = "Transfers must have positive amount")]
#[error("Transfers must have positive amount")]
IncorrectTransferAmount,
#[fail(
display = "The given sequence number must match the next expected sequence number of the account"
#[error(
"The given sequence number must match the next expected sequence number of the account"
)]
UnexpectedSequenceNumber,
#[fail(
display = "The transferred amount must be not exceed the current account balance: {:?}",
current_balance
#[error(
"The transferred amount must be not exceed the current account balance: {current_balance:?}"
)]
InsufficientFunding { current_balance: Balance },
#[fail(
display = "Cannot initiate transfer while a transfer order is still pending confirmation: {:?}",
pending_confirmation
#[error(
"Cannot initiate transfer while a transfer order is still pending confirmation: {pending_confirmation:?}"
)]
PreviousTransferMustBeConfirmedFirst { pending_confirmation: Order },
#[fail(display = "Transfer order was processed but no signature was produced by authority")]
#[error("Transfer order was processed but no signature was produced by authority")]
ErrorWhileProcessingTransferOrder,
#[fail(
display = "An invalid answer was returned by the authority while requesting a certificate"
)]
#[error("An invalid answer was returned by the authority while requesting a certificate")]
ErrorWhileRequestingCertificate,
#[fail(
display = "Cannot confirm a transfer while previous transfer orders are still pending confirmation: {:?}",
current_sequence_number
#[error(
"Cannot confirm a transfer while previous transfer orders are still pending confirmation: {current_sequence_number:?}"
)]
MissingEalierConfirmations {
current_sequence_number: VersionNumber,
},
// Synchronization validation
#[fail(display = "Transaction index must increase by one")]
#[error("Transaction index must increase by one")]
UnexpectedTransactionIndex,
// Account access
#[fail(display = "No certificate for this account and sequence number")]
#[error("No certificate for this account and sequence number")]
CertificateNotfound,
#[fail(display = "Unknown sender's account")]
#[error("Unknown sender's account")]
UnknownSenderAccount,
#[fail(display = "Signatures in a certificate must be from different authorities.")]
#[error("Signatures in a certificate must be from different authorities.")]
CertificateAuthorityReuse,
#[fail(display = "Sequence numbers above the maximal value are not usable for transfers.")]
#[error("Sequence numbers above the maximal value are not usable for transfers.")]
InvalidSequenceNumber,
#[fail(display = "Sequence number overflow.")]
#[error("Sequence number overflow.")]
SequenceOverflow,
#[fail(display = "Sequence number underflow.")]
#[error("Sequence number underflow.")]
SequenceUnderflow,
#[fail(display = "Amount overflow.")]
#[error("Amount overflow.")]
AmountOverflow,
#[fail(display = "Amount underflow.")]
#[error("Amount underflow.")]
AmountUnderflow,
#[fail(display = "Account balance overflow.")]
#[error("Account balance overflow.")]
BalanceOverflow,
#[fail(display = "Account balance underflow.")]
#[error("Account balance underflow.")]
BalanceUnderflow,
#[fail(display = "Wrong shard used.")]
#[error("Wrong shard used.")]
WrongShard,
#[fail(display = "Invalid cross shard update.")]
#[error("Invalid cross shard update.")]
InvalidCrossShardUpdate,
#[fail(display = "Cannot deserialize.")]
#[error("Cannot deserialize.")]
InvalidDecoding,
#[fail(display = "Unexpected message.")]
#[error("Unexpected message.")]
UnexpectedMessage,
#[fail(display = "Network error while querying service: {:?}.", error)]
#[error("Network error while querying service: {:?}.", error)]
ClientIoError { error: String },

// Move related errors
#[fail(display = "Failed to load the Move module, reason: {:?}.", error)]
#[error("Failed to load the Move module, reason: {error:?}.")]
ModuleLoadFailure { error: String },
#[fail(display = "Failed to verify the Move module, reason: {:?}.", error)]
#[error("Failed to verify the Move module, reason: {error:?}.")]
ModuleVerificationFailure { error: String },

// Internal state errors
#[fail(display = "Attempt to re-initialize an order lock.")]
#[error("Attempt to re-initialize an order lock.")]
OrderLockExists,
#[fail(display = "Attempt to set an non-existing order lock.")]
#[error("Attempt to set an non-existing order lock.")]
OrderLockDoesNotExist,
#[fail(display = "Attempt to reset a set order lock to a different value.")]
#[error("Attempt to reset a set order lock to a different value.")]
OrderLockReset,
#[fail(display = "Could not find the referenced object.")]
#[error("Could not find the referenced object.")]
ObjectNotFound,
}

Expand Down
Loading

0 comments on commit 20b313d

Please sign in to comment.