Skip to content

Commit

Permalink
The big error refactor (#2046)
Browse files Browse the repository at this point in the history
* The big error refactor

* better display derives

* no_std

* missed

* fix the merge 😤

* simplify bindings error handling

* re-enable high-level examples

* more disabled examples

* fix send_all

* missed

* fill in last display derives

* okay really the last one this time

* add common conversions

* improve signature error

* tiny improvement

* remove another id error

* review

* Remove some more

* Fix test

* review

* improve addresses verification

* wrap hrp error

* fmt

---------

Co-authored-by: Thibault Martinez <[email protected]>
  • Loading branch information
DaughterOfMars and thibault-martinez authored Feb 29, 2024
1 parent 7fd9c9b commit f459c48
Show file tree
Hide file tree
Showing 222 changed files with 2,219 additions and 2,210 deletions.
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 21 additions & 2 deletions bindings/core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use iota_sdk::types::block::{
mana::ManaError, output::OutputError, payload::PayloadError, semantic::TransactionFailureReason,
signature::SignatureError, BlockError,
};
use packable::error::UnexpectedEOF;
use serde::{Serialize, Serializer};

Expand All @@ -14,7 +18,22 @@ pub type Result<T> = std::result::Result<T, Error>;
pub enum Error {
/// Block errors.
#[error("{0}")]
Block(#[from] iota_sdk::types::block::Error),
Block(#[from] BlockError),
/// Output errors.
#[error("{0}")]
Output(#[from] OutputError),
/// Payload errors.
#[error("{0}")]
Payload(#[from] PayloadError),
/// Signature errors.
#[error("{0}")]
Signature(#[from] SignatureError),
/// Mana errors.
#[error("{0}")]
Mana(#[from] ManaError),
/// Semantic errors.
#[error("{0}")]
TransactionSemantic(#[from] TransactionFailureReason),
/// Client errors.
#[error("{0}")]
Client(#[from] iota_sdk::client::Error),
Expand All @@ -29,7 +48,7 @@ pub enum Error {
SerdeJson(#[from] serde_json::error::Error),
/// Unpack errors.
#[error("{0}")]
Unpack(#[from] packable::error::UnpackError<iota_sdk::types::block::Error, UnexpectedEOF>),
Unpack(#[from] packable::error::UnpackError<BlockError, UnexpectedEOF>),
}

#[cfg(feature = "stronghold")]
Expand Down
14 changes: 8 additions & 6 deletions bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ use iota_sdk::{
output::{AccountId, FoundryId, MinimumOutputAmount, NftId, Output, OutputId, TokenId},
payload::{signed_transaction::Transaction, SignedTransactionPayload},
semantic::SemanticValidationContext,
Block, Error,
signature::SignatureError,
Block,
},
TryFromDto,
},
Expand Down Expand Up @@ -91,7 +92,7 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
}
UtilsMethod::VerifyEd25519Signature { signature, message } => {
let message: Vec<u8> = prefix_hex::decode(message)?;
Response::Bool(signature.try_verify(&message).map_err(Error::from)?)
Response::Bool(signature.try_verify(&message).map_err(iota_sdk::client::Error::from)?)
}
UtilsMethod::VerifySecp256k1EcdsaSignature {
public_key,
Expand All @@ -100,9 +101,11 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
} => {
use crypto::signatures::secp256k1_ecdsa;
let public_key = prefix_hex::decode(public_key)?;
let public_key = secp256k1_ecdsa::PublicKey::try_from_bytes(&public_key).map_err(Error::from)?;
let public_key = secp256k1_ecdsa::PublicKey::try_from_bytes(&public_key)
.map_err(SignatureError::InvalidPublicKeyBytes)?;
let signature = prefix_hex::decode(signature)?;
let signature = secp256k1_ecdsa::Signature::try_from_bytes(&signature).map_err(Error::from)?;
let signature = secp256k1_ecdsa::Signature::try_from_bytes(&signature)
.map_err(SignatureError::InvalidSignatureBytes)?;
let message: Vec<u8> = prefix_hex::decode(message)?;
Response::Bool(public_key.verify_keccak256(&signature, &message))
}
Expand All @@ -129,8 +132,7 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
mana_rewards,
protocol_parameters,
);

context.validate().map_err(Error::from)?;
context.validate()?;

Response::Ok
}
Expand Down
4 changes: 2 additions & 2 deletions bindings/core/tests/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
// SPDX-License-Identifier: Apache-2.0

use iota_sdk::types::block::address::{Bech32Address, Hrp};
use iota_sdk_bindings_core::{call_utils_method, Response, Result, UtilsMethod};
use iota_sdk_bindings_core::{call_utils_method, Response, UtilsMethod};
use pretty_assertions::assert_eq;

#[tokio::test]
async fn utils() -> Result<()> {
async fn utils() -> Result<(), Box<dyn std::error::Error>> {
let response = call_utils_method(UtilsMethod::GenerateMnemonic);
match response {
Response::GeneratedMnemonic(mnemonic) => println!("{:?}", serde_json::to_string(&mnemonic)?),
Expand Down
8 changes: 0 additions & 8 deletions bindings/python/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,6 @@ impl From<std::io::Error> for Error {
}
}

impl From<iota_sdk_bindings_core::iota_sdk::types::block::Error> for Error {
fn from(err: iota_sdk_bindings_core::iota_sdk::types::block::Error) -> Self {
Self {
error: PyErr::new::<exceptions::PyValueError, _>(err.to_string()),
}
}
}

impl From<iota_sdk_bindings_core::Error> for Error {
fn from(err: iota_sdk_bindings_core::Error) -> Self {
Self {
Expand Down
1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ dialoguer = { version = "0.11.0", default-features = false, features = [
"password",
] }
dotenvy = { version = "0.15.7", default-features = false }
eyre = { version = "0.6.12", default-features = false }
fern-logger = { version = "0.5.0", default-features = false }
log = { version = "0.4.20", default-features = false }
prefix-hex = { version = "0.7.1", default-features = false, features = ["std"] }
Expand Down
46 changes: 11 additions & 35 deletions cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use std::{path::Path, str::FromStr};

use clap::{builder::BoolishValueParser, Args, CommandFactory, Parser, Subcommand};
use eyre::{bail, Error};
use iota_sdk::{
client::{
constants::SHIMMER_COIN_TYPE,
Expand All @@ -18,7 +19,6 @@ use iota_sdk::{
use log::LevelFilter;

use crate::{
error::Error,
helper::{
check_file_exists, enter_or_generate_mnemonic, generate_mnemonic, get_alias, get_decision, get_password,
import_mnemonic, select_secret_manager, SecretManagerChoice,
Expand Down Expand Up @@ -206,21 +206,15 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
return Ok(None);
}
LinkedSecretManager::Stronghold { snapshot_path, .. } => {
return Err(Error::Miscellaneous(format!(
"Stronghold snapshot does not exist at '{}'",
snapshot_path.display()
)));
bail!("Stronghold snapshot does not exist at '{}'", snapshot_path.display());
}
_ => {
println_log_info!("only Stronghold backup supported");
return Ok(None);
}
}
} else {
return Err(Error::Miscellaneous(format!(
"wallet db does not exist at '{}'",
storage_path.display()
)));
bail!("wallet db does not exist at '{}'", storage_path.display());
}
}
CliCommand::ChangePassword => {
Expand All @@ -234,29 +228,23 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
Some(wallet)
}
LinkedSecretManager::Stronghold { snapshot_path, .. } => {
return Err(Error::Miscellaneous(format!(
"Stronghold snapshot does not exist at '{}'",
snapshot_path.display()
)));
bail!("Stronghold snapshot does not exist at '{}'", snapshot_path.display());
}
_ => {
println_log_info!("only Stronghold password change supported");
return Ok(None);
}
}
} else {
return Err(Error::Miscellaneous(format!(
"wallet db does not exist at '{}'",
storage_path.display()
)));
bail!("wallet db does not exist at '{}'", storage_path.display());
}
}
CliCommand::Init(init_parameters) => {
if wallet_and_secret_manager.is_some() {
return Err(Error::Miscellaneous(format!(
bail!(
"cannot initialize: wallet db at '{}' already exists",
storage_path.display()
)));
);
}
let secret_manager = create_secret_manager(&init_parameters).await?;
let secret_manager_variant = secret_manager.to_string();
Expand All @@ -281,10 +269,7 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
crate::wallet_cli::node_info_command(&wallet).await?;
return Ok(None);
} else {
return Err(Error::Miscellaneous(format!(
"wallet db does not exist at '{}'",
storage_path.display()
)));
bail!("wallet db does not exist at '{}'", storage_path.display());
}
}
CliCommand::Restore { backup_path } => {
Expand Down Expand Up @@ -322,21 +307,15 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
set_node_url_command(&wallet, url).await?;
Some(wallet)
} else {
return Err(Error::Miscellaneous(format!(
"wallet db does not exist at '{}'",
storage_path.display()
)));
bail!("wallet db does not exist at '{}'", storage_path.display());
}
}
CliCommand::Sync => {
if let Some((wallet, _)) = wallet_and_secret_manager {
sync_command(&wallet).await?;
Some(wallet)
} else {
return Err(Error::Miscellaneous(format!(
"wallet db does not exist at '{}'",
storage_path.display()
)));
bail!("wallet db does not exist at '{}'", storage_path.display());
}
}
}
Expand Down Expand Up @@ -540,10 +519,7 @@ async fn create_secret_manager(init_params: &InitParameters) -> Result<SecretMan
let snapshot_path = Path::new(&init_params.stronghold_snapshot_path);

if snapshot_path.exists() {
return Err(Error::Miscellaneous(format!(
"cannot initialize: {} already exists",
snapshot_path.display()
)));
bail!("cannot initialize: {} already exists", snapshot_path.display());
}

let password = get_password("Stronghold password", true)?;
Expand Down
45 changes: 0 additions & 45 deletions cli/src/error.rs

This file was deleted.

Loading

0 comments on commit f459c48

Please sign in to comment.