From 192890162998e60276686bb335f22c81d3825682 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 26 Aug 2024 10:19:17 -0500 Subject: [PATCH 001/107] Define DecodingError in ibc-primitives --- .../ics721-nft-transfer/types/src/data.rs | 8 ++++-- .../ics721-nft-transfer/types/src/error.rs | 19 +++++++++---- .../ics721-nft-transfer/types/src/packet.rs | 24 ++++++++-------- ibc-primitives/src/types/error.rs | 28 +++++++++++++++++++ ibc-primitives/src/types/mod.rs | 2 ++ 5 files changed, 61 insertions(+), 20 deletions(-) create mode 100644 ibc-primitives/src/types/error.rs diff --git a/ibc-apps/ics721-nft-transfer/types/src/data.rs b/ibc-apps/ics721-nft-transfer/types/src/data.rs index 8150545bb..ea0d37126 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/data.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/data.rs @@ -6,7 +6,7 @@ use core::str::FromStr; use base64::prelude::BASE64_STANDARD; #[cfg(feature = "serde")] use base64::Engine; -use ibc_core::primitives::prelude::*; +use ibc_core::primitives::{prelude::*, DecodingError}; use mime::Mime; use crate::error::NftTransferError; @@ -97,8 +97,10 @@ impl FromStr for Ics721Data { type Err = NftTransferError; fn from_str(s: &str) -> Result { - serde_json::from_str(s).map_err(|e| NftTransferError::InvalidJsonData { - description: e.to_string(), + serde_json::from_str(s).map_err(|e| { + NftTransferError::DecodingError(DecodingError::InvalidJson { + description: e.to_string(), + }) }) } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 626eb9f6d..a94eb0941 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -1,24 +1,26 @@ //! Defines the Non-Fungible Token Transfer (ICS-721) error types. use core::convert::Infallible; -use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::error::IdentifierError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; +use ibc_core::primitives::DecodingError; + +use displaydoc::Display; #[derive(Display, Debug)] pub enum NftTransferError { /// context error: `{0}` ContextError(ContextError), + /// decoding error: `{0}` + DecodingError(DecodingError), /// invalid identifier: `{0}` InvalidIdentifier(IdentifierError), /// invalid URI: `{0}` InvalidUri(http::uri::InvalidUri), - /// invalid json data: `{description}` - InvalidJsonData { description: String }, /// invalid trace `{0}` InvalidTrace(String), /// missing destination channel `{channel_id}` on port `{port_id}` @@ -57,6 +59,7 @@ impl std::error::Error for NftTransferError { Self::ContextError(e) => Some(e), Self::InvalidUri(e) => Some(e), Self::InvalidIdentifier(e) => Some(e), + Self::DecodingError(e) => Some(e), _ => None, } } @@ -69,17 +72,23 @@ impl From for NftTransferError { } impl From for NftTransferError { - fn from(err: ContextError) -> NftTransferError { + fn from(err: ContextError) -> Self { Self::ContextError(err) } } impl From for NftTransferError { - fn from(err: IdentifierError) -> NftTransferError { + fn from(err: IdentifierError) -> Self { Self::InvalidIdentifier(err) } } +impl From for NftTransferError { + fn from(err: DecodingError) -> Self { + Self::DecodingError(err) + } +} + impl From for StatusValue { fn from(err: NftTransferError) -> Self { StatusValue::new(err.to_string()).expect("error message must not be empty") diff --git a/ibc-apps/ics721-nft-transfer/types/src/packet.rs b/ibc-apps/ics721-nft-transfer/types/src/packet.rs index 027e5fcb1..06009d372 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/packet.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/packet.rs @@ -2,10 +2,10 @@ use base64::prelude::BASE64_STANDARD; use base64::Engine; -use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; use ibc_core::primitives::Signer; +use ibc_core::primitives::{prelude::*, DecodingError}; use ibc_proto::ibc::applications::nft_transfer::v1::NonFungibleTokenPacketData as RawPacketData; use crate::class::{ClassData, ClassUri, PrefixedClassId}; @@ -128,13 +128,12 @@ impl TryFrom for PacketData { } else { let decoded = BASE64_STANDARD .decode(raw_pkt_data.class_data) - .map_err(|e| NftTransferError::InvalidJsonData { - description: e.to_string(), - })?; - let data_str = - String::from_utf8(decoded).map_err(|e| NftTransferError::InvalidJsonData { + .map_err(|e| DecodingError::InvalidJson { description: e.to_string(), })?; + let data_str = String::from_utf8(decoded).map_err(|e| DecodingError::InvalidUtf8 { + description: e.to_string(), + })?; Some(data_str.parse()?) }; @@ -145,13 +144,14 @@ impl TryFrom for PacketData { .token_data .iter() .map(|data| { - let decoded = BASE64_STANDARD.decode(data).map_err(|e| { - NftTransferError::InvalidJsonData { - description: e.to_string(), - } - })?; + let decoded = + BASE64_STANDARD + .decode(data) + .map_err(|e| DecodingError::InvalidJson { + description: e.to_string(), + })?; let data_str = - String::from_utf8(decoded).map_err(|e| NftTransferError::InvalidJsonData { + String::from_utf8(decoded).map_err(|e| DecodingError::InvalidUtf8 { description: e.to_string(), })?; data_str.parse() diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs new file mode 100644 index 000000000..a84815c6b --- /dev/null +++ b/ibc-primitives/src/types/error.rs @@ -0,0 +1,28 @@ +//! Foundational error types that are applicable across multiple ibc-rs workspaces. + +use alloc::string::String; + +use displaydoc::Display; + +/// Causes of decoding failures +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[derive(Debug, Display)] +pub enum DecodingError { + /// invalid identifier: `{0}` + InvalidIdentifier(String), + /// invalid field: `{0}` + InvalidField(String), + /// invalid JSON data: `{description}` + InvalidJson { description: String }, + /// invalid UTF-8 data: `{description}` + InvalidUtf8 { description: String }, + /// missing field: `{0}` + MissingField(String), + /// mismatched type URLs: expected `{expected}`, actual `{actual}` + MismatchedTypeUrls { expected: String, actual: String }, + /// failed to decode: `{description}` + FailedToDecode { description: String }, +} + +#[cfg(feature = "std")] +impl std::error::Error for DecodingError {} diff --git a/ibc-primitives/src/types/mod.rs b/ibc-primitives/src/types/mod.rs index 8df0d3c40..85849f97c 100644 --- a/ibc-primitives/src/types/mod.rs +++ b/ibc-primitives/src/types/mod.rs @@ -1,5 +1,7 @@ +mod error; mod signer; mod timestamp; +pub use error::*; pub use signer::*; pub use timestamp::*; From 527aa8f56e27db96981b5794ffcd79e1dde65246 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 26 Aug 2024 10:57:46 -0500 Subject: [PATCH 002/107] Utilize DecodingError in ics721 --- ibc-apps/ics721-nft-transfer/types/src/class.rs | 6 ++++-- ibc-apps/ics721-nft-transfer/types/src/error.rs | 10 +--------- .../ics721-nft-transfer/types/src/msgs/transfer.rs | 6 +++--- ibc-apps/ics721-nft-transfer/types/src/token.rs | 6 ++++-- ibc-primitives/Cargo.toml | 1 + ibc-primitives/src/types/error.rs | 10 ++++++---- 6 files changed, 19 insertions(+), 20 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/class.rs b/ibc-apps/ics721-nft-transfer/types/src/class.rs index 8a7c941e6..4d5a7f63f 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/class.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/class.rs @@ -5,9 +5,9 @@ use core::str::FromStr; use http::Uri; pub use ibc_app_transfer_types::{TracePath, TracePrefix}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; -use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; +use ibc_core::primitives::{prelude::*, DecodingError}; use ibc_proto::ibc::applications::nft_transfer::v1::ClassTrace as RawClassTrace; use crate::data::Data; @@ -248,7 +248,9 @@ impl FromStr for ClassUri { fn from_str(class_uri: &str) -> Result { match Uri::from_str(class_uri) { Ok(uri) => Ok(Self(uri)), - Err(err) => Err(NftTransferError::InvalidUri(err)), + Err(err) => Err(NftTransferError::DecodingError(DecodingError::InvalidUri( + err, + ))), } } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index a94eb0941..bf78bf405 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -17,10 +17,6 @@ pub enum NftTransferError { ContextError(ContextError), /// decoding error: `{0}` DecodingError(DecodingError), - /// invalid identifier: `{0}` - InvalidIdentifier(IdentifierError), - /// invalid URI: `{0}` - InvalidUri(http::uri::InvalidUri), /// invalid trace `{0}` InvalidTrace(String), /// missing destination channel `{channel_id}` on port `{port_id}` @@ -44,8 +40,6 @@ pub enum NftTransferError { FailedToDeserializeAck, /// failed to parse account ID FailedToParseAccount, - /// failed to decode raw msg: `{description}` - FailedToDecodeRawMsg { description: String }, /// channel cannot be closed UnsupportedClosedChannel, /// unknown msg type: `{0}` @@ -57,8 +51,6 @@ impl std::error::Error for NftTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::ContextError(e) => Some(e), - Self::InvalidUri(e) => Some(e), - Self::InvalidIdentifier(e) => Some(e), Self::DecodingError(e) => Some(e), _ => None, } @@ -79,7 +71,7 @@ impl From for NftTransferError { impl From for NftTransferError { fn from(err: IdentifierError) -> Self { - Self::InvalidIdentifier(err) + Self::DecodingError(DecodingError::InvalidIdentifier(err.to_string())) } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index 499d7d448..d6ef7bec5 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -4,7 +4,7 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; -use ibc_core::primitives::prelude::*; +use ibc_core::primitives::{prelude::*, DecodingError}; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::nft_transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::Protobuf; @@ -123,9 +123,9 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { TYPE_URL => MsgTransfer::decode_vec(&raw.value).map_err(|e| { - NftTransferError::FailedToDecodeRawMsg { + NftTransferError::DecodingError(DecodingError::FailedToDecodeRawMsg { description: e.to_string(), - } + }) }), _ => Err(NftTransferError::UnknownMsgType(raw.type_url)), } diff --git a/ibc-apps/ics721-nft-transfer/types/src/token.rs b/ibc-apps/ics721-nft-transfer/types/src/token.rs index fa11e93a1..31d245374 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/token.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/token.rs @@ -3,9 +3,9 @@ use core::fmt::{self, Display}; use core::str::FromStr; use http::Uri; -use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; +use ibc_core::primitives::{prelude::*, DecodingError}; use crate::data::Data; use crate::error::NftTransferError; @@ -182,7 +182,9 @@ impl FromStr for TokenUri { fn from_str(token_uri: &str) -> Result { match Uri::from_str(token_uri) { Ok(uri) => Ok(Self(uri)), - Err(err) => Err(NftTransferError::InvalidUri(err)), + Err(err) => Err(NftTransferError::DecodingError(DecodingError::InvalidUri( + err, + ))), } } } diff --git a/ibc-primitives/Cargo.toml b/ibc-primitives/Cargo.toml index 2c56cd6de..0e419381e 100644 --- a/ibc-primitives/Cargo.toml +++ b/ibc-primitives/Cargo.toml @@ -23,6 +23,7 @@ all-features = true borsh = { workspace = true, optional = true } derive_more = { workspace = true } displaydoc = { workspace = true } +http = { version = "1.1.0" } prost = { workspace = true } schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs index a84815c6b..37d4201f5 100644 --- a/ibc-primitives/src/types/error.rs +++ b/ibc-primitives/src/types/error.rs @@ -3,12 +3,12 @@ use alloc::string::String; use displaydoc::Display; +use http::uri::InvalidUri; /// Causes of decoding failures -#[cfg_attr(feature = "serde", derive(serde::Serialize))] #[derive(Debug, Display)] pub enum DecodingError { - /// invalid identifier: `{0}` + /// invalid identifier error: `{0}` InvalidIdentifier(String), /// invalid field: `{0}` InvalidField(String), @@ -16,12 +16,14 @@ pub enum DecodingError { InvalidJson { description: String }, /// invalid UTF-8 data: `{description}` InvalidUtf8 { description: String }, + /// invalid URI: `{0}` + InvalidUri(InvalidUri), /// missing field: `{0}` MissingField(String), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, - /// failed to decode: `{description}` - FailedToDecode { description: String }, + /// failed to decode raw msg: `{description}` + FailedToDecodeRawMsg { description: String }, } #[cfg(feature = "std")] From 7d24ab5a39efc72e50c34c69f7394de2b0eac5bf Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 26 Aug 2024 11:25:34 -0500 Subject: [PATCH 003/107] Start using DecodingError in ClientError --- .../ics07-tendermint/types/src/header.rs | 17 +++++++++++------ ibc-core/ics02-client/types/src/error.rs | 6 +++++- ibc-primitives/src/types/error.rs | 4 ++-- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index 72fc83333..f3313ab5b 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -6,8 +6,8 @@ use core::str::FromStr; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::Height; use ibc_core_host_types::identifiers::ChainId; -use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; +use ibc_primitives::{prelude::*, DecodingError}; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Header as RawHeader; use ibc_proto::Protobuf; @@ -199,15 +199,20 @@ impl TryFrom for Header { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_header(value: &[u8]) -> Result { - let header = Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), + fn decode_header(value: &[u8]) -> Result { + let header = Protobuf::::decode(value).map_err(|e| { + DecodingError::FailedToDecodeRawValue { + description: e.to_string(), + } })?; Ok(header) } match raw.type_url.as_str() { - TENDERMINT_HEADER_TYPE_URL => decode_header(&raw.value), - _ => Err(ClientError::InvalidHeaderType(raw.type_url)), + TENDERMINT_HEADER_TYPE_URL => decode_header(&raw.value).map_err(ClientError::Decoding), + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: TENDERMINT_HEADER_TYPE_URL.to_string(), + actual: raw.type_url.to_string(), + })), } } } diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 9b16557ad..f3abf6b1f 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -7,7 +7,7 @@ use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::IdentifierError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; -use ibc_primitives::Timestamp; +use ibc_primitives::{DecodingError, Timestamp}; use super::status::Status; use crate::height::Height; @@ -17,6 +17,8 @@ use crate::height::Height; pub enum ClientError { /// upgrade client error: `{0}` Upgrade(UpgradeClientError), + /// decoding error: `{0}` + Decoding(DecodingError), /// invalid client status: `{0}` InvalidStatus(Status), /// invalid trust threshold: `{numerator}`/`{denominator}` @@ -29,6 +31,7 @@ pub enum ClientError { InvalidHeaderType(String), /// invalid update client message InvalidUpdateClientMessage, + // TODO(seanchen1991): Should this be removed in favor of DecodingError::InvalidIdentifier? /// invalid client identifier: `{0}` InvalidClientIdentifier(IdentifierError), /// invalid raw header: `{description}` @@ -114,6 +117,7 @@ impl std::error::Error for ClientError { match &self { Self::InvalidClientIdentifier(e) => Some(e), Self::FailedICS23Verification(e) => Some(e), + Self::Decoding(e) => Some(e), _ => None, } } diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs index 37d4201f5..21273cc8e 100644 --- a/ibc-primitives/src/types/error.rs +++ b/ibc-primitives/src/types/error.rs @@ -22,8 +22,8 @@ pub enum DecodingError { MissingField(String), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, - /// failed to decode raw msg: `{description}` - FailedToDecodeRawMsg { description: String }, + /// failed to decode a raw value: `{description}` + FailedToDecodeRawValue { description: String }, } #[cfg(feature = "std")] From fb923d4308e42f2ad1e3fe091bb3e3428689a09c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 26 Aug 2024 14:42:39 -0500 Subject: [PATCH 004/107] Define StatusError type --- .../ics721-nft-transfer/types/src/class.rs | 4 +-- .../ics721-nft-transfer/types/src/data.rs | 2 +- .../ics721-nft-transfer/types/src/error.rs | 8 ++--- .../types/src/msgs/transfer.rs | 2 +- .../ics721-nft-transfer/types/src/token.rs | 4 +-- .../types/src/consensus_state.rs | 18 +++++----- .../ics07-tendermint/types/src/header.rs | 6 +--- .../ics08-wasm/types/src/consensus_state.rs | 20 +++++------ ibc-core/ics02-client/types/src/error.rs | 8 +++-- ibc-core/ics02-client/types/src/status.rs | 33 +++++++++++++------ ibc-core/ics25-handler/types/src/error.rs | 1 + ibc-primitives/Cargo.toml | 3 +- ibc-primitives/src/types/error.rs | 16 +++++++-- .../testapp/ibc/clients/mock/client_state.rs | 17 ++++++---- .../src/testapp/ibc/clients/mock/header.rs | 11 +++---- .../testapp/ibc/clients/mock/misbehaviour.rs | 17 ++++++---- 16 files changed, 99 insertions(+), 71 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/class.rs b/ibc-apps/ics721-nft-transfer/types/src/class.rs index 4d5a7f63f..98ae0a765 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/class.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/class.rs @@ -248,9 +248,7 @@ impl FromStr for ClassUri { fn from_str(class_uri: &str) -> Result { match Uri::from_str(class_uri) { Ok(uri) => Ok(Self(uri)), - Err(err) => Err(NftTransferError::DecodingError(DecodingError::InvalidUri( - err, - ))), + Err(err) => Err(NftTransferError::Decoding(DecodingError::InvalidUri(err))), } } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/data.rs b/ibc-apps/ics721-nft-transfer/types/src/data.rs index ea0d37126..8b91d3025 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/data.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/data.rs @@ -98,7 +98,7 @@ impl FromStr for Ics721Data { fn from_str(s: &str) -> Result { serde_json::from_str(s).map_err(|e| { - NftTransferError::DecodingError(DecodingError::InvalidJson { + NftTransferError::Decoding(DecodingError::InvalidJson { description: e.to_string(), }) }) diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index bf78bf405..637f13f1d 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -16,7 +16,7 @@ pub enum NftTransferError { /// context error: `{0}` ContextError(ContextError), /// decoding error: `{0}` - DecodingError(DecodingError), + Decoding(DecodingError), /// invalid trace `{0}` InvalidTrace(String), /// missing destination channel `{channel_id}` on port `{port_id}` @@ -51,7 +51,7 @@ impl std::error::Error for NftTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::ContextError(e) => Some(e), - Self::DecodingError(e) => Some(e), + Self::Decoding(e) => Some(e), _ => None, } } @@ -71,13 +71,13 @@ impl From for NftTransferError { impl From for NftTransferError { fn from(err: IdentifierError) -> Self { - Self::DecodingError(DecodingError::InvalidIdentifier(err.to_string())) + Self::Decoding(DecodingError::InvalidIdentifier(err.to_string())) } } impl From for NftTransferError { fn from(err: DecodingError) -> Self { - Self::DecodingError(err) + Self::Decoding(err) } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index d6ef7bec5..c98aceb5f 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -123,7 +123,7 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { TYPE_URL => MsgTransfer::decode_vec(&raw.value).map_err(|e| { - NftTransferError::DecodingError(DecodingError::FailedToDecodeRawMsg { + NftTransferError::Decoding(DecodingError::FailedToDecodeProto { description: e.to_string(), }) }), diff --git a/ibc-apps/ics721-nft-transfer/types/src/token.rs b/ibc-apps/ics721-nft-transfer/types/src/token.rs index 31d245374..374b3e54b 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/token.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/token.rs @@ -182,9 +182,7 @@ impl FromStr for TokenUri { fn from_str(token_uri: &str) -> Result { match Uri::from_str(token_uri) { Ok(uri) => Ok(Self(uri)), - Err(err) => Err(NftTransferError::DecodingError(DecodingError::InvalidUri( - err, - ))), + Err(err) => Err(NftTransferError::Decoding(DecodingError::InvalidUri(err))), } } } diff --git a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs index ec66fb264..e12fe66dc 100644 --- a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs @@ -2,7 +2,7 @@ use ibc_core_client_types::error::ClientError; use ibc_core_commitment_types::commitment::CommitmentRoot; -use ibc_primitives::prelude::*; +use ibc_primitives::{prelude::*, DecodingError}; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::ConsensusState as RawConsensusState; use ibc_proto::Protobuf; @@ -107,17 +107,19 @@ impl TryFrom for ConsensusState { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_consensus_state(value: &[u8]) -> Result { - let client_state = - Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), - })?; + fn decode_consensus_state(value: &[u8]) -> Result { + let client_state = Protobuf::::decode(value)?; Ok(client_state) } match raw.type_url.as_str() { - TENDERMINT_CONSENSUS_STATE_TYPE_URL => decode_consensus_state(&raw.value), - _ => Err(ClientError::InvalidConsensusStateType(raw.type_url)), + TENDERMINT_CONSENSUS_STATE_TYPE_URL => { + decode_consensus_state(&raw.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: TENDERMINT_CONSENSUS_STATE_TYPE_URL.to_string(), + actual: raw.type_url.to_string(), + })), } } } diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index f3313ab5b..15dd6315a 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -200,11 +200,7 @@ impl TryFrom for Header { fn try_from(raw: Any) -> Result { fn decode_header(value: &[u8]) -> Result { - let header = Protobuf::::decode(value).map_err(|e| { - DecodingError::FailedToDecodeRawValue { - description: e.to_string(), - } - })?; + let header = Protobuf::::decode(value)?; Ok(header) } match raw.type_url.as_str() { diff --git a/ibc-clients/ics08-wasm/types/src/consensus_state.rs b/ibc-clients/ics08-wasm/types/src/consensus_state.rs index 597cc4e87..9d50f7177 100644 --- a/ibc-clients/ics08-wasm/types/src/consensus_state.rs +++ b/ibc-clients/ics08-wasm/types/src/consensus_state.rs @@ -1,8 +1,8 @@ //! Defines the consensus state type for the ICS-08 Wasm light client. use ibc_core_client::types::error::ClientError; -use ibc_primitives::prelude::*; use ibc_primitives::proto::{Any, Protobuf}; +use ibc_primitives::{prelude::*, DecodingError}; use ibc_proto::ibc::lightclients::wasm::v1::ConsensusState as RawConsensusState; #[cfg(feature = "serde")] @@ -57,18 +57,18 @@ impl TryFrom for ConsensusState { type Error = ClientError; fn try_from(any: Any) -> Result { - fn decode_consensus_state(value: &[u8]) -> Result { - let consensus_state = - Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), - })?; + fn decode_consensus_state(value: &[u8]) -> Result { + let consensus_state = Protobuf::::decode(value)?; Ok(consensus_state) } match any.type_url.as_str() { - WASM_CONSENSUS_STATE_TYPE_URL => decode_consensus_state(&any.value), - _ => Err(ClientError::Other { - description: "type_url does not match".into(), - }), + WASM_CONSENSUS_STATE_TYPE_URL => { + decode_consensus_state(&any.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: WASM_CONSENSUS_STATE_TYPE_URL.to_string(), + actual: any.type_url.to_string(), + })), } } } diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index f3abf6b1f..d4ea1a9e5 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -27,8 +27,6 @@ pub enum ClientError { InvalidClientStateType(String), /// invalid client consensus state type: `{0}` InvalidConsensusStateType(String), - /// invalid header type: `{0}` - InvalidHeaderType(String), /// invalid update client message InvalidUpdateClientMessage, // TODO(seanchen1991): Should this be removed in favor of DecodingError::InvalidIdentifier? @@ -111,6 +109,12 @@ impl From for ClientError { } } +impl From for ClientError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { diff --git a/ibc-core/ics02-client/types/src/status.rs b/ibc-core/ics02-client/types/src/status.rs index 5fe9b9e0a..03833dcad 100644 --- a/ibc-core/ics02-client/types/src/status.rs +++ b/ibc-core/ics02-client/types/src/status.rs @@ -1,10 +1,9 @@ use core::fmt::{Debug, Display, Formatter}; use core::str::FromStr; +use displaydoc::Display; use ibc_primitives::prelude::*; -use crate::error::ClientError; - /// `UpdateKind` represents the 2 ways that a client can be updated /// in IBC: either through a `MsgUpdateClient`, or a `MsgSubmitMisbehaviour`. #[derive(Clone, Debug, PartialEq, Eq)] @@ -33,6 +32,15 @@ pub enum Status { Unauthorized, } +/// Encapsulates Status-related errors +#[derive(Debug, Display)] +pub enum StatusError { + /// invalid client status: `{0}` + InvalidStatus(String), + /// mismatched client status: expected `{expected}`, actual `{actual}` + MismatchedStatus { expected: Status, actual: Status }, +} + impl Status { pub fn is_active(&self) -> bool { *self == Status::Active @@ -47,18 +55,25 @@ impl Status { } /// Checks whether the status is active; returns `Err` if not. - pub fn verify_is_active(&self) -> Result<(), ClientError> { + pub fn verify_is_active(&self) -> Result<(), StatusError> { match self { Self::Active => Ok(()), - &status => Err(ClientError::InvalidStatus(status)), + &status => Err(StatusError::MismatchedStatus { + expected: Status::Active, + actual: status, + }), } } /// Checks whether the client is either frozen or expired; returns `Err` if not. - pub fn verify_is_inactive(&self) -> Result<(), ClientError> { + pub fn verify_is_inactive(&self) -> Result<(), StatusError> { match self { Self::Frozen | Self::Expired => Ok(()), - &status => Err(ClientError::InvalidStatus(status)), + &status => Err(StatusError::MismatchedStatus { + // `Status::Expired` is also allowed in this context + expected: Status::Frozen, + actual: status, + }), } } } @@ -70,7 +85,7 @@ impl Display for Status { } impl FromStr for Status { - type Err = ClientError; + type Err = StatusError; fn from_str(s: &str) -> Result { match s { @@ -78,9 +93,7 @@ impl FromStr for Status { "FROZEN" => Ok(Status::Frozen), "EXPIRED" => Ok(Status::Expired), "UNAUTHORIZED" => Ok(Status::Unauthorized), - _ => Err(ClientError::Other { - description: format!("invalid status string: {s}"), - }), + _ => Err(StatusError::InvalidStatus(s.to_string())), } } } diff --git a/ibc-core/ics25-handler/types/src/error.rs b/ibc-core/ics25-handler/types/src/error.rs index 5bea4b54d..84bc0b939 100644 --- a/ibc-core/ics25-handler/types/src/error.rs +++ b/ibc-core/ics25-handler/types/src/error.rs @@ -23,6 +23,7 @@ pub enum ContextError { RouterError(RouterError), } +// TODO(seanchen1991): Figure out how to remove this impl From for ClientError { fn from(context_error: ContextError) -> Self { match context_error { diff --git a/ibc-primitives/Cargo.toml b/ibc-primitives/Cargo.toml index 0e419381e..e4a5d723d 100644 --- a/ibc-primitives/Cargo.toml +++ b/ibc-primitives/Cargo.toml @@ -33,7 +33,8 @@ time = { version = ">=0.3.0, <0.3.37", default-features = false } ibc-proto = { workspace = true } # cosmos dependencies -tendermint = { workspace = true } +tendermint = { workspace = true } +tendermint-proto = { workspace = true } # parity dependencies parity-scale-codec = { workspace = true, optional = true } diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs index 21273cc8e..b8aa169e5 100644 --- a/ibc-primitives/src/types/error.rs +++ b/ibc-primitives/src/types/error.rs @@ -1,10 +1,12 @@ //! Foundational error types that are applicable across multiple ibc-rs workspaces. -use alloc::string::String; +use alloc::string::{String, ToString}; use displaydoc::Display; use http::uri::InvalidUri; +use tendermint_proto::Error as ProtoError; + /// Causes of decoding failures #[derive(Debug, Display)] pub enum DecodingError { @@ -22,8 +24,16 @@ pub enum DecodingError { MissingField(String), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, - /// failed to decode a raw value: `{description}` - FailedToDecodeRawValue { description: String }, + /// failed to decode proto value: `{description}` + FailedToDecodeProto { description: String }, +} + +impl From for DecodingError { + fn from(e: ProtoError) -> Self { + Self::FailedToDecodeProto { + description: e.to_string(), + } + } } #[cfg(feature = "std")] diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index 780392577..01566b1b8 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -14,6 +14,7 @@ use ibc::core::host::types::path::{ClientConsensusStatePath, ClientStatePath, Pa use ibc::core::primitives::prelude::*; use ibc::core::primitives::Timestamp; use ibc::primitives::proto::{Any, Protobuf}; +use ibc::primitives::DecodingError; use crate::testapp::ibc::clients::mock::client_state::client_type as mock_client_type; use crate::testapp::ibc::clients::mock::consensus_state::MockConsensusState; @@ -127,16 +128,18 @@ impl TryFrom for MockClientState { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_client_state(value: &[u8]) -> Result { - let client_state = - Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), - })?; + fn decode_client_state(value: &[u8]) -> Result { + let client_state = Protobuf::::decode(value)?; Ok(client_state) } match raw.type_url.as_str() { - MOCK_CLIENT_STATE_TYPE_URL => decode_client_state(&raw.value), - _ => Err(ClientError::InvalidClientStateType(raw.type_url)), + MOCK_CLIENT_STATE_TYPE_URL => { + decode_client_state(&raw.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: MOCK_CLIENT_STATE_TYPE_URL.to_string(), + actual: raw.type_url.to_string(), + })), } } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs index fac7bf00c..f943476ce 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs @@ -95,12 +95,11 @@ impl TryFrom for MockHeader { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - MOCK_HEADER_TYPE_URL => Ok(Protobuf::::decode_vec(&raw.value).map_err( - |e| ClientError::InvalidRawHeader { - description: e.to_string(), - }, - )?), - _ => Err(ClientError::InvalidHeaderType(raw.type_url)), + MOCK_HEADER_TYPE_URL => Ok(Protobuf::::decode_vec(&raw.value)?), + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: MOCK_HEADER_TYPE_URL.to_string(), + actual: raw.type_url.to_string(), + })), } } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs index e07c310a1..24d355ebd 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs @@ -2,6 +2,7 @@ use ibc::core::client::types::error::ClientError; use ibc::core::host::types::identifiers::ClientId; use ibc::core::primitives::prelude::*; use ibc::primitives::proto::{Any, Protobuf}; +use ibc::primitives::DecodingError; use crate::testapp::ibc::clients::mock::header::MockHeader; use crate::testapp::ibc::clients::mock::proto::Misbehaviour as RawMisbehaviour; @@ -52,16 +53,18 @@ impl TryFrom for Misbehaviour { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_misbehaviour(value: &[u8]) -> Result { - let raw_misbehaviour = - Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), - })?; + fn decode_misbehaviour(value: &[u8]) -> Result { + let raw_misbehaviour = Protobuf::::decode(value)?; Ok(raw_misbehaviour) } match raw.type_url.as_str() { - MOCK_MISBEHAVIOUR_TYPE_URL => decode_misbehaviour(&raw.value), - _ => Err(ClientError::InvalidMisbehaviourType(raw.type_url)), + MOCK_MISBEHAVIOUR_TYPE_URL => { + decode_misbehaviour(&raw.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: MOCK_MISBEHAVIOUR_TYPE_URL.to_string(), + actual: raw.type_url.to_string(), + })), } } } From 529163de7b62aab127a22b00b02f7ea85c6d6536 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 26 Aug 2024 15:45:37 -0500 Subject: [PATCH 005/107] Wire up StatusError --- .../src/client_state/common.rs | 6 ++++-- .../types/src/consensus_state.rs | 2 +- .../ics07-tendermint/types/src/header.rs | 2 +- .../types/src/misbehaviour.rs | 18 ++++++++++-------- .../ics02-client/src/handler/create_client.rs | 4 ++-- .../src/handler/recover_client.rs | 6 ++++-- .../ics02-client/src/handler/update_client.rs | 3 ++- .../src/handler/upgrade_client.rs | 3 ++- ibc-core/ics02-client/types/src/error.rs | 13 ++++++++++--- ibc-core/ics02-client/types/src/status.rs | 18 +++++++----------- .../src/handler/conn_open_ack.rs | 4 +++- .../src/handler/conn_open_confirm.rs | 5 ++++- .../src/handler/conn_open_init.rs | 4 +++- .../src/handler/conn_open_try.rs | 4 +++- .../src/handler/acknowledgement.rs | 5 ++++- .../src/handler/chan_close_confirm.rs | 5 ++++- .../src/handler/chan_close_init.rs | 4 +++- .../src/handler/chan_open_ack.rs | 5 ++++- .../src/handler/chan_open_confirm.rs | 5 ++++- .../src/handler/chan_open_init.rs | 4 +++- .../src/handler/chan_open_try.rs | 4 +++- .../ics04-channel/src/handler/recv_packet.rs | 4 +++- .../ics04-channel/src/handler/send_packet.rs | 4 +++- ibc-core/ics04-channel/src/handler/timeout.rs | 4 +++- .../src/handler/timeout_on_close.rs | 4 +++- .../cosmos/src/validate_self_client.rs | 4 ++-- .../testapp/ibc/clients/mock/client_state.rs | 2 +- .../ibc/clients/mock/consensus_state.rs | 19 ++++++++++--------- .../src/testapp/ibc/clients/mock/header.rs | 2 +- .../testapp/ibc/clients/mock/misbehaviour.rs | 2 +- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 2 +- 31 files changed, 109 insertions(+), 62 deletions(-) diff --git a/ibc-clients/ics07-tendermint/src/client_state/common.rs b/ibc-clients/ics07-tendermint/src/client_state/common.rs index 66ac52aec..3671e6bd6 100644 --- a/ibc-clients/ics07-tendermint/src/client_state/common.rs +++ b/ibc-clients/ics07-tendermint/src/client_state/common.rs @@ -4,7 +4,7 @@ use ibc_client_tendermint_types::{client_type as tm_client_type, ClientState as use ibc_core_client::context::client_state::ClientStateCommon; use ibc_core_client::context::consensus_state::ConsensusState; use ibc_core_client::types::error::{ClientError, UpgradeClientError}; -use ibc_core_client::types::{Height, Status}; +use ibc_core_client::types::{Height, Status, StatusError}; use ibc_core_commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; @@ -166,7 +166,9 @@ pub fn verify_consensus_state( }; if consensus_state_status(&tm_consensus_state, host_timestamp, trusting_period)?.is_expired() { - return Err(ClientError::InvalidStatus(Status::Expired)); + return Err(ClientError::Status(StatusError::UnexpectedStatus( + Status::Expired, + ))); } Ok(()) diff --git a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs index e12fe66dc..82c6b2c7a 100644 --- a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs @@ -118,7 +118,7 @@ impl TryFrom for ConsensusState { } _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: TENDERMINT_CONSENSUS_STATE_TYPE_URL.to_string(), - actual: raw.type_url.to_string(), + actual: raw.type_url, })), } } diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index 15dd6315a..e15044653 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -207,7 +207,7 @@ impl TryFrom for Header { TENDERMINT_HEADER_TYPE_URL => decode_header(&raw.value).map_err(ClientError::Decoding), _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: TENDERMINT_HEADER_TYPE_URL.to_string(), - actual: raw.type_url.to_string(), + actual: raw.type_url, })), } } diff --git a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs index dc35a34ec..fd314b6eb 100644 --- a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs +++ b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs @@ -2,7 +2,7 @@ use ibc_core_client_types::error::ClientError; use ibc_core_host_types::identifiers::ClientId; -use ibc_primitives::prelude::*; +use ibc_primitives::{prelude::*, DecodingError}; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Misbehaviour as RawMisbehaviour; use ibc_proto::Protobuf; @@ -114,16 +114,18 @@ impl TryFrom for Misbehaviour { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_misbehaviour(value: &[u8]) -> Result { - let misbehaviour = - Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), - })?; + fn decode_misbehaviour(value: &[u8]) -> Result { + let misbehaviour = Protobuf::::decode(value)?; Ok(misbehaviour) } match raw.type_url.as_str() { - TENDERMINT_MISBEHAVIOUR_TYPE_URL => decode_misbehaviour(&raw.value), - _ => Err(ClientError::InvalidMisbehaviourType(raw.type_url)), + TENDERMINT_MISBEHAVIOUR_TYPE_URL => { + decode_misbehaviour(&raw.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: TENDERMINT_MISBEHAVIOUR_TYPE_URL.to_string(), + actual: raw.type_url, + })), } } } diff --git a/ibc-core/ics02-client/src/handler/create_client.rs b/ibc-core/ics02-client/src/handler/create_client.rs index 263f8ffa4..d775ddf02 100644 --- a/ibc-core/ics02-client/src/handler/create_client.rs +++ b/ibc-core/ics02-client/src/handler/create_client.rs @@ -4,7 +4,7 @@ use ibc_core_client_context::prelude::*; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::events::CreateClient; use ibc_core_client_types::msgs::MsgCreateClient; -use ibc_core_client_types::Status; +use ibc_core_client_types::{Status, StatusError}; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::{ClientStateMut, ClientStateRef, ExecutionContext, ValidationContext}; @@ -36,7 +36,7 @@ where let status = client_state.status(client_val_ctx, &client_id)?; if status.is_frozen() { - return Err(ClientError::InvalidStatus(Status::Frozen).into()); + return Err(ClientError::Status(StatusError::UnexpectedStatus(Status::Frozen)).into()); }; let host_timestamp = ctx.host_timestamp()?; diff --git a/ibc-core/ics02-client/src/handler/recover_client.rs b/ibc-core/ics02-client/src/handler/recover_client.rs index 7994edab3..8c24bbbce 100644 --- a/ibc-core/ics02-client/src/handler/recover_client.rs +++ b/ibc-core/ics02-client/src/handler/recover_client.rs @@ -39,12 +39,14 @@ where substitute_client_state .status(ctx.get_client_validation_context(), &substitute_client_id)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; // TODO(seanchen1991): Why is this `map_err` necessary? // Verify that the subject client is inactive, i.e., that it is either frozen or expired subject_client_state .status(ctx.get_client_validation_context(), &subject_client_id)? - .verify_is_inactive()?; + .verify_is_inactive() + .map_err(ClientError::Status)?; // Check that the subject client state and substitute client states match, i.e., that // all their respective client state parameters match except for frozen height, latest diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index 66ce95ce1..f67debcbd 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -26,7 +26,8 @@ where client_state .status(client_val_ctx, &client_id)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; let client_message = msg.client_message(); diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index 7dce4cdaa..c79cbcb93 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -28,7 +28,8 @@ where // Check if the client is active. old_client_state .status(client_val_ctx, &client_id)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; // Read the latest consensus state from the host chain store. let old_client_cons_state_path = ClientConsensusStatePath::new( diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index d4ea1a9e5..aaa085331 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -9,8 +9,8 @@ use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::{DecodingError, Timestamp}; -use super::status::Status; use crate::height::Height; +use crate::StatusError; /// Encodes all the possible client errors #[derive(Debug, Display)] @@ -19,8 +19,8 @@ pub enum ClientError { Upgrade(UpgradeClientError), /// decoding error: `{0}` Decoding(DecodingError), - /// invalid client status: `{0}` - InvalidStatus(Status), + /// client status error: `{0}` + Status(StatusError), /// invalid trust threshold: `{numerator}`/`{denominator}` InvalidTrustThreshold { numerator: u64, denominator: u64 }, /// invalid client state type: `{0}` @@ -115,12 +115,19 @@ impl From for ClientError { } } +impl From for ClientError { + fn from(e: StatusError) -> Self { + Self::Status(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::InvalidClientIdentifier(e) => Some(e), Self::FailedICS23Verification(e) => Some(e), + Self::Status(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-core/ics02-client/types/src/status.rs b/ibc-core/ics02-client/types/src/status.rs index 03833dcad..e63df1793 100644 --- a/ibc-core/ics02-client/types/src/status.rs +++ b/ibc-core/ics02-client/types/src/status.rs @@ -37,8 +37,8 @@ pub enum Status { pub enum StatusError { /// invalid client status: `{0}` InvalidStatus(String), - /// mismatched client status: expected `{expected}`, actual `{actual}` - MismatchedStatus { expected: Status, actual: Status }, + /// unexpected status `{0}` found + UnexpectedStatus(Status), } impl Status { @@ -58,10 +58,7 @@ impl Status { pub fn verify_is_active(&self) -> Result<(), StatusError> { match self { Self::Active => Ok(()), - &status => Err(StatusError::MismatchedStatus { - expected: Status::Active, - actual: status, - }), + &status => Err(StatusError::UnexpectedStatus(status)), } } @@ -69,11 +66,7 @@ impl Status { pub fn verify_is_inactive(&self) -> Result<(), StatusError> { match self { Self::Frozen | Self::Expired => Ok(()), - &status => Err(StatusError::MismatchedStatus { - // `Status::Expired` is also allowed in this context - expected: Status::Frozen, - actual: status, - }), + &status => Err(StatusError::UnexpectedStatus(status)), } } } @@ -97,3 +90,6 @@ impl FromStr for Status { } } } + +#[cfg(feature = "std")] +impl std::error::Error for StatusError {} diff --git a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs index a061b3f06..05bdc0fcb 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs @@ -67,7 +67,9 @@ where client_state_of_b_on_a .status(client_val_ctx_a, vars.client_id_on_a())? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_b_on_a.validate_proof_height(msg.proofs_height_on_b)?; let client_cons_state_path_on_a = ClientConsensusStatePath::new( diff --git a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs index e1751cfc9..2dd0105f3 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs @@ -1,6 +1,7 @@ //! Protocol logic specific to processing ICS3 messages of type `MsgConnectionOpenConfirm`. use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection_types::error::ConnectionError; use ibc_core_connection_types::events::OpenConfirm; use ibc_core_connection_types::msgs::MsgConnectionOpenConfirm; @@ -47,7 +48,9 @@ where client_state_of_a_on_b .status(client_val_ctx_b, client_id_on_b)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = ClientConsensusStatePath::new( diff --git a/ibc-core/ics03-connection/src/handler/conn_open_init.rs b/ibc-core/ics03-connection/src/handler/conn_open_init.rs index 8d4286616..ad6c8de4f 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_init.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_init.rs @@ -1,5 +1,6 @@ //! Protocol logic specific to ICS3 messages of type `MsgConnectionOpenInit`. use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection_types::events::OpenInit; use ibc_core_connection_types::msgs::MsgConnectionOpenInit; use ibc_core_connection_types::{ConnectionEnd, Counterparty, State}; @@ -23,7 +24,8 @@ where client_state_of_b_on_a .status(client_val_ctx_a, &msg.client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; if let Some(version) = msg.version { version.verify_is_supported(&ctx_a.get_compatible_versions())?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_try.rs b/ibc-core/ics03-connection/src/handler/conn_open_try.rs index 34bb18ae0..606a55a49 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_try.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_try.rs @@ -67,7 +67,9 @@ where client_state_of_a_on_b .status(client_val_ctx_b, &msg.client_id_on_b)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_a_on_b.validate_proof_height(msg.proofs_height_on_a)?; let client_cons_state_path_on_b = ClientConsensusStatePath::new( diff --git a/ibc-core/ics04-channel/src/handler/acknowledgement.rs b/ibc-core/ics04-channel/src/handler/acknowledgement.rs index 68bc43128..659befb1b 100644 --- a/ibc-core/ics04-channel/src/handler/acknowledgement.rs +++ b/ibc-core/ics04-channel/src/handler/acknowledgement.rs @@ -4,6 +4,7 @@ use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_channel_types::events::AcknowledgePacket; use ibc_core_channel_types::msgs::MsgAcknowledgement; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::State as ConnectionState; use ibc_core_handler_types::error::ContextError; @@ -176,7 +177,9 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; let client_cons_state_path_on_a = ClientConsensusStatePath::new( diff --git a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs index 4f2dc0293..25f8ebbc9 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs @@ -5,6 +5,7 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::CloseConfirm; use ibc_core_channel_types::msgs::MsgChannelCloseConfirm; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -113,7 +114,9 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = ClientConsensusStatePath::new( diff --git a/ibc-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-core/ics04-channel/src/handler/chan_close_init.rs index 6bdab73f6..dbe604ef6 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_init.rs @@ -4,6 +4,7 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::CloseInit; use ibc_core_channel_types::msgs::MsgChannelCloseInit; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; @@ -110,7 +111,8 @@ where let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; Ok(()) } diff --git a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs index 9369733a0..34d43c33a 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs @@ -4,6 +4,7 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::OpenAck; use ibc_core_channel_types::msgs::MsgChannelOpenAck; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -114,7 +115,9 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; let client_cons_state_path_on_a = ClientConsensusStatePath::new( diff --git a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs index 9d375a295..a3d05dddf 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs @@ -5,6 +5,7 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::OpenConfirm; use ibc_core_channel_types::msgs::MsgChannelOpenConfirm; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -118,7 +119,9 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; + client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = ClientConsensusStatePath::new( diff --git a/ibc-core/ics04-channel/src/handler/chan_open_init.rs b/ibc-core/ics04-channel/src/handler/chan_open_init.rs index 58a161d0b..a8b917cf9 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_init.rs @@ -4,6 +4,7 @@ use ibc_core_channel_types::channel::{ChannelEnd, Counterparty, State}; use ibc_core_channel_types::events::OpenInit; use ibc_core_channel_types::msgs::MsgChannelOpenInit; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::ChannelId; @@ -125,7 +126,8 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; let conn_version = conn_end_on_a.versions(); diff --git a/ibc-core/ics04-channel/src/handler/chan_open_try.rs b/ibc-core/ics04-channel/src/handler/chan_open_try.rs index 48138ce69..54807c1be 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_try.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_try.rs @@ -5,6 +5,7 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::OpenTry; use ibc_core_channel_types::msgs::MsgChannelOpenTry; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -140,7 +141,8 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index f3229f493..e9f7b7101 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -5,6 +5,7 @@ use ibc_core_channel_types::events::{ReceivePacket, WriteAcknowledgement}; use ibc_core_channel_types::msgs::MsgRecvPacket; use ibc_core_channel_types::packet::Receipt; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::State as ConnectionState; use ibc_core_handler_types::error::ContextError; @@ -186,7 +187,8 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/send_packet.rs b/ibc-core/ics04-channel/src/handler/send_packet.rs index 6680bf6fb..714242383 100644 --- a/ibc-core/ics04-channel/src/handler/send_packet.rs +++ b/ibc-core/ics04-channel/src/handler/send_packet.rs @@ -4,6 +4,7 @@ use ibc_core_channel_types::error::PacketError; use ibc_core_channel_types::events::SendPacket; use ibc_core_channel_types::packet::Packet; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ @@ -59,7 +60,8 @@ pub fn send_packet_validate( client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; let latest_height_on_a = client_state_of_b_on_a.latest_height(); diff --git a/ibc-core/ics04-channel/src/handler/timeout.rs b/ibc-core/ics04-channel/src/handler/timeout.rs index 9ce98bc0a..5963f810a 100644 --- a/ibc-core/ics04-channel/src/handler/timeout.rs +++ b/ibc-core/ics04-channel/src/handler/timeout.rs @@ -4,6 +4,7 @@ use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_channel_types::events::{ChannelClosed, TimeoutPacket}; use ibc_core_channel_types::msgs::{MsgTimeout, MsgTimeoutOnClose}; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; @@ -186,7 +187,8 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs index c52225f81..eda55002a 100644 --- a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs +++ b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs @@ -3,6 +3,7 @@ use ibc_core_channel_types::commitment::compute_packet_commitment; use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_channel_types::msgs::MsgTimeoutOnClose; use ibc_core_client::context::prelude::*; +use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -70,7 +71,8 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; + .verify_is_active() + .map_err(ClientError::Status)?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index d2f2d2eba..446c3ebbf 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -2,7 +2,7 @@ use core::time::Duration; use ibc_client_tendermint::types::ClientState as TmClientState; use ibc_core_client_types::error::ClientError; -use ibc_core_client_types::{Height, Status}; +use ibc_core_client_types::{Height, Status, StatusError}; use ibc_core_commitment_types::specs::ProofSpecs; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -25,7 +25,7 @@ pub trait ValidateSelfClientContext { .map_err(ClientError::from)?; if client_state_of_host_on_counterparty.is_frozen() { - return Err(ClientError::InvalidStatus(Status::Frozen).into()); + return Err(ClientError::Status(StatusError::UnexpectedStatus(Status::Frozen)).into()); } let self_chain_id = self.chain_id(); diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index 01566b1b8..d8f9685ff 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -138,7 +138,7 @@ impl TryFrom for MockClientState { } _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: MOCK_CLIENT_STATE_TYPE_URL.to_string(), - actual: raw.type_url.to_string(), + actual: raw.type_url, })), } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs index 96273f780..1121e5147 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs @@ -4,6 +4,7 @@ use ibc::core::commitment_types::commitment::CommitmentRoot; use ibc::core::primitives::prelude::*; use ibc::core::primitives::Timestamp; use ibc::primitives::proto::{Any, Protobuf}; +use ibc::primitives::DecodingError; use crate::testapp::ibc::clients::mock::header::MockHeader; use crate::testapp::ibc::clients::mock::proto::ConsensusState as RawMockConsensusState; @@ -64,18 +65,18 @@ impl TryFrom for MockConsensusState { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_consensus_state(value: &[u8]) -> Result { - let mock_consensus_state = - Protobuf::::decode(value).map_err(|e| { - ClientError::Other { - description: e.to_string(), - } - })?; + fn decode_consensus_state(value: &[u8]) -> Result { + let mock_consensus_state = Protobuf::::decode(value)?; Ok(mock_consensus_state) } match raw.type_url.as_str() { - MOCK_CONSENSUS_STATE_TYPE_URL => decode_consensus_state(&raw.value), - _ => Err(ClientError::InvalidConsensusStateType(raw.type_url)), + MOCK_CONSENSUS_STATE_TYPE_URL => { + decode_consensus_state(&raw.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: MOCK_CONSENSUS_STATE_TYPE_URL.to_string(), + actual: raw.type_url, + })), } } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs index f943476ce..e95e4685f 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs @@ -98,7 +98,7 @@ impl TryFrom for MockHeader { MOCK_HEADER_TYPE_URL => Ok(Protobuf::::decode_vec(&raw.value)?), _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: MOCK_HEADER_TYPE_URL.to_string(), - actual: raw.type_url.to_string(), + actual: raw.type_url, })), } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs index 24d355ebd..af8434b25 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs @@ -63,7 +63,7 @@ impl TryFrom for Misbehaviour { } _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: MOCK_MISBEHAVIOUR_TYPE_URL.to_string(), - actual: raw.type_url.to_string(), + actual: raw.type_url, })), } } diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 5f572cf6b..b01dfa3f7 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -80,7 +80,7 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), ContextError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err(ClientError::InvalidStatus(Status::Frozen).into()); + return Err(ClientError::Status(StatusError::UnexpectedStatus(Status::Frozen)).into()); } let latest_height = self.host_height()?; From e68cb54802f4b4c747bc5eba21dfaeeb13c00c83 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 12:46:42 -0500 Subject: [PATCH 006/107] Wiring up DecodingError --- ibc-apps/ics20-transfer/types/src/error.rs | 20 ++++++++-------- .../ics20-transfer/types/src/msgs/transfer.rs | 16 +++++++------ .../ics721-nft-transfer/types/src/error.rs | 2 -- .../types/src/msgs/transfer.rs | 14 ++++++----- .../ics08-wasm/types/src/client_state.rs | 24 +++++++++---------- ibc-clients/ics08-wasm/types/src/error.rs | 7 +++--- ibc-core/ics02-client/types/src/error.rs | 12 ++-------- .../cosmos/src/upgrade_proposal/plan.rs | 24 ++++++++----------- ibc-primitives/src/types/error.rs | 10 ++++---- 9 files changed, 58 insertions(+), 71 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 7924e2609..38c9581a7 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -8,12 +8,15 @@ use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::error::IdentifierError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; +use ibc_core::primitives::DecodingError; use uint::FromDecStrErr; #[derive(Display, Debug)] pub enum TokenTransferError { /// context error: `{0}` ContextError(ContextError), + /// decoding error: `{0}` + Decoding(DecodingError), /// invalid identifier: `{0}` InvalidIdentifier(IdentifierError), /// invalid trace: `{0}` @@ -41,14 +44,10 @@ pub enum TokenTransferError { // to a host-relevant error /// failed to parse account ID FailedToParseAccount, - /// failed to decode raw msg: `{description}` - FailedToDecodeRawMsg { description: String }, /// channel cannot be closed UnsupportedClosedChannel, /// empty base denomination EmptyBaseDenom, - /// unknown msg type: `{0}` - UnknownMsgType(String), } #[cfg(feature = "std")] @@ -58,6 +57,7 @@ impl std::error::Error for TokenTransferError { Self::ContextError(e) => Some(e), Self::InvalidIdentifier(e) => Some(e), Self::InvalidAmount(e) => Some(e), + Self::Decoding(e) => Some(e), _ => None, } } @@ -70,19 +70,19 @@ impl From for TokenTransferError { } impl From for TokenTransferError { - fn from(err: ContextError) -> TokenTransferError { - Self::ContextError(err) + fn from(e: ContextError) -> Self { + Self::ContextError(e) } } impl From for TokenTransferError { - fn from(err: IdentifierError) -> TokenTransferError { - Self::InvalidIdentifier(err) + fn from(e: IdentifierError) -> Self { + Self::InvalidIdentifier(e) } } impl From for StatusValue { - fn from(err: TokenTransferError) -> Self { - StatusValue::new(err.to_string()).expect("error message must not be empty") + fn from(e: TokenTransferError) -> Self { + StatusValue::new(e.to_string()).expect("error message must not be empty") } } diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index 048ea956c..d10d538a3 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -4,7 +4,7 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; -use ibc_core::primitives::prelude::*; +use ibc_core::primitives::{prelude::*, DecodingError}; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::Protobuf; @@ -104,12 +104,14 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - TYPE_URL => MsgTransfer::decode_vec(&raw.value).map_err(|e| { - TokenTransferError::FailedToDecodeRawMsg { - description: e.to_string(), - } - }), - _ => Err(TokenTransferError::UnknownMsgType(raw.type_url)), + TYPE_URL => MsgTransfer::decode_vec(&raw.value) + .map_err(|e| TokenTransferError::Decoding(DecodingError::FailedToDecodeProto(e))), + _ => Err(TokenTransferError::Decoding( + DecodingError::MismatchedTypeUrls { + expected: TYPE_URL.to_string(), + actual: raw.type_url, + }, + )), } } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 637f13f1d..744665564 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -42,8 +42,6 @@ pub enum NftTransferError { FailedToParseAccount, /// channel cannot be closed UnsupportedClosedChannel, - /// unknown msg type: `{0}` - UnknownMsgType(String), } #[cfg(feature = "std")] diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index c98aceb5f..56be700ca 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -122,12 +122,14 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - TYPE_URL => MsgTransfer::decode_vec(&raw.value).map_err(|e| { - NftTransferError::Decoding(DecodingError::FailedToDecodeProto { - description: e.to_string(), - }) - }), - _ => Err(NftTransferError::UnknownMsgType(raw.type_url)), + TYPE_URL => MsgTransfer::decode_vec(&raw.value) + .map_err(|e| NftTransferError::Decoding(DecodingError::FailedToDecodeProto(e))), + _ => Err(NftTransferError::Decoding( + DecodingError::MismatchedTypeUrls { + expected: TYPE_URL.to_string(), + actual: raw.type_url, + }, + )), } } } diff --git a/ibc-clients/ics08-wasm/types/src/client_state.rs b/ibc-clients/ics08-wasm/types/src/client_state.rs index c8c4aca41..a99bb7547 100644 --- a/ibc-clients/ics08-wasm/types/src/client_state.rs +++ b/ibc-clients/ics08-wasm/types/src/client_state.rs @@ -3,6 +3,7 @@ use ibc_core_client::types::Height; use ibc_primitives::prelude::*; use ibc_primitives::proto::{Any, Protobuf}; +use ibc_primitives::DecodingError; use ibc_proto::ibc::lightclients::wasm::v1::ClientState as RawClientState; use crate::error::WasmClientError; @@ -69,22 +70,21 @@ impl TryFrom for ClientState { type Error = WasmClientError; fn try_from(any: Any) -> Result { - fn decode_client_state(value: &[u8]) -> Result { - let client_state = Protobuf::::decode(value).map_err(|e| { - WasmClientError::DecodingError { - description: e.to_string(), - } - })?; - + fn decode_client_state(value: &[u8]) -> Result { + let client_state = Protobuf::::decode(value)?; Ok(client_state) } match any.type_url.as_str() { - WASM_CLIENT_STATE_TYPE_URL => decode_client_state(&any.value), - other_type_url => Err(WasmClientError::MismatchedTypeUrls { - expected: WASM_CLIENT_STATE_TYPE_URL.to_string(), - actual: other_type_url.to_string(), - }), + WASM_CLIENT_STATE_TYPE_URL => { + decode_client_state(&any.value).map_err(WasmClientError::Decoding) + } + _ => Err(WasmClientError::Decoding( + DecodingError::MismatchedTypeUrls { + expected: WASM_CLIENT_STATE_TYPE_URL.to_string(), + actual: any.type_url, + }, + )), } } } diff --git a/ibc-clients/ics08-wasm/types/src/error.rs b/ibc-clients/ics08-wasm/types/src/error.rs index ecb3e1984..3ec6c9ea5 100644 --- a/ibc-clients/ics08-wasm/types/src/error.rs +++ b/ibc-clients/ics08-wasm/types/src/error.rs @@ -3,20 +3,19 @@ use displaydoc::Display; use ibc_core_host_types::error::IdentifierError; use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; /// The main error type #[derive(Debug, Display)] pub enum WasmClientError { + /// decoding error: `{0}` + Decoding(DecodingError), /// invalid identifier: `{0}` InvalidIdentifier(IdentifierError), /// invalid client state latest height InvalidLatestHeight, /// missing latest height MissingLatestHeight, - /// mismatched type URLs: expected `{expected}`, actual `{actual}` - MismatchedTypeUrls { expected: String, actual: String }, - /// decoding error: `{description}` - DecodingError { description: String }, } #[cfg(feature = "std")] diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index aaa085331..6ecb663dd 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -109,12 +109,6 @@ impl From for ClientError { } } -impl From for ClientError { - fn from(e: DecodingError) -> Self { - Self::Decoding(e) - } -} - impl From for ClientError { fn from(e: StatusError) -> Self { Self::Status(e) @@ -137,6 +131,8 @@ impl std::error::Error for ClientError { /// Encodes all the possible upgrade client errors #[derive(Debug, Display)] pub enum UpgradeClientError { + /// decoding error: `{0}` + Decoding(DecodingError), /// invalid proof for the upgraded client state: `{0}` InvalidUpgradeClientProof(CommitmentError), /// invalid proof for the upgraded consensus state: `{0}` @@ -147,14 +143,10 @@ pub enum UpgradeClientError { InvalidUpgradeProposal { description: String }, /// invalid upgrade plan: `{description}` InvalidUpgradePlan { description: String }, - /// mismatched type URLs: expected `{expected}`, actual `{actual}` - MismatchedTypeUrls { expected: String, actual: String }, /// missing upgraded client state MissingUpgradedClientState, /// missing upgraded consensus state MissingUpgradedConsensusState, - /// failed to decode raw upgrade plan: `{description}` - FailedToDecodeRawUpgradePlan { description: String }, /// failed to store upgrade plan: `{description}` FailedToStoreUpgradePlan { description: String }, /// failed to store upgraded client state: `{description}` diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index f66487cc7..7880c1810 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -1,7 +1,7 @@ //! Definition of domain `Plan` type. use ibc_core_client_types::error::UpgradeClientError; -use ibc_primitives::prelude::*; +use ibc_primitives::{prelude::*, DecodingError}; use ibc_proto::cosmos::upgrade::v1beta1::Plan as RawPlan; use ibc_proto::google::protobuf::Any; use ibc_proto::Protobuf; @@ -82,20 +82,16 @@ impl TryFrom for Plan { type Error = UpgradeClientError; fn try_from(any: Any) -> Result { - if any.type_url != TYPE_URL { - return Err(UpgradeClientError::MismatchedTypeUrls { - expected: TYPE_URL.to_string(), - actual: any.type_url, - }); + match any.type_url.as_str() { + TYPE_URL => Protobuf::::decode_vec(&any.value) + .map_err(|e| UpgradeClientError::Decoding(DecodingError::FailedToDecodeProto(e))), + _ => Err(UpgradeClientError::Decoding( + DecodingError::MismatchedTypeUrls { + expected: TYPE_URL.to_string(), + actual: any.type_url, + }, + )), } - - let plan = Protobuf::::decode_vec(&any.value).map_err(|e| { - UpgradeClientError::FailedToDecodeRawUpgradePlan { - description: e.to_string(), - } - })?; - - Ok(plan) } } diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs index b8aa169e5..e76d74b44 100644 --- a/ibc-primitives/src/types/error.rs +++ b/ibc-primitives/src/types/error.rs @@ -1,6 +1,6 @@ //! Foundational error types that are applicable across multiple ibc-rs workspaces. -use alloc::string::{String, ToString}; +use alloc::string::String; use displaydoc::Display; use http::uri::InvalidUri; @@ -24,15 +24,13 @@ pub enum DecodingError { MissingField(String), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, - /// failed to decode proto value: `{description}` - FailedToDecodeProto { description: String }, + /// failed to decode proto; error: `{0}` + FailedToDecodeProto(ProtoError), } impl From for DecodingError { fn from(e: ProtoError) -> Self { - Self::FailedToDecodeProto { - description: e.to_string(), - } + Self::FailedToDecodeProto(e) } } From 56816c4dd0c979002c980ff5012ae00136c1a256 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 13:17:17 -0500 Subject: [PATCH 007/107] Add DecodingError to RouterError --- ibc-core/ics25-handler/types/src/msgs.rs | 73 ++++++++++++----------- ibc-core/ics26-routing/types/src/error.rs | 5 +- ibc-primitives/src/types/error.rs | 2 + 3 files changed, 42 insertions(+), 38 deletions(-) diff --git a/ibc-core/ics25-handler/types/src/msgs.rs b/ibc-core/ics25-handler/types/src/msgs.rs index e3276b951..cfb13e631 100644 --- a/ibc-core/ics25-handler/types/src/msgs.rs +++ b/ibc-core/ics25-handler/types/src/msgs.rs @@ -19,6 +19,7 @@ use ibc_core_connection_types::msgs::{ }; use ibc_core_router_types::error::RouterError; use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::Protobuf; @@ -46,34 +47,34 @@ impl TryFrom for MsgEnvelope { CREATE_CLIENT_TYPE_URL => { // Pop out the message and then wrap it in the corresponding type. let domain_msg = MsgCreateClient::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Client(ClientMsg::CreateClient(domain_msg))) } UPDATE_CLIENT_TYPE_URL => { let domain_msg = MsgUpdateClient::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Client(ClientMsg::UpdateClient(domain_msg))) } UPGRADE_CLIENT_TYPE_URL => { let domain_msg = MsgUpgradeClient::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Client(ClientMsg::UpgradeClient(domain_msg))) } SUBMIT_MISBEHAVIOUR_TYPE_URL => { let domain_msg = MsgSubmitMisbehaviour::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Client(ClientMsg::Misbehaviour(domain_msg))) } @@ -82,34 +83,34 @@ impl TryFrom for MsgEnvelope { CONN_OPEN_INIT_TYPE_URL => { let domain_msg = MsgConnectionOpenInit::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenInit(domain_msg))) } CONN_OPEN_TRY_TYPE_URL => { let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenTry(domain_msg))) } CONN_OPEN_ACK_TYPE_URL => { let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenAck(domain_msg))) } CONN_OPEN_CONFIRM_TYPE_URL => { let domain_msg = MsgConnectionOpenConfirm::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenConfirm( domain_msg, @@ -119,84 +120,84 @@ impl TryFrom for MsgEnvelope { // ICS04 channel messages CHAN_OPEN_INIT_TYPE_URL => { let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenInit(domain_msg))) } CHAN_OPEN_TRY_TYPE_URL => { let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenTry(domain_msg))) } CHAN_OPEN_ACK_TYPE_URL => { let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenAck(domain_msg))) } CHAN_OPEN_CONFIRM_TYPE_URL => { let domain_msg = MsgChannelOpenConfirm::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenConfirm(domain_msg))) } CHAN_CLOSE_INIT_TYPE_URL => { let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseInit(domain_msg))) } CHAN_CLOSE_CONFIRM_TYPE_URL => { let domain_msg = MsgChannelCloseConfirm::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseConfirm(domain_msg))) } // ICS04 packet messages RECV_PACKET_TYPE_URL => { let domain_msg = MsgRecvPacket::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Packet(PacketMsg::Recv(domain_msg))) } ACKNOWLEDGEMENT_TYPE_URL => { let domain_msg = MsgAcknowledgement::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Packet(PacketMsg::Ack(domain_msg))) } TIMEOUT_TYPE_URL => { let domain_msg = MsgTimeout::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Packet(PacketMsg::Timeout(domain_msg))) } TIMEOUT_ON_CLOSE_TYPE_URL => { let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value).map_err(|e| { - RouterError::MalformedMessageBytes { + RouterError::Decoding(DecodingError::MalformedBytes { description: e.to_string(), - } + }) })?; Ok(MsgEnvelope::Packet(PacketMsg::TimeoutOnClose(domain_msg))) } diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index 663cbcc6a..b9de1e97a 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -1,12 +1,13 @@ use displaydoc::Display; use ibc_core_host_types::identifiers::PortId; use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; /// Error type for the router module. #[derive(Debug, Display)] pub enum RouterError { - /// malformed message that could not be decoded: `{description}` - MalformedMessageBytes { description: String }, + /// decoding error: `{0}` + Decoding(DecodingError), /// missing module MissingModule, /// unknown message type URL `{0}` diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs index e76d74b44..d7f06f80e 100644 --- a/ibc-primitives/src/types/error.rs +++ b/ibc-primitives/src/types/error.rs @@ -20,6 +20,8 @@ pub enum DecodingError { InvalidUtf8 { description: String }, /// invalid URI: `{0}` InvalidUri(InvalidUri), + /// malformed bytes that could not be decoded: `{description}` + MalformedBytes { description: String }, /// missing field: `{0}` MissingField(String), /// mismatched type URLs: expected `{expected}`, actual `{actual}` From c06e06b77c7fab06872d6c7c21cff176ffc2ecd9 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 13:37:51 -0500 Subject: [PATCH 008/107] Remove unused From impl --- ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs index 1121e5147..4c364d61b 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs @@ -65,7 +65,7 @@ impl TryFrom for MockConsensusState { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_consensus_state(value: &[u8]) -> Result { + fn decode_consensus_state(value: &[u8]) -> Result { let mock_consensus_state = Protobuf::::decode(value)?; Ok(mock_consensus_state) } From 098ba0fbbf24a8b9a097a8e0f142a2a95207ef62 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 13:39:16 -0500 Subject: [PATCH 009/107] Change format of an import --- ibc-apps/ics20-transfer/types/src/msgs/transfer.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index d10d538a3..022f5559c 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -4,7 +4,8 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; -use ibc_core::primitives::{prelude::*, DecodingError}; +use ibc_core::primitives::prelude::*; +use ibc_core::primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::Protobuf; From 27e83896edc65655cd114f9737b81749aa04968b Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 13:39:56 -0500 Subject: [PATCH 010/107] Change format of an import --- ibc-apps/ics721-nft-transfer/types/src/class.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/class.rs b/ibc-apps/ics721-nft-transfer/types/src/class.rs index 98ae0a765..2869e130a 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/class.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/class.rs @@ -5,9 +5,10 @@ use core::str::FromStr; use http::Uri; pub use ibc_app_transfer_types::{TracePath, TracePrefix}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; +use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; -use ibc_core::primitives::{prelude::*, DecodingError}; +use ibc_core::primitives::DecodingError; use ibc_proto::ibc::applications::nft_transfer::v1::ClassTrace as RawClassTrace; use crate::data::Data; From 9f69bf074d38dd48875e517db9e4bfa1a5b459a8 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 13:52:22 -0500 Subject: [PATCH 011/107] Change format of an import --- ibc-apps/ics721-nft-transfer/types/src/data.rs | 3 ++- ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs | 3 ++- ibc-apps/ics721-nft-transfer/types/src/packet.rs | 4 ++-- ibc-apps/ics721-nft-transfer/types/src/token.rs | 3 ++- ibc-clients/ics07-tendermint/types/src/consensus_state.rs | 3 ++- ibc-clients/ics07-tendermint/types/src/header.rs | 3 ++- ibc-clients/ics07-tendermint/types/src/misbehaviour.rs | 3 ++- ibc-clients/ics08-wasm/types/src/consensus_state.rs | 3 ++- ibc-core/ics02-client/types/src/status.rs | 2 +- ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs | 3 ++- ibc-primitives/src/types/error.rs | 4 ---- 11 files changed, 19 insertions(+), 15 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/data.rs b/ibc-apps/ics721-nft-transfer/types/src/data.rs index 8b91d3025..d78d9fb4e 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/data.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/data.rs @@ -6,7 +6,8 @@ use core::str::FromStr; use base64::prelude::BASE64_STANDARD; #[cfg(feature = "serde")] use base64::Engine; -use ibc_core::primitives::{prelude::*, DecodingError}; +use ibc_core::primitives::prelude::*; +use ibc_core::primitives::DecodingError; use mime::Mime; use crate::error::NftTransferError; diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index 56be700ca..cfb279c27 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -4,7 +4,8 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; -use ibc_core::primitives::{prelude::*, DecodingError}; +use ibc_core::primitives::prelude::*; +use ibc_core::primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::nft_transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::Protobuf; diff --git a/ibc-apps/ics721-nft-transfer/types/src/packet.rs b/ibc-apps/ics721-nft-transfer/types/src/packet.rs index 06009d372..1eb970bba 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/packet.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/packet.rs @@ -2,10 +2,10 @@ use base64::prelude::BASE64_STANDARD; use base64::Engine; +use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; -use ibc_core::primitives::Signer; -use ibc_core::primitives::{prelude::*, DecodingError}; +use ibc_core::primitives::{DecodingError, Signer}; use ibc_proto::ibc::applications::nft_transfer::v1::NonFungibleTokenPacketData as RawPacketData; use crate::class::{ClassData, ClassUri, PrefixedClassId}; diff --git a/ibc-apps/ics721-nft-transfer/types/src/token.rs b/ibc-apps/ics721-nft-transfer/types/src/token.rs index 374b3e54b..aeb141f20 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/token.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/token.rs @@ -3,9 +3,10 @@ use core::fmt::{self, Display}; use core::str::FromStr; use http::Uri; +use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; -use ibc_core::primitives::{prelude::*, DecodingError}; +use ibc_core::primitives::DecodingError; use crate::data::Data; use crate::error::NftTransferError; diff --git a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs index 82c6b2c7a..62e0b35de 100644 --- a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs @@ -2,7 +2,8 @@ use ibc_core_client_types::error::ClientError; use ibc_core_commitment_types::commitment::CommitmentRoot; -use ibc_primitives::{prelude::*, DecodingError}; +use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::ConsensusState as RawConsensusState; use ibc_proto::Protobuf; diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index e15044653..b63f80408 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -6,8 +6,9 @@ use core::str::FromStr; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::Height; use ibc_core_host_types::identifiers::ChainId; +use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; use ibc_primitives::Timestamp; -use ibc_primitives::{prelude::*, DecodingError}; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Header as RawHeader; use ibc_proto::Protobuf; diff --git a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs index fd314b6eb..b50cdb0d4 100644 --- a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs +++ b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs @@ -2,7 +2,8 @@ use ibc_core_client_types::error::ClientError; use ibc_core_host_types::identifiers::ClientId; -use ibc_primitives::{prelude::*, DecodingError}; +use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Misbehaviour as RawMisbehaviour; use ibc_proto::Protobuf; diff --git a/ibc-clients/ics08-wasm/types/src/consensus_state.rs b/ibc-clients/ics08-wasm/types/src/consensus_state.rs index 9d50f7177..ed84364a6 100644 --- a/ibc-clients/ics08-wasm/types/src/consensus_state.rs +++ b/ibc-clients/ics08-wasm/types/src/consensus_state.rs @@ -1,8 +1,9 @@ //! Defines the consensus state type for the ICS-08 Wasm light client. use ibc_core_client::types::error::ClientError; +use ibc_primitives::prelude::*; use ibc_primitives::proto::{Any, Protobuf}; -use ibc_primitives::{prelude::*, DecodingError}; +use ibc_primitives::DecodingError; use ibc_proto::ibc::lightclients::wasm::v1::ConsensusState as RawConsensusState; #[cfg(feature = "serde")] diff --git a/ibc-core/ics02-client/types/src/status.rs b/ibc-core/ics02-client/types/src/status.rs index e63df1793..a16d1218d 100644 --- a/ibc-core/ics02-client/types/src/status.rs +++ b/ibc-core/ics02-client/types/src/status.rs @@ -37,7 +37,7 @@ pub enum Status { pub enum StatusError { /// invalid client status: `{0}` InvalidStatus(String), - /// unexpected status `{0}` found + /// unexpected status found: `{0}` UnexpectedStatus(Status), } diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index 7880c1810..3a37c87f5 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -1,7 +1,8 @@ //! Definition of domain `Plan` type. use ibc_core_client_types::error::UpgradeClientError; -use ibc_primitives::{prelude::*, DecodingError}; +use ibc_primitives::prelude::*; +use ibc_primitives::DecodingError; use ibc_proto::cosmos::upgrade::v1beta1::Plan as RawPlan; use ibc_proto::google::protobuf::Any; use ibc_proto::Protobuf; diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs index d7f06f80e..859f94ba6 100644 --- a/ibc-primitives/src/types/error.rs +++ b/ibc-primitives/src/types/error.rs @@ -12,8 +12,6 @@ use tendermint_proto::Error as ProtoError; pub enum DecodingError { /// invalid identifier error: `{0}` InvalidIdentifier(String), - /// invalid field: `{0}` - InvalidField(String), /// invalid JSON data: `{description}` InvalidJson { description: String }, /// invalid UTF-8 data: `{description}` @@ -22,8 +20,6 @@ pub enum DecodingError { InvalidUri(InvalidUri), /// malformed bytes that could not be decoded: `{description}` MalformedBytes { description: String }, - /// missing field: `{0}` - MissingField(String), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, /// failed to decode proto; error: `{0}` From b98ab2954e170ecaa5a5bf7de6c5b19bc7d6dc8f Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 27 Aug 2024 15:36:08 -0500 Subject: [PATCH 012/107] Move DecodingError into ics24 --- ibc-apps/ics20-transfer/types/src/error.rs | 2 +- .../ics20-transfer/types/src/msgs/transfer.rs | 2 +- .../ics721-nft-transfer/types/src/class.rs | 2 +- .../ics721-nft-transfer/types/src/data.rs | 2 +- .../ics721-nft-transfer/types/src/error.rs | 18 +++++----- .../types/src/msgs/transfer.rs | 2 +- .../ics721-nft-transfer/types/src/packet.rs | 3 +- .../ics721-nft-transfer/types/src/token.rs | 2 +- .../src/client_state/common.rs | 2 +- .../types/src/consensus_state.rs | 2 +- .../ics07-tendermint/types/src/header.rs | 2 +- .../types/src/misbehaviour.rs | 2 +- .../ics08-wasm/types/src/client_state.rs | 2 +- .../ics08-wasm/types/src/consensus_state.rs | 2 +- ibc-clients/ics08-wasm/types/src/error.rs | 2 +- .../ics02-client/src/handler/create_client.rs | 4 ++- .../src/handler/recover_client.rs | 4 +-- .../ics02-client/src/handler/update_client.rs | 2 +- .../src/handler/upgrade_client.rs | 2 +- ibc-core/ics02-client/types/src/error.rs | 12 ++++--- .../src/handler/conn_open_ack.rs | 2 +- .../src/handler/conn_open_confirm.rs | 2 +- .../src/handler/conn_open_init.rs | 2 +- .../src/handler/conn_open_try.rs | 2 +- .../src/handler/acknowledgement.rs | 2 +- .../src/handler/chan_close_confirm.rs | 2 +- .../src/handler/chan_close_init.rs | 2 +- .../src/handler/chan_open_ack.rs | 2 +- .../src/handler/chan_open_confirm.rs | 2 +- .../src/handler/chan_open_init.rs | 2 +- .../src/handler/chan_open_try.rs | 2 +- .../ics04-channel/src/handler/recv_packet.rs | 2 +- .../ics04-channel/src/handler/send_packet.rs | 2 +- ibc-core/ics04-channel/src/handler/timeout.rs | 2 +- .../src/handler/timeout_on_close.rs | 2 +- .../cosmos/src/upgrade_proposal/plan.rs | 2 +- .../cosmos/src/validate_self_client.rs | 4 ++- ibc-core/ics24-host/types/Cargo.toml | 4 +++ ibc-core/ics24-host/types/src/error.rs | 35 ++++++++++++++++++ ibc-core/ics24-host/types/src/lib.rs | 2 ++ ibc-core/ics25-handler/types/src/msgs.rs | 2 +- ibc-core/ics26-routing/types/src/error.rs | 3 +- ibc-primitives/Cargo.toml | 1 - ibc-primitives/src/types/error.rs | 36 ------------------- ibc-primitives/src/types/mod.rs | 2 -- ibc-query/src/error.rs | 13 ++++++- .../testapp/ibc/clients/mock/client_state.rs | 8 +++-- .../ibc/clients/mock/consensus_state.rs | 2 +- .../src/testapp/ibc/clients/mock/header.rs | 4 ++- .../testapp/ibc/clients/mock/misbehaviour.rs | 2 +- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 6 ++-- .../tests/core/ics02_client/create_client.rs | 14 ++++---- 52 files changed, 134 insertions(+), 107 deletions(-) delete mode 100644 ibc-primitives/src/types/error.rs diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 38c9581a7..b71ccddda 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -5,10 +5,10 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::error::IdentifierError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -use ibc_core::primitives::DecodingError; use uint::FromDecStrErr; #[derive(Display, Debug)] diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index 022f5559c..b8809d6c9 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -3,9 +3,9 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; use ibc_core::handler::types::error::ContextError; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -use ibc_core::primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::Protobuf; diff --git a/ibc-apps/ics721-nft-transfer/types/src/class.rs b/ibc-apps/ics721-nft-transfer/types/src/class.rs index 2869e130a..c4aaa5ae5 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/class.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/class.rs @@ -4,11 +4,11 @@ use core::str::FromStr; use http::Uri; pub use ibc_app_transfer_types::{TracePath, TracePrefix}; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; -use ibc_core::primitives::DecodingError; use ibc_proto::ibc::applications::nft_transfer::v1::ClassTrace as RawClassTrace; use crate::data::Data; diff --git a/ibc-apps/ics721-nft-transfer/types/src/data.rs b/ibc-apps/ics721-nft-transfer/types/src/data.rs index d78d9fb4e..bbbfb3f3d 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/data.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/data.rs @@ -6,8 +6,8 @@ use core::str::FromStr; use base64::prelude::BASE64_STANDARD; #[cfg(feature = "serde")] use base64::Engine; +use ibc_core::host::types::error::DecodingError; use ibc_core::primitives::prelude::*; -use ibc_core::primitives::DecodingError; use mime::Mime; use crate::error::NftTransferError; diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 744665564..32f55ce29 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -4,10 +4,10 @@ use core::convert::Infallible; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::error::IdentifierError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -use ibc_core::primitives::DecodingError; use displaydoc::Display; @@ -62,25 +62,25 @@ impl From for NftTransferError { } impl From for NftTransferError { - fn from(err: ContextError) -> Self { - Self::ContextError(err) + fn from(e: ContextError) -> Self { + Self::ContextError(e) } } impl From for NftTransferError { - fn from(err: IdentifierError) -> Self { - Self::Decoding(DecodingError::InvalidIdentifier(err.to_string())) + fn from(e: IdentifierError) -> Self { + Self::Decoding(DecodingError::InvalidIdentifier(e)) } } impl From for NftTransferError { - fn from(err: DecodingError) -> Self { - Self::Decoding(err) + fn from(e: DecodingError) -> Self { + Self::Decoding(e) } } impl From for StatusValue { - fn from(err: NftTransferError) -> Self { - StatusValue::new(err.to_string()).expect("error message must not be empty") + fn from(e: NftTransferError) -> Self { + StatusValue::new(e.to_string()).expect("error message must not be empty") } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index cfb279c27..8412f333f 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -3,9 +3,9 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; use ibc_core::handler::types::error::ContextError; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -use ibc_core::primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::nft_transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::Protobuf; diff --git a/ibc-apps/ics721-nft-transfer/types/src/packet.rs b/ibc-apps/ics721-nft-transfer/types/src/packet.rs index 1eb970bba..4dcde60a8 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/packet.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/packet.rs @@ -2,10 +2,11 @@ use base64::prelude::BASE64_STANDARD; use base64::Engine; +use ibc_core::host::types::error::DecodingError; use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; -use ibc_core::primitives::{DecodingError, Signer}; +use ibc_core::primitives::Signer; use ibc_proto::ibc::applications::nft_transfer::v1::NonFungibleTokenPacketData as RawPacketData; use crate::class::{ClassData, ClassUri, PrefixedClassId}; diff --git a/ibc-apps/ics721-nft-transfer/types/src/token.rs b/ibc-apps/ics721-nft-transfer/types/src/token.rs index aeb141f20..3c1e56aeb 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/token.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/token.rs @@ -3,10 +3,10 @@ use core::fmt::{self, Display}; use core::str::FromStr; use http::Uri; +use ibc_core::host::types::error::DecodingError; use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; -use ibc_core::primitives::DecodingError; use crate::data::Data; use crate::error::NftTransferError; diff --git a/ibc-clients/ics07-tendermint/src/client_state/common.rs b/ibc-clients/ics07-tendermint/src/client_state/common.rs index 3671e6bd6..4528447cf 100644 --- a/ibc-clients/ics07-tendermint/src/client_state/common.rs +++ b/ibc-clients/ics07-tendermint/src/client_state/common.rs @@ -166,7 +166,7 @@ pub fn verify_consensus_state( }; if consensus_state_status(&tm_consensus_state, host_timestamp, trusting_period)?.is_expired() { - return Err(ClientError::Status(StatusError::UnexpectedStatus( + return Err(ClientError::ClientStatus(StatusError::UnexpectedStatus( Status::Expired, ))); } diff --git a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs index 62e0b35de..3008b756b 100644 --- a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs @@ -2,8 +2,8 @@ use ibc_core_client_types::error::ClientError; use ibc_core_commitment_types::commitment::CommitmentRoot; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::ConsensusState as RawConsensusState; use ibc_proto::Protobuf; diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index b63f80408..085bec887 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -5,9 +5,9 @@ use core::str::FromStr; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::Height; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ChainId; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; use ibc_primitives::Timestamp; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Header as RawHeader; diff --git a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs index b50cdb0d4..059b4b4ee 100644 --- a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs +++ b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs @@ -1,9 +1,9 @@ //! Defines the misbehaviour type for the tendermint light client use ibc_core_client_types::error::ClientError; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Misbehaviour as RawMisbehaviour; use ibc_proto::Protobuf; diff --git a/ibc-clients/ics08-wasm/types/src/client_state.rs b/ibc-clients/ics08-wasm/types/src/client_state.rs index a99bb7547..acc2fbecd 100644 --- a/ibc-clients/ics08-wasm/types/src/client_state.rs +++ b/ibc-clients/ics08-wasm/types/src/client_state.rs @@ -1,9 +1,9 @@ //! Defines the client state type for the ICS-08 Wasm light client. use ibc_core_client::types::Height; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::proto::{Any, Protobuf}; -use ibc_primitives::DecodingError; use ibc_proto::ibc::lightclients::wasm::v1::ClientState as RawClientState; use crate::error::WasmClientError; diff --git a/ibc-clients/ics08-wasm/types/src/consensus_state.rs b/ibc-clients/ics08-wasm/types/src/consensus_state.rs index ed84364a6..588455b9b 100644 --- a/ibc-clients/ics08-wasm/types/src/consensus_state.rs +++ b/ibc-clients/ics08-wasm/types/src/consensus_state.rs @@ -1,9 +1,9 @@ //! Defines the consensus state type for the ICS-08 Wasm light client. use ibc_core_client::types::error::ClientError; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::proto::{Any, Protobuf}; -use ibc_primitives::DecodingError; use ibc_proto::ibc::lightclients::wasm::v1::ConsensusState as RawConsensusState; #[cfg(feature = "serde")] diff --git a/ibc-clients/ics08-wasm/types/src/error.rs b/ibc-clients/ics08-wasm/types/src/error.rs index 3ec6c9ea5..513bdddad 100644 --- a/ibc-clients/ics08-wasm/types/src/error.rs +++ b/ibc-clients/ics08-wasm/types/src/error.rs @@ -1,9 +1,9 @@ //! Defines the error type for the ICS-08 Wasm light client. use displaydoc::Display; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::error::IdentifierError; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; /// The main error type #[derive(Debug, Display)] diff --git a/ibc-core/ics02-client/src/handler/create_client.rs b/ibc-core/ics02-client/src/handler/create_client.rs index d775ddf02..1663c2cc4 100644 --- a/ibc-core/ics02-client/src/handler/create_client.rs +++ b/ibc-core/ics02-client/src/handler/create_client.rs @@ -36,7 +36,9 @@ where let status = client_state.status(client_val_ctx, &client_id)?; if status.is_frozen() { - return Err(ClientError::Status(StatusError::UnexpectedStatus(Status::Frozen)).into()); + return Err( + ClientError::ClientStatus(StatusError::UnexpectedStatus(Status::Frozen)).into(), + ); }; let host_timestamp = ctx.host_timestamp()?; diff --git a/ibc-core/ics02-client/src/handler/recover_client.rs b/ibc-core/ics02-client/src/handler/recover_client.rs index 8c24bbbce..c48aae2ec 100644 --- a/ibc-core/ics02-client/src/handler/recover_client.rs +++ b/ibc-core/ics02-client/src/handler/recover_client.rs @@ -40,13 +40,13 @@ where substitute_client_state .status(ctx.get_client_validation_context(), &substitute_client_id)? .verify_is_active() - .map_err(ClientError::Status)?; // TODO(seanchen1991): Why is this `map_err` necessary? + .map_err(ClientError::ClientStatus)?; // TODO(seanchen1991): Why is this `map_err` necessary? // Verify that the subject client is inactive, i.e., that it is either frozen or expired subject_client_state .status(ctx.get_client_validation_context(), &subject_client_id)? .verify_is_inactive() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; // Check that the subject client state and substitute client states match, i.e., that // all their respective client state parameters match except for frozen height, latest diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index f67debcbd..d2a18b8b5 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -27,7 +27,7 @@ where client_state .status(client_val_ctx, &client_id)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; let client_message = msg.client_message(); diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index c79cbcb93..475e86c1d 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -29,7 +29,7 @@ where old_client_state .status(client_val_ctx, &client_id)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; // Read the latest consensus state from the host chain store. let old_client_cons_state_path = ClientConsensusStatePath::new( diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 6ecb663dd..e11268cd7 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -4,10 +4,10 @@ use core::convert::Infallible; use displaydoc::Display; use ibc_core_commitment_types::error::CommitmentError; -use ibc_core_host_types::error::IdentifierError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; -use ibc_primitives::{DecodingError, Timestamp}; +use ibc_primitives::Timestamp; use crate::height::Height; use crate::StatusError; @@ -20,7 +20,9 @@ pub enum ClientError { /// decoding error: `{0}` Decoding(DecodingError), /// client status error: `{0}` - Status(StatusError), + ClientStatus(StatusError), + /// invalid header type: `{0}` + InvalidHeaderType(String), /// invalid trust threshold: `{numerator}`/`{denominator}` InvalidTrustThreshold { numerator: u64, denominator: u64 }, /// invalid client state type: `{0}` @@ -111,7 +113,7 @@ impl From for ClientError { impl From for ClientError { fn from(e: StatusError) -> Self { - Self::Status(e) + Self::ClientStatus(e) } } @@ -121,7 +123,7 @@ impl std::error::Error for ClientError { match &self { Self::InvalidClientIdentifier(e) => Some(e), Self::FailedICS23Verification(e) => Some(e), - Self::Status(e) => Some(e), + Self::ClientStatus(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs index 05bdc0fcb..493bb1f8d 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs @@ -68,7 +68,7 @@ where client_state_of_b_on_a .status(client_val_ctx_a, vars.client_id_on_a())? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_b_on_a.validate_proof_height(msg.proofs_height_on_b)?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs index 2dd0105f3..b622a3037 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs @@ -49,7 +49,7 @@ where client_state_of_a_on_b .status(client_val_ctx_b, client_id_on_b)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_init.rs b/ibc-core/ics03-connection/src/handler/conn_open_init.rs index ad6c8de4f..f6196a787 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_init.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_init.rs @@ -25,7 +25,7 @@ where client_state_of_b_on_a .status(client_val_ctx_a, &msg.client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; if let Some(version) = msg.version { version.verify_is_supported(&ctx_a.get_compatible_versions())?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_try.rs b/ibc-core/ics03-connection/src/handler/conn_open_try.rs index 606a55a49..4c86a6261 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_try.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_try.rs @@ -68,7 +68,7 @@ where client_state_of_a_on_b .status(client_val_ctx_b, &msg.client_id_on_b)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_a_on_b.validate_proof_height(msg.proofs_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/acknowledgement.rs b/ibc-core/ics04-channel/src/handler/acknowledgement.rs index 659befb1b..a0cb98e86 100644 --- a/ibc-core/ics04-channel/src/handler/acknowledgement.rs +++ b/ibc-core/ics04-channel/src/handler/acknowledgement.rs @@ -178,7 +178,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs index 25f8ebbc9..fb3479864 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs @@ -115,7 +115,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-core/ics04-channel/src/handler/chan_close_init.rs index dbe604ef6..ba2bd2585 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_init.rs @@ -112,7 +112,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; Ok(()) } diff --git a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs index 34d43c33a..bc3506652 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs @@ -116,7 +116,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs index a3d05dddf..71ad5a00f 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs @@ -120,7 +120,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_open_init.rs b/ibc-core/ics04-channel/src/handler/chan_open_init.rs index a8b917cf9..0553b7b1d 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_init.rs @@ -127,7 +127,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; let conn_version = conn_end_on_a.versions(); diff --git a/ibc-core/ics04-channel/src/handler/chan_open_try.rs b/ibc-core/ics04-channel/src/handler/chan_open_try.rs index 54807c1be..738f8d67c 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_try.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_try.rs @@ -142,7 +142,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index e9f7b7101..fe7230b20 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -188,7 +188,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/send_packet.rs b/ibc-core/ics04-channel/src/handler/send_packet.rs index 714242383..6247197cf 100644 --- a/ibc-core/ics04-channel/src/handler/send_packet.rs +++ b/ibc-core/ics04-channel/src/handler/send_packet.rs @@ -61,7 +61,7 @@ pub fn send_packet_validate( client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; let latest_height_on_a = client_state_of_b_on_a.latest_height(); diff --git a/ibc-core/ics04-channel/src/handler/timeout.rs b/ibc-core/ics04-channel/src/handler/timeout.rs index 5963f810a..325803985 100644 --- a/ibc-core/ics04-channel/src/handler/timeout.rs +++ b/ibc-core/ics04-channel/src/handler/timeout.rs @@ -188,7 +188,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs index eda55002a..0d31ae234 100644 --- a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs +++ b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs @@ -72,7 +72,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? .verify_is_active() - .map_err(ClientError::Status)?; + .map_err(ClientError::ClientStatus)?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index 3a37c87f5..33f1ad782 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -1,8 +1,8 @@ //! Definition of domain `Plan` type. use ibc_core_client_types::error::UpgradeClientError; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; use ibc_proto::cosmos::upgrade::v1beta1::Plan as RawPlan; use ibc_proto::google::protobuf::Any; use ibc_proto::Protobuf; diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index 446c3ebbf..6f72e2937 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -25,7 +25,9 @@ pub trait ValidateSelfClientContext { .map_err(ClientError::from)?; if client_state_of_host_on_counterparty.is_frozen() { - return Err(ClientError::Status(StatusError::UnexpectedStatus(Status::Frozen)).into()); + return Err( + ClientError::ClientStatus(StatusError::UnexpectedStatus(Status::Frozen)).into(), + ); } let self_chain_id = self.chain_id(); diff --git a/ibc-core/ics24-host/types/Cargo.toml b/ibc-core/ics24-host/types/Cargo.toml index 7ad95dcc0..b1126d300 100644 --- a/ibc-core/ics24-host/types/Cargo.toml +++ b/ibc-core/ics24-host/types/Cargo.toml @@ -23,6 +23,7 @@ all-features = true borsh = { workspace = true, optional = true } derive_more = { workspace = true } displaydoc = { workspace = true } +http = { version = "1.1.0" } schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } @@ -33,6 +34,9 @@ ibc-primitives = { workspace = true } parity-scale-codec = { workspace = true, optional = true } scale-info = { workspace = true, optional = true } +# cosmos dependencies +tendermint-proto = { workspace = true } + [dev-dependencies] rstest = { workspace = true } serde-json = { workspace = true } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 72d8535c2..721adfa5f 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -1,5 +1,12 @@ +//! Foundational error types that are applicable across multiple ibc-rs workspaces. + +use alloc::string::String; + use displaydoc::Display; +use http::uri::InvalidUri; + use ibc_primitives::prelude::*; +use tendermint_proto::Error as ProtoError; /// Errors that arise when parsing identifiers. #[cfg_attr(feature = "serde", derive(serde::Serialize))] @@ -17,5 +24,33 @@ pub enum IdentifierError { OverflowedRevisionNumber, } +/// Errors that result in decoding failures +#[derive(Debug, Display)] +pub enum DecodingError { + /// invalid identifier error: `{0}` + InvalidIdentifier(IdentifierError), + /// invalid JSON data: `{description}` + InvalidJson { description: String }, + /// invalid UTF-8 data: `{description}` + InvalidUtf8 { description: String }, + /// invalid URI: `{0}` + InvalidUri(InvalidUri), + /// malformed bytes that could not be decoded: `{description}` + MalformedBytes { description: String }, + /// mismatched type URLs: expected `{expected}`, actual `{actual}` + MismatchedTypeUrls { expected: String, actual: String }, + /// failed to decode proto; error: `{0}` + FailedToDecodeProto(ProtoError), +} + +impl From for DecodingError { + fn from(e: ProtoError) -> Self { + Self::FailedToDecodeProto(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for IdentifierError {} + +#[cfg(feature = "std")] +impl std::error::Error for DecodingError {} diff --git a/ibc-core/ics24-host/types/src/lib.rs b/ibc-core/ics24-host/types/src/lib.rs index f466de4c2..1fae79ac6 100644 --- a/ibc-core/ics24-host/types/src/lib.rs +++ b/ibc-core/ics24-host/types/src/lib.rs @@ -12,6 +12,8 @@ rust_2018_idioms )] +extern crate alloc; + #[cfg(feature = "std")] extern crate std; diff --git a/ibc-core/ics25-handler/types/src/msgs.rs b/ibc-core/ics25-handler/types/src/msgs.rs index cfb13e631..7f1b5c9a5 100644 --- a/ibc-core/ics25-handler/types/src/msgs.rs +++ b/ibc-core/ics25-handler/types/src/msgs.rs @@ -17,9 +17,9 @@ use ibc_core_connection_types::msgs::{ MsgConnectionOpenTry, CONN_OPEN_ACK_TYPE_URL, CONN_OPEN_CONFIRM_TYPE_URL, CONN_OPEN_INIT_TYPE_URL, CONN_OPEN_TRY_TYPE_URL, }; +use ibc_core_host_types::error::DecodingError; use ibc_core_router_types::error::RouterError; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; use ibc_proto::google::protobuf::Any; use ibc_proto::Protobuf; diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index b9de1e97a..b64eb2fe6 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -1,7 +1,8 @@ use displaydoc::Display; + +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::PortId; use ibc_primitives::prelude::*; -use ibc_primitives::DecodingError; /// Error type for the router module. #[derive(Debug, Display)] diff --git a/ibc-primitives/Cargo.toml b/ibc-primitives/Cargo.toml index e4a5d723d..1e090acf6 100644 --- a/ibc-primitives/Cargo.toml +++ b/ibc-primitives/Cargo.toml @@ -23,7 +23,6 @@ all-features = true borsh = { workspace = true, optional = true } derive_more = { workspace = true } displaydoc = { workspace = true } -http = { version = "1.1.0" } prost = { workspace = true } schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } diff --git a/ibc-primitives/src/types/error.rs b/ibc-primitives/src/types/error.rs deleted file mode 100644 index 859f94ba6..000000000 --- a/ibc-primitives/src/types/error.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Foundational error types that are applicable across multiple ibc-rs workspaces. - -use alloc::string::String; - -use displaydoc::Display; -use http::uri::InvalidUri; - -use tendermint_proto::Error as ProtoError; - -/// Causes of decoding failures -#[derive(Debug, Display)] -pub enum DecodingError { - /// invalid identifier error: `{0}` - InvalidIdentifier(String), - /// invalid JSON data: `{description}` - InvalidJson { description: String }, - /// invalid UTF-8 data: `{description}` - InvalidUtf8 { description: String }, - /// invalid URI: `{0}` - InvalidUri(InvalidUri), - /// malformed bytes that could not be decoded: `{description}` - MalformedBytes { description: String }, - /// mismatched type URLs: expected `{expected}`, actual `{actual}` - MismatchedTypeUrls { expected: String, actual: String }, - /// failed to decode proto; error: `{0}` - FailedToDecodeProto(ProtoError), -} - -impl From for DecodingError { - fn from(e: ProtoError) -> Self { - Self::FailedToDecodeProto(e) - } -} - -#[cfg(feature = "std")] -impl std::error::Error for DecodingError {} diff --git a/ibc-primitives/src/types/mod.rs b/ibc-primitives/src/types/mod.rs index 85849f97c..8df0d3c40 100644 --- a/ibc-primitives/src/types/mod.rs +++ b/ibc-primitives/src/types/mod.rs @@ -1,7 +1,5 @@ -mod error; mod signer; mod timestamp; -pub use error::*; pub use signer::*; pub use timestamp::*; diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index 4c41120eb..8e8bd3949 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -1,12 +1,14 @@ use alloc::string::{String, ToString}; use displaydoc::Display; +use tonic::Status; + use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; +use ibc::core::client::types::StatusError; use ibc::core::connection::types::error::ConnectionError; use ibc::core::handler::types::error::ContextError; use ibc::core::host::types::error::IdentifierError; -use tonic::Status; /// The main error type of the ibc-query crate. This type mainly /// serves to surface lower-level errors that occur when executing @@ -15,6 +17,8 @@ use tonic::Status; pub enum QueryError { /// context error: `{0}` ContextError(ContextError), + /// client status error: `{0}` + ClientStatus(StatusError), /// identifier error: `{0}` IdentifierError(IdentifierError), /// missing proof: `{0}` @@ -38,6 +42,7 @@ impl From for Status { match e { QueryError::ContextError(ctx_err) => Self::internal(ctx_err.to_string()), QueryError::IdentifierError(id_err) => Self::internal(id_err.to_string()), + QueryError::ClientStatus(status_err) => Self::invalid_argument(status_err.to_string()), QueryError::MissingProof(description) => Self::not_found(description), QueryError::MissingField(description) => Self::invalid_argument(description), } @@ -79,3 +84,9 @@ impl From for QueryError { Self::IdentifierError(e) } } + +impl From for QueryError { + fn from(e: StatusError) -> Self { + Self::ClientStatus(e) + } +} diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index d8f9685ff..6f8cd0533 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -4,17 +4,17 @@ use core::time::Duration; use ibc::clients::tendermint::client_state::consensus_state_status; use ibc::core::client::context::prelude::*; use ibc::core::client::types::error::{ClientError, UpgradeClientError}; -use ibc::core::client::types::{Height, Status}; +use ibc::core::client::types::{Height, Status, StatusError}; use ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; use ibc::core::handler::types::error::ContextError; +use ibc::core::host::types::error::DecodingError; use ibc::core::host::types::identifiers::{ClientId, ClientType}; use ibc::core::host::types::path::{ClientConsensusStatePath, ClientStatePath, Path, PathBytes}; use ibc::core::primitives::prelude::*; use ibc::core::primitives::Timestamp; use ibc::primitives::proto::{Any, Protobuf}; -use ibc::primitives::DecodingError; use crate::testapp::ibc::clients::mock::client_state::client_type as mock_client_type; use crate::testapp::ibc::clients::mock::consensus_state::MockConsensusState; @@ -172,7 +172,9 @@ impl ClientStateCommon for MockClientState { if consensus_state_status(&mock_consensus_state, host_timestamp, self.trusting_period)? .is_expired() { - return Err(ClientError::InvalidStatus(Status::Expired)); + return Err(ClientError::ClientStatus(StatusError::UnexpectedStatus( + Status::Expired, + ))); } Ok(()) diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs index 4c364d61b..e5d7a2ad5 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs @@ -1,10 +1,10 @@ use ibc::core::client::context::consensus_state::ConsensusState; use ibc::core::client::types::error::ClientError; use ibc::core::commitment_types::commitment::CommitmentRoot; +use ibc::core::host::types::error::DecodingError; use ibc::core::primitives::prelude::*; use ibc::core::primitives::Timestamp; use ibc::primitives::proto::{Any, Protobuf}; -use ibc::primitives::DecodingError; use crate::testapp::ibc::clients::mock::header::MockHeader; use crate::testapp::ibc::clients::mock::proto::ConsensusState as RawMockConsensusState; diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs index e95e4685f..f6ac8f11e 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs @@ -3,6 +3,7 @@ use core::fmt::{Display, Error as FmtError, Formatter}; use ibc::core::client::types::error::ClientError; use ibc::core::client::types::Height; +use ibc::core::host::types::error::DecodingError; use ibc::core::primitives::Timestamp; use ibc::primitives::proto::{Any, Protobuf}; @@ -95,7 +96,8 @@ impl TryFrom for MockHeader { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - MOCK_HEADER_TYPE_URL => Ok(Protobuf::::decode_vec(&raw.value)?), + MOCK_HEADER_TYPE_URL => Protobuf::::decode_vec(&raw.value) + .map_err(|e| ClientError::Decoding(DecodingError::FailedToDecodeProto(e))), _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: MOCK_HEADER_TYPE_URL.to_string(), actual: raw.type_url, diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs index af8434b25..83b07623a 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs @@ -1,8 +1,8 @@ use ibc::core::client::types::error::ClientError; +use ibc::core::host::types::error::DecodingError; use ibc::core::host::types::identifiers::ClientId; use ibc::core::primitives::prelude::*; use ibc::primitives::proto::{Any, Protobuf}; -use ibc::primitives::DecodingError; use crate::testapp::ibc::clients::mock::header::MockHeader; use crate::testapp::ibc::clients::mock::proto::Misbehaviour as RawMisbehaviour; diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index b01dfa3f7..41333372e 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -11,7 +11,7 @@ use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::channel::types::packet::{PacketState, Receipt}; use ibc::core::client::context::consensus_state::ConsensusState; use ibc::core::client::types::error::ClientError; -use ibc::core::client::types::{Height, Status}; +use ibc::core::client::types::{Height, Status, StatusError}; use ibc::core::commitment_types::commitment::CommitmentPrefix; use ibc::core::commitment_types::merkle::MerkleProof; use ibc::core::connection::types::error::ConnectionError; @@ -80,7 +80,9 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), ContextError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err(ClientError::Status(StatusError::UnexpectedStatus(Status::Frozen)).into()); + return Err( + ClientError::ClientStatus(StatusError::UnexpectedStatus(Status::Frozen)).into(), + ); } let latest_height = self.host_height()?; diff --git a/tests-integration/tests/core/ics02_client/create_client.rs b/tests-integration/tests/core/ics02_client/create_client.rs index 78c4f8392..3ab8712a3 100644 --- a/tests-integration/tests/core/ics02_client/create_client.rs +++ b/tests-integration/tests/core/ics02_client/create_client.rs @@ -13,7 +13,7 @@ use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::ClientId; use ibc::core::host::types::path::{ClientConsensusStatePath, NextClientSequencePath}; use ibc::core::host::{ClientStateRef, ValidationContext}; -use ibc_core_client_types::Status; +use ibc_core_client_types::{Status, StatusError}; use ibc_query::core::context::ProvableContext; use ibc_testkit::context::{MockContext, TendermintContext}; use ibc_testkit::fixtures::clients::tendermint::dummy_tm_client_state_from_header; @@ -180,8 +180,8 @@ fn test_create_expired_mock_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredMockHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError(ClientError::InvalidStatus( - Status::Expired, + Expect::Failure(Some(ContextError::ClientError(ClientError::ClientStatus( + StatusError::UnexpectedStatus(Status::Expired), )))), ); } @@ -206,8 +206,8 @@ fn test_create_expired_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError(ClientError::InvalidStatus( - Status::Expired, + Expect::Failure(Some(ContextError::ClientError(ClientError::ClientStatus( + StatusError::UnexpectedStatus(Status::Expired), )))), ); } @@ -218,8 +218,8 @@ fn test_create_frozen_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::FrozenTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError(ClientError::InvalidStatus( - Status::Frozen, + Expect::Failure(Some(ContextError::ClientError(ClientError::ClientStatus( + StatusError::UnexpectedStatus(Status::Frozen), )))), ); } From 4e1c9e346a65f377757a55e60ab6f30d610537c8 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 09:36:23 -0500 Subject: [PATCH 013/107] Cargo nightly fmt --- ibc-apps/ics20-transfer/types/src/error.rs | 3 +-- ibc-apps/ics721-nft-transfer/types/src/error.rs | 6 ++---- ibc-clients/ics08-wasm/types/src/error.rs | 3 +-- ibc-core/ics24-host/types/src/error.rs | 1 - ibc-core/ics26-routing/types/src/error.rs | 1 - ibc-query/src/error.rs | 3 +-- 6 files changed, 5 insertions(+), 12 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index b71ccddda..291a12635 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -5,8 +5,7 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; -use ibc_core::host::types::error::DecodingError; -use ibc_core::host::types::error::IdentifierError; +use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use uint::FromDecStrErr; diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 32f55ce29..8e5497c6b 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -1,16 +1,14 @@ //! Defines the Non-Fungible Token Transfer (ICS-721) error types. use core::convert::Infallible; +use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; -use ibc_core::host::types::error::DecodingError; -use ibc_core::host::types::error::IdentifierError; +use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -use displaydoc::Display; - #[derive(Display, Debug)] pub enum NftTransferError { /// context error: `{0}` diff --git a/ibc-clients/ics08-wasm/types/src/error.rs b/ibc-clients/ics08-wasm/types/src/error.rs index 513bdddad..b94a14b53 100644 --- a/ibc-clients/ics08-wasm/types/src/error.rs +++ b/ibc-clients/ics08-wasm/types/src/error.rs @@ -1,8 +1,7 @@ //! Defines the error type for the ICS-08 Wasm light client. use displaydoc::Display; -use ibc_core_host_types::error::DecodingError; -use ibc_core_host_types::error::IdentifierError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_primitives::prelude::*; /// The main error type diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 721adfa5f..972b36c40 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -4,7 +4,6 @@ use alloc::string::String; use displaydoc::Display; use http::uri::InvalidUri; - use ibc_primitives::prelude::*; use tendermint_proto::Error as ProtoError; diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index b64eb2fe6..aab2fa8fd 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -1,5 +1,4 @@ use displaydoc::Display; - use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::PortId; use ibc_primitives::prelude::*; diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index 8e8bd3949..badea0b59 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -1,14 +1,13 @@ use alloc::string::{String, ToString}; use displaydoc::Display; -use tonic::Status; - use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; use ibc::core::client::types::StatusError; use ibc::core::connection::types::error::ConnectionError; use ibc::core::handler::types::error::ContextError; use ibc::core::host::types::error::IdentifierError; +use tonic::Status; /// The main error type of the ibc-query crate. This type mainly /// serves to surface lower-level errors that occur when executing From d1860151abc0d54d3b826813ec291418e02bb71c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 10:41:04 -0500 Subject: [PATCH 014/107] Use DecodingError in more places --- .../ics20-transfer/types/src/msgs/transfer.rs | 2 +- .../ics721-nft-transfer/types/src/error.rs | 4 +- .../types/src/msgs/transfer.rs | 2 +- .../ics721-nft-transfer/types/src/packet.rs | 22 +-- .../types/src/client_state.rs | 17 ++- .../ics23-commitment/types/src/commitment.rs | 3 +- ibc-core/ics23-commitment/types/src/error.rs | 12 +- .../cosmos/src/upgrade_proposal/plan.rs | 2 +- ibc-core/ics24-host/types/Cargo.toml | 1 + ibc-core/ics24-host/types/src/error.rs | 20 +-- ibc-core/ics25-handler/types/src/msgs.rs | 131 +++++------------- .../src/testapp/ibc/clients/mock/header.rs | 2 +- 12 files changed, 82 insertions(+), 136 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index b8809d6c9..eefcdbf5d 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -106,7 +106,7 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { TYPE_URL => MsgTransfer::decode_vec(&raw.value) - .map_err(|e| TokenTransferError::Decoding(DecodingError::FailedToDecodeProto(e))), + .map_err(|e| TokenTransferError::Decoding(DecodingError::Protobuf(e))), _ => Err(TokenTransferError::Decoding( DecodingError::MismatchedTypeUrls { expected: TYPE_URL.to_string(), diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 8e5497c6b..d7303ce17 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -15,6 +15,8 @@ pub enum NftTransferError { ContextError(ContextError), /// decoding error: `{0}` Decoding(DecodingError), + /// identifier error: `{0}` + Identifier(IdentifierError), /// invalid trace `{0}` InvalidTrace(String), /// missing destination channel `{channel_id}` on port `{port_id}` @@ -67,7 +69,7 @@ impl From for NftTransferError { impl From for NftTransferError { fn from(e: IdentifierError) -> Self { - Self::Decoding(DecodingError::InvalidIdentifier(e)) + Self::Identifier(e) } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index 8412f333f..abd73e681 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -124,7 +124,7 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { TYPE_URL => MsgTransfer::decode_vec(&raw.value) - .map_err(|e| NftTransferError::Decoding(DecodingError::FailedToDecodeProto(e))), + .map_err(|e| NftTransferError::Decoding(DecodingError::Protobuf(e))), _ => Err(NftTransferError::Decoding( DecodingError::MismatchedTypeUrls { expected: TYPE_URL.to_string(), diff --git a/ibc-apps/ics721-nft-transfer/types/src/packet.rs b/ibc-apps/ics721-nft-transfer/types/src/packet.rs index 4dcde60a8..a0bd962fe 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/packet.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/packet.rs @@ -129,12 +129,8 @@ impl TryFrom for PacketData { } else { let decoded = BASE64_STANDARD .decode(raw_pkt_data.class_data) - .map_err(|e| DecodingError::InvalidJson { - description: e.to_string(), - })?; - let data_str = String::from_utf8(decoded).map_err(|e| DecodingError::InvalidUtf8 { - description: e.to_string(), - })?; + .map_err(DecodingError::Base64)?; + let data_str = String::from_utf8(decoded).map_err(DecodingError::Utf8)?; Some(data_str.parse()?) }; @@ -145,16 +141,10 @@ impl TryFrom for PacketData { .token_data .iter() .map(|data| { - let decoded = - BASE64_STANDARD - .decode(data) - .map_err(|e| DecodingError::InvalidJson { - description: e.to_string(), - })?; - let data_str = - String::from_utf8(decoded).map_err(|e| DecodingError::InvalidUtf8 { - description: e.to_string(), - })?; + let decoded = BASE64_STANDARD + .decode(data) + .map_err(DecodingError::Base64)?; + let data_str = String::from_utf8(decoded).map_err(DecodingError::Utf8)?; data_str.parse() }) .collect(); diff --git a/ibc-clients/ics07-tendermint/types/src/client_state.rs b/ibc-clients/ics07-tendermint/types/src/client_state.rs index 98ce38460..3595a7e4e 100644 --- a/ibc-clients/ics07-tendermint/types/src/client_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/client_state.rs @@ -8,6 +8,7 @@ use ibc_core_client_types::error::ClientError; use ibc_core_client_types::proto::v1::Height as RawHeight; use ibc_core_client_types::Height; use ibc_core_commitment_types::specs::ProofSpecs; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ChainId; use ibc_primitives::prelude::*; use ibc_primitives::ZERO_DURATION; @@ -341,17 +342,19 @@ impl TryFrom for ClientState { type Error = ClientError; fn try_from(raw: Any) -> Result { - fn decode_client_state(value: &[u8]) -> Result { - let client_state = - Protobuf::::decode(value).map_err(|e| ClientError::Other { - description: e.to_string(), - })?; + fn decode_client_state(value: &[u8]) -> Result { + let client_state = Protobuf::::decode(value)?; Ok(client_state) } match raw.type_url.as_str() { - TENDERMINT_CLIENT_STATE_TYPE_URL => decode_client_state(&raw.value), - _ => Err(ClientError::InvalidClientStateType(raw.type_url)), + TENDERMINT_CLIENT_STATE_TYPE_URL => { + decode_client_state(&raw.value).map_err(ClientError::Decoding) + } + _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + expected: TENDERMINT_CLIENT_STATE_TYPE_URL.to_string(), + actual: raw.type_url, + })), } } } diff --git a/ibc-core/ics23-commitment/types/src/commitment.rs b/ibc-core/ics23-commitment/types/src/commitment.rs index 43506a798..f43162668 100644 --- a/ibc-core/ics23-commitment/types/src/commitment.rs +++ b/ibc-core/ics23-commitment/types/src/commitment.rs @@ -2,6 +2,7 @@ use core::fmt; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::ToVec; use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; @@ -122,7 +123,7 @@ impl<'a> TryFrom<&'a CommitmentProofBytes> for MerkleProof { fn try_from(value: &'a CommitmentProofBytes) -> Result { Protobuf::::decode(value.as_ref()) - .map_err(|e| CommitmentError::FailedDecoding(e.to_string())) + .map_err(|e| CommitmentError::Decoding(DecodingError::Protobuf(e))) } } diff --git a/ibc-core/ics23-commitment/types/src/error.rs b/ibc-core/ics23-commitment/types/src/error.rs index 81ee26e06..8505de71d 100644 --- a/ibc-core/ics23-commitment/types/src/error.rs +++ b/ibc-core/ics23-commitment/types/src/error.rs @@ -1,10 +1,14 @@ //! Defines the commitment error type use displaydoc::Display; + +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; #[derive(Debug, Display)] pub enum CommitmentError { + /// decoding error: `{0}` + Decoding(DecodingError), /// empty commitment prefix EmptyCommitmentPrefix, /// empty commitment root @@ -31,11 +35,15 @@ pub enum CommitmentError { InvalidHashOp(i32), /// invalid length operation: `{0}` InvalidLengthOp(i32), - /// failed decoding commitment proof: `{0}` - FailedDecoding(String), /// failed to verify membership FailedToVerifyMembership, } +impl From for CommitmentError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for CommitmentError {} diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index 33f1ad782..0a7251351 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -85,7 +85,7 @@ impl TryFrom for Plan { fn try_from(any: Any) -> Result { match any.type_url.as_str() { TYPE_URL => Protobuf::::decode_vec(&any.value) - .map_err(|e| UpgradeClientError::Decoding(DecodingError::FailedToDecodeProto(e))), + .map_err(|e| UpgradeClientError::Decoding(DecodingError::Protobuf(e))), _ => Err(UpgradeClientError::Decoding( DecodingError::MismatchedTypeUrls { expected: TYPE_URL.to_string(), diff --git a/ibc-core/ics24-host/types/Cargo.toml b/ibc-core/ics24-host/types/Cargo.toml index b1126d300..d603049c0 100644 --- a/ibc-core/ics24-host/types/Cargo.toml +++ b/ibc-core/ics24-host/types/Cargo.toml @@ -20,6 +20,7 @@ all-features = true [dependencies] # external dependencies +base64 = { workspace = true } borsh = { workspace = true, optional = true } derive_more = { workspace = true } displaydoc = { workspace = true } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 972b36c40..e048f1e95 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -1,9 +1,11 @@ //! Foundational error types that are applicable across multiple ibc-rs workspaces. -use alloc::string::String; +use alloc::string::{FromUtf8Error, String}; +use base64::DecodeError as Base64Error; use displaydoc::Display; use http::uri::InvalidUri; + use ibc_primitives::prelude::*; use tendermint_proto::Error as ProtoError; @@ -26,25 +28,23 @@ pub enum IdentifierError { /// Errors that result in decoding failures #[derive(Debug, Display)] pub enum DecodingError { - /// invalid identifier error: `{0}` - InvalidIdentifier(IdentifierError), + /// base64 decoding error: `{0}` + Base64(Base64Error), + /// utf-8 decoding error: `{0}` + Utf8(FromUtf8Error), + /// protobuf decoding error: `{0}` + Protobuf(ProtoError), /// invalid JSON data: `{description}` InvalidJson { description: String }, - /// invalid UTF-8 data: `{description}` - InvalidUtf8 { description: String }, /// invalid URI: `{0}` InvalidUri(InvalidUri), - /// malformed bytes that could not be decoded: `{description}` - MalformedBytes { description: String }, /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, - /// failed to decode proto; error: `{0}` - FailedToDecodeProto(ProtoError), } impl From for DecodingError { fn from(e: ProtoError) -> Self { - Self::FailedToDecodeProto(e) + Self::Protobuf(e) } } diff --git a/ibc-core/ics25-handler/types/src/msgs.rs b/ibc-core/ics25-handler/types/src/msgs.rs index 7f1b5c9a5..64b13665f 100644 --- a/ibc-core/ics25-handler/types/src/msgs.rs +++ b/ibc-core/ics25-handler/types/src/msgs.rs @@ -46,72 +46,45 @@ impl TryFrom for MsgEnvelope { // ICS2 messages CREATE_CLIENT_TYPE_URL => { // Pop out the message and then wrap it in the corresponding type. - let domain_msg = MsgCreateClient::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgCreateClient::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Client(ClientMsg::CreateClient(domain_msg))) } UPDATE_CLIENT_TYPE_URL => { - let domain_msg = MsgUpdateClient::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgUpdateClient::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Client(ClientMsg::UpdateClient(domain_msg))) } UPGRADE_CLIENT_TYPE_URL => { - let domain_msg = MsgUpgradeClient::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgUpgradeClient::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Client(ClientMsg::UpgradeClient(domain_msg))) } SUBMIT_MISBEHAVIOUR_TYPE_URL => { - let domain_msg = - MsgSubmitMisbehaviour::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgSubmitMisbehaviour::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Client(ClientMsg::Misbehaviour(domain_msg))) } // ICS03 CONN_OPEN_INIT_TYPE_URL => { - let domain_msg = - MsgConnectionOpenInit::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgConnectionOpenInit::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenInit(domain_msg))) } CONN_OPEN_TRY_TYPE_URL => { - let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenTry(domain_msg))) } CONN_OPEN_ACK_TYPE_URL => { - let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenAck(domain_msg))) } CONN_OPEN_CONFIRM_TYPE_URL => { - let domain_msg = - MsgConnectionOpenConfirm::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgConnectionOpenConfirm::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenConfirm( domain_msg, ))) @@ -119,86 +92,54 @@ impl TryFrom for MsgEnvelope { // ICS04 channel messages CHAN_OPEN_INIT_TYPE_URL => { - let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenInit(domain_msg))) } CHAN_OPEN_TRY_TYPE_URL => { - let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenTry(domain_msg))) } CHAN_OPEN_ACK_TYPE_URL => { - let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenAck(domain_msg))) } CHAN_OPEN_CONFIRM_TYPE_URL => { - let domain_msg = - MsgChannelOpenConfirm::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgChannelOpenConfirm::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenConfirm(domain_msg))) } CHAN_CLOSE_INIT_TYPE_URL => { - let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseInit(domain_msg))) } CHAN_CLOSE_CONFIRM_TYPE_URL => { - let domain_msg = - MsgChannelCloseConfirm::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgChannelCloseConfirm::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseConfirm(domain_msg))) } // ICS04 packet messages RECV_PACKET_TYPE_URL => { - let domain_msg = MsgRecvPacket::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgRecvPacket::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Packet(PacketMsg::Recv(domain_msg))) } ACKNOWLEDGEMENT_TYPE_URL => { - let domain_msg = MsgAcknowledgement::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgAcknowledgement::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Packet(PacketMsg::Ack(domain_msg))) } TIMEOUT_TYPE_URL => { - let domain_msg = MsgTimeout::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgTimeout::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Packet(PacketMsg::Timeout(domain_msg))) } TIMEOUT_ON_CLOSE_TYPE_URL => { - let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value).map_err(|e| { - RouterError::Decoding(DecodingError::MalformedBytes { - description: e.to_string(), - }) - })?; + let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value) + .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; Ok(MsgEnvelope::Packet(PacketMsg::TimeoutOnClose(domain_msg))) } _ => Err(RouterError::UnknownMessageTypeUrl(any_msg.type_url)), diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs index f6ac8f11e..a485d2341 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs @@ -97,7 +97,7 @@ impl TryFrom for MockHeader { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { MOCK_HEADER_TYPE_URL => Protobuf::::decode_vec(&raw.value) - .map_err(|e| ClientError::Decoding(DecodingError::FailedToDecodeProto(e))), + .map_err(|e| ClientError::Decoding(DecodingError::Protobuf(e))), _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { expected: MOCK_HEADER_TYPE_URL.to_string(), actual: raw.type_url, From 12056b37f111842c4ee90338ea1656a03e2f7c31 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 10:41:16 -0500 Subject: [PATCH 015/107] cargo fmt --- ibc-core/ics23-commitment/types/src/error.rs | 1 - ibc-core/ics24-host/types/src/error.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/ibc-core/ics23-commitment/types/src/error.rs b/ibc-core/ics23-commitment/types/src/error.rs index 8505de71d..511aa3fb9 100644 --- a/ibc-core/ics23-commitment/types/src/error.rs +++ b/ibc-core/ics23-commitment/types/src/error.rs @@ -1,7 +1,6 @@ //! Defines the commitment error type use displaydoc::Display; - use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index e048f1e95..da843b20b 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -5,7 +5,6 @@ use alloc::string::{FromUtf8Error, String}; use base64::DecodeError as Base64Error; use displaydoc::Display; use http::uri::InvalidUri; - use ibc_primitives::prelude::*; use tendermint_proto::Error as ProtoError; From 1252cd539bd49fab967f478b75cf92c23a054f66 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 12:49:41 -0500 Subject: [PATCH 016/107] cargo fmt --- ibc-core/ics03-connection/src/handler/mod.rs | 5 ++--- ibc-core/ics03-connection/types/src/error.rs | 4 +++- ibc-core/ics24-host/types/Cargo.toml | 1 + ibc-core/ics24-host/types/src/error.rs | 3 +++ 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/ibc-core/ics03-connection/src/handler/mod.rs b/ibc-core/ics03-connection/src/handler/mod.rs index effc57fda..15f00a645 100644 --- a/ibc-core/ics03-connection/src/handler/mod.rs +++ b/ibc-core/ics03-connection/src/handler/mod.rs @@ -1,5 +1,6 @@ use ibc_core_client::types::error::ClientError; use ibc_core_handler_types::error::ContextError; +use ibc_core_host::types::error::DecodingError; use ibc_core_host::types::identifiers::ClientId; use ibc_primitives::proto::Any; @@ -36,9 +37,7 @@ where let any_client_state = ::decode(wasm_client_state.data.as_slice()) .map_err(|e| { - ContextError::ConnectionError(ConnectionError::InvalidClientState { - description: e.to_string(), - }) + ContextError::ConnectionError(ConnectionError::Decoding(DecodingError::Prost(e))) })?; Ok(CS::try_from(any_client_state).map_err(Into::::into)?) diff --git a/ibc-core/ics03-connection/types/src/error.rs b/ibc-core/ics03-connection/types/src/error.rs index 6062dfae6..7016256b7 100644 --- a/ibc-core/ics03-connection/types/src/error.rs +++ b/ibc-core/ics03-connection/types/src/error.rs @@ -3,7 +3,7 @@ use displaydoc::Display; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::Height; -use ibc_core_host_types::error::IdentifierError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_core_host_types::identifiers::ConnectionId; use ibc_primitives::prelude::*; use ibc_primitives::{Timestamp, TimestampError}; @@ -12,6 +12,8 @@ use crate::version::Version; #[derive(Debug, Display)] pub enum ConnectionError { + /// decoding error: `{0}` + Decoding(DecodingError), /// invalid identifier: `{0}` InvalidIdentifier(IdentifierError), /// invalid state for initializing new ConnectionEnd; expected `Init` connection state and a single version diff --git a/ibc-core/ics24-host/types/Cargo.toml b/ibc-core/ics24-host/types/Cargo.toml index d603049c0..4bf0eb6a0 100644 --- a/ibc-core/ics24-host/types/Cargo.toml +++ b/ibc-core/ics24-host/types/Cargo.toml @@ -25,6 +25,7 @@ borsh = { workspace = true, optional = true } derive_more = { workspace = true } displaydoc = { workspace = true } http = { version = "1.1.0" } +prost = { workspace = true } schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index da843b20b..b026b05d0 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -6,6 +6,7 @@ use base64::DecodeError as Base64Error; use displaydoc::Display; use http::uri::InvalidUri; use ibc_primitives::prelude::*; +use prost::DecodeError as ProstError; use tendermint_proto::Error as ProtoError; /// Errors that arise when parsing identifiers. @@ -33,6 +34,8 @@ pub enum DecodingError { Utf8(FromUtf8Error), /// protobuf decoding error: `{0}` Protobuf(ProtoError), + /// prost decoding error: `{0}` + Prost(ProstError), /// invalid JSON data: `{description}` InvalidJson { description: String }, /// invalid URI: `{0}` From 66ded64ec4c34c851cac97dfd5eddc8598a19264 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 12:52:24 -0500 Subject: [PATCH 017/107] Update cw-check Cargo.lock --- ci/cw-check/Cargo.lock | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/ci/cw-check/Cargo.lock b/ci/cw-check/Cargo.lock index 2ba932c42..78413a1c2 100644 --- a/ci/cw-check/Cargo.lock +++ b/ci/cw-check/Cargo.lock @@ -658,6 +658,12 @@ dependencies = [ "paste", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "futures" version = "0.3.30" @@ -786,6 +792,17 @@ dependencies = [ "digest", ] +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + [[package]] name = "ibc-app-transfer" version = "0.54.0" @@ -1031,13 +1048,17 @@ dependencies = [ name = "ibc-core-host-types" version = "0.54.0" dependencies = [ + "base64 0.22.1", "derive_more 0.99.18", "displaydoc", + "http", "ibc-primitives", "parity-scale-codec", + "prost", "scale-info", "schemars", "serde", + "tendermint-proto", ] [[package]] @@ -1092,6 +1113,7 @@ dependencies = [ "schemars", "serde", "tendermint", + "tendermint-proto", "time", ] From 8e0a3c0cb7c5a026d3987483c698f2f1fbf1de26 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 12:56:35 -0500 Subject: [PATCH 018/107] Add necessary wasm-client feature attribute --- ibc-core/ics03-connection/src/handler/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ibc-core/ics03-connection/src/handler/mod.rs b/ibc-core/ics03-connection/src/handler/mod.rs index 15f00a645..3421ebb16 100644 --- a/ibc-core/ics03-connection/src/handler/mod.rs +++ b/ibc-core/ics03-connection/src/handler/mod.rs @@ -1,5 +1,6 @@ use ibc_core_client::types::error::ClientError; use ibc_core_handler_types::error::ContextError; +#[cfg(feature = "wasm-client")] use ibc_core_host::types::error::DecodingError; use ibc_core_host::types::identifiers::ClientId; use ibc_primitives::proto::Any; From 906dc95c3732aa5f148d754bf7c0b9bb0283035d Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 13:23:42 -0500 Subject: [PATCH 019/107] Move InvalidUri error variant back to NftTransferError --- ibc-apps/ics721-nft-transfer/types/src/class.rs | 3 +-- ibc-apps/ics721-nft-transfer/types/src/error.rs | 5 ++++- ibc-apps/ics721-nft-transfer/types/src/token.rs | 3 +-- ibc-core/ics24-host/types/Cargo.toml | 1 - ibc-core/ics24-host/types/src/error.rs | 3 --- 5 files changed, 6 insertions(+), 9 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/class.rs b/ibc-apps/ics721-nft-transfer/types/src/class.rs index c4aaa5ae5..8a7c941e6 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/class.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/class.rs @@ -4,7 +4,6 @@ use core::str::FromStr; use http::Uri; pub use ibc_app_transfer_types::{TracePath, TracePrefix}; -use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] @@ -249,7 +248,7 @@ impl FromStr for ClassUri { fn from_str(class_uri: &str) -> Result { match Uri::from_str(class_uri) { Ok(uri) => Ok(Self(uri)), - Err(err) => Err(NftTransferError::Decoding(DecodingError::InvalidUri(err))), + Err(err) => Err(NftTransferError::InvalidUri(err)), } } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index d7303ce17..c04b391b6 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -2,6 +2,7 @@ use core::convert::Infallible; use displaydoc::Display; +use http::uri::InvalidUri; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; @@ -17,8 +18,10 @@ pub enum NftTransferError { Decoding(DecodingError), /// identifier error: `{0}` Identifier(IdentifierError), - /// invalid trace `{0}` + /// invalid trace: `{0}` InvalidTrace(String), + /// invalid URI error: `{0}` + InvalidUri(InvalidUri), /// missing destination channel `{channel_id}` on port `{port_id}` MissingDestinationChannel { port_id: PortId, diff --git a/ibc-apps/ics721-nft-transfer/types/src/token.rs b/ibc-apps/ics721-nft-transfer/types/src/token.rs index 3c1e56aeb..fa11e93a1 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/token.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/token.rs @@ -3,7 +3,6 @@ use core::fmt::{self, Display}; use core::str::FromStr; use http::Uri; -use ibc_core::host::types::error::DecodingError; use ibc_core::primitives::prelude::*; #[cfg(feature = "serde")] use ibc_core::primitives::serializers; @@ -183,7 +182,7 @@ impl FromStr for TokenUri { fn from_str(token_uri: &str) -> Result { match Uri::from_str(token_uri) { Ok(uri) => Ok(Self(uri)), - Err(err) => Err(NftTransferError::Decoding(DecodingError::InvalidUri(err))), + Err(err) => Err(NftTransferError::InvalidUri(err)), } } } diff --git a/ibc-core/ics24-host/types/Cargo.toml b/ibc-core/ics24-host/types/Cargo.toml index 4bf0eb6a0..fa69e483f 100644 --- a/ibc-core/ics24-host/types/Cargo.toml +++ b/ibc-core/ics24-host/types/Cargo.toml @@ -24,7 +24,6 @@ base64 = { workspace = true } borsh = { workspace = true, optional = true } derive_more = { workspace = true } displaydoc = { workspace = true } -http = { version = "1.1.0" } prost = { workspace = true } schemars = { workspace = true, optional = true } serde = { workspace = true, optional = true } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index b026b05d0..1e583f8aa 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -4,7 +4,6 @@ use alloc::string::{FromUtf8Error, String}; use base64::DecodeError as Base64Error; use displaydoc::Display; -use http::uri::InvalidUri; use ibc_primitives::prelude::*; use prost::DecodeError as ProstError; use tendermint_proto::Error as ProtoError; @@ -38,8 +37,6 @@ pub enum DecodingError { Prost(ProstError), /// invalid JSON data: `{description}` InvalidJson { description: String }, - /// invalid URI: `{0}` - InvalidUri(InvalidUri), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, } From 98fb94206a0ea8ef8fb878a6e7fc527c35ba714e Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 13:26:21 -0500 Subject: [PATCH 020/107] Regenerate cw hcheck cargo.lock --- ci/cw-check/Cargo.lock | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/ci/cw-check/Cargo.lock b/ci/cw-check/Cargo.lock index 78413a1c2..e0be4007f 100644 --- a/ci/cw-check/Cargo.lock +++ b/ci/cw-check/Cargo.lock @@ -658,12 +658,6 @@ dependencies = [ "paste", ] -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - [[package]] name = "futures" version = "0.3.30" @@ -792,17 +786,6 @@ dependencies = [ "digest", ] -[[package]] -name = "http" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "ibc-app-transfer" version = "0.54.0" @@ -1051,7 +1034,6 @@ dependencies = [ "base64 0.22.1", "derive_more 0.99.18", "displaydoc", - "http", "ibc-primitives", "parity-scale-codec", "prost", From 8a7074a21f9506b23dcf18e0895102e9926b9b68 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 28 Aug 2024 13:43:52 -0500 Subject: [PATCH 021/107] Add serde feature attribute --- ibc-apps/ics721-nft-transfer/types/src/data.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ibc-apps/ics721-nft-transfer/types/src/data.rs b/ibc-apps/ics721-nft-transfer/types/src/data.rs index bbbfb3f3d..a54d990af 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/data.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/data.rs @@ -6,6 +6,7 @@ use core::str::FromStr; use base64::prelude::BASE64_STANDARD; #[cfg(feature = "serde")] use base64::Engine; +#[cfg(feature = "serde")] use ibc_core::host::types::error::DecodingError; use ibc_core::primitives::prelude::*; use mime::Mime; From 691887fa2dd0be9feebbb848cf9dce9597ca9f7a Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 13:50:27 -0500 Subject: [PATCH 022/107] Remove ClientError::InvalidClientIdentifier error variant in favor of DecodingError::InvalidIdentifier --- ibc-core/ics02-client/types/src/error.rs | 6 +----- ibc-core/ics02-client/types/src/msgs/misbehaviour.rs | 3 ++- ibc-core/ics02-client/types/src/msgs/recover_client.rs | 5 +++-- ibc-core/ics02-client/types/src/msgs/update_client.rs | 3 ++- ibc-core/ics02-client/types/src/msgs/upgrade_client.rs | 3 ++- ibc-core/ics24-host/types/src/error.rs | 2 ++ 6 files changed, 12 insertions(+), 10 deletions(-) diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index e11268cd7..5c3d0f0e7 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -4,7 +4,7 @@ use core::convert::Infallible; use displaydoc::Display; use ibc_core_commitment_types::error::CommitmentError; -use ibc_core_host_types::error::{DecodingError, IdentifierError}; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; @@ -31,9 +31,6 @@ pub enum ClientError { InvalidConsensusStateType(String), /// invalid update client message InvalidUpdateClientMessage, - // TODO(seanchen1991): Should this be removed in favor of DecodingError::InvalidIdentifier? - /// invalid client identifier: `{0}` - InvalidClientIdentifier(IdentifierError), /// invalid raw header: `{description}` InvalidRawHeader { description: String }, /// invalid misbehaviour type: `{0}` @@ -121,7 +118,6 @@ impl From for ClientError { impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::InvalidClientIdentifier(e) => Some(e), Self::FailedICS23Verification(e) => Some(e), Self::ClientStatus(e) => Some(e), Self::Decoding(e) => Some(e), diff --git a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs index 7d14f133f..e5b083196 100644 --- a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs +++ b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs @@ -1,5 +1,6 @@ //! Definition of domain type message `MsgSubmitMisbehaviour`. +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -48,7 +49,7 @@ impl TryFrom for MsgSubmitMisbehaviour { client_id: raw .client_id .parse() - .map_err(ClientError::InvalidClientIdentifier)?, + .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, misbehaviour: raw_misbehaviour, signer: raw.signer.into(), }) diff --git a/ibc-core/ics02-client/types/src/msgs/recover_client.rs b/ibc-core/ics02-client/types/src/msgs/recover_client.rs index 62fc738fe..d71c8d90c 100644 --- a/ibc-core/ics02-client/types/src/msgs/recover_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/recover_client.rs @@ -1,5 +1,6 @@ //! Definition of domain type message `MsgRecoverClient`. +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -45,11 +46,11 @@ impl TryFrom for MsgRecoverClient { subject_client_id: raw .subject_client_id .parse() - .map_err(ClientError::InvalidClientIdentifier)?, + .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, substitute_client_id: raw .substitute_client_id .parse() - .map_err(ClientError::InvalidClientIdentifier)?, + .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, signer: raw.signer.into(), }) } diff --git a/ibc-core/ics02-client/types/src/msgs/update_client.rs b/ibc-core/ics02-client/types/src/msgs/update_client.rs index 9eb088017..26d719fac 100644 --- a/ibc-core/ics02-client/types/src/msgs/update_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/update_client.rs @@ -1,5 +1,6 @@ //! Definition of domain type message `MsgUpdateClient`. +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -37,7 +38,7 @@ impl TryFrom for MsgUpdateClient { client_id: raw .client_id .parse() - .map_err(ClientError::InvalidClientIdentifier)?, + .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, client_message: raw .client_message .ok_or(ClientError::MissingRawClientMessage)?, diff --git a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs index c3d9a956b..1fbff9e7d 100644 --- a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs @@ -4,6 +4,7 @@ use core::str::FromStr; use ibc_core_commitment_types::commitment::CommitmentProofBytes; use ibc_core_commitment_types::error::CommitmentError; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -78,7 +79,7 @@ impl TryFrom for MsgUpgradeClient { Ok(MsgUpgradeClient { client_id: ClientId::from_str(&proto_msg.client_id) - .map_err(ClientError::InvalidClientIdentifier)?, + .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, upgraded_client_state: raw_client_state, upgraded_consensus_state: raw_consensus_state, proof_upgrade_client: c_bytes, diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 1e583f8aa..1fa203a65 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -37,6 +37,8 @@ pub enum DecodingError { Prost(ProstError), /// invalid JSON data: `{description}` InvalidJson { description: String }, + /// invalid identifier error: `{0}` + InvalidIdentifier(IdentifierError), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, } From ea9c83d66ab8fed7f271b2bb387fd4e65d0170ba Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 15:05:19 -0500 Subject: [PATCH 023/107] Add derive_more::From on NftTransferError --- ibc-apps/ics20-transfer/types/src/error.rs | 3 ++- .../ics721-nft-transfer/types/src/error.rs | 21 ++----------------- 2 files changed, 4 insertions(+), 20 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 291a12635..ff50b055c 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -2,13 +2,14 @@ use core::convert::Infallible; use displaydoc::Display; +use uint::FromDecStrErr; + use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -use uint::FromDecStrErr; #[derive(Display, Debug)] pub enum TokenTransferError { diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index c04b391b6..281450111 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -3,6 +3,7 @@ use core::convert::Infallible; use displaydoc::Display; use http::uri::InvalidUri; + use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; @@ -10,7 +11,7 @@ use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -#[derive(Display, Debug)] +#[derive(Display, Debug, derive_more::From)] pub enum NftTransferError { /// context error: `{0}` ContextError(ContextError), @@ -64,24 +65,6 @@ impl From for NftTransferError { } } -impl From for NftTransferError { - fn from(e: ContextError) -> Self { - Self::ContextError(e) - } -} - -impl From for NftTransferError { - fn from(e: IdentifierError) -> Self { - Self::Identifier(e) - } -} - -impl From for NftTransferError { - fn from(e: DecodingError) -> Self { - Self::Decoding(e) - } -} - impl From for StatusValue { fn from(e: NftTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") From d79d9ead411e216814bc454a65d70f765a594fab Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 15:33:28 -0500 Subject: [PATCH 024/107] Stashing changes --- ibc-apps/ics20-transfer/types/src/error.rs | 8 ++++---- ibc-apps/ics721-nft-transfer/types/src/error.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index ff50b055c..252ab1727 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -17,8 +17,8 @@ pub enum TokenTransferError { ContextError(ContextError), /// decoding error: `{0}` Decoding(DecodingError), - /// invalid identifier: `{0}` - InvalidIdentifier(IdentifierError), + /// identifier error: `{0}` + Identifier(IdentifierError), /// invalid trace: `{0}` InvalidTrace(String), /// invalid amount: `{0}` @@ -55,7 +55,7 @@ impl std::error::Error for TokenTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::ContextError(e) => Some(e), - Self::InvalidIdentifier(e) => Some(e), + Self::Identifier(e) => Some(e), Self::InvalidAmount(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, @@ -77,7 +77,7 @@ impl From for TokenTransferError { impl From for TokenTransferError { fn from(e: IdentifierError) -> Self { - Self::InvalidIdentifier(e) + Self::Identifier(e) } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 281450111..c847e5589 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -11,7 +11,7 @@ use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -#[derive(Display, Debug, derive_more::From)] +#[derive(Display, Debug)] pub enum NftTransferError { /// context error: `{0}` ContextError(ContextError), From 33ff24624a2e8e11b5632e5b8f01dde0ec7686c0 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 15:33:32 -0500 Subject: [PATCH 025/107] Revert "Add derive_more::From on NftTransferError" This reverts commit ea9c83d66ab8fed7f271b2bb387fd4e65d0170ba. --- ibc-apps/ics20-transfer/types/src/error.rs | 3 +-- .../ics721-nft-transfer/types/src/error.rs | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 252ab1727..72a68f4c3 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -2,14 +2,13 @@ use core::convert::Infallible; use displaydoc::Display; -use uint::FromDecStrErr; - use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; +use uint::FromDecStrErr; #[derive(Display, Debug)] pub enum TokenTransferError { diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index c847e5589..c04b391b6 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -3,7 +3,6 @@ use core::convert::Infallible; use displaydoc::Display; use http::uri::InvalidUri; - use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::ContextError; @@ -65,6 +64,24 @@ impl From for NftTransferError { } } +impl From for NftTransferError { + fn from(e: ContextError) -> Self { + Self::ContextError(e) + } +} + +impl From for NftTransferError { + fn from(e: IdentifierError) -> Self { + Self::Identifier(e) + } +} + +impl From for NftTransferError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + impl From for StatusValue { fn from(e: NftTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") From 77b42b1e55254e0f9432c3dc941b6a15ab9ee3e1 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 15:42:40 -0500 Subject: [PATCH 026/107] Remove RouterError::UnknownMessageTypeUrl --- ibc-core/ics24-host/types/src/error.rs | 2 + ibc-core/ics25-handler/types/src/msgs.rs | 47 ++++++++++++----------- ibc-core/ics26-routing/types/src/error.rs | 4 +- 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 1fa203a65..ad0c98b3c 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -41,6 +41,8 @@ pub enum DecodingError { InvalidIdentifier(IdentifierError), /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, + /// unknown type URL: `{0}` + UnknownTypeUrl(String), } impl From for DecodingError { diff --git a/ibc-core/ics25-handler/types/src/msgs.rs b/ibc-core/ics25-handler/types/src/msgs.rs index 64b13665f..b2a34c773 100644 --- a/ibc-core/ics25-handler/types/src/msgs.rs +++ b/ibc-core/ics25-handler/types/src/msgs.rs @@ -46,45 +46,45 @@ impl TryFrom for MsgEnvelope { // ICS2 messages CREATE_CLIENT_TYPE_URL => { // Pop out the message and then wrap it in the corresponding type. - let domain_msg = MsgCreateClient::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + let domain_msg = + MsgCreateClient::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Client(ClientMsg::CreateClient(domain_msg))) } UPDATE_CLIENT_TYPE_URL => { - let domain_msg = MsgUpdateClient::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + let domain_msg = + MsgUpdateClient::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Client(ClientMsg::UpdateClient(domain_msg))) } UPGRADE_CLIENT_TYPE_URL => { let domain_msg = MsgUpgradeClient::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Client(ClientMsg::UpgradeClient(domain_msg))) } SUBMIT_MISBEHAVIOUR_TYPE_URL => { let domain_msg = MsgSubmitMisbehaviour::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Client(ClientMsg::Misbehaviour(domain_msg))) } // ICS03 CONN_OPEN_INIT_TYPE_URL => { let domain_msg = MsgConnectionOpenInit::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenInit(domain_msg))) } CONN_OPEN_TRY_TYPE_URL => { let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenTry(domain_msg))) } CONN_OPEN_ACK_TYPE_URL => { let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenAck(domain_msg))) } CONN_OPEN_CONFIRM_TYPE_URL => { let domain_msg = MsgConnectionOpenConfirm::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenConfirm( domain_msg, ))) @@ -93,56 +93,57 @@ impl TryFrom for MsgEnvelope { // ICS04 channel messages CHAN_OPEN_INIT_TYPE_URL => { let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenInit(domain_msg))) } CHAN_OPEN_TRY_TYPE_URL => { let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenTry(domain_msg))) } CHAN_OPEN_ACK_TYPE_URL => { let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenAck(domain_msg))) } CHAN_OPEN_CONFIRM_TYPE_URL => { let domain_msg = MsgChannelOpenConfirm::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenConfirm(domain_msg))) } CHAN_CLOSE_INIT_TYPE_URL => { let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseInit(domain_msg))) } CHAN_CLOSE_CONFIRM_TYPE_URL => { let domain_msg = MsgChannelCloseConfirm::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseConfirm(domain_msg))) } // ICS04 packet messages RECV_PACKET_TYPE_URL => { - let domain_msg = MsgRecvPacket::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + let domain_msg = + MsgRecvPacket::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Packet(PacketMsg::Recv(domain_msg))) } ACKNOWLEDGEMENT_TYPE_URL => { let domain_msg = MsgAcknowledgement::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Packet(PacketMsg::Ack(domain_msg))) } TIMEOUT_TYPE_URL => { - let domain_msg = MsgTimeout::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + let domain_msg = + MsgTimeout::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Packet(PacketMsg::Timeout(domain_msg))) } TIMEOUT_ON_CLOSE_TYPE_URL => { let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value) - .map_err(|e| RouterError::Decoding(DecodingError::Protobuf(e)))?; + .map_err(DecodingError::Protobuf)?; Ok(MsgEnvelope::Packet(PacketMsg::TimeoutOnClose(domain_msg))) } - _ => Err(RouterError::UnknownMessageTypeUrl(any_msg.type_url)), + + _ => Err(DecodingError::UnknownTypeUrl(any_msg.type_url))?, } } } diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index aab2fa8fd..cb998dd76 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -4,14 +4,12 @@ use ibc_core_host_types::identifiers::PortId; use ibc_primitives::prelude::*; /// Error type for the router module. -#[derive(Debug, Display)] +#[derive(Debug, Display, derive_more::From)] pub enum RouterError { /// decoding error: `{0}` Decoding(DecodingError), /// missing module MissingModule, - /// unknown message type URL `{0}` - UnknownMessageTypeUrl(String), /// unknown port `{0}` UnknownPort(PortId), } From 802462271d1a34a28f7c247b222774975797053d Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 16:00:40 -0500 Subject: [PATCH 027/107] Add derive_more::From on TokenTransferError --- ibc-apps/ics20-transfer/types/src/coin.rs | 5 +++- ibc-apps/ics20-transfer/types/src/denom.rs | 5 +++- ibc-apps/ics20-transfer/types/src/error.rs | 28 +++++++++---------- .../ics20-transfer/types/src/msgs/transfer.rs | 13 ++++----- .../types/src/msgs/transfer.rs | 13 ++++----- 5 files changed, 31 insertions(+), 33 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/coin.rs b/ibc-apps/ics20-transfer/types/src/coin.rs index 9470bbdbc..2f091eb84 100644 --- a/ibc-apps/ics20-transfer/types/src/coin.rs +++ b/ibc-apps/ics20-transfer/types/src/coin.rs @@ -76,7 +76,10 @@ where .chars() .all(|x| x.is_alphanumeric() || VALID_DENOM_CHARACTERS.contains(x)) }) - .ok_or_else(|| TokenTransferError::InvalidCoin(coin_str.to_string()))?; + .ok_or_else(|| TokenTransferError::FailedToParseType { + expected: "Coin".to_string(), + actual: coin_str.to_string(), + })?; Ok(Coin { amount: amount.parse()?, diff --git a/ibc-apps/ics20-transfer/types/src/denom.rs b/ibc-apps/ics20-transfer/types/src/denom.rs index cc814280f..b668813a5 100644 --- a/ibc-apps/ics20-transfer/types/src/denom.rs +++ b/ibc-apps/ics20-transfer/types/src/denom.rs @@ -219,7 +219,10 @@ impl FromStr for TracePath { remaining_parts .is_none() .then_some(trace_path) - .ok_or_else(|| TokenTransferError::InvalidTrace(s.to_string())) + .ok_or_else(|| TokenTransferError::FailedToParseType { + expected: "TracePath".to_string(), + actual: s.to_string(), + }) } } diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 72a68f4c3..892dcc6ee 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -10,7 +10,7 @@ use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use uint::FromDecStrErr; -#[derive(Display, Debug)] +#[derive(Display, Debug, derive_more::From)] pub enum TokenTransferError { /// context error: `{0}` ContextError(ContextError), @@ -18,12 +18,8 @@ pub enum TokenTransferError { Decoding(DecodingError), /// identifier error: `{0}` Identifier(IdentifierError), - /// invalid trace: `{0}` - InvalidTrace(String), /// invalid amount: `{0}` InvalidAmount(FromDecStrErr), - /// invalid coin: `{0}` - InvalidCoin(String), /// missing token MissingToken, /// missing destination channel `{channel_id}` on port `{port_id}` @@ -43,6 +39,8 @@ pub enum TokenTransferError { // to a host-relevant error /// failed to parse account ID FailedToParseAccount, + /// failed to parse `{expected}` from `{actual}` + FailedToParseType { expected: String, actual: String }, /// channel cannot be closed UnsupportedClosedChannel, /// empty base denomination @@ -68,17 +66,17 @@ impl From for TokenTransferError { } } -impl From for TokenTransferError { - fn from(e: ContextError) -> Self { - Self::ContextError(e) - } -} +// impl From for TokenTransferError { +// fn from(e: ContextError) -> Self { +// Self::ContextError(e) +// } +// } -impl From for TokenTransferError { - fn from(e: IdentifierError) -> Self { - Self::Identifier(e) - } -} +// impl From for TokenTransferError { +// fn from(e: IdentifierError) -> Self { +// Self::Identifier(e) +// } +// } impl From for StatusValue { fn from(e: TokenTransferError) -> Self { diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index eefcdbf5d..fcc23863b 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -105,14 +105,11 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - TYPE_URL => MsgTransfer::decode_vec(&raw.value) - .map_err(|e| TokenTransferError::Decoding(DecodingError::Protobuf(e))), - _ => Err(TokenTransferError::Decoding( - DecodingError::MismatchedTypeUrls { - expected: TYPE_URL.to_string(), - actual: raw.type_url, - }, - )), + TYPE_URL => Ok(MsgTransfer::decode_vec(&raw.value).map_err(DecodingError::Protobuf)?), + _ => Err(DecodingError::MismatchedTypeUrls { + expected: TYPE_URL.to_string(), + actual: raw.type_url, + })?, } } } diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index abd73e681..5b2bfb077 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -123,14 +123,11 @@ impl TryFrom for MsgTransfer { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - TYPE_URL => MsgTransfer::decode_vec(&raw.value) - .map_err(|e| NftTransferError::Decoding(DecodingError::Protobuf(e))), - _ => Err(NftTransferError::Decoding( - DecodingError::MismatchedTypeUrls { - expected: TYPE_URL.to_string(), - actual: raw.type_url, - }, - )), + TYPE_URL => Ok(MsgTransfer::decode_vec(&raw.value).map_err(DecodingError::Protobuf)?), + _ => Err(DecodingError::MismatchedTypeUrls { + expected: TYPE_URL.to_string(), + actual: raw.type_url, + })?, } } } From bfbc79ef2590f364f5e36c0ed78ce0c968e6d0a2 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 16:04:01 -0500 Subject: [PATCH 028/107] Add derive_more to NftTransferError --- ibc-apps/ics20-transfer/types/src/error.rs | 12 ----------- .../ics721-nft-transfer/types/src/error.rs | 20 +------------------ 2 files changed, 1 insertion(+), 31 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 892dcc6ee..31180b646 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -66,18 +66,6 @@ impl From for TokenTransferError { } } -// impl From for TokenTransferError { -// fn from(e: ContextError) -> Self { -// Self::ContextError(e) -// } -// } - -// impl From for TokenTransferError { -// fn from(e: IdentifierError) -> Self { -// Self::Identifier(e) -// } -// } - impl From for StatusValue { fn from(e: TokenTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index c04b391b6..6826f4a58 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -10,7 +10,7 @@ use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -#[derive(Display, Debug)] +#[derive(Display, Debug, derive_more::From)] pub enum NftTransferError { /// context error: `{0}` ContextError(ContextError), @@ -64,24 +64,6 @@ impl From for NftTransferError { } } -impl From for NftTransferError { - fn from(e: ContextError) -> Self { - Self::ContextError(e) - } -} - -impl From for NftTransferError { - fn from(e: IdentifierError) -> Self { - Self::Identifier(e) - } -} - -impl From for NftTransferError { - fn from(e: DecodingError) -> Self { - Self::Decoding(e) - } -} - impl From for StatusValue { fn from(e: NftTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") From 531587c4394909c3f0be2721b577d8f34a578d75 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 29 Aug 2024 16:07:12 -0500 Subject: [PATCH 029/107] Remove tendermint-proto dependency from ibc-primitives --- ibc-primitives/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/ibc-primitives/Cargo.toml b/ibc-primitives/Cargo.toml index 1e090acf6..dac541f33 100644 --- a/ibc-primitives/Cargo.toml +++ b/ibc-primitives/Cargo.toml @@ -33,7 +33,6 @@ ibc-proto = { workspace = true } # cosmos dependencies tendermint = { workspace = true } -tendermint-proto = { workspace = true } # parity dependencies parity-scale-codec = { workspace = true, optional = true } From dc5906edf30fa2b756b3aa34271889078bc840f3 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 30 Aug 2024 09:32:58 -0500 Subject: [PATCH 030/107] Remove StatusError --- .../src/client_state/common.rs | 6 ++--- .../ics02-client/src/handler/create_client.rs | 6 ++--- .../src/handler/recover_client.rs | 6 ++--- .../ics02-client/src/handler/update_client.rs | 3 +-- .../src/handler/upgrade_client.rs | 3 +-- ibc-core/ics02-client/types/src/error.rs | 15 ++++------- ibc-core/ics02-client/types/src/status.rs | 27 ++++++------------- .../src/handler/conn_open_ack.rs | 3 +-- .../src/handler/conn_open_confirm.rs | 4 +-- .../src/handler/conn_open_init.rs | 4 +-- .../src/handler/conn_open_try.rs | 3 +-- .../src/handler/acknowledgement.rs | 4 +-- .../src/handler/chan_close_confirm.rs | 4 +-- .../src/handler/chan_close_init.rs | 4 +-- .../src/handler/chan_open_ack.rs | 4 +-- .../src/handler/chan_open_confirm.rs | 4 +-- .../src/handler/chan_open_init.rs | 4 +-- .../src/handler/chan_open_try.rs | 4 +-- .../ics04-channel/src/handler/recv_packet.rs | 4 +-- .../ics04-channel/src/handler/send_packet.rs | 4 +-- ibc-core/ics04-channel/src/handler/timeout.rs | 4 +-- .../src/handler/timeout_on_close.rs | 4 +-- .../cosmos/src/validate_self_client.rs | 6 ++--- ibc-query/src/error.rs | 10 ------- .../testapp/ibc/clients/mock/client_state.rs | 6 ++--- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 6 ++--- .../tests/core/ics02_client/create_client.rs | 20 +++++++------- 27 files changed, 52 insertions(+), 120 deletions(-) diff --git a/ibc-clients/ics07-tendermint/src/client_state/common.rs b/ibc-clients/ics07-tendermint/src/client_state/common.rs index 4528447cf..5c573135f 100644 --- a/ibc-clients/ics07-tendermint/src/client_state/common.rs +++ b/ibc-clients/ics07-tendermint/src/client_state/common.rs @@ -4,7 +4,7 @@ use ibc_client_tendermint_types::{client_type as tm_client_type, ClientState as use ibc_core_client::context::client_state::ClientStateCommon; use ibc_core_client::context::consensus_state::ConsensusState; use ibc_core_client::types::error::{ClientError, UpgradeClientError}; -use ibc_core_client::types::{Height, Status, StatusError}; +use ibc_core_client::types::{Height, Status}; use ibc_core_commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; @@ -166,9 +166,7 @@ pub fn verify_consensus_state( }; if consensus_state_status(&tm_consensus_state, host_timestamp, trusting_period)?.is_expired() { - return Err(ClientError::ClientStatus(StatusError::UnexpectedStatus( - Status::Expired, - ))); + return Err(ClientError::UnexpectedStatus(Status::Expired)); } Ok(()) diff --git a/ibc-core/ics02-client/src/handler/create_client.rs b/ibc-core/ics02-client/src/handler/create_client.rs index 1663c2cc4..8c7010443 100644 --- a/ibc-core/ics02-client/src/handler/create_client.rs +++ b/ibc-core/ics02-client/src/handler/create_client.rs @@ -4,7 +4,7 @@ use ibc_core_client_context::prelude::*; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::events::CreateClient; use ibc_core_client_types::msgs::MsgCreateClient; -use ibc_core_client_types::{Status, StatusError}; +use ibc_core_client_types::Status; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::{ClientStateMut, ClientStateRef, ExecutionContext, ValidationContext}; @@ -36,9 +36,7 @@ where let status = client_state.status(client_val_ctx, &client_id)?; if status.is_frozen() { - return Err( - ClientError::ClientStatus(StatusError::UnexpectedStatus(Status::Frozen)).into(), - ); + return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); }; let host_timestamp = ctx.host_timestamp()?; diff --git a/ibc-core/ics02-client/src/handler/recover_client.rs b/ibc-core/ics02-client/src/handler/recover_client.rs index c48aae2ec..7994edab3 100644 --- a/ibc-core/ics02-client/src/handler/recover_client.rs +++ b/ibc-core/ics02-client/src/handler/recover_client.rs @@ -39,14 +39,12 @@ where substitute_client_state .status(ctx.get_client_validation_context(), &substitute_client_id)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; // TODO(seanchen1991): Why is this `map_err` necessary? + .verify_is_active()?; // Verify that the subject client is inactive, i.e., that it is either frozen or expired subject_client_state .status(ctx.get_client_validation_context(), &subject_client_id)? - .verify_is_inactive() - .map_err(ClientError::ClientStatus)?; + .verify_is_inactive()?; // Check that the subject client state and substitute client states match, i.e., that // all their respective client state parameters match except for frozen height, latest diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index d2a18b8b5..66ce95ce1 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -26,8 +26,7 @@ where client_state .status(client_val_ctx, &client_id)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; let client_message = msg.client_message(); diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index 475e86c1d..7dce4cdaa 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -28,8 +28,7 @@ where // Check if the client is active. old_client_state .status(client_val_ctx, &client_id)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; // Read the latest consensus state from the host chain store. let old_client_cons_state_path = ClientConsensusStatePath::new( diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 5c3d0f0e7..b6eaed20d 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -10,7 +10,7 @@ use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; use crate::height::Height; -use crate::StatusError; +use crate::Status; /// Encodes all the possible client errors #[derive(Debug, Display)] @@ -19,8 +19,6 @@ pub enum ClientError { Upgrade(UpgradeClientError), /// decoding error: `{0}` Decoding(DecodingError), - /// client status error: `{0}` - ClientStatus(StatusError), /// invalid header type: `{0}` InvalidHeaderType(String), /// invalid trust threshold: `{numerator}`/`{denominator}` @@ -45,6 +43,8 @@ pub enum ClientError { InvalidAttributeKey(String), /// invalid attribute value: `{0}` InvalidAttributeValue(String), + /// invalid status: `{0}` + InvalidStatus(String), /// missing client state for client: `{0}` MissingClientState(ClientId), /// missing consensus state for client `{client_id}` at height `{height}` @@ -65,6 +65,8 @@ pub enum ClientError { MissingAttributeKey, /// missing attribute value MissingAttributeValue, + /// unexpected status found: `{0}` + UnexpectedStatus(Status), /// client state already exists: `{0}` AlreadyExistingClientState(ClientId), /// mismatched client recovery states @@ -108,18 +110,11 @@ impl From for ClientError { } } -impl From for ClientError { - fn from(e: StatusError) -> Self { - Self::ClientStatus(e) - } -} - #[cfg(feature = "std")] impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::FailedICS23Verification(e) => Some(e), - Self::ClientStatus(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-core/ics02-client/types/src/status.rs b/ibc-core/ics02-client/types/src/status.rs index a16d1218d..25f28d3cf 100644 --- a/ibc-core/ics02-client/types/src/status.rs +++ b/ibc-core/ics02-client/types/src/status.rs @@ -1,9 +1,10 @@ use core::fmt::{Debug, Display, Formatter}; use core::str::FromStr; -use displaydoc::Display; use ibc_primitives::prelude::*; +use crate::error::ClientError; + /// `UpdateKind` represents the 2 ways that a client can be updated /// in IBC: either through a `MsgUpdateClient`, or a `MsgSubmitMisbehaviour`. #[derive(Clone, Debug, PartialEq, Eq)] @@ -32,15 +33,6 @@ pub enum Status { Unauthorized, } -/// Encapsulates Status-related errors -#[derive(Debug, Display)] -pub enum StatusError { - /// invalid client status: `{0}` - InvalidStatus(String), - /// unexpected status found: `{0}` - UnexpectedStatus(Status), -} - impl Status { pub fn is_active(&self) -> bool { *self == Status::Active @@ -55,18 +47,18 @@ impl Status { } /// Checks whether the status is active; returns `Err` if not. - pub fn verify_is_active(&self) -> Result<(), StatusError> { + pub fn verify_is_active(&self) -> Result<(), ClientError> { match self { Self::Active => Ok(()), - &status => Err(StatusError::UnexpectedStatus(status)), + &status => Err(ClientError::UnexpectedStatus(status)), } } /// Checks whether the client is either frozen or expired; returns `Err` if not. - pub fn verify_is_inactive(&self) -> Result<(), StatusError> { + pub fn verify_is_inactive(&self) -> Result<(), ClientError> { match self { Self::Frozen | Self::Expired => Ok(()), - &status => Err(StatusError::UnexpectedStatus(status)), + &status => Err(ClientError::UnexpectedStatus(status)), } } } @@ -78,7 +70,7 @@ impl Display for Status { } impl FromStr for Status { - type Err = StatusError; + type Err = ClientError; fn from_str(s: &str) -> Result { match s { @@ -86,10 +78,7 @@ impl FromStr for Status { "FROZEN" => Ok(Status::Frozen), "EXPIRED" => Ok(Status::Expired), "UNAUTHORIZED" => Ok(Status::Unauthorized), - _ => Err(StatusError::InvalidStatus(s.to_string())), + _ => Err(ClientError::InvalidStatus(s.to_string())), } } } - -#[cfg(feature = "std")] -impl std::error::Error for StatusError {} diff --git a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs index 493bb1f8d..91027ff43 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs @@ -67,8 +67,7 @@ where client_state_of_b_on_a .status(client_val_ctx_a, vars.client_id_on_a())? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_b_on_a.validate_proof_height(msg.proofs_height_on_b)?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs index b622a3037..1987c047f 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs @@ -1,7 +1,6 @@ //! Protocol logic specific to processing ICS3 messages of type `MsgConnectionOpenConfirm`. use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection_types::error::ConnectionError; use ibc_core_connection_types::events::OpenConfirm; use ibc_core_connection_types::msgs::MsgConnectionOpenConfirm; @@ -48,8 +47,7 @@ where client_state_of_a_on_b .status(client_val_ctx_b, client_id_on_b)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_init.rs b/ibc-core/ics03-connection/src/handler/conn_open_init.rs index f6196a787..8d4286616 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_init.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_init.rs @@ -1,6 +1,5 @@ //! Protocol logic specific to ICS3 messages of type `MsgConnectionOpenInit`. use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection_types::events::OpenInit; use ibc_core_connection_types::msgs::MsgConnectionOpenInit; use ibc_core_connection_types::{ConnectionEnd, Counterparty, State}; @@ -24,8 +23,7 @@ where client_state_of_b_on_a .status(client_val_ctx_a, &msg.client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; if let Some(version) = msg.version { version.verify_is_supported(&ctx_a.get_compatible_versions())?; diff --git a/ibc-core/ics03-connection/src/handler/conn_open_try.rs b/ibc-core/ics03-connection/src/handler/conn_open_try.rs index 4c86a6261..fbb013824 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_try.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_try.rs @@ -67,8 +67,7 @@ where client_state_of_a_on_b .status(client_val_ctx_b, &msg.client_id_on_b)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_a_on_b.validate_proof_height(msg.proofs_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/acknowledgement.rs b/ibc-core/ics04-channel/src/handler/acknowledgement.rs index a0cb98e86..e5f484f2b 100644 --- a/ibc-core/ics04-channel/src/handler/acknowledgement.rs +++ b/ibc-core/ics04-channel/src/handler/acknowledgement.rs @@ -4,7 +4,6 @@ use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_channel_types::events::AcknowledgePacket; use ibc_core_channel_types::msgs::MsgAcknowledgement; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::State as ConnectionState; use ibc_core_handler_types::error::ContextError; @@ -177,8 +176,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs index fb3479864..5b315ecbf 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs @@ -5,7 +5,6 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::CloseConfirm; use ibc_core_channel_types::msgs::MsgChannelCloseConfirm; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -114,8 +113,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-core/ics04-channel/src/handler/chan_close_init.rs index ba2bd2585..6bdab73f6 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_init.rs @@ -4,7 +4,6 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::CloseInit; use ibc_core_channel_types::msgs::MsgChannelCloseInit; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; @@ -111,8 +110,7 @@ where let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; Ok(()) } diff --git a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs index bc3506652..f6271bcd0 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs @@ -4,7 +4,6 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::OpenAck; use ibc_core_channel_types::msgs::MsgChannelOpenAck; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -115,8 +114,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs index 71ad5a00f..2ea7078a4 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs @@ -5,7 +5,6 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::OpenConfirm; use ibc_core_channel_types::msgs::MsgChannelOpenConfirm; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -119,8 +118,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/chan_open_init.rs b/ibc-core/ics04-channel/src/handler/chan_open_init.rs index 0553b7b1d..58a161d0b 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_init.rs @@ -4,7 +4,6 @@ use ibc_core_channel_types::channel::{ChannelEnd, Counterparty, State}; use ibc_core_channel_types::events::OpenInit; use ibc_core_channel_types::msgs::MsgChannelOpenInit; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::ChannelId; @@ -126,8 +125,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; let conn_version = conn_end_on_a.versions(); diff --git a/ibc-core/ics04-channel/src/handler/chan_open_try.rs b/ibc-core/ics04-channel/src/handler/chan_open_try.rs index 738f8d67c..48138ce69 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_try.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_try.rs @@ -5,7 +5,6 @@ use ibc_core_channel_types::error::ChannelError; use ibc_core_channel_types::events::OpenTry; use ibc_core_channel_types::msgs::MsgChannelOpenTry; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -141,8 +140,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index fe7230b20..f3229f493 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -5,7 +5,6 @@ use ibc_core_channel_types::events::{ReceivePacket, WriteAcknowledgement}; use ibc_core_channel_types::msgs::MsgRecvPacket; use ibc_core_channel_types::packet::Receipt; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::State as ConnectionState; use ibc_core_handler_types::error::ContextError; @@ -187,8 +186,7 @@ where client_state_of_a_on_b .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/send_packet.rs b/ibc-core/ics04-channel/src/handler/send_packet.rs index 6247197cf..6680bf6fb 100644 --- a/ibc-core/ics04-channel/src/handler/send_packet.rs +++ b/ibc-core/ics04-channel/src/handler/send_packet.rs @@ -4,7 +4,6 @@ use ibc_core_channel_types::error::PacketError; use ibc_core_channel_types::events::SendPacket; use ibc_core_channel_types::packet::Packet; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ @@ -60,8 +59,7 @@ pub fn send_packet_validate( client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; let latest_height_on_a = client_state_of_b_on_a.latest_height(); diff --git a/ibc-core/ics04-channel/src/handler/timeout.rs b/ibc-core/ics04-channel/src/handler/timeout.rs index 325803985..9ce98bc0a 100644 --- a/ibc-core/ics04-channel/src/handler/timeout.rs +++ b/ibc-core/ics04-channel/src/handler/timeout.rs @@ -4,7 +4,6 @@ use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_channel_types::events::{ChannelClosed, TimeoutPacket}; use ibc_core_channel_types::msgs::{MsgTimeout, MsgTimeoutOnClose}; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_handler_types::error::ContextError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; @@ -187,8 +186,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs index 0d31ae234..c52225f81 100644 --- a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs +++ b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs @@ -3,7 +3,6 @@ use ibc_core_channel_types::commitment::compute_packet_commitment; use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_channel_types::msgs::MsgTimeoutOnClose; use ibc_core_client::context::prelude::*; -use ibc_core_client::types::error::ClientError; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -71,8 +70,7 @@ where client_state_of_b_on_a .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active() - .map_err(ClientError::ClientStatus)?; + .verify_is_active()?; client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index 6f72e2937..f6d66994d 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -2,7 +2,7 @@ use core::time::Duration; use ibc_client_tendermint::types::ClientState as TmClientState; use ibc_core_client_types::error::ClientError; -use ibc_core_client_types::{Height, Status, StatusError}; +use ibc_core_client_types::{Height, Status}; use ibc_core_commitment_types::specs::ProofSpecs; use ibc_core_connection_types::error::ConnectionError; use ibc_core_handler_types::error::ContextError; @@ -25,9 +25,7 @@ pub trait ValidateSelfClientContext { .map_err(ClientError::from)?; if client_state_of_host_on_counterparty.is_frozen() { - return Err( - ClientError::ClientStatus(StatusError::UnexpectedStatus(Status::Frozen)).into(), - ); + return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); } let self_chain_id = self.chain_id(); diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index badea0b59..4c41120eb 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -3,7 +3,6 @@ use alloc::string::{String, ToString}; use displaydoc::Display; use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; -use ibc::core::client::types::StatusError; use ibc::core::connection::types::error::ConnectionError; use ibc::core::handler::types::error::ContextError; use ibc::core::host::types::error::IdentifierError; @@ -16,8 +15,6 @@ use tonic::Status; pub enum QueryError { /// context error: `{0}` ContextError(ContextError), - /// client status error: `{0}` - ClientStatus(StatusError), /// identifier error: `{0}` IdentifierError(IdentifierError), /// missing proof: `{0}` @@ -41,7 +38,6 @@ impl From for Status { match e { QueryError::ContextError(ctx_err) => Self::internal(ctx_err.to_string()), QueryError::IdentifierError(id_err) => Self::internal(id_err.to_string()), - QueryError::ClientStatus(status_err) => Self::invalid_argument(status_err.to_string()), QueryError::MissingProof(description) => Self::not_found(description), QueryError::MissingField(description) => Self::invalid_argument(description), } @@ -83,9 +79,3 @@ impl From for QueryError { Self::IdentifierError(e) } } - -impl From for QueryError { - fn from(e: StatusError) -> Self { - Self::ClientStatus(e) - } -} diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index 6f8cd0533..34db638d7 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -4,7 +4,7 @@ use core::time::Duration; use ibc::clients::tendermint::client_state::consensus_state_status; use ibc::core::client::context::prelude::*; use ibc::core::client::types::error::{ClientError, UpgradeClientError}; -use ibc::core::client::types::{Height, Status, StatusError}; +use ibc::core::client::types::{Height, Status}; use ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; @@ -172,9 +172,7 @@ impl ClientStateCommon for MockClientState { if consensus_state_status(&mock_consensus_state, host_timestamp, self.trusting_period)? .is_expired() { - return Err(ClientError::ClientStatus(StatusError::UnexpectedStatus( - Status::Expired, - ))); + return Err(ClientError::UnexpectedStatus(Status::Expired)); } Ok(()) diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 41333372e..aef595159 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -11,7 +11,7 @@ use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::channel::types::packet::{PacketState, Receipt}; use ibc::core::client::context::consensus_state::ConsensusState; use ibc::core::client::types::error::ClientError; -use ibc::core::client::types::{Height, Status, StatusError}; +use ibc::core::client::types::{Height, Status}; use ibc::core::commitment_types::commitment::CommitmentPrefix; use ibc::core::commitment_types::merkle::MerkleProof; use ibc::core::connection::types::error::ConnectionError; @@ -80,9 +80,7 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), ContextError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err( - ClientError::ClientStatus(StatusError::UnexpectedStatus(Status::Frozen)).into(), - ); + return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); } let latest_height = self.host_height()?; diff --git a/tests-integration/tests/core/ics02_client/create_client.rs b/tests-integration/tests/core/ics02_client/create_client.rs index 3ab8712a3..c78fef45c 100644 --- a/tests-integration/tests/core/ics02_client/create_client.rs +++ b/tests-integration/tests/core/ics02_client/create_client.rs @@ -13,7 +13,7 @@ use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::ClientId; use ibc::core::host::types::path::{ClientConsensusStatePath, NextClientSequencePath}; use ibc::core::host::{ClientStateRef, ValidationContext}; -use ibc_core_client_types::{Status, StatusError}; +use ibc_core_client_types::Status; use ibc_query::core::context::ProvableContext; use ibc_testkit::context::{MockContext, TendermintContext}; use ibc_testkit::fixtures::clients::tendermint::dummy_tm_client_state_from_header; @@ -180,9 +180,9 @@ fn test_create_expired_mock_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredMockHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError(ClientError::ClientStatus( - StatusError::UnexpectedStatus(Status::Expired), - )))), + Expect::Failure(Some(ContextError::ClientError( + ClientError::UnexpectedStatus(Status::Expired), + ))), ); } @@ -206,9 +206,9 @@ fn test_create_expired_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError(ClientError::ClientStatus( - StatusError::UnexpectedStatus(Status::Expired), - )))), + Expect::Failure(Some(ContextError::ClientError( + ClientError::UnexpectedStatus(Status::Expired), + ))), ); } @@ -218,9 +218,9 @@ fn test_create_frozen_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::FrozenTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError(ClientError::ClientStatus( - StatusError::UnexpectedStatus(Status::Frozen), - )))), + Expect::Failure(Some(ContextError::ClientError( + ClientError::UnexpectedStatus(Status::Frozen), + ))), ); } From f414ff734fab0c169022079bc7940ceaed5fb810 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 30 Aug 2024 10:23:31 -0500 Subject: [PATCH 031/107] Remove unnecessary ClientError::Decoding wrappings --- .../ics07-tendermint/types/src/client_state.rs | 4 ++-- .../types/src/consensus_state.rs | 4 ++-- ibc-clients/ics07-tendermint/types/src/error.rs | 11 ++++++++++- ibc-clients/ics07-tendermint/types/src/header.rs | 16 +++++++++++----- .../ics07-tendermint/types/src/misbehaviour.rs | 4 ++-- ibc-clients/ics08-wasm/types/src/client_state.rs | 10 ++++------ .../ics08-wasm/types/src/consensus_state.rs | 4 ++-- ibc-clients/ics08-wasm/types/src/error.rs | 9 ++++++++- ibc-core/ics02-client/types/src/error.rs | 16 ++++++++++++---- .../ics02-client/types/src/msgs/misbehaviour.rs | 8 ++++---- .../types/src/msgs/recover_client.rs | 4 ++-- .../ics02-client/types/src/msgs/update_client.rs | 8 ++++---- .../types/src/msgs/upgrade_client.rs | 2 +- .../cosmos/src/upgrade_proposal/plan.rs | 15 +++++++-------- ibc-core/ics24-host/types/src/error.rs | 4 ++++ .../src/testapp/ibc/clients/mock/client_state.rs | 4 ++-- .../testapp/ibc/clients/mock/consensus_state.rs | 4 ++-- .../src/testapp/ibc/clients/mock/header.rs | 8 ++++---- .../src/testapp/ibc/clients/mock/misbehaviour.rs | 12 ++++++++---- 19 files changed, 91 insertions(+), 56 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/client_state.rs b/ibc-clients/ics07-tendermint/types/src/client_state.rs index 3595a7e4e..a2c5a2360 100644 --- a/ibc-clients/ics07-tendermint/types/src/client_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/client_state.rs @@ -351,10 +351,10 @@ impl TryFrom for ClientState { TENDERMINT_CLIENT_STATE_TYPE_URL => { decode_client_state(&raw.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: TENDERMINT_CLIENT_STATE_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs index 3008b756b..f069a812c 100644 --- a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs @@ -117,10 +117,10 @@ impl TryFrom for ConsensusState { TENDERMINT_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(&raw.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: TENDERMINT_CONSENSUS_STATE_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-clients/ics07-tendermint/types/src/error.rs b/ibc-clients/ics07-tendermint/types/src/error.rs index 45f00354e..dde87fa60 100644 --- a/ibc-clients/ics07-tendermint/types/src/error.rs +++ b/ibc-clients/ics07-tendermint/types/src/error.rs @@ -5,7 +5,7 @@ use core::time::Duration; use displaydoc::Display; use ibc_core_client_types::error::ClientError; use ibc_core_commitment_types::error::CommitmentError; -use ibc_core_host_types::error::IdentifierError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_primitives::prelude::*; use ibc_primitives::TimestampError; use tendermint::{Error as TendermintError, Hash}; @@ -16,6 +16,8 @@ use tendermint_light_client_verifier::Verdict; /// The main error type for the Tendermint light client #[derive(Debug, Display)] pub enum TendermintClientError { + /// decoding error: `{0}` + Decoding(DecodingError), /// invalid identifier: `{0}` InvalidIdentifier(IdentifierError), /// invalid client state trust threshold: `{description}` @@ -75,6 +77,7 @@ impl std::error::Error for TendermintClientError { match &self { Self::InvalidIdentifier(e) => Some(e), Self::InvalidRawHeader(e) => Some(e), + Self::Decoding(e) => Some(e), _ => None, } } @@ -100,6 +103,12 @@ impl From for TendermintClientError { } } +impl From for TendermintClientError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + pub trait IntoResult { fn into_result(self) -> Result; } diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index 085bec887..7c33f7fdd 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -173,12 +173,16 @@ impl TryFrom for Header { .signed_header .ok_or(TendermintClientError::MissingSignedHeader)? .try_into() - .map_err(TendermintClientError::InvalidRawHeader)?, + .map_err(|e| DecodingError::InvalidRawData { + description: format!("{e:?}"), + })?, validator_set: raw .validator_set .ok_or(TendermintClientError::MissingValidatorSet)? .try_into() - .map_err(TendermintClientError::InvalidRawHeader)?, + .map_err(|e| DecodingError::InvalidRawData { + description: format!("{e:?}"), + })?, trusted_height: raw .trusted_height .and_then(|raw_height| raw_height.try_into().ok()) @@ -187,7 +191,9 @@ impl TryFrom for Header { .trusted_validators .ok_or(TendermintClientError::MissingTrustedNextValidatorSet)? .try_into() - .map_err(TendermintClientError::InvalidRawHeader)?, + .map_err(|e| DecodingError::InvalidRawData { + description: format!("{e:?}"), + })?, }; Ok(header) @@ -206,10 +212,10 @@ impl TryFrom for Header { } match raw.type_url.as_str() { TENDERMINT_HEADER_TYPE_URL => decode_header(&raw.value).map_err(ClientError::Decoding), - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: TENDERMINT_HEADER_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs index 059b4b4ee..cdea2bf68 100644 --- a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs +++ b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs @@ -123,10 +123,10 @@ impl TryFrom for Misbehaviour { TENDERMINT_MISBEHAVIOUR_TYPE_URL => { decode_misbehaviour(&raw.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: TENDERMINT_MISBEHAVIOUR_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-clients/ics08-wasm/types/src/client_state.rs b/ibc-clients/ics08-wasm/types/src/client_state.rs index acc2fbecd..7124636ae 100644 --- a/ibc-clients/ics08-wasm/types/src/client_state.rs +++ b/ibc-clients/ics08-wasm/types/src/client_state.rs @@ -79,12 +79,10 @@ impl TryFrom for ClientState { WASM_CLIENT_STATE_TYPE_URL => { decode_client_state(&any.value).map_err(WasmClientError::Decoding) } - _ => Err(WasmClientError::Decoding( - DecodingError::MismatchedTypeUrls { - expected: WASM_CLIENT_STATE_TYPE_URL.to_string(), - actual: any.type_url, - }, - )), + _ => Err(DecodingError::MismatchedTypeUrls { + expected: WASM_CLIENT_STATE_TYPE_URL.to_string(), + actual: any.type_url, + })?, } } } diff --git a/ibc-clients/ics08-wasm/types/src/consensus_state.rs b/ibc-clients/ics08-wasm/types/src/consensus_state.rs index 588455b9b..a1346cb32 100644 --- a/ibc-clients/ics08-wasm/types/src/consensus_state.rs +++ b/ibc-clients/ics08-wasm/types/src/consensus_state.rs @@ -66,10 +66,10 @@ impl TryFrom for ConsensusState { WASM_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(&any.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: WASM_CONSENSUS_STATE_TYPE_URL.to_string(), actual: any.type_url.to_string(), - })), + })?, } } } diff --git a/ibc-clients/ics08-wasm/types/src/error.rs b/ibc-clients/ics08-wasm/types/src/error.rs index b94a14b53..f7615f802 100644 --- a/ibc-clients/ics08-wasm/types/src/error.rs +++ b/ibc-clients/ics08-wasm/types/src/error.rs @@ -21,7 +21,8 @@ pub enum WasmClientError { impl std::error::Error for WasmClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - Self::InvalidIdentifier(err) => Some(err), + Self::InvalidIdentifier(e) => Some(e), + Self::Decoding(e) => Some(e), _ => None, } } @@ -32,3 +33,9 @@ impl From for WasmClientError { Self::InvalidIdentifier(e) } } + +impl From for WasmClientError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index b6eaed20d..5fed54576 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -29,8 +29,6 @@ pub enum ClientError { InvalidConsensusStateType(String), /// invalid update client message InvalidUpdateClientMessage, - /// invalid raw header: `{description}` - InvalidRawHeader { description: String }, /// invalid misbehaviour type: `{0}` InvalidMisbehaviourType(String), /// invalid height; cannot be zero or negative @@ -57,8 +55,6 @@ pub enum ClientError { MissingRawConsensusState, /// missing raw client message MissingRawClientMessage, - /// missing raw misbehaviour - MissingRawMisbehaviour, /// missing local consensus state at `{0}` MissingLocalConsensusState(Height), /// missing attribute key @@ -110,6 +106,12 @@ impl From for ClientError { } } +impl From for ClientError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { @@ -159,6 +161,12 @@ impl From for ClientError { } } +impl From for UpgradeClientError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for UpgradeClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { diff --git a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs index e5b083196..7215ca534 100644 --- a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs +++ b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs @@ -41,15 +41,15 @@ impl TryFrom for MsgSubmitMisbehaviour { type Error = ClientError; fn try_from(raw: RawMsgSubmitMisbehaviour) -> Result { - let raw_misbehaviour = raw - .misbehaviour - .ok_or(ClientError::MissingRawMisbehaviour)?; + let raw_misbehaviour = raw.misbehaviour.ok_or(DecodingError::MissingRawData { + description: "missing raw misbehaviour".to_string(), + })?; Ok(MsgSubmitMisbehaviour { client_id: raw .client_id .parse() - .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, + .map_err(DecodingError::InvalidIdentifier)?, misbehaviour: raw_misbehaviour, signer: raw.signer.into(), }) diff --git a/ibc-core/ics02-client/types/src/msgs/recover_client.rs b/ibc-core/ics02-client/types/src/msgs/recover_client.rs index d71c8d90c..6d78f0ed1 100644 --- a/ibc-core/ics02-client/types/src/msgs/recover_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/recover_client.rs @@ -46,11 +46,11 @@ impl TryFrom for MsgRecoverClient { subject_client_id: raw .subject_client_id .parse() - .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, + .map_err(DecodingError::InvalidIdentifier)?, substitute_client_id: raw .substitute_client_id .parse() - .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, + .map_err(DecodingError::InvalidIdentifier)?, signer: raw.signer.into(), }) } diff --git a/ibc-core/ics02-client/types/src/msgs/update_client.rs b/ibc-core/ics02-client/types/src/msgs/update_client.rs index 26d719fac..0ffa8430a 100644 --- a/ibc-core/ics02-client/types/src/msgs/update_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/update_client.rs @@ -38,10 +38,10 @@ impl TryFrom for MsgUpdateClient { client_id: raw .client_id .parse() - .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, - client_message: raw - .client_message - .ok_or(ClientError::MissingRawClientMessage)?, + .map_err(DecodingError::InvalidIdentifier)?, + client_message: raw.client_message.ok_or(DecodingError::MissingRawData { + description: "missing raw client message".to_string(), + })?, signer: raw.signer.into(), }) } diff --git a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs index 1fbff9e7d..4b545e452 100644 --- a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs @@ -79,7 +79,7 @@ impl TryFrom for MsgUpgradeClient { Ok(MsgUpgradeClient { client_id: ClientId::from_str(&proto_msg.client_id) - .map_err(|e| ClientError::Decoding(DecodingError::InvalidIdentifier(e)))?, + .map_err(DecodingError::InvalidIdentifier)?, upgraded_client_state: raw_client_state, upgraded_consensus_state: raw_consensus_state, proof_upgrade_client: c_bytes, diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index 0a7251351..48ceaf0e5 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -84,14 +84,13 @@ impl TryFrom for Plan { fn try_from(any: Any) -> Result { match any.type_url.as_str() { - TYPE_URL => Protobuf::::decode_vec(&any.value) - .map_err(|e| UpgradeClientError::Decoding(DecodingError::Protobuf(e))), - _ => Err(UpgradeClientError::Decoding( - DecodingError::MismatchedTypeUrls { - expected: TYPE_URL.to_string(), - actual: any.type_url, - }, - )), + TYPE_URL => { + Ok(Protobuf::::decode_vec(&any.value).map_err(DecodingError::Protobuf)?) + } + _ => Err(DecodingError::MismatchedTypeUrls { + expected: TYPE_URL.to_string(), + actual: any.type_url, + })?, } } } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index ad0c98b3c..9996f8268 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -39,6 +39,10 @@ pub enum DecodingError { InvalidJson { description: String }, /// invalid identifier error: `{0}` InvalidIdentifier(IdentifierError), + /// invalid raw data: `{description}` + InvalidRawData { description: String }, + /// missing raw data: `{description}` + MissingRawData { description: String }, /// mismatched type URLs: expected `{expected}`, actual `{actual}` MismatchedTypeUrls { expected: String, actual: String }, /// unknown type URL: `{0}` diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index 34db638d7..dff68ecd9 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -136,10 +136,10 @@ impl TryFrom for MockClientState { MOCK_CLIENT_STATE_TYPE_URL => { decode_client_state(&raw.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: MOCK_CLIENT_STATE_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs index e5d7a2ad5..48561f087 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs @@ -73,10 +73,10 @@ impl TryFrom for MockConsensusState { MOCK_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(&raw.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: MOCK_CONSENSUS_STATE_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs index a485d2341..9f46592e4 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/header.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/header.rs @@ -96,12 +96,12 @@ impl TryFrom for MockHeader { fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - MOCK_HEADER_TYPE_URL => Protobuf::::decode_vec(&raw.value) - .map_err(|e| ClientError::Decoding(DecodingError::Protobuf(e))), - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + MOCK_HEADER_TYPE_URL => Ok(Protobuf::::decode_vec(&raw.value) + .map_err(DecodingError::Protobuf)?), + _ => Err(DecodingError::MismatchedTypeUrls { expected: MOCK_HEADER_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs index 83b07623a..1e0a90091 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs @@ -27,11 +27,15 @@ impl TryFrom for Misbehaviour { client_id: ClientId::new("07-tendermint", 0).expect("no error"), header1: raw .header1 - .ok_or(ClientError::MissingRawMisbehaviour)? + .ok_or(DecodingError::MissingRawData { + description: "missing header1 in raw misbehaviour".to_string(), + })? .try_into()?, header2: raw .header2 - .ok_or(ClientError::MissingRawMisbehaviour)? + .ok_or(DecodingError::MissingRawData { + description: "missing header2 in raw misbehaviour".to_string(), + })? .try_into()?, }) } @@ -61,10 +65,10 @@ impl TryFrom for Misbehaviour { MOCK_MISBEHAVIOUR_TYPE_URL => { decode_misbehaviour(&raw.value).map_err(ClientError::Decoding) } - _ => Err(ClientError::Decoding(DecodingError::MismatchedTypeUrls { + _ => Err(DecodingError::MismatchedTypeUrls { expected: MOCK_MISBEHAVIOUR_TYPE_URL.to_string(), actual: raw.type_url, - })), + })?, } } } From b4ae4b844a4b683b14bce296a568cf74214a1816 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 30 Aug 2024 10:32:51 -0500 Subject: [PATCH 032/107] Clean up TendermintClientError --- ibc-clients/ics07-tendermint/types/src/error.rs | 5 +---- ibc-clients/ics07-tendermint/types/src/misbehaviour.rs | 8 ++++---- ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs | 4 ++-- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/error.rs b/ibc-clients/ics07-tendermint/types/src/error.rs index dde87fa60..3d2d6dfb1 100644 --- a/ibc-clients/ics07-tendermint/types/src/error.rs +++ b/ibc-clients/ics07-tendermint/types/src/error.rs @@ -8,7 +8,7 @@ use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_primitives::prelude::*; use ibc_primitives::TimestampError; -use tendermint::{Error as TendermintError, Hash}; +use tendermint::Hash; use tendermint_light_client_verifier::errors::VerificationErrorDetail as LightClientErrorDetail; use tendermint_light_client_verifier::operations::VotingPowerTally; use tendermint_light_client_verifier::Verdict; @@ -28,8 +28,6 @@ pub enum TendermintClientError { InvalidProofSpec(CommitmentError), /// invalid raw client state: `{description}` InvalidRawClientState { description: String }, - /// invalid raw header error: `{0}` - InvalidRawHeader(TendermintError), /// invalid raw misbehaviour: `{description}` InvalidRawMisbehaviour { description: String }, /// invalid header timestamp: `{0}` @@ -76,7 +74,6 @@ impl std::error::Error for TendermintClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::InvalidIdentifier(e) => Some(e), - Self::InvalidRawHeader(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs index cdea2bf68..b49f0a328 100644 --- a/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs +++ b/ibc-clients/ics07-tendermint/types/src/misbehaviour.rs @@ -82,15 +82,15 @@ impl TryFrom for Misbehaviour { let header1: Header = raw .header_1 - .ok_or_else(|| TendermintClientError::InvalidRawMisbehaviour { - description: "missing header1".into(), + .ok_or_else(|| DecodingError::MissingRawData { + description: "missing header1 in raw misbehaviour".into(), })? .try_into()?; let header2: Header = raw .header_2 - .ok_or_else(|| TendermintClientError::InvalidRawMisbehaviour { - description: "missing header2".into(), + .ok_or_else(|| DecodingError::MissingRawData { + description: "missing header2 in raw misbehaviour".into(), })? .try_into()?; diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs index 1e0a90091..d537e8209 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/misbehaviour.rs @@ -28,13 +28,13 @@ impl TryFrom for Misbehaviour { header1: raw .header1 .ok_or(DecodingError::MissingRawData { - description: "missing header1 in raw misbehaviour".to_string(), + description: "missing header1 in raw misbehaviour".into(), })? .try_into()?, header2: raw .header2 .ok_or(DecodingError::MissingRawData { - description: "missing header2 in raw misbehaviour".to_string(), + description: "missing header2 in raw misbehaviour".into(), })? .try_into()?, }) From 05be8b6a448b9ac1c8f259d2a2f07a5c5c560e74 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 30 Aug 2024 10:33:40 -0500 Subject: [PATCH 033/107] Regenerate cw-check cargo.lock --- ci/cw-check/Cargo.lock | 1 - 1 file changed, 1 deletion(-) diff --git a/ci/cw-check/Cargo.lock b/ci/cw-check/Cargo.lock index e0be4007f..e80c0a8a3 100644 --- a/ci/cw-check/Cargo.lock +++ b/ci/cw-check/Cargo.lock @@ -1095,7 +1095,6 @@ dependencies = [ "schemars", "serde", "tendermint", - "tendermint-proto", "time", ] From b7ba000522e69b6168cfbe8ad1a01cb12164dfd1 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 30 Aug 2024 11:43:38 -0500 Subject: [PATCH 034/107] taplo fmt --- ibc-primitives/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibc-primitives/Cargo.toml b/ibc-primitives/Cargo.toml index dac541f33..2c56cd6de 100644 --- a/ibc-primitives/Cargo.toml +++ b/ibc-primitives/Cargo.toml @@ -32,7 +32,7 @@ time = { version = ">=0.3.0, <0.3.37", default-features = false } ibc-proto = { workspace = true } # cosmos dependencies -tendermint = { workspace = true } +tendermint = { workspace = true } # parity dependencies parity-scale-codec = { workspace = true, optional = true } From aeb80fc9ac413e1f641286bce142f7be3df6a9de Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 30 Aug 2024 13:33:02 -0500 Subject: [PATCH 035/107] Apply PR feedback --- ibc-clients/ics07-tendermint/types/src/client_state.rs | 6 +++++- ibc-core/ics03-connection/src/handler/mod.rs | 4 +--- ibc-core/ics23-commitment/types/src/commitment.rs | 9 +++++++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/client_state.rs b/ibc-clients/ics07-tendermint/types/src/client_state.rs index a2c5a2360..ca76e9c32 100644 --- a/ibc-clients/ics07-tendermint/types/src/client_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/client_state.rs @@ -343,7 +343,11 @@ impl TryFrom for ClientState { fn try_from(raw: Any) -> Result { fn decode_client_state(value: &[u8]) -> Result { - let client_state = Protobuf::::decode(value)?; + let client_state = Protobuf::::decode(value).map_err(|e| { + DecodingError::Protobuf { + description: e.to_string(), + } + })?; Ok(client_state) } diff --git a/ibc-core/ics03-connection/src/handler/mod.rs b/ibc-core/ics03-connection/src/handler/mod.rs index 3421ebb16..f780295e4 100644 --- a/ibc-core/ics03-connection/src/handler/mod.rs +++ b/ibc-core/ics03-connection/src/handler/mod.rs @@ -37,9 +37,7 @@ where })?; let any_client_state = ::decode(wasm_client_state.data.as_slice()) - .map_err(|e| { - ContextError::ConnectionError(ConnectionError::Decoding(DecodingError::Prost(e))) - })?; + .map_err(|e| ConnectionError::Decoding(DecodingError::Prost(e)))?; Ok(CS::try_from(any_client_state).map_err(Into::::into)?) } else { diff --git a/ibc-core/ics23-commitment/types/src/commitment.rs b/ibc-core/ics23-commitment/types/src/commitment.rs index f43162668..0d1d34082 100644 --- a/ibc-core/ics23-commitment/types/src/commitment.rs +++ b/ibc-core/ics23-commitment/types/src/commitment.rs @@ -122,8 +122,13 @@ impl<'a> TryFrom<&'a CommitmentProofBytes> for MerkleProof { type Error = CommitmentError; fn try_from(value: &'a CommitmentProofBytes) -> Result { - Protobuf::::decode(value.as_ref()) - .map_err(|e| CommitmentError::Decoding(DecodingError::Protobuf(e))) + Ok( + Protobuf::::decode(value.as_ref()).map_err(|e| { + DecodingError::Protobuf { + description: e.to_string(), + } + })?, + ) } } From b10ee71322fef19bc456cc0f14aaa9d69bf9e3b5 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 3 Sep 2024 11:38:09 -0500 Subject: [PATCH 036/107] Use ibc_proto::Error type instead of tendermint_proto::Error --- Cargo.toml | 2 +- ibc-clients/ics07-tendermint/types/src/client_state.rs | 7 ++----- ibc-core/ics23-commitment/types/src/commitment.rs | 8 +------- ibc-core/ics24-host/types/src/error.rs | 2 +- ibc-primitives/src/lib.rs | 1 + 5 files changed, 6 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 454378242..f38401ab3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -105,7 +105,7 @@ ibc-client-wasm-types = { version = "0.54.0", path = "./ibc-clients/ics08- ibc-app-transfer-types = { version = "0.54.0", path = "./ibc-apps/ics20-transfer/types", default-features = false } ibc-app-nft-transfer-types = { version = "0.54.0", path = "./ibc-apps/ics721-nft-transfer/types", default-features = false } -ibc-proto = { version = "0.47.0", default-features = false } +ibc-proto = { version = "0.47.1", default-features = false } # cosmos dependencies tendermint = { version = "0.38.0", default-features = false } diff --git a/ibc-clients/ics07-tendermint/types/src/client_state.rs b/ibc-clients/ics07-tendermint/types/src/client_state.rs index ca76e9c32..87f588d82 100644 --- a/ibc-clients/ics07-tendermint/types/src/client_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/client_state.rs @@ -343,11 +343,8 @@ impl TryFrom for ClientState { fn try_from(raw: Any) -> Result { fn decode_client_state(value: &[u8]) -> Result { - let client_state = Protobuf::::decode(value).map_err(|e| { - DecodingError::Protobuf { - description: e.to_string(), - } - })?; + let client_state = + Protobuf::::decode(value).map_err(DecodingError::Protobuf)?; Ok(client_state) } diff --git a/ibc-core/ics23-commitment/types/src/commitment.rs b/ibc-core/ics23-commitment/types/src/commitment.rs index 0d1d34082..1f6c94175 100644 --- a/ibc-core/ics23-commitment/types/src/commitment.rs +++ b/ibc-core/ics23-commitment/types/src/commitment.rs @@ -122,13 +122,7 @@ impl<'a> TryFrom<&'a CommitmentProofBytes> for MerkleProof { type Error = CommitmentError; fn try_from(value: &'a CommitmentProofBytes) -> Result { - Ok( - Protobuf::::decode(value.as_ref()).map_err(|e| { - DecodingError::Protobuf { - description: e.to_string(), - } - })?, - ) + Ok(Protobuf::::decode(value.as_ref()).map_err(DecodingError::Protobuf)?) } } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 9996f8268..048392de6 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -5,8 +5,8 @@ use alloc::string::{FromUtf8Error, String}; use base64::DecodeError as Base64Error; use displaydoc::Display; use ibc_primitives::prelude::*; +use ibc_primitives::proto::Error as ProtoError; use prost::DecodeError as ProstError; -use tendermint_proto::Error as ProtoError; /// Errors that arise when parsing identifiers. #[cfg_attr(feature = "serde", derive(serde::Serialize))] diff --git a/ibc-primitives/src/lib.rs b/ibc-primitives/src/lib.rs index 5aa99f4e5..8de7a3d39 100644 --- a/ibc-primitives/src/lib.rs +++ b/ibc-primitives/src/lib.rs @@ -32,5 +32,6 @@ pub mod serializers; pub mod proto { pub use ibc_proto::google::protobuf::{Any, Duration, Timestamp}; + pub use ibc_proto::Error; pub use ibc_proto::Protobuf; } From bff57f6a3f129a747b73f400626da865ae84a008 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 3 Sep 2024 11:43:04 -0500 Subject: [PATCH 037/107] Change FailedToParseType fields to make them more clear --- ibc-apps/ics20-transfer/types/src/coin.rs | 4 ++-- ibc-apps/ics20-transfer/types/src/denom.rs | 4 ++-- ibc-apps/ics20-transfer/types/src/error.rs | 7 +++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/coin.rs b/ibc-apps/ics20-transfer/types/src/coin.rs index 2f091eb84..0846029ad 100644 --- a/ibc-apps/ics20-transfer/types/src/coin.rs +++ b/ibc-apps/ics20-transfer/types/src/coin.rs @@ -77,8 +77,8 @@ where .all(|x| x.is_alphanumeric() || VALID_DENOM_CHARACTERS.contains(x)) }) .ok_or_else(|| TokenTransferError::FailedToParseType { - expected: "Coin".to_string(), - actual: coin_str.to_string(), + desired_type: "Coin".to_string(), + str_repr: coin_str.to_string(), })?; Ok(Coin { diff --git a/ibc-apps/ics20-transfer/types/src/denom.rs b/ibc-apps/ics20-transfer/types/src/denom.rs index b668813a5..42a55bd98 100644 --- a/ibc-apps/ics20-transfer/types/src/denom.rs +++ b/ibc-apps/ics20-transfer/types/src/denom.rs @@ -220,8 +220,8 @@ impl FromStr for TracePath { .is_none() .then_some(trace_path) .ok_or_else(|| TokenTransferError::FailedToParseType { - expected: "TracePath".to_string(), - actual: s.to_string(), + desired_type: "TracePath".to_string(), + str_repr: s.to_string(), }) } } diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 31180b646..e89b41e33 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -39,8 +39,11 @@ pub enum TokenTransferError { // to a host-relevant error /// failed to parse account ID FailedToParseAccount, - /// failed to parse `{expected}` from `{actual}` - FailedToParseType { expected: String, actual: String }, + /// failed to parse `{desired_type}` type from string representation `{str_repr}` + FailedToParseType { + desired_type: String, + str_repr: String, + }, /// channel cannot be closed UnsupportedClosedChannel, /// empty base denomination From 29522914999b02c31f3e933d7cfc273f2c24a916 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 3 Sep 2024 14:17:34 -0500 Subject: [PATCH 038/107] Revert InvalidTrace and InvalidCoin TokenTransferError variants --- ibc-apps/ics20-transfer/src/module.rs | 66 ++++++++++++++----- ibc-apps/ics20-transfer/types/src/coin.rs | 5 +- ibc-apps/ics20-transfer/types/src/denom.rs | 5 +- ibc-apps/ics20-transfer/types/src/error.rs | 33 +++++++--- .../types/src/acknowledgement.rs | 7 ++ 5 files changed, 83 insertions(+), 33 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/module.rs b/ibc-apps/ics20-transfer/src/module.rs index 66370f10c..062f34c2d 100644 --- a/ibc-apps/ics20-transfer/src/module.rs +++ b/ibc-apps/ics20-transfer/src/module.rs @@ -7,6 +7,7 @@ use ibc_core::channel::types::channel::{Counterparty, Order}; use ibc_core::channel::types::packet::Packet; use ibc_core::channel::types::Version; use ibc_core::handler::types::error::ContextError; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, ConnectionId, PortId}; use ibc_core::primitives::prelude::*; use ibc_core::primitives::Signer; @@ -171,8 +172,12 @@ pub fn on_recv_packet_execute( packet: &Packet, ) -> (ModuleExtras, Acknowledgement) { let Ok(data) = serde_json::from_slice::(&packet.data) else { - let ack = - AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()); + let ack = AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ); return (ModuleExtras::empty(), ack.into()); }; @@ -203,11 +208,16 @@ pub fn on_acknowledgement_packet_validate( where Ctx: TokenTransferValidationContext, { - let data = serde_json::from_slice::(&packet.data) - .map_err(|_| TokenTransferError::FailedToDeserializePacketData)?; + let data = serde_json::from_slice::(&packet.data).map_err(|e| { + DecodingError::InvalidJson { + description: format!("failed to deserialize packet data: {e}"), + } + })?; let acknowledgement = serde_json::from_slice::(acknowledgement.as_ref()) - .map_err(|_| TokenTransferError::FailedToDeserializeAck)?; + .map_err(|e| DecodingError::InvalidJson { + description: format!("failed to deserialize acknowledgment status: {e}"), + })?; if !acknowledgement.is_successful() { refund_packet_token_validate(ctx, packet, &data)?; @@ -225,7 +235,10 @@ pub fn on_acknowledgement_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(TokenTransferError::FailedToDeserializePacketData), + Err(DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into()), ); }; @@ -234,7 +247,10 @@ pub fn on_acknowledgement_packet_execute( else { return ( ModuleExtras::empty(), - Err(TokenTransferError::FailedToDeserializeAck), + Err(DecodingError::InvalidJson { + description: "failed to deserialize acknowledgment status".to_string(), + } + .into()), ); }; @@ -269,8 +285,11 @@ pub fn on_timeout_packet_validate( where Ctx: TokenTransferValidationContext, { - let data = serde_json::from_slice::(&packet.data) - .map_err(|_| TokenTransferError::FailedToDeserializePacketData)?; + let data = serde_json::from_slice::(&packet.data).map_err(|e| { + DecodingError::InvalidJson { + description: format!("failed to deserialize packet data: {e}"), + } + })?; refund_packet_token_validate(ctx, packet, &data)?; @@ -285,7 +304,10 @@ pub fn on_timeout_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(TokenTransferError::FailedToDeserializePacketData), + Err(DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into()), ); }; @@ -324,7 +346,12 @@ mod test { r#"{"result":"AQ=="}"#, ); ser_json_assert_eq( - AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()), + AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ), r#"{"error":"failed to deserialize packet data"}"#, ); } @@ -341,9 +368,13 @@ mod test { #[test] fn test_ack_error_to_vec() { - let ack_error: Vec = - AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()) - .into(); + let ack_error: Vec = AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ) + .into(); // Check that it's the same output as ibc-go // Note: this also implicitly checks that the ack bytes are non-empty, @@ -367,7 +398,12 @@ mod test { ); de_json_assert_eq( r#"{"error":"failed to deserialize packet data"}"#, - AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()), + AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ), ); assert!(serde_json::from_str::(r#"{"success":"AQ=="}"#).is_err()); diff --git a/ibc-apps/ics20-transfer/types/src/coin.rs b/ibc-apps/ics20-transfer/types/src/coin.rs index 0846029ad..3a8b7387f 100644 --- a/ibc-apps/ics20-transfer/types/src/coin.rs +++ b/ibc-apps/ics20-transfer/types/src/coin.rs @@ -76,10 +76,7 @@ where .chars() .all(|x| x.is_alphanumeric() || VALID_DENOM_CHARACTERS.contains(x)) }) - .ok_or_else(|| TokenTransferError::FailedToParseType { - desired_type: "Coin".to_string(), - str_repr: coin_str.to_string(), - })?; + .ok_or_else(|| TokenTransferError::InvalidCoin(coin_str.to_owned()))?; Ok(Coin { amount: amount.parse()?, diff --git a/ibc-apps/ics20-transfer/types/src/denom.rs b/ibc-apps/ics20-transfer/types/src/denom.rs index 42a55bd98..ce014ee68 100644 --- a/ibc-apps/ics20-transfer/types/src/denom.rs +++ b/ibc-apps/ics20-transfer/types/src/denom.rs @@ -219,10 +219,7 @@ impl FromStr for TracePath { remaining_parts .is_none() .then_some(trace_path) - .ok_or_else(|| TokenTransferError::FailedToParseType { - desired_type: "TracePath".to_string(), - str_repr: s.to_string(), - }) + .ok_or_else(|| TokenTransferError::InvalidTrace(s.to_owned())) } } diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index e89b41e33..0d421b836 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -10,7 +10,7 @@ use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use uint::FromDecStrErr; -#[derive(Display, Debug, derive_more::From)] +#[derive(Display, Debug)] pub enum TokenTransferError { /// context error: `{0}` ContextError(ContextError), @@ -20,6 +20,10 @@ pub enum TokenTransferError { Identifier(IdentifierError), /// invalid amount: `{0}` InvalidAmount(FromDecStrErr), + /// invalid coin: `{0}` + InvalidCoin(String), + /// invalid trace: `{0}` + InvalidTrace(String), /// missing token MissingToken, /// missing destination channel `{channel_id}` on port `{port_id}` @@ -31,19 +35,10 @@ pub enum TokenTransferError { MismatchedChannelOrders { expected: Order, actual: Order }, /// mismatched port IDs: expected `{expected}`, actual `{actual}` MismatchedPortIds { expected: PortId, actual: PortId }, - /// failed to deserialize packet data - FailedToDeserializePacketData, - /// failed to deserialize acknowledgement - FailedToDeserializeAck, // TODO(seanchen1991): Used in basecoin; this variant should be moved // to a host-relevant error /// failed to parse account ID FailedToParseAccount, - /// failed to parse `{desired_type}` type from string representation `{str_repr}` - FailedToParseType { - desired_type: String, - str_repr: String, - }, /// channel cannot be closed UnsupportedClosedChannel, /// empty base denomination @@ -69,6 +64,24 @@ impl From for TokenTransferError { } } +impl From for TokenTransferError { + fn from(e: ContextError) -> Self { + Self::ContextError(e) + } +} + +impl From for TokenTransferError { + fn from(e: IdentifierError) -> Self { + Self::Identifier(e) + } +} + +impl From for TokenTransferError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + impl From for StatusValue { fn from(e: TokenTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") diff --git a/ibc-core/ics04-channel/types/src/acknowledgement.rs b/ibc-core/ics04-channel/types/src/acknowledgement.rs index 0e983b0ce..2e19d3358 100644 --- a/ibc-core/ics04-channel/types/src/acknowledgement.rs +++ b/ibc-core/ics04-channel/types/src/acknowledgement.rs @@ -3,6 +3,7 @@ use core::fmt::{Display, Error as FmtError, Formatter}; use derive_more::Into; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use super::error::PacketError; @@ -139,3 +140,9 @@ impl From for Acknowledgement { .expect("token transfer internal error: ack is never supposed to be empty") } } + +impl From for StatusValue { + fn from(e: DecodingError) -> Self { + StatusValue::new(e.to_string()).expect("error message must not be empty") + } +} From 3ffdf2f1e5428a496d59e41117f1e75beea5c4c9 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 3 Sep 2024 14:38:32 -0500 Subject: [PATCH 039/107] Remove NftTransferError variants in favor of DecodingError::InvalidJson --- ibc-apps/ics20-transfer/src/module.rs | 6 +- ibc-apps/ics721-nft-transfer/src/module.rs | 72 ++++++++++++++----- .../ics721-nft-transfer/types/src/error.rs | 4 -- 3 files changed, 57 insertions(+), 25 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/module.rs b/ibc-apps/ics20-transfer/src/module.rs index 062f34c2d..e493760e6 100644 --- a/ibc-apps/ics20-transfer/src/module.rs +++ b/ibc-apps/ics20-transfer/src/module.rs @@ -352,7 +352,7 @@ mod test { } .into(), ), - r#"{"error":"failed to deserialize packet data"}"#, + r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, ); } @@ -381,7 +381,7 @@ mod test { // which would make the conversion to `Acknowledgement` panic assert_eq!( ack_error, - br#"{"error":"failed to deserialize packet data"}"# + br#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"# ); } @@ -397,7 +397,7 @@ mod test { AcknowledgementStatus::success(ack_success_b64()), ); de_json_assert_eq( - r#"{"error":"failed to deserialize packet data"}"#, + r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, AcknowledgementStatus::error( DecodingError::InvalidJson { description: "failed to deserialize packet data".to_string(), diff --git a/ibc-apps/ics721-nft-transfer/src/module.rs b/ibc-apps/ics721-nft-transfer/src/module.rs index 5560b686f..8b1ffef0f 100644 --- a/ibc-apps/ics721-nft-transfer/src/module.rs +++ b/ibc-apps/ics721-nft-transfer/src/module.rs @@ -4,6 +4,7 @@ use ibc_core::channel::types::channel::{Counterparty, Order}; use ibc_core::channel::types::packet::Packet; use ibc_core::channel::types::Version; use ibc_core::handler::types::error::ContextError; +use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, ConnectionId, PortId}; use ibc_core::primitives::prelude::*; use ibc_core::primitives::Signer; @@ -172,8 +173,12 @@ pub fn on_recv_packet_execute( packet: &Packet, ) -> (ModuleExtras, Acknowledgement) { let Ok(data) = serde_json::from_slice::(&packet.data) else { - let ack = - AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()); + let ack = AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ); return (ModuleExtras::empty(), ack.into()); }; @@ -204,11 +209,16 @@ pub fn on_acknowledgement_packet_validate( acknowledgement: &Acknowledgement, _relayer: &Signer, ) -> Result<(), NftTransferError> { - let data = serde_json::from_slice::(&packet.data) - .map_err(|_| NftTransferError::FailedToDeserializePacketData)?; + let data = serde_json::from_slice::(&packet.data).map_err(|e| { + DecodingError::InvalidJson { + description: format!("failed to deserialize packet data: {e}"), + } + })?; let acknowledgement = serde_json::from_slice::(acknowledgement.as_ref()) - .map_err(|_| NftTransferError::FailedToDeserializeAck)?; + .map_err(|e| DecodingError::InvalidJson { + description: format!("failed to deserialize acknowledgment: {e}"), + })?; if !acknowledgement.is_successful() { refund_packet_nft_validate(ctx, packet, &data)?; @@ -226,7 +236,10 @@ pub fn on_acknowledgement_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(NftTransferError::FailedToDeserializePacketData), + Err(DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into()), ); }; @@ -235,7 +248,10 @@ pub fn on_acknowledgement_packet_execute( else { return ( ModuleExtras::empty(), - Err(NftTransferError::FailedToDeserializeAck), + Err(DecodingError::InvalidJson { + description: "failed to deserialize acknowledgment".to_string(), + } + .into()), ); }; @@ -267,8 +283,11 @@ pub fn on_timeout_packet_validate( packet: &Packet, _relayer: &Signer, ) -> Result<(), NftTransferError> { - let data = serde_json::from_slice::(&packet.data) - .map_err(|_| NftTransferError::FailedToDeserializePacketData)?; + let data = serde_json::from_slice::(&packet.data).map_err(|e| { + DecodingError::InvalidJson { + description: format!("failed to deserialize packet data: {e}"), + } + })?; refund_packet_nft_validate(ctx, packet, &data)?; @@ -283,7 +302,10 @@ pub fn on_timeout_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(NftTransferError::FailedToDeserializePacketData), + Err(DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into()), ); }; @@ -322,8 +344,13 @@ mod test { r#"{"result":"AQ=="}"#, ); ser_json_assert_eq( - AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()), - r#"{"error":"failed to deserialize packet data"}"#, + AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ), + r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, ); } @@ -339,16 +366,20 @@ mod test { #[test] fn test_ack_error_to_vec() { - let ack_error: Vec = - AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()) - .into(); + let ack_error: Vec = AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ) + .into(); // Check that it's the same output as ibc-go // Note: this also implicitly checks that the ack bytes are non-empty, // which would make the conversion to `Acknowledgement` panic assert_eq!( ack_error, - br#"{"error":"failed to deserialize packet data"}"# + br#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"# ); } @@ -364,8 +395,13 @@ mod test { AcknowledgementStatus::success(ack_success_b64()), ); de_json_assert_eq( - r#"{"error":"failed to deserialize packet data"}"#, - AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()), + r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, + AcknowledgementStatus::error( + DecodingError::InvalidJson { + description: "failed to deserialize packet data".to_string(), + } + .into(), + ), ); assert!(serde_json::from_str::(r#"{"success":"AQ=="}"#).is_err()); diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 6826f4a58..2e7456b5b 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -37,10 +37,6 @@ pub enum NftTransferError { MismatchedChannelOrders { expected: Order, actual: Order }, /// mismatched port IDs: expected `{expected}`, actual `{actual}` MismatchedPortIds { expected: PortId, actual: PortId }, - /// failed to deserialize packet data - FailedToDeserializePacketData, - /// failed to deserialize acknowledgement - FailedToDeserializeAck, /// failed to parse account ID FailedToParseAccount, /// channel cannot be closed From b326f45b815029fc7e81b439fd6befd5180f71f8 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 3 Sep 2024 14:56:21 -0500 Subject: [PATCH 040/107] cargo fmt --- ibc-clients/ics07-tendermint/src/client_state/common.rs | 5 +---- ibc-core/ics02-client/types/src/error.rs | 2 ++ .../ics24-host/cosmos/src/upgrade_proposal/proposal.rs | 8 ++++---- ibc-primitives/src/lib.rs | 3 +-- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/ibc-clients/ics07-tendermint/src/client_state/common.rs b/ibc-clients/ics07-tendermint/src/client_state/common.rs index 5c573135f..ca0a82eec 100644 --- a/ibc-clients/ics07-tendermint/src/client_state/common.rs +++ b/ibc-clients/ics07-tendermint/src/client_state/common.rs @@ -66,10 +66,7 @@ impl ClientStateCommon for ClientState { let upgrade_path = &self.inner().upgrade_path; let (upgrade_path_prefix, upgrade_path) = match upgrade_path.len() { 0 => { - return Err(UpgradeClientError::InvalidUpgradePath { - description: "no upgrade path has been set".to_string(), - } - .into()); + return Err(UpgradeClientError::MissingUpgradePath.into()); } 1 => (CommitmentPrefix::empty(), upgrade_path[0].clone()), 2 => ( diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 5fed54576..505ce8322 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -138,6 +138,8 @@ pub enum UpgradeClientError { InvalidUpgradeProposal { description: String }, /// invalid upgrade plan: `{description}` InvalidUpgradePlan { description: String }, + /// missing upgrade path + MissingUpgradePath, /// missing upgraded client state MissingUpgradedClientState, /// missing upgraded consensus state diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs index 4a72af753..f069e6852 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs @@ -33,13 +33,13 @@ impl TryFrom for UpgradeProposal { fn try_from(raw: RawUpgradeProposal) -> Result { if raw.title.is_empty() { return Err(UpgradeClientError::InvalidUpgradeProposal { - description: "title field cannot be empty".to_string(), + description: "missing title field".to_string(), }); } if raw.description.is_empty() { return Err(UpgradeClientError::InvalidUpgradeProposal { - description: "description field cannot be empty".to_string(), + description: "missing description field".to_string(), }); } @@ -47,13 +47,13 @@ impl TryFrom for UpgradeProposal { plan.try_into()? } else { return Err(UpgradeClientError::InvalidUpgradeProposal { - description: "plan field cannot be empty".to_string(), + description: "missing plan field".to_string(), }); }; let upgraded_client_state = raw.upgraded_client_state.ok_or_else(|| { UpgradeClientError::InvalidUpgradeProposal { - description: "upgraded client state cannot be empty".to_string(), + description: "missing upgraded client state".to_string(), } })?; diff --git a/ibc-primitives/src/lib.rs b/ibc-primitives/src/lib.rs index 8de7a3d39..277c794cd 100644 --- a/ibc-primitives/src/lib.rs +++ b/ibc-primitives/src/lib.rs @@ -32,6 +32,5 @@ pub mod serializers; pub mod proto { pub use ibc_proto::google::protobuf::{Any, Duration, Timestamp}; - pub use ibc_proto::Error; - pub use ibc_proto::Protobuf; + pub use ibc_proto::{Error, Protobuf}; } From 6e048640fedeac69c471f1c834e4aebb8483c94c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 3 Sep 2024 14:57:21 -0500 Subject: [PATCH 041/107] Regenerate cw-check cargo.lock --- ci/cw-check/Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/cw-check/Cargo.lock b/ci/cw-check/Cargo.lock index e80c0a8a3..3a5d9fe84 100644 --- a/ci/cw-check/Cargo.lock +++ b/ci/cw-check/Cargo.lock @@ -1100,9 +1100,9 @@ dependencies = [ [[package]] name = "ibc-proto" -version = "0.47.0" +version = "0.47.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1678333cf68c9094ca66aaf9a271269f1f6bf5c26881161def8bd88cee831a23" +checksum = "c852d22b782d2d793f4a646f968de419be635e02bc8798d5d74a6e44eef27733" dependencies = [ "base64 0.22.1", "bytes", From 6f92e551b01da44aee47ea5a13a113da8a23a1f3 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 4 Sep 2024 09:24:55 -0500 Subject: [PATCH 042/107] Separate out error variants that need to be moved to host-relevant errors --- ibc-apps/ics20-transfer/types/src/error.rs | 9 ++-- ibc-core/ics02-client/types/src/error.rs | 43 ++++++++++++-------- ibc-core/ics03-connection/types/src/error.rs | 10 ++--- ibc-core/ics04-channel/types/src/error.rs | 16 ++++---- ibc-core/ics26-routing/types/src/error.rs | 2 + 5 files changed, 45 insertions(+), 35 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 0d421b836..43150c0cb 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -35,14 +35,15 @@ pub enum TokenTransferError { MismatchedChannelOrders { expected: Order, actual: Order }, /// mismatched port IDs: expected `{expected}`, actual `{actual}` MismatchedPortIds { expected: PortId, actual: PortId }, - // TODO(seanchen1991): Used in basecoin; this variant should be moved - // to a host-relevant error - /// failed to parse account ID - FailedToParseAccount, /// channel cannot be closed UnsupportedClosedChannel, /// empty base denomination EmptyBaseDenom, + + // TODO(seanchen1991): Used in basecoin; this variant should be moved + // to a host-relevant error + /// failed to parse account ID + FailedToParseAccount, } #[cfg(feature = "std")] diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 505ce8322..87d5b78ef 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -3,6 +3,8 @@ use core::convert::Infallible; use displaydoc::Display; +use tendermint::Error as TendermintError; + use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; @@ -19,8 +21,6 @@ pub enum ClientError { Upgrade(UpgradeClientError), /// decoding error: `{0}` Decoding(DecodingError), - /// invalid header type: `{0}` - InvalidHeaderType(String), /// invalid trust threshold: `{numerator}`/`{denominator}` InvalidTrustThreshold { numerator: u64, denominator: u64 }, /// invalid client state type: `{0}` @@ -43,12 +43,6 @@ pub enum ClientError { InvalidAttributeValue(String), /// invalid status: `{0}` InvalidStatus(String), - /// missing client state for client: `{0}` - MissingClientState(ClientId), - /// missing consensus state for client `{client_id}` at height `{height}` - MissingConsensusState { client_id: ClientId, height: Height }, - /// missing update client metadata for client `{client_id}` at height `{height}` - MissingUpdateMetaData { client_id: ClientId, height: Height }, /// missing raw client state MissingRawClientState, /// missing raw client consensus state @@ -81,7 +75,18 @@ pub enum ClientError { /// client-specific error: `{description}` ClientSpecific { description: String }, - // TODO(seanchen1991): Incorporate these errors into their own variants + // TODO(seanchen1991): Add these to host-relevant errors + /// missing client state for client: `{0}` + MissingClientState(ClientId), + /// missing consensus state for client `{client_id}` at height `{height}` + MissingConsensusState { client_id: ClientId, height: Height }, + /// missing update client metadata for client `{client_id}` at height `{height}` + MissingUpdateMetaData { client_id: ClientId, height: Height }, + /// invalid raw header: `{0}` + InvalidRawHeader(TendermintError), + /// invalid header type: `{0}` + InvalidHeaderType(String), + // TODO(seanchen1991): Incorporate this error into its own variants /// other error: `{description}` Other { description: String }, } @@ -134,12 +139,19 @@ pub enum UpgradeClientError { InvalidUpgradeConsensusStateProof(CommitmentError), /// invalid upgrade path: `{description}` InvalidUpgradePath { description: String }, - /// invalid upgrade proposal: `{description}` - InvalidUpgradeProposal { description: String }, - /// invalid upgrade plan: `{description}` - InvalidUpgradePlan { description: String }, /// missing upgrade path MissingUpgradePath, + /// insufficient upgrade client height `{upgraded_height}`; must be greater than current client height `{client_height}` + InsufficientUpgradeHeight { + upgraded_height: Height, + client_height: Height, + }, + + // TODO(seanchen1991): Move these variants to host-relevant errors + /// invalid upgrade plan: `{description}` + InvalidUpgradePlan { description: String }, + /// invalid upgrade proposal: `{description}` + InvalidUpgradeProposal { description: String }, /// missing upgraded client state MissingUpgradedClientState, /// missing upgraded consensus state @@ -150,11 +162,6 @@ pub enum UpgradeClientError { FailedToStoreUpgradedClientState { description: String }, /// failed to store upgraded consensus state: `{description}` FailedToStoreUpgradedConsensusState { description: String }, - /// insufficient upgrade client height `{upgraded_height}`; must be greater than current client height `{client_height}` - InsufficientUpgradeHeight { - upgraded_height: Height, - client_height: Height, - }, } impl From for ClientError { diff --git a/ibc-core/ics03-connection/types/src/error.rs b/ibc-core/ics03-connection/types/src/error.rs index 7016256b7..d141c6303 100644 --- a/ibc-core/ics03-connection/types/src/error.rs +++ b/ibc-core/ics03-connection/types/src/error.rs @@ -44,9 +44,9 @@ pub enum ConnectionError { MissingProofHeight, /// missing consensus height MissingConsensusHeight, - /// missing connection `{0}` + /// [HostError] missing connection `{0}` MissingConnection(ConnectionId), - /// missing connection counter + /// [HostError] missing connection counter MissingConnectionCounter, /// missing counterparty MissingCounterparty, @@ -73,11 +73,11 @@ pub enum ConnectionError { FailedToVerifyConsensusState(ClientError), /// failed to verify client state: `{0}` FailedToVerifyClientState(ClientError), - /// failed to store connection IDs + /// [HostError] failed to store connection IDs FailedToStoreConnectionIds, - /// failed to store connection end + /// [HostError] failed to store connection end FailedToStoreConnectionEnd, - /// failed to update connection counter + /// [HostError] failed to update connection counter FailedToUpdateConnectionCounter, /// overflowed timestamp: `{0}` OverflowedTimestamp(TimestampError), diff --git a/ibc-core/ics04-channel/types/src/error.rs b/ibc-core/ics04-channel/types/src/error.rs index 56cdadcd5..a44f1975b 100644 --- a/ibc-core/ics04-channel/types/src/error.rs +++ b/ibc-core/ics04-channel/types/src/error.rs @@ -16,8 +16,6 @@ use crate::Version; #[derive(Debug, Display)] pub enum ChannelError { - /// application module error: `{description}` - AppModule { description: String }, /// identifier error: `{0}` InvalidIdentifier(IdentifierError), /// invalid channel id: expected `{expected}`, actual `{actual}` @@ -41,8 +39,6 @@ pub enum ChannelError { MissingCounterparty, /// missing channel end in raw message MissingRawChannelEnd, - /// missing channel counter - MissingCounter, /// unsupported channel upgrade sequence UnsupportedChannelUpgradeSequence, /// unsupported version: expected `{expected}`, actual `{actual}` @@ -62,8 +58,12 @@ pub enum ChannelError { /// failed proof verification: `{0}` FailedProofVerification(ClientError), - // TODO(seanchen1991): These two variants should be encoded by host-relevant error types + // TODO(seanchen1991): These variants should be encoded by host-relevant error types // once those have been defined. + /// application module error: `{description}` + AppModule { description: String }, + /// missing channel counter + MissingCounter, /// failed to update counter: `{description}` FailedToUpdateCounter { description: String }, /// failed to store channel: `{description}` @@ -72,7 +72,7 @@ pub enum ChannelError { #[derive(Debug, Display)] pub enum PacketError { - /// application module error: `{description}` + /// [HostError] application module error: `{description}` AppModule { description: String }, /// channel error: `{0}` Channel(ChannelError), @@ -94,11 +94,11 @@ pub enum PacketError { expected: PacketCommitment, actual: PacketCommitment, }, - /// missing packet receipt for packet `{0}` + /// [HostError] missing packet receipt for packet `{0}` MissingPacketReceipt(Sequence), /// missing proof MissingProof, - /// missing acknowledgment for packet `{0}` + /// [HostError] missing acknowledgment for packet `{0}` MissingPacketAcknowledgment(Sequence), /// missing proof height MissingProofHeight, diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index cb998dd76..8e53c1a86 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -10,6 +10,8 @@ pub enum RouterError { Decoding(DecodingError), /// missing module MissingModule, + + // TODO(seanchen1991): This variant needs to be moved to HostError /// unknown port `{0}` UnknownPort(PortId), } From 2d8bbd6610ea8be1932336f968ea3dd4fbc69e8b Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 4 Sep 2024 14:08:39 -0500 Subject: [PATCH 043/107] Consolidate TendermintClientError decoding errors --- .../types/src/client_state.rs | 52 ++++++++++++------- .../types/src/consensus_state.rs | 21 ++++---- .../ics07-tendermint/types/src/error.rs | 20 +------ .../ics07-tendermint/types/src/header.rs | 22 +++++--- ibc-core/ics02-client/types/src/error.rs | 17 ++---- .../types/src/msgs/create_client.rs | 11 ++-- .../types/src/msgs/upgrade_client.rs | 18 +++++-- ibc-core/ics24-host/types/src/error.rs | 2 + .../ibc/clients/mock/consensus_state.rs | 4 +- 9 files changed, 89 insertions(+), 78 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/client_state.rs b/ibc-clients/ics07-tendermint/types/src/client_state.rs index 87f588d82..91ab3d944 100644 --- a/ibc-clients/ics07-tendermint/types/src/client_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/client_state.rs @@ -241,48 +241,64 @@ impl TryFrom for ClientState { let chain_id = ChainId::from_str(raw.chain_id.as_str())?; let trust_level = { - let trust_level = raw - .trust_level - .ok_or(TendermintClientError::MissingTrustingPeriod)?; + let trust_level = raw.trust_level.ok_or(DecodingError::MissingRawData { + description: "trust level not set".to_string(), + })?; trust_level .try_into() - .map_err(|e| TendermintClientError::InvalidTrustThreshold { - description: format!("{e}"), + .map_err(|e| DecodingError::InvalidRawData { + description: format!("failed to decoding trust threshold: {e}"), })? }; let trusting_period = raw .trusting_period - .ok_or(TendermintClientError::MissingTrustingPeriod)? + .ok_or(DecodingError::MissingRawData { + description: "trusting period not set".to_string(), + })? .try_into() - .map_err(|_| TendermintClientError::MissingTrustingPeriod)?; + .map_err(|_| DecodingError::InvalidRawData { + description: "failed to decode trusting period".to_string(), + })?; let unbonding_period = raw .unbonding_period - .ok_or(TendermintClientError::MissingUnbondingPeriod)? + .ok_or(DecodingError::MissingRawData { + description: "unbonding period not set".to_string(), + })? .try_into() - .map_err(|_| TendermintClientError::MissingUnbondingPeriod)?; + .map_err(|_| DecodingError::InvalidRawData { + description: "failed to decode unbonding period".to_string(), + })?; let max_clock_drift = raw .max_clock_drift - .ok_or(TendermintClientError::InvalidMaxClockDrift)? + .ok_or(DecodingError::MissingRawData { + description: "max clock drift not set".to_string(), + })? .try_into() - .map_err(|_| TendermintClientError::InvalidMaxClockDrift)?; + .map_err(|_| DecodingError::InvalidRawData { + description: "failed to decode max clock drift".to_string(), + })?; let latest_height = raw .latest_height - .ok_or(TendermintClientError::MissingLatestHeight)? + .ok_or(DecodingError::MissingRawData { + description: "latest height not set".to_string(), + })? .try_into() - .map_err(|_| TendermintClientError::MissingLatestHeight)?; + .map_err(|e| DecodingError::InvalidRawData { + description: format!("failed to decode latest height: {e}"), + })?; // NOTE: In `RawClientState`, a `frozen_height` of `0` means "not // frozen". See: // https://github.com/cosmos/ibc-go/blob/8422d0c4c35ef970539466c5bdec1cd27369bab3/modules/light-clients/07-tendermint/types/client_state.go#L74 - let frozen_height = Height::try_from( - raw.frozen_height - .ok_or(TendermintClientError::MissingFrozenHeight)?, - ) - .ok(); + let frozen_height = + Height::try_from(raw.frozen_height.ok_or(DecodingError::MissingRawData { + description: "frozen height not set".to_string(), + })?) + .ok(); // We use set this deprecated field just so that we can properly convert // it back in its raw form diff --git a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs index f069a812c..40e5837b2 100644 --- a/ibc-clients/ics07-tendermint/types/src/consensus_state.rs +++ b/ibc-clients/ics07-tendermint/types/src/consensus_state.rs @@ -53,27 +53,26 @@ impl TryFrom for ConsensusState { fn try_from(raw: RawConsensusState) -> Result { let proto_root = raw .root - .ok_or(TendermintClientError::InvalidRawClientState { - description: "missing commitment root".into(), + .ok_or(DecodingError::MissingRawData { + description: "no commitment root set".into(), })? .hash; let ibc_proto::google::protobuf::Timestamp { seconds, nanos } = - raw.timestamp - .ok_or(TendermintClientError::InvalidRawClientState { - description: "missing timestamp".into(), - })?; + raw.timestamp.ok_or(DecodingError::MissingRawData { + description: "no timestamp set".into(), + })?; // FIXME: shunts like this are necessary due to // https://github.com/informalsystems/tendermint-rs/issues/1053 let proto_timestamp = tpb::Timestamp { seconds, nanos }; - let timestamp = proto_timestamp.try_into().map_err(|e| { - TendermintClientError::InvalidRawClientState { + let timestamp = proto_timestamp + .try_into() + .map_err(|e| DecodingError::InvalidRawData { description: format!("invalid timestamp: {e}"), - } - })?; + })?; let next_validators_hash = Hash::from_bytes(Algorithm::Sha256, &raw.next_validators_hash) - .map_err(|e| TendermintClientError::InvalidRawClientState { + .map_err(|e| DecodingError::InvalidHash { description: e.to_string(), })?; diff --git a/ibc-clients/ics07-tendermint/types/src/error.rs b/ibc-clients/ics07-tendermint/types/src/error.rs index 3d2d6dfb1..11bf310b7 100644 --- a/ibc-clients/ics07-tendermint/types/src/error.rs +++ b/ibc-clients/ics07-tendermint/types/src/error.rs @@ -26,30 +26,12 @@ pub enum TendermintClientError { InvalidMaxClockDrift, /// invalid client proof specs: `{0}` InvalidProofSpec(CommitmentError), - /// invalid raw client state: `{description}` - InvalidRawClientState { description: String }, /// invalid raw misbehaviour: `{description}` InvalidRawMisbehaviour { description: String }, /// invalid header timestamp: `{0}` InvalidHeaderTimestamp(TimestampError), /// invalid header height: `{0}` InvalidHeaderHeight(u64), - /// missing signed header - MissingSignedHeader, - /// missing validator set - MissingValidatorSet, - /// missing trusted next validator set - MissingTrustedNextValidatorSet, - /// missing trusted height - MissingTrustedHeight, - /// missing trusting period - MissingTrustingPeriod, - /// missing unbonding period - MissingUnbondingPeriod, - /// missing the latest height - MissingLatestHeight, - /// missing frozen height - MissingFrozenHeight, /// mismatched revision heights: expected `{expected}`, actual `{actual}` MismatchedRevisionHeights { expected: u64, actual: u64 }, /// mismatched header chain ids: expected `{expected}`, actual `{actual}` @@ -80,6 +62,8 @@ impl std::error::Error for TendermintClientError { } } +// TODO(seanchen1991): Should this impl be deprecated in favor of a +// From for TendermintClientError impl? impl From for ClientError { fn from(e: TendermintClientError) -> Self { Self::ClientSpecific { diff --git a/ibc-clients/ics07-tendermint/types/src/header.rs b/ibc-clients/ics07-tendermint/types/src/header.rs index 7c33f7fdd..aaadfde07 100644 --- a/ibc-clients/ics07-tendermint/types/src/header.rs +++ b/ibc-clients/ics07-tendermint/types/src/header.rs @@ -171,28 +171,36 @@ impl TryFrom for Header { let header = Self { signed_header: raw .signed_header - .ok_or(TendermintClientError::MissingSignedHeader)? + .ok_or(DecodingError::MissingRawData { + description: "signed header not set".to_string(), + })? .try_into() .map_err(|e| DecodingError::InvalidRawData { - description: format!("{e:?}"), + description: format!("failed to decode signed header: {e:?}"), })?, validator_set: raw .validator_set - .ok_or(TendermintClientError::MissingValidatorSet)? + .ok_or(DecodingError::MissingRawData { + description: "validator set not set".to_string(), + })? .try_into() .map_err(|e| DecodingError::InvalidRawData { - description: format!("{e:?}"), + description: format!("failed to decode validator set: {e:?}"), })?, trusted_height: raw .trusted_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(TendermintClientError::MissingTrustedHeight)?, + .ok_or(DecodingError::MissingRawData { + description: "trusted height not set".to_string(), + })?, trusted_next_validator_set: raw .trusted_validators - .ok_or(TendermintClientError::MissingTrustedNextValidatorSet)? + .ok_or(DecodingError::MissingRawData { + description: "trusted next validator set not set".to_string(), + })? .try_into() .map_err(|e| DecodingError::InvalidRawData { - description: format!("{e:?}"), + description: format!("failed to decode trusted next validator set: {e:?}"), })?, }; diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 87d5b78ef..eb283e2b4 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -25,12 +25,8 @@ pub enum ClientError { InvalidTrustThreshold { numerator: u64, denominator: u64 }, /// invalid client state type: `{0}` InvalidClientStateType(String), - /// invalid client consensus state type: `{0}` - InvalidConsensusStateType(String), /// invalid update client message InvalidUpdateClientMessage, - /// invalid misbehaviour type: `{0}` - InvalidMisbehaviourType(String), /// invalid height; cannot be zero or negative InvalidHeight, /// invalid proof height; expected `{actual}` >= `{expected}` @@ -43,12 +39,6 @@ pub enum ClientError { InvalidAttributeValue(String), /// invalid status: `{0}` InvalidStatus(String), - /// missing raw client state - MissingRawClientState, - /// missing raw client consensus state - MissingRawConsensusState, - /// missing raw client message - MissingRawClientMessage, /// missing local consensus state at `{0}` MissingLocalConsensusState(Height), /// missing attribute key @@ -134,7 +124,7 @@ pub enum UpgradeClientError { /// decoding error: `{0}` Decoding(DecodingError), /// invalid proof for the upgraded client state: `{0}` - InvalidUpgradeClientProof(CommitmentError), + InvalidUpgradeClientStateProof(CommitmentError), /// invalid proof for the upgraded consensus state: `{0}` InvalidUpgradeConsensusStateProof(CommitmentError), /// invalid upgrade path: `{description}` @@ -180,9 +170,8 @@ impl From for UpgradeClientError { impl std::error::Error for UpgradeClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::InvalidUpgradeClientProof(e) | Self::InvalidUpgradeConsensusStateProof(e) => { - Some(e) - } + Self::InvalidUpgradeClientStateProof(e) + | Self::InvalidUpgradeConsensusStateProof(e) => Some(e), _ => None, } } diff --git a/ibc-core/ics02-client/types/src/msgs/create_client.rs b/ibc-core/ics02-client/types/src/msgs/create_client.rs index fe6944b3d..72a035c9e 100644 --- a/ibc-core/ics02-client/types/src/msgs/create_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/create_client.rs @@ -1,5 +1,6 @@ //! Definition of domain type message `MsgCreateClient`. +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::Signer; use ibc_proto::google::protobuf::Any; @@ -39,11 +40,13 @@ impl TryFrom for MsgCreateClient { type Error = ClientError; fn try_from(raw: RawMsgCreateClient) -> Result { - let raw_client_state = raw.client_state.ok_or(ClientError::MissingRawClientState)?; + let raw_client_state = raw.client_state.ok_or(DecodingError::MissingRawData { + description: "no raw client state set".to_string(), + })?; - let raw_consensus_state = raw - .consensus_state - .ok_or(ClientError::MissingRawConsensusState)?; + let raw_consensus_state = raw.consensus_state.ok_or(DecodingError::MissingRawData { + description: "no raw consensus state set".to_string(), + })?; Ok(MsgCreateClient::new( raw_client_state, diff --git a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs index 4b545e452..b1d2964d1 100644 --- a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs @@ -60,16 +60,24 @@ impl TryFrom for MsgUpgradeClient { fn try_from(proto_msg: RawMsgUpgradeClient) -> Result { let raw_client_state = proto_msg .client_state - .ok_or(ClientError::MissingRawClientState)?; + .ok_or(DecodingError::MissingRawData { + description: "no raw client state set".to_string(), + })?; - let raw_consensus_state = proto_msg - .consensus_state - .ok_or(ClientError::MissingRawConsensusState)?; + let raw_consensus_state = + proto_msg + .consensus_state + .ok_or(DecodingError::MissingRawData { + description: "no raw consensus state set".to_string(), + })?; let c_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client).map_err(|_| { - UpgradeClientError::InvalidUpgradeClientProof(CommitmentError::EmptyMerkleProof) + UpgradeClientError::InvalidUpgradeClientStateProof( + CommitmentError::EmptyMerkleProof, + ) })?; + let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) .map_err(|_| { UpgradeClientError::InvalidUpgradeConsensusStateProof( diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 048392de6..bf1d8a129 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -35,6 +35,8 @@ pub enum DecodingError { Protobuf(ProtoError), /// prost decoding error: `{0}` Prost(ProstError), + /// invalid hash bytes: `{description}` + InvalidHash { description: String }, /// invalid JSON data: `{description}` InvalidJson { description: String }, /// invalid identifier error: `{0}` diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs index 48561f087..66d53d595 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/consensus_state.rs @@ -42,7 +42,9 @@ impl TryFrom for MockConsensusState { type Error = ClientError; fn try_from(raw: RawMockConsensusState) -> Result { - let raw_header = raw.header.ok_or(ClientError::MissingRawConsensusState)?; + let raw_header = raw.header.ok_or(DecodingError::MissingRawData { + description: "no raw header set".to_string(), + })?; Ok(Self { header: raw_header.try_into()?, From 4877a7ee7cc57fbde8cddb0596e67577b3f0536a Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 4 Sep 2024 14:56:48 -0500 Subject: [PATCH 044/107] Consolidate Connection and Packet decoding errors --- .../ics721-nft-transfer/types/src/packet.rs | 4 +- .../ics02-client/src/handler/create_client.rs | 2 +- ibc-core/ics02-client/types/src/error.rs | 2 +- .../types/src/acknowledgement.rs | 4 +- ibc-core/ics04-channel/types/src/error.rs | 58 +++++++++++-------- .../types/src/events/packet_attributes.rs | 6 +- .../types/src/msgs/acknowledgement.rs | 18 ++++-- .../types/src/msgs/chan_open_ack.rs | 14 +++-- .../types/src/msgs/chan_open_init.rs | 5 +- .../types/src/msgs/chan_open_try.rs | 10 ++-- .../types/src/msgs/recv_packet.rs | 18 ++++-- .../ics04-channel/types/src/msgs/timeout.rs | 18 ++++-- .../types/src/msgs/timeout_on_close.rs | 27 +++++---- ibc-core/ics04-channel/types/src/packet.rs | 9 ++- ibc-core/ics24-host/types/src/error.rs | 7 ++- 15 files changed, 126 insertions(+), 76 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/packet.rs b/ibc-apps/ics721-nft-transfer/types/src/packet.rs index a0bd962fe..6a8813d07 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/packet.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/packet.rs @@ -130,7 +130,7 @@ impl TryFrom for PacketData { let decoded = BASE64_STANDARD .decode(raw_pkt_data.class_data) .map_err(DecodingError::Base64)?; - let data_str = String::from_utf8(decoded).map_err(DecodingError::Utf8)?; + let data_str = String::from_utf8(decoded).map_err(DecodingError::StringUtf8)?; Some(data_str.parse()?) }; @@ -144,7 +144,7 @@ impl TryFrom for PacketData { let decoded = BASE64_STANDARD .decode(data) .map_err(DecodingError::Base64)?; - let data_str = String::from_utf8(decoded).map_err(DecodingError::Utf8)?; + let data_str = String::from_utf8(decoded).map_err(DecodingError::StringUtf8)?; data_str.parse() }) .collect(); diff --git a/ibc-core/ics02-client/src/handler/create_client.rs b/ibc-core/ics02-client/src/handler/create_client.rs index 8c7010443..47f5bab4a 100644 --- a/ibc-core/ics02-client/src/handler/create_client.rs +++ b/ibc-core/ics02-client/src/handler/create_client.rs @@ -44,7 +44,7 @@ where client_state.verify_consensus_state(consensus_state, &host_timestamp)?; if client_val_ctx.client_state(&client_id).is_ok() { - return Err(ClientError::AlreadyExistingClientState(client_id).into()); + return Err(ClientError::DuplicateClientState(client_id).into()); }; Ok(()) diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index eb283e2b4..f6000ac47 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -48,7 +48,7 @@ pub enum ClientError { /// unexpected status found: `{0}` UnexpectedStatus(Status), /// client state already exists: `{0}` - AlreadyExistingClientState(ClientId), + DuplicateClientState(ClientId), /// mismatched client recovery states MismatchedClientRecoveryStates, /// client recovery heights not allowed: expected substitute client height `{substitute_height}` > subject client height `{subject_height}` diff --git a/ibc-core/ics04-channel/types/src/acknowledgement.rs b/ibc-core/ics04-channel/types/src/acknowledgement.rs index 2e19d3358..fbd0ffdd5 100644 --- a/ibc-core/ics04-channel/types/src/acknowledgement.rs +++ b/ibc-core/ics04-channel/types/src/acknowledgement.rs @@ -46,7 +46,9 @@ impl TryFrom> for Acknowledgement { fn try_from(bytes: Vec) -> Result { if bytes.is_empty() { - Err(PacketError::EmptyAcknowledgment) + Err(DecodingError::MissingRawData { + description: "acknowledgment not set".to_string(), + })? } else { Ok(Self(bytes)) } diff --git a/ibc-core/ics04-channel/types/src/error.rs b/ibc-core/ics04-channel/types/src/error.rs index a44f1975b..93a67b134 100644 --- a/ibc-core/ics04-channel/types/src/error.rs +++ b/ibc-core/ics04-channel/types/src/error.rs @@ -3,7 +3,7 @@ use displaydoc::Display; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::Height; -use ibc_core_host_types::error::IdentifierError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_core_host_types::identifiers::{ChannelId, PortId, Sequence}; use ibc_primitives::prelude::*; use ibc_primitives::{Timestamp, TimestampError}; @@ -16,6 +16,8 @@ use crate::Version; #[derive(Debug, Display)] pub enum ChannelError { + /// decoding error: `{0}` + Decoding(DecodingError), /// identifier error: `{0}` InvalidIdentifier(IdentifierError), /// invalid channel id: expected `{expected}`, actual `{actual}` @@ -37,8 +39,6 @@ pub enum ChannelError { MissingProofHeight, /// missing counterparty MissingCounterparty, - /// missing channel end in raw message - MissingRawChannelEnd, /// unsupported channel upgrade sequence UnsupportedChannelUpgradeSequence, /// unsupported version: expected `{expected}`, actual `{actual}` @@ -48,8 +48,6 @@ pub enum ChannelError { port_id: PortId, channel_id: ChannelId, }, - /// packet data bytes must be valid UTF-8 - NonUtf8PacketData, /// failed packet verification for packet with sequence `{sequence}`: `{client_error}` FailedPacketVerification { sequence: Sequence, @@ -72,10 +70,10 @@ pub enum ChannelError { #[derive(Debug, Display)] pub enum PacketError { - /// [HostError] application module error: `{description}` - AppModule { description: String }, /// channel error: `{0}` Channel(ChannelError), + /// decoding error: `{0}` + Decoding(DecodingError), /// insufficient packet timeout height: should have `{timeout_height}` > `{chain_height}` InsufficientPacketHeight { chain_height: Height, @@ -94,14 +92,6 @@ pub enum PacketError { expected: PacketCommitment, actual: PacketCommitment, }, - /// [HostError] missing packet receipt for packet `{0}` - MissingPacketReceipt(Sequence), - /// missing proof - MissingProof, - /// [HostError] missing acknowledgment for packet `{0}` - MissingPacketAcknowledgment(Sequence), - /// missing proof height - MissingProofHeight, /// missing timeout MissingTimeout, /// invalid timeout height: `{0}` @@ -110,12 +100,8 @@ pub enum PacketError { InvalidTimeoutTimestamp(TimestampError), /// invalid identifier: `{0}` InvalidIdentifier(IdentifierError), - /// empty acknowledgment not allowed - EmptyAcknowledgment, /// empty acknowledgment status not allowed EmptyAcknowledgmentStatus, - /// packet data bytes cannot be empty - EmptyPacketData, /// packet acknowledgment for sequence `{0}` already exists DuplicateAcknowledgment(Sequence), /// packet sequence cannot be 0 @@ -129,23 +115,43 @@ pub enum PacketError { }, /// implementation-specific error ImplementationSpecific, + + // TODO(seanchen1991): Move these variants to host-relevant error types + /// application module error: `{description}` + AppModule { description: String }, + /// missing acknowledgment for packet `{0}` + MissingPacketAcknowledgment(Sequence), + /// missing packet receipt for packet `{0}` + MissingPacketReceipt(Sequence), } impl From for ChannelError { - fn from(err: IdentifierError) -> Self { - Self::InvalidIdentifier(err) + fn from(e: IdentifierError) -> Self { + Self::InvalidIdentifier(e) } } impl From for PacketError { - fn from(err: IdentifierError) -> Self { - Self::InvalidIdentifier(err) + fn from(e: IdentifierError) -> Self { + Self::InvalidIdentifier(e) + } +} + +impl From for ChannelError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } +} + +impl From for PacketError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) } } impl From for PacketError { - fn from(err: TimestampError) -> Self { - Self::InvalidTimeoutTimestamp(err) + fn from(e: TimestampError) -> Self { + Self::InvalidTimeoutTimestamp(e) } } @@ -154,6 +160,7 @@ impl std::error::Error for PacketError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::Channel(e) => Some(e), + Self::Decoding(e) => Some(e), Self::InvalidIdentifier(e) => Some(e), _ => None, } @@ -165,6 +172,7 @@ impl std::error::Error for ChannelError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::InvalidIdentifier(e) => Some(e), + Self::Decoding(e) => Some(e), Self::FailedPacketVerification { client_error: e, .. } => Some(e), diff --git a/ibc-core/ics04-channel/types/src/events/packet_attributes.rs b/ibc-core/ics04-channel/types/src/events/packet_attributes.rs index a15a31220..35fb84a7f 100644 --- a/ibc-core/ics04-channel/types/src/events/packet_attributes.rs +++ b/ibc-core/ics04-channel/types/src/events/packet_attributes.rs @@ -4,6 +4,7 @@ use core::str; use derive_more::From; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ChannelId, ConnectionId, PortId, Sequence}; use ibc_primitives::prelude::*; use subtle_encoding::hex; @@ -53,7 +54,7 @@ impl TryFrom for Vec { let tags = vec![ ( PKT_DATA_ATTRIBUTE_KEY, - str::from_utf8(&attr.packet_data).map_err(|_| ChannelError::NonUtf8PacketData)?, + str::from_utf8(&attr.packet_data).map_err(DecodingError::StrUtf8)?, ) .into(), ( @@ -322,8 +323,7 @@ impl TryFrom for Vec { // is valid UTF-8, even though the standard doesn't require // it. It has been deprecated in ibc-go. It will be removed // in the future. - str::from_utf8(attr.acknowledgement.as_bytes()) - .map_err(|_| ChannelError::NonUtf8PacketData)?, + str::from_utf8(attr.acknowledgement.as_bytes()).map_err(DecodingError::StrUtf8)?, ) .into(), ( diff --git a/ibc-core/ics04-channel/types/src/msgs/acknowledgement.rs b/ibc-core/ics04-channel/types/src/msgs/acknowledgement.rs index 2446395d7..b9f7d119e 100644 --- a/ibc-core/ics04-channel/types/src/msgs/acknowledgement.rs +++ b/ibc-core/ics04-channel/types/src/msgs/acknowledgement.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::Signer; use ibc_proto::ibc::core::channel::v1::MsgAcknowledgement as RawMsgAcknowledgement; @@ -39,17 +40,22 @@ impl TryFrom for MsgAcknowledgement { Ok(MsgAcknowledgement { packet: raw_msg .packet - .ok_or(PacketError::EmptyPacketData)? + .ok_or(DecodingError::MissingRawData { + description: "packet data not set".to_string(), + })? .try_into()?, acknowledgement: raw_msg.acknowledgement.try_into()?, - proof_acked_on_b: raw_msg - .proof_acked - .try_into() - .map_err(|_| PacketError::MissingProof)?, + proof_acked_on_b: raw_msg.proof_acked.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode proof: {e}"), + } + })?, proof_height_on_b: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(PacketError::MissingProofHeight)?, + .ok_or(DecodingError::InvalidRawData { + description: "failed to decode proof height".to_string(), + })?, signer: raw_msg.signer.into(), }) } diff --git a/ibc-core/ics04-channel/types/src/msgs/chan_open_ack.rs b/ibc-core/ics04-channel/types/src/msgs/chan_open_ack.rs index 8634eb3e8..cb13fe9cb 100644 --- a/ibc-core/ics04-channel/types/src/msgs/chan_open_ack.rs +++ b/ibc-core/ics04-channel/types/src/msgs/chan_open_ack.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ChannelId, PortId}; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -41,14 +42,17 @@ impl TryFrom for MsgChannelOpenAck { chan_id_on_a: raw_msg.channel_id.parse()?, chan_id_on_b: raw_msg.counterparty_channel_id.parse()?, version_on_b: raw_msg.counterparty_version.into(), - proof_chan_end_on_b: raw_msg - .proof_try - .try_into() - .map_err(|_| ChannelError::MissingProof)?, + proof_chan_end_on_b: raw_msg.proof_try.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode proof: {e}"), + } + })?, proof_height_on_b: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ChannelError::MissingProofHeight)?, + .ok_or(DecodingError::MissingRawData { + description: "proof height not set".to_string(), + })?, signer: raw_msg.signer.into(), }) } diff --git a/ibc-core/ics04-channel/types/src/msgs/chan_open_init.rs b/ibc-core/ics04-channel/types/src/msgs/chan_open_init.rs index afac87752..c264ddabe 100644 --- a/ibc-core/ics04-channel/types/src/msgs/chan_open_init.rs +++ b/ibc-core/ics04-channel/types/src/msgs/chan_open_init.rs @@ -1,3 +1,4 @@ +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ConnectionId, PortId}; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -47,7 +48,9 @@ impl TryFrom for MsgChannelOpenInit { fn try_from(raw_msg: RawMsgChannelOpenInit) -> Result { let chan_end_on_a: ChannelEnd = raw_msg .channel - .ok_or(ChannelError::MissingRawChannelEnd)? + .ok_or(DecodingError::MissingRawData { + description: "channel end not set".to_string(), + })? .try_into()?; chan_end_on_a.verify_state_matches(&State::Init)?; chan_end_on_a.counterparty().verify_empty_channel_id()?; diff --git a/ibc-core/ics04-channel/types/src/msgs/chan_open_try.rs b/ibc-core/ics04-channel/types/src/msgs/chan_open_try.rs index 8d85d1fa3..77e5afd89 100644 --- a/ibc-core/ics04-channel/types/src/msgs/chan_open_try.rs +++ b/ibc-core/ics04-channel/types/src/msgs/chan_open_try.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ChannelId, ConnectionId, PortId}; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -55,17 +56,16 @@ impl TryFrom for MsgChannelOpenTry { fn try_from(raw_msg: RawMsgChannelOpenTry) -> Result { let chan_end_on_b: ChannelEnd = raw_msg .channel - .ok_or(ChannelError::MissingRawChannelEnd)? + .ok_or(DecodingError::MissingRawData { + description: "channel end not set".to_string(), + })? .try_into()?; chan_end_on_b.verify_state_matches(&State::TryOpen)?; #[allow(deprecated)] if !raw_msg.previous_channel_id.is_empty() { - return Err(ChannelError::InvalidChannelId { - expected: "previous channel id must be empty. It has been deprecated as crossing hellos are no longer supported".to_string(), - actual: raw_msg.previous_channel_id, - }); + return Err(DecodingError::InvalidRawData { description: "previous channel id must be empty. It has been deprecated as crossing hellos are no longer supported".to_string() })?; } #[allow(deprecated)] diff --git a/ibc-core/ics04-channel/types/src/msgs/recv_packet.rs b/ibc-core/ics04-channel/types/src/msgs/recv_packet.rs index 53e4a6716..030449b72 100644 --- a/ibc-core/ics04-channel/types/src/msgs/recv_packet.rs +++ b/ibc-core/ics04-channel/types/src/msgs/recv_packet.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::Signer; use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; @@ -39,16 +40,21 @@ impl TryFrom for MsgRecvPacket { Ok(MsgRecvPacket { packet: raw_msg .packet - .ok_or(PacketError::EmptyPacketData)? + .ok_or(DecodingError::MissingRawData { + description: "packet data not set".to_string(), + })? .try_into()?, - proof_commitment_on_a: raw_msg - .proof_commitment - .try_into() - .map_err(|_| PacketError::MissingProof)?, + proof_commitment_on_a: raw_msg.proof_commitment.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode proof: {e}"), + } + })?, proof_height_on_a: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(PacketError::MissingProofHeight)?, + .ok_or(DecodingError::InvalidRawData { + description: "failed to decode proof height".to_string(), + })?, signer: raw_msg.signer.into(), }) } diff --git a/ibc-core/ics04-channel/types/src/msgs/timeout.rs b/ibc-core/ics04-channel/types/src/msgs/timeout.rs index 657e8233e..aaa24bd05 100644 --- a/ibc-core/ics04-channel/types/src/msgs/timeout.rs +++ b/ibc-core/ics04-channel/types/src/msgs/timeout.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::Sequence; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -41,17 +42,22 @@ impl TryFrom for MsgTimeout { Ok(MsgTimeout { packet: raw_msg .packet - .ok_or(PacketError::EmptyPacketData)? + .ok_or(DecodingError::MissingRawData { + description: "packet data not set".to_string(), + })? .try_into()?, next_seq_recv_on_b: Sequence::from(raw_msg.next_sequence_recv), - proof_unreceived_on_b: raw_msg - .proof_unreceived - .try_into() - .map_err(|_| PacketError::MissingProof)?, + proof_unreceived_on_b: raw_msg.proof_unreceived.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode proof: {e}"), + } + })?, proof_height_on_b: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(PacketError::MissingProofHeight)?, + .ok_or(DecodingError::MissingRawData { + description: "proof height not set".to_string(), + })?, signer: raw_msg.signer.into(), }) } diff --git a/ibc-core/ics04-channel/types/src/msgs/timeout_on_close.rs b/ibc-core/ics04-channel/types/src/msgs/timeout_on_close.rs index 670205716..fd1142a7c 100644 --- a/ibc-core/ics04-channel/types/src/msgs/timeout_on_close.rs +++ b/ibc-core/ics04-channel/types/src/msgs/timeout_on_close.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::Sequence; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -48,21 +49,27 @@ impl TryFrom for MsgTimeoutOnClose { Ok(MsgTimeoutOnClose { packet: raw_msg .packet - .ok_or(PacketError::EmptyPacketData)? + .ok_or(DecodingError::MissingRawData { + description: "packet data not set".to_string(), + })? .try_into()?, next_seq_recv_on_b: Sequence::from(raw_msg.next_sequence_recv), - proof_unreceived_on_b: raw_msg - .proof_unreceived - .try_into() - .map_err(|_| PacketError::MissingProof)?, - proof_close_on_b: raw_msg - .proof_close - .try_into() - .map_err(|_| PacketError::MissingProof)?, + proof_unreceived_on_b: raw_msg.proof_unreceived.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode proof: {e}"), + } + })?, + proof_close_on_b: raw_msg.proof_close.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode proof: {e}"), + } + })?, proof_height_on_b: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(PacketError::MissingProofHeight)?, + .ok_or(DecodingError::InvalidRawData { + description: "failed to decode proof height".to_string(), + })?, signer: raw_msg.signer.into(), }) } diff --git a/ibc-core/ics04-channel/types/src/packet.rs b/ibc-core/ics04-channel/types/src/packet.rs index dfd6f0358..e1be45ef3 100644 --- a/ibc-core/ics04-channel/types/src/packet.rs +++ b/ibc-core/ics04-channel/types/src/packet.rs @@ -1,5 +1,6 @@ //! Defines the packet type use ibc_core_client_types::Height; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ChannelId, PortId, Sequence}; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; @@ -172,7 +173,9 @@ impl TryFrom for Packet { } if raw_pkt.data.is_empty() { - return Err(PacketError::EmptyPacketData); + return Err(DecodingError::MissingRawData { + description: "packet data is not set".to_string(), + })?; } // Note: ibc-go currently (July 2022) incorrectly treats the timeout @@ -282,7 +285,9 @@ impl TryFrom for PacketState { } if raw_pkt.data.is_empty() { - return Err(PacketError::EmptyPacketData); + return Err(DecodingError::MissingRawData { + description: "packet data not set".to_string(), + })?; } Ok(PacketState { diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index bf1d8a129..5a89f9ab8 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -1,6 +1,7 @@ //! Foundational error types that are applicable across multiple ibc-rs workspaces. use alloc::string::{FromUtf8Error, String}; +use core::str::Utf8Error; use base64::DecodeError as Base64Error; use displaydoc::Display; @@ -29,8 +30,10 @@ pub enum IdentifierError { pub enum DecodingError { /// base64 decoding error: `{0}` Base64(Base64Error), - /// utf-8 decoding error: `{0}` - Utf8(FromUtf8Error), + /// utf-8 String decoding error: `{0}` + StringUtf8(FromUtf8Error), + /// utf-8 str decoding error: `{0}` + StrUtf8(Utf8Error), /// protobuf decoding error: `{0}` Protobuf(ProtoError), /// prost decoding error: `{0}` From cd95fa5c0d2f026b3d37664917bc8682544cacf9 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 4 Sep 2024 15:05:40 -0500 Subject: [PATCH 045/107] Remove WasmClientError --- .../ics08-wasm/types/src/client_state.rs | 17 ++++---- ibc-clients/ics08-wasm/types/src/error.rs | 41 ------------------- ibc-clients/ics08-wasm/types/src/lib.rs | 1 - .../types/src/msgs/migrate_contract.rs | 7 ++-- 4 files changed, 13 insertions(+), 53 deletions(-) delete mode 100644 ibc-clients/ics08-wasm/types/src/error.rs diff --git a/ibc-clients/ics08-wasm/types/src/client_state.rs b/ibc-clients/ics08-wasm/types/src/client_state.rs index 7124636ae..b7506267a 100644 --- a/ibc-clients/ics08-wasm/types/src/client_state.rs +++ b/ibc-clients/ics08-wasm/types/src/client_state.rs @@ -6,7 +6,6 @@ use ibc_primitives::prelude::*; use ibc_primitives::proto::{Any, Protobuf}; use ibc_proto::ibc::lightclients::wasm::v1::ClientState as RawClientState; -use crate::error::WasmClientError; #[cfg(feature = "serde")] use crate::serializer::Base64; use crate::Bytes; @@ -39,14 +38,18 @@ impl From for RawClientState { } impl TryFrom for ClientState { - type Error = WasmClientError; + type Error = DecodingError; fn try_from(raw: RawClientState) -> Result { let latest_height = raw .latest_height - .ok_or(WasmClientError::MissingLatestHeight)? + .ok_or(DecodingError::MissingRawData { + description: "latest height not set".to_string(), + })? .try_into() - .map_err(|_| WasmClientError::InvalidLatestHeight)?; + .map_err(|e| DecodingError::InvalidRawData { + description: format!("failed to decode latest height: {e}"), + })?; Ok(Self { data: raw.data, checksum: raw.checksum, @@ -67,7 +70,7 @@ impl From for Any { } impl TryFrom for ClientState { - type Error = WasmClientError; + type Error = DecodingError; fn try_from(any: Any) -> Result { fn decode_client_state(value: &[u8]) -> Result { @@ -76,9 +79,7 @@ impl TryFrom for ClientState { } match any.type_url.as_str() { - WASM_CLIENT_STATE_TYPE_URL => { - decode_client_state(&any.value).map_err(WasmClientError::Decoding) - } + WASM_CLIENT_STATE_TYPE_URL => decode_client_state(&any.value), _ => Err(DecodingError::MismatchedTypeUrls { expected: WASM_CLIENT_STATE_TYPE_URL.to_string(), actual: any.type_url, diff --git a/ibc-clients/ics08-wasm/types/src/error.rs b/ibc-clients/ics08-wasm/types/src/error.rs deleted file mode 100644 index f7615f802..000000000 --- a/ibc-clients/ics08-wasm/types/src/error.rs +++ /dev/null @@ -1,41 +0,0 @@ -//! Defines the error type for the ICS-08 Wasm light client. - -use displaydoc::Display; -use ibc_core_host_types::error::{DecodingError, IdentifierError}; -use ibc_primitives::prelude::*; - -/// The main error type -#[derive(Debug, Display)] -pub enum WasmClientError { - /// decoding error: `{0}` - Decoding(DecodingError), - /// invalid identifier: `{0}` - InvalidIdentifier(IdentifierError), - /// invalid client state latest height - InvalidLatestHeight, - /// missing latest height - MissingLatestHeight, -} - -#[cfg(feature = "std")] -impl std::error::Error for WasmClientError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::InvalidIdentifier(e) => Some(e), - Self::Decoding(e) => Some(e), - _ => None, - } - } -} - -impl From for WasmClientError { - fn from(e: IdentifierError) -> Self { - Self::InvalidIdentifier(e) - } -} - -impl From for WasmClientError { - fn from(e: DecodingError) -> Self { - Self::Decoding(e) - } -} diff --git a/ibc-clients/ics08-wasm/types/src/lib.rs b/ibc-clients/ics08-wasm/types/src/lib.rs index 169eb3b30..3a88d0431 100644 --- a/ibc-clients/ics08-wasm/types/src/lib.rs +++ b/ibc-clients/ics08-wasm/types/src/lib.rs @@ -15,7 +15,6 @@ pub mod client_message; pub mod client_state; pub mod consensus_state; -pub mod error; pub mod msgs; #[cfg(feature = "serde")] diff --git a/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs b/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs index cd0bd9d3d..c00d36080 100644 --- a/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs +++ b/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs @@ -1,12 +1,12 @@ use core::str::FromStr; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; use ibc_proto::ibc::lightclients::wasm::v1::MsgMigrateContract as RawMsgMigrateContract; use ibc_proto::Protobuf; -use crate::error::WasmClientError; use crate::Bytes; pub const MIGRATE_CONTRACT_TYPE_URL: &str = "/ibc.lightclients.wasm.v1.MsgMigrateContract"; @@ -34,12 +34,13 @@ impl From for RawMsgMigrateContract { } impl TryFrom for MsgMigrateContract { - type Error = WasmClientError; + type Error = DecodingError; fn try_from(value: RawMsgMigrateContract) -> Result { Ok(Self { signer: Signer::from(value.signer), - client_id: ClientId::from_str(&value.client_id)?, + client_id: ClientId::from_str(&value.client_id) + .map_err(DecodingError::InvalidIdentifier)?, checksum: value.checksum, msg: value.msg, }) From a4279884f3d50eed20413dbdcb660921505c014a Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 4 Sep 2024 15:12:43 -0500 Subject: [PATCH 046/107] Consolidate Identifier variant naming --- ibc-clients/ics07-tendermint/types/src/error.rs | 8 ++++---- .../ics08-wasm/types/src/msgs/migrate_contract.rs | 3 +-- ibc-core/ics02-client/types/src/error.rs | 3 +-- .../ics02-client/types/src/msgs/misbehaviour.rs | 7 ++----- .../ics02-client/types/src/msgs/recover_client.rs | 4 ++-- .../ics02-client/types/src/msgs/update_client.rs | 7 ++----- .../ics02-client/types/src/msgs/upgrade_client.rs | 2 +- ibc-core/ics03-connection/types/src/connection.rs | 11 ++++------- ibc-core/ics03-connection/types/src/error.rs | 4 ++-- .../types/src/msgs/conn_open_ack.rs | 4 ++-- .../types/src/msgs/conn_open_confirm.rs | 2 +- .../types/src/msgs/conn_open_init.rs | 5 +---- .../types/src/msgs/conn_open_try.rs | 5 +---- ibc-core/ics04-channel/types/src/error.rs | 14 +++++++------- ibc-core/ics24-host/types/src/error.rs | 4 ++-- 15 files changed, 33 insertions(+), 50 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/error.rs b/ibc-clients/ics07-tendermint/types/src/error.rs index 11bf310b7..f09c74748 100644 --- a/ibc-clients/ics07-tendermint/types/src/error.rs +++ b/ibc-clients/ics07-tendermint/types/src/error.rs @@ -18,8 +18,8 @@ use tendermint_light_client_verifier::Verdict; pub enum TendermintClientError { /// decoding error: `{0}` Decoding(DecodingError), - /// invalid identifier: `{0}` - InvalidIdentifier(IdentifierError), + /// identifier error: `{0}` + Identifier(IdentifierError), /// invalid client state trust threshold: `{description}` InvalidTrustThreshold { description: String }, /// invalid clock drift; must be greater than 0 @@ -55,7 +55,7 @@ pub enum TendermintClientError { impl std::error::Error for TendermintClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::InvalidIdentifier(e) => Some(e), + Self::Identifier(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } @@ -74,7 +74,7 @@ impl From for ClientError { impl From for TendermintClientError { fn from(e: IdentifierError) -> Self { - Self::InvalidIdentifier(e) + Self::Identifier(e) } } diff --git a/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs b/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs index c00d36080..6a8e860e3 100644 --- a/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs +++ b/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs @@ -39,8 +39,7 @@ impl TryFrom for MsgMigrateContract { fn try_from(value: RawMsgMigrateContract) -> Result { Ok(Self { signer: Signer::from(value.signer), - client_id: ClientId::from_str(&value.client_id) - .map_err(DecodingError::InvalidIdentifier)?, + client_id: ClientId::from_str(&value.client_id).map_err(DecodingError::Identifier)?, checksum: value.checksum, msg: value.msg, }) diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index f6000ac47..26aeb03dd 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -3,13 +3,12 @@ use core::convert::Infallible; use displaydoc::Display; -use tendermint::Error as TendermintError; - use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; +use tendermint::Error as TendermintError; use crate::height::Height; use crate::Status; diff --git a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs index 7215ca534..dac0eb62e 100644 --- a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs +++ b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs @@ -42,14 +42,11 @@ impl TryFrom for MsgSubmitMisbehaviour { fn try_from(raw: RawMsgSubmitMisbehaviour) -> Result { let raw_misbehaviour = raw.misbehaviour.ok_or(DecodingError::MissingRawData { - description: "missing raw misbehaviour".to_string(), + description: "misbehaviour not set".to_string(), })?; Ok(MsgSubmitMisbehaviour { - client_id: raw - .client_id - .parse() - .map_err(DecodingError::InvalidIdentifier)?, + client_id: raw.client_id.parse().map_err(DecodingError::Identifier)?, misbehaviour: raw_misbehaviour, signer: raw.signer.into(), }) diff --git a/ibc-core/ics02-client/types/src/msgs/recover_client.rs b/ibc-core/ics02-client/types/src/msgs/recover_client.rs index 6d78f0ed1..e9b79c78f 100644 --- a/ibc-core/ics02-client/types/src/msgs/recover_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/recover_client.rs @@ -46,11 +46,11 @@ impl TryFrom for MsgRecoverClient { subject_client_id: raw .subject_client_id .parse() - .map_err(DecodingError::InvalidIdentifier)?, + .map_err(DecodingError::Identifier)?, substitute_client_id: raw .substitute_client_id .parse() - .map_err(DecodingError::InvalidIdentifier)?, + .map_err(DecodingError::Identifier)?, signer: raw.signer.into(), }) } diff --git a/ibc-core/ics02-client/types/src/msgs/update_client.rs b/ibc-core/ics02-client/types/src/msgs/update_client.rs index 0ffa8430a..5c5518884 100644 --- a/ibc-core/ics02-client/types/src/msgs/update_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/update_client.rs @@ -35,12 +35,9 @@ impl TryFrom for MsgUpdateClient { fn try_from(raw: RawMsgUpdateClient) -> Result { Ok(MsgUpdateClient { - client_id: raw - .client_id - .parse() - .map_err(DecodingError::InvalidIdentifier)?, + client_id: raw.client_id.parse().map_err(DecodingError::Identifier)?, client_message: raw.client_message.ok_or(DecodingError::MissingRawData { - description: "missing raw client message".to_string(), + description: "client message not set".to_string(), })?, signer: raw.signer.into(), }) diff --git a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs index b1d2964d1..8bcf63956 100644 --- a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs @@ -87,7 +87,7 @@ impl TryFrom for MsgUpgradeClient { Ok(MsgUpgradeClient { client_id: ClientId::from_str(&proto_msg.client_id) - .map_err(DecodingError::InvalidIdentifier)?, + .map_err(DecodingError::Identifier)?, upgraded_client_state: raw_client_state, upgraded_consensus_state: raw_consensus_state, proof_upgrade_client: c_bytes, diff --git a/ibc-core/ics03-connection/types/src/connection.rs b/ibc-core/ics03-connection/types/src/connection.rs index 2602c456d..8af322e41 100644 --- a/ibc-core/ics03-connection/types/src/connection.rs +++ b/ibc-core/ics03-connection/types/src/connection.rs @@ -67,10 +67,7 @@ impl TryFrom for IdentifiedConnectionEnd { }; Ok(IdentifiedConnectionEnd { - connection_id: value - .id - .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + connection_id: value.id.parse().map_err(ConnectionError::Identifier)?, connection_end: raw_connection_end.try_into()?, }) } @@ -214,7 +211,7 @@ impl TryFrom for ConnectionEnd { value .client_id .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + .map_err(ConnectionError::Identifier)?, value .counterparty .ok_or(ConnectionError::MissingCounterparty)? @@ -378,14 +375,14 @@ impl TryFrom for Counterparty { raw_counterparty .connection_id .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + .map_err(ConnectionError::Identifier)?, ) }; Ok(Counterparty::new( raw_counterparty .client_id .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + .map_err(ConnectionError::Identifier)?, connection_id, raw_counterparty .prefix diff --git a/ibc-core/ics03-connection/types/src/error.rs b/ibc-core/ics03-connection/types/src/error.rs index d141c6303..fa6d49ad1 100644 --- a/ibc-core/ics03-connection/types/src/error.rs +++ b/ibc-core/ics03-connection/types/src/error.rs @@ -14,8 +14,8 @@ use crate::version::Version; pub enum ConnectionError { /// decoding error: `{0}` Decoding(DecodingError), - /// invalid identifier: `{0}` - InvalidIdentifier(IdentifierError), + /// identifier error: `{0}` + Identifier(IdentifierError), /// invalid state for initializing new ConnectionEnd; expected `Init` connection state and a single version InvalidStateForConnectionEndInit, /// invalid connection proof diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs index dc3056b2a..611102f8b 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs @@ -54,11 +54,11 @@ impl TryFrom for MsgConnectionOpenAck { conn_id_on_a: msg .connection_id .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + .map_err(ConnectionError::Identifier)?, conn_id_on_b: msg .counterparty_connection_id .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + .map_err(ConnectionError::Identifier)?, client_state_of_a_on_b: msg .client_state .ok_or(ConnectionError::MissingClientState)?, diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs index e18821d57..3f534a2d6 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs @@ -38,7 +38,7 @@ impl TryFrom for MsgConnectionOpenConfirm { conn_id_on_b: msg .connection_id .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + .map_err(ConnectionError::Identifier)?, proof_conn_end_on_a: msg .proof_ack .try_into() diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_init.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_init.rs index 7d9affcfd..eed8736a3 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_init.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_init.rs @@ -95,10 +95,7 @@ impl TryFrom for MsgConnectionOpenInit { counterparty.verify_empty_connection_id()?; Ok(Self { - client_id_on_a: msg - .client_id - .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + client_id_on_a: msg.client_id.parse().map_err(ConnectionError::Identifier)?, counterparty, version: msg.version.map(TryInto::try_into).transpose()?, delay_period: Duration::from_nanos(msg.delay_period), diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs index 6686b806a..0c9e884ea 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs @@ -162,10 +162,7 @@ impl TryFrom for MsgConnectionOpenTry { #[allow(deprecated)] Ok(Self { previous_connection_id: msg.previous_connection_id, - client_id_on_b: msg - .client_id - .parse() - .map_err(ConnectionError::InvalidIdentifier)?, + client_id_on_b: msg.client_id.parse().map_err(ConnectionError::Identifier)?, client_state_of_b_on_a: msg .client_state .ok_or(ConnectionError::MissingClientState)?, diff --git a/ibc-core/ics04-channel/types/src/error.rs b/ibc-core/ics04-channel/types/src/error.rs index 93a67b134..abf150b13 100644 --- a/ibc-core/ics04-channel/types/src/error.rs +++ b/ibc-core/ics04-channel/types/src/error.rs @@ -19,7 +19,7 @@ pub enum ChannelError { /// decoding error: `{0}` Decoding(DecodingError), /// identifier error: `{0}` - InvalidIdentifier(IdentifierError), + Identifier(IdentifierError), /// invalid channel id: expected `{expected}`, actual `{actual}` InvalidChannelId { expected: String, actual: String }, /// invalid channel state: expected `{expected}`, actual `{actual}` @@ -98,8 +98,8 @@ pub enum PacketError { InvalidTimeoutHeight(ClientError), /// invalid timeout timestamp: `{0}` InvalidTimeoutTimestamp(TimestampError), - /// invalid identifier: `{0}` - InvalidIdentifier(IdentifierError), + /// identifier error: `{0}` + Identifier(IdentifierError), /// empty acknowledgment status not allowed EmptyAcknowledgmentStatus, /// packet acknowledgment for sequence `{0}` already exists @@ -127,13 +127,13 @@ pub enum PacketError { impl From for ChannelError { fn from(e: IdentifierError) -> Self { - Self::InvalidIdentifier(e) + Self::Identifier(e) } } impl From for PacketError { fn from(e: IdentifierError) -> Self { - Self::InvalidIdentifier(e) + Self::Identifier(e) } } @@ -161,7 +161,7 @@ impl std::error::Error for PacketError { match &self { Self::Channel(e) => Some(e), Self::Decoding(e) => Some(e), - Self::InvalidIdentifier(e) => Some(e), + Self::Identifier(e) => Some(e), _ => None, } } @@ -171,7 +171,7 @@ impl std::error::Error for PacketError { impl std::error::Error for ChannelError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::InvalidIdentifier(e) => Some(e), + Self::Identifier(e) => Some(e), Self::Decoding(e) => Some(e), Self::FailedPacketVerification { client_error: e, .. diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 5a89f9ab8..fefc02871 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -28,6 +28,8 @@ pub enum IdentifierError { /// Errors that result in decoding failures #[derive(Debug, Display)] pub enum DecodingError { + /// identifier error: `{0}` + Identifier(IdentifierError), /// base64 decoding error: `{0}` Base64(Base64Error), /// utf-8 String decoding error: `{0}` @@ -42,8 +44,6 @@ pub enum DecodingError { InvalidHash { description: String }, /// invalid JSON data: `{description}` InvalidJson { description: String }, - /// invalid identifier error: `{0}` - InvalidIdentifier(IdentifierError), /// invalid raw data: `{description}` InvalidRawData { description: String }, /// missing raw data: `{description}` From 5da4717d03e2719e850f970e1e746a902429e0a9 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 4 Sep 2024 16:44:32 -0500 Subject: [PATCH 047/107] Remove HostError annotations in doc comments --- ibc-core/ics03-connection/types/src/error.rs | 26 +++++--- .../types/src/msgs/conn_open_try.rs | 62 +++++++++++-------- 2 files changed, 54 insertions(+), 34 deletions(-) diff --git a/ibc-core/ics03-connection/types/src/error.rs b/ibc-core/ics03-connection/types/src/error.rs index fa6d49ad1..f7ef3426e 100644 --- a/ibc-core/ics03-connection/types/src/error.rs +++ b/ibc-core/ics03-connection/types/src/error.rs @@ -44,10 +44,6 @@ pub enum ConnectionError { MissingProofHeight, /// missing consensus height MissingConsensusHeight, - /// [HostError] missing connection `{0}` - MissingConnection(ConnectionId), - /// [HostError] missing connection counter - MissingConnectionCounter, /// missing counterparty MissingCounterparty, /// missing client state @@ -73,14 +69,26 @@ pub enum ConnectionError { FailedToVerifyConsensusState(ClientError), /// failed to verify client state: `{0}` FailedToVerifyClientState(ClientError), - /// [HostError] failed to store connection IDs + /// overflowed timestamp: `{0}` + OverflowedTimestamp(TimestampError), + + // TODO(seanchen1991): Move these variants to host-relevant error types + /// missing connection `{0}` + MissingConnection(ConnectionId), + /// missing connection counter + MissingConnectionCounter, + /// failed to store connection IDs FailedToStoreConnectionIds, - /// [HostError] failed to store connection end + /// failed to store connection end FailedToStoreConnectionEnd, - /// [HostError] failed to update connection counter + /// failed to update connection counter FailedToUpdateConnectionCounter, - /// overflowed timestamp: `{0}` - OverflowedTimestamp(TimestampError), +} + +impl From for ConnectionError { + fn from(e: DecodingError) -> Self { + Self::Decoding(e) + } } #[cfg(feature = "std")] diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs index 0c9e884ea..2bc0526aa 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_try.rs @@ -2,6 +2,7 @@ use core::time::Duration; use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -154,7 +155,9 @@ impl TryFrom for MsgConnectionOpenTry { .collect::, _>>()?; if counterparty_versions.is_empty() { - return Err(ConnectionError::EmptyVersions); + return Err(DecodingError::MissingRawData { + description: "connection versions not set".to_string(), + })?; } // We set the deprecated `previous_connection_id` field so that we can @@ -162,45 +165,54 @@ impl TryFrom for MsgConnectionOpenTry { #[allow(deprecated)] Ok(Self { previous_connection_id: msg.previous_connection_id, - client_id_on_b: msg.client_id.parse().map_err(ConnectionError::Identifier)?, - client_state_of_b_on_a: msg - .client_state - .ok_or(ConnectionError::MissingClientState)?, + client_id_on_b: msg.client_id.parse().map_err(DecodingError::Identifier)?, + client_state_of_b_on_a: msg.client_state.ok_or(DecodingError::MissingRawData { + description: "client state not set".to_string(), + })?, counterparty: msg .counterparty - .ok_or(ConnectionError::MissingCounterparty)? + .ok_or(DecodingError::MissingRawData { + description: "counterparty not set".to_string(), + })? .try_into()?, versions_on_a: counterparty_versions, - proof_conn_end_on_a: msg - .proof_init - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, - proof_client_state_of_b_on_a: msg - .proof_client - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, - proof_consensus_state_of_b_on_a: msg - .proof_consensus - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, + proof_conn_end_on_a: msg.proof_init.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode connection end proof: {e}"), + } + })?, + proof_client_state_of_b_on_a: msg.proof_client.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode client state proof: {e}"), + } + })?, + proof_consensus_state_of_b_on_a: msg.proof_consensus.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode consensus state proof: {e}"), + } + })?, proofs_height_on_a: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ConnectionError::MissingProofHeight)?, + .ok_or(DecodingError::InvalidRawData { + description: "failed to decode proof height".to_string(), + })?, consensus_height_of_b_on_a: msg .consensus_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ConnectionError::MissingConsensusHeight)?, + .ok_or(DecodingError::InvalidRawData { + description: "failed to decode consensus height".to_string(), + })?, delay_period: Duration::from_nanos(msg.delay_period), signer: msg.signer.into(), proof_consensus_state_of_b: if msg.host_consensus_state_proof.is_empty() { None } else { - Some( - msg.host_consensus_state_proof - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, - ) + Some(msg.host_consensus_state_proof.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode consensus state proof: {e}"), + } + })?) }, }) } From 3a0365d8bbc10fe833d8f2e9709b230323248ed0 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 5 Sep 2024 09:07:43 -0500 Subject: [PATCH 048/107] Consolidate CommitmentError variants --- .../types/src/msgs/upgrade_client.rs | 8 +++--- .../ics23-commitment/types/src/commitment.rs | 4 ++- ibc-core/ics23-commitment/types/src/error.rs | 6 ----- ibc-core/ics23-commitment/types/src/specs.rs | 25 ++++++++++++------- 4 files changed, 23 insertions(+), 20 deletions(-) diff --git a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs index 8bcf63956..72251e3d7 100644 --- a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs @@ -61,27 +61,27 @@ impl TryFrom for MsgUpgradeClient { let raw_client_state = proto_msg .client_state .ok_or(DecodingError::MissingRawData { - description: "no raw client state set".to_string(), + description: "client state not set".to_string(), })?; let raw_consensus_state = proto_msg .consensus_state .ok_or(DecodingError::MissingRawData { - description: "no raw consensus state set".to_string(), + description: "consensus state not set".to_string(), })?; let c_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client).map_err(|_| { UpgradeClientError::InvalidUpgradeClientStateProof( - CommitmentError::EmptyMerkleProof, + CommitmentError::InvalidMerkleProof, ) })?; let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) .map_err(|_| { UpgradeClientError::InvalidUpgradeConsensusStateProof( - CommitmentError::EmptyMerkleProof, + CommitmentError::InvalidMerkleProof, ) })?; diff --git a/ibc-core/ics23-commitment/types/src/commitment.rs b/ibc-core/ics23-commitment/types/src/commitment.rs index 1f6c94175..88df28c54 100644 --- a/ibc-core/ics23-commitment/types/src/commitment.rs +++ b/ibc-core/ics23-commitment/types/src/commitment.rs @@ -95,7 +95,9 @@ impl TryFrom> for CommitmentProofBytes { fn try_from(bytes: Vec) -> Result { if bytes.is_empty() { - Err(Self::Error::EmptyMerkleProof) + Err(DecodingError::InvalidRawData { + description: "empty commitment proof bytes".to_string(), + })? } else { Ok(Self { bytes }) } diff --git a/ibc-core/ics23-commitment/types/src/error.rs b/ibc-core/ics23-commitment/types/src/error.rs index 511aa3fb9..3b6d09927 100644 --- a/ibc-core/ics23-commitment/types/src/error.rs +++ b/ibc-core/ics23-commitment/types/src/error.rs @@ -22,18 +22,12 @@ pub enum CommitmentError { EmptyProofSpecs, /// mismatched number of proofs: expected `{expected}`, actual `{actual}` MismatchedNumberOfProofs { expected: usize, actual: usize }, - /// mismatched proofs: expected `{expected}`, actual `{actual}` - MismatchedProofs { expected: String, actual: String }, /// invalid range: [`{min}`, `{max}`] InvalidRange { min: i32, max: i32 }, /// invalid merkle proof InvalidMerkleProof, /// invalid child size: `{0}` InvalidChildSize(i32), - /// invalid hash operation: `{0}` - InvalidHashOp(i32), - /// invalid length operation: `{0}` - InvalidLengthOp(i32), /// failed to verify membership FailedToVerifyMembership, } diff --git a/ibc-core/ics23-commitment/types/src/specs.rs b/ibc-core/ics23-commitment/types/src/specs.rs index a37abf6cc..8b4f934a9 100644 --- a/ibc-core/ics23-commitment/types/src/specs.rs +++ b/ibc-core/ics23-commitment/types/src/specs.rs @@ -1,5 +1,6 @@ //! Defines proof specs, which encode the structure of proofs +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_proto::ics23::{InnerSpec as RawInnerSpec, LeafOp as RawLeafOp, ProofSpec as RawProofSpec}; use ics23::{HashOp, LengthOp}; @@ -129,16 +130,21 @@ struct LeafOp(RawLeafOp); impl TryFrom for LeafOp { type Error = CommitmentError; - fn try_from(leaf_op: RawLeafOp) -> Result { - let _ = HashOp::try_from(leaf_op.hash) - .map_err(|_| CommitmentError::InvalidHashOp(leaf_op.hash))?; - let _ = HashOp::try_from(leaf_op.prehash_key) - .map_err(|_| CommitmentError::InvalidHashOp(leaf_op.prehash_key))?; - let _ = HashOp::try_from(leaf_op.prehash_value) - .map_err(|_| CommitmentError::InvalidHashOp(leaf_op.prehash_value))?; - let _ = LengthOp::try_from(leaf_op.length) - .map_err(|_| CommitmentError::InvalidLengthOp(leaf_op.length))?; + fn try_from(leaf_op: RawLeafOp) -> Result { + let _ = HashOp::try_from(leaf_op.hash).map_err(|e| DecodingError::InvalidHash { + description: format!("hash op {0} is invalid: {e}", leaf_op.hash), + })?; + let _ = HashOp::try_from(leaf_op.prehash_key).map_err(|e| DecodingError::InvalidHash { + description: format!("hash op {0} is invalid: {e}", leaf_op.prehash_key), + })?; + let _ = + HashOp::try_from(leaf_op.prehash_value).map_err(|e| DecodingError::InvalidHash { + description: format!("hash op {0} is invalid: {e}", leaf_op.prehash_value), + })?; + let _ = LengthOp::try_from(leaf_op.length).map_err(|e| DecodingError::InvalidHash { + description: format!("length op {0} is invalid: {e}", leaf_op.length), + })?; Ok(Self(leaf_op)) } } @@ -155,6 +161,7 @@ struct InnerSpec(RawInnerSpec); impl TryFrom for InnerSpec { type Error = CommitmentError; + fn try_from(inner_spec: RawInnerSpec) -> Result { if inner_spec.child_size <= 0 { return Err(CommitmentError::InvalidChildSize(inner_spec.child_size)); From ca7e3a3f697f097f86760370321c06ae904e9539 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 5 Sep 2024 09:48:50 -0500 Subject: [PATCH 049/107] Consolidate ConnectionError variants --- .../ics03-connection/types/src/connection.rs | 10 +++- ibc-core/ics03-connection/types/src/error.rs | 14 ----- .../types/src/msgs/conn_open_ack.rs | 60 +++++++++++-------- .../types/src/msgs/conn_open_confirm.rs | 16 +++-- .../ics03-connection/types/src/version.rs | 6 +- 5 files changed, 58 insertions(+), 48 deletions(-) diff --git a/ibc-core/ics03-connection/types/src/connection.rs b/ibc-core/ics03-connection/types/src/connection.rs index 8af322e41..901cf4f5c 100644 --- a/ibc-core/ics03-connection/types/src/connection.rs +++ b/ibc-core/ics03-connection/types/src/connection.rs @@ -4,6 +4,7 @@ use core::fmt::{Display, Error as FmtError, Formatter}; use core::time::Duration; use ibc_core_commitment_types::commitment::CommitmentPrefix; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ClientId, ConnectionId}; use ibc_primitives::prelude::*; use ibc_proto::ibc::core::connection::v1::{ @@ -195,15 +196,20 @@ impl Protobuf for ConnectionEnd {} impl TryFrom for ConnectionEnd { type Error = ConnectionError; + fn try_from(value: RawConnectionEnd) -> Result { let state = value.state.try_into()?; if value.client_id.is_empty() { - return Err(ConnectionError::EmptyProtoConnectionEnd); + return Err(DecodingError::MissingRawData { + description: "connection end is empty".to_string(), + })?; } if value.versions.is_empty() { - return Err(ConnectionError::EmptyVersions); + return Err(DecodingError::MissingRawData { + description: "connection versions is empty".to_string(), + })?; } Self::new( diff --git a/ibc-core/ics03-connection/types/src/error.rs b/ibc-core/ics03-connection/types/src/error.rs index f7ef3426e..d80c0d6a0 100644 --- a/ibc-core/ics03-connection/types/src/error.rs +++ b/ibc-core/ics03-connection/types/src/error.rs @@ -18,18 +18,12 @@ pub enum ConnectionError { Identifier(IdentifierError), /// invalid state for initializing new ConnectionEnd; expected `Init` connection state and a single version InvalidStateForConnectionEndInit, - /// invalid connection proof - InvalidProof, /// invalid counterparty InvalidCounterparty, /// invalid client state: `{description}` InvalidClientState { description: String }, /// mismatched connection states: expected `{expected}`, actual `{actual}` MismatchedConnectionStates { expected: String, actual: String }, - /// empty proto connection end; failed to construct ConnectionEnd domain object - EmptyProtoConnectionEnd, - /// empty supported versions - EmptyVersions, /// empty supported features EmptyFeatures, /// unsupported version \"`{0}`\" @@ -40,14 +34,8 @@ pub enum ConnectionError { MissingCommonVersion, /// missing common features MissingCommonFeatures, - /// missing proof height - MissingProofHeight, - /// missing consensus height - MissingConsensusHeight, /// missing counterparty MissingCounterparty, - /// missing client state - MissingClientState, /// insufficient consensus height `{current_height}` for host chain; needs to meet counterparty's height `{target_height}` InsufficientConsensusHeight { target_height: Height, @@ -98,8 +86,6 @@ impl std::error::Error for ConnectionError { Self::FailedToVerifyConnectionState(e) | Self::FailedToVerifyConsensusState(e) | Self::FailedToVerifyClientState(e) => Some(e), - // Self::InvalidIdentifier(e) => Some(e), - // Self::OverflowedTimestamp(e) => Some(e), _ => None, } } diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs index 611102f8b..e0675b3ca 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_ack.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ConnectionId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -54,47 +55,56 @@ impl TryFrom for MsgConnectionOpenAck { conn_id_on_a: msg .connection_id .parse() - .map_err(ConnectionError::Identifier)?, + .map_err(DecodingError::Identifier)?, conn_id_on_b: msg .counterparty_connection_id .parse() - .map_err(ConnectionError::Identifier)?, - client_state_of_a_on_b: msg - .client_state - .ok_or(ConnectionError::MissingClientState)?, + .map_err(DecodingError::Identifier)?, + client_state_of_a_on_b: msg.client_state.ok_or(DecodingError::MissingRawData { + description: "client state not set".to_string(), + })?, version: msg .version - .ok_or(ConnectionError::EmptyVersions)? + .ok_or(DecodingError::MissingRawData { + description: "connection version not set".to_string(), + })? .try_into()?, - proof_conn_end_on_b: msg - .proof_try - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, - proof_client_state_of_a_on_b: msg - .proof_client - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, - proof_consensus_state_of_a_on_b: msg - .proof_consensus - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, + proof_conn_end_on_b: msg.proof_try.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode connection end proof: {e}"), + } + })?, + proof_client_state_of_a_on_b: msg.proof_client.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode client state proof: {e}"), + } + })?, + proof_consensus_state_of_a_on_b: msg.proof_consensus.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode consensus state proof: {e}"), + } + })?, proofs_height_on_b: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ConnectionError::MissingProofHeight)?, + .ok_or(DecodingError::MissingRawData { + description: "proof height not set".to_string(), + })?, consensus_height_of_a_on_b: msg .consensus_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ConnectionError::MissingConsensusHeight)?, + .ok_or(DecodingError::MissingRawData { + description: "consensus height not set".to_string(), + })?, signer: msg.signer.into(), proof_consensus_state_of_a: if msg.host_consensus_state_proof.is_empty() { None } else { - Some( - msg.host_consensus_state_proof - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, - ) + Some(msg.host_consensus_state_proof.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode host consensus state proof: {e}"), + } + })?) }, }) } diff --git a/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs b/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs index 3f534a2d6..0157b9bb7 100644 --- a/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs +++ b/ibc-core/ics03-connection/types/src/msgs/conn_open_confirm.rs @@ -1,5 +1,6 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentProofBytes; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ConnectionId; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -38,15 +39,18 @@ impl TryFrom for MsgConnectionOpenConfirm { conn_id_on_b: msg .connection_id .parse() - .map_err(ConnectionError::Identifier)?, - proof_conn_end_on_a: msg - .proof_ack - .try_into() - .map_err(|_| ConnectionError::InvalidProof)?, + .map_err(DecodingError::Identifier)?, + proof_conn_end_on_a: msg.proof_ack.try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("failed to decode connection end proof: {e}"), + } + })?, proof_height_on_a: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ConnectionError::MissingProofHeight)?, + .ok_or(DecodingError::InvalidRawData { + description: "failed to decode proof height".to_string(), + })?, signer: msg.signer.into(), }) } diff --git a/ibc-core/ics03-connection/types/src/version.rs b/ibc-core/ics03-connection/types/src/version.rs index aa6f5316a..ac8f9d975 100644 --- a/ibc-core/ics03-connection/types/src/version.rs +++ b/ibc-core/ics03-connection/types/src/version.rs @@ -2,6 +2,7 @@ use core::fmt::Display; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_primitives::utils::PrettySlice; use ibc_proto::ibc::core::connection::v1::Version as RawVersion; @@ -72,9 +73,12 @@ impl Protobuf for Version {} impl TryFrom for Version { type Error = ConnectionError; + fn try_from(value: RawVersion) -> Result { if value.identifier.trim().is_empty() { - return Err(ConnectionError::EmptyVersions); + return Err(DecodingError::MissingRawData { + description: "version is empty".to_string(), + })?; } for feature in value.features.iter() { if feature.trim().is_empty() { From 231b3cd3b47f7fb051960fbc3c7052651ebd943b Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 5 Sep 2024 10:19:53 -0500 Subject: [PATCH 050/107] Revert some CommitmentError variants --- ibc-core/ics23-commitment/types/src/error.rs | 4 ++++ ibc-core/ics23-commitment/types/src/specs.rs | 23 ++++++++------------ 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/ibc-core/ics23-commitment/types/src/error.rs b/ibc-core/ics23-commitment/types/src/error.rs index 3b6d09927..c367a0817 100644 --- a/ibc-core/ics23-commitment/types/src/error.rs +++ b/ibc-core/ics23-commitment/types/src/error.rs @@ -28,6 +28,10 @@ pub enum CommitmentError { InvalidMerkleProof, /// invalid child size: `{0}` InvalidChildSize(i32), + /// invalid hash operation: `{0}` + InvalidHashOp(i32), + /// invalid length operation: `{0}` + InvalidLengthOp(i32), /// failed to verify membership FailedToVerifyMembership, } diff --git a/ibc-core/ics23-commitment/types/src/specs.rs b/ibc-core/ics23-commitment/types/src/specs.rs index 8b4f934a9..d163c6bf8 100644 --- a/ibc-core/ics23-commitment/types/src/specs.rs +++ b/ibc-core/ics23-commitment/types/src/specs.rs @@ -1,6 +1,5 @@ //! Defines proof specs, which encode the structure of proofs -use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_proto::ics23::{InnerSpec as RawInnerSpec, LeafOp as RawLeafOp, ProofSpec as RawProofSpec}; use ics23::{HashOp, LengthOp}; @@ -132,19 +131,15 @@ impl TryFrom for LeafOp { type Error = CommitmentError; fn try_from(leaf_op: RawLeafOp) -> Result { - let _ = HashOp::try_from(leaf_op.hash).map_err(|e| DecodingError::InvalidHash { - description: format!("hash op {0} is invalid: {e}", leaf_op.hash), - })?; - let _ = HashOp::try_from(leaf_op.prehash_key).map_err(|e| DecodingError::InvalidHash { - description: format!("hash op {0} is invalid: {e}", leaf_op.prehash_key), - })?; - let _ = - HashOp::try_from(leaf_op.prehash_value).map_err(|e| DecodingError::InvalidHash { - description: format!("hash op {0} is invalid: {e}", leaf_op.prehash_value), - })?; - let _ = LengthOp::try_from(leaf_op.length).map_err(|e| DecodingError::InvalidHash { - description: format!("length op {0} is invalid: {e}", leaf_op.length), - })?; + let _ = HashOp::try_from(leaf_op.hash) + .map_err(|_| CommitmentError::InvalidHashOp(leaf_op.hash))?; + let _ = HashOp::try_from(leaf_op.prehash_key) + .map_err(|_| CommitmentError::InvalidHashOp(leaf_op.prehash_key))?; + let _ = HashOp::try_from(leaf_op.prehash_value) + .map_err(|_| CommitmentError::InvalidHashOp(leaf_op.prehash_value))?; + let _ = LengthOp::try_from(leaf_op.length) + .map_err(|_| CommitmentError::InvalidLengthOp(leaf_op.length))?; + Ok(Self(leaf_op)) } } From dd49a78840786343e4077688dad806ff19552a19 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 5 Sep 2024 13:28:09 -0500 Subject: [PATCH 051/107] Change TryFrom for MsgEnvelope Error type to DecodingError --- ibc-core/ics25-handler/types/src/msgs.rs | 57 ++++++++---------------- 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/ibc-core/ics25-handler/types/src/msgs.rs b/ibc-core/ics25-handler/types/src/msgs.rs index b2a34c773..a47a9b702 100644 --- a/ibc-core/ics25-handler/types/src/msgs.rs +++ b/ibc-core/ics25-handler/types/src/msgs.rs @@ -18,7 +18,6 @@ use ibc_core_connection_types::msgs::{ CONN_OPEN_INIT_TYPE_URL, CONN_OPEN_TRY_TYPE_URL, }; use ibc_core_host_types::error::DecodingError; -use ibc_core_router_types::error::RouterError; use ibc_primitives::prelude::*; use ibc_proto::google::protobuf::Any; use ibc_proto::Protobuf; @@ -39,52 +38,44 @@ pub enum MsgEnvelope { #[allow(deprecated)] impl TryFrom for MsgEnvelope { - type Error = RouterError; + type Error = DecodingError; fn try_from(any_msg: Any) -> Result { match any_msg.type_url.as_str() { // ICS2 messages CREATE_CLIENT_TYPE_URL => { // Pop out the message and then wrap it in the corresponding type. - let domain_msg = - MsgCreateClient::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; + let domain_msg = MsgCreateClient::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Client(ClientMsg::CreateClient(domain_msg))) } UPDATE_CLIENT_TYPE_URL => { - let domain_msg = - MsgUpdateClient::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; + let domain_msg = MsgUpdateClient::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Client(ClientMsg::UpdateClient(domain_msg))) } UPGRADE_CLIENT_TYPE_URL => { - let domain_msg = MsgUpgradeClient::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgUpgradeClient::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Client(ClientMsg::UpgradeClient(domain_msg))) } SUBMIT_MISBEHAVIOUR_TYPE_URL => { - let domain_msg = MsgSubmitMisbehaviour::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgSubmitMisbehaviour::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Client(ClientMsg::Misbehaviour(domain_msg))) } // ICS03 CONN_OPEN_INIT_TYPE_URL => { - let domain_msg = MsgConnectionOpenInit::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgConnectionOpenInit::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenInit(domain_msg))) } CONN_OPEN_TRY_TYPE_URL => { - let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenTry(domain_msg))) } CONN_OPEN_ACK_TYPE_URL => { - let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenAck(domain_msg))) } CONN_OPEN_CONFIRM_TYPE_URL => { - let domain_msg = MsgConnectionOpenConfirm::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgConnectionOpenConfirm::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Connection(ConnectionMsg::OpenConfirm( domain_msg, ))) @@ -92,54 +83,44 @@ impl TryFrom for MsgEnvelope { // ICS04 channel messages CHAN_OPEN_INIT_TYPE_URL => { - let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenInit(domain_msg))) } CHAN_OPEN_TRY_TYPE_URL => { - let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenTry(domain_msg))) } CHAN_OPEN_ACK_TYPE_URL => { - let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenAck(domain_msg))) } CHAN_OPEN_CONFIRM_TYPE_URL => { - let domain_msg = MsgChannelOpenConfirm::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgChannelOpenConfirm::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Channel(ChannelMsg::OpenConfirm(domain_msg))) } CHAN_CLOSE_INIT_TYPE_URL => { - let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseInit(domain_msg))) } CHAN_CLOSE_CONFIRM_TYPE_URL => { - let domain_msg = MsgChannelCloseConfirm::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgChannelCloseConfirm::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Channel(ChannelMsg::CloseConfirm(domain_msg))) } // ICS04 packet messages RECV_PACKET_TYPE_URL => { - let domain_msg = - MsgRecvPacket::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; + let domain_msg = MsgRecvPacket::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Packet(PacketMsg::Recv(domain_msg))) } ACKNOWLEDGEMENT_TYPE_URL => { - let domain_msg = MsgAcknowledgement::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgAcknowledgement::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Packet(PacketMsg::Ack(domain_msg))) } TIMEOUT_TYPE_URL => { - let domain_msg = - MsgTimeout::decode_vec(&any_msg.value).map_err(DecodingError::Protobuf)?; + let domain_msg = MsgTimeout::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Packet(PacketMsg::Timeout(domain_msg))) } TIMEOUT_ON_CLOSE_TYPE_URL => { - let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value) - .map_err(DecodingError::Protobuf)?; + let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Packet(PacketMsg::TimeoutOnClose(domain_msg))) } From 4ee95158b8d5ba64c0d57c3ebf52f891ea19d14b Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 5 Sep 2024 14:45:33 -0500 Subject: [PATCH 052/107] Define HostError type --- ibc-core/ics24-host/types/src/error.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index fefc02871..220fb1353 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -9,6 +9,25 @@ use ibc_primitives::prelude::*; use ibc_primitives::proto::Error as ProtoError; use prost::DecodeError as ProstError; +/// Errors that originate from host implementations. +#[derive(Debug, Display)] +pub enum HostError { + /// invalid data: `{description}` + InvalidData { description: String }, + /// missing data: `{description}` + MissingData { description: String }, + /// failed to update state: `{description}` + FailedToUpdateState { description: String }, + /// failed to store data: `{description}` + FailedToStoreData { description: String }, + /// failed to parse data: `{description}` + FailedToParseData { description: String }, + /// non-existent type: `{description}` + NonexistentType { description: String }, + /// other error: `{description}` + Other { description: String }, +} + /// Errors that arise when parsing identifiers. #[cfg_attr(feature = "serde", derive(serde::Serialize))] #[derive(Debug, Display)] @@ -25,7 +44,8 @@ pub enum IdentifierError { OverflowedRevisionNumber, } -/// Errors that result in decoding failures +/// Errors that occur during the process of decoding, deserializing, +/// and/or converting raw types into domain types. #[derive(Debug, Display)] pub enum DecodingError { /// identifier error: `{0}` From ca664adcfeb85906924dc456e8267a7a7cb70941 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 5 Sep 2024 15:10:24 -0500 Subject: [PATCH 053/107] Rename ContextError to HandlerError --- ...482-fix-validate-self-client-error-type.md | 6 +- .../v0.33.0/improvement/547-error-strings.md | 2 +- ...-use-result-for-safe-counters-increment.md | 2 +- ...-result-in-logger-event-emitter-methods.md | 2 +- CHANGELOG.md | 8 +- .../adr-006-upgrade-client-implementation.md | 4 +- .../adr-007-light-client-contexts.md | 6 +- ...010-enable-standalone-ics02-integration.md | 42 ++++----- ibc-apps/ics20-transfer/src/module.rs | 8 +- ibc-apps/ics20-transfer/types/src/error.rs | 12 +-- .../ics20-transfer/types/src/msgs/transfer.rs | 6 +- ibc-apps/ics721-nft-transfer/src/module.rs | 8 +- .../ics721-nft-transfer/types/src/error.rs | 6 +- .../types/src/msgs/transfer.rs | 6 +- ibc-core/ics02-client/context/src/context.rs | 30 +++---- .../ics02-client/src/handler/create_client.rs | 6 +- .../src/handler/recover_client.rs | 6 +- .../ics02-client/src/handler/update_client.rs | 6 +- .../src/handler/upgrade_client.rs | 6 +- ibc-core/ics03-connection/src/delay.rs | 8 +- .../src/handler/conn_open_ack.rs | 12 +-- .../src/handler/conn_open_confirm.rs | 12 +-- .../src/handler/conn_open_init.rs | 6 +- .../src/handler/conn_open_try.rs | 12 +-- ibc-core/ics03-connection/src/handler/mod.rs | 6 +- ibc-core/ics04-channel/src/context.rs | 30 +++---- .../src/handler/acknowledgement.rs | 10 +-- .../src/handler/chan_close_confirm.rs | 10 +-- .../src/handler/chan_close_init.rs | 10 +-- .../src/handler/chan_open_ack.rs | 8 +- .../src/handler/chan_open_confirm.rs | 10 +-- .../src/handler/chan_open_init.rs | 8 +- .../src/handler/chan_open_try.rs | 8 +- .../ics04-channel/src/handler/recv_packet.rs | 14 +-- .../ics04-channel/src/handler/send_packet.rs | 10 +-- ibc-core/ics04-channel/src/handler/timeout.rs | 12 +-- .../src/handler/timeout_on_close.rs | 6 +- .../cosmos/src/validate_self_client.rs | 18 ++-- ibc-core/ics24-host/src/context.rs | 68 +++++++------- ibc-core/ics24-host/types/src/error.rs | 3 + ibc-core/ics25-handler/src/entrypoint.rs | 8 +- ibc-core/ics25-handler/types/src/error.rs | 40 +++++---- ibc-query/src/core/context.rs | 22 ++--- ibc-query/src/error.rs | 20 ++--- ibc-testkit/src/context.rs | 10 +-- ibc-testkit/src/fixtures/mod.rs | 6 +- .../testapp/ibc/clients/mock/client_state.rs | 6 +- .../src/testapp/ibc/core/client_ctx.rs | 32 +++---- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 90 +++++++++---------- .../tests/core/ics02_client/create_client.rs | 8 +- .../tests/core/ics02_client/upgrade_client.rs | 8 +- .../core/ics03_connection/conn_open_ack.rs | 14 +-- tests-integration/tests/core/router.rs | 4 +- 53 files changed, 364 insertions(+), 357 deletions(-) diff --git a/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md b/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md index b68e2b01c..1e0889aa9 100644 --- a/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md +++ b/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md @@ -1,3 +1,3 @@ -- Modify `validate_self_client` error type to return `ContextError` instead of - `ConnectionError` - ([#482](https://github.com/cosmos/ibc-rs/issues/482)) \ No newline at end of file +- Modify `validate_self_client` error type to return `HandlerError` instead of + `ConnectionError` + ([#482](https://github.com/cosmos/ibc-rs/issues/482)) diff --git a/.changelog/v0.33.0/improvement/547-error-strings.md b/.changelog/v0.33.0/improvement/547-error-strings.md index 661201f75..064388cf1 100644 --- a/.changelog/v0.33.0/improvement/547-error-strings.md +++ b/.changelog/v0.33.0/improvement/547-error-strings.md @@ -1,2 +1,2 @@ -- Fix ContextError Display output +- Fix HandlerError Display output ([#547](https://github.com/cosmos/ibc-rs/issues/547)) diff --git a/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md b/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md index f0f87285e..23b9d0ed1 100644 --- a/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md +++ b/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md @@ -1,3 +1,3 @@ - Allow hosts to handle overflow cases in `increase_*_counter` methods by - returning `Result<(),ContextError>` type. + returning `Result<(),HandlerError>` type. ([#857](https://github.com/cosmos/ibc-rs/issues/857)) diff --git a/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md b/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md index 9c25b1ba3..901281fc9 100644 --- a/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md +++ b/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md @@ -1,2 +1,2 @@ -- logger and event emitter methods return `Result<(), ContextError>` type. +- logger and event emitter methods return `Result<(), HandlerError>` type. ([#859](https://github.com/cosmos/ibc-rs/issues/859)) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56e149579..2d4949e2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -641,9 +641,9 @@ There are no consensus-breaking changes. - Bump ibc-proto-rs to v0.34.0 ([#790](https://github.com/cosmos/ibc-rs/issues/790)) - Allow hosts to handle overflow cases in `increase_*_counter` methods by - returning `Result<(),ContextError>` type. + returning `Result<(),HandlerError>` type. ([#857](https://github.com/cosmos/ibc-rs/issues/857)) -- logger and event emitter methods return `Result<(), ContextError>` type. +- logger and event emitter methods return `Result<(), HandlerError>` type. ([#859](https://github.com/cosmos/ibc-rs/issues/859)) - Bump `ibc-proto-rs` to v0.35.0 along with some other minor dependency updates ([#873](https://github.com/cosmos/ibc-rs/issues/873)) @@ -1042,7 +1042,7 @@ There are no consensus-breaking changes. ### IMPROVEMENT -- Fix `ContextError` Display output +- Fix `HandlerError` Display output ([#547](https://github.com/cosmos/ibc-rs/issues/547)) ## v0.32.0 @@ -1099,7 +1099,7 @@ There are no consensus-breaking changes. ([#479](https://github.com/cosmos/ibc-rs/issues/479)) - Remove Send + Sync supertraits on the Module trait ([#480](https://github.com/cosmos/ibc-rs/issues/480)) -- Modify `validate_self_client` error type to return `ContextError` instead of +- Modify `validate_self_client` error type to return `HandlerError` instead of `ConnectionError` ([#482](https://github.com/cosmos/ibc-rs/issues/482)) diff --git a/docs/architecture/adr-006-upgrade-client-implementation.md b/docs/architecture/adr-006-upgrade-client-implementation.md index d1aa8fc86..90e2d8828 100644 --- a/docs/architecture/adr-006-upgrade-client-implementation.md +++ b/docs/architecture/adr-006-upgrade-client-implementation.md @@ -119,7 +119,7 @@ supported by `IBC-rs`: negotiated on connection handshake. 10. (U) Changing parameters that are customizable by relayers like `TrustLevel` and `TrustingPeriod`, `max_clock_drift` - + #### Upgrade Process Step-by-step An IBC-connected Tendermint chain will take the following steps to completely @@ -250,7 +250,7 @@ previous section as mentioned: 1. ```rust if old_client_state.is_frozen() { - return Err(ContextError::ClientError(ClientError::ClientFrozen { + return Err(HandlerError::ClientError(ClientError::ClientFrozen { client_id, })); } diff --git a/docs/architecture/adr-007-light-client-contexts.md b/docs/architecture/adr-007-light-client-contexts.md index b0caabdd5..973626b25 100644 --- a/docs/architecture/adr-007-light-client-contexts.md +++ b/docs/architecture/adr-007-light-client-contexts.md @@ -98,12 +98,12 @@ pub trait ClientExecutionContext: Sized { /// Called upon successful client creation and update fn store_client_state( ... - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Called upon successful client creation and update fn store_consensus_state( ... - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; } ``` @@ -120,7 +120,7 @@ pub trait ValidationContext: Router { type ClientValidationContext; type ClientExecutionContext; /// Enum that can contain a `ConsensusState` object of any supported light client - type AnyConsensusState: ConsensusState; + type AnyConsensusState: ConsensusState; /// Enum that can contain a `ClientState` object of any supported light client type AnyClientState: ClientState< Self::AnyConsensusState, diff --git a/docs/architecture/adr-010-enable-standalone-ics02-integration.md b/docs/architecture/adr-010-enable-standalone-ics02-integration.md index 24dbe1149..7cb9782a0 100644 --- a/docs/architecture/adr-010-enable-standalone-ics02-integration.md +++ b/docs/architecture/adr-010-enable-standalone-ics02-integration.md @@ -129,26 +129,26 @@ pub trait ValidationContext { fn get_client_validation_context(&self) -> &Self::V; // This method will be removed and replaced by a `ClientStateDecoder` trait that will encapsulate the ability to decode a client state from an `Any` -- fn decode_client_state(&self, client_state: Any) -> Result; +- fn decode_client_state(&self, client_state: Any) -> Result; -- fn client_state(&self, client_id: &ClientId) -> Result; +- fn client_state(&self, client_id: &ClientId) -> Result; - fn consensus_state( - &self, - client_cons_state_path: &ClientConsensusStatePath, -- ) -> Result; +- ) -> Result; fn host_consensus_state( &self, height: &Height, -- ) -> Result; -+ ) -> Result; +- ) -> Result; ++ ) -> Result; fn validate_self_client( &self, - client_state_of_host_on_counterparty: Any, + client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; ... // other methods } @@ -200,18 +200,18 @@ pub trait ClientValidationContext: Sized { + type ClientStateRef: ClientStateValidation; + type ConsensusStateRef: ConsensusState; -+ fn client_state(&self, client_id: &ClientId) -> Result; ++ fn client_state(&self, client_id: &ClientId) -> Result; + fn consensus_state( + &self, + client_cons_state_path: &ClientConsensusStatePath, -+ ) -> Result; ++ ) -> Result; fn client_update_meta( &self, client_id: &ClientId, height: &Height, - ) -> Result<(Timestamp, Height), ContextError>; + ) -> Result<(Timestamp, Height), HandlerError>; } pub trait ClientExecutionContext: @@ -222,7 +222,7 @@ pub trait ClientExecutionContext: - type AnyConsensusState: ConsensusState; + type ClientStateMut: ClientStateExecution; -+ fn client_state_mut(&self, client_id: &ClientId) -> Result { ++ fn client_state_mut(&self, client_id: &ClientId) -> Result { + self.client_state(client_id) + } @@ -230,18 +230,18 @@ pub trait ClientExecutionContext: &mut self, client_state_path: ClientStatePath, client_state: Self::ClientStateMut, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; fn store_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Self::ConsensusStateRef, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; fn delete_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; fn store_update_meta( &mut self, @@ -249,13 +249,13 @@ pub trait ClientExecutionContext: height: Height, host_timestamp: Timestamp, host_height: Height, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; fn delete_update_meta( &mut self, client_id: ClientId, height: Height, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; } ``` @@ -306,28 +306,28 @@ pub trait ExtClientValidationContext: + type ConversionError: ToString; + type AnyConsensusState: TryInto; -+ fn host_timestamp(&self) -> Result; ++ fn host_timestamp(&self) -> Result; -+ fn host_height(&self) -> Result; ++ fn host_height(&self) -> Result; - fn consensus_state( - &self, - client_cons_state_path: &ClientConsensusStatePath, -- ) -> Result; +- ) -> Result; -+ fn consensus_state_heights(&self, client_id: &ClientId) -> Result, ContextError>; ++ fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError>; fn next_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; fn prev_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; } -impl ExecutionContext for T where T: CommonContext + ClientExecutionContext {} diff --git a/ibc-apps/ics20-transfer/src/module.rs b/ibc-apps/ics20-transfer/src/module.rs index e493760e6..e6c124351 100644 --- a/ibc-apps/ics20-transfer/src/module.rs +++ b/ibc-apps/ics20-transfer/src/module.rs @@ -6,7 +6,7 @@ use ibc_core::channel::types::acknowledgement::{Acknowledgement, Acknowledgement use ibc_core::channel::types::channel::{Counterparty, Order}; use ibc_core::channel::types::packet::Packet; use ibc_core::channel::types::Version; -use ibc_core::handler::types::error::ContextError; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, ConnectionId, PortId}; use ibc_core::primitives::prelude::*; @@ -44,7 +44,7 @@ pub fn on_chan_open_init_validate( if !version.is_empty() { version .verify_is_expected(Version::new(VERSION.to_string())) - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; } Ok(()) @@ -80,7 +80,7 @@ pub fn on_chan_open_try_validate( counterparty_version .verify_is_expected(Version::new(VERSION.to_string())) - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; Ok(()) } @@ -105,7 +105,7 @@ pub fn on_chan_open_ack_validate( ) -> Result<(), TokenTransferError> { counterparty_version .verify_is_expected(Version::new(VERSION.to_string())) - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; Ok(()) } diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 43150c0cb..3ffad202a 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -4,7 +4,7 @@ use core::convert::Infallible; use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; -use ibc_core::handler::types::error::ContextError; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -13,7 +13,7 @@ use uint::FromDecStrErr; #[derive(Display, Debug)] pub enum TokenTransferError { /// context error: `{0}` - ContextError(ContextError), + HandlerError(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), /// identifier error: `{0}` @@ -50,7 +50,7 @@ pub enum TokenTransferError { impl std::error::Error for TokenTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::ContextError(e) => Some(e), + Self::HandlerError(e) => Some(e), Self::Identifier(e) => Some(e), Self::InvalidAmount(e) => Some(e), Self::Decoding(e) => Some(e), @@ -65,9 +65,9 @@ impl From for TokenTransferError { } } -impl From for TokenTransferError { - fn from(e: ContextError) -> Self { - Self::ContextError(e) +impl From for TokenTransferError { + fn from(e: HandlerError) -> Self { + Self::HandlerError(e) } } diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index fcc23863b..f5459097a 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -2,7 +2,7 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; -use ibc_core::handler::types::error::ContextError; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -55,13 +55,13 @@ impl TryFrom for MsgTransfer { let timeout_height_on_b: TimeoutHeight = raw_msg .timeout_height .try_into() - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; let timeout_timestamp_on_b: TimeoutTimestamp = raw_msg.timeout_timestamp.into(); // Packet timeout height and packet timeout timestamp cannot both be unset. if !timeout_height_on_b.is_set() && !timeout_timestamp_on_b.is_set() { - return Err(ContextError::from(PacketError::MissingTimeout))?; + return Err(HandlerError::from(PacketError::MissingTimeout))?; } Ok(MsgTransfer { diff --git a/ibc-apps/ics721-nft-transfer/src/module.rs b/ibc-apps/ics721-nft-transfer/src/module.rs index 8b1ffef0f..ee13595f7 100644 --- a/ibc-apps/ics721-nft-transfer/src/module.rs +++ b/ibc-apps/ics721-nft-transfer/src/module.rs @@ -3,7 +3,7 @@ use ibc_core::channel::types::acknowledgement::{Acknowledgement, Acknowledgement use ibc_core::channel::types::channel::{Counterparty, Order}; use ibc_core::channel::types::packet::Packet; use ibc_core::channel::types::Version; -use ibc_core::handler::types::error::ContextError; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, ConnectionId, PortId}; use ibc_core::primitives::prelude::*; @@ -45,7 +45,7 @@ pub fn on_chan_open_init_validate( if !version.is_empty() { version .verify_is_expected(Version::new(VERSION.to_string())) - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; } Ok(()) @@ -81,7 +81,7 @@ pub fn on_chan_open_try_validate( counterparty_version .verify_is_expected(Version::new(VERSION.to_string())) - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; Ok(()) } @@ -106,7 +106,7 @@ pub fn on_chan_open_ack_validate( ) -> Result<(), NftTransferError> { counterparty_version .verify_is_expected(Version::new(VERSION.to_string())) - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; Ok(()) } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 2e7456b5b..56c3f0981 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -5,7 +5,7 @@ use displaydoc::Display; use http::uri::InvalidUri; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; -use ibc_core::handler::types::error::ContextError; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::{DecodingError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -13,7 +13,7 @@ use ibc_core::primitives::prelude::*; #[derive(Display, Debug, derive_more::From)] pub enum NftTransferError { /// context error: `{0}` - ContextError(ContextError), + HandlerError(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), /// identifier error: `{0}` @@ -47,7 +47,7 @@ pub enum NftTransferError { impl std::error::Error for NftTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::ContextError(e) => Some(e), + Self::HandlerError(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index 5b2bfb077..d7b8bfe59 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -2,7 +2,7 @@ use ibc_core::channel::types::error::PacketError; use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; -use ibc_core::handler::types::error::ContextError; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -55,13 +55,13 @@ impl TryFrom for MsgTransfer { let timeout_height_on_b: TimeoutHeight = raw_msg .timeout_height .try_into() - .map_err(ContextError::from)?; + .map_err(HandlerError::from)?; let timeout_timestamp_on_b: TimeoutTimestamp = raw_msg.timeout_timestamp.into(); // Packet timeout height and packet timeout timestamp cannot both be unset. if !timeout_height_on_b.is_set() && !timeout_timestamp_on_b.is_set() { - return Err(ContextError::from(PacketError::MissingTimeout))?; + return Err(HandlerError::from(PacketError::MissingTimeout))?; } let memo = if raw_msg.memo.is_empty() { diff --git a/ibc-core/ics02-client/context/src/context.rs b/ibc-core/ics02-client/context/src/context.rs index 972ec547e..a13e9a4b7 100644 --- a/ibc-core/ics02-client/context/src/context.rs +++ b/ibc-core/ics02-client/context/src/context.rs @@ -1,5 +1,5 @@ use ibc_core_client_types::Height; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_host_types::identifiers::ClientId; use ibc_core_host_types::path::{ClientConsensusStatePath, ClientStatePath}; use ibc_primitives::prelude::*; @@ -19,7 +19,7 @@ pub trait ClientValidationContext: Sized { /// Returns the ClientState for the given identifier `client_id`. /// /// Note: Clients have the responsibility to store client states on client creation and update. - fn client_state(&self, client_id: &ClientId) -> Result; + fn client_state(&self, client_id: &ClientId) -> Result; /// Retrieve the consensus state for the given client ID at the specified /// height. @@ -30,7 +30,7 @@ pub trait ClientValidationContext: Sized { fn consensus_state( &self, client_cons_state_path: &ClientConsensusStatePath, - ) -> Result; + ) -> Result; /// Returns the timestamp and height of the host when it processed a client /// update request at the specified height. @@ -38,7 +38,7 @@ pub trait ClientValidationContext: Sized { &self, client_id: &ClientId, height: &Height, - ) -> Result<(Timestamp, Height), ContextError>; + ) -> Result<(Timestamp, Height), HandlerError>; } /// Defines the methods that all client `ExecutionContext`s (precisely the @@ -54,7 +54,7 @@ pub trait ClientExecutionContext: { type ClientStateMut: ClientStateExecution; - fn client_state_mut(&self, client_id: &ClientId) -> Result { + fn client_state_mut(&self, client_id: &ClientId) -> Result { self.client_state(client_id) } @@ -63,20 +63,20 @@ pub trait ClientExecutionContext: &mut self, client_state_path: ClientStatePath, client_state: Self::ClientStateRef, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Called upon successful client creation and update fn store_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Self::ConsensusStateRef, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Delete the consensus state from the store located at the given `ClientConsensusStatePath` fn delete_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Called upon successful client update. /// @@ -88,7 +88,7 @@ pub trait ClientExecutionContext: height: Height, host_timestamp: Timestamp, host_height: Height, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Delete the update time and height associated with the client at the /// specified height. @@ -101,7 +101,7 @@ pub trait ClientExecutionContext: &mut self, client_id: ClientId, height: Height, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; } /// An optional trait that extends the client validation context capabilities by @@ -115,27 +115,27 @@ pub trait ClientExecutionContext: /// specific light client requirements. pub trait ExtClientValidationContext: ClientValidationContext { /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; /// Returns all the heights at which a consensus state is stored. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, ContextError>; + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError>; /// Search for the lowest consensus state higher than `height`. fn next_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; /// Search for the highest consensus state lower than `height`. fn prev_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; } /// An optional trait that extends the client context required during execution. diff --git a/ibc-core/ics02-client/src/handler/create_client.rs b/ibc-core/ics02-client/src/handler/create_client.rs index 47f5bab4a..8ea87b2f1 100644 --- a/ibc-core/ics02-client/src/handler/create_client.rs +++ b/ibc-core/ics02-client/src/handler/create_client.rs @@ -5,13 +5,13 @@ use ibc_core_client_types::error::ClientError; use ibc_core_client_types::events::CreateClient; use ibc_core_client_types::msgs::MsgCreateClient; use ibc_core_client_types::Status; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::{ClientStateMut, ClientStateRef, ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; use ibc_primitives::proto::Any; -pub fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), ContextError> +pub fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), HandlerError> where Ctx: ValidationContext, as TryFrom>::Error: Into, @@ -50,7 +50,7 @@ where Ok(()) } -pub fn execute(ctx: &mut Ctx, msg: MsgCreateClient) -> Result<(), ContextError> +pub fn execute(ctx: &mut Ctx, msg: MsgCreateClient) -> Result<(), HandlerError> where Ctx: ExecutionContext, as TryFrom>::Error: Into, diff --git a/ibc-core/ics02-client/src/handler/recover_client.rs b/ibc-core/ics02-client/src/handler/recover_client.rs index 7994edab3..c3e2826b2 100644 --- a/ibc-core/ics02-client/src/handler/recover_client.rs +++ b/ibc-core/ics02-client/src/handler/recover_client.rs @@ -3,7 +3,7 @@ use ibc_core_client_context::prelude::*; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::msgs::MsgRecoverClient; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_host::types::path::ClientConsensusStatePath; use ibc_core_host::{ExecutionContext, ValidationContext}; @@ -11,7 +11,7 @@ use ibc_core_host::{ExecutionContext, ValidationContext}; /// includes validating that the parameters of the subject and substitute clients match, /// as well as validating that the substitute client *is* active and that the subject /// client is *not* active. -pub fn validate(ctx: &Ctx, msg: MsgRecoverClient) -> Result<(), ContextError> +pub fn validate(ctx: &Ctx, msg: MsgRecoverClient) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -62,7 +62,7 @@ where /// - copying the substitute client's consensus state as the subject's consensus state /// - setting the subject client's processed height and processed time values to match the substitute client's /// - setting the subject client's latest height, trusting period, and chain ID values to match the substitute client's -pub fn execute(ctx: &mut Ctx, msg: MsgRecoverClient) -> Result<(), ContextError> +pub fn execute(ctx: &mut Ctx, msg: MsgRecoverClient) -> Result<(), HandlerError> where Ctx: ExecutionContext, { diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index 66ce95ce1..8f16bbcaf 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -5,13 +5,13 @@ use ibc_core_client_types::error::ClientError; use ibc_core_client_types::events::{ClientMisbehaviour, UpdateClient}; use ibc_core_client_types::msgs::MsgUpdateOrMisbehaviour; use ibc_core_client_types::UpdateKind; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; use ibc_primitives::ToVec; -pub fn validate(ctx: &Ctx, msg: MsgUpdateOrMisbehaviour) -> Result<(), ContextError> +pub fn validate(ctx: &Ctx, msg: MsgUpdateOrMisbehaviour) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -35,7 +35,7 @@ where Ok(()) } -pub fn execute(ctx: &mut Ctx, msg: MsgUpdateOrMisbehaviour) -> Result<(), ContextError> +pub fn execute(ctx: &mut Ctx, msg: MsgUpdateOrMisbehaviour) -> Result<(), HandlerError> where Ctx: ExecutionContext, { diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index 7dce4cdaa..4ddcdc734 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -4,13 +4,13 @@ use ibc_core_client_context::prelude::*; use ibc_core_client_types::error::ClientError; use ibc_core_client_types::events::UpgradeClient; use ibc_core_client_types::msgs::MsgUpgradeClient; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::ClientConsensusStatePath; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; -pub fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), ContextError> +pub fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -55,7 +55,7 @@ where Ok(()) } -pub fn execute(ctx: &mut Ctx, msg: MsgUpgradeClient) -> Result<(), ContextError> +pub fn execute(ctx: &mut Ctx, msg: MsgUpgradeClient) -> Result<(), HandlerError> where Ctx: ExecutionContext, { diff --git a/ibc-core/ics03-connection/src/delay.rs b/ibc-core/ics03-connection/src/delay.rs index 82c162e4f..aed025930 100644 --- a/ibc-core/ics03-connection/src/delay.rs +++ b/ibc-core/ics03-connection/src/delay.rs @@ -2,14 +2,14 @@ use ibc_core_client::context::ClientValidationContext; use ibc_core_client::types::Height; use ibc_core_connection_types::error::ConnectionError; use ibc_core_connection_types::ConnectionEnd; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_host::ValidationContext; pub fn verify_conn_delay_passed( ctx: &Ctx, packet_proof_height: Height, connection_end: &ConnectionEnd, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -31,7 +31,7 @@ where let earliest_valid_time = (last_client_update.0 + conn_delay_time_period) .map_err(ConnectionError::OverflowedTimestamp)?; if current_host_time < earliest_valid_time { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InsufficientTimeElapsed { current_host_time, earliest_valid_time, @@ -42,7 +42,7 @@ where // Verify that the current host chain height is later than the last client update height let earliest_valid_height = last_client_update.1.add(conn_delay_height_period); if current_host_height < earliest_valid_height { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InsufficientBlocksElapsed { current_host_height, earliest_valid_height, diff --git a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs index 91027ff43..470100833 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_ack.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_ack.rs @@ -6,7 +6,7 @@ use ibc_core_connection_types::error::ConnectionError; use ibc_core_connection_types::events::OpenAck; use ibc_core_connection_types::msgs::MsgConnectionOpenAck; use ibc_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::ClientId; use ibc_core_host::types::path::{ClientConsensusStatePath, ClientStatePath, ConnectionPath, Path}; @@ -17,7 +17,7 @@ use ibc_primitives::ToVec; use crate::handler::{pack_host_consensus_state, unpack_host_client_state}; -pub fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenAck) -> Result<(), ContextError> +pub fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenAck) -> Result<(), HandlerError> where Ctx: ValidationContext, >::Error: Into, @@ -30,7 +30,7 @@ fn validate_impl( ctx_a: &Ctx, msg: &MsgConnectionOpenAck, vars: &LocalVars, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ValidationContext, >::Error: Into, @@ -143,7 +143,7 @@ where Ok(()) } -pub fn execute(ctx_a: &mut Ctx, msg: MsgConnectionOpenAck) -> Result<(), ContextError> +pub fn execute(ctx_a: &mut Ctx, msg: MsgConnectionOpenAck) -> Result<(), HandlerError> where Ctx: ExecutionContext, { @@ -155,7 +155,7 @@ fn execute_impl( ctx_a: &mut Ctx, msg: MsgConnectionOpenAck, vars: LocalVars, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ExecutionContext, { @@ -193,7 +193,7 @@ struct LocalVars { } impl LocalVars { - fn new(ctx_a: &Ctx, msg: &MsgConnectionOpenAck) -> Result + fn new(ctx_a: &Ctx, msg: &MsgConnectionOpenAck) -> Result where Ctx: ValidationContext, { diff --git a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs index 1987c047f..414b01006 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_confirm.rs @@ -5,7 +5,7 @@ use ibc_core_connection_types::error::ConnectionError; use ibc_core_connection_types::events::OpenConfirm; use ibc_core_connection_types::msgs::MsgConnectionOpenConfirm; use ibc_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::{ClientId, ConnectionId}; use ibc_core_host::types::path::{ClientConsensusStatePath, ConnectionPath, Path}; @@ -13,7 +13,7 @@ use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; use ibc_primitives::proto::Protobuf; -pub fn validate(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), ContextError> +pub fn validate(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -25,7 +25,7 @@ fn validate_impl( ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm, vars: &LocalVars, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -88,7 +88,7 @@ where Ok(()) } -pub fn execute(ctx_b: &mut Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), ContextError> +pub fn execute(ctx_b: &mut Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), HandlerError> where Ctx: ExecutionContext, { @@ -100,7 +100,7 @@ fn execute_impl( ctx_b: &mut Ctx, msg: &MsgConnectionOpenConfirm, vars: LocalVars, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ExecutionContext, { @@ -137,7 +137,7 @@ struct LocalVars { } impl LocalVars { - fn new(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result + fn new(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result where Ctx: ValidationContext, { diff --git a/ibc-core/ics03-connection/src/handler/conn_open_init.rs b/ibc-core/ics03-connection/src/handler/conn_open_init.rs index 8d4286616..9a42ec556 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_init.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_init.rs @@ -3,14 +3,14 @@ use ibc_core_client::context::prelude::*; use ibc_core_connection_types::events::OpenInit; use ibc_core_connection_types::msgs::MsgConnectionOpenInit; use ibc_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::ConnectionId; use ibc_core_host::types::path::{ClientConnectionPath, ConnectionPath}; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; -pub fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenInit) -> Result<(), ContextError> +pub fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenInit) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -32,7 +32,7 @@ where Ok(()) } -pub fn execute(ctx_a: &mut Ctx, msg: MsgConnectionOpenInit) -> Result<(), ContextError> +pub fn execute(ctx_a: &mut Ctx, msg: MsgConnectionOpenInit) -> Result<(), HandlerError> where Ctx: ExecutionContext, { diff --git a/ibc-core/ics03-connection/src/handler/conn_open_try.rs b/ibc-core/ics03-connection/src/handler/conn_open_try.rs index fbb013824..93a963643 100644 --- a/ibc-core/ics03-connection/src/handler/conn_open_try.rs +++ b/ibc-core/ics03-connection/src/handler/conn_open_try.rs @@ -5,7 +5,7 @@ use ibc_core_connection_types::error::ConnectionError; use ibc_core_connection_types::events::OpenTry; use ibc_core_connection_types::msgs::MsgConnectionOpenTry; use ibc_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::{ClientId, ConnectionId}; use ibc_core_host::types::path::{ @@ -18,7 +18,7 @@ use ibc_primitives::ToVec; use crate::handler::{pack_host_consensus_state, unpack_host_client_state}; -pub fn validate(ctx_b: &Ctx, msg: MsgConnectionOpenTry) -> Result<(), ContextError> +pub fn validate(ctx_b: &Ctx, msg: MsgConnectionOpenTry) -> Result<(), HandlerError> where Ctx: ValidationContext, >::Error: Into, @@ -31,7 +31,7 @@ fn validate_impl( ctx_b: &Ctx, msg: &MsgConnectionOpenTry, vars: &LocalVars, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ValidationContext, >::Error: Into, @@ -139,7 +139,7 @@ where Ok(()) } -pub fn execute(ctx_b: &mut Ctx, msg: MsgConnectionOpenTry) -> Result<(), ContextError> +pub fn execute(ctx_b: &mut Ctx, msg: MsgConnectionOpenTry) -> Result<(), HandlerError> where Ctx: ExecutionContext, { @@ -151,7 +151,7 @@ fn execute_impl( ctx_b: &mut Ctx, msg: MsgConnectionOpenTry, vars: LocalVars, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ExecutionContext, { @@ -188,7 +188,7 @@ struct LocalVars { } impl LocalVars { - fn new(ctx_b: &Ctx, msg: &MsgConnectionOpenTry) -> Result + fn new(ctx_b: &Ctx, msg: &MsgConnectionOpenTry) -> Result where Ctx: ValidationContext, { diff --git a/ibc-core/ics03-connection/src/handler/mod.rs b/ibc-core/ics03-connection/src/handler/mod.rs index f780295e4..e023f9623 100644 --- a/ibc-core/ics03-connection/src/handler/mod.rs +++ b/ibc-core/ics03-connection/src/handler/mod.rs @@ -1,5 +1,5 @@ use ibc_core_client::types::error::ClientError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; #[cfg(feature = "wasm-client")] use ibc_core_host::types::error::DecodingError; use ibc_core_host::types::identifiers::ClientId; @@ -18,7 +18,7 @@ pub mod conn_open_try; pub(crate) fn unpack_host_client_state( value: Any, host_client_id_at_counterparty: &ClientId, -) -> Result +) -> Result where CS: TryFrom, >::Error: Into, @@ -31,7 +31,7 @@ where use prost::Message; let wasm_client_state = WasmClientState::try_from(value).map_err(|e| { - ContextError::ConnectionError(ConnectionError::InvalidClientState { + HandlerError::ConnectionError(ConnectionError::InvalidClientState { description: e.to_string(), }) })?; diff --git a/ibc-core/ics04-channel/src/context.rs b/ibc-core/ics04-channel/src/context.rs index 1fba1de8f..1b235db92 100644 --- a/ibc-core/ics04-channel/src/context.rs +++ b/ibc-core/ics04-channel/src/context.rs @@ -4,7 +4,7 @@ use ibc_core_channel_types::channel::ChannelEnd; use ibc_core_channel_types::commitment::PacketCommitment; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::ConnectionEnd; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::IbcEvent; use ibc_core_host::types::identifiers::{ConnectionId, Sequence}; use ibc_core_host::types::path::{ChannelEndPath, CommitmentPath, SeqSendPath}; @@ -19,13 +19,13 @@ pub trait SendPacketValidationContext { fn get_client_validation_context(&self) -> &Self::V; /// Returns the ChannelEnd for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; /// Returns the ConnectionState for the given identifier `connection_id`. - fn connection_end(&self, connection_id: &ConnectionId) -> Result; + fn connection_end(&self, connection_id: &ConnectionId) -> Result; fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) - -> Result; + -> Result; } impl SendPacketValidationContext for T @@ -38,18 +38,18 @@ where self.get_client_validation_context() } - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { self.channel_end(channel_end_path) } - fn connection_end(&self, connection_id: &ConnectionId) -> Result { + fn connection_end(&self, connection_id: &ConnectionId) -> Result { self.connection_end(connection_id) } fn get_next_sequence_send( &self, seq_send_path: &SeqSendPath, - ) -> Result { + ) -> Result { self.get_next_sequence_send(seq_send_path) } } @@ -60,19 +60,19 @@ pub trait SendPacketExecutionContext: SendPacketValidationContext { &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; fn store_packet_commitment( &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Ibc events - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), ContextError>; + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError>; /// Logging facility - fn log_message(&mut self, message: String) -> Result<(), ContextError>; + fn log_message(&mut self, message: String) -> Result<(), HandlerError>; } impl SendPacketExecutionContext for T @@ -83,7 +83,7 @@ where &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.store_next_sequence_send(seq_send_path, seq) } @@ -91,15 +91,15 @@ where &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.store_packet_commitment(commitment_path, commitment) } - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), ContextError> { + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError> { self.emit_ibc_event(event) } - fn log_message(&mut self, message: String) -> Result<(), ContextError> { + fn log_message(&mut self, message: String) -> Result<(), HandlerError> { self.log_message(message) } } diff --git a/ibc-core/ics04-channel/src/handler/acknowledgement.rs b/ibc-core/ics04-channel/src/handler/acknowledgement.rs index e5f484f2b..1224b9ff1 100644 --- a/ibc-core/ics04-channel/src/handler/acknowledgement.rs +++ b/ibc-core/ics04-channel/src/handler/acknowledgement.rs @@ -6,7 +6,7 @@ use ibc_core_channel_types::msgs::MsgAcknowledgement; use ibc_core_client::context::prelude::*; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::State as ConnectionState; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, SeqAckPath, @@ -19,7 +19,7 @@ pub fn acknowledgement_packet_validate( ctx_a: &ValCtx, module: &dyn Module, msg: MsgAcknowledgement, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -27,14 +27,14 @@ where module .on_acknowledgement_packet_validate(&msg.packet, &msg.acknowledgement, &msg.signer) - .map_err(ContextError::PacketError) + .map_err(HandlerError::PacketError) } pub fn acknowledgement_packet_execute( ctx_a: &mut ExecCtx, module: &mut dyn Module, msg: MsgAcknowledgement, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -103,7 +103,7 @@ where Ok(()) } -fn validate(ctx_a: &Ctx, msg: &MsgAcknowledgement) -> Result<(), ContextError> +fn validate(ctx_a: &Ctx, msg: &MsgAcknowledgement) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs index 5b315ecbf..a37e9639d 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs @@ -7,7 +7,7 @@ use ibc_core_channel_types::msgs::MsgChannelCloseConfirm; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ChannelEndPath, ClientConsensusStatePath, Path}; use ibc_core_host::{ExecutionContext, ValidationContext}; @@ -19,7 +19,7 @@ pub fn chan_close_confirm_validate( ctx_b: &ValCtx, module: &dyn Module, msg: MsgChannelCloseConfirm, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -34,7 +34,7 @@ pub fn chan_close_confirm_execute( ctx_b: &mut ExecCtx, module: &mut dyn Module, msg: MsgChannelCloseConfirm, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -59,7 +59,7 @@ where let core_event = { let port_id_on_a = chan_end_on_b.counterparty().port_id.clone(); let chan_id_on_a = chan_end_on_b.counterparty().channel_id.clone().ok_or( - ContextError::ChannelError(ChannelError::MissingCounterparty), + HandlerError::ChannelError(ChannelError::MissingCounterparty), )?; let conn_id_on_b = chan_end_on_b.connection_hops[0].clone(); @@ -86,7 +86,7 @@ where Ok(()) } -fn validate(ctx_b: &Ctx, msg: &MsgChannelCloseConfirm) -> Result<(), ContextError> +fn validate(ctx_b: &Ctx, msg: &MsgChannelCloseConfirm) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-core/ics04-channel/src/handler/chan_close_init.rs index 6bdab73f6..3dc0b5b10 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_init.rs @@ -5,7 +5,7 @@ use ibc_core_channel_types::events::CloseInit; use ibc_core_channel_types::msgs::MsgChannelCloseInit; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::State as ConnectionState; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::ChannelEndPath; use ibc_core_host::{ExecutionContext, ValidationContext}; @@ -16,7 +16,7 @@ pub fn chan_close_init_validate( ctx_a: &ValCtx, module: &dyn Module, msg: MsgChannelCloseInit, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -31,7 +31,7 @@ pub fn chan_close_init_execute( ctx_a: &mut ExecCtx, module: &mut dyn Module, msg: MsgChannelCloseInit, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -57,7 +57,7 @@ where let core_event = { let port_id_on_b = chan_end_on_a.counterparty().port_id.clone(); let chan_id_on_b = chan_end_on_a.counterparty().channel_id.clone().ok_or( - ContextError::ChannelError(ChannelError::MissingCounterparty), + HandlerError::ChannelError(ChannelError::MissingCounterparty), )?; let conn_id_on_a = chan_end_on_a.connection_hops[0].clone(); @@ -84,7 +84,7 @@ where Ok(()) } -fn validate(ctx_a: &Ctx, msg: &MsgChannelCloseInit) -> Result<(), ContextError> +fn validate(ctx_a: &Ctx, msg: &MsgChannelCloseInit) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs index f6271bcd0..64aff01d6 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_ack.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_ack.rs @@ -6,7 +6,7 @@ use ibc_core_channel_types::msgs::MsgChannelOpenAck; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ChannelEndPath, ClientConsensusStatePath, Path}; use ibc_core_host::{ExecutionContext, ValidationContext}; @@ -18,7 +18,7 @@ pub fn chan_open_ack_validate( ctx_a: &ValCtx, module: &dyn Module, msg: MsgChannelOpenAck, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -33,7 +33,7 @@ pub fn chan_open_ack_execute( ctx_a: &mut ExecCtx, module: &mut dyn Module, msg: MsgChannelOpenAck, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -87,7 +87,7 @@ where Ok(()) } -fn validate(ctx_a: &Ctx, msg: &MsgChannelOpenAck) -> Result<(), ContextError> +fn validate(ctx_a: &Ctx, msg: &MsgChannelOpenAck) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs index 2ea7078a4..451a6e222 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs @@ -7,7 +7,7 @@ use ibc_core_channel_types::msgs::MsgChannelOpenConfirm; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ChannelEndPath, ClientConsensusStatePath, Path}; use ibc_core_host::{ExecutionContext, ValidationContext}; @@ -19,7 +19,7 @@ pub fn chan_open_confirm_validate( ctx_b: &ValCtx, module: &dyn Module, msg: MsgChannelOpenConfirm, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -34,7 +34,7 @@ pub fn chan_open_confirm_execute( ctx_b: &mut ExecCtx, module: &mut dyn Module, msg: MsgChannelOpenConfirm, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -64,7 +64,7 @@ where .counterparty() .channel_id .clone() - .ok_or(ContextError::ChannelError( + .ok_or(HandlerError::ChannelError( ChannelError::MissingCounterparty, ))?; @@ -90,7 +90,7 @@ where Ok(()) } -fn validate(ctx_b: &Ctx, msg: &MsgChannelOpenConfirm) -> Result<(), ContextError> +fn validate(ctx_b: &Ctx, msg: &MsgChannelOpenConfirm) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/chan_open_init.rs b/ibc-core/ics04-channel/src/handler/chan_open_init.rs index 58a161d0b..b952e7d1a 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_init.rs @@ -4,7 +4,7 @@ use ibc_core_channel_types::channel::{ChannelEnd, Counterparty, State}; use ibc_core_channel_types::events::OpenInit; use ibc_core_channel_types::msgs::MsgChannelOpenInit; use ibc_core_client::context::prelude::*; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::ChannelId; use ibc_core_host::types::path::{ChannelEndPath, SeqAckPath, SeqRecvPath, SeqSendPath}; @@ -16,7 +16,7 @@ pub fn chan_open_init_validate( ctx_a: &ValCtx, module: &dyn Module, msg: MsgChannelOpenInit, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -39,7 +39,7 @@ pub fn chan_open_init_execute( ctx_a: &mut ExecCtx, module: &mut dyn Module, msg: MsgChannelOpenInit, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -107,7 +107,7 @@ where Ok(()) } -fn validate(ctx_a: &Ctx, msg: &MsgChannelOpenInit) -> Result<(), ContextError> +fn validate(ctx_a: &Ctx, msg: &MsgChannelOpenInit) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/chan_open_try.rs b/ibc-core/ics04-channel/src/handler/chan_open_try.rs index 48138ce69..09ca21604 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_try.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_try.rs @@ -7,7 +7,7 @@ use ibc_core_channel_types::msgs::MsgChannelOpenTry; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::State as ConnectionState; use ibc_core_connection_types::error::ConnectionError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::identifiers::ChannelId; use ibc_core_host::types::path::{ @@ -22,7 +22,7 @@ pub fn chan_open_try_validate( ctx_b: &ValCtx, module: &dyn Module, msg: MsgChannelOpenTry, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -46,7 +46,7 @@ pub fn chan_open_try_execute( ctx_b: &mut ExecCtx, module: &mut dyn Module, msg: MsgChannelOpenTry, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -116,7 +116,7 @@ where Ok(()) } -fn validate(ctx_b: &Ctx, msg: &MsgChannelOpenTry) -> Result<(), ContextError> +fn validate(ctx_b: &Ctx, msg: &MsgChannelOpenTry) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index f3229f493..684502f9c 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -7,7 +7,7 @@ use ibc_core_channel_types::packet::Receipt; use ibc_core_client::context::prelude::*; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::State as ConnectionState; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, @@ -17,7 +17,7 @@ use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_core_router::module::Module; use ibc_primitives::prelude::*; -pub fn recv_packet_validate(ctx_b: &ValCtx, msg: MsgRecvPacket) -> Result<(), ContextError> +pub fn recv_packet_validate(ctx_b: &ValCtx, msg: MsgRecvPacket) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -32,7 +32,7 @@ pub fn recv_packet_execute( ctx_b: &mut ExecCtx, module: &mut dyn Module, msg: MsgRecvPacket, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -136,7 +136,7 @@ where Ok(()) } -fn validate(ctx_b: &Ctx, msg: &MsgRecvPacket) -> Result<(), ContextError> +fn validate(ctx_b: &Ctx, msg: &MsgRecvPacket) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -252,7 +252,7 @@ where let packet_rec = ctx_b.get_packet_receipt(&receipt_path_on_b); match packet_rec { Ok(_receipt) => {} - Err(ContextError::PacketError(PacketError::MissingPacketReceipt(sequence))) + Err(HandlerError::PacketError(PacketError::MissingPacketReceipt(sequence))) if sequence == msg.packet.seq_on_a => {} Err(e) => return Err(e), } @@ -261,7 +261,7 @@ where validate_write_acknowledgement(ctx_b, msg)?; } Order::None => { - return Err(ContextError::ChannelError(ChannelError::InvalidOrderType { + return Err(HandlerError::ChannelError(ChannelError::InvalidOrderType { expected: "Channel ordering cannot be None".to_string(), actual: chan_end_on_b.ordering.to_string(), })) @@ -271,7 +271,7 @@ where Ok(()) } -fn validate_write_acknowledgement(ctx_b: &Ctx, msg: &MsgRecvPacket) -> Result<(), ContextError> +fn validate_write_acknowledgement(ctx_b: &Ctx, msg: &MsgRecvPacket) -> Result<(), HandlerError> where Ctx: ValidationContext, { diff --git a/ibc-core/ics04-channel/src/handler/send_packet.rs b/ibc-core/ics04-channel/src/handler/send_packet.rs index 6680bf6fb..157203643 100644 --- a/ibc-core/ics04-channel/src/handler/send_packet.rs +++ b/ibc-core/ics04-channel/src/handler/send_packet.rs @@ -4,7 +4,7 @@ use ibc_core_channel_types::error::PacketError; use ibc_core_channel_types::events::SendPacket; use ibc_core_channel_types::packet::Packet; use ibc_core_client::context::prelude::*; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqSendPath, @@ -19,7 +19,7 @@ use crate::context::{SendPacketExecutionContext, SendPacketValidationContext}; pub fn send_packet( ctx_a: &mut impl SendPacketExecutionContext, packet: Packet, -) -> Result<(), ContextError> { +) -> Result<(), HandlerError> { send_packet_validate(ctx_a, &packet)?; send_packet_execute(ctx_a, packet) } @@ -28,9 +28,9 @@ pub fn send_packet( pub fn send_packet_validate( ctx_a: &impl SendPacketValidationContext, packet: &Packet, -) -> Result<(), ContextError> { +) -> Result<(), HandlerError> { if !packet.timeout_height_on_b.is_set() && !packet.timeout_timestamp_on_b.is_set() { - return Err(ContextError::PacketError(PacketError::MissingTimeout)); + return Err(HandlerError::PacketError(PacketError::MissingTimeout)); } let chan_end_path_on_a = ChannelEndPath::new(&packet.port_id_on_a, &packet.chan_id_on_a); @@ -104,7 +104,7 @@ pub fn send_packet_validate( pub fn send_packet_execute( ctx_a: &mut impl SendPacketExecutionContext, packet: Packet, -) -> Result<(), ContextError> { +) -> Result<(), HandlerError> { { let seq_send_path_on_a = SeqSendPath::new(&packet.port_id_on_a, &packet.chan_id_on_a); let next_seq_send_on_a = ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; diff --git a/ibc-core/ics04-channel/src/handler/timeout.rs b/ibc-core/ics04-channel/src/handler/timeout.rs index 9ce98bc0a..9d122854b 100644 --- a/ibc-core/ics04-channel/src/handler/timeout.rs +++ b/ibc-core/ics04-channel/src/handler/timeout.rs @@ -5,7 +5,7 @@ use ibc_core_channel_types::events::{ChannelClosed, TimeoutPacket}; use ibc_core_channel_types::msgs::{MsgTimeout, MsgTimeoutOnClose}; use ibc_core_client::context::prelude::*; use ibc_core_connection::delay::verify_conn_delay_passed; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_core_host::types::path::{ ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, @@ -25,7 +25,7 @@ pub fn timeout_packet_validate( ctx_a: &ValCtx, module: &dyn Module, timeout_msg_type: TimeoutMsgType, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ValCtx: ValidationContext, { @@ -41,14 +41,14 @@ where module .on_timeout_packet_validate(&packet, &signer) - .map_err(ContextError::PacketError) + .map_err(HandlerError::PacketError) } pub fn timeout_packet_execute( ctx_a: &mut ExecCtx, module: &mut dyn Module, timeout_msg_type: TimeoutMsgType, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where ExecCtx: ExecutionContext, { @@ -126,7 +126,7 @@ where Ok(()) } -fn validate(ctx_a: &Ctx, msg: &MsgTimeout) -> Result<(), ContextError> +fn validate(ctx_a: &Ctx, msg: &MsgTimeout) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -247,7 +247,7 @@ where ) } Order::None => { - return Err(ContextError::ChannelError(ChannelError::InvalidOrderType { + return Err(HandlerError::ChannelError(ChannelError::InvalidOrderType { expected: "Channel ordering cannot be None".to_string(), actual: chan_end_on_a.ordering.to_string(), })) diff --git a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs index c52225f81..e1a0b94fb 100644 --- a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs +++ b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs @@ -5,7 +5,7 @@ use ibc_core_channel_types::msgs::MsgTimeoutOnClose; use ibc_core_client::context::prelude::*; use ibc_core_connection::delay::verify_conn_delay_passed; use ibc_core_connection::types::error::ConnectionError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_host::types::path::{ ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, }; @@ -13,7 +13,7 @@ use ibc_core_host::ValidationContext; use ibc_primitives::prelude::*; use ibc_primitives::proto::Protobuf; -pub fn validate(ctx_a: &Ctx, msg: &MsgTimeoutOnClose) -> Result<(), ContextError> +pub fn validate(ctx_a: &Ctx, msg: &MsgTimeoutOnClose) -> Result<(), HandlerError> where Ctx: ValidationContext, { @@ -155,7 +155,7 @@ where ) } Order::None => { - return Err(ContextError::ChannelError(ChannelError::InvalidOrderType { + return Err(HandlerError::ChannelError(ChannelError::InvalidOrderType { expected: "Channel ordering cannot be None".to_string(), actual: chan_end_on_a.ordering.to_string(), })) diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index f6d66994d..51c1595e3 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -5,7 +5,7 @@ use ibc_core_client_types::error::ClientError; use ibc_core_client_types::{Height, Status}; use ibc_core_commitment_types::specs::ProofSpecs; use ibc_core_connection_types::error::ConnectionError; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_host_types::identifiers::ChainId; use ibc_primitives::prelude::*; use tendermint::trust_threshold::TrustThresholdFraction as TendermintTrustThresholdFraction; @@ -19,7 +19,7 @@ pub trait ValidateSelfClientContext { fn validate_self_tendermint_client( &self, client_state_of_host_on_counterparty: TmClientState, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { client_state_of_host_on_counterparty .validate() .map_err(ClientError::from)?; @@ -30,7 +30,7 @@ pub trait ValidateSelfClientContext { let self_chain_id = self.chain_id(); if self_chain_id != &client_state_of_host_on_counterparty.chain_id { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "invalid chain-id. expected: {}, got: {}", @@ -43,7 +43,7 @@ pub trait ValidateSelfClientContext { let latest_height = client_state_of_host_on_counterparty.latest_height; let self_revision_number = self_chain_id.revision_number(); if self_revision_number != latest_height.revision_number() { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "client is not in the same revision as the chain. expected: {}, got: {}", @@ -55,7 +55,7 @@ pub trait ValidateSelfClientContext { } if latest_height >= self.host_current_height() { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "client has latest height {} greater than or equal to chain height {}", @@ -67,7 +67,7 @@ pub trait ValidateSelfClientContext { } if self.proof_specs() != &client_state_of_host_on_counterparty.proof_specs { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "client has invalid proof specs. expected: {:?}, got: {:?}", @@ -91,7 +91,7 @@ pub trait ValidateSelfClientContext { }; if self.unbonding_period() != client_state_of_host_on_counterparty.unbonding_period { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "invalid unbonding period. expected: {:?}, got: {:?}", @@ -105,7 +105,7 @@ pub trait ValidateSelfClientContext { if client_state_of_host_on_counterparty.unbonding_period < client_state_of_host_on_counterparty.trusting_period { - return Err(ContextError::ConnectionError(ConnectionError::InvalidClientState{ description: format!( + return Err(HandlerError::ConnectionError(ConnectionError::InvalidClientState{ description: format!( "unbonding period must be greater than trusting period. unbonding period ({:?}) < trusting period ({:?})", client_state_of_host_on_counterparty.unbonding_period, client_state_of_host_on_counterparty.trusting_period @@ -115,7 +115,7 @@ pub trait ValidateSelfClientContext { if !client_state_of_host_on_counterparty.upgrade_path.is_empty() && self.upgrade_path() != client_state_of_host_on_counterparty.upgrade_path { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "invalid upgrade path. expected: {:?}, got: {:?}", diff --git a/ibc-core/ics24-host/src/context.rs b/ibc-core/ics24-host/src/context.rs index da858968d..30f100a33 100644 --- a/ibc-core/ics24-host/src/context.rs +++ b/ibc-core/ics24-host/src/context.rs @@ -8,7 +8,7 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentPrefix; use ibc_core_connection_types::version::{pick_version, Version as ConnectionVersion}; use ibc_core_connection_types::ConnectionEnd; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::IbcEvent; use ibc_core_host_types::identifiers::{ConnectionId, Sequence}; use ibc_core_host_types::path::{ @@ -34,24 +34,24 @@ pub trait ValidationContext { fn get_client_validation_context(&self) -> &Self::V; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the `ConsensusState` of the host (local) chain at a specific height. fn host_consensus_state( &self, height: &Height, - ) -> Result; + ) -> Result; /// Returns a natural number, counting how many clients have been created /// thus far. The value of this counter should increase only via method /// `ExecutionContext::increase_client_counter`. - fn client_counter(&self) -> Result; + fn client_counter(&self) -> Result; /// Returns the ConnectionEnd for the given identifier `conn_id`. - fn connection_end(&self, conn_id: &ConnectionId) -> Result; + fn connection_end(&self, conn_id: &ConnectionId) -> Result; /// Validates the `ClientState` of the host chain stored on the counterparty /// chain against the host's internal state. @@ -65,13 +65,13 @@ pub trait ValidationContext { fn validate_self_client( &self, client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Returns the prefix that the local chain uses in the KV store. fn commitment_prefix(&self) -> CommitmentPrefix; /// Returns a counter on how many connections have been created thus far. - fn connection_counter(&self) -> Result; + fn connection_counter(&self) -> Result; /// Function required by ICS-03. Returns the list of all possible versions that the connection /// handshake protocol supports. @@ -84,7 +84,7 @@ pub trait ValidationContext { fn pick_version( &self, counterparty_candidate_versions: &[ConnectionVersion], - ) -> Result { + ) -> Result { let version = pick_version( &self.get_compatible_versions(), counterparty_candidate_versions, @@ -93,38 +93,38 @@ pub trait ValidationContext { } /// Returns the `ChannelEnd` for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; /// Returns the sequence number for the next packet to be sent for the given store path fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) - -> Result; + -> Result; /// Returns the sequence number for the next packet to be received for the given store path fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) - -> Result; + -> Result; /// Returns the sequence number for the next packet to be acknowledged for the given store path - fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result; + fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result; /// Returns the packet commitment for the given store path fn get_packet_commitment( &self, commitment_path: &CommitmentPath, - ) -> Result; + ) -> Result; /// Returns the packet receipt for the given store path - fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result; + fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result; /// Returns the packet acknowledgement for the given store path fn get_packet_acknowledgement( &self, ack_path: &AckPath, - ) -> Result; + ) -> Result; /// Returns a counter on the number of channel ids have been created thus far. /// The value of this counter should increase only via method /// `ExecutionContext::increase_channel_counter`. - fn channel_counter(&self) -> Result; + fn channel_counter(&self) -> Result; /// Returns the maximum expected time per block fn max_expected_time_per_block(&self) -> Duration; @@ -137,7 +137,7 @@ pub trait ValidationContext { /// Validates the `signer` field of IBC messages, which represents the address /// of the user/relayer that signed the given message. - fn validate_message_signer(&self, signer: &Signer) -> Result<(), ContextError>; + fn validate_message_signer(&self, signer: &Signer) -> Result<(), HandlerError>; } /// Context to be implemented by the host that provides all "write-only" methods. @@ -151,93 +151,93 @@ pub trait ExecutionContext: ValidationContext { /// Called upon client creation. /// Increases the counter, that keeps track of how many clients have been created. - fn increase_client_counter(&mut self) -> Result<(), ContextError>; + fn increase_client_counter(&mut self) -> Result<(), HandlerError>; /// Stores the given connection_end at path fn store_connection( &mut self, connection_path: &ConnectionPath, connection_end: ConnectionEnd, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Stores the given connection_id at a path associated with the client_id. fn store_connection_to_client( &mut self, client_connection_path: &ClientConnectionPath, conn_id: ConnectionId, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Called upon connection identifier creation (Init or Try process). /// Increases the counter which keeps track of how many connections have been created. - fn increase_connection_counter(&mut self) -> Result<(), ContextError>; + fn increase_connection_counter(&mut self) -> Result<(), HandlerError>; /// Stores the given packet commitment at the given store path fn store_packet_commitment( &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Deletes the packet commitment at the given store path fn delete_packet_commitment( &mut self, commitment_path: &CommitmentPath, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Stores the given packet receipt at the given store path fn store_packet_receipt( &mut self, receipt_path: &ReceiptPath, receipt: Receipt, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Stores the given packet acknowledgement at the given store path fn store_packet_acknowledgement( &mut self, ack_path: &AckPath, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Deletes the packet acknowledgement at the given store path - fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), ContextError>; + fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HandlerError>; /// Stores the given channel_end at a path associated with the port_id and channel_id. fn store_channel( &mut self, channel_end_path: &ChannelEndPath, channel_end: ChannelEnd, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Stores the given `nextSequenceSend` number at the given store path fn store_next_sequence_send( &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Stores the given `nextSequenceRecv` number at the given store path fn store_next_sequence_recv( &mut self, seq_recv_path: &SeqRecvPath, seq: Sequence, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Stores the given `nextSequenceAck` number at the given store path fn store_next_sequence_ack( &mut self, seq_ack_path: &SeqAckPath, seq: Sequence, - ) -> Result<(), ContextError>; + ) -> Result<(), HandlerError>; /// Called upon channel identifier creation (Init or Try message processing). /// Increases the counter, that keeps track of how many channels have been created. - fn increase_channel_counter(&mut self) -> Result<(), ContextError>; + fn increase_channel_counter(&mut self) -> Result<(), HandlerError>; /// Emit the given IBC event - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), ContextError>; + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError>; /// Log the given message. - fn log_message(&mut self, message: String) -> Result<(), ContextError>; + fn log_message(&mut self, message: String) -> Result<(), HandlerError>; } /// Convenient type alias for `ClientStateRef`, providing access to client diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 220fb1353..9cf25fe51 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -85,3 +85,6 @@ impl std::error::Error for IdentifierError {} #[cfg(feature = "std")] impl std::error::Error for DecodingError {} + +#[cfg(feature = "std")] +impl std::error::Error for HostError {} diff --git a/ibc-core/ics25-handler/src/entrypoint.rs b/ibc-core/ics25-handler/src/entrypoint.rs index 575e5e096..7a0d63349 100644 --- a/ibc-core/ics25-handler/src/entrypoint.rs +++ b/ibc-core/ics25-handler/src/entrypoint.rs @@ -17,7 +17,7 @@ use ibc_core_connection::handler::{ conn_open_ack, conn_open_confirm, conn_open_init, conn_open_try, }; use ibc_core_connection::types::msgs::ConnectionMsg; -use ibc_core_handler_types::error::ContextError; +use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::msgs::MsgEnvelope; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_core_router::router::Router; @@ -29,7 +29,7 @@ pub fn dispatch( ctx: &mut Ctx, router: &mut impl Router, msg: MsgEnvelope, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ExecutionContext, <::ClientStateRef as TryFrom>::Error: Into, @@ -48,7 +48,7 @@ where /// That is, the state transition of message `i` must be applied before /// message `i+1` is validated. This is equivalent to calling /// `dispatch()` on each successively. -pub fn validate(ctx: &Ctx, router: &impl Router, msg: MsgEnvelope) -> Result<(), ContextError> +pub fn validate(ctx: &Ctx, router: &impl Router, msg: MsgEnvelope) -> Result<(), HandlerError> where Ctx: ValidationContext, <::ClientStateRef as TryFrom>::Error: Into, @@ -122,7 +122,7 @@ pub fn execute( ctx: &mut Ctx, router: &mut impl Router, msg: MsgEnvelope, -) -> Result<(), ContextError> +) -> Result<(), HandlerError> where Ctx: ExecutionContext, <::ClientStateMut as TryFrom>::Error: Into, diff --git a/ibc-core/ics25-handler/types/src/error.rs b/ibc-core/ics25-handler/types/src/error.rs index 84bc0b939..1544170f2 100644 --- a/ibc-core/ics25-handler/types/src/error.rs +++ b/ibc-core/ics25-handler/types/src/error.rs @@ -5,45 +5,49 @@ use displaydoc::Display; use ibc_core_channel_types::error::{ChannelError, PacketError}; use ibc_core_client_types::error::ClientError; use ibc_core_connection_types::error::ConnectionError; +use ibc_core_host_types::error::HostError; use ibc_core_router_types::error::RouterError; use ibc_primitives::prelude::*; -/// Top-level error +/// Top-level type that surfaces errors from the core ibc-rs crates. #[derive(Debug, Display, From)] -pub enum ContextError { +pub enum HandlerError { /// ICS02 Client error: {0} - ClientError(ClientError), + Client(ClientError), /// ICS03 Connection error: {0} - ConnectionError(ConnectionError), + Connection(ConnectionError), /// ICS04 Channel error: {0} - ChannelError(ChannelError), + Channel(ChannelError), /// ICS04 Packet error: {0} - PacketError(PacketError), + Packet(PacketError), /// ICS26 Routing error: {0} - RouterError(RouterError), + Router(RouterError), + /// ICS25 Host error: {0} + Host(HostError), } // TODO(seanchen1991): Figure out how to remove this -impl From for ClientError { - fn from(context_error: ContextError) -> Self { - match context_error { - ContextError::ClientError(e) => e, +impl From for ClientError { + fn from(e: HandlerError) -> Self { + match e { + HandlerError::Client(e) => e, _ => ClientError::Other { - description: context_error.to_string(), + description: e.to_string(), }, } } } #[cfg(feature = "std")] -impl std::error::Error for ContextError { +impl std::error::Error for HandlerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - Self::ClientError(e) => Some(e), - Self::ConnectionError(e) => Some(e), - Self::ChannelError(e) => Some(e), - Self::PacketError(e) => Some(e), - Self::RouterError(e) => Some(e), + Self::Client(e) => Some(e), + Self::Connection(e) => Some(e), + Self::Channel(e) => Some(e), + Self::Packet(e) => Some(e), + Self::Router(e) => Some(e), + Self::Host(e) => Some(e), } } } diff --git a/ibc-query/src/core/context.rs b/ibc-query/src/core/context.rs index 693dafec9..540b7a690 100644 --- a/ibc-query/src/core/context.rs +++ b/ibc-query/src/core/context.rs @@ -4,7 +4,7 @@ use ibc::core::channel::types::channel::IdentifiedChannelEnd; use ibc::core::channel::types::packet::PacketState; use ibc::core::client::types::Height; use ibc::core::connection::types::IdentifiedConnectionEnd; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::host::types::identifiers::{ClientId, ConnectionId, Sequence}; use ibc::core::host::types::path::{ChannelEndPath, Path}; use ibc::core::host::{ClientStateRef, ConsensusStateRef, ValidationContext}; @@ -22,32 +22,32 @@ pub trait QueryContext: ProvableContext + ValidationContext { // Client queries /// Returns the list of all clients. - fn client_states(&self) -> Result)>, ContextError>; + fn client_states(&self) -> Result)>, HandlerError>; /// Returns the list of all consensus states for the given client. fn consensus_states( &self, client_id: &ClientId, - ) -> Result)>, ContextError>; + ) -> Result)>, HandlerError>; /// Returns the list of all heights at which consensus states for the given client are. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, ContextError>; + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError>; // Connection queries /// Returns the list of all connection ends. - fn connection_ends(&self) -> Result, ContextError>; + fn connection_ends(&self) -> Result, HandlerError>; /// Returns the list of all connection ids of the given client. fn client_connection_ends( &self, client_id: &ClientId, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; // Channel queries /// Returns the list of all channel ends. - fn channel_ends(&self) -> Result, ContextError>; + fn channel_ends(&self) -> Result, HandlerError>; // Packet queries @@ -55,7 +55,7 @@ pub trait QueryContext: ProvableContext + ValidationContext { fn packet_commitments( &self, channel_end_path: &ChannelEndPath, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; /// Filters the list of packet sequences for the given channel end that are acknowledged. /// Returns all the packet acknowledgements if `sequences` is empty. @@ -63,14 +63,14 @@ pub trait QueryContext: ProvableContext + ValidationContext { &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; /// Filters the packet sequences for the given channel end that are not received. fn unreceived_packets( &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; /// Filters the list of packet sequences for the given channel end whose acknowledgement is not received. /// Returns all the unreceived acknowledgements if `sequences` is empty. @@ -78,5 +78,5 @@ pub trait QueryContext: ProvableContext + ValidationContext { &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, ContextError>; + ) -> Result, HandlerError>; } diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index 4c41120eb..91eeb70a7 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -4,7 +4,7 @@ use displaydoc::Display; use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; use ibc::core::connection::types::error::ConnectionError; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::host::types::error::IdentifierError; use tonic::Status; @@ -14,7 +14,7 @@ use tonic::Status; #[derive(Debug, Display)] pub enum QueryError { /// context error: `{0}` - ContextError(ContextError), + HandlerError(HandlerError), /// identifier error: `{0}` IdentifierError(IdentifierError), /// missing proof: `{0}` @@ -36,7 +36,7 @@ impl QueryError { impl From for Status { fn from(e: QueryError) -> Self { match e { - QueryError::ContextError(ctx_err) => Self::internal(ctx_err.to_string()), + QueryError::HandlerError(ctx_err) => Self::internal(ctx_err.to_string()), QueryError::IdentifierError(id_err) => Self::internal(id_err.to_string()), QueryError::MissingProof(description) => Self::not_found(description), QueryError::MissingField(description) => Self::invalid_argument(description), @@ -44,33 +44,33 @@ impl From for Status { } } -impl From for QueryError { - fn from(e: ContextError) -> Self { - Self::ContextError(e) +impl From for QueryError { + fn from(e: HandlerError) -> Self { + Self::HandlerError(e) } } impl From for QueryError { fn from(e: ClientError) -> Self { - Self::ContextError(ContextError::ClientError(e)) + Self::HandlerError(HandlerError::ClientError(e)) } } impl From for QueryError { fn from(e: ConnectionError) -> Self { - Self::ContextError(ContextError::ConnectionError(e)) + Self::HandlerError(HandlerError::ConnectionError(e)) } } impl From for QueryError { fn from(e: ChannelError) -> Self { - Self::ContextError(ContextError::ChannelError(e)) + Self::HandlerError(HandlerError::ChannelError(e)) } } impl From for QueryError { fn from(e: PacketError) -> Self { - Self::ContextError(ContextError::PacketError(e)) + Self::HandlerError(HandlerError::PacketError(e)) } } diff --git a/ibc-testkit/src/context.rs b/ibc-testkit/src/context.rs index 92255ba3d..92986d14f 100644 --- a/ibc-testkit/src/context.rs +++ b/ibc-testkit/src/context.rs @@ -10,7 +10,7 @@ use ibc::core::client::context::{ClientExecutionContext, ClientValidationContext use ibc::core::client::types::Height; use ibc::core::connection::types::ConnectionEnd; use ibc::core::entrypoint::{dispatch, execute, validate}; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::IbcEvent; use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::{ChannelId, ClientId, ConnectionId, PortId, Sequence}; @@ -462,24 +462,24 @@ where } /// Calls [`validate`] function on [`MsgEnvelope`] using the context's IBC store and router. - pub fn validate(&mut self, msg: MsgEnvelope) -> Result<(), ContextError> { + pub fn validate(&mut self, msg: MsgEnvelope) -> Result<(), HandlerError> { validate(&self.ibc_store, &self.ibc_router, msg) } /// Calls [`execute`] function on [`MsgEnvelope`] using the context's IBC store and router. - pub fn execute(&mut self, msg: MsgEnvelope) -> Result<(), ContextError> { + pub fn execute(&mut self, msg: MsgEnvelope) -> Result<(), HandlerError> { execute(&mut self.ibc_store, &mut self.ibc_router, msg) } /// Calls [`dispatch`] function on [`MsgEnvelope`] using the context's IBC store and router. - pub fn dispatch(&mut self, msg: MsgEnvelope) -> Result<(), ContextError> { + pub fn dispatch(&mut self, msg: MsgEnvelope) -> Result<(), HandlerError> { dispatch(&mut self.ibc_store, &mut self.ibc_router, msg) } /// A datagram passes from the relayer to the IBC module (on host chain). /// Alternative method to `Ics18Context::send` that does not exercise any serialization. /// Used in testing the Ics18 algorithms, hence this may return an Ics18Error. - pub fn deliver(&mut self, msg: MsgEnvelope) -> Result<(), ContextError> { + pub fn deliver(&mut self, msg: MsgEnvelope) -> Result<(), HandlerError> { self.dispatch(msg)?; // Create a new block. diff --git a/ibc-testkit/src/fixtures/mod.rs b/ibc-testkit/src/fixtures/mod.rs index f6b51ef46..c5e14f29a 100644 --- a/ibc-testkit/src/fixtures/mod.rs +++ b/ibc-testkit/src/fixtures/mod.rs @@ -3,13 +3,13 @@ pub mod clients; pub mod core; use alloc::fmt::Debug; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::primitives::prelude::*; use crate::testapp::ibc::core::types::DefaultIbcStore; pub enum Expect { Success, - Failure(Option), + Failure(Option), } #[derive(Debug)] @@ -23,7 +23,7 @@ impl Fixture { &self, expect: &Expect, process: &str, - res: &Result<(), ContextError>, + res: &Result<(), HandlerError>, ) -> String { let base_error = match expect { Expect::Success => "step failed!", diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index dff68ecd9..c62735bca 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -8,7 +8,7 @@ use ibc::core::client::types::{Height, Status}; use ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::host::types::error::DecodingError; use ibc::core::host::types::identifiers::{ClientId, ClientType}; use ibc::core::host::types::path::{ClientConsensusStatePath, ClientStatePath, Path, PathBytes}; @@ -155,10 +155,10 @@ impl From for Any { pub trait MockClientContext { /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; } impl ClientStateCommon for MockClientState { diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index a2c9d59d7..f7927d5bb 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -7,7 +7,7 @@ use ibc::core::client::context::{ }; use ibc::core::client::types::error::ClientError; use ibc::core::client::types::Height; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::host::types::identifiers::{ChannelId, ClientId, PortId}; use ibc::core::host::types::path::{ ClientConsensusStatePath, ClientStatePath, ClientUpdateHeightPath, ClientUpdateTimePath, Path, @@ -37,11 +37,11 @@ impl MockClientContext for MockIbcStore where S: ProvableStore + Debug, { - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { ValidationContext::host_timestamp(self) } - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { ValidationContext::host_height(self) } } @@ -50,16 +50,16 @@ impl ExtClientValidationContext for MockIbcStore where S: ProvableStore + Debug, { - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { ValidationContext::host_timestamp(self) } - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { ValidationContext::host_height(self) } /// Returns the list of heights at which the consensus state of the given client was updated. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, ContextError> { + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError> { let path = format!("clients/{}/consensusStates", client_id) .try_into() .map_err(|_| ClientError::Other { @@ -89,7 +89,7 @@ where &self, client_id: &ClientId, height: &Height, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { let path = format!("clients/{client_id}/consensusStates").into(); let keys = self.store.get_keys(&path); @@ -122,7 +122,7 @@ where &self, client_id: &ClientId, height: &Height, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { let path = format!("clients/{client_id}/consensusStates").into(); let keys = self.store.get_keys(&path); @@ -159,7 +159,7 @@ where type ClientStateRef = AnyClientState; type ConsensusStateRef = AnyConsensusState; - fn client_state(&self, client_id: &ClientId) -> Result { + fn client_state(&self, client_id: &ClientId) -> Result { Ok(self .client_state_store .get(StoreHeight::Pending, &ClientStatePath(client_id.clone())) @@ -169,7 +169,7 @@ where fn consensus_state( &self, client_cons_state_path: &ClientConsensusStatePath, - ) -> Result { + ) -> Result { let height = Height::new( client_cons_state_path.revision_number, client_cons_state_path.revision_height, @@ -192,7 +192,7 @@ where &self, client_id: &ClientId, height: &Height, - ) -> Result<(Timestamp, Height), ContextError> { + ) -> Result<(Timestamp, Height), HandlerError> { let client_update_time_path = ClientUpdateTimePath::new( client_id.clone(), height.revision_number(), @@ -233,7 +233,7 @@ where &mut self, client_state_path: ClientStatePath, client_state: Self::ClientStateRef, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.client_state_store .set(client_state_path, client_state) .map_err(|_| ClientError::Other { @@ -248,7 +248,7 @@ where &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Self::ConsensusStateRef, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.consensus_state_store .set(consensus_state_path, consensus_state) .map_err(|_| ClientError::Other { @@ -260,7 +260,7 @@ where fn delete_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.consensus_state_store.delete(consensus_state_path); Ok(()) } @@ -271,7 +271,7 @@ where &mut self, client_id: ClientId, height: Height, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { let client_update_time_path = ClientUpdateTimePath::new( client_id.clone(), height.revision_number(), @@ -297,7 +297,7 @@ where height: Height, host_timestamp: Timestamp, host_height: Height, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { let client_update_time_path = ClientUpdateTimePath::new( client_id.clone(), height.revision_number(), diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index aef595159..0b71426a7 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -16,7 +16,7 @@ use ibc::core::commitment_types::commitment::CommitmentPrefix; use ibc::core::commitment_types::merkle::MerkleProof; use ibc::core::connection::types::error::ConnectionError; use ibc::core::connection::types::{ConnectionEnd, IdentifiedConnectionEnd}; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::IbcEvent; use ibc::core::host::types::identifiers::{ClientId, ConnectionId, Sequence}; use ibc::core::host::types::path::{ @@ -42,20 +42,20 @@ where type HostClientState = AnyClientState; type HostConsensusState = AnyConsensusState; - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { Ok(Height::new( *self.revision_number.lock(), self.store.current_height(), )?) } - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { let host_height = self.host_height()?; let host_cons_state = self.host_consensus_state(&host_height)?; Ok(host_cons_state.timestamp()) } - fn client_counter(&self) -> Result { + fn client_counter(&self) -> Result { Ok(self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) @@ -67,7 +67,7 @@ where fn host_consensus_state( &self, height: &Height, - ) -> Result { + ) -> Result { let consensus_states_binding = self.host_consensus_states.lock(); Ok(consensus_states_binding .get(&height.revision_height()) @@ -78,7 +78,7 @@ where fn validate_self_client( &self, client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { if client_state_of_host_on_counterparty.is_frozen() { return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); } @@ -91,7 +91,7 @@ where .latest_height() .revision_number() { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "client is not in the same revision as the chain. expected: {}, got: {}", @@ -106,7 +106,7 @@ where let host_current_height = latest_height.increment(); if client_state_of_host_on_counterparty.latest_height() >= host_current_height { - return Err(ContextError::ConnectionError( + return Err(HandlerError::ConnectionError( ConnectionError::InvalidClientState { description: format!( "client has latest height {} greater than or equal to chain height {}", @@ -120,7 +120,7 @@ where Ok(()) } - fn connection_end(&self, conn_id: &ConnectionId) -> Result { + fn connection_end(&self, conn_id: &ConnectionId) -> Result { Ok(self .connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) @@ -133,14 +133,14 @@ where CommitmentPrefix::from(b"mock".to_vec()) } - fn connection_counter(&self) -> Result { + fn connection_counter(&self) -> Result { Ok(self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) .ok_or(ConnectionError::MissingConnectionCounter)?) } - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { Ok(self .channel_end_store .get( @@ -156,7 +156,7 @@ where fn get_next_sequence_send( &self, seq_send_path: &SeqSendPath, - ) -> Result { + ) -> Result { Ok(self .send_sequence_store .get( @@ -169,7 +169,7 @@ where fn get_next_sequence_recv( &self, seq_recv_path: &SeqRecvPath, - ) -> Result { + ) -> Result { Ok(self .recv_sequence_store .get( @@ -179,7 +179,7 @@ where .ok_or(PacketError::ImplementationSpecific)?) } - fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { + fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { Ok(self .ack_sequence_store .get( @@ -192,7 +192,7 @@ where fn get_packet_commitment( &self, commitment_path: &CommitmentPath, - ) -> Result { + ) -> Result { Ok(self .packet_commitment_store .get( @@ -206,7 +206,7 @@ where .ok_or(PacketError::ImplementationSpecific)?) } - fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { + fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { Ok(self .packet_receipt_store .is_path_set( @@ -224,7 +224,7 @@ where fn get_packet_acknowledgement( &self, ack_path: &AckPath, - ) -> Result { + ) -> Result { Ok(self .packet_ack_store .get( @@ -237,7 +237,7 @@ where /// Returns a counter of the number of channel ids that have been created thus far. /// The value of this counter should increase only via the /// `ChannelKeeper::increase_channel_counter` method. - fn channel_counter(&self) -> Result { + fn channel_counter(&self) -> Result { Ok(self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) @@ -249,7 +249,7 @@ where Duration::from_secs(DEFAULT_BLOCK_TIME_SECS) } - fn validate_message_signer(&self, _signer: &Signer) -> Result<(), ContextError> { + fn validate_message_signer(&self, _signer: &Signer) -> Result<(), HandlerError> { Ok(()) } @@ -289,7 +289,7 @@ where S: ProvableStore + Debug, { /// Returns the list of all client states. - fn client_states(&self) -> Result)>, ContextError> { + fn client_states(&self) -> Result)>, HandlerError> { let path = "clients".to_owned().into(); self.client_state_store @@ -316,7 +316,7 @@ where fn consensus_states( &self, client_id: &ClientId, - ) -> Result)>, ContextError> { + ) -> Result)>, HandlerError> { let path = format!("clients/{}/consensusStates", client_id) .try_into() .map_err(|_| ClientError::Other { @@ -353,7 +353,7 @@ where } /// Returns the list of heights at which the consensus state of the given client was updated. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, ContextError> { + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError> { let path = format!("clients/{}/consensusStates", client_id) .try_into() .map_err(|_| ClientError::Other { @@ -380,7 +380,7 @@ where } /// Returns all the IBC connection ends of a chain. - fn connection_ends(&self) -> Result, ContextError> { + fn connection_ends(&self) -> Result, HandlerError> { let path = "connections".to_owned().into(); self.connection_end_store @@ -410,7 +410,7 @@ where fn client_connection_ends( &self, client_id: &ClientId, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { let client_connection_path = ClientConnectionPath::new(client_id.clone()); Ok(self @@ -420,7 +420,7 @@ where } /// Returns all the IBC channel ends of a chain. - fn channel_ends(&self) -> Result, ContextError> { + fn channel_ends(&self) -> Result, HandlerError> { let path = "channelEnds".to_owned().into(); self.channel_end_store @@ -454,7 +454,7 @@ where fn packet_commitments( &self, channel_end_path: &ChannelEndPath, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { let path = format!( "commitments/ports/{}/channels/{}/sequences", channel_end_path.0, channel_end_path.1 @@ -496,7 +496,7 @@ where &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { let collected_paths: Vec<_> = if sequences.len() == 0 { // if sequences is empty, return all the acks let ack_path_prefix = format!( @@ -549,7 +549,7 @@ where &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { // QUESTION. Currently only works for unordered channels; ordered channels // don't use receipts. However, ibc-go does it this way. Investigate if // this query only ever makes sense on unordered channels. @@ -574,7 +574,7 @@ where &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, ContextError> { + ) -> Result, HandlerError> { let collected_paths: Vec<_> = if sequences.len() == 0 { // if sequences is empty, return all the acks let commitment_path_prefix = format!( @@ -625,7 +625,7 @@ where /// Called upon client creation. /// Increases the counter, that keeps track of how many clients have been created. - fn increase_client_counter(&mut self) -> Result<(), ContextError> { + fn increase_client_counter(&mut self) -> Result<(), HandlerError> { let current_sequence = self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) @@ -647,7 +647,7 @@ where &mut self, connection_path: &ConnectionPath, connection_end: ConnectionEnd, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.connection_end_store .set(connection_path.clone(), connection_end) .map_err(|_| ConnectionError::FailedToStoreConnectionEnd)?; @@ -659,7 +659,7 @@ where &mut self, client_connection_path: &ClientConnectionPath, conn_id: ConnectionId, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { let mut conn_ids: Vec = self .connection_ids_store .get(StoreHeight::Pending, client_connection_path) @@ -673,7 +673,7 @@ where /// Called upon connection identifier creation (Init or Try process). /// Increases the counter, that keeps track of how many connections have been created. - fn increase_connection_counter(&mut self) -> Result<(), ContextError> { + fn increase_connection_counter(&mut self) -> Result<(), HandlerError> { let current_sequence = self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) @@ -690,7 +690,7 @@ where &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.packet_commitment_store .set(commitment_path.clone(), commitment) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -700,7 +700,7 @@ where fn delete_packet_commitment( &mut self, commitment_path: &CommitmentPath, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.packet_commitment_store.delete(commitment_path.clone()); Ok(()) } @@ -709,7 +709,7 @@ where &mut self, receipt_path: &ReceiptPath, _receipt: Receipt, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.packet_receipt_store .set_path(receipt_path.clone()) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -720,14 +720,14 @@ where &mut self, ack_path: &AckPath, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.packet_ack_store .set(ack_path.clone(), ack_commitment) .map_err(|_| PacketError::ImplementationSpecific)?; Ok(()) } - fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), ContextError> { + fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HandlerError> { self.packet_ack_store.delete(ack_path.clone()); Ok(()) } @@ -736,7 +736,7 @@ where &mut self, channel_end_path: &ChannelEndPath, channel_end: ChannelEnd, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.channel_end_store .set(channel_end_path.clone(), channel_end) .map_err(|e| ChannelError::FailedToStoreChannel { @@ -749,7 +749,7 @@ where &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.send_sequence_store .set(seq_send_path.clone(), seq) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -760,7 +760,7 @@ where &mut self, seq_recv_path: &SeqRecvPath, seq: Sequence, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.recv_sequence_store .set(seq_recv_path.clone(), seq) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -771,14 +771,14 @@ where &mut self, seq_ack_path: &SeqAckPath, seq: Sequence, - ) -> Result<(), ContextError> { + ) -> Result<(), HandlerError> { self.ack_sequence_store .set(seq_ack_path.clone(), seq) .map_err(|_| PacketError::ImplementationSpecific)?; Ok(()) } - fn increase_channel_counter(&mut self) -> Result<(), ContextError> { + fn increase_channel_counter(&mut self) -> Result<(), HandlerError> { let current_sequence = self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) @@ -793,12 +793,12 @@ where Ok(()) } - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), ContextError> { + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError> { self.events.lock().push(event); Ok(()) } - fn log_message(&mut self, message: String) -> Result<(), ContextError> { + fn log_message(&mut self, message: String) -> Result<(), HandlerError> { self.logs.lock().push(message); Ok(()) } diff --git a/tests-integration/tests/core/ics02_client/create_client.rs b/tests-integration/tests/core/ics02_client/create_client.rs index c78fef45c..ad91c58b7 100644 --- a/tests-integration/tests/core/ics02_client/create_client.rs +++ b/tests-integration/tests/core/ics02_client/create_client.rs @@ -8,7 +8,7 @@ use ibc::core::client::types::msgs::{ClientMsg, MsgCreateClient}; use ibc::core::client::types::Height; use ibc::core::commitment_types::error::CommitmentError; use ibc::core::entrypoint::{execute, validate}; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::ClientId; use ibc::core::host::types::path::{ClientConsensusStatePath, NextClientSequencePath}; @@ -180,7 +180,7 @@ fn test_create_expired_mock_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredMockHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError( + Expect::Failure(Some(HandlerError::ClientError( ClientError::UnexpectedStatus(Status::Expired), ))), ); @@ -206,7 +206,7 @@ fn test_create_expired_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError( + Expect::Failure(Some(HandlerError::ClientError( ClientError::UnexpectedStatus(Status::Expired), ))), ); @@ -218,7 +218,7 @@ fn test_create_frozen_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::FrozenTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(ContextError::ClientError( + Expect::Failure(Some(HandlerError::ClientError( ClientError::UnexpectedStatus(Status::Frozen), ))), ); diff --git a/tests-integration/tests/core/ics02_client/upgrade_client.rs b/tests-integration/tests/core/ics02_client/upgrade_client.rs index 153d69e42..34706ae2e 100644 --- a/tests-integration/tests/core/ics02_client/upgrade_client.rs +++ b/tests-integration/tests/core/ics02_client/upgrade_client.rs @@ -4,7 +4,7 @@ use ibc::core::client::types::error::{ClientError, UpgradeClientError}; use ibc::core::client::types::msgs::{ClientMsg, MsgUpgradeClient}; use ibc::core::client::types::Height; use ibc::core::entrypoint::{execute, validate}; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::{IbcEvent, MessageEvent}; use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::path::ClientConsensusStatePath; @@ -143,7 +143,7 @@ fn msg_upgrade_client_healthy() { fn upgrade_client_fail_nonexisting_client() { let fxt = msg_upgrade_client_fixture(Ctx::Default, Msg::Default); let expected_err = - ContextError::ClientError(ClientError::MissingClientState(fxt.msg.client_id.clone())); + HandlerError::ClientError(ClientError::MissingClientState(fxt.msg.client_id.clone())); upgrade_client_validate(&fxt, Expect::Failure(Some(expected_err))); } @@ -158,14 +158,14 @@ fn upgrade_client_fail_low_upgrade_height() { .into(); upgrade_client_validate( &fxt, - Expect::Failure(Some(ContextError::from(expected_err))), + Expect::Failure(Some(HandlerError::from(expected_err))), ); } #[test] fn upgrade_client_fail_unknown_upgraded_client_state() { let fxt = msg_upgrade_client_fixture(Ctx::WithClient, Msg::UnknownUpgradedClientStateType); - let expected_err = ContextError::ClientError(ClientError::InvalidClientStateType( + let expected_err = HandlerError::ClientError(ClientError::InvalidClientStateType( client_type().to_string(), )); upgrade_client_validate(&fxt, Expect::Failure(Some(expected_err))); diff --git a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs index 5d292b3f7..8f09a2fb7 100644 --- a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs +++ b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs @@ -6,7 +6,7 @@ use ibc::core::connection::types::error::ConnectionError; use ibc::core::connection::types::msgs::{ConnectionMsg, MsgConnectionOpenAck}; use ibc::core::connection::types::{ConnectionEnd, Counterparty, State}; use ibc::core::entrypoint::{execute, validate}; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::{IbcEvent, MessageEvent}; use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::{ChainId, ClientId}; @@ -126,16 +126,16 @@ fn conn_open_ack_validate(fxt: &Fixture, expect: Expect) { let cons_state_height = fxt.msg.consensus_height_of_a_on_b; match res.unwrap_err() { - ContextError::ConnectionError(ConnectionError::MissingConnection(connection_id)) => { + HandlerError::ConnectionError(ConnectionError::MissingConnection(connection_id)) => { assert_eq!(connection_id, right_connection_id) } - ContextError::ConnectionError(ConnectionError::InsufficientConsensusHeight { + HandlerError::ConnectionError(ConnectionError::InsufficientConsensusHeight { target_height, current_height: _, }) => { assert_eq!(cons_state_height, target_height); } - ContextError::ConnectionError(ConnectionError::MismatchedConnectionStates { + HandlerError::ConnectionError(ConnectionError::MismatchedConnectionStates { expected: _, actual: _, }) => {} @@ -187,7 +187,7 @@ fn conn_open_ack_healthy() { #[test] fn conn_open_ack_no_connection() { let fxt = conn_open_ack_fixture(Ctx::New); - let expected_err = ContextError::ConnectionError(ConnectionError::MissingConnection( + let expected_err = HandlerError::ConnectionError(ConnectionError::MissingConnection( fxt.msg.conn_id_on_a.clone(), )); conn_open_ack_validate(&fxt, Expect::Failure(Some(expected_err))); @@ -197,7 +197,7 @@ fn conn_open_ack_no_connection() { fn conn_open_ack_invalid_consensus_height() { let fxt = conn_open_ack_fixture(Ctx::DefaultWithConnection); let expected_err = - ContextError::ConnectionError(ConnectionError::InsufficientConsensusHeight { + HandlerError::ConnectionError(ConnectionError::InsufficientConsensusHeight { target_height: fxt.msg.consensus_height_of_a_on_b, current_height: Height::new(0, 10).unwrap(), }); @@ -207,7 +207,7 @@ fn conn_open_ack_invalid_consensus_height() { #[test] fn conn_open_ack_connection_mismatch() { let fxt = conn_open_ack_fixture(Ctx::NewWithConnectionEndOpen); - let expected_err = ContextError::ConnectionError(ConnectionError::MismatchedConnectionStates { + let expected_err = HandlerError::ConnectionError(ConnectionError::MismatchedConnectionStates { expected: State::Init.to_string(), actual: State::Open.to_string(), }); diff --git a/tests-integration/tests/core/router.rs b/tests-integration/tests/core/router.rs index 303f5f469..52ef77d63 100644 --- a/tests-integration/tests/core/router.rs +++ b/tests-integration/tests/core/router.rs @@ -14,7 +14,7 @@ use ibc::core::client::types::msgs::{ClientMsg, MsgCreateClient, MsgUpdateClient use ibc::core::client::types::Height; use ibc::core::connection::types::msgs::ConnectionMsg; use ibc::core::entrypoint::dispatch; -use ibc::core::handler::types::error::ContextError; +use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::{IbcEvent, MessageEvent}; use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::ConnectionId; @@ -410,7 +410,7 @@ fn routing_module_and_keepers() { .map_err(|e: TokenTransferError| ChannelError::AppModule { description: e.to_string(), }) - .map_err(ContextError::from), + .map_err(HandlerError::from), }; assert_eq!( From d30ffaf7e0674c2f9dd11166df769308a9b87ff9 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 6 Sep 2024 09:28:18 -0500 Subject: [PATCH 054/107] Change `pick_version` impl --- .../ics03-connection/types/src/version.rs | 18 ++-- ibc-core/ics24-host/src/context.rs | 86 +++++++++++-------- 2 files changed, 59 insertions(+), 45 deletions(-) diff --git a/ibc-core/ics03-connection/types/src/version.rs b/ibc-core/ics03-connection/types/src/version.rs index ac8f9d975..2117325d5 100644 --- a/ibc-core/ics03-connection/types/src/version.rs +++ b/ibc-core/ics03-connection/types/src/version.rs @@ -117,15 +117,18 @@ impl Display for Version { /// counterparty. The returned version contains a feature set with the /// intersection of the features supported by the source and counterparty /// chains. If the feature set intersection is nil, the search for a -/// compatible version continues. This function is called in the `conn_open_try` -/// handshake procedure. +/// compatible version continues. If no feature set intersection is found +/// after searching through every supported version, then `None` is returned. /// -/// NOTE: Empty feature set is not currently allowed for a chosen version. +/// This function is called in the `conn_open_try` handshake procedure. +/// +/// NOTE: Empty feature sets are not currently allowed for a chosen version. pub fn pick_version( supported_versions: &[Version], counterparty_versions: &[Version], -) -> Result { +) -> Option { let mut intersection: Vec = Vec::new(); + for sv in supported_versions.iter() { if let Ok(cv) = find_supported_version(sv, counterparty_versions) { if let Ok(feature_set) = get_feature_set_intersection(&sv.features, &cv.features) { @@ -138,11 +141,12 @@ pub fn pick_version( } if intersection.is_empty() { - return Err(ConnectionError::MissingCommonVersion); + return None; } intersection.sort_by(|a, b| a.identifier.cmp(&b.identifier)); - Ok(intersection[0].clone()) + + Some(intersection[0].clone()) } /// Returns the version from the list of supported versions that matches the @@ -380,7 +384,7 @@ mod tests { assert_eq!( test.want_pass, - version.is_ok(), + version.is_some(), "Validate versions failed for test {}", test.name, ); diff --git a/ibc-core/ics24-host/src/context.rs b/ibc-core/ics24-host/src/context.rs index 30f100a33..877cbd535 100644 --- a/ibc-core/ics24-host/src/context.rs +++ b/ibc-core/ics24-host/src/context.rs @@ -29,29 +29,31 @@ pub trait ValidationContext { type HostClientState: ClientStateValidation; /// The consensus state type for the host chain. type HostConsensusState: ConsensusState; + /// The error type for the host chain. + type HostError: Into; /// Retrieve the context that implements all clients' `ValidationContext`. fn get_client_validation_context(&self) -> &Self::V; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the `ConsensusState` of the host (local) chain at a specific height. fn host_consensus_state( &self, height: &Height, - ) -> Result; + ) -> Result; /// Returns a natural number, counting how many clients have been created /// thus far. The value of this counter should increase only via method /// `ExecutionContext::increase_client_counter`. - fn client_counter(&self) -> Result; + fn client_counter(&self) -> Result; /// Returns the ConnectionEnd for the given identifier `conn_id`. - fn connection_end(&self, conn_id: &ConnectionId) -> Result; + fn connection_end(&self, conn_id: &ConnectionId) -> Result; /// Validates the `ClientState` of the host chain stored on the counterparty /// chain against the host's internal state. @@ -65,13 +67,13 @@ pub trait ValidationContext { fn validate_self_client( &self, client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Returns the prefix that the local chain uses in the KV store. fn commitment_prefix(&self) -> CommitmentPrefix; /// Returns a counter on how many connections have been created thus far. - fn connection_counter(&self) -> Result; + fn connection_counter(&self) -> Result; /// Function required by ICS-03. Returns the list of all possible versions that the connection /// handshake protocol supports. @@ -84,47 +86,55 @@ pub trait ValidationContext { fn pick_version( &self, counterparty_candidate_versions: &[ConnectionVersion], - ) -> Result { - let version = pick_version( + ) -> Result { + match pick_version( &self.get_compatible_versions(), counterparty_candidate_versions, - )?; - Ok(version) + ) { + Some(version) => Ok(version), + None => Err(Self::HostError), + } } /// Returns the `ChannelEnd` for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; + fn channel_end(&self, channel_end_path: &ChannelEndPath) + -> Result; /// Returns the sequence number for the next packet to be sent for the given store path - fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) - -> Result; + fn get_next_sequence_send( + &self, + seq_send_path: &SeqSendPath, + ) -> Result; /// Returns the sequence number for the next packet to be received for the given store path - fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) - -> Result; + fn get_next_sequence_recv( + &self, + seq_recv_path: &SeqRecvPath, + ) -> Result; /// Returns the sequence number for the next packet to be acknowledged for the given store path - fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result; + fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) + -> Result; /// Returns the packet commitment for the given store path fn get_packet_commitment( &self, commitment_path: &CommitmentPath, - ) -> Result; + ) -> Result; /// Returns the packet receipt for the given store path - fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result; + fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result; /// Returns the packet acknowledgement for the given store path fn get_packet_acknowledgement( &self, ack_path: &AckPath, - ) -> Result; + ) -> Result; /// Returns a counter on the number of channel ids have been created thus far. /// The value of this counter should increase only via method /// `ExecutionContext::increase_channel_counter`. - fn channel_counter(&self) -> Result; + fn channel_counter(&self) -> Result; /// Returns the maximum expected time per block fn max_expected_time_per_block(&self) -> Duration; @@ -137,7 +147,7 @@ pub trait ValidationContext { /// Validates the `signer` field of IBC messages, which represents the address /// of the user/relayer that signed the given message. - fn validate_message_signer(&self, signer: &Signer) -> Result<(), HandlerError>; + fn validate_message_signer(&self, signer: &Signer) -> Result<(), Self::HostError>; } /// Context to be implemented by the host that provides all "write-only" methods. @@ -151,93 +161,93 @@ pub trait ExecutionContext: ValidationContext { /// Called upon client creation. /// Increases the counter, that keeps track of how many clients have been created. - fn increase_client_counter(&mut self) -> Result<(), HandlerError>; + fn increase_client_counter(&mut self) -> Result<(), Self::HostError>; /// Stores the given connection_end at path fn store_connection( &mut self, connection_path: &ConnectionPath, connection_end: ConnectionEnd, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Stores the given connection_id at a path associated with the client_id. fn store_connection_to_client( &mut self, client_connection_path: &ClientConnectionPath, conn_id: ConnectionId, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Called upon connection identifier creation (Init or Try process). /// Increases the counter which keeps track of how many connections have been created. - fn increase_connection_counter(&mut self) -> Result<(), HandlerError>; + fn increase_connection_counter(&mut self) -> Result<(), Self::HostError>; /// Stores the given packet commitment at the given store path fn store_packet_commitment( &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Deletes the packet commitment at the given store path fn delete_packet_commitment( &mut self, commitment_path: &CommitmentPath, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Stores the given packet receipt at the given store path fn store_packet_receipt( &mut self, receipt_path: &ReceiptPath, receipt: Receipt, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Stores the given packet acknowledgement at the given store path fn store_packet_acknowledgement( &mut self, ack_path: &AckPath, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Deletes the packet acknowledgement at the given store path - fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HandlerError>; + fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), Self::HostError>; /// Stores the given channel_end at a path associated with the port_id and channel_id. fn store_channel( &mut self, channel_end_path: &ChannelEndPath, channel_end: ChannelEnd, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Stores the given `nextSequenceSend` number at the given store path fn store_next_sequence_send( &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Stores the given `nextSequenceRecv` number at the given store path fn store_next_sequence_recv( &mut self, seq_recv_path: &SeqRecvPath, seq: Sequence, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Stores the given `nextSequenceAck` number at the given store path fn store_next_sequence_ack( &mut self, seq_ack_path: &SeqAckPath, seq: Sequence, - ) -> Result<(), HandlerError>; + ) -> Result<(), Self::HostError>; /// Called upon channel identifier creation (Init or Try message processing). /// Increases the counter, that keeps track of how many channels have been created. - fn increase_channel_counter(&mut self) -> Result<(), HandlerError>; + fn increase_channel_counter(&mut self) -> Result<(), Self::HostError>; /// Emit the given IBC event - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError>; + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), Self::HostError>; /// Log the given message. - fn log_message(&mut self, message: String) -> Result<(), HandlerError>; + fn log_message(&mut self, message: String) -> Result<(), Self::HostError>; } /// Convenient type alias for `ClientStateRef`, providing access to client From 61f5645d4f0cb377450441ad2777485b3ae54b1f Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 9 Sep 2024 09:53:18 -0500 Subject: [PATCH 055/107] Update ValidationContext trait methods to return HostError type --- .../ics03-connection/types/src/version.rs | 8 +- ibc-core/ics24-host/src/context.rs | 91 ++++++++----------- 2 files changed, 43 insertions(+), 56 deletions(-) diff --git a/ibc-core/ics03-connection/types/src/version.rs b/ibc-core/ics03-connection/types/src/version.rs index 2117325d5..2a2db6fcf 100644 --- a/ibc-core/ics03-connection/types/src/version.rs +++ b/ibc-core/ics03-connection/types/src/version.rs @@ -126,7 +126,7 @@ impl Display for Version { pub fn pick_version( supported_versions: &[Version], counterparty_versions: &[Version], -) -> Option { +) -> Result { let mut intersection: Vec = Vec::new(); for sv in supported_versions.iter() { @@ -141,12 +141,12 @@ pub fn pick_version( } if intersection.is_empty() { - return None; + return Err(ConnectionError::MissingCommonVersion); } intersection.sort_by(|a, b| a.identifier.cmp(&b.identifier)); - Some(intersection[0].clone()) + Ok(intersection[0].clone()) } /// Returns the version from the list of supported versions that matches the @@ -384,7 +384,7 @@ mod tests { assert_eq!( test.want_pass, - version.is_some(), + version.is_ok(), "Validate versions failed for test {}", test.name, ); diff --git a/ibc-core/ics24-host/src/context.rs b/ibc-core/ics24-host/src/context.rs index 877cbd535..6ef0822b9 100644 --- a/ibc-core/ics24-host/src/context.rs +++ b/ibc-core/ics24-host/src/context.rs @@ -8,8 +8,8 @@ use ibc_core_client_types::Height; use ibc_core_commitment_types::commitment::CommitmentPrefix; use ibc_core_connection_types::version::{pick_version, Version as ConnectionVersion}; use ibc_core_connection_types::ConnectionEnd; -use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::IbcEvent; +use ibc_core_host_types::error::HostError; use ibc_core_host_types::identifiers::{ConnectionId, Sequence}; use ibc_core_host_types::path::{ AckPath, ChannelEndPath, ClientConnectionPath, CommitmentPath, ConnectionPath, ReceiptPath, @@ -29,31 +29,26 @@ pub trait ValidationContext { type HostClientState: ClientStateValidation; /// The consensus state type for the host chain. type HostConsensusState: ConsensusState; - /// The error type for the host chain. - type HostError: Into; /// Retrieve the context that implements all clients' `ValidationContext`. fn get_client_validation_context(&self) -> &Self::V; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the `ConsensusState` of the host (local) chain at a specific height. - fn host_consensus_state( - &self, - height: &Height, - ) -> Result; + fn host_consensus_state(&self, height: &Height) -> Result; /// Returns a natural number, counting how many clients have been created /// thus far. The value of this counter should increase only via method /// `ExecutionContext::increase_client_counter`. - fn client_counter(&self) -> Result; + fn client_counter(&self) -> Result; /// Returns the ConnectionEnd for the given identifier `conn_id`. - fn connection_end(&self, conn_id: &ConnectionId) -> Result; + fn connection_end(&self, conn_id: &ConnectionId) -> Result; /// Validates the `ClientState` of the host chain stored on the counterparty /// chain against the host's internal state. @@ -67,13 +62,13 @@ pub trait ValidationContext { fn validate_self_client( &self, client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Returns the prefix that the local chain uses in the KV store. fn commitment_prefix(&self) -> CommitmentPrefix; /// Returns a counter on how many connections have been created thus far. - fn connection_counter(&self) -> Result; + fn connection_counter(&self) -> Result; /// Function required by ICS-03. Returns the list of all possible versions that the connection /// handshake protocol supports. @@ -86,55 +81,47 @@ pub trait ValidationContext { fn pick_version( &self, counterparty_candidate_versions: &[ConnectionVersion], - ) -> Result { - match pick_version( + ) -> Result { + pick_version( &self.get_compatible_versions(), counterparty_candidate_versions, - ) { - Some(version) => Ok(version), - None => Err(Self::HostError), - } + ) + .map_err(|e| HostError::MissingData { + description: e.to_string(), + }) } /// Returns the `ChannelEnd` for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) - -> Result; + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; /// Returns the sequence number for the next packet to be sent for the given store path - fn get_next_sequence_send( - &self, - seq_send_path: &SeqSendPath, - ) -> Result; + fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result; /// Returns the sequence number for the next packet to be received for the given store path - fn get_next_sequence_recv( - &self, - seq_recv_path: &SeqRecvPath, - ) -> Result; + fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) -> Result; /// Returns the sequence number for the next packet to be acknowledged for the given store path - fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) - -> Result; + fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result; /// Returns the packet commitment for the given store path fn get_packet_commitment( &self, commitment_path: &CommitmentPath, - ) -> Result; + ) -> Result; /// Returns the packet receipt for the given store path - fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result; + fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result; /// Returns the packet acknowledgement for the given store path fn get_packet_acknowledgement( &self, ack_path: &AckPath, - ) -> Result; + ) -> Result; /// Returns a counter on the number of channel ids have been created thus far. /// The value of this counter should increase only via method /// `ExecutionContext::increase_channel_counter`. - fn channel_counter(&self) -> Result; + fn channel_counter(&self) -> Result; /// Returns the maximum expected time per block fn max_expected_time_per_block(&self) -> Duration; @@ -147,7 +134,7 @@ pub trait ValidationContext { /// Validates the `signer` field of IBC messages, which represents the address /// of the user/relayer that signed the given message. - fn validate_message_signer(&self, signer: &Signer) -> Result<(), Self::HostError>; + fn validate_message_signer(&self, signer: &Signer) -> Result<(), HostError>; } /// Context to be implemented by the host that provides all "write-only" methods. @@ -161,93 +148,93 @@ pub trait ExecutionContext: ValidationContext { /// Called upon client creation. /// Increases the counter, that keeps track of how many clients have been created. - fn increase_client_counter(&mut self) -> Result<(), Self::HostError>; + fn increase_client_counter(&mut self) -> Result<(), HostError>; /// Stores the given connection_end at path fn store_connection( &mut self, connection_path: &ConnectionPath, connection_end: ConnectionEnd, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Stores the given connection_id at a path associated with the client_id. fn store_connection_to_client( &mut self, client_connection_path: &ClientConnectionPath, conn_id: ConnectionId, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Called upon connection identifier creation (Init or Try process). /// Increases the counter which keeps track of how many connections have been created. - fn increase_connection_counter(&mut self) -> Result<(), Self::HostError>; + fn increase_connection_counter(&mut self) -> Result<(), HostError>; /// Stores the given packet commitment at the given store path fn store_packet_commitment( &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Deletes the packet commitment at the given store path fn delete_packet_commitment( &mut self, commitment_path: &CommitmentPath, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Stores the given packet receipt at the given store path fn store_packet_receipt( &mut self, receipt_path: &ReceiptPath, receipt: Receipt, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Stores the given packet acknowledgement at the given store path fn store_packet_acknowledgement( &mut self, ack_path: &AckPath, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Deletes the packet acknowledgement at the given store path - fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), Self::HostError>; + fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HostError>; /// Stores the given channel_end at a path associated with the port_id and channel_id. fn store_channel( &mut self, channel_end_path: &ChannelEndPath, channel_end: ChannelEnd, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Stores the given `nextSequenceSend` number at the given store path fn store_next_sequence_send( &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Stores the given `nextSequenceRecv` number at the given store path fn store_next_sequence_recv( &mut self, seq_recv_path: &SeqRecvPath, seq: Sequence, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Stores the given `nextSequenceAck` number at the given store path fn store_next_sequence_ack( &mut self, seq_ack_path: &SeqAckPath, seq: Sequence, - ) -> Result<(), Self::HostError>; + ) -> Result<(), HostError>; /// Called upon channel identifier creation (Init or Try message processing). /// Increases the counter, that keeps track of how many channels have been created. - fn increase_channel_counter(&mut self) -> Result<(), Self::HostError>; + fn increase_channel_counter(&mut self) -> Result<(), HostError>; /// Emit the given IBC event - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), Self::HostError>; + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HostError>; /// Log the given message. - fn log_message(&mut self, message: String) -> Result<(), Self::HostError>; + fn log_message(&mut self, message: String) -> Result<(), HostError>; } /// Convenient type alias for `ClientStateRef`, providing access to client From 2ef5b66b33a5032f536b03348bbbef39e50b6178 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 9 Sep 2024 09:59:06 -0500 Subject: [PATCH 056/107] Rename HandlerError variants throughout the code base --- ibc-core/ics03-connection/src/delay.rs | 4 ++-- ibc-core/ics03-connection/src/handler/mod.rs | 2 +- .../src/handler/acknowledgement.rs | 2 +- .../src/handler/chan_close_confirm.rs | 2 +- .../src/handler/chan_close_init.rs | 2 +- .../src/handler/chan_open_confirm.rs | 2 +- .../ics04-channel/src/handler/recv_packet.rs | 4 ++-- .../ics04-channel/src/handler/send_packet.rs | 2 +- ibc-core/ics04-channel/src/handler/timeout.rs | 4 ++-- .../src/handler/timeout_on_close.rs | 2 +- .../cosmos/src/validate_self_client.rs | 14 +++++++------- ibc-core/ics25-handler/types/src/error.rs | 2 +- ibc-query/src/error.rs | 8 ++++---- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 4 ++-- .../tests/core/ics02_client/create_client.rs | 18 +++++++++--------- .../tests/core/ics02_client/upgrade_client.rs | 4 ++-- .../core/ics03_connection/conn_open_ack.rs | 19 +++++++++---------- 17 files changed, 47 insertions(+), 48 deletions(-) diff --git a/ibc-core/ics03-connection/src/delay.rs b/ibc-core/ics03-connection/src/delay.rs index aed025930..b2c51158a 100644 --- a/ibc-core/ics03-connection/src/delay.rs +++ b/ibc-core/ics03-connection/src/delay.rs @@ -31,7 +31,7 @@ where let earliest_valid_time = (last_client_update.0 + conn_delay_time_period) .map_err(ConnectionError::OverflowedTimestamp)?; if current_host_time < earliest_valid_time { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InsufficientTimeElapsed { current_host_time, earliest_valid_time, @@ -42,7 +42,7 @@ where // Verify that the current host chain height is later than the last client update height let earliest_valid_height = last_client_update.1.add(conn_delay_height_period); if current_host_height < earliest_valid_height { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InsufficientBlocksElapsed { current_host_height, earliest_valid_height, diff --git a/ibc-core/ics03-connection/src/handler/mod.rs b/ibc-core/ics03-connection/src/handler/mod.rs index e023f9623..8026db244 100644 --- a/ibc-core/ics03-connection/src/handler/mod.rs +++ b/ibc-core/ics03-connection/src/handler/mod.rs @@ -31,7 +31,7 @@ where use prost::Message; let wasm_client_state = WasmClientState::try_from(value).map_err(|e| { - HandlerError::ConnectionError(ConnectionError::InvalidClientState { + HandlerError::Connection(ConnectionError::InvalidClientState { description: e.to_string(), }) })?; diff --git a/ibc-core/ics04-channel/src/handler/acknowledgement.rs b/ibc-core/ics04-channel/src/handler/acknowledgement.rs index 1224b9ff1..4c7b1c30e 100644 --- a/ibc-core/ics04-channel/src/handler/acknowledgement.rs +++ b/ibc-core/ics04-channel/src/handler/acknowledgement.rs @@ -27,7 +27,7 @@ where module .on_acknowledgement_packet_validate(&msg.packet, &msg.acknowledgement, &msg.signer) - .map_err(HandlerError::PacketError) + .map_err(HandlerError::Packet) } pub fn acknowledgement_packet_execute( diff --git a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs index a37e9639d..19b1f2697 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs @@ -59,7 +59,7 @@ where let core_event = { let port_id_on_a = chan_end_on_b.counterparty().port_id.clone(); let chan_id_on_a = chan_end_on_b.counterparty().channel_id.clone().ok_or( - HandlerError::ChannelError(ChannelError::MissingCounterparty), + HandlerError::Channel(ChannelError::MissingCounterparty), )?; let conn_id_on_b = chan_end_on_b.connection_hops[0].clone(); diff --git a/ibc-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-core/ics04-channel/src/handler/chan_close_init.rs index 3dc0b5b10..97912774b 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_init.rs @@ -57,7 +57,7 @@ where let core_event = { let port_id_on_b = chan_end_on_a.counterparty().port_id.clone(); let chan_id_on_b = chan_end_on_a.counterparty().channel_id.clone().ok_or( - HandlerError::ChannelError(ChannelError::MissingCounterparty), + HandlerError::Channel(ChannelError::MissingCounterparty), )?; let conn_id_on_a = chan_end_on_a.connection_hops[0].clone(); diff --git a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs index 451a6e222..b246008cf 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs @@ -64,7 +64,7 @@ where .counterparty() .channel_id .clone() - .ok_or(HandlerError::ChannelError( + .ok_or(HandlerError::Channel( ChannelError::MissingCounterparty, ))?; diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index 684502f9c..b03e2e52f 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -252,7 +252,7 @@ where let packet_rec = ctx_b.get_packet_receipt(&receipt_path_on_b); match packet_rec { Ok(_receipt) => {} - Err(HandlerError::PacketError(PacketError::MissingPacketReceipt(sequence))) + Err(HandlerError::Packet(PacketError::MissingPacketReceipt(sequence))) if sequence == msg.packet.seq_on_a => {} Err(e) => return Err(e), } @@ -261,7 +261,7 @@ where validate_write_acknowledgement(ctx_b, msg)?; } Order::None => { - return Err(HandlerError::ChannelError(ChannelError::InvalidOrderType { + return Err(HandlerError::Channel(ChannelError::InvalidOrderType { expected: "Channel ordering cannot be None".to_string(), actual: chan_end_on_b.ordering.to_string(), })) diff --git a/ibc-core/ics04-channel/src/handler/send_packet.rs b/ibc-core/ics04-channel/src/handler/send_packet.rs index 157203643..c15b03d21 100644 --- a/ibc-core/ics04-channel/src/handler/send_packet.rs +++ b/ibc-core/ics04-channel/src/handler/send_packet.rs @@ -30,7 +30,7 @@ pub fn send_packet_validate( packet: &Packet, ) -> Result<(), HandlerError> { if !packet.timeout_height_on_b.is_set() && !packet.timeout_timestamp_on_b.is_set() { - return Err(HandlerError::PacketError(PacketError::MissingTimeout)); + return Err(HandlerError::Packet(PacketError::MissingTimeout)); } let chan_end_path_on_a = ChannelEndPath::new(&packet.port_id_on_a, &packet.chan_id_on_a); diff --git a/ibc-core/ics04-channel/src/handler/timeout.rs b/ibc-core/ics04-channel/src/handler/timeout.rs index 9d122854b..9e587256d 100644 --- a/ibc-core/ics04-channel/src/handler/timeout.rs +++ b/ibc-core/ics04-channel/src/handler/timeout.rs @@ -41,7 +41,7 @@ where module .on_timeout_packet_validate(&packet, &signer) - .map_err(HandlerError::PacketError) + .map_err(HandlerError::Packet) } pub fn timeout_packet_execute( @@ -247,7 +247,7 @@ where ) } Order::None => { - return Err(HandlerError::ChannelError(ChannelError::InvalidOrderType { + return Err(HandlerError::Channel(ChannelError::InvalidOrderType { expected: "Channel ordering cannot be None".to_string(), actual: chan_end_on_a.ordering.to_string(), })) diff --git a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs index e1a0b94fb..e6bd30724 100644 --- a/ibc-core/ics04-channel/src/handler/timeout_on_close.rs +++ b/ibc-core/ics04-channel/src/handler/timeout_on_close.rs @@ -155,7 +155,7 @@ where ) } Order::None => { - return Err(HandlerError::ChannelError(ChannelError::InvalidOrderType { + return Err(HandlerError::Channel(ChannelError::InvalidOrderType { expected: "Channel ordering cannot be None".to_string(), actual: chan_end_on_a.ordering.to_string(), })) diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index 51c1595e3..ff870c051 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -30,7 +30,7 @@ pub trait ValidateSelfClientContext { let self_chain_id = self.chain_id(); if self_chain_id != &client_state_of_host_on_counterparty.chain_id { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "invalid chain-id. expected: {}, got: {}", @@ -43,7 +43,7 @@ pub trait ValidateSelfClientContext { let latest_height = client_state_of_host_on_counterparty.latest_height; let self_revision_number = self_chain_id.revision_number(); if self_revision_number != latest_height.revision_number() { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "client is not in the same revision as the chain. expected: {}, got: {}", @@ -55,7 +55,7 @@ pub trait ValidateSelfClientContext { } if latest_height >= self.host_current_height() { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "client has latest height {} greater than or equal to chain height {}", @@ -67,7 +67,7 @@ pub trait ValidateSelfClientContext { } if self.proof_specs() != &client_state_of_host_on_counterparty.proof_specs { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "client has invalid proof specs. expected: {:?}, got: {:?}", @@ -91,7 +91,7 @@ pub trait ValidateSelfClientContext { }; if self.unbonding_period() != client_state_of_host_on_counterparty.unbonding_period { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "invalid unbonding period. expected: {:?}, got: {:?}", @@ -105,7 +105,7 @@ pub trait ValidateSelfClientContext { if client_state_of_host_on_counterparty.unbonding_period < client_state_of_host_on_counterparty.trusting_period { - return Err(HandlerError::ConnectionError(ConnectionError::InvalidClientState{ description: format!( + return Err(HandlerError::Connection(ConnectionError::InvalidClientState{ description: format!( "unbonding period must be greater than trusting period. unbonding period ({:?}) < trusting period ({:?})", client_state_of_host_on_counterparty.unbonding_period, client_state_of_host_on_counterparty.trusting_period @@ -115,7 +115,7 @@ pub trait ValidateSelfClientContext { if !client_state_of_host_on_counterparty.upgrade_path.is_empty() && self.upgrade_path() != client_state_of_host_on_counterparty.upgrade_path { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "invalid upgrade path. expected: {:?}, got: {:?}", diff --git a/ibc-core/ics25-handler/types/src/error.rs b/ibc-core/ics25-handler/types/src/error.rs index 1544170f2..bc93d11f4 100644 --- a/ibc-core/ics25-handler/types/src/error.rs +++ b/ibc-core/ics25-handler/types/src/error.rs @@ -1,4 +1,4 @@ -//! Defines the context error type +//! Defines the handler error type use derive_more::From; use displaydoc::Display; diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index 91eeb70a7..d2bd46af5 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -52,25 +52,25 @@ impl From for QueryError { impl From for QueryError { fn from(e: ClientError) -> Self { - Self::HandlerError(HandlerError::ClientError(e)) + Self::HandlerError(HandlerError::Client(e)) } } impl From for QueryError { fn from(e: ConnectionError) -> Self { - Self::HandlerError(HandlerError::ConnectionError(e)) + Self::HandlerError(HandlerError::Connection(e)) } } impl From for QueryError { fn from(e: ChannelError) -> Self { - Self::HandlerError(HandlerError::ChannelError(e)) + Self::HandlerError(HandlerError::Channel(e)) } } impl From for QueryError { fn from(e: PacketError) -> Self { - Self::HandlerError(HandlerError::PacketError(e)) + Self::HandlerError(HandlerError::Packet(e)) } } diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 0b71426a7..e03f4f91d 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -91,7 +91,7 @@ where .latest_height() .revision_number() { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "client is not in the same revision as the chain. expected: {}, got: {}", @@ -106,7 +106,7 @@ where let host_current_height = latest_height.increment(); if client_state_of_host_on_counterparty.latest_height() >= host_current_height { - return Err(HandlerError::ConnectionError( + return Err(HandlerError::Connection( ConnectionError::InvalidClientState { description: format!( "client has latest height {} greater than or equal to chain height {}", diff --git a/tests-integration/tests/core/ics02_client/create_client.rs b/tests-integration/tests/core/ics02_client/create_client.rs index ad91c58b7..baa9188c0 100644 --- a/tests-integration/tests/core/ics02_client/create_client.rs +++ b/tests-integration/tests/core/ics02_client/create_client.rs @@ -180,9 +180,9 @@ fn test_create_expired_mock_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredMockHeader); create_client_validate( &fxt, - Expect::Failure(Some(HandlerError::ClientError( - ClientError::UnexpectedStatus(Status::Expired), - ))), + Expect::Failure(Some(HandlerError::Client(ClientError::UnexpectedStatus( + Status::Expired, + )))), ); } @@ -206,9 +206,9 @@ fn test_create_expired_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::ExpiredTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(HandlerError::ClientError( - ClientError::UnexpectedStatus(Status::Expired), - ))), + Expect::Failure(Some(HandlerError::Client(ClientError::UnexpectedStatus( + Status::Expired, + )))), ); } @@ -218,9 +218,9 @@ fn test_create_frozen_tm_client() { let fxt = create_client_fixture(Ctx::Default, Msg::FrozenTendermintHeader); create_client_validate( &fxt, - Expect::Failure(Some(HandlerError::ClientError( - ClientError::UnexpectedStatus(Status::Frozen), - ))), + Expect::Failure(Some(HandlerError::Client(ClientError::UnexpectedStatus( + Status::Frozen, + )))), ); } diff --git a/tests-integration/tests/core/ics02_client/upgrade_client.rs b/tests-integration/tests/core/ics02_client/upgrade_client.rs index 34706ae2e..8f44f3e1c 100644 --- a/tests-integration/tests/core/ics02_client/upgrade_client.rs +++ b/tests-integration/tests/core/ics02_client/upgrade_client.rs @@ -143,7 +143,7 @@ fn msg_upgrade_client_healthy() { fn upgrade_client_fail_nonexisting_client() { let fxt = msg_upgrade_client_fixture(Ctx::Default, Msg::Default); let expected_err = - HandlerError::ClientError(ClientError::MissingClientState(fxt.msg.client_id.clone())); + HandlerError::Client(ClientError::MissingClientState(fxt.msg.client_id.clone())); upgrade_client_validate(&fxt, Expect::Failure(Some(expected_err))); } @@ -165,7 +165,7 @@ fn upgrade_client_fail_low_upgrade_height() { #[test] fn upgrade_client_fail_unknown_upgraded_client_state() { let fxt = msg_upgrade_client_fixture(Ctx::WithClient, Msg::UnknownUpgradedClientStateType); - let expected_err = HandlerError::ClientError(ClientError::InvalidClientStateType( + let expected_err = HandlerError::Client(ClientError::InvalidClientStateType( client_type().to_string(), )); upgrade_client_validate(&fxt, Expect::Failure(Some(expected_err))); diff --git a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs index 8f09a2fb7..7f7b8662f 100644 --- a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs +++ b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs @@ -126,16 +126,16 @@ fn conn_open_ack_validate(fxt: &Fixture, expect: Expect) { let cons_state_height = fxt.msg.consensus_height_of_a_on_b; match res.unwrap_err() { - HandlerError::ConnectionError(ConnectionError::MissingConnection(connection_id)) => { + HandlerError::Connection(ConnectionError::MissingConnection(connection_id)) => { assert_eq!(connection_id, right_connection_id) } - HandlerError::ConnectionError(ConnectionError::InsufficientConsensusHeight { + HandlerError::Connection(ConnectionError::InsufficientConsensusHeight { target_height, current_height: _, }) => { assert_eq!(cons_state_height, target_height); } - HandlerError::ConnectionError(ConnectionError::MismatchedConnectionStates { + HandlerError::Connection(ConnectionError::MismatchedConnectionStates { expected: _, actual: _, }) => {} @@ -187,7 +187,7 @@ fn conn_open_ack_healthy() { #[test] fn conn_open_ack_no_connection() { let fxt = conn_open_ack_fixture(Ctx::New); - let expected_err = HandlerError::ConnectionError(ConnectionError::MissingConnection( + let expected_err = HandlerError::Connection(ConnectionError::MissingConnection( fxt.msg.conn_id_on_a.clone(), )); conn_open_ack_validate(&fxt, Expect::Failure(Some(expected_err))); @@ -196,18 +196,17 @@ fn conn_open_ack_no_connection() { #[test] fn conn_open_ack_invalid_consensus_height() { let fxt = conn_open_ack_fixture(Ctx::DefaultWithConnection); - let expected_err = - HandlerError::ConnectionError(ConnectionError::InsufficientConsensusHeight { - target_height: fxt.msg.consensus_height_of_a_on_b, - current_height: Height::new(0, 10).unwrap(), - }); + let expected_err = HandlerError::Connection(ConnectionError::InsufficientConsensusHeight { + target_height: fxt.msg.consensus_height_of_a_on_b, + current_height: Height::new(0, 10).unwrap(), + }); conn_open_ack_validate(&fxt, Expect::Failure(Some(expected_err))); } #[test] fn conn_open_ack_connection_mismatch() { let fxt = conn_open_ack_fixture(Ctx::NewWithConnectionEndOpen); - let expected_err = HandlerError::ConnectionError(ConnectionError::MismatchedConnectionStates { + let expected_err = HandlerError::Connection(ConnectionError::MismatchedConnectionStates { expected: State::Init.to_string(), actual: State::Open.to_string(), }); From cec5f79ca96e2e9dc6d87849bf39cdef5e846044 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 9 Sep 2024 10:34:04 -0500 Subject: [PATCH 057/107] Remove match arm that is no longer relevant --- ibc-core/ics04-channel/src/handler/recv_packet.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index b03e2e52f..f920662b6 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -252,9 +252,7 @@ where let packet_rec = ctx_b.get_packet_receipt(&receipt_path_on_b); match packet_rec { Ok(_receipt) => {} - Err(HandlerError::Packet(PacketError::MissingPacketReceipt(sequence))) - if sequence == msg.packet.seq_on_a => {} - Err(e) => return Err(e), + Err(e) => return Err(e)?, } // Case where the recvPacket is successful and an // acknowledgement will be written (not a no-op) From fa2a7cd2e12001b9f1f9bea7663b75fb16277fe0 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 9 Sep 2024 10:45:13 -0500 Subject: [PATCH 058/107] Change ClientValidationContext trait methods to return HostErrors --- ...010-enable-standalone-ics02-integration.md | 2 +- ibc-core/ics02-client/context/src/context.rs | 34 ++++++++----------- .../ics04-channel/src/handler/recv_packet.rs | 2 +- .../testapp/ibc/clients/mock/client_state.rs | 2 +- .../src/testapp/ibc/core/client_ctx.rs | 4 +-- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 2 +- 6 files changed, 21 insertions(+), 25 deletions(-) diff --git a/docs/architecture/adr-010-enable-standalone-ics02-integration.md b/docs/architecture/adr-010-enable-standalone-ics02-integration.md index 7cb9782a0..a0a8fb7fc 100644 --- a/docs/architecture/adr-010-enable-standalone-ics02-integration.md +++ b/docs/architecture/adr-010-enable-standalone-ics02-integration.md @@ -308,7 +308,7 @@ pub trait ExtClientValidationContext: + fn host_timestamp(&self) -> Result; -+ fn host_height(&self) -> Result; ++ fn host_height(&self) -> Result; - fn consensus_state( - &self, diff --git a/ibc-core/ics02-client/context/src/context.rs b/ibc-core/ics02-client/context/src/context.rs index a13e9a4b7..e9a47bf0d 100644 --- a/ibc-core/ics02-client/context/src/context.rs +++ b/ibc-core/ics02-client/context/src/context.rs @@ -1,5 +1,5 @@ use ibc_core_client_types::Height; -use ibc_core_handler_types::error::HandlerError; +use ibc_core_host_types::error::HostError; use ibc_core_host_types::identifiers::ClientId; use ibc_core_host_types::path::{ClientConsensusStatePath, ClientStatePath}; use ibc_primitives::prelude::*; @@ -19,7 +19,7 @@ pub trait ClientValidationContext: Sized { /// Returns the ClientState for the given identifier `client_id`. /// /// Note: Clients have the responsibility to store client states on client creation and update. - fn client_state(&self, client_id: &ClientId) -> Result; + fn client_state(&self, client_id: &ClientId) -> Result; /// Retrieve the consensus state for the given client ID at the specified /// height. @@ -30,7 +30,7 @@ pub trait ClientValidationContext: Sized { fn consensus_state( &self, client_cons_state_path: &ClientConsensusStatePath, - ) -> Result; + ) -> Result; /// Returns the timestamp and height of the host when it processed a client /// update request at the specified height. @@ -38,7 +38,7 @@ pub trait ClientValidationContext: Sized { &self, client_id: &ClientId, height: &Height, - ) -> Result<(Timestamp, Height), HandlerError>; + ) -> Result<(Timestamp, Height), HostError>; } /// Defines the methods that all client `ExecutionContext`s (precisely the @@ -54,7 +54,7 @@ pub trait ClientExecutionContext: { type ClientStateMut: ClientStateExecution; - fn client_state_mut(&self, client_id: &ClientId) -> Result { + fn client_state_mut(&self, client_id: &ClientId) -> Result { self.client_state(client_id) } @@ -63,20 +63,20 @@ pub trait ClientExecutionContext: &mut self, client_state_path: ClientStatePath, client_state: Self::ClientStateRef, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; /// Called upon successful client creation and update fn store_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Self::ConsensusStateRef, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; /// Delete the consensus state from the store located at the given `ClientConsensusStatePath` fn delete_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; /// Called upon successful client update. /// @@ -88,7 +88,7 @@ pub trait ClientExecutionContext: height: Height, host_timestamp: Timestamp, host_height: Height, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; /// Delete the update time and height associated with the client at the /// specified height. @@ -97,11 +97,7 @@ pub trait ClientExecutionContext: /// specified height. /// /// Note that this timestamp is determined by the host. - fn delete_update_meta( - &mut self, - client_id: ClientId, - height: Height, - ) -> Result<(), HandlerError>; + fn delete_update_meta(&mut self, client_id: ClientId, height: Height) -> Result<(), HostError>; } /// An optional trait that extends the client validation context capabilities by @@ -115,27 +111,27 @@ pub trait ClientExecutionContext: /// specific light client requirements. pub trait ExtClientValidationContext: ClientValidationContext { /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; /// Returns all the heights at which a consensus state is stored. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError>; + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HostError>; /// Search for the lowest consensus state higher than `height`. fn next_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, HandlerError>; + ) -> Result, HostError>; /// Search for the highest consensus state lower than `height`. fn prev_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, HandlerError>; + ) -> Result, HostError>; } /// An optional trait that extends the client context required during execution. diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index f920662b6..a7845e86f 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -260,7 +260,7 @@ where } Order::None => { return Err(HandlerError::Channel(ChannelError::InvalidOrderType { - expected: "Channel ordering cannot be None".to_string(), + expected: "Channel ordering to not be None".to_string(), actual: chan_end_on_b.ordering.to_string(), })) } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index c62735bca..054be94c6 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -158,7 +158,7 @@ pub trait MockClientContext { fn host_timestamp(&self) -> Result; /// Returns the current height of the local chain. - fn host_height(&self) -> Result; + fn host_height(&self) -> Result; } impl ClientStateCommon for MockClientState { diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index f7927d5bb..0936dd12c 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -41,7 +41,7 @@ where ValidationContext::host_timestamp(self) } - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { ValidationContext::host_height(self) } } @@ -54,7 +54,7 @@ where ValidationContext::host_timestamp(self) } - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { ValidationContext::host_height(self) } diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index e03f4f91d..b2a01b5f7 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -42,7 +42,7 @@ where type HostClientState = AnyClientState; type HostConsensusState = AnyConsensusState; - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { Ok(Height::new( *self.revision_number.lock(), self.store.current_height(), From 27a823300cf4b8f7b631cc6135b2eb7d9d164afd Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 9 Sep 2024 11:49:24 -0500 Subject: [PATCH 059/107] Change TokenTransferValidationContext and NftTransferValidationContext trait error types --- ibc-apps/ics20-transfer/src/context.rs | 23 ++--- ibc-apps/ics20-transfer/types/src/error.rs | 8 +- ibc-apps/ics721-nft-transfer/src/context.rs | 32 +++---- .../ics721-nft-transfer/types/src/error.rs | 6 +- .../src/client_state/validation.rs | 1 + ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 94 ++++++++----------- 6 files changed, 77 insertions(+), 87 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/context.rs b/ibc-apps/ics20-transfer/src/context.rs index 8c22ad386..eb39686d2 100644 --- a/ibc-apps/ics20-transfer/src/context.rs +++ b/ibc-apps/ics20-transfer/src/context.rs @@ -2,6 +2,7 @@ use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::{Memo, PrefixedCoin, PrefixedDenom}; +use ibc_core::host::types::error::HostError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use ibc_core::primitives::Signer; @@ -11,13 +12,13 @@ pub trait TokenTransferValidationContext { type AccountId: TryFrom; /// get_port returns the portID for the transfer module. - fn get_port(&self) -> Result; + fn get_port(&self) -> Result; /// Returns Ok() if the host chain supports sending coins. - fn can_send_coins(&self) -> Result<(), TokenTransferError>; + fn can_send_coins(&self) -> Result<(), HostError>; /// Returns Ok() if the host chain supports receiving coins. - fn can_receive_coins(&self) -> Result<(), TokenTransferError>; + fn can_receive_coins(&self) -> Result<(), HostError>; /// Validates that the tokens can be escrowed successfully. /// @@ -30,7 +31,7 @@ pub trait TokenTransferValidationContext { channel_id: &ChannelId, coin: &PrefixedCoin, memo: &Memo, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Validates that the tokens can be unescrowed successfully. fn unescrow_coins_validate( @@ -39,14 +40,14 @@ pub trait TokenTransferValidationContext { port_id: &PortId, channel_id: &ChannelId, coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Validates the receiver account and the coin input fn mint_coins_validate( &self, account: &Self::AccountId, coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Validates the sender account and the coin input before burning. /// @@ -57,7 +58,7 @@ pub trait TokenTransferValidationContext { account: &Self::AccountId, coin: &PrefixedCoin, memo: &Memo, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Returns a hash of the prefixed denom. /// Implement only if the host chain supports hashed denominations. @@ -79,7 +80,7 @@ pub trait TokenTransferExecutionContext: TokenTransferValidationContext { channel_id: &ChannelId, coin: &PrefixedCoin, memo: &Memo, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Executes the unescrow of the tokens in a user account. fn unescrow_coins_execute( @@ -88,14 +89,14 @@ pub trait TokenTransferExecutionContext: TokenTransferValidationContext { port_id: &PortId, channel_id: &ChannelId, coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Executes minting of the tokens in a user account. fn mint_coins_execute( &mut self, account: &Self::AccountId, coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; /// Executes burning of the tokens in a user account. /// @@ -106,5 +107,5 @@ pub trait TokenTransferExecutionContext: TokenTransferValidationContext { account: &Self::AccountId, coin: &PrefixedCoin, memo: &Memo, - ) -> Result<(), TokenTransferError>; + ) -> Result<(), HostError>; } diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 3ffad202a..1e9aec5a1 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -12,8 +12,8 @@ use uint::FromDecStrErr; #[derive(Display, Debug)] pub enum TokenTransferError { - /// context error: `{0}` - HandlerError(HandlerError), + /// handler error: `{0}` + Handler(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), /// identifier error: `{0}` @@ -50,7 +50,7 @@ pub enum TokenTransferError { impl std::error::Error for TokenTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::HandlerError(e) => Some(e), + Self::Handler(e) => Some(e), Self::Identifier(e) => Some(e), Self::InvalidAmount(e) => Some(e), Self::Decoding(e) => Some(e), @@ -67,7 +67,7 @@ impl From for TokenTransferError { impl From for TokenTransferError { fn from(e: HandlerError) -> Self { - Self::HandlerError(e) + Self::Handler(e) } } diff --git a/ibc-apps/ics721-nft-transfer/src/context.rs b/ibc-apps/ics721-nft-transfer/src/context.rs index ede6ee898..c16fb8dd1 100644 --- a/ibc-apps/ics721-nft-transfer/src/context.rs +++ b/ibc-apps/ics721-nft-transfer/src/context.rs @@ -1,5 +1,6 @@ //! Defines the required context traits for ICS-721 to interact with host //! machine. +use ibc_core::host::types::error::HostError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use ibc_core::primitives::Signer; @@ -41,13 +42,13 @@ pub trait NftTransferValidationContext { type NftClass: NftClassContext; /// get_port returns the portID for the transfer module. - fn get_port(&self) -> Result; + fn get_port(&self) -> Result; /// Returns Ok() if the host chain supports sending NFTs. - fn can_send_nft(&self) -> Result<(), NftTransferError>; + fn can_send_nft(&self) -> Result<(), HostError>; /// Returns Ok() if the host chain supports receiving NFTs. - fn can_receive_nft(&self) -> Result<(), NftTransferError>; + fn can_receive_nft(&self) -> Result<(), HostError>; /// Validates that the NFT can be created or updated successfully. /// @@ -62,7 +63,7 @@ pub trait NftTransferValidationContext { class_id: &PrefixedClassId, class_uri: Option<&ClassUri>, class_data: Option<&ClassData>, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Validates that the tokens can be escrowed successfully. /// @@ -77,7 +78,7 @@ pub trait NftTransferValidationContext { class_id: &PrefixedClassId, token_id: &TokenId, memo: &Memo, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Validates that the NFT can be unescrowed successfully. fn unescrow_nft_validate( @@ -87,7 +88,7 @@ pub trait NftTransferValidationContext { channel_id: &ChannelId, class_id: &PrefixedClassId, token_id: &TokenId, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Validates the receiver account and the NFT input /// @@ -104,7 +105,7 @@ pub trait NftTransferValidationContext { token_id: &TokenId, token_uri: Option<&TokenUri>, token_data: Option<&TokenData>, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Validates the sender account and the coin input before burning. /// @@ -117,7 +118,7 @@ pub trait NftTransferValidationContext { class_id: &PrefixedClassId, token_id: &TokenId, memo: &Memo, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Returns a hash of the prefixed class ID and the token ID. /// Implement only if the host chain supports hashed class ID and token ID. @@ -134,11 +135,10 @@ pub trait NftTransferValidationContext { &self, class_id: &PrefixedClassId, token_id: &TokenId, - ) -> Result; + ) -> Result; /// Returns the NFT class - fn get_nft_class(&self, class_id: &PrefixedClassId) - -> Result; + fn get_nft_class(&self, class_id: &PrefixedClassId) -> Result; } /// Read-write methods required in NFT transfer execution context. @@ -149,7 +149,7 @@ pub trait NftTransferExecutionContext: NftTransferValidationContext { class_id: &PrefixedClassId, class_uri: Option<&ClassUri>, class_data: Option<&ClassData>, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Executes the escrow of the NFT in a user account. /// @@ -163,7 +163,7 @@ pub trait NftTransferExecutionContext: NftTransferValidationContext { class_id: &PrefixedClassId, token_id: &TokenId, memo: &Memo, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Executes the unescrow of the NFT in a user account. fn unescrow_nft_execute( @@ -173,7 +173,7 @@ pub trait NftTransferExecutionContext: NftTransferValidationContext { channel_id: &ChannelId, class_id: &PrefixedClassId, token_id: &TokenId, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Executes minting of the NFT in a user account. fn mint_nft_execute( @@ -183,7 +183,7 @@ pub trait NftTransferExecutionContext: NftTransferValidationContext { token_id: &TokenId, token_uri: Option<&TokenUri>, token_data: Option<&TokenData>, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; /// Executes burning of the NFT in a user account. /// @@ -195,5 +195,5 @@ pub trait NftTransferExecutionContext: NftTransferValidationContext { class_id: &PrefixedClassId, token_id: &TokenId, memo: &Memo, - ) -> Result<(), NftTransferError>; + ) -> Result<(), HostError>; } diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 56c3f0981..35779f88b 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -12,8 +12,8 @@ use ibc_core::primitives::prelude::*; #[derive(Display, Debug, derive_more::From)] pub enum NftTransferError { - /// context error: `{0}` - HandlerError(HandlerError), + /// handler error: `{0}` + Handler(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), /// identifier error: `{0}` @@ -47,7 +47,7 @@ pub enum NftTransferError { impl std::error::Error for NftTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::HandlerError(e) => Some(e), + Self::Handler(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-clients/ics07-tendermint/src/client_state/validation.rs b/ibc-clients/ics07-tendermint/src/client_state/validation.rs index 4cd1a9cc8..8b89e2785 100644 --- a/ibc-clients/ics07-tendermint/src/client_state/validation.rs +++ b/ibc-clients/ics07-tendermint/src/client_state/validation.rs @@ -6,6 +6,7 @@ use ibc_core_client::context::client_state::ClientStateValidation; use ibc_core_client::context::{Convertible, ExtClientValidationContext}; use ibc_core_client::types::error::ClientError; use ibc_core_client::types::Status; +use ibc_core_handler_types::error::HandlerError; use ibc_core_host::types::identifiers::ClientId; use ibc_core_host::types::path::ClientConsensusStatePath; use ibc_primitives::prelude::*; diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index b2a01b5f7..9c74cc86a 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -49,13 +49,13 @@ where )?) } - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { let host_height = self.host_height()?; let host_cons_state = self.host_consensus_state(&host_height)?; Ok(host_cons_state.timestamp()) } - fn client_counter(&self) -> Result { + fn client_counter(&self) -> Result { Ok(self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) @@ -64,10 +64,7 @@ where })?) } - fn host_consensus_state( - &self, - height: &Height, - ) -> Result { + fn host_consensus_state(&self, height: &Height) -> Result { let consensus_states_binding = self.host_consensus_states.lock(); Ok(consensus_states_binding .get(&height.revision_height()) @@ -78,7 +75,7 @@ where fn validate_self_client( &self, client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { if client_state_of_host_on_counterparty.is_frozen() { return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); } @@ -120,7 +117,7 @@ where Ok(()) } - fn connection_end(&self, conn_id: &ConnectionId) -> Result { + fn connection_end(&self, conn_id: &ConnectionId) -> Result { Ok(self .connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) @@ -133,14 +130,14 @@ where CommitmentPrefix::from(b"mock".to_vec()) } - fn connection_counter(&self) -> Result { + fn connection_counter(&self) -> Result { Ok(self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) .ok_or(ConnectionError::MissingConnectionCounter)?) } - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { Ok(self .channel_end_store .get( @@ -153,10 +150,7 @@ where })?) } - fn get_next_sequence_send( - &self, - seq_send_path: &SeqSendPath, - ) -> Result { + fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result { Ok(self .send_sequence_store .get( @@ -166,10 +160,7 @@ where .ok_or(PacketError::ImplementationSpecific)?) } - fn get_next_sequence_recv( - &self, - seq_recv_path: &SeqRecvPath, - ) -> Result { + fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) -> Result { Ok(self .recv_sequence_store .get( @@ -179,7 +170,7 @@ where .ok_or(PacketError::ImplementationSpecific)?) } - fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { + fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { Ok(self .ack_sequence_store .get( @@ -192,7 +183,7 @@ where fn get_packet_commitment( &self, commitment_path: &CommitmentPath, - ) -> Result { + ) -> Result { Ok(self .packet_commitment_store .get( @@ -206,7 +197,7 @@ where .ok_or(PacketError::ImplementationSpecific)?) } - fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { + fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { Ok(self .packet_receipt_store .is_path_set( @@ -224,7 +215,7 @@ where fn get_packet_acknowledgement( &self, ack_path: &AckPath, - ) -> Result { + ) -> Result { Ok(self .packet_ack_store .get( @@ -237,7 +228,7 @@ where /// Returns a counter of the number of channel ids that have been created thus far. /// The value of this counter should increase only via the /// `ChannelKeeper::increase_channel_counter` method. - fn channel_counter(&self) -> Result { + fn channel_counter(&self) -> Result { Ok(self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) @@ -249,7 +240,7 @@ where Duration::from_secs(DEFAULT_BLOCK_TIME_SECS) } - fn validate_message_signer(&self, _signer: &Signer) -> Result<(), HandlerError> { + fn validate_message_signer(&self, _signer: &Signer) -> Result<(), HostError> { Ok(()) } @@ -289,7 +280,7 @@ where S: ProvableStore + Debug, { /// Returns the list of all client states. - fn client_states(&self) -> Result)>, HandlerError> { + fn client_states(&self) -> Result)>, HostError> { let path = "clients".to_owned().into(); self.client_state_store @@ -316,7 +307,7 @@ where fn consensus_states( &self, client_id: &ClientId, - ) -> Result)>, HandlerError> { + ) -> Result)>, HostError> { let path = format!("clients/{}/consensusStates", client_id) .try_into() .map_err(|_| ClientError::Other { @@ -353,7 +344,7 @@ where } /// Returns the list of heights at which the consensus state of the given client was updated. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError> { + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HostError> { let path = format!("clients/{}/consensusStates", client_id) .try_into() .map_err(|_| ClientError::Other { @@ -380,7 +371,7 @@ where } /// Returns all the IBC connection ends of a chain. - fn connection_ends(&self) -> Result, HandlerError> { + fn connection_ends(&self) -> Result, HostError> { let path = "connections".to_owned().into(); self.connection_end_store @@ -407,10 +398,7 @@ where } /// Returns all the IBC connection ends associated with a client. - fn client_connection_ends( - &self, - client_id: &ClientId, - ) -> Result, HandlerError> { + fn client_connection_ends(&self, client_id: &ClientId) -> Result, HostError> { let client_connection_path = ClientConnectionPath::new(client_id.clone()); Ok(self @@ -420,7 +408,7 @@ where } /// Returns all the IBC channel ends of a chain. - fn channel_ends(&self) -> Result, HandlerError> { + fn channel_ends(&self) -> Result, HostError> { let path = "channelEnds".to_owned().into(); self.channel_end_store @@ -454,7 +442,7 @@ where fn packet_commitments( &self, channel_end_path: &ChannelEndPath, - ) -> Result, HandlerError> { + ) -> Result, HostError> { let path = format!( "commitments/ports/{}/channels/{}/sequences", channel_end_path.0, channel_end_path.1 @@ -496,7 +484,7 @@ where &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, HandlerError> { + ) -> Result, HostError> { let collected_paths: Vec<_> = if sequences.len() == 0 { // if sequences is empty, return all the acks let ack_path_prefix = format!( @@ -549,7 +537,7 @@ where &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, HandlerError> { + ) -> Result, HostError> { // QUESTION. Currently only works for unordered channels; ordered channels // don't use receipts. However, ibc-go does it this way. Investigate if // this query only ever makes sense on unordered channels. @@ -574,7 +562,7 @@ where &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, HandlerError> { + ) -> Result, HostError> { let collected_paths: Vec<_> = if sequences.len() == 0 { // if sequences is empty, return all the acks let commitment_path_prefix = format!( @@ -625,7 +613,7 @@ where /// Called upon client creation. /// Increases the counter, that keeps track of how many clients have been created. - fn increase_client_counter(&mut self) -> Result<(), HandlerError> { + fn increase_client_counter(&mut self) -> Result<(), HostError> { let current_sequence = self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) @@ -647,7 +635,7 @@ where &mut self, connection_path: &ConnectionPath, connection_end: ConnectionEnd, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.connection_end_store .set(connection_path.clone(), connection_end) .map_err(|_| ConnectionError::FailedToStoreConnectionEnd)?; @@ -659,7 +647,7 @@ where &mut self, client_connection_path: &ClientConnectionPath, conn_id: ConnectionId, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { let mut conn_ids: Vec = self .connection_ids_store .get(StoreHeight::Pending, client_connection_path) @@ -673,7 +661,7 @@ where /// Called upon connection identifier creation (Init or Try process). /// Increases the counter, that keeps track of how many connections have been created. - fn increase_connection_counter(&mut self) -> Result<(), HandlerError> { + fn increase_connection_counter(&mut self) -> Result<(), HostError> { let current_sequence = self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) @@ -690,7 +678,7 @@ where &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.packet_commitment_store .set(commitment_path.clone(), commitment) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -700,7 +688,7 @@ where fn delete_packet_commitment( &mut self, commitment_path: &CommitmentPath, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.packet_commitment_store.delete(commitment_path.clone()); Ok(()) } @@ -709,7 +697,7 @@ where &mut self, receipt_path: &ReceiptPath, _receipt: Receipt, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.packet_receipt_store .set_path(receipt_path.clone()) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -720,14 +708,14 @@ where &mut self, ack_path: &AckPath, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.packet_ack_store .set(ack_path.clone(), ack_commitment) .map_err(|_| PacketError::ImplementationSpecific)?; Ok(()) } - fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HandlerError> { + fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HostError> { self.packet_ack_store.delete(ack_path.clone()); Ok(()) } @@ -736,7 +724,7 @@ where &mut self, channel_end_path: &ChannelEndPath, channel_end: ChannelEnd, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.channel_end_store .set(channel_end_path.clone(), channel_end) .map_err(|e| ChannelError::FailedToStoreChannel { @@ -749,7 +737,7 @@ where &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.send_sequence_store .set(seq_send_path.clone(), seq) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -760,7 +748,7 @@ where &mut self, seq_recv_path: &SeqRecvPath, seq: Sequence, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.recv_sequence_store .set(seq_recv_path.clone(), seq) .map_err(|_| PacketError::ImplementationSpecific)?; @@ -771,14 +759,14 @@ where &mut self, seq_ack_path: &SeqAckPath, seq: Sequence, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.ack_sequence_store .set(seq_ack_path.clone(), seq) .map_err(|_| PacketError::ImplementationSpecific)?; Ok(()) } - fn increase_channel_counter(&mut self) -> Result<(), HandlerError> { + fn increase_channel_counter(&mut self) -> Result<(), HostError> { let current_sequence = self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) @@ -793,12 +781,12 @@ where Ok(()) } - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError> { + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HostError> { self.events.lock().push(event); Ok(()) } - fn log_message(&mut self, message: String) -> Result<(), HandlerError> { + fn log_message(&mut self, message: String) -> Result<(), HostError> { self.logs.lock().push(message); Ok(()) } From 2a4fea59971635462c14a5c4e0411ce8410d9e53 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 9 Sep 2024 16:30:52 -0500 Subject: [PATCH 060/107] Updating validation contexts to return HostError types --- ibc-apps/ics20-transfer/src/context.rs | 1 - ibc-apps/ics20-transfer/src/handler/mod.rs | 12 +- .../src/handler/on_recv_packet.rs | 10 +- ibc-apps/ics20-transfer/types/src/error.rs | 8 +- ibc-apps/ics721-nft-transfer/src/context.rs | 1 - .../ics721-nft-transfer/src/handler/mod.rs | 48 +++++--- .../src/handler/on_recv_packet.rs | 14 +-- .../ics721-nft-transfer/types/src/error.rs | 30 +++-- .../src/client_state/validation.rs | 1 - ibc-core/ics02-client/types/src/error.rs | 9 ++ ibc-core/ics04-channel/src/context.rs | 34 +++--- ibc-core/ics24-host/types/src/error.rs | 4 + ibc-query/src/error.rs | 28 +++-- .../ibc/applications/nft_transfer/context.rs | 35 +++--- .../ibc/applications/transfer/context.rs | 24 ++-- .../testapp/ibc/clients/mock/client_state.rs | 5 +- .../src/testapp/ibc/core/client_ctx.rs | 104 ++++++++++-------- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 102 ++++++++++------- 18 files changed, 271 insertions(+), 199 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/context.rs b/ibc-apps/ics20-transfer/src/context.rs index eb39686d2..2917c9fe9 100644 --- a/ibc-apps/ics20-transfer/src/context.rs +++ b/ibc-apps/ics20-transfer/src/context.rs @@ -1,6 +1,5 @@ //! Defines the main context traits and IBC module callbacks -use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::{Memo, PrefixedCoin, PrefixedDenom}; use ibc_core::host::types::error::HostError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index 6d3cde510..a6cbc3237 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -27,16 +27,16 @@ pub fn refund_packet_token_execute( packet.chan_id_on_a.clone(), &data.token.denom, ) { - ctx_a.unescrow_coins_execute( + Ok(ctx_a.unescrow_coins_execute( &sender, &packet.port_id_on_a, &packet.chan_id_on_a, &data.token, - ) + )?) } // mint vouchers back to sender else { - ctx_a.mint_coins_execute(&sender, &data.token) + Ok(ctx_a.mint_coins_execute(&sender, &data.token)?) } } @@ -56,13 +56,13 @@ pub fn refund_packet_token_validate( packet.chan_id_on_a.clone(), &data.token.denom, ) { - ctx_a.unescrow_coins_validate( + Ok(ctx_a.unescrow_coins_validate( &sender, &packet.port_id_on_a, &packet.chan_id_on_a, &data.token, - ) + )?) } else { - ctx_a.mint_coins_validate(&sender, &data.token) + Ok(ctx_a.mint_coins_validate(&sender, &data.token)?) } } diff --git a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs index b0fcbd877..76e22b3b6 100644 --- a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs +++ b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs @@ -21,7 +21,7 @@ pub fn process_recv_packet_execute( ) -> Result { ctx_b .can_receive_coins() - .map_err(|err| (ModuleExtras::empty(), err))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; let receiver_account = data.receiver.clone().try_into().map_err(|_| { ( @@ -60,7 +60,7 @@ pub fn process_recv_packet_execute( &packet.chan_id_on_b, &coin, ) - .map_err(|token_err| (ModuleExtras::empty(), token_err))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; ctx_b .unescrow_coins_execute( &receiver_account, @@ -68,7 +68,7 @@ pub fn process_recv_packet_execute( &packet.chan_id_on_b, &coin, ) - .map_err(|token_err| (ModuleExtras::empty(), token_err))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; ModuleExtras::empty() } else { @@ -103,11 +103,11 @@ pub fn process_recv_packet_execute( // can be refunded. ctx_b .mint_coins_validate(&receiver_account, &coin) - .map_err(|token_err| (extras.clone(), token_err))?; + .map_err(|err| (extras.clone(), err.into()))?; ctx_b .mint_coins_execute(&receiver_account, &coin) - .map_err(|token_err| (extras.clone(), token_err))?; + .map_err(|err| (extras.clone(), err.into()))?; extras }; diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 1e9aec5a1..6158ef0f1 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -5,7 +5,7 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; -use ibc_core::host::types::error::{DecodingError, IdentifierError}; +use ibc_core::host::types::error::{DecodingError, HostError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use uint::FromDecStrErr; @@ -83,6 +83,12 @@ impl From for TokenTransferError { } } +impl From for TokenTransferError { + fn from(e: HostError) -> Self { + Self::Handler(HandlerError::Host(e)) + } +} + impl From for StatusValue { fn from(e: TokenTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") diff --git a/ibc-apps/ics721-nft-transfer/src/context.rs b/ibc-apps/ics721-nft-transfer/src/context.rs index c16fb8dd1..201d342cb 100644 --- a/ibc-apps/ics721-nft-transfer/src/context.rs +++ b/ibc-apps/ics721-nft-transfer/src/context.rs @@ -5,7 +5,6 @@ use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; use ibc_core::primitives::Signer; -use crate::types::error::NftTransferError; use crate::types::{ ClassData, ClassId, ClassUri, Memo, PrefixedClassId, TokenData, TokenId, TokenUri, }; diff --git a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs index 8f8d0775c..80935871a 100644 --- a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs +++ b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs @@ -3,7 +3,6 @@ mod on_recv_packet; mod send_transfer; -use ibc_core::channel::types::packet::Packet; pub use on_recv_packet::*; pub use send_transfer::*; @@ -12,6 +11,9 @@ use crate::types::error::NftTransferError; use crate::types::is_sender_chain_source; use crate::types::packet::PacketData; +use ibc_core::channel::types::packet::Packet; +use ibc_core::handler::types::error::HandlerError; + pub fn refund_packet_nft_execute( ctx_a: &mut impl NftTransferExecutionContext, packet: &Packet, @@ -29,13 +31,15 @@ pub fn refund_packet_nft_execute( &data.class_id, ) { data.token_ids.as_ref().iter().try_for_each(|token_id| { - ctx_a.unescrow_nft_execute( - &sender, - &packet.port_id_on_a, - &packet.chan_id_on_a, - &data.class_id, - token_id, - ) + ctx_a + .unescrow_nft_execute( + &sender, + &packet.port_id_on_a, + &packet.chan_id_on_a, + &data.class_id, + token_id, + ) + .map_err(|e| NftTransferError::Handler(HandlerError::Host(e))) }) } // mint vouchers back to sender @@ -43,8 +47,12 @@ pub fn refund_packet_nft_execute( for (i, token_id) in data.token_ids.0.iter().enumerate() { let token_uri = data.token_uris.as_ref().and_then(|uris| uris.get(i)); let token_data = data.token_data.as_ref().and_then(|data| data.get(i)); - ctx_a.mint_nft_execute(&sender, &data.class_id, token_id, token_uri, token_data)?; + + let _ = ctx_a + .mint_nft_execute(&sender, &data.class_id, token_id, token_uri, token_data) + .map_err(|_| NftTransferError::Handler); } + Ok(()) } } @@ -66,20 +74,26 @@ pub fn refund_packet_nft_validate( &data.class_id, ) { data.token_ids.0.iter().try_for_each(|token_id| { - ctx_a.unescrow_nft_validate( - &sender, - &packet.port_id_on_a, - &packet.chan_id_on_a, - &data.class_id, - token_id, - ) + ctx_a + .unescrow_nft_validate( + &sender, + &packet.port_id_on_a, + &packet.chan_id_on_a, + &data.class_id, + token_id, + ) + .map_err(|e| NftTransferError::Handler(HandlerError::Host(e))) }) } else { for (i, token_id) in data.token_ids.0.iter().enumerate() { let token_uri = data.token_uris.as_ref().and_then(|uris| uris.get(i)); let token_data = data.token_data.as_ref().and_then(|data| data.get(i)); - ctx_a.mint_nft_validate(&sender, &data.class_id, token_id, token_uri, token_data)?; + + let _ = ctx_a + .mint_nft_validate(&sender, &data.class_id, token_id, token_uri, token_data) + .map_err(|_| NftTransferError::Handler); } + Ok(()) } } diff --git a/ibc-apps/ics721-nft-transfer/src/handler/on_recv_packet.rs b/ibc-apps/ics721-nft-transfer/src/handler/on_recv_packet.rs index 59e6f3cb8..6d8eeb194 100644 --- a/ibc-apps/ics721-nft-transfer/src/handler/on_recv_packet.rs +++ b/ibc-apps/ics721-nft-transfer/src/handler/on_recv_packet.rs @@ -23,7 +23,7 @@ where { ctx_b .can_receive_nft() - .map_err(|err| (ModuleExtras::empty(), err))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; let receiver_account = data.receiver.clone().try_into().map_err(|_| { ( @@ -56,7 +56,7 @@ where &class_id, token_id, ) - .map_err(|nft_error| (ModuleExtras::empty(), nft_error))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; ctx_b .unescrow_nft_execute( &receiver_account, @@ -65,7 +65,7 @@ where &class_id, token_id, ) - .map_err(|nft_error| (ModuleExtras::empty(), nft_error))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; } ModuleExtras::empty() @@ -102,14 +102,14 @@ where data.class_uri.as_ref(), data.class_data.as_ref(), ) - .map_err(|nft_error| (ModuleExtras::empty(), nft_error))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; ctx_b .create_or_update_class_execute( &class_id, data.class_uri.as_ref(), data.class_data.as_ref(), ) - .map_err(|nft_error| (ModuleExtras::empty(), nft_error))?; + .map_err(|err| (ModuleExtras::empty(), err.into()))?; ctx_b .mint_nft_validate( @@ -119,7 +119,7 @@ where token_uri, token_data, ) - .map_err(|nft_error| (extras.clone(), nft_error))?; + .map_err(|err| (extras.clone(), err.into()))?; ctx_b .mint_nft_execute( &receiver_account, @@ -128,7 +128,7 @@ where token_uri, token_data, ) - .map_err(|nft_error| (extras.clone(), nft_error))?; + .map_err(|err| (extras.clone(), err.into()))?; } extras diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 35779f88b..da4d7a73f 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -6,7 +6,7 @@ use http::uri::InvalidUri; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; -use ibc_core::host::types::error::{DecodingError, IdentifierError}; +use ibc_core::host::types::error::{DecodingError, HostError, IdentifierError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -43,25 +43,31 @@ pub enum NftTransferError { UnsupportedClosedChannel, } -#[cfg(feature = "std")] -impl std::error::Error for NftTransferError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match &self { - Self::Handler(e) => Some(e), - Self::Decoding(e) => Some(e), - _ => None, - } - } -} - impl From for NftTransferError { fn from(e: Infallible) -> Self { match e {} } } +impl From for NftTransferError { + fn from(e: HostError) -> Self { + Self::Handler(HandlerError::Host(e)) + } +} + impl From for StatusValue { fn from(e: NftTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") } } + +#[cfg(feature = "std")] +impl std::error::Error for NftTransferError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Self::Handler(e) => Some(e), + Self::Decoding(e) => Some(e), + _ => None, + } + } +} diff --git a/ibc-clients/ics07-tendermint/src/client_state/validation.rs b/ibc-clients/ics07-tendermint/src/client_state/validation.rs index 8b89e2785..4cd1a9cc8 100644 --- a/ibc-clients/ics07-tendermint/src/client_state/validation.rs +++ b/ibc-clients/ics07-tendermint/src/client_state/validation.rs @@ -6,7 +6,6 @@ use ibc_core_client::context::client_state::ClientStateValidation; use ibc_core_client::context::{Convertible, ExtClientValidationContext}; use ibc_core_client::types::error::ClientError; use ibc_core_client::types::Status; -use ibc_core_handler_types::error::HandlerError; use ibc_core_host::types::identifiers::ClientId; use ibc_core_host::types::path::ClientConsensusStatePath; use ibc_primitives::prelude::*; diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 26aeb03dd..a1135f49e 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -5,6 +5,7 @@ use core::convert::Infallible; use displaydoc::Display; use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::DecodingError; +use ibc_core_host_types::error::HostError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; @@ -16,6 +17,8 @@ use crate::Status; /// Encodes all the possible client errors #[derive(Debug, Display)] pub enum ClientError { + /// host error : `{0}` + Host(HostError), /// upgrade client error: `{0}` Upgrade(UpgradeClientError), /// decoding error: `{0}` @@ -106,6 +109,12 @@ impl From for ClientError { } } +impl From for ClientError { + fn from(e: HostError) -> Self { + Self::Host(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { diff --git a/ibc-core/ics04-channel/src/context.rs b/ibc-core/ics04-channel/src/context.rs index 1b235db92..92844b4d4 100644 --- a/ibc-core/ics04-channel/src/context.rs +++ b/ibc-core/ics04-channel/src/context.rs @@ -4,8 +4,8 @@ use ibc_core_channel_types::channel::ChannelEnd; use ibc_core_channel_types::commitment::PacketCommitment; use ibc_core_client::context::prelude::*; use ibc_core_connection::types::ConnectionEnd; -use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::IbcEvent; +use ibc_core_host::types::error::HostError; use ibc_core_host::types::identifiers::{ConnectionId, Sequence}; use ibc_core_host::types::path::{ChannelEndPath, CommitmentPath, SeqSendPath}; use ibc_core_host::{ExecutionContext, ValidationContext}; @@ -19,13 +19,12 @@ pub trait SendPacketValidationContext { fn get_client_validation_context(&self) -> &Self::V; /// Returns the ChannelEnd for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; /// Returns the ConnectionState for the given identifier `connection_id`. - fn connection_end(&self, connection_id: &ConnectionId) -> Result; + fn connection_end(&self, connection_id: &ConnectionId) -> Result; - fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) - -> Result; + fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result; } impl SendPacketValidationContext for T @@ -38,18 +37,15 @@ where self.get_client_validation_context() } - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { self.channel_end(channel_end_path) } - fn connection_end(&self, connection_id: &ConnectionId) -> Result { + fn connection_end(&self, connection_id: &ConnectionId) -> Result { self.connection_end(connection_id) } - fn get_next_sequence_send( - &self, - seq_send_path: &SeqSendPath, - ) -> Result { + fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result { self.get_next_sequence_send(seq_send_path) } } @@ -60,19 +56,19 @@ pub trait SendPacketExecutionContext: SendPacketValidationContext { &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; fn store_packet_commitment( &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; /// Ibc events - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError>; + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HostError>; /// Logging facility - fn log_message(&mut self, message: String) -> Result<(), HandlerError>; + fn log_message(&mut self, message: String) -> Result<(), HostError>; } impl SendPacketExecutionContext for T @@ -83,7 +79,7 @@ where &mut self, seq_send_path: &SeqSendPath, seq: Sequence, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.store_next_sequence_send(seq_send_path, seq) } @@ -91,15 +87,15 @@ where &mut self, commitment_path: &CommitmentPath, commitment: PacketCommitment, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.store_packet_commitment(commitment_path, commitment) } - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HandlerError> { + fn emit_ibc_event(&mut self, event: IbcEvent) -> Result<(), HostError> { self.emit_ibc_event(event) } - fn log_message(&mut self, message: String) -> Result<(), HandlerError> { + fn log_message(&mut self, message: String) -> Result<(), HostError> { self.log_message(message) } } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 9cf25fe51..e951b43b6 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -16,10 +16,14 @@ pub enum HostError { InvalidData { description: String }, /// missing data: `{description}` MissingData { description: String }, + /// unexpected data: `{description}` + UnexpectedData { description: String }, /// failed to update state: `{description}` FailedToUpdateState { description: String }, /// failed to store data: `{description}` FailedToStoreData { description: String }, + /// failed to retrieve data from store: `{description}` + FailedToRetrieveFromStore { description: String }, /// failed to parse data: `{description}` FailedToParseData { description: String }, /// non-existent type: `{description}` diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index d2bd46af5..09bbf971e 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -5,7 +5,7 @@ use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; use ibc::core::connection::types::error::ConnectionError; use ibc::core::handler::types::error::HandlerError; -use ibc::core::host::types::error::IdentifierError; +use ibc::core::host::types::error::{HostError, IdentifierError}; use tonic::Status; /// The main error type of the ibc-query crate. This type mainly @@ -14,9 +14,9 @@ use tonic::Status; #[derive(Debug, Display)] pub enum QueryError { /// context error: `{0}` - HandlerError(HandlerError), + Handler(HandlerError), /// identifier error: `{0}` - IdentifierError(IdentifierError), + Identifier(IdentifierError), /// missing proof: `{0}` MissingProof(String), /// missing field: `{0}` @@ -36,8 +36,8 @@ impl QueryError { impl From for Status { fn from(e: QueryError) -> Self { match e { - QueryError::HandlerError(ctx_err) => Self::internal(ctx_err.to_string()), - QueryError::IdentifierError(id_err) => Self::internal(id_err.to_string()), + QueryError::Handler(ctx_err) => Self::internal(ctx_err.to_string()), + QueryError::Identifier(id_err) => Self::internal(id_err.to_string()), QueryError::MissingProof(description) => Self::not_found(description), QueryError::MissingField(description) => Self::invalid_argument(description), } @@ -46,36 +46,42 @@ impl From for Status { impl From for QueryError { fn from(e: HandlerError) -> Self { - Self::HandlerError(e) + Self::Handler(e) } } impl From for QueryError { fn from(e: ClientError) -> Self { - Self::HandlerError(HandlerError::Client(e)) + Self::Handler(HandlerError::Client(e)) } } impl From for QueryError { fn from(e: ConnectionError) -> Self { - Self::HandlerError(HandlerError::Connection(e)) + Self::Handler(HandlerError::Connection(e)) } } impl From for QueryError { fn from(e: ChannelError) -> Self { - Self::HandlerError(HandlerError::Channel(e)) + Self::Handler(HandlerError::Channel(e)) } } impl From for QueryError { fn from(e: PacketError) -> Self { - Self::HandlerError(HandlerError::Packet(e)) + Self::Handler(HandlerError::Packet(e)) } } impl From for QueryError { fn from(e: IdentifierError) -> Self { - Self::IdentifierError(e) + Self::Identifier(e) + } +} + +impl From for QueryError { + fn from(e: HostError) -> Self { + Self::Handler(HandlerError::Host(e)) } } diff --git a/ibc-testkit/src/testapp/ibc/applications/nft_transfer/context.rs b/ibc-testkit/src/testapp/ibc/applications/nft_transfer/context.rs index a526dcf45..84838d846 100644 --- a/ibc-testkit/src/testapp/ibc/applications/nft_transfer/context.rs +++ b/ibc-testkit/src/testapp/ibc/applications/nft_transfer/context.rs @@ -1,10 +1,10 @@ use ibc::apps::nft_transfer::context::{ NftClassContext, NftContext, NftTransferExecutionContext, NftTransferValidationContext, }; -use ibc::apps::nft_transfer::types::error::NftTransferError; use ibc::apps::nft_transfer::types::{ ClassData, ClassId, ClassUri, Memo, PrefixedClassId, TokenData, TokenId, TokenUri, }; +use ibc::core::host::types::error::HostError; use ibc::core::host::types::identifiers::{ChannelId, PortId}; use ibc::core::primitives::prelude::*; use ibc::core::primitives::Signer; @@ -48,15 +48,15 @@ impl NftTransferValidationContext for DummyNftTransferModule { type Nft = DummyNft; type NftClass = DummyNftClass; - fn get_port(&self) -> Result { + fn get_port(&self) -> Result { Ok(PortId::transfer()) } - fn can_send_nft(&self) -> Result<(), NftTransferError> { + fn can_send_nft(&self) -> Result<(), HostError> { Ok(()) } - fn can_receive_nft(&self) -> Result<(), NftTransferError> { + fn can_receive_nft(&self) -> Result<(), HostError> { Ok(()) } @@ -65,7 +65,7 @@ impl NftTransferValidationContext for DummyNftTransferModule { _class_id: &PrefixedClassId, _class_uri: Option<&ClassUri>, _class_data: Option<&ClassData>, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -77,7 +77,7 @@ impl NftTransferValidationContext for DummyNftTransferModule { _class_id: &PrefixedClassId, _token_id: &TokenId, _memo: &Memo, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -88,7 +88,7 @@ impl NftTransferValidationContext for DummyNftTransferModule { _channel_id: &ChannelId, _class_id: &PrefixedClassId, _token_id: &TokenId, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -99,7 +99,7 @@ impl NftTransferValidationContext for DummyNftTransferModule { _token_id: &TokenId, _token_uri: Option<&TokenUri>, _token_data: Option<&TokenData>, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -109,7 +109,7 @@ impl NftTransferValidationContext for DummyNftTransferModule { _class_id: &PrefixedClassId, _token_id: &TokenId, _memo: &Memo, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -117,14 +117,11 @@ impl NftTransferValidationContext for DummyNftTransferModule { &self, _class_id: &PrefixedClassId, _token_id: &TokenId, - ) -> Result { + ) -> Result { Ok(DummyNft::default()) } - fn get_nft_class( - &self, - _class_id: &PrefixedClassId, - ) -> Result { + fn get_nft_class(&self, _class_id: &PrefixedClassId) -> Result { Ok(DummyNftClass::default()) } } @@ -135,7 +132,7 @@ impl NftTransferExecutionContext for DummyNftTransferModule { _class_id: &PrefixedClassId, _class_uri: Option<&ClassUri>, _class_data: Option<&ClassData>, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -147,7 +144,7 @@ impl NftTransferExecutionContext for DummyNftTransferModule { _class_id: &PrefixedClassId, _token_id: &TokenId, _memo: &Memo, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -158,7 +155,7 @@ impl NftTransferExecutionContext for DummyNftTransferModule { _channel_id: &ChannelId, _class_id: &PrefixedClassId, _token_id: &TokenId, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -169,7 +166,7 @@ impl NftTransferExecutionContext for DummyNftTransferModule { _token_id: &TokenId, _token_uri: Option<&TokenUri>, _token_data: Option<&TokenData>, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -179,7 +176,7 @@ impl NftTransferExecutionContext for DummyNftTransferModule { _class_id: &PrefixedClassId, _token_id: &TokenId, _memo: &Memo, - ) -> Result<(), NftTransferError> { + ) -> Result<(), HostError> { Ok(()) } } diff --git a/ibc-testkit/src/testapp/ibc/applications/transfer/context.rs b/ibc-testkit/src/testapp/ibc/applications/transfer/context.rs index d8876b315..d4a9677ef 100644 --- a/ibc-testkit/src/testapp/ibc/applications/transfer/context.rs +++ b/ibc-testkit/src/testapp/ibc/applications/transfer/context.rs @@ -1,6 +1,6 @@ use ibc::apps::transfer::context::{TokenTransferExecutionContext, TokenTransferValidationContext}; -use ibc::apps::transfer::types::error::TokenTransferError; use ibc::apps::transfer::types::{Memo, PrefixedCoin}; +use ibc::core::host::types::error::HostError; use ibc::core::host::types::identifiers::{ChannelId, PortId}; use ibc::core::primitives::Signer; @@ -9,15 +9,15 @@ use super::types::DummyTransferModule; impl TokenTransferValidationContext for DummyTransferModule { type AccountId = Signer; - fn get_port(&self) -> Result { + fn get_port(&self) -> Result { Ok(PortId::transfer()) } - fn can_send_coins(&self) -> Result<(), TokenTransferError> { + fn can_send_coins(&self) -> Result<(), HostError> { Ok(()) } - fn can_receive_coins(&self) -> Result<(), TokenTransferError> { + fn can_receive_coins(&self) -> Result<(), HostError> { Ok(()) } fn escrow_coins_validate( @@ -27,7 +27,7 @@ impl TokenTransferValidationContext for DummyTransferModule { _channel_id: &ChannelId, _coin: &PrefixedCoin, _memo: &Memo, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -37,7 +37,7 @@ impl TokenTransferValidationContext for DummyTransferModule { _port_id: &PortId, _channel_id: &ChannelId, _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -45,7 +45,7 @@ impl TokenTransferValidationContext for DummyTransferModule { &self, _account: &Self::AccountId, _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -54,7 +54,7 @@ impl TokenTransferValidationContext for DummyTransferModule { _account: &Self::AccountId, _coin: &PrefixedCoin, _memo: &Memo, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } } @@ -67,7 +67,7 @@ impl TokenTransferExecutionContext for DummyTransferModule { _channel_id: &ChannelId, _coin: &PrefixedCoin, _memo: &Memo, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -77,7 +77,7 @@ impl TokenTransferExecutionContext for DummyTransferModule { _port_id: &PortId, _channel_id: &ChannelId, _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -85,7 +85,7 @@ impl TokenTransferExecutionContext for DummyTransferModule { &mut self, _account: &Self::AccountId, _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } @@ -94,7 +94,7 @@ impl TokenTransferExecutionContext for DummyTransferModule { _account: &Self::AccountId, _coin: &PrefixedCoin, _memo: &Memo, - ) -> Result<(), TokenTransferError> { + ) -> Result<(), HostError> { Ok(()) } } diff --git a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs index 054be94c6..ef6f4c0f0 100644 --- a/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs +++ b/ibc-testkit/src/testapp/ibc/clients/mock/client_state.rs @@ -8,8 +8,7 @@ use ibc::core::client::types::{Height, Status}; use ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; -use ibc::core::handler::types::error::HandlerError; -use ibc::core::host::types::error::DecodingError; +use ibc::core::host::types::error::{DecodingError, HostError}; use ibc::core::host::types::identifiers::{ClientId, ClientType}; use ibc::core::host::types::path::{ClientConsensusStatePath, ClientStatePath, Path, PathBytes}; use ibc::core::primitives::prelude::*; @@ -155,7 +154,7 @@ impl From for Any { pub trait MockClientContext { /// Returns the current timestamp of the local chain. - fn host_timestamp(&self) -> Result; + fn host_timestamp(&self) -> Result; /// Returns the current height of the local chain. fn host_height(&self) -> Result; diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index 0936dd12c..d7ba951a5 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -7,7 +7,7 @@ use ibc::core::client::context::{ }; use ibc::core::client::types::error::ClientError; use ibc::core::client::types::Height; -use ibc::core::handler::types::error::HandlerError; +use ibc::core::host::types::error::HostError; use ibc::core::host::types::identifiers::{ChannelId, ClientId, PortId}; use ibc::core::host::types::path::{ ClientConsensusStatePath, ClientStatePath, ClientUpdateHeightPath, ClientUpdateTimePath, Path, @@ -37,7 +37,7 @@ impl MockClientContext for MockIbcStore where S: ProvableStore + Debug, { - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { ValidationContext::host_timestamp(self) } @@ -50,7 +50,7 @@ impl ExtClientValidationContext for MockIbcStore where S: ProvableStore + Debug, { - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { ValidationContext::host_timestamp(self) } @@ -59,12 +59,8 @@ where } /// Returns the list of heights at which the consensus state of the given client was updated. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError> { - let path = format!("clients/{}/consensusStates", client_id) - .try_into() - .map_err(|_| ClientError::Other { - description: "Invalid consensus state path".into(), - })?; + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HostError> { + let path = format!("clients/{}/consensusStates", client_id).into(); self.consensus_state_store .get_keys(&path) @@ -80,7 +76,10 @@ where Ok(Height::new( consensus_path.revision_number, consensus_path.revision_height, - )?) + ) + .map_err(|e| HostError::InvalidData { + description: e.to_string(), + })?) }) .collect::, _>>() } @@ -89,7 +88,7 @@ where &self, client_id: &ClientId, height: &Height, - ) -> Result, HandlerError> { + ) -> Result, HostError> { let path = format!("clients/{client_id}/consensusStates").into(); let keys = self.store.get_keys(&path); @@ -113,7 +112,10 @@ where height: *height, }) }) - .transpose()?; + .transpose() + .map_err(|e| HostError::MissingData { + description: e.to_string(), + })?; Ok(consensus_state) } @@ -122,7 +124,7 @@ where &self, client_id: &ClientId, height: &Height, - ) -> Result, HandlerError> { + ) -> Result, HostError> { let path = format!("clients/{client_id}/consensusStates").into(); let keys = self.store.get_keys(&path); @@ -146,7 +148,10 @@ where height: *height, }) }) - .transpose()?; + .transpose() + .map_err(|e| HostError::MissingData { + description: e.to_string(), + })?; Ok(consensus_state) } @@ -159,28 +164,35 @@ where type ClientStateRef = AnyClientState; type ConsensusStateRef = AnyConsensusState; - fn client_state(&self, client_id: &ClientId) -> Result { + fn client_state(&self, client_id: &ClientId) -> Result { Ok(self .client_state_store .get(StoreHeight::Pending, &ClientStatePath(client_id.clone())) - .ok_or(ClientError::MissingClientState(client_id.clone()))?) + .ok_or(HostError::MissingData { + description: ClientError::MissingClientState(client_id.clone()).to_string(), + })?) } fn consensus_state( &self, client_cons_state_path: &ClientConsensusStatePath, - ) -> Result { + ) -> Result { let height = Height::new( client_cons_state_path.revision_number, client_cons_state_path.revision_height, ) - .map_err(|_| ClientError::InvalidHeight)?; + .map_err(|e| HostError::InvalidData { + description: e.to_string(), + })?; let consensus_state = self .consensus_state_store .get(StoreHeight::Pending, client_cons_state_path) - .ok_or(ClientError::MissingConsensusState { - client_id: client_cons_state_path.client_id.clone(), - height, + .ok_or(HostError::MissingData { + description: ClientError::MissingConsensusState { + client_id: client_cons_state_path.client_id.clone(), + height, + } + .to_string(), })?; Ok(consensus_state) @@ -192,7 +204,7 @@ where &self, client_id: &ClientId, height: &Height, - ) -> Result<(Timestamp, Height), HandlerError> { + ) -> Result<(Timestamp, Height), HostError> { let client_update_time_path = ClientUpdateTimePath::new( client_id.clone(), height.revision_number(), @@ -201,9 +213,12 @@ where let processed_timestamp = self .client_processed_times .get(StoreHeight::Pending, &client_update_time_path) - .ok_or(ClientError::MissingUpdateMetaData { - client_id: client_id.clone(), - height: *height, + .ok_or(HostError::MissingData { + description: ClientError::MissingUpdateMetaData { + client_id: client_id.clone(), + height: *height, + } + .to_string(), })?; let client_update_height_path = ClientUpdateHeightPath::new( client_id.clone(), @@ -213,9 +228,12 @@ where let processed_height = self .client_processed_heights .get(StoreHeight::Pending, &client_update_height_path) - .ok_or(ClientError::MissingUpdateMetaData { - client_id: client_id.clone(), - height: *height, + .ok_or(HostError::MissingData { + description: ClientError::MissingUpdateMetaData { + client_id: client_id.clone(), + height: *height, + } + .to_string(), })?; Ok((processed_timestamp, processed_height)) @@ -233,11 +251,11 @@ where &mut self, client_state_path: ClientStatePath, client_state: Self::ClientStateRef, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.client_state_store .set(client_state_path, client_state) - .map_err(|_| ClientError::Other { - description: "Client state store error".to_string(), + .map_err(|e| HostError::FailedToStoreData { + description: format!("{e:?}"), })?; Ok(()) @@ -248,11 +266,11 @@ where &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Self::ConsensusStateRef, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.consensus_state_store .set(consensus_state_path, consensus_state) - .map_err(|_| ClientError::Other { - description: "Consensus state store error".to_string(), + .map_err(|e| HostError::FailedToStoreData { + description: format!("{e:?}"), })?; Ok(()) } @@ -260,18 +278,14 @@ where fn delete_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { self.consensus_state_store.delete(consensus_state_path); Ok(()) } /// Delete the update metadata associated with the client at the specified /// height. - fn delete_update_meta( - &mut self, - client_id: ClientId, - height: Height, - ) -> Result<(), HandlerError> { + fn delete_update_meta(&mut self, client_id: ClientId, height: Height) -> Result<(), HostError> { let client_update_time_path = ClientUpdateTimePath::new( client_id.clone(), height.revision_number(), @@ -297,7 +311,7 @@ where height: Height, host_timestamp: Timestamp, host_height: Height, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { let client_update_time_path = ClientUpdateTimePath::new( client_id.clone(), height.revision_number(), @@ -305,8 +319,8 @@ where ); self.client_processed_times .set(client_update_time_path, host_timestamp) - .map_err(|_| ClientError::Other { - description: "store update error".into(), + .map_err(|e| HostError::FailedToStoreData { + description: format!("{e:?}"), })?; let client_update_height_path = ClientUpdateHeightPath::new( client_id, @@ -315,8 +329,8 @@ where ); self.client_processed_heights .set(client_update_height_path, host_height) - .map_err(|_| ClientError::Other { - description: "store update error".into(), + .map_err(|e| HostError::FailedToStoreData { + description: format!("{e:?}"), })?; Ok(()) } diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 9c74cc86a..cc0e45a6a 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -16,8 +16,8 @@ use ibc::core::commitment_types::commitment::CommitmentPrefix; use ibc::core::commitment_types::merkle::MerkleProof; use ibc::core::connection::types::error::ConnectionError; use ibc::core::connection::types::{ConnectionEnd, IdentifiedConnectionEnd}; -use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::IbcEvent; +use ibc::core::host::types::error::HostError; use ibc::core::host::types::identifiers::{ClientId, ConnectionId, Sequence}; use ibc::core::host::types::path::{ AckPath, ChannelEndPath, ClientConnectionPath, CommitmentPath, ConnectionPath, @@ -43,10 +43,13 @@ where type HostConsensusState = AnyConsensusState; fn host_height(&self) -> Result { - Ok(Height::new( - *self.revision_number.lock(), - self.store.current_height(), - )?) + Ok( + Height::new(*self.revision_number.lock(), self.store.current_height()).map_err( + |e| HostError::InvalidData { + description: e.to_string(), + }, + )?, + ) } fn host_timestamp(&self) -> Result { @@ -59,17 +62,20 @@ where Ok(self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(ClientError::Other { - description: "client counter not found".into(), + .ok_or(HostError::MissingData { + description: "client counter not found".to_string(), })?) } fn host_consensus_state(&self, height: &Height) -> Result { let consensus_states_binding = self.host_consensus_states.lock(); + Ok(consensus_states_binding .get(&height.revision_height()) .cloned() - .ok_or(ClientError::MissingLocalConsensusState(*height))?) + .ok_or(HostError::MissingData { + description: ClientError::MissingLocalConsensusState(*height).to_string(), + })?) } fn validate_self_client( @@ -77,7 +83,9 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), HostError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); + return Err(HostError::UnexpectedData { + description: ClientError::UnexpectedStatus(Status::Frozen).to_string(), + }); } let latest_height = self.host_height()?; @@ -88,30 +96,26 @@ where .latest_height() .revision_number() { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "client is not in the same revision as the chain. expected: {}, got: {}", - self_revision_number, - client_state_of_host_on_counterparty - .latest_height() - .revision_number() - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "client is not in the same revision as the chain. expected: {}, got: {}", + self_revision_number, + client_state_of_host_on_counterparty + .latest_height() + .revision_number() + ), + }); } let host_current_height = latest_height.increment(); if client_state_of_host_on_counterparty.latest_height() >= host_current_height { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "client has latest height {} greater than or equal to chain height {}", - client_state_of_host_on_counterparty.latest_height(), - host_current_height - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "client has latest height {} greater than or equal to chain height {}", + client_state_of_host_on_counterparty.latest_height(), + host_current_height + ), + }); } Ok(()) @@ -121,7 +125,9 @@ where Ok(self .connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) - .ok_or(ConnectionError::MissingConnection(conn_id.clone()))?) + .ok_or(HostError::MissingData { + description: ConnectionError::MissingConnection(conn_id.clone()).to_string(), + })?) } fn commitment_prefix(&self) -> CommitmentPrefix { @@ -134,7 +140,9 @@ where Ok(self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(ConnectionError::MissingConnectionCounter)?) + .ok_or(HostError::MissingData { + description: ConnectionError::MissingConnectionCounter.to_string(), + })?) } fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { @@ -144,9 +152,12 @@ where StoreHeight::Pending, &ChannelEndPath::new(&channel_end_path.0, &channel_end_path.1), ) - .ok_or(ChannelError::NonexistentChannel { - port_id: channel_end_path.0.clone(), - channel_id: channel_end_path.1.clone(), + .ok_or(HostError::NonexistentType { + description: ChannelError::NonexistentChannel { + port_id: channel_end_path.0.clone(), + channel_id: channel_end_path.1.clone(), + } + .to_string(), })?) } @@ -157,7 +168,9 @@ where StoreHeight::Pending, &SeqSendPath::new(&seq_send_path.0, &seq_send_path.1), ) - .ok_or(PacketError::ImplementationSpecific)?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: "failed to retrieve send packet sequence from store".to_string(), + })?) } fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) -> Result { @@ -167,7 +180,9 @@ where StoreHeight::Pending, &SeqRecvPath::new(&seq_recv_path.0, &seq_recv_path.1), ) - .ok_or(PacketError::ImplementationSpecific)?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: "failed to retrieve recv packet sequence from store".to_string(), + })?) } fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { @@ -177,7 +192,9 @@ where StoreHeight::Pending, &SeqAckPath::new(&seq_ack_path.0, &seq_ack_path.1), ) - .ok_or(PacketError::ImplementationSpecific)?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: "failed to retrieve ack packet sequence from store".to_string(), + })?) } fn get_packet_commitment( @@ -194,7 +211,9 @@ where commitment_path.sequence, ), ) - .ok_or(PacketError::ImplementationSpecific)?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: "failed to retrieve packet commitment from store".to_string(), + })?) } fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { @@ -209,7 +228,12 @@ where ), ) .then_some(Receipt::Ok) - .ok_or(PacketError::MissingPacketReceipt(receipt_path.sequence))?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!( + "failed to retrieve packet receipt {0} from store", + receipt_path.sequence + ), + })?) } fn get_packet_acknowledgement( From 6f1db7b906f22ad499638c22378d8e9d4ea68be1 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 10 Sep 2024 10:56:59 -0500 Subject: [PATCH 061/107] Map errors to HostError variants --- ibc-apps/ics20-transfer/src/handler/mod.rs | 13 +- .../src/handler/on_recv_packet.rs | 6 +- .../src/handler/send_transfer.rs | 29 ++- ibc-apps/ics20-transfer/src/lib.rs | 2 + ibc-apps/ics20-transfer/types/src/error.rs | 5 - .../src/handler/upgrade_client.rs | 11 +- ibc-core/ics02-client/types/src/error.rs | 36 +-- .../cosmos/src/upgrade_proposal/plan.rs | 20 +- .../cosmos/src/upgrade_proposal/proposal.rs | 26 +-- ibc-core/ics24-host/types/src/error.rs | 7 +- ibc-query/src/core/context.rs | 25 +-- .../src/testapp/ibc/core/client_ctx.rs | 68 +++--- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 205 ++++++++++-------- .../tests/core/ics02_client/upgrade_client.rs | 9 +- 14 files changed, 241 insertions(+), 221 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index a6cbc3237..7d213d197 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -2,10 +2,13 @@ mod on_recv_packet; mod send_transfer; +use alloc::string::ToString; + use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::is_sender_chain_source; use ibc_app_transfer_types::packet::PacketData; -use ibc_core::channel::types::packet::Packet; +use ibc_core::{channel::types::packet::Packet, host::types::error::HostError}; + pub use on_recv_packet::*; pub use send_transfer::*; @@ -20,7 +23,9 @@ pub fn refund_packet_token_execute( .sender .clone() .try_into() - .map_err(|_| TokenTransferError::FailedToParseAccount)?; + .map_err(|_| HostError::FailedToParseData { + description: "invalid signer".to_string(), + })?; if is_sender_chain_source( packet.port_id_on_a.clone(), @@ -49,7 +54,9 @@ pub fn refund_packet_token_validate( .sender .clone() .try_into() - .map_err(|_| TokenTransferError::FailedToParseAccount)?; + .map_err(|_| HostError::FailedToParseData { + description: "invalid signer".to_string(), + })?; if is_sender_chain_source( packet.port_id_on_a.clone(), diff --git a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs index 76e22b3b6..e13b2ec25 100644 --- a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs +++ b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs @@ -3,6 +3,7 @@ use ibc_app_transfer_types::events::DenomTraceEvent; use ibc_app_transfer_types::packet::PacketData; use ibc_app_transfer_types::{is_receiver_chain_source, TracePrefix}; use ibc_core::channel::types::packet::Packet; +use ibc_core::host::types::error::HostError; use ibc_core::primitives::prelude::*; use ibc_core::router::types::module::ModuleExtras; @@ -26,7 +27,10 @@ pub fn process_recv_packet_execute( let receiver_account = data.receiver.clone().try_into().map_err(|_| { ( ModuleExtras::empty(), - TokenTransferError::FailedToParseAccount, + HostError::FailedToParseData { + description: "account ID".to_string(), + } + .into(), ) })?; diff --git a/ibc-apps/ics20-transfer/src/handler/send_transfer.rs b/ibc-apps/ics20-transfer/src/handler/send_transfer.rs index 39d40ea46..3d0c59b5d 100644 --- a/ibc-apps/ics20-transfer/src/handler/send_transfer.rs +++ b/ibc-apps/ics20-transfer/src/handler/send_transfer.rs @@ -6,6 +6,7 @@ use ibc_core::channel::context::{SendPacketExecutionContext, SendPacketValidatio use ibc_core::channel::handler::{send_packet_execute, send_packet_validate}; use ibc_core::channel::types::packet::Packet; use ibc_core::handler::types::events::MessageEvent; +use ibc_core::host::types::error::HostError; use ibc_core::host::types::path::{ChannelEndPath, SeqSendPath}; use ibc_core::primitives::prelude::*; use ibc_core::router::types::event::ModuleEvent; @@ -56,12 +57,14 @@ where let token = &msg.packet_data.token; - let sender: TokenCtx::AccountId = msg - .packet_data - .sender - .clone() - .try_into() - .map_err(|_| TokenTransferError::FailedToParseAccount)?; + let sender: TokenCtx::AccountId = + msg.packet_data + .sender + .clone() + .try_into() + .map_err(|_| HostError::FailedToParseData { + description: "invalid signer".to_string(), + })?; if is_sender_chain_source( msg.port_id_on_a.clone(), @@ -129,12 +132,14 @@ where let token = &msg.packet_data.token; - let sender = msg - .packet_data - .sender - .clone() - .try_into() - .map_err(|_| TokenTransferError::FailedToParseAccount)?; + let sender = + msg.packet_data + .sender + .clone() + .try_into() + .map_err(|_| HostError::FailedToParseData { + description: "invalid signer".to_string(), + })?; if is_sender_chain_source( msg.port_id_on_a.clone(), diff --git a/ibc-apps/ics20-transfer/src/lib.rs b/ibc-apps/ics20-transfer/src/lib.rs index 2f2bec601..12691afaa 100644 --- a/ibc-apps/ics20-transfer/src/lib.rs +++ b/ibc-apps/ics20-transfer/src/lib.rs @@ -13,6 +13,8 @@ )] #![allow(clippy::result_large_err)] +extern crate alloc; + #[cfg(any(test, feature = "std"))] extern crate std; diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 6158ef0f1..47c6c46ff 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -39,11 +39,6 @@ pub enum TokenTransferError { UnsupportedClosedChannel, /// empty base denomination EmptyBaseDenom, - - // TODO(seanchen1991): Used in basecoin; this variant should be moved - // to a host-relevant error - /// failed to parse account ID - FailedToParseAccount, } #[cfg(feature = "std")] diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index 4ddcdc734..195ca4da8 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -1,11 +1,11 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgUpgradeAnyClient`. //! use ibc_core_client_context::prelude::*; -use ibc_core_client_types::error::ClientError; use ibc_core_client_types::events::UpgradeClient; use ibc_core_client_types::msgs::MsgUpgradeClient; use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; +use ibc_core_host::types::error::HostError; use ibc_core_host::types::path::ClientConsensusStatePath; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; @@ -38,9 +38,12 @@ where ); let old_consensus_state = client_val_ctx .consensus_state(&old_client_cons_state_path) - .map_err(|_| ClientError::MissingConsensusState { - client_id, - height: old_client_state.latest_height(), + .map_err(|_| HostError::MissingData { + description: format!( + "missing consensus state for client {0} at height {1}", + client_id, + old_client_state.latest_height() + ), })?; // Validate the upgraded client state and consensus state and verify proofs against the root diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index a1135f49e..aa82b8348 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -9,7 +9,6 @@ use ibc_core_host_types::error::HostError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; -use tendermint::Error as TendermintError; use crate::height::Height; use crate::Status; @@ -41,6 +40,8 @@ pub enum ClientError { InvalidAttributeValue(String), /// invalid status: `{0}` InvalidStatus(String), + /// invalid header type: `{0}` + InvalidHeaderType(String), /// missing local consensus state at `{0}` MissingLocalConsensusState(Height), /// missing attribute key @@ -64,21 +65,10 @@ pub enum ClientError { FailedHeaderVerification { description: String }, /// failed misbehaviour handling: `{description}` FailedMisbehaviourHandling { description: String }, - /// client-specific error: `{description}` - ClientSpecific { description: String }, - // TODO(seanchen1991): Add these to host-relevant errors - /// missing client state for client: `{0}` - MissingClientState(ClientId), - /// missing consensus state for client `{client_id}` at height `{height}` - MissingConsensusState { client_id: ClientId, height: Height }, - /// missing update client metadata for client `{client_id}` at height `{height}` - MissingUpdateMetaData { client_id: ClientId, height: Height }, - /// invalid raw header: `{0}` - InvalidRawHeader(TendermintError), - /// invalid header type: `{0}` - InvalidHeaderType(String), // TODO(seanchen1991): Incorporate this error into its own variants + /// client-specific error: `{description}` + ClientSpecific { description: String }, /// other error: `{description}` Other { description: String }, } @@ -131,6 +121,8 @@ impl std::error::Error for ClientError { pub enum UpgradeClientError { /// decoding error: `{0}` Decoding(DecodingError), + /// invalid upgrade proposal: `{description}` + InvalidUpgradeProposal { description: String }, /// invalid proof for the upgraded client state: `{0}` InvalidUpgradeClientStateProof(CommitmentError), /// invalid proof for the upgraded consensus state: `{0}` @@ -144,22 +136,6 @@ pub enum UpgradeClientError { upgraded_height: Height, client_height: Height, }, - - // TODO(seanchen1991): Move these variants to host-relevant errors - /// invalid upgrade plan: `{description}` - InvalidUpgradePlan { description: String }, - /// invalid upgrade proposal: `{description}` - InvalidUpgradeProposal { description: String }, - /// missing upgraded client state - MissingUpgradedClientState, - /// missing upgraded consensus state - MissingUpgradedConsensusState, - /// failed to store upgrade plan: `{description}` - FailedToStoreUpgradePlan { description: String }, - /// failed to store upgraded client state: `{description}` - FailedToStoreUpgradedClientState { description: String }, - /// failed to store upgraded consensus state: `{description}` - FailedToStoreUpgradedConsensusState { description: String }, } impl From for ClientError { diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index 48ceaf0e5..ccba17567 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -1,7 +1,7 @@ //! Definition of domain `Plan` type. use ibc_core_client_types::error::UpgradeClientError; -use ibc_core_host_types::error::DecodingError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_primitives::prelude::*; use ibc_proto::cosmos::upgrade::v1beta1::Plan as RawPlan; use ibc_proto::google::protobuf::Any; @@ -29,35 +29,33 @@ pub struct Plan { impl Protobuf for Plan {} impl TryFrom for Plan { - type Error = UpgradeClientError; + type Error = DecodingError; fn try_from(raw: RawPlan) -> Result { if raw.name.is_empty() { - return Err(UpgradeClientError::InvalidUpgradePlan { - description: "name field cannot be empty".to_string(), + return Err(DecodingError::InvalidRawData { + description: "upgrade plan name cannot be empty".to_string(), }); } #[allow(deprecated)] if raw.time.is_some() { - return Err(UpgradeClientError::InvalidUpgradePlan { - description: "time field must be empty".to_string(), + return Err(DecodingError::InvalidRawData { + description: "upgrade plan time must be empty".to_string(), }); } #[allow(deprecated)] if raw.upgraded_client_state.is_some() { - return Err(UpgradeClientError::InvalidUpgradePlan { - description: "upgraded_client_state field must be empty".to_string(), + return Err(DecodingError::InvalidRawData { + description: "upgrade plan `upgraded_client_state` field must be empty".to_string(), }); } Ok(Self { name: raw.name, height: u64::try_from(raw.height).map_err(|_| { - UpgradeClientError::InvalidUpgradePlan { - description: "height plan overflow".to_string(), - } + DecodingError::Identifier(IdentifierError::OverflowedRevisionNumber) })?, info: raw.info, }) diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs index f069e6852..4ffacfa3c 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs @@ -1,6 +1,6 @@ //! Definition of domain `UpgradeProposal` type for handling upgrade client proposal -use ibc_core_client_types::error::UpgradeClientError; +use ibc_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::UpgradeProposal as RawUpgradeProposal; @@ -28,34 +28,34 @@ pub struct UpgradeProposal { impl Protobuf for UpgradeProposal {} impl TryFrom for UpgradeProposal { - type Error = UpgradeClientError; + type Error = DecodingError; fn try_from(raw: RawUpgradeProposal) -> Result { if raw.title.is_empty() { - return Err(UpgradeClientError::InvalidUpgradeProposal { - description: "missing title field".to_string(), + return Err(DecodingError::InvalidRawData { + description: "upgrade proposal missing title field".to_string(), }); } if raw.description.is_empty() { - return Err(UpgradeClientError::InvalidUpgradeProposal { - description: "missing description field".to_string(), + return Err(DecodingError::InvalidRawData { + description: "upgrade proposal missing description field".to_string(), }); } let plan = if let Some(plan) = raw.plan { plan.try_into()? } else { - return Err(UpgradeClientError::InvalidUpgradeProposal { - description: "missing plan field".to_string(), + return Err(DecodingError::InvalidRawData { + description: "upgrade proposal missing plan field".to_string(), }); }; - let upgraded_client_state = raw.upgraded_client_state.ok_or_else(|| { - UpgradeClientError::InvalidUpgradeProposal { - description: "missing upgraded client state".to_string(), - } - })?; + let upgraded_client_state = + raw.upgraded_client_state + .ok_or_else(|| DecodingError::InvalidRawData { + description: "upgrade proposal missing upgraded client state".to_string(), + })?; Ok(Self { title: raw.title, diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index e951b43b6..76e00a100 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -5,9 +5,10 @@ use core::str::Utf8Error; use base64::DecodeError as Base64Error; use displaydoc::Display; +use prost::DecodeError as ProstError; + use ibc_primitives::prelude::*; use ibc_primitives::proto::Error as ProtoError; -use prost::DecodeError as ProstError; /// Errors that originate from host implementations. #[derive(Debug, Display)] @@ -18,8 +19,8 @@ pub enum HostError { MissingData { description: String }, /// unexpected data: `{description}` UnexpectedData { description: String }, - /// failed to update state: `{description}` - FailedToUpdateState { description: String }, + /// failed to update store: `{description}` + FailedToUpdateStore { description: String }, /// failed to store data: `{description}` FailedToStoreData { description: String }, /// failed to retrieve data from store: `{description}` diff --git a/ibc-query/src/core/context.rs b/ibc-query/src/core/context.rs index 540b7a690..7f29306c6 100644 --- a/ibc-query/src/core/context.rs +++ b/ibc-query/src/core/context.rs @@ -4,7 +4,7 @@ use ibc::core::channel::types::channel::IdentifiedChannelEnd; use ibc::core::channel::types::packet::PacketState; use ibc::core::client::types::Height; use ibc::core::connection::types::IdentifiedConnectionEnd; -use ibc::core::handler::types::error::HandlerError; +use ibc::core::host::types::error::HostError; use ibc::core::host::types::identifiers::{ClientId, ConnectionId, Sequence}; use ibc::core::host::types::path::{ChannelEndPath, Path}; use ibc::core::host::{ClientStateRef, ConsensusStateRef, ValidationContext}; @@ -22,32 +22,29 @@ pub trait QueryContext: ProvableContext + ValidationContext { // Client queries /// Returns the list of all clients. - fn client_states(&self) -> Result)>, HandlerError>; + fn client_states(&self) -> Result)>, HostError>; /// Returns the list of all consensus states for the given client. fn consensus_states( &self, client_id: &ClientId, - ) -> Result)>, HandlerError>; + ) -> Result)>, HostError>; /// Returns the list of all heights at which consensus states for the given client are. - fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError>; + fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HostError>; // Connection queries /// Returns the list of all connection ends. - fn connection_ends(&self) -> Result, HandlerError>; + fn connection_ends(&self) -> Result, HostError>; /// Returns the list of all connection ids of the given client. - fn client_connection_ends( - &self, - client_id: &ClientId, - ) -> Result, HandlerError>; + fn client_connection_ends(&self, client_id: &ClientId) -> Result, HostError>; // Channel queries /// Returns the list of all channel ends. - fn channel_ends(&self) -> Result, HandlerError>; + fn channel_ends(&self) -> Result, HostError>; // Packet queries @@ -55,7 +52,7 @@ pub trait QueryContext: ProvableContext + ValidationContext { fn packet_commitments( &self, channel_end_path: &ChannelEndPath, - ) -> Result, HandlerError>; + ) -> Result, HostError>; /// Filters the list of packet sequences for the given channel end that are acknowledged. /// Returns all the packet acknowledgements if `sequences` is empty. @@ -63,14 +60,14 @@ pub trait QueryContext: ProvableContext + ValidationContext { &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, HandlerError>; + ) -> Result, HostError>; /// Filters the packet sequences for the given channel end that are not received. fn unreceived_packets( &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, HandlerError>; + ) -> Result, HostError>; /// Filters the list of packet sequences for the given channel end whose acknowledgement is not received. /// Returns all the unreceived acknowledgements if `sequences` is empty. @@ -78,5 +75,5 @@ pub trait QueryContext: ProvableContext + ValidationContext { &self, channel_end_path: &ChannelEndPath, sequences: impl ExactSizeIterator, - ) -> Result, HandlerError>; + ) -> Result, HostError>; } diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index d7ba951a5..d55c654c0 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -5,7 +5,6 @@ use basecoin_store::types::Height as StoreHeight; use ibc::core::client::context::{ ClientExecutionContext, ClientValidationContext, ExtClientValidationContext, }; -use ibc::core::client::types::error::ClientError; use ibc::core::client::types::Height; use ibc::core::host::types::error::HostError; use ibc::core::host::types::identifiers::{ChannelId, ClientId, PortId}; @@ -73,13 +72,13 @@ where } }) .map(|consensus_path| { - Ok(Height::new( + Height::new( consensus_path.revision_number, consensus_path.revision_height, ) .map_err(|e| HostError::InvalidData { description: e.to_string(), - })?) + }) }) .collect::, _>>() } @@ -107,9 +106,12 @@ where .map(|path| { self.consensus_state_store .get(StoreHeight::Pending, &path) - .ok_or_else(|| ClientError::MissingConsensusState { - client_id: client_id.clone(), - height: *height, + .ok_or_else(|| HostError::FailedToRetrieveFromStore { + description: format!( + "missing consensus state for client {0} at height {1}", + client_id.clone(), + *height + ), }) }) .transpose() @@ -143,9 +145,12 @@ where .map(|path| { self.consensus_state_store .get(StoreHeight::Pending, &path) - .ok_or_else(|| ClientError::MissingConsensusState { - client_id: client_id.clone(), - height: *height, + .ok_or_else(|| HostError::FailedToRetrieveFromStore { + description: format!( + "missing consensus state for client {0} at height {1}", + client_id.clone(), + *height + ), }) }) .transpose() @@ -165,12 +170,11 @@ where type ConsensusStateRef = AnyConsensusState; fn client_state(&self, client_id: &ClientId) -> Result { - Ok(self - .client_state_store + self.client_state_store .get(StoreHeight::Pending, &ClientStatePath(client_id.clone())) - .ok_or(HostError::MissingData { - description: ClientError::MissingClientState(client_id.clone()).to_string(), - })?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!("missing client state for client {0}", client_id.clone()), + }) } fn consensus_state( @@ -187,12 +191,12 @@ where let consensus_state = self .consensus_state_store .get(StoreHeight::Pending, client_cons_state_path) - .ok_or(HostError::MissingData { - description: ClientError::MissingConsensusState { - client_id: client_cons_state_path.client_id.clone(), - height, - } - .to_string(), + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!( + "missing consensus state for client {0} at height {1}", + client_cons_state_path.client_id.clone(), + height + ), })?; Ok(consensus_state) @@ -213,12 +217,12 @@ where let processed_timestamp = self .client_processed_times .get(StoreHeight::Pending, &client_update_time_path) - .ok_or(HostError::MissingData { - description: ClientError::MissingUpdateMetaData { - client_id: client_id.clone(), - height: *height, - } - .to_string(), + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!( + "missing client update metadata for client {0} at height {1}", + client_id.clone(), + *height, + ), })?; let client_update_height_path = ClientUpdateHeightPath::new( client_id.clone(), @@ -228,12 +232,12 @@ where let processed_height = self .client_processed_heights .get(StoreHeight::Pending, &client_update_height_path) - .ok_or(HostError::MissingData { - description: ClientError::MissingUpdateMetaData { - client_id: client_id.clone(), - height: *height, - } - .to_string(), + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!( + "missing client update metadata for client {0} at height {1}", + client_id.clone(), + *height, + ), })?; Ok((processed_timestamp, processed_height)) diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index cc0e45a6a..6af4181cf 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -7,7 +7,7 @@ use basecoin_store::context::{ProvableStore, Store}; use basecoin_store::types::Height as StoreHeight; use ibc::core::channel::types::channel::{ChannelEnd, IdentifiedChannelEnd}; use ibc::core::channel::types::commitment::{AcknowledgementCommitment, PacketCommitment}; -use ibc::core::channel::types::error::{ChannelError, PacketError}; +use ibc::core::channel::types::error::ChannelError; use ibc::core::channel::types::packet::{PacketState, Receipt}; use ibc::core::client::context::consensus_state::ConsensusState; use ibc::core::client::types::error::ClientError; @@ -43,13 +43,11 @@ where type HostConsensusState = AnyConsensusState; fn host_height(&self) -> Result { - Ok( - Height::new(*self.revision_number.lock(), self.store.current_height()).map_err( - |e| HostError::InvalidData { - description: e.to_string(), - }, - )?, - ) + Height::new(*self.revision_number.lock(), self.store.current_height()).map_err(|e| { + HostError::InvalidData { + description: e.to_string(), + } + }) } fn host_timestamp(&self) -> Result { @@ -59,23 +57,22 @@ where } fn client_counter(&self) -> Result { - Ok(self - .client_counter + self.client_counter .get(StoreHeight::Pending, &NextClientSequencePath) .ok_or(HostError::MissingData { description: "client counter not found".to_string(), - })?) + }) } fn host_consensus_state(&self, height: &Height) -> Result { let consensus_states_binding = self.host_consensus_states.lock(); - Ok(consensus_states_binding + consensus_states_binding .get(&height.revision_height()) .cloned() .ok_or(HostError::MissingData { description: ClientError::MissingLocalConsensusState(*height).to_string(), - })?) + }) } fn validate_self_client( @@ -122,12 +119,11 @@ where } fn connection_end(&self, conn_id: &ConnectionId) -> Result { - Ok(self - .connection_end_store + self.connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) .ok_or(HostError::MissingData { description: ConnectionError::MissingConnection(conn_id.clone()).to_string(), - })?) + }) } fn commitment_prefix(&self) -> CommitmentPrefix { @@ -137,17 +133,15 @@ where } fn connection_counter(&self) -> Result { - Ok(self - .conn_counter + self.conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) .ok_or(HostError::MissingData { description: ConnectionError::MissingConnectionCounter.to_string(), - })?) + }) } fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { - Ok(self - .channel_end_store + self.channel_end_store .get( StoreHeight::Pending, &ChannelEndPath::new(&channel_end_path.0, &channel_end_path.1), @@ -158,51 +152,47 @@ where channel_id: channel_end_path.1.clone(), } .to_string(), - })?) + }) } fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result { - Ok(self - .send_sequence_store + self.send_sequence_store .get( StoreHeight::Pending, &SeqSendPath::new(&seq_send_path.0, &seq_send_path.1), ) .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve send packet sequence from store".to_string(), - })?) + description: "failed to retrieve send packet sequence".to_string(), + }) } fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) -> Result { - Ok(self - .recv_sequence_store + self.recv_sequence_store .get( StoreHeight::Pending, &SeqRecvPath::new(&seq_recv_path.0, &seq_recv_path.1), ) .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve recv packet sequence from store".to_string(), - })?) + description: "failed to retrieve recv packet sequence".to_string(), + }) } fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { - Ok(self - .ack_sequence_store + self.ack_sequence_store .get( StoreHeight::Pending, &SeqAckPath::new(&seq_ack_path.0, &seq_ack_path.1), ) .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve ack packet sequence from store".to_string(), - })?) + description: "failed to retrieve ack packet sequence".to_string(), + }) } fn get_packet_commitment( &self, commitment_path: &CommitmentPath, ) -> Result { - Ok(self - .packet_commitment_store + self.packet_commitment_store .get( StoreHeight::Pending, &CommitmentPath::new( @@ -212,13 +202,12 @@ where ), ) .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve packet commitment from store".to_string(), - })?) + description: "failed to retrieve packet commitment".to_string(), + }) } fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { - Ok(self - .packet_receipt_store + self.packet_receipt_store .is_path_set( StoreHeight::Pending, &ReceiptPath::new( @@ -230,33 +219,38 @@ where .then_some(Receipt::Ok) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "failed to retrieve packet receipt {0} from store", + "failed to retrieve packet receipt {0}", receipt_path.sequence ), - })?) + }) } fn get_packet_acknowledgement( &self, ack_path: &AckPath, ) -> Result { - Ok(self - .packet_ack_store + self.packet_ack_store .get( StoreHeight::Pending, &AckPath::new(&ack_path.port_id, &ack_path.channel_id, ack_path.sequence), ) - .ok_or(PacketError::MissingPacketAcknowledgment(ack_path.sequence))?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!( + "failed to retrieve packet acknowledgment {0}", + ack_path.sequence + ), + }) } /// Returns a counter of the number of channel ids that have been created thus far. /// The value of this counter should increase only via the /// `ChannelKeeper::increase_channel_counter` method. fn channel_counter(&self) -> Result { - Ok(self - .channel_counter + self.channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(ChannelError::MissingCounter)?) + .ok_or(HostError::FailedToRetrieveFromStore { + description: "failed to retrieve channel counter".to_string(), + }) } /// Returns the maximum expected time per block @@ -321,7 +315,12 @@ where let client_state = self .client_state_store .get(StoreHeight::Pending, &client_state_path) - .ok_or_else(|| ClientError::MissingClientState(client_state_path.0.clone()))?; + .ok_or_else(|| HostError::FailedToRetrieveFromStore { + description: format!( + "failed to retrieve client state from path {0}", + client_state_path.0.clone() + ), + })?; Ok((client_state_path.0, client_state)) }) .collect() @@ -332,11 +331,7 @@ where &self, client_id: &ClientId, ) -> Result)>, HostError> { - let path = format!("clients/{}/consensusStates", client_id) - .try_into() - .map_err(|_| ClientError::Other { - description: "Invalid consensus state path".into(), - })?; + let path = format!("clients/{}/consensusStates", client_id).into(); self.consensus_state_store .get_keys(&path) @@ -352,15 +347,18 @@ where let height = Height::new( consensus_path.revision_number, consensus_path.revision_height, - )?; + ) + .map_err(|e| HostError::InvalidData { + description: e.to_string(), + })?; let client_state = self .consensus_state_store .get(StoreHeight::Pending, &consensus_path) - .ok_or({ - ClientError::MissingConsensusState { - client_id: consensus_path.client_id, - height, - } + .ok_or(HostError::FailedToRetrieveFromStore { + description: format!( + "missing consensus state for client {0} at height {1}", + consensus_path.client_id, height, + ), })?; Ok((height, client_state)) }) @@ -369,11 +367,7 @@ where /// Returns the list of heights at which the consensus state of the given client was updated. fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HostError> { - let path = format!("clients/{}/consensusStates", client_id) - .try_into() - .map_err(|_| ClientError::Other { - description: "Invalid consensus state path".into(), - })?; + let path = format!("clients/{}/consensusStates", client_id).into(); self.consensus_state_store .get_keys(&path) @@ -386,10 +380,13 @@ where } }) .map(|consensus_path| { - Ok(Height::new( + Height::new( consensus_path.revision_number, consensus_path.revision_height, - )?) + ) + .map_err(|e| HostError::InvalidData { + description: e.to_string(), + }) }) .collect::, _>>() } @@ -412,7 +409,9 @@ where let connection_end = self .connection_end_store .get(StoreHeight::Pending, &connection_path) - .ok_or_else(|| ConnectionError::MissingConnection(connection_path.0.clone()))?; + .ok_or_else(|| HostError::FailedToRetrieveFromStore { + description: format!("missing connection {0}", connection_path.0.clone()), + })?; Ok(IdentifiedConnectionEnd { connection_id: connection_path.0, connection_end, @@ -449,9 +448,12 @@ where let channel_end = self .channel_end_store .get(StoreHeight::Pending, &channel_path) - .ok_or_else(|| ChannelError::NonexistentChannel { - port_id: channel_path.0.clone(), - channel_id: channel_path.1.clone(), + .ok_or_else(|| HostError::FailedToRetrieveFromStore { + description: format!( + "missing channel {0} with port {1}", + channel_path.1.clone(), + channel_path.0.clone() + ), })?; Ok(IdentifiedChannelEnd { port_id: channel_path.0, @@ -641,14 +643,14 @@ where let current_sequence = self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(ClientError::Other { - description: "client counter not found".into(), + .ok_or(HostError::FailedToRetrieveFromStore { + description: "missing client counter".to_string(), })?; self.client_counter .set(NextClientSequencePath, current_sequence + 1) - .map_err(|e| ClientError::Other { - description: format!("client counter update failed: {e:?}"), + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to update client counter: {e:?}"), })?; Ok(()) @@ -662,7 +664,9 @@ where ) -> Result<(), HostError> { self.connection_end_store .set(connection_path.clone(), connection_end) - .map_err(|_| ConnectionError::FailedToStoreConnectionEnd)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to set connection end: {e:?}"), + })?; Ok(()) } @@ -679,7 +683,9 @@ where conn_ids.push(conn_id); self.connection_ids_store .set(client_connection_path.clone(), conn_ids) - .map_err(|_| ConnectionError::FailedToStoreConnectionIds)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store connection IDs: {e:?}"), + })?; Ok(()) } @@ -689,11 +695,15 @@ where let current_sequence = self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(ConnectionError::MissingConnectionCounter)?; + .ok_or(HostError::FailedToRetrieveFromStore { + description: "missing connection counter".to_string(), + })?; self.conn_counter .set(NextConnectionSequencePath, current_sequence + 1) - .map_err(|_| ConnectionError::FailedToUpdateConnectionCounter)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to update connection counter: {e:?}"), + })?; Ok(()) } @@ -705,7 +715,9 @@ where ) -> Result<(), HostError> { self.packet_commitment_store .set(commitment_path.clone(), commitment) - .map_err(|_| PacketError::ImplementationSpecific)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store packet commitment: {e:?}"), + })?; Ok(()) } @@ -724,7 +736,9 @@ where ) -> Result<(), HostError> { self.packet_receipt_store .set_path(receipt_path.clone()) - .map_err(|_| PacketError::ImplementationSpecific)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store packet receipt: {e:?}"), + })?; Ok(()) } @@ -735,7 +749,9 @@ where ) -> Result<(), HostError> { self.packet_ack_store .set(ack_path.clone(), ack_commitment) - .map_err(|_| PacketError::ImplementationSpecific)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store packet acknowledgment: {e:?}"), + })?; Ok(()) } @@ -751,8 +767,8 @@ where ) -> Result<(), HostError> { self.channel_end_store .set(channel_end_path.clone(), channel_end) - .map_err(|e| ChannelError::FailedToStoreChannel { - description: format!("{e:?}"), + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store channel: {e:?}"), })?; Ok(()) } @@ -764,7 +780,9 @@ where ) -> Result<(), HostError> { self.send_sequence_store .set(seq_send_path.clone(), seq) - .map_err(|_| PacketError::ImplementationSpecific)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store send sequence: {e:?}"), + })?; Ok(()) } @@ -775,7 +793,9 @@ where ) -> Result<(), HostError> { self.recv_sequence_store .set(seq_recv_path.clone(), seq) - .map_err(|_| PacketError::ImplementationSpecific)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store recv sequence: {e:?}"), + })?; Ok(()) } @@ -786,7 +806,9 @@ where ) -> Result<(), HostError> { self.ack_sequence_store .set(seq_ack_path.clone(), seq) - .map_err(|_| PacketError::ImplementationSpecific)?; + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to store ack sequence: {e:?}"), + })?; Ok(()) } @@ -794,14 +816,15 @@ where let current_sequence = self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(ChannelError::MissingCounter)?; + .ok_or(HostError::FailedToRetrieveFromStore { + description: "missing counter".to_string(), + })?; self.channel_counter .set(NextChannelSequencePath, current_sequence + 1) - .map_err(|e| ChannelError::FailedToUpdateCounter { - description: format!("{e:?}"), + .map_err(|e| HostError::FailedToUpdateStore { + description: format!("failed to update counter: {e:?}"), })?; - Ok(()) } diff --git a/tests-integration/tests/core/ics02_client/upgrade_client.rs b/tests-integration/tests/core/ics02_client/upgrade_client.rs index 8f44f3e1c..ed09d154a 100644 --- a/tests-integration/tests/core/ics02_client/upgrade_client.rs +++ b/tests-integration/tests/core/ics02_client/upgrade_client.rs @@ -8,6 +8,7 @@ use ibc::core::handler::types::error::HandlerError; use ibc::core::handler::types::events::{IbcEvent, MessageEvent}; use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::path::ClientConsensusStatePath; +use ibc_core_host_types::error::HostError; use ibc_testkit::context::MockContext; use ibc_testkit::fixtures::clients::tendermint::{ dummy_tm_client_state_from_header, dummy_valid_tendermint_header, @@ -142,8 +143,12 @@ fn msg_upgrade_client_healthy() { #[test] fn upgrade_client_fail_nonexisting_client() { let fxt = msg_upgrade_client_fixture(Ctx::Default, Msg::Default); - let expected_err = - HandlerError::Client(ClientError::MissingClientState(fxt.msg.client_id.clone())); + let expected_err = HandlerError::Host(HostError::MissingData { + description: format!( + "missing client state for client {0}", + fxt.msg.client_id.clone() + ), + }); upgrade_client_validate(&fxt, Expect::Failure(Some(expected_err))); } From e714eb94a8e47f07cddb1a29012705c0e2526c5c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 10 Sep 2024 11:15:40 -0500 Subject: [PATCH 062/107] Update ValidateSelfClientContext trait --- .../cosmos/src/validate_self_client.rs | 122 ++++++++---------- ibc-core/ics24-host/types/src/error.rs | 2 + 2 files changed, 59 insertions(+), 65 deletions(-) diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index ff870c051..46e2cfc94 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -1,11 +1,9 @@ use core::time::Duration; use ibc_client_tendermint::types::ClientState as TmClientState; -use ibc_core_client_types::error::ClientError; -use ibc_core_client_types::{Height, Status}; +use ibc_core_client_types::Height; use ibc_core_commitment_types::specs::ProofSpecs; -use ibc_core_connection_types::error::ConnectionError; -use ibc_core_handler_types::error::HandlerError; +use ibc_core_host_types::error::HostError; use ibc_core_host_types::identifiers::ChainId; use ibc_primitives::prelude::*; use tendermint::trust_threshold::TrustThresholdFraction as TendermintTrustThresholdFraction; @@ -19,63 +17,61 @@ pub trait ValidateSelfClientContext { fn validate_self_tendermint_client( &self, client_state_of_host_on_counterparty: TmClientState, - ) -> Result<(), HandlerError> { + ) -> Result<(), HostError> { client_state_of_host_on_counterparty .validate() - .map_err(ClientError::from)?; + .map_err(|e| HostError::FailedToValidateClient { + description: e.to_string(), + })?; if client_state_of_host_on_counterparty.is_frozen() { - return Err(ClientError::UnexpectedStatus(Status::Frozen).into()); + return Err(HostError::UnexpectedData { + description: "client unexpectedly frozen".to_string(), + }); } let self_chain_id = self.chain_id(); + if self_chain_id != &client_state_of_host_on_counterparty.chain_id { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "invalid chain-id. expected: {}, got: {}", - self_chain_id, client_state_of_host_on_counterparty.chain_id - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "invalid chain ID: expected {}, actual {}", + self_chain_id, client_state_of_host_on_counterparty.chain_id + ), + }); } let latest_height = client_state_of_host_on_counterparty.latest_height; let self_revision_number = self_chain_id.revision_number(); + if self_revision_number != latest_height.revision_number() { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "client is not in the same revision as the chain. expected: {}, got: {}", - self_revision_number, - latest_height.revision_number() - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "mismatched client revision numbers; expected {}, actual {}", + self_revision_number, + latest_height.revision_number() + ), + }); } if latest_height >= self.host_current_height() { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "client has latest height {} greater than or equal to chain height {}", - latest_height, - self.host_current_height() - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "client latest height {} should be less than chain height {}", + latest_height, + self.host_current_height() + ), + }); } if self.proof_specs() != &client_state_of_host_on_counterparty.proof_specs { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "client has invalid proof specs. expected: {:?}, got: {:?}", - self.proof_specs(), - client_state_of_host_on_counterparty.proof_specs - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "invalid client proof specs; expected {:?}, actual {:?}", + self.proof_specs(), + client_state_of_host_on_counterparty.proof_specs + ), + }); } let _ = { @@ -85,45 +81,41 @@ pub trait ValidateSelfClientContext { trust_level.numerator(), trust_level.denominator(), ) - .map_err(|_| ConnectionError::InvalidClientState { - description: "invalid trust level".to_string(), + .map_err(|e| HostError::InvalidData { + description: e.to_string(), })? }; if self.unbonding_period() != client_state_of_host_on_counterparty.unbonding_period { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "invalid unbonding period. expected: {:?}, got: {:?}", - self.unbonding_period(), - client_state_of_host_on_counterparty.unbonding_period, - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "invalid unbonding period; expected {:?}, actual {:?}", + self.unbonding_period(), + client_state_of_host_on_counterparty.unbonding_period, + ), + }); } if client_state_of_host_on_counterparty.unbonding_period < client_state_of_host_on_counterparty.trusting_period { - return Err(HandlerError::Connection(ConnectionError::InvalidClientState{ description: format!( - "unbonding period must be greater than trusting period. unbonding period ({:?}) < trusting period ({:?})", + return Err(HostError::InvalidData { description: format!( + "unbonding period must be greater than trusting period; unbonding period ({:?}) < trusting period ({:?})", client_state_of_host_on_counterparty.unbonding_period, client_state_of_host_on_counterparty.trusting_period - )})); + )}); } if !client_state_of_host_on_counterparty.upgrade_path.is_empty() && self.upgrade_path() != client_state_of_host_on_counterparty.upgrade_path { - return Err(HandlerError::Connection( - ConnectionError::InvalidClientState { - description: format!( - "invalid upgrade path. expected: {:?}, got: {:?}", - self.upgrade_path(), - client_state_of_host_on_counterparty.upgrade_path - ), - }, - )); + return Err(HostError::InvalidData { + description: format!( + "invalid upgrade path; expected {:?}, actual {:?}", + self.upgrade_path(), + client_state_of_host_on_counterparty.upgrade_path + ), + }); } Ok(()) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 76e00a100..053fb715f 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -27,6 +27,8 @@ pub enum HostError { FailedToRetrieveFromStore { description: String }, /// failed to parse data: `{description}` FailedToParseData { description: String }, + /// failed to validate client: `{description}` + FailedToValidateClient { description: String }, /// non-existent type: `{description}` NonexistentType { description: String }, /// other error: `{description}` From 286e666923ec5e95079f01b4009b5825d733db97 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 10 Sep 2024 14:27:46 -0500 Subject: [PATCH 063/107] Update Upgrade validation and execution contexts to return HostErrors --- ibc-apps/ics20-transfer/src/handler/mod.rs | 4 ++-- ibc-apps/ics721-nft-transfer/src/handler/mod.rs | 5 ++--- ibc-core/ics02-client/types/src/error.rs | 5 +++-- .../src/handler/chan_close_confirm.rs | 8 +++++--- .../ics04-channel/src/handler/chan_close_init.rs | 8 +++++--- .../src/handler/chan_open_confirm.rs | 13 +++++-------- .../cosmos/src/upgrade_proposal/context.rs | 16 ++++++++-------- .../cosmos/src/upgrade_proposal/handler.rs | 10 ++++++---- ibc-core/ics24-host/types/src/error.rs | 3 +-- 9 files changed, 37 insertions(+), 35 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index 7d213d197..d84364e99 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -7,8 +7,8 @@ use alloc::string::ToString; use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::is_sender_chain_source; use ibc_app_transfer_types::packet::PacketData; -use ibc_core::{channel::types::packet::Packet, host::types::error::HostError}; - +use ibc_core::channel::types::packet::Packet; +use ibc_core::host::types::error::HostError; pub use on_recv_packet::*; pub use send_transfer::*; diff --git a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs index 80935871a..94b3f6e5b 100644 --- a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs +++ b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs @@ -3,6 +3,8 @@ mod on_recv_packet; mod send_transfer; +use ibc_core::channel::types::packet::Packet; +use ibc_core::handler::types::error::HandlerError; pub use on_recv_packet::*; pub use send_transfer::*; @@ -11,9 +13,6 @@ use crate::types::error::NftTransferError; use crate::types::is_sender_chain_source; use crate::types::packet::PacketData; -use ibc_core::channel::types::packet::Packet; -use ibc_core::handler::types::error::HandlerError; - pub fn refund_packet_nft_execute( ctx_a: &mut impl NftTransferExecutionContext, packet: &Packet, diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index aa82b8348..b911095b5 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -4,8 +4,7 @@ use core::convert::Infallible; use displaydoc::Display; use ibc_core_commitment_types::error::CommitmentError; -use ibc_core_host_types::error::DecodingError; -use ibc_core_host_types::error::HostError; +use ibc_core_host_types::error::{DecodingError, HostError}; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; @@ -131,6 +130,8 @@ pub enum UpgradeClientError { InvalidUpgradePath { description: String }, /// missing upgrade path MissingUpgradePath, + /// failed to clear upgrade plan + FailedToClearUpgradePlan, /// insufficient upgrade client height `{upgraded_height}`; must be greater than current client height `{client_height}` InsufficientUpgradeHeight { upgraded_height: Height, diff --git a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs index 19b1f2697..e9cc78d5c 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_confirm.rs @@ -58,9 +58,11 @@ where let core_event = { let port_id_on_a = chan_end_on_b.counterparty().port_id.clone(); - let chan_id_on_a = chan_end_on_b.counterparty().channel_id.clone().ok_or( - HandlerError::Channel(ChannelError::MissingCounterparty), - )?; + let chan_id_on_a = chan_end_on_b + .counterparty() + .channel_id + .clone() + .ok_or(HandlerError::Channel(ChannelError::MissingCounterparty))?; let conn_id_on_b = chan_end_on_b.connection_hops[0].clone(); IbcEvent::CloseConfirmChannel(CloseConfirm::new( diff --git a/ibc-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-core/ics04-channel/src/handler/chan_close_init.rs index 97912774b..0f0cd557d 100644 --- a/ibc-core/ics04-channel/src/handler/chan_close_init.rs +++ b/ibc-core/ics04-channel/src/handler/chan_close_init.rs @@ -56,9 +56,11 @@ where let core_event = { let port_id_on_b = chan_end_on_a.counterparty().port_id.clone(); - let chan_id_on_b = chan_end_on_a.counterparty().channel_id.clone().ok_or( - HandlerError::Channel(ChannelError::MissingCounterparty), - )?; + let chan_id_on_b = chan_end_on_a + .counterparty() + .channel_id + .clone() + .ok_or(HandlerError::Channel(ChannelError::MissingCounterparty))?; let conn_id_on_a = chan_end_on_a.connection_hops[0].clone(); IbcEvent::CloseInitChannel(CloseInit::new( diff --git a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs index b246008cf..e3ade9e35 100644 --- a/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs +++ b/ibc-core/ics04-channel/src/handler/chan_open_confirm.rs @@ -59,14 +59,11 @@ where let conn_id_on_b = chan_end_on_b.connection_hops[0].clone(); let port_id_on_a = chan_end_on_b.counterparty().port_id.clone(); - let chan_id_on_a = - chan_end_on_b - .counterparty() - .channel_id - .clone() - .ok_or(HandlerError::Channel( - ChannelError::MissingCounterparty, - ))?; + let chan_id_on_a = chan_end_on_b + .counterparty() + .channel_id + .clone() + .ok_or(HandlerError::Channel(ChannelError::MissingCounterparty))?; let core_event = IbcEvent::OpenConfirmChannel(OpenConfirm::new( msg.port_id_on_b.clone(), diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/context.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/context.rs index 1328355e8..89ec14ff3 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/context.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/context.rs @@ -6,7 +6,7 @@ //! If it proves to be generic enough, we may move it to the ICS02 section. use ibc_core_client_context::ClientValidationContext; -use ibc_core_client_types::error::UpgradeClientError; +use ibc_core_host_types::error::HostError; use ibc_core_host_types::path::{UpgradeClientStatePath, UpgradeConsensusStatePath}; use super::Plan; @@ -23,41 +23,41 @@ pub trait UpgradeValidationContext { type V: ClientValidationContext; /// Returns the upgrade plan that is scheduled and has not been executed yet. - fn upgrade_plan(&self) -> Result; + fn upgrade_plan(&self) -> Result; /// Returns the upgraded client state at the specified upgrade path. fn upgraded_client_state( &self, upgrade_path: &UpgradeClientStatePath, - ) -> Result, UpgradeClientError>; + ) -> Result, HostError>; /// Returns the upgraded consensus state at the specified upgrade path. fn upgraded_consensus_state( &self, upgrade_path: &UpgradeConsensusStatePath, - ) -> Result, UpgradeClientError>; + ) -> Result, HostError>; } /// Helper context to execute client upgrades, providing methods to schedule /// an upgrade and store related upgraded client and consensus states. pub trait UpgradeExecutionContext: UpgradeValidationContext { /// Schedules an upgrade based on the specified plan. If there is another `Plan` it should be overwritten. - fn schedule_upgrade(&mut self, plan: Plan) -> Result<(), UpgradeClientError>; + fn schedule_upgrade(&mut self, plan: Plan) -> Result<(), HostError>; /// Clears the upgrade plan at the specified height. - fn clear_upgrade_plan(&mut self, plan_height: u64) -> Result<(), UpgradeClientError>; + fn clear_upgrade_plan(&mut self, plan_height: u64) -> Result<(), HostError>; /// Stores the upgraded client state at the specified upgrade path. fn store_upgraded_client_state( &mut self, upgrade_path: UpgradeClientStatePath, client_state: UpgradedClientStateRef, - ) -> Result<(), UpgradeClientError>; + ) -> Result<(), HostError>; /// Stores the upgraded consensus state at the specified upgrade path. fn store_upgraded_consensus_state( &mut self, upgrade_path: UpgradeConsensusStatePath, consensus_state: UpgradedConsensusStateRef, - ) -> Result<(), UpgradeClientError>; + ) -> Result<(), HostError>; } diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs index 419a1e46c..558bdc150 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs @@ -1,5 +1,5 @@ use ibc_client_tendermint::types::ClientState as TmClientState; -use ibc_core_client_types::error::UpgradeClientError; +use ibc_core_host_types::error::HostError; use ibc_core_host_types::path::UpgradeClientStatePath; use ibc_primitives::prelude::*; use tendermint::abci::Event as TmEvent; @@ -15,7 +15,7 @@ use crate::upgrade_proposal::{UpgradeClientProposal, UpgradeExecutionContext, Up pub fn execute_upgrade_client_proposal( ctx: &mut Ctx, proposal: UpgradeProposal, -) -> Result +) -> Result where Ctx: UpgradeExecutionContext, UpgradedClientStateRef: From, @@ -28,8 +28,10 @@ where let mut client_state = TmClientState::try_from(proposal.upgraded_client_state).map_err(|e| { - UpgradeClientError::InvalidUpgradeProposal { - description: e.to_string(), + HostError::InvalidData { + description: format!( + "invalid tendermint client state that could not be converted: {e}" + ), } })?; diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 053fb715f..133860639 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -5,10 +5,9 @@ use core::str::Utf8Error; use base64::DecodeError as Base64Error; use displaydoc::Display; -use prost::DecodeError as ProstError; - use ibc_primitives::prelude::*; use ibc_primitives::proto::Error as ProtoError; +use prost::DecodeError as ProstError; /// Errors that originate from host implementations. #[derive(Debug, Display)] From 799e21aa4a600c61f57193cf7cdfc40d1ff2eec3 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 10 Sep 2024 15:04:29 -0500 Subject: [PATCH 064/107] Fix merge conflicts --- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 5fdcd5566..712127120 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -60,7 +60,7 @@ where self.client_counter .get(StoreHeight::Pending, &NextClientSequencePath) .ok_or(HostError::MissingData { - description: "client counter not found".to_string(), + description: "missing client counter".to_string(), }) } @@ -81,7 +81,7 @@ where ) -> Result<(), HostError> { if client_state_of_host_on_counterparty.is_frozen() { return Err(HostError::UnexpectedData { - description: "client unexpectedly frozen".to_string(), + description: "unexpected frozen client".to_string(), }); } @@ -108,7 +108,7 @@ where if client_state_of_host_on_counterparty.latest_height() >= host_current_height { return Err(HostError::InvalidData { description: format!( - "client has latest height {} greater than or equal to chain height {}", + "invalid counterparty client state: client latest height {} should be less than chain height {}", client_state_of_host_on_counterparty.latest_height(), host_current_height ), @@ -122,7 +122,7 @@ where self.connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) .ok_or(HostError::MissingData { - description: ConnectionError::MissingConnection(conn_id.clone()).to_string(), + description: format!("missing connection end for connection {}", conn_id.clone()), }) } @@ -136,7 +136,7 @@ where self.conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) .ok_or(HostError::MissingData { - description: ConnectionError::MissingConnectionCounter.to_string(), + description: "missing connection counter".to_string(), }) } @@ -147,11 +147,7 @@ where &ChannelEndPath::new(&channel_end_path.0, &channel_end_path.1), ) .ok_or(HostError::NonexistentType { - description: ChannelError::NonexistentChannel { - port_id: channel_end_path.0.clone(), - channel_id: channel_end_path.1.clone(), - } - .to_string(), + description: format!("non-existent channel {} in port {}", channel_end_path.1.clone(), channel_end_path.0.clone()), }) } From 84c7329d46c1d8eab6b49c01816f7a690b51376b Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Tue, 10 Sep 2024 15:15:51 -0500 Subject: [PATCH 065/107] Fix merge conflicts --- .../ics721-nft-transfer/types/src/error.rs | 6 ------ ibc-core/ics02-client/types/src/error.rs | 1 - .../types/src/msgs/misbehaviour.rs | 4 +--- .../types/src/msgs/recover_client.rs | 4 +--- .../types/src/msgs/update_client.rs | 4 +--- .../types/src/msgs/upgrade_client.rs | 19 +++++++------------ ibc-core/ics04-channel/types/src/error.rs | 18 ------------------ .../cosmos/src/upgrade_proposal/plan.rs | 2 +- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 10 ++++++---- 9 files changed, 17 insertions(+), 51 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 3d0a88651..da4d7a73f 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -43,12 +43,6 @@ pub enum NftTransferError { UnsupportedClosedChannel, } -impl From for NftTransferError { - fn from(e: IdentifierError) -> Self { - Self::Decoding(DecodingError::Identifier(e)) - } -} - impl From for NftTransferError { fn from(e: Infallible) -> Self { match e {} diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index f2b70eedf..54eb263c4 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -8,7 +8,6 @@ use ibc_core_host_types::error::{DecodingError, HostError}; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; use ibc_primitives::Timestamp; -use tendermint::Error as TendermintError; use crate::height::Height; use crate::Status; diff --git a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs index dd627ae02..f923902ba 100644 --- a/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs +++ b/ibc-core/ics02-client/types/src/msgs/misbehaviour.rs @@ -8,8 +8,6 @@ use ibc_proto::google::protobuf::Any as ProtoAny; use ibc_proto::ibc::core::client::v1::MsgSubmitMisbehaviour as RawMsgSubmitMisbehaviour; use ibc_proto::Protobuf; -use crate::error::ClientError; - pub const SUBMIT_MISBEHAVIOUR_TYPE_URL: &str = "/ibc.core.client.v1.MsgSubmitMisbehaviour"; /// A type of message that submits client misbehaviour proof. @@ -38,7 +36,7 @@ pub struct MsgSubmitMisbehaviour { impl Protobuf for MsgSubmitMisbehaviour {} impl TryFrom for MsgSubmitMisbehaviour { - type Error = ClientError; + type Error = DecodingError; fn try_from(raw: RawMsgSubmitMisbehaviour) -> Result { let raw_misbehaviour = raw.misbehaviour.ok_or(DecodingError::MissingRawData { diff --git a/ibc-core/ics02-client/types/src/msgs/recover_client.rs b/ibc-core/ics02-client/types/src/msgs/recover_client.rs index 2e82b1d0d..5ef857cba 100644 --- a/ibc-core/ics02-client/types/src/msgs/recover_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/recover_client.rs @@ -7,8 +7,6 @@ use ibc_primitives::Signer; use ibc_proto::ibc::core::client::v1::MsgRecoverClient as RawMsgRecoverClient; use ibc_proto::Protobuf; -use crate::error::ClientError; - pub const RECOVER_CLIENT_TYPE_URL: &str = "/ibc.core.client.v1.MsgRecoverClient"; /// Defines the message used to recover a frozen or expired client. @@ -39,7 +37,7 @@ pub struct MsgRecoverClient { impl Protobuf for MsgRecoverClient {} impl TryFrom for MsgRecoverClient { - type Error = ClientError; + type Error = DecodingError; fn try_from(raw: RawMsgRecoverClient) -> Result { Ok(MsgRecoverClient { diff --git a/ibc-core/ics02-client/types/src/msgs/update_client.rs b/ibc-core/ics02-client/types/src/msgs/update_client.rs index fc99faf9a..16a5d250d 100644 --- a/ibc-core/ics02-client/types/src/msgs/update_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/update_client.rs @@ -8,8 +8,6 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::MsgUpdateClient as RawMsgUpdateClient; use ibc_proto::Protobuf; -use crate::error::ClientError; - pub const UPDATE_CLIENT_TYPE_URL: &str = "/ibc.core.client.v1.MsgUpdateClient"; /// Represents the message that triggers the update of an on-chain (IBC) client @@ -31,7 +29,7 @@ pub struct MsgUpdateClient { impl Protobuf for MsgUpdateClient {} impl TryFrom for MsgUpdateClient { - type Error = ClientError; + type Error = DecodingError; fn try_from(raw: RawMsgUpdateClient) -> Result { Ok(MsgUpdateClient { diff --git a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs index de1941b00..f5ed52afb 100644 --- a/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs +++ b/ibc-core/ics02-client/types/src/msgs/upgrade_client.rs @@ -3,7 +3,6 @@ use core::str::FromStr; use ibc_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::ClientId; use ibc_primitives::prelude::*; @@ -12,8 +11,6 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::MsgUpgradeClient as RawMsgUpgradeClient; use ibc_proto::Protobuf; -use crate::error::{ClientError, UpgradeClientError}; - pub const UPGRADE_CLIENT_TYPE_URL: &str = "/ibc.core.client.v1.MsgUpgradeClient"; /// A type of message that triggers the upgrade of an on-chain (IBC) client. @@ -55,7 +52,7 @@ impl From for RawMsgUpgradeClient { } impl TryFrom for MsgUpgradeClient { - type Error = ClientError; + type Error = DecodingError; fn try_from(proto_msg: RawMsgUpgradeClient) -> Result { let raw_client_state = proto_msg @@ -72,17 +69,15 @@ impl TryFrom for MsgUpgradeClient { })?; let c_bytes = - CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client).map_err(|_| { - UpgradeClientError::InvalidUpgradeClientStateProof( - CommitmentError::InvalidMerkleProof, - ) + CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client).map_err(|e| { + DecodingError::InvalidRawData { + description: format!("invalid upgrade client state proof: {e}"), + } })?; let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) - .map_err(|_| { - UpgradeClientError::InvalidUpgradeConsensusStateProof( - CommitmentError::InvalidMerkleProof, - ) + .map_err(|e| DecodingError::InvalidRawData { + description: format!("invalid upgrade consensus state proof: {e}"), })?; Ok(MsgUpgradeClient { diff --git a/ibc-core/ics04-channel/types/src/error.rs b/ibc-core/ics04-channel/types/src/error.rs index 2b4b01851..aa29b83c9 100644 --- a/ibc-core/ics04-channel/types/src/error.rs +++ b/ibc-core/ics04-channel/types/src/error.rs @@ -109,24 +109,6 @@ pub enum PacketError { timeout_timestamp: TimeoutTimestamp, chain_timestamp: Timestamp, }, - - // TODO(seanchen1991): Move these variants to host-relevant error types - /// application module error: `{description}` - AppModule { description: String }, - /// missing acknowledgment for packet `{0}` - MissingPacketAcknowledgment(Sequence), - /// missing packet receipt for packet `{0}` - MissingPacketReceipt(Sequence), - /// implementation-specific error - ImplementationSpecific, - - // TODO(seanchen1991): Move these variants to host-relevant error types - /// application module error: `{description}` - AppModule { description: String }, - /// missing acknowledgment for packet `{0}` - MissingPacketAcknowledgment(Sequence), - /// missing packet receipt for packet `{0}` - MissingPacketReceipt(Sequence), } impl From for ChannelError { diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs index 276162d25..ccba17567 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/plan.rs @@ -1,7 +1,7 @@ //! Definition of domain `Plan` type. use ibc_core_client_types::error::UpgradeClientError; -use ibc_core_host_types::error::DecodingError; +use ibc_core_host_types::error::{DecodingError, IdentifierError}; use ibc_primitives::prelude::*; use ibc_proto::cosmos::upgrade::v1beta1::Plan as RawPlan; use ibc_proto::google::protobuf::Any; diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 712127120..20c643cce 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -7,14 +7,12 @@ use basecoin_store::context::{ProvableStore, Store}; use basecoin_store::types::Height as StoreHeight; use ibc::core::channel::types::channel::{ChannelEnd, IdentifiedChannelEnd}; use ibc::core::channel::types::commitment::{AcknowledgementCommitment, PacketCommitment}; -use ibc::core::channel::types::error::ChannelError; use ibc::core::channel::types::packet::{PacketState, Receipt}; use ibc::core::client::context::consensus_state::ConsensusState; use ibc::core::client::types::error::ClientError; -use ibc::core::client::types::{Height, Status}; +use ibc::core::client::types::Height; use ibc::core::commitment_types::commitment::CommitmentPrefix; use ibc::core::commitment_types::merkle::MerkleProof; -use ibc::core::connection::types::error::ConnectionError; use ibc::core::connection::types::{ConnectionEnd, IdentifiedConnectionEnd}; use ibc::core::handler::types::events::IbcEvent; use ibc::core::host::types::error::HostError; @@ -147,7 +145,11 @@ where &ChannelEndPath::new(&channel_end_path.0, &channel_end_path.1), ) .ok_or(HostError::NonexistentType { - description: format!("non-existent channel {} in port {}", channel_end_path.1.clone(), channel_end_path.0.clone()), + description: format!( + "non-existent channel {} in port {}", + channel_end_path.1.clone(), + channel_end_path.0.clone() + ), }) } From 1310c0c5f032af32469d0bebedd77e0c08067bc0 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 07:48:57 -0500 Subject: [PATCH 066/107] Revert execute_upgrade_client_proposal error type to UpgradeClientError --- ibc-core/ics02-client/types/src/error.rs | 12 ++++++++++++ .../cosmos/src/upgrade_proposal/handler.rs | 10 ++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 54eb263c4..19f17645d 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -110,6 +110,8 @@ impl std::error::Error for ClientError { match &self { Self::FailedICS23Verification(e) => Some(e), Self::Decoding(e) => Some(e), + Self::Upgrade(e) => Some(e), + Self::Host(e) => Some(e), _ => None, } } @@ -120,6 +122,8 @@ impl std::error::Error for ClientError { pub enum UpgradeClientError { /// decoding error: `{0}` Decoding(DecodingError), + /// host chain error: `{0}` + Host(HostError), /// invalid upgrade proposal: `{description}` InvalidUpgradeProposal { description: String }, /// invalid proof for the upgraded client state: `{0}` @@ -149,10 +153,18 @@ impl From for UpgradeClientError { } } +impl From for UpgradeClientError { + fn from(e: HostError) -> Self { + Self::Host(e) + } +} + #[cfg(feature = "std")] impl std::error::Error for UpgradeClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { + Self::Decoding(e) => Some(e), + Self::Host(e) => Some(e), Self::InvalidUpgradeClientStateProof(e) | Self::InvalidUpgradeConsensusStateProof(e) => Some(e), _ => None, diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs index 558bdc150..419a1e46c 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/handler.rs @@ -1,5 +1,5 @@ use ibc_client_tendermint::types::ClientState as TmClientState; -use ibc_core_host_types::error::HostError; +use ibc_core_client_types::error::UpgradeClientError; use ibc_core_host_types::path::UpgradeClientStatePath; use ibc_primitives::prelude::*; use tendermint::abci::Event as TmEvent; @@ -15,7 +15,7 @@ use crate::upgrade_proposal::{UpgradeClientProposal, UpgradeExecutionContext, Up pub fn execute_upgrade_client_proposal( ctx: &mut Ctx, proposal: UpgradeProposal, -) -> Result +) -> Result where Ctx: UpgradeExecutionContext, UpgradedClientStateRef: From, @@ -28,10 +28,8 @@ where let mut client_state = TmClientState::try_from(proposal.upgraded_client_state).map_err(|e| { - HostError::InvalidData { - description: format!( - "invalid tendermint client state that could not be converted: {e}" - ), + UpgradeClientError::InvalidUpgradeProposal { + description: e.to_string(), } })?; From d6a44b15866b9114998559a4194c3074d5cb5888 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 07:49:29 -0500 Subject: [PATCH 067/107] cargo fmt --- ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs | 3 ++- ibc-core/ics26-routing/types/src/error.rs | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs index c34899d59..9de0a272a 100644 --- a/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs +++ b/ibc-core/ics24-host/cosmos/src/upgrade_proposal/proposal.rs @@ -54,7 +54,8 @@ impl TryFrom for UpgradeProposal { let upgraded_client_state = raw.upgraded_client_state .ok_or_else(|| DecodingError::InvalidRawData { - description: "invalid upgrade proposal: missing upgraded client state".to_string(), + description: "invalid upgrade proposal: missing upgraded client state" + .to_string(), })?; Ok(Self { diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index edfeb8a83..97650e147 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -1,5 +1,4 @@ use displaydoc::Display; - use ibc_core_host_types::identifiers::PortId; use ibc_primitives::prelude::*; From 2252786a92523b8c0500d91bdaf622a57a4cb93c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 08:05:30 -0500 Subject: [PATCH 068/107] Remove unused alloc::string::ToString --- ibc-apps/ics20-transfer/src/handler/mod.rs | 6 +++--- ibc-apps/ics20-transfer/src/lib.rs | 2 -- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index d84364e99..3d1186408 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -2,17 +2,17 @@ mod on_recv_packet; mod send_transfer; -use alloc::string::ToString; +pub use on_recv_packet::*; +pub use send_transfer::*; use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::is_sender_chain_source; use ibc_app_transfer_types::packet::PacketData; use ibc_core::channel::types::packet::Packet; use ibc_core::host::types::error::HostError; -pub use on_recv_packet::*; -pub use send_transfer::*; use crate::context::{TokenTransferExecutionContext, TokenTransferValidationContext}; +use crate::std::string::ToString; pub fn refund_packet_token_execute( ctx_a: &mut impl TokenTransferExecutionContext, diff --git a/ibc-apps/ics20-transfer/src/lib.rs b/ibc-apps/ics20-transfer/src/lib.rs index 12691afaa..2f2bec601 100644 --- a/ibc-apps/ics20-transfer/src/lib.rs +++ b/ibc-apps/ics20-transfer/src/lib.rs @@ -13,8 +13,6 @@ )] #![allow(clippy::result_large_err)] -extern crate alloc; - #[cfg(any(test, feature = "std"))] extern crate std; From 4e85573571196755ba42df81d3ec9d2477adcd52 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 08:36:16 -0500 Subject: [PATCH 069/107] Import ibc_core::primitives::prelude into handler/mod.rs --- ibc-apps/ics20-transfer/src/handler/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index 3d1186408..43ececf3e 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -10,9 +10,9 @@ use ibc_app_transfer_types::is_sender_chain_source; use ibc_app_transfer_types::packet::PacketData; use ibc_core::channel::types::packet::Packet; use ibc_core::host::types::error::HostError; +use ibc_core::primitives::prelude::*; use crate::context::{TokenTransferExecutionContext, TokenTransferValidationContext}; -use crate::std::string::ToString; pub fn refund_packet_token_execute( ctx_a: &mut impl TokenTransferExecutionContext, From b9cae6cf09625389014bc977a8fd1a74d953a202 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 08:59:41 -0500 Subject: [PATCH 070/107] cargo fmt --- ibc-apps/ics20-transfer/src/handler/mod.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index 43ececf3e..155749747 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -2,15 +2,14 @@ mod on_recv_packet; mod send_transfer; -pub use on_recv_packet::*; -pub use send_transfer::*; - use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::is_sender_chain_source; use ibc_app_transfer_types::packet::PacketData; use ibc_core::channel::types::packet::Packet; use ibc_core::host::types::error::HostError; use ibc_core::primitives::prelude::*; +pub use on_recv_packet::*; +pub use send_transfer::*; use crate::context::{TokenTransferExecutionContext, TokenTransferValidationContext}; From d0c07a8b1599673fafb0e5dce0edec53e312d3bb Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 09:27:10 -0500 Subject: [PATCH 071/107] Attempt to fix failing testkit test --- ibc-testkit/src/testapp/ibc/core/client_ctx.rs | 12 ++++++------ ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index d55c654c0..cc4d06f83 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -108,7 +108,7 @@ where .get(StoreHeight::Pending, &path) .ok_or_else(|| HostError::FailedToRetrieveFromStore { description: format!( - "missing consensus state for client {0} at height {1}", + "missing consensus state for client {} at height {}", client_id.clone(), *height ), @@ -147,7 +147,7 @@ where .get(StoreHeight::Pending, &path) .ok_or_else(|| HostError::FailedToRetrieveFromStore { description: format!( - "missing consensus state for client {0} at height {1}", + "missing consensus state for client {} at height {}", client_id.clone(), *height ), @@ -173,7 +173,7 @@ where self.client_state_store .get(StoreHeight::Pending, &ClientStatePath(client_id.clone())) .ok_or(HostError::FailedToRetrieveFromStore { - description: format!("missing client state for client {0}", client_id.clone()), + description: format!("missing client state for client {}", client_id.clone()), }) } @@ -193,7 +193,7 @@ where .get(StoreHeight::Pending, client_cons_state_path) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "missing consensus state for client {0} at height {1}", + "missing consensus state for client {} at height {}", client_cons_state_path.client_id.clone(), height ), @@ -219,7 +219,7 @@ where .get(StoreHeight::Pending, &client_update_time_path) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "missing client update metadata for client {0} at height {1}", + "missing client update metadata for client {} at height {}", client_id.clone(), *height, ), @@ -234,7 +234,7 @@ where .get(StoreHeight::Pending, &client_update_height_path) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "missing client update metadata for client {0} at height {1}", + "missing client update metadata for client {} at height {}", client_id.clone(), *height, ), diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 20c643cce..f76aaf776 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -217,7 +217,7 @@ where .then_some(Receipt::Ok) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "failed to retrieve packet receipt {0}", + "failed to retrieve packet receipt {}", receipt_path.sequence ), }) @@ -234,7 +234,7 @@ where ) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "failed to retrieve packet acknowledgment {0}", + "failed to retrieve packet acknowledgment {}", ack_path.sequence ), }) @@ -315,7 +315,7 @@ where .get(StoreHeight::Pending, &client_state_path) .ok_or_else(|| HostError::FailedToRetrieveFromStore { description: format!( - "failed to retrieve client state from path {0}", + "failed to retrieve client state from path {}", client_state_path.0.clone() ), })?; @@ -354,7 +354,7 @@ where .get(StoreHeight::Pending, &consensus_path) .ok_or(HostError::FailedToRetrieveFromStore { description: format!( - "missing consensus state for client {0} at height {1}", + "missing consensus state for client {} at height {}", consensus_path.client_id, height, ), })?; @@ -408,7 +408,7 @@ where .connection_end_store .get(StoreHeight::Pending, &connection_path) .ok_or_else(|| HostError::FailedToRetrieveFromStore { - description: format!("missing connection {0}", connection_path.0.clone()), + description: format!("missing connection {}", connection_path.0.clone()), })?; Ok(IdentifiedConnectionEnd { connection_id: connection_path.0, @@ -448,7 +448,7 @@ where .get(StoreHeight::Pending, &channel_path) .ok_or_else(|| HostError::FailedToRetrieveFromStore { description: format!( - "missing channel {0} with port {1}", + "missing channel {} with port {}", channel_path.1.clone(), channel_path.0.clone() ), From 71337638f07b7d34b09b0a88ce5ffd119f190299 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 12:01:44 -0500 Subject: [PATCH 072/107] Remove RouterError::UnknownPort variant --- ibc-core/ics24-host/types/src/error.rs | 6 ++++-- ibc-core/ics25-handler/src/entrypoint.rs | 18 ++++++++++++++---- ibc-core/ics26-routing/types/src/error.rs | 5 ----- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index f72c27a0c..f61e00232 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -16,8 +16,6 @@ pub enum HostError { InvalidData { description: String }, /// missing data: `{description}` MissingData { description: String }, - /// unexpected data: `{description}` - UnexpectedData { description: String }, /// failed to update store: `{description}` FailedToUpdateStore { description: String }, /// failed to store data: `{description}` @@ -30,6 +28,10 @@ pub enum HostError { FailedToValidateClient { description: String }, /// non-existent type: `{description}` NonexistentType { description: String }, + /// unexpected data: `{description}` + UnexpectedData { description: String }, + /// unknown resource: `{description}` + UnknownResource { description: String }, /// other error: `{description}` Other { description: String }, } diff --git a/ibc-core/ics25-handler/src/entrypoint.rs b/ibc-core/ics25-handler/src/entrypoint.rs index 7a0d63349..144ee33b3 100644 --- a/ibc-core/ics25-handler/src/entrypoint.rs +++ b/ibc-core/ics25-handler/src/entrypoint.rs @@ -19,9 +19,11 @@ use ibc_core_connection::handler::{ use ibc_core_connection::types::msgs::ConnectionMsg; use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::msgs::MsgEnvelope; +use ibc_core_host::types::error::HostError; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_core_router::router::Router; use ibc_core_router::types::error::RouterError; +use ibc_primitives::prelude::*; use ibc_primitives::proto::Any; /// Entrypoint which performs both validation and message execution @@ -80,7 +82,9 @@ where let port_id = channel_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(RouterError::UnknownPort(port_id.clone()))?; + .ok_or(HostError::UnknownResource { + description: format!("port {}", port_id.clone()), + })?; let module = router .get_route(&module_id) .ok_or(RouterError::MissingModule)?; @@ -98,7 +102,9 @@ where let port_id = packet_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(RouterError::UnknownPort(port_id.clone()))?; + .ok_or(HostError::UnknownResource { + description: format!("port {}", port_id.clone()), + })?; let module = router .get_route(&module_id) .ok_or(RouterError::MissingModule)?; @@ -153,7 +159,9 @@ where let port_id = channel_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(RouterError::UnknownPort(port_id.clone()))?; + .ok_or(HostError::UnknownResource { + description: format!("port {}", port_id.clone()), + })?; let module = router .get_route_mut(&module_id) .ok_or(RouterError::MissingModule)?; @@ -171,7 +179,9 @@ where let port_id = packet_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(RouterError::UnknownPort(port_id.clone()))?; + .ok_or(HostError::UnknownResource { + description: format!("port {}", port_id.clone()), + })?; let module = router .get_route_mut(&module_id) .ok_or(RouterError::MissingModule)?; diff --git a/ibc-core/ics26-routing/types/src/error.rs b/ibc-core/ics26-routing/types/src/error.rs index 97650e147..b49f70993 100644 --- a/ibc-core/ics26-routing/types/src/error.rs +++ b/ibc-core/ics26-routing/types/src/error.rs @@ -1,5 +1,4 @@ use displaydoc::Display; -use ibc_core_host_types::identifiers::PortId; use ibc_primitives::prelude::*; /// Error type for the router module. @@ -7,10 +6,6 @@ use ibc_primitives::prelude::*; pub enum RouterError { /// missing module MissingModule, - - // TODO(seanchen1991): This variant needs to be moved to HostError - /// unknown port `{0}` - UnknownPort(PortId), } #[cfg(feature = "std")] From 49229a389c15f0be8faf5950d8175351a5a5d3d4 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 12:38:46 -0500 Subject: [PATCH 073/107] Remove some uses of ClientError::Other variants --- .../ics02-client/src/handler/update_client.rs | 5 +- ibc-core/ics02-client/types/src/events.rs | 86 +++++++++++++------ ibc-core/ics02-client/types/src/height.rs | 1 + ibc-core/ics03-connection/types/src/error.rs | 14 +-- ibc-core/ics04-channel/types/src/error.rs | 11 --- ibc-core/ics24-host/types/src/error.rs | 2 + tests-integration/tests/core/router.rs | 4 +- 7 files changed, 68 insertions(+), 55 deletions(-) diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index 8f16bbcaf..10d16504a 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -7,6 +7,7 @@ use ibc_core_client_types::msgs::MsgUpdateOrMisbehaviour; use ibc_core_client_types::UpdateKind; use ibc_core_handler_types::error::HandlerError; use ibc_core_handler_types::events::{IbcEvent, MessageEvent}; +use ibc_core_host::types::error::HostError; use ibc_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; use ibc_primitives::ToVec; @@ -77,8 +78,8 @@ where { let event = { - let consensus_height = consensus_heights.first().ok_or(ClientError::Other { - description: "client update state returned no updated height".to_string(), + let consensus_height = consensus_heights.first().ok_or(HostError::MissingData { + description: "missing updated height in client update state".to_string(), })?; IbcEvent::UpdateClient(UpdateClient::new( diff --git a/ibc-core/ics02-client/types/src/events.rs b/ibc-core/ics02-client/types/src/events.rs index 56585036a..ecaa8d851 100644 --- a/ibc-core/ics02-client/types/src/events.rs +++ b/ibc-core/ics02-client/types/src/events.rs @@ -1,5 +1,7 @@ //! Types for the IBC events emitted from Tendermint Websocket by the client module. + use derive_more::From; +use ibc_core_host_types::error::DecodingError; use ibc_core_host_types::identifiers::{ClientId, ClientType}; use ibc_primitives::prelude::*; use subtle_encoding::hex; @@ -53,26 +55,30 @@ impl From for abci::EventAttribute { } } impl TryFrom for ClientIdAttribute { - type Error = ClientError; + type Error = DecodingError; fn try_from(value: abci::EventAttribute) -> Result { if let Ok(key_str) = value.key_str() { if key_str != CLIENT_ID_ATTRIBUTE_KEY { - return Err(ClientError::InvalidAttributeKey(key_str.to_string())); + return Err(DecodingError::InvalidRawData { + description: format!("invalid attribute key {}", key_str), + }); } } else { - return Err(ClientError::MissingAttributeKey); + return Err(DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + }); } value .value_str() .map(|value| { - let client_id = ClientId::from_str(value) - .map_err(|_| ClientError::InvalidAttributeValue(value.to_string()))?; - + let client_id = ClientId::from_str(value)?; Ok(ClientIdAttribute { client_id }) }) - .map_err(|_| ClientError::MissingAttributeValue)? + .map_err(|e| DecodingError::MissingRawData { + description: format!("missing attribute value: {e}"), + })? } } @@ -101,26 +107,30 @@ impl From for abci::EventAttribute { } impl TryFrom for ClientTypeAttribute { - type Error = ClientError; + type Error = DecodingError; fn try_from(value: abci::EventAttribute) -> Result { if let Ok(key_str) = value.key_str() { if key_str != CLIENT_TYPE_ATTRIBUTE_KEY { - return Err(ClientError::InvalidAttributeKey(key_str.to_string())); + return Err(DecodingError::InvalidRawData { + description: format!("invalid attribute key {}", key_str), + }); } } else { - return Err(ClientError::MissingAttributeKey); + return Err(DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + }); } value .value_str() .map(|value| { - let client_type = ClientType::from_str(value) - .map_err(|_| ClientError::InvalidAttributeValue(value.to_string()))?; - + let client_type = ClientType::from_str(value)?; Ok(ClientTypeAttribute { client_type }) }) - .map_err(|_| ClientError::MissingAttributeValue)? + .map_err(|e| DecodingError::MissingRawData { + description: format!("missing attribute value: {e}"), + })? } } @@ -149,25 +159,33 @@ impl From for abci::EventAttribute { } impl TryFrom for ConsensusHeightAttribute { - type Error = ClientError; + type Error = DecodingError; fn try_from(value: abci::EventAttribute) -> Result { if let Ok(key_str) = value.key_str() { if key_str != CONSENSUS_HEIGHT_ATTRIBUTE_KEY { - return Err(ClientError::InvalidAttributeKey(key_str.to_string())); + return Err(DecodingError::InvalidRawData { + description: format!("invalid attribute key {}", key_str), + }); } } else { - return Err(ClientError::MissingAttributeKey); + return Err(DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + }); } value .value_str() .map(|value| { - let consensus_height = Height::from_str(value) - .map_err(|_| ClientError::InvalidAttributeValue(value.to_string()))?; + let consensus_height = + Height::from_str(value).map_err(|e| DecodingError::InvalidRawData { + description: format!("invalid attribute value: {e}"), + })?; Ok(ConsensusHeightAttribute { consensus_height }) }) - .map_err(|_| ClientError::MissingAttributeValue)? + .map_err(|e| DecodingError::MissingRawData { + description: format!("missing attribute value: {e}"), + })? } } @@ -344,12 +362,12 @@ impl From for abci::Event { } impl TryFrom for CreateClient { - type Error = ClientError; + type Error = DecodingError; fn try_from(value: abci::Event) -> Result { if value.kind != CREATE_CLIENT_EVENT { - return Err(ClientError::Other { - description: "Error in parsing CreateClient event".to_string(), + return Err(DecodingError::InvalidRawData { + description: format!("invalid event kind: expected `{}`", CREATE_CLIENT_EVENT), }); } @@ -366,11 +384,17 @@ impl TryFrom for CreateClient { attribute| { let key = attribute .key_str() - .map_err(|_| ClientError::MissingAttributeKey)?; + .map_err(|_| DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + })?; match key { CLIENT_ID_ATTRIBUTE_KEY => Ok(( - Some(attribute.clone().try_into()?), + Some(attribute.clone().try_into().map_err(|e| { + DecodingError::InvalidRawData { + description: format!("{e}"), + } + })?), client_type, consensus_height, )), @@ -392,10 +416,16 @@ impl TryFrom for CreateClient { Option, Option, )| { - let client_id = client_id.ok_or(ClientError::MissingAttributeKey)?; - let client_type = client_type.ok_or(ClientError::MissingAttributeKey)?; + let client_id = client_id.ok_or(DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + })?; + let client_type = client_type.ok_or(DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + })?; let consensus_height = - consensus_height.ok_or(ClientError::MissingAttributeKey)?; + consensus_height.ok_or(DecodingError::MissingRawData { + description: "missing attribute key".to_string(), + })?; Ok(CreateClient::new( client_id.client_id, diff --git a/ibc-core/ics02-client/types/src/height.rs b/ibc-core/ics02-client/types/src/height.rs index 8785a89d8..f7da878b5 100644 --- a/ibc-core/ics02-client/types/src/height.rs +++ b/ibc-core/ics02-client/types/src/height.rs @@ -5,6 +5,7 @@ use core::num::ParseIntError; use core::str::FromStr; use displaydoc::Display; + use ibc_primitives::prelude::*; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use ibc_proto::Protobuf; diff --git a/ibc-core/ics03-connection/types/src/error.rs b/ibc-core/ics03-connection/types/src/error.rs index 7a4342c74..96febd06f 100644 --- a/ibc-core/ics03-connection/types/src/error.rs +++ b/ibc-core/ics03-connection/types/src/error.rs @@ -34,6 +34,8 @@ pub enum ConnectionError { MissingCommonFeatures, /// missing counterparty MissingCounterparty, + /// missing connection `{0}` + MissingConnection(ConnectionId), /// insufficient consensus height `{current_height}` for host chain; needs to meet counterparty's height `{target_height}` InsufficientConsensusHeight { target_height: Height, @@ -57,18 +59,6 @@ pub enum ConnectionError { FailedToVerifyClientState(ClientError), /// overflowed timestamp: `{0}` OverflowedTimestamp(TimestampError), - - // TODO(seanchen1991): Move these variants to host-relevant error types - /// missing connection `{0}` - MissingConnection(ConnectionId), - /// missing connection counter - MissingConnectionCounter, - /// failed to store connection IDs - FailedToStoreConnectionIds, - /// failed to store connection end - FailedToStoreConnectionEnd, - /// failed to update connection counter - FailedToUpdateConnectionCounter, } impl From for ConnectionError { diff --git a/ibc-core/ics04-channel/types/src/error.rs b/ibc-core/ics04-channel/types/src/error.rs index aa29b83c9..722c5bf26 100644 --- a/ibc-core/ics04-channel/types/src/error.rs +++ b/ibc-core/ics04-channel/types/src/error.rs @@ -53,17 +53,6 @@ pub enum ChannelError { }, /// failed proof verification: `{0}` FailedProofVerification(ClientError), - - // TODO(seanchen1991): These variants should be encoded by host-relevant error types - // once those have been defined. - /// application module error: `{description}` - AppModule { description: String }, - /// missing channel counter - MissingCounter, - /// failed to update counter: `{description}` - FailedToUpdateCounter { description: String }, - /// failed to store channel: `{description}` - FailedToStoreChannel { description: String }, } #[derive(Debug, Display)] diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index f61e00232..9173d8fdb 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -12,6 +12,8 @@ use prost::DecodeError as ProstError; /// Errors that originate from host implementations. #[derive(Debug, Display)] pub enum HostError { + /// application module error: `{description}` + AppModule { description: String }, /// invalid data: `{description}` InvalidData { description: String }, /// missing data: `{description}` diff --git a/tests-integration/tests/core/router.rs b/tests-integration/tests/core/router.rs index 52ef77d63..c0f7ed9be 100644 --- a/tests-integration/tests/core/router.rs +++ b/tests-integration/tests/core/router.rs @@ -4,7 +4,6 @@ use ibc::apps::transfer::handler::send_transfer; use ibc::apps::transfer::types::error::TokenTransferError; use ibc::apps::transfer::types::msgs::transfer::MsgTransfer; use ibc::apps::transfer::types::{BaseCoin, U256}; -use ibc::core::channel::types::error::ChannelError; use ibc::core::channel::types::msgs::{ ChannelMsg, MsgAcknowledgement, MsgChannelCloseConfirm, MsgChannelCloseInit, MsgChannelOpenAck, MsgChannelOpenInit, MsgChannelOpenTry, MsgRecvPacket, MsgTimeoutOnClose, PacketMsg, @@ -22,6 +21,7 @@ use ibc::core::host::types::path::CommitmentPath; use ibc::core::host::ValidationContext; use ibc::core::primitives::prelude::*; use ibc::core::primitives::Timestamp; +use ibc_core_host_types::error::HostError; use ibc_testkit::context::MockContext; use ibc_testkit::fixtures::applications::transfer::{ extract_transfer_packet, MsgTransferConfig, PacketDataConfig, @@ -407,7 +407,7 @@ fn routing_module_and_keepers() { let res = match test.msg.clone() { TestMsg::Ics26(msg) => dispatch(&mut ctx.ibc_store, &mut router, msg), TestMsg::Ics20(msg) => send_transfer(&mut ctx.ibc_store, &mut DummyTransferModule, msg) - .map_err(|e: TokenTransferError| ChannelError::AppModule { + .map_err(|e: TokenTransferError| HostError::AppModule { description: e.to_string(), }) .map_err(HandlerError::from), From a461318af9e2b6ea342e647adfe81ed7acc1d974 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 13:28:55 -0500 Subject: [PATCH 074/107] Fix recv_packet_validate_happy_path test --- ibc-testkit/src/context.rs | 19 ++++++++++++++++++- .../tests/core/ics04_channel/recv_packet.rs | 5 +++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/ibc-testkit/src/context.rs b/ibc-testkit/src/context.rs index 92986d14f..82be0ad6e 100644 --- a/ibc-testkit/src/context.rs +++ b/ibc-testkit/src/context.rs @@ -5,6 +5,7 @@ use basecoin_store::context::ProvableStore; use basecoin_store::impls::InMemoryStore; use ibc::core::channel::types::channel::ChannelEnd; use ibc::core::channel::types::commitment::PacketCommitment; +use ibc::core::channel::types::packet::Receipt; use ibc::core::client::context::client_state::ClientStateValidation; use ibc::core::client::context::{ClientExecutionContext, ClientValidationContext}; use ibc::core::client::types::Height; @@ -16,7 +17,7 @@ use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::{ChannelId, ClientId, ConnectionId, PortId, Sequence}; use ibc::core::host::types::path::{ ChannelEndPath, ClientConsensusStatePath, ClientStatePath, CommitmentPath, ConnectionPath, - SeqAckPath, SeqRecvPath, SeqSendPath, + ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, }; use ibc::core::host::{ExecutionContext, ValidationContext}; use ibc::primitives::prelude::*; @@ -461,6 +462,22 @@ where self } + /// Bootstraps a packet receipt to this context. + /// + /// This does not bootstrap any corresponding IBC channel, connection or light client. + pub fn with_packet_receipt( + mut self, + port_id: PortId, + chan_id: ChannelId, + seq: Sequence, + ) -> Self { + let receipt_path = ReceiptPath::new(&port_id, &chan_id, seq); + self.ibc_store + .store_packet_receipt(&receipt_path, Receipt::Ok) + .expect("error writing to store"); + self + } + /// Calls [`validate`] function on [`MsgEnvelope`] using the context's IBC store and router. pub fn validate(&mut self, msg: MsgEnvelope) -> Result<(), HandlerError> { validate(&self.ibc_store, &self.ibc_router, msg) diff --git a/tests-integration/tests/core/ics04_channel/recv_packet.rs b/tests-integration/tests/core/ics04_channel/recv_packet.rs index de8d1b287..895fb816d 100644 --- a/tests-integration/tests/core/ics04_channel/recv_packet.rs +++ b/tests-integration/tests/core/ics04_channel/recv_packet.rs @@ -140,6 +140,11 @@ fn recv_packet_validate_happy_path(fixture: Fixture) { packet.port_id_on_b.clone(), packet.chan_id_on_b.clone(), packet.seq_on_a, + ) + .with_packet_receipt( + packet.port_id_on_b.clone(), + packet.chan_id_on_b.clone(), + packet.seq_on_a, ); let msg_envelope = MsgEnvelope::from(PacketMsg::from(msg)); From 357e0ea74ad4501e1539a502b5f0f69de55091f9 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 13:50:17 -0500 Subject: [PATCH 075/107] Fix conn_open_ack_no_connection test --- ibc-core/ics24-host/types/src/error.rs | 6 ++++++ ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 4 +--- .../tests/core/ics03_connection/conn_open_ack.rs | 8 ++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 9173d8fdb..4b1a174ad 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -9,6 +9,8 @@ use ibc_primitives::prelude::*; use ibc_primitives::proto::Error as ProtoError; use prost::DecodeError as ProstError; +use crate::identifiers::ConnectionId; + /// Errors that originate from host implementations. #[derive(Debug, Display)] pub enum HostError { @@ -36,6 +38,10 @@ pub enum HostError { UnknownResource { description: String }, /// other error: `{description}` Other { description: String }, + + // this variant exists for testing purposes + /// missing connection `{0}` + MissingConnection(ConnectionId), } /// Errors that arise when parsing identifiers. diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index f76aaf776..813985c37 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -119,9 +119,7 @@ where fn connection_end(&self, conn_id: &ConnectionId) -> Result { self.connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) - .ok_or(HostError::MissingData { - description: format!("missing connection end for connection {}", conn_id.clone()), - }) + .ok_or(HostError::MissingConnection(conn_id.clone())) } fn commitment_prefix(&self) -> CommitmentPrefix { diff --git a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs index 7f7b8662f..115eaab15 100644 --- a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs +++ b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs @@ -13,6 +13,7 @@ use ibc::core::host::types::identifiers::{ChainId, ClientId}; use ibc::core::host::ValidationContext; use ibc::core::primitives::prelude::*; use ibc::core::primitives::ZERO_DURATION; +use ibc_core_host_types::error::HostError; use ibc_testkit::context::MockContext; use ibc_testkit::fixtures::core::connection::dummy_msg_conn_open_ack; use ibc_testkit::fixtures::core::context::TestContextConfig; @@ -126,7 +127,7 @@ fn conn_open_ack_validate(fxt: &Fixture, expect: Expect) { let cons_state_height = fxt.msg.consensus_height_of_a_on_b; match res.unwrap_err() { - HandlerError::Connection(ConnectionError::MissingConnection(connection_id)) => { + HandlerError::Host(HostError::MissingConnection(connection_id)) => { assert_eq!(connection_id, right_connection_id) } HandlerError::Connection(ConnectionError::InsufficientConsensusHeight { @@ -187,9 +188,8 @@ fn conn_open_ack_healthy() { #[test] fn conn_open_ack_no_connection() { let fxt = conn_open_ack_fixture(Ctx::New); - let expected_err = HandlerError::Connection(ConnectionError::MissingConnection( - fxt.msg.conn_id_on_a.clone(), - )); + let expected_err = + HandlerError::Host(HostError::MissingConnection(fxt.msg.conn_id_on_a.clone())); conn_open_ack_validate(&fxt, Expect::Failure(Some(expected_err))); } From 4049045c4e41e8ddb615e549f6f311f53ba260dd Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 13:50:31 -0500 Subject: [PATCH 076/107] cargo fmt --- ibc-core/ics02-client/types/src/height.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/ibc-core/ics02-client/types/src/height.rs b/ibc-core/ics02-client/types/src/height.rs index f7da878b5..8785a89d8 100644 --- a/ibc-core/ics02-client/types/src/height.rs +++ b/ibc-core/ics02-client/types/src/height.rs @@ -5,7 +5,6 @@ use core::num::ParseIntError; use core::str::FromStr; use displaydoc::Display; - use ibc_primitives::prelude::*; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use ibc_proto::Protobuf; From b229224f2544a8446ed8fe3a0e7f1ae787f5d853 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 15:42:41 -0500 Subject: [PATCH 077/107] fix conn_open_ack_no_connection test without adding new HostError variant --- ibc-core/ics24-host/types/src/error.rs | 4 ---- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 4 +++- .../tests/core/ics03_connection/conn_open_ack.rs | 12 ++++++++---- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 4b1a174ad..09f75cd54 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -38,10 +38,6 @@ pub enum HostError { UnknownResource { description: String }, /// other error: `{description}` Other { description: String }, - - // this variant exists for testing purposes - /// missing connection `{0}` - MissingConnection(ConnectionId), } /// Errors that arise when parsing identifiers. diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 813985c37..f76aaf776 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -119,7 +119,9 @@ where fn connection_end(&self, conn_id: &ConnectionId) -> Result { self.connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) - .ok_or(HostError::MissingConnection(conn_id.clone())) + .ok_or(HostError::MissingData { + description: format!("missing connection end for connection {}", conn_id.clone()), + }) } fn commitment_prefix(&self) -> CommitmentPrefix { diff --git a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs index 115eaab15..45e4bc395 100644 --- a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs +++ b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs @@ -127,8 +127,8 @@ fn conn_open_ack_validate(fxt: &Fixture, expect: Expect) { let cons_state_height = fxt.msg.consensus_height_of_a_on_b; match res.unwrap_err() { - HandlerError::Host(HostError::MissingConnection(connection_id)) => { - assert_eq!(connection_id, right_connection_id) + HandlerError::Host(HostError::MissingData { ref description }) => { + assert!(description.contains(right_connection_id.to_string().as_str())) } HandlerError::Connection(ConnectionError::InsufficientConsensusHeight { target_height, @@ -188,8 +188,12 @@ fn conn_open_ack_healthy() { #[test] fn conn_open_ack_no_connection() { let fxt = conn_open_ack_fixture(Ctx::New); - let expected_err = - HandlerError::Host(HostError::MissingConnection(fxt.msg.conn_id_on_a.clone())); + let expected_err = HandlerError::Host(HostError::MissingData { + description: format!( + "missing connection end for connection {}", + fxt.msg.conn_id_on_a.clone() + ), + }); conn_open_ack_validate(&fxt, Expect::Failure(Some(expected_err))); } From ca0eb9718fe2f5831c602ec8e8862a0c47e096cc Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 15:45:09 -0500 Subject: [PATCH 078/107] fix test_create_client_try_from test --- ibc-core/ics02-client/types/src/events.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibc-core/ics02-client/types/src/events.rs b/ibc-core/ics02-client/types/src/events.rs index ecaa8d851..7846d427b 100644 --- a/ibc-core/ics02-client/types/src/events.rs +++ b/ibc-core/ics02-client/types/src/events.rs @@ -774,7 +774,7 @@ mod tests { )] fn test_create_client_try_from( #[case] event: abci::Event, - #[case] expected: Result, + #[case] expected: Result, ) { let result = CreateClient::try_from(event); if expected.is_err() { From 8e2cab767a8cadf9508daa32481b1b53ab34300c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Wed, 11 Sep 2024 15:49:03 -0500 Subject: [PATCH 079/107] Remove unnecessary import --- ibc-core/ics24-host/types/src/error.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 09f75cd54..9173d8fdb 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -9,8 +9,6 @@ use ibc_primitives::prelude::*; use ibc_primitives::proto::Error as ProtoError; use prost::DecodeError as ProstError; -use crate::identifiers::ConnectionId; - /// Errors that originate from host implementations. #[derive(Debug, Display)] pub enum HostError { From a7f579545397151c1aefc5b9cd9d12bd74f91651 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 12 Sep 2024 09:19:17 -0500 Subject: [PATCH 080/107] Fix test_create_client_try_from --- ibc-core/ics02-client/types/src/events.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ibc-core/ics02-client/types/src/events.rs b/ibc-core/ics02-client/types/src/events.rs index 7846d427b..625e95cb4 100644 --- a/ibc-core/ics02-client/types/src/events.rs +++ b/ibc-core/ics02-client/types/src/events.rs @@ -729,6 +729,7 @@ impl From for abci::Event { mod tests { use core::any::Any; + use ibc_core_host_types::error::IdentifierError; use rstest::*; use super::*; @@ -758,9 +759,10 @@ mod tests { abci::EventAttribute::from(("consensus_height", "1-10")), ], }, - Err(ClientError::Other { - description: "Error in parsing CreateClient event".to_string(), - }), + Err(IdentifierError::FailedToParse { + value: "CreateClient".to_string(), + description: "failed to parse event".to_string() + }.into()) )] #[case( abci::Event { @@ -770,7 +772,7 @@ mod tests { abci::EventAttribute::from(("consensus_height", "1-10")), ], }, - Err(ClientError::MissingAttributeKey), + Err(DecodingError::MissingRawData { description: "missing attribute key".to_string() }), )] fn test_create_client_try_from( #[case] event: abci::Event, From a2d02058b20ffb3173340e1ea18a4484df4b9a95 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Thu, 12 Sep 2024 10:44:48 -0500 Subject: [PATCH 081/107] cargo fmt --- ibc-core/ics02-client/types/src/events.rs | 6 +++--- ibc-core/ics04-channel/src/handler/recv_packet.rs | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ibc-core/ics02-client/types/src/events.rs b/ibc-core/ics02-client/types/src/events.rs index 625e95cb4..c6c36dc3c 100644 --- a/ibc-core/ics02-client/types/src/events.rs +++ b/ibc-core/ics02-client/types/src/events.rs @@ -759,9 +759,9 @@ mod tests { abci::EventAttribute::from(("consensus_height", "1-10")), ], }, - Err(IdentifierError::FailedToParse { - value: "CreateClient".to_string(), - description: "failed to parse event".to_string() + Err(IdentifierError::FailedToParse { + value: "CreateClient".to_string(), + description: "failed to parse event".to_string() }.into()) )] #[case( diff --git a/ibc-core/ics04-channel/src/handler/recv_packet.rs b/ibc-core/ics04-channel/src/handler/recv_packet.rs index a7845e86f..a7eb1f1ce 100644 --- a/ibc-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-core/ics04-channel/src/handler/recv_packet.rs @@ -249,8 +249,7 @@ where &msg.packet.chan_id_on_a, msg.packet.seq_on_a, ); - let packet_rec = ctx_b.get_packet_receipt(&receipt_path_on_b); - match packet_rec { + match ctx_b.get_packet_receipt(&receipt_path_on_b) { Ok(_receipt) => {} Err(e) => return Err(e)?, } From 4b3644411ba19463f52c5c4f9ac70db9a842de27 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 13 Sep 2024 09:09:09 -0700 Subject: [PATCH 082/107] fix: remove now unneeded with_packet_receipt --- ibc-testkit/src/context.rs | 19 +------------------ .../tests/core/ics04_channel/recv_packet.rs | 5 ----- 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/ibc-testkit/src/context.rs b/ibc-testkit/src/context.rs index 82be0ad6e..92986d14f 100644 --- a/ibc-testkit/src/context.rs +++ b/ibc-testkit/src/context.rs @@ -5,7 +5,6 @@ use basecoin_store::context::ProvableStore; use basecoin_store::impls::InMemoryStore; use ibc::core::channel::types::channel::ChannelEnd; use ibc::core::channel::types::commitment::PacketCommitment; -use ibc::core::channel::types::packet::Receipt; use ibc::core::client::context::client_state::ClientStateValidation; use ibc::core::client::context::{ClientExecutionContext, ClientValidationContext}; use ibc::core::client::types::Height; @@ -17,7 +16,7 @@ use ibc::core::handler::types::msgs::MsgEnvelope; use ibc::core::host::types::identifiers::{ChannelId, ClientId, ConnectionId, PortId, Sequence}; use ibc::core::host::types::path::{ ChannelEndPath, ClientConsensusStatePath, ClientStatePath, CommitmentPath, ConnectionPath, - ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, + SeqAckPath, SeqRecvPath, SeqSendPath, }; use ibc::core::host::{ExecutionContext, ValidationContext}; use ibc::primitives::prelude::*; @@ -462,22 +461,6 @@ where self } - /// Bootstraps a packet receipt to this context. - /// - /// This does not bootstrap any corresponding IBC channel, connection or light client. - pub fn with_packet_receipt( - mut self, - port_id: PortId, - chan_id: ChannelId, - seq: Sequence, - ) -> Self { - let receipt_path = ReceiptPath::new(&port_id, &chan_id, seq); - self.ibc_store - .store_packet_receipt(&receipt_path, Receipt::Ok) - .expect("error writing to store"); - self - } - /// Calls [`validate`] function on [`MsgEnvelope`] using the context's IBC store and router. pub fn validate(&mut self, msg: MsgEnvelope) -> Result<(), HandlerError> { validate(&self.ibc_store, &self.ibc_router, msg) diff --git a/tests-integration/tests/core/ics04_channel/recv_packet.rs b/tests-integration/tests/core/ics04_channel/recv_packet.rs index 45df6cf9d..e86d815be 100644 --- a/tests-integration/tests/core/ics04_channel/recv_packet.rs +++ b/tests-integration/tests/core/ics04_channel/recv_packet.rs @@ -140,11 +140,6 @@ fn recv_packet_validate_happy_path(fixture: Fixture) { packet.port_id_on_b.clone(), packet.chan_id_on_b.clone(), packet.seq_on_a, - ) - .with_packet_receipt( - packet.port_id_on_b.clone(), - packet.chan_id_on_b.clone(), - packet.seq_on_a, ); // Note: For unordered channels, there's no need to set a packet receipt. From 761959a4e65e947df80e4109e6bc738eff512f8d Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 13 Sep 2024 09:19:29 -0700 Subject: [PATCH 083/107] fix: revert unintended ack status changes in ICS-20 --- ibc-apps/ics20-transfer/src/module.rs | 59 ++++++---------------- ibc-apps/ics20-transfer/types/src/error.rs | 4 ++ 2 files changed, 19 insertions(+), 44 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/module.rs b/ibc-apps/ics20-transfer/src/module.rs index e6c124351..2c24dc6fe 100644 --- a/ibc-apps/ics20-transfer/src/module.rs +++ b/ibc-apps/ics20-transfer/src/module.rs @@ -172,12 +172,8 @@ pub fn on_recv_packet_execute( packet: &Packet, ) -> (ModuleExtras, Acknowledgement) { let Ok(data) = serde_json::from_slice::(&packet.data) else { - let ack = AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ); + let ack = + AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()); return (ModuleExtras::empty(), ack.into()); }; @@ -208,16 +204,11 @@ pub fn on_acknowledgement_packet_validate( where Ctx: TokenTransferValidationContext, { - let data = serde_json::from_slice::(&packet.data).map_err(|e| { - DecodingError::InvalidJson { - description: format!("failed to deserialize packet data: {e}"), - } - })?; + let data = serde_json::from_slice::(&packet.data) + .map_err(|_| TokenTransferError::FailedToDeserializePacketData)?; let acknowledgement = serde_json::from_slice::(acknowledgement.as_ref()) - .map_err(|e| DecodingError::InvalidJson { - description: format!("failed to deserialize acknowledgment status: {e}"), - })?; + .map_err(|_| TokenTransferError::FailedToDeserializeAck)?; if !acknowledgement.is_successful() { refund_packet_token_validate(ctx, packet, &data)?; @@ -235,10 +226,7 @@ pub fn on_acknowledgement_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into()), + Err(TokenTransferError::FailedToDeserializePacketData), ); }; @@ -247,10 +235,7 @@ pub fn on_acknowledgement_packet_execute( else { return ( ModuleExtras::empty(), - Err(DecodingError::InvalidJson { - description: "failed to deserialize acknowledgment status".to_string(), - } - .into()), + Err(TokenTransferError::FailedToDeserializeAck), ); }; @@ -346,13 +331,8 @@ mod test { r#"{"result":"AQ=="}"#, ); ser_json_assert_eq( - AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ), - r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, + AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()), + r#"{"error":"failed to deserialize packet data"}"#, ); } @@ -368,20 +348,16 @@ mod test { #[test] fn test_ack_error_to_vec() { - let ack_error: Vec = AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ) - .into(); + let ack_error: Vec = + AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()) + .into(); // Check that it's the same output as ibc-go // Note: this also implicitly checks that the ack bytes are non-empty, // which would make the conversion to `Acknowledgement` panic assert_eq!( ack_error, - br#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"# + br#"{"error":"failed to deserialize packet data"}"# ); } @@ -397,13 +373,8 @@ mod test { AcknowledgementStatus::success(ack_success_b64()), ); de_json_assert_eq( - r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, - AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ), + r#"{"error":"failed to deserialize packet data"}"#, + AcknowledgementStatus::error(TokenTransferError::FailedToDeserializePacketData.into()), ); assert!(serde_json::from_str::(r#"{"success":"AQ=="}"#).is_err()); diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 47c6c46ff..e92872af7 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -39,6 +39,10 @@ pub enum TokenTransferError { UnsupportedClosedChannel, /// empty base denomination EmptyBaseDenom, + /// failed to deserialize packet data + FailedToDeserializePacketData, + /// failed to deserialize acknowledgement + FailedToDeserializeAck, } #[cfg(feature = "std")] From 80597b03929cfe3d90618a52106f692ffaccc9ae Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 13 Sep 2024 09:21:07 -0700 Subject: [PATCH 084/107] fix: revert unintended ack status changes in ICS-721 --- ibc-apps/ics721-nft-transfer/types/src/error.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index da4d7a73f..18c8a7ec7 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -37,6 +37,10 @@ pub enum NftTransferError { MismatchedChannelOrders { expected: Order, actual: Order }, /// mismatched port IDs: expected `{expected}`, actual `{actual}` MismatchedPortIds { expected: PortId, actual: PortId }, + /// failed to deserialize packet data + FailedToDeserializePacketData, + /// failed to deserialize acknowledgement + FailedToDeserializeAck, /// failed to parse account ID FailedToParseAccount, /// channel cannot be closed From bd8622059c133185ccac29a88f8650be80ed095a Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 13 Sep 2024 09:38:12 -0700 Subject: [PATCH 085/107] fix: remove unintended tendermint-proto --- ibc-clients/ics07-tendermint/types/src/error.rs | 5 +---- ibc-core/ics24-host/types/Cargo.toml | 3 --- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/ibc-clients/ics07-tendermint/types/src/error.rs b/ibc-clients/ics07-tendermint/types/src/error.rs index 1409cfc7a..eb4c2c67d 100644 --- a/ibc-clients/ics07-tendermint/types/src/error.rs +++ b/ibc-clients/ics07-tendermint/types/src/error.rs @@ -19,8 +19,6 @@ use tendermint_light_client_verifier::Verdict; pub enum TendermintClientError { /// decoding error: `{0}` Decoding(DecodingError), - /// identifier error: `{0}` - Identifier(IdentifierError), /// invalid client state trust threshold: `{description}` InvalidTrustThreshold { description: String }, /// invalid clock drift; must be greater than 0 @@ -56,7 +54,6 @@ pub enum TendermintClientError { impl std::error::Error for TendermintClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::Identifier(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } @@ -75,7 +72,7 @@ impl From for ClientError { impl From for TendermintClientError { fn from(e: IdentifierError) -> Self { - Self::Identifier(e) + Self::Decoding(DecodingError::Identifier(e)) } } diff --git a/ibc-core/ics24-host/types/Cargo.toml b/ibc-core/ics24-host/types/Cargo.toml index fa69e483f..e4953c720 100644 --- a/ibc-core/ics24-host/types/Cargo.toml +++ b/ibc-core/ics24-host/types/Cargo.toml @@ -35,9 +35,6 @@ ibc-primitives = { workspace = true } parity-scale-codec = { workspace = true, optional = true } scale-info = { workspace = true, optional = true } -# cosmos dependencies -tendermint-proto = { workspace = true } - [dev-dependencies] rstest = { workspace = true } serde-json = { workspace = true } From ac0e5be64e47c73116abc68a643466bf6750d44c Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 13 Sep 2024 09:46:31 -0700 Subject: [PATCH 086/107] fix: update Cargo.lock for cw-check --- ci/cw-check/Cargo.lock | 1 - 1 file changed, 1 deletion(-) diff --git a/ci/cw-check/Cargo.lock b/ci/cw-check/Cargo.lock index 575b3f094..a67985134 100644 --- a/ci/cw-check/Cargo.lock +++ b/ci/cw-check/Cargo.lock @@ -1040,7 +1040,6 @@ dependencies = [ "scale-info", "schemars", "serde", - "tendermint-proto", ] [[package]] From 9abffa7583e380719d15c5303326c4f77e26c28f Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 12:33:05 -0500 Subject: [PATCH 087/107] Fix lingering issues from merge conflicts --- ibc-apps/ics20-transfer/types/src/error.rs | 10 +------ .../ics20-transfer/types/src/msgs/transfer.rs | 1 - .../ics721-nft-transfer/types/src/error.rs | 28 ++++++------------- .../types/src/msgs/transfer.rs | 1 - ibc-query/src/error.rs | 2 +- 5 files changed, 10 insertions(+), 32 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 94f5dcaa2..762d33d9d 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -1,5 +1,6 @@ //! Defines the token transfer error type use displaydoc::Display; + use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; @@ -15,14 +16,6 @@ pub enum TokenTransferError { Decoding(DecodingError), /// identifier error: `{0}` Identifier(IdentifierError), - /// invalid amount: `{0}` - InvalidAmount(FromDecStrErr), - /// invalid coin: `{0}` - InvalidCoin(String), - /// invalid trace: `{0}` - InvalidTrace(String), - /// missing token - MissingToken, /// missing destination channel `{channel_id}` on port `{port_id}` MissingDestinationChannel { port_id: PortId, @@ -46,7 +39,6 @@ impl std::error::Error for TokenTransferError { match &self { Self::Handler(e) => Some(e), Self::Identifier(e) => Some(e), - Self::InvalidAmount(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } diff --git a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs index bc665229f..0bdaf0979 100644 --- a/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics20-transfer/types/src/msgs/transfer.rs @@ -1,7 +1,6 @@ //! Defines the token transfer message type use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; -use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index d50a707b2..122c04684 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -3,7 +3,7 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; -use ibc_core::host::types::error::{DecodingError, HostError, IdentifierError}; +use ibc_core::host::types::error::{DecodingError, HostError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -13,12 +13,6 @@ pub enum NftTransferError { Handler(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), - /// identifier error: `{0}` - Identifier(IdentifierError), - /// invalid trace: `{0}` - InvalidTrace(String), - /// invalid URI error: `{0}` - InvalidUri(InvalidUri), /// missing destination channel `{channel_id}` on port `{port_id}` MissingDestinationChannel { port_id: PortId, @@ -42,18 +36,6 @@ pub enum NftTransferError { UnsupportedClosedChannel, } -impl From for NftTransferError { - fn from(e: HostError) -> Self { - Self::Handler(HandlerError::Host(e)) - } -} - -impl From for StatusValue { - fn from(e: NftTransferError) -> Self { - StatusValue::new(e.to_string()).expect("error message must not be empty") - } -} - #[cfg(feature = "std")] impl std::error::Error for NftTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { @@ -62,7 +44,13 @@ impl std::error::Error for NftTransferError { Self::Decoding(e) => Some(e), _ => None, } - } + } +} + +impl From for NftTransferError { + fn from(e: HostError) -> Self { + Self::Handler(HandlerError::Host(e)) + } } impl From for StatusValue { diff --git a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs index 9be17e324..ae9a31bc4 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/msgs/transfer.rs @@ -1,7 +1,6 @@ //! Defines the Non-Fungible Token Transfer message type use ibc_core::channel::types::timeout::{TimeoutHeight, TimeoutTimestamp}; -use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index 50dd084ac..8f62e9858 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -6,7 +6,7 @@ use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; use ibc::core::connection::types::error::ConnectionError; use ibc::core::handler::types::error::HandlerError; -use ibc::core::host::types::error::{HostError, IdentifierError}; +use ibc::core::host::types::error::{DecodingError, HostError, IdentifierError}; /// The main error type of the ibc-query crate. This type mainly /// serves to surface lower-level errors that occur when executing From f4d034b33b864256ae9252854fda478de28d1ac3 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 12:35:03 -0500 Subject: [PATCH 088/107] Fix lingering issues from merge conflicts --- ibc-apps/ics20-transfer/types/src/error.rs | 11 +---------- ibc-core/ics02-client/types/src/error.rs | 2 +- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 762d33d9d..6824ad5ce 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -4,7 +4,7 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; -use ibc_core::host::types::error::{DecodingError, HostError, IdentifierError}; +use ibc_core::host::types::error::{DecodingError, HostError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -14,8 +14,6 @@ pub enum TokenTransferError { Handler(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), - /// identifier error: `{0}` - Identifier(IdentifierError), /// missing destination channel `{channel_id}` on port `{port_id}` MissingDestinationChannel { port_id: PortId, @@ -38,7 +36,6 @@ impl std::error::Error for TokenTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::Handler(e) => Some(e), - Self::Identifier(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } @@ -51,12 +48,6 @@ impl From for TokenTransferError { } } -impl From for TokenTransferError { - fn from(e: IdentifierError) -> Self { - Self::Identifier(e) - } -} - impl From for TokenTransferError { fn from(e: DecodingError) -> Self { Self::Decoding(e) diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 19f17645d..08da417ff 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -1,8 +1,8 @@ //! Defines the client error type use core::convert::Infallible; - use displaydoc::Display; + use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::{DecodingError, HostError}; use ibc_core_host_types::identifiers::ClientId; From 88c8bf88abd15a3ea2627df546e4afbde1a9fdae Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 12:36:02 -0500 Subject: [PATCH 089/107] Remove From for ClientError impl --- ibc-core/ics02-client/types/src/error.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index 08da417ff..c3fd9425b 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -1,6 +1,5 @@ //! Defines the client error type -use core::convert::Infallible; use displaydoc::Display; use ibc_core_commitment_types::error::CommitmentError; @@ -80,12 +79,6 @@ impl From<&'static str> for ClientError { } } -impl From for ClientError { - fn from(value: Infallible) -> Self { - match value {} - } -} - impl From for ClientError { fn from(e: CommitmentError) -> Self { Self::FailedICS23Verification(e) From 35f7844548e414376a2bc4d405698aa67a1ccb2a Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 12:36:33 -0500 Subject: [PATCH 090/107] cargo fmt --- ibc-apps/ics20-transfer/types/src/error.rs | 1 - ibc-core/ics02-client/types/src/error.rs | 1 - ibc-query/src/error.rs | 4 ++-- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 6824ad5ce..d694b6659 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -1,6 +1,5 @@ //! Defines the token transfer error type use displaydoc::Display; - use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; diff --git a/ibc-core/ics02-client/types/src/error.rs b/ibc-core/ics02-client/types/src/error.rs index c3fd9425b..0b15ac36c 100644 --- a/ibc-core/ics02-client/types/src/error.rs +++ b/ibc-core/ics02-client/types/src/error.rs @@ -1,7 +1,6 @@ //! Defines the client error type use displaydoc::Display; - use ibc_core_commitment_types::error::CommitmentError; use ibc_core_host_types::error::{DecodingError, HostError}; use ibc_core_host_types::identifiers::ClientId; diff --git a/ibc-query/src/error.rs b/ibc-query/src/error.rs index 8f62e9858..2d18a8547 100644 --- a/ibc-query/src/error.rs +++ b/ibc-query/src/error.rs @@ -1,12 +1,12 @@ use alloc::string::{String, ToString}; -use displaydoc::Display; -use tonic::Status; +use displaydoc::Display; use ibc::core::channel::types::error::{ChannelError, PacketError}; use ibc::core::client::types::error::ClientError; use ibc::core::connection::types::error::ConnectionError; use ibc::core::handler::types::error::HandlerError; use ibc::core::host::types::error::{DecodingError, HostError, IdentifierError}; +use tonic::Status; /// The main error type of the ibc-query crate. This type mainly /// serves to surface lower-level errors that occur when executing From 126f87432dd3287c5a341bc22ae3bc52cab289a8 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 12:46:33 -0500 Subject: [PATCH 091/107] Rename HostError InvalidData and MissingData variants --- .../ics02-client/src/handler/update_client.rs | 7 ++++--- .../ics02-client/src/handler/upgrade_client.rs | 4 ++-- .../cosmos/src/validate_self_client.rs | 16 ++++++++-------- ibc-core/ics24-host/src/context.rs | 2 +- ibc-core/ics24-host/types/src/error.rs | 8 ++++---- ibc-testkit/src/testapp/ibc/core/client_ctx.rs | 8 ++++---- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 18 +++++++++--------- .../tests/core/ics02_client/upgrade_client.rs | 2 +- .../core/ics03_connection/conn_open_ack.rs | 4 ++-- 9 files changed, 35 insertions(+), 34 deletions(-) diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index 10d16504a..1f8bdae14 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -78,9 +78,10 @@ where { let event = { - let consensus_height = consensus_heights.first().ok_or(HostError::MissingData { - description: "missing updated height in client update state".to_string(), - })?; + let consensus_height = + consensus_heights.first().ok_or(HostError::MissingState { + description: "missing updated height in client update state".to_string(), + })?; IbcEvent::UpdateClient(UpdateClient::new( client_id, diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index 195ca4da8..300540212 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -38,9 +38,9 @@ where ); let old_consensus_state = client_val_ctx .consensus_state(&old_client_cons_state_path) - .map_err(|_| HostError::MissingData { + .map_err(|_| HostError::MissingState { description: format!( - "missing consensus state for client {0} at height {1}", + "missing consensus state for client {} at height {}", client_id, old_client_state.latest_height() ), diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index 4528d917d..d1f4dd162 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -33,7 +33,7 @@ pub trait ValidateSelfClientContext { let self_chain_id = self.chain_id(); if self_chain_id != &client_state_of_host_on_counterparty.chain_id { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "invalid chain ID: expected {}, actual {}", self_chain_id, client_state_of_host_on_counterparty.chain_id @@ -45,7 +45,7 @@ pub trait ValidateSelfClientContext { let self_revision_number = self_chain_id.revision_number(); if self_revision_number != latest_height.revision_number() { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "mismatched client revision numbers; expected {}, actual {}", self_revision_number, @@ -55,7 +55,7 @@ pub trait ValidateSelfClientContext { } if latest_height >= self.host_current_height() { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "client latest height {} should be less than chain height {}", latest_height, @@ -65,7 +65,7 @@ pub trait ValidateSelfClientContext { } if self.proof_specs() != &client_state_of_host_on_counterparty.proof_specs { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "invalid client proof specs; expected {:?}, actual {:?}", self.proof_specs(), @@ -81,13 +81,13 @@ pub trait ValidateSelfClientContext { trust_level.numerator(), trust_level.denominator(), ) - .map_err(|e| HostError::InvalidData { + .map_err(|e| HostError::InvalidState { description: e.to_string(), })? }; if self.unbonding_period() != client_state_of_host_on_counterparty.unbonding_period { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "invalid unbonding period; expected {:?}, actual {:?}", self.unbonding_period(), @@ -99,7 +99,7 @@ pub trait ValidateSelfClientContext { if client_state_of_host_on_counterparty.unbonding_period < client_state_of_host_on_counterparty.trusting_period { - return Err(HostError::InvalidData { description: format!( + return Err(HostError::InvalidState { description: format!( "invalid counterparty client state: unbonding period must be greater than trusting period; unbonding period ({:?}) < trusting period ({:?})", client_state_of_host_on_counterparty.unbonding_period, client_state_of_host_on_counterparty.trusting_period @@ -109,7 +109,7 @@ pub trait ValidateSelfClientContext { if !client_state_of_host_on_counterparty.upgrade_path.is_empty() && self.upgrade_path() != client_state_of_host_on_counterparty.upgrade_path { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "invalid upgrade path; expected {:?}, actual {:?}", self.upgrade_path(), diff --git a/ibc-core/ics24-host/src/context.rs b/ibc-core/ics24-host/src/context.rs index 46bbc6a30..4a11b276b 100644 --- a/ibc-core/ics24-host/src/context.rs +++ b/ibc-core/ics24-host/src/context.rs @@ -86,7 +86,7 @@ pub trait ValidationContext { &self.get_compatible_versions(), counterparty_candidate_versions, ) - .map_err(|e| HostError::MissingData { + .map_err(|e| HostError::MissingState { description: e.to_string(), }) } diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 4a7336ae7..7e0e5563a 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -14,10 +14,10 @@ use prost::DecodeError as ProstError; pub enum HostError { /// application module error: `{description}` AppModule { description: String }, - /// invalid data: `{description}` - InvalidData { description: String }, - /// missing data: `{description}` - MissingData { description: String }, + /// invalid state: `{description}` + InvalidState { description: String }, + /// missing state: `{description}` + MissingState { description: String }, /// failed to update store: `{description}` FailedToUpdateStore { description: String }, /// failed to store data: `{description}` diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index cc4d06f83..afc7e7611 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -76,7 +76,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::InvalidData { + .map_err(|e| HostError::InvalidState { description: e.to_string(), }) }) @@ -115,7 +115,7 @@ where }) }) .transpose() - .map_err(|e| HostError::MissingData { + .map_err(|e| HostError::MissingState { description: e.to_string(), })?; @@ -154,7 +154,7 @@ where }) }) .transpose() - .map_err(|e| HostError::MissingData { + .map_err(|e| HostError::MissingState { description: e.to_string(), })?; @@ -185,7 +185,7 @@ where client_cons_state_path.revision_number, client_cons_state_path.revision_height, ) - .map_err(|e| HostError::InvalidData { + .map_err(|e| HostError::InvalidState { description: e.to_string(), })?; let consensus_state = self diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index faefd28c9..93b17319b 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -42,7 +42,7 @@ where fn host_height(&self) -> Result { Height::new(*self.revision_number.lock(), self.store.current_height()).map_err(|e| { - HostError::InvalidData { + HostError::InvalidState { description: e.to_string(), } }) @@ -57,7 +57,7 @@ where fn client_counter(&self) -> Result { self.client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(HostError::MissingData { + .ok_or(HostError::MissingState { description: "missing client counter".to_string(), }) } @@ -68,7 +68,7 @@ where consensus_states_binding .get(&height.revision_height()) .cloned() - .ok_or(HostError::MissingData { + .ok_or(HostError::MissingState { description: ClientError::MissingLocalConsensusState(*height).to_string(), }) } @@ -91,7 +91,7 @@ where .latest_height() .revision_number() { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "client is not in the same revision as the chain. expected: {}, got: {}", self_revision_number, @@ -104,7 +104,7 @@ where let host_current_height = latest_height.increment(); if client_state_of_host_on_counterparty.latest_height() >= host_current_height { - return Err(HostError::InvalidData { + return Err(HostError::InvalidState { description: format!( "invalid counterparty client state: client latest height {} should be less than chain height {}", client_state_of_host_on_counterparty.latest_height(), @@ -119,7 +119,7 @@ where fn connection_end(&self, conn_id: &ConnectionId) -> Result { self.connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) - .ok_or(HostError::MissingData { + .ok_or(HostError::MissingState { description: format!("missing connection end for connection {}", conn_id.clone()), }) } @@ -133,7 +133,7 @@ where fn connection_counter(&self) -> Result { self.conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(HostError::MissingData { + .ok_or(HostError::MissingState { description: "missing connection counter".to_string(), }) } @@ -338,7 +338,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::InvalidData { + .map_err(|e| HostError::InvalidState { description: e.to_string(), })?; let client_state = self @@ -374,7 +374,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::InvalidData { + .map_err(|e| HostError::InvalidState { description: e.to_string(), }) }) diff --git a/tests-integration/tests/core/ics02_client/upgrade_client.rs b/tests-integration/tests/core/ics02_client/upgrade_client.rs index ed09d154a..7ec273f15 100644 --- a/tests-integration/tests/core/ics02_client/upgrade_client.rs +++ b/tests-integration/tests/core/ics02_client/upgrade_client.rs @@ -143,7 +143,7 @@ fn msg_upgrade_client_healthy() { #[test] fn upgrade_client_fail_nonexisting_client() { let fxt = msg_upgrade_client_fixture(Ctx::Default, Msg::Default); - let expected_err = HandlerError::Host(HostError::MissingData { + let expected_err = HandlerError::Host(HostError::MissingState { description: format!( "missing client state for client {0}", fxt.msg.client_id.clone() diff --git a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs index 45e4bc395..29b87495d 100644 --- a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs +++ b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs @@ -127,7 +127,7 @@ fn conn_open_ack_validate(fxt: &Fixture, expect: Expect) { let cons_state_height = fxt.msg.consensus_height_of_a_on_b; match res.unwrap_err() { - HandlerError::Host(HostError::MissingData { ref description }) => { + HandlerError::Host(HostError::MissingState { ref description }) => { assert!(description.contains(right_connection_id.to_string().as_str())) } HandlerError::Connection(ConnectionError::InsufficientConsensusHeight { @@ -188,7 +188,7 @@ fn conn_open_ack_healthy() { #[test] fn conn_open_ack_no_connection() { let fxt = conn_open_ack_fixture(Ctx::New); - let expected_err = HandlerError::Host(HostError::MissingData { + let expected_err = HandlerError::Host(HostError::MissingState { description: format!( "missing connection end for connection {}", fxt.msg.conn_id_on_a.clone() From 96b4797f800c6b903bd66a389c4a4e74d3e037f7 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 12:55:10 -0500 Subject: [PATCH 092/107] Define helper functions for HostError --- ibc-core/ics24-host/types/src/error.rs | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 7e0e5563a..588eff7b9 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -38,6 +38,38 @@ pub enum HostError { Other { description: String }, } +impl HostError { + pub fn invalid_state(description: T) -> Self { + Self::InvalidState { + description: description.to_string(), + } + } + + pub fn missing_state(description: T) -> Self { + Self::MissingState { + description: description.to_string(), + } + } + + pub fn failed_to_update_store(description: T) -> Self { + Self::FailedToUpdateStore { + description: description.to_string(), + } + } + + pub fn failed_to_retrieve_from_store(description: T) -> Self { + Self::FailedToRetrieveFromStore { + description: description.to_string(), + } + } + + pub fn failed_to_store_data(description: T) -> Self { + Self::FailedToStoreData { + description: description.to_string(), + } + } +} + /// Errors that arise when parsing identifiers. #[cfg_attr(feature = "serde", derive(serde::Serialize))] #[derive(Debug, Display)] From ee93e43c7f389efc0d50f1499c63f18466be4a51 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:12:19 -0500 Subject: [PATCH 093/107] Use newly-define HostError helpers --- .../ics02-client/src/handler/update_client.rs | 6 +- .../src/handler/upgrade_client.rs | 6 +- .../cosmos/src/validate_self_client.rs | 80 +++---- ibc-core/ics24-host/src/context.rs | 4 +- ibc-core/ics24-host/types/src/error.rs | 4 +- .../src/testapp/ibc/core/client_ctx.rs | 71 +++--- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 205 +++++++++--------- .../tests/core/ics02_client/upgrade_client.rs | 10 +- .../core/ics03_connection/conn_open_ack.rs | 10 +- 9 files changed, 180 insertions(+), 216 deletions(-) diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index 1f8bdae14..2cce3dd1e 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -79,9 +79,9 @@ where { let event = { let consensus_height = - consensus_heights.first().ok_or(HostError::MissingState { - description: "missing updated height in client update state".to_string(), - })?; + consensus_heights.first().ok_or(HostError::missing_state( + "missing updated height in client update state".to_string(), + ))?; IbcEvent::UpdateClient(UpdateClient::new( client_id, diff --git a/ibc-core/ics02-client/src/handler/upgrade_client.rs b/ibc-core/ics02-client/src/handler/upgrade_client.rs index 300540212..3fe5f8b95 100644 --- a/ibc-core/ics02-client/src/handler/upgrade_client.rs +++ b/ibc-core/ics02-client/src/handler/upgrade_client.rs @@ -38,12 +38,12 @@ where ); let old_consensus_state = client_val_ctx .consensus_state(&old_client_cons_state_path) - .map_err(|_| HostError::MissingState { - description: format!( + .map_err(|_| { + HostError::missing_state(format!( "missing consensus state for client {} at height {}", client_id, old_client_state.latest_height() - ), + )) })?; // Validate the upgraded client state and consensus state and verify proofs against the root diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index d1f4dd162..e36b9a314 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -25,7 +25,7 @@ pub trait ValidateSelfClientContext { })?; if client_state_of_host_on_counterparty.is_frozen() { - return Err(HostError::UnexpectedData { + return Err(HostError::UnexpectedState { description: "client unexpectedly frozen".to_string(), }); } @@ -33,45 +33,37 @@ pub trait ValidateSelfClientContext { let self_chain_id = self.chain_id(); if self_chain_id != &client_state_of_host_on_counterparty.chain_id { - return Err(HostError::InvalidState { - description: format!( - "invalid chain ID: expected {}, actual {}", - self_chain_id, client_state_of_host_on_counterparty.chain_id - ), - }); + return Err(HostError::invalid_state(format!( + "invalid chain ID: expected {}, actual {}", + self_chain_id, client_state_of_host_on_counterparty.chain_id + ))); } let latest_height = client_state_of_host_on_counterparty.latest_height; let self_revision_number = self_chain_id.revision_number(); if self_revision_number != latest_height.revision_number() { - return Err(HostError::InvalidState { - description: format!( - "mismatched client revision numbers; expected {}, actual {}", - self_revision_number, - latest_height.revision_number() - ), - }); + return Err(HostError::invalid_state(format!( + "mismatched client revision numbers; expected {}, actual {}", + self_revision_number, + latest_height.revision_number() + ))); } if latest_height >= self.host_current_height() { - return Err(HostError::InvalidState { - description: format!( - "client latest height {} should be less than chain height {}", - latest_height, - self.host_current_height() - ), - }); + return Err(HostError::invalid_state(format!( + "client latest height {} should be less than chain height {}", + latest_height, + self.host_current_height() + ))); } if self.proof_specs() != &client_state_of_host_on_counterparty.proof_specs { - return Err(HostError::InvalidState { - description: format!( - "invalid client proof specs; expected {:?}, actual {:?}", - self.proof_specs(), - client_state_of_host_on_counterparty.proof_specs - ), - }); + return Err(HostError::invalid_state(format!( + "invalid client proof specs; expected {:?}, actual {:?}", + self.proof_specs(), + client_state_of_host_on_counterparty.proof_specs + ))); } let _ = { @@ -81,41 +73,35 @@ pub trait ValidateSelfClientContext { trust_level.numerator(), trust_level.denominator(), ) - .map_err(|e| HostError::InvalidState { - description: e.to_string(), - })? + .map_err(|e| HostError::invalid_state(e.to_string()))? }; if self.unbonding_period() != client_state_of_host_on_counterparty.unbonding_period { - return Err(HostError::InvalidState { - description: format!( - "invalid unbonding period; expected {:?}, actual {:?}", - self.unbonding_period(), - client_state_of_host_on_counterparty.unbonding_period, - ), - }); + return Err(HostError::invalid_state(format!( + "invalid unbonding period; expected {:?}, actual {:?}", + self.unbonding_period(), + client_state_of_host_on_counterparty.unbonding_period, + ))); } if client_state_of_host_on_counterparty.unbonding_period < client_state_of_host_on_counterparty.trusting_period { - return Err(HostError::InvalidState { description: format!( + return Err(HostError::invalid_state(format!( "invalid counterparty client state: unbonding period must be greater than trusting period; unbonding period ({:?}) < trusting period ({:?})", client_state_of_host_on_counterparty.unbonding_period, client_state_of_host_on_counterparty.trusting_period - )}); + ))); } if !client_state_of_host_on_counterparty.upgrade_path.is_empty() && self.upgrade_path() != client_state_of_host_on_counterparty.upgrade_path { - return Err(HostError::InvalidState { - description: format!( - "invalid upgrade path; expected {:?}, actual {:?}", - self.upgrade_path(), - client_state_of_host_on_counterparty.upgrade_path - ), - }); + return Err(HostError::invalid_state(format!( + "invalid upgrade path; expected {:?}, actual {:?}", + self.upgrade_path(), + client_state_of_host_on_counterparty.upgrade_path + ))); } Ok(()) diff --git a/ibc-core/ics24-host/src/context.rs b/ibc-core/ics24-host/src/context.rs index 4a11b276b..19e9769ec 100644 --- a/ibc-core/ics24-host/src/context.rs +++ b/ibc-core/ics24-host/src/context.rs @@ -86,9 +86,7 @@ pub trait ValidationContext { &self.get_compatible_versions(), counterparty_candidate_versions, ) - .map_err(|e| HostError::MissingState { - description: e.to_string(), - }) + .map_err(|e| HostError::missing_state(e.to_string())) } /// Returns the `ChannelEnd` for the given `port_id` and `chan_id`. diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 588eff7b9..e73fe53cd 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -30,8 +30,8 @@ pub enum HostError { FailedToValidateClient { description: String }, /// non-existent type: `{description}` NonexistentType { description: String }, - /// unexpected data: `{description}` - UnexpectedData { description: String }, + /// unexpected state: `{description}` + UnexpectedState { description: String }, /// unknown resource: `{description}` UnknownResource { description: String }, /// other error: `{description}` diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index afc7e7611..3f6248082 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -76,9 +76,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::InvalidState { - description: e.to_string(), - }) + .map_err(|e| HostError::invalid_state(e.to_string())) }) .collect::, _>>() } @@ -106,18 +104,16 @@ where .map(|path| { self.consensus_state_store .get(StoreHeight::Pending, &path) - .ok_or_else(|| HostError::FailedToRetrieveFromStore { - description: format!( + .ok_or_else(|| { + HostError::failed_to_retrieve_from_store(format!( "missing consensus state for client {} at height {}", client_id.clone(), *height - ), + )) }) }) .transpose() - .map_err(|e| HostError::MissingState { - description: e.to_string(), - })?; + .map_err(|e| HostError::missing_state(e.to_string()))?; Ok(consensus_state) } @@ -145,18 +141,16 @@ where .map(|path| { self.consensus_state_store .get(StoreHeight::Pending, &path) - .ok_or_else(|| HostError::FailedToRetrieveFromStore { - description: format!( + .ok_or_else(|| { + HostError::failed_to_retrieve_from_store(format!( "missing consensus state for client {} at height {}", client_id.clone(), *height - ), + )) }) }) .transpose() - .map_err(|e| HostError::MissingState { - description: e.to_string(), - })?; + .map_err(|e| HostError::missing_state(e.to_string()))?; Ok(consensus_state) } @@ -172,9 +166,10 @@ where fn client_state(&self, client_id: &ClientId) -> Result { self.client_state_store .get(StoreHeight::Pending, &ClientStatePath(client_id.clone())) - .ok_or(HostError::FailedToRetrieveFromStore { - description: format!("missing client state for client {}", client_id.clone()), - }) + .ok_or(HostError::failed_to_retrieve_from_store(format!( + "missing client state for client {}", + client_id.clone() + ))) } fn consensus_state( @@ -185,19 +180,15 @@ where client_cons_state_path.revision_number, client_cons_state_path.revision_height, ) - .map_err(|e| HostError::InvalidState { - description: e.to_string(), - })?; + .map_err(|e| HostError::invalid_state(e.to_string()))?; let consensus_state = self .consensus_state_store .get(StoreHeight::Pending, client_cons_state_path) - .ok_or(HostError::FailedToRetrieveFromStore { - description: format!( - "missing consensus state for client {} at height {}", - client_cons_state_path.client_id.clone(), - height - ), - })?; + .ok_or(HostError::failed_to_retrieve_from_store(format!( + "missing consensus state for client {} at height {}", + client_cons_state_path.client_id.clone(), + height + )))?; Ok(consensus_state) } @@ -217,13 +208,11 @@ where let processed_timestamp = self .client_processed_times .get(StoreHeight::Pending, &client_update_time_path) - .ok_or(HostError::FailedToRetrieveFromStore { - description: format!( - "missing client update metadata for client {} at height {}", - client_id.clone(), - *height, - ), - })?; + .ok_or(HostError::failed_to_retrieve_from_store(format!( + "missing client update metadata for client {} at height {}", + client_id.clone(), + *height, + )))?; let client_update_height_path = ClientUpdateHeightPath::new( client_id.clone(), height.revision_number(), @@ -232,13 +221,11 @@ where let processed_height = self .client_processed_heights .get(StoreHeight::Pending, &client_update_height_path) - .ok_or(HostError::FailedToRetrieveFromStore { - description: format!( - "missing client update metadata for client {} at height {}", - client_id.clone(), - *height, - ), - })?; + .ok_or(HostError::failed_to_retrieve_from_store(format!( + "missing client update metadata for client {} at height {}", + client_id.clone(), + *height, + )))?; Ok((processed_timestamp, processed_height)) } diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 93b17319b..1f9159bbc 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -41,11 +41,8 @@ where type HostConsensusState = AnyConsensusState; fn host_height(&self) -> Result { - Height::new(*self.revision_number.lock(), self.store.current_height()).map_err(|e| { - HostError::InvalidState { - description: e.to_string(), - } - }) + Height::new(*self.revision_number.lock(), self.store.current_height()) + .map_err(|e| HostError::invalid_state(e.to_string())) } fn host_timestamp(&self) -> Result { @@ -57,9 +54,9 @@ where fn client_counter(&self) -> Result { self.client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(HostError::MissingState { - description: "missing client counter".to_string(), - }) + .ok_or(HostError::missing_state( + "missing client counter".to_string(), + )) } fn host_consensus_state(&self, height: &Height) -> Result { @@ -68,9 +65,9 @@ where consensus_states_binding .get(&height.revision_height()) .cloned() - .ok_or(HostError::MissingState { - description: ClientError::MissingLocalConsensusState(*height).to_string(), - }) + .ok_or(HostError::missing_state( + ClientError::MissingLocalConsensusState(*height).to_string(), + )) } fn validate_self_client( @@ -78,7 +75,7 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), HostError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err(HostError::UnexpectedData { + return Err(HostError::UnexpectedState { description: "unexpected frozen client".to_string(), }); } @@ -91,26 +88,24 @@ where .latest_height() .revision_number() { - return Err(HostError::InvalidState { - description: format!( - "client is not in the same revision as the chain. expected: {}, got: {}", - self_revision_number, - client_state_of_host_on_counterparty - .latest_height() - .revision_number() - ), - }); + return Err(HostError::invalid_state(format!( + "client is not in the same revision as the chain; expected {}, actual {}", + self_revision_number, + client_state_of_host_on_counterparty + .latest_height() + .revision_number() + ))); } let host_current_height = latest_height.increment(); if client_state_of_host_on_counterparty.latest_height() >= host_current_height { - return Err(HostError::InvalidState { - description: format!( + return Err(HostError::invalid_state( + format!( "invalid counterparty client state: client latest height {} should be less than chain height {}", client_state_of_host_on_counterparty.latest_height(), host_current_height ), - }); + )); } Ok(()) @@ -119,9 +114,10 @@ where fn connection_end(&self, conn_id: &ConnectionId) -> Result { self.connection_end_store .get(StoreHeight::Pending, &ConnectionPath::new(conn_id)) - .ok_or(HostError::MissingState { - description: format!("missing connection end for connection {}", conn_id.clone()), - }) + .ok_or(HostError::missing_state(format!( + "missing connection end for connection {}", + conn_id.clone() + ))) } fn commitment_prefix(&self) -> CommitmentPrefix { @@ -133,9 +129,9 @@ where fn connection_counter(&self) -> Result { self.conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(HostError::MissingState { - description: "missing connection counter".to_string(), - }) + .ok_or(HostError::missing_state( + "missing connection counter".to_string(), + )) } fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { @@ -159,9 +155,9 @@ where StoreHeight::Pending, &SeqSendPath::new(&seq_send_path.0, &seq_send_path.1), ) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve send packet sequence".to_string(), - }) + .ok_or(HostError::failed_to_retrieve_from_store( + "failed to retrieve send packet sequence".to_string(), + )) } fn get_next_sequence_recv(&self, seq_recv_path: &SeqRecvPath) -> Result { @@ -170,9 +166,9 @@ where StoreHeight::Pending, &SeqRecvPath::new(&seq_recv_path.0, &seq_recv_path.1), ) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve recv packet sequence".to_string(), - }) + .ok_or(HostError::failed_to_retrieve_from_store( + "failed to retrieve recv packet sequence".to_string(), + )) } fn get_next_sequence_ack(&self, seq_ack_path: &SeqAckPath) -> Result { @@ -181,9 +177,9 @@ where StoreHeight::Pending, &SeqAckPath::new(&seq_ack_path.0, &seq_ack_path.1), ) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve ack packet sequence".to_string(), - }) + .ok_or(HostError::failed_to_retrieve_from_store( + "failed to retrieve ack packet sequence".to_string(), + )) } fn get_packet_commitment( @@ -199,9 +195,9 @@ where commitment_path.sequence, ), ) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve packet commitment".to_string(), - }) + .ok_or(HostError::failed_to_retrieve_from_store( + "failed to retrieve packet commitment".to_string(), + )) } fn get_packet_receipt(&self, receipt_path: &ReceiptPath) -> Result { @@ -224,12 +220,10 @@ where StoreHeight::Pending, &AckPath::new(&ack_path.port_id, &ack_path.channel_id, ack_path.sequence), ) - .ok_or(HostError::FailedToRetrieveFromStore { - description: format!( - "failed to retrieve packet acknowledgment {}", - ack_path.sequence - ), - }) + .ok_or(HostError::failed_to_retrieve_from_store(format!( + "failed to retrieve packet acknowledgment {}", + ack_path.sequence + ))) } /// Returns a counter of the number of channel ids that have been created thus far. @@ -238,9 +232,9 @@ where fn channel_counter(&self) -> Result { self.channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "failed to retrieve channel counter".to_string(), - }) + .ok_or(HostError::failed_to_retrieve_from_store( + "failed to retrieve channel counter".to_string(), + )) } /// Returns the maximum expected time per block @@ -305,11 +299,11 @@ where let client_state = self .client_state_store .get(StoreHeight::Pending, &client_state_path) - .ok_or_else(|| HostError::FailedToRetrieveFromStore { - description: format!( + .ok_or_else(|| { + HostError::failed_to_retrieve_from_store(format!( "failed to retrieve client state from path {}", client_state_path.0.clone() - ), + )) })?; Ok((client_state_path.0, client_state)) }) @@ -338,18 +332,14 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::InvalidState { - description: e.to_string(), - })?; + .map_err(|e| HostError::invalid_state(e.to_string()))?; let client_state = self .consensus_state_store .get(StoreHeight::Pending, &consensus_path) - .ok_or(HostError::FailedToRetrieveFromStore { - description: format!( - "missing consensus state for client {} at height {}", - consensus_path.client_id, height, - ), - })?; + .ok_or(HostError::failed_to_retrieve_from_store(format!( + "missing consensus state for client {} at height {}", + consensus_path.client_id, height, + )))?; Ok((height, client_state)) }) .collect() @@ -374,9 +364,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::InvalidState { - description: e.to_string(), - }) + .map_err(|e| HostError::invalid_state(e.to_string())) }) .collect::, _>>() } @@ -399,8 +387,11 @@ where let connection_end = self .connection_end_store .get(StoreHeight::Pending, &connection_path) - .ok_or_else(|| HostError::FailedToRetrieveFromStore { - description: format!("missing connection {}", connection_path.0.clone()), + .ok_or_else(|| { + HostError::failed_to_retrieve_from_store(format!( + "missing connection {}", + connection_path.0.clone() + )) })?; Ok(IdentifiedConnectionEnd { connection_id: connection_path.0, @@ -438,12 +429,12 @@ where let channel_end = self .channel_end_store .get(StoreHeight::Pending, &channel_path) - .ok_or_else(|| HostError::FailedToRetrieveFromStore { - description: format!( + .ok_or_else(|| { + HostError::failed_to_retrieve_from_store(format!( "missing channel {} with port {}", channel_path.1.clone(), channel_path.0.clone() - ), + )) })?; Ok(IdentifiedChannelEnd { port_id: channel_path.0, @@ -633,14 +624,14 @@ where let current_sequence = self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "missing client counter".to_string(), - })?; + .ok_or(HostError::failed_to_retrieve_from_store( + "missing client counter".to_string(), + ))?; self.client_counter .set(NextClientSequencePath, current_sequence + 1) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to update client counter: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to update client counter: {e:?}")) })?; Ok(()) @@ -654,8 +645,8 @@ where ) -> Result<(), HostError> { self.connection_end_store .set(connection_path.clone(), connection_end) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to set connection end: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to set connection end: {e:?}")) })?; Ok(()) } @@ -673,8 +664,8 @@ where conn_ids.push(conn_id); self.connection_ids_store .set(client_connection_path.clone(), conn_ids) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store connection IDs: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to store connection IDs: {e:?}")) })?; Ok(()) } @@ -685,14 +676,16 @@ where let current_sequence = self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "missing connection counter".to_string(), - })?; + .ok_or(HostError::failed_to_retrieve_from_store( + "missing connection counter".to_string(), + ))?; self.conn_counter .set(NextConnectionSequencePath, current_sequence + 1) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to update connection counter: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!( + "failed to update connection counter: {e:?}" + )) })?; Ok(()) @@ -705,8 +698,10 @@ where ) -> Result<(), HostError> { self.packet_commitment_store .set(commitment_path.clone(), commitment) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store packet commitment: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!( + "failed to store packet commitment: {e:?}" + )) })?; Ok(()) } @@ -726,8 +721,8 @@ where ) -> Result<(), HostError> { self.packet_receipt_store .set_path(receipt_path.clone()) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store packet receipt: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to store packet receipt: {e:?}")) })?; Ok(()) } @@ -739,8 +734,10 @@ where ) -> Result<(), HostError> { self.packet_ack_store .set(ack_path.clone(), ack_commitment) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store packet acknowledgment: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!( + "failed to store packet acknowledgment: {e:?}" + )) })?; Ok(()) } @@ -757,8 +754,8 @@ where ) -> Result<(), HostError> { self.channel_end_store .set(channel_end_path.clone(), channel_end) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store channel: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to store channel: {e:?}")) })?; Ok(()) } @@ -770,8 +767,8 @@ where ) -> Result<(), HostError> { self.send_sequence_store .set(seq_send_path.clone(), seq) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store send sequence: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to store send sequence: {e:?}")) })?; Ok(()) } @@ -783,8 +780,8 @@ where ) -> Result<(), HostError> { self.recv_sequence_store .set(seq_recv_path.clone(), seq) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store recv sequence: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to store recv sequence: {e:?}")) })?; Ok(()) } @@ -796,8 +793,8 @@ where ) -> Result<(), HostError> { self.ack_sequence_store .set(seq_ack_path.clone(), seq) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to store ack sequence: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to store ack sequence: {e:?}")) })?; Ok(()) } @@ -806,14 +803,14 @@ where let current_sequence = self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(HostError::FailedToRetrieveFromStore { - description: "missing counter".to_string(), - })?; + .ok_or(HostError::failed_to_retrieve_from_store( + "missing counter".to_string(), + ))?; self.channel_counter .set(NextChannelSequencePath, current_sequence + 1) - .map_err(|e| HostError::FailedToUpdateStore { - description: format!("failed to update counter: {e:?}"), + .map_err(|e| { + HostError::failed_to_update_store(format!("failed to update counter: {e:?}")) })?; Ok(()) } diff --git a/tests-integration/tests/core/ics02_client/upgrade_client.rs b/tests-integration/tests/core/ics02_client/upgrade_client.rs index 7ec273f15..fb2e0f22b 100644 --- a/tests-integration/tests/core/ics02_client/upgrade_client.rs +++ b/tests-integration/tests/core/ics02_client/upgrade_client.rs @@ -143,12 +143,10 @@ fn msg_upgrade_client_healthy() { #[test] fn upgrade_client_fail_nonexisting_client() { let fxt = msg_upgrade_client_fixture(Ctx::Default, Msg::Default); - let expected_err = HandlerError::Host(HostError::MissingState { - description: format!( - "missing client state for client {0}", - fxt.msg.client_id.clone() - ), - }); + let expected_err = HandlerError::Host(HostError::missing_state(format!( + "missing client state for client {0}", + fxt.msg.client_id.clone() + ))); upgrade_client_validate(&fxt, Expect::Failure(Some(expected_err))); } diff --git a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs index 29b87495d..bf5064ad5 100644 --- a/tests-integration/tests/core/ics03_connection/conn_open_ack.rs +++ b/tests-integration/tests/core/ics03_connection/conn_open_ack.rs @@ -188,12 +188,10 @@ fn conn_open_ack_healthy() { #[test] fn conn_open_ack_no_connection() { let fxt = conn_open_ack_fixture(Ctx::New); - let expected_err = HandlerError::Host(HostError::MissingState { - description: format!( - "missing connection end for connection {}", - fxt.msg.conn_id_on_a.clone() - ), - }); + let expected_err = HandlerError::Host(HostError::missing_state(format!( + "missing connection end for connection {}", + fxt.msg.conn_id_on_a.clone() + ))); conn_open_ack_validate(&fxt, Expect::Failure(Some(expected_err))); } From 2a53a7dbf5e4c934c56ef998d0d77d1e5bc9c204 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:15:17 -0500 Subject: [PATCH 094/107] Remove HostError::AppModule variant --- ibc-core/ics24-host/types/src/error.rs | 2 -- tests-integration/tests/core/router.rs | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index e73fe53cd..7e97559ae 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -12,8 +12,6 @@ use prost::DecodeError as ProstError; /// Errors that originate from host implementations. #[derive(Debug, Display)] pub enum HostError { - /// application module error: `{description}` - AppModule { description: String }, /// invalid state: `{description}` InvalidState { description: String }, /// missing state: `{description}` diff --git a/tests-integration/tests/core/router.rs b/tests-integration/tests/core/router.rs index c0f7ed9be..825352428 100644 --- a/tests-integration/tests/core/router.rs +++ b/tests-integration/tests/core/router.rs @@ -407,8 +407,8 @@ fn routing_module_and_keepers() { let res = match test.msg.clone() { TestMsg::Ics26(msg) => dispatch(&mut ctx.ibc_store, &mut router, msg), TestMsg::Ics20(msg) => send_transfer(&mut ctx.ibc_store, &mut DummyTransferModule, msg) - .map_err(|e: TokenTransferError| HostError::AppModule { - description: e.to_string(), + .map_err(|e: TokenTransferError| HostError::Other { + description: format!("token transfer application error: {e}"), }) .map_err(HandlerError::from), }; From a1926e2ff08c5db594cb9ae8e23237aebcd94966 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:37:51 -0500 Subject: [PATCH 095/107] Prune some HostError variants --- ibc-apps/ics20-transfer/src/handler/mod.rs | 4 ++-- .../src/handler/on_recv_packet.rs | 2 +- .../src/handler/send_transfer.rs | 4 ++-- .../ics721-nft-transfer/src/handler/mod.rs | 17 ++++++------- .../ics721-nft-transfer/types/src/error.rs | 4 +++- .../types/src/msgs/migrate_contract.rs | 2 +- ibc-core/ics24-host/types/src/error.rs | 24 +++++++------------ 7 files changed, 24 insertions(+), 33 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index 155749747..1f88ad64c 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -22,7 +22,7 @@ pub fn refund_packet_token_execute( .sender .clone() .try_into() - .map_err(|_| HostError::FailedToParseData { + .map_err(|_| HostError::FailedToParse { description: "invalid signer".to_string(), })?; @@ -53,7 +53,7 @@ pub fn refund_packet_token_validate( .sender .clone() .try_into() - .map_err(|_| HostError::FailedToParseData { + .map_err(|_| HostError::FailedToParse { description: "invalid signer".to_string(), })?; diff --git a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs index e13b2ec25..9ae4781c1 100644 --- a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs +++ b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs @@ -27,7 +27,7 @@ pub fn process_recv_packet_execute( let receiver_account = data.receiver.clone().try_into().map_err(|_| { ( ModuleExtras::empty(), - HostError::FailedToParseData { + HostError::FailedToParse { description: "account ID".to_string(), } .into(), diff --git a/ibc-apps/ics20-transfer/src/handler/send_transfer.rs b/ibc-apps/ics20-transfer/src/handler/send_transfer.rs index 3d0c59b5d..e16c6b33d 100644 --- a/ibc-apps/ics20-transfer/src/handler/send_transfer.rs +++ b/ibc-apps/ics20-transfer/src/handler/send_transfer.rs @@ -62,7 +62,7 @@ where .sender .clone() .try_into() - .map_err(|_| HostError::FailedToParseData { + .map_err(|_| HostError::FailedToParse { description: "invalid signer".to_string(), })?; @@ -137,7 +137,7 @@ where .sender .clone() .try_into() - .map_err(|_| HostError::FailedToParseData { + .map_err(|_| HostError::FailedToParse { description: "invalid signer".to_string(), })?; diff --git a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs index 94b3f6e5b..5574fc345 100644 --- a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs +++ b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs @@ -3,8 +3,6 @@ mod on_recv_packet; mod send_transfer; -use ibc_core::channel::types::packet::Packet; -use ibc_core::handler::types::error::HandlerError; pub use on_recv_packet::*; pub use send_transfer::*; @@ -12,6 +10,7 @@ use crate::context::{NftTransferExecutionContext, NftTransferValidationContext}; use crate::types::error::NftTransferError; use crate::types::is_sender_chain_source; use crate::types::packet::PacketData; +use ibc_core::channel::types::packet::Packet; pub fn refund_packet_nft_execute( ctx_a: &mut impl NftTransferExecutionContext, @@ -38,7 +37,7 @@ pub fn refund_packet_nft_execute( &data.class_id, token_id, ) - .map_err(|e| NftTransferError::Handler(HandlerError::Host(e))) + .map_err(NftTransferError::from) }) } // mint vouchers back to sender @@ -47,9 +46,8 @@ pub fn refund_packet_nft_execute( let token_uri = data.token_uris.as_ref().and_then(|uris| uris.get(i)); let token_data = data.token_data.as_ref().and_then(|data| data.get(i)); - let _ = ctx_a - .mint_nft_execute(&sender, &data.class_id, token_id, token_uri, token_data) - .map_err(|_| NftTransferError::Handler); + let _ = + ctx_a.mint_nft_execute(&sender, &data.class_id, token_id, token_uri, token_data); } Ok(()) @@ -81,16 +79,15 @@ pub fn refund_packet_nft_validate( &data.class_id, token_id, ) - .map_err(|e| NftTransferError::Handler(HandlerError::Host(e))) + .map_err(NftTransferError::from) }) } else { for (i, token_id) in data.token_ids.0.iter().enumerate() { let token_uri = data.token_uris.as_ref().and_then(|uris| uris.get(i)); let token_data = data.token_data.as_ref().and_then(|data| data.get(i)); - let _ = ctx_a - .mint_nft_validate(&sender, &data.class_id, token_id, token_uri, token_data) - .map_err(|_| NftTransferError::Handler); + let _ = + ctx_a.mint_nft_validate(&sender, &data.class_id, token_id, token_uri, token_data); } Ok(()) diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 122c04684..1aba5f367 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -1,5 +1,7 @@ //! Defines the Non-Fungible Token Transfer (ICS-721) error types. +use derive_more::From; use displaydoc::Display; + use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; @@ -7,7 +9,7 @@ use ibc_core::host::types::error::{DecodingError, HostError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; -#[derive(Display, Debug, derive_more::From)] +#[derive(Display, Debug, From)] pub enum NftTransferError { /// handler error: `{0}` Handler(HandlerError), diff --git a/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs b/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs index 6a8e860e3..3f7bc6a93 100644 --- a/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs +++ b/ibc-clients/ics08-wasm/types/src/msgs/migrate_contract.rs @@ -39,7 +39,7 @@ impl TryFrom for MsgMigrateContract { fn try_from(value: RawMsgMigrateContract) -> Result { Ok(Self { signer: Signer::from(value.signer), - client_id: ClientId::from_str(&value.client_id).map_err(DecodingError::Identifier)?, + client_id: ClientId::from_str(&value.client_id)?, checksum: value.checksum, msg: value.msg, }) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 7e97559ae..72bc835eb 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -17,13 +17,11 @@ pub enum HostError { /// missing state: `{description}` MissingState { description: String }, /// failed to update store: `{description}` - FailedToUpdateStore { description: String }, - /// failed to store data: `{description}` - FailedToStoreData { description: String }, - /// failed to retrieve data from store: `{description}` - FailedToRetrieveFromStore { description: String }, + FailedToStore { description: String }, + /// failed to retrieve from store: `{description}` + FailedToRetrieve { description: String }, /// failed to parse data: `{description}` - FailedToParseData { description: String }, + FailedToParse { description: String }, /// failed to validate client: `{description}` FailedToValidateClient { description: String }, /// non-existent type: `{description}` @@ -49,20 +47,14 @@ impl HostError { } } - pub fn failed_to_update_store(description: T) -> Self { - Self::FailedToUpdateStore { + pub fn failed_to_retrieve(description: T) -> Self { + Self::FailedToRetrieve { description: description.to_string(), } } - pub fn failed_to_retrieve_from_store(description: T) -> Self { - Self::FailedToRetrieveFromStore { - description: description.to_string(), - } - } - - pub fn failed_to_store_data(description: T) -> Self { - Self::FailedToStoreData { + pub fn failed_to_store(description: T) -> Self { + Self::FailedToStore { description: description.to_string(), } } From 3604b3b66a16fc4f971363650e3806f8880c78d3 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:42:54 -0500 Subject: [PATCH 096/107] Consolidate some HostError variants --- .../src/testapp/ibc/core/client_ctx.rs | 28 +++------ ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 62 ++++++++----------- 2 files changed, 35 insertions(+), 55 deletions(-) diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index 3f6248082..f46cfa112 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -105,7 +105,7 @@ where self.consensus_state_store .get(StoreHeight::Pending, &path) .ok_or_else(|| { - HostError::failed_to_retrieve_from_store(format!( + HostError::failed_to_retrieve(format!( "missing consensus state for client {} at height {}", client_id.clone(), *height @@ -142,7 +142,7 @@ where self.consensus_state_store .get(StoreHeight::Pending, &path) .ok_or_else(|| { - HostError::failed_to_retrieve_from_store(format!( + HostError::failed_to_retrieve(format!( "missing consensus state for client {} at height {}", client_id.clone(), *height @@ -166,7 +166,7 @@ where fn client_state(&self, client_id: &ClientId) -> Result { self.client_state_store .get(StoreHeight::Pending, &ClientStatePath(client_id.clone())) - .ok_or(HostError::failed_to_retrieve_from_store(format!( + .ok_or(HostError::failed_to_retrieve(format!( "missing client state for client {}", client_id.clone() ))) @@ -184,7 +184,7 @@ where let consensus_state = self .consensus_state_store .get(StoreHeight::Pending, client_cons_state_path) - .ok_or(HostError::failed_to_retrieve_from_store(format!( + .ok_or(HostError::failed_to_retrieve(format!( "missing consensus state for client {} at height {}", client_cons_state_path.client_id.clone(), height @@ -208,7 +208,7 @@ where let processed_timestamp = self .client_processed_times .get(StoreHeight::Pending, &client_update_time_path) - .ok_or(HostError::failed_to_retrieve_from_store(format!( + .ok_or(HostError::failed_to_retrieve(format!( "missing client update metadata for client {} at height {}", client_id.clone(), *height, @@ -221,7 +221,7 @@ where let processed_height = self .client_processed_heights .get(StoreHeight::Pending, &client_update_height_path) - .ok_or(HostError::failed_to_retrieve_from_store(format!( + .ok_or(HostError::failed_to_retrieve(format!( "missing client update metadata for client {} at height {}", client_id.clone(), *height, @@ -245,9 +245,7 @@ where ) -> Result<(), HostError> { self.client_state_store .set(client_state_path, client_state) - .map_err(|e| HostError::FailedToStoreData { - description: format!("{e:?}"), - })?; + .map_err(|e| HostError::failed_to_store(format!("{e:?}")))?; Ok(()) } @@ -260,9 +258,7 @@ where ) -> Result<(), HostError> { self.consensus_state_store .set(consensus_state_path, consensus_state) - .map_err(|e| HostError::FailedToStoreData { - description: format!("{e:?}"), - })?; + .map_err(|e| HostError::failed_to_store(format!("{e:?}")))?; Ok(()) } @@ -310,9 +306,7 @@ where ); self.client_processed_times .set(client_update_time_path, host_timestamp) - .map_err(|e| HostError::FailedToStoreData { - description: format!("{e:?}"), - })?; + .map_err(|e| HostError::failed_to_store(format!("{e:?}")))?; let client_update_height_path = ClientUpdateHeightPath::new( client_id, height.revision_number(), @@ -320,9 +314,7 @@ where ); self.client_processed_heights .set(client_update_height_path, host_height) - .map_err(|e| HostError::FailedToStoreData { - description: format!("{e:?}"), - })?; + .map_err(|e| HostError::failed_to_store(format!("{e:?}")))?; Ok(()) } } diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 1f9159bbc..425cb2aff 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -155,7 +155,7 @@ where StoreHeight::Pending, &SeqSendPath::new(&seq_send_path.0, &seq_send_path.1), ) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "failed to retrieve send packet sequence".to_string(), )) } @@ -166,7 +166,7 @@ where StoreHeight::Pending, &SeqRecvPath::new(&seq_recv_path.0, &seq_recv_path.1), ) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "failed to retrieve recv packet sequence".to_string(), )) } @@ -177,7 +177,7 @@ where StoreHeight::Pending, &SeqAckPath::new(&seq_ack_path.0, &seq_ack_path.1), ) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "failed to retrieve ack packet sequence".to_string(), )) } @@ -195,7 +195,7 @@ where commitment_path.sequence, ), ) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "failed to retrieve packet commitment".to_string(), )) } @@ -220,7 +220,7 @@ where StoreHeight::Pending, &AckPath::new(&ack_path.port_id, &ack_path.channel_id, ack_path.sequence), ) - .ok_or(HostError::failed_to_retrieve_from_store(format!( + .ok_or(HostError::failed_to_retrieve(format!( "failed to retrieve packet acknowledgment {}", ack_path.sequence ))) @@ -232,7 +232,7 @@ where fn channel_counter(&self) -> Result { self.channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "failed to retrieve channel counter".to_string(), )) } @@ -300,7 +300,7 @@ where .client_state_store .get(StoreHeight::Pending, &client_state_path) .ok_or_else(|| { - HostError::failed_to_retrieve_from_store(format!( + HostError::failed_to_retrieve(format!( "failed to retrieve client state from path {}", client_state_path.0.clone() )) @@ -336,7 +336,7 @@ where let client_state = self .consensus_state_store .get(StoreHeight::Pending, &consensus_path) - .ok_or(HostError::failed_to_retrieve_from_store(format!( + .ok_or(HostError::failed_to_retrieve(format!( "missing consensus state for client {} at height {}", consensus_path.client_id, height, )))?; @@ -388,7 +388,7 @@ where .connection_end_store .get(StoreHeight::Pending, &connection_path) .ok_or_else(|| { - HostError::failed_to_retrieve_from_store(format!( + HostError::failed_to_retrieve(format!( "missing connection {}", connection_path.0.clone() )) @@ -430,7 +430,7 @@ where .channel_end_store .get(StoreHeight::Pending, &channel_path) .ok_or_else(|| { - HostError::failed_to_retrieve_from_store(format!( + HostError::failed_to_retrieve(format!( "missing channel {} with port {}", channel_path.1.clone(), channel_path.0.clone() @@ -624,14 +624,14 @@ where let current_sequence = self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "missing client counter".to_string(), ))?; self.client_counter .set(NextClientSequencePath, current_sequence + 1) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to update client counter: {e:?}")) + HostError::failed_to_store(format!("failed to update client counter: {e:?}")) })?; Ok(()) @@ -646,7 +646,7 @@ where self.connection_end_store .set(connection_path.clone(), connection_end) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to set connection end: {e:?}")) + HostError::failed_to_store(format!("failed to set connection end: {e:?}")) })?; Ok(()) } @@ -665,7 +665,7 @@ where self.connection_ids_store .set(client_connection_path.clone(), conn_ids) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to store connection IDs: {e:?}")) + HostError::failed_to_store(format!("failed to store connection IDs: {e:?}")) })?; Ok(()) } @@ -676,16 +676,14 @@ where let current_sequence = self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(HostError::failed_to_retrieve_from_store( + .ok_or(HostError::failed_to_retrieve( "missing connection counter".to_string(), ))?; self.conn_counter .set(NextConnectionSequencePath, current_sequence + 1) .map_err(|e| { - HostError::failed_to_update_store(format!( - "failed to update connection counter: {e:?}" - )) + HostError::failed_to_store(format!("failed to update connection counter: {e:?}")) })?; Ok(()) @@ -699,9 +697,7 @@ where self.packet_commitment_store .set(commitment_path.clone(), commitment) .map_err(|e| { - HostError::failed_to_update_store(format!( - "failed to store packet commitment: {e:?}" - )) + HostError::failed_to_store(format!("failed to store packet commitment: {e:?}")) })?; Ok(()) } @@ -722,7 +718,7 @@ where self.packet_receipt_store .set_path(receipt_path.clone()) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to store packet receipt: {e:?}")) + HostError::failed_to_store(format!("failed to store packet receipt: {e:?}")) })?; Ok(()) } @@ -735,9 +731,7 @@ where self.packet_ack_store .set(ack_path.clone(), ack_commitment) .map_err(|e| { - HostError::failed_to_update_store(format!( - "failed to store packet acknowledgment: {e:?}" - )) + HostError::failed_to_store(format!("failed to store packet acknowledgment: {e:?}")) })?; Ok(()) } @@ -754,9 +748,7 @@ where ) -> Result<(), HostError> { self.channel_end_store .set(channel_end_path.clone(), channel_end) - .map_err(|e| { - HostError::failed_to_update_store(format!("failed to store channel: {e:?}")) - })?; + .map_err(|e| HostError::failed_to_store(format!("failed to store channel: {e:?}")))?; Ok(()) } @@ -768,7 +760,7 @@ where self.send_sequence_store .set(seq_send_path.clone(), seq) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to store send sequence: {e:?}")) + HostError::failed_to_store(format!("failed to store send sequence: {e:?}")) })?; Ok(()) } @@ -781,7 +773,7 @@ where self.recv_sequence_store .set(seq_recv_path.clone(), seq) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to store recv sequence: {e:?}")) + HostError::failed_to_store(format!("failed to store recv sequence: {e:?}")) })?; Ok(()) } @@ -794,7 +786,7 @@ where self.ack_sequence_store .set(seq_ack_path.clone(), seq) .map_err(|e| { - HostError::failed_to_update_store(format!("failed to store ack sequence: {e:?}")) + HostError::failed_to_store(format!("failed to store ack sequence: {e:?}")) })?; Ok(()) } @@ -803,15 +795,11 @@ where let current_sequence = self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(HostError::failed_to_retrieve_from_store( - "missing counter".to_string(), - ))?; + .ok_or(HostError::failed_to_retrieve("missing counter".to_string()))?; self.channel_counter .set(NextChannelSequencePath, current_sequence + 1) - .map_err(|e| { - HostError::failed_to_update_store(format!("failed to update counter: {e:?}")) - })?; + .map_err(|e| HostError::failed_to_store(format!("failed to update counter: {e:?}")))?; Ok(()) } From 817fa33cfab6b7e165d531565c1995b0d096d42c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:44:39 -0500 Subject: [PATCH 097/107] Remove HostError::NonexistentType variant --- ibc-core/ics24-host/types/src/error.rs | 2 -- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 12 +++++------- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 72bc835eb..b01b21e62 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -24,8 +24,6 @@ pub enum HostError { FailedToParse { description: String }, /// failed to validate client: `{description}` FailedToValidateClient { description: String }, - /// non-existent type: `{description}` - NonexistentType { description: String }, /// unexpected state: `{description}` UnexpectedState { description: String }, /// unknown resource: `{description}` diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index 425cb2aff..a34f7eeb4 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -140,13 +140,11 @@ where StoreHeight::Pending, &ChannelEndPath::new(&channel_end_path.0, &channel_end_path.1), ) - .ok_or(HostError::NonexistentType { - description: format!( - "non-existent channel {} in port {}", - channel_end_path.1.clone(), - channel_end_path.0.clone() - ), - }) + .ok_or(HostError::missing_state(format!( + "missing channel {} in port {}", + channel_end_path.1.clone(), + channel_end_path.0.clone() + ))) } fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result { From 579e8179866c7781c39c9c2b7be59ac63a718d5a Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:46:30 -0500 Subject: [PATCH 098/107] Remove HostError::UnexpectedState variant --- ibc-core/ics24-host/cosmos/src/validate_self_client.rs | 6 +++--- ibc-core/ics24-host/types/src/error.rs | 2 -- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 6 +++--- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index e36b9a314..5671af5d2 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -25,9 +25,9 @@ pub trait ValidateSelfClientContext { })?; if client_state_of_host_on_counterparty.is_frozen() { - return Err(HostError::UnexpectedState { - description: "client unexpectedly frozen".to_string(), - }); + return Err(HostError::invalid_state( + "client unexpectedly frozen".to_string(), + )); } let self_chain_id = self.chain_id(); diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index b01b21e62..15f76c83f 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -24,8 +24,6 @@ pub enum HostError { FailedToParse { description: String }, /// failed to validate client: `{description}` FailedToValidateClient { description: String }, - /// unexpected state: `{description}` - UnexpectedState { description: String }, /// unknown resource: `{description}` UnknownResource { description: String }, /// other error: `{description}` diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index a34f7eeb4..eeaa2e7e1 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -75,9 +75,9 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), HostError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err(HostError::UnexpectedState { - description: "unexpected frozen client".to_string(), - }); + return Err(HostError::invalid_state( + "client unexpectedly frozen".to_string(), + )); } let latest_height = self.host_height()?; From 6db8f1f170e56c9d2368227f2f9b30fc8fa8971c Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:49:07 -0500 Subject: [PATCH 099/107] Consolidate HostError::UnknownResource variant --- ibc-core/ics24-host/types/src/error.rs | 2 -- ibc-core/ics25-handler/src/entrypoint.rs | 28 ++++++++++++++---------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 15f76c83f..19531fcc3 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -24,8 +24,6 @@ pub enum HostError { FailedToParse { description: String }, /// failed to validate client: `{description}` FailedToValidateClient { description: String }, - /// unknown resource: `{description}` - UnknownResource { description: String }, /// other error: `{description}` Other { description: String }, } diff --git a/ibc-core/ics25-handler/src/entrypoint.rs b/ibc-core/ics25-handler/src/entrypoint.rs index 144ee33b3..f3aa2323a 100644 --- a/ibc-core/ics25-handler/src/entrypoint.rs +++ b/ibc-core/ics25-handler/src/entrypoint.rs @@ -82,9 +82,10 @@ where let port_id = channel_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(HostError::UnknownResource { - description: format!("port {}", port_id.clone()), - })?; + .ok_or(HostError::missing_state(format!( + "failed to look up port {}", + port_id.clone() + )))?; let module = router .get_route(&module_id) .ok_or(RouterError::MissingModule)?; @@ -102,9 +103,10 @@ where let port_id = packet_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(HostError::UnknownResource { - description: format!("port {}", port_id.clone()), - })?; + .ok_or(HostError::missing_state(format!( + "failed to look up port {}", + port_id.clone() + )))?; let module = router .get_route(&module_id) .ok_or(RouterError::MissingModule)?; @@ -159,9 +161,10 @@ where let port_id = channel_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(HostError::UnknownResource { - description: format!("port {}", port_id.clone()), - })?; + .ok_or(HostError::missing_state(format!( + "failed to look up port {}", + port_id.clone() + )))?; let module = router .get_route_mut(&module_id) .ok_or(RouterError::MissingModule)?; @@ -179,9 +182,10 @@ where let port_id = packet_msg_to_port_id(&msg); let module_id = router .lookup_module(port_id) - .ok_or(HostError::UnknownResource { - description: format!("port {}", port_id.clone()), - })?; + .ok_or(HostError::missing_state(format!( + "failed to look up port {}", + port_id.clone() + )))?; let module = router .get_route_mut(&module_id) .ok_or(RouterError::MissingModule)?; From 33972e08f6c6eb598053ad9e1112076a74120dbe Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Fri, 13 Sep 2024 13:49:39 -0500 Subject: [PATCH 100/107] cargo fmt --- ibc-apps/ics721-nft-transfer/src/handler/mod.rs | 2 +- ibc-apps/ics721-nft-transfer/types/src/error.rs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs index 5574fc345..9acca019f 100644 --- a/ibc-apps/ics721-nft-transfer/src/handler/mod.rs +++ b/ibc-apps/ics721-nft-transfer/src/handler/mod.rs @@ -3,6 +3,7 @@ mod on_recv_packet; mod send_transfer; +use ibc_core::channel::types::packet::Packet; pub use on_recv_packet::*; pub use send_transfer::*; @@ -10,7 +11,6 @@ use crate::context::{NftTransferExecutionContext, NftTransferValidationContext}; use crate::types::error::NftTransferError; use crate::types::is_sender_chain_source; use crate::types::packet::PacketData; -use ibc_core::channel::types::packet::Packet; pub fn refund_packet_nft_execute( ctx_a: &mut impl NftTransferExecutionContext, diff --git a/ibc-apps/ics721-nft-transfer/types/src/error.rs b/ibc-apps/ics721-nft-transfer/types/src/error.rs index 1aba5f367..bda017a9b 100644 --- a/ibc-apps/ics721-nft-transfer/types/src/error.rs +++ b/ibc-apps/ics721-nft-transfer/types/src/error.rs @@ -1,7 +1,6 @@ //! Defines the Non-Fungible Token Transfer (ICS-721) error types. use derive_more::From; use displaydoc::Display; - use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; use ibc_core::handler::types::error::HandlerError; From c5bb0afd3ca24e839fbfbe7a117229aae0468c2b Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 16 Sep 2024 10:10:14 -0500 Subject: [PATCH 101/107] Remove unnecessary to_string calls --- .../ics02-client/src/handler/update_client.rs | 7 ++-- .../cosmos/src/validate_self_client.rs | 6 +-- ibc-core/ics24-host/src/context.rs | 2 +- .../src/testapp/ibc/core/client_ctx.rs | 8 ++-- ibc-testkit/src/testapp/ibc/core/core_ctx.rs | 40 +++++++------------ 5 files changed, 25 insertions(+), 38 deletions(-) diff --git a/ibc-core/ics02-client/src/handler/update_client.rs b/ibc-core/ics02-client/src/handler/update_client.rs index 2cce3dd1e..b40d94a68 100644 --- a/ibc-core/ics02-client/src/handler/update_client.rs +++ b/ibc-core/ics02-client/src/handler/update_client.rs @@ -78,10 +78,9 @@ where { let event = { - let consensus_height = - consensus_heights.first().ok_or(HostError::missing_state( - "missing updated height in client update state".to_string(), - ))?; + let consensus_height = consensus_heights.first().ok_or( + HostError::missing_state("missing updated height in client update state"), + )?; IbcEvent::UpdateClient(UpdateClient::new( client_id, diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index 5671af5d2..a15601395 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -25,9 +25,7 @@ pub trait ValidateSelfClientContext { })?; if client_state_of_host_on_counterparty.is_frozen() { - return Err(HostError::invalid_state( - "client unexpectedly frozen".to_string(), - )); + return Err(HostError::invalid_state("client unexpectedly frozen")); } let self_chain_id = self.chain_id(); @@ -73,7 +71,7 @@ pub trait ValidateSelfClientContext { trust_level.numerator(), trust_level.denominator(), ) - .map_err(|e| HostError::invalid_state(e.to_string()))? + .map_err(HostError::invalid_state)? }; if self.unbonding_period() != client_state_of_host_on_counterparty.unbonding_period { diff --git a/ibc-core/ics24-host/src/context.rs b/ibc-core/ics24-host/src/context.rs index 19e9769ec..a9a84ab53 100644 --- a/ibc-core/ics24-host/src/context.rs +++ b/ibc-core/ics24-host/src/context.rs @@ -86,7 +86,7 @@ pub trait ValidationContext { &self.get_compatible_versions(), counterparty_candidate_versions, ) - .map_err(|e| HostError::missing_state(e.to_string())) + .map_err(HostError::missing_state) } /// Returns the `ChannelEnd` for the given `port_id` and `chan_id`. diff --git a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs index f46cfa112..f2dbe930c 100644 --- a/ibc-testkit/src/testapp/ibc/core/client_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/client_ctx.rs @@ -76,7 +76,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::invalid_state(e.to_string())) + .map_err(HostError::invalid_state) }) .collect::, _>>() } @@ -113,7 +113,7 @@ where }) }) .transpose() - .map_err(|e| HostError::missing_state(e.to_string()))?; + .map_err(HostError::missing_state)?; Ok(consensus_state) } @@ -150,7 +150,7 @@ where }) }) .transpose() - .map_err(|e| HostError::missing_state(e.to_string()))?; + .map_err(HostError::missing_state)?; Ok(consensus_state) } @@ -180,7 +180,7 @@ where client_cons_state_path.revision_number, client_cons_state_path.revision_height, ) - .map_err(|e| HostError::invalid_state(e.to_string()))?; + .map_err(HostError::invalid_state)?; let consensus_state = self .consensus_state_store .get(StoreHeight::Pending, client_cons_state_path) diff --git a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs index eeaa2e7e1..d97140764 100644 --- a/ibc-testkit/src/testapp/ibc/core/core_ctx.rs +++ b/ibc-testkit/src/testapp/ibc/core/core_ctx.rs @@ -42,7 +42,7 @@ where fn host_height(&self) -> Result { Height::new(*self.revision_number.lock(), self.store.current_height()) - .map_err(|e| HostError::invalid_state(e.to_string())) + .map_err(HostError::invalid_state) } fn host_timestamp(&self) -> Result { @@ -54,9 +54,7 @@ where fn client_counter(&self) -> Result { self.client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(HostError::missing_state( - "missing client counter".to_string(), - )) + .ok_or(HostError::missing_state("missing client counter")) } fn host_consensus_state(&self, height: &Height) -> Result { @@ -66,7 +64,7 @@ where .get(&height.revision_height()) .cloned() .ok_or(HostError::missing_state( - ClientError::MissingLocalConsensusState(*height).to_string(), + ClientError::MissingLocalConsensusState(*height), )) } @@ -75,9 +73,7 @@ where client_state_of_host_on_counterparty: Self::HostClientState, ) -> Result<(), HostError> { if client_state_of_host_on_counterparty.is_frozen() { - return Err(HostError::invalid_state( - "client unexpectedly frozen".to_string(), - )); + return Err(HostError::invalid_state("client unexpectedly frozen")); } let latest_height = self.host_height()?; @@ -129,9 +125,7 @@ where fn connection_counter(&self) -> Result { self.conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(HostError::missing_state( - "missing connection counter".to_string(), - )) + .ok_or(HostError::missing_state("missing connection counter")) } fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { @@ -154,7 +148,7 @@ where &SeqSendPath::new(&seq_send_path.0, &seq_send_path.1), ) .ok_or(HostError::failed_to_retrieve( - "failed to retrieve send packet sequence".to_string(), + "failed to retrieve send packet sequence", )) } @@ -165,7 +159,7 @@ where &SeqRecvPath::new(&seq_recv_path.0, &seq_recv_path.1), ) .ok_or(HostError::failed_to_retrieve( - "failed to retrieve recv packet sequence".to_string(), + "failed to retrieve recv packet sequence", )) } @@ -176,7 +170,7 @@ where &SeqAckPath::new(&seq_ack_path.0, &seq_ack_path.1), ) .ok_or(HostError::failed_to_retrieve( - "failed to retrieve ack packet sequence".to_string(), + "failed to retrieve ack packet sequence", )) } @@ -194,7 +188,7 @@ where ), ) .ok_or(HostError::failed_to_retrieve( - "failed to retrieve packet commitment".to_string(), + "failed to retrieve packet commitment", )) } @@ -231,7 +225,7 @@ where self.channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) .ok_or(HostError::failed_to_retrieve( - "failed to retrieve channel counter".to_string(), + "failed to retrieve channel counter", )) } @@ -330,7 +324,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::invalid_state(e.to_string()))?; + .map_err(HostError::invalid_state)?; let client_state = self .consensus_state_store .get(StoreHeight::Pending, &consensus_path) @@ -362,7 +356,7 @@ where consensus_path.revision_number, consensus_path.revision_height, ) - .map_err(|e| HostError::invalid_state(e.to_string())) + .map_err(HostError::invalid_state) }) .collect::, _>>() } @@ -622,9 +616,7 @@ where let current_sequence = self .client_counter .get(StoreHeight::Pending, &NextClientSequencePath) - .ok_or(HostError::failed_to_retrieve( - "missing client counter".to_string(), - ))?; + .ok_or(HostError::failed_to_retrieve("missing client counter"))?; self.client_counter .set(NextClientSequencePath, current_sequence + 1) @@ -674,9 +666,7 @@ where let current_sequence = self .conn_counter .get(StoreHeight::Pending, &NextConnectionSequencePath) - .ok_or(HostError::failed_to_retrieve( - "missing connection counter".to_string(), - ))?; + .ok_or(HostError::failed_to_retrieve("missing connection counter"))?; self.conn_counter .set(NextConnectionSequencePath, current_sequence + 1) @@ -793,7 +783,7 @@ where let current_sequence = self .channel_counter .get(StoreHeight::Pending, &NextChannelSequencePath) - .ok_or(HostError::failed_to_retrieve("missing counter".to_string()))?; + .ok_or(HostError::failed_to_retrieve("missing counter"))?; self.channel_counter .set(NextChannelSequencePath, current_sequence + 1) From 29fbe1cbe4f99bc656fe8b75b509b217d3a358e1 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 16 Sep 2024 10:17:55 -0500 Subject: [PATCH 102/107] Revert `pick_version` method's documentation --- ibc-core/ics03-connection/types/src/version.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ibc-core/ics03-connection/types/src/version.rs b/ibc-core/ics03-connection/types/src/version.rs index 2a2db6fcf..5a2061edf 100644 --- a/ibc-core/ics03-connection/types/src/version.rs +++ b/ibc-core/ics03-connection/types/src/version.rs @@ -117,10 +117,8 @@ impl Display for Version { /// counterparty. The returned version contains a feature set with the /// intersection of the features supported by the source and counterparty /// chains. If the feature set intersection is nil, the search for a -/// compatible version continues. If no feature set intersection is found -/// after searching through every supported version, then `None` is returned. -/// -/// This function is called in the `conn_open_try` handshake procedure. +/// compatible version continues. This function is called in the `conn_open_try` +/// handshake procedure. /// /// NOTE: Empty feature sets are not currently allowed for a chosen version. pub fn pick_version( From c8ad6e5156eb7b09b3676fa46902cd917473b819 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 16 Sep 2024 10:34:36 -0500 Subject: [PATCH 103/107] Remove some more HostError variants --- ibc-apps/ics20-transfer/src/handler/mod.rs | 9 ++---- .../src/handler/on_recv_packet.rs | 6 +--- .../src/handler/send_transfer.rs | 29 ++++++++----------- ibc-apps/ics20-transfer/types/src/error.rs | 21 +++++--------- .../cosmos/src/validate_self_client.rs | 6 ++-- ibc-core/ics24-host/types/src/error.rs | 4 --- 6 files changed, 27 insertions(+), 48 deletions(-) diff --git a/ibc-apps/ics20-transfer/src/handler/mod.rs b/ibc-apps/ics20-transfer/src/handler/mod.rs index 1f88ad64c..95ed5441c 100644 --- a/ibc-apps/ics20-transfer/src/handler/mod.rs +++ b/ibc-apps/ics20-transfer/src/handler/mod.rs @@ -6,7 +6,6 @@ use ibc_app_transfer_types::error::TokenTransferError; use ibc_app_transfer_types::is_sender_chain_source; use ibc_app_transfer_types::packet::PacketData; use ibc_core::channel::types::packet::Packet; -use ibc_core::host::types::error::HostError; use ibc_core::primitives::prelude::*; pub use on_recv_packet::*; pub use send_transfer::*; @@ -22,9 +21,7 @@ pub fn refund_packet_token_execute( .sender .clone() .try_into() - .map_err(|_| HostError::FailedToParse { - description: "invalid signer".to_string(), - })?; + .map_err(|_| TokenTransferError::FailedToParseAccount)?; if is_sender_chain_source( packet.port_id_on_a.clone(), @@ -53,9 +50,7 @@ pub fn refund_packet_token_validate( .sender .clone() .try_into() - .map_err(|_| HostError::FailedToParse { - description: "invalid signer".to_string(), - })?; + .map_err(|_| TokenTransferError::FailedToParseAccount)?; if is_sender_chain_source( packet.port_id_on_a.clone(), diff --git a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs index 9ae4781c1..76e22b3b6 100644 --- a/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs +++ b/ibc-apps/ics20-transfer/src/handler/on_recv_packet.rs @@ -3,7 +3,6 @@ use ibc_app_transfer_types::events::DenomTraceEvent; use ibc_app_transfer_types::packet::PacketData; use ibc_app_transfer_types::{is_receiver_chain_source, TracePrefix}; use ibc_core::channel::types::packet::Packet; -use ibc_core::host::types::error::HostError; use ibc_core::primitives::prelude::*; use ibc_core::router::types::module::ModuleExtras; @@ -27,10 +26,7 @@ pub fn process_recv_packet_execute( let receiver_account = data.receiver.clone().try_into().map_err(|_| { ( ModuleExtras::empty(), - HostError::FailedToParse { - description: "account ID".to_string(), - } - .into(), + TokenTransferError::FailedToParseAccount, ) })?; diff --git a/ibc-apps/ics20-transfer/src/handler/send_transfer.rs b/ibc-apps/ics20-transfer/src/handler/send_transfer.rs index e16c6b33d..39d40ea46 100644 --- a/ibc-apps/ics20-transfer/src/handler/send_transfer.rs +++ b/ibc-apps/ics20-transfer/src/handler/send_transfer.rs @@ -6,7 +6,6 @@ use ibc_core::channel::context::{SendPacketExecutionContext, SendPacketValidatio use ibc_core::channel::handler::{send_packet_execute, send_packet_validate}; use ibc_core::channel::types::packet::Packet; use ibc_core::handler::types::events::MessageEvent; -use ibc_core::host::types::error::HostError; use ibc_core::host::types::path::{ChannelEndPath, SeqSendPath}; use ibc_core::primitives::prelude::*; use ibc_core::router::types::event::ModuleEvent; @@ -57,14 +56,12 @@ where let token = &msg.packet_data.token; - let sender: TokenCtx::AccountId = - msg.packet_data - .sender - .clone() - .try_into() - .map_err(|_| HostError::FailedToParse { - description: "invalid signer".to_string(), - })?; + let sender: TokenCtx::AccountId = msg + .packet_data + .sender + .clone() + .try_into() + .map_err(|_| TokenTransferError::FailedToParseAccount)?; if is_sender_chain_source( msg.port_id_on_a.clone(), @@ -132,14 +129,12 @@ where let token = &msg.packet_data.token; - let sender = - msg.packet_data - .sender - .clone() - .try_into() - .map_err(|_| HostError::FailedToParse { - description: "invalid signer".to_string(), - })?; + let sender = msg + .packet_data + .sender + .clone() + .try_into() + .map_err(|_| TokenTransferError::FailedToParseAccount)?; if is_sender_chain_source( msg.port_id_on_a.clone(), diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index d694b6659..50f2cbd39 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -2,15 +2,14 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; -use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::{DecodingError, HostError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; #[derive(Display, Debug)] pub enum TokenTransferError { - /// handler error: `{0}` - Handler(HandlerError), + /// host error: `{0}` + Host(HostError), /// decoding error: `{0}` Decoding(DecodingError), /// missing destination channel `{channel_id}` on port `{port_id}` @@ -28,22 +27,24 @@ pub enum TokenTransferError { FailedToDeserializePacketData, /// failed to deserialize acknowledgement FailedToDeserializeAck, + /// failed to parse account + FailedToParseAccount, } #[cfg(feature = "std")] impl std::error::Error for TokenTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::Handler(e) => Some(e), + Self::Host(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } } } -impl From for TokenTransferError { - fn from(e: HandlerError) -> Self { - Self::Handler(e) +impl From for TokenTransferError { + fn from(e: HostError) -> Self { + Self::Host(e) } } @@ -53,12 +54,6 @@ impl From for TokenTransferError { } } -impl From for TokenTransferError { - fn from(e: HostError) -> Self { - Self::Handler(HandlerError::Host(e)) - } -} - impl From for StatusValue { fn from(e: TokenTransferError) -> Self { StatusValue::new(e.to_string()).expect("error message must not be empty") diff --git a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs index a15601395..d6c84e365 100644 --- a/ibc-core/ics24-host/cosmos/src/validate_self_client.rs +++ b/ibc-core/ics24-host/cosmos/src/validate_self_client.rs @@ -20,8 +20,10 @@ pub trait ValidateSelfClientContext { ) -> Result<(), HostError> { client_state_of_host_on_counterparty .validate() - .map_err(|e| HostError::FailedToValidateClient { - description: e.to_string(), + .map_err(|e| { + HostError::invalid_state(format!( + "invalid counterparty client state that could not be validated: {e}" + )) })?; if client_state_of_host_on_counterparty.is_frozen() { diff --git a/ibc-core/ics24-host/types/src/error.rs b/ibc-core/ics24-host/types/src/error.rs index 19531fcc3..7fd47c2cc 100644 --- a/ibc-core/ics24-host/types/src/error.rs +++ b/ibc-core/ics24-host/types/src/error.rs @@ -20,10 +20,6 @@ pub enum HostError { FailedToStore { description: String }, /// failed to retrieve from store: `{description}` FailedToRetrieve { description: String }, - /// failed to parse data: `{description}` - FailedToParse { description: String }, - /// failed to validate client: `{description}` - FailedToValidateClient { description: String }, /// other error: `{description}` Other { description: String }, } From 191239572cda876fccfba0f072ba062f2c6baafa Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 16 Sep 2024 11:07:56 -0500 Subject: [PATCH 104/107] Remove From for StatusValue impl --- ibc-apps/ics20-transfer/types/src/error.rs | 13 ++++++-- ibc-apps/ics721-nft-transfer/src/module.rs | 32 ++++--------------- .../types/src/acknowledgement.rs | 6 ---- 3 files changed, 17 insertions(+), 34 deletions(-) diff --git a/ibc-apps/ics20-transfer/types/src/error.rs b/ibc-apps/ics20-transfer/types/src/error.rs index 50f2cbd39..00e81614b 100644 --- a/ibc-apps/ics20-transfer/types/src/error.rs +++ b/ibc-apps/ics20-transfer/types/src/error.rs @@ -2,6 +2,7 @@ use displaydoc::Display; use ibc_core::channel::types::acknowledgement::StatusValue; use ibc_core::channel::types::channel::Order; +use ibc_core::handler::types::error::HandlerError; use ibc_core::host::types::error::{DecodingError, HostError}; use ibc_core::host::types::identifiers::{ChannelId, PortId}; use ibc_core::primitives::prelude::*; @@ -9,7 +10,7 @@ use ibc_core::primitives::prelude::*; #[derive(Display, Debug)] pub enum TokenTransferError { /// host error: `{0}` - Host(HostError), + Handler(HandlerError), /// decoding error: `{0}` Decoding(DecodingError), /// missing destination channel `{channel_id}` on port `{port_id}` @@ -35,16 +36,22 @@ pub enum TokenTransferError { impl std::error::Error for TokenTransferError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::Host(e) => Some(e), + Self::Handler(e) => Some(e), Self::Decoding(e) => Some(e), _ => None, } } } +impl From for TokenTransferError { + fn from(e: HandlerError) -> Self { + Self::Handler(e) + } +} + impl From for TokenTransferError { fn from(e: HostError) -> Self { - Self::Host(e) + Self::Handler(HandlerError::Host(e)) } } diff --git a/ibc-apps/ics721-nft-transfer/src/module.rs b/ibc-apps/ics721-nft-transfer/src/module.rs index ee13595f7..5084b50ba 100644 --- a/ibc-apps/ics721-nft-transfer/src/module.rs +++ b/ibc-apps/ics721-nft-transfer/src/module.rs @@ -173,12 +173,8 @@ pub fn on_recv_packet_execute( packet: &Packet, ) -> (ModuleExtras, Acknowledgement) { let Ok(data) = serde_json::from_slice::(&packet.data) else { - let ack = AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ); + let ack = + AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()); return (ModuleExtras::empty(), ack.into()); }; @@ -344,12 +340,7 @@ mod test { r#"{"result":"AQ=="}"#, ); ser_json_assert_eq( - AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ), + AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()), r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, ); } @@ -366,13 +357,9 @@ mod test { #[test] fn test_ack_error_to_vec() { - let ack_error: Vec = AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ) - .into(); + let ack_error: Vec = + AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()) + .into(); // Check that it's the same output as ibc-go // Note: this also implicitly checks that the ack bytes are non-empty, @@ -396,12 +383,7 @@ mod test { ); de_json_assert_eq( r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, - AcknowledgementStatus::error( - DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into(), - ), + AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()), ); assert!(serde_json::from_str::(r#"{"success":"AQ=="}"#).is_err()); diff --git a/ibc-core/ics04-channel/types/src/acknowledgement.rs b/ibc-core/ics04-channel/types/src/acknowledgement.rs index fbd0ffdd5..c061f2be5 100644 --- a/ibc-core/ics04-channel/types/src/acknowledgement.rs +++ b/ibc-core/ics04-channel/types/src/acknowledgement.rs @@ -142,9 +142,3 @@ impl From for Acknowledgement { .expect("token transfer internal error: ack is never supposed to be empty") } } - -impl From for StatusValue { - fn from(e: DecodingError) -> Self { - StatusValue::new(e.to_string()).expect("error message must not be empty") - } -} From d9b07868922c19f251196e28d1459b9a1e681ee2 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 16 Sep 2024 11:26:58 -0500 Subject: [PATCH 105/107] Fix AcknowledgementStatus tests --- ibc-apps/ics721-nft-transfer/src/module.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/src/module.rs b/ibc-apps/ics721-nft-transfer/src/module.rs index 5084b50ba..ab5a84448 100644 --- a/ibc-apps/ics721-nft-transfer/src/module.rs +++ b/ibc-apps/ics721-nft-transfer/src/module.rs @@ -341,7 +341,7 @@ mod test { ); ser_json_assert_eq( AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()), - r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, + r#"{"error":"failed to deserialize packet data"}"#, ); } @@ -366,7 +366,7 @@ mod test { // which would make the conversion to `Acknowledgement` panic assert_eq!( ack_error, - br#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"# + br#"{"error":"failed to deserialize packet data"}"# ); } @@ -382,7 +382,7 @@ mod test { AcknowledgementStatus::success(ack_success_b64()), ); de_json_assert_eq( - r#"{"error":"invalid JSON data: `failed to deserialize packet data`"}"#, + r#"{"error":"failed to deserialize packet data"}"#, AcknowledgementStatus::error(NftTransferError::FailedToDeserializePacketData.into()), ); From 63a1e5cecc6e5bdd7acb4584969b69d55cc7f09b Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Mon, 16 Sep 2024 10:20:56 -0700 Subject: [PATCH 106/107] fix: revert errors in ICS721 callbacks --- ibc-apps/ics721-nft-transfer/src/module.rs | 34 +++++----------------- 1 file changed, 8 insertions(+), 26 deletions(-) diff --git a/ibc-apps/ics721-nft-transfer/src/module.rs b/ibc-apps/ics721-nft-transfer/src/module.rs index ab5a84448..a1f479b51 100644 --- a/ibc-apps/ics721-nft-transfer/src/module.rs +++ b/ibc-apps/ics721-nft-transfer/src/module.rs @@ -4,7 +4,6 @@ use ibc_core::channel::types::channel::{Counterparty, Order}; use ibc_core::channel::types::packet::Packet; use ibc_core::channel::types::Version; use ibc_core::handler::types::error::HandlerError; -use ibc_core::host::types::error::DecodingError; use ibc_core::host::types::identifiers::{ChannelId, ConnectionId, PortId}; use ibc_core::primitives::prelude::*; use ibc_core::primitives::Signer; @@ -205,16 +204,11 @@ pub fn on_acknowledgement_packet_validate( acknowledgement: &Acknowledgement, _relayer: &Signer, ) -> Result<(), NftTransferError> { - let data = serde_json::from_slice::(&packet.data).map_err(|e| { - DecodingError::InvalidJson { - description: format!("failed to deserialize packet data: {e}"), - } - })?; + let data = serde_json::from_slice::(&packet.data) + .map_err(|_| NftTransferError::FailedToDeserializePacketData)?; let acknowledgement = serde_json::from_slice::(acknowledgement.as_ref()) - .map_err(|e| DecodingError::InvalidJson { - description: format!("failed to deserialize acknowledgment: {e}"), - })?; + .map_err(|_| NftTransferError::FailedToDeserializeAck)?; if !acknowledgement.is_successful() { refund_packet_nft_validate(ctx, packet, &data)?; @@ -232,10 +226,7 @@ pub fn on_acknowledgement_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into()), + Err(NftTransferError::FailedToDeserializePacketData), ); }; @@ -244,10 +235,7 @@ pub fn on_acknowledgement_packet_execute( else { return ( ModuleExtras::empty(), - Err(DecodingError::InvalidJson { - description: "failed to deserialize acknowledgment".to_string(), - } - .into()), + Err(NftTransferError::FailedToDeserializeAck), ); }; @@ -279,11 +267,8 @@ pub fn on_timeout_packet_validate( packet: &Packet, _relayer: &Signer, ) -> Result<(), NftTransferError> { - let data = serde_json::from_slice::(&packet.data).map_err(|e| { - DecodingError::InvalidJson { - description: format!("failed to deserialize packet data: {e}"), - } - })?; + let data = serde_json::from_slice::(&packet.data) + .map_err(|_| NftTransferError::FailedToDeserializePacketData)?; refund_packet_nft_validate(ctx, packet, &data)?; @@ -298,10 +283,7 @@ pub fn on_timeout_packet_execute( let Ok(data) = serde_json::from_slice::(&packet.data) else { return ( ModuleExtras::empty(), - Err(DecodingError::InvalidJson { - description: "failed to deserialize packet data".to_string(), - } - .into()), + Err(NftTransferError::FailedToDeserializePacketData), ); }; From da81e6365e4ce7d0b173127c29a6c6926aa53664 Mon Sep 17 00:00:00 2001 From: Sean Chen Date: Mon, 16 Sep 2024 12:34:47 -0500 Subject: [PATCH 107/107] Change references to HandlerError in docs to refer to HostError where appropriate --- .../1320-define-host-error-type.md | 0 ...482-fix-validate-self-client-error-type.md | 2 +- ...-use-result-for-safe-counters-increment.md | 2 +- ...-result-in-logger-event-emitter-methods.md | 2 +- .../adr-006-upgrade-client-implementation.md | 2 +- .../adr-007-light-client-contexts.md | 6 +-- ...010-enable-standalone-ics02-integration.md | 40 +++++++++---------- 7 files changed, 27 insertions(+), 27 deletions(-) rename .changelog/unreleased/{improvements => breaking-changes}/1320-define-host-error-type.md (100%) diff --git a/.changelog/unreleased/improvements/1320-define-host-error-type.md b/.changelog/unreleased/breaking-changes/1320-define-host-error-type.md similarity index 100% rename from .changelog/unreleased/improvements/1320-define-host-error-type.md rename to .changelog/unreleased/breaking-changes/1320-define-host-error-type.md diff --git a/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md b/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md index 1e0889aa9..f05961027 100644 --- a/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md +++ b/.changelog/v0.31.0/breaking-changes/482-fix-validate-self-client-error-type.md @@ -1,3 +1,3 @@ -- Modify `validate_self_client` error type to return `HandlerError` instead of +- Modify `validate_self_client` error type to return `HostError` instead of `ConnectionError` ([#482](https://github.com/cosmos/ibc-rs/issues/482)) diff --git a/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md b/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md index 23b9d0ed1..c656a7fd9 100644 --- a/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md +++ b/.changelog/v0.45.0/breaking-changes/857-use-result-for-safe-counters-increment.md @@ -1,3 +1,3 @@ - Allow hosts to handle overflow cases in `increase_*_counter` methods by - returning `Result<(),HandlerError>` type. + returning `Result<(),HostError>` type. ([#857](https://github.com/cosmos/ibc-rs/issues/857)) diff --git a/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md b/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md index 901281fc9..7157bd3be 100644 --- a/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md +++ b/.changelog/v0.45.0/breaking-changes/859-return-result-in-logger-event-emitter-methods.md @@ -1,2 +1,2 @@ -- logger and event emitter methods return `Result<(), HandlerError>` type. +- logger and event emitter methods return `Result<(), HostError>` type. ([#859](https://github.com/cosmos/ibc-rs/issues/859)) diff --git a/docs/architecture/adr-006-upgrade-client-implementation.md b/docs/architecture/adr-006-upgrade-client-implementation.md index 90e2d8828..fbfd86535 100644 --- a/docs/architecture/adr-006-upgrade-client-implementation.md +++ b/docs/architecture/adr-006-upgrade-client-implementation.md @@ -250,7 +250,7 @@ previous section as mentioned: 1. ```rust if old_client_state.is_frozen() { - return Err(HandlerError::ClientError(ClientError::ClientFrozen { + return Err(HandlerError::Client(ClientError::ClientFrozen { client_id, })); } diff --git a/docs/architecture/adr-007-light-client-contexts.md b/docs/architecture/adr-007-light-client-contexts.md index 973626b25..5bf30de70 100644 --- a/docs/architecture/adr-007-light-client-contexts.md +++ b/docs/architecture/adr-007-light-client-contexts.md @@ -98,12 +98,12 @@ pub trait ClientExecutionContext: Sized { /// Called upon successful client creation and update fn store_client_state( ... - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; /// Called upon successful client creation and update fn store_consensus_state( ... - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; } ``` @@ -120,7 +120,7 @@ pub trait ValidationContext: Router { type ClientValidationContext; type ClientExecutionContext; /// Enum that can contain a `ConsensusState` object of any supported light client - type AnyConsensusState: ConsensusState; + type AnyConsensusState: ConsensusState; /// Enum that can contain a `ClientState` object of any supported light client type AnyClientState: ClientState< Self::AnyConsensusState, diff --git a/docs/architecture/adr-010-enable-standalone-ics02-integration.md b/docs/architecture/adr-010-enable-standalone-ics02-integration.md index a0a8fb7fc..feb0c9695 100644 --- a/docs/architecture/adr-010-enable-standalone-ics02-integration.md +++ b/docs/architecture/adr-010-enable-standalone-ics02-integration.md @@ -129,26 +129,26 @@ pub trait ValidationContext { fn get_client_validation_context(&self) -> &Self::V; // This method will be removed and replaced by a `ClientStateDecoder` trait that will encapsulate the ability to decode a client state from an `Any` -- fn decode_client_state(&self, client_state: Any) -> Result; +- fn decode_client_state(&self, client_state: Any) -> Result; -- fn client_state(&self, client_id: &ClientId) -> Result; +- fn client_state(&self, client_id: &ClientId) -> Result; - fn consensus_state( - &self, - client_cons_state_path: &ClientConsensusStatePath, -- ) -> Result; +- ) -> Result; fn host_consensus_state( &self, height: &Height, -- ) -> Result; -+ ) -> Result; +- ) -> Result; ++ ) -> Result; fn validate_self_client( &self, - client_state_of_host_on_counterparty: Any, + client_state_of_host_on_counterparty: Self::HostClientState, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; ... // other methods } @@ -200,18 +200,18 @@ pub trait ClientValidationContext: Sized { + type ClientStateRef: ClientStateValidation; + type ConsensusStateRef: ConsensusState; -+ fn client_state(&self, client_id: &ClientId) -> Result; ++ fn client_state(&self, client_id: &ClientId) -> Result; + fn consensus_state( + &self, + client_cons_state_path: &ClientConsensusStatePath, -+ ) -> Result; ++ ) -> Result; fn client_update_meta( &self, client_id: &ClientId, height: &Height, - ) -> Result<(Timestamp, Height), HandlerError>; + ) -> Result<(Timestamp, Height), HostError>; } pub trait ClientExecutionContext: @@ -222,7 +222,7 @@ pub trait ClientExecutionContext: - type AnyConsensusState: ConsensusState; + type ClientStateMut: ClientStateExecution; -+ fn client_state_mut(&self, client_id: &ClientId) -> Result { ++ fn client_state_mut(&self, client_id: &ClientId) -> Result { + self.client_state(client_id) + } @@ -230,18 +230,18 @@ pub trait ClientExecutionContext: &mut self, client_state_path: ClientStatePath, client_state: Self::ClientStateMut, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; fn store_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Self::ConsensusStateRef, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; fn delete_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; fn store_update_meta( &mut self, @@ -249,13 +249,13 @@ pub trait ClientExecutionContext: height: Height, host_timestamp: Timestamp, host_height: Height, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; fn delete_update_meta( &mut self, client_id: ClientId, height: Height, - ) -> Result<(), HandlerError>; + ) -> Result<(), HostError>; } ``` @@ -306,28 +306,28 @@ pub trait ExtClientValidationContext: + type ConversionError: ToString; + type AnyConsensusState: TryInto; -+ fn host_timestamp(&self) -> Result; ++ fn host_timestamp(&self) -> Result; + fn host_height(&self) -> Result; - fn consensus_state( - &self, - client_cons_state_path: &ClientConsensusStatePath, -- ) -> Result; +- ) -> Result; -+ fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HandlerError>; ++ fn consensus_state_heights(&self, client_id: &ClientId) -> Result, HostError>; fn next_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, HandlerError>; + ) -> Result, HostError>; fn prev_consensus_state( &self, client_id: &ClientId, height: &Height, - ) -> Result, HandlerError>; + ) -> Result, HostError>; } -impl ExecutionContext for T where T: CommonContext + ClientExecutionContext {}