diff --git a/.dependabot/config.yml b/.dependabot/config.yml index bbc5dfa373..5e87736a23 100644 --- a/.dependabot/config.yml +++ b/.dependabot/config.yml @@ -43,10 +43,6 @@ update_configs: update_schedule: "live" target_branch: "iroha2-dev" directory: "iroha_error" - - package_manager: "rust:cargo" - update_schedule: "live" - target_branch: "iroha2-dev" - directory: "iroha_error/iroha_error_macro" - package_manager: "rust:cargo" update_schedule: "live" target_branch: "iroha2-dev" diff --git a/Cargo.lock b/Cargo.lock index 5a82b088ee..61aa737567 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -809,6 +809,16 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" +[[package]] +name = "eyre" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "221239d1d5ea86bf5d6f91c9d6bc3646ffe471b08ff9b0f91c44f115ac969d2b" +dependencies = [ + "indenter", + "once_cell", +] + [[package]] name = "failure" version = "0.1.8" @@ -1305,6 +1315,12 @@ dependencies = [ "syn", ] +[[package]] +name = "indenter" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683" + [[package]] name = "indexmap" version = "1.7.0" @@ -1339,6 +1355,7 @@ dependencies = [ "chrono", "criterion", "dashmap", + "eyre", "futures", "hex", "hex-literal", @@ -1347,7 +1364,6 @@ dependencies = [ "iroha_crypto", "iroha_data_model", "iroha_derive", - "iroha_error", "iroha_futures", "iroha_logger", "iroha_macro", @@ -1362,6 +1378,7 @@ dependencies = [ "serde_json", "structopt", "tempfile", + "thiserror", "tokio", "tokio-stream", "tracing", @@ -1377,11 +1394,12 @@ dependencies = [ "actor_derive", "async-trait", "dashmap", + "eyre", "futures", - "iroha_error", "iroha_logger", "once_cell", "petgraph", + "thiserror", "tokio", "trybuild", ] @@ -1390,6 +1408,7 @@ dependencies = [ name = "iroha_cli" version = "0.1.0" dependencies = [ + "eyre", "iroha", "iroha_error", "iroha_logger", @@ -1406,6 +1425,7 @@ dependencies = [ "async-trait", "attohttpc", "criterion", + "eyre", "futures", "http", "iroha", @@ -1436,6 +1456,7 @@ name = "iroha_client_cli" version = "0.1.0" dependencies = [ "dialoguer", + "eyre", "futures", "iroha_client", "iroha_crypto", @@ -1470,9 +1491,9 @@ dependencies = [ name = "iroha_crypto" version = "0.1.0" dependencies = [ + "eyre", "hex", "hex-literal", - "iroha_error", "iroha_schema", "openssl-sys", "parity-scale-codec", @@ -1486,6 +1507,7 @@ name = "iroha_crypto_cli" version = "0.1.0" dependencies = [ "clap", + "eyre", "hex", "iroha_crypto", "iroha_error", @@ -1498,16 +1520,17 @@ version = "0.1.0" dependencies = [ "chrono", "dashmap", + "eyre", "fixnum", "iroha_crypto", "iroha_derive", - "iroha_error", "iroha_macro", "iroha_schema", "iroha_version", "parity-scale-codec", "serde", "serde_json", + "thiserror", "ursa", "warp", ] @@ -1530,9 +1553,9 @@ dependencies = [ name = "iroha_docs" version = "0.1.0" dependencies = [ + "eyre", "iroha", "iroha_config", - "iroha_error", "serde_json", ] @@ -1554,21 +1577,9 @@ name = "iroha_error" version = "0.1.0" dependencies = [ "backtrace", - "iroha_error_macro", "owo-colors", ] -[[package]] -name = "iroha_error_macro" -version = "0.1.0" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn", - "trybuild", -] - [[package]] name = "iroha_futures" version = "0.1.0" @@ -1587,8 +1598,8 @@ name = "iroha_logger" version = "0.1.0" dependencies = [ "chrono", + "eyre", "iroha_config", - "iroha_error", "serde", "serde_json", "tokio", @@ -1602,7 +1613,7 @@ dependencies = [ name = "iroha_macro" version = "0.1.0" dependencies = [ - "iroha_error", + "eyre", "parity-scale-codec", ] @@ -1613,17 +1624,18 @@ dependencies = [ "aead", "async-stream", "async-trait", + "eyre", "futures", "iroha_actor", "iroha_crypto", "iroha_data_model", "iroha_derive", - "iroha_error", "iroha_logger", "iroha_macro", "parity-scale-codec", "rand 0.7.3", "serde", + "thiserror", "tokio", "unique_port", "ursa", @@ -1655,9 +1667,9 @@ dependencies = [ name = "iroha_schema_bin" version = "0.1.0" dependencies = [ + "eyre", "iroha", "iroha_data_model", - "iroha_error", "iroha_schema", "serde_json", ] @@ -1695,14 +1707,15 @@ dependencies = [ name = "iroha_version" version = "0.1.0" dependencies = [ + "eyre", "iroha_derive", - "iroha_error", "iroha_macro", "iroha_schema", "iroha_version_derive", "parity-scale-codec", "serde", "serde_json", + "thiserror", "warp", ] @@ -2879,6 +2892,7 @@ name = "test_network" version = "0.1.0" dependencies = [ "async-trait", + "eyre", "futures", "iroha", "iroha_actor", diff --git a/Cargo.toml b/Cargo.toml index fa18a00234..9f3f5c8b22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,6 @@ members = [ "iroha_data_model", "iroha_dsl", "iroha_error", - "iroha_error/iroha_error_macro", "iroha_macro", "iroha_macro/iroha_derive", "iroha_p2p", diff --git a/iroha/Cargo.toml b/iroha/Cargo.toml index d5976b3d41..6e866d297a 100644 --- a/iroha/Cargo.toml +++ b/iroha/Cargo.toml @@ -29,7 +29,6 @@ maintenance = { status = "actively-developed" } iroha_data_model = { path = "../iroha_data_model", features = ["warp"] } iroha_derive = { version = "=0.1.0", path = "../iroha_macro/iroha_derive" } iroha_macro = { version = "=0.1.0", path = "../iroha_macro" } -iroha_error = { version = "=0.1.0", path = "../iroha_error" } iroha_p2p = { version = "=0.1.0", path = "../iroha_p2p" } iroha_logger = { version = "=0.1.0", path = "../iroha_logger"} iroha_crypto = { version = "=0.1.0", path = "../iroha_crypto" } @@ -43,6 +42,7 @@ iroha_schema = { path = "../iroha_schema"} async-trait = "0.1" chrono = "0.4" dashmap = { version = "4.0" } +eyre = "0.6.5" futures = { version = "0.3.4" } parity-scale-codec = { version = "2", features = ["derive"] } rand = "0.7.3" @@ -54,6 +54,7 @@ tracing = "0.1" warp = "0.3" ursa = "=0.3.6" structopt = { version = "0.3", optional = true } +thiserror = "1.0.28" [dev-dependencies] hex-literal = "0.2.1" diff --git a/iroha/docs/Cargo.toml b/iroha/docs/Cargo.toml index 36cd0cb095..a52926a7cb 100644 --- a/iroha/docs/Cargo.toml +++ b/iroha/docs/Cargo.toml @@ -8,6 +8,6 @@ edition = "2018" [dependencies] iroha = { path = "../../iroha" } -iroha_error = { path = "../../iroha_error" } iroha_config = { path = "../../iroha_config" } +eyre = "0.6.5" serde_json = "1" \ No newline at end of file diff --git a/iroha/docs/src/main.rs b/iroha/docs/src/main.rs index 2a8cdd5b53..5033393c0b 100644 --- a/iroha/docs/src/main.rs +++ b/iroha/docs/src/main.rs @@ -7,12 +7,12 @@ use std::{ io::{stdout, BufWriter, Result, Write}, }; +use eyre::Context; use iroha::config::Configuration; use iroha_config::Configurable; -use iroha_error::WrapErr; use serde_json::{Map, Value}; -fn main() -> iroha_error::Result<()> { +fn main() -> eyre::Result<()> { Configuration::get_markdown(&mut BufWriter::new(stdout())) .wrap_err("Failed to generate documentation") } diff --git a/iroha/src/block.rs b/iroha/src/block.rs index b85526a91b..559acfd5a4 100644 --- a/iroha/src/block.rs +++ b/iroha/src/block.rs @@ -9,10 +9,10 @@ use std::{iter, time::SystemTime}; use dashmap::{iter::Iter as MapIter, mapref::one::Ref as MapRef, DashMap}; +use eyre::Result; use iroha_crypto::{KeyPair, Signatures}; use iroha_data_model::{events::prelude::*, transaction::prelude::*}; use iroha_derive::Io; -use iroha_error::Result; use iroha_version::{declare_versioned_with_scale, version_with_scale}; use parity_scale_codec::{Decode, Encode}; diff --git a/iroha/src/config.rs b/iroha/src/config.rs index dc45242e6f..9a98df5e30 100644 --- a/iroha/src/config.rs +++ b/iroha/src/config.rs @@ -1,10 +1,10 @@ //! This module contains [`Configuration`] structure and related implementation. use std::{fmt::Debug, fs::File, io::BufReader, path::Path}; +use eyre::{Result, WrapErr}; use iroha_config::derive::Configurable; use iroha_crypto::{KeyPair, PrivateKey, PublicKey}; use iroha_data_model::prelude::*; -use iroha_error::{Result, WrapErr}; use iroha_logger::config::LoggerConfiguration; use serde::{Deserialize, Serialize}; diff --git a/iroha/src/event.rs b/iroha/src/event.rs index 912cab3be7..99ccf3e664 100644 --- a/iroha/src/event.rs +++ b/iroha/src/event.rs @@ -4,9 +4,9 @@ use std::{convert::TryInto, fmt::Debug, time::Duration}; +use eyre::{eyre, Result, WrapErr}; use futures::{SinkExt, StreamExt}; use iroha_data_model::events::{prelude::*, SubscriptionRequest}; -use iroha_error::{error, Result, WrapErr}; use iroha_version::prelude::*; use tokio::{sync::broadcast, time}; use warp::ws::{self, WebSocket}; @@ -39,11 +39,11 @@ impl Consumer { let message = time::timeout(TIMEOUT, stream.next()) .await .wrap_err("Read message timeout")? - .ok_or_else(|| error!("Failed to read message: no message"))? + .ok_or_else(|| eyre!("Failed to read message: no message"))? .wrap_err("Web Socket failure")?; if !message.is_binary() { - return Err(error!("Unexpected message type")); + return Err(eyre!("Unexpected message type")); } let SubscriptionRequest(filter): SubscriptionRequest = VersionedEventSocketMessage::decode_versioned(message.as_bytes())? @@ -85,11 +85,11 @@ impl Consumer { let message = time::timeout(TIMEOUT, self.stream.next()) .await .wrap_err("Failed to read receipt")? - .ok_or_else(|| error!("Failed to read receipt: no receipt"))? + .ok_or_else(|| eyre!("Failed to read receipt: no receipt"))? .wrap_err("Web Socket failure")?; if !message.is_binary() { - return Err(error!("Unexpected message type")); + return Err(eyre!("Unexpected message type")); } if let EventSocketMessage::EventReceived = @@ -98,7 +98,7 @@ impl Consumer { self.stream.flush().await?; Ok(()) } else { - Err(error!("Expected `EventReceived`.")) + Err(eyre!("Expected `EventReceived`.")) } } } diff --git a/iroha/src/genesis.rs b/iroha/src/genesis.rs index 6edf83bb6f..27e5dc1340 100644 --- a/iroha/src/genesis.rs +++ b/iroha/src/genesis.rs @@ -3,10 +3,10 @@ use std::{collections::HashSet, fmt::Debug, fs::File, io::BufReader, ops::Deref, path::Path}; +use eyre::{eyre, Result, WrapErr}; use iroha_actor::Addr; use iroha_crypto::KeyPair; use iroha_data_model::{account::Account, isi::Instruction, prelude::*}; -use iroha_error::{error, Result, WrapErr}; use iroha_schema::prelude::*; use serde::Deserialize; use tokio::{time, time::Duration}; @@ -100,7 +100,7 @@ async fn try_get_online_topology( check_peers_status(this_peer_id, network_topology, network).await; let set_a_len = network_topology.min_votes_for_commit() as usize; if online_peers.len() < set_a_len { - return Err(error!("Not enough online peers for consensus.")); + return Err(eyre!("Not enough online peers for consensus.")); } let genesis_topology = if network_topology.sorted_peers().len() == 1 { network_topology.clone() @@ -167,11 +167,11 @@ impl GenesisNetworkTrait for GenesisNetwork { public_key: genesis_config .genesis_account_public_key .clone() - .ok_or_else(|| error!("Genesis account public key is empty."))?, + .ok_or_else(|| eyre!("Genesis account public key is empty."))?, private_key: genesis_config .genesis_account_private_key .clone() - .ok_or_else(|| error!("Genesis account private key is empty."))?, + .ok_or_else(|| eyre!("Genesis account private key is empty."))?, }; Ok(Some(GenesisNetwork { transactions: raw_block @@ -206,7 +206,7 @@ impl GenesisNetworkTrait for GenesisNetwork { iroha_logger::info!("Retrying to connect in {} ms.", reconnect_in_ms); time::sleep(Duration::from_millis(reconnect_in_ms)).await; } - Err(error!("Waiting for peers failed.")) + Err(eyre!("Waiting for peers failed.")) } } diff --git a/iroha/src/kura.rs b/iroha/src/kura.rs index ba04e51cfa..45168e9690 100644 --- a/iroha/src/kura.rs +++ b/iroha/src/kura.rs @@ -7,8 +7,8 @@ use std::{ sync::Arc, }; +use eyre::{Result, WrapErr}; use iroha_actor::{broker::*, prelude::*}; -use iroha_error::{Result, WrapErr}; use iroha_version::scale::{DecodeVersioned, EncodeVersioned}; use serde::{Deserialize, Serialize}; use tokio::{ @@ -256,8 +256,8 @@ impl BlockStore { pub mod config { use std::path::Path; + use eyre::{eyre, Result}; use iroha_config::derive::Configurable; - use iroha_error::{error, Result}; use serde::{Deserialize, Serialize}; use super::Mode; @@ -293,7 +293,7 @@ pub mod config { pub fn kura_block_store_path(&mut self, path: &Path) -> Result<()> { self.kura_block_store_path = path .to_str() - .ok_or_else(|| error!("Failed to yield slice from path"))? + .ok_or_else(|| eyre!("Failed to yield slice from path"))? .to_owned(); Ok(()) } diff --git a/iroha/src/lib.rs b/iroha/src/lib.rs index b8774ef9c3..f126ae2453 100644 --- a/iroha/src/lib.rs +++ b/iroha/src/lib.rs @@ -20,10 +20,10 @@ pub mod wsv; use std::{path::PathBuf, sync::Arc, time::Duration}; +use eyre::{eyre, Result, WrapErr}; use genesis::GenesisNetworkTrait; use iroha_actor::{broker::*, prelude::*}; use iroha_data_model::prelude::*; -use iroha_error::{error, Result, WrapErr}; use parity_scale_codec::{Decode, Encode}; use smartcontracts::permissions::{IsInstructionAllowedBoxed, IsQueryAllowedBoxed}; use tokio::{sync::broadcast, task::JoinHandle}; @@ -284,7 +284,7 @@ where iroha_logger::info!("Starting Iroha."); self.torii .take() - .ok_or_else(|| error!("Seems like peer was already started"))? + .ok_or_else(|| eyre!("Seems like peer was already started"))? .start() .await .wrap_err("Failed to start Torii") @@ -293,12 +293,12 @@ where /// Starts iroha in separate tokio task. /// # Errors /// Can fail if initing kura fails - pub fn start_as_task(&mut self) -> Result>> { + pub fn start_as_task(&mut self) -> Result>> { iroha_logger::info!("Starting Iroha as task."); let torii = self .torii .take() - .ok_or_else(|| error!("Seems like peer was already started"))?; + .ok_or_else(|| eyre!("Seems like peer was already started"))?; Ok(tokio::spawn(async move { torii.start().await.wrap_err("Failed to start Torii") })) diff --git a/iroha/src/queue.rs b/iroha/src/queue.rs index 4354244e6d..d2ccb007bf 100644 --- a/iroha/src/queue.rs +++ b/iroha/src/queue.rs @@ -7,9 +7,9 @@ use std::{ time::Duration, }; +use eyre::{eyre, Result}; use iroha_actor::{broker::*, prelude::*, Context as ActorContext}; use iroha_data_model::prelude::*; -use iroha_error::{error, Result}; use self::config::QueueConfiguration; use crate::{prelude::*, wsv::WorldTrait}; @@ -151,7 +151,7 @@ impl Queue { let _result = self.pending_tx_by_hash.insert(tx.hash(), tx); Ok(()) } else { - Err(error!("The queue is full.")) + Err(eyre!("The queue is full.")) } } diff --git a/iroha/src/smartcontracts/isi/account.rs b/iroha/src/smartcontracts/isi/account.rs index 85f58f07d8..ebfbaf9a45 100644 --- a/iroha/src/smartcontracts/isi/account.rs +++ b/iroha/src/smartcontracts/isi/account.rs @@ -155,7 +155,7 @@ pub mod isi { /// Query module provides [`Query`] Account related implementations. pub mod query { - use iroha_error::{error, Result, WrapErr}; + use eyre::{eyre, Result, WrapErr}; use iroha_logger::log; use super::{super::Evaluate, *}; @@ -259,7 +259,7 @@ pub mod query { .evaluate(wsv, &Context::default()) .wrap_err("Failed to get key")?; wsv.map_account(&id, |account| account.metadata.get(&key).map(Clone::clone))? - .ok_or_else(|| error!("No metadata entry with this key.")) + .ok_or_else(|| eyre!("No metadata entry with this key.")) } } } diff --git a/iroha/src/smartcontracts/isi/asset.rs b/iroha/src/smartcontracts/isi/asset.rs index a6b06a0f32..ae5a397a67 100644 --- a/iroha/src/smartcontracts/isi/asset.rs +++ b/iroha/src/smartcontracts/isi/asset.rs @@ -11,7 +11,7 @@ use crate::prelude::*; /// - update metadata /// - transfer, etc. pub mod isi { - use iroha_error::error; + use eyre::eyre; use iroha_logger::log; use super::*; @@ -238,7 +238,7 @@ pub mod isi { wsv: &WorldStateView, ) -> Result<(), Error> { if self.destination_id.definition_id != self.source_id.definition_id { - return Err(error!("Can not transfer asset between different asset types.").into()); + return Err(eyre!("Can not transfer asset between different asset types.").into()); } assert_asset_type(&self.source_id.definition_id, wsv, AssetValueType::Quantity)?; assert_asset_type( @@ -250,7 +250,7 @@ pub mod isi { let quantity: &mut u32 = asset.try_as_mut()?; *quantity = quantity .checked_sub(self.object) - .ok_or_else(|| error!("Source account does not have enough asset quantity."))?; + .ok_or_else(|| eyre!("Source account does not have enough asset quantity."))?; Ok(()) })?; wsv.asset_or_insert(&self.destination_id, 0_u32)?; @@ -268,7 +268,7 @@ pub mod isi { /// Query module provides [`Query`] Asset related implementations. pub mod query { - use iroha_error::{error, Result, WrapErr}; + use eyre::{eyre, Result, WrapErr}; use iroha_logger::log; use super::*; @@ -437,7 +437,7 @@ pub mod query { let store: &Metadata = asset.value.try_as_ref()?; Ok(store .get(&key) - .ok_or_else(|| error!("Key {} not found in asset {}", key, id))? + .ok_or_else(|| eyre!("Key {} not found in asset {}", key, id))? .clone()) } } diff --git a/iroha/src/smartcontracts/isi/domain.rs b/iroha/src/smartcontracts/isi/domain.rs index b4fe24b831..48073c27aa 100644 --- a/iroha/src/smartcontracts/isi/domain.rs +++ b/iroha/src/smartcontracts/isi/domain.rs @@ -1,8 +1,8 @@ //! This module contains [`Domain`] structure and related implementations and trait implementations. use std::collections::btree_map::Entry; +use eyre::{eyre, Result}; use iroha_data_model::prelude::*; -use iroha_error::{error, Result}; use super::super::isi::prelude::*; use crate::prelude::*; @@ -27,7 +27,7 @@ pub mod isi { let name = account.id.domain_name.clone(); match wsv.domain_mut(&name)?.accounts.entry(account.id.clone()) { Entry::Occupied(_) => { - return Err(error!( + return Err(eyre!( "Domain already contains an account with this Id: {:?}", &account.id ) @@ -77,7 +77,7 @@ pub mod isi { }); } Entry::Occupied(entry) => { - return Err(error!( + return Err(eyre!( "Asset definition already exists and was registered by {}", entry.get().registered_by ) @@ -120,7 +120,7 @@ pub mod isi { /// Query module provides [`Query`] Domain related implementations. pub mod query { - use iroha_error::{Result, WrapErr}; + use eyre::{Result, WrapErr}; use iroha_logger::log; use super::*; diff --git a/iroha/src/smartcontracts/isi/expression.rs b/iroha/src/smartcontracts/isi/expression.rs index e7231367a5..eb89a3837f 100644 --- a/iroha/src/smartcontracts/isi/expression.rs +++ b/iroha/src/smartcontracts/isi/expression.rs @@ -2,11 +2,11 @@ use std::convert::TryFrom; +use eyre::{eyre, Error, Result}; use iroha_data_model::{ expression::{prelude::*, Expression}, prelude::*, }; -use iroha_error::{error, Error, Result}; use super::Evaluate; use crate::{prelude::*, wsv::WorldTrait}; @@ -58,7 +58,7 @@ impl Evaluate for ContextValue { fn evaluate(&self, _wsv: &WorldStateView, context: &Context) -> Result { context .get(&self.value_name) - .ok_or_else(|| error!("Value with name {} not found in context", self.value_name)) + .ok_or_else(|| eyre!("Value with name {} not found in context", self.value_name)) .map(ToOwned::to_owned) } } @@ -244,7 +244,7 @@ impl Evaluate for Divide { let right = self.right.evaluate(wsv, context)?; #[allow(clippy::integer_division)] if right == 0 { - Err(error!("Failed to divide by zero")) + Err(eyre!("Failed to divide by zero")) } else { Ok((left / right).into()) } @@ -267,8 +267,8 @@ mod tests { use std::{error::Error as StdError, fmt::Debug}; + use eyre::Result; use iroha_crypto::KeyPair; - use iroha_error::Result; use iroha_macro::error::ErrorTryFromEnum; use parity_scale_codec::{Decode, Encode}; @@ -415,7 +415,7 @@ mod tests { where I: Evaluate + Debug, I::Value: Debug, - E: StdError + Eq + Default + 'static, + E: StdError + Eq + Default + Send + Sync + 'static, { let wsv = WorldStateView::new(World::default()); let result: Result<_> = inst.evaluate(&wsv, &Context::new()); diff --git a/iroha/src/smartcontracts/isi/mod.rs b/iroha/src/smartcontracts/isi/mod.rs index 4019b6319b..7f144ed9ff 100644 --- a/iroha/src/smartcontracts/isi/mod.rs +++ b/iroha/src/smartcontracts/isi/mod.rs @@ -14,9 +14,10 @@ use std::{ fmt::{self, Display, Formatter}, }; +use eyre::{eyre, Result}; use iroha_data_model::{expression::prelude::*, isi::*, prelude::*}; use iroha_derive::FromVariant; -use iroha_error::{derive::Error, error, Result}; +use thiserror::Error; use super::{Evaluate, Execute}; use crate::{prelude::*, wsv::WorldTrait}; @@ -36,7 +37,7 @@ pub enum Error { MathError(#[source] MathError), /// Some other error happened #[error("Some other error happened")] - Other(#[skip_try_from] iroha_error::Error), + Other(#[skip_try_from] eyre::Error), } /// Type assertion error @@ -85,7 +86,6 @@ pub struct AssetTypeError { impl Display for AssetTypeError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - #[allow(clippy::use_debug)] write!( f, "Asset type error: expected asset of type {:?}, but got {:?}", @@ -170,7 +170,7 @@ impl Execute for RegisterBox { Register::::new(*domain).execute(authority, wsv) } IdentifiableBox::Peer(peer) => Register::::new(*peer).execute(authority, wsv), - _ => Err(error!("Unsupported register instruction.").into()), + _ => Err(eyre!("Unsupported register instruction.").into()), } } } @@ -195,7 +195,7 @@ impl Execute for UnregisterBox { IdBox::DomainName(domain_name) => { Unregister::::new(domain_name).execute(authority, wsv) } - _ => Err(error!("Unsupported unregister instruction.").into()), + _ => Err(eyre!("Unsupported unregister instruction.").into()), } } } @@ -227,7 +227,7 @@ impl Execute for MintBox { Mint::::new(condition, account_id) .execute(authority, wsv) } - _ => Err(error!("Unsupported mint instruction.").into()), + _ => Err(eyre!("Unsupported mint instruction.").into()), } } } @@ -255,7 +255,7 @@ impl Execute for BurnBox { (IdBox::AccountId(account_id), Value::PublicKey(public_key)) => { Burn::::new(public_key, account_id).execute(authority, wsv) } - _ => Err(error!("Unsupported burn instruction.").into()), + _ => Err(eyre!("Unsupported burn instruction.").into()), } } } @@ -272,12 +272,12 @@ impl Execute for TransferBox { let context = Context::new(); let source_asset_id = match self.source_id.evaluate(wsv, &context)? { IdBox::AssetId(source_asset_id) => source_asset_id, - _ => return Err(error!("Unsupported transfer instruction.").into()), + _ => return Err(eyre!("Unsupported transfer instruction.").into()), }; let quantity = match self.object.evaluate(wsv, &context)? { Value::U32(quantity) => quantity, - _ => return Err(error!("Unsupported transfer instruction.").into()), + _ => return Err(eyre!("Unsupported transfer instruction.").into()), }; match self.destination_id.evaluate(wsv, &context)? { @@ -285,7 +285,7 @@ impl Execute for TransferBox { Transfer::::new(source_asset_id, quantity, destination_asset_id) .execute(authority, wsv) } - _ => Err(error!("Unsupported transfer instruction.").into()), + _ => Err(eyre!("Unsupported transfer instruction.").into()), } } } @@ -311,7 +311,7 @@ impl Execute for SetKeyValueBox { SetKeyValue::::new(account_id, key, value) .execute(authority, wsv) } - _ => Err(error!("Unsupported set key-value instruction.").into()), + _ => Err(eyre!("Unsupported set key-value instruction.").into()), } } } @@ -334,7 +334,7 @@ impl Execute for RemoveKeyValueBox { IdBox::AccountId(account_id) => { RemoveKeyValue::::new(account_id, key).execute(authority, wsv) } - _ => Err(error!("Unsupported remove key-value instruction.").into()), + _ => Err(eyre!("Unsupported remove key-value instruction.").into()), } } } @@ -398,7 +398,7 @@ impl Execute for FailBox { _authority: ::Id, _wsv: &WorldStateView, ) -> Result<(), Error> { - Err(error!("Execution failed: {}.", self.message).into()) + Err(eyre!("Execution failed: {}.", self.message).into()) } } @@ -424,7 +424,7 @@ impl Execute for GrantBox { (IdBox::AccountId(account_id), Value::Id(IdBox::RoleId(role_id))) => { Grant::::new(role_id, account_id).execute(authority, wsv) } - _ => Err(error!("Unsupported grant instruction.").into()), + _ => Err(eyre!("Unsupported grant instruction.").into()), } } } diff --git a/iroha/src/smartcontracts/isi/permissions.rs b/iroha/src/smartcontracts/isi/permissions.rs index 1a569e48f1..1dbc3ea16b 100644 --- a/iroha/src/smartcontracts/isi/permissions.rs +++ b/iroha/src/smartcontracts/isi/permissions.rs @@ -4,8 +4,8 @@ use std::iter; +use eyre::Result; use iroha_data_model::prelude::*; -use iroha_error::Result; use super::prelude::WorldTrait; #[cfg(feature = "roles")] diff --git a/iroha/src/smartcontracts/isi/query.rs b/iroha/src/smartcontracts/isi/query.rs index 8e48facccd..575402c597 100644 --- a/iroha/src/smartcontracts/isi/query.rs +++ b/iroha/src/smartcontracts/isi/query.rs @@ -2,11 +2,12 @@ use std::{convert::TryFrom, error::Error as StdError, fmt}; +use eyre::{eyre, Error, Result}; use iroha_data_model::{prelude::*, query}; use iroha_derive::Io; -use iroha_error::{derive::Error, error, Error, Result}; use iroha_version::{scale::DecodeVersioned, Version}; use parity_scale_codec::{Decode, Encode}; +use thiserror::Error; use warp::{ http::StatusCode, hyper::body::Bytes, @@ -41,13 +42,13 @@ impl VerifiedQueryRequest { account.signatories.contains(&self.signature.public_key) })?; if !account_has_public_key { - return Err(error!( + return Err(eyre!( "Public key used for the signature does not correspond to the account." )); } query_validator .check(&self.payload.account_id, &self.payload.query, wsv) - .map_err(|denial_reason| error!(denial_reason))?; + .map_err(|denial_reason| eyre!(denial_reason))?; Ok(ValidQueryRequest { query: self.payload.query, }) @@ -120,7 +121,7 @@ pub enum AcceptQueryError { DecodeVersionedSignedQuery(#[source] iroha_version::error::Error), /// Failed to verify query request #[error("Failed to verify query request")] - VerifyQuery(iroha_error::Error), + VerifyQuery(eyre::Error), } impl Reply for AcceptQueryError { diff --git a/iroha/src/smartcontracts/isi/tx.rs b/iroha/src/smartcontracts/isi/tx.rs index 7ffe5dfc3b..6d0e27e4f4 100644 --- a/iroha/src/smartcontracts/isi/tx.rs +++ b/iroha/src/smartcontracts/isi/tx.rs @@ -1,7 +1,7 @@ //! Query module provides [`Query`] Transaction related implementations. +use eyre::{Result, WrapErr}; use iroha_data_model::prelude::*; -use iroha_error::{Result, WrapErr}; use super::*; diff --git a/iroha/src/smartcontracts/isi/world.rs b/iroha/src/smartcontracts/isi/world.rs index 563e1a22ce..3054490eff 100644 --- a/iroha/src/smartcontracts/isi/world.rs +++ b/iroha/src/smartcontracts/isi/world.rs @@ -5,8 +5,8 @@ use crate::prelude::*; /// Iroha Special Instructions that have `World` as their target. pub mod isi { + use eyre::{eyre, Result}; use iroha_data_model::prelude::*; - use iroha_error::{error, Result}; use super::*; @@ -21,7 +21,7 @@ pub mod isi { if wsv.trusted_peers_ids().insert(self.object.id) { Ok(()) } else { - Err(error!("Peer already presented in the list of trusted peers.",).into()) + Err(eyre!("Peer already presented in the list of trusted peers.",).into()) } } } @@ -92,8 +92,8 @@ pub mod isi { /// Query module provides `IrohaQuery` Peer related implementations. pub mod query { + use eyre::Result; use iroha_data_model::prelude::*; - use iroha_error::Result; use iroha_logger::log; use super::*; diff --git a/iroha/src/smartcontracts/mod.rs b/iroha/src/smartcontracts/mod.rs index 88fd9ccbb1..f6bd53efb9 100644 --- a/iroha/src/smartcontracts/mod.rs +++ b/iroha/src/smartcontracts/mod.rs @@ -33,11 +33,7 @@ pub trait Evaluate { type Value; /// Calculates result. - fn evaluate( - &self, - wsv: &WorldStateView, - context: &Context, - ) -> iroha_error::Result; + fn evaluate(&self, wsv: &WorldStateView, context: &Context) -> eyre::Result; } /// This trait should be implemented for all Iroha Queries. @@ -47,10 +43,10 @@ pub trait Query: QueryOutput { /// Should not mutate [`WorldStateView`]! /// /// Returns Ok(QueryResult) if succeeded and Err(String) if failed. - fn execute(&self, wsv: &WorldStateView) -> iroha_error::Result; + fn execute(&self, wsv: &WorldStateView) -> eyre::Result; /// Executes query and maps it into value - fn execute_into_value(&self, wsv: &WorldStateView) -> iroha_error::Result { + fn execute_into_value(&self, wsv: &WorldStateView) -> eyre::Result { self.execute(wsv).map(Into::into) } } diff --git a/iroha/src/sumeragi/mod.rs b/iroha/src/sumeragi/mod.rs index 37386e0ba5..8b3060c64b 100644 --- a/iroha/src/sumeragi/mod.rs +++ b/iroha/src/sumeragi/mod.rs @@ -12,11 +12,11 @@ use std::{ }; use dashmap::{DashMap, DashSet}; +use eyre::{eyre, Result}; use futures::future; use iroha_actor::{broker::*, prelude::*}; use iroha_crypto::{Hash, KeyPair}; use iroha_data_model::{events::Event, peer::Id as PeerId}; -use iroha_error::{error, Result}; use iroha_logger::Instrument; use network_topology::{Role, Topology}; use tokio::{sync::RwLock, task, time}; @@ -452,15 +452,15 @@ impl Sumeragi { genesis_topology: Topology, ) -> Result<()> { if transactions.is_empty() { - Err(error!("Genesis transactions set is empty.")) + Err(eyre!("Genesis transactions set is empty.")) } else if genesis_topology.leader() != &self.peer_id { - Err(error!( + Err(eyre!( "Incorrect network topology this peer should be {:?} but is {:?}", Role::Leader, genesis_topology.role(&self.peer_id) )) } else if self.block_height > 0 { - Err(error!( + Err(eyre!( "Block height should be 0 for genesis round. But it is: {}", self.block_height )) @@ -860,11 +860,11 @@ pub mod message { time::{Duration, Instant, SystemTime}, }; + use eyre::{Result, WrapErr}; use iroha_actor::broker::Broker; use iroha_crypto::{Hash, KeyPair, Signature, Signatures}; use iroha_data_model::prelude::*; use iroha_derive::*; - use iroha_error::{Result, WrapErr}; use iroha_logger::Instrument; use iroha_p2p::Post; use iroha_version::prelude::*; @@ -1529,10 +1529,10 @@ pub mod message { pub mod config { use std::{collections::HashSet, fmt::Debug, fs::File, io::BufReader, path::Path}; + use eyre::{Result, WrapErr}; use iroha_config::derive::Configurable; use iroha_crypto::prelude::*; use iroha_data_model::prelude::*; - use iroha_error::{Result, WrapErr}; use serde::{Deserialize, Serialize}; const DEFAULT_BLOCK_TIME_MS: u64 = 1000; diff --git a/iroha/src/sumeragi/network_topology.rs b/iroha/src/sumeragi/network_topology.rs index ae3415d927..2ffa387816 100644 --- a/iroha/src/sumeragi/network_topology.rs +++ b/iroha/src/sumeragi/network_topology.rs @@ -2,9 +2,9 @@ use std::{collections::HashSet, convert::TryInto, iter}; +use eyre::{eyre, Result}; use iroha_crypto::{Hash, Signature}; use iroha_data_model::prelude::PeerId; -use iroha_error::{error, Result}; use parity_scale_codec::{Decode, Encode}; use rand::{rngs::StdRng, seq::SliceRandom, SeedableRng}; @@ -49,7 +49,7 @@ pub fn shift_peers_by_n(mut peers: Vec, n: u64) -> Vec { macro_rules! field_is_some_or_err { ($s:ident.$f:ident) => { - $s.$f.ok_or(error!( + $s.$f.ok_or(eyre!( "Field with name {} should not be `None`.", stringify!($f) )) @@ -115,12 +115,12 @@ impl GenesisBuilder { field_is_some_or_err!(self.reshuffle_after_n_view_changes)?; let max_faults_rem = (set_a.len() - 1) % 2; if max_faults_rem > 0 { - return Err(error!("Could not deduce max faults. As given: 2f+1=set_a.len() We get a non integer f. f should be an integer.")); + return Err(eyre!("Could not deduce max faults. As given: 2f+1=set_a.len() We get a non integer f. f should be an integer.")); } #[allow(clippy::integer_division)] let max_faults = (set_a.len() - 1_usize) / 2_usize; if set_b.len() < max_faults { - return Err(error!( + return Err(eyre!( "Not enough peers to be Byzantine fault tolerant. Expected least {} peers in `set_b`, got {}", max_faults, set_b.len(), @@ -228,7 +228,7 @@ impl Builder { view_change_proofs: self.view_change_proofs, }) } else { - Err(error!( + Err(eyre!( "Not enough peers to be Byzantine fault tolerant. Expected a least {} peers, got {}", min_peers, peers.len(), @@ -374,7 +374,7 @@ impl Topology { { Ok(()) } else { - Err(error!("No {:?} with this public key exists.", role)) + Err(eyre!("No {:?} with this public key exists.", role)) } .and(signature.verify(message_payload)) } diff --git a/iroha/src/sumeragi/view_change.rs b/iroha/src/sumeragi/view_change.rs index eb8075ddf8..34ab2696d0 100644 --- a/iroha/src/sumeragi/view_change.rs +++ b/iroha/src/sumeragi/view_change.rs @@ -3,10 +3,10 @@ use std::{collections::HashSet, fmt::Display}; +use eyre::Result; use iroha_crypto::{Hash, KeyPair, PublicKey, Signature, Signatures}; use iroha_data_model::prelude::PeerId; use iroha_derive::*; -use iroha_error::Result; use parity_scale_codec::{Decode, Encode}; use super::message::TransactionReceipt; diff --git a/iroha/src/telemetry/dev.rs b/iroha/src/telemetry/dev.rs index 61b346840d..f5479d847b 100644 --- a/iroha/src/telemetry/dev.rs +++ b/iroha/src/telemetry/dev.rs @@ -2,7 +2,7 @@ use std::path::PathBuf; -use iroha_error::{Result, WrapErr}; +use eyre::{Result, WrapErr}; use iroha_logger::telemetry::Telemetry; use iroha_telemetry::futures; use tokio::{ diff --git a/iroha/src/telemetry/mod.rs b/iroha/src/telemetry/mod.rs index c638ab88e0..be5d0ff7fb 100644 --- a/iroha/src/telemetry/mod.rs +++ b/iroha/src/telemetry/mod.rs @@ -6,8 +6,8 @@ use std::path::PathBuf; #[cfg(feature = "dev-telemetry")] pub mod dev; +use eyre::Result; use iroha_config::derive::Configurable; -use iroha_error::Result; use iroha_logger::telemetry::Telemetry; use serde::{Deserialize, Serialize}; use tokio::{sync::mpsc::Receiver, task::JoinHandle}; diff --git a/iroha/src/torii/mod.rs b/iroha/src/torii/mod.rs index 71443fc9b9..459b5e5a3f 100644 --- a/iroha/src/torii/mod.rs +++ b/iroha/src/torii/mod.rs @@ -7,8 +7,8 @@ use config::ToriiConfiguration; use iroha_actor::{broker::*, prelude::*}; use iroha_config::{derive::Error as ConfigError, Configurable}; use iroha_data_model::prelude::*; -use iroha_error::{derive::Error, error}; use serde::{Deserialize, Serialize}; +use thiserror::Error; use utils::*; use warp::{ http::StatusCode, @@ -47,16 +47,16 @@ pub enum Error { VersionedTransaction(#[source] iroha_version::error::Error), /// Failed to accept transaction #[error("Failed to accept transaction")] - AcceptTransaction(iroha_error::Error), + AcceptTransaction(eyre::Error), /// Failed to execute query #[error("Failed to execute query")] - ExecuteQuery(iroha_error::Error), + ExecuteQuery(eyre::Error), /// Failed to validate query #[error("Failed to validate query")] - ValidateQuery(iroha_error::Error), + ValidateQuery(eyre::Error), /// Failed to get pending transaction #[error("Failed to get pending transactions")] - RequestPendingTransactions(iroha_error::Error), + RequestPendingTransactions(eyre::Error), /// Failed to decode pending transactions from leader #[error("Failed to decode pending transactions from leader")] DecodeRequestPendingTransactions(#[source] iroha_version::error::Error), @@ -140,7 +140,7 @@ impl Torii { /// # Errors /// Can fail due to listening to network or if http server fails #[iroha_futures::telemetry_future] - pub async fn start(self) -> iroha_error::Result<()> { + pub async fn start(self) -> eyre::Result<()> { let state = self.create_state(); let get_router = warp::path(uri::HEALTH) @@ -201,7 +201,7 @@ impl Torii { } Err(e) => { iroha_logger::error!("Failed to get socket addr"); - Err(iroha_error::Error::new(e)) + Err(eyre::Error::new(e)) } } } @@ -320,7 +320,7 @@ async fn handle_get_configuration( } #[iroha_futures::telemetry_future] -async fn handle_subscription(events: EventsSender, stream: WebSocket) -> iroha_error::Result<()> { +async fn handle_subscription(events: EventsSender, stream: WebSocket) -> eyre::Result<()> { let mut events = events.subscribe(); let mut consumer = Consumer::new(stream).await?; diff --git a/iroha/src/tx.rs b/iroha/src/tx.rs index 3097641ff8..75d017e1f5 100644 --- a/iroha/src/tx.rs +++ b/iroha/src/tx.rs @@ -9,10 +9,10 @@ use std::{ time::{Duration, SystemTime}, }; +use eyre::{Result, WrapErr}; use iroha_actor::Message; pub use iroha_data_model::prelude::*; use iroha_derive::Io; -use iroha_error::{Result, WrapErr}; use iroha_version::{declare_versioned_with_scale, version_with_scale}; use parity_scale_codec::{Decode, Encode}; @@ -518,11 +518,11 @@ mod tests { use std::collections::BTreeSet; + use eyre::Result; use iroha_data_model::{ account::GENESIS_ACCOUNT_NAME, domain::GENESIS_DOMAIN_NAME, transaction::MAX_INSTRUCTION_NUMBER, }; - use iroha_error::{Error, MessageError, Result, WrappedError}; use super::*; use crate::{config::Configuration, init, smartcontracts::permissions::AllowAll, wsv::World}; @@ -582,11 +582,14 @@ mod tests { assert!(result.is_err()); let err = result.unwrap_err(); - let err = err - .downcast_ref::>() - .unwrap(); - assert_eq!(err.msg, "Failed to accept transaction"); - let err = err.downcast_ref::>().unwrap(); - assert_eq!(err.msg, "Too many instructions in payload"); + let mut chain = err.chain(); + assert_eq!( + chain.next().unwrap().to_string(), + "Failed to accept transaction" + ); + assert_eq!( + chain.next().unwrap().to_string(), + "Too many instructions in payload" + ); } } diff --git a/iroha/src/wsv.rs b/iroha/src/wsv.rs index 42490c06eb..48687fe31a 100644 --- a/iroha/src/wsv.rs +++ b/iroha/src/wsv.rs @@ -12,8 +12,8 @@ use dashmap::{ mapref::one::{Ref as DashmapRef, RefMut as DashmapRefMut}, DashSet, }; +use eyre::Result; use iroha_data_model::{domain::DomainsMap, peer::PeersIds, prelude::*}; -use iroha_error::Result; use tokio::task; use crate::{ diff --git a/iroha/test_network/Cargo.toml b/iroha/test_network/Cargo.toml index 55df90a54e..b79f84b7b5 100644 --- a/iroha/test_network/Cargo.toml +++ b/iroha/test_network/Cargo.toml @@ -13,11 +13,11 @@ iroha = { path = "../../iroha" } iroha_client = { path = "../../iroha_client" } iroha_data_model = { path = "../../iroha_data_model" } iroha_logger = { path = "../../iroha_logger" } -iroha_error = { path = "../../iroha_error" } iroha_config = { path = "../../iroha_config" } iroha_p2p = { path = "../../iroha_p2p" } iroha_actor = { path = "../../iroha_actor" } +eyre = "0.6.5" tempfile = "3" unique_port = "0.1.0" tokio = { version = "1.6.0", features = ["rt", "rt-multi-thread", "macros"]} @@ -25,5 +25,7 @@ rand = "0.7.3" futures = "0.3" [dev-dependencies] +iroha_error = { path = "../../iroha_error" } + async-trait = "0.1" once_cell = "1" diff --git a/iroha/test_network/src/lib.rs b/iroha/test_network/src/lib.rs index 1bd02893af..f20eaeb4b4 100644 --- a/iroha/test_network/src/lib.rs +++ b/iroha/test_network/src/lib.rs @@ -13,6 +13,7 @@ use std::{convert::TryFrom, fmt::Debug, thread, time::Duration}; +use eyre::{Error, Result}; use futures::future; use iroha::{ block_sync::{BlockSynchronizer, BlockSynchronizerTrait}, @@ -30,7 +31,6 @@ use iroha::{ use iroha_actor::{broker::*, prelude::*}; use iroha_client::{client::Client, config::Configuration as ClientConfiguration}; use iroha_data_model::{peer::Peer as DataModelPeer, prelude::*}; -use iroha_error::{Error, Result}; use iroha_logger::{ config::{LevelEnv, LoggerConfiguration}, InstrumentFutures, @@ -580,7 +580,7 @@ pub trait TestClient: Sized { ) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug; /// Submits instructions with polling @@ -592,14 +592,14 @@ pub trait TestClient: Sized { ) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug; /// Polls request till predicate `f` is satisfied, with default period and max attempts. fn poll_request(&mut self, request: R, f: impl Fn(&R::Output) -> bool) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug; /// Polls request till predicate `f` is satisfied with `period` and `max_attempts` supplied. @@ -612,7 +612,7 @@ pub trait TestClient: Sized { ) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug; } @@ -698,7 +698,7 @@ impl TestClient for Client { ) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug, { self.submit(instruction) @@ -714,7 +714,7 @@ impl TestClient for Client { ) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug, { self.submit_all(instructions) @@ -731,7 +731,7 @@ impl TestClient for Client { ) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug, { let mut query_result = None; @@ -748,7 +748,7 @@ impl TestClient for Client { fn poll_request(&mut self, request: R, f: impl Fn(&R::Output) -> bool) -> R::Output where R: Query + Into + Debug + Clone, - >::Error: Into, + >::Error: Into, R::Output: Clone + Debug, { self.poll_request_with_period(request, Configuration::pipeline_time(), 10, f) diff --git a/iroha/test_network/tests/sumeragi_with_mock.rs b/iroha/test_network/tests/sumeragi_with_mock.rs index 72914f6351..62e72066a5 100644 --- a/iroha/test_network/tests/sumeragi_with_mock.rs +++ b/iroha/test_network/tests/sumeragi_with_mock.rs @@ -7,6 +7,7 @@ use std::{fmt::Debug, ops::Deref, path::Path, sync::Arc, time::Duration}; +use eyre::Result; use iroha::{ block_sync::{BlockSynchronizer, BlockSynchronizerTrait, ContinueSync}, event::EventsSender, @@ -24,7 +25,6 @@ use iroha::{ }; use iroha_actor::{broker::*, prelude::*, Context}; use iroha_data_model::prelude::*; -use iroha_error::Result; use iroha_p2p::network::StopSelf; use test_network::*; use tokio::{sync::mpsc, time}; @@ -611,7 +611,7 @@ where #[tokio::test(flavor = "multi_thread")] #[ignore = "mock"] async fn all_peers_commit_block() { - iroha_error::install_panic_reporter(); + iroha_error::install_panic_hook(); let (network, _) = Result<(), Reporter> { - iroha_error::install_panic_reporter(); +async fn main() -> Result<(), Report> { + iroha_error::install_panic_hook(); ::new( &Arguments::from_args(), diff --git a/iroha_client/Cargo.toml b/iroha_client/Cargo.toml index ac5fd0e014..52f96cf24e 100644 --- a/iroha_client/Cargo.toml +++ b/iroha_client/Cargo.toml @@ -24,7 +24,7 @@ iroha_logger = { version = "=0.1.0", path = "../iroha_logger"} iroha_crypto = { version = "=0.1.0", path = "../iroha_crypto" } iroha_config = { path = "../iroha_config" } iroha_version = { version = "=0.1.0", path = "../iroha_version" } -iroha_error = { version = "=0.1.0", path = "../iroha_error" } +eyre = "0.6.5" ursa = "0.3.2" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" @@ -36,6 +36,7 @@ iroha_telemetry = { path = "../iroha_telemetry" } [dev-dependencies] iroha = { path = "../iroha", features = ["dev-telemetry", "telemetry"] } +iroha_error = { path = "../iroha_error" } iroha_data_model = { path = "../iroha_data_model" } async-trait = "0.1.31" criterion = "0.3" diff --git a/iroha_client/src/client.rs b/iroha_client/src/client.rs index b1b47f185a..caa568fd23 100644 --- a/iroha_client/src/client.rs +++ b/iroha_client/src/client.rs @@ -6,11 +6,11 @@ use std::{ time::Duration, }; +use eyre::{eyre, Error, Result, WrapErr}; use http_client::WebSocketStream; use iroha::{smartcontracts::Query, wsv::World}; use iroha_crypto::{Hash, KeyPair}; use iroha_dsl::prelude::*; -use iroha_error::{error, Error, Result, WrapErr}; use iroha_logger::log; use iroha_version::prelude::*; @@ -149,7 +149,7 @@ impl Client { if response.status() == StatusCode::OK { Ok(hash) } else { - Err(error!( + Err(eyre!( "Failed to submit instructions with HTTP status: {}", response.status() )) @@ -206,7 +206,7 @@ impl Client { let (init_sender, init_receiver) = mpsc::channel(); let transaction = self.build_transaction(instructions, metadata)?; let hash = transaction.hash(); - let _handle = thread::spawn(move || -> iroha_error::Result<()> { + let _handle = thread::spawn(move || -> eyre::Result<()> { let event_iterator = client .listen_for_events(PipelineEventFilter::by_hash(hash).into()) .wrap_err("Failed to establish event listener connection.")?; @@ -252,7 +252,7 @@ impl Client { ) -> Result where R: Query + Into + Debug, - >::Error: Into, + >::Error: Into, { let pagination: Vec<_> = pagination.into(); let request = QueryRequest::new(request.into(), self.account_id.clone()); @@ -263,7 +263,7 @@ impl Client { pagination, )?; if response.status() != StatusCode::OK { - return Err(error!( + return Err(eyre!( "Failed to make query request with HTTP status: {}, {}", response.status(), std::str::from_utf8(response.body()).unwrap_or(""), @@ -283,7 +283,7 @@ impl Client { pub fn request(&mut self, request: R) -> Result where R: Query + Into + Debug, - >::Error: Into, + >::Error: Into, { self.request_with_pagination(request, Pagination::default()) } @@ -323,7 +323,7 @@ impl Client { let pending_transactions: PendingTransactions = VersionedPendingTransactions::decode_versioned(response.body())? .into_v1() - .ok_or_else(|| error!("Expected pending transaction message version 1."))? + .ok_or_else(|| eyre!("Expected pending transaction message version 1."))? .into(); let transaction = pending_transactions .into_iter() @@ -337,7 +337,7 @@ impl Client { } thread::sleep(retry_in) } else { - return Err(error!( + return Err(eyre!( "Failed to make query request with HTTP status: {}, {}", response.status(), std::str::from_utf8(response.body()).unwrap_or(""), @@ -394,11 +394,11 @@ impl EventIterator { { break; } - return Err(error!("Expected `SubscriptionAccepted`.")); + return Err(eyre!("Expected `SubscriptionAccepted`.")); } Ok(_) => continue, Err(WebSocketError::ConnectionClosed | WebSocketError::AlreadyClosed) => { - return Err(error!("WebSocket connection closed.")) + return Err(eyre!("WebSocket connection closed.")) } Err(err) => return Err(err.into()), } @@ -421,9 +421,7 @@ impl Iterator for EventIterator { }; let event = match event_socket_message { EventSocketMessage::Event(event) => event, - message => { - return Some(Err(error!("Expected Event but got {:?}", message))) - } + message => return Some(Err(eyre!("Expected Event but got {:?}", message))), }; let message = match VersionedEventSocketMessage::from(EventSocketMessage::EventReceived) @@ -435,7 +433,7 @@ impl Iterator for EventIterator { }; return match self.stream.write_message(WebSocketMessage::Binary(message)) { Ok(_) => Some(Ok(event)), - Err(err) => Some(Err(error!("Failed to send receipt: {}", err))), + Err(err) => Some(Err(eyre!("Failed to send receipt: {}", err))), }; } Ok(_) => continue, diff --git a/iroha_client/src/config.rs b/iroha_client/src/config.rs index dd652c6a92..ec6811ca94 100644 --- a/iroha_client/src/config.rs +++ b/iroha_client/src/config.rs @@ -1,9 +1,9 @@ use std::{fmt::Debug, fs::File, io::BufReader, path::Path}; +use eyre::{Result, WrapErr}; use iroha_config::derive::Configurable; use iroha_crypto::{PrivateKey, PublicKey}; use iroha_dsl::prelude::*; -use iroha_error::{Result, WrapErr}; use iroha_logger::config::LoggerConfiguration; use serde::{Deserialize, Serialize}; diff --git a/iroha_client/src/http_client.rs b/iroha_client/src/http_client.rs index a6e782307a..bc249a1b7b 100644 --- a/iroha_client/src/http_client.rs +++ b/iroha_client/src/http_client.rs @@ -4,8 +4,8 @@ use std::{ }; use attohttpc::Response as AttohttpcResponse; +use eyre::{eyre, Error, Result, WrapErr}; pub use http::{Response, StatusCode}; -use iroha_error::{error, Error, Result, WrapErr}; use tungstenite::{client::AutoStream, WebSocket}; pub use tungstenite::{Error as WebSocketError, Message as WebSocketMessage}; @@ -65,7 +65,7 @@ impl TryFrom for Response { let mut builder = Response::builder().status(response.status()); let headers = builder .headers_mut() - .ok_or_else(|| error!("Failed to get headers map reference."))?; + .ok_or_else(|| eyre!("Failed to get headers map reference."))?; for (key, value) in response.headers() { headers.insert(key, value.clone()); } diff --git a/iroha_client/tests/account_with_multiple_signatories.rs b/iroha_client/tests/account_with_multiple_signatories.rs index 8cb0cb3abd..3f6ab5d184 100644 --- a/iroha_client/tests/account_with_multiple_signatories.rs +++ b/iroha_client/tests/account_with_multiple_signatories.rs @@ -4,10 +4,10 @@ mod tests { use std::thread; + use eyre::Result; use iroha::{config::Configuration, prelude::*}; use iroha_client::client::{self, Client}; use iroha_data_model::prelude::*; - use iroha_error::Result; use test_network::{Peer as TestPeer, *}; #[test] diff --git a/iroha_client/tests/add_account.rs b/iroha_client/tests/add_account.rs index 43dfc72296..c4f492a66c 100644 --- a/iroha_client/tests/add_account.rs +++ b/iroha_client/tests/add_account.rs @@ -2,10 +2,10 @@ use std::thread; +use eyre::Result; use iroha::config::Configuration; use iroha_client::client; use iroha_data_model::prelude::*; -use iroha_error::Result; use test_network::{Peer as TestPeer, *}; #[test] diff --git a/iroha_client/tests/add_asset.rs b/iroha_client/tests/add_asset.rs index 116843bba4..26772e0275 100644 --- a/iroha_client/tests/add_asset.rs +++ b/iroha_client/tests/add_asset.rs @@ -2,10 +2,10 @@ use std::{convert::TryFrom, thread}; +use eyre::Result; use iroha::config::Configuration; use iroha_client::client; use iroha_data_model::prelude::*; -use iroha_error::Result; use test_network::{Peer as TestPeer, *}; #[test] diff --git a/iroha_client/tests/add_asset_should_propagate_to_another_peer.rs b/iroha_client/tests/add_asset_should_propagate_to_another_peer.rs index d44174b668..b719454787 100644 --- a/iroha_client/tests/add_asset_should_propagate_to_another_peer.rs +++ b/iroha_client/tests/add_asset_should_propagate_to_another_peer.rs @@ -4,10 +4,10 @@ mod tests { use std::thread; + use eyre::Result; use iroha::{config::Configuration, prelude::*}; use iroha_client::client::{self, Client}; use iroha_data_model::prelude::*; - use iroha_error::Result; use test_network::{Network, *}; #[test] diff --git a/iroha_client/tests/add_domain.rs b/iroha_client/tests/add_domain.rs index 4c3b4cdc66..37d4e855a1 100644 --- a/iroha_client/tests/add_domain.rs +++ b/iroha_client/tests/add_domain.rs @@ -2,10 +2,10 @@ use std::thread; +use eyre::Result; use iroha::config::Configuration; use iroha_client::client; use iroha_data_model::prelude::*; -use iroha_error::Result; use test_network::{Peer as TestPeer, *}; #[test] diff --git a/iroha_client/tests/asset_amount_should_be_the_same_on_a_recently_added_peer.rs b/iroha_client/tests/asset_amount_should_be_the_same_on_a_recently_added_peer.rs index f861d5e988..e4faab2750 100644 --- a/iroha_client/tests/asset_amount_should_be_the_same_on_a_recently_added_peer.rs +++ b/iroha_client/tests/asset_amount_should_be_the_same_on_a_recently_added_peer.rs @@ -4,10 +4,10 @@ mod tests { use std::thread; + use eyre::Result; use iroha::{config::Configuration, prelude::*}; use iroha_client::client; use iroha_data_model::prelude::*; - use iroha_error::Result; use test_network::*; #[test] diff --git a/iroha_client/tests/events.rs b/iroha_client/tests/events.rs index 457882ff91..526c9c4831 100644 --- a/iroha_client/tests/events.rs +++ b/iroha_client/tests/events.rs @@ -5,9 +5,9 @@ use std::{ thread, }; +use eyre::Result; use iroha::config::Configuration; use iroha_data_model::prelude::*; -use iroha_error::Result; use test_network::{Peer as TestPeer, *}; #[test] diff --git a/iroha_client/tests/unstable_network.rs b/iroha_client/tests/unstable_network.rs index 96c114ac69..ef71dddf90 100644 --- a/iroha_client/tests/unstable_network.rs +++ b/iroha_client/tests/unstable_network.rs @@ -33,7 +33,7 @@ fn unstable_network( n_transactions: usize, polling_max_attempts: u32, ) { - iroha_error::install_panic_reporter(); + iroha_error::install_panic_hook(); let rt = Runtime::test(); // Given let (_network, mut iroha_client) = diff --git a/iroha_client_cli/Cargo.toml b/iroha_client_cli/Cargo.toml index f120899bec..27dc4ec00e 100644 --- a/iroha_client_cli/Cargo.toml +++ b/iroha_client_cli/Cargo.toml @@ -19,8 +19,9 @@ maintenance = { status = "actively-developed" } [dependencies] iroha_client = { version = "=0.1.0", path = "../iroha_client" } iroha_crypto = { version = "=0.1.0", path = "../iroha_crypto" } -iroha_error = { version = "=0.1.0", path = "../iroha_error" } iroha_dsl = { path = "../iroha_dsl" } +iroha_error = { path = "../iroha_error" } +eyre = "0.6.5" structopt = "0.3" futures = "0.3.4" dialoguer = "0.8" diff --git a/iroha_client_cli/src/main.rs b/iroha_client_cli/src/main.rs index 3f9c97da2b..ffb825bc18 100644 --- a/iroha_client_cli/src/main.rs +++ b/iroha_client_cli/src/main.rs @@ -5,10 +5,10 @@ use std::{fmt, fs::File, str::FromStr, time::Duration}; use dialoguer::Confirm; +use eyre::{Error, Report, Result, WrapErr}; use iroha_client::{client::Client, config::Configuration as ClientConfiguration}; use iroha_crypto::prelude::*; use iroha_dsl::prelude::*; -use iroha_error::{Error, Reporter, Result, WrapErr}; use structopt::StructOpt; /// Metadata wrapper, which can be captured from cli arguments (from user suplied file). @@ -104,8 +104,8 @@ impl RunArgs for Subcommand { const RETRY_COUNT_MST: u32 = 1; const RETRY_IN_MST: Duration = Duration::from_millis(100); -fn main() -> Result<(), Reporter> { - iroha_error::install_panic_reporter(); +fn main() -> Result<(), Report> { + iroha_error::install_panic_hook(); let Args { config: Configuration(config), subcommand, diff --git a/iroha_crypto/Cargo.toml b/iroha_crypto/Cargo.toml index 0ff25f358e..69f4ad90b0 100644 --- a/iroha_crypto/Cargo.toml +++ b/iroha_crypto/Cargo.toml @@ -7,13 +7,13 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +eyre = "0.6.5" ursa = "=0.3.6" openssl-sys = { version = "0", features = ["vendored"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1" parity-scale-codec = { version = "2", features = ["derive"] } hex = "0.4.0" -iroha_error = { path = "../iroha_error" } iroha_schema = { path = "../iroha_schema"} [dev-dependencies] diff --git a/iroha_crypto/src/lib.rs b/iroha_crypto/src/lib.rs index 972db96fac..c6d7994572 100644 --- a/iroha_crypto/src/lib.rs +++ b/iroha_crypto/src/lib.rs @@ -15,7 +15,7 @@ use std::{ str::FromStr, }; -use iroha_error::{error, Error, Result, WrapErr}; +use eyre::{eyre, Error, Result, WrapErr}; use iroha_schema::IntoSchema; use multihash::{DigestFunction as MultihashDigestFunction, Multihash}; use parity_scale_codec::{Decode, Encode}; @@ -128,7 +128,7 @@ impl FromStr for Algorithm { SECP_256_K1 => Ok(Algorithm::Secp256k1), BLS_NORMAL => Ok(Algorithm::BlsNormal), BLS_SMALL => Ok(Algorithm::BlsSmall), - _ => Err(error!("The {} algorithm is not supported.")), + _ => Err(eyre!("The {} algorithm is not supported.")), } } } @@ -164,7 +164,7 @@ impl TryFrom for UrsaKeyGenOption { if key.digest_function == ED_25519 || key.digest_function == SECP_256_K1 { Ok(UrsaKeyGenOption::FromSecretKey(UrsaPrivateKey(key.payload))) } else { - Err(error!( + Err(eyre!( "Ursa does not support {} digest function.", key.digest_function )) @@ -239,7 +239,7 @@ impl KeyPair { } // TODO: Create an issue for ursa to impl Error for ursa::CryptoError //.wrap_err("Failed to generate key pair")?; - .map_err(|e| error!("{}", e.to_string()))?; + .map_err(|e| eyre!("{}", e.to_string()))?; Ok(KeyPair { public_key: PublicKey { digest_function: configuration.algorithm.to_string(), @@ -326,7 +326,7 @@ impl TryFrom<&PublicKey> for Multihash { SECP_256_K1 => Ok(MultihashDigestFunction::Secp256k1Pub), BLS_NORMAL => Ok(MultihashDigestFunction::Bls12381G1Pub), BLS_SMALL => Ok(MultihashDigestFunction::Bls12381G2Pub), - _ => Err(error!("Digest function not implemented.")), + _ => Err(eyre!("Digest function not implemented.")), } .map(|digest_function| Multihash { digest_function, @@ -420,7 +420,7 @@ impl Signature { Algorithm::BlsSmall => BlsSmall::new().sign(payload, &private_key), Algorithm::BlsNormal => BlsNormal::new().sign(payload, &private_key), } - .map_err(|e| error!("Failed to sign payload: {}", e))?; + .map_err(|e| eyre!("Failed to sign payload: {}", e))?; Ok(Signature { public_key: key_pair.public_key, signature, @@ -446,7 +446,7 @@ impl Signature { }; match result { Ok(true) => Ok(()), - _ => Err(error!("Signature did not pass verification: {}")), + _ => Err(eyre!("Signature did not pass verification: {}")), } } } diff --git a/iroha_crypto/src/multihash.rs b/iroha_crypto/src/multihash.rs index 52f4127e5f..ca4dc705f9 100644 --- a/iroha_crypto/src/multihash.rs +++ b/iroha_crypto/src/multihash.rs @@ -4,7 +4,7 @@ use std::{ str::FromStr, }; -use iroha_error::{error, Error, Result}; +use eyre::{eyre, Error, Result}; use super::varint::VarUint; @@ -59,7 +59,7 @@ impl FromStr for DigestFunction { SECP_256_K1_PUB_STR => Ok(DigestFunction::Secp256k1Pub), BLS12_381_G1_PUB => Ok(DigestFunction::Bls12381G1Pub), BLS12_381_G2_PUB => Ok(DigestFunction::Bls12381G2Pub), - _ => Err(error!("The specified digest function is not supported.",)), + _ => Err(eyre!("The specified digest function is not supported.",)), } } } @@ -87,7 +87,7 @@ impl TryFrom for DigestFunction { variant if variant == DigestFunction::Bls12381G2Pub as u64 => { Ok(DigestFunction::Bls12381G2Pub) } - _ => Err(error!("The specified digest function is not supported.",)), + _ => Err(eyre!("The specified digest function is not supported.",)), } } } @@ -117,7 +117,7 @@ impl TryFrom> for Multihash { .iter() .enumerate() .find(|&(_, &byte)| (byte & 0b1000_0000) == 0) - .ok_or_else(|| error!("Last byte should be less than 128"))? + .ok_or_else(|| eyre!("Last byte should be less than 128"))? .0; let (digest_function, bytes) = bytes.split_at(idx + 1); let mut bytes = bytes.iter().copied(); @@ -127,7 +127,7 @@ impl TryFrom> for Multihash { let digest_size = bytes .next() - .ok_or_else(|| error!("Failed to parse digest size."))?; + .ok_or_else(|| eyre!("Failed to parse digest size."))?; let payload: Vec = bytes.collect(); if payload.len() == digest_size as usize { Ok(Multihash { @@ -135,7 +135,7 @@ impl TryFrom> for Multihash { payload, }) } else { - Err(error!("The digest size is not equal to the actual length.",)) + Err(eyre!("The digest size is not equal to the actual length.",)) } } } diff --git a/iroha_crypto/src/varint.rs b/iroha_crypto/src/varint.rs index f60ef7af4c..d893dbed70 100644 --- a/iroha_crypto/src/varint.rs +++ b/iroha_crypto/src/varint.rs @@ -1,4 +1,4 @@ -use iroha_error::{error, Error, Result}; +use eyre::{eyre, Error, Result}; /// Variable length unsigned int. [ref](https://github.com/multiformats/unsigned-varint) #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)] @@ -19,7 +19,7 @@ macro_rules! try_into_uint( fn try_into(self) -> Result<$ty> { let VarUint { payload } = self; if std::mem::size_of::<$ty>() * 8 < payload.len() * 7 { - return Err(error!( + return Err(eyre!( concat!("Number is too large for type ", stringify!($ty)) )); } @@ -82,7 +82,7 @@ impl VarUint { .iter() .enumerate() .find(|&(_, &byte)| (byte & 0b1000_0000) == 0) - .ok_or_else(|| error!("Last byte should be less than 128"))? + .ok_or_else(|| eyre!("Last byte should be less than 128"))? .0; let (payload, empty) = bytes.as_ref().split_at(idx + 1); let payload = payload.to_vec(); @@ -90,7 +90,7 @@ impl VarUint { if empty.is_empty() { Ok(Self { payload }) } else { - Err(error!("Last byte shouldn't be followed by anything")) + Err(eyre!("Last byte shouldn't be followed by anything")) } } } diff --git a/iroha_crypto_cli/Cargo.toml b/iroha_crypto_cli/Cargo.toml index 5dfa0a9113..8a79ca97a5 100644 --- a/iroha_crypto_cli/Cargo.toml +++ b/iroha_crypto_cli/Cargo.toml @@ -7,8 +7,10 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +iroha_crypto = { version = "=0.1.0", path = "../iroha_crypto" } +iroha_error = { version = "=0.1.0", path = "../iroha_error" } + clap = "2.33.0" -iroha_crypto = { version = "=0.1.0", path = "../iroha_crypto"} -serde_json = "1.0" +eyre = "0.6.5" hex = "0.4.0" -iroha_error = { path = "../iroha_error" } +serde_json = "1.0" diff --git a/iroha_crypto_cli/src/main.rs b/iroha_crypto_cli/src/main.rs index 95e058d7ba..2c5d556519 100644 --- a/iroha_crypto_cli/src/main.rs +++ b/iroha_crypto_cli/src/main.rs @@ -1,11 +1,11 @@ //! `iroha_crypto_cli` is a command line tool used to generate keys for Iroha peers and clients. use clap::{App, Arg, ArgGroup}; +use eyre::{eyre, Report, Result, WrapErr}; use iroha_crypto::{Algorithm, KeyGenConfiguration, KeyPair, PrivateKey}; -use iroha_error::{error, Reporter, Result, WrapErr}; -fn main() -> Result<(), Reporter> { - iroha_error::install_panic_reporter(); +fn main() -> Result<(), Report> { + iroha_error::install_panic_hook(); let default_algorithm = Algorithm::default().to_string(); let matches = App::new("iroha_crypto_cli") .version("0.1") @@ -57,13 +57,13 @@ fn main() -> Result<(), Reporter> { let private_key_option = matches.value_of("private_key"); let algorithm = matches .value_of("algorithm") - .ok_or_else(|| error!("Failed to get algorithm name."))? + .ok_or_else(|| eyre!("Failed to get algorithm name."))? .parse::() .wrap_err("Failed to parse algorithm.")?; let key_gen_configuration = KeyGenConfiguration::default().with_algorithm(algorithm); let keypair: KeyPair = seed_option .map_or_else( - || -> iroha_error::Result<_> { + || -> eyre::Result<_> { private_key_option.map_or_else( || KeyPair::generate_with_configuration(key_gen_configuration.clone()), |private_key| { @@ -77,7 +77,7 @@ fn main() -> Result<(), Reporter> { }, ) }, - |seed| -> iroha_error::Result<_> { + |seed| -> eyre::Result<_> { KeyPair::generate_with_configuration( key_gen_configuration .clone() diff --git a/iroha_data_model/Cargo.toml b/iroha_data_model/Cargo.toml index 4e55582262..bb7202fb19 100644 --- a/iroha_data_model/Cargo.toml +++ b/iroha_data_model/Cargo.toml @@ -23,11 +23,11 @@ roles = [] [dependencies] iroha_crypto = { path = "../iroha_crypto" } iroha_derive = { version = "=0.1.0", path = "../iroha_macro/iroha_derive" } -iroha_error = { version = "=0.1.0", path = "../iroha_error" } iroha_macro = { version = "=0.1.0", path = "../iroha_macro" } iroha_schema = { path = "../iroha_schema"} iroha_version = { version = "=0.1.0", path = "../iroha_version", features = ["warp"] } +eyre = "0.6.5" fixnum = { version = "0.6", features = ["i64"]} chrono = "0.4" dashmap = { version = "4.0" } @@ -35,5 +35,6 @@ parity-scale-codec = { version = "2", features = ["derive"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ursa = "0.3.2" +thiserror = "1.0.28" warp = { version = "0.3", default-features = false, optional = true } diff --git a/iroha_data_model/src/events.rs b/iroha_data_model/src/events.rs index 0328e63a90..0253020df3 100644 --- a/iroha_data_model/src/events.rs +++ b/iroha_data_model/src/events.rs @@ -195,10 +195,10 @@ pub mod pipeline { use iroha_crypto::{Hash, Signature}; use iroha_derive::FromVariant; - use iroha_error::derive::Error; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; + use thiserror::Error; use crate::isi::Instruction; diff --git a/iroha_data_model/src/expression.rs b/iroha_data_model/src/expression.rs index b4a8017d8f..910526258e 100644 --- a/iroha_data_model/src/expression.rs +++ b/iroha_data_model/src/expression.rs @@ -13,8 +13,8 @@ use std::{ marker::PhantomData, }; +use eyre::{eyre, Result}; use iroha_derive::FromVariant; -use iroha_error::{error, Result}; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; @@ -615,7 +615,7 @@ impl IfBuilder { { Ok(If::new(self.condition, then_expression, else_expression)) } else { - Err(error!("Not all fields are filled.")) + Err(eyre!("Not all fields are filled.")) } } } diff --git a/iroha_data_model/src/lib.rs b/iroha_data_model/src/lib.rs index 075672f887..1c9415a093 100644 --- a/iroha_data_model/src/lib.rs +++ b/iroha_data_model/src/lib.rs @@ -5,9 +5,9 @@ use std::{convert::TryFrom, error, fmt::Debug, ops::RangeInclusive}; +use eyre::{eyre, Result, WrapErr}; use iroha_crypto::PublicKey; use iroha_derive::FromVariant; -use iroha_error::{error, Result, WrapErr}; use iroha_macro::error::ErrorTryFromEnum; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; @@ -317,7 +317,7 @@ where V: TryFrom, >::Error: Send + Sync + error::Error + 'static, { - type Error = iroha_error::Error; + type Error = eyre::Error; fn try_from(value: Value) -> Result> { if let Value::Vec(vec) = value { vec.into_iter() @@ -325,7 +325,7 @@ where .collect::, _>>() .wrap_err("Failed to convert to vector") } else { - Err(error!("Expected vector, but found something else")) + Err(eyre!("Expected vector, but found something else")) } } } @@ -666,10 +666,10 @@ pub mod account { ops::RangeInclusive, }; + use eyre::{eyre, Error, Result}; //TODO: get rid of it? use iroha_crypto::prelude::*; use iroha_derive::Io; - use iroha_error::{error, Error, Result}; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; @@ -837,7 +837,7 @@ pub mod account { if range.contains(&self.id.name.len()) { Ok(()) } else { - Err(error!( + Err(eyre!( "Length of the account name must be in range {}-{}", &range.start(), &range.end() @@ -1030,7 +1030,7 @@ pub mod account { fn from_str(string: &str) -> Result { let vector: Vec<&str> = string.split('@').collect(); if vector.len() != 2 { - return Err(error!("Id should have format `name@domain_name`")); + return Err(eyre!("Id should have format `name@domain_name`")); } Ok(Id { name: String::from(vector[0]), @@ -1184,8 +1184,8 @@ pub mod asset { str::FromStr, }; + use eyre::{eyre, Error, Result, WrapErr}; use iroha_derive::{FromVariant, Io}; - use iroha_error::{error, Error, Result, WrapErr}; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; @@ -1365,7 +1365,7 @@ pub mod asset { if let AssetValue:: $variant (value) = self { Ok(value) } else { - Err(error!( + Err(eyre!( concat!( "Expected source asset with value type:", stringify!($variant), @@ -1384,7 +1384,7 @@ pub mod asset { if let AssetValue:: $variant (value) = self { Ok(value) } else { - Err(error!( + Err(eyre!( concat!( "Expected source asset with value type:", stringify!($variant), @@ -1506,7 +1506,7 @@ pub mod asset { if range.contains(&self.id.name.len()) { Ok(()) } else { - Err(error!( + Err(eyre!( "Length of the asset defenition name must be in range {}-{}", &range.start(), &range.end() @@ -1658,7 +1658,7 @@ pub mod asset { fn from_str(string: &str) -> Result { let vector: Vec<&str> = string.split('#').collect(); if vector.len() != 2 { - return Err(error!( + return Err(eyre!( "Asset definition ID should have format `name#domain_name`.", )); } @@ -1699,9 +1699,9 @@ pub mod domain { }; use dashmap::DashMap; + use eyre::{eyre, Result}; use iroha_crypto::PublicKey; use iroha_derive::Io; - use iroha_error::{error, Result}; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; @@ -1797,7 +1797,7 @@ pub mod domain { if range.contains(&self.name.len()) { Ok(()) } else { - Err(error!( + Err(eyre!( "Length of the domain name must be in range {}-{}", &range.start(), &range.end() @@ -1946,9 +1946,9 @@ pub mod transaction { use std::{cmp::Ordering, iter::FromIterator, time::SystemTime, vec::IntoIter as VecIter}; + use eyre::{eyre, Result}; use iroha_crypto::prelude::*; use iroha_derive::Io; - use iroha_error::{error, Result}; use iroha_schema::prelude::*; use iroha_version::{ declare_versioned, declare_versioned_with_scale, version, version_with_scale, @@ -2158,7 +2158,7 @@ pub mod transaction { .sum::() as u64 > max_instruction_number { - return Err(error!("Too many instructions in payload")); + return Err(eyre!("Too many instructions in payload")); } Ok(()) } @@ -2599,7 +2599,7 @@ pub mod metadata { use std::{borrow::Borrow, collections::BTreeMap}; - use iroha_error::{error, Result}; + use eyre::{eyre, Result}; use iroha_schema::prelude::*; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; @@ -2669,7 +2669,7 @@ pub mod metadata { limits: Limits, ) -> Result> { if self.map.len() == limits.max_len as usize && !self.map.contains_key(&key) { - return Err(error!( + return Err(eyre!( "Metadata length limit is reached: {}", limits.max_len )); @@ -2677,7 +2677,7 @@ pub mod metadata { let entry_bytes: Vec = (key.clone(), value.clone()).encode(); let byte_size = entry_bytes.len(); if byte_size > limits.max_entry_byte_size as usize { - return Err(error!("Metadata entry is bigger than allowed. Expected less or equal to {} bytes. Got: {} bytes", limits.max_entry_byte_size, byte_size)); + return Err(eyre!("Metadata entry is bigger than allowed. Expected less or equal to {} bytes. Got: {} bytes", limits.max_entry_byte_size, byte_size)); } Ok(self.map.insert(key, value)) } diff --git a/iroha_data_model/src/query.rs b/iroha_data_model/src/query.rs index 1a97c03624..41bc780a71 100644 --- a/iroha_data_model/src/query.rs +++ b/iroha_data_model/src/query.rs @@ -4,9 +4,9 @@ use std::{convert::TryFrom, time::SystemTime}; +use eyre::Result; use iroha_crypto::prelude::*; use iroha_derive::{FromVariant, Io}; -use iroha_error::Result; use iroha_schema::prelude::*; use iroha_version::prelude::*; use parity_scale_codec::{Decode, Encode}; diff --git a/iroha_error/Cargo.toml b/iroha_error/Cargo.toml index 2e0f3c6285..7d453d04bf 100644 --- a/iroha_error/Cargo.toml +++ b/iroha_error/Cargo.toml @@ -7,6 +7,5 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -iroha_error_macro = { path = "./iroha_error_macro" } owo-colors = "2" backtrace = "0.3" diff --git a/iroha_error/iroha_error_macro/Cargo.toml b/iroha_error/iroha_error_macro/Cargo.toml deleted file mode 100644 index 510935da47..0000000000 --- a/iroha_error/iroha_error_macro/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "iroha_error_macro" -version = "0.1.0" -authors = ["i1i1"] -edition = "2018" - -[lib] -proc-macro = true - -[dependencies] -syn = { version = "1.0", features = ["parsing", "full"] } -quote = "1.0" -proc-macro2 = "1.0" -proc-macro-error = "1.0" - -[dev-dependencies] -trybuild = "1.0" diff --git a/iroha_error/iroha_error_macro/src/display.rs b/iroha_error/iroha_error_macro/src/display.rs deleted file mode 100644 index 8a8c6fa549..0000000000 --- a/iroha_error/iroha_error_macro/src/display.rs +++ /dev/null @@ -1,71 +0,0 @@ -use proc_macro_error::abort; -use quote::quote; - -fn get_attr_str(attrs: &[syn::Attribute]) -> Option { - attrs - .iter() - .filter(|attr| attr.path.is_ident("error")) - .find_map(|attr| { - let nested_meta = match attr.parse_meta().ok()? { - syn::Meta::List(syn::MetaList { ref nested, .. }) if nested.len() == 1 => { - nested[0].clone() - } - syn::Meta::List(list) => { - abort!(list, "error attribute should have only 1 argument string") - } - _ => { - abort!(attr, "Only function like attributes supported") - } - }; - match nested_meta { - syn::NestedMeta::Lit(syn::Lit::Str(s)) => Some(s), - _ => { - abort!(nested_meta, "Argument for error attribute should be string") - } - } - }) -} - -pub fn impl_fmt(ast: &syn::DeriveInput) -> proc_macro2::TokenStream { - let name = &ast.ident; - - let variants = if let syn::Data::Enum(ref data_enum) = ast.data { - &data_enum.variants - } else { - abort!(ast, "Only enums are supported") - } - .iter() - .map(|variant| { - let fmt = get_attr_str(&variant.attrs) - .expect("Enum variants should have error attribute with display format"); - match variant.fields { - syn::Fields::Unnamed(_) => (&variant.ident, true, fmt), - syn::Fields::Unit => (&variant.ident, false, fmt), - _ => abort!( - variant, - "Invalid variant. Only unnamed fields supported or units. Check out iroha2 style-guide" - ), - } - }) - .map(|(variant, field, fmt)| { - if field { - quote! { - Self:: #variant (inner) => { - write!(f, "{}. Caused by: {}", #fmt, inner) - } - } - } else { - quote! { Self:: #variant => write!(f, #fmt) } - } - }); - - quote! { - impl std::fmt::Display for #name { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { - match self { - #(#variants,)* - } - } - } - } -} diff --git a/iroha_error/iroha_error_macro/src/error.rs b/iroha_error/iroha_error_macro/src/error.rs deleted file mode 100644 index 6f2824b34a..0000000000 --- a/iroha_error/iroha_error_macro/src/error.rs +++ /dev/null @@ -1,50 +0,0 @@ -use proc_macro_error::abort; -use quote::quote; - -const SOURCE_ATTR: &str = "source"; - -fn attrs_have_ident(attrs: &[syn::Attribute], ident: &str) -> bool { - attrs.iter().any(|attr| attr.path.is_ident(ident)) -} - -pub fn impl_source(ast: &syn::DeriveInput) -> proc_macro2::TokenStream { - let name = &ast.ident; - - let variants = if let syn::Data::Enum(ref data_enum) = ast.data { - &data_enum.variants - } else { - abort!(ast, "Only enums are supported") - } - .iter() - .map(|variant| { - let ident = &variant.ident; - match variant.fields { - syn::Fields::Unnamed(ref fields) if fields.unnamed.len() == 1 && attrs_have_ident(&fields.unnamed[0].attrs, SOURCE_ATTR) => { - quote! { Self:: #ident (var) => Some(var) } - }, - syn::Fields::Unnamed(ref fields) if fields.unnamed.len() == 1 => { - quote! { Self:: #ident (_) => None } - }, - syn::Fields::Unit => quote! { Self:: #ident => None }, - - syn::Fields::Unnamed(_) => abort!( - variant, - "Unnamed variant should have exactly one arguments. Check out iroha2 style-guide." - ), - syn::Fields::Named(_) => abort!( - variant, - "Invalid variant. Named structures inside enum are not supported. Check out iroha2 style-guide." - ), - } - }); - - quote! { - impl std::error::Error for #name { - fn source(&self) -> std::option::Option<&(dyn std::error::Error + 'static)> { - match self { - #(#variants,)* - } - } - } - } -} diff --git a/iroha_error/iroha_error_macro/src/lib.rs b/iroha_error/iroha_error_macro/src/lib.rs deleted file mode 100644 index 415dda9908..0000000000 --- a/iroha_error/iroha_error_macro/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -#![allow(clippy::module_name_repetitions, missing_docs, clippy::restriction)] - -use proc_macro::TokenStream; -use quote::quote; - -mod display; -mod error; - -#[proc_macro_derive(Error, attributes(error, source))] -pub fn error_derive(input: TokenStream) -> TokenStream { - let ast = syn::parse(input).expect("Failed to parse input Token Stream."); - impl_error(&ast) -} - -fn impl_error(ast: &syn::DeriveInput) -> TokenStream { - let display = display::impl_fmt(ast); - let error = error::impl_source(ast); - let result = quote! { - #display - #error - }; - result.into() -} diff --git a/iroha_error/iroha_error_macro/tests/display_inner.rs b/iroha_error/iroha_error_macro/tests/display_inner.rs deleted file mode 100644 index 3e28b0e85c..0000000000 --- a/iroha_error/iroha_error_macro/tests/display_inner.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::fmt::Display; - -#[derive(Debug)] -struct ErrorInner; - -impl Display for ErrorInner { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "This is inner.") - } -} - -impl std::error::Error for ErrorInner {} - -#[derive(Debug, iroha_error_macro::Error)] -enum Error { - #[error("This is A")] - A(#[source] ErrorInner), -} - -#[test] -fn display_inner() { - assert_eq!( - Error::A(ErrorInner).to_string(), - "This is A. Caused by: This is inner.".to_owned() - ); -} diff --git a/iroha_error/iroha_error_macro/tests/error/01-basic-test.rs b/iroha_error/iroha_error_macro/tests/error/01-basic-test.rs deleted file mode 100644 index 919e506e47..0000000000 --- a/iroha_error/iroha_error_macro/tests/error/01-basic-test.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[derive(Debug, iroha_error_macro::Error)] -enum Error { - #[error("This is A")] - A, -} - -fn main() {} diff --git a/iroha_error/iroha_error_macro/tests/error/02-fail-debug.rs b/iroha_error/iroha_error_macro/tests/error/02-fail-debug.rs deleted file mode 100644 index 504299e418..0000000000 --- a/iroha_error/iroha_error_macro/tests/error/02-fail-debug.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[derive(iroha_error_macro::Error)] -enum Error { - #[error("This is A")] - A, -} - -fn main() {} diff --git a/iroha_error/iroha_error_macro/tests/error/03-unnamed-field-variant.rs b/iroha_error/iroha_error_macro/tests/error/03-unnamed-field-variant.rs deleted file mode 100644 index c21adf45fb..0000000000 --- a/iroha_error/iroha_error_macro/tests/error/03-unnamed-field-variant.rs +++ /dev/null @@ -1,17 +0,0 @@ -#[derive(Debug, iroha_error_macro::Error)] -enum ErrorInner { - #[error("This is A")] - A, - #[error("This is B")] - B, - #[error("This is C")] - C, -} - -#[derive(Debug, iroha_error_macro::Error)] -enum Error { - #[error("This is A")] - A(ErrorInner), -} - -fn main() {} diff --git a/iroha_error/iroha_error_macro/tests/trybuild.rs b/iroha_error/iroha_error_macro/tests/trybuild.rs deleted file mode 100644 index fcea49b8e3..0000000000 --- a/iroha_error/iroha_error_macro/tests/trybuild.rs +++ /dev/null @@ -1,15 +0,0 @@ -use trybuild::TestCases; - -#[test] -fn test_error() { - let pass = ["01-basic-test", "03-unnamed-field-variant"]; - let fail = ["02-fail-debug"]; - let to_test = |test| format!("tests/error/{}.rs", test); - - let t = TestCases::new(); - - pass.iter().map(to_test).for_each(|test| t.pass(test)); - fail.iter() - .map(to_test) - .for_each(|test| t.compile_fail(test)); -} diff --git a/iroha_error/src/lib.rs b/iroha_error/src/lib.rs index d738506616..469fb65ba1 100644 --- a/iroha_error/src/lib.rs +++ b/iroha_error/src/lib.rs @@ -1,196 +1,145 @@ -//! Iroha Error crate contains error type similar to anyhow and eyre crates. -//! -//! It has general [`Error`] type which can wrap any type implementing [`std::error::Error`]. -//! Also it contains alias `iroha_error::Result = Result`. -//! -//! Example: -//! ```rust -//! # pub trait Deserialize {} -//! # -//! # mod serde_json { -//! # use super::Deserialize; -//! # use std::io; -//! # -//! # pub fn from_str(json: &str) -> io::Result { -//! # unimplemented!() -//! # } -//! # } -//! # -//! # struct ClusterMap; -//! # -//! # impl Deserialize for ClusterMap {} -//! # -//! use iroha_error::Result; -//! -//! fn get_cluster_info() -> Result { -//! let config = std::fs::read_to_string("cluster.json")?; -//! let map: ClusterMap = serde_json::from_str(&config)?; -//! Ok(map) -//! } -//! # fn main() {} -//! ``` -//! -//! Wrap a lower level errors with some context: -//! ```rust -//! # struct It; -//! # -//! # impl It { -//! # fn detach(&self) -> Result<()> { -//! # unimplemented!() -//! # } -//! # } -//! # -//! use iroha_error::{WrapErr, Result}; -//! -//! fn main() -> Result<()> { -//! # return Ok(()); -//! # -//! # const _: &str = stringify! { -//! ... -//! # }; -//! # -//! # let it = It; -//! # let path = "./path/to/instrs.json"; -//! # -//! it.detach().wrap_err("Failed to detach the important thing")?; -//! -//! let content = std::fs::read(path) -//! .wrap_err_with(|| format!("Failed to read instrs from {}", path))?; -//! # -//! # const _: &str = stringify! { -//! ... -//! # }; -//! # -//! # Ok(()) -//! } -//! ``` - -#![allow(clippy::module_name_repetitions)] - use std::{ - convert::{AsRef, From}, + env, error::Error as StdError, - fmt::{self, Debug, Display}, - ops::{Deref, DerefMut}, - result::Result as StdResult, + fmt::{self, Display, Formatter}, + panic, + panic::PanicInfo, + path::Path, + ptr, + sync::atomic::{AtomicBool, Ordering}, }; -pub use message_error::MessageError; -pub use reporter::{install as install_panic_reporter, Reporter}; -pub use wrap_err::{WrapErr, WrappedError}; - -pub mod reporter; - -/// Module with derive macroses -pub mod derive { - /// Derive macro for enums which implements source and display for it. - /// - /// ```rust - /// #[derive(iroha_error::derive::Error, Debug)] - /// enum Error { - /// #[error("Failed because of reason a")] - /// ErrorA, - /// // #[source] tells macro to use io::Error as source for this variant - /// #[error("Failed during reading file")] - /// IOError(#[source] std::io::Error), - /// } - /// ``` - pub use iroha_error_macro::Error; -} - -mod message_error; -mod wrap_err; - -/// Error type similar to `anyhow::Error`, `eyre::Reporter`. -pub struct Error { - inner: Box, -} - -/// Result type which uses Error -pub type Result = StdResult; - -impl Display for Error { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - Display::fmt(&self.inner, formatter) +use owo_colors::OwoColorize; + +#[derive(Clone, Copy, Debug)] +struct Backtrace; + +impl Display for Backtrace { + #[allow(clippy::unwrap_used)] + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + macro_rules! try_writeln { + ($res:expr, $dst:expr, $($arg:tt)*) => { + if let Err(e) = writeln!($dst, $($arg)*) { + $res = Err(e); + return; + } + } + } + + const SKIPPED: &[&str] = &[ + "backtrace::backtrace::", + "iroha_error::reporter", + "std::panicking::", + "std::sys_common::backtrace", + "std::panic::catch_unwind", + "std::rt::", + "_main", + "rust_begin_unwind", + "", + "core::fmt::", + "alloc::fmt::", + "core::ops::function", + "", + "std::thread::local::", + ]; + + let mut out = Ok(()); + let mut i = 0; + + backtrace::trace(|frame| { + backtrace::resolve_frame(frame, |symbol| { + let name = symbol + .name() + .map_or_else(|| "".to_owned(), |name| name.to_string()); + if SKIPPED.iter().any(|skip| name.starts_with(skip)) { + return; + } + + let addr = symbol.addr().unwrap_or(ptr::null_mut()); + let filename = symbol + .filename() + .and_then(|name| { + let buf = name.to_path_buf(); + buf.strip_prefix(env::current_dir().ok()?) + .ok() + .map(Path::to_path_buf) + }) + .map_or_else( + || "".to_owned(), + |name| name.into_os_string().into_string().unwrap(), + ); + let lineno = symbol.lineno().unwrap_or(0); + let colno = symbol.colno().unwrap_or(0); + + let file = format!("{}:{}:{}", filename, lineno, colno); + + try_writeln!(out, f, "{:6}: {}", i.red(), name.yellow()); + try_writeln!(out, f, "{:12}at {}", "", file.green()); + try_writeln!(out, f, "{:12}at addr {:p}", "", addr.blue()); + + i += 1; + }); + + true + }); + + out } } -impl Debug for Error { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - Debug::fmt(&self.inner, formatter) - } -} - -impl AsRef for Error { - fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) { - self.inner.as_ref() - } -} +fn panic_hook(info: &PanicInfo<'_>) { + let payload = info.payload(); + let location = if let Some(location) = info.location() { + format!( + "{}:{}:{}", + location.file(), + location.line(), + location.column() + ) + } else { + "Error at ".to_owned() + }; + #[allow(clippy::option_if_let_else)] + let payload = if let Some(error) = payload.downcast_ref::() { + error.red().to_string() + } else { + "".to_owned() + }; -impl AsRef for Error { - fn as_ref(&self) -> &(dyn StdError + 'static) { - self.inner.as_ref() - } + println!("{} {}:\n", "Error at".green(), location.red()); + println!("\t{}", payload); + println!( + "\n{}\n{:>4}", + "Backtrace:".underline().yellow(), + Backtrace.to_string().red() + ); } -impl Deref for Error { - type Target = dyn StdError + Send + Sync + 'static; - fn deref(&self) -> &Self::Target { - self.as_ref() - } -} +/// Hook that signals that panic hook is set. (it should be set once) +static HOOK_SET: AtomicBool = AtomicBool::new(false); -impl DerefMut for Error { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut *self.inner - } -} +/// Failed to install error reporter +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct InstallError; -impl From for Error { - fn from(error: E) -> Self { - Self::new(error) +impl Display for InstallError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "Failed to install panic hook.") } } -impl Error { - /// Wraps error with message - pub fn wrap_err(self, msg: impl Display + Send + Sync + 'static) -> Self { - let error = self; - WrappedError { msg, error }.into() - } +impl StdError for InstallError {} - /// Constructs reporter from error - pub const fn report(self) -> Reporter { - Reporter(self) +/// Installs panic hook for printing errors. Usually set up at the beginning of program. +pub fn install_panic_hook() { + if HOOK_SET + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) + .is_err() + { + return; } - /// Creates error from message - pub fn msg(msg: impl Display + Debug + Send + Sync + 'static) -> Self { - MessageError { msg }.into() - } - - /// Creates error from another error - pub fn new(error: impl StdError + Send + Sync + 'static) -> Self { - let inner = Box::new(error); - Self { inner } - } + panic::set_hook(Box::new(panic_hook)); } - -/// Macro for creation of error messages -/// ```rust -/// use iroha_error::{Error, error}; -/// -/// # stringify!( -/// assert_eq!(error!("x = {}", 2), Error::msg(format!("x = {}", 2))); -/// # ); -/// ``` -/// -#[macro_export] -macro_rules! error( - ( $x:expr ) => { - iroha_error::Error::msg($x) - }; - ( $( $x:expr ),* $(,)* ) => { - iroha_error::Error::msg(format!($($x,)*)) - }; -); diff --git a/iroha_error/src/reporter.rs b/iroha_error/src/reporter.rs index be6d8d8d9d..5dc6688981 100644 --- a/iroha_error/src/reporter.rs +++ b/iroha_error/src/reporter.rs @@ -148,57 +148,3 @@ fn print_error(error: &Error, f: &mut Formatter) -> fmt::Result { Ok(()) } -fn panic_hook(info: &PanicInfo<'_>) { - let payload = info.payload(); - let location = if let Some(location) = info.location() { - format!( - "{}:{}:{}", - location.file(), - location.line(), - location.column() - ) - } else { - "Error at ".to_owned() - }; - #[allow(clippy::option_if_let_else)] - let payload = if let Some(error) = payload.downcast_ref::() { - error.red().to_string() - } else { - "".to_owned() - }; - - println!("{} {}:\n", "Error at".green(), location.red()); - println!("\t{}", payload); - println!( - "\n{}\n{:>4}", - "Backtrace:".underline().yellow(), - Backtrace.to_string().red() - ); -} - -/// Hook that signals that panic hook is set. (it should be set once) -static HOOK_SET: AtomicBool = AtomicBool::new(false); - -/// Failed to install error reporter -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub struct InstallError; - -impl Display for InstallError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "Failed to install panic hook.") - } -} - -impl StdError for InstallError {} - -/// Installs panic hook for printing errors. Usually set up at the beginning of program. -pub fn install() { - if HOOK_SET - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) - .is_err() - { - return; - } - - panic::set_hook(Box::new(panic_hook)); -} diff --git a/iroha_logger/Cargo.toml b/iroha_logger/Cargo.toml index e65676dccb..7f5b322ba7 100644 --- a/iroha_logger/Cargo.toml +++ b/iroha_logger/Cargo.toml @@ -6,8 +6,8 @@ edition = "2018" [dependencies] chrono = "0.4" +eyre = "0.6.5" iroha_config = { path = "../iroha_config" } -iroha_error = { path = "../iroha_error" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tracing = "0.1" diff --git a/iroha_macro/Cargo.toml b/iroha_macro/Cargo.toml index 44bf4c2a67..66401f3b92 100644 --- a/iroha_macro/Cargo.toml +++ b/iroha_macro/Cargo.toml @@ -17,5 +17,5 @@ is-it-maintained-open-issues = { repository = "https://github.com/hyperledger/ir maintenance = { status = "actively-developed" } [dependencies] +eyre = "0.6.5" parity-scale-codec = "2" -iroha_error = { path = "../iroha_error" } diff --git a/iroha_macro/src/lib.rs b/iroha_macro/src/lib.rs index 57120d6f09..dce73b941b 100644 --- a/iroha_macro/src/lib.rs +++ b/iroha_macro/src/lib.rs @@ -6,7 +6,7 @@ pub mod error { use std::{any::type_name, error, fmt, marker::PhantomData}; - pub use iroha_error::*; + pub use eyre::*; /// Error which happens if TryFrom from enum variant fails #[derive(Clone, Copy, Eq, PartialEq)] diff --git a/iroha_p2p/Cargo.toml b/iroha_p2p/Cargo.toml index 72d7e2d8d0..c110aeea4a 100644 --- a/iroha_p2p/Cargo.toml +++ b/iroha_p2p/Cargo.toml @@ -15,11 +15,11 @@ categories = ["cryptography::cryptocurrencies", "network-programming"] iroha_logger = { path = "../iroha_logger" } iroha_crypto = { path = "../iroha_crypto" } iroha_actor = { path = "../iroha_actor" } -iroha_error = { path = "../iroha_error" } iroha_macro = { version = "=0.1.0", path = "../iroha_macro" } iroha_derive = { version = "=0.1.0", path = "../iroha_macro/iroha_derive" } iroha_data_model = { path = "../iroha_data_model" } +eyre = "0.6.5" rand = "0.7.3" tokio = { version = "1.6.0", features = ["net", "sync", "time", "io-util"]} async-stream = "0.3" @@ -29,6 +29,7 @@ serde = { version = "1", features = ["derive"] } parity-scale-codec = { version = "2", features = ["derive"] } ursa = "=0.3.6" aead = "0.3.2" +thiserror = "1.0.28" [dev-dependencies] unique_port = "0.1.1" diff --git a/iroha_p2p/src/lib.rs b/iroha_p2p/src/lib.rs index 2c95d694c5..400754e082 100644 --- a/iroha_p2p/src/lib.rs +++ b/iroha_p2p/src/lib.rs @@ -5,9 +5,9 @@ use std::{io, net::AddrParseError}; use iroha_derive::FromVariant; -use iroha_error::{derive::Error, error}; pub use network::{ConnectPeer, NetworkBase, Post}; use parity_scale_codec::{Decode, Encode}; +use thiserror::Error; use ursa::{encryption::symm::prelude::ChaCha20Poly1305, kex::x25519::X25519Sha256}; /// Network is a main p2p start point. diff --git a/iroha_p2p/src/peer.rs b/iroha_p2p/src/peer.rs index b17baa9bb4..78736814c7 100644 --- a/iroha_p2p/src/peer.rs +++ b/iroha_p2p/src/peer.rs @@ -571,7 +571,6 @@ pub enum State { impl Display for State { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - #[allow(clippy::use_debug)] write!(f, "{:?}", &self) } } diff --git a/iroha_schema/iroha_schema_bin/Cargo.toml b/iroha_schema/iroha_schema_bin/Cargo.toml index 64237c4517..91b90ab55e 100644 --- a/iroha_schema/iroha_schema_bin/Cargo.toml +++ b/iroha_schema/iroha_schema_bin/Cargo.toml @@ -9,5 +9,5 @@ edition = "2018" iroha_schema = { path = "../../iroha_schema" } iroha_data_model = { path = "../../iroha_data_model" } iroha = { path = "../../iroha" } -iroha_error = { path = "../../iroha_error" } +eyre = "0.6.5" serde_json = "1" diff --git a/iroha_version/Cargo.toml b/iroha_version/Cargo.toml index 7aeb2f3269..eec102a01b 100644 --- a/iroha_version/Cargo.toml +++ b/iroha_version/Cargo.toml @@ -13,9 +13,10 @@ json = ["serde_json"] derive = ["iroha_version_derive"] [dependencies] -iroha_error = { version = "=0.1.0", path = "../iroha_error" } +eyre = "0.6.5" serde = { version = "1.0", features = ["derive"] } serde_json = {version = "1.0", optional = true } +thiserror = "1.0.28" iroha_derive = { path = "../iroha_macro/iroha_derive" } iroha_macro = { path = "../iroha_macro" } iroha_schema = { path = "../iroha_schema"} diff --git a/iroha_version/src/lib.rs b/iroha_version/src/lib.rs index bcbaf9d58b..3a067f761d 100644 --- a/iroha_version/src/lib.rs +++ b/iroha_version/src/lib.rs @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; /// Module which contains error and result for versioning pub mod error { use iroha_derive::FromVariant; - use iroha_error::derive::Error; + use thiserror::Error; #[cfg(feature = "warp")] use warp::{ http::StatusCode,