From 969d65aac53759e5e640ea2fb93f9483e6be25bd Mon Sep 17 00:00:00 2001 From: Davirain Date: Tue, 22 Nov 2022 18:21:27 +0800 Subject: [PATCH 01/43] Redefine Ics20Error by displaydoc --- crates/ibc/Cargo.toml | 3 +- .../ibc/src/applications/transfer/amount.rs | 2 +- crates/ibc/src/applications/transfer/coin.rs | 13 +- .../ibc/src/applications/transfer/context.rs | 44 ++-- crates/ibc/src/applications/transfer/denom.rs | 17 +- crates/ibc/src/applications/transfer/error.rs | 228 ++++++++---------- .../applications/transfer/msgs/transfer.rs | 47 ++-- .../ibc/src/applications/transfer/packet.rs | 4 +- crates/ibc/src/applications/transfer/relay.rs | 2 +- .../transfer/relay/on_recv_packet.rs | 4 +- .../transfer/relay/send_transfer.rs | 22 +- crates/ibc/src/core/ics26_routing/error.rs | 5 - 12 files changed, 196 insertions(+), 195 deletions(-) diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index e1502dd25..5ea9a8f15 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -18,7 +18,7 @@ all-features = true [features] default = ["std"] -std = ["flex-error/std", "flex-error/eyre_tracer", "ibc-proto/std", "clock"] +std = ["flex-error/std", "flex-error/eyre_tracer", "ibc-proto/std", "clock", "displaydoc/std" ] clock = ["tendermint/clock", "time/std"] # This feature grants access to development-time mocking libraries, such as `MockContext` or `MockHeader`. @@ -41,6 +41,7 @@ safe-regex = { version = "0.2.5", default-features = false } subtle-encoding = { version = "0.5", default-features = false } sha2 = { version = "0.10.6", default-features = false } flex-error = { version = "0.4.4", default-features = false } +displaydoc = { version = "0.2", default-features = false } num-traits = { version = "0.2.15", default-features = false } derive_more = { version = "0.99.17", default-features = false, features = ["from", "into", "display"] } uint = { version = "0.9", default-features = false } diff --git a/crates/ibc/src/applications/transfer/amount.rs b/crates/ibc/src/applications/transfer/amount.rs index c250e9190..06fdbeb0d 100644 --- a/crates/ibc/src/applications/transfer/amount.rs +++ b/crates/ibc/src/applications/transfer/amount.rs @@ -25,7 +25,7 @@ impl FromStr for Amount { type Err = Error; fn from_str(s: &str) -> Result { - let amount = U256::from_dec_str(s).map_err(Error::invalid_amount)?; + let amount = U256::from_dec_str(s).map_err(Error::InvalidAmount)?; Ok(Self(amount)) } } diff --git a/crates/ibc/src/applications/transfer/coin.rs b/crates/ibc/src/applications/transfer/coin.rs index b6581c6fd..4de581d86 100644 --- a/crates/ibc/src/applications/transfer/coin.rs +++ b/crates/ibc/src/applications/transfer/coin.rs @@ -51,14 +51,17 @@ where // https://github.com/cosmos/cosmos-sdk/blob/v0.45.5/types/coin.go#L760-L762 let matcher = regex!(br"([0-9]+)([a-zA-Z0-9/:\\._\x2d]+)"); - let (m1, m2) = matcher - .match_slices(coin_str.as_bytes()) - .ok_or_else(|| Error::invalid_coin(coin_str.to_string()))?; + let (m1, m2) = + matcher + .match_slices(coin_str.as_bytes()) + .ok_or_else(|| Error::InvalidCoin { + coin: coin_str.to_string(), + })?; - let amount = from_utf8(m1).map_err(Error::utf8_decode)?.parse()?; + let amount = from_utf8(m1).map_err(Error::Utf8Decode)?.parse()?; let denom = from_utf8(m2) - .map_err(Error::utf8_decode)? + .map_err(Error::Utf8Decode)? .parse() .map_err(Into::into)?; diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index abeb72baf..ef5c6b4ea 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -165,15 +165,24 @@ pub fn on_chan_open_init( version: &Version, ) -> Result<(ModuleExtras, Version), Ics20Error> { if order != Order::Unordered { - return Err(Ics20Error::channel_not_unordered(order)); + return Err(Ics20Error::ChannelNotUnordered { + expect_order: Order::Unordered, + got_order: order, + }); } let bound_port = ctx.get_port()?; if port_id != &bound_port { - return Err(Ics20Error::invalid_port(port_id.clone(), bound_port)); + return Err(Ics20Error::InvalidPort { + port_id: port_id.clone(), + exp_port_id: bound_port, + }); } if !version.is_empty() && version != &Version::ics20() { - return Err(Ics20Error::invalid_version(version.clone())); + return Err(Ics20Error::InvalidVersion { + expect_version: Version::ics20(), + got_version: version.clone(), + }); } Ok((ModuleExtras::empty(), Version::ics20())) @@ -190,12 +199,16 @@ pub fn on_chan_open_try( counterparty_version: &Version, ) -> Result<(ModuleExtras, Version), Ics20Error> { if order != Order::Unordered { - return Err(Ics20Error::channel_not_unordered(order)); + return Err(Ics20Error::ChannelNotUnordered { + expect_order: Order::Unordered, + got_order: order, + }); } if counterparty_version != &Version::ics20() { - return Err(Ics20Error::invalid_counterparty_version( - counterparty_version.clone(), - )); + return Err(Ics20Error::InvalidCounterpartyVersion { + expect_version: Version::ics20(), + got_version: counterparty_version.clone(), + }); } Ok((ModuleExtras::empty(), Version::ics20())) @@ -208,9 +221,10 @@ pub fn on_chan_open_ack( counterparty_version: &Version, ) -> Result { if counterparty_version != &Version::ics20() { - return Err(Ics20Error::invalid_counterparty_version( - counterparty_version.clone(), - )); + return Err(Ics20Error::InvalidCounterpartyVersion { + expect_version: Version::ics20(), + got_version: counterparty_version.clone(), + }); } Ok(ModuleExtras::empty()) @@ -229,7 +243,7 @@ pub fn on_chan_close_init( _port_id: &PortId, _channel_id: &ChannelId, ) -> Result { - Err(Ics20Error::cant_close_channel()) + Err(Ics20Error::CantCloseChannel) } pub fn on_chan_close_confirm( @@ -250,7 +264,7 @@ pub fn on_recv_packet( Ok(data) => data, Err(_) => { return OnRecvPacketAck::Failed(Box::new(Acknowledgement::Error( - Ics20Error::packet_data_deserialization().to_string(), + Ics20Error::PacketDataDeserialization.to_string(), ))); } }; @@ -279,10 +293,10 @@ pub fn on_acknowledgement_packet( _relayer: &Signer, ) -> Result<(), Ics20Error> { let data = serde_json::from_slice::(&packet.data) - .map_err(|_| Ics20Error::packet_data_deserialization())?; + .map_err(|_| Ics20Error::PacketDataDeserialization)?; let acknowledgement = serde_json::from_slice::(acknowledgement.as_ref()) - .map_err(|_| Ics20Error::ack_deserialization())?; + .map_err(|_| Ics20Error::AckDeserialization)?; process_ack_packet(ctx, packet, &data, &acknowledgement)?; @@ -305,7 +319,7 @@ pub fn on_timeout_packet( _relayer: &Signer, ) -> Result<(), Ics20Error> { let data = serde_json::from_slice::(&packet.data) - .map_err(|_| Ics20Error::packet_data_deserialization())?; + .map_err(|_| Ics20Error::PacketDataDeserialization)?; process_timeout_packet(ctx, packet, &data)?; diff --git a/crates/ibc/src/applications/transfer/denom.rs b/crates/ibc/src/applications/transfer/denom.rs index 4192ba821..148795eac 100644 --- a/crates/ibc/src/applications/transfer/denom.rs +++ b/crates/ibc/src/applications/transfer/denom.rs @@ -26,7 +26,7 @@ impl FromStr for BaseDenom { fn from_str(s: &str) -> Result { if s.trim().is_empty() { - Err(Error::empty_base_denom()) + Err(Error::EmptyBaseDenom) } else { Ok(BaseDenom(s.to_owned())) } @@ -90,16 +90,21 @@ impl<'a> TryFrom> for TracePath { fn try_from(v: Vec<&'a str>) -> Result { if v.len() % 2 != 0 { - return Err(Error::invalid_trace_length(v.len())); + return Err(Error::InvalidTraceLength { len: v.len() }); } let mut trace = vec![]; let id_pairs = v.chunks_exact(2).map(|paths| (paths[0], paths[1])); for (pos, (port_id, channel_id)) in id_pairs.rev().enumerate() { - let port_id = - PortId::from_str(port_id).map_err(|e| Error::invalid_trace_port_id(pos, e))?; - let channel_id = ChannelId::from_str(channel_id) - .map_err(|e| Error::invalid_trace_channel_id(pos, e))?; + let port_id = PortId::from_str(port_id).map_err(|e| Error::InvalidTracePortId { + pos, + validation_error: e, + })?; + let channel_id = + ChannelId::from_str(channel_id).map_err(|e| Error::InvalidTraceChannelId { + pos, + validation_error: e, + })?; trace.push(TracePrefix { port_id, channel_id, diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index e13cb14fe..25e9189ec 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -2,7 +2,7 @@ use alloc::string::FromUtf8Error; use core::convert::Infallible; use core::str::Utf8Error; -use flex_error::{define_error, DisplayOnly, TraceError}; +use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; use subtle_encoding::Error as EncodingError; use uint::FromDecStrErr; @@ -15,134 +15,104 @@ use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::prelude::*; use crate::signer::SignerError; -define_error! { - #[derive(Debug, PartialEq, Eq)] - Error { - UnknowMessageTypeUrl - { url: String } - | e | { format_args!("unrecognized ICS-20 transfer message type URL {0}", e.url) }, - - Ics04Channel - [ channel_error::Error ] - |_ | { "Ics04 channel error" }, - - DestinationChannelNotFound - { port_id: PortId, channel_id: ChannelId } - | e | { format_args!("destination channel not found in the counterparty of port_id {0} and channel_id {1} ", e.port_id, e.channel_id) }, - - InvalidPortId - { context: String } - [ ValidationError ] - | _ | { "invalid port identifier" }, - - InvalidChannelId - { context: String } - [ ValidationError ] - | _ | { "invalid channel identifier" }, - - InvalidPacketTimeoutHeight - { context: String } - | _ | { "invalid packet timeout height value" }, - - InvalidPacketTimeoutTimestamp - { timestamp: u64 } - | _ | { "invalid packet timeout timestamp value" }, - - Utf8 - [ DisplayOnly ] - | _ | { "utf8 decoding error" }, - - EmptyBaseDenom - |_| { "base denomination is empty" }, - - InvalidTracePortId - { pos: usize } - [ ValidationError ] - | e | { format_args!("invalid port id in trace at position: {0}", e.pos) }, - - InvalidTraceChannelId - { pos: usize } - [ ValidationError ] - | e | { format_args!("invalid channel id in trace at position: {0}", e.pos) }, - - InvalidTraceLength - { len: usize } - | e | { format_args!("trace length must be even but got: {0}", e.len) }, - - InvalidAmount - [ TraceError ] - | _ | { "invalid amount" }, - - InvalidToken - | _ | { "invalid token" }, - - Signer - [ SignerError ] - | _ | { "failed to parse signer" }, - - MissingDenomIbcPrefix - | _ | { "missing 'ibc/' prefix in denomination" }, - - MalformedHashDenom - | _ | { "hashed denom must be of the form 'ibc/{Hash}'" }, - - ParseHex - [ TraceError ] - | _ | { "invalid hex string" }, - - ChannelNotUnordered - { order: Order } - | e | { format_args!("expected '{0}' channel, got '{1}'", Order::Unordered, e.order) }, - - InvalidVersion - { version: Version } - | e | { format_args!("expected version '{0}', got '{1}'", Version::ics20(), e.version) }, - - InvalidCounterpartyVersion - { version: Version } - | e | { format_args!("expected counterparty version '{0}', got '{1}'", Version::ics20(), e.version) }, - - CantCloseChannel - | _ | { "channel cannot be closed" }, - - PacketDataDeserialization - | _ | { "failed to deserialize packet data" }, - - AckDeserialization - | _ | { "failed to deserialize acknowledgement" }, - - ReceiveDisabled - | _ | { "receive is not enabled" }, - - SendDisabled - | _ | { "send is not enabled" }, - - ParseAccountFailure - | _ | { "failed to parse as AccountId" }, - - InvalidPort - { port_id: PortId, exp_port_id: PortId } - | e | { format_args!("invalid port: '{0}', expected '{1}'", e.port_id, e.exp_port_id) }, - - TraceNotFound - | _ | { "no trace associated with specified hash" }, - - DecodeRawMsg - [ TraceError ] - | _ | { "error decoding raw msg" }, - - UnknownMsgType - { msg_type: String } - | e | { format_args!("unknown msg type: {0}", e.msg_type) }, - - InvalidCoin - { coin: String } - | e | { format_args!("invalid coin string: {}", e.coin) }, - - Utf8Decode - [ TraceError ] - | _ | { "error decoding raw bytes as UTF8 string" }, - } +#[cfg(feature = "std")] +impl std::error::Error for Error {} + +#[derive(Display, Debug)] +pub enum Error { + /// unrecognized ICS-20 transfer message type URL `{url}` + UnknowMessageTypeUrl { url: String }, + /// Ics04 channel Error + Ics04Channel(channel_error::Error), + /// destination channel not found in the counterparty of port_id `{port_id}` and channel_id `{channel_id}` + DestinationChannelNotFound { + port_id: PortId, + channel_id: ChannelId, + }, + /// invalid port identifier `{context}` + InvalidPortId { + context: String, + validation_error: ValidationError, + }, + /// invalid channel identifier `{context}` + InvalidChannelId { + context: String, + validation_error: ValidationError, + }, + /// invalid packet timeout height value `{context}` + InvalidPacketTimeoutHeight { context: String }, + /// invalid packet timeout timestamp value `{timestamp}` + InvalidPacketTimeoutTimestamp { timestamp: u64 }, + /// utf8 decoding error + Utf8(FromUtf8Error), + /// base denomination is empty + EmptyBaseDenom, + /// invalid prot id n trace at postion: `{pos}` + InvalidTracePortId { + pos: usize, + validation_error: ValidationError, + }, + /// invalid channel id in trace at position: `{pos}` + InvalidTraceChannelId { + pos: usize, + validation_error: ValidationError, + }, + /// trace length must be even but got: `{len}` + InvalidTraceLength { len: usize }, + /// invalid amount + InvalidAmount(FromDecStrErr), + /// invalid token + InvalidToken, + /// failed to parse signer + Signer(SignerError), + /// missing 'ibc/' prefix in denomination + MissingDenomIbcPrefix, + /// hashed denom must be of the form 'ibc/Hash' + MalformedHashDenom, + /// invalid hex string + ParseHex(EncodingError), + /// expected `{expect_order}` channel, got `{got_order}` + ChannelNotUnordered { + expect_order: Order, + got_order: Order, + }, + /// expected version `{expect_version}` , got `{got_version}` + InvalidVersion { + expect_version: Version, + got_version: Version, + }, + /// expected counterparty version `{expect_version}`, got `{got_version}` + InvalidCounterpartyVersion { + expect_version: Version, + got_version: Version, + }, + /// channel cannot be closed + CantCloseChannel, + /// failed to deserialize packet data + PacketDataDeserialization, + /// failed to deserialize acknowledgement + AckDeserialization, + /// receive is not enabled + ReceiveDisabled, + /// send is not enabled + SendDisabled, + /// failed to parse as AccountId + ParseAccountFailure, + /// invalid port: `{port_id}`, expected `{exp_port_id}` + InvalidPort { + port_id: PortId, + exp_port_id: PortId, + }, + /// no trace associated with specified hash + TraceNotFound, + /// error decoding raw msg + DecodeRawMsg(TendermintProtoError), + /// unknown msg type: `{msg_type}` + UnknownMsgType { msg_type: String }, + /// invalid coin string: `{coin}` + InvalidCoin { coin: String }, + /// error decoding raw bytes as UTF8 string + Utf8Decode(Utf8Error), } impl From for Error { diff --git a/crates/ibc/src/applications/transfer/msgs/transfer.rs b/crates/ibc/src/applications/transfer/msgs/transfer.rs index 1964d54df..64edb8293 100644 --- a/crates/ibc/src/applications/transfer/msgs/transfer.rs +++ b/crates/ibc/src/applications/transfer/msgs/transfer.rs @@ -60,25 +60,38 @@ impl TryFrom for MsgTransfer { type Error = Error; fn try_from(raw_msg: RawMsgTransfer) -> Result { - let timeout_timestamp = Timestamp::from_nanoseconds(raw_msg.timeout_timestamp) - .map_err(|_| Error::invalid_packet_timeout_timestamp(raw_msg.timeout_timestamp))?; - - let timeout_height: TimeoutHeight = raw_msg.timeout_height.try_into().map_err(|e| { - Error::invalid_packet_timeout_height(format!("invalid timeout height {}", e)) - })?; + let timeout_timestamp = + Timestamp::from_nanoseconds(raw_msg.timeout_timestamp).map_err(|_| { + Error::InvalidPacketTimeoutTimestamp { + timestamp: raw_msg.timeout_timestamp, + } + })?; + + let timeout_height: TimeoutHeight = + raw_msg + .timeout_height + .try_into() + .map_err(|e| Error::InvalidPacketTimeoutHeight { + context: format!("invalid timeout height {}", e), + })?; Ok(MsgTransfer { source_port: raw_msg .source_port .parse() - .map_err(|e| Error::invalid_port_id(raw_msg.source_port.clone(), e))?, - source_channel: raw_msg - .source_channel - .parse() - .map_err(|e| Error::invalid_channel_id(raw_msg.source_channel.clone(), e))?, - token: raw_msg.token.ok_or_else(Error::invalid_token)?, - sender: raw_msg.sender.parse().map_err(Error::signer)?, - receiver: raw_msg.receiver.parse().map_err(Error::signer)?, + .map_err(|e| Error::InvalidPortId { + context: raw_msg.source_port.clone(), + validation_error: e, + })?, + source_channel: raw_msg.source_channel.parse().map_err(|e| { + Error::InvalidChannelId { + context: raw_msg.source_channel.clone(), + validation_error: e, + } + })?, + token: raw_msg.token.ok_or(Error::InvalidToken)?, + sender: raw_msg.sender.parse().map_err(Error::Signer)?, + receiver: raw_msg.receiver.parse().map_err(Error::Signer)?, timeout_height, timeout_timestamp, }) @@ -106,8 +119,10 @@ 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(Error::decode_raw_msg), - _ => Err(Error::unknown_msg_type(raw.type_url)), + TYPE_URL => MsgTransfer::decode_vec(&raw.value).map_err(Error::DecodeRawMsg), + _ => Err(Error::UnknownMsgType { + msg_type: raw.type_url, + }), } } } diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index 587f7608b..5e9fcce3c 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -26,8 +26,8 @@ impl TryFrom for PacketData { let amount = Amount::from_str(&raw_pkt_data.amount)?; Ok(Self { token: PrefixedCoin { denom, amount }, - sender: raw_pkt_data.sender.parse().map_err(Error::signer)?, - receiver: raw_pkt_data.receiver.parse().map_err(Error::signer)?, + sender: raw_pkt_data.sender.parse().map_err(Error::Signer)?, + receiver: raw_pkt_data.receiver.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/applications/transfer/relay.rs b/crates/ibc/src/applications/transfer/relay.rs index f5a9196d5..d664b9005 100644 --- a/crates/ibc/src/applications/transfer/relay.rs +++ b/crates/ibc/src/applications/transfer/relay.rs @@ -20,7 +20,7 @@ fn refund_packet_token( .sender .clone() .try_into() - .map_err(|_| Ics20Error::parse_account_failure())?; + .map_err(|_| Ics20Error::ParseAccountFailure)?; if is_sender_chain_source( packet.source_port.clone(), diff --git a/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs b/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs index cbdb7b980..c23f2ba18 100644 --- a/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs +++ b/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs @@ -14,14 +14,14 @@ pub fn process_recv_packet( data: PacketData, ) -> Result, Ics20Error> { if !ctx.is_receive_enabled() { - return Err(Ics20Error::receive_disabled()); + return Err(Ics20Error::ReceiveDisabled); } let receiver_account = data .receiver .clone() .try_into() - .map_err(|_| Ics20Error::parse_account_failure())?; + .map_err(|_| Ics20Error::ParseAccountFailure)?; if is_receiver_chain_source( packet.source_port.clone(), diff --git a/crates/ibc/src/applications/transfer/relay/send_transfer.rs b/crates/ibc/src/applications/transfer/relay/send_transfer.rs index 5d17e03d3..eb0206137 100644 --- a/crates/ibc/src/applications/transfer/relay/send_transfer.rs +++ b/crates/ibc/src/applications/transfer/relay/send_transfer.rs @@ -23,31 +23,29 @@ where C: TryInto, { if !ctx.is_send_enabled() { - return Err(Error::send_disabled()); + return Err(Error::SendDisabled); } let source_channel_end = ctx .channel_end(&msg.source_port, &msg.source_channel) - .map_err(Error::ics04_channel)?; + .map_err(Error::Ics04Channel)?; let destination_port = source_channel_end.counterparty().port_id().clone(); let destination_channel = source_channel_end .counterparty() .channel_id() - .ok_or_else(|| { - Error::destination_channel_not_found( - msg.source_port.clone(), - msg.source_channel.clone(), - ) + .ok_or_else(|| Error::DestinationChannelNotFound { + port_id: msg.source_port.clone(), + channel_id: msg.source_channel.clone(), })? .clone(); // get the next sequence let sequence = ctx .get_next_sequence_send(&msg.source_port, &msg.source_channel) - .map_err(Error::ics04_channel)?; + .map_err(Error::Ics04Channel)?; - let token = msg.token.try_into().map_err(|_| Error::invalid_token())?; + let token = msg.token.try_into().map_err(|_| Error::InvalidToken)?; let denom = token.denom.clone(); let coin = Coin { denom: denom.clone(), @@ -58,7 +56,7 @@ where .sender .clone() .try_into() - .map_err(|_| Error::parse_account_failure())?; + .map_err(|_| Error::ParseAccountFailure)?; if is_sender_chain_source(msg.source_port.clone(), msg.source_channel.clone(), &denom) { let escrow_address = @@ -92,10 +90,10 @@ where result, log, events, - } = send_packet(ctx, packet).map_err(Error::ics04_channel)?; + } = send_packet(ctx, packet).map_err(Error::Ics04Channel)?; ctx.store_send_packet_result(result) - .map_err(Error::ics04_channel)?; + .map_err(Error::Ics04Channel)?; output.merge_output( HandlerOutput::builder() diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index c0d3c69c6..dd2761db6 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -1,7 +1,6 @@ use crate::prelude::*; use flex_error::{define_error, TraceError}; -use crate::applications::transfer; use crate::core::ics02_client; use crate::core::ics03_connection; use crate::core::ics04_channel; @@ -21,10 +20,6 @@ define_error! { [ ics04_channel::error::Error ] | _ | { "ICS04 channel error" }, - Ics20FungibleTokenTransfer - [ transfer::error::Error ] - | _ | { "ICS20 fungible token transfer error" }, - UnknownMessageTypeUrl { url: String } | e | { format_args!("unknown type URL {0}", e.url) }, From 99d8205c6c2bd3e922b3f52e8d4e8ff28f916c44 Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 23 Nov 2022 00:56:09 +0800 Subject: [PATCH 02/43] Redefine Ics02Error by displaydoc --- crates/ibc/src/applications/transfer/error.rs | 22 +- .../clients/ics07_tendermint/client_state.rs | 94 ++-- .../ics07_tendermint/consensus_state.rs | 4 +- .../ibc/src/clients/ics07_tendermint/error.rs | 4 +- .../src/clients/ics07_tendermint/header.rs | 4 +- crates/ibc/src/core/ics02_client/error.rs | 401 ++++++------------ .../ics02_client/handler/create_client.rs | 21 +- .../ics02_client/handler/update_client.rs | 70 +-- .../ics02_client/handler/upgrade_client.rs | 35 +- crates/ibc/src/core/ics02_client/height.rs | 4 +- .../core/ics02_client/msgs/create_client.rs | 10 +- .../core/ics02_client/msgs/misbehaviour.rs | 8 +- .../core/ics02_client/msgs/update_client.rs | 6 +- .../core/ics02_client/msgs/upgrade_client.rs | 18 +- .../src/core/ics02_client/trust_threshold.rs | 11 +- .../src/core/ics03_connection/connection.rs | 2 +- crates/ibc/src/core/ics03_connection/error.rs | 12 +- crates/ibc/src/core/ics04_channel/error.rs | 6 +- .../ics04_channel/handler/chan_open_try.rs | 15 +- .../core/ics04_channel/handler/recv_packet.rs | 8 +- .../handler/write_acknowledgement.rs | 5 +- crates/ibc/src/core/ics26_routing/error.rs | 4 +- crates/ibc/src/events.rs | 2 +- crates/ibc/src/mock/client_state.rs | 22 +- crates/ibc/src/mock/consensus_state.rs | 8 +- crates/ibc/src/mock/context.rs | 62 ++- crates/ibc/src/mock/header.rs | 10 +- crates/ibc/src/mock/misbehaviour.rs | 4 +- crates/ibc/src/test_utils.rs | 28 +- 29 files changed, 423 insertions(+), 477 deletions(-) diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index 25e9189ec..2e1373976 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -22,19 +22,19 @@ impl std::error::Error for Error {} pub enum Error { /// unrecognized ICS-20 transfer message type URL `{url}` UnknowMessageTypeUrl { url: String }, - /// Ics04 channel Error + /// Ics04 channel error(`{0}`) Ics04Channel(channel_error::Error), /// destination channel not found in the counterparty of port_id `{port_id}` and channel_id `{channel_id}` DestinationChannelNotFound { port_id: PortId, channel_id: ChannelId, }, - /// invalid port identifier `{context}` + /// invalid port identifier `{context}` error(`{validation_error}`) InvalidPortId { context: String, validation_error: ValidationError, }, - /// invalid channel identifier `{context}` + /// invalid channel identifier `{context}` error(`{validation_error}`) InvalidChannelId { context: String, validation_error: ValidationError, @@ -43,33 +43,33 @@ pub enum Error { InvalidPacketTimeoutHeight { context: String }, /// invalid packet timeout timestamp value `{timestamp}` InvalidPacketTimeoutTimestamp { timestamp: u64 }, - /// utf8 decoding error + /// utf8 decoding error(`{0}`) Utf8(FromUtf8Error), /// base denomination is empty EmptyBaseDenom, - /// invalid prot id n trace at postion: `{pos}` + /// invalid prot id n trace at postion: `{pos}`, error(`{validation_error}`) InvalidTracePortId { pos: usize, validation_error: ValidationError, }, - /// invalid channel id in trace at position: `{pos}` + /// invalid channel id in trace at position: `{pos}`, error(`{validation_error}`) InvalidTraceChannelId { pos: usize, validation_error: ValidationError, }, /// trace length must be even but got: `{len}` InvalidTraceLength { len: usize }, - /// invalid amount + /// invalid amount error(`{0}`) InvalidAmount(FromDecStrErr), /// invalid token InvalidToken, - /// failed to parse signer + /// failed to parse signer error(`{0}`) Signer(SignerError), /// missing 'ibc/' prefix in denomination MissingDenomIbcPrefix, /// hashed denom must be of the form 'ibc/Hash' MalformedHashDenom, - /// invalid hex string + /// invalid hex string error(`{0}`) ParseHex(EncodingError), /// expected `{expect_order}` channel, got `{got_order}` ChannelNotUnordered { @@ -105,13 +105,13 @@ pub enum Error { }, /// no trace associated with specified hash TraceNotFound, - /// error decoding raw msg + /// error decoding raw msg error(`{0}`) DecodeRawMsg(TendermintProtoError), /// unknown msg type: `{msg_type}` UnknownMsgType { msg_type: String }, /// invalid coin string: `{coin}` InvalidCoin { coin: String }, - /// error decoding raw bytes as UTF8 string + /// error decoding raw bytes as UTF8 string error(`{0}`) Utf8Decode(Utf8Error), } diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index f4584ac58..1e919fe73 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -38,7 +38,7 @@ use crate::core::ics02_client::client_state::{ }; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::{Error as Ics02Error, ErrorDetail as Ics02ErrorDetail}; +use crate::core::ics02_client::error::Error as Ics02Error; use crate::core::ics02_client::trust_threshold::TrustThreshold; use crate::core::ics04_channel::context::ChannelReader; use crate::core::ics23_commitment::specs::ProofSpecs; @@ -325,8 +325,11 @@ impl Ics2ClientState for ClientState { ) -> Result>, Ics02Error> { match ctx.consensus_state(client_id, height) { Ok(cs) => Ok(Some(cs)), - Err(e) => match e.detail() { - Ics02ErrorDetail::ConsensusStateNotFound(_) => Ok(None), + Err(e) => match e { + Ics02Error::ConsensusStateNotFound { + client_id: _, + height: _, + } => Ok(None), _ => Err(e), }, } @@ -336,13 +339,13 @@ impl Ics2ClientState for ClientState { let header = TmHeader::try_from(header)?; if header.height().revision_number() != client_state.chain_id().version() { - return Err(Ics02Error::client_specific( - Error::mismatched_revisions( + return Err(Ics02Error::ClientSpecific { + description: Error::mismatched_revisions( client_state.chain_id().version(), header.height().revision_number(), ) .to_string(), - )); + }); } // Check if a consensus state is already installed; if so it should @@ -378,11 +381,11 @@ impl Ics2ClientState for ClientState { .trusted_height .revision_height() .try_into() - .map_err(|_| { - Ics02Error::client_specific( - Error::invalid_header_height(header.trusted_height.revision_height()) - .to_string(), + .map_err(|_| Ics02Error::ClientSpecific { + description: Error::invalid_header_height( + header.trusted_height.revision_height(), ) + .to_string(), })?, next_validators: &header.trusted_validator_set, next_validators_hash: trusted_consensus_state.next_validators_hash, @@ -443,13 +446,13 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur after next // consensus state's height if header.signed_header.header().time > next_cs.timestamp { - return Err(Ics02Error::client_specific( - Error::header_timestamp_too_high( + return Err(Ics02Error::ClientSpecific { + description: Error::header_timestamp_too_high( header.signed_header.header().time.to_string(), next_cs.timestamp.to_string(), ) .to_string(), - )); + }); } } } @@ -466,13 +469,13 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur before the // previous consensus state's height if header.signed_header.header().time < prev_cs.timestamp { - return Err(Ics02Error::client_specific( - Error::header_timestamp_too_low( + return Err(Ics02Error::ClientSpecific { + description: Error::header_timestamp_too_low( header.signed_header.header().time.to_string(), prev_cs.timestamp.to_string(), ) .to_string(), - )); + }); } } } @@ -496,8 +499,11 @@ impl Ics2ClientState for ClientState { ) -> Result>, Ics02Error> { match ctx.consensus_state(client_id, height) { Ok(cs) => Ok(Some(cs)), - Err(e) => match e.detail() { - Ics02ErrorDetail::ConsensusStateNotFound(_) => Ok(None), + Err(e) => match e { + Ics02Error::ConsensusStateNotFound { + client_id: _, + height: _, + } => Ok(None), _ => Err(e), }, } @@ -507,13 +513,13 @@ impl Ics2ClientState for ClientState { let header = TmHeader::try_from(header)?; if header.height().revision_number() != client_state.chain_id().version() { - return Err(Ics02Error::client_specific( - Error::mismatched_revisions( + return Err(Ics02Error::ClientSpecific { + description: Error::mismatched_revisions( client_state.chain_id().version(), header.height().revision_number(), ) .to_string(), - )); + }); } // Check if a consensus state is already installed; if so it should @@ -549,11 +555,11 @@ impl Ics2ClientState for ClientState { .trusted_height .revision_height() .try_into() - .map_err(|_| { - Ics02Error::client_specific( - Error::invalid_header_height(header.trusted_height.revision_height()) - .to_string(), + .map_err(|_| Ics02Error::ClientSpecific { + description: Error::invalid_header_height( + header.trusted_height.revision_height(), ) + .to_string(), })?, next_validators: &header.trusted_validator_set, next_validators_hash: trusted_consensus_state.next_validators_hash, @@ -614,13 +620,13 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur after next // consensus state's height if header.signed_header.header().time > next_cs.timestamp { - return Err(Ics02Error::client_specific( - Error::header_timestamp_too_high( + return Err(Ics02Error::ClientSpecific { + description: Error::header_timestamp_too_high( header.signed_header.header().time.to_string(), next_cs.timestamp.to_string(), ) .to_string(), - )); + }); } } } @@ -637,13 +643,13 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur before the // previous consensus state's height if header.signed_header.header().time < prev_cs.timestamp { - return Err(Ics02Error::client_specific( - Error::header_timestamp_too_low( + return Err(Ics02Error::ClientSpecific { + description: Error::header_timestamp_too_low( header.signed_header.header().time.to_string(), prev_cs.timestamp.to_string(), ) .to_string(), - )); + }); } } } @@ -683,7 +689,7 @@ impl Ics2ClientState for ClientState { }; let value = expected_consensus_state .encode_vec() - .map_err(Ics02Error::invalid_any_consensus_state)?; + .map_err(Ics02Error::InvalidAnyConsensusState)?; verify_membership(client_state, prefix, proof, root, path, value) } @@ -703,7 +709,7 @@ impl Ics2ClientState for ClientState { let path = ConnectionsPath(connection_id.clone()); let value = expected_connection_end .encode_vec() - .map_err(Ics02Error::invalid_connection_end)?; + .map_err(Ics02Error::InvalidConnectionEnd)?; verify_membership(client_state, prefix, proof, root, path, value) } @@ -723,7 +729,7 @@ impl Ics2ClientState for ClientState { let path = ChannelEndsPath(port_id.clone(), channel_id.clone()); let value = expected_channel_end .encode_vec() - .map_err(Ics02Error::invalid_channel_end)?; + .map_err(Ics02Error::InvalidChannelEnd)?; verify_membership(client_state, prefix, proof, root, path, value) } @@ -879,7 +885,7 @@ fn verify_membership( ) -> Result<(), Ics02Error> { let merkle_path = apply_prefix(prefix, vec![path.into().to_string()]); let merkle_proof: MerkleProof = RawMerkleProof::try_from(proof.clone()) - .map_err(Ics02Error::invalid_commitment_proof)? + .map_err(Ics02Error::InvalidCommitmentProof)? .into(); merkle_proof @@ -890,7 +896,7 @@ fn verify_membership( value, 0, ) - .map_err(Ics02Error::ics23_verification) + .map_err(Ics02Error::Ics23Verification) } fn verify_non_membership( @@ -902,12 +908,12 @@ fn verify_non_membership( ) -> Result<(), Ics02Error> { let merkle_path = apply_prefix(prefix, vec![path.into().to_string()]); let merkle_proof: MerkleProof = RawMerkleProof::try_from(proof.clone()) - .map_err(Ics02Error::invalid_commitment_proof)? + .map_err(Ics02Error::InvalidCommitmentProof)? .into(); merkle_proof .verify_non_membership(&client_state.proof_specs, root.clone().into(), merkle_path) - .map_err(Ics02Error::ics23_verification) + .map_err(Ics02Error::Ics23Verification) } fn verify_delay_passed( @@ -943,13 +949,17 @@ fn verify_delay_passed( fn downcast_tm_client_state(cs: &dyn Ics2ClientState) -> Result<&ClientState, Ics02Error> { cs.as_any() .downcast_ref::() - .ok_or_else(|| Ics02Error::client_args_type_mismatch(tm_client_type())) + .ok_or_else(|| Ics02Error::ClientArgsTypeMismatch { + client_type: tm_client_type(), + }) } fn downcast_tm_consensus_state(cs: &dyn ConsensusState) -> Result { cs.as_any() .downcast_ref::() - .ok_or_else(|| Ics02Error::client_args_type_mismatch(tm_client_type())) + .ok_or_else(|| Ics02Error::ClientArgsTypeMismatch { + client_type: tm_client_type(), + }) .map(Clone::clone) } @@ -1070,7 +1080,9 @@ impl TryFrom for ClientState { TENDERMINT_CLIENT_STATE_TYPE_URL => { decode_client_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Ics02Error::unknown_client_state_type(raw.type_url)), + _ => Err(Ics02Error::UnknownClientStateType { + client_state_type: raw.type_url, + }), } } } diff --git a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs index f6e4ea001..1d852d3ab 100644 --- a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs @@ -118,7 +118,9 @@ impl TryFrom for ConsensusState { TENDERMINT_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Ics02Error::unknown_consensus_state_type(raw.type_url)), + _ => Err(Ics02Error::UnknownConsensusStateType { + consensus_state_type: raw.type_url, + }), } } } diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index 38f497865..7d67fc10a 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -311,6 +311,8 @@ define_error! { impl From for Ics02Error { fn from(e: Error) -> Self { - Self::client_specific(e.to_string()) + Self::ClientSpecific { + description: e.to_string(), + } } } diff --git a/crates/ibc/src/clients/ics07_tendermint/header.rs b/crates/ibc/src/clients/ics07_tendermint/header.rs index a1d5f1c10..fc45ae78d 100644 --- a/crates/ibc/src/clients/ics07_tendermint/header.rs +++ b/crates/ibc/src/clients/ics07_tendermint/header.rs @@ -146,7 +146,9 @@ impl TryFrom for Header { match raw.type_url.as_str() { TENDERMINT_HEADER_TYPE_URL => decode_header(raw.value.deref()).map_err(Into::into), - _ => Err(Ics02Error::unknown_header_type(raw.type_url)), + _ => Err(Ics02Error::UnknownHeaderType { + header_type: raw.type_url, + }), } } } diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index b4e1dd105..2d90b88da 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -1,6 +1,6 @@ use crate::prelude::*; -use flex_error::{define_error, TraceError}; +use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; use crate::core::ics02_client::client_type::ClientType; @@ -12,269 +12,138 @@ use crate::signer::SignerError; use crate::timestamp::Timestamp; use crate::Height; -define_error! { - #[derive(Debug, PartialEq, Eq)] - Error { - UnknownClientType - { client_type: String } - | e | { format_args!("unknown client type: {0}", e.client_type) }, - - ClientIdentifierConstructor - { client_type: ClientType, counter: u64 } - [ ValidationError ] - | e | { - format_args!("Client identifier constructor failed for type {0} with counter {1}", - e.client_type, e.counter) - }, - - ClientAlreadyExists - { client_id: ClientId } - | e | { format_args!("client already exists: {0}", e.client_id) }, - - ClientNotFound - { client_id: ClientId } - | e | { format_args!("client not found: {0}", e.client_id) }, - - ClientFrozen - { client_id: ClientId } - | e | { format_args!("client is frozen: {0}", e.client_id) }, - - ConsensusStateNotFound - { client_id: ClientId, height: Height } - | e | { - format_args!("consensus state not found at: {0} at height {1}", - e.client_id, e.height) - }, - - ImplementationSpecific - | _ | { "implementation specific error" }, - - HeaderVerificationFailure - { reason: String } - | e | { format_args!("header verification failed with reason: {}", e.reason) }, - - InvalidTrustThreshold - { numerator: u64, denominator: u64 } - | e | { format_args!("failed to build trust threshold from fraction: {}/{}", e.numerator, e.denominator) }, - - FailedTrustThresholdConversion - { numerator: u64, denominator: u64 } - | e | { format_args!("failed to build Tendermint domain type trust threshold from fraction: {}/{}", e.numerator, e.denominator) }, - - UnknownClientStateType - { client_state_type: String } - | e | { format_args!("unknown client state type: {0}", e.client_state_type) }, - - EmptyClientStateResponse - | _ | { "the client state was not found" }, - - EmptyPrefix - | _ | { "empty prefix" }, - - UnknownConsensusStateType - { consensus_state_type: String } - | e | { - format_args!("unknown client consensus state type: {0}", - e.consensus_state_type) - }, - - EmptyConsensusStateResponse - | _ | { "the client consensus state was not found" }, - - UnknownHeaderType - { header_type: String } - | e | { - format_args!("unknown header type: {0}", - e.header_type) - }, - - UnknownMisbehaviourType - { misbehavior_type: String } - | e | { - format_args!("unknown misbehaviour type: {0}", - e.misbehavior_type) - }, - - InvalidRawClientId - { client_id: String } - [ ValidationError ] - | e | { - format_args!("invalid raw client identifier {0}", - e.client_id) - }, - - DecodeRawClientState - [ TraceError ] - | _ | { "error decoding raw client state" }, - - MissingRawClientState - | _ | { "missing raw client state" }, - - InvalidRawConsensusState - [ TraceError ] - | _ | { "invalid raw client consensus state" }, - - MissingRawConsensusState - | _ | { "missing raw client consensus state" }, - - InvalidMsgUpdateClientId - [ ValidationError ] - | _ | { "invalid client id in the update client message" }, - - Decode - [ TraceError ] - | _ | { "decode error" }, - - MissingHeight - | _ | { "invalid raw client consensus state: the height field is missing" }, - - InvalidClientIdentifier - [ ValidationError ] - | _ | { "invalid client identifier" }, - - InvalidRawHeader - [ TraceError ] - | _ | { "invalid raw header" }, - - MissingRawHeader - | _ | { "missing raw header" }, - - DecodeRawMisbehaviour - [ TraceError ] - | _ | { "invalid raw misbehaviour" }, - - InvalidRawMisbehaviour - [ ValidationError ] - | _ | { "invalid raw misbehaviour" }, - - MissingRawMisbehaviour - | _ | { "missing raw misbehaviour" }, - - InvalidStringAsHeight - { value: String } - [ HeightError ] - | e | { format_args!("String {0} cannnot be converted to height", e.value) }, - - InvalidHeight - | _ | { "revision height cannot be zero" }, - - InvalidHeightResult - | _ | { "height cannot end up zero or negative" }, - - InvalidAddress - | _ | { "invalid address" }, - - InvalidUpgradeClientProof - [ Ics23Error ] - | _ | { "invalid proof for the upgraded client state" }, - - InvalidUpgradeConsensusStateProof - [ Ics23Error ] - | _ | { "invalid proof for the upgraded consensus state" }, - - InvalidCommitmentProof - [ Ics23Error ] - | _ | { "invalid commitment proof bytes" }, - - InvalidPacketTimestamp - [ crate::timestamp::ParseTimestampError ] - | _ | { "invalid packet timeout timestamp value" }, - - ClientArgsTypeMismatch - { client_type: ClientType } - | e | { - format_args!("mismatch between client and arguments types, expected: {0:?}", - e.client_type) - }, - - InsufficientVotingPower - { reason: String } - | e | { - format_args!("Insufficient overlap {}", e.reason) - }, - - RawClientAndConsensusStateTypesMismatch - { - state_type: ClientType, - consensus_type: ClientType, - } - | e | { - format_args!("mismatch in raw client consensus state {} with expected state {}", - e.state_type, e.consensus_type) - }, - - LowHeaderHeight - { - header_height: Height, - latest_height: Height - } - | e | { - format!("received header height ({}) is lower than (or equal to) client latest height ({})", - e.header_height, e.latest_height) - }, - - LowUpgradeHeight - { - upgraded_height: Height, - client_height: Height, - } - | e | { - format_args!("upgraded client height {} must be at greater than current client height {}", - e.upgraded_height, e.client_height) - }, - - InvalidConsensusStateTimestamp - { - time1: Timestamp, - time2: Timestamp, - } - | e | { - format_args!("timestamp is invalid or missing, timestamp={0}, now={1}", e.time1, e.time2) - }, - - HeaderNotWithinTrustPeriod - { - latest_time:Timestamp, - update_time: Timestamp, - } - | e | { - format_args!("header not withing trusting period: expires_at={0} now={1}", e.latest_time, e.update_time) - }, - - MissingLocalConsensusState - { height: Height } - | e | { format_args!("the local consensus state could not be retrieved for height {}", e.height) }, - - InvalidConnectionEnd - [ TraceError] - | _ | { "invalid connection end" }, - - InvalidChannelEnd - [ TraceError] - | _ | { "invalid channel end" }, - - InvalidAnyClientState - [ TraceError] - | _ | { "invalid any client state" }, - - InvalidAnyConsensusState - [ TraceError ] - | _ | { "invalid any client consensus state" }, - - Signer - [ SignerError ] - | _ | { "failed to parse signer" }, - - Ics23Verification - [ Ics23Error ] - | _ | { "ics23 verification failure" }, - - ClientSpecific - { description: String } - | e | { format_args!("client specific error: {0}", e.description) }, - - Other - { description: String } - | e| { format_args!("other error: {0}", e.description) }, - } +#[derive(Debug, Display)] +pub enum Error { + /// unknown client type: `{client_type}` + UnknownClientType { client_type: String }, + /// Client identifier constructor failed for type `{client_type}` with counter `{counter}`, error(`{validation_error}`) + ClientIdentifierConstructor { + client_type: ClientType, + counter: u64, + validation_error: ValidationError, + }, + /// client already exists: `{client_id}` + ClientAlreadyExists { client_id: ClientId }, + /// client not found: `{client_id}` + ClientNotFound { client_id: ClientId }, + /// client is frozen: `{client_id}` + ClientFrozen { client_id: ClientId }, + /// consensus state not found at: `{client_id}` at height `{height}` + ConsensusStateNotFound { client_id: ClientId, height: Height }, + /// implementation specific error + ImplementationSpecific, + /// header verification failed with reason: `{reaseon}` + HeaderVerificationFailure { reaseon: String }, + /// failed to build trust threshold from fraction: `{numerator}`/`{denominator}` + InvalidTrustThreshold { numerator: u64, denominator: u64 }, + /// failed to build Tendermint domain type trust threshold from fraction: `{numerator}`/`{denominator}` + FailedTrustThresholdConversion { numerator: u64, denominator: u64 }, + /// unknown client state type: `{client_state_type}` + UnknownClientStateType { client_state_type: String }, + /// the client state was not found + EmptyClientStateResponse, + /// empty prefix + EmptyPrefix, + /// unknown client consensus state type: `{consensus_state_type}` + UnknownConsensusStateType { consensus_state_type: String }, + /// the client consensus state was not found + EmptyConsensusStateResponse, + /// unknown header type: `{header_type}` + UnknownHeaderType { header_type: String }, + /// unknown misbehaviour type: `{misbehavior_type}` + UnknownMisbehaviourType { misbehavior_type: String }, + /// invalid raw client identifier `{client_id}`, error(`{validation_error}`) + InvalidRawClientId { + client_id: String, + validation_error: ValidationError, + }, + /// error decoding raw client state, error(`{0}`) + DecodeRawClientState(TendermintProtoError), + /// missing raw client state + MissingRawClientState, + /// invalid raw client consensus state, error(`{0}`) + InvalidRawConsensusState(TendermintProtoError), + /// missing raw client consensus state + MissingRawConsensusState, + /// invalid client id in the update client message, error(`{0}`) + InvalidMsgUpdateClientId(ValidationError), + /// decode error(`{0}`) + Decode(prost::DecodeError), + /// invalid raw client consensus state: the height field is missing + MissingHeight, + /// invalid client identifier, error(`{0}`) + InvalidClientIdentifier(ValidationError), + /// invalid raw header, error(`{0}`) + InvalidRawHeader(TendermintProtoError), + /// missing raw header + MissingRawHeader, + /// invalid raw misbehaviour, error(`{0}`) + DecodeRawMisbehaviour(TendermintProtoError), + /// invalid raw misbehaviour, error(`{0}`) + InvalidRawMisbehaviour(ValidationError), + /// missing raw misbehaviour + MissingRawMisbehaviour, + /// String `{value}` cannnot be converted to height, error(`{height_error}`) + InvalidStringAsHeight { + value: String, + height_error: HeightError, + }, + /// revision height cannot be zero + InvalidHeight, + /// height cannot end up zero or negative + InvalidHeightResult, + /// invalid address + InvalidAddress, + /// invalid proof for the upgraded client state, error(`{0}`) + InvalidUpgradeClientProof(Ics23Error), + /// invalid proof for the upgraded consensus state, error(`{0}`) + InvalidUpgradeConsensusStateProof(Ics23Error), + /// invalid commitment proof bytes, error(`{0}`) + InvalidCommitmentProof(Ics23Error), + /// invalid packet timeout timestamp value, error(`{0}`) + InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), + /// mismatch between client and arguments types, expected: `{client_type}` + ClientArgsTypeMismatch { client_type: ClientType }, + /// Insufficient overlap `{reason}` + InsufficientVotingPower { reason: String }, + /// mismatch in raw client consensus state `{state_type}` with expected state `{consensus_type}` + RawClientAndConsensusStateTypesMismatch { + state_type: ClientType, + consensus_type: ClientType, + }, + /// received header height (`{header_height}`) is lower than (or equal to) client latest height (`{latest_height}`) + LowHeaderHeight { + header_height: Height, + latest_height: Height, + }, + /// upgraded client height `{upgraded_height}` must be at greater than current client height `{client_height}` + LowUpgradeHeight { + upgraded_height: Height, + client_height: Height, + }, + /// timestamp is invalid or missing, timestamp=`{time1}`, now=`{time2}` + InvalidConsensusStateTimestamp { time1: Timestamp, time2: Timestamp }, + /// header not withing trusting period: expires_at=`{latest_time}` now=`{update_time}` + HeaderNotWithinTrustPeriod { + latest_time: Timestamp, + update_time: Timestamp, + }, + /// the local consensus state could not be retrieved for height `{height}` + MissingLocalConsensusState { height: Height }, + /// invalid connection end, error(`{0}`) + InvalidConnectionEnd(TendermintProtoError), + /// invalid channel end, error(`{0}`) + InvalidChannelEnd(TendermintProtoError), + /// invalid any client state, error(`{0}`) + InvalidAnyClientState(TendermintProtoError), + /// invalid any client consensus state, error(`{0}`) + InvalidAnyConsensusState(TendermintProtoError), + /// failed to parse signer, error(`{0}`) + Signer(SignerError), + /// ics23 verification failure, error(`{0}`) + Ics23Verification(Ics23Error), + /// client specific error: `{description}` + ClientSpecific { description: String }, + /// other error: `{description}` + Other { description: String }, } diff --git a/crates/ibc/src/core/ics02_client/handler/create_client.rs b/crates/ibc/src/core/ics02_client/handler/create_client.rs index 49b2e50cb..3b3d6d0da 100644 --- a/crates/ibc/src/core/ics02_client/handler/create_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/create_client.rs @@ -51,9 +51,12 @@ where let client_type = client_state.client_type(); - let _client_id = ClientId::new(client_type, id_counter).map_err(|e| { - Error::client_identifier_constructor(client_state.client_type(), id_counter, e) - })?; + let _client_id = + ClientId::new(client_type, id_counter).map_err(|e| Error::ClientIdentifierConstructor { + client_type: client_state.client_type(), + counter: id_counter, + validation_error: e, + })?; Ok(()) } @@ -76,7 +79,11 @@ where let client_type = client_state.client_type(); let client_id = ClientId::new(client_type.clone(), id_counter).map_err(|e| { - Error::client_identifier_constructor(client_state.client_type(), id_counter, e) + Error::ClientIdentifierConstructor { + client_type: client_state.client_type(), + counter: id_counter, + validation_error: e, + } })?; let consensus_state = client_state.initialise(consensus_state)?; @@ -129,7 +136,11 @@ pub fn process(ctx: &dyn ClientReader, msg: MsgCreateClient) -> HandlerResult( let client_state = ctx.client_state(&client_id)?; if client_state.is_frozen() { - return Err(Error::client_frozen(client_id)); + return Err(Error::ClientFrozen { client_id }); } // Read consensus state from the host chain store. let latest_consensus_state = ClientReader::consensus_state(ctx, &client_id, client_state.latest_height()).map_err( - |_| Error::consensus_state_not_found(client_id.clone(), client_state.latest_height()), + |_| Error::ConsensusStateNotFound { + client_id: client_id.clone(), + height: client_state.latest_height(), + }, )?; debug!("latest consensus state: {:?}", latest_consensus_state); @@ -163,15 +172,16 @@ pub fn process( let now = ClientReader::host_timestamp(ctx); let duration = now .duration_since(&latest_consensus_state.timestamp()) - .ok_or_else(|| { - Error::invalid_consensus_state_timestamp(latest_consensus_state.timestamp(), now) + .ok_or_else(|| Error::InvalidConsensusStateTimestamp { + time1: latest_consensus_state.timestamp(), + time2: now, })?; if client_state.expired(duration) { - return Err(Error::header_not_within_trust_period( - latest_consensus_state.timestamp(), - now, - )); + return Err(Error::HeaderNotWithinTrustPeriod { + latest_time: latest_consensus_state.timestamp(), + update_time: now, + }); } // Use client_state to validate the new header against the latest consensus_state. @@ -182,7 +192,9 @@ pub fn process( consensus_state, } = client_state .old_check_header_and_update_state(ctx, client_id.clone(), header.clone()) - .map_err(|e| Error::header_verification_failure(e.to_string()))?; + .map_err(|e| Error::HeaderVerificationFailure { + reaseon: e.to_string(), + })?; let client_type = client_state.client_type(); let consensus_height = client_state.latest_height(); @@ -216,7 +228,7 @@ mod tests { use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::downcast_consensus_state; - use crate::core::ics02_client::error::{Error, ErrorDetail}; + use crate::core::ics02_client::error::Error; use crate::core::ics02_client::handler::dispatch; use crate::core::ics02_client::handler::ClientResult::Update; use crate::core::ics02_client::msgs::update_client::MsgUpdateClient; @@ -272,7 +284,7 @@ mod tests { } } Err(err) => { - panic!("unexpected error: {}", err); + panic!("unexpected error: {:?}", err); } } } @@ -293,8 +305,8 @@ mod tests { let output = dispatch(&ctx, ClientMsg::UpdateClient(msg.clone())); match output { - Err(Error(ErrorDetail::ClientNotFound(e), _)) => { - assert_eq!(e.client_id, msg.client_id); + Err(Error::ClientNotFound { client_id }) => { + assert_eq!(client_id, msg.client_id); } _ => { panic!("expected ClientNotFound error, instead got {:?}", output) @@ -337,7 +349,7 @@ mod tests { assert!(log.is_empty()); } Err(err) => { - panic!("unexpected error: {}", err); + panic!("unexpected error: {:?}", err); } } } @@ -401,7 +413,7 @@ mod tests { } } Err(err) => { - panic!("unexpected error: {}", err); + panic!("unexpected error: {:?}", err); } } } @@ -465,7 +477,7 @@ mod tests { } } Err(err) => { - panic!("unexpected error: {}", err); + panic!("unexpected error: {:?}", err); } } } @@ -591,8 +603,8 @@ mod tests { Ok(_) => { panic!("update handler result has incorrect type"); } - Err(err) => match err.detail() { - ErrorDetail::HeaderVerificationFailure(_) => {} + Err(err) => match err { + Error::HeaderVerificationFailure { reaseon: _ } => {} _ => panic!("unexpected error: {:?}", err), }, } diff --git a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs index 53f510045..a38a4cacd 100644 --- a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs @@ -33,16 +33,16 @@ where let old_client_state = ctx.client_state(&client_id)?; if old_client_state.is_frozen() { - return Err(Error::client_frozen(client_id)); + return Err(Error::ClientFrozen { client_id }); } let upgrade_client_state = ctx.decode_client_state(msg.client_state)?; if old_client_state.latest_height() >= upgrade_client_state.latest_height() { - return Err(Error::low_upgrade_height( - old_client_state.latest_height(), - upgrade_client_state.latest_height(), - )); + return Err(Error::LowUpgradeHeight { + upgraded_height: old_client_state.latest_height(), + client_height: upgrade_client_state.latest_height(), + }); } Ok(()) @@ -94,16 +94,16 @@ pub fn process( let old_client_state = ctx.client_state(&client_id)?; if old_client_state.is_frozen() { - return Err(Error::client_frozen(client_id)); + return Err(Error::ClientFrozen { client_id }); } let upgrade_client_state = ctx.decode_client_state(msg.client_state)?; if old_client_state.latest_height() >= upgrade_client_state.latest_height() { - return Err(Error::low_upgrade_height( - old_client_state.latest_height(), - upgrade_client_state.latest_height(), - )); + return Err(Error::LowUpgradeHeight { + upgraded_height: old_client_state.latest_height(), + client_height: upgrade_client_state.latest_height(), + }); } let UpdatedState { @@ -143,7 +143,7 @@ mod tests { use core::str::FromStr; - use crate::core::ics02_client::error::{Error, ErrorDetail}; + use crate::core::ics02_client::error::Error; use crate::core::ics02_client::handler::dispatch; use crate::core::ics02_client::handler::ClientResult::Upgrade; use crate::core::ics02_client::msgs::upgrade_client::MsgUpgradeClient; @@ -219,8 +219,8 @@ mod tests { let output = dispatch(&ctx, ClientMsg::UpgradeClient(msg.clone())); match output { - Err(Error(ErrorDetail::ClientNotFound(e), _)) => { - assert_eq!(e.client_id, msg.client_id); + Err(Error::ClientNotFound { client_id }) => { + assert_eq!(client_id, msg.client_id); } _ => { panic!("expected ClientNotFound error, instead got {:?}", output); @@ -248,10 +248,13 @@ mod tests { let output = dispatch(&ctx, ClientMsg::UpgradeClient(msg.clone())); match output { - Err(Error(ErrorDetail::LowUpgradeHeight(e), _)) => { - assert_eq!(e.upgraded_height, Height::new(0, 42).unwrap()); + Err(Error::LowUpgradeHeight { + upgraded_height, + client_height, + }) => { + assert_eq!(upgraded_height, Height::new(0, 42).unwrap()); assert_eq!( - e.client_height, + client_height, MockClientState::try_from(msg.client_state) .unwrap() .latest_height() diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index 9dee17454..0205241eb 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -24,7 +24,7 @@ pub struct Height { impl Height { pub fn new(revision_number: u64, revision_height: u64) -> Result { if revision_height == 0 { - return Err(Error::invalid_height()); + return Err(Error::InvalidHeight); } Ok(Self { @@ -54,7 +54,7 @@ impl Height { pub fn sub(&self, delta: u64) -> Result { if self.revision_height <= delta { - return Err(Error::invalid_height_result()); + return Err(Error::InvalidHeightResult); } Ok(Height { diff --git a/crates/ibc/src/core/ics02_client/msgs/create_client.rs b/crates/ibc/src/core/ics02_client/msgs/create_client.rs index 496e28638..32c96f749 100644 --- a/crates/ibc/src/core/ics02_client/msgs/create_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/create_client.rs @@ -49,18 +49,14 @@ impl TryFrom for MsgCreateClient { type Error = Error; fn try_from(raw: RawMsgCreateClient) -> Result { - let raw_client_state = raw - .client_state - .ok_or_else(Error::missing_raw_client_state)?; + let raw_client_state = raw.client_state.ok_or(Error::MissingRawClientState)?; - let raw_consensus_state = raw - .consensus_state - .ok_or_else(Error::missing_raw_client_state)?; + let raw_consensus_state = raw.consensus_state.ok_or(Error::MissingRawConsensusState)?; MsgCreateClient::new( raw_client_state, raw_consensus_state, - raw.signer.parse().map_err(Error::signer)?, + raw.signer.parse().map_err(Error::Signer)?, ) } } diff --git a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs index 07923bae8..3c0b18b3f 100644 --- a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs +++ b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs @@ -41,17 +41,15 @@ impl TryFrom for MsgSubmitMisbehaviour { type Error = Error; fn try_from(raw: RawMsgSubmitMisbehaviour) -> Result { - let raw_misbehaviour = raw - .misbehaviour - .ok_or_else(Error::missing_raw_misbehaviour)?; + let raw_misbehaviour = raw.misbehaviour.ok_or(Error::MissingRawMisbehaviour)?; Ok(MsgSubmitMisbehaviour { client_id: raw .client_id .parse() - .map_err(Error::invalid_raw_misbehaviour)?, + .map_err(Error::InvalidRawMisbehaviour)?, misbehaviour: raw_misbehaviour, - signer: raw.signer.parse().map_err(Error::signer)?, + signer: raw.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics02_client/msgs/update_client.rs b/crates/ibc/src/core/ics02_client/msgs/update_client.rs index dcc3dc975..71ce9aab1 100644 --- a/crates/ibc/src/core/ics02_client/msgs/update_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/update_client.rs @@ -55,9 +55,9 @@ impl TryFrom for MsgUpdateClient { client_id: raw .client_id .parse() - .map_err(Error::invalid_msg_update_client_id)?, - header: raw.header.ok_or_else(Error::missing_raw_header)?, - signer: raw.signer.parse().map_err(Error::signer)?, + .map_err(Error::InvalidMsgUpdateClientId)?, + header: raw.header.ok_or(Error::MissingRawHeader)?, + signer: raw.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs index f8d1b9fa1..c08d85bda 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -86,31 +86,29 @@ impl TryFrom for MsgUpgradeClient { type Error = Error; fn try_from(proto_msg: RawMsgUpgradeClient) -> Result { - let raw_client_state = proto_msg - .client_state - .ok_or_else(Error::missing_raw_client_state)?; + let raw_client_state = proto_msg.client_state.ok_or(Error::MissingRawClientState)?; let raw_consensus_state = proto_msg .consensus_state - .ok_or_else(Error::missing_raw_client_state)?; + .ok_or(Error::MissingRawConsensusState)?; let c_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client) - .map_err(|_| Error::invalid_upgrade_client_proof(Ics23Error::empty_merkle_proof()))?; + .map_err(|_| Error::InvalidUpgradeClientProof(Ics23Error::empty_merkle_proof()))?; let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) .map_err(|_| { - Error::invalid_upgrade_consensus_state_proof(Ics23Error::empty_merkle_proof()) + Error::InvalidUpgradeConsensusStateProof(Ics23Error::empty_merkle_proof()) })?; Ok(MsgUpgradeClient { client_id: ClientId::from_str(&proto_msg.client_id) - .map_err(Error::invalid_client_identifier)?, + .map_err(Error::InvalidClientIdentifier)?, client_state: raw_client_state, consensus_state: raw_consensus_state, proof_upgrade_client: RawMerkleProof::try_from(c_bytes) - .map_err(Error::invalid_upgrade_client_proof)?, + .map_err(Error::InvalidUpgradeClientProof)?, proof_upgrade_consensus_state: RawMerkleProof::try_from(cs_bytes) - .map_err(Error::invalid_upgrade_consensus_state_proof)?, - signer: proto_msg.signer.parse().map_err(Error::signer)?, + .map_err(Error::InvalidUpgradeConsensusStateProof)?, + signer: proto_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics02_client/trust_threshold.rs b/crates/ibc/src/core/ics02_client/trust_threshold.rs index 4202b6611..b2df62d2f 100644 --- a/crates/ibc/src/core/ics02_client/trust_threshold.rs +++ b/crates/ibc/src/core/ics02_client/trust_threshold.rs @@ -59,7 +59,10 @@ impl TrustThreshold { || (denominator == 0 && numerator != 0) || (numerator == denominator && numerator != 0) { - return Err(Error::invalid_trust_threshold(numerator, denominator)); + return Err(Error::InvalidTrustThreshold { + numerator, + denominator, + }); } Ok(Self { @@ -96,8 +99,10 @@ impl TryFrom for TrustThresholdFraction { type Error = Error; fn try_from(t: TrustThreshold) -> Result { - Self::new(t.numerator, t.denominator) - .map_err(|_| Error::failed_trust_threshold_conversion(t.numerator, t.denominator)) + Self::new(t.numerator, t.denominator).map_err(|_| Error::FailedTrustThresholdConversion { + numerator: t.numerator, + denominator: t.denominator, + }) } } diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index 7b0a84afa..2d4f3188d 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -269,7 +269,7 @@ impl TryFrom for Counterparty { .ok_or_else(Error::missing_counterparty)? .key_prefix .try_into() - .map_err(|_| Error::ics02_client(ClientError::empty_prefix()))?, + .map_err(|_| Error::ics02_client(ClientError::EmptyPrefix))?, )) } } diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 6acd3921e..1c259d360 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -7,13 +7,13 @@ use crate::signer::SignerError; use crate::Height; use alloc::string::String; -use flex_error::define_error; +use flex_error::{define_error, DisplayError}; define_error! { - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug)] Error { Ics02Client - [ client_error::Error ] + [ DisplayError ] | _ | { "ics02 client error" }, InvalidState @@ -90,7 +90,7 @@ define_error! { | _ | { "invalid connection proof" }, VerifyConnectionState - [ client_error::Error ] + [ DisplayError ] | _ | { "error verifying connnection state" }, Signer @@ -141,7 +141,7 @@ define_error! { ConsensusStateVerificationFailure { height: Height } - [ client_error::Error ] + [ DisplayError ] | e | { format_args!("the consensus proof verification failed (height: {0})", e.height) @@ -152,7 +152,7 @@ define_error! { { client_id: ClientId, } - [ client_error::Error ] + [ DisplayError ] | e | { format_args!("the client state proof verification failed for client id {0}", e.client_id) diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 469fbf8c2..080161c60 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -16,7 +16,7 @@ use flex_error::{define_error, TraceError}; use ibc_proto::protobuf::Error as TendermintError; define_error! { - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug)] Error { Ics03Connection [ connection_error::Error ] @@ -147,7 +147,7 @@ define_error! { PacketVerificationFailed { sequence: Sequence } - [ client_error::Error ] + [ TraceError ] | e | { format_args!( "Verification fails for the packet with the sequence number {0}", @@ -155,7 +155,7 @@ define_error! { }, VerifyChannelFailed - [ client_error::Error ] + [ TraceError ] | _ | { "Error verifying channel state" }, diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index b26c630fa..430a48eb8 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -201,10 +201,11 @@ mod tests { Box::new(move |e| match e { error::ErrorDetail::Ics03Connection(e) => { assert_eq!( - e.source, + e.source.to_string(), ics03_error::ErrorDetail::ConnectionNotFound( ics03_error::ConnectionNotFoundSubdetail { connection_id } ) + .to_string() ); } _ => { @@ -228,17 +229,15 @@ mod tests { match_error: Box::new(|e| match e { error::ErrorDetail::Ics03Connection(e) => { assert_eq!( - e.source, + e.source.to_string(), ics03_error::ErrorDetail::Ics02Client( ics03_error::Ics02ClientSubdetail { - source: ics02_error::ErrorDetail::ClientNotFound( - ics02_error::ClientNotFoundSubdetail { - client_id: ClientId::new(mock_client_type(), 45) - .unwrap() - } - ) + source: ics02_error::Error::ClientNotFound { + client_id: ClientId::new(mock_client_type(), 45).unwrap() + } } ) + .to_string() ); } _ => { diff --git a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs index 37844705e..0eaee16fb 100644 --- a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs @@ -10,6 +10,7 @@ use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; use crate::timestamp::Expiry; +use alloc::string::ToString; #[derive(Clone, Debug)] pub enum RecvPacketResult { @@ -128,7 +129,12 @@ pub fn process( return Ok(output.with_result(PacketResult::Recv(RecvPacketResult::NoOp))); } - Err(e) if e.detail() == Error::packet_receipt_not_found(packet.sequence).detail() => { + Err(e) + if e.detail().to_string() + == Error::packet_receipt_not_found(packet.sequence) + .detail() + .to_string() => + { // store a receipt that does not contain any data PacketResult::Recv(RecvPacketResult::Unordered { port_id: packet.destination_port.clone(), diff --git a/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs index 68ec0919e..ecd8b770f 100644 --- a/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs @@ -46,7 +46,10 @@ pub fn process( ) { Ok(_) => return Err(Error::acknowledgement_exists(packet.sequence)), Err(e) - if e.detail() == Error::packet_acknowledgement_not_found(packet.sequence).detail() => {} + if e.detail().to_string() + == Error::packet_acknowledgement_not_found(packet.sequence) + .detail() + .to_string() => {} Err(e) => return Err(e), } diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index dd2761db6..015706ce7 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -6,10 +6,10 @@ use crate::core::ics03_connection; use crate::core::ics04_channel; define_error! { - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug)] Error { Ics02Client - [ ics02_client::error::Error ] + [ TraceError ] | _ | { "ICS02 client error" }, Ics03Connection diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index eb6bcb1d1..78f16145a 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -26,7 +26,7 @@ define_error! { | _ | { "parse error" }, Client - [ client_error::Error ] + [ TraceError ] | _ | { "ICS02 client error" }, Connection diff --git a/crates/ibc/src/mock/client_state.rs b/crates/ibc/src/mock/client_state.rs index 80088a0e8..542c7aaf8 100644 --- a/crates/ibc/src/mock/client_state.rs +++ b/crates/ibc/src/mock/client_state.rs @@ -112,7 +112,7 @@ impl TryFrom for MockClientState { fn decode_client_state(buf: B) -> Result { RawMockClientState::decode(buf) - .map_err(Error::decode)? + .map_err(Error::Decode)? .try_into() } @@ -120,7 +120,9 @@ impl TryFrom for MockClientState { MOCK_CLIENT_STATE_TYPE_URL => { decode_client_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Error::unknown_client_state_type(raw.type_url)), + _ => Err(Error::UnknownClientStateType { + client_state_type: raw.type_url, + }), } } } @@ -178,10 +180,10 @@ impl ClientState for MockClientState { let header = MockHeader::try_from(header)?; if self.latest_height() >= header.height() { - return Err(Error::low_header_height( - header.height(), - self.latest_height(), - )); + return Err(Error::LowHeaderHeight { + header_height: header.height(), + latest_height: self.latest_height(), + }); } Ok(UpdatedState { @@ -199,10 +201,10 @@ impl ClientState for MockClientState { let header = MockHeader::try_from(header)?; if self.latest_height() >= header.height() { - return Err(Error::low_header_height( - header.height(), - self.latest_height(), - )); + return Err(Error::LowHeaderHeight { + header_height: header.height(), + latest_height: self.latest_height(), + }); } Ok(UpdatedState { diff --git a/crates/ibc/src/mock/consensus_state.rs b/crates/ibc/src/mock/consensus_state.rs index 51ceed757..232aee018 100644 --- a/crates/ibc/src/mock/consensus_state.rs +++ b/crates/ibc/src/mock/consensus_state.rs @@ -40,7 +40,7 @@ impl TryFrom for MockConsensusState { type Error = Error; fn try_from(raw: RawMockConsensusState) -> Result { - let raw_header = raw.header.ok_or_else(Error::missing_raw_consensus_state)?; + let raw_header = raw.header.ok_or(Error::MissingRawConsensusState)?; Ok(Self { header: MockHeader::try_from(raw_header)?, @@ -72,7 +72,7 @@ impl TryFrom for MockConsensusState { fn decode_consensus_state(buf: B) -> Result { RawMockConsensusState::decode(buf) - .map_err(Error::decode)? + .map_err(Error::Decode)? .try_into() } @@ -80,7 +80,9 @@ impl TryFrom for MockConsensusState { MOCK_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Error::unknown_consensus_state_type(raw.type_url)), + _ => Err(Error::UnknownConsensusStateType { + consensus_state_type: raw.type_url, + }), } } } diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 88b845ad2..a4401a720 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -1175,17 +1175,25 @@ impl ClientReader for MockContext { fn client_type(&self, client_id: &ClientId) -> Result { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => Ok(client_record.client_type.clone()), - None => Err(Ics02Error::client_not_found(client_id.clone())), + None => Err(Ics02Error::ClientNotFound { + client_id: client_id.clone(), + }), } } fn client_state(&self, client_id: &ClientId) -> Result, Ics02Error> { match self.ibc_store.lock().unwrap().clients.get(client_id) { - Some(client_record) => client_record - .client_state - .clone() - .ok_or_else(|| Ics02Error::client_not_found(client_id.clone())), - None => Err(Ics02Error::client_not_found(client_id.clone())), + Some(client_record) => { + client_record + .client_state + .clone() + .ok_or_else(|| Ics02Error::ClientNotFound { + client_id: client_id.clone(), + }) + } + None => Err(Ics02Error::ClientNotFound { + client_id: client_id.clone(), + }), } } @@ -1195,7 +1203,9 @@ impl ClientReader for MockContext { } else if let Ok(client_state) = MockClientState::try_from(client_state.clone()) { Ok(client_state.into_box()) } else { - Err(Ics02Error::unknown_client_state_type(client_state.type_url)) + Err(Ics02Error::UnknownClientStateType { + client_state_type: client_state.type_url, + }) } } @@ -1207,15 +1217,15 @@ impl ClientReader for MockContext { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => match client_record.consensus_states.get(&height) { Some(consensus_state) => Ok(consensus_state.clone()), - None => Err(Ics02Error::consensus_state_not_found( - client_id.clone(), + None => Err(Ics02Error::ConsensusStateNotFound { + client_id: client_id.clone(), height, - )), + }), }, - None => Err(Ics02Error::consensus_state_not_found( - client_id.clone(), + None => Err(Ics02Error::ConsensusStateNotFound { + client_id: client_id.clone(), height, - )), + }), } } @@ -1226,10 +1236,13 @@ impl ClientReader for MockContext { height: Height, ) -> Result>, Ics02Error> { let ibc_store = self.ibc_store.lock().unwrap(); - let client_record = ibc_store - .clients - .get(client_id) - .ok_or_else(|| Ics02Error::client_not_found(client_id.clone()))?; + let client_record = + ibc_store + .clients + .get(client_id) + .ok_or_else(|| Ics02Error::ClientNotFound { + client_id: client_id.clone(), + })?; // Get the consensus state heights and sort them in ascending order. let mut heights: Vec = client_record.consensus_states.keys().cloned().collect(); @@ -1254,10 +1267,13 @@ impl ClientReader for MockContext { height: Height, ) -> Result>, Ics02Error> { let ibc_store = self.ibc_store.lock().unwrap(); - let client_record = ibc_store - .clients - .get(client_id) - .ok_or_else(|| Ics02Error::client_not_found(client_id.clone()))?; + let client_record = + ibc_store + .clients + .get(client_id) + .ok_or_else(|| Ics02Error::ClientNotFound { + client_id: client_id.clone(), + })?; // Get the consensus state heights and sort them in descending order. let mut heights: Vec = client_record.consensus_states.keys().cloned().collect(); @@ -1291,12 +1307,12 @@ impl ClientReader for MockContext { fn host_consensus_state(&self, height: Height) -> Result, Ics02Error> { match self.host_block(height) { Some(block_ref) => Ok(block_ref.clone().into()), - None => Err(Ics02Error::missing_local_consensus_state(height)), + None => Err(Ics02Error::MissingLocalConsensusState { height }), } } fn pending_host_consensus_state(&self) -> Result, Ics02Error> { - Err(Ics02Error::implementation_specific()) + Err(Ics02Error::ImplementationSpecific) } fn client_counter(&self) -> Result { diff --git a/crates/ibc/src/mock/header.rs b/crates/ibc/src/mock/header.rs index df5570f4f..68e88bbc8 100644 --- a/crates/ibc/src/mock/header.rs +++ b/crates/ibc/src/mock/header.rs @@ -50,10 +50,10 @@ impl TryFrom for MockHeader { height: raw .height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_raw_header)?, + .ok_or(Error::MissingRawHeader)?, timestamp: Timestamp::from_nanoseconds(raw.timestamp) - .map_err(Error::invalid_packet_timestamp)?, + .map_err(Error::InvalidPacketTimestamp)?, }) } } @@ -106,8 +106,10 @@ 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(Error::invalid_raw_header)?), - _ => Err(Error::unknown_header_type(raw.type_url)), + .map_err(Error::InvalidRawHeader)?), + _ => Err(Error::UnknownHeaderType { + header_type: raw.type_url, + }), } } } diff --git a/crates/ibc/src/mock/misbehaviour.rs b/crates/ibc/src/mock/misbehaviour.rs index e75cdb3e1..d49723fc0 100644 --- a/crates/ibc/src/mock/misbehaviour.rs +++ b/crates/ibc/src/mock/misbehaviour.rs @@ -38,11 +38,11 @@ impl TryFrom for Misbehaviour { client_id: Default::default(), header1: raw .header1 - .ok_or_else(Error::missing_raw_misbehaviour)? + .ok_or(Error::MissingRawMisbehaviour)? .try_into()?, header2: raw .header2 - .ok_or_else(Error::missing_raw_misbehaviour)? + .ok_or(Error::MissingRawMisbehaviour)? .try_into()?, }) } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index b2e2fce15..142829dc5 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -241,11 +241,17 @@ impl SendPacketReader for DummyTransferModule { fn client_state(&self, client_id: &ClientId) -> Result, Error> { match self.ibc_store.lock().unwrap().clients.get(client_id) { - Some(client_record) => client_record - .client_state - .clone() - .ok_or_else(|| Ics02Error::client_not_found(client_id.clone())), - None => Err(Ics02Error::client_not_found(client_id.clone())), + Some(client_record) => { + client_record + .client_state + .clone() + .ok_or_else(|| Ics02Error::ClientNotFound { + client_id: client_id.clone(), + }) + } + None => Err(Ics02Error::ClientNotFound { + client_id: client_id.clone(), + }), } .map_err(|e| Error::ics03_connection(Ics03Error::ics02_client(e))) } @@ -258,15 +264,15 @@ impl SendPacketReader for DummyTransferModule { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => match client_record.consensus_states.get(&height) { Some(consensus_state) => Ok(consensus_state.clone()), - None => Err(Ics02Error::consensus_state_not_found( - client_id.clone(), + None => Err(Ics02Error::ConsensusStateNotFound { + client_id: client_id.clone(), height, - )), + }), }, - None => Err(Ics02Error::consensus_state_not_found( - client_id.clone(), + None => Err(Ics02Error::ConsensusStateNotFound { + client_id: client_id.clone(), height, - )), + }), } .map_err(|e| Error::ics03_connection(Ics03Error::ics02_client(e))) } From 1b2fcc3738586d2f6ee72e944d43a6d1b25ada4d Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 23 Nov 2022 01:01:30 +0800 Subject: [PATCH 03/43] Update client_state.rs --- .../ibc/src/clients/ics07_tendermint/client_state.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index b0f648b9b..3112d0d66 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -921,12 +921,12 @@ fn verify_delay_passed( height: Height, connection_end: &ConnectionEnd, ) -> Result<(), Ics02Error> { - let current_timestamp = ctx - .host_timestamp() - .map_err(|e| Ics02Error::other(e.to_string()))?; - let current_height = ctx - .host_height() - .map_err(|e| Ics02Error::other(e.to_string()))?; + let current_timestamp = ctx.host_timestamp().map_err(|e| Ics02Error::Other { + description: e.to_string(), + })?; + let current_height = ctx.host_height().map_err(|e| Ics02Error::Other { + description: e.to_string(), + })?; let client_id = connection_end.client_id(); let processed_time = ctx From a067a5ea5f1b46dd1bf5c0b8020a77d83b20941b Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 23 Nov 2022 12:52:06 +0800 Subject: [PATCH 04/43] Redefine Ics07Error by displaydoc --- .../clients/ics07_tendermint/client_state.rs | 229 +++++---- .../ics07_tendermint/consensus_state.rs | 21 +- .../ibc/src/clients/ics07_tendermint/error.rs | 439 ++++++------------ .../src/clients/ics07_tendermint/header.rs | 29 +- .../clients/ics07_tendermint/misbehaviour.rs | 8 +- crates/ibc/src/core/ics02_client/error.rs | 3 + 6 files changed, 309 insertions(+), 420 deletions(-) diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index 3112d0d66..4b62e58b9 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -87,75 +87,84 @@ impl ClientState { frozen_height: Option, ) -> Result { if chain_id.as_str().len() > MaxChainIdLen { - return Err(Error::chain_id_too_long( - chain_id.to_string(), - chain_id.as_str().len(), - MaxChainIdLen, - )); + return Err(Error::ChainIdTooLong { + chain_id: chain_id.clone(), + len: chain_id.as_str().len(), + max_len: MaxChainIdLen, + }); } // `TrustThreshold` is guaranteed to be in the range `[0, 1)`, but a `TrustThreshold::ZERO` // value is invalid in this context if trust_level == TrustThreshold::ZERO { - return Err(Error::invalid_trust_threshold( - "ClientState trust-level cannot be zero".to_string(), - )); + return Err(Error::InvalidTrustThreshold { + reason: "ClientState trust-level cannot be zero".to_string(), + }); } let _ = TendermintTrustThresholdFraction::new( trust_level.numerator(), trust_level.denominator(), ) - .map_err(Error::invalid_tendermint_trust_threshold)?; + .map_err(Error::InvalidTendermintTrustThreshold)?; // Basic validation of trusting period and unbonding period: each should be non-zero. if trusting_period <= Duration::new(0, 0) { - return Err(Error::invalid_trusting_period(format!( - "ClientState trusting period ({:?}) must be greater than zero", - trusting_period - ))); + return Err(Error::InvalidTrustThreshold { + reason: format!( + "ClientState trusting period ({:?}) must be greater than zero", + trusting_period + ), + }); } if unbonding_period <= Duration::new(0, 0) { - return Err(Error::invalid_unbonding_period(format!( - "ClientState unbonding period ({:?}) must be greater than zero", - unbonding_period - ))); + return Err(Error::InvalidTrustThreshold { + reason: format!( + "ClientState unbonding period ({:?}) must be greater than zero", + unbonding_period + ), + }); } if trusting_period >= unbonding_period { - return Err(Error::invalid_trusting_period(format!( + return Err(Error::InvalidTrustThreshold { + reason: format!( "ClientState trusting period ({:?}) must be smaller than unbonding period ({:?})", trusting_period, unbonding_period, - ))); + ), + }); } if max_clock_drift <= Duration::new(0, 0) { - return Err(Error::invalid_max_clock_drift( - "ClientState max-clock-drift must be greater than zero".to_string(), - )); + return Err(Error::InvalidMaxClockDrift { + reason: "ClientState max-clock-drift must be greater than zero".to_string(), + }); } if latest_height.revision_number() != chain_id.version() { - return Err(Error::invalid_latest_height( - "ClientState latest-height revision number must match chain-id version".to_string(), - )); + return Err(Error::InvalidLatestHeight { + reason: "ClientState latest-height revision number must match chain-id version" + .to_string(), + }); } // Disallow empty proof-specs if proof_specs.is_empty() { - return Err(Error::validation( - "ClientState proof-specs cannot be empty".to_string(), - )); + return Err(Error::Validation { + reason: "ClientState proof-specs cannot be empty".to_string(), + }); } // `upgrade_path` itself may be empty, but if not then each key must be non-empty for (idx, key) in upgrade_path.iter().enumerate() { if key.trim().is_empty() { - return Err(Error::validation(format!( - "ClientState upgrade-path key at index {:?} cannot be empty", - idx - ))); + return Err(Error::Validation { + reason: format!( + "ClientState upgrade-path key at index {:?} cannot be empty", + idx + ), + }); } } @@ -184,7 +193,9 @@ impl ClientState { self.latest_height.revision_number(), h.signed_header.header.height.into(), ) - .map_err(|_| Error::invalid_header_height(h.signed_header.header.height.value()))?, + .map_err(|_| Error::InvalidHeaderHeight { + height: h.signed_header.header.height.value(), + })?, ..self }) } @@ -205,10 +216,11 @@ impl ClientState { /// Tendermint-specific light client verification. pub fn as_light_client_options(&self) -> Result { Ok(Options { - trust_threshold: self - .trust_level - .try_into() - .map_err(|e: Ics02Error| Error::invalid_trust_threshold(e.to_string()))?, + trust_threshold: self.trust_level.try_into().map_err(|e: Ics02Error| { + Error::InvalidTrustThreshold { + reason: e.to_string(), + } + })?, trusting_period: self.trusting_period, clock_drift: self.max_clock_drift, }) @@ -224,17 +236,20 @@ impl ClientState { delay_period_blocks: u64, ) -> Result<(), Error> { let earliest_time = - (processed_time + delay_period_time).map_err(Error::timestamp_overflow)?; + (processed_time + delay_period_time).map_err(Error::TimestampOverflow)?; if !(current_time == earliest_time || current_time.after(&earliest_time)) { - return Err(Error::not_enough_time_elapsed(current_time, earliest_time)); + return Err(Error::NotEnoughTimeElapsed { + current_time, + earliest_time, + }); } let earliest_height = processed_height.add(delay_period_blocks); if current_height < earliest_height { - return Err(Error::not_enough_blocks_elapsed( + return Err(Error::NotEnoughBlocksElapsed { current_height, earliest_height, - )); + }); } Ok(()) @@ -243,13 +258,17 @@ impl ClientState { /// Verify that the client is at a sufficient height and unfrozen at the given height pub fn verify_height(&self, height: Height) -> Result<(), Error> { if self.latest_height < height { - return Err(Error::insufficient_height(self.latest_height(), height)); + return Err(Error::InsufficientHeight { + latest_height: self.latest_height(), + target_height: height, + }); } match self.frozen_height { - Some(frozen_height) if frozen_height <= height => { - Err(Error::client_frozen(frozen_height, height)) - } + Some(frozen_height) if frozen_height <= height => Err(Error::ClientFrozen { + frozen_height, + target_height: height, + }), _ => Ok(()), } } @@ -340,10 +359,10 @@ impl Ics2ClientState for ClientState { if header.height().revision_number() != client_state.chain_id().version() { return Err(Ics02Error::ClientSpecific { - description: Error::mismatched_revisions( - client_state.chain_id().version(), - header.height().revision_number(), - ) + description: Error::MismatchedRevisions { + current_revision: client_state.chain_id().version(), + update_revision: header.height().revision_number(), + } .to_string(), }); } @@ -382,9 +401,9 @@ impl Ics2ClientState for ClientState { .revision_height() .try_into() .map_err(|_| Ics02Error::ClientSpecific { - description: Error::invalid_header_height( - header.trusted_height.revision_height(), - ) + description: Error::InvalidHeaderHeight { + height: header.trusted_height.revision_height(), + } .to_string(), })?, next_validators: &header.trusted_validator_set, @@ -412,13 +431,12 @@ impl Ics2ClientState for ClientState { match verdict { Verdict::Success => {} Verdict::NotEnoughTrust(voting_power_tally) => { - return Err(Error::not_enough_trusted_vals_signed(format!( - "voting power tally: {}", - voting_power_tally - )) + return Err(Error::NotEnoughTrustedValsSigned { + reason: format!("voting power tally: {}", voting_power_tally), + } .into()); } - Verdict::Invalid(detail) => return Err(Error::verification_error(detail).into()), + Verdict::Invalid(detail) => return Err(Error::VerificationError { detail }.into()), } // If the header has verified, but its corresponding consensus state @@ -447,10 +465,10 @@ impl Ics2ClientState for ClientState { // consensus state's height if header.signed_header.header().time > next_cs.timestamp { return Err(Ics02Error::ClientSpecific { - description: Error::header_timestamp_too_high( - header.signed_header.header().time.to_string(), - next_cs.timestamp.to_string(), - ) + description: Error::HeaderTimestampTooHigh { + actual: header.signed_header.header().time.to_string(), + max: next_cs.timestamp.to_string(), + } .to_string(), }); } @@ -470,10 +488,10 @@ impl Ics2ClientState for ClientState { // previous consensus state's height if header.signed_header.header().time < prev_cs.timestamp { return Err(Ics02Error::ClientSpecific { - description: Error::header_timestamp_too_low( - header.signed_header.header().time.to_string(), - prev_cs.timestamp.to_string(), - ) + description: Error::HeaderTimestampTooLow { + actual: header.signed_header.header().time.to_string(), + min: prev_cs.timestamp.to_string(), + } .to_string(), }); } @@ -514,10 +532,10 @@ impl Ics2ClientState for ClientState { if header.height().revision_number() != client_state.chain_id().version() { return Err(Ics02Error::ClientSpecific { - description: Error::mismatched_revisions( - client_state.chain_id().version(), - header.height().revision_number(), - ) + description: Error::MismatchedRevisions { + current_revision: client_state.chain_id().version(), + update_revision: header.height().revision_number(), + } .to_string(), }); } @@ -556,9 +574,9 @@ impl Ics2ClientState for ClientState { .revision_height() .try_into() .map_err(|_| Ics02Error::ClientSpecific { - description: Error::invalid_header_height( - header.trusted_height.revision_height(), - ) + description: Error::InvalidHeaderHeight { + height: header.trusted_height.revision_height(), + } .to_string(), })?, next_validators: &header.trusted_validator_set, @@ -586,13 +604,12 @@ impl Ics2ClientState for ClientState { match verdict { Verdict::Success => {} Verdict::NotEnoughTrust(voting_power_tally) => { - return Err(Error::not_enough_trusted_vals_signed(format!( - "voting power tally: {}", - voting_power_tally - )) + return Err(Error::NotEnoughTrustedValsSigned { + reason: format!("voting power tally: {}", voting_power_tally), + } .into()); } - Verdict::Invalid(detail) => return Err(Error::verification_error(detail).into()), + Verdict::Invalid(detail) => return Err(Error::VerificationError { detail }.into()), } // If the header has verified, but its corresponding consensus state @@ -621,10 +638,10 @@ impl Ics2ClientState for ClientState { // consensus state's height if header.signed_header.header().time > next_cs.timestamp { return Err(Ics02Error::ClientSpecific { - description: Error::header_timestamp_too_high( - header.signed_header.header().time.to_string(), - next_cs.timestamp.to_string(), - ) + description: Error::HeaderTimestampTooHigh { + actual: header.signed_header.header().time.to_string(), + max: next_cs.timestamp.to_string(), + } .to_string(), }); } @@ -644,10 +661,10 @@ impl Ics2ClientState for ClientState { // previous consensus state's height if header.signed_header.header().time < prev_cs.timestamp { return Err(Ics02Error::ClientSpecific { - description: Error::header_timestamp_too_low( - header.signed_header.header().time.to_string(), - prev_cs.timestamp.to_string(), - ) + description: Error::HeaderTimestampTooLow { + actual: header.signed_header.header().time.to_string(), + min: prev_cs.timestamp.to_string(), + } .to_string(), }); } @@ -929,12 +946,18 @@ fn verify_delay_passed( })?; let client_id = connection_end.client_id(); - let processed_time = ctx - .client_update_time(client_id, height) - .map_err(|_| Error::processed_time_not_found(client_id.clone(), height))?; - let processed_height = ctx - .client_update_height(client_id, height) - .map_err(|_| Error::processed_height_not_found(client_id.clone(), height))?; + let processed_time = + ctx.client_update_time(client_id, height) + .map_err(|_| Error::ProcessedTimeNotFound { + client_id: client_id.clone(), + height, + })?; + let processed_height = ctx.client_update_height(client_id, height).map_err(|_| { + Error::ProcessedHeightNotFound { + client_id: client_id.clone(), + height, + } + })?; let delay_period_time = connection_end.delay_period(); let delay_period_height = ctx.block_delay(delay_period_time); @@ -979,35 +1002,37 @@ impl TryFrom for ClientState { let trust_level = raw .trust_level .clone() - .ok_or_else(Error::missing_trusting_period)?; + .ok_or(Error::MissingTrustingPeriod)?; trust_level .try_into() - .map_err(|e| Error::invalid_trust_threshold(format!("{}", e)))? + .map_err(|e| Error::InvalidTrustThreshold { + reason: format!("{}", e), + })? }; let trusting_period = raw .trusting_period - .ok_or_else(Error::missing_trusting_period)? + .ok_or(Error::MissingTrustingPeriod)? .try_into() - .map_err(|_| Error::negative_trusting_period())?; + .map_err(|_| Error::MissingTrustingPeriod)?; let unbonding_period = raw .unbonding_period - .ok_or_else(Error::missing_unbonding_period)? + .ok_or(Error::MissingUnbondingPeriod)? .try_into() - .map_err(|_| Error::negative_unbonding_period())?; + .map_err(|_| Error::MissingUnbondingPeriod)?; let max_clock_drift = raw .max_clock_drift - .ok_or_else(Error::missing_max_clock_drift)? + .ok_or(Error::NegativeMaxClockDrift)? .try_into() - .map_err(|_| Error::negative_max_clock_drift())?; + .map_err(|_| Error::NegativeMaxClockDrift)?; let latest_height = raw .latest_height - .ok_or_else(Error::missing_latest_height)? + .ok_or(Error::MissingLatestHeight)? .try_into() - .map_err(|_| Error::missing_latest_height())?; + .map_err(|_| Error::MissingLatestHeight)?; // In `RawClientState`, a `frozen_height` of `0` means "not frozen". // See: @@ -1076,7 +1101,7 @@ impl TryFrom for ClientState { fn decode_client_state(buf: B) -> Result { RawTmClientState::decode(buf) - .map_err(Error::decode)? + .map_err(Error::Decode)? .try_into() } diff --git a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs index 1d852d3ab..8a916dd29 100644 --- a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs @@ -56,27 +56,32 @@ impl TryFrom for ConsensusState { type Error = Error; fn try_from(raw: RawConsensusState) -> Result { - let ibc_proto::google::protobuf::Timestamp { seconds, nanos } = raw - .timestamp - .ok_or_else(|| Error::invalid_raw_consensus_state("missing timestamp".into()))?; + let ibc_proto::google::protobuf::Timestamp { seconds, nanos } = + raw.timestamp.ok_or(Error::InvalidRawClientState { + reason: "missing timestamp".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| Error::invalid_raw_consensus_state(format!("invalid timestamp: {}", e)))?; + .map_err(|e| Error::InvalidRawClientState { + reason: format!("invalid timestamp: {}", e), + })?; Ok(Self { root: raw .root - .ok_or_else(|| { - Error::invalid_raw_consensus_state("missing commitment root".into()) + .ok_or(Error::InvalidRawClientState { + reason: "missing commitment root".into(), })? .hash .into(), timestamp, next_validators_hash: Hash::from_bytes(Algorithm::Sha256, &raw.next_validators_hash) - .map_err(|e| Error::invalid_raw_consensus_state(e.to_string()))?, + .map_err(|e| Error::InvalidRawClientState { + reason: e.to_string(), + })?, }) } } @@ -110,7 +115,7 @@ impl TryFrom for ConsensusState { fn decode_consensus_state(buf: B) -> Result { RawConsensusState::decode(buf) - .map_err(Error::decode)? + .map_err(Error::Decode)? .try_into() } diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index 7d67fc10a..92115837c 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -1,11 +1,10 @@ use crate::prelude::*; -use flex_error::{define_error, TraceError}; - use crate::core::ics02_client::error::Error as Ics02Error; use crate::core::ics24_host::error::ValidationError; -use crate::core::ics24_host::identifier::ClientId; +use crate::core::ics24_host::identifier::{ChainId, ClientId}; use crate::timestamp::{Timestamp, TimestampOverflowError}; +use displaydoc::Display; use crate::Height; use tendermint::account::Id; @@ -13,300 +12,150 @@ use tendermint::hash::Hash; use tendermint::Error as TendermintError; use tendermint_light_client_verifier::errors::VerificationErrorDetail as LightClientErrorDetail; -define_error! { - #[derive(Debug, PartialEq, Eq)] - Error { - ChainIdTooLong - { - chain_id: String, - len: usize, - max_len: usize, - } - |e| { format_args!("chain-id is ({0}) is too long, got: {1}, max allowed: {2}", e.chain_id, e.len, e.max_len) }, - - InvalidTrustingPeriod - { reason: String } - |e| { format_args!("invalid trusting period: {}", e.reason) }, - - InvalidUnbondingPeriod - { reason: String } - |e| { format_args!("invalid unbonding period: {}", e.reason) }, - - InvalidAddress - |_| { "invalid address" }, - - InvalidHeader - { reason: String } - [ TendermintError ] - |e| { format_args!("invalid header, failed basic validation: {}", e.reason) }, - - InvalidTrustThreshold - { reason: String } - |e| { format_args!("invalid client state trust threshold: {}", e.reason) }, - - InvalidTendermintTrustThreshold - [ TendermintError ] - |_| { "invalid tendermint client state trust threshold" }, - - InvalidMaxClockDrift - { reason: String } - |e| { format_args!("invalid client state max clock drift: {}", e.reason) }, - - InvalidLatestHeight - { reason: String } - |e| { format_args!("invalid client state latest height: {}", e.reason) }, - - MissingSignedHeader - |_| { "missing signed header" }, - - Validation - { reason: String } - |e| { format_args!("invalid header, failed basic validation: {}", e.reason) }, - - InvalidRawClientState - { reason: String } - |e| { format_args!("invalid raw client state: {}", e.reason) }, - - MissingValidatorSet - |_| { "missing validator set" }, - - MissingTrustedValidatorSet - |_| { "missing trusted validator set" }, - - MissingTrustedHeight - |_| { "missing trusted height" }, - - MissingTrustingPeriod - |_| { "missing trusting period" }, - - MissingUnbondingPeriod - |_| { "missing unbonding period" }, - - InvalidChainIdentifier - [ ValidationError ] - |_| { "invalid chain identifier" }, - - NegativeTrustingPeriod - |_| { "negative trusting period" }, - - NegativeUnbondingPeriod - |_| { "negative unbonding period" }, - - MissingMaxClockDrift - |_| { "missing max clock drift" }, - - NegativeMaxClockDrift - |_| { "negative max clock drift" }, - - MissingLatestHeight - |_| { "missing latest height" }, - - InvalidFrozenHeight - |_| { "invalid frozen height" }, - - InvalidChainId - { raw_value: String } - [ ValidationError ] - |e| { format_args!("invalid chain identifier: {}", e.raw_value) }, - - InvalidRawHeight - { raw_height: u64 } - |e| { format_args!("invalid raw height: {}", e.raw_height) }, - - InvalidRawConsensusState - { reason: String } - | e | { format_args!("invalid raw client consensus state: {}", e.reason) }, - - InvalidRawHeader - [ TendermintError ] - | _ | { "invalid raw header" }, - - InvalidRawMisbehaviour - { reason: String } - | e | { format_args!("invalid raw misbehaviour: {}", e.reason) }, - - Decode - [ TraceError ] - | _ | { "decode error" }, - - InsufficientVotingPower - { reason: String } - | e | { - format_args!("insufficient overlap: {}", e.reason) - }, - - LowUpdateTimestamp - { - low: String, - high: String - } - | e | { - format_args!("header timestamp {0} must be greater than current client consensus state timestamp {1}", e.low, e.high) - }, - - HeaderTimestampOutsideTrustingTime - { - low: String, - high: String - } - | e | { - format_args!("header timestamp {0} is outside the trusting period w.r.t. consensus state timestamp {1}", e.low, e.high) - }, - - HeaderTimestampTooHigh - { - actual: String, - max: String, - } - | e | { - format_args!("given other previous updates, header timestamp should be at most {0}, but was {1}", e.max, e.actual) - }, - - HeaderTimestampTooLow - { - actual: String, - min: String, - } - | e | { - format_args!("given other previous updates, header timestamp should be at least {0}, but was {1}", e.min, e.actual) - }, - - TimestampOverflow - [ TimestampOverflowError ] - |_| { "timestamp overflowed" }, - - NotEnoughTimeElapsed - { - current_time: Timestamp, - earliest_time: Timestamp, - } - | e | { - format_args!("not enough time elapsed, current timestamp {0} is still less than earliest acceptable timestamp {1}", e.current_time, e.earliest_time) - }, - - NotEnoughBlocksElapsed - { - current_height: Height, - earliest_height: Height, - } - | e | { - format_args!("not enough blocks elapsed, current height {0} is still less than earliest acceptable height {1}", e.current_height, e.earliest_height) - }, - - InvalidHeaderHeight - { height: u64 } - | e | { - format_args!("header revision height = {0} is invalid", e.height) - }, - - InvalidTrustedHeaderHeight - { - trusted_header_height: Height, - height_header: Height - } - | e | { - format_args!("header height is {0} and is lower than the trusted header height, which is {1} ", e.height_header, e.trusted_header_height) - }, - - LowUpdateHeight - { - low: Height, - high: Height - } - | e | { - format_args!("header height is {0} but it must be greater than the current client height which is {1}", e.low, e.high) - }, - - MismatchedRevisions - { - current_revision: u64, - update_revision: u64, - } - | e | { - format_args!("the header's current/trusted revision number ({0}) and the update's revision number ({1}) should be the same", e.current_revision, e.update_revision) - }, - - InvalidValidatorSet - { - hash1: Hash, - hash2: Hash, - } - | e | { - format_args!("invalid validator set: header_validators_hash={} and validators_hash={}", e.hash1, e.hash2) - }, - - NotEnoughTrustedValsSigned - { reason: String } - | e | { - format_args!("not enough trust because insufficient validators overlap: {}", e.reason) - }, - - VerificationError - { detail: LightClientErrorDetail } - | e | { - format_args!("verification failed: {}", e.detail) - }, - - ProcessedTimeNotFound - { - client_id: ClientId, - height: Height, - } - | e | { - format_args!( - "Processed time for the client {0} at height {1} not found", - e.client_id, e.height) - }, - - ProcessedHeightNotFound - { - client_id: ClientId, - height: Height, - } - | e | { - format_args!( - "Processed height for the client {0} at height {1} not found", - e.client_id, e.height) - }, - - InsufficientHeight - { - latest_height: Height, - target_height: Height, - } - | e | { - format_args!("the height is insufficient: latest_height={0} target_height={1}", e.latest_height, e.target_height) - }, - - ClientFrozen - { - frozen_height: Height, - target_height: Height, - } - | e | { - format_args!("the client is frozen: frozen_height={0} target_height={1}", e.frozen_height, e.target_height) - }, - } +#[cfg(feature = "std")] +impl std::error::Error for Error {} + +#[derive(Debug, Display)] +pub enum Error { + /// chain-id is (`{chain_id}`) is too long, got: `{len}`, max allowed: `{max_len}` + ChainIdTooLong { + chain_id: ChainId, + len: usize, + max_len: usize, + }, + /// invalid trusting period: `{reason}` + InvalidTrustingPeriod { reason: String }, + /// invalid unbonding period: `{reason}` + InvalidUnbondingPeriod { reason: String }, + /// invalid address + InvalidAddress, + /// invalid header, failed basic validation: `{reason}`, error(`{error}`) + InvalidHeader { + reason: String, + error: TendermintError, + }, + /// invalid client state trust threshold: `{reason}` + InvalidTrustThreshold { reason: String }, + /// invalid tendermint client state trust threshold, error(`{0}`) + InvalidTendermintTrustThreshold(TendermintError), + /// invalid client state max clock drift: `{reason}` + InvalidMaxClockDrift { reason: String }, + /// invalid client state latest height: `{reason}` + InvalidLatestHeight { reason: String }, + /// missing signed header + MissingSignedHeader, + /// invalid header, failed basic validation: `{reason}` + Validation { reason: String }, + /// invalid raw client state: `{reason}` + InvalidRawClientState { reason: String }, + /// missing validator set + MissingValidatorSet, + /// missing trusted validator set + MissingTrustedValidatorSet, + /// missing trusted height + MissingTrustedHeight, + /// missing trusting period + MissingTrustingPeriod, + /// missing unbonding period + MissingUnbondingPeriod, + /// invalid chain identifier, error(`{0}`) + InvalidChainIdentifier(ValidationError), + /// negative trusting period + NegativeTrustingPeriod, + /// negative unbonding period + NegativeUnbondingPeriod, + /// missing max clock drift + MissingMaxClockDrift, + /// negative max clock drift + NegativeMaxClockDrift, + /// missing latest height + MissingLatestHeight, + /// invalid frozen height + InvalidFrozenHeight, + /// invalid chain identifier: `{raw_value}`, error(`{error}`) + InvalidChainId { + raw_value: String, + error: ValidationError, + }, + /// invalid raw height: `{raw_height}` + InvalidRawHeight { raw_height: u64 }, + /// invalid raw client consensus state: `{reason}` + InvalidRawConsensusState { reason: String }, + /// invalid raw header, error(`{0}`) + InvalidRawHeader(TendermintError), + /// invalid raw misbehaviour: `{reason}` + InvalidRawMisbehaviour { reason: String }, + /// decode error, error(`{0}`) + Decode(prost::DecodeError), + /// insufficient overlap: `{reason}` + InsufficientVotingPower { reason: String }, + /// header timestamp `{low}` must be greater than current client consensus state timestamp `{high}` + LowUpdateTimestamp { low: String, high: String }, + /// header timestamp `{low}` is outside the trusting period w.r.t. consensus state timestamp `{high}` + HeaderTimestampOutsideTrustingTime { low: String, high: String }, + /// given other previous updates, header timestamp should be at most `{max}`, but was `{actual}` + HeaderTimestampTooHigh { actual: String, max: String }, + /// given other previous updates, header timestamp should be at least `{min}`, but was `{actual}` + HeaderTimestampTooLow { actual: String, min: String }, + /// timestamp overflowed, error(`{0}`) + TimestampOverflow(TimestampOverflowError), + /// not enough time elapsed, current timestamp `{current_time}` is still less than earliest acceptable timestamp `{earliest_time}` + NotEnoughTimeElapsed { + current_time: Timestamp, + earliest_time: Timestamp, + }, + /// not enough blocks elapsed, current height `{current_height}` is still less than earliest acceptable height `{earliest_height}` + NotEnoughBlocksElapsed { + current_height: Height, + earliest_height: Height, + }, + /// header revision height = `{height}` is invalid + InvalidHeaderHeight { height: u64 }, + /// header height is `{height_header}` and is lower than the trusted header height, which is `{trusted_header_height}` + InvalidTrustedHeaderHeight { + trusted_header_height: Height, + height_header: Height, + }, + /// header height is `{low}` but it must be greater than the current client height which is `{high}` + LowUpdateHeight { low: Height, high: Height }, + /// the header's current/trusted revision number (`{current_revision}`) and the update's revision number (`{update_revision}`) should be the same + MismatchedRevisions { + current_revision: u64, + update_revision: u64, + }, + /// invalid validator set: header_validators_hash=`{hash1}` and validators_hash=`{hash2}` + InvalidValidatorSet { hash1: Hash, hash2: Hash }, + /// not enough trust because insufficient validators overlap: `{reason}` + NotEnoughTrustedValsSigned { reason: String }, + /// verification failed: `{detail}` + VerificationError { detail: LightClientErrorDetail }, + /// Processed time for the client `{client_id}` at height `{height}` not found + ProcessedTimeNotFound { client_id: ClientId, height: Height }, + /// Processed height for the client `{client_id}` at height `{height}` not found + ProcessedHeightNotFound { client_id: ClientId, height: Height }, + /// the height is insufficient: latest_height=`{latest_height}` target_height=`{target_height}` + InsufficientHeight { + latest_height: Height, + target_height: Height, + }, + /// the client is frozen: frozen_height=`{frozen_height}` target_height=`{target_height}` + ClientFrozen { + frozen_height: Height, + target_height: Height, + }, } -define_error! { - #[derive(Debug, PartialEq, Eq)] - VerificationError { - InvalidSignature - | _ | { "couldn't verify validator signature" }, - - DuplicateValidator - { id: Id } - | e | { - format_args!("duplicate validator in commit signatures with address {}", e.id) - }, - - InsufficientOverlap - { q1: u64, q2: u64 } - | e | { - format_args!("insufficient signers overlap between {0} and {1}", e.q1, e.q2) - }, - } +#[cfg(feature = "std")] +impl std::error::Error for VerificationError {} + +#[derive(Debug, Display)] +pub enum VerificationError { + /// couldn't verify validator signature + InvalidSignature, + /// duplicate validator in commit signatures with address `{id}` + DuplicateValidator { id: Id }, + /// insufficient signers overlap between `{q1}` and `{q2}` + InsufficientOverlap { q1: u64, q2: u64 }, } impl From for Ics02Error { diff --git a/crates/ibc/src/clients/ics07_tendermint/header.rs b/crates/ibc/src/clients/ics07_tendermint/header.rs index fc45ae78d..27dc53eea 100644 --- a/crates/ibc/src/clients/ics07_tendermint/header.rs +++ b/crates/ibc/src/clients/ics07_tendermint/header.rs @@ -102,30 +102,33 @@ impl TryFrom for Header { let header = Self { signed_header: raw .signed_header - .ok_or_else(Error::missing_signed_header)? + .ok_or(Error::MissingSignedHeader)? .try_into() - .map_err(|e| Error::invalid_header("signed header conversion".to_string(), e))?, + .map_err(|e| Error::InvalidHeader { + reason: "signed header conversion".to_string(), + error: e, + })?, validator_set: raw .validator_set - .ok_or_else(Error::missing_validator_set)? + .ok_or(Error::MissingValidatorSet)? .try_into() - .map_err(Error::invalid_raw_header)?, + .map_err(Error::InvalidRawHeader)?, trusted_height: raw .trusted_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_trusted_height)?, + .ok_or(Error::MissingTrustedHeight)?, trusted_validator_set: raw .trusted_validators - .ok_or_else(Error::missing_trusted_validator_set)? + .ok_or(Error::MissingTrustedValidatorSet)? .try_into() - .map_err(Error::invalid_raw_header)?, + .map_err(Error::InvalidRawHeader)?, }; if header.height().revision_number() != header.trusted_height.revision_number() { - return Err(Error::mismatched_revisions( - header.trusted_height.revision_number(), - header.height().revision_number(), - )); + return Err(Error::MismatchedRevisions { + current_revision: header.trusted_height.revision_number(), + update_revision: header.height().revision_number(), + }); } Ok(header) @@ -141,7 +144,7 @@ impl TryFrom for Header { use core::ops::Deref; fn decode_header(buf: B) -> Result { - RawHeader::decode(buf).map_err(Error::decode)?.try_into() + RawHeader::decode(buf).map_err(Error::Decode)?.try_into() } match raw.type_url.as_str() { @@ -164,7 +167,7 @@ impl From
for Any { } pub fn decode_header(buf: B) -> Result { - RawHeader::decode(buf).map_err(Error::decode)?.try_into() + RawHeader::decode(buf).map_err(Error::Decode)?.try_into() } impl From
for RawHeader { diff --git a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs index afe161cfd..7368421fb 100644 --- a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs +++ b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs @@ -38,11 +38,15 @@ impl TryFrom for Misbehaviour { client_id: Default::default(), header1: raw .header_1 - .ok_or_else(|| Error::invalid_raw_misbehaviour("missing header1".into()))? + .ok_or_else(|| Error::InvalidRawMisbehaviour { + reason: "missing header1".into(), + })? .try_into()?, header2: raw .header_2 - .ok_or_else(|| Error::invalid_raw_misbehaviour("missing header2".into()))? + .ok_or_else(|| Error::InvalidRawMisbehaviour { + reason: "missing header2".into(), + })? .try_into()?, }) } diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 2d90b88da..4f2a82f70 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -12,6 +12,9 @@ use crate::signer::SignerError; use crate::timestamp::Timestamp; use crate::Height; +#[cfg(feature = "std")] +impl std::error::Error for Error {} + #[derive(Debug, Display)] pub enum Error { /// unknown client type: `{client_type}` From 1af91288094a5329c556cfeec768bfed46e1d47b Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 23 Nov 2022 16:25:06 +0800 Subject: [PATCH 05/43] Redefine Ics03Error by displaydoc --- .../clients/ics07_tendermint/host_helpers.rs | 86 +++--- .../src/core/ics03_connection/connection.rs | 20 +- crates/ibc/src/core/ics03_connection/error.rs | 246 ++++++------------ .../ics03_connection/handler/conn_open_ack.rs | 42 +-- .../handler/conn_open_confirm.rs | 8 +- .../handler/conn_open_init.rs | 2 +- .../ics03_connection/handler/conn_open_try.rs | 22 +- .../ics03_connection/msgs/conn_open_ack.rs | 20 +- .../msgs/conn_open_confirm.rs | 8 +- .../ics03_connection/msgs/conn_open_init.rs | 6 +- .../ics03_connection/msgs/conn_open_try.rs | 20 +- .../ibc/src/core/ics03_connection/version.rs | 10 +- crates/ibc/src/core/ics04_channel/error.rs | 4 +- .../ics04_channel/handler/chan_open_try.rs | 16 +- crates/ibc/src/core/ics26_routing/error.rs | 2 +- crates/ibc/src/events.rs | 2 +- crates/ibc/src/mock/context.rs | 18 +- crates/ibc/src/relayer/ics18_relayer/error.rs | 4 +- crates/ibc/src/test_utils.rs | 6 +- 19 files changed, 243 insertions(+), 299 deletions(-) diff --git a/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs b/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs index 32fc73d72..21ae8f22f 100644 --- a/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs +++ b/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs @@ -18,45 +18,55 @@ use tendermint::trust_threshold::TrustThresholdFraction as TendermintTrustThresh pub trait ValidateSelfClientContext { fn validate_self_client(&self, counterparty_client_state: Any) -> Result<(), Error> { let counterparty_client_state = TmClientState::try_from(counterparty_client_state) - .map_err(|_| { - Error::invalid_client_state("client must be a tendermint client".to_string()) + .map_err(|_| Error::InvalidClientState { + reason: "client must be a tendermint client".to_string(), })?; if counterparty_client_state.is_frozen() { - return Err(Error::invalid_client_state("client is frozen".to_string())); + return Err(Error::InvalidClientState { + reason: "client is frozen".to_string(), + }); } let self_chain_id = self.chain_id(); if self_chain_id != &counterparty_client_state.chain_id { - return Err(Error::invalid_client_state(format!( - "invalid chain-id. expected: {}, got: {}", - self_chain_id, counterparty_client_state.chain_id - ))); + return Err(Error::InvalidClientState { + reason: format!( + "invalid chain-id. expected: {}, got: {}", + self_chain_id, counterparty_client_state.chain_id + ), + }); } let self_revision_number = self_chain_id.version(); if self_revision_number != counterparty_client_state.latest_height().revision_number() { - return Err(Error::invalid_client_state(format!( - "client is not in the same revision as the chain. expected: {}, got: {}", - self_revision_number, - counterparty_client_state.latest_height().revision_number() - ))); + return Err(Error::InvalidClientState { + reason: format!( + "client is not in the same revision as the chain. expected: {}, got: {}", + self_revision_number, + counterparty_client_state.latest_height().revision_number() + ), + }); } if counterparty_client_state.latest_height() >= self.host_current_height() { - return Err(Error::invalid_client_state(format!( - "client has latest height {} greater than or equal to chain height {}", - counterparty_client_state.latest_height(), - self.host_current_height() - ))); + return Err(Error::InvalidClientState { + reason: format!( + "client has latest height {} greater than or equal to chain height {}", + counterparty_client_state.latest_height(), + self.host_current_height() + ), + }); } if self.proof_specs() != &counterparty_client_state.proof_specs { - return Err(Error::invalid_client_state(format!( - "client has invalid proof specs. expected: {:?}, got: {:?}", - self.proof_specs(), - counterparty_client_state.proof_specs - ))); + return Err(Error::InvalidClientState { + reason: format!( + "client has invalid proof specs. expected: {:?}, got: {:?}", + self.proof_specs(), + counterparty_client_state.proof_specs + ), + }); } let _ = { @@ -66,33 +76,39 @@ pub trait ValidateSelfClientContext { trust_level.numerator(), trust_level.denominator(), ) - .map_err(|_| Error::invalid_client_state("invalid trust level".to_string()))? + .map_err(|_| Error::InvalidClientState { + reason: "invalid trust level".to_string(), + })? }; if self.unbonding_period() != counterparty_client_state.unbonding_period { - return Err(Error::invalid_client_state(format!( - "invalid unbonding period. expected: {:?}, got: {:?}", - self.unbonding_period(), - counterparty_client_state.unbonding_period, - ))); + return Err(Error::InvalidClientState { + reason: format!( + "invalid unbonding period. expected: {:?}, got: {:?}", + self.unbonding_period(), + counterparty_client_state.unbonding_period, + ), + }); } if counterparty_client_state.unbonding_period < counterparty_client_state.trusting_period { - return Err(Error::invalid_client_state(format!( + return Err(Error::InvalidClientState{ reason: format!( "unbonding period must be greater than trusting period. unbonding period ({:?}) < trusting period ({:?})", counterparty_client_state.unbonding_period, counterparty_client_state.trusting_period - ))); + )}); } if !counterparty_client_state.upgrade_path.is_empty() && self.upgrade_path() != counterparty_client_state.upgrade_path { - return Err(Error::invalid_client_state(format!( - "invalid upgrade path. expected: {:?}, got: {:?}", - self.upgrade_path(), - counterparty_client_state.upgrade_path - ))); + return Err(Error::InvalidClientState { + reason: format!( + "invalid upgrade path. expected: {:?}, got: {:?}", + self.upgrade_path(), + counterparty_client_state.upgrade_path + ), + }); } Ok(()) diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index 2d4f3188d..d69b89c71 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -61,7 +61,7 @@ impl TryFrom for IdentifiedConnectionEnd { }; Ok(IdentifiedConnectionEnd { - connection_id: value.id.parse().map_err(Error::invalid_identifier)?, + connection_id: value.id.parse().map_err(Error::InvalidIdentifier)?, connection_end: raw_connection_end.try_into()?, }) } @@ -116,15 +116,15 @@ impl TryFrom for ConnectionEnd { return Ok(ConnectionEnd::default()); } if value.client_id.is_empty() { - return Err(Error::empty_proto_connection_end()); + return Err(Error::EmptyProtoConnectionEnd); } Ok(Self::new( state, - value.client_id.parse().map_err(Error::invalid_identifier)?, + value.client_id.parse().map_err(Error::InvalidIdentifier)?, value .counterparty - .ok_or_else(Error::missing_counterparty)? + .ok_or(Error::MissingCounterparty)? .try_into()?, value .versions @@ -260,16 +260,16 @@ impl TryFrom for Counterparty { .filter(|x| !x.is_empty()) .map(|v| FromStr::from_str(v.as_str())) .transpose() - .map_err(Error::invalid_identifier)?; + .map_err(Error::InvalidIdentifier)?; Ok(Counterparty::new( - value.client_id.parse().map_err(Error::invalid_identifier)?, + value.client_id.parse().map_err(Error::InvalidIdentifier)?, connection_id, value .prefix - .ok_or_else(Error::missing_counterparty)? + .ok_or(Error::MissingCounterparty)? .key_prefix .try_into() - .map_err(|_| Error::ics02_client(ClientError::EmptyPrefix))?, + .map_err(|_| Error::Ics02Client(ClientError::EmptyPrefix))?, )) } } @@ -346,7 +346,7 @@ impl State { 1 => Ok(Self::Init), 2 => Ok(Self::TryOpen), 3 => Ok(Self::Open), - _ => Err(Error::invalid_state(s)), + _ => Err(Error::InvalidState { state: s }), } } @@ -383,7 +383,7 @@ impl TryFrom for State { 1 => Ok(Self::Init), 2 => Ok(Self::TryOpen), 3 => Ok(Self::Open), - _ => Err(Error::invalid_state(value)), + _ => Err(Error::InvalidState { state: value }), } } } diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 1c259d360..926cdc341 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -7,168 +7,88 @@ use crate::signer::SignerError; use crate::Height; use alloc::string::String; -use flex_error::{define_error, DisplayError}; - -define_error! { - #[derive(Debug)] - Error { - Ics02Client - [ DisplayError ] - | _ | { "ics02 client error" }, - - InvalidState - { state: i32 } - | e | { format_args!("connection state is unknown: {}", e.state) }, - - ConnectionExistsAlready - { connection_id: ConnectionId } - | e | { - format_args!("connection exists (was initialized) already: {0}", - e.connection_id) - }, - - ConnectionMismatch - { connection_id: ConnectionId } - | e | { - format_args!("connection end for identifier {0} was never initialized", - e.connection_id) - }, - - InvalidConsensusHeight - { - target_height: Height, - currrent_height: Height - } - | e | { - format_args!("consensus height claimed by the client on the other party is too advanced: {0} (host chain current height: {1})", - e.target_height, e.currrent_height) - }, - - StaleConsensusHeight - { - target_height: Height, - oldest_height: Height - } - | e | { - format_args!("consensus height claimed by the client on the other party has been pruned: {0} (host chain oldest height: {1})", - e.target_height, e.oldest_height) - }, - - InvalidIdentifier - [ ValidationError ] - | _ | { "identifier error" }, - - EmptyProtoConnectionEnd - | _ | { "ConnectionEnd domain object could not be constructed out of empty proto object" }, - - EmptyVersions - | _ | { "empty supported versions" }, - - EmptyFeatures - | _ | { "empty supported features" }, - - NoCommonVersion - | _ | { "no common version" }, - - VersionNotSupported - { - version: Version, - } - | e | { format_args!("version \"{}\" not supported", e.version) }, - - InvalidAddress - | _ | { "invalid address" }, - - MissingProofHeight - | _ | { "missing proof height" }, - - MissingConsensusHeight - | _ | { "missing consensus height" }, - - InvalidProof - [ ProofError ] - | _ | { "invalid connection proof" }, - - VerifyConnectionState - [ DisplayError ] - | _ | { "error verifying connnection state" }, - - Signer - [ SignerError ] - | _ | { "invalid signer" }, - - ConnectionNotFound - { connection_id: ConnectionId } - | e | { - format_args!("no connection was found for the previous connection id provided {0}", - e.connection_id) - }, - - InvalidCounterparty - | _ | { "invalid signer" }, - - ConnectionIdMismatch - { - connection_id: ConnectionId, - counterparty_connection_id: ConnectionId, - } - | e | { - format_args!("counterparty chosen connection id {0} is different than the connection id {1}", - e.connection_id, e.counterparty_connection_id) - }, - - MissingCounterparty - | _ | { "missing counterparty" }, - - - MissingCounterpartyPrefix - | _ | { "missing counterparty prefix" }, - MissingClientState - | _ | { "missing client state" }, - - NullClientProof - | _ | { "client proof must be present" }, - - FrozenClient - { client_id: ClientId } - | e | { - format_args!("the client id does not match any client state: {0}", - e.client_id) - }, - - ConnectionVerificationFailure - | _ | { "the connection proof verification failed" }, - - ConsensusStateVerificationFailure - { height: Height } - [ DisplayError ] - | e | { - format_args!("the consensus proof verification failed (height: {0})", - e.height) - }, - +use displaydoc::Display; + +#[derive(Debug, Display)] +pub enum Error { + /// ics02 client error(`{0}`) + Ics02Client(client_error::Error), + /// connection state is unknown: `{state}` + InvalidState { state: i32 }, + /// connection exists (was initialized) already: `{connection_id}` + ConnectionExistsAlready { connection_id: ConnectionId }, + /// connection end for identifier `{connection_id}` was never initialized + ConnectionMismatch { connection_id: ConnectionId }, + /// consensus height claimed by the client on the other party is too advanced: `{target_height}` (host chain current height: `{current_height}`) + InvalidConsensusHeight { + target_height: Height, + current_height: Height, + }, + /// consensus height claimed by the client on the other party has been pruned: `{target_height}` (host chain oldest height: `{oldest_height}`) + StaleConsensusHeight { + target_height: Height, + oldest_height: Height, + }, + /// identifier error(`{0}`) + InvalidIdentifier(ValidationError), + /// ConnectionEnd domain object could not be constructed out of empty proto object + EmptyProtoConnectionEnd, + /// empty supported versions + EmptyVersions, + /// empty supported features + EmptyFeatures, + /// no common version + NoCommonVersion, + /// version \"`{version}`\" not supported + VersionNotSupported { version: Version }, + /// invalid address + InvalidAddress, + /// missing proof height + MissingProofHeight, + /// missing consensus height + MissingConsensusHeight, + /// invalid connection proof, error(`{0}`) + InvalidProof(ProofError), + /// error verifying connnection state, error(`{0}`) + VerifyConnectionState(client_error::Error), + /// invalid signer, error(`{0}`) + Signer(SignerError), + /// no connection was found for the previous connection id provided `{connection_id}` + ConnectionNotFound { connection_id: ConnectionId }, + /// invalid counterparty + InvalidCounterparty, + /// counterparty chosen connection id `{connection_id}` is different than the connection id `{counterparty_connection_id}` + ConnectionIdMismatch { + connection_id: ConnectionId, + counterparty_connection_id: ConnectionId, + }, + /// missing counterparty + MissingCounterparty, + /// missing counterparty prefix + MissingCounterpartyPrefix, + /// missing client state + MissingClientState, + /// client proof must be present + NullClientProof, + /// the client id does not match any client state: `{client_id}` + FrozenClient { client_id: ClientId }, + /// the connection proof verification failed + ConnectionVerificationFailure, + /// the consensus proof verification failed (height: `{height}`), error(`{client_error}`) + ConsensusStateVerificationFailure { + height: Height, + client_error: client_error::Error, + }, + /// the client state proof verification failed for client id `{client_id}`, error(`{client_error}`) + ClientStateVerificationFailure { // TODO: use more specific error source - ClientStateVerificationFailure - { - client_id: ClientId, - } - [ DisplayError ] - | e | { - format_args!("the client state proof verification failed for client id {0}", - e.client_id) - }, - - ImplementationSpecific - | _ | { "implementation specific error" }, - - InvalidClientState - { - reason: String, - } - | e | { format_args!("invalid client state: {0}", e.reason) }, - - Other - { description: String } - | e| { format_args!("other error: {0}", e.description) }, - } + client_id: ClientId, + client_error: client_error::Error, + }, + /// implementation specific error + ImplementationSpecific, + /// invalid client state: `{reason}` + InvalidClientState { reason: String }, + /// other error: `{description}` + Other { description: String }, } diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs index ebc41ed4c..cca1bba0f 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs @@ -20,10 +20,10 @@ pub(crate) fn process( let mut output = HandlerOutput::builder(); if msg.consensus_height_of_a_on_b > ctx_a.host_current_height()? { - return Err(Error::invalid_consensus_height( - msg.consensus_height_of_a_on_b, - ctx_a.host_current_height()?, - )); + return Err(Error::InvalidConsensusHeight { + target_height: msg.consensus_height_of_a_on_b, + current_height: ctx_a.host_current_height()?, + }); } ctx_a.validate_self_client(msg.client_state_of_a_on_b.clone())?; @@ -32,7 +32,9 @@ pub(crate) fn process( if !(conn_end_on_a.state_matches(&State::Init) && conn_end_on_a.versions().contains(&msg.version)) { - return Err(Error::connection_mismatch(msg.conn_id_on_a)); + return Err(Error::ConnectionMismatch { + connection_id: msg.conn_id_on_a, + }); } let client_id_on_a = conn_end_on_a.client_id(); @@ -41,7 +43,7 @@ pub(crate) fn process( let conn_id_on_b = conn_end_on_a .counterparty() .connection_id() - .ok_or_else(Error::invalid_counterparty)?; + .ok_or(Error::InvalidCounterparty)?; // Proof verification. { @@ -74,7 +76,7 @@ pub(crate) fn process( conn_id_on_b, &expected_conn_end_on_b, ) - .map_err(Error::verify_connection_state)?; + .map_err(Error::VerifyConnectionState)?; } client_state_of_b_on_a @@ -86,8 +88,9 @@ pub(crate) fn process( client_id_on_b, msg.client_state_of_a_on_b, ) - .map_err(|e| { - Error::client_state_verification_failure(conn_end_on_a.client_id().clone(), e) + .map_err(|e| Error::ClientStateVerificationFailure { + client_id: conn_end_on_a.client_id().clone(), + client_error: e, })?; let expected_consensus_state_of_a_on_b = @@ -102,7 +105,10 @@ pub(crate) fn process( msg.consensus_height_of_a_on_b, expected_consensus_state_of_a_on_b.as_ref(), ) - .map_err(|e| Error::consensus_state_verification_failure(msg.proofs_height_on_b, e))?; + .map_err(|e| Error::ConsensusStateVerificationFailure { + height: msg.proofs_height_on_b, + client_error: e, + })?; } // Success @@ -221,10 +227,10 @@ mod tests { msg: ConnectionMsg::ConnectionOpenAck(Box::new(msg_ack.clone())), want_pass: false, match_error: { - let connection_id = conn_id.clone(); - Box::new(move |e| match e.detail() { - error::ErrorDetail::ConnectionNotFound(e) => { - assert_eq!(e.connection_id, connection_id) + let right_connection_id = conn_id.clone(); + Box::new(move |e| match e { + error::Error::ConnectionNotFound { connection_id } => { + assert_eq!(connection_id, right_connection_id) } _ => { panic!("Expected ConnectionNotFound error"); @@ -241,10 +247,10 @@ mod tests { msg: ConnectionMsg::ConnectionOpenAck(Box::new(msg_ack)), want_pass: false, match_error: { - let connection_id = conn_id; - Box::new(move |e| match e.detail() { - error::ErrorDetail::ConnectionMismatch(e) => { - assert_eq!(e.connection_id, connection_id); + let right_connection_id = conn_id; + Box::new(move |e| match e { + error::Error::ConnectionMismatch { connection_id } => { + assert_eq!(connection_id, right_connection_id); } _ => { panic!("Expected ConnectionMismatch error"); diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs index 1e157b8ae..018715c9e 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs @@ -19,14 +19,16 @@ pub(crate) fn process( let conn_end_on_b = ctx_b.connection_end(&msg.conn_id_on_b)?; if !conn_end_on_b.state_matches(&State::TryOpen) { - return Err(Error::connection_mismatch(msg.conn_id_on_b)); + return Err(Error::ConnectionMismatch { + connection_id: msg.conn_id_on_b, + }); } let client_id_on_a = conn_end_on_b.counterparty().client_id(); let client_id_on_b = conn_end_on_b.client_id(); let conn_id_on_a = conn_end_on_b .counterparty() .connection_id() - .ok_or_else(Error::invalid_counterparty)?; + .ok_or(Error::InvalidCounterparty)?; // Verify proofs { @@ -58,7 +60,7 @@ pub(crate) fn process( conn_id_on_a, &expected_conn_end_on_a, ) - .map_err(Error::verify_connection_state)?; + .map_err(Error::VerifyConnectionState)?; } // Success diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs index 6760e202a..91551ca5f 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs @@ -28,7 +28,7 @@ pub(crate) fn process( if ctx_a.get_compatible_versions().contains(&version) { Ok(vec![version]) } else { - Err(Error::version_not_supported(version)) + Err(Error::VersionNotSupported { version }) } } None => Ok(ctx_a.get_compatible_versions()), diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs index 41d984567..6ffd462c5 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs @@ -26,10 +26,10 @@ pub(crate) fn process( if msg.consensus_height_of_b_on_a > ctx_b.host_current_height()? { // Fail if the consensus height is too advanced. - return Err(Error::invalid_consensus_height( - msg.consensus_height_of_b_on_a, - ctx_b.host_current_height()?, - )); + return Err(Error::InvalidConsensusHeight { + target_height: msg.consensus_height_of_b_on_a, + current_height: ctx_b.host_current_height()?, + }); } let version_on_b = @@ -47,7 +47,7 @@ pub(crate) fn process( let conn_id_on_a = conn_end_on_b .counterparty() .connection_id() - .ok_or_else(Error::invalid_counterparty)?; + .ok_or(Error::InvalidCounterparty)?; // Verify proofs { @@ -77,7 +77,7 @@ pub(crate) fn process( conn_id_on_a, &expected_conn_end_on_a, ) - .map_err(Error::verify_connection_state)?; + .map_err(Error::VerifyConnectionState)?; } client_state_of_a_on_b @@ -89,8 +89,9 @@ pub(crate) fn process( client_id_on_a, msg.client_state_of_b_on_a, ) - .map_err(|e| { - Error::client_state_verification_failure(conn_end_on_b.client_id().clone(), e) + .map_err(|e| Error::ClientStateVerificationFailure { + client_id: conn_end_on_b.client_id().clone(), + client_error: e, })?; let expected_consensus_state_of_b_on_a = @@ -105,7 +106,10 @@ pub(crate) fn process( msg.consensus_height_of_b_on_a, expected_consensus_state_of_b_on_a.as_ref(), ) - .map_err(|e| Error::consensus_state_verification_failure(msg.proofs_height_on_a, e))?; + .map_err(|e| Error::ConsensusStateVerificationFailure { + height: msg.proofs_height_on_a, + client_error: e, + })?; } // Success diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs index b929d4da0..d5e5c5f17 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs @@ -61,31 +61,31 @@ impl TryFrom for MsgConnectionOpenAck { conn_id_on_a: msg .connection_id .parse() - .map_err(Error::invalid_identifier)?, + .map_err(Error::InvalidIdentifier)?, conn_id_on_b: msg .counterparty_connection_id .parse() - .map_err(Error::invalid_identifier)?, - client_state_of_a_on_b: msg.client_state.ok_or_else(Error::missing_client_state)?, - version: msg.version.ok_or_else(Error::empty_versions)?.try_into()?, - proof_conn_end_on_b: msg.proof_try.try_into().map_err(Error::invalid_proof)?, + .map_err(Error::InvalidIdentifier)?, + client_state_of_a_on_b: msg.client_state.ok_or(Error::MissingClientState)?, + version: msg.version.ok_or(Error::EmptyVersions)?.try_into()?, + proof_conn_end_on_b: msg.proof_try.try_into().map_err(Error::InvalidProof)?, proof_client_state_of_a_on_b: msg .proof_client .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, proof_consensus_state_of_a_on_b: msg .proof_consensus .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, proofs_height_on_b: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_proof_height)?, + .ok_or(Error::MissingProofHeight)?, consensus_height_of_a_on_b: msg .consensus_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_consensus_height)?, - signer: msg.signer.parse().map_err(Error::signer)?, + .ok_or(Error::MissingConsensusHeight)?, + signer: msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs index a52673e11..533ed79d8 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs @@ -48,13 +48,13 @@ impl TryFrom for MsgConnectionOpenConfirm { conn_id_on_b: msg .connection_id .parse() - .map_err(Error::invalid_identifier)?, - proof_conn_end_on_a: msg.proof_ack.try_into().map_err(Error::invalid_proof)?, + .map_err(Error::InvalidIdentifier)?, + proof_conn_end_on_a: msg.proof_ack.try_into().map_err(Error::InvalidProof)?, proof_height_on_a: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_proof_height)?, - signer: msg.signer.parse().map_err(Error::signer)?, + .ok_or(Error::MissingProofHeight)?, + signer: msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs index a3ae47e50..401ab3b85 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs @@ -46,14 +46,14 @@ impl TryFrom for MsgConnectionOpenInit { fn try_from(msg: RawMsgConnectionOpenInit) -> Result { Ok(Self { - client_id_on_a: msg.client_id.parse().map_err(Error::invalid_identifier)?, + client_id_on_a: msg.client_id.parse().map_err(Error::InvalidIdentifier)?, counterparty: msg .counterparty - .ok_or_else(Error::missing_counterparty)? + .ok_or(Error::MissingCounterparty)? .try_into()?, version: msg.version.map(|version| version.try_into()).transpose()?, delay_period: Duration::from_nanos(msg.delay_period), - signer: msg.signer.parse().map_err(Error::signer)?, + signer: msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs index 3b04ae899..12fb936ec 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs @@ -76,7 +76,7 @@ impl TryFrom for MsgConnectionOpenTry { .collect::, _>>()?; if counterparty_versions.is_empty() { - return Err(Error::empty_versions()); + return Err(Error::EmptyVersions); } // We set the deprecated `previous_connection_id` field so that we can @@ -84,32 +84,32 @@ 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(Error::invalid_identifier)?, - client_state_of_b_on_a: msg.client_state.ok_or_else(Error::missing_client_state)?, + client_id_on_b: msg.client_id.parse().map_err(Error::InvalidIdentifier)?, + client_state_of_b_on_a: msg.client_state.ok_or(Error::MissingClientState)?, counterparty: msg .counterparty - .ok_or_else(Error::missing_counterparty)? + .ok_or(Error::MissingCounterparty)? .try_into()?, versions_on_a: counterparty_versions, - proof_conn_end_on_a: msg.proof_init.try_into().map_err(Error::invalid_proof)?, + proof_conn_end_on_a: msg.proof_init.try_into().map_err(Error::InvalidProof)?, proof_client_state_of_b_on_a: msg .proof_client .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, proof_consensus_state_of_b_on_a: msg .proof_consensus .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, proofs_height_on_a: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_proof_height)?, + .ok_or(Error::MissingProofHeight)?, consensus_height_of_b_on_a: msg .consensus_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_consensus_height)?, + .ok_or(Error::MissingConsensusHeight)?, delay_period: Duration::from_nanos(msg.delay_period), - signer: msg.signer.parse().map_err(Error::signer)?, + signer: msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/version.rs b/crates/ibc/src/core/ics03_connection/version.rs index 4109aade3..b336c0181 100644 --- a/crates/ibc/src/core/ics03_connection/version.rs +++ b/crates/ibc/src/core/ics03_connection/version.rs @@ -32,11 +32,11 @@ impl TryFrom for Version { type Error = Error; fn try_from(value: RawVersion) -> Result { if value.identifier.trim().is_empty() { - return Err(Error::empty_versions()); + return Err(Error::EmptyVersions); } for feature in value.features.iter() { if feature.trim().is_empty() { - return Err(Error::empty_features()); + return Err(Error::EmptyFeatures); } } Ok(Version { @@ -96,7 +96,7 @@ pub fn pick_version( } for feature in c.features.iter() { if feature.trim().is_empty() { - return Err(Error::empty_features()); + return Err(Error::EmptyFeatures); } } intersection.append(&mut vec![s.clone()]); @@ -104,7 +104,7 @@ pub fn pick_version( } intersection.sort_by(|a, b| a.identifier.cmp(&b.identifier)); if intersection.is_empty() { - return Err(Error::no_common_version()); + return Err(Error::NoCommonVersion); } Ok(intersection[0].clone()) } @@ -285,7 +285,7 @@ mod tests { name: "Disjoint versions".to_string(), supported: disjoint().0, counterparty: disjoint().1, - picked: Err(Error::no_common_version()), + picked: Err(Error::NoCommonVersion), want_pass: false, }, ]; diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 080161c60..2b7d9db6d 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -12,14 +12,14 @@ use crate::signer::SignerError; use crate::timestamp::Timestamp; use crate::Height; -use flex_error::{define_error, TraceError}; +use flex_error::{define_error, DisplayError, TraceError}; use ibc_proto::protobuf::Error as TendermintError; define_error! { #[derive(Debug)] Error { Ics03Connection - [ connection_error::Error ] + [ DisplayError ] | _ | { "ics03 connection error" }, Ics05Port diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index 430a48eb8..dbc8e0f13 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -202,10 +202,8 @@ mod tests { error::ErrorDetail::Ics03Connection(e) => { assert_eq!( e.source.to_string(), - ics03_error::ErrorDetail::ConnectionNotFound( - ics03_error::ConnectionNotFoundSubdetail { connection_id } - ) - .to_string() + ics03_error::Error::ConnectionNotFound { connection_id } + .to_string() ); } _ => { @@ -230,13 +228,9 @@ mod tests { error::ErrorDetail::Ics03Connection(e) => { assert_eq!( e.source.to_string(), - ics03_error::ErrorDetail::Ics02Client( - ics03_error::Ics02ClientSubdetail { - source: ics02_error::Error::ClientNotFound { - client_id: ClientId::new(mock_client_type(), 45).unwrap() - } - } - ) + ics03_error::Error::Ics02Client(ics02_error::Error::ClientNotFound { + client_id: ClientId::new(mock_client_type(), 45).unwrap() + }) .to_string() ); } diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 015706ce7..8d77dc480 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -13,7 +13,7 @@ define_error! { | _ | { "ICS02 client error" }, Ics03Connection - [ ics03_connection::error::Error ] + [ TraceError ] | _ | { "ICS03 connection error" }, Ics04Channel diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index 78f16145a..45b7637ba 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -30,7 +30,7 @@ define_error! { | _ | { "ICS02 client error" }, Connection - [ connection_error::Error ] + [ TraceError ] | _ | { "connection error" }, Channel diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index f189f234f..6b4f7fb8c 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -706,7 +706,7 @@ impl ChannelReader for MockContext { fn client_state(&self, client_id: &ClientId) -> Result, Ics04Error> { ClientReader::client_state(self, client_id) - .map_err(|e| Ics04Error::ics03_connection(Ics03Error::ics02_client(e))) + .map_err(|e| Ics04Error::ics03_connection(Ics03Error::Ics02Client(e))) } fn client_consensus_state( @@ -715,7 +715,7 @@ impl ChannelReader for MockContext { height: Height, ) -> Result, Ics04Error> { ClientReader::consensus_state(self, client_id, height) - .map_err(|e| Ics04Error::ics03_connection(Ics03Error::ics02_client(e))) + .map_err(|e| Ics04Error::ics03_connection(Ics03Error::Ics02Client(e))) } fn get_next_sequence_send( @@ -859,7 +859,7 @@ impl ChannelReader for MockContext { fn pending_host_consensus_state(&self) -> Result, Ics04Error> { ClientReader::pending_host_consensus_state(self) - .map_err(|e| Ics04Error::ics03_connection(Ics03Error::ics02_client(e))) + .map_err(|e| Ics04Error::ics03_connection(Ics03Error::Ics02Client(e))) } fn client_update_time( @@ -1090,17 +1090,19 @@ impl ConnectionReader for MockContext { fn connection_end(&self, cid: &ConnectionId) -> Result { match self.ibc_store.lock().unwrap().connections.get(cid) { Some(connection_end) => Ok(connection_end.clone()), - None => Err(Ics03Error::connection_not_found(cid.clone())), + None => Err(Ics03Error::ConnectionNotFound { + connection_id: cid.clone(), + }), } } fn client_state(&self, client_id: &ClientId) -> Result, Ics03Error> { // Forward method call to the Ics2 Client-specific method. - ClientReader::client_state(self, client_id).map_err(Ics03Error::ics02_client) + ClientReader::client_state(self, client_id).map_err(Ics03Error::Ics02Client) } fn decode_client_state(&self, client_state: Any) -> Result, Ics03Error> { - ClientReader::decode_client_state(self, client_state).map_err(Ics03Error::ics02_client) + ClientReader::decode_client_state(self, client_state).map_err(Ics03Error::Ics02Client) } fn host_current_height(&self) -> Result { @@ -1123,11 +1125,11 @@ impl ConnectionReader for MockContext { ) -> Result, Ics03Error> { // Forward method call to the Ics2Client-specific method. self.consensus_state(client_id, height) - .map_err(Ics03Error::ics02_client) + .map_err(Ics03Error::Ics02Client) } fn host_consensus_state(&self, height: Height) -> Result, Ics03Error> { - ClientReader::host_consensus_state(self, height).map_err(Ics03Error::ics02_client) + ClientReader::host_consensus_state(self, height).map_err(Ics03Error::Ics02Client) } fn connection_counter(&self) -> Result { diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index d141358ca..2eb4a4f39 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection; use crate::core::ics24_host::identifier::ClientId; use crate::core::ics26_routing::error::Error as RoutingError; use crate::Height; -use flex_error::define_error; +use flex_error::{define_error, TraceError}; define_error! { Error { @@ -37,7 +37,7 @@ define_error! { | _ | { "transaction processing by modules failed" }, Ics03 - [ ics03_connection::error::Error ] + [ TraceError ] | _ | { "ics03 connection error" } } } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 142829dc5..300648126 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -234,7 +234,7 @@ impl SendPacketReader for DummyTransferModule { fn connection_end(&self, cid: &ConnectionId) -> Result { match self.ibc_store.lock().unwrap().connections.get(cid) { Some(connection_end) => Ok(connection_end.clone()), - None => Err(Ics03Error::connection_not_found(cid.clone())), + None => Err(Ics03Error::ConnectionNotFound { connection_id: cid.clone() }), } .map_err(Error::ics03_connection) } @@ -253,7 +253,7 @@ impl SendPacketReader for DummyTransferModule { client_id: client_id.clone(), }), } - .map_err(|e| Error::ics03_connection(Ics03Error::ics02_client(e))) + .map_err(|e| Error::ics03_connection(Ics03Error::Ics02Client(e))) } fn client_consensus_state( @@ -274,7 +274,7 @@ impl SendPacketReader for DummyTransferModule { height, }), } - .map_err(|e| Error::ics03_connection(Ics03Error::ics02_client(e))) + .map_err(|e| Error::ics03_connection(Ics03Error::Ics02Client(e))) } fn get_next_sequence_send( From a2e7cbec6cb49c586d9fdc4289c43111a94c6a5b Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 23 Nov 2022 23:54:31 +0800 Subject: [PATCH 06/43] Redefine Ics04Error by displaydoc --- .../ibc/src/applications/transfer/context.rs | 4 +- crates/ibc/src/core/ics04_channel/channel.rs | 30 +- crates/ibc/src/core/ics04_channel/error.rs | 504 ++++++------------ .../ics04_channel/events/packet_attributes.rs | 4 +- crates/ibc/src/core/ics04_channel/handler.rs | 20 +- .../ics04_channel/handler/acknowledgement.rs | 30 +- .../handler/chan_close_confirm.rs | 37 +- .../ics04_channel/handler/chan_close_init.rs | 22 +- .../ics04_channel/handler/chan_open_ack.rs | 39 +- .../handler/chan_open_confirm.rs | 41 +- .../ics04_channel/handler/chan_open_init.rs | 12 +- .../ics04_channel/handler/chan_open_try.rs | 51 +- .../core/ics04_channel/handler/recv_packet.rs | 51 +- .../core/ics04_channel/handler/send_packet.rs | 34 +- .../src/core/ics04_channel/handler/timeout.rs | 40 +- .../ics04_channel/handler/timeout_on_close.rs | 32 +- .../src/core/ics04_channel/handler/verify.rs | 42 +- .../handler/write_acknowledgement.rs | 25 +- crates/ibc/src/core/ics04_channel/msgs.rs | 12 +- .../ics04_channel/msgs/acknowledgement.rs | 13 +- .../ics04_channel/msgs/chan_close_confirm.rs | 13 +- .../ics04_channel/msgs/chan_close_init.rs | 6 +- .../core/ics04_channel/msgs/chan_open_ack.rs | 12 +- .../ics04_channel/msgs/chan_open_confirm.rs | 10 +- .../core/ics04_channel/msgs/chan_open_init.rs | 9 +- .../core/ics04_channel/msgs/chan_open_try.rs | 12 +- .../core/ics04_channel/msgs/recv_packet.rs | 13 +- .../src/core/ics04_channel/msgs/timeout.rs | 13 +- .../ics04_channel/msgs/timeout_on_close.rs | 15 +- crates/ibc/src/core/ics04_channel/packet.rs | 21 +- crates/ibc/src/core/ics26_routing/error.rs | 2 +- crates/ibc/src/events.rs | 2 +- crates/ibc/src/mock/context.rs | 66 +-- crates/ibc/src/test_utils.rs | 26 +- 34 files changed, 557 insertions(+), 706 deletions(-) diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index ef5c6b4ea..c30b1b0ad 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -357,7 +357,9 @@ pub(crate) mod test { output: &mut HandlerOutputBuilder<()>, msg: MsgTransfer, ) -> Result<(), Error> { - send_transfer(ctx, output, msg).map_err(|e: Ics20Error| Error::app_module(e.to_string())) + send_transfer(ctx, output, msg).map_err(|e: Ics20Error| Error::AppModule { + description: e.to_string(), + }) } fn get_defaults() -> ( diff --git a/crates/ibc/src/core/ics04_channel/channel.rs b/crates/ibc/src/core/ics04_channel/channel.rs index 032161521..8d6f730c7 100644 --- a/crates/ibc/src/core/ics04_channel/channel.rs +++ b/crates/ibc/src/core/ics04_channel/channel.rs @@ -47,8 +47,8 @@ impl TryFrom for IdentifiedChannelEnd { }; Ok(IdentifiedChannelEnd { - port_id: value.port_id.parse().map_err(Error::identifier)?, - channel_id: value.channel_id.parse().map_err(Error::identifier)?, + port_id: value.port_id.parse().map_err(Error::Identifier)?, + channel_id: value.channel_id.parse().map_err(Error::Identifier)?, channel_end: raw_channel_end.try_into()?, }) } @@ -121,7 +121,7 @@ impl TryFrom for ChannelEnd { // Assemble the 'remote' attribute of the Channel, which represents the Counterparty. let remote = value .counterparty - .ok_or_else(Error::missing_counterparty)? + .ok_or(Error::MissingCounterparty)? .try_into()?; // Parse each item in connection_hops into a ConnectionId. @@ -130,7 +130,7 @@ impl TryFrom for ChannelEnd { .into_iter() .map(|conn_id| ConnectionId::from_str(conn_id.as_str())) .collect::, _>>() - .map_err(Error::identifier)?; + .map_err(Error::Identifier)?; let version = value.version.into(); @@ -218,10 +218,10 @@ impl ChannelEnd { pub fn validate_basic(&self) -> Result<(), Error> { if self.connection_hops.len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - self.connection_hops.len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: self.connection_hops.len(), + }); } self.counterparty().validate_basic() } @@ -304,9 +304,9 @@ impl TryFrom for Counterparty { .filter(|x| !x.is_empty()) .map(|v| FromStr::from_str(v.as_str())) .transpose() - .map_err(Error::identifier)?; + .map_err(Error::Identifier)?; Ok(Counterparty::new( - value.port_id.parse().map_err(Error::identifier)?, + value.port_id.parse().map_err(Error::Identifier)?, channel_id, )) } @@ -359,7 +359,9 @@ impl Order { 0 => Ok(Self::None), 1 => Ok(Self::Unordered), 2 => Ok(Self::Ordered), - _ => Err(Error::unknown_order_type(nr.to_string())), + _ => Err(Error::UnknownOrderType { + type_id: nr.to_string(), + }), } } } @@ -372,7 +374,9 @@ impl FromStr for Order { "uninitialized" => Ok(Self::None), "unordered" => Ok(Self::Unordered), "ordered" => Ok(Self::Ordered), - _ => Err(Error::unknown_order_type(s.to_string())), + _ => Err(Error::UnknownOrderType { + type_id: s.to_string(), + }), } } } @@ -406,7 +410,7 @@ impl State { 2 => Ok(Self::TryOpen), 3 => Ok(Self::Open), 4 => Ok(Self::Closed), - _ => Err(Error::unknown_state(s)), + _ => Err(Error::UnknownState { state: s }), } } diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 2b7d9db6d..44f64beab 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -12,354 +12,164 @@ use crate::signer::SignerError; use crate::timestamp::Timestamp; use crate::Height; -use flex_error::{define_error, DisplayError, TraceError}; +use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintError; -define_error! { - #[derive(Debug)] - Error { - Ics03Connection - [ DisplayError ] - | _ | { "ics03 connection error" }, - - Ics05Port - [ port_error::Error ] - | _ | { "ics05 port error" }, - - UnknownState - { state: i32 } - | e | { format_args!("channel state unknown: {}", e.state) }, - - Identifier - [ ValidationError ] - | _ | { "identifier error" }, - - UnknownOrderType - { type_id: String } - | e | { format_args!("channel order type unknown: {}", e.type_id) }, - - InvalidConnectionHopsLength - { expected: usize, actual: usize } - | e | { - format_args!( - "invalid connection hops length: expected {0}; actual {1}", - e.expected, e.actual) - }, - - InvalidPacketCounterparty - { port_id: PortId, channel_id: ChannelId } - | e | { - format_args!( - "packet destination port {} and channel {} doesn't match the counterparty's port/channel", - e.port_id, e.channel_id) - }, - - InvalidVersion - [ TraceError ] - | _ | { "invalid version" }, - - Signer - [ SignerError ] - | _ | { "invalid signer address" }, - - InvalidProof - [ ProofError ] - | _ | { "invalid proof" }, - - MissingHeight - | _ | { "invalid proof: missing height" }, - - MissingNextRecvSeq - { port_id: PortId, channel_id: ChannelId } - | e | { - format_args!("Missing sequence number for receiving packets on port {0} and channel {1}", - e.port_id, - e.channel_id) - }, - - ZeroPacketSequence - | _ | { "packet sequence cannot be 0" }, - - ZeroPacketData - | _ | { "packet data bytes cannot be empty" }, - - NonUtf8PacketData - | _ | { "packet data bytes must be valid UTF-8 (this restriction will be lifted in the future)" }, - - InvalidTimeoutHeight - | _ | { "invalid timeout height for the packet" }, - - InvalidPacket - | _ | { "invalid packet" }, - - MissingPacket - | _ | { "there is no packet in this message" }, - - MissingChannelId - | _ | { "missing channel id" }, - - MissingCounterparty - | _ | { "missing counterparty" }, - - NoCommonVersion - | _ | { "no commong version" }, - - MissingChannel - | _ | { "missing channel end" }, - - InvalidVersionLengthConnection - | _ | { "single version must be negociated on connection before opening channel" }, - - ChannelFeatureNotSuportedByConnection - | _ | { "the channel ordering is not supported by connection" }, - - ChannelNotFound - { port_id: PortId, channel_id: ChannelId } - | e | { - format_args!( - "the channel end ({0}, {1}) does not exist", - e.port_id, e.channel_id) - }, - - ChannelMismatch - { channel_id: ChannelId } - | e | { - format_args!( - "a different channel exists (was initialized) already for the same channel identifier {0}", - e.channel_id) - }, - - ConnectionNotOpen - { connection_id: ConnectionId } - | e | { - format_args!( - "the associated connection {0} is not OPEN", - e.connection_id) - }, - - UndefinedConnectionCounterparty - { connection_id: ConnectionId } - | e | { - format_args!( - "Undefined counterparty connection for {0}", - e.connection_id) - }, - - PacketVerificationFailed - { sequence: Sequence } - [ TraceError ] - | e | { - format_args!( - "Verification fails for the packet with the sequence number {0}", - e.sequence) - }, - - VerifyChannelFailed - [ TraceError ] - | _ | { - "Error verifying channel state" - }, - - InvalidAcknowledgement - | _ | { "Acknowledgment cannot be empty" }, - - AcknowledgementExists - { sequence: Sequence } - | e | { - format_args!( - "Packet acknowledgement exists for the packet with the sequence {0}", - e.sequence) - }, - - MissingNextSendSeq - { port_id: PortId, channel_id: ChannelId } - | e | { - format_args!("Missing sequence number for sending packets on port {0} and channel {1}", - e.port_id, - e.channel_id) - }, - - InvalidStringAsSequence - { value: String } - [ TraceError ] - | e | { - format_args!( - "String {0} cannot be converted to packet sequence", - e.value) - }, - - InvalidPacketSequence - { - given_sequence: Sequence, - next_sequence: Sequence - } - | e | { - format_args!( - "Invalid packet sequence {0} ≠ next send sequence {1}", - e.given_sequence, e.next_sequence) - }, - - LowPacketHeight - { - chain_height: Height, - timeout_height: TimeoutHeight - } - | e | { - format_args!( - "Receiving chain block height {0} >= packet timeout height {1}", - e.chain_height, e.timeout_height) - }, - - PacketTimeoutHeightNotReached - { - timeout_height: TimeoutHeight, - chain_height: Height, - } - | e | { - format_args!( - "Packet timeout height {0} > chain height {1}", - e.timeout_height, e.chain_height) - }, - - PacketTimeoutTimestampNotReached - { - timeout_timestamp: Timestamp, - chain_timestamp: Timestamp, - } - | e | { - format_args!( - "Packet timeout timestamp {0} > chain timestamp {1}", - e.timeout_timestamp, e.chain_timestamp) - }, - - LowPacketTimestamp - | _ | { "Receiving chain block timestamp >= packet timeout timestamp" }, - - InvalidPacketTimestamp - [ crate::timestamp::ParseTimestampError ] - | _ | { "Invalid packet timeout timestamp value" }, - - ErrorInvalidConsensusState - | _ | { "Invalid timestamp in consensus state; timestamp must be a positive value" }, - - FrozenClient - { client_id: ClientId } - | e | { - format_args!( - "Client with id {0} is frozen", - e.client_id) - }, - - InvalidCounterpartyChannelId - | _ | { "Invalid channel id in counterparty" }, - - InvalidChannelState - { channel_id: ChannelId, state: State } - | e | { - format_args!( - "Channel {0} should not be state {1}", - e.channel_id, e.state) - }, - - ChannelClosed - { channel_id: ChannelId } - | e | { - format_args!( - "Channel {0} is Closed", - e.channel_id) - }, - - ChanOpenAckProofVerification - | _ | { "Handshake proof verification fails at ChannelOpenAck" }, - - PacketCommitmentNotFound - { sequence: Sequence } - | e | { - format_args!( - "Commitment for the packet {0} not found", - e.sequence) - }, - - IncorrectPacketCommitment - { sequence: Sequence } - | e | { - format_args!( - "The stored commitment of the packet {0} is incorrect", - e.sequence) - }, - - PacketReceiptNotFound - { sequence: Sequence } - | e | { - format_args!( - "Receipt for the packet {0} not found", - e.sequence) - }, - - PacketAcknowledgementNotFound - { sequence: Sequence } - | e | { - format_args!( - "Acknowledgment for the packet {0} not found", - e.sequence) - }, - - MissingNextAckSeq - { port_id: PortId, channel_id: ChannelId } - | e | { - format_args!("Missing sequence number for ack packets on port {0} and channel {1}", - e.port_id, - e.channel_id) - }, - - ProcessedTimeNotFound - { - client_id: ClientId, - height: Height, - } - | e | { - format_args!( - "Processed time for the client {0} at height {1} not found", - e.client_id, e.height) - }, - - ProcessedHeightNotFound - { - client_id: ClientId, - height: Height, - } - | e | { - format_args!( - "Processed height for the client {0} at height {1} not found", - e.client_id, e.height) - }, - - RouteNotFound - | _ | { "route not found" }, - - ImplementationSpecific - | _ | { "implementation specific error" }, - - AppModule - { description: String } - | e | { - format_args!( - "application module error: {0}", - e.description) - }, - - AbciConversionFailed - { abci_event: String } - | e | { format_args!("Failed to convert abci event to IbcEvent: {}", e.abci_event)}, - - Other - { description: String } - | e| { format_args!("other error: {0}", e.description) }, - } +#[derive(Debug, Display)] +pub enum Error { + /// ics03 connection error(`{0}`) + Ics03Connection(connection_error::Error), + /// ics05 port error(`{0}`) + Ics05Port(port_error::Error), + /// channel state unknown: `{state}` + UnknownState { state: i32 }, + /// identifier error(`{0}`) + Identifier(ValidationError), + /// channel order type unknown: `{type_id}` + UnknownOrderType { type_id: String }, + /// invalid connection hops length: expected `{expected}`; actual `{actual}` + InvalidConnectionHopsLength { expected: usize, actual: usize }, + /// packet destination port `{port_id}` and channel `{channel_id}` doesn't match the counterparty's port/channel + InvalidPacketCounterparty { + port_id: PortId, + channel_id: ChannelId, + }, + /// invalid version, error(`{0}`) + InvalidVersion(TendermintError), + /// invalid signer address, error(`{0}`) + Signer(SignerError), + /// invalid proof, error(`{0}`) + InvalidProof(ProofError), + /// invalid proof: missing height + MissingHeight, + /// Missing sequence number for receiving packets on port `{port_id}` and channel `{channel_id}` + MissingNextRecvSeq { + port_id: PortId, + channel_id: ChannelId, + }, + /// packet sequence cannot be 0 + ZeroPacketSequence, + /// packet data bytes cannot be empty + ZeroPacketData, + /// packet data bytes must be valid UTF-8 (this restriction will be lifted in the future) + NonUtf8PacketData, + /// invalid timeout height for the packet + InvalidTimeoutHeight, + /// invalid packet + InvalidPacket, + /// there is no packet in this message + MissingPacket, + /// missing channel id + MissingChannelId, + /// missing counterparty + MissingCounterparty, + /// no commong version + NoCommonVersion, + /// missing channel end + MissingChannel, + /// single version must be negociated on connection before opening channel + InvalidVersionLengthConnection, + /// the channel ordering is not supported by connection + ChannelFeatureNotSuportedByConnection, + /// the channel end (`{port_id}`, `{channel_id}`) does not exist + ChannelNotFound { + port_id: PortId, + channel_id: ChannelId, + }, + /// a different channel exists (was initialized) already for the same channel identifier `{channel_id}` + ChannelMismatch { channel_id: ChannelId }, + /// the associated connection `{connection_id}` is not OPEN + ConnectionNotOpen { connection_id: ConnectionId }, + /// Undefined counterparty connection for `{connection_id}` + UndefinedConnectionCounterparty { connection_id: ConnectionId }, + /// Verification fails for the packet with the sequence number `{sequence}`, error(`{ics02_error}`) + PacketVerificationFailed { + sequence: Sequence, + ics02_error: client_error::Error, + }, + /// Error verifying channel state, error(`{0}`) + VerifyChannelFailed(client_error::Error), + /// Acknowledgment cannot be empty + InvalidAcknowledgement, + /// Packet acknowledgement exists for the packet with the sequence `{sequence}` + AcknowledgementExists { sequence: Sequence }, + /// Missing sequence number for sending packets on port `{port_id}` and channel `{channel_id}` + MissingNextSendSeq { + port_id: PortId, + channel_id: ChannelId, + }, + /// String `{value}` cannot be converted to packet sequence, error(`{error}`) + InvalidStringAsSequence { + value: String, + error: core::num::ParseIntError, + }, + /// Invalid packet sequence `{given_sequence}` ≠ next send sequence `{next_sequence}` + InvalidPacketSequence { + given_sequence: Sequence, + next_sequence: Sequence, + }, + /// Receiving chain block height `{chain_height}` >= packet timeout height `{timeout_height}` + LowPacketHeight { + chain_height: Height, + timeout_height: TimeoutHeight, + }, + /// Packet timeout height `{timeout_height}` > chain height `{chain_height}` + PacketTimeoutHeightNotReached { + timeout_height: TimeoutHeight, + chain_height: Height, + }, + /// Packet timeout timestamp `{timeout_timestamp}` > chain timestamp `{chain_timestamp}` + PacketTimeoutTimestampNotReached { + timeout_timestamp: Timestamp, + chain_timestamp: Timestamp, + }, + /// Receiving chain block timestamp >= packet timeout timestamp + LowPacketTimestamp, + /// Invalid packet timeout timestamp value, error(`{0}`) + InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), + /// Invalid timestamp in consensus state; timestamp must be a positive value + ErrorInvalidConsensusState, + /// Client with id `{client_id}` is frozen + FrozenClient { client_id: ClientId }, + /// Invalid channel id in counterparty + InvalidCounterpartyChannelId, + /// Channel `{channel_id}` should not be state `{state}` + InvalidChannelState { channel_id: ChannelId, state: State }, + /// Channel `{channel_id}` is Closed + ChannelClosed { channel_id: ChannelId }, + /// Handshake proof verification fails at ChannelOpenAck + ChanOpenAckProofVerification, + /// Commitment for the packet `{sequence}` not found + PacketCommitmentNotFound { sequence: Sequence }, + /// The stored commitment of the packet `{sequence}` is incorrect + IncorrectPacketCommitment { sequence: Sequence }, + /// Receipt for the packet `{sequence}` not found + PacketReceiptNotFound { sequence: Sequence }, + /// Acknowledgment for the packet `{sequence}` not found + PacketAcknowledgementNotFound { sequence: Sequence }, + /// Missing sequence number for ack packets on port `{port_id}` and channel `{channel_id}` + MissingNextAckSeq { + port_id: PortId, + channel_id: ChannelId, + }, + /// Processed time for the client `{client_id}` at height `{height}` not found + ProcessedTimeNotFound { client_id: ClientId, height: Height }, + /// Processed height for the client `{client_id}` at height `{height}` not found + ProcessedHeightNotFound { client_id: ClientId, height: Height }, + /// route not found + RouteNotFound, + /// implementation specific error + ImplementationSpecific, + /// application module error: `{description}` + AppModule { description: String }, + /// Failed to convert abci event to IbcEvent: `{abci_event}` + AbciConversionFailed { abci_event: String }, + /// other error: `{description}` + Other { description: String }, } -impl Error { - pub fn chan_open_confirm_proof_verification(e: Error) -> Error { - e.add_trace(&"Handshake proof verification fails at ChannelOpenConfirm") - } -} +// impl Error { +// pub fn chan_open_confirm_proof_verification(e: Error) -> Error { +// e.add_trace(&"Handshake proof verification fails at ChannelOpenConfirm") +// } +// } diff --git a/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs b/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs index 8e2251aa0..607521b2a 100644 --- a/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs +++ b/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs @@ -44,7 +44,7 @@ impl TryFrom for Vec { let tags = vec![ ( PKT_DATA_ATTRIBUTE_KEY, - str::from_utf8(&attr.packet_data).map_err(|_| Error::non_utf8_packet_data())?, + str::from_utf8(&attr.packet_data).map_err(|_| Error::NonUtf8PacketData)?, ) .into(), ( @@ -183,7 +183,7 @@ impl TryFrom for Vec { // it. It has been deprecated in ibc-go. It will be removed // in the future. str::from_utf8(attr.acknowledgement.as_bytes()) - .map_err(|_| Error::non_utf8_packet_data())?, + .map_err(|_| Error::NonUtf8PacketData)?, ) .into(), ( diff --git a/crates/ibc/src/core/ics04_channel/handler.rs b/crates/ibc/src/core/ics04_channel/handler.rs index bdbcb8e23..7f41ae145 100644 --- a/crates/ibc/src/core/ics04_channel/handler.rs +++ b/crates/ibc/src/core/ics04_channel/handler.rs @@ -73,7 +73,7 @@ where if ctx.router().has_route(&module_id) { Ok(module_id) } else { - Err(Error::route_not_found()) + Err(Error::RouteNotFound) } } @@ -111,7 +111,7 @@ where let cb = ctx .router_mut() .get_route_mut(module_id) - .ok_or_else(Error::route_not_found)?; + .ok_or(Error::RouteNotFound)?; match msg { ChannelMsg::ChannelOpenInit(msg) => { @@ -229,22 +229,22 @@ where let module_id = match msg { PacketMsg::RecvPacket(msg) => ctx .lookup_module_by_port(&msg.packet.destination_port) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, PacketMsg::AckPacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, PacketMsg::TimeoutPacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, PacketMsg::TimeoutOnClosePacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, }; if ctx.router().has_route(&module_id) { Ok(module_id) } else { - Err(Error::route_not_found()) + Err(Error::RouteNotFound) } } @@ -300,17 +300,17 @@ fn do_packet_callback( let cb = ctx .router_mut() .get_route_mut(module_id) - .ok_or_else(Error::route_not_found)?; + .ok_or(Error::RouteNotFound)?; match msg { PacketMsg::RecvPacket(msg) => { let result = cb.on_recv_packet(module_output, &msg.packet, &msg.signer); match result { OnRecvPacketAck::Nil(write_fn) => { - write_fn(cb.as_any_mut()).map_err(Error::app_module) + write_fn(cb.as_any_mut()).map_err(|e| Error::AppModule { description: e }) } OnRecvPacketAck::Successful(ack, write_fn) => { - write_fn(cb.as_any_mut()).map_err(Error::app_module)?; + write_fn(cb.as_any_mut()).map_err(|e| Error::AppModule { description: e })?; process_write_ack(ctx, msg.packet.clone(), ack.as_ref(), core_output) } diff --git a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs index 717a85122..174fc3819 100644 --- a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs @@ -30,7 +30,9 @@ pub fn process( let source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; if !source_channel_end.state_matches(&State::Open) { - return Err(Error::channel_closed(packet.source_channel.clone())); + return Err(Error::ChannelClosed { + channel_id: packet.source_channel.clone(), + }); } let counterparty = Counterparty::new( @@ -39,19 +41,19 @@ pub fn process( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::invalid_packet_counterparty( - packet.destination_port.clone(), - packet.destination_channel.clone(), - )); + return Err(Error::InvalidPacketCounterparty { + port_id: packet.destination_port.clone(), + channel_id: packet.destination_channel.clone(), + }); } let source_connection_id = &source_channel_end.connection_hops()[0]; let connection_end = ctx.connection_end(source_connection_id)?; if !connection_end.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - source_channel_end.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: source_channel_end.connection_hops()[0].clone(), + }); } // Verify packet commitment @@ -65,7 +67,9 @@ pub fn process( packet.timeout_timestamp, ) { - return Err(Error::incorrect_packet_commitment(packet.sequence)); + return Err(Error::IncorrectPacketCommitment { + sequence: packet.sequence, + }); } // Verify the acknowledgement proof @@ -83,10 +87,10 @@ pub fn process( ctx.get_next_sequence_ack(&packet.source_port, &packet.source_channel)?; if packet.sequence != next_seq_ack { - return Err(Error::invalid_packet_sequence( - packet.sequence, - next_seq_ack, - )); + return Err(Error::InvalidPacketSequence { + given_sequence: packet.sequence, + next_sequence: next_seq_ack, + }); } PacketResult::Ack(AckPacketResult { diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs b/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs index bd99e5070..381da4be3 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs @@ -20,23 +20,25 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be closed. if chan_end_on_b.state_matches(&State::Closed) { - return Err(Error::channel_closed(msg.chan_id_on_b.clone())); + return Err(Error::ChannelClosed { + channel_id: msg.chan_id_on_b.clone(), + }); } // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_b.connection_hops().len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - chan_end_on_b.connection_hops().len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: chan_end_on_b.connection_hops().len(), + }); } let conn_end_on_b = ctx_b.connection_end(&chan_end_on_b.connection_hops()[0])?; if !conn_end_on_b.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - chan_end_on_b.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: chan_end_on_b.connection_hops()[0].clone(), + }); } // Verify proofs @@ -50,17 +52,18 @@ pub(crate) fn process( let chan_id_on_a = chan_end_on_b .counterparty() .channel_id() - .ok_or_else(Error::invalid_counterparty_channel_id)?; - let conn_id_on_a = conn_end_on_b - .counterparty() - .connection_id() - .ok_or_else(|| { - Error::undefined_connection_counterparty(chan_end_on_b.connection_hops()[0].clone()) - })?; + .ok_or(Error::InvalidCounterpartyChannelId)?; + let conn_id_on_a = conn_end_on_b.counterparty().connection_id().ok_or( + Error::UndefinedConnectionCounterparty { + connection_id: chan_end_on_b.connection_hops()[0].clone(), + }, + )?; // The client must not be frozen. if client_state_of_a_on_b.is_frozen() { - return Err(Error::frozen_client(client_id_on_b)); + return Err(Error::FrozenClient { + client_id: client_id_on_b, + }); } let expected_chan_end_on_a = ChannelEnd::new( @@ -83,7 +86,7 @@ pub(crate) fn process( chan_id_on_a, &expected_chan_end_on_a, ) - .map_err(Error::verify_channel_failed)?; + .map_err(Error::VerifyChannelFailed)?; } output.log("success: channel close confirm"); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs b/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs index 829fd2b86..22c7b1f4b 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs @@ -18,26 +18,26 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be closed. if chan_end_on_a.state_matches(&State::Closed) { - return Err(Error::invalid_channel_state( - msg.chan_id_on_a.clone(), - chan_end_on_a.state, - )); + return Err(Error::InvalidChannelState { + channel_id: msg.chan_id_on_a.clone(), + state: chan_end_on_a.state, + }); } // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_a.connection_hops().len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - chan_end_on_a.connection_hops().len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: chan_end_on_a.connection_hops().len(), + }); } let conn_end_on_a = ctx_a.connection_end(&chan_end_on_a.connection_hops()[0])?; if !conn_end_on_a.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - chan_end_on_a.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: chan_end_on_a.connection_hops()[0].clone(), + }); } output.log("success: channel close init"); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs index e1b4fc36f..140f3a043 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs @@ -20,27 +20,27 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be ack. if !chan_end_on_a.state_matches(&State::Init) { - return Err(Error::invalid_channel_state( - msg.chan_id_on_a.clone(), - chan_end_on_a.state, - )); + return Err(Error::InvalidChannelState { + channel_id: msg.chan_id_on_a.clone(), + state: chan_end_on_a.state, + }); } // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_a.connection_hops().len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - chan_end_on_a.connection_hops().len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: chan_end_on_a.connection_hops().len(), + }); } let conn_end_on_a = ctx_a.connection_end(&chan_end_on_a.connection_hops()[0])?; if !conn_end_on_a.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - chan_end_on_a.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: chan_end_on_a.connection_hops()[0].clone(), + }); } // Verify proofs @@ -51,16 +51,17 @@ pub(crate) fn process( ctx_a.client_consensus_state(&client_id_on_a, msg.proof_height_on_b)?; let prefix_on_b = conn_end_on_a.counterparty().prefix(); let port_id_on_b = &chan_end_on_a.counterparty().port_id; - let conn_id_on_b = conn_end_on_a - .counterparty() - .connection_id() - .ok_or_else(|| { - Error::undefined_connection_counterparty(chan_end_on_a.connection_hops()[0].clone()) - })?; + let conn_id_on_b = conn_end_on_a.counterparty().connection_id().ok_or( + Error::UndefinedConnectionCounterparty { + connection_id: chan_end_on_a.connection_hops()[0].clone(), + }, + )?; // The client must not be frozen. if client_state_of_b_on_a.is_frozen() { - return Err(Error::frozen_client(client_id_on_a)); + return Err(Error::FrozenClient { + client_id: client_id_on_a, + }); } let expected_chan_end_on_b = ChannelEnd::new( @@ -85,7 +86,7 @@ pub(crate) fn process( &msg.chan_id_on_b, &expected_chan_end_on_b, ) - .map_err(Error::verify_channel_failed)?; + .map_err(Error::VerifyChannelFailed)?; } output.log("success: channel open ack"); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs index 4f7901d35..905ef1609 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs @@ -20,26 +20,26 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be confirmed. if !chan_end_on_b.state_matches(&State::TryOpen) { - return Err(Error::invalid_channel_state( - msg.chan_id_on_b.clone(), - chan_end_on_b.state, - )); + return Err(Error::InvalidChannelState { + channel_id: msg.chan_id_on_b.clone(), + state: chan_end_on_b.state, + }); } // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_b.connection_hops().len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - chan_end_on_b.connection_hops().len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: chan_end_on_b.connection_hops().len(), + }); } let conn_end_on_b = ctx_b.connection_end(&chan_end_on_b.connection_hops()[0])?; if !conn_end_on_b.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - chan_end_on_b.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: chan_end_on_b.connection_hops()[0].clone(), + }); } // Verify proofs @@ -53,17 +53,18 @@ pub(crate) fn process( let chan_id_on_a = chan_end_on_b .counterparty() .channel_id() - .ok_or_else(Error::invalid_counterparty_channel_id)?; - let conn_id_on_a = conn_end_on_b - .counterparty() - .connection_id() - .ok_or_else(|| { - Error::undefined_connection_counterparty(chan_end_on_b.connection_hops()[0].clone()) - })?; + .ok_or(Error::InvalidCounterpartyChannelId)?; + let conn_id_on_a = conn_end_on_b.counterparty().connection_id().ok_or( + Error::UndefinedConnectionCounterparty { + connection_id: chan_end_on_b.connection_hops()[0].clone(), + }, + )?; // The client must not be frozen. if client_state_of_a_on_b.is_frozen() { - return Err(Error::frozen_client(client_id_on_b)); + return Err(Error::FrozenClient { + client_id: client_id_on_b, + }); } let expected_chan_end_on_a = ChannelEnd::new( @@ -86,7 +87,7 @@ pub(crate) fn process( chan_id_on_a, &expected_chan_end_on_a, ) - .map_err(Error::verify_channel_failed)?; + .map_err(Error::VerifyChannelFailed)?; } output.log("success: channel open confirm "); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs index 3868f6bd9..9a97e2d54 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs @@ -17,10 +17,10 @@ pub(crate) fn process( let mut output = HandlerOutput::builder(); if msg.chan_end_on_a.connection_hops().len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - msg.chan_end_on_a.connection_hops().len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: msg.chan_end_on_a.connection_hops().len(), + }); } // An IBC connection running on the local (host) chain should exist. @@ -28,12 +28,12 @@ pub(crate) fn process( let conn_version = match conn_end_on_a.versions() { [version] => version, - _ => return Err(Error::invalid_version_length_connection()), + _ => return Err(Error::InvalidVersionLengthConnection), }; let channel_feature = msg.chan_end_on_a.ordering().to_string(); if !conn_version.is_supported_feature(channel_feature) { - return Err(Error::channel_feature_not_suported_by_connection()); + return Err(Error::ChannelFeatureNotSuportedByConnection); } let chan_end_on_a = ChannelEnd::new( diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index dbc8e0f13..f775c493a 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -20,27 +20,27 @@ pub(crate) fn process( // An IBC connection running on the local (host) chain should exist. if msg.chan_end_on_b.connection_hops().len() != 1 { - return Err(Error::invalid_connection_hops_length( - 1, - msg.chan_end_on_b.connection_hops().len(), - )); + return Err(Error::InvalidConnectionHopsLength { + expected: 1, + actual: msg.chan_end_on_b.connection_hops().len(), + }); } let conn_end_on_b = ctx_b.connection_end(&msg.chan_end_on_b.connection_hops()[0])?; if !conn_end_on_b.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - msg.chan_end_on_b.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: msg.chan_end_on_b.connection_hops()[0].clone(), + }); } let conn_version = match conn_end_on_b.versions() { [version] => version, - _ => return Err(Error::invalid_version_length_connection()), + _ => return Err(Error::InvalidVersionLengthConnection), }; let channel_feature = msg.chan_end_on_b.ordering().to_string(); if !conn_version.is_supported_feature(channel_feature) { - return Err(Error::channel_feature_not_suported_by_connection()); + return Err(Error::ChannelFeatureNotSuportedByConnection); } // Verify proofs @@ -55,19 +55,18 @@ pub(crate) fn process( .chan_end_on_b .counterparty() .channel_id() - .ok_or_else(Error::invalid_counterparty_channel_id)?; - let conn_id_on_a = conn_end_on_b - .counterparty() - .connection_id() - .ok_or_else(|| { - Error::undefined_connection_counterparty( - msg.chan_end_on_b.connection_hops()[0].clone(), - ) - })?; + .ok_or(Error::InvalidCounterpartyChannelId)?; + let conn_id_on_a = conn_end_on_b.counterparty().connection_id().ok_or( + Error::UndefinedConnectionCounterparty { + connection_id: msg.chan_end_on_b.connection_hops()[0].clone(), + }, + )?; // The client must not be frozen. if client_state_of_a_on_b.is_frozen() { - return Err(Error::frozen_client(client_id_on_b)); + return Err(Error::FrozenClient { + client_id: client_id_on_b, + }); } let expected_chan_end_on_a = ChannelEnd::new( @@ -90,7 +89,7 @@ pub(crate) fn process( chan_id_on_a, &expected_chan_end_on_a, ) - .map_err(Error::verify_channel_failed)?; + .map_err(Error::VerifyChannelFailed)?; } let chan_end_on_b = ChannelEnd::new( @@ -152,7 +151,7 @@ mod tests { ctx: MockContext, msg: ChannelMsg, want_pass: bool, - match_error: Box, + match_error: Box, } // Some general-purpose variable to parametrize the messages and the context. @@ -199,9 +198,9 @@ mod tests { match_error: { let connection_id = msg.chan_end_on_b.connection_hops()[0].clone(); Box::new(move |e| match e { - error::ErrorDetail::Ics03Connection(e) => { + error::Error::Ics03Connection(e) => { assert_eq!( - e.source.to_string(), + e.to_string(), ics03_error::Error::ConnectionNotFound { connection_id } .to_string() ); @@ -225,9 +224,9 @@ mod tests { msg: ChannelMsg::ChannelOpenTry(msg.clone()), want_pass: false, match_error: Box::new(|e| match e { - error::ErrorDetail::Ics03Connection(e) => { + error::Error::Ics03Connection(e) => { assert_eq!( - e.source.to_string(), + e.to_string(), ics03_error::Error::Ics02Client(ics02_error::Error::ClientNotFound { client_id: ClientId::new(mock_client_type(), 45).unwrap() }) @@ -294,7 +293,7 @@ mod tests { e, ); - (test.match_error)(e.0); + (test.match_error)(e); } } } diff --git a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs index 95a33009d..856f29201 100644 --- a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs @@ -40,10 +40,10 @@ pub fn process( ctx.channel_end(&packet.destination_port, &packet.destination_channel)?; if !dest_channel_end.state_matches(&State::Open) { - return Err(Error::invalid_channel_state( - packet.source_channel.clone(), - dest_channel_end.state, - )); + return Err(Error::InvalidChannelState { + channel_id: packet.source_channel.clone(), + state: dest_channel_end.state, + }); } let counterparty = Counterparty::new( @@ -52,32 +52,32 @@ pub fn process( ); if !dest_channel_end.counterparty_matches(&counterparty) { - return Err(Error::invalid_packet_counterparty( - packet.source_port.clone(), - packet.source_channel.clone(), - )); + return Err(Error::InvalidPacketCounterparty { + port_id: packet.source_port.clone(), + channel_id: packet.source_channel.clone(), + }); } let dest_connection_id = &dest_channel_end.connection_hops()[0]; let connection_end = ctx.connection_end(dest_connection_id)?; if !connection_end.state_matches(&ConnectionState::Open) { - return Err(Error::connection_not_open( - dest_channel_end.connection_hops()[0].clone(), - )); + return Err(Error::ConnectionNotOpen { + connection_id: dest_channel_end.connection_hops()[0].clone(), + }); } let latest_height = ChannelReader::host_height(ctx)?; if packet.timeout_height.has_expired(latest_height) { - return Err(Error::low_packet_height( - latest_height, - packet.timeout_height, - )); + return Err(Error::LowPacketHeight { + chain_height: latest_height, + timeout_height: packet.timeout_height, + }); } let latest_timestamp = ChannelReader::host_timestamp(ctx)?; if let Expiry::Expired = latest_timestamp.check_expiry(&packet.timeout_timestamp) { - return Err(Error::low_packet_timestamp()); + return Err(Error::LowPacketTimestamp); } verify_packet_recv_proofs( @@ -101,10 +101,10 @@ pub fn process( return Ok(output.with_result(PacketResult::Recv(RecvPacketResult::NoOp))); } else if packet.sequence != next_seq_recv { - return Err(Error::invalid_packet_sequence( - packet.sequence, - next_seq_recv, - )); + return Err(Error::InvalidPacketSequence { + given_sequence: packet.sequence, + next_sequence: next_seq_recv, + }); } PacketResult::Recv(RecvPacketResult::Ordered { @@ -130,10 +130,11 @@ pub fn process( return Ok(output.with_result(PacketResult::Recv(RecvPacketResult::NoOp))); } Err(e) - if e.detail().to_string() - == Error::packet_receipt_not_found(packet.sequence) - .detail() - .to_string() => + if e.to_string() + == Error::PacketReceiptNotFound { + sequence: packet.sequence, + } + .to_string() => { // store a receipt that does not contain any data PacketResult::Recv(RecvPacketResult::Unordered { @@ -143,7 +144,7 @@ pub fn process( receipt: Receipt::Ok, }) } - Err(_) => return Err(Error::implementation_specific()), + Err(_) => return Err(Error::ImplementationSpecific), } }; diff --git a/crates/ibc/src/core/ics04_channel/handler/send_packet.rs b/crates/ibc/src/core/ics04_channel/handler/send_packet.rs index 9b610dc8f..cf144caaa 100644 --- a/crates/ibc/src/core/ics04_channel/handler/send_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/send_packet.rs @@ -28,7 +28,9 @@ pub fn send_packet( let source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; if source_channel_end.state_matches(&State::Closed) { - return Err(Error::channel_closed(packet.source_channel)); + return Err(Error::ChannelClosed { + channel_id: packet.source_channel, + }); } let counterparty = Counterparty::new( @@ -37,10 +39,10 @@ pub fn send_packet( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::invalid_packet_counterparty( - packet.destination_port.clone(), - packet.destination_channel, - )); + return Err(Error::InvalidPacketCounterparty { + port_id: packet.destination_port.clone(), + channel_id: packet.destination_channel, + }); } let source_connection_id = &source_channel_end.connection_hops()[0]; let connection_end = ctx.connection_end(source_connection_id)?; @@ -51,32 +53,34 @@ pub fn send_packet( // prevent accidental sends with clients that cannot be updated if client_state.is_frozen() { - return Err(Error::frozen_client(connection_end.client_id().clone())); + return Err(Error::FrozenClient { + client_id: connection_end.client_id().clone(), + }); } let latest_height = client_state.latest_height(); if packet.timeout_height.has_expired(latest_height) { - return Err(Error::low_packet_height( - latest_height, - packet.timeout_height, - )); + return Err(Error::LowPacketHeight { + chain_height: latest_height, + timeout_height: packet.timeout_height, + }); } let consensus_state = ctx.client_consensus_state(&client_id, latest_height)?; let latest_timestamp = consensus_state.timestamp(); let packet_timestamp = packet.timeout_timestamp; if let Expiry::Expired = latest_timestamp.check_expiry(&packet_timestamp) { - return Err(Error::low_packet_timestamp()); + return Err(Error::LowPacketTimestamp); } let next_seq_send = ctx.get_next_sequence_send(&packet.source_port, &packet.source_channel)?; if packet.sequence != next_seq_send { - return Err(Error::invalid_packet_sequence( - packet.sequence, - next_seq_send, - )); + return Err(Error::InvalidPacketSequence { + given_sequence: packet.sequence, + next_sequence: next_seq_send, + }); } output.log("success: packet send "); diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout.rs b/crates/ibc/src/core/ics04_channel/handler/timeout.rs index eab4b8d12..59788243d 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout.rs @@ -37,7 +37,9 @@ pub fn process( let mut source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; if !source_channel_end.state_matches(&State::Open) { - return Err(Error::channel_closed(packet.source_channel.clone())); + return Err(Error::ChannelClosed { + channel_id: packet.source_channel.clone(), + }); } let counterparty = Counterparty::new( @@ -46,10 +48,10 @@ pub fn process( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::invalid_packet_counterparty( - packet.destination_port.clone(), - packet.destination_channel.clone(), - )); + return Err(Error::InvalidPacketCounterparty { + port_id: packet.destination_port.clone(), + channel_id: packet.destination_channel.clone(), + }); } let source_connection_id = source_channel_end.connection_hops()[0].clone(); @@ -61,10 +63,10 @@ pub fn process( let proof_height = msg.proofs.height(); if packet.timeout_height.has_expired(proof_height) { - return Err(Error::packet_timeout_height_not_reached( - packet.timeout_height, - proof_height, - )); + return Err(Error::PacketTimeoutHeightNotReached { + timeout_height: packet.timeout_height, + chain_height: proof_height, + }); } let consensus_state = ctx.client_consensus_state(&client_id, proof_height)?; @@ -73,10 +75,10 @@ pub fn process( let packet_timestamp = packet.timeout_timestamp; if let Expiry::Expired = packet_timestamp.check_expiry(&proof_timestamp) { - return Err(Error::packet_timeout_timestamp_not_reached( - packet_timestamp, - proof_timestamp, - )); + return Err(Error::PacketTimeoutTimestampNotReached { + timeout_timestamp: packet_timestamp, + chain_timestamp: proof_timestamp, + }); } //verify packet commitment @@ -89,15 +91,17 @@ pub fn process( packet.timeout_timestamp, ); if packet_commitment != expected_commitment { - return Err(Error::incorrect_packet_commitment(packet.sequence)); + return Err(Error::IncorrectPacketCommitment { + sequence: packet.sequence, + }); } let result = if source_channel_end.order_matches(&Order::Ordered) { if packet.sequence < msg.next_sequence_recv { - return Err(Error::invalid_packet_sequence( - packet.sequence, - msg.next_sequence_recv, - )); + return Err(Error::InvalidPacketSequence { + given_sequence: packet.sequence, + next_sequence: msg.next_sequence_recv, + }); } verify_next_sequence_recv( ctx, diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs b/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs index 1ae91ec70..753f69d03 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs @@ -31,10 +31,10 @@ pub fn process( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::invalid_packet_counterparty( - packet.destination_port.clone(), - packet.destination_channel.clone(), - )); + return Err(Error::InvalidPacketCounterparty { + port_id: packet.destination_port.clone(), + channel_id: packet.destination_channel.clone(), + }); } let source_connection_id = source_channel_end.connection_hops()[0].clone(); @@ -50,7 +50,9 @@ pub fn process( packet.timeout_timestamp, ); if packet_commitment != expected_commitment { - return Err(Error::incorrect_packet_commitment(packet.sequence)); + return Err(Error::IncorrectPacketCommitment { + sequence: packet.sequence, + }); } let expected_counterparty = Counterparty::new( @@ -59,9 +61,11 @@ pub fn process( ); let counterparty = connection_end.counterparty(); - let ccid = counterparty.connection_id().ok_or_else(|| { - Error::undefined_connection_counterparty(source_channel_end.connection_hops()[0].clone()) - })?; + let ccid = counterparty + .connection_id() + .ok_or(Error::UndefinedConnectionCounterparty { + connection_id: source_channel_end.connection_hops()[0].clone(), + })?; let expected_connection_hops = vec![ccid.clone()]; @@ -76,10 +80,10 @@ pub fn process( // The message's proofs have the channel proof as `other_proof` let proof_close = match msg.proofs.other_proof() { Some(p) => p.clone(), - None => return Err(Error::invalid_proof(ProofError::empty_proof())), + None => return Err(Error::InvalidProof(ProofError::empty_proof())), }; let proofs = Proofs::new(proof_close, None, None, None, msg.proofs.height()) - .map_err(Error::invalid_proof)?; + .map_err(Error::InvalidProof)?; verify_channel_proofs( ctx, msg.proofs.height(), @@ -91,10 +95,10 @@ pub fn process( let result = if source_channel_end.order_matches(&Order::Ordered) { if packet.sequence < msg.next_sequence_recv { - return Err(Error::invalid_packet_sequence( - packet.sequence, - msg.next_sequence_recv, - )); + return Err(Error::InvalidPacketSequence { + given_sequence: packet.sequence, + next_sequence: msg.next_sequence_recv, + }); } verify_next_sequence_recv( ctx, diff --git a/crates/ibc/src/core/ics04_channel/handler/verify.rs b/crates/ibc/src/core/ics04_channel/handler/verify.rs index 07a07d8ae..10667d130 100644 --- a/crates/ibc/src/core/ics04_channel/handler/verify.rs +++ b/crates/ibc/src/core/ics04_channel/handler/verify.rs @@ -24,7 +24,7 @@ pub fn verify_channel_proofs( // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::frozen_client(client_id)); + return Err(Error::FrozenClient { client_id }); } let consensus_state = ctx.client_consensus_state(&client_id, proofs.height())?; @@ -41,10 +41,10 @@ pub fn verify_channel_proofs( channel_end .counterparty() .channel_id() - .ok_or_else(Error::invalid_counterparty_channel_id)?, + .ok_or(Error::InvalidCounterpartyChannelId)?, expected_chan, ) - .map_err(Error::verify_channel_failed) + .map_err(Error::VerifyChannelFailed) } /// Entry point for verifying all proofs bundled in a ICS4 packet recv. message. @@ -60,7 +60,9 @@ pub fn verify_packet_recv_proofs( // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::frozen_client(client_id.clone())); + return Err(Error::FrozenClient { + client_id: client_id.clone(), + }); } let consensus_state = ctx.client_consensus_state(client_id, proofs.height())?; @@ -84,7 +86,10 @@ pub fn verify_packet_recv_proofs( packet.sequence, commitment, ) - .map_err(|e| Error::packet_verification_failed(packet.sequence, e))?; + .map_err(|e| Error::PacketVerificationFailed { + sequence: packet.sequence, + ics02_error: e, + })?; Ok(()) } @@ -103,7 +108,9 @@ pub fn verify_packet_acknowledgement_proofs( // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::frozen_client(client_id.clone())); + return Err(Error::FrozenClient { + client_id: client_id.clone(), + }); } let consensus_state = ctx.client_consensus_state(client_id, proofs.height())?; @@ -123,7 +130,10 @@ pub fn verify_packet_acknowledgement_proofs( packet.sequence, ack_commitment, ) - .map_err(|e| Error::packet_verification_failed(packet.sequence, e))?; + .map_err(|e| Error::PacketVerificationFailed { + sequence: packet.sequence, + ics02_error: e, + })?; Ok(()) } @@ -142,7 +152,9 @@ pub fn verify_next_sequence_recv( // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::frozen_client(client_id.clone())); + return Err(Error::FrozenClient { + client_id: client_id.clone(), + }); } let consensus_state = ctx.client_consensus_state(client_id, proofs.height())?; @@ -159,7 +171,10 @@ pub fn verify_next_sequence_recv( &packet.destination_channel, packet.sequence, ) - .map_err(|e| Error::packet_verification_failed(seq, e))?; + .map_err(|e| Error::PacketVerificationFailed { + sequence: seq, + ics02_error: e, + })?; Ok(()) } @@ -176,7 +191,9 @@ pub fn verify_packet_receipt_absence( // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::frozen_client(client_id.clone())); + return Err(Error::FrozenClient { + client_id: client_id.clone(), + }); } let consensus_state = ctx.client_consensus_state(client_id, proofs.height())?; @@ -193,7 +210,10 @@ pub fn verify_packet_receipt_absence( &packet.destination_channel, packet.sequence, ) - .map_err(|e| Error::packet_verification_failed(packet.sequence, e))?; + .map_err(|e| Error::PacketVerificationFailed { + sequence: packet.sequence, + ics02_error: e, + })?; Ok(()) } diff --git a/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs index ecd8b770f..bd6b77d92 100644 --- a/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs @@ -30,10 +30,10 @@ pub fn process( ctx.channel_end(&packet.destination_port, &packet.destination_channel)?; if !dest_channel_end.state_matches(&State::Open) { - return Err(Error::invalid_channel_state( - packet.source_channel, - dest_channel_end.state, - )); + return Err(Error::InvalidChannelState { + channel_id: packet.source_channel, + state: dest_channel_end.state, + }); } // NOTE: IBC app modules might have written the acknowledgement synchronously on @@ -44,17 +44,22 @@ pub fn process( &packet.destination_channel, packet.sequence, ) { - Ok(_) => return Err(Error::acknowledgement_exists(packet.sequence)), + Ok(_) => { + return Err(Error::AcknowledgementExists { + sequence: packet.sequence, + }) + } Err(e) - if e.detail().to_string() - == Error::packet_acknowledgement_not_found(packet.sequence) - .detail() - .to_string() => {} + if e.to_string() + == Error::PacketAcknowledgementNotFound { + sequence: packet.sequence, + } + .to_string() => {} Err(e) => return Err(e), } if ack.is_empty() { - return Err(Error::invalid_acknowledgement()); + return Err(Error::InvalidAcknowledgement); } let result = PacketResult::WriteAck(WriteAckPacketResult { diff --git a/crates/ibc/src/core/ics04_channel/msgs.rs b/crates/ibc/src/core/ics04_channel/msgs.rs index 54bbbfd61..4a8a68c6e 100644 --- a/crates/ibc/src/core/ics04_channel/msgs.rs +++ b/crates/ibc/src/core/ics04_channel/msgs.rs @@ -46,22 +46,22 @@ impl ChannelMsg { let module_id = match self { ChannelMsg::ChannelOpenInit(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, ChannelMsg::ChannelOpenTry(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, ChannelMsg::ChannelOpenAck(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, ChannelMsg::ChannelOpenConfirm(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, ChannelMsg::ChannelCloseInit(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, ChannelMsg::ChannelCloseConfirm(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::ics05_port)?, + .map_err(Error::Ics05Port)?, }; Ok(module_id) } diff --git a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs index 3259d48b1..f78965cd4 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs @@ -91,24 +91,21 @@ impl TryFrom for MsgAcknowledgement { raw_msg .proof_acked .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, None, None, None, raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, + .ok_or(Error::MissingHeight)?, ) - .map_err(Error::invalid_proof)?; + .map_err(Error::InvalidProof)?; Ok(MsgAcknowledgement { - packet: raw_msg - .packet - .ok_or_else(Error::missing_packet)? - .try_into()?, + packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, acknowledgement: raw_msg.acknowledgement.into(), - signer: raw_msg.signer.parse().map_err(Error::signer)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, proofs, }) } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs index 4b7b25daa..076f2a271 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs @@ -64,17 +64,14 @@ impl TryFrom for MsgChannelCloseConfirm { fn try_from(raw_msg: RawMsgChannelCloseConfirm) -> Result { Ok(MsgChannelCloseConfirm { - port_id_on_b: raw_msg.port_id.parse().map_err(Error::identifier)?, - chan_id_on_b: raw_msg.channel_id.parse().map_err(Error::identifier)?, - proof_chan_end_on_a: raw_msg - .proof_init - .try_into() - .map_err(Error::invalid_proof)?, + port_id_on_b: raw_msg.port_id.parse().map_err(Error::Identifier)?, + chan_id_on_b: raw_msg.channel_id.parse().map_err(Error::Identifier)?, + proof_chan_end_on_a: raw_msg.proof_init.try_into().map_err(Error::InvalidProof)?, proof_height_on_a: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, - signer: raw_msg.signer.parse().map_err(Error::signer)?, + .ok_or(Error::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs index b447d1b58..a23b27a5d 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs @@ -52,9 +52,9 @@ impl TryFrom for MsgChannelCloseInit { fn try_from(raw_msg: RawMsgChannelCloseInit) -> Result { Ok(MsgChannelCloseInit { - port_id_on_a: raw_msg.port_id.parse().map_err(Error::identifier)?, - chan_id_on_a: raw_msg.channel_id.parse().map_err(Error::identifier)?, - signer: raw_msg.signer.parse().map_err(Error::signer)?, + port_id_on_a: raw_msg.port_id.parse().map_err(Error::Identifier)?, + chan_id_on_a: raw_msg.channel_id.parse().map_err(Error::Identifier)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs index 703e5504b..c9c0a2e33 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs @@ -68,19 +68,19 @@ impl TryFrom for MsgChannelOpenAck { fn try_from(raw_msg: RawMsgChannelOpenAck) -> Result { Ok(MsgChannelOpenAck { - port_id_on_a: raw_msg.port_id.parse().map_err(Error::identifier)?, - chan_id_on_a: raw_msg.channel_id.parse().map_err(Error::identifier)?, + port_id_on_a: raw_msg.port_id.parse().map_err(Error::Identifier)?, + chan_id_on_a: raw_msg.channel_id.parse().map_err(Error::Identifier)?, chan_id_on_b: raw_msg .counterparty_channel_id .parse() - .map_err(Error::identifier)?, + .map_err(Error::Identifier)?, version_on_b: raw_msg.counterparty_version.into(), - proof_chan_end_on_b: raw_msg.proof_try.try_into().map_err(Error::invalid_proof)?, + proof_chan_end_on_b: raw_msg.proof_try.try_into().map_err(Error::InvalidProof)?, proof_height_on_b: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, - signer: raw_msg.signer.parse().map_err(Error::signer)?, + .ok_or(Error::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs index 9e2e7ef63..588ca3036 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs @@ -62,14 +62,14 @@ impl TryFrom for MsgChannelOpenConfirm { fn try_from(raw_msg: RawMsgChannelOpenConfirm) -> Result { Ok(MsgChannelOpenConfirm { - port_id_on_b: raw_msg.port_id.parse().map_err(Error::identifier)?, - chan_id_on_b: raw_msg.channel_id.parse().map_err(Error::identifier)?, - proof_chan_end_on_a: raw_msg.proof_ack.try_into().map_err(Error::invalid_proof)?, + port_id_on_b: raw_msg.port_id.parse().map_err(Error::Identifier)?, + chan_id_on_b: raw_msg.channel_id.parse().map_err(Error::Identifier)?, + proof_chan_end_on_a: raw_msg.proof_ack.try_into().map_err(Error::InvalidProof)?, proof_height_on_a: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, - signer: raw_msg.signer.parse().map_err(Error::signer)?, + .ok_or(Error::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs index 77e16382e..1954b7664 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs @@ -51,12 +51,9 @@ impl TryFrom for MsgChannelOpenInit { fn try_from(raw_msg: RawMsgChannelOpenInit) -> Result { Ok(MsgChannelOpenInit { - port_id_on_a: raw_msg.port_id.parse().map_err(Error::identifier)?, - chan_end_on_a: raw_msg - .channel - .ok_or_else(Error::missing_channel)? - .try_into()?, - signer: raw_msg.signer.parse().map_err(Error::signer)?, + port_id_on_a: raw_msg.port_id.parse().map_err(Error::Identifier)?, + chan_end_on_a: raw_msg.channel.ok_or(Error::MissingChannel)?.try_into()?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs index dd1bcb9a7..cba984767 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs @@ -81,26 +81,26 @@ impl TryFrom for MsgChannelOpenTry { fn try_from(raw_msg: RawMsgChannelOpenTry) -> Result { #[allow(deprecated)] let msg = MsgChannelOpenTry { - port_id_on_b: raw_msg.port_id.parse().map_err(ChannelError::identifier)?, + port_id_on_b: raw_msg.port_id.parse().map_err(ChannelError::Identifier)?, previous_channel_id: raw_msg.previous_channel_id, chan_end_on_b: raw_msg .channel - .ok_or_else(ChannelError::missing_channel)? + .ok_or(ChannelError::MissingChannel)? .try_into()?, version_on_a: raw_msg.counterparty_version.into(), proof_chan_end_on_a: raw_msg .proof_init .try_into() - .map_err(ChannelError::invalid_proof)?, + .map_err(ChannelError::InvalidProof)?, proof_height_on_a: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(ChannelError::missing_height)?, - signer: raw_msg.signer.parse().map_err(ChannelError::signer)?, + .ok_or(ChannelError::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(ChannelError::Signer)?, }; msg.validate_basic() - .map_err(|_| ChannelError::invalid_counterparty_channel_id())?; + .map_err(|_| ChannelError::InvalidCounterpartyChannelId)?; Ok(msg) } diff --git a/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs b/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs index 274ffa3bb..1e79b4834 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs @@ -55,24 +55,21 @@ impl TryFrom for MsgRecvPacket { raw_msg .proof_commitment .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, None, None, None, raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, + .ok_or(Error::MissingHeight)?, ) - .map_err(Error::invalid_proof)?; + .map_err(Error::InvalidProof)?; Ok(MsgRecvPacket { - packet: raw_msg - .packet - .ok_or_else(Error::missing_packet)? - .try_into()?, + packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, proofs, - signer: raw_msg.signer.parse().map_err(Error::signer)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs index 58d5761e9..099a2aac6 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs @@ -62,26 +62,23 @@ impl TryFrom for MsgTimeout { raw_msg .proof_unreceived .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, None, None, None, raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, + .ok_or(Error::MissingHeight)?, ) - .map_err(Error::invalid_proof)?; + .map_err(Error::InvalidProof)?; // TODO: Domain type verification for the next sequence: this should probably be > 0. Ok(MsgTimeout { - packet: raw_msg - .packet - .ok_or_else(Error::missing_packet)? - .try_into()?, + packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, next_sequence_recv: Sequence::from(raw_msg.next_sequence_recv), - signer: raw_msg.signer.parse().map_err(Error::signer)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, proofs, }) } diff --git a/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs b/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs index 82b10928b..fe0335345 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs @@ -61,31 +61,28 @@ impl TryFrom for MsgTimeoutOnClose { raw_msg .proof_unreceived .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, None, None, Some( raw_msg .proof_close .try_into() - .map_err(Error::invalid_proof)?, + .map_err(Error::InvalidProof)?, ), raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or_else(Error::missing_height)?, + .ok_or(Error::MissingHeight)?, ) - .map_err(Error::invalid_proof)?; + .map_err(Error::InvalidProof)?; // TODO: Domain type verification for the next sequence: this should probably be > 0. Ok(MsgTimeoutOnClose { - packet: raw_msg - .packet - .ok_or_else(Error::missing_packet)? - .try_into()?, + packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, next_sequence_recv: Sequence::from(raw_msg.next_sequence_recv), - signer: raw_msg.signer.parse().map_err(Error::signer)?, + signer: raw_msg.signer.parse().map_err(Error::Signer)?, proofs, }) } diff --git a/crates/ibc/src/core/ics04_channel/packet.rs b/crates/ibc/src/core/ics04_channel/packet.rs index 585564caa..25b68443a 100644 --- a/crates/ibc/src/core/ics04_channel/packet.rs +++ b/crates/ibc/src/core/ics04_channel/packet.rs @@ -63,7 +63,10 @@ impl FromStr for Sequence { fn from_str(s: &str) -> Result { Ok(Self::from(s.parse::().map_err(|e| { - Error::invalid_string_as_sequence(s.to_string(), e) + Error::InvalidStringAsSequence { + value: s.to_string(), + error: e, + } })?)) } } @@ -195,7 +198,7 @@ impl TryFrom for Packet { fn try_from(raw_pkt: RawPacket) -> Result { if Sequence::from(raw_pkt.sequence).is_zero() { - return Err(Error::zero_packet_sequence()); + return Err(Error::ZeroPacketSequence); } // Note: ibc-go currently (July 2022) incorrectly treats the timeout @@ -209,27 +212,27 @@ impl TryFrom for Packet { let packet_timeout_height: TimeoutHeight = raw_pkt .timeout_height .try_into() - .map_err(|_| Error::invalid_timeout_height())?; + .map_err(|_| Error::InvalidTimeoutHeight)?; if raw_pkt.data.is_empty() { - return Err(Error::zero_packet_data()); + return Err(Error::ZeroPacketData); } let timeout_timestamp = Timestamp::from_nanoseconds(raw_pkt.timeout_timestamp) - .map_err(Error::invalid_packet_timestamp)?; + .map_err(Error::InvalidPacketTimestamp)?; Ok(Packet { sequence: Sequence::from(raw_pkt.sequence), - source_port: raw_pkt.source_port.parse().map_err(Error::identifier)?, - source_channel: raw_pkt.source_channel.parse().map_err(Error::identifier)?, + source_port: raw_pkt.source_port.parse().map_err(Error::Identifier)?, + source_channel: raw_pkt.source_channel.parse().map_err(Error::Identifier)?, destination_port: raw_pkt .destination_port .parse() - .map_err(Error::identifier)?, + .map_err(Error::Identifier)?, destination_channel: raw_pkt .destination_channel .parse() - .map_err(Error::identifier)?, + .map_err(Error::Identifier)?, data: raw_pkt.data, timeout_height: packet_timeout_height, timeout_timestamp, diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 8d77dc480..c9fd2789a 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -17,7 +17,7 @@ define_error! { | _ | { "ICS03 connection error" }, Ics04Channel - [ ics04_channel::error::Error ] + [ TraceError ] | _ | { "ICS04 channel error" }, UnknownMessageTypeUrl diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index 45b7637ba..32a683707 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -34,7 +34,7 @@ define_error! { | _ | { "connection error" }, Channel - [ channel_error::Error ] + [ TraceError ] | _ | { "channel error" }, Timestamp diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 6b4f7fb8c..1113c2609 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -683,15 +683,15 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(channel_end) => Ok(channel_end.clone()), - None => Err(Ics04Error::channel_not_found( - port_id.clone(), - channel_id.clone(), - )), + None => Err(Ics04Error::ChannelNotFound { + port_id: port_id.clone(), + channel_id: channel_id.clone(), + }), } } fn connection_end(&self, cid: &ConnectionId) -> Result { - ConnectionReader::connection_end(self, cid).map_err(Ics04Error::ics03_connection) + ConnectionReader::connection_end(self, cid).map_err(Ics04Error::Ics03Connection) } fn connection_channels( @@ -700,13 +700,13 @@ impl ChannelReader for MockContext { ) -> Result, Ics04Error> { match self.ibc_store.lock().unwrap().connection_channels.get(cid) { Some(pcid) => Ok(pcid.clone()), - None => Err(Ics04Error::missing_channel()), + None => Err(Ics04Error::MissingChannel), } } fn client_state(&self, client_id: &ClientId) -> Result, Ics04Error> { ClientReader::client_state(self, client_id) - .map_err(|e| Ics04Error::ics03_connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Ics02Client(e))) } fn client_consensus_state( @@ -715,7 +715,7 @@ impl ChannelReader for MockContext { height: Height, ) -> Result, Ics04Error> { ClientReader::consensus_state(self, client_id, height) - .map_err(|e| Ics04Error::ics03_connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Ics02Client(e))) } fn get_next_sequence_send( @@ -732,10 +732,10 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Ics04Error::missing_next_send_seq( - port_id.clone(), - channel_id.clone(), - )), + None => Err(Ics04Error::MissingNextSendSeq { + port_id: port_id.clone(), + channel_id: channel_id.clone(), + }), } } @@ -753,10 +753,10 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Ics04Error::missing_next_recv_seq( - port_id.clone(), - channel_id.clone(), - )), + None => Err(Ics04Error::MissingNextRecvSeq { + port_id: port_id.clone(), + channel_id: channel_id.clone(), + }), } } @@ -774,10 +774,10 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Ics04Error::missing_next_ack_seq( - port_id.clone(), - channel_id.clone(), - )), + None => Err(Ics04Error::MissingNextAckSeq { + port_id: port_id.clone(), + channel_id: channel_id.clone(), + }), } } @@ -797,7 +797,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(&seq)) { Some(commitment) => Ok(commitment.clone()), - None => Err(Ics04Error::packet_commitment_not_found(seq)), + None => Err(Ics04Error::PacketCommitmentNotFound { sequence: seq }), } } @@ -817,7 +817,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(&seq)) { Some(receipt) => Ok(receipt.clone()), - None => Err(Ics04Error::packet_receipt_not_found(seq)), + None => Err(Ics04Error::PacketReceiptNotFound { sequence: seq }), } } @@ -837,7 +837,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(&seq)) { Some(ack) => Ok(ack.clone()), - None => Err(Ics04Error::packet_acknowledgement_not_found(seq)), + None => Err(Ics04Error::PacketAcknowledgementNotFound { sequence: seq }), } } @@ -850,16 +850,18 @@ impl ChannelReader for MockContext { } fn host_timestamp(&self) -> Result { - ClientReader::host_timestamp(self).map_err(|e| Ics04Error::other(e.to_string())) + ClientReader::host_timestamp(self).map_err(|e| Ics04Error::Other { + description: e.to_string(), + }) } fn host_consensus_state(&self, height: Height) -> Result, Ics04Error> { - ConnectionReader::host_consensus_state(self, height).map_err(Ics04Error::ics03_connection) + ConnectionReader::host_consensus_state(self, height).map_err(Ics04Error::Ics03Connection) } fn pending_host_consensus_state(&self) -> Result, Ics04Error> { ClientReader::pending_host_consensus_state(self) - .map_err(|e| Ics04Error::ics03_connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Ics02Client(e))) } fn client_update_time( @@ -875,10 +877,10 @@ impl ChannelReader for MockContext { .get(&(client_id.clone(), height)) { Some(time) => Ok(*time), - None => Err(Ics04Error::processed_time_not_found( - client_id.clone(), + None => Err(Ics04Error::ProcessedTimeNotFound { + client_id: client_id.clone(), height, - )), + }), } } @@ -895,10 +897,10 @@ impl ChannelReader for MockContext { .get(&(client_id.clone(), height)) { Some(height) => Ok(*height), - None => Err(Ics04Error::processed_height_not_found( - client_id.clone(), + None => Err(Ics04Error::ProcessedHeightNotFound { + client_id: client_id.clone(), height, - )), + }), } } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 300648126..116582a1c 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -224,19 +224,21 @@ impl SendPacketReader for DummyTransferModule { .and_then(|map| map.get(channel_id)) { Some(channel_end) => Ok(channel_end.clone()), - None => Err(Error::channel_not_found( - port_id.clone(), - channel_id.clone(), - )), + None => Err(Error::ChannelNotFound { + port_id: port_id.clone(), + channel_id: channel_id.clone(), + }), } } fn connection_end(&self, cid: &ConnectionId) -> Result { match self.ibc_store.lock().unwrap().connections.get(cid) { Some(connection_end) => Ok(connection_end.clone()), - None => Err(Ics03Error::ConnectionNotFound { connection_id: cid.clone() }), + None => Err(Ics03Error::ConnectionNotFound { + connection_id: cid.clone(), + }), } - .map_err(Error::ics03_connection) + .map_err(Error::Ics03Connection) } fn client_state(&self, client_id: &ClientId) -> Result, Error> { @@ -253,7 +255,7 @@ impl SendPacketReader for DummyTransferModule { client_id: client_id.clone(), }), } - .map_err(|e| Error::ics03_connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Error::Ics03Connection(Ics03Error::Ics02Client(e))) } fn client_consensus_state( @@ -274,7 +276,7 @@ impl SendPacketReader for DummyTransferModule { height, }), } - .map_err(|e| Error::ics03_connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Error::Ics03Connection(Ics03Error::Ics02Client(e))) } fn get_next_sequence_send( @@ -291,10 +293,10 @@ impl SendPacketReader for DummyTransferModule { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Error::missing_next_send_seq( - port_id.clone(), - channel_id.clone(), - )), + None => Err(Error::MissingNextSendSeq { + port_id: port_id.clone(), + channel_id: channel_id.clone(), + }), } } From d40612f8e0afdabd8de6e37891346d3b10345a58 Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 23 Nov 2022 23:58:52 +0800 Subject: [PATCH 07/43] Redefine Ics05Error by displaydoc --- crates/ibc/src/core/ics05_port/error.rs | 32 ++++++++++--------------- crates/ibc/src/mock/context.rs | 4 +++- 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/crates/ibc/src/core/ics05_port/error.rs b/crates/ibc/src/core/ics05_port/error.rs index 4c49d3d80..e9978f4ab 100644 --- a/crates/ibc/src/core/ics05_port/error.rs +++ b/crates/ibc/src/core/ics05_port/error.rs @@ -1,22 +1,14 @@ use crate::core::ics24_host::identifier::PortId; -use flex_error::define_error; - -define_error! { - #[derive(Debug, PartialEq, Eq)] - Error { - UnknownPort - { port_id: PortId } - | e | { format_args!("port '{0}' is unknown", e.port_id) }, - - PortAlreadyBound - { port_id: PortId } - | e | { format_args!("port '{0}' is already bound", e.port_id) }, - - ModuleNotFound - { port_id: PortId } - | e | { format_args!("could not retrieve module from port '{0}'", e.port_id) }, - - ImplementationSpecific - | _ | { "implementation specific error" }, - } +use displaydoc::Display; + +#[derive(Debug, Display)] +pub enum Error { + /// port `{port_id}` is unknown + UnknownPort { port_id: PortId }, + /// port `{port_id}` is already bound + PortAlreadyBound { port_id: PortId }, + /// could not retrieve module from port `{port_id}` + ModuleNotFound { port_id: PortId }, + /// implementation specific error + ImplementationSpecific, } diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 1113c2609..a1e5b7ce9 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -663,7 +663,9 @@ impl PortReader for MockContext { fn lookup_module_by_port(&self, port_id: &PortId) -> Result { match self.ibc_store.lock().unwrap().port_to_module.get(port_id) { Some(mod_id) => Ok(mod_id.clone()), - None => Err(Ics05Error::unknown_port(port_id.clone())), + None => Err(Ics05Error::UnknownPort { + port_id: port_id.clone(), + }), } } } From fdbe14ee05463d0bab511b07133f0862b5e99893 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 00:11:08 +0800 Subject: [PATCH 08/43] Redefine Ics23Error by displaydoc --- .../core/ics02_client/msgs/upgrade_client.rs | 6 +- .../src/core/ics23_commitment/commitment.rs | 4 +- crates/ibc/src/core/ics23_commitment/error.rs | 59 ++++++++----------- .../ibc/src/core/ics23_commitment/merkle.rs | 44 +++++++------- 4 files changed, 49 insertions(+), 64 deletions(-) diff --git a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs index c08d85bda..4e8b65049 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -93,11 +93,9 @@ impl TryFrom for MsgUpgradeClient { .ok_or(Error::MissingRawConsensusState)?; let c_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client) - .map_err(|_| Error::InvalidUpgradeClientProof(Ics23Error::empty_merkle_proof()))?; + .map_err(|_| Error::InvalidUpgradeClientProof(Ics23Error::EmptyMerkleProof))?; let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) - .map_err(|_| { - Error::InvalidUpgradeConsensusStateProof(Ics23Error::empty_merkle_proof()) - })?; + .map_err(|_| Error::InvalidUpgradeConsensusStateProof(Ics23Error::EmptyMerkleProof))?; Ok(MsgUpgradeClient { client_id: ClientId::from_str(&proto_msg.client_id) diff --git a/crates/ibc/src/core/ics23_commitment/commitment.rs b/crates/ibc/src/core/ics23_commitment/commitment.rs index 59a9df743..3525877c1 100644 --- a/crates/ibc/src/core/ics23_commitment/commitment.rs +++ b/crates/ibc/src/core/ics23_commitment/commitment.rs @@ -104,7 +104,7 @@ impl TryFrom for RawMerkleProof { fn try_from(value: CommitmentProofBytes) -> Result { let value: Vec = value.into(); let res: RawMerkleProof = - prost::Message::decode(value.as_ref()).map_err(Error::invalid_raw_merkle_proof)?; + prost::Message::decode(value.as_ref()).map_err(Error::InvalidRawMerkleProof)?; Ok(res) } } @@ -129,7 +129,7 @@ impl TryFrom> for CommitmentPrefix { fn try_from(bytes: Vec) -> Result { if bytes.is_empty() { - Err(Self::Error::empty_commitment_prefix()) + Err(Self::Error::EmptyCommitmentPrefix) } else { Ok(Self { bytes }) } diff --git a/crates/ibc/src/core/ics23_commitment/error.rs b/crates/ibc/src/core/ics23_commitment/error.rs index 260c9557b..df0d9c9b3 100644 --- a/crates/ibc/src/core/ics23_commitment/error.rs +++ b/crates/ibc/src/core/ics23_commitment/error.rs @@ -1,39 +1,26 @@ -use flex_error::{define_error, TraceError}; +use displaydoc::Display; use prost::DecodeError; -define_error! { - #[derive(Debug, PartialEq, Eq)] - Error { - InvalidRawMerkleProof - [ TraceError ] - |_| { "invalid raw merkle proof" }, - - CommitmentProofDecodingFailed - [ TraceError ] - |_| { "failed to decode commitment proof" }, - - EmptyCommitmentPrefix - |_| { "empty commitment prefix" }, - - EmptyMerkleProof - |_| { "empty merkle proof" }, - - EmptyMerkleRoot - |_| { "empty merkle root" }, - - EmptyVerifiedValue - |_| { "empty verified value" }, - - NumberOfSpecsMismatch - |_| { "mismatch between the number of proofs with that of specs" }, - - NumberOfKeysMismatch - |_| { "mismatch between the number of proofs with that of keys" }, - - InvalidMerkleProof - |_| { "invalid merkle proof" }, - - VerificationFailure - |_| { "proof verification failed" } - } +#[derive(Debug, Display)] +pub enum Error { + /// invalid raw merkle proof, error(`{0}`) + InvalidRawMerkleProof(DecodeError), + /// failed to decode commitment proof, error(`{0}`) + CommitmentProofDecodingFailed(DecodeError), + /// empty commitment prefix + EmptyCommitmentPrefix, + /// empty merkle proof + EmptyMerkleProof, + /// empty merkle root + EmptyMerkleRoot, + /// empty verified value + EmptyVerifiedValue, + /// mismatch between the number of proofs with that of specs + NumberOfSpecsMismatch, + /// mismatch between the number of proofs with that of keys + NumberOfKeysMismatch, + /// invalid merkle proof + InvalidMerkleProof, + /// proof verification failed + VerificationFailure, } diff --git a/crates/ibc/src/core/ics23_commitment/merkle.rs b/crates/ibc/src/core/ics23_commitment/merkle.rs index 74e990d76..649251b80 100644 --- a/crates/ibc/src/core/ics23_commitment/merkle.rs +++ b/crates/ibc/src/core/ics23_commitment/merkle.rs @@ -78,21 +78,21 @@ impl MerkleProof { ) -> Result<(), Error> { // validate arguments if self.proofs.is_empty() { - return Err(Error::empty_merkle_proof()); + return Err(Error::EmptyMerkleProof); } if root.hash.is_empty() { - return Err(Error::empty_merkle_root()); + return Err(Error::EmptyMerkleRoot); } let num = self.proofs.len(); let ics23_specs = Vec::::from(specs.clone()); if ics23_specs.len() != num { - return Err(Error::number_of_specs_mismatch()); + return Err(Error::NumberOfSpecsMismatch); } if keys.key_path.len() != num { - return Err(Error::number_of_keys_mismatch()); + return Err(Error::NumberOfKeysMismatch); } if value.is_empty() { - return Err(Error::empty_verified_value()); + return Err(Error::EmptyVerifiedValue); } let mut subroot = value.clone(); @@ -109,7 +109,7 @@ impl MerkleProof { Some(Proof::Exist(existence_proof)) => { subroot = calculate_existence_root::(existence_proof) - .map_err(|_| Error::invalid_merkle_proof())?; + .map_err(|_| Error::InvalidMerkleProof)?; if !verify_membership::( proof, @@ -118,16 +118,16 @@ impl MerkleProof { key.as_bytes(), &value, ) { - return Err(Error::verification_failure()); + return Err(Error::VerificationFailure); } value = subroot.clone(); } - _ => return Err(Error::invalid_merkle_proof()), + _ => return Err(Error::InvalidMerkleProof), } } if root.hash != subroot { - return Err(Error::verification_failure()); + return Err(Error::VerificationFailure); } Ok(()) @@ -141,28 +141,28 @@ impl MerkleProof { ) -> Result<(), Error> { // validate arguments if self.proofs.is_empty() { - return Err(Error::empty_merkle_proof()); + return Err(Error::EmptyMerkleProof); } if root.hash.is_empty() { - return Err(Error::empty_merkle_root()); + return Err(Error::EmptyMerkleRoot); } let num = self.proofs.len(); let ics23_specs = Vec::::from(specs.clone()); if ics23_specs.len() != num { - return Err(Error::number_of_specs_mismatch()); + return Err(Error::NumberOfSpecsMismatch); } if keys.key_path.len() != num { - return Err(Error::number_of_keys_mismatch()); + return Err(Error::NumberOfKeysMismatch); } // verify the absence of key in lowest subtree - let proof = self.proofs.get(0).ok_or_else(Error::invalid_merkle_proof)?; - let spec = ics23_specs.get(0).ok_or_else(Error::invalid_merkle_proof)?; + let proof = self.proofs.get(0).ok_or(Error::InvalidMerkleProof)?; + let spec = ics23_specs.get(0).ok_or(Error::InvalidMerkleProof)?; // keys are represented from root-to-leaf let key = keys .key_path .get(num - 1) - .ok_or_else(Error::invalid_merkle_proof)?; + .ok_or(Error::InvalidMerkleProof)?; match &proof.proof { Some(Proof::Nonexist(non_existence_proof)) => { let subroot = calculate_non_existence_root(non_existence_proof)?; @@ -173,13 +173,13 @@ impl MerkleProof { &subroot, key.as_bytes(), ) { - return Err(Error::verification_failure()); + return Err(Error::VerificationFailure); } // verify membership proofs starting from index 1 with value = subroot self.verify_membership(specs, root, keys, subroot, 1) } - _ => Err(Error::invalid_merkle_proof()), + _ => Err(Error::InvalidMerkleProof), } } } @@ -188,12 +188,12 @@ impl MerkleProof { fn calculate_non_existence_root(proof: &NonExistenceProof) -> Result, Error> { if let Some(left) = &proof.left { calculate_existence_root::(left) - .map_err(|_| Error::invalid_merkle_proof()) + .map_err(|_| Error::InvalidMerkleProof) } else if let Some(right) = &proof.right { calculate_existence_root::(right) - .map_err(|_| Error::invalid_merkle_proof()) + .map_err(|_| Error::InvalidMerkleProof) } else { - Err(Error::invalid_merkle_proof()) + Err(Error::InvalidMerkleProof) } } @@ -255,7 +255,7 @@ pub fn convert_tm_to_ics_merkle_proof(tm_proof: &TendermintProof) -> Result Date: Thu, 24 Nov 2022 00:26:09 +0800 Subject: [PATCH 09/43] Redefine Ics24Error by displaydoc --- .../core/ics04_channel/msgs/chan_open_try.rs | 2 +- crates/ibc/src/core/ics24_host/error.rs | 54 ++++++++----------- crates/ibc/src/core/ics24_host/validate.rs | 13 +++-- crates/ibc/src/events.rs | 2 +- 4 files changed, 32 insertions(+), 39 deletions(-) diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs index cba984767..3557c5dc6 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs @@ -67,7 +67,7 @@ impl Msg for MsgChannelOpenTry { fn validate_basic(&self) -> Result<(), ValidationError> { match self.chan_end_on_b.counterparty().channel_id() { - None => Err(ValidationError::invalid_counterparty_channel_id()), + None => Err(ValidationError::InvalidCounterpartyChannelId), Some(_c) => Ok(()), } } diff --git a/crates/ibc/src/core/ics24_host/error.rs b/crates/ibc/src/core/ics24_host/error.rs index 022141421..5dc37d1e1 100644 --- a/crates/ibc/src/core/ics24_host/error.rs +++ b/crates/ibc/src/core/ics24_host/error.rs @@ -1,36 +1,24 @@ -use flex_error::define_error; -use serde::Serialize; - use crate::prelude::*; +use displaydoc::Display; +use serde::Serialize; -define_error! { - #[derive(Debug, PartialEq, Eq, Serialize)] - ValidationError { - ContainSeparator - { id : String } - | e | { format_args!("identifier {0} cannot contain separator '/'", e.id) }, - - InvalidLength - { - id: String, - length: usize, - min: usize, - max: usize, - } - | e | { format_args!("identifier {0} has invalid length {1} must be between {2}-{3} characters", e.id, e.length, e.min, e.max) }, - - InvalidCharacter - { id: String } - | e | { format_args!("identifier {0} must only contain alphanumeric characters or `.`, `_`, `+`, `-`, `#`, - `[`, `]`, `<`, `>`", e.id) }, - - Empty - | _ | { "identifier cannot be empty" }, - - ChainIdInvalidFormat - { id: String } - | e | { format_args!("chain identifiers are expected to be in epoch format {0}", e.id) }, - - InvalidCounterpartyChannelId - |_| { "Invalid channel id in counterparty" } - } +#[derive(Debug, Display, Serialize)] +pub enum ValidationError { + /// identifier `{id}` cannot contain separator '/' + ContainSeparator { id: String }, + /// identifier `{id}` has invalid length `{length}` must be between `{min}`-`{max}` characters + InvalidLength { + id: String, + length: usize, + min: usize, + max: usize, + }, + /// identifier `{id}` must only contain alphanumeric characters or `.`, `_`, `+`, `-`, `#`, - `[`, `]`, `<`, `>` + InvalidCharacter { id: String }, + /// identifier cannot be empty + Empty, + /// chain identifiers are expected to be in epoch format `{id}` + ChainIdInvalidFormat { id: String }, + /// Invalid channel id in counterparty + InvalidCounterpartyChannelId, } diff --git a/crates/ibc/src/core/ics24_host/validate.rs b/crates/ibc/src/core/ics24_host/validate.rs index 0bc4163bb..bfa2d04ab 100644 --- a/crates/ibc/src/core/ics24_host/validate.rs +++ b/crates/ibc/src/core/ics24_host/validate.rs @@ -15,17 +15,22 @@ pub fn validate_identifier(id: &str, min: usize, max: usize) -> Result<(), Error // Check identifier is not empty if id.is_empty() { - return Err(Error::empty()); + return Err(Error::Empty); } // Check identifier does not contain path separators if id.contains(PATH_SEPARATOR) { - return Err(Error::contain_separator(id.to_string())); + return Err(Error::ContainSeparator { id: id.into() }); } // Check identifier length is between given min/max if id.len() < min || id.len() > max { - return Err(Error::invalid_length(id.to_string(), id.len(), min, max)); + return Err(Error::InvalidLength { + id: id.into(), + length: id.len(), + min, + max, + }); } // Check that the identifier comprises only valid characters: @@ -36,7 +41,7 @@ pub fn validate_identifier(id: &str, min: usize, max: usize) -> Result<(), Error .chars() .all(|c| c.is_alphanumeric() || VALID_SPECIAL_CHARS.contains(c)) { - return Err(Error::invalid_character(id.to_string())); + return Err(Error::InvalidCharacter { id: id.into() }); } // All good! diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index 32a683707..2889a078b 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -22,7 +22,7 @@ define_error! { | _ | { "error parsing height" }, Parse - [ ValidationError ] + [ TraceError ] | _ | { "parse error" }, Client From c68bab8f63a1ea4e702d8b74206ce33cfad069c4 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 00:38:47 +0800 Subject: [PATCH 10/43] Redefine Ics26Error by displaydoc --- crates/ibc/src/core/context.rs | 4 +- crates/ibc/src/core/ics26_routing/error.rs | 37 +++++++----------- crates/ibc/src/core/ics26_routing/handler.rs | 26 ++++++------- crates/ibc/src/core/ics26_routing/msgs.rs | 38 ++++++++++--------- crates/ibc/src/relayer/ics18_relayer/error.rs | 2 +- 5 files changed, 49 insertions(+), 58 deletions(-) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 7fead02c4..a787c9eee 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -52,7 +52,7 @@ pub trait ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::validate(self, message), } - .map_err(RouterError::ics02_client), + .map_err(RouterError::Ics02Client), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), @@ -255,7 +255,7 @@ pub trait ExecutionContext: ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::execute(self, message), } - .map_err(RouterError::ics02_client), + .map_err(RouterError::Ics02Client), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index c9fd2789a..5a2d91a36 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -1,31 +1,20 @@ use crate::prelude::*; -use flex_error::{define_error, TraceError}; use crate::core::ics02_client; use crate::core::ics03_connection; use crate::core::ics04_channel; +use displaydoc::Display; -define_error! { - #[derive(Debug)] - Error { - Ics02Client - [ TraceError ] - | _ | { "ICS02 client error" }, - - Ics03Connection - [ TraceError ] - | _ | { "ICS03 connection error" }, - - Ics04Channel - [ TraceError ] - | _ | { "ICS04 channel error" }, - - UnknownMessageTypeUrl - { url: String } - | e | { format_args!("unknown type URL {0}", e.url) }, - - MalformedMessageBytes - [ TraceError ] - | _ | { "the message is malformed and cannot be decoded" }, - } +#[derive(Debug, Display)] +pub enum Error { + /// ICS02 client error(`{0}`) + Ics02Client(ics02_client::error::Error), + /// ICS03 connection error(`{0}`) + Ics03Connection(ics03_connection::error::Error), + /// ICS04 channel error(`{0}`) + Ics04Channel(ics04_channel::error::Error), + /// unknown type URL `{url}` + UnknownMessageTypeUrl { url: String }, + /// the message is malformed and cannot be decoded, error(`{0}`) + MalformedMessageBytes(ibc_proto::protobuf::Error), } diff --git a/crates/ibc/src/core/ics26_routing/handler.rs b/crates/ibc/src/core/ics26_routing/handler.rs index bc3f32dd5..6f7dc02d9 100644 --- a/crates/ibc/src/core/ics26_routing/handler.rs +++ b/crates/ibc/src/core/ics26_routing/handler.rs @@ -59,11 +59,11 @@ where { let output = match msg { ClientMsg(msg) => { - let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(Error::ics02_client)?; + let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(Error::Ics02Client)?; // Apply the result to the context (host chain store). ctx.store_client_result(handler_output.result) - .map_err(Error::ics02_client)?; + .map_err(Error::Ics02Client)?; HandlerOutput::builder() .with_log(handler_output.log) @@ -72,11 +72,11 @@ where } ConnectionMsg(msg) => { - let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(Error::ics03_connection)?; + let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(Error::Ics03Connection)?; // Apply any results to the host chain store. ctx.store_connection_result(handler_output.result) - .map_err(Error::ics03_connection)?; + .map_err(Error::Ics03Connection)?; HandlerOutput::builder() .with_log(handler_output.log) @@ -85,18 +85,18 @@ where } ChannelMsg(msg) => { - let module_id = channel_validate(ctx, &msg).map_err(Error::ics04_channel)?; + let module_id = channel_validate(ctx, &msg).map_err(Error::Ics04Channel)?; let dispatch_output = HandlerOutputBuilder::<()>::new(); let (dispatch_log, mut channel_result) = - channel_dispatch(ctx, &msg).map_err(Error::ics04_channel)?; + channel_dispatch(ctx, &msg).map_err(Error::Ics04Channel)?; // Note: `OpenInit` and `OpenTry` modify the `version` field of the `channel_result`, // so we must pass it mutably. We intend to clean this up with the implementation of // ADR 5. // See issue [#190](https://github.com/cosmos/ibc-rs/issues/190) let callback_extras = channel_callback(ctx, &module_id, &msg, &mut channel_result) - .map_err(Error::ics04_channel)?; + .map_err(Error::Ics04Channel)?; // We need to construct events here instead of directly in the // `process` functions because we need to wait for the callback to @@ -111,7 +111,7 @@ where // Apply any results to the host chain store. ctx.store_channel_result(channel_result) - .map_err(Error::ics04_channel)?; + .map_err(Error::Ics04Channel)?; dispatch_output .with_events(dispatch_events) @@ -128,20 +128,20 @@ where } PacketMsg(msg) => { - let module_id = get_module_for_packet_msg(ctx, &msg).map_err(Error::ics04_channel)?; + let module_id = get_module_for_packet_msg(ctx, &msg).map_err(Error::Ics04Channel)?; let (mut handler_builder, packet_result) = - ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::ics04_channel)?; + ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::Ics04Channel)?; if matches!(packet_result, PacketResult::Recv(RecvPacketResult::NoOp)) { return Ok(handler_builder.with_result(())); } let cb_result = ics4_packet_callback(ctx, &module_id, &msg, &mut handler_builder); - cb_result.map_err(Error::ics04_channel)?; + cb_result.map_err(Error::Ics04Channel)?; // Apply any results to the host chain store. ctx.store_packet_result(packet_result) - .map_err(Error::ics04_channel)?; + .map_err(Error::Ics04Channel)?; handler_builder.with_result(()) } @@ -632,7 +632,7 @@ mod tests { msg, ) .map(|_| ()) - .map_err(Error::ics04_channel) + .map_err(Error::Ics04Channel) } }; diff --git a/crates/ibc/src/core/ics26_routing/msgs.rs b/crates/ibc/src/core/ics26_routing/msgs.rs index a037a8562..008757c3e 100644 --- a/crates/ibc/src/core/ics26_routing/msgs.rs +++ b/crates/ibc/src/core/ics26_routing/msgs.rs @@ -31,38 +31,38 @@ impl TryFrom for MsgEnvelope { create_client::TYPE_URL => { // Pop out the message and then wrap it in the corresponding type. let domain_msg = create_client::MsgCreateClient::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ClientMsg(ClientMsg::CreateClient(domain_msg))) } update_client::TYPE_URL => { let domain_msg = update_client::MsgUpdateClient::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ClientMsg(ClientMsg::UpdateClient(domain_msg))) } upgrade_client::TYPE_URL => { let domain_msg = upgrade_client::MsgUpgradeClient::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ClientMsg(ClientMsg::UpgradeClient(domain_msg))) } // ICS03 conn_open_init::TYPE_URL => { let domain_msg = conn_open_init::MsgConnectionOpenInit::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenInit(domain_msg), )) } conn_open_try::TYPE_URL => { let domain_msg = conn_open_try::MsgConnectionOpenTry::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenTry(Box::new(domain_msg)), )) } conn_open_ack::TYPE_URL => { let domain_msg = conn_open_ack::MsgConnectionOpenAck::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenAck(Box::new(domain_msg)), )) @@ -70,7 +70,7 @@ impl TryFrom for MsgEnvelope { conn_open_confirm::TYPE_URL => { let domain_msg = conn_open_confirm::MsgConnectionOpenConfirm::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenConfirm(domain_msg), )) @@ -79,21 +79,21 @@ impl TryFrom for MsgEnvelope { // ICS04 channel messages chan_open_init::TYPE_URL => { let domain_msg = chan_open_init::MsgChannelOpenInit::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenInit( domain_msg, ))) } chan_open_try::TYPE_URL => { let domain_msg = chan_open_try::MsgChannelOpenTry::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenTry( domain_msg, ))) } chan_open_ack::TYPE_URL => { let domain_msg = chan_open_ack::MsgChannelOpenAck::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenAck( domain_msg, ))) @@ -101,14 +101,14 @@ impl TryFrom for MsgEnvelope { chan_open_confirm::TYPE_URL => { let domain_msg = chan_open_confirm::MsgChannelOpenConfirm::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenConfirm( domain_msg, ))) } chan_close_init::TYPE_URL => { let domain_msg = chan_close_init::MsgChannelCloseInit::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelCloseInit( domain_msg, ))) @@ -116,7 +116,7 @@ impl TryFrom for MsgEnvelope { chan_close_confirm::TYPE_URL => { let domain_msg = chan_close_confirm::MsgChannelCloseConfirm::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelCloseConfirm( domain_msg, ))) @@ -124,27 +124,29 @@ impl TryFrom for MsgEnvelope { // ICS04 packet messages recv_packet::TYPE_URL => { let domain_msg = recv_packet::MsgRecvPacket::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::RecvPacket(domain_msg))) } acknowledgement::TYPE_URL => { let domain_msg = acknowledgement::MsgAcknowledgement::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::AckPacket(domain_msg))) } timeout::TYPE_URL => { let domain_msg = timeout::MsgTimeout::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::TimeoutPacket(domain_msg))) } timeout_on_close::TYPE_URL => { let domain_msg = timeout_on_close::MsgTimeoutOnClose::decode_vec(&any_msg.value) - .map_err(Error::malformed_message_bytes)?; + .map_err(Error::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::TimeoutOnClosePacket( domain_msg, ))) } - _ => Err(Error::unknown_message_type_url(any_msg.type_url)), + _ => Err(Error::UnknownMessageTypeUrl { + url: any_msg.type_url, + }), } } } diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index 2eb4a4f39..e31af6739 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -33,7 +33,7 @@ define_error! { }, TransactionFailed - [ RoutingError ] + [ TraceError ] | _ | { "transaction processing by modules failed" }, Ics03 From fcb198a4031dfc81051add0325c1d1f84eb723f8 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 00:46:34 +0800 Subject: [PATCH 11/43] Redefine Ics18Error by displaydoc --- crates/ibc/src/mock/context.rs | 6 +- crates/ibc/src/relayer/ics18_relayer/error.rs | 58 +++++++------------ crates/ibc/src/relayer/ics18_relayer/utils.rs | 28 ++++----- 3 files changed, 39 insertions(+), 53 deletions(-) diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index a1e5b7ce9..37d5becfe 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -467,7 +467,7 @@ impl MockContext { /// Alternative method to `Ics18Context::send` that does not exercise any serialization. /// Used in testing the Ics18 algorithms, hence this may return a Ics18Error. pub fn deliver(&mut self, msg: MsgEnvelope) -> Result<(), Ics18Error> { - dispatch(self, msg).map_err(Ics18Error::transaction_failed)?; + dispatch(self, msg).map_err(Ics18Error::TransactionFailed)?; // Create a new block. self.advance_host_chain_height(); Ok(()) @@ -1425,7 +1425,7 @@ impl ClientKeeper for MockContext { impl RelayerContext for MockContext { fn query_latest_height(&self) -> Result { - self.host_current_height().map_err(Ics18Error::ics03) + self.host_current_height().map_err(Ics18Error::Ics03) } fn query_client_full_state(&self, client_id: &ClientId) -> Option> { @@ -1443,7 +1443,7 @@ impl RelayerContext for MockContext { let mut all_events = vec![]; for msg in msgs { let MsgReceipt { mut events, .. } = - deliver(self, msg).map_err(Ics18Error::transaction_failed)?; + deliver(self, msg).map_err(Ics18Error::TransactionFailed)?; all_events.append(&mut events); } self.advance_host_chain_height(); // Advance chain height diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index e31af6739..354c1d73e 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -2,42 +2,26 @@ use crate::core::ics03_connection; use crate::core::ics24_host::identifier::ClientId; use crate::core::ics26_routing::error::Error as RoutingError; use crate::Height; -use flex_error::{define_error, TraceError}; +use displaydoc::Display; -define_error! { - Error { - ClientStateNotFound - { client_id: ClientId } - | e | { format_args!("client state on destination chain not found, (client id: {0})", e.client_id) }, - - ClientAlreadyUpToDate - { - client_id: ClientId, - source_height: Height, - destination_height: Height, - } - | e | { - format_args!("the client on destination chain is already up-to-date (client id: {0}, source height: {1}, dest height: {2})", - e.client_id, e.source_height, e.destination_height) - }, - - ClientAtHigherHeight - { - client_id: ClientId, - source_height: Height, - destination_height: Height, - } - | e | { - format_args!("the client on destination chain is at a higher height (client id: {0}, source height: {1}, dest height: {2})", - e.client_id, e.source_height, e.destination_height) - }, - - TransactionFailed - [ TraceError ] - | _ | { "transaction processing by modules failed" }, - - Ics03 - [ TraceError ] - | _ | { "ics03 connection error" } - } +#[derive(Debug, Display)] +pub enum Error { + /// client state on destination chain not found, (client id: `{client_id}`) + ClientStateNotFound { client_id: ClientId }, + /// the client on destination chain is already up-to-date (client id: `{client_id}`, source height: `{source_height}`, dest height: `{destination_height}`) + ClientAlreadyUpToDate { + client_id: ClientId, + source_height: Height, + destination_height: Height, + }, + /// the client on destination chain is at a higher height (client id: `{client_id}`, source height: `{source_height}`, dest height: `{destination_height}`) + ClientAtHigherHeight { + client_id: ClientId, + source_height: Height, + destination_height: Height, + }, + /// transaction processing by modules failed, error(`{0}`) + TransactionFailed(RoutingError), + /// ics03 connection error(`{0}`) + Ics03(ics03_connection::error::Error), } diff --git a/crates/ibc/src/relayer/ics18_relayer/utils.rs b/crates/ibc/src/relayer/ics18_relayer/utils.rs index 349008fc8..69ea5144a 100644 --- a/crates/ibc/src/relayer/ics18_relayer/utils.rs +++ b/crates/ibc/src/relayer/ics18_relayer/utils.rs @@ -17,26 +17,28 @@ where { // Check if client for ibc0 on ibc1 has been updated to latest height: // - query client state on destination chain - let dest_client_state = dest - .query_client_full_state(client_id) - .ok_or_else(|| Error::client_state_not_found(client_id.clone()))?; + let dest_client_state = + dest.query_client_full_state(client_id) + .ok_or_else(|| Error::ClientStateNotFound { + client_id: client_id.clone(), + })?; let dest_client_latest_height = dest_client_state.latest_height(); if src_header.height() == dest_client_latest_height { - return Err(Error::client_already_up_to_date( - client_id.clone(), - src_header.height(), - dest_client_latest_height, - )); + return Err(Error::ClientAlreadyUpToDate { + client_id: client_id.clone(), + source_height: src_header.height(), + destination_height: dest_client_latest_height, + }); }; if dest_client_latest_height > src_header.height() { - return Err(Error::client_at_higher_height( - client_id.clone(), - src_header.height(), - dest_client_latest_height, - )); + return Err(Error::ClientAtHigherHeight { + client_id: client_id.clone(), + source_height: src_header.height(), + destination_height: dest_client_latest_height, + }); }; // Client on destination chain can be updated. From 42b9788cab6bda49e45794013401ee808208f94c Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 00:54:07 +0800 Subject: [PATCH 12/43] Redefine ParseFailure Error --- crates/ibc/src/core/ics24_host/path.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/crates/ibc/src/core/ics24_host/path.rs b/crates/ibc/src/core/ics24_host/path.rs index efa001c79..c5d589587 100644 --- a/crates/ibc/src/core/ics24_host/path.rs +++ b/crates/ibc/src/core/ics24_host/path.rs @@ -10,7 +10,6 @@ use crate::core::ics04_channel::packet::Sequence; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; use derive_more::{Display, From}; -use flex_error::define_error; /// ABCI Query path for the IBC sub-store pub const IBC_QUERY_PATH: &str = "store/ibc/key"; @@ -178,18 +177,17 @@ impl Path { } } -define_error! { - #[derive(Eq, PartialEq)] - PathError { - ParseFailure - { path: String } - | e | { format!("'{}' could not be parsed into a Path", e.path) }, - } + +#[derive(Debug, displaydoc::Display)] +/// `{path}` could not be parsed into a Path +pub struct ParseFailure { + path: String, } + /// The FromStr trait allows paths encoded as strings to be parsed into Paths. impl FromStr for Path { - type Err = PathError; + type Err = ParseFailure; fn from_str(s: &str) -> Result { let components: Vec<&str> = s.split('/').collect(); @@ -203,7 +201,7 @@ impl FromStr for Path { .or_else(|| parse_acks(&components)) .or_else(|| parse_receipts(&components)) .or_else(|| parse_upgrades(&components)) - .ok_or_else(|| PathError::parse_failure(s.to_string())) + .ok_or(ParseFailure{path : s.to_string() }) } } From 0abb3097b9ad4ccd333cf97b6a60acfedf89ebae Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:03:38 +0800 Subject: [PATCH 13/43] Redefine HeightError --- crates/ibc/src/core/ics02_client/height.rs | 30 ++++++++++------------ crates/ibc/src/core/ics24_host/path.rs | 12 +++++---- 2 files changed, 20 insertions(+), 22 deletions(-) diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index 0205241eb..376e480d3 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -4,7 +4,7 @@ use core::cmp::Ordering; use core::num::ParseIntError; use core::str::FromStr; -use flex_error::{define_error, TraceError}; +use displaydoc::Display; use ibc_proto::protobuf::Protobuf; use serde_derive::{Deserialize, Serialize}; @@ -125,19 +125,15 @@ impl core::fmt::Display for Height { } } -define_error! { - #[derive(Debug, PartialEq, Eq)] - HeightError { - HeightConversion - { height: String } - [ TraceError ] - | e | { - format_args!("cannot convert into a `Height` type from string {0}", - e.height) - }, - ZeroHeight - |_| { "attempted to parse an invalid zero height" } - } +#[derive(Debug, Display)] +pub enum HeightError { + /// cannot convert into a `Height` type from string `{height}`, error(`{error}`) + HeightConversion + { height: String , + error: ParseIntError + }, + /// attempted to parse an invalid zero height + ZeroHeight, } impl TryFrom<&str> for Height { @@ -148,12 +144,12 @@ impl TryFrom<&str> for Height { let revision_number = split[0] .parse::() - .map_err(|e| HeightError::height_conversion(value.to_owned(), e))?; + .map_err(|e| HeightError::HeightConversion{ height: value.to_owned(), error: e })?; let revision_height = split[1] .parse::() - .map_err(|e| HeightError::height_conversion(value.to_owned(), e))?; + .map_err(|e| HeightError::HeightConversion{ height: value.to_owned(), error: e })?; - Height::new(revision_number, revision_height).map_err(|_| HeightError::zero_height()) + Height::new(revision_number, revision_height).map_err(|_| HeightError::ZeroHeight) } } diff --git a/crates/ibc/src/core/ics24_host/path.rs b/crates/ibc/src/core/ics24_host/path.rs index c5d589587..f03135eab 100644 --- a/crates/ibc/src/core/ics24_host/path.rs +++ b/crates/ibc/src/core/ics24_host/path.rs @@ -179,15 +179,17 @@ impl Path { #[derive(Debug, displaydoc::Display)] -/// `{path}` could not be parsed into a Path -pub struct ParseFailure { - path: String, +pub enum PathError { + /// `{path}` could not be parsed into a Path + ParseFailure { + path: String, + }, } /// The FromStr trait allows paths encoded as strings to be parsed into Paths. impl FromStr for Path { - type Err = ParseFailure; + type Err = PathError; fn from_str(s: &str) -> Result { let components: Vec<&str> = s.split('/').collect(); @@ -201,7 +203,7 @@ impl FromStr for Path { .or_else(|| parse_acks(&components)) .or_else(|| parse_receipts(&components)) .or_else(|| parse_upgrades(&components)) - .ok_or(ParseFailure{path : s.to_string() }) + .ok_or(PathError::ParseFailure{path : s.to_string() }) } } From 5b9375c62d603c9cc8977af99a1743550c8a2e58 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:06:53 +0800 Subject: [PATCH 14/43] Redefine ProofError --- crates/ibc/src/core/ics02_client/height.rs | 26 ++++++++++++------- .../ics04_channel/handler/timeout_on_close.rs | 2 +- .../src/core/ics23_commitment/commitment.rs | 2 +- crates/ibc/src/core/ics24_host/path.rs | 10 +++---- crates/ibc/src/proofs.rs | 16 +++++------- 5 files changed, 30 insertions(+), 26 deletions(-) diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index 376e480d3..fcf0d543c 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -128,9 +128,9 @@ impl core::fmt::Display for Height { #[derive(Debug, Display)] pub enum HeightError { /// cannot convert into a `Height` type from string `{height}`, error(`{error}`) - HeightConversion - { height: String , - error: ParseIntError + HeightConversion { + height: String, + error: ParseIntError, }, /// attempted to parse an invalid zero height ZeroHeight, @@ -142,12 +142,20 @@ impl TryFrom<&str> for Height { fn try_from(value: &str) -> Result { let split: Vec<&str> = value.split('-').collect(); - let revision_number = split[0] - .parse::() - .map_err(|e| HeightError::HeightConversion{ height: value.to_owned(), error: e })?; - let revision_height = split[1] - .parse::() - .map_err(|e| HeightError::HeightConversion{ height: value.to_owned(), error: e })?; + let revision_number = + split[0] + .parse::() + .map_err(|e| HeightError::HeightConversion { + height: value.to_owned(), + error: e, + })?; + let revision_height = + split[1] + .parse::() + .map_err(|e| HeightError::HeightConversion { + height: value.to_owned(), + error: e, + })?; Height::new(revision_number, revision_height).map_err(|_| HeightError::ZeroHeight) } diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs b/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs index 753f69d03..e09e8bf15 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs @@ -80,7 +80,7 @@ pub fn process( // The message's proofs have the channel proof as `other_proof` let proof_close = match msg.proofs.other_proof() { Some(p) => p.clone(), - None => return Err(Error::InvalidProof(ProofError::empty_proof())), + None => return Err(Error::InvalidProof(ProofError::EmptyProof)), }; let proofs = Proofs::new(proof_close, None, None, None, msg.proofs.height()) .map_err(Error::InvalidProof)?; diff --git a/crates/ibc/src/core/ics23_commitment/commitment.rs b/crates/ibc/src/core/ics23_commitment/commitment.rs index 3525877c1..8ff129d95 100644 --- a/crates/ibc/src/core/ics23_commitment/commitment.rs +++ b/crates/ibc/src/core/ics23_commitment/commitment.rs @@ -67,7 +67,7 @@ impl TryFrom> for CommitmentProofBytes { fn try_from(bytes: Vec) -> Result { if bytes.is_empty() { - Err(Self::Error::empty_proof()) + Err(Self::Error::EmptyProof) } else { Ok(Self { bytes }) } diff --git a/crates/ibc/src/core/ics24_host/path.rs b/crates/ibc/src/core/ics24_host/path.rs index f03135eab..2fbcf8b64 100644 --- a/crates/ibc/src/core/ics24_host/path.rs +++ b/crates/ibc/src/core/ics24_host/path.rs @@ -177,16 +177,12 @@ impl Path { } } - #[derive(Debug, displaydoc::Display)] pub enum PathError { /// `{path}` could not be parsed into a Path - ParseFailure { - path: String, - }, + ParseFailure { path: String }, } - /// The FromStr trait allows paths encoded as strings to be parsed into Paths. impl FromStr for Path { type Err = PathError; @@ -203,7 +199,9 @@ impl FromStr for Path { .or_else(|| parse_acks(&components)) .or_else(|| parse_receipts(&components)) .or_else(|| parse_upgrades(&components)) - .ok_or(PathError::ParseFailure{path : s.to_string() }) + .ok_or(PathError::ParseFailure { + path: s.to_string(), + }) } } diff --git a/crates/ibc/src/proofs.rs b/crates/ibc/src/proofs.rs index dead16749..01725ec51 100644 --- a/crates/ibc/src/proofs.rs +++ b/crates/ibc/src/proofs.rs @@ -2,16 +2,14 @@ use serde::Serialize; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::Height; -use flex_error::define_error; +use displaydoc::Display; -define_error! { - #[derive(Debug, PartialEq, Eq)] - ProofError { - ZeroHeight - | _ | { format_args!("proof height cannot be zero") }, - EmptyProof - | _ | { format_args!("proof cannot be empty") }, - } +#[derive(Debug, Display)] +pub enum ProofError { + /// proof height cannot be zero + ZeroHeight, + /// proof cannot be empty + EmptyProof, } /// Structure comprising proofs in a message. Proofs are typically present in messages for From a11d007652637c9fc3b2959febb887c7c4682978 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:08:41 +0800 Subject: [PATCH 15/43] Redefine SignerError --- crates/ibc/src/signer.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/crates/ibc/src/signer.rs b/crates/ibc/src/signer.rs index 21c62bf11..01ea54bcf 100644 --- a/crates/ibc/src/signer.rs +++ b/crates/ibc/src/signer.rs @@ -3,15 +3,12 @@ use core::str::FromStr; use crate::prelude::*; use derive_more::Display; -use flex_error::define_error; use serde::{Deserialize, Serialize}; -define_error! { - #[derive(Debug, PartialEq, Eq)] - SignerError { - EmptySigner - | _ | { "signer cannot be empty" }, - } +#[derive(Debug, displaydoc::Display)] +pub enum SignerError { + /// signer cannot be empty + EmptySigner, } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Display)] @@ -23,7 +20,7 @@ impl FromStr for Signer { fn from_str(s: &str) -> Result { let s = s.to_string(); if s.trim().is_empty() { - return Err(SignerError::empty_signer()); + return Err(SignerError::EmptySigner); } Ok(Self(s)) } From 4d62320050d9d9ce153abb902f49dc88d4a87a2d Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:12:25 +0800 Subject: [PATCH 16/43] Redefine TimestampOverflowError, ParseTimestampError --- crates/ibc/src/events.rs | 2 +- crates/ibc/src/timestamp.rs | 29 ++++++++++++----------------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index 2889a078b..e5f17a4ca 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -38,7 +38,7 @@ define_error! { | _ | { "channel error" }, Timestamp - [ ParseTimestampError ] + [ TraceError ] | _ | { "error parsing timestamp" }, MissingKey diff --git a/crates/ibc/src/timestamp.rs b/crates/ibc/src/timestamp.rs index c3d655185..ff3b5b512 100644 --- a/crates/ibc/src/timestamp.rs +++ b/crates/ibc/src/timestamp.rs @@ -7,7 +7,7 @@ use core::ops::{Add, Sub}; use core::str::FromStr; use core::time::Duration; -use flex_error::{define_error, TraceError}; +use displaydoc::Display; use serde_derive::{Deserialize, Serialize}; use tendermint::Time; use time::OffsetDateTime; @@ -176,12 +176,10 @@ impl Display for Timestamp { } } -define_error! { - #[derive(Debug, PartialEq, Eq)] - TimestampOverflowError { - TimestampOverflow - |_| { "Timestamp overflow when modifying with duration" } - } +#[derive(Debug, Display)] +pub enum TimestampOverflowError { + /// Timestamp overflow when modifying with duration + TimestampOverflow, } impl Add for Timestamp { @@ -191,7 +189,7 @@ impl Add for Timestamp { match self.time { Some(time) => { let time = - (time + duration).map_err(|_| TimestampOverflowError::timestamp_overflow())?; + (time + duration).map_err(|_| TimestampOverflowError::TimestampOverflow)?; Ok(Timestamp { time: Some(time) }) } None => Ok(self), @@ -206,7 +204,7 @@ impl Sub for Timestamp { match self.time { Some(time) => { let time = - (time - duration).map_err(|_| TimestampOverflowError::timestamp_overflow())?; + (time - duration).map_err(|_| TimestampOverflowError::TimestampOverflow)?; Ok(Timestamp { time: Some(time) }) } None => Ok(self), @@ -214,20 +212,17 @@ impl Sub for Timestamp { } } -define_error! { - #[derive(Debug, PartialEq, Eq)] - ParseTimestampError { - ParseInt - [ TraceError ] - | _ | { "error parsing u64 integer from string"}, - } +#[derive(Debug, Display)] +pub enum ParseTimestampError { + /// error parsing u64 integer from string, error(`{0}`) + ParseInt(ParseIntError), } impl FromStr for Timestamp { type Err = ParseTimestampError; fn from_str(s: &str) -> Result { - let nanoseconds = u64::from_str(s).map_err(ParseTimestampError::parse_int)?; + let nanoseconds = u64::from_str(s).map_err(ParseTimestampError::ParseInt)?; Timestamp::from_nanoseconds(nanoseconds) } From 5cdfca10ebe823c5c944d19aee28da416808d1f0 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:21:20 +0800 Subject: [PATCH 17/43] Redefine event Error --- crates/ibc/src/events.rs | 98 ++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 60 deletions(-) diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index e5f17a4ca..8e12f4ba6 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -2,7 +2,7 @@ use crate::prelude::*; use core::convert::{TryFrom, TryInto}; use core::str::FromStr; -use flex_error::{define_error, TraceError}; +use displaydoc::Display; use serde_derive::{Deserialize, Serialize}; use tendermint::abci; @@ -16,58 +16,34 @@ use crate::core::ics24_host::error::ValidationError; use crate::core::ics26_routing::context::ModuleId; use crate::timestamp::ParseTimestampError; -define_error! { - Error { - Height - | _ | { "error parsing height" }, - - Parse - [ TraceError ] - | _ | { "parse error" }, - - Client - [ TraceError ] - | _ | { "ICS02 client error" }, - - Connection - [ TraceError ] - | _ | { "connection error" }, - - Channel - [ TraceError ] - | _ | { "channel error" }, - - Timestamp - [ TraceError ] - | _ | { "error parsing timestamp" }, - - MissingKey - { key: String } - | e | { format_args!("missing event key {}", e.key) }, - - Decode - [ TraceError ] - | _ | { "error decoding protobuf" }, - - SubtleEncoding - [ TraceError ] - | _ | { "error decoding hex" }, - - MissingActionString - | _ | { "missing action string" }, - - IncorrectEventType - { event: String } - | e | { format_args!("incorrect event type: {}", e.event) }, - - MalformedModuleEvent - { event: ModuleEvent } - | e | { format_args!("module event cannot use core event types: {:?}", e.event) }, - - UnsupportedAbciEvent - {event_type: String} - |e| { format_args!("Unable to parse abci event type '{}' into IbcEvent", e.event_type)} - } +#[derive(Debug, Display)] +pub enum Error { + /// error parsing height + Height, + /// parse error, error(`{0}`) + Parse(ValidationError), + /// ICS02 client error, error(`{0}`) + Client(client_error::Error), + /// connection error, error(`{0}`) + Connection(connection_error::Error), + /// channel error, error(`{0}`) + Channel(channel_error::Error), + /// error parsing timestamp, error(`{0}`) + Timestamp(ParseTimestampError), + /// missing event key `{key}` + MissingKey { key: String }, + /// error decoding protobuf, error(`{0}`) + Decode(prost::DecodeError), + /// error decoding hex, error(`{0}`) + SubtleEncoding(subtle_encoding::Error), + /// missing action string + MissingActionString, + /// incorrect event type: `{event}` + IncorrectEventType { event: String }, + /// module event cannot use core event types: `{event:?}` + MalformedModuleEvent { event: ModuleEvent }, + /// Unable to parse abci event type `{event_type}` into IbcEvent" + UnsupportedAbciEvent { event_type: String }, } /// Events whose data is not included in the app state and must be extracted using tendermint RPCs @@ -197,7 +173,9 @@ impl FromStr for IbcEventType { TIMEOUT_EVENT => Ok(IbcEventType::Timeout), CHANNEL_CLOSED_EVENT => Ok(IbcEventType::ChannelClosed), // from_str() for `APP_MODULE_EVENT` MUST fail because a `ModuleEvent`'s type isn't constant - _ => Err(Error::incorrect_event_type(s.to_string())), + _ => Err(Error::IncorrectEventType { + event: s.to_string(), + }), } } } @@ -251,11 +229,11 @@ impl TryFrom for abci::Event { IbcEvent::OpenConfirmChannel(event) => event.into(), IbcEvent::CloseInitChannel(event) => event.into(), IbcEvent::CloseConfirmChannel(event) => event.into(), - IbcEvent::SendPacket(event) => event.try_into().map_err(Error::channel)?, - IbcEvent::ReceivePacket(event) => event.try_into().map_err(Error::channel)?, - IbcEvent::WriteAcknowledgement(event) => event.try_into().map_err(Error::channel)?, - IbcEvent::AcknowledgePacket(event) => event.try_into().map_err(Error::channel)?, - IbcEvent::TimeoutPacket(event) => event.try_into().map_err(Error::channel)?, + IbcEvent::SendPacket(event) => event.try_into().map_err(Error::Channel)?, + IbcEvent::ReceivePacket(event) => event.try_into().map_err(Error::Channel)?, + IbcEvent::WriteAcknowledgement(event) => event.try_into().map_err(Error::Channel)?, + IbcEvent::AcknowledgePacket(event) => event.try_into().map_err(Error::Channel)?, + IbcEvent::TimeoutPacket(event) => event.try_into().map_err(Error::Channel)?, IbcEvent::ChannelClosed(event) => event.into(), IbcEvent::AppModule(event) => event.try_into()?, }) @@ -302,7 +280,7 @@ impl TryFrom for abci::Event { fn try_from(event: ModuleEvent) -> Result { if IbcEventType::from_str(event.kind.as_str()).is_ok() { - return Err(Error::malformed_module_event(event)); + return Err(Error::MalformedModuleEvent { event }); } let attributes = event.attributes.into_iter().map(Into::into).collect(); From 2bcd1c919bb277c0b96ccbd1436361ee651e6a98 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:24:06 +0800 Subject: [PATCH 18/43] update ics03Error --- crates/ibc/src/core/ics03_connection/connection.rs | 2 +- crates/ibc/src/core/ics03_connection/error.rs | 2 +- .../core/ics04_channel/handler/chan_open_try.rs | 2 +- crates/ibc/src/mock/context.rs | 14 +++++++------- crates/ibc/src/test_utils.rs | 4 ++-- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index d69b89c71..70710e944 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -269,7 +269,7 @@ impl TryFrom for Counterparty { .ok_or(Error::MissingCounterparty)? .key_prefix .try_into() - .map_err(|_| Error::Ics02Client(ClientError::EmptyPrefix))?, + .map_err(|_| Error::Client(ClientError::EmptyPrefix))?, )) } } diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 926cdc341..3d9694a8a 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -12,7 +12,7 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { /// ics02 client error(`{0}`) - Ics02Client(client_error::Error), + Client(client_error::Error), /// connection state is unknown: `{state}` InvalidState { state: i32 }, /// connection exists (was initialized) already: `{connection_id}` diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index f775c493a..b443e1d4b 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -227,7 +227,7 @@ mod tests { error::Error::Ics03Connection(e) => { assert_eq!( e.to_string(), - ics03_error::Error::Ics02Client(ics02_error::Error::ClientNotFound { + ics03_error::Error::Client(ics02_error::Error::ClientNotFound { client_id: ClientId::new(mock_client_type(), 45).unwrap() }) .to_string() diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 37d5becfe..341a02d11 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -708,7 +708,7 @@ impl ChannelReader for MockContext { fn client_state(&self, client_id: &ClientId) -> Result, Ics04Error> { ClientReader::client_state(self, client_id) - .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Client(e))) } fn client_consensus_state( @@ -717,7 +717,7 @@ impl ChannelReader for MockContext { height: Height, ) -> Result, Ics04Error> { ClientReader::consensus_state(self, client_id, height) - .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Client(e))) } fn get_next_sequence_send( @@ -863,7 +863,7 @@ impl ChannelReader for MockContext { fn pending_host_consensus_state(&self) -> Result, Ics04Error> { ClientReader::pending_host_consensus_state(self) - .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Client(e))) } fn client_update_time( @@ -1102,11 +1102,11 @@ impl ConnectionReader for MockContext { fn client_state(&self, client_id: &ClientId) -> Result, Ics03Error> { // Forward method call to the Ics2 Client-specific method. - ClientReader::client_state(self, client_id).map_err(Ics03Error::Ics02Client) + ClientReader::client_state(self, client_id).map_err(Ics03Error::Client) } fn decode_client_state(&self, client_state: Any) -> Result, Ics03Error> { - ClientReader::decode_client_state(self, client_state).map_err(Ics03Error::Ics02Client) + ClientReader::decode_client_state(self, client_state).map_err(Ics03Error::Client) } fn host_current_height(&self) -> Result { @@ -1129,11 +1129,11 @@ impl ConnectionReader for MockContext { ) -> Result, Ics03Error> { // Forward method call to the Ics2Client-specific method. self.consensus_state(client_id, height) - .map_err(Ics03Error::Ics02Client) + .map_err(Ics03Error::Client) } fn host_consensus_state(&self, height: Height) -> Result, Ics03Error> { - ClientReader::host_consensus_state(self, height).map_err(Ics03Error::Ics02Client) + ClientReader::host_consensus_state(self, height).map_err(Ics03Error::Client) } fn connection_counter(&self) -> Result { diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 116582a1c..80c3b36f9 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -255,7 +255,7 @@ impl SendPacketReader for DummyTransferModule { client_id: client_id.clone(), }), } - .map_err(|e| Error::Ics03Connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Error::Ics03Connection(Ics03Error::Client(e))) } fn client_consensus_state( @@ -276,7 +276,7 @@ impl SendPacketReader for DummyTransferModule { height, }), } - .map_err(|e| Error::Ics03Connection(Ics03Error::Ics02Client(e))) + .map_err(|e| Error::Ics03Connection(Ics03Error::Client(e))) } fn get_next_sequence_send( From 78d45e953ed526f97b8666e20eb642dce6eb74d0 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:28:45 +0800 Subject: [PATCH 19/43] Update Ics04Error --- crates/ibc/src/core/ics03_connection/error.rs | 2 +- crates/ibc/src/core/ics04_channel/error.rs | 8 ++++---- crates/ibc/src/core/ics04_channel/handler.rs | 8 ++++---- .../src/core/ics04_channel/handler/chan_open_try.rs | 4 ++-- crates/ibc/src/core/ics04_channel/msgs.rs | 12 ++++++------ crates/ibc/src/mock/context.rs | 10 +++++----- crates/ibc/src/test_utils.rs | 6 +++--- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 3d9694a8a..c6662aa5b 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -11,7 +11,7 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { - /// ics02 client error(`{0}`) + /// ICS02 client error(`{0}`) Client(client_error::Error), /// connection state is unknown: `{state}` InvalidState { state: i32 }, diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 44f64beab..3c8a1ac5f 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -17,10 +17,10 @@ use ibc_proto::protobuf::Error as TendermintError; #[derive(Debug, Display)] pub enum Error { - /// ics03 connection error(`{0}`) - Ics03Connection(connection_error::Error), - /// ics05 port error(`{0}`) - Ics05Port(port_error::Error), + /// ICS03 connection error(`{0}`) + Connection(connection_error::Error), + /// ICS05 port error(`{0}`) + Port(port_error::Error), /// channel state unknown: `{state}` UnknownState { state: i32 }, /// identifier error(`{0}`) diff --git a/crates/ibc/src/core/ics04_channel/handler.rs b/crates/ibc/src/core/ics04_channel/handler.rs index 7f41ae145..e753da328 100644 --- a/crates/ibc/src/core/ics04_channel/handler.rs +++ b/crates/ibc/src/core/ics04_channel/handler.rs @@ -229,16 +229,16 @@ where let module_id = match msg { PacketMsg::RecvPacket(msg) => ctx .lookup_module_by_port(&msg.packet.destination_port) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, PacketMsg::AckPacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, PacketMsg::TimeoutPacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, PacketMsg::TimeoutOnClosePacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, }; if ctx.router().has_route(&module_id) { diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index b443e1d4b..d9654a27e 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -198,7 +198,7 @@ mod tests { match_error: { let connection_id = msg.chan_end_on_b.connection_hops()[0].clone(); Box::new(move |e| match e { - error::Error::Ics03Connection(e) => { + error::Error::Connection(e) => { assert_eq!( e.to_string(), ics03_error::Error::ConnectionNotFound { connection_id } @@ -224,7 +224,7 @@ mod tests { msg: ChannelMsg::ChannelOpenTry(msg.clone()), want_pass: false, match_error: Box::new(|e| match e { - error::Error::Ics03Connection(e) => { + error::Error::Connection(e) => { assert_eq!( e.to_string(), ics03_error::Error::Client(ics02_error::Error::ClientNotFound { diff --git a/crates/ibc/src/core/ics04_channel/msgs.rs b/crates/ibc/src/core/ics04_channel/msgs.rs index 4a8a68c6e..97238f99b 100644 --- a/crates/ibc/src/core/ics04_channel/msgs.rs +++ b/crates/ibc/src/core/ics04_channel/msgs.rs @@ -46,22 +46,22 @@ impl ChannelMsg { let module_id = match self { ChannelMsg::ChannelOpenInit(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, ChannelMsg::ChannelOpenTry(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, ChannelMsg::ChannelOpenAck(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, ChannelMsg::ChannelOpenConfirm(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, ChannelMsg::ChannelCloseInit(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, ChannelMsg::ChannelCloseConfirm(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::Ics05Port)?, + .map_err(Error::Port)?, }; Ok(module_id) } diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 341a02d11..b11c434e8 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -693,7 +693,7 @@ impl ChannelReader for MockContext { } fn connection_end(&self, cid: &ConnectionId) -> Result { - ConnectionReader::connection_end(self, cid).map_err(Ics04Error::Ics03Connection) + ConnectionReader::connection_end(self, cid).map_err(Ics04Error::Connection) } fn connection_channels( @@ -708,7 +708,7 @@ impl ChannelReader for MockContext { fn client_state(&self, client_id: &ClientId) -> Result, Ics04Error> { ClientReader::client_state(self, client_id) - .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Client(e))) + .map_err(|e| Ics04Error::Connection(Ics03Error::Client(e))) } fn client_consensus_state( @@ -717,7 +717,7 @@ impl ChannelReader for MockContext { height: Height, ) -> Result, Ics04Error> { ClientReader::consensus_state(self, client_id, height) - .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Client(e))) + .map_err(|e| Ics04Error::Connection(Ics03Error::Client(e))) } fn get_next_sequence_send( @@ -858,12 +858,12 @@ impl ChannelReader for MockContext { } fn host_consensus_state(&self, height: Height) -> Result, Ics04Error> { - ConnectionReader::host_consensus_state(self, height).map_err(Ics04Error::Ics03Connection) + ConnectionReader::host_consensus_state(self, height).map_err(Ics04Error::Connection) } fn pending_host_consensus_state(&self) -> Result, Ics04Error> { ClientReader::pending_host_consensus_state(self) - .map_err(|e| Ics04Error::Ics03Connection(Ics03Error::Client(e))) + .map_err(|e| Ics04Error::Connection(Ics03Error::Client(e))) } fn client_update_time( diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 80c3b36f9..53764df20 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -238,7 +238,7 @@ impl SendPacketReader for DummyTransferModule { connection_id: cid.clone(), }), } - .map_err(Error::Ics03Connection) + .map_err(Error::Connection) } fn client_state(&self, client_id: &ClientId) -> Result, Error> { @@ -255,7 +255,7 @@ impl SendPacketReader for DummyTransferModule { client_id: client_id.clone(), }), } - .map_err(|e| Error::Ics03Connection(Ics03Error::Client(e))) + .map_err(|e| Error::Connection(Ics03Error::Client(e))) } fn client_consensus_state( @@ -276,7 +276,7 @@ impl SendPacketReader for DummyTransferModule { height, }), } - .map_err(|e| Error::Ics03Connection(Ics03Error::Client(e))) + .map_err(|e| Error::Connection(Ics03Error::Client(e))) } fn get_next_sequence_send( From 2ca3b77583c44943c727537a7a26782a3824b790 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:30:58 +0800 Subject: [PATCH 20/43] Update Ics26Error --- crates/ibc/src/core/context.rs | 4 +-- crates/ibc/src/core/ics26_routing/error.rs | 6 ++--- crates/ibc/src/core/ics26_routing/handler.rs | 26 ++++++++++---------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index a787c9eee..c761f1b75 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -52,7 +52,7 @@ pub trait ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::validate(self, message), } - .map_err(RouterError::Ics02Client), + .map_err(RouterError::Client), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), @@ -255,7 +255,7 @@ pub trait ExecutionContext: ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::execute(self, message), } - .map_err(RouterError::Ics02Client), + .map_err(RouterError::Client), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 5a2d91a36..11529890b 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -8,11 +8,11 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { /// ICS02 client error(`{0}`) - Ics02Client(ics02_client::error::Error), + Client(ics02_client::error::Error), /// ICS03 connection error(`{0}`) - Ics03Connection(ics03_connection::error::Error), + Connection(ics03_connection::error::Error), /// ICS04 channel error(`{0}`) - Ics04Channel(ics04_channel::error::Error), + Channel(ics04_channel::error::Error), /// unknown type URL `{url}` UnknownMessageTypeUrl { url: String }, /// the message is malformed and cannot be decoded, error(`{0}`) diff --git a/crates/ibc/src/core/ics26_routing/handler.rs b/crates/ibc/src/core/ics26_routing/handler.rs index 6f7dc02d9..17cefeea6 100644 --- a/crates/ibc/src/core/ics26_routing/handler.rs +++ b/crates/ibc/src/core/ics26_routing/handler.rs @@ -59,11 +59,11 @@ where { let output = match msg { ClientMsg(msg) => { - let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(Error::Ics02Client)?; + let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(Error::Client)?; // Apply the result to the context (host chain store). ctx.store_client_result(handler_output.result) - .map_err(Error::Ics02Client)?; + .map_err(Error::Client)?; HandlerOutput::builder() .with_log(handler_output.log) @@ -72,11 +72,11 @@ where } ConnectionMsg(msg) => { - let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(Error::Ics03Connection)?; + let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(Error::Connection)?; // Apply any results to the host chain store. ctx.store_connection_result(handler_output.result) - .map_err(Error::Ics03Connection)?; + .map_err(Error::Connection)?; HandlerOutput::builder() .with_log(handler_output.log) @@ -85,18 +85,18 @@ where } ChannelMsg(msg) => { - let module_id = channel_validate(ctx, &msg).map_err(Error::Ics04Channel)?; + let module_id = channel_validate(ctx, &msg).map_err(Error::Channel)?; let dispatch_output = HandlerOutputBuilder::<()>::new(); let (dispatch_log, mut channel_result) = - channel_dispatch(ctx, &msg).map_err(Error::Ics04Channel)?; + channel_dispatch(ctx, &msg).map_err(Error::Channel)?; // Note: `OpenInit` and `OpenTry` modify the `version` field of the `channel_result`, // so we must pass it mutably. We intend to clean this up with the implementation of // ADR 5. // See issue [#190](https://github.com/cosmos/ibc-rs/issues/190) let callback_extras = channel_callback(ctx, &module_id, &msg, &mut channel_result) - .map_err(Error::Ics04Channel)?; + .map_err(Error::Channel)?; // We need to construct events here instead of directly in the // `process` functions because we need to wait for the callback to @@ -111,7 +111,7 @@ where // Apply any results to the host chain store. ctx.store_channel_result(channel_result) - .map_err(Error::Ics04Channel)?; + .map_err(Error::Channel)?; dispatch_output .with_events(dispatch_events) @@ -128,20 +128,20 @@ where } PacketMsg(msg) => { - let module_id = get_module_for_packet_msg(ctx, &msg).map_err(Error::Ics04Channel)?; + let module_id = get_module_for_packet_msg(ctx, &msg).map_err(Error::Channel)?; let (mut handler_builder, packet_result) = - ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::Ics04Channel)?; + ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::Channel)?; if matches!(packet_result, PacketResult::Recv(RecvPacketResult::NoOp)) { return Ok(handler_builder.with_result(())); } let cb_result = ics4_packet_callback(ctx, &module_id, &msg, &mut handler_builder); - cb_result.map_err(Error::Ics04Channel)?; + cb_result.map_err(Error::Channel)?; // Apply any results to the host chain store. ctx.store_packet_result(packet_result) - .map_err(Error::Ics04Channel)?; + .map_err(Error::Channel)?; handler_builder.with_result(()) } @@ -632,7 +632,7 @@ mod tests { msg, ) .map(|_| ()) - .map_err(Error::Ics04Channel) + .map_err(Error::Channel) } }; From 070aea4d095499530bf3ed935e326c0a9494314a Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:32:29 +0800 Subject: [PATCH 21/43] Remove flex-error --- crates/ibc/Cargo.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 319b01c86..a4fb28abf 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -18,7 +18,7 @@ all-features = true [features] default = ["std"] -std = ["flex-error/std", "flex-error/eyre_tracer", "ibc-proto/std", "clock", "displaydoc/std" ] +std = ["ibc-proto/std", "clock", "displaydoc/std" ] clock = ["tendermint/clock", "time/std"] # This feature grants access to development-time mocking libraries, such as `MockContext` or `MockHeader`. @@ -40,7 +40,6 @@ bytes = { version = "1.2.1", default-features = false } safe-regex = { version = "0.2.5", default-features = false } subtle-encoding = { version = "0.5", default-features = false } sha2 = { version = "0.10.6", default-features = false } -flex-error = { version = "0.4.4", default-features = false } displaydoc = { version = "0.2", default-features = false } num-traits = { version = "0.2.15", default-features = false } derive_more = { version = "0.99.17", default-features = false, features = ["from", "into", "display"] } From a6c2ccb8de38381175ac00da5223537574cb044a Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:33:48 +0800 Subject: [PATCH 22/43] Update error.rs --- crates/ibc/src/core/ics04_channel/error.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 3c8a1ac5f..d5d53b8e7 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -167,9 +167,3 @@ pub enum Error { /// other error: `{description}` Other { description: String }, } - -// impl Error { -// pub fn chan_open_confirm_proof_verification(e: Error) -> Error { -// e.add_trace(&"Handshake proof verification fails at ChannelOpenConfirm") -// } -// } From d4985734d703251a783826be1477fe939f59f621 Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 24 Nov 2022 01:39:58 +0800 Subject: [PATCH 23/43] Create 164-refactor-error-system.md --- .changelog/unreleased/enhancement/164-refactor-error-system.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 .changelog/unreleased/enhancement/164-refactor-error-system.md diff --git a/.changelog/unreleased/enhancement/164-refactor-error-system.md b/.changelog/unreleased/enhancement/164-refactor-error-system.md new file mode 100644 index 000000000..c8d0d1176 --- /dev/null +++ b/.changelog/unreleased/enhancement/164-refactor-error-system.md @@ -0,0 +1 @@ +- Refactor error system ([#164](https://github.com/cosmos/ibc-rs/issues/164)) \ No newline at end of file From f0bf23b0de22a8296c67033a854ea14d29c405b0 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 00:00:09 +0800 Subject: [PATCH 24/43] Impl std::erorr::Error for IbcError --- crates/ibc/Cargo.toml | 21 ++++- crates/ibc/src/applications/transfer/error.rs | 55 +++++++++--- .../transfer/relay/send_transfer.rs | 8 +- .../ibc/src/clients/ics07_tendermint/error.rs | 33 ++++--- crates/ibc/src/core/ics02_client/error.rs | 86 +++++++++++++------ crates/ibc/src/core/ics02_client/height.rs | 12 ++- crates/ibc/src/core/ics03_connection/error.rs | 34 ++++++-- crates/ibc/src/core/ics04_channel/error.rs | 36 ++++++-- crates/ibc/src/core/ics05_port/error.rs | 3 + crates/ibc/src/core/ics23_commitment/error.rs | 15 +++- crates/ibc/src/core/ics24_host/error.rs | 3 + crates/ibc/src/core/ics24_host/path.rs | 3 + crates/ibc/src/core/ics26_routing/error.rs | 21 ++++- crates/ibc/src/events.rs | 30 +++++-- crates/ibc/src/proofs.rs | 3 + crates/ibc/src/signer.rs | 3 + crates/ibc/src/timestamp.rs | 14 ++- 17 files changed, 294 insertions(+), 86 deletions(-) diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index a4fb28abf..21fded570 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -18,7 +18,24 @@ all-features = true [features] default = ["std"] -std = ["ibc-proto/std", "clock", "displaydoc/std" ] +std = [ + "ibc-proto/std", + "ics23/std", + "serde/std", + "serde_json/std", + "erased-serde/std", + "tracing/std", + "prost/std", + "bytes/std", + "subtle-encoding/std", + "sha2/std", + "displaydoc/std", + "num-traits/std", + "uint/std", + "primitive-types/std", + "clock", + "tendermint/std", +] clock = ["tendermint/clock", "time/std"] # This feature grants access to development-time mocking libraries, such as `MockContext` or `MockHeader`. @@ -27,7 +44,7 @@ mocks = ["tendermint-testgen", "clock", "std"] [dependencies] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. -ibc-proto = { version = "0.22.0", default-features = false } +ibc-proto = { version = "0.22.0", default-features = false, git = "https://github.com/octopus-network/ibc-proto-rs.git", branch = "refactor-error-system" } ics23 = { version = "=0.8.1", default-features = false, features = ["host-functions"] } time = { version = ">=0.3.0, <0.3.18", default-features = false } serde_derive = { version = "1.0.104", default-features = false } diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index 2e1373976..c337d3ffb 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -16,25 +16,54 @@ use crate::prelude::*; use crate::signer::SignerError; #[cfg(feature = "std")] -impl std::error::Error for Error {} +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::ChannelError(e) => Some(e), + Error::InvalidPortId { + validation_error: e, + .. + } => Some(e), + Error::InvalidChannelId { + validation_error: e, + .. + } => Some(e), + Error::Utf8(e) => Some(e), + Error::InvalidTracePortId { + validation_error: e, + .. + } => Some(e), + Error::InvalidTraceChannelId { + validation_error: e, + .. + } => Some(e), + Error::InvalidAmount(e) => Some(e), + Error::Signer(e) => Some(e), + Error::ParseHex(e) => Some(e), + Error::DecodeRawMsg(e) => Some(e), + Error::Utf8Decode(e) => Some(e), + _ => None, + } + } +} #[derive(Display, Debug)] pub enum Error { /// unrecognized ICS-20 transfer message type URL `{url}` UnknowMessageTypeUrl { url: String }, - /// Ics04 channel error(`{0}`) - Ics04Channel(channel_error::Error), + /// ICS04 channel error + ChannelError(channel_error::Error), /// destination channel not found in the counterparty of port_id `{port_id}` and channel_id `{channel_id}` DestinationChannelNotFound { port_id: PortId, channel_id: ChannelId, }, - /// invalid port identifier `{context}` error(`{validation_error}`) + /// invalid port identifier `{context}` InvalidPortId { context: String, validation_error: ValidationError, }, - /// invalid channel identifier `{context}` error(`{validation_error}`) + /// invalid channel identifier `{context}` InvalidChannelId { context: String, validation_error: ValidationError, @@ -43,33 +72,33 @@ pub enum Error { InvalidPacketTimeoutHeight { context: String }, /// invalid packet timeout timestamp value `{timestamp}` InvalidPacketTimeoutTimestamp { timestamp: u64 }, - /// utf8 decoding error(`{0}`) + /// utf8 decoding error Utf8(FromUtf8Error), /// base denomination is empty EmptyBaseDenom, - /// invalid prot id n trace at postion: `{pos}`, error(`{validation_error}`) + /// invalid prot id n trace at postion: `{pos}` InvalidTracePortId { pos: usize, validation_error: ValidationError, }, - /// invalid channel id in trace at position: `{pos}`, error(`{validation_error}`) + /// invalid channel id in trace at position: `{pos}` InvalidTraceChannelId { pos: usize, validation_error: ValidationError, }, /// trace length must be even but got: `{len}` InvalidTraceLength { len: usize }, - /// invalid amount error(`{0}`) + /// invalid amount error InvalidAmount(FromDecStrErr), /// invalid token InvalidToken, - /// failed to parse signer error(`{0}`) + /// failed to parse signer error Signer(SignerError), /// missing 'ibc/' prefix in denomination MissingDenomIbcPrefix, /// hashed denom must be of the form 'ibc/Hash' MalformedHashDenom, - /// invalid hex string error(`{0}`) + /// invalid hex string error ParseHex(EncodingError), /// expected `{expect_order}` channel, got `{got_order}` ChannelNotUnordered { @@ -105,13 +134,13 @@ pub enum Error { }, /// no trace associated with specified hash TraceNotFound, - /// error decoding raw msg error(`{0}`) + /// error decoding raw msg DecodeRawMsg(TendermintProtoError), /// unknown msg type: `{msg_type}` UnknownMsgType { msg_type: String }, /// invalid coin string: `{coin}` InvalidCoin { coin: String }, - /// error decoding raw bytes as UTF8 string error(`{0}`) + /// error decoding raw bytes as UTF8 string Utf8Decode(Utf8Error), } diff --git a/crates/ibc/src/applications/transfer/relay/send_transfer.rs b/crates/ibc/src/applications/transfer/relay/send_transfer.rs index eb0206137..9f3414bd4 100644 --- a/crates/ibc/src/applications/transfer/relay/send_transfer.rs +++ b/crates/ibc/src/applications/transfer/relay/send_transfer.rs @@ -28,7 +28,7 @@ where let source_channel_end = ctx .channel_end(&msg.source_port, &msg.source_channel) - .map_err(Error::Ics04Channel)?; + .map_err(Error::ChannelError)?; let destination_port = source_channel_end.counterparty().port_id().clone(); let destination_channel = source_channel_end @@ -43,7 +43,7 @@ where // get the next sequence let sequence = ctx .get_next_sequence_send(&msg.source_port, &msg.source_channel) - .map_err(Error::Ics04Channel)?; + .map_err(Error::ChannelError)?; let token = msg.token.try_into().map_err(|_| Error::InvalidToken)?; let denom = token.denom.clone(); @@ -90,10 +90,10 @@ where result, log, events, - } = send_packet(ctx, packet).map_err(Error::Ics04Channel)?; + } = send_packet(ctx, packet).map_err(Error::ChannelError)?; ctx.store_send_packet_result(result) - .map_err(Error::Ics04Channel)?; + .map_err(Error::ChannelError)?; output.merge_output( HandlerOutput::builder() diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index 92115837c..6cbac4c3e 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -12,9 +12,6 @@ use tendermint::hash::Hash; use tendermint::Error as TendermintError; use tendermint_light_client_verifier::errors::VerificationErrorDetail as LightClientErrorDetail; -#[cfg(feature = "std")] -impl std::error::Error for Error {} - #[derive(Debug, Display)] pub enum Error { /// chain-id is (`{chain_id}`) is too long, got: `{len}`, max allowed: `{max_len}` @@ -29,14 +26,14 @@ pub enum Error { InvalidUnbondingPeriod { reason: String }, /// invalid address InvalidAddress, - /// invalid header, failed basic validation: `{reason}`, error(`{error}`) + /// invalid header, failed basic validation: `{reason}` InvalidHeader { reason: String, error: TendermintError, }, /// invalid client state trust threshold: `{reason}` InvalidTrustThreshold { reason: String }, - /// invalid tendermint client state trust threshold, error(`{0}`) + /// invalid tendermint client state trust threshold InvalidTendermintTrustThreshold(TendermintError), /// invalid client state max clock drift: `{reason}` InvalidMaxClockDrift { reason: String }, @@ -58,7 +55,7 @@ pub enum Error { MissingTrustingPeriod, /// missing unbonding period MissingUnbondingPeriod, - /// invalid chain identifier, error(`{0}`) + /// invalid chain identifier InvalidChainIdentifier(ValidationError), /// negative trusting period NegativeTrustingPeriod, @@ -72,7 +69,7 @@ pub enum Error { MissingLatestHeight, /// invalid frozen height InvalidFrozenHeight, - /// invalid chain identifier: `{raw_value}`, error(`{error}`) + /// invalid chain identifier: `{raw_value}` InvalidChainId { raw_value: String, error: ValidationError, @@ -81,11 +78,11 @@ pub enum Error { InvalidRawHeight { raw_height: u64 }, /// invalid raw client consensus state: `{reason}` InvalidRawConsensusState { reason: String }, - /// invalid raw header, error(`{0}`) + /// invalid raw header InvalidRawHeader(TendermintError), /// invalid raw misbehaviour: `{reason}` InvalidRawMisbehaviour { reason: String }, - /// decode error, error(`{0}`) + /// decode error Decode(prost::DecodeError), /// insufficient overlap: `{reason}` InsufficientVotingPower { reason: String }, @@ -97,7 +94,7 @@ pub enum Error { HeaderTimestampTooHigh { actual: String, max: String }, /// given other previous updates, header timestamp should be at least `{min}`, but was `{actual}` HeaderTimestampTooLow { actual: String, min: String }, - /// timestamp overflowed, error(`{0}`) + /// timestamp overflowed TimestampOverflow(TimestampOverflowError), /// not enough time elapsed, current timestamp `{current_time}` is still less than earliest acceptable timestamp `{earliest_time}` NotEnoughTimeElapsed { @@ -145,6 +142,22 @@ pub enum Error { }, } +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::InvalidHeader { error: e, .. } => Some(e), + Error::InvalidTendermintTrustThreshold(e) => Some(e), + Error::InvalidChainIdentifier(e) => Some(e), + Error::InvalidChainId { error: e, .. } => Some(e), + Error::InvalidRawHeader(e) => Some(e), + Error::Decode(e) => Some(e), + Error::TimestampOverflow(e) => Some(e), + _ => None, + } + } +} + #[cfg(feature = "std")] impl std::error::Error for VerificationError {} diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 4f2a82f70..164d71850 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -1,5 +1,4 @@ use crate::prelude::*; - use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; @@ -12,14 +11,11 @@ use crate::signer::SignerError; use crate::timestamp::Timestamp; use crate::Height; -#[cfg(feature = "std")] -impl std::error::Error for Error {} - #[derive(Debug, Display)] pub enum Error { /// unknown client type: `{client_type}` UnknownClientType { client_type: String }, - /// Client identifier constructor failed for type `{client_type}` with counter `{counter}`, error(`{validation_error}`) + /// Client identifier constructor failed for type `{client_type}` with counter `{counter}` ClientIdentifierConstructor { client_type: ClientType, counter: u64, @@ -55,38 +51,38 @@ pub enum Error { UnknownHeaderType { header_type: String }, /// unknown misbehaviour type: `{misbehavior_type}` UnknownMisbehaviourType { misbehavior_type: String }, - /// invalid raw client identifier `{client_id}`, error(`{validation_error}`) + /// invalid raw client identifier `{client_id}` InvalidRawClientId { client_id: String, validation_error: ValidationError, }, - /// error decoding raw client state, error(`{0}`) + /// error decoding raw client state DecodeRawClientState(TendermintProtoError), /// missing raw client state MissingRawClientState, - /// invalid raw client consensus state, error(`{0}`) + /// invalid raw client consensus state InvalidRawConsensusState(TendermintProtoError), /// missing raw client consensus state MissingRawConsensusState, - /// invalid client id in the update client message, error(`{0}`) + /// invalid client id in the update client message InvalidMsgUpdateClientId(ValidationError), - /// decode error(`{0}`) + /// decode error Decode(prost::DecodeError), /// invalid raw client consensus state: the height field is missing MissingHeight, - /// invalid client identifier, error(`{0}`) + /// invalid client identifier InvalidClientIdentifier(ValidationError), - /// invalid raw header, error(`{0}`) + /// invalid raw header InvalidRawHeader(TendermintProtoError), /// missing raw header MissingRawHeader, - /// invalid raw misbehaviour, error(`{0}`) + /// invalid raw misbehaviour DecodeRawMisbehaviour(TendermintProtoError), - /// invalid raw misbehaviour, error(`{0}`) + /// invalid raw misbehaviour InvalidRawMisbehaviour(ValidationError), /// missing raw misbehaviour MissingRawMisbehaviour, - /// String `{value}` cannnot be converted to height, error(`{height_error}`) + /// String `{value}` cannnot be converted to height InvalidStringAsHeight { value: String, height_error: HeightError, @@ -97,15 +93,15 @@ pub enum Error { InvalidHeightResult, /// invalid address InvalidAddress, - /// invalid proof for the upgraded client state, error(`{0}`) + /// invalid proof for the upgraded client state InvalidUpgradeClientProof(Ics23Error), - /// invalid proof for the upgraded consensus state, error(`{0}`) + /// invalid proof for the upgraded consensus state InvalidUpgradeConsensusStateProof(Ics23Error), - /// invalid commitment proof bytes, error(`{0}`) + /// invalid commitment proof bytes InvalidCommitmentProof(Ics23Error), - /// invalid packet timeout timestamp value, error(`{0}`) + /// invalid packet timeout timestamp value InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), - /// mismatch between client and arguments types, expected: `{client_type}` + /// mismatch between client and arguments types ClientArgsTypeMismatch { client_type: ClientType }, /// Insufficient overlap `{reason}` InsufficientVotingPower { reason: String }, @@ -133,20 +129,58 @@ pub enum Error { }, /// the local consensus state could not be retrieved for height `{height}` MissingLocalConsensusState { height: Height }, - /// invalid connection end, error(`{0}`) + /// invalid connection end InvalidConnectionEnd(TendermintProtoError), - /// invalid channel end, error(`{0}`) + /// invalid channel end InvalidChannelEnd(TendermintProtoError), - /// invalid any client state, error(`{0}`) + /// invalid any client state InvalidAnyClientState(TendermintProtoError), - /// invalid any client consensus state, error(`{0}`) + /// invalid any client consensus state InvalidAnyConsensusState(TendermintProtoError), - /// failed to parse signer, error(`{0}`) + /// failed to parse signer Signer(SignerError), - /// ics23 verification failure, error(`{0}`) + /// ics23 verification failure Ics23Verification(Ics23Error), /// client specific error: `{description}` ClientSpecific { description: String }, /// other error: `{description}` Other { description: String }, } + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::ClientIdentifierConstructor { + validation_error: e, + .. + } => Some(e), + Error::InvalidRawClientId { + validation_error: e, + .. + } => Some(e), + Error::DecodeRawClientState(e) => Some(e), + Error::InvalidRawConsensusState(e) => Some(e), + Error::InvalidMsgUpdateClientId(e) => Some(e), + Error::Decode(e) => Some(e), + Error::InvalidClientIdentifier(e) => Some(e), + Error::InvalidRawHeader(e) => Some(e), + Error::DecodeRawMisbehaviour(e) => Some(e), + Error::InvalidRawMisbehaviour(e) => Some(e), + Error::InvalidStringAsHeight { + height_error: e, .. + } => Some(e), + Error::InvalidUpgradeClientProof(e) => Some(e), + Error::InvalidUpgradeConsensusStateProof(e) => Some(e), + Error::InvalidCommitmentProof(e) => Some(e), + Error::InvalidPacketTimestamp(e) => Some(e), + Error::InvalidConnectionEnd(e) => Some(e), + Error::InvalidChannelEnd(e) => Some(e), + Error::InvalidAnyClientState(e) => Some(e), + Error::InvalidAnyConsensusState(e) => Some(e), + Error::Signer(e) => Some(e), + Error::Ics23Verification(e) => Some(e), + _ => None, + } + } +} diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index fcf0d543c..49e84e235 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -127,7 +127,7 @@ impl core::fmt::Display for Height { #[derive(Debug, Display)] pub enum HeightError { - /// cannot convert into a `Height` type from string `{height}`, error(`{error}`) + /// cannot convert into a `Height` type from string `{height}` HeightConversion { height: String, error: ParseIntError, @@ -136,6 +136,16 @@ pub enum HeightError { ZeroHeight, } +#[cfg(feature = "std")] +impl std::error::Error for HeightError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + HeightError::HeightConversion { error: e, .. } => Some(e), + HeightError::ZeroHeight => None, + } + } +} + impl TryFrom<&str> for Height { type Error = HeightError; diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index c6662aa5b..99c933b98 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -11,7 +11,7 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { - /// ICS02 client error(`{0}`) + /// ICS02 client error Client(client_error::Error), /// connection state is unknown: `{state}` InvalidState { state: i32 }, @@ -29,7 +29,7 @@ pub enum Error { target_height: Height, oldest_height: Height, }, - /// identifier error(`{0}`) + /// identifier error InvalidIdentifier(ValidationError), /// ConnectionEnd domain object could not be constructed out of empty proto object EmptyProtoConnectionEnd, @@ -47,11 +47,11 @@ pub enum Error { MissingProofHeight, /// missing consensus height MissingConsensusHeight, - /// invalid connection proof, error(`{0}`) + /// invalid connection proof InvalidProof(ProofError), - /// error verifying connnection state, error(`{0}`) + /// error verifying connnection state VerifyConnectionState(client_error::Error), - /// invalid signer, error(`{0}`) + /// invalid signer Signer(SignerError), /// no connection was found for the previous connection id provided `{connection_id}` ConnectionNotFound { connection_id: ConnectionId }, @@ -74,12 +74,12 @@ pub enum Error { FrozenClient { client_id: ClientId }, /// the connection proof verification failed ConnectionVerificationFailure, - /// the consensus proof verification failed (height: `{height}`), error(`{client_error}`) + /// the consensus proof verification failed (height: `{height}`) ConsensusStateVerificationFailure { height: Height, client_error: client_error::Error, }, - /// the client state proof verification failed for client id `{client_id}`, error(`{client_error}`) + /// the client state proof verification failed for client id `{client_id}` ClientStateVerificationFailure { // TODO: use more specific error source client_id: ClientId, @@ -92,3 +92,23 @@ pub enum Error { /// other error: `{description}` Other { description: String }, } + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::Client(e) => Some(e), + Error::InvalidIdentifier(e) => Some(e), + Error::InvalidProof(e) => Some(e), + Error::VerifyConnectionState(e) => Some(e), + Error::Signer(e) => Some(e), + Error::ConsensusStateVerificationFailure { + client_error: e, .. + } => Some(e), + Error::ClientStateVerificationFailure { + client_error: e, .. + } => Some(e), + _ => None, + } + } +} diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index d5d53b8e7..ec08b99cb 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -17,13 +17,13 @@ use ibc_proto::protobuf::Error as TendermintError; #[derive(Debug, Display)] pub enum Error { - /// ICS03 connection error(`{0}`) + /// ICS03 connection error Connection(connection_error::Error), - /// ICS05 port error(`{0}`) + /// ICS05 port error Port(port_error::Error), /// channel state unknown: `{state}` UnknownState { state: i32 }, - /// identifier error(`{0}`) + /// identifier error Identifier(ValidationError), /// channel order type unknown: `{type_id}` UnknownOrderType { type_id: String }, @@ -34,11 +34,11 @@ pub enum Error { port_id: PortId, channel_id: ChannelId, }, - /// invalid version, error(`{0}`) + /// invalid version InvalidVersion(TendermintError), - /// invalid signer address, error(`{0}`) + /// invalid signer address Signer(SignerError), - /// invalid proof, error(`{0}`) + /// invalid proof InvalidProof(ProofError), /// invalid proof: missing height MissingHeight, @@ -87,7 +87,7 @@ pub enum Error { sequence: Sequence, ics02_error: client_error::Error, }, - /// Error verifying channel state, error(`{0}`) + /// Error verifying channel state VerifyChannelFailed(client_error::Error), /// Acknowledgment cannot be empty InvalidAcknowledgement, @@ -98,7 +98,7 @@ pub enum Error { port_id: PortId, channel_id: ChannelId, }, - /// String `{value}` cannot be converted to packet sequence, error(`{error}`) + /// String `{value}` cannot be converted to packet sequence InvalidStringAsSequence { value: String, error: core::num::ParseIntError, @@ -125,7 +125,7 @@ pub enum Error { }, /// Receiving chain block timestamp >= packet timeout timestamp LowPacketTimestamp, - /// Invalid packet timeout timestamp value, error(`{0}`) + /// Invalid packet timeout timestamp value InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), /// Invalid timestamp in consensus state; timestamp must be a positive value ErrorInvalidConsensusState, @@ -167,3 +167,21 @@ pub enum Error { /// other error: `{description}` Other { description: String }, } + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::Connection(e) => Some(e), + Error::Port(e) => Some(e), + Error::Identifier(e) => Some(e), + Error::InvalidVersion(e) => Some(e), + Error::Signer(e) => Some(e), + Error::InvalidProof(e) => Some(e), + Error::PacketVerificationFailed { ics02_error: e, .. } => Some(e), + Error::InvalidStringAsSequence { error: e, .. } => Some(e), + Error::InvalidPacketTimestamp(e) => Some(e), + _ => None, + } + } +} diff --git a/crates/ibc/src/core/ics05_port/error.rs b/crates/ibc/src/core/ics05_port/error.rs index e9978f4ab..335495d36 100644 --- a/crates/ibc/src/core/ics05_port/error.rs +++ b/crates/ibc/src/core/ics05_port/error.rs @@ -12,3 +12,6 @@ pub enum Error { /// implementation specific error ImplementationSpecific, } + +#[cfg(feature = "std")] +impl std::error::Error for Error {} diff --git a/crates/ibc/src/core/ics23_commitment/error.rs b/crates/ibc/src/core/ics23_commitment/error.rs index df0d9c9b3..2ff424de6 100644 --- a/crates/ibc/src/core/ics23_commitment/error.rs +++ b/crates/ibc/src/core/ics23_commitment/error.rs @@ -3,9 +3,9 @@ use prost::DecodeError; #[derive(Debug, Display)] pub enum Error { - /// invalid raw merkle proof, error(`{0}`) + /// invalid raw merkle proof InvalidRawMerkleProof(DecodeError), - /// failed to decode commitment proof, error(`{0}`) + /// failed to decode commitment proof CommitmentProofDecodingFailed(DecodeError), /// empty commitment prefix EmptyCommitmentPrefix, @@ -24,3 +24,14 @@ pub enum Error { /// proof verification failed VerificationFailure, } + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::InvalidRawMerkleProof(e) => Some(e), + Error::CommitmentProofDecodingFailed(e) => Some(e), + _ => None, + } + } +} diff --git a/crates/ibc/src/core/ics24_host/error.rs b/crates/ibc/src/core/ics24_host/error.rs index 5dc37d1e1..5fdcf932a 100644 --- a/crates/ibc/src/core/ics24_host/error.rs +++ b/crates/ibc/src/core/ics24_host/error.rs @@ -22,3 +22,6 @@ pub enum ValidationError { /// Invalid channel id in counterparty InvalidCounterpartyChannelId, } + +#[cfg(feature = "std")] +impl std::error::Error for ValidationError {} diff --git a/crates/ibc/src/core/ics24_host/path.rs b/crates/ibc/src/core/ics24_host/path.rs index 2fbcf8b64..06abfa264 100644 --- a/crates/ibc/src/core/ics24_host/path.rs +++ b/crates/ibc/src/core/ics24_host/path.rs @@ -183,6 +183,9 @@ pub enum PathError { ParseFailure { path: String }, } +#[cfg(feature = "std")] +impl std::error::Error for PathError {} + /// The FromStr trait allows paths encoded as strings to be parsed into Paths. impl FromStr for Path { type Err = PathError; diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 11529890b..813098d37 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -7,14 +7,27 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { - /// ICS02 client error(`{0}`) + /// ICS02 client error Client(ics02_client::error::Error), - /// ICS03 connection error(`{0}`) + /// ICS03 connection error Connection(ics03_connection::error::Error), - /// ICS04 channel error(`{0}`) + /// ICS04 channel error Channel(ics04_channel::error::Error), /// unknown type URL `{url}` UnknownMessageTypeUrl { url: String }, - /// the message is malformed and cannot be decoded, error(`{0}`) + /// the message is malformed and cannot be decoded MalformedMessageBytes(ibc_proto::protobuf::Error), } + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::Client(e) => Some(e), + Error::Connection(e) => Some(e), + Error::Channel(e) => Some(e), + Error::UnknownMessageTypeUrl { .. } => None, + Error::MalformedMessageBytes(e) => Some(e), + } + } +} diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index 8e12f4ba6..ce68ff504 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -20,21 +20,21 @@ use crate::timestamp::ParseTimestampError; pub enum Error { /// error parsing height Height, - /// parse error, error(`{0}`) + /// parse error Parse(ValidationError), - /// ICS02 client error, error(`{0}`) + /// ICS02 client error Client(client_error::Error), - /// connection error, error(`{0}`) + /// connection error Connection(connection_error::Error), - /// channel error, error(`{0}`) + /// channel error Channel(channel_error::Error), - /// error parsing timestamp, error(`{0}`) + /// error parsing timestamp Timestamp(ParseTimestampError), /// missing event key `{key}` MissingKey { key: String }, - /// error decoding protobuf, error(`{0}`) + /// error decoding protobuf Decode(prost::DecodeError), - /// error decoding hex, error(`{0}`) + /// error decoding hex SubtleEncoding(subtle_encoding::Error), /// missing action string MissingActionString, @@ -46,6 +46,22 @@ pub enum Error { UnsupportedAbciEvent { event_type: String }, } +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::Parse(e) => Some(e), + Error::Client(e) => Some(e), + Error::Connection(e) => Some(e), + Error::Channel(e) => Some(e), + Error::Timestamp(e) => Some(e), + Error::Decode(e) => Some(e), + Error::SubtleEncoding(e) => Some(e), + _ => None, + } + } +} + /// Events whose data is not included in the app state and must be extracted using tendermint RPCs /// (i.e. /tx_search or /block_search) #[derive(Debug, Clone, Deserialize, Serialize)] diff --git a/crates/ibc/src/proofs.rs b/crates/ibc/src/proofs.rs index 01725ec51..0eb21cf3d 100644 --- a/crates/ibc/src/proofs.rs +++ b/crates/ibc/src/proofs.rs @@ -12,6 +12,9 @@ pub enum ProofError { EmptyProof, } +#[cfg(feature = "std")] +impl std::error::Error for ProofError {} + /// Structure comprising proofs in a message. Proofs are typically present in messages for /// handshake protocols, e.g., ICS3 connection (open) handshake or ICS4 channel (open and close) /// handshake, as well as for ICS4 packets, timeouts, and acknowledgements. diff --git a/crates/ibc/src/signer.rs b/crates/ibc/src/signer.rs index 01ea54bcf..ee273ed4d 100644 --- a/crates/ibc/src/signer.rs +++ b/crates/ibc/src/signer.rs @@ -11,6 +11,9 @@ pub enum SignerError { EmptySigner, } +#[cfg(feature = "std")] +impl std::error::Error for SignerError {} + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Display)] pub struct Signer(String); diff --git a/crates/ibc/src/timestamp.rs b/crates/ibc/src/timestamp.rs index ff3b5b512..8af96731c 100644 --- a/crates/ibc/src/timestamp.rs +++ b/crates/ibc/src/timestamp.rs @@ -182,6 +182,9 @@ pub enum TimestampOverflowError { TimestampOverflow, } +#[cfg(feature = "std")] +impl std::error::Error for TimestampOverflowError {} + impl Add for Timestamp { type Output = Result; @@ -214,10 +217,19 @@ impl Sub for Timestamp { #[derive(Debug, Display)] pub enum ParseTimestampError { - /// error parsing u64 integer from string, error(`{0}`) + /// error parsing u64 integer from string ParseInt(ParseIntError), } +#[cfg(feature = "std")] +impl std::error::Error for ParseTimestampError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + ParseTimestampError::ParseInt(e) => Some(e), + } + } +} + impl FromStr for Timestamp { type Err = ParseTimestampError; From c1c0b58266b7cc0d2d1b8a74b59cc2ffa1a36db1 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 00:04:30 +0800 Subject: [PATCH 25/43] Add #![allow(clippy::result_large_err)] --- crates/ibc/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ibc/src/lib.rs b/crates/ibc/src/lib.rs index 8c186b8b6..97cd33e22 100644 --- a/crates/ibc/src/lib.rs +++ b/crates/ibc/src/lib.rs @@ -4,6 +4,7 @@ #![no_std] #![allow(clippy::large_enum_variant)] +#![allow(clippy::result_large_err)] #![deny( warnings, trivial_casts, From 0da59dbfe84c9b8cfe68fd7133de646c229b5837 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 01:07:06 +0800 Subject: [PATCH 26/43] Rename Ics02Error to ClientError --- .../clients/ics07_tendermint/client_state.rs | 88 +++++++++---------- .../ics07_tendermint/consensus_state.rs | 6 +- .../ibc/src/clients/ics07_tendermint/error.rs | 4 +- .../src/clients/ics07_tendermint/header.rs | 8 +- crates/ibc/src/core/context.rs | 2 +- .../ibc/src/core/ics02_client/client_state.rs | 28 +++--- .../src/core/ics02_client/consensus_state.rs | 4 +- crates/ibc/src/core/ics02_client/context.rs | 36 ++++---- crates/ibc/src/core/ics02_client/error.rs | 46 +++++----- crates/ibc/src/core/ics02_client/handler.rs | 4 +- .../ics02_client/handler/create_client.rs | 22 +++-- .../ics02_client/handler/update_client.rs | 36 ++++---- .../ics02_client/handler/upgrade_client.rs | 22 ++--- crates/ibc/src/core/ics02_client/header.rs | 4 +- crates/ibc/src/core/ics02_client/height.rs | 14 +-- .../core/ics02_client/msgs/create_client.rs | 20 +++-- .../core/ics02_client/msgs/misbehaviour.rs | 12 +-- .../core/ics02_client/msgs/update_client.rs | 10 +-- .../core/ics02_client/msgs/upgrade_client.rs | 24 ++--- .../src/core/ics02_client/trust_threshold.rs | 22 ++--- .../src/core/ics03_connection/connection.rs | 2 +- crates/ibc/src/core/ics03_connection/error.rs | 8 +- crates/ibc/src/core/ics04_channel/error.rs | 4 +- .../ics04_channel/handler/chan_open_try.rs | 2 +- crates/ibc/src/core/ics04_channel/timeout.rs | 6 +- crates/ibc/src/core/ics26_routing/error.rs | 2 +- crates/ibc/src/events.rs | 2 +- crates/ibc/src/mock/client_state.rs | 42 ++++----- crates/ibc/src/mock/consensus_state.rs | 16 ++-- crates/ibc/src/mock/context.rs | 54 ++++++------ crates/ibc/src/mock/header.rs | 16 ++-- crates/ibc/src/mock/host.rs | 6 +- crates/ibc/src/mock/misbehaviour.rs | 8 +- crates/ibc/src/test_utils.rs | 10 +-- 34 files changed, 304 insertions(+), 286 deletions(-) diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index 4b62e58b9..ded507b2f 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -38,7 +38,7 @@ use crate::core::ics02_client::client_state::{ }; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::Error as Ics02Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::trust_threshold::TrustThreshold; use crate::core::ics04_channel::context::ChannelReader; use crate::core::ics23_commitment::specs::ProofSpecs; @@ -216,7 +216,7 @@ impl ClientState { /// Tendermint-specific light client verification. pub fn as_light_client_options(&self) -> Result { Ok(Options { - trust_threshold: self.trust_level.try_into().map_err(|e: Ics02Error| { + trust_threshold: self.trust_level.try_into().map_err(|e: ClientError| { Error::InvalidTrustThreshold { reason: e.to_string(), } @@ -327,7 +327,7 @@ impl Ics2ClientState for ClientState { elapsed > self.trusting_period } - fn initialise(&self, consensus_state: Any) -> Result, Ics02Error> { + fn initialise(&self, consensus_state: Any) -> Result, ClientError> { TmConsensusState::try_from(consensus_state).map(TmConsensusState::into_box) } @@ -336,16 +336,16 @@ impl Ics2ClientState for ClientState { ctx: &dyn ClientReader, client_id: ClientId, header: Any, - ) -> Result { + ) -> Result { fn maybe_consensus_state( ctx: &dyn ClientReader, client_id: &ClientId, height: Height, - ) -> Result>, Ics02Error> { + ) -> Result>, ClientError> { match ctx.consensus_state(client_id, height) { Ok(cs) => Ok(Some(cs)), Err(e) => match e { - Ics02Error::ConsensusStateNotFound { + ClientError::ConsensusStateNotFound { client_id: _, height: _, } => Ok(None), @@ -358,7 +358,7 @@ impl Ics2ClientState for ClientState { let header = TmHeader::try_from(header)?; if header.height().revision_number() != client_state.chain_id().version() { - return Err(Ics02Error::ClientSpecific { + return Err(ClientError::ClientSpecific { description: Error::MismatchedRevisions { current_revision: client_state.chain_id().version(), update_revision: header.height().revision_number(), @@ -400,7 +400,7 @@ impl Ics2ClientState for ClientState { .trusted_height .revision_height() .try_into() - .map_err(|_| Ics02Error::ClientSpecific { + .map_err(|_| ClientError::ClientSpecific { description: Error::InvalidHeaderHeight { height: header.trusted_height.revision_height(), } @@ -464,7 +464,7 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur after next // consensus state's height if header.signed_header.header().time > next_cs.timestamp { - return Err(Ics02Error::ClientSpecific { + return Err(ClientError::ClientSpecific { description: Error::HeaderTimestampTooHigh { actual: header.signed_header.header().time.to_string(), max: next_cs.timestamp.to_string(), @@ -487,7 +487,7 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur before the // previous consensus state's height if header.signed_header.header().time < prev_cs.timestamp { - return Err(Ics02Error::ClientSpecific { + return Err(ClientError::ClientSpecific { description: Error::HeaderTimestampTooLow { actual: header.signed_header.header().time.to_string(), min: prev_cs.timestamp.to_string(), @@ -509,16 +509,16 @@ impl Ics2ClientState for ClientState { ctx: &dyn ValidationContext, client_id: ClientId, header: Any, - ) -> Result { + ) -> Result { fn maybe_consensus_state( ctx: &dyn ValidationContext, client_id: &ClientId, height: Height, - ) -> Result>, Ics02Error> { + ) -> Result>, ClientError> { match ctx.consensus_state(client_id, height) { Ok(cs) => Ok(Some(cs)), Err(e) => match e { - Ics02Error::ConsensusStateNotFound { + ClientError::ConsensusStateNotFound { client_id: _, height: _, } => Ok(None), @@ -531,7 +531,7 @@ impl Ics2ClientState for ClientState { let header = TmHeader::try_from(header)?; if header.height().revision_number() != client_state.chain_id().version() { - return Err(Ics02Error::ClientSpecific { + return Err(ClientError::ClientSpecific { description: Error::MismatchedRevisions { current_revision: client_state.chain_id().version(), update_revision: header.height().revision_number(), @@ -573,7 +573,7 @@ impl Ics2ClientState for ClientState { .trusted_height .revision_height() .try_into() - .map_err(|_| Ics02Error::ClientSpecific { + .map_err(|_| ClientError::ClientSpecific { description: Error::InvalidHeaderHeight { height: header.trusted_height.revision_height(), } @@ -637,7 +637,7 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur after next // consensus state's height if header.signed_header.header().time > next_cs.timestamp { - return Err(Ics02Error::ClientSpecific { + return Err(ClientError::ClientSpecific { description: Error::HeaderTimestampTooHigh { actual: header.signed_header.header().time.to_string(), max: next_cs.timestamp.to_string(), @@ -660,7 +660,7 @@ impl Ics2ClientState for ClientState { // New (untrusted) header timestamp cannot occur before the // previous consensus state's height if header.signed_header.header().time < prev_cs.timestamp { - return Err(Ics02Error::ClientSpecific { + return Err(ClientError::ClientSpecific { description: Error::HeaderTimestampTooLow { actual: header.signed_header.header().time.to_string(), min: prev_cs.timestamp.to_string(), @@ -682,7 +682,7 @@ impl Ics2ClientState for ClientState { _consensus_state: Any, _proof_upgrade_client: RawMerkleProof, _proof_upgrade_consensus_state: RawMerkleProof, - ) -> Result { + ) -> Result { unimplemented!() } @@ -695,7 +695,7 @@ impl Ics2ClientState for ClientState { client_id: &ClientId, consensus_height: Height, expected_consensus_state: &dyn ConsensusState, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; @@ -706,7 +706,7 @@ impl Ics2ClientState for ClientState { }; let value = expected_consensus_state .encode_vec() - .map_err(Ics02Error::InvalidAnyConsensusState)?; + .map_err(ClientError::InvalidAnyConsensusState)?; verify_membership(client_state, prefix, proof, root, path, value) } @@ -719,14 +719,14 @@ impl Ics2ClientState for ClientState { root: &CommitmentRoot, connection_id: &ConnectionId, expected_connection_end: &ConnectionEnd, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; let path = ConnectionsPath(connection_id.clone()); let value = expected_connection_end .encode_vec() - .map_err(Ics02Error::InvalidConnectionEnd)?; + .map_err(ClientError::InvalidConnectionEnd)?; verify_membership(client_state, prefix, proof, root, path, value) } @@ -739,14 +739,14 @@ impl Ics2ClientState for ClientState { port_id: &PortId, channel_id: &ChannelId, expected_channel_end: &crate::core::ics04_channel::channel::ChannelEnd, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; let path = ChannelEndsPath(port_id.clone(), channel_id.clone()); let value = expected_channel_end .encode_vec() - .map_err(Ics02Error::InvalidChannelEnd)?; + .map_err(ClientError::InvalidChannelEnd)?; verify_membership(client_state, prefix, proof, root, path, value) } @@ -758,7 +758,7 @@ impl Ics2ClientState for ClientState { root: &CommitmentRoot, client_id: &ClientId, expected_client_state: Any, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; @@ -778,7 +778,7 @@ impl Ics2ClientState for ClientState { channel_id: &ChannelId, sequence: Sequence, commitment: PacketCommitment, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; verify_delay_passed(ctx, height, connection_end)?; @@ -810,7 +810,7 @@ impl Ics2ClientState for ClientState { channel_id: &ChannelId, sequence: Sequence, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; verify_delay_passed(ctx, height, connection_end)?; @@ -840,7 +840,7 @@ impl Ics2ClientState for ClientState { port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; verify_delay_passed(ctx, height, connection_end)?; @@ -872,7 +872,7 @@ impl Ics2ClientState for ClientState { port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let client_state = downcast_tm_client_state(self)?; client_state.verify_height(height)?; verify_delay_passed(ctx, height, connection_end)?; @@ -899,10 +899,10 @@ fn verify_membership( root: &CommitmentRoot, path: impl Into, value: Vec, -) -> Result<(), Ics02Error> { +) -> Result<(), ClientError> { let merkle_path = apply_prefix(prefix, vec![path.into().to_string()]); let merkle_proof: MerkleProof = RawMerkleProof::try_from(proof.clone()) - .map_err(Ics02Error::InvalidCommitmentProof)? + .map_err(ClientError::InvalidCommitmentProof)? .into(); merkle_proof @@ -913,7 +913,7 @@ fn verify_membership( value, 0, ) - .map_err(Ics02Error::Ics23Verification) + .map_err(ClientError::Ics23Verification) } fn verify_non_membership( @@ -922,26 +922,26 @@ fn verify_non_membership( proof: &CommitmentProofBytes, root: &CommitmentRoot, path: impl Into, -) -> Result<(), Ics02Error> { +) -> Result<(), ClientError> { let merkle_path = apply_prefix(prefix, vec![path.into().to_string()]); let merkle_proof: MerkleProof = RawMerkleProof::try_from(proof.clone()) - .map_err(Ics02Error::InvalidCommitmentProof)? + .map_err(ClientError::InvalidCommitmentProof)? .into(); merkle_proof .verify_non_membership(&client_state.proof_specs, root.clone().into(), merkle_path) - .map_err(Ics02Error::Ics23Verification) + .map_err(ClientError::Ics23Verification) } fn verify_delay_passed( ctx: &dyn ChannelReader, height: Height, connection_end: &ConnectionEnd, -) -> Result<(), Ics02Error> { - let current_timestamp = ctx.host_timestamp().map_err(|e| Ics02Error::Other { +) -> Result<(), ClientError> { + let current_timestamp = ctx.host_timestamp().map_err(|e| ClientError::Other { description: e.to_string(), })?; - let current_height = ctx.host_height().map_err(|e| Ics02Error::Other { + let current_height = ctx.host_height().map_err(|e| ClientError::Other { description: e.to_string(), })?; @@ -973,18 +973,18 @@ fn verify_delay_passed( .map_err(|e| e.into()) } -fn downcast_tm_client_state(cs: &dyn Ics2ClientState) -> Result<&ClientState, Ics02Error> { +fn downcast_tm_client_state(cs: &dyn Ics2ClientState) -> Result<&ClientState, ClientError> { cs.as_any() .downcast_ref::() - .ok_or_else(|| Ics02Error::ClientArgsTypeMismatch { + .ok_or_else(|| ClientError::ClientArgsTypeMismatch { client_type: tm_client_type(), }) } -fn downcast_tm_consensus_state(cs: &dyn ConsensusState) -> Result { +fn downcast_tm_consensus_state(cs: &dyn ConsensusState) -> Result { cs.as_any() .downcast_ref::() - .ok_or_else(|| Ics02Error::ClientArgsTypeMismatch { + .ok_or_else(|| ClientError::ClientArgsTypeMismatch { client_type: tm_client_type(), }) .map(Clone::clone) @@ -1093,7 +1093,7 @@ impl From for RawTmClientState { impl Protobuf for ClientState {} impl TryFrom for ClientState { - type Error = Ics02Error; + type Error = ClientError; fn try_from(raw: Any) -> Result { use bytes::Buf; @@ -1109,7 +1109,7 @@ impl TryFrom for ClientState { TENDERMINT_CLIENT_STATE_TYPE_URL => { decode_client_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Ics02Error::UnknownClientStateType { + _ => Err(ClientError::UnknownClientStateType { client_state_type: raw.type_url, }), } diff --git a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs index 8a916dd29..53e600ccd 100644 --- a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs @@ -10,7 +10,7 @@ use tendermint_proto::google::protobuf as tpb; use crate::clients::ics07_tendermint::error::Error; use crate::clients::ics07_tendermint::header::Header; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::error::Error as Ics02Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics23_commitment::commitment::CommitmentRoot; use crate::timestamp::Timestamp; @@ -106,7 +106,7 @@ impl From for RawConsensusState { impl Protobuf for ConsensusState {} impl TryFrom for ConsensusState { - type Error = Ics02Error; + type Error = ClientError; fn try_from(raw: Any) -> Result { use bytes::Buf; @@ -123,7 +123,7 @@ impl TryFrom for ConsensusState { TENDERMINT_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Ics02Error::UnknownConsensusStateType { + _ => Err(ClientError::UnknownConsensusStateType { consensus_state_type: raw.type_url, }), } diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index 6cbac4c3e..a9aad3e59 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -1,6 +1,6 @@ use crate::prelude::*; -use crate::core::ics02_client::error::Error as Ics02Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::error::ValidationError; use crate::core::ics24_host::identifier::{ChainId, ClientId}; use crate::timestamp::{Timestamp, TimestampOverflowError}; @@ -171,7 +171,7 @@ pub enum VerificationError { InsufficientOverlap { q1: u64, q2: u64 }, } -impl From for Ics02Error { +impl From for ClientError { fn from(e: Error) -> Self { Self::ClientSpecific { description: e.to_string(), diff --git a/crates/ibc/src/clients/ics07_tendermint/header.rs b/crates/ibc/src/clients/ics07_tendermint/header.rs index 27dc53eea..8816edb11 100644 --- a/crates/ibc/src/clients/ics07_tendermint/header.rs +++ b/crates/ibc/src/clients/ics07_tendermint/header.rs @@ -13,7 +13,7 @@ use tendermint::validator::Set as ValidatorSet; use crate::clients::ics07_tendermint::error::Error; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::error::Error as Ics02Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ChainId; use crate::timestamp::Timestamp; use crate::utils::pretty::{PrettySignedHeader, PrettyValidatorSet}; @@ -138,9 +138,9 @@ impl TryFrom for Header { impl Protobuf for Header {} impl TryFrom for Header { - type Error = Ics02Error; + type Error = ClientError; - fn try_from(raw: Any) -> Result { + fn try_from(raw: Any) -> Result { use core::ops::Deref; fn decode_header(buf: B) -> Result { @@ -149,7 +149,7 @@ impl TryFrom for Header { match raw.type_url.as_str() { TENDERMINT_HEADER_TYPE_URL => decode_header(raw.value.deref()).map_err(Into::into), - _ => Err(Ics02Error::UnknownHeaderType { + _ => Err(ClientError::UnknownHeaderType { header_type: raw.type_url, }), } diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index c761f1b75..48770a634 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -17,7 +17,7 @@ use super::ics24_host::path::{ use super::ics26_routing::msgs::MsgEnvelope; use super::{ ics02_client::{ - client_state::ClientState, consensus_state::ConsensusState, error::Error as ClientError, + client_state::ClientState, consensus_state::ConsensusState, error::ClientError, }, ics03_connection::{ connection::ConnectionEnd, diff --git a/crates/ibc/src/core/ics02_client/client_state.rs b/crates/ibc/src/core/ics02_client/client_state.rs index 2167c2f4a..42bf9a939 100644 --- a/crates/ibc/src/core/ics02_client/client_state.rs +++ b/crates/ibc/src/core/ics02_client/client_state.rs @@ -8,7 +8,7 @@ use ibc_proto::ibc::core::commitment::v1::MerkleProof; use ibc_proto::protobuf::Protobuf as ErasedProtobuf; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment}; @@ -31,7 +31,7 @@ pub trait ClientState: + sealed::ErasedPartialEqClientState + DynClone + ErasedSerialize - + ErasedProtobuf + + ErasedProtobuf + core::fmt::Debug + Send + Sync @@ -76,7 +76,7 @@ pub trait ClientState: Box::new(self) } - fn initialise(&self, consensus_state: Any) -> Result, Error>; + fn initialise(&self, consensus_state: Any) -> Result, ClientError>; /// XXX: temporary solution until we get rid of `ClientReader` fn old_check_header_and_update_state( @@ -84,21 +84,21 @@ pub trait ClientState: ctx: &dyn ClientReader, client_id: ClientId, header: Any, - ) -> Result; + ) -> Result; fn check_header_and_update_state( &self, ctx: &dyn ValidationContext, client_id: ClientId, header: Any, - ) -> Result; + ) -> Result; fn verify_upgrade_and_update_state( &self, consensus_state: Any, proof_upgrade_client: MerkleProof, proof_upgrade_consensus_state: MerkleProof, - ) -> Result; + ) -> Result; /// Verification functions as specified in: /// @@ -117,7 +117,7 @@ pub trait ClientState: counterparty_client_id: &ClientId, consensus_height: Height, expected_consensus_state: &dyn ConsensusState, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify a `proof` that a connection state matches that of the input `connection_end`. #[allow(clippy::too_many_arguments)] @@ -129,7 +129,7 @@ pub trait ClientState: root: &CommitmentRoot, counterparty_connection_id: &ConnectionId, expected_counterparty_connection_end: &ConnectionEnd, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify a `proof` that a channel state matches that of the input `channel_end`. #[allow(clippy::too_many_arguments)] @@ -142,7 +142,7 @@ pub trait ClientState: counterparty_port_id: &PortId, counterparty_channel_id: &ChannelId, expected_counterparty_channel_end: &ChannelEnd, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify the client state for this chain that it is stored on the counterparty chain. #[allow(clippy::too_many_arguments)] @@ -154,7 +154,7 @@ pub trait ClientState: root: &CommitmentRoot, client_id: &ClientId, expected_client_state: Any, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify a `proof` that a packet has been commited. #[allow(clippy::too_many_arguments)] @@ -169,7 +169,7 @@ pub trait ClientState: channel_id: &ChannelId, sequence: Sequence, commitment: PacketCommitment, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify a `proof` that a packet has been commited. #[allow(clippy::too_many_arguments)] @@ -184,7 +184,7 @@ pub trait ClientState: channel_id: &ChannelId, sequence: Sequence, ack: AcknowledgementCommitment, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify a `proof` that of the next_seq_received. #[allow(clippy::too_many_arguments)] @@ -198,7 +198,7 @@ pub trait ClientState: port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Verify a `proof` that a packet has not been received. #[allow(clippy::too_many_arguments)] @@ -212,7 +212,7 @@ pub trait ClientState: port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; } // Implements `Clone` for `Box` diff --git a/crates/ibc/src/core/ics02_client/consensus_state.rs b/crates/ibc/src/core/ics02_client/consensus_state.rs index 4d7c0adac..e7ee8f03b 100644 --- a/crates/ibc/src/core/ics02_client/consensus_state.rs +++ b/crates/ibc/src/core/ics02_client/consensus_state.rs @@ -8,7 +8,7 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::protobuf::Protobuf as ErasedProtobuf; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics23_commitment::commitment::CommitmentRoot; use crate::dynamic_typing::AsAny; use crate::timestamp::Timestamp; @@ -25,7 +25,7 @@ pub trait ConsensusState: + sealed::ErasedPartialEqConsensusState + DynClone + ErasedSerialize - + ErasedProtobuf + + ErasedProtobuf + core::fmt::Debug + Send + Sync diff --git a/crates/ibc/src/core/ics02_client/context.rs b/crates/ibc/src/core/ics02_client/context.rs index 77d0aed88..a5cfc30ba 100644 --- a/crates/ibc/src/core/ics02_client/context.rs +++ b/crates/ibc/src/core/ics02_client/context.rs @@ -9,7 +9,7 @@ use ibc_proto::google::protobuf::Any; use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::handler::ClientResult::{self, Create, Update, Upgrade}; use crate::core::ics24_host::identifier::ClientId; use crate::timestamp::Timestamp; @@ -18,13 +18,13 @@ use crate::Height; /// Defines the read-only part of ICS2 (client functions) context. pub trait ClientReader { /// Returns the ClientType for the given identifier `client_id`. - fn client_type(&self, client_id: &ClientId) -> Result; + fn client_type(&self, client_id: &ClientId) -> Result; /// Returns the ClientState for the given identifier `client_id`. - fn client_state(&self, client_id: &ClientId) -> Result, Error>; + fn client_state(&self, client_id: &ClientId) -> Result, ClientError>; /// Tries to decode the given `client_state` into a concrete light client state. - fn decode_client_state(&self, client_state: Any) -> Result, Error>; + fn decode_client_state(&self, client_state: Any) -> Result, ClientError>; /// Retrieve the consensus state for the given client ID at the specified /// height. @@ -34,27 +34,27 @@ pub trait ClientReader { &self, client_id: &ClientId, height: Height, - ) -> Result, Error>; + ) -> Result, ClientError>; /// Search for the lowest consensus state higher than `height`. fn next_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result>, Error>; + ) -> Result>, ClientError>; /// Search for the highest consensus state lower than `height`. fn prev_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result>, Error>; + ) -> Result>, ClientError>; /// 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 { let pending_consensus_state = self .pending_host_consensus_state() .expect("host must have pending consensus state"); @@ -62,19 +62,19 @@ pub trait ClientReader { } /// Returns the `ConsensusState` of the host (local) chain at a specific height. - fn host_consensus_state(&self, height: Height) -> Result, Error>; + fn host_consensus_state(&self, height: Height) -> Result, ClientError>; /// Returns the pending `ConsensusState` of the host (local) chain. - fn pending_host_consensus_state(&self) -> Result, Error>; + fn pending_host_consensus_state(&self) -> Result, ClientError>; /// Returns a natural number, counting how many clients have been created thus far. /// The value of this counter should increase only via method `ClientKeeper::increase_client_counter`. - fn client_counter(&self) -> Result; + fn client_counter(&self) -> Result; } /// Defines the write-only part of ICS2 (client functions) context. pub trait ClientKeeper { - fn store_client_result(&mut self, handler_res: ClientResult) -> Result<(), Error> { + fn store_client_result(&mut self, handler_res: ClientResult) -> Result<(), ClientError> { match handler_res { Create(res) => { self.store_client_type(res.client_id.clone(), res.client_type)?; @@ -133,14 +133,14 @@ pub trait ClientKeeper { &mut self, client_id: ClientId, client_type: ClientType, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Called upon successful client creation and update fn store_client_state( &mut self, client_id: ClientId, client_state: Box, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Called upon successful client creation and update fn store_consensus_state( @@ -148,7 +148,7 @@ pub trait ClientKeeper { client_id: ClientId, height: Height, consensus_state: Box, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Called upon client creation. /// Increases the counter which keeps track of how many clients have been created. @@ -163,7 +163,7 @@ pub trait ClientKeeper { client_id: ClientId, height: Height, timestamp: Timestamp, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; /// Called upon successful client update. /// Implementations are expected to use this to record the specified height as the height at @@ -173,5 +173,5 @@ pub trait ClientKeeper { client_id: ClientId, height: Height, host_height: Height, - ) -> Result<(), Error>; + ) -> Result<(), ClientError>; } diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 164d71850..70857023e 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -12,7 +12,7 @@ use crate::timestamp::Timestamp; use crate::Height; #[derive(Debug, Display)] -pub enum Error { +pub enum ClientError { /// unknown client type: `{client_type}` UnknownClientType { client_type: String }, /// Client identifier constructor failed for type `{client_type}` with counter `{counter}` @@ -148,38 +148,38 @@ pub enum Error { } #[cfg(feature = "std")] -impl std::error::Error for Error { +impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::ClientIdentifierConstructor { + Self::ClientIdentifierConstructor { validation_error: e, .. } => Some(e), - Error::InvalidRawClientId { + Self::InvalidRawClientId { validation_error: e, .. } => Some(e), - Error::DecodeRawClientState(e) => Some(e), - Error::InvalidRawConsensusState(e) => Some(e), - Error::InvalidMsgUpdateClientId(e) => Some(e), - Error::Decode(e) => Some(e), - Error::InvalidClientIdentifier(e) => Some(e), - Error::InvalidRawHeader(e) => Some(e), - Error::DecodeRawMisbehaviour(e) => Some(e), - Error::InvalidRawMisbehaviour(e) => Some(e), - Error::InvalidStringAsHeight { + Self::DecodeRawClientState(e) => Some(e), + Self::InvalidRawConsensusState(e) => Some(e), + Self::InvalidMsgUpdateClientId(e) => Some(e), + Self::Decode(e) => Some(e), + Self::InvalidClientIdentifier(e) => Some(e), + Self::InvalidRawHeader(e) => Some(e), + Self::DecodeRawMisbehaviour(e) => Some(e), + Self::InvalidRawMisbehaviour(e) => Some(e), + Self::InvalidStringAsHeight { height_error: e, .. } => Some(e), - Error::InvalidUpgradeClientProof(e) => Some(e), - Error::InvalidUpgradeConsensusStateProof(e) => Some(e), - Error::InvalidCommitmentProof(e) => Some(e), - Error::InvalidPacketTimestamp(e) => Some(e), - Error::InvalidConnectionEnd(e) => Some(e), - Error::InvalidChannelEnd(e) => Some(e), - Error::InvalidAnyClientState(e) => Some(e), - Error::InvalidAnyConsensusState(e) => Some(e), - Error::Signer(e) => Some(e), - Error::Ics23Verification(e) => Some(e), + Self::InvalidUpgradeClientProof(e) => Some(e), + Self::InvalidUpgradeConsensusStateProof(e) => Some(e), + Self::InvalidCommitmentProof(e) => Some(e), + Self::InvalidPacketTimestamp(e) => Some(e), + Self::InvalidConnectionEnd(e) => Some(e), + Self::InvalidChannelEnd(e) => Some(e), + Self::InvalidAnyClientState(e) => Some(e), + Self::InvalidAnyConsensusState(e) => Some(e), + Self::Signer(e) => Some(e), + Self::Ics23Verification(e) => Some(e), _ => None, } } diff --git a/crates/ibc/src/core/ics02_client/handler.rs b/crates/ibc/src/core/ics02_client/handler.rs index 80ffe91b1..8b89d22a0 100644 --- a/crates/ibc/src/core/ics02_client/handler.rs +++ b/crates/ibc/src/core/ics02_client/handler.rs @@ -1,7 +1,7 @@ //! This module implements the processing logic for ICS2 (client abstractions and functions) msgs. use crate::core::ics02_client::context::ClientReader; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::msgs::ClientMsg; use crate::handler::HandlerOutput; @@ -17,7 +17,7 @@ pub enum ClientResult { } /// General entry point for processing any message related to ICS2 (client functions) protocols. -pub fn dispatch(ctx: &Ctx, msg: ClientMsg) -> Result, Error> +pub fn dispatch(ctx: &Ctx, msg: ClientMsg) -> Result, ClientError> where Ctx: ClientReader, { diff --git a/crates/ibc/src/core/ics02_client/handler/create_client.rs b/crates/ibc/src/core/ics02_client/handler/create_client.rs index 5a7111fd9..f601cc250 100644 --- a/crates/ibc/src/core/ics02_client/handler/create_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/create_client.rs @@ -12,7 +12,7 @@ use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::context::ClientReader; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::events::CreateClient; use crate::core::ics02_client::handler::ClientResult; use crate::core::ics02_client::height::Height; @@ -34,7 +34,7 @@ pub struct CreateClientResult { pub processed_height: Height, } -pub(crate) fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), Error> +pub(crate) fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), ClientError> where Ctx: ValidationContext, { @@ -51,17 +51,18 @@ where let client_type = client_state.client_type(); - let _client_id = - ClientId::new(client_type, id_counter).map_err(|e| Error::ClientIdentifierConstructor { + let _client_id = ClientId::new(client_type, id_counter).map_err(|e| { + ClientError::ClientIdentifierConstructor { client_type: client_state.client_type(), counter: id_counter, validation_error: e, - })?; + } + })?; Ok(()) } -pub(crate) fn execute(ctx: &mut Ctx, msg: MsgCreateClient) -> Result<(), Error> +pub(crate) fn execute(ctx: &mut Ctx, msg: MsgCreateClient) -> Result<(), ClientError> where Ctx: ExecutionContext, { @@ -79,7 +80,7 @@ where let client_type = client_state.client_type(); let client_id = ClientId::new(client_type.clone(), id_counter).map_err(|e| { - Error::ClientIdentifierConstructor { + ClientError::ClientIdentifierConstructor { client_type: client_state.client_type(), counter: id_counter, validation_error: e, @@ -119,7 +120,10 @@ where Ok(()) } -pub fn process(ctx: &dyn ClientReader, msg: MsgCreateClient) -> HandlerResult { +pub fn process( + ctx: &dyn ClientReader, + msg: MsgCreateClient, +) -> HandlerResult { let mut output = HandlerOutput::builder(); let MsgCreateClient { @@ -136,7 +140,7 @@ pub fn process(ctx: &dyn ClientReader, msg: MsgCreateClient) -> HandlerResult(ctx: &Ctx, msg: MsgUpdateClient) -> Result<(), Error> +pub(crate) fn validate(ctx: &Ctx, msg: MsgUpdateClient) -> Result<(), ClientError> where Ctx: ValidationContext, { @@ -44,13 +44,13 @@ where let client_state = ctx.client_state(&client_id)?; if client_state.is_frozen() { - return Err(Error::ClientFrozen { client_id }); + return Err(ClientError::ClientFrozen { client_id }); } // Read consensus state from the host chain store. let latest_consensus_state = ctx .consensus_state(&client_id, client_state.latest_height()) - .map_err(|_| Error::ConsensusStateNotFound { + .map_err(|_| ClientError::ConsensusStateNotFound { client_id: client_id.clone(), height: client_state.latest_height(), })?; @@ -60,13 +60,13 @@ where let now = ctx.host_timestamp()?; let duration = now .duration_since(&latest_consensus_state.timestamp()) - .ok_or_else(|| Error::InvalidConsensusStateTimestamp { + .ok_or_else(|| ClientError::InvalidConsensusStateTimestamp { time1: latest_consensus_state.timestamp(), time2: now, })?; if client_state.expired(duration) { - return Err(Error::HeaderNotWithinTrustPeriod { + return Err(ClientError::HeaderNotWithinTrustPeriod { latest_time: latest_consensus_state.timestamp(), update_time: now, }); @@ -77,14 +77,14 @@ where // consensus_state obtained from header. These will be later persisted by the keeper. let _ = client_state .check_header_and_update_state(ctx, client_id.clone(), header) - .map_err(|e| Error::HeaderVerificationFailure { + .map_err(|e| ClientError::HeaderVerificationFailure { reaseon: e.to_string(), })?; Ok(()) } -pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpdateClient) -> Result<(), Error> +pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpdateClient) -> Result<(), ClientError> where Ctx: ExecutionContext, { @@ -103,7 +103,7 @@ where consensus_state, } = client_state .check_header_and_update_state(ctx, client_id.clone(), header.clone()) - .map_err(|e| Error::HeaderVerificationFailure { + .map_err(|e| ClientError::HeaderVerificationFailure { reaseon: e.to_string(), })?; @@ -141,7 +141,7 @@ where pub fn process( ctx: &Ctx, msg: MsgUpdateClient, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let MsgUpdateClient { @@ -155,13 +155,13 @@ pub fn process( let client_state = ctx.client_state(&client_id)?; if client_state.is_frozen() { - return Err(Error::ClientFrozen { client_id }); + return Err(ClientError::ClientFrozen { client_id }); } // Read consensus state from the host chain store. let latest_consensus_state = ClientReader::consensus_state(ctx, &client_id, client_state.latest_height()).map_err( - |_| Error::ConsensusStateNotFound { + |_| ClientError::ConsensusStateNotFound { client_id: client_id.clone(), height: client_state.latest_height(), }, @@ -172,13 +172,13 @@ pub fn process( let now = ClientReader::host_timestamp(ctx)?; let duration = now .duration_since(&latest_consensus_state.timestamp()) - .ok_or_else(|| Error::InvalidConsensusStateTimestamp { + .ok_or_else(|| ClientError::InvalidConsensusStateTimestamp { time1: latest_consensus_state.timestamp(), time2: now, })?; if client_state.expired(duration) { - return Err(Error::HeaderNotWithinTrustPeriod { + return Err(ClientError::HeaderNotWithinTrustPeriod { latest_time: latest_consensus_state.timestamp(), update_time: now, }); @@ -192,7 +192,7 @@ pub fn process( consensus_state, } = client_state .old_check_header_and_update_state(ctx, client_id.clone(), header.clone()) - .map_err(|e| Error::HeaderVerificationFailure { + .map_err(|e| ClientError::HeaderVerificationFailure { reaseon: e.to_string(), })?; @@ -228,7 +228,7 @@ mod tests { use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::downcast_consensus_state; - use crate::core::ics02_client::error::Error; + use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::handler::dispatch; use crate::core::ics02_client::handler::ClientResult::Update; use crate::core::ics02_client::msgs::update_client::MsgUpdateClient; @@ -305,7 +305,7 @@ mod tests { let output = dispatch(&ctx, ClientMsg::UpdateClient(msg.clone())); match output { - Err(Error::ClientNotFound { client_id }) => { + Err(ClientError::ClientNotFound { client_id }) => { assert_eq!(client_id, msg.client_id); } _ => { @@ -604,7 +604,7 @@ mod tests { panic!("update handler result has incorrect type"); } Err(err) => match err { - Error::HeaderVerificationFailure { reaseon: _ } => {} + ClientError::HeaderVerificationFailure { reaseon: _ } => {} _ => panic!("unexpected error: {:?}", err), }, } diff --git a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs index a38a4cacd..8b0afb25e 100644 --- a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs @@ -3,7 +3,7 @@ use crate::core::ics02_client::client_state::{ClientState, UpdatedState}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::context::ClientReader; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::events::UpgradeClient; use crate::core::ics02_client::handler::ClientResult; use crate::core::ics02_client::msgs::upgrade_client::MsgUpgradeClient; @@ -23,7 +23,7 @@ pub struct UpgradeClientResult { pub consensus_state: Box, } -pub(crate) fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), Error> +pub(crate) fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), ClientError> where Ctx: ValidationContext, { @@ -33,13 +33,13 @@ where let old_client_state = ctx.client_state(&client_id)?; if old_client_state.is_frozen() { - return Err(Error::ClientFrozen { client_id }); + return Err(ClientError::ClientFrozen { client_id }); } let upgrade_client_state = ctx.decode_client_state(msg.client_state)?; if old_client_state.latest_height() >= upgrade_client_state.latest_height() { - return Err(Error::LowUpgradeHeight { + return Err(ClientError::LowUpgradeHeight { upgraded_height: old_client_state.latest_height(), client_height: upgrade_client_state.latest_height(), }); @@ -48,7 +48,7 @@ where Ok(()) } -pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpgradeClient) -> Result<(), Error> +pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpgradeClient) -> Result<(), ClientError> where Ctx: ExecutionContext, { @@ -86,7 +86,7 @@ where pub fn process( ctx: &dyn ClientReader, msg: MsgUpgradeClient, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let MsgUpgradeClient { client_id, .. } = msg; @@ -94,13 +94,13 @@ pub fn process( let old_client_state = ctx.client_state(&client_id)?; if old_client_state.is_frozen() { - return Err(Error::ClientFrozen { client_id }); + return Err(ClientError::ClientFrozen { client_id }); } let upgrade_client_state = ctx.decode_client_state(msg.client_state)?; if old_client_state.latest_height() >= upgrade_client_state.latest_height() { - return Err(Error::LowUpgradeHeight { + return Err(ClientError::LowUpgradeHeight { upgraded_height: old_client_state.latest_height(), client_height: upgrade_client_state.latest_height(), }); @@ -143,7 +143,7 @@ mod tests { use core::str::FromStr; - use crate::core::ics02_client::error::Error; + use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::handler::dispatch; use crate::core::ics02_client::handler::ClientResult::Upgrade; use crate::core::ics02_client::msgs::upgrade_client::MsgUpgradeClient; @@ -219,7 +219,7 @@ mod tests { let output = dispatch(&ctx, ClientMsg::UpgradeClient(msg.clone())); match output { - Err(Error::ClientNotFound { client_id }) => { + Err(ClientError::ClientNotFound { client_id }) => { assert_eq!(client_id, msg.client_id); } _ => { @@ -248,7 +248,7 @@ mod tests { let output = dispatch(&ctx, ClientMsg::UpgradeClient(msg.clone())); match output { - Err(Error::LowUpgradeHeight { + Err(ClientError::LowUpgradeHeight { upgraded_height, client_height, }) => { diff --git a/crates/ibc/src/core/ics02_client/header.rs b/crates/ibc/src/core/ics02_client/header.rs index 99f05c886..0174ddea1 100644 --- a/crates/ibc/src/core/ics02_client/header.rs +++ b/crates/ibc/src/core/ics02_client/header.rs @@ -6,7 +6,7 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::protobuf::Protobuf as ErasedProtobuf; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::dynamic_typing::AsAny; use crate::timestamp::Timestamp; use crate::Height; @@ -22,7 +22,7 @@ pub trait Header: + sealed::ErasedPartialEqHeader + DynClone + ErasedSerialize - + ErasedProtobuf + + ErasedProtobuf + core::fmt::Debug + Send + Sync diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index 49e84e235..08d30d67c 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -10,7 +10,7 @@ use serde_derive::{Deserialize, Serialize}; use ibc_proto::ibc::core::client::v1::Height as RawHeight; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; #[derive(Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Height { @@ -22,9 +22,9 @@ pub struct Height { } impl Height { - pub fn new(revision_number: u64, revision_height: u64) -> Result { + pub fn new(revision_number: u64, revision_height: u64) -> Result { if revision_height == 0 { - return Err(Error::InvalidHeight); + return Err(ClientError::InvalidHeight); } Ok(Self { @@ -52,9 +52,9 @@ impl Height { self.add(1) } - pub fn sub(&self, delta: u64) -> Result { + pub fn sub(&self, delta: u64) -> Result { if self.revision_height <= delta { - return Err(Error::InvalidHeightResult); + return Err(ClientError::InvalidHeightResult); } Ok(Height { @@ -63,7 +63,7 @@ impl Height { }) } - pub fn decrement(&self) -> Result { + pub fn decrement(&self) -> Result { self.sub(1) } } @@ -93,7 +93,7 @@ impl Ord for Height { impl Protobuf for Height {} impl TryFrom for Height { - type Error = Error; + type Error = ClientError; fn try_from(raw_height: RawHeight) -> Result { Height::new(raw_height.revision_number, raw_height.revision_height) diff --git a/crates/ibc/src/core/ics02_client/msgs/create_client.rs b/crates/ibc/src/core/ics02_client/msgs/create_client.rs index 32c96f749..d3210cb0f 100644 --- a/crates/ibc/src/core/ics02_client/msgs/create_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/create_client.rs @@ -6,7 +6,7 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::MsgCreateClient as RawMsgCreateClient; use ibc_proto::protobuf::Protobuf; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::signer::Signer; use crate::tx_msg::Msg; @@ -21,7 +21,11 @@ pub struct MsgCreateClient { } impl MsgCreateClient { - pub fn new(client_state: Any, consensus_state: Any, signer: Signer) -> Result { + pub fn new( + client_state: Any, + consensus_state: Any, + signer: Signer, + ) -> Result { Ok(MsgCreateClient { client_state, consensus_state, @@ -46,17 +50,19 @@ impl Msg for MsgCreateClient { impl Protobuf for MsgCreateClient {} impl TryFrom for MsgCreateClient { - type Error = Error; + type Error = ClientError; - fn try_from(raw: RawMsgCreateClient) -> Result { - let raw_client_state = raw.client_state.ok_or(Error::MissingRawClientState)?; + fn try_from(raw: RawMsgCreateClient) -> Result { + let raw_client_state = raw.client_state.ok_or(ClientError::MissingRawClientState)?; - let raw_consensus_state = raw.consensus_state.ok_or(Error::MissingRawConsensusState)?; + let raw_consensus_state = raw + .consensus_state + .ok_or(ClientError::MissingRawConsensusState)?; MsgCreateClient::new( raw_client_state, raw_consensus_state, - raw.signer.parse().map_err(Error::Signer)?, + raw.signer.parse().map_err(ClientError::Signer)?, ) } } diff --git a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs index 3c0b18b3f..51bc0011c 100644 --- a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs +++ b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs @@ -4,7 +4,7 @@ use ibc_proto::google::protobuf::Any as ProtoAny; use ibc_proto::ibc::core::client::v1::MsgSubmitMisbehaviour as RawMsgSubmitMisbehaviour; use ibc_proto::protobuf::Protobuf; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ClientId; use crate::signer::Signer; use crate::tx_msg::Msg; @@ -38,18 +38,20 @@ impl Msg for MsgSubmitMisbehaviour { impl Protobuf for MsgSubmitMisbehaviour {} impl TryFrom for MsgSubmitMisbehaviour { - type Error = Error; + type Error = ClientError; fn try_from(raw: RawMsgSubmitMisbehaviour) -> Result { - let raw_misbehaviour = raw.misbehaviour.ok_or(Error::MissingRawMisbehaviour)?; + let raw_misbehaviour = raw + .misbehaviour + .ok_or(ClientError::MissingRawMisbehaviour)?; Ok(MsgSubmitMisbehaviour { client_id: raw .client_id .parse() - .map_err(Error::InvalidRawMisbehaviour)?, + .map_err(ClientError::InvalidRawMisbehaviour)?, misbehaviour: raw_misbehaviour, - signer: raw.signer.parse().map_err(Error::Signer)?, + signer: raw.signer.parse().map_err(ClientError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics02_client/msgs/update_client.rs b/crates/ibc/src/core/ics02_client/msgs/update_client.rs index 71ce9aab1..d2fd43609 100644 --- a/crates/ibc/src/core/ics02_client/msgs/update_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/update_client.rs @@ -6,7 +6,7 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::MsgUpdateClient as RawMsgUpdateClient; use ibc_proto::protobuf::Protobuf; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::error::ValidationError; use crate::core::ics24_host::identifier::ClientId; use crate::signer::Signer; @@ -48,16 +48,16 @@ impl Msg for MsgUpdateClient { impl Protobuf for MsgUpdateClient {} impl TryFrom for MsgUpdateClient { - type Error = Error; + type Error = ClientError; fn try_from(raw: RawMsgUpdateClient) -> Result { Ok(MsgUpdateClient { client_id: raw .client_id .parse() - .map_err(Error::InvalidMsgUpdateClientId)?, - header: raw.header.ok_or(Error::MissingRawHeader)?, - signer: raw.signer.parse().map_err(Error::Signer)?, + .map_err(ClientError::InvalidMsgUpdateClientId)?, + header: raw.header.ok_or(ClientError::MissingRawHeader)?, + signer: raw.signer.parse().map_err(ClientError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs index 4e8b65049..27d35cb08 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -9,7 +9,7 @@ use ibc_proto::ibc::core::client::v1::MsgUpgradeClient as RawMsgUpgradeClient; use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; use ibc_proto::protobuf::Protobuf; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics23_commitment::error::Error as Ics23Error; use crate::core::ics24_host::identifier::ClientId; @@ -83,30 +83,34 @@ impl From for RawMsgUpgradeClient { } impl TryFrom for MsgUpgradeClient { - type Error = Error; + type Error = ClientError; fn try_from(proto_msg: RawMsgUpgradeClient) -> Result { - let raw_client_state = proto_msg.client_state.ok_or(Error::MissingRawClientState)?; + let raw_client_state = proto_msg + .client_state + .ok_or(ClientError::MissingRawClientState)?; let raw_consensus_state = proto_msg .consensus_state - .ok_or(Error::MissingRawConsensusState)?; + .ok_or(ClientError::MissingRawConsensusState)?; let c_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client) - .map_err(|_| Error::InvalidUpgradeClientProof(Ics23Error::EmptyMerkleProof))?; + .map_err(|_| ClientError::InvalidUpgradeClientProof(Ics23Error::EmptyMerkleProof))?; let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) - .map_err(|_| Error::InvalidUpgradeConsensusStateProof(Ics23Error::EmptyMerkleProof))?; + .map_err(|_| { + ClientError::InvalidUpgradeConsensusStateProof(Ics23Error::EmptyMerkleProof) + })?; Ok(MsgUpgradeClient { client_id: ClientId::from_str(&proto_msg.client_id) - .map_err(Error::InvalidClientIdentifier)?, + .map_err(ClientError::InvalidClientIdentifier)?, client_state: raw_client_state, consensus_state: raw_consensus_state, proof_upgrade_client: RawMerkleProof::try_from(c_bytes) - .map_err(Error::InvalidUpgradeClientProof)?, + .map_err(ClientError::InvalidUpgradeClientProof)?, proof_upgrade_consensus_state: RawMerkleProof::try_from(cs_bytes) - .map_err(Error::InvalidUpgradeConsensusStateProof)?, - signer: proto_msg.signer.parse().map_err(Error::Signer)?, + .map_err(ClientError::InvalidUpgradeConsensusStateProof)?, + signer: proto_msg.signer.parse().map_err(ClientError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics02_client/trust_threshold.rs b/crates/ibc/src/core/ics02_client/trust_threshold.rs index b2df62d2f..dd6cfeb64 100644 --- a/crates/ibc/src/core/ics02_client/trust_threshold.rs +++ b/crates/ibc/src/core/ics02_client/trust_threshold.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; use ibc_proto::ibc::lightclients::tendermint::v1::Fraction; use tendermint::trust_threshold::TrustThresholdFraction; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; /// [`TrustThreshold`] defines the level of trust that a client has /// towards a set of validators of a chain. @@ -53,13 +53,13 @@ impl TrustThreshold { /// /// The constructor succeeds if long as the resulting fraction /// is in the range`[0, 1)`. - pub fn new(numerator: u64, denominator: u64) -> Result { + pub fn new(numerator: u64, denominator: u64) -> Result { // The two parameters cannot yield a fraction that is bigger or equal to 1 if (numerator > denominator) || (denominator == 0 && numerator != 0) || (numerator == denominator && numerator != 0) { - return Err(Error::InvalidTrustThreshold { + return Err(ClientError::InvalidTrustThreshold { numerator, denominator, }); @@ -96,12 +96,14 @@ impl From for TrustThreshold { /// Conversion from IBC domain type into /// Tendermint domain type. impl TryFrom for TrustThresholdFraction { - type Error = Error; - - fn try_from(t: TrustThreshold) -> Result { - Self::new(t.numerator, t.denominator).map_err(|_| Error::FailedTrustThresholdConversion { - numerator: t.numerator, - denominator: t.denominator, + type Error = ClientError; + + fn try_from(t: TrustThreshold) -> Result { + Self::new(t.numerator, t.denominator).map_err(|_| { + ClientError::FailedTrustThresholdConversion { + numerator: t.numerator, + denominator: t.denominator, + } }) } } @@ -118,7 +120,7 @@ impl From for Fraction { } impl TryFrom for TrustThreshold { - type Error = Error; + type Error = ClientError; fn try_from(value: Fraction) -> Result { Self::new(value.numerator, value.denominator) diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index 70710e944..e46cc9ed1 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -15,7 +15,7 @@ use ibc_proto::ibc::core::connection::v1::{ IdentifiedConnection as RawIdentifiedConnection, }; -use crate::core::ics02_client::error::Error as ClientError; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::error::Error; use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentPrefix; diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 99c933b98..ec13764d3 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -12,7 +12,7 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { /// ICS02 client error - Client(client_error::Error), + Client(client_error::ClientError), /// connection state is unknown: `{state}` InvalidState { state: i32 }, /// connection exists (was initialized) already: `{connection_id}` @@ -50,7 +50,7 @@ pub enum Error { /// invalid connection proof InvalidProof(ProofError), /// error verifying connnection state - VerifyConnectionState(client_error::Error), + VerifyConnectionState(client_error::ClientError), /// invalid signer Signer(SignerError), /// no connection was found for the previous connection id provided `{connection_id}` @@ -77,13 +77,13 @@ pub enum Error { /// the consensus proof verification failed (height: `{height}`) ConsensusStateVerificationFailure { height: Height, - client_error: client_error::Error, + client_error: client_error::ClientError, }, /// the client state proof verification failed for client id `{client_id}` ClientStateVerificationFailure { // TODO: use more specific error source client_id: ClientId, - client_error: client_error::Error, + client_error: client_error::ClientError, }, /// implementation specific error ImplementationSpecific, diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index ec08b99cb..338e08fc8 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -85,10 +85,10 @@ pub enum Error { /// Verification fails for the packet with the sequence number `{sequence}`, error(`{ics02_error}`) PacketVerificationFailed { sequence: Sequence, - ics02_error: client_error::Error, + ics02_error: client_error::ClientError, }, /// Error verifying channel state - VerifyChannelFailed(client_error::Error), + VerifyChannelFailed(client_error::ClientError), /// Acknowledgment cannot be empty InvalidAcknowledgement, /// Packet acknowledgement exists for the packet with the sequence `{sequence}` diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index d9654a27e..a1c15ff88 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -227,7 +227,7 @@ mod tests { error::Error::Connection(e) => { assert_eq!( e.to_string(), - ics03_error::Error::Client(ics02_error::Error::ClientNotFound { + ics03_error::Error::Client(ics02_error::ClientError::ClientNotFound { client_id: ClientId::new(mock_client_type(), 45).unwrap() }) .to_string() diff --git a/crates/ibc/src/core/ics04_channel/timeout.rs b/crates/ibc/src/core/ics04_channel/timeout.rs index d72537140..12dcc3248 100644 --- a/crates/ibc/src/core/ics04_channel/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/timeout.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use ibc_proto::ibc::core::client::v1::Height as RawHeight; -use crate::core::ics02_client::{error::Error as ICS2Error, height::Height}; +use crate::core::ics02_client::{error::ClientError, height::Height}; use crate::prelude::*; /// Indicates a consensus height on the destination chain after which the packet @@ -70,7 +70,7 @@ impl Default for TimeoutHeight { } impl TryFrom for TimeoutHeight { - type Error = ICS2Error; + type Error = ClientError; // Note: it is important for `revision_number` to also be `0`, otherwise // packet commitment proofs will be incorrect (proof construction in @@ -87,7 +87,7 @@ impl TryFrom for TimeoutHeight { } impl TryFrom> for TimeoutHeight { - type Error = ICS2Error; + type Error = ClientError; fn try_from(maybe_raw_height: Option) -> Result { match maybe_raw_height { diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 813098d37..7da2e7f8b 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -8,7 +8,7 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum Error { /// ICS02 client error - Client(ics02_client::error::Error), + Client(ics02_client::error::ClientError), /// ICS03 connection error Connection(ics03_connection::error::Error), /// ICS04 channel error diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index ce68ff504..bb1b9abba 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -23,7 +23,7 @@ pub enum Error { /// parse error Parse(ValidationError), /// ICS02 client error - Client(client_error::Error), + Client(client_error::ClientError), /// connection error Connection(connection_error::Error), /// channel error diff --git a/crates/ibc/src/mock/client_state.rs b/crates/ibc/src/mock/client_state.rs index 542c7aaf8..b445c7153 100644 --- a/crates/ibc/src/mock/client_state.rs +++ b/crates/ibc/src/mock/client_state.rs @@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize}; use crate::core::ics02_client::client_state::{ClientState, UpdatedState, UpgradeOptions}; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortId}; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::consensus_state::MockConsensusState; @@ -82,7 +82,7 @@ impl MockClientState { impl Protobuf for MockClientState {} impl TryFrom for MockClientState { - type Error = Error; + type Error = ClientError; fn try_from(raw: RawMockClientState) -> Result { Ok(Self::new(raw.header.unwrap().try_into()?)) @@ -103,16 +103,16 @@ impl From for RawMockClientState { impl Protobuf for MockClientState {} impl TryFrom for MockClientState { - type Error = Error; + type Error = ClientError; - fn try_from(raw: Any) -> Result { + fn try_from(raw: Any) -> Result { use bytes::Buf; use core::ops::Deref; use prost::Message; - fn decode_client_state(buf: B) -> Result { + fn decode_client_state(buf: B) -> Result { RawMockClientState::decode(buf) - .map_err(Error::Decode)? + .map_err(ClientError::Decode)? .try_into() } @@ -120,7 +120,7 @@ impl TryFrom for MockClientState { MOCK_CLIENT_STATE_TYPE_URL => { decode_client_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Error::UnknownClientStateType { + _ => Err(ClientError::UnknownClientStateType { client_state_type: raw.type_url, }), } @@ -167,7 +167,7 @@ impl ClientState for MockClientState { false } - fn initialise(&self, consensus_state: Any) -> Result, Error> { + fn initialise(&self, consensus_state: Any) -> Result, ClientError> { MockConsensusState::try_from(consensus_state).map(MockConsensusState::into_box) } @@ -176,11 +176,11 @@ impl ClientState for MockClientState { _ctx: &dyn ClientReader, _client_id: ClientId, header: Any, - ) -> Result { + ) -> Result { let header = MockHeader::try_from(header)?; if self.latest_height() >= header.height() { - return Err(Error::LowHeaderHeight { + return Err(ClientError::LowHeaderHeight { header_height: header.height(), latest_height: self.latest_height(), }); @@ -197,11 +197,11 @@ impl ClientState for MockClientState { _ctx: &dyn crate::core::ValidationContext, _client_id: ClientId, header: Any, - ) -> Result { + ) -> Result { let header = MockHeader::try_from(header)?; if self.latest_height() >= header.height() { - return Err(Error::LowHeaderHeight { + return Err(ClientError::LowHeaderHeight { header_height: header.height(), latest_height: self.latest_height(), }); @@ -218,7 +218,7 @@ impl ClientState for MockClientState { consensus_state: Any, _proof_upgrade_client: MerkleProof, _proof_upgrade_consensus_state: MerkleProof, - ) -> Result { + ) -> Result { let consensus_state = MockConsensusState::try_from(consensus_state)?; Ok(UpdatedState { client_state: clone_box(self), @@ -235,7 +235,7 @@ impl ClientState for MockClientState { client_id: &ClientId, consensus_height: Height, _expected_consensus_state: &dyn ConsensusState, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { let client_prefixed_path = Path::ClientConsensusState(ClientConsensusStatePath { client_id: client_id.clone(), epoch: consensus_height.revision_number(), @@ -256,7 +256,7 @@ impl ClientState for MockClientState { _root: &CommitmentRoot, _connection_id: &ConnectionId, _expected_connection_end: &ConnectionEnd, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } @@ -269,7 +269,7 @@ impl ClientState for MockClientState { _port_id: &PortId, _channel_id: &ChannelId, _expected_channel_end: &ChannelEnd, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } @@ -281,7 +281,7 @@ impl ClientState for MockClientState { _root: &CommitmentRoot, _client_id: &ClientId, _expected_client_state: Any, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } @@ -296,7 +296,7 @@ impl ClientState for MockClientState { _channel_id: &ChannelId, _sequence: Sequence, _commitment: PacketCommitment, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } @@ -311,7 +311,7 @@ impl ClientState for MockClientState { _channel_id: &ChannelId, _sequence: Sequence, _ack: AcknowledgementCommitment, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } @@ -325,7 +325,7 @@ impl ClientState for MockClientState { _port_id: &PortId, _channel_id: &ChannelId, _sequence: Sequence, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } @@ -339,7 +339,7 @@ impl ClientState for MockClientState { _port_id: &PortId, _channel_id: &ChannelId, _sequence: Sequence, - ) -> Result<(), Error> { + ) -> Result<(), ClientError> { Ok(()) } } diff --git a/crates/ibc/src/mock/consensus_state.rs b/crates/ibc/src/mock/consensus_state.rs index 232aee018..5cf3a157f 100644 --- a/crates/ibc/src/mock/consensus_state.rs +++ b/crates/ibc/src/mock/consensus_state.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics23_commitment::commitment::CommitmentRoot; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::header::MockHeader; @@ -37,10 +37,10 @@ impl MockConsensusState { impl Protobuf for MockConsensusState {} impl TryFrom for MockConsensusState { - type Error = Error; + type Error = ClientError; fn try_from(raw: RawMockConsensusState) -> Result { - let raw_header = raw.header.ok_or(Error::MissingRawConsensusState)?; + let raw_header = raw.header.ok_or(ClientError::MissingRawConsensusState)?; Ok(Self { header: MockHeader::try_from(raw_header)?, @@ -63,16 +63,16 @@ impl From for RawMockConsensusState { impl Protobuf for MockConsensusState {} impl TryFrom for MockConsensusState { - type Error = Error; + type Error = ClientError; - fn try_from(raw: Any) -> Result { + fn try_from(raw: Any) -> Result { use bytes::Buf; use core::ops::Deref; use prost::Message; - fn decode_consensus_state(buf: B) -> Result { + fn decode_consensus_state(buf: B) -> Result { RawMockConsensusState::decode(buf) - .map_err(Error::Decode)? + .map_err(ClientError::Decode)? .try_into() } @@ -80,7 +80,7 @@ impl TryFrom for MockConsensusState { MOCK_CONSENSUS_STATE_TYPE_URL => { decode_consensus_state(raw.value.deref()).map_err(Into::into) } - _ => Err(Error::UnknownConsensusStateType { + _ => Err(ClientError::UnknownConsensusStateType { consensus_state_type: raw.type_url, }), } diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index b11c434e8..f4b7a63a4 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -22,7 +22,7 @@ use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::context::{ClientKeeper, ClientReader}; -use crate::core::ics02_client::error::Error as Ics02Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::header::Header; use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics03_connection::context::{ConnectionKeeper, ConnectionReader}; @@ -1178,38 +1178,38 @@ impl ConnectionKeeper for MockContext { } impl ClientReader for MockContext { - fn client_type(&self, client_id: &ClientId) -> Result { + fn client_type(&self, client_id: &ClientId) -> Result { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => Ok(client_record.client_type.clone()), - None => Err(Ics02Error::ClientNotFound { + None => Err(ClientError::ClientNotFound { client_id: client_id.clone(), }), } } - fn client_state(&self, client_id: &ClientId) -> Result, Ics02Error> { + fn client_state(&self, client_id: &ClientId) -> Result, ClientError> { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => { client_record .client_state .clone() - .ok_or_else(|| Ics02Error::ClientNotFound { + .ok_or_else(|| ClientError::ClientNotFound { client_id: client_id.clone(), }) } - None => Err(Ics02Error::ClientNotFound { + None => Err(ClientError::ClientNotFound { client_id: client_id.clone(), }), } } - fn decode_client_state(&self, client_state: Any) -> Result, Ics02Error> { + fn decode_client_state(&self, client_state: Any) -> Result, ClientError> { if let Ok(client_state) = TmClientState::try_from(client_state.clone()) { Ok(client_state.into_box()) } else if let Ok(client_state) = MockClientState::try_from(client_state.clone()) { Ok(client_state.into_box()) } else { - Err(Ics02Error::UnknownClientStateType { + Err(ClientError::UnknownClientStateType { client_state_type: client_state.type_url, }) } @@ -1219,16 +1219,16 @@ impl ClientReader for MockContext { &self, client_id: &ClientId, height: Height, - ) -> Result, Ics02Error> { + ) -> Result, ClientError> { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => match client_record.consensus_states.get(&height) { Some(consensus_state) => Ok(consensus_state.clone()), - None => Err(Ics02Error::ConsensusStateNotFound { + None => Err(ClientError::ConsensusStateNotFound { client_id: client_id.clone(), height, }), }, - None => Err(Ics02Error::ConsensusStateNotFound { + None => Err(ClientError::ConsensusStateNotFound { client_id: client_id.clone(), height, }), @@ -1240,13 +1240,13 @@ impl ClientReader for MockContext { &self, client_id: &ClientId, height: Height, - ) -> Result>, Ics02Error> { + ) -> Result>, ClientError> { let ibc_store = self.ibc_store.lock().unwrap(); let client_record = ibc_store .clients .get(client_id) - .ok_or_else(|| Ics02Error::ClientNotFound { + .ok_or_else(|| ClientError::ClientNotFound { client_id: client_id.clone(), })?; @@ -1271,13 +1271,13 @@ impl ClientReader for MockContext { &self, client_id: &ClientId, height: Height, - ) -> Result>, Ics02Error> { + ) -> Result>, ClientError> { let ibc_store = self.ibc_store.lock().unwrap(); let client_record = ibc_store .clients .get(client_id) - .ok_or_else(|| Ics02Error::ClientNotFound { + .ok_or_else(|| ClientError::ClientNotFound { client_id: client_id.clone(), })?; @@ -1297,11 +1297,11 @@ impl ClientReader for MockContext { Ok(None) } - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { Ok(self.latest_height()) } - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { Ok(self .history .last() @@ -1311,18 +1311,18 @@ impl ClientReader for MockContext { .unwrap()) } - fn host_consensus_state(&self, height: Height) -> Result, Ics02Error> { + fn host_consensus_state(&self, height: Height) -> Result, ClientError> { match self.host_block(height) { Some(block_ref) => Ok(block_ref.clone().into()), - None => Err(Ics02Error::MissingLocalConsensusState { height }), + None => Err(ClientError::MissingLocalConsensusState { height }), } } - fn pending_host_consensus_state(&self) -> Result, Ics02Error> { - Err(Ics02Error::ImplementationSpecific) + fn pending_host_consensus_state(&self) -> Result, ClientError> { + Err(ClientError::ImplementationSpecific) } - fn client_counter(&self) -> Result { + fn client_counter(&self) -> Result { Ok(self.ibc_store.lock().unwrap().client_ids_counter) } } @@ -1332,7 +1332,7 @@ impl ClientKeeper for MockContext { &mut self, client_id: ClientId, client_type: ClientType, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let mut ibc_store = self.ibc_store.lock().unwrap(); let client_record = ibc_store .clients @@ -1351,7 +1351,7 @@ impl ClientKeeper for MockContext { &mut self, client_id: ClientId, client_state: Box, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let mut ibc_store = self.ibc_store.lock().unwrap(); let client_record = ibc_store .clients @@ -1371,7 +1371,7 @@ impl ClientKeeper for MockContext { client_id: ClientId, height: Height, consensus_state: Box, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let mut ibc_store = self.ibc_store.lock().unwrap(); let client_record = ibc_store .clients @@ -1397,7 +1397,7 @@ impl ClientKeeper for MockContext { client_id: ClientId, height: Height, timestamp: Timestamp, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let _ = self .ibc_store .lock() @@ -1412,7 +1412,7 @@ impl ClientKeeper for MockContext { client_id: ClientId, height: Height, host_height: Height, - ) -> Result<(), Ics02Error> { + ) -> Result<(), ClientError> { let _ = self .ibc_store .lock() diff --git a/crates/ibc/src/mock/header.rs b/crates/ibc/src/mock/header.rs index 68e88bbc8..2856eb398 100644 --- a/crates/ibc/src/mock/header.rs +++ b/crates/ibc/src/mock/header.rs @@ -7,7 +7,7 @@ use ibc_proto::protobuf::Protobuf; use serde_derive::{Deserialize, Serialize}; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::header::Header; use crate::mock::client_state::client_type as mock_client_type; use crate::timestamp::Timestamp; @@ -43,17 +43,17 @@ impl Display for MockHeader { impl Protobuf for MockHeader {} impl TryFrom for MockHeader { - type Error = Error; + type Error = ClientError; fn try_from(raw: RawMockHeader) -> Result { Ok(MockHeader { height: raw .height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingRawHeader)?, + .ok_or(ClientError::MissingRawHeader)?, timestamp: Timestamp::from_nanoseconds(raw.timestamp) - .map_err(Error::InvalidPacketTimestamp)?, + .map_err(ClientError::InvalidPacketTimestamp)?, }) } } @@ -101,13 +101,13 @@ impl Header for MockHeader { impl Protobuf for MockHeader {} impl TryFrom for MockHeader { - type Error = Error; + type Error = ClientError; - fn try_from(raw: Any) -> Result { + fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { MOCK_HEADER_TYPE_URL => Ok(Protobuf::::decode_vec(&raw.value) - .map_err(Error::InvalidRawHeader)?), - _ => Err(Error::UnknownHeaderType { + .map_err(ClientError::InvalidRawHeader)?), + _ => Err(ClientError::UnknownHeaderType { header_type: raw.type_url, }), } diff --git a/crates/ibc/src/mock/host.rs b/crates/ibc/src/mock/host.rs index f4c78dceb..ca59c360b 100644 --- a/crates/ibc/src/mock/host.rs +++ b/crates/ibc/src/mock/host.rs @@ -13,7 +13,7 @@ use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TMConse use crate::clients::ics07_tendermint::header::TENDERMINT_HEADER_TYPE_URL; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::header::Header; use crate::core::ics24_host::identifier::ChainId; use crate::mock::client_state::client_type as mock_client_type; @@ -140,9 +140,9 @@ impl From for Box { impl ErasedProtobuf for HostBlock {} impl TryFrom for HostBlock { - type Error = Error; + type Error = ClientError; - fn try_from(_raw: Any) -> Result { + fn try_from(_raw: Any) -> Result { todo!() } } diff --git a/crates/ibc/src/mock/misbehaviour.rs b/crates/ibc/src/mock/misbehaviour.rs index d49723fc0..d04216e25 100644 --- a/crates/ibc/src/mock/misbehaviour.rs +++ b/crates/ibc/src/mock/misbehaviour.rs @@ -4,7 +4,7 @@ use ibc_proto::ibc::mock::Misbehaviour as RawMisbehaviour; use ibc_proto::protobuf::Protobuf; use serde::{Deserialize, Serialize}; -use crate::core::ics02_client::error::Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ClientId; use crate::mock::header::MockHeader; use crate::Height; @@ -31,18 +31,18 @@ impl crate::core::ics02_client::misbehaviour::Misbehaviour for Misbehaviour { impl Protobuf for Misbehaviour {} impl TryFrom for Misbehaviour { - type Error = Error; + type Error = ClientError; fn try_from(raw: RawMisbehaviour) -> Result { Ok(Self { client_id: Default::default(), header1: raw .header1 - .ok_or(Error::MissingRawMisbehaviour)? + .ok_or(ClientError::MissingRawMisbehaviour)? .try_into()?, header2: raw .header2 - .ok_or(Error::MissingRawMisbehaviour)? + .ok_or(ClientError::MissingRawMisbehaviour)? .try_into()?, }) } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 53764df20..cf5a5e337 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -10,7 +10,7 @@ use crate::applications::transfer::context::{ use crate::applications::transfer::{error::Error as Ics20Error, PrefixedCoin}; use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::ConsensusState; -use crate::core::ics02_client::error::Error as Ics02Error; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics03_connection::error::Error as Ics03Error; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; @@ -247,11 +247,11 @@ impl SendPacketReader for DummyTransferModule { client_record .client_state .clone() - .ok_or_else(|| Ics02Error::ClientNotFound { + .ok_or_else(|| ClientError::ClientNotFound { client_id: client_id.clone(), }) } - None => Err(Ics02Error::ClientNotFound { + None => Err(ClientError::ClientNotFound { client_id: client_id.clone(), }), } @@ -266,12 +266,12 @@ impl SendPacketReader for DummyTransferModule { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => match client_record.consensus_states.get(&height) { Some(consensus_state) => Ok(consensus_state.clone()), - None => Err(Ics02Error::ConsensusStateNotFound { + None => Err(ClientError::ConsensusStateNotFound { client_id: client_id.clone(), height, }), }, - None => Err(Ics02Error::ConsensusStateNotFound { + None => Err(ClientError::ConsensusStateNotFound { client_id: client_id.clone(), height, }), From 7cf22770922524d9f435c9f576de4ae76dbae960 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 02:08:17 +0800 Subject: [PATCH 27/43] Rename Ics03Error to ConnectionError --- .../clients/ics07_tendermint/host_helpers.rs | 24 +++++----- crates/ibc/src/core/context.rs | 2 +- .../src/core/ics03_connection/connection.rs | 41 ++++++++++------- .../ibc/src/core/ics03_connection/context.rs | 34 ++++++++------ crates/ibc/src/core/ics03_connection/error.rs | 18 ++++---- .../ibc/src/core/ics03_connection/handler.rs | 4 +- .../ics03_connection/handler/conn_open_ack.rs | 22 ++++----- .../handler/conn_open_confirm.rs | 10 ++-- .../handler/conn_open_init.rs | 6 +-- .../ics03_connection/handler/conn_open_try.rs | 14 +++--- .../ics03_connection/msgs/conn_open_ack.rs | 34 ++++++++------ .../msgs/conn_open_confirm.rs | 17 ++++--- .../ics03_connection/msgs/conn_open_init.rs | 15 +++--- .../ics03_connection/msgs/conn_open_try.rs | 34 ++++++++------ .../ibc/src/core/ics03_connection/version.rs | 20 ++++---- crates/ibc/src/core/ics04_channel/error.rs | 2 +- .../ics04_channel/handler/chan_open_try.rs | 10 ++-- crates/ibc/src/core/ics26_routing/error.rs | 2 +- crates/ibc/src/events.rs | 2 +- crates/ibc/src/mock/context.rs | 46 +++++++++++-------- crates/ibc/src/relayer/ics18_relayer/error.rs | 2 +- crates/ibc/src/test_utils.rs | 8 ++-- 22 files changed, 206 insertions(+), 161 deletions(-) diff --git a/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs b/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs index 21ae8f22f..9a822bfd0 100644 --- a/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs +++ b/crates/ibc/src/clients/ics07_tendermint/host_helpers.rs @@ -6,7 +6,7 @@ use ibc_proto::google::protobuf::Any; use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState; use crate::core::ics02_client::client_state::ClientState; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics23_commitment::specs::ProofSpecs; use crate::core::ics24_host::identifier::ChainId; use crate::Height; @@ -16,21 +16,21 @@ use tendermint::trust_threshold::TrustThresholdFraction as TendermintTrustThresh /// Provides an implementation of `ConnectionReader::validate_self_client` for /// Tendermint-based hosts. pub trait ValidateSelfClientContext { - fn validate_self_client(&self, counterparty_client_state: Any) -> Result<(), Error> { + fn validate_self_client(&self, counterparty_client_state: Any) -> Result<(), ConnectionError> { let counterparty_client_state = TmClientState::try_from(counterparty_client_state) - .map_err(|_| Error::InvalidClientState { + .map_err(|_| ConnectionError::InvalidClientState { reason: "client must be a tendermint client".to_string(), })?; if counterparty_client_state.is_frozen() { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: "client is frozen".to_string(), }); } let self_chain_id = self.chain_id(); if self_chain_id != &counterparty_client_state.chain_id { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: format!( "invalid chain-id. expected: {}, got: {}", self_chain_id, counterparty_client_state.chain_id @@ -40,7 +40,7 @@ pub trait ValidateSelfClientContext { let self_revision_number = self_chain_id.version(); if self_revision_number != counterparty_client_state.latest_height().revision_number() { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: format!( "client is not in the same revision as the chain. expected: {}, got: {}", self_revision_number, @@ -50,7 +50,7 @@ pub trait ValidateSelfClientContext { } if counterparty_client_state.latest_height() >= self.host_current_height() { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: format!( "client has latest height {} greater than or equal to chain height {}", counterparty_client_state.latest_height(), @@ -60,7 +60,7 @@ pub trait ValidateSelfClientContext { } if self.proof_specs() != &counterparty_client_state.proof_specs { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: format!( "client has invalid proof specs. expected: {:?}, got: {:?}", self.proof_specs(), @@ -76,13 +76,13 @@ pub trait ValidateSelfClientContext { trust_level.numerator(), trust_level.denominator(), ) - .map_err(|_| Error::InvalidClientState { + .map_err(|_| ConnectionError::InvalidClientState { reason: "invalid trust level".to_string(), })? }; if self.unbonding_period() != counterparty_client_state.unbonding_period { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: format!( "invalid unbonding period. expected: {:?}, got: {:?}", self.unbonding_period(), @@ -92,7 +92,7 @@ pub trait ValidateSelfClientContext { } if counterparty_client_state.unbonding_period < counterparty_client_state.trusting_period { - return Err(Error::InvalidClientState{ reason: format!( + return Err(ConnectionError::InvalidClientState{ reason: format!( "unbonding period must be greater than trusting period. unbonding period ({:?}) < trusting period ({:?})", counterparty_client_state.unbonding_period, counterparty_client_state.trusting_period @@ -102,7 +102,7 @@ pub trait ValidateSelfClientContext { if !counterparty_client_state.upgrade_path.is_empty() && self.upgrade_path() != counterparty_client_state.upgrade_path { - return Err(Error::InvalidClientState { + return Err(ConnectionError::InvalidClientState { reason: format!( "invalid upgrade path. expected: {:?}, got: {:?}", self.upgrade_path(), diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 48770a634..980f8ba33 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -21,7 +21,7 @@ use super::{ }, ics03_connection::{ connection::ConnectionEnd, - error::Error as ConnectionError, + error::ConnectionError, version::{get_compatible_versions, pick_version, Version as ConnectionVersion}, }, ics04_channel::{ diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index e46cc9ed1..8c7fd76e4 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -16,7 +16,7 @@ use ibc_proto::ibc::core::connection::v1::{ }; use crate::core::ics02_client::error::ClientError; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentPrefix; use crate::core::ics24_host::error::ValidationError; @@ -49,7 +49,7 @@ impl IdentifiedConnectionEnd { impl Protobuf for IdentifiedConnectionEnd {} impl TryFrom for IdentifiedConnectionEnd { - type Error = Error; + type Error = ConnectionError; fn try_from(value: RawIdentifiedConnection) -> Result { let raw_connection_end = RawConnectionEnd { @@ -61,7 +61,10 @@ impl TryFrom for IdentifiedConnectionEnd { }; Ok(IdentifiedConnectionEnd { - connection_id: value.id.parse().map_err(Error::InvalidIdentifier)?, + connection_id: value + .id + .parse() + .map_err(ConnectionError::InvalidIdentifier)?, connection_end: raw_connection_end.try_into()?, }) } @@ -109,22 +112,25 @@ impl Default for ConnectionEnd { impl Protobuf for ConnectionEnd {} impl TryFrom for ConnectionEnd { - type Error = Error; + type Error = ConnectionError; fn try_from(value: RawConnectionEnd) -> Result { let state = value.state.try_into()?; if state == State::Uninitialized { return Ok(ConnectionEnd::default()); } if value.client_id.is_empty() { - return Err(Error::EmptyProtoConnectionEnd); + return Err(ConnectionError::EmptyProtoConnectionEnd); } Ok(Self::new( state, - value.client_id.parse().map_err(Error::InvalidIdentifier)?, + value + .client_id + .parse() + .map_err(ConnectionError::InvalidIdentifier)?, value .counterparty - .ok_or(Error::MissingCounterparty)? + .ok_or(ConnectionError::MissingCounterparty)? .try_into()?, value .versions @@ -253,23 +259,26 @@ impl Protobuf for Counterparty {} // Converts from the wire format RawCounterparty. Typically used from the relayer side // during queries for response validation and to extract the Counterparty structure. impl TryFrom for Counterparty { - type Error = Error; + type Error = ConnectionError; fn try_from(value: RawCounterparty) -> Result { let connection_id = Some(value.connection_id) .filter(|x| !x.is_empty()) .map(|v| FromStr::from_str(v.as_str())) .transpose() - .map_err(Error::InvalidIdentifier)?; + .map_err(ConnectionError::InvalidIdentifier)?; Ok(Counterparty::new( - value.client_id.parse().map_err(Error::InvalidIdentifier)?, + value + .client_id + .parse() + .map_err(ConnectionError::InvalidIdentifier)?, connection_id, value .prefix - .ok_or(Error::MissingCounterparty)? + .ok_or(ConnectionError::MissingCounterparty)? .key_prefix .try_into() - .map_err(|_| Error::Client(ClientError::EmptyPrefix))?, + .map_err(|_| ConnectionError::Client(ClientError::EmptyPrefix))?, )) } } @@ -340,13 +349,13 @@ impl State { } /// Parses the State out from a i32. - pub fn from_i32(s: i32) -> Result { + pub fn from_i32(s: i32) -> Result { match s { 0 => Ok(Self::Uninitialized), 1 => Ok(Self::Init), 2 => Ok(Self::TryOpen), 3 => Ok(Self::Open), - _ => Err(Error::InvalidState { state: s }), + _ => Err(ConnectionError::InvalidState { state: s }), } } @@ -376,14 +385,14 @@ impl Display for State { } impl TryFrom for State { - type Error = Error; + type Error = ConnectionError; fn try_from(value: i32) -> Result { match value { 0 => Ok(Self::Uninitialized), 1 => Ok(Self::Init), 2 => Ok(Self::TryOpen), 3 => Ok(Self::Open), - _ => Err(Error::InvalidState { state: value }), + _ => Err(ConnectionError::InvalidState { state: value }), } } } diff --git a/crates/ibc/src/core/ics03_connection/context.rs b/crates/ibc/src/core/ics03_connection/context.rs index 3e33775ed..ac31e1563 100644 --- a/crates/ibc/src/core/ics03_connection/context.rs +++ b/crates/ibc/src/core/ics03_connection/context.rs @@ -5,7 +5,7 @@ use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics03_connection::connection::ConnectionEnd; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::handler::ConnectionResult; use crate::core::ics03_connection::version::{get_compatible_versions, pick_version, Version}; use crate::core::ics23_commitment::commitment::CommitmentPrefix; @@ -19,20 +19,23 @@ use super::handler::ConnectionIdState; /// A context supplying all the necessary read-only dependencies for processing any `ConnectionMsg`. pub trait ConnectionReader { /// 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; /// Returns the ClientState for the given identifier `client_id`. - fn client_state(&self, client_id: &ClientId) -> Result, Error>; + fn client_state(&self, client_id: &ClientId) -> Result, ConnectionError>; /// Tries to decode the given `client_state` into a concrete light client state. - fn decode_client_state(&self, client_state: Any) -> Result, Error>; + fn decode_client_state( + &self, + client_state: Any, + ) -> Result, ConnectionError>; /// Returns the current height of the local chain. - fn host_current_height(&self) -> Result; + fn host_current_height(&self) -> Result; #[deprecated(since = "0.20.0")] /// Returns the oldest height available on the local chain. - fn host_oldest_height(&self) -> Result; + fn host_oldest_height(&self) -> Result; /// Returns the prefix that the local chain uses in the KV store. fn commitment_prefix(&self) -> CommitmentPrefix; @@ -42,10 +45,13 @@ pub trait ConnectionReader { &self, client_id: &ClientId, height: Height, - ) -> Result, Error>; + ) -> Result, ConnectionError>; /// Returns the ConsensusState of the host (local) chain at a specific height. - fn host_consensus_state(&self, height: Height) -> Result, Error>; + fn host_consensus_state( + &self, + height: Height, + ) -> Result, ConnectionError>; /// Function required by ICS 03. Returns the list of all possible versions that the connection /// handshake protocol supports. @@ -59,23 +65,23 @@ pub trait ConnectionReader { &self, supported_versions: Vec, counterparty_candidate_versions: Vec, - ) -> Result { + ) -> Result { pick_version(supported_versions, counterparty_candidate_versions) } /// Returns a counter on how many connections have been created thus far. /// The value of this counter should increase only via method /// `ConnectionKeeper::increase_connection_counter`. - fn connection_counter(&self) -> Result; + fn connection_counter(&self) -> Result; /// Validates the `ClientState` of the client on the counterparty chain. - fn validate_self_client(&self, counterparty_client_state: Any) -> Result<(), Error>; + fn validate_self_client(&self, counterparty_client_state: Any) -> Result<(), ConnectionError>; } /// A context supplying all the necessary write-only dependencies (i.e., storage writing facility) /// for processing any `ConnectionMsg`. pub trait ConnectionKeeper { - fn store_connection_result(&mut self, result: ConnectionResult) -> Result<(), Error> { + fn store_connection_result(&mut self, result: ConnectionResult) -> Result<(), ConnectionError> { self.store_connection(result.connection_id.clone(), &result.connection_end)?; // If we generated an identifier, increase the counter & associate this new identifier @@ -98,14 +104,14 @@ pub trait ConnectionKeeper { &mut self, connection_id: ConnectionId, connection_end: &ConnectionEnd, - ) -> Result<(), Error>; + ) -> Result<(), ConnectionError>; /// Stores the given connection_id at a path associated with the client_id. fn store_connection_to_client( &mut self, connection_id: ConnectionId, client_id: &ClientId, - ) -> Result<(), Error>; + ) -> Result<(), ConnectionError>; /// Called upon connection identifier creation (Init or Try process). /// Increases the counter which keeps track of how many connections have been created. diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index ec13764d3..344708d62 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -10,7 +10,7 @@ use alloc::string::String; use displaydoc::Display; #[derive(Debug, Display)] -pub enum Error { +pub enum ConnectionError { /// ICS02 client error Client(client_error::ClientError), /// connection state is unknown: `{state}` @@ -94,18 +94,18 @@ pub enum Error { } #[cfg(feature = "std")] -impl std::error::Error for Error { +impl std::error::Error for ConnectionError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::Client(e) => Some(e), - Error::InvalidIdentifier(e) => Some(e), - Error::InvalidProof(e) => Some(e), - Error::VerifyConnectionState(e) => Some(e), - Error::Signer(e) => Some(e), - Error::ConsensusStateVerificationFailure { + Self::Client(e) => Some(e), + Self::InvalidIdentifier(e) => Some(e), + Self::InvalidProof(e) => Some(e), + Self::VerifyConnectionState(e) => Some(e), + Self::Signer(e) => Some(e), + Self::ConsensusStateVerificationFailure { client_error: e, .. } => Some(e), - Error::ClientStateVerificationFailure { + Self::ClientStateVerificationFailure { client_error: e, .. } => Some(e), _ => None, diff --git a/crates/ibc/src/core/ics03_connection/handler.rs b/crates/ibc/src/core/ics03_connection/handler.rs index 5c9d67993..bcf627f62 100644 --- a/crates/ibc/src/core/ics03_connection/handler.rs +++ b/crates/ibc/src/core/ics03_connection/handler.rs @@ -3,7 +3,7 @@ use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics03_connection::context::ConnectionReader; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::msgs::ConnectionMsg; use crate::core::ics24_host::identifier::ConnectionId; use crate::handler::HandlerOutput; @@ -43,7 +43,7 @@ pub struct ConnectionResult { pub fn dispatch( ctx: &Ctx, msg: ConnectionMsg, -) -> Result, Error> +) -> Result, ConnectionError> where Ctx: ConnectionReader, { diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs index cca1bba0f..21467775e 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_ack.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::context::ConnectionReader; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenAck; use crate::core::ics03_connection::handler::ConnectionResult; use crate::core::ics03_connection::msgs::conn_open_ack::MsgConnectionOpenAck; @@ -16,11 +16,11 @@ use super::ConnectionIdState; pub(crate) fn process( ctx_a: &dyn ConnectionReader, msg: MsgConnectionOpenAck, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); if msg.consensus_height_of_a_on_b > ctx_a.host_current_height()? { - return Err(Error::InvalidConsensusHeight { + return Err(ConnectionError::InvalidConsensusHeight { target_height: msg.consensus_height_of_a_on_b, current_height: ctx_a.host_current_height()?, }); @@ -32,7 +32,7 @@ pub(crate) fn process( if !(conn_end_on_a.state_matches(&State::Init) && conn_end_on_a.versions().contains(&msg.version)) { - return Err(Error::ConnectionMismatch { + return Err(ConnectionError::ConnectionMismatch { connection_id: msg.conn_id_on_a, }); } @@ -43,7 +43,7 @@ pub(crate) fn process( let conn_id_on_b = conn_end_on_a .counterparty() .connection_id() - .ok_or(Error::InvalidCounterparty)?; + .ok_or(ConnectionError::InvalidCounterparty)?; // Proof verification. { @@ -76,7 +76,7 @@ pub(crate) fn process( conn_id_on_b, &expected_conn_end_on_b, ) - .map_err(Error::VerifyConnectionState)?; + .map_err(ConnectionError::VerifyConnectionState)?; } client_state_of_b_on_a @@ -88,7 +88,7 @@ pub(crate) fn process( client_id_on_b, msg.client_state_of_a_on_b, ) - .map_err(|e| Error::ClientStateVerificationFailure { + .map_err(|e| ConnectionError::ClientStateVerificationFailure { client_id: conn_end_on_a.client_id().clone(), client_error: e, })?; @@ -105,7 +105,7 @@ pub(crate) fn process( msg.consensus_height_of_a_on_b, expected_consensus_state_of_a_on_b.as_ref(), ) - .map_err(|e| Error::ConsensusStateVerificationFailure { + .map_err(|e| ConnectionError::ConsensusStateVerificationFailure { height: msg.proofs_height_on_b, client_error: e, })?; @@ -169,7 +169,7 @@ mod tests { ctx: MockContext, msg: ConnectionMsg, want_pass: bool, - match_error: Box, + match_error: Box, } let msg_ack = @@ -229,7 +229,7 @@ mod tests { match_error: { let right_connection_id = conn_id.clone(); Box::new(move |e| match e { - error::Error::ConnectionNotFound { connection_id } => { + error::ConnectionError::ConnectionNotFound { connection_id } => { assert_eq!(connection_id, right_connection_id) } _ => { @@ -249,7 +249,7 @@ mod tests { match_error: { let right_connection_id = conn_id; Box::new(move |e| match e { - error::Error::ConnectionMismatch { connection_id } => { + error::ConnectionError::ConnectionMismatch { connection_id } => { assert_eq!(connection_id, right_connection_id); } _ => { diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs index 018715c9e..f0867f158 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_confirm.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::context::ConnectionReader; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenConfirm; use crate::core::ics03_connection::handler::{ConnectionIdState, ConnectionResult}; use crate::core::ics03_connection::msgs::conn_open_confirm::MsgConnectionOpenConfirm; @@ -14,12 +14,12 @@ use crate::prelude::*; pub(crate) fn process( ctx_b: &dyn ConnectionReader, msg: MsgConnectionOpenConfirm, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let conn_end_on_b = ctx_b.connection_end(&msg.conn_id_on_b)?; if !conn_end_on_b.state_matches(&State::TryOpen) { - return Err(Error::ConnectionMismatch { + return Err(ConnectionError::ConnectionMismatch { connection_id: msg.conn_id_on_b, }); } @@ -28,7 +28,7 @@ pub(crate) fn process( let conn_id_on_a = conn_end_on_b .counterparty() .connection_id() - .ok_or(Error::InvalidCounterparty)?; + .ok_or(ConnectionError::InvalidCounterparty)?; // Verify proofs { @@ -60,7 +60,7 @@ pub(crate) fn process( conn_id_on_a, &expected_conn_end_on_a, ) - .map_err(Error::VerifyConnectionState)?; + .map_err(ConnectionError::VerifyConnectionState)?; } // Success diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs index 91551ca5f..65911d8ef 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_init.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::{ConnectionEnd, State}; use crate::core::ics03_connection::context::ConnectionReader; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenInit; use crate::core::ics03_connection::handler::ConnectionResult; use crate::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; @@ -17,7 +17,7 @@ use super::ConnectionIdState; pub(crate) fn process( ctx_a: &dyn ConnectionReader, msg: MsgConnectionOpenInit, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); // An IBC client running on the local (host) chain should exist. @@ -28,7 +28,7 @@ pub(crate) fn process( if ctx_a.get_compatible_versions().contains(&version) { Ok(vec![version]) } else { - Err(Error::VersionNotSupported { version }) + Err(ConnectionError::VersionNotSupported { version }) } } None => Ok(ctx_a.get_compatible_versions()), diff --git a/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs b/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs index 6ffd462c5..96dfe5956 100644 --- a/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs +++ b/crates/ibc/src/core/ics03_connection/handler/conn_open_try.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::context::ConnectionReader; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenTry; use crate::core::ics03_connection::handler::ConnectionResult; use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry; @@ -17,7 +17,7 @@ use super::ConnectionIdState; pub(crate) fn process( ctx_b: &dyn ConnectionReader, msg: MsgConnectionOpenTry, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let conn_id_on_b = ConnectionId::new(ctx_b.connection_counter()?); @@ -26,7 +26,7 @@ pub(crate) fn process( if msg.consensus_height_of_b_on_a > ctx_b.host_current_height()? { // Fail if the consensus height is too advanced. - return Err(Error::InvalidConsensusHeight { + return Err(ConnectionError::InvalidConsensusHeight { target_height: msg.consensus_height_of_b_on_a, current_height: ctx_b.host_current_height()?, }); @@ -47,7 +47,7 @@ pub(crate) fn process( let conn_id_on_a = conn_end_on_b .counterparty() .connection_id() - .ok_or(Error::InvalidCounterparty)?; + .ok_or(ConnectionError::InvalidCounterparty)?; // Verify proofs { @@ -77,7 +77,7 @@ pub(crate) fn process( conn_id_on_a, &expected_conn_end_on_a, ) - .map_err(Error::VerifyConnectionState)?; + .map_err(ConnectionError::VerifyConnectionState)?; } client_state_of_a_on_b @@ -89,7 +89,7 @@ pub(crate) fn process( client_id_on_a, msg.client_state_of_b_on_a, ) - .map_err(|e| Error::ClientStateVerificationFailure { + .map_err(|e| ConnectionError::ClientStateVerificationFailure { client_id: conn_end_on_b.client_id().clone(), client_error: e, })?; @@ -106,7 +106,7 @@ pub(crate) fn process( msg.consensus_height_of_b_on_a, expected_consensus_state_of_b_on_a.as_ref(), ) - .map_err(|e| Error::ConsensusStateVerificationFailure { + .map_err(|e| ConnectionError::ConsensusStateVerificationFailure { height: msg.proofs_height_on_a, client_error: e, })?; diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs index d5e5c5f17..3fc90775c 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_ack.rs @@ -4,7 +4,7 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenAck as RawMsgConnectionOpenAck; use ibc_proto::protobuf::Protobuf; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::ConnectionId; @@ -39,7 +39,7 @@ pub struct MsgConnectionOpenAck { } impl Msg for MsgConnectionOpenAck { - type ValidationError = Error; + type ValidationError = ConnectionError; type Raw = RawMsgConnectionOpenAck; fn route(&self) -> String { @@ -54,38 +54,46 @@ impl Msg for MsgConnectionOpenAck { impl Protobuf for MsgConnectionOpenAck {} impl TryFrom for MsgConnectionOpenAck { - type Error = Error; + type Error = ConnectionError; fn try_from(msg: RawMsgConnectionOpenAck) -> Result { Ok(Self { conn_id_on_a: msg .connection_id .parse() - .map_err(Error::InvalidIdentifier)?, + .map_err(ConnectionError::InvalidIdentifier)?, conn_id_on_b: msg .counterparty_connection_id .parse() - .map_err(Error::InvalidIdentifier)?, - client_state_of_a_on_b: msg.client_state.ok_or(Error::MissingClientState)?, - version: msg.version.ok_or(Error::EmptyVersions)?.try_into()?, - proof_conn_end_on_b: msg.proof_try.try_into().map_err(Error::InvalidProof)?, + .map_err(ConnectionError::InvalidIdentifier)?, + client_state_of_a_on_b: msg + .client_state + .ok_or(ConnectionError::MissingClientState)?, + version: msg + .version + .ok_or(ConnectionError::EmptyVersions)? + .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(Error::InvalidProof)?, + .map_err(ConnectionError::InvalidProof)?, proof_consensus_state_of_a_on_b: msg .proof_consensus .try_into() - .map_err(Error::InvalidProof)?, + .map_err(ConnectionError::InvalidProof)?, proofs_height_on_b: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingProofHeight)?, + .ok_or(ConnectionError::MissingProofHeight)?, consensus_height_of_a_on_b: msg .consensus_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingConsensusHeight)?, - signer: msg.signer.parse().map_err(Error::Signer)?, + .ok_or(ConnectionError::MissingConsensusHeight)?, + signer: msg.signer.parse().map_err(ConnectionError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs index 533ed79d8..2ca8419e2 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_confirm.rs @@ -5,7 +5,7 @@ use ibc_proto::protobuf::Protobuf; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenConfirm as RawMsgConnectionOpenConfirm; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics24_host::identifier::ConnectionId; use crate::signer::Signer; use crate::tx_msg::Msg; @@ -26,7 +26,7 @@ pub struct MsgConnectionOpenConfirm { } impl Msg for MsgConnectionOpenConfirm { - type ValidationError = Error; + type ValidationError = ConnectionError; type Raw = RawMsgConnectionOpenConfirm; fn route(&self) -> String { @@ -41,20 +41,23 @@ impl Msg for MsgConnectionOpenConfirm { impl Protobuf for MsgConnectionOpenConfirm {} impl TryFrom for MsgConnectionOpenConfirm { - type Error = Error; + type Error = ConnectionError; fn try_from(msg: RawMsgConnectionOpenConfirm) -> Result { Ok(Self { conn_id_on_b: msg .connection_id .parse() - .map_err(Error::InvalidIdentifier)?, - proof_conn_end_on_a: msg.proof_ack.try_into().map_err(Error::InvalidProof)?, + .map_err(ConnectionError::InvalidIdentifier)?, + proof_conn_end_on_a: msg + .proof_ack + .try_into() + .map_err(ConnectionError::InvalidProof)?, proof_height_on_a: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingProofHeight)?, - signer: msg.signer.parse().map_err(Error::Signer)?, + .ok_or(ConnectionError::MissingProofHeight)?, + signer: msg.signer.parse().map_err(ConnectionError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs index 401ab3b85..2dcc6fa29 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_init.rs @@ -6,7 +6,7 @@ use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenInit as RawMsgConnect use ibc_proto::protobuf::Protobuf; use crate::core::ics03_connection::connection::Counterparty; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::Version; use crate::core::ics24_host::identifier::ClientId; use crate::signer::Signer; @@ -27,7 +27,7 @@ pub struct MsgConnectionOpenInit { } impl Msg for MsgConnectionOpenInit { - type ValidationError = Error; + type ValidationError = ConnectionError; type Raw = RawMsgConnectionOpenInit; fn route(&self) -> String { @@ -42,18 +42,21 @@ impl Msg for MsgConnectionOpenInit { impl Protobuf for MsgConnectionOpenInit {} impl TryFrom for MsgConnectionOpenInit { - type Error = Error; + type Error = ConnectionError; fn try_from(msg: RawMsgConnectionOpenInit) -> Result { Ok(Self { - client_id_on_a: msg.client_id.parse().map_err(Error::InvalidIdentifier)?, + client_id_on_a: msg + .client_id + .parse() + .map_err(ConnectionError::InvalidIdentifier)?, counterparty: msg .counterparty - .ok_or(Error::MissingCounterparty)? + .ok_or(ConnectionError::MissingCounterparty)? .try_into()?, version: msg.version.map(|version| version.try_into()).transpose()?, delay_period: Duration::from_nanos(msg.delay_period), - signer: msg.signer.parse().map_err(Error::Signer)?, + signer: msg.signer.parse().map_err(ConnectionError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs b/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs index 12fb936ec..2e828ff70 100644 --- a/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs +++ b/crates/ibc/src/core/ics03_connection/msgs/conn_open_try.rs @@ -10,7 +10,7 @@ use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenTry as RawMsgConnecti use ibc_proto::protobuf::Protobuf; use crate::core::ics03_connection::connection::Counterparty; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::ClientId; @@ -51,7 +51,7 @@ pub struct MsgConnectionOpenTry { } impl Msg for MsgConnectionOpenTry { - type ValidationError = Error; + type ValidationError = ConnectionError; type Raw = RawMsgConnectionOpenTry; fn route(&self) -> String { @@ -66,7 +66,7 @@ impl Msg for MsgConnectionOpenTry { impl Protobuf for MsgConnectionOpenTry {} impl TryFrom for MsgConnectionOpenTry { - type Error = Error; + type Error = ConnectionError; fn try_from(msg: RawMsgConnectionOpenTry) -> Result { let counterparty_versions = msg @@ -76,7 +76,7 @@ impl TryFrom for MsgConnectionOpenTry { .collect::, _>>()?; if counterparty_versions.is_empty() { - return Err(Error::EmptyVersions); + return Err(ConnectionError::EmptyVersions); } // We set the deprecated `previous_connection_id` field so that we can @@ -84,32 +84,40 @@ 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(Error::InvalidIdentifier)?, - client_state_of_b_on_a: msg.client_state.ok_or(Error::MissingClientState)?, + client_id_on_b: msg + .client_id + .parse() + .map_err(ConnectionError::InvalidIdentifier)?, + client_state_of_b_on_a: msg + .client_state + .ok_or(ConnectionError::MissingClientState)?, counterparty: msg .counterparty - .ok_or(Error::MissingCounterparty)? + .ok_or(ConnectionError::MissingCounterparty)? .try_into()?, versions_on_a: counterparty_versions, - proof_conn_end_on_a: msg.proof_init.try_into().map_err(Error::InvalidProof)?, + 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(Error::InvalidProof)?, + .map_err(ConnectionError::InvalidProof)?, proof_consensus_state_of_b_on_a: msg .proof_consensus .try_into() - .map_err(Error::InvalidProof)?, + .map_err(ConnectionError::InvalidProof)?, proofs_height_on_a: msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingProofHeight)?, + .ok_or(ConnectionError::MissingProofHeight)?, consensus_height_of_b_on_a: msg .consensus_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingConsensusHeight)?, + .ok_or(ConnectionError::MissingConsensusHeight)?, delay_period: Duration::from_nanos(msg.delay_period), - signer: msg.signer.parse().map_err(Error::Signer)?, + signer: msg.signer.parse().map_err(ConnectionError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics03_connection/version.rs b/crates/ibc/src/core/ics03_connection/version.rs index b336c0181..6f188599e 100644 --- a/crates/ibc/src/core/ics03_connection/version.rs +++ b/crates/ibc/src/core/ics03_connection/version.rs @@ -7,7 +7,7 @@ use ibc_proto::ibc::core::connection::v1::Version as RawVersion; use ibc_proto::protobuf::Protobuf; use serde::{Deserialize, Serialize}; -use crate::core::ics03_connection::error::Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::Order; /// Stores the identifier and the features supported by a version @@ -29,14 +29,14 @@ impl Version { impl Protobuf for Version {} impl TryFrom for Version { - type Error = Error; + type Error = ConnectionError; fn try_from(value: RawVersion) -> Result { if value.identifier.trim().is_empty() { - return Err(Error::EmptyVersions); + return Err(ConnectionError::EmptyVersions); } for feature in value.features.iter() { if feature.trim().is_empty() { - return Err(Error::EmptyFeatures); + return Err(ConnectionError::EmptyFeatures); } } Ok(Version { @@ -87,7 +87,7 @@ pub fn get_compatible_versions() -> Vec { pub fn pick_version( supported_versions: Vec, counterparty_versions: Vec, -) -> Result { +) -> Result { let mut intersection: Vec = Vec::new(); for s in supported_versions.iter() { for c in counterparty_versions.iter() { @@ -96,7 +96,7 @@ pub fn pick_version( } for feature in c.features.iter() { if feature.trim().is_empty() { - return Err(Error::EmptyFeatures); + return Err(ConnectionError::EmptyFeatures); } } intersection.append(&mut vec![s.clone()]); @@ -104,7 +104,7 @@ pub fn pick_version( } intersection.sort_by(|a, b| a.identifier.cmp(&b.identifier)); if intersection.is_empty() { - return Err(Error::NoCommonVersion); + return Err(ConnectionError::NoCommonVersion); } Ok(intersection[0].clone()) } @@ -117,7 +117,7 @@ mod tests { use ibc_proto::ibc::core::connection::v1::Version as RawVersion; - use crate::core::ics03_connection::error::Error; + use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::{get_compatible_versions, pick_version, Version}; fn good_versions() -> Vec { @@ -263,7 +263,7 @@ mod tests { name: String, supported: Vec, counterparty: Vec, - picked: Result, + picked: Result, want_pass: bool, } let tests: Vec = vec![ @@ -285,7 +285,7 @@ mod tests { name: "Disjoint versions".to_string(), supported: disjoint().0, counterparty: disjoint().1, - picked: Err(Error::NoCommonVersion), + picked: Err(ConnectionError::NoCommonVersion), want_pass: false, }, ]; diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 338e08fc8..b5d893478 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -18,7 +18,7 @@ use ibc_proto::protobuf::Error as TendermintError; #[derive(Debug, Display)] pub enum Error { /// ICS03 connection error - Connection(connection_error::Error), + Connection(connection_error::ConnectionError), /// ICS05 port error Port(port_error::Error), /// channel state unknown: `{state}` diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index a1c15ff88..82714a7ac 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -201,7 +201,7 @@ mod tests { error::Error::Connection(e) => { assert_eq!( e.to_string(), - ics03_error::Error::ConnectionNotFound { connection_id } + ics03_error::ConnectionError::ConnectionNotFound { connection_id } .to_string() ); } @@ -227,9 +227,11 @@ mod tests { error::Error::Connection(e) => { assert_eq!( e.to_string(), - ics03_error::Error::Client(ics02_error::ClientError::ClientNotFound { - client_id: ClientId::new(mock_client_type(), 45).unwrap() - }) + ics03_error::ConnectionError::Client( + ics02_error::ClientError::ClientNotFound { + client_id: ClientId::new(mock_client_type(), 45).unwrap() + } + ) .to_string() ); } diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 7da2e7f8b..b31004850 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -10,7 +10,7 @@ pub enum Error { /// ICS02 client error Client(ics02_client::error::ClientError), /// ICS03 connection error - Connection(ics03_connection::error::Error), + Connection(ics03_connection::error::ConnectionError), /// ICS04 channel error Channel(ics04_channel::error::Error), /// unknown type URL `{url}` diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index bb1b9abba..24682f5af 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -25,7 +25,7 @@ pub enum Error { /// ICS02 client error Client(client_error::ClientError), /// connection error - Connection(connection_error::Error), + Connection(connection_error::ConnectionError), /// channel error Channel(channel_error::Error), /// error parsing timestamp diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index f4b7a63a4..d2746854d 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -26,7 +26,7 @@ use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::header::Header; use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics03_connection::context::{ConnectionKeeper, ConnectionReader}; -use crate::core::ics03_connection::error::Error as Ics03Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment}; use crate::core::ics04_channel::context::{ChannelKeeper, ChannelReader}; @@ -708,7 +708,7 @@ impl ChannelReader for MockContext { fn client_state(&self, client_id: &ClientId) -> Result, Ics04Error> { ClientReader::client_state(self, client_id) - .map_err(|e| Ics04Error::Connection(Ics03Error::Client(e))) + .map_err(|e| Ics04Error::Connection(ConnectionError::Client(e))) } fn client_consensus_state( @@ -717,7 +717,7 @@ impl ChannelReader for MockContext { height: Height, ) -> Result, Ics04Error> { ClientReader::consensus_state(self, client_id, height) - .map_err(|e| Ics04Error::Connection(Ics03Error::Client(e))) + .map_err(|e| Ics04Error::Connection(ConnectionError::Client(e))) } fn get_next_sequence_send( @@ -863,7 +863,7 @@ impl ChannelReader for MockContext { fn pending_host_consensus_state(&self) -> Result, Ics04Error> { ClientReader::pending_host_consensus_state(self) - .map_err(|e| Ics04Error::Connection(Ics03Error::Client(e))) + .map_err(|e| Ics04Error::Connection(ConnectionError::Client(e))) } fn client_update_time( @@ -1091,29 +1091,32 @@ impl ChannelKeeper for MockContext { } impl ConnectionReader for MockContext { - fn connection_end(&self, cid: &ConnectionId) -> Result { + fn connection_end(&self, cid: &ConnectionId) -> Result { match self.ibc_store.lock().unwrap().connections.get(cid) { Some(connection_end) => Ok(connection_end.clone()), - None => Err(Ics03Error::ConnectionNotFound { + None => Err(ConnectionError::ConnectionNotFound { connection_id: cid.clone(), }), } } - fn client_state(&self, client_id: &ClientId) -> Result, Ics03Error> { + fn client_state(&self, client_id: &ClientId) -> Result, ConnectionError> { // Forward method call to the Ics2 Client-specific method. - ClientReader::client_state(self, client_id).map_err(Ics03Error::Client) + ClientReader::client_state(self, client_id).map_err(ConnectionError::Client) } - fn decode_client_state(&self, client_state: Any) -> Result, Ics03Error> { - ClientReader::decode_client_state(self, client_state).map_err(Ics03Error::Client) + fn decode_client_state( + &self, + client_state: Any, + ) -> Result, ConnectionError> { + ClientReader::decode_client_state(self, client_state).map_err(ConnectionError::Client) } - fn host_current_height(&self) -> Result { + fn host_current_height(&self) -> Result { Ok(self.latest_height()) } - fn host_oldest_height(&self) -> Result { + fn host_oldest_height(&self) -> Result { // history must be non-empty, so `self.history[0]` is valid Ok(self.history[0].height()) } @@ -1126,21 +1129,24 @@ impl ConnectionReader for MockContext { &self, client_id: &ClientId, height: Height, - ) -> Result, Ics03Error> { + ) -> Result, ConnectionError> { // Forward method call to the Ics2Client-specific method. self.consensus_state(client_id, height) - .map_err(Ics03Error::Client) + .map_err(ConnectionError::Client) } - fn host_consensus_state(&self, height: Height) -> Result, Ics03Error> { - ClientReader::host_consensus_state(self, height).map_err(Ics03Error::Client) + fn host_consensus_state( + &self, + height: Height, + ) -> Result, ConnectionError> { + ClientReader::host_consensus_state(self, height).map_err(ConnectionError::Client) } - fn connection_counter(&self) -> Result { + fn connection_counter(&self) -> Result { Ok(self.ibc_store.lock().unwrap().connection_ids_counter) } - fn validate_self_client(&self, _counterparty_client_state: Any) -> Result<(), Ics03Error> { + fn validate_self_client(&self, _counterparty_client_state: Any) -> Result<(), ConnectionError> { Ok(()) } } @@ -1150,7 +1156,7 @@ impl ConnectionKeeper for MockContext { &mut self, connection_id: ConnectionId, connection_end: &ConnectionEnd, - ) -> Result<(), Ics03Error> { + ) -> Result<(), ConnectionError> { self.ibc_store .lock() .unwrap() @@ -1163,7 +1169,7 @@ impl ConnectionKeeper for MockContext { &mut self, connection_id: ConnectionId, client_id: &ClientId, - ) -> Result<(), Ics03Error> { + ) -> Result<(), ConnectionError> { self.ibc_store .lock() .unwrap() diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index 354c1d73e..61cb3a3f0 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -23,5 +23,5 @@ pub enum Error { /// transaction processing by modules failed, error(`{0}`) TransactionFailed(RoutingError), /// ics03 connection error(`{0}`) - Ics03(ics03_connection::error::Error), + Ics03(ics03_connection::error::ConnectionError), } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index cf5a5e337..de40b754c 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -12,7 +12,7 @@ use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::ConnectionEnd; -use crate::core::ics03_connection::error::Error as Ics03Error; +use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics04_channel::context::SendPacketReader; @@ -234,7 +234,7 @@ impl SendPacketReader for DummyTransferModule { fn connection_end(&self, cid: &ConnectionId) -> Result { match self.ibc_store.lock().unwrap().connections.get(cid) { Some(connection_end) => Ok(connection_end.clone()), - None => Err(Ics03Error::ConnectionNotFound { + None => Err(ConnectionError::ConnectionNotFound { connection_id: cid.clone(), }), } @@ -255,7 +255,7 @@ impl SendPacketReader for DummyTransferModule { client_id: client_id.clone(), }), } - .map_err(|e| Error::Connection(Ics03Error::Client(e))) + .map_err(|e| Error::Connection(ConnectionError::Client(e))) } fn client_consensus_state( @@ -276,7 +276,7 @@ impl SendPacketReader for DummyTransferModule { height, }), } - .map_err(|e| Error::Connection(Ics03Error::Client(e))) + .map_err(|e| Error::Connection(ConnectionError::Client(e))) } fn get_next_sequence_send( From 77bed23c8b8127f0b7f6ae137a20262ea3201d81 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 03:25:02 +0800 Subject: [PATCH 28/43] Disassembling out PacketError --- .../ibc/src/applications/transfer/context.rs | 12 +- crates/ibc/src/applications/transfer/error.rs | 6 +- .../transfer/relay/send_transfer.rs | 8 +- crates/ibc/src/core/ics04_channel/context.rs | 82 ++++--- crates/ibc/src/core/ics04_channel/error.rs | 213 ++++++++++++------ crates/ibc/src/core/ics04_channel/handler.rs | 17 +- .../ics04_channel/handler/acknowledgement.rs | 25 +- .../core/ics04_channel/handler/recv_packet.rs | 36 +-- .../core/ics04_channel/handler/send_packet.rs | 16 +- .../src/core/ics04_channel/handler/timeout.rs | 34 +-- .../ics04_channel/handler/timeout_on_close.rs | 42 ++-- .../handler/write_acknowledgement.rs | 17 +- .../ics04_channel/msgs/acknowledgement.rs | 23 +- .../core/ics04_channel/msgs/recv_packet.rs | 23 +- .../src/core/ics04_channel/msgs/timeout.rs | 23 +- .../ics04_channel/msgs/timeout_on_close.rs | 21 +- crates/ibc/src/core/ics04_channel/packet.rs | 26 ++- crates/ibc/src/core/ics26_routing/context.rs | 6 +- crates/ibc/src/core/ics26_routing/error.rs | 3 + crates/ibc/src/core/ics26_routing/handler.rs | 8 +- crates/ibc/src/mock/context.rs | 42 ++-- crates/ibc/src/test_utils.rs | 30 +-- 22 files changed, 423 insertions(+), 290 deletions(-) diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index c30b1b0ad..26edb0821 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -11,7 +11,7 @@ use crate::applications::transfer::{PrefixedCoin, PrefixedDenom, VERSION}; use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics04_channel::context::{ChannelKeeper, SendPacketReader}; -use crate::core::ics04_channel::error::Error as Ics04Error; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::handler::send_packet::SendPacketResult; use crate::core::ics04_channel::handler::ModuleExtras; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement as GenericAcknowledgement; @@ -23,7 +23,7 @@ use crate::prelude::*; use crate::signer::Signer; pub trait TokenTransferKeeper: BankKeeper { - fn store_send_packet_result(&mut self, result: SendPacketResult) -> Result<(), Ics04Error> { + fn store_send_packet_result(&mut self, result: SendPacketResult) -> Result<(), PacketError> { self.store_next_sequence_send( result.port_id.clone(), result.channel_id.clone(), @@ -45,14 +45,14 @@ pub trait TokenTransferKeeper: BankKeeper { channel_id: ChannelId, sequence: Sequence, commitment: PacketCommitment, - ) -> Result<(), Ics04Error>; + ) -> Result<(), PacketError>; fn store_next_sequence_send( &mut self, port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error>; + ) -> Result<(), PacketError>; } pub trait TokenTransferReader: SendPacketReader { @@ -91,7 +91,7 @@ where channel_id: ChannelId, sequence: Sequence, commitment: PacketCommitment, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { ChannelKeeper::store_packet_commitment(self, port_id, channel_id, sequence, commitment) } @@ -100,7 +100,7 @@ where port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { ChannelKeeper::store_next_sequence_send(self, port_id, channel_id, seq) } } diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index c337d3ffb..e6e226ade 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -19,7 +19,7 @@ use crate::signer::SignerError; impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::ChannelError(e) => Some(e), + Error::PacketError(e) => Some(e), Error::InvalidPortId { validation_error: e, .. @@ -51,8 +51,8 @@ impl std::error::Error for Error { pub enum Error { /// unrecognized ICS-20 transfer message type URL `{url}` UnknowMessageTypeUrl { url: String }, - /// ICS04 channel error - ChannelError(channel_error::Error), + /// ICS04 Packet error + PacketError(channel_error::PacketError), /// destination channel not found in the counterparty of port_id `{port_id}` and channel_id `{channel_id}` DestinationChannelNotFound { port_id: PortId, diff --git a/crates/ibc/src/applications/transfer/relay/send_transfer.rs b/crates/ibc/src/applications/transfer/relay/send_transfer.rs index 9f3414bd4..30c7f0f9c 100644 --- a/crates/ibc/src/applications/transfer/relay/send_transfer.rs +++ b/crates/ibc/src/applications/transfer/relay/send_transfer.rs @@ -28,7 +28,7 @@ where let source_channel_end = ctx .channel_end(&msg.source_port, &msg.source_channel) - .map_err(Error::ChannelError)?; + .map_err(Error::PacketError)?; let destination_port = source_channel_end.counterparty().port_id().clone(); let destination_channel = source_channel_end @@ -43,7 +43,7 @@ where // get the next sequence let sequence = ctx .get_next_sequence_send(&msg.source_port, &msg.source_channel) - .map_err(Error::ChannelError)?; + .map_err(Error::PacketError)?; let token = msg.token.try_into().map_err(|_| Error::InvalidToken)?; let denom = token.denom.clone(); @@ -90,10 +90,10 @@ where result, log, events, - } = send_packet(ctx, packet).map_err(Error::ChannelError)?; + } = send_packet(ctx, packet).map_err(Error::PacketError)?; ctx.store_send_packet_result(result) - .map_err(Error::ChannelError)?; + .map_err(Error::PacketError)?; output.merge_output( HandlerOutput::builder() diff --git a/crates/ibc/src/core/ics04_channel/context.rs b/crates/ibc/src/core/ics04_channel/context.rs index e153c5cef..1dfd960a2 100644 --- a/crates/ibc/src/core/ics04_channel/context.rs +++ b/crates/ibc/src/core/ics04_channel/context.rs @@ -12,7 +12,10 @@ use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCo use crate::core::ics04_channel::handler::recv_packet::RecvPacketResult; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement; -use crate::core::ics04_channel::{error::Error, packet::Receipt}; +use crate::core::ics04_channel::{ + error::{Error, PacketError}, + packet::Receipt, +}; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; use crate::prelude::*; use crate::timestamp::Timestamp; @@ -45,40 +48,40 @@ pub trait ChannelReader { &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result; + ) -> Result; fn get_next_sequence_recv( &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result; + ) -> Result; fn get_next_sequence_ack( &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result; + ) -> Result; fn get_packet_commitment( &self, port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result; + ) -> Result; fn get_packet_receipt( &self, port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result; + ) -> Result; fn get_packet_acknowledgement( &self, port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result; + ) -> Result; /// Compute the commitment for a packet. /// Note that the absence of `timeout_height` is treated as @@ -152,26 +155,30 @@ pub trait ChannelReader { pub trait SendPacketReader { /// Returns the ChannelEnd for the given `port_id` and `chan_id`. - fn channel_end(&self, port_id: &PortId, channel_id: &ChannelId) -> Result; + fn channel_end( + &self, + port_id: &PortId, + channel_id: &ChannelId, + ) -> 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; /// Returns the ClientState for the given identifier `client_id`. Necessary dependency towards /// proof verification. - fn client_state(&self, client_id: &ClientId) -> Result, Error>; + fn client_state(&self, client_id: &ClientId) -> Result, PacketError>; fn client_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result, Error>; + ) -> Result, PacketError>; fn get_next_sequence_send( &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result; + ) -> Result; fn hash(&self, value: Vec) -> Vec; @@ -200,31 +207,35 @@ impl SendPacketReader for T where T: ChannelReader, { - fn channel_end(&self, port_id: &PortId, channel_id: &ChannelId) -> Result { - ChannelReader::channel_end(self, port_id, channel_id) + fn channel_end( + &self, + port_id: &PortId, + channel_id: &ChannelId, + ) -> Result { + ChannelReader::channel_end(self, port_id, channel_id).map_err(PacketError::Channel) } - fn connection_end(&self, connection_id: &ConnectionId) -> Result { - ChannelReader::connection_end(self, connection_id) + fn connection_end(&self, connection_id: &ConnectionId) -> Result { + ChannelReader::connection_end(self, connection_id).map_err(PacketError::Channel) } - fn client_state(&self, client_id: &ClientId) -> Result, Error> { - ChannelReader::client_state(self, client_id) + fn client_state(&self, client_id: &ClientId) -> Result, PacketError> { + ChannelReader::client_state(self, client_id).map_err(PacketError::Channel) } fn client_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result, Error> { - ChannelReader::client_consensus_state(self, client_id, height) + ) -> Result, PacketError> { + ChannelReader::client_consensus_state(self, client_id, height).map_err(PacketError::Channel) } fn get_next_sequence_send( &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result { + ) -> Result { ChannelReader::get_next_sequence_send(self, port_id, channel_id) } @@ -236,7 +247,7 @@ where /// A context supplying all the necessary write-only dependencies (i.e., storage writing facility) /// for processing any `ChannelMsg`. pub trait ChannelKeeper { - fn store_channel_result(&mut self, result: ChannelResult) -> Result<(), Error> { + fn store_channel_result(&mut self, result: ChannelResult) -> Result<(), PacketError> { let connection_id = result.channel_end.connection_hops()[0].clone(); // The handler processed this channel & some modifications occurred, store the new end. @@ -244,7 +255,8 @@ pub trait ChannelKeeper { result.port_id.clone(), result.channel_id.clone(), result.channel_end, - )?; + ) + .map_err(PacketError::Channel)?; // The channel identifier was freshly brewed. // Increase counter & initialize seq. nrs. @@ -256,7 +268,8 @@ pub trait ChannelKeeper { connection_id, result.port_id.clone(), result.channel_id.clone(), - )?; + ) + .map_err(PacketError::Channel)?; // Initialize send, recv, and ack sequence numbers. self.store_next_sequence_send( @@ -275,7 +288,7 @@ pub trait ChannelKeeper { Ok(()) } - fn store_packet_result(&mut self, general_result: PacketResult) -> Result<(), Error> { + fn store_packet_result(&mut self, general_result: PacketResult) -> Result<(), PacketError> { match general_result { PacketResult::Send(res) => { self.store_next_sequence_send( @@ -319,7 +332,8 @@ pub trait ChannelKeeper { self.delete_packet_commitment(&res.port_id, &res.channel_id, res.seq)?; if let Some(c) = res.channel { // Ordered Channel: closes channel - self.store_channel(res.port_id, res.channel_id, c)?; + self.store_channel(res.port_id, res.channel_id, c) + .map_err(PacketError::Channel)?; } } } @@ -332,14 +346,14 @@ pub trait ChannelKeeper { channel_id: ChannelId, sequence: Sequence, commitment: PacketCommitment, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn delete_packet_commitment( &mut self, port_id: &PortId, channel_id: &ChannelId, seq: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn store_packet_receipt( &mut self, @@ -347,7 +361,7 @@ pub trait ChannelKeeper { channel_id: ChannelId, sequence: Sequence, receipt: Receipt, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn store_packet_acknowledgement( &mut self, @@ -355,14 +369,14 @@ pub trait ChannelKeeper { channel_id: ChannelId, sequence: Sequence, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn delete_packet_acknowledgement( &mut self, port_id: &PortId, channel_id: &ChannelId, sequence: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn store_connection_channels( &mut self, @@ -384,21 +398,21 @@ pub trait ChannelKeeper { port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn store_next_sequence_recv( &mut self, port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; fn store_next_sequence_ack( &mut self, port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Error>; + ) -> Result<(), PacketError>; /// Called upon channel identifier creation (Init or Try message processing). /// Increases the counter which keeps track of how many channels have been created. diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index b5d893478..7ff0053b4 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -23,38 +23,22 @@ pub enum Error { Port(port_error::Error), /// channel state unknown: `{state}` UnknownState { state: i32 }, - /// identifier error - Identifier(ValidationError), + /// channel order type unknown: `{type_id}` UnknownOrderType { type_id: String }, /// invalid connection hops length: expected `{expected}`; actual `{actual}` InvalidConnectionHopsLength { expected: usize, actual: usize }, - /// packet destination port `{port_id}` and channel `{channel_id}` doesn't match the counterparty's port/channel - InvalidPacketCounterparty { - port_id: PortId, - channel_id: ChannelId, - }, /// invalid version InvalidVersion(TendermintError), /// invalid signer address Signer(SignerError), - /// invalid proof - InvalidProof(ProofError), + /// invalid proof: missing height MissingHeight, - /// Missing sequence number for receiving packets on port `{port_id}` and channel `{channel_id}` - MissingNextRecvSeq { - port_id: PortId, - channel_id: ChannelId, - }, - /// packet sequence cannot be 0 - ZeroPacketSequence, - /// packet data bytes cannot be empty - ZeroPacketData, + /// packet data bytes must be valid UTF-8 (this restriction will be lifted in the future) NonUtf8PacketData, - /// invalid timeout height for the packet - InvalidTimeoutHeight, + /// invalid packet InvalidPacket, /// there is no packet in this message @@ -78,10 +62,7 @@ pub enum Error { }, /// a different channel exists (was initialized) already for the same channel identifier `{channel_id}` ChannelMismatch { channel_id: ChannelId }, - /// the associated connection `{connection_id}` is not OPEN - ConnectionNotOpen { connection_id: ConnectionId }, - /// Undefined counterparty connection for `{connection_id}` - UndefinedConnectionCounterparty { connection_id: ConnectionId }, + /// Verification fails for the packet with the sequence number `{sequence}`, error(`{ics02_error}`) PacketVerificationFailed { sequence: Sequence, @@ -89,30 +70,97 @@ pub enum Error { }, /// Error verifying channel state VerifyChannelFailed(client_error::ClientError), - /// Acknowledgment cannot be empty - InvalidAcknowledgement, - /// Packet acknowledgement exists for the packet with the sequence `{sequence}` - AcknowledgementExists { sequence: Sequence }, - /// Missing sequence number for sending packets on port `{port_id}` and channel `{channel_id}` - MissingNextSendSeq { - port_id: PortId, - channel_id: ChannelId, - }, + /// String `{value}` cannot be converted to packet sequence InvalidStringAsSequence { value: String, error: core::num::ParseIntError, }, - /// Invalid packet sequence `{given_sequence}` ≠ next send sequence `{next_sequence}` - InvalidPacketSequence { - given_sequence: Sequence, - next_sequence: Sequence, + + /// Invalid timestamp in consensus state; timestamp must be a positive value + ErrorInvalidConsensusState, + + /// Invalid channel id in counterparty + InvalidCounterpartyChannelId, + + /// Handshake proof verification fails at ChannelOpenAck + ChanOpenAckProofVerification, + + /// Processed time for the client `{client_id}` at height `{height}` not found + ProcessedTimeNotFound { client_id: ClientId, height: Height }, + /// Processed height for the client `{client_id}` at height `{height}` not found + ProcessedHeightNotFound { client_id: ClientId, height: Height }, + /// route not found + RouteNotFound, + + /// application module error: `{description}` + AppModule { description: String }, + /// Failed to convert abci event to IbcEvent: `{abci_event}` + AbciConversionFailed { abci_event: String }, + /// other error: `{description}` + Other { description: String }, + /// Channel `{channel_id}` is Closed + ChannelClosed { channel_id: ChannelId }, + /// the associated connection `{connection_id}` is not OPEN + ConnectionNotOpen { connection_id: ConnectionId }, + /// Undefined counterparty connection for `{connection_id}` + UndefinedConnectionCounterparty { connection_id: ConnectionId }, + /// Client with id `{client_id}` is frozen + FrozenClient { client_id: ClientId }, + /// Channel `{channel_id}` should not be state `{state}` + InvalidChannelState { channel_id: ChannelId, state: State }, + /// invalid proof + InvalidProof(ProofError), + /// identifier error + Identifier(ValidationError), + /// Missing sequence number for sending packets on port `{port_id}` and channel `{channel_id}` + MissingNextSendSeq { + port_id: PortId, + channel_id: ChannelId, }, +} + +#[derive(Debug, Display)] +pub enum PacketError { + /// ICS03 connection error + Connection(connection_error::ConnectionError), + /// ICS04 channel error + Channel(Error), + /// Channel `{channel_id}` is Closed + ChannelClosed { channel_id: ChannelId }, + /// packet destination port `{port_id}` and channel `{channel_id}` doesn't match the counterparty's port/channel + InvalidPacketCounterparty { + port_id: PortId, + channel_id: ChannelId, + }, + /// Client with id `{client_id}` is frozen + FrozenClient { client_id: ClientId }, /// Receiving chain block height `{chain_height}` >= packet timeout height `{timeout_height}` LowPacketHeight { chain_height: Height, timeout_height: TimeoutHeight, }, + /// Receiving chain block timestamp >= packet timeout timestamp + LowPacketTimestamp, + /// Invalid packet sequence `{given_sequence}` ≠ next send sequence `{next_sequence}` + InvalidPacketSequence { + given_sequence: Sequence, + next_sequence: Sequence, + }, + /// Channel `{channel_id}` should not be state `{state}` + InvalidChannelState { channel_id: ChannelId, state: State }, + /// the associated connection `{connection_id}` is not OPEN + ConnectionNotOpen { connection_id: ConnectionId }, + /// Receipt for the packet `{sequence}` not found + PacketReceiptNotFound { sequence: Sequence }, + /// The stored commitment of the packet `{sequence}` is incorrect + IncorrectPacketCommitment { sequence: Sequence }, + /// implementation specific error + ImplementationSpecific, + /// Undefined counterparty connection for `{connection_id}` + UndefinedConnectionCounterparty { connection_id: ConnectionId }, + /// invalid proof + InvalidProof(ProofError), /// Packet timeout height `{timeout_height}` > chain height `{chain_height}` PacketTimeoutHeightNotReached { timeout_height: TimeoutHeight, @@ -123,49 +171,68 @@ pub enum Error { timeout_timestamp: Timestamp, chain_timestamp: Timestamp, }, - /// Receiving chain block timestamp >= packet timeout timestamp - LowPacketTimestamp, + /// Packet acknowledgement exists for the packet with the sequence `{sequence}` + AcknowledgementExists { sequence: Sequence }, + /// Acknowledgment cannot be empty + InvalidAcknowledgement, + /// Acknowledgment for the packet `{sequence}` not found + PacketAcknowledgementNotFound { sequence: Sequence }, + /// invalid proof: missing height + MissingHeight, + /// there is no packet in this message + MissingPacket, + /// invalid signer address + Signer(SignerError), + /// application module error: `{description}` + AppModule { description: String }, + /// route not found + RouteNotFound, + /// packet sequence cannot be 0 + ZeroPacketSequence, + /// invalid timeout height for the packet + InvalidTimeoutHeight, + /// packet data bytes cannot be empty + ZeroPacketData, /// Invalid packet timeout timestamp value InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), - /// Invalid timestamp in consensus state; timestamp must be a positive value - ErrorInvalidConsensusState, - /// Client with id `{client_id}` is frozen - FrozenClient { client_id: ClientId }, - /// Invalid channel id in counterparty - InvalidCounterpartyChannelId, - /// Channel `{channel_id}` should not be state `{state}` - InvalidChannelState { channel_id: ChannelId, state: State }, - /// Channel `{channel_id}` is Closed - ChannelClosed { channel_id: ChannelId }, - /// Handshake proof verification fails at ChannelOpenAck - ChanOpenAckProofVerification, + /// identifier error + Identifier(ValidationError), + /// Missing sequence number for sending packets on port `{port_id}` and channel `{channel_id}` + MissingNextSendSeq { + port_id: PortId, + channel_id: ChannelId, + }, + /// the channel end (`{port_id}`, `{channel_id}`) does not exist + ChannelNotFound { + port_id: PortId, + channel_id: ChannelId, + }, /// Commitment for the packet `{sequence}` not found PacketCommitmentNotFound { sequence: Sequence }, - /// The stored commitment of the packet `{sequence}` is incorrect - IncorrectPacketCommitment { sequence: Sequence }, - /// Receipt for the packet `{sequence}` not found - PacketReceiptNotFound { sequence: Sequence }, - /// Acknowledgment for the packet `{sequence}` not found - PacketAcknowledgementNotFound { sequence: Sequence }, + /// Missing sequence number for receiving packets on port `{port_id}` and channel `{channel_id}` + MissingNextRecvSeq { + port_id: PortId, + channel_id: ChannelId, + }, /// Missing sequence number for ack packets on port `{port_id}` and channel `{channel_id}` MissingNextAckSeq { port_id: PortId, channel_id: ChannelId, }, - /// Processed time for the client `{client_id}` at height `{height}` not found - ProcessedTimeNotFound { client_id: ClientId, height: Height }, - /// Processed height for the client `{client_id}` at height `{height}` not found - ProcessedHeightNotFound { client_id: ClientId, height: Height }, - /// route not found - RouteNotFound, - /// implementation specific error - ImplementationSpecific, - /// application module error: `{description}` - AppModule { description: String }, - /// Failed to convert abci event to IbcEvent: `{abci_event}` - AbciConversionFailed { abci_event: String }, - /// other error: `{description}` - Other { description: String }, +} + +#[cfg(feature = "std")] +impl std::error::Error for PacketError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + PacketError::Connection(e) => Some(e), + PacketError::Channel(e) => Some(e), + PacketError::InvalidProof(e) => Some(e), + PacketError::Signer(e) => Some(e), + PacketError::Identifier(e) => Some(e), + _ => None, + } + } } #[cfg(feature = "std")] @@ -174,13 +241,13 @@ impl std::error::Error for Error { match &self { Error::Connection(e) => Some(e), Error::Port(e) => Some(e), - Error::Identifier(e) => Some(e), + // Error::Identifier(e) => Some(e), Error::InvalidVersion(e) => Some(e), Error::Signer(e) => Some(e), Error::InvalidProof(e) => Some(e), Error::PacketVerificationFailed { ics02_error: e, .. } => Some(e), Error::InvalidStringAsSequence { error: e, .. } => Some(e), - Error::InvalidPacketTimestamp(e) => Some(e), + // Error::InvalidPacketTimestamp(e) => Some(e), _ => None, } } diff --git a/crates/ibc/src/core/ics04_channel/handler.rs b/crates/ibc/src/core/ics04_channel/handler.rs index e753da328..34997b885 100644 --- a/crates/ibc/src/core/ics04_channel/handler.rs +++ b/crates/ibc/src/core/ics04_channel/handler.rs @@ -4,7 +4,7 @@ use crate::prelude::*; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::{Error, PacketError}; use crate::core::ics04_channel::msgs::ChannelMsg; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::{msgs::PacketMsg, packet::PacketResult}; @@ -252,7 +252,7 @@ where pub fn packet_dispatch( ctx: &Ctx, msg: &PacketMsg, -) -> Result<(HandlerOutputBuilder<()>, PacketResult), Error> +) -> Result<(HandlerOutputBuilder<()>, PacketResult), PacketError> where Ctx: ChannelReader, { @@ -276,7 +276,7 @@ pub fn packet_callback( module_id: &ModuleId, msg: &PacketMsg, output: &mut HandlerOutputBuilder<()>, -) -> Result<(), Error> +) -> Result<(), PacketError> where Ctx: RouterContext, { @@ -296,21 +296,22 @@ fn do_packet_callback( msg: &PacketMsg, module_output: &mut ModuleOutputBuilder, core_output: &mut HandlerOutputBuilder<()>, -) -> Result<(), Error> { +) -> Result<(), PacketError> { let cb = ctx .router_mut() .get_route_mut(module_id) - .ok_or(Error::RouteNotFound)?; + .ok_or(PacketError::RouteNotFound)?; match msg { PacketMsg::RecvPacket(msg) => { let result = cb.on_recv_packet(module_output, &msg.packet, &msg.signer); match result { OnRecvPacketAck::Nil(write_fn) => { - write_fn(cb.as_any_mut()).map_err(|e| Error::AppModule { description: e }) + write_fn(cb.as_any_mut()).map_err(|e| PacketError::AppModule { description: e }) } OnRecvPacketAck::Successful(ack, write_fn) => { - write_fn(cb.as_any_mut()).map_err(|e| Error::AppModule { description: e })?; + write_fn(cb.as_any_mut()) + .map_err(|e| PacketError::AppModule { description: e })?; process_write_ack(ctx, msg.packet.clone(), ack.as_ref(), core_output) } @@ -339,7 +340,7 @@ fn process_write_ack( packet: Packet, acknowledgement: &dyn Acknowledgement, core_output: &mut HandlerOutputBuilder<()>, -) -> Result<(), Error> { +) -> Result<(), PacketError> { let HandlerOutput { result, log, diff --git a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs index 174fc3819..fa4e4d6d8 100644 --- a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs @@ -5,7 +5,7 @@ use crate::core::ics04_channel::events::AcknowledgePacket; use crate::core::ics04_channel::handler::verify::verify_packet_acknowledgement_proofs; use crate::core::ics04_channel::msgs::acknowledgement::MsgAcknowledgement; use crate::core::ics04_channel::packet::{PacketResult, Sequence}; -use crate::core::ics04_channel::{context::ChannelReader, error::Error}; +use crate::core::ics04_channel::{context::ChannelReader, error::PacketError}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; @@ -22,15 +22,17 @@ pub struct AckPacketResult { pub fn process( ctx: &Ctx, msg: &MsgAcknowledgement, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let packet = &msg.packet; - let source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; + let source_channel_end = ctx + .channel_end(&packet.source_port, &packet.source_channel) + .map_err(PacketError::Channel)?; if !source_channel_end.state_matches(&State::Open) { - return Err(Error::ChannelClosed { + return Err(PacketError::ChannelClosed { channel_id: packet.source_channel.clone(), }); } @@ -41,17 +43,19 @@ pub fn process( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::InvalidPacketCounterparty { + return Err(PacketError::InvalidPacketCounterparty { port_id: packet.destination_port.clone(), channel_id: packet.destination_channel.clone(), }); } let source_connection_id = &source_channel_end.connection_hops()[0]; - let connection_end = ctx.connection_end(source_connection_id)?; + let connection_end = ctx + .connection_end(source_connection_id) + .map_err(PacketError::Channel)?; if !connection_end.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(PacketError::ConnectionNotOpen { connection_id: source_channel_end.connection_hops()[0].clone(), }); } @@ -67,7 +71,7 @@ pub fn process( packet.timeout_timestamp, ) { - return Err(Error::IncorrectPacketCommitment { + return Err(PacketError::IncorrectPacketCommitment { sequence: packet.sequence, }); } @@ -80,14 +84,15 @@ pub fn process( msg.acknowledgement.clone(), &connection_end, &msg.proofs, - )?; + ) + .map_err(PacketError::Channel)?; let result = if source_channel_end.order_matches(&Order::Ordered) { let next_seq_ack = ctx.get_next_sequence_ack(&packet.source_port, &packet.source_channel)?; if packet.sequence != next_seq_ack { - return Err(Error::InvalidPacketSequence { + return Err(PacketError::InvalidPacketSequence { given_sequence: packet.sequence, next_sequence: next_seq_ack, }); diff --git a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs index 856f29201..2ebba2f37 100644 --- a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs @@ -1,7 +1,7 @@ use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::{Counterparty, Order, State}; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::events::ReceivePacket; use crate::core::ics04_channel::handler::verify::verify_packet_recv_proofs; use crate::core::ics04_channel::msgs::recv_packet::MsgRecvPacket; @@ -31,16 +31,17 @@ pub enum RecvPacketResult { pub fn process( ctx: &Ctx, msg: &MsgRecvPacket, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let packet = &msg.packet; - let dest_channel_end = - ctx.channel_end(&packet.destination_port, &packet.destination_channel)?; + let dest_channel_end = ctx + .channel_end(&packet.destination_port, &packet.destination_channel) + .map_err(PacketError::Channel)?; if !dest_channel_end.state_matches(&State::Open) { - return Err(Error::InvalidChannelState { + return Err(PacketError::InvalidChannelState { channel_id: packet.source_channel.clone(), state: dest_channel_end.state, }); @@ -52,32 +53,34 @@ pub fn process( ); if !dest_channel_end.counterparty_matches(&counterparty) { - return Err(Error::InvalidPacketCounterparty { + return Err(PacketError::InvalidPacketCounterparty { port_id: packet.source_port.clone(), channel_id: packet.source_channel.clone(), }); } let dest_connection_id = &dest_channel_end.connection_hops()[0]; - let connection_end = ctx.connection_end(dest_connection_id)?; + let connection_end = ctx + .connection_end(dest_connection_id) + .map_err(PacketError::Channel)?; if !connection_end.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(PacketError::ConnectionNotOpen { connection_id: dest_channel_end.connection_hops()[0].clone(), }); } - let latest_height = ChannelReader::host_height(ctx)?; + let latest_height = ChannelReader::host_height(ctx).map_err(PacketError::Channel)?; if packet.timeout_height.has_expired(latest_height) { - return Err(Error::LowPacketHeight { + return Err(PacketError::LowPacketHeight { chain_height: latest_height, timeout_height: packet.timeout_height, }); } - let latest_timestamp = ChannelReader::host_timestamp(ctx)?; + let latest_timestamp = ChannelReader::host_timestamp(ctx).map_err(PacketError::Channel)?; if let Expiry::Expired = latest_timestamp.check_expiry(&packet.timeout_timestamp) { - return Err(Error::LowPacketTimestamp); + return Err(PacketError::LowPacketTimestamp); } verify_packet_recv_proofs( @@ -86,7 +89,8 @@ pub fn process( packet, &connection_end, &msg.proofs, - )?; + ) + .map_err(PacketError::Channel)?; let result = if dest_channel_end.order_matches(&Order::Ordered) { let next_seq_recv = @@ -101,7 +105,7 @@ pub fn process( return Ok(output.with_result(PacketResult::Recv(RecvPacketResult::NoOp))); } else if packet.sequence != next_seq_recv { - return Err(Error::InvalidPacketSequence { + return Err(PacketError::InvalidPacketSequence { given_sequence: packet.sequence, next_sequence: next_seq_recv, }); @@ -131,7 +135,7 @@ pub fn process( } Err(e) if e.to_string() - == Error::PacketReceiptNotFound { + == PacketError::PacketReceiptNotFound { sequence: packet.sequence, } .to_string() => @@ -144,7 +148,7 @@ pub fn process( receipt: Receipt::Ok, }) } - Err(_) => return Err(Error::ImplementationSpecific), + Err(_) => return Err(PacketError::ImplementationSpecific), } }; diff --git a/crates/ibc/src/core/ics04_channel/handler/send_packet.rs b/crates/ibc/src/core/ics04_channel/handler/send_packet.rs index cf144caaa..81cae8f80 100644 --- a/crates/ibc/src/core/ics04_channel/handler/send_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/send_packet.rs @@ -3,7 +3,7 @@ use crate::core::ics04_channel::channel::State; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics04_channel::events::SendPacket; use crate::core::ics04_channel::packet::Sequence; -use crate::core::ics04_channel::{context::SendPacketReader, error::Error, packet::Packet}; +use crate::core::ics04_channel::{context::SendPacketReader, error::PacketError, packet::Packet}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; @@ -22,13 +22,13 @@ pub struct SendPacketResult { pub fn send_packet( ctx: &impl SendPacketReader, packet: Packet, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; if source_channel_end.state_matches(&State::Closed) { - return Err(Error::ChannelClosed { + return Err(PacketError::ChannelClosed { channel_id: packet.source_channel, }); } @@ -39,7 +39,7 @@ pub fn send_packet( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::InvalidPacketCounterparty { + return Err(PacketError::InvalidPacketCounterparty { port_id: packet.destination_port.clone(), channel_id: packet.destination_channel, }); @@ -53,7 +53,7 @@ pub fn send_packet( // prevent accidental sends with clients that cannot be updated if client_state.is_frozen() { - return Err(Error::FrozenClient { + return Err(PacketError::FrozenClient { client_id: connection_end.client_id().clone(), }); } @@ -61,7 +61,7 @@ pub fn send_packet( let latest_height = client_state.latest_height(); if packet.timeout_height.has_expired(latest_height) { - return Err(Error::LowPacketHeight { + return Err(PacketError::LowPacketHeight { chain_height: latest_height, timeout_height: packet.timeout_height, }); @@ -71,13 +71,13 @@ pub fn send_packet( let latest_timestamp = consensus_state.timestamp(); let packet_timestamp = packet.timeout_timestamp; if let Expiry::Expired = latest_timestamp.check_expiry(&packet_timestamp) { - return Err(Error::LowPacketTimestamp); + return Err(PacketError::LowPacketTimestamp); } let next_seq_send = ctx.get_next_sequence_send(&packet.source_port, &packet.source_channel)?; if packet.sequence != next_seq_send { - return Err(Error::InvalidPacketSequence { + return Err(PacketError::InvalidPacketSequence { given_sequence: packet.sequence, next_sequence: next_seq_send, }); diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout.rs b/crates/ibc/src/core/ics04_channel/handler/timeout.rs index 59788243d..b040dad31 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout.rs @@ -6,7 +6,7 @@ use crate::core::ics04_channel::handler::verify::{ }; use crate::core::ics04_channel::msgs::timeout::MsgTimeout; use crate::core::ics04_channel::packet::{PacketResult, Sequence}; -use crate::core::ics04_channel::{context::ChannelReader, error::Error}; +use crate::core::ics04_channel::{context::ChannelReader, error::PacketError}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; @@ -29,15 +29,17 @@ pub struct TimeoutPacketResult { pub fn process( ctx: &Ctx, msg: &MsgTimeout, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let packet = &msg.packet; - let mut source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; + let mut source_channel_end = ctx + .channel_end(&packet.source_port, &packet.source_channel) + .map_err(PacketError::Channel)?; if !source_channel_end.state_matches(&State::Open) { - return Err(Error::ChannelClosed { + return Err(PacketError::ChannelClosed { channel_id: packet.source_channel.clone(), }); } @@ -48,14 +50,16 @@ pub fn process( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::InvalidPacketCounterparty { + return Err(PacketError::InvalidPacketCounterparty { port_id: packet.destination_port.clone(), channel_id: packet.destination_channel.clone(), }); } let source_connection_id = source_channel_end.connection_hops()[0].clone(); - let connection_end = ctx.connection_end(&source_connection_id)?; + let connection_end = ctx + .connection_end(&source_connection_id) + .map_err(PacketError::Channel)?; let client_id = connection_end.client_id().clone(); @@ -63,19 +67,21 @@ pub fn process( let proof_height = msg.proofs.height(); if packet.timeout_height.has_expired(proof_height) { - return Err(Error::PacketTimeoutHeightNotReached { + return Err(PacketError::PacketTimeoutHeightNotReached { timeout_height: packet.timeout_height, chain_height: proof_height, }); } - let consensus_state = ctx.client_consensus_state(&client_id, proof_height)?; + let consensus_state = ctx + .client_consensus_state(&client_id, proof_height) + .map_err(PacketError::Channel)?; let proof_timestamp = consensus_state.timestamp(); let packet_timestamp = packet.timeout_timestamp; if let Expiry::Expired = packet_timestamp.check_expiry(&proof_timestamp) { - return Err(Error::PacketTimeoutTimestampNotReached { + return Err(PacketError::PacketTimeoutTimestampNotReached { timeout_timestamp: packet_timestamp, chain_timestamp: proof_timestamp, }); @@ -91,14 +97,14 @@ pub fn process( packet.timeout_timestamp, ); if packet_commitment != expected_commitment { - return Err(Error::IncorrectPacketCommitment { + return Err(PacketError::IncorrectPacketCommitment { sequence: packet.sequence, }); } let result = if source_channel_end.order_matches(&Order::Ordered) { if packet.sequence < msg.next_sequence_recv { - return Err(Error::InvalidPacketSequence { + return Err(PacketError::InvalidPacketSequence { given_sequence: packet.sequence, next_sequence: msg.next_sequence_recv, }); @@ -110,7 +116,8 @@ pub fn process( packet.clone(), msg.next_sequence_recv, &msg.proofs, - )?; + ) + .map_err(PacketError::Channel)?; source_channel_end.state = State::Closed; PacketResult::Timeout(TimeoutPacketResult { @@ -126,7 +133,8 @@ pub fn process( &connection_end, packet.clone(), &msg.proofs, - )?; + ) + .map_err(PacketError::Channel)?; PacketResult::Timeout(TimeoutPacketResult { port_id: packet.source_port.clone(), diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs b/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs index e09e8bf15..9b3036230 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout_on_close.rs @@ -8,7 +8,7 @@ use crate::core::ics04_channel::handler::verify::{ use crate::core::ics04_channel::msgs::timeout_on_close::MsgTimeoutOnClose; use crate::core::ics04_channel::packet::PacketResult; use crate::core::ics04_channel::{ - context::ChannelReader, error::Error, handler::timeout::TimeoutPacketResult, + context::ChannelReader, error::PacketError, handler::timeout::TimeoutPacketResult, }; use crate::events::IbcEvent; use crate::handler::{HandlerOutput, HandlerResult}; @@ -18,12 +18,14 @@ use crate::proofs::{ProofError, Proofs}; pub fn process( ctx: &Ctx, msg: &MsgTimeoutOnClose, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let packet = &msg.packet; - let source_channel_end = ctx.channel_end(&packet.source_port, &packet.source_channel)?; + let source_channel_end = ctx + .channel_end(&packet.source_port, &packet.source_channel) + .map_err(PacketError::Channel)?; let counterparty = Counterparty::new( packet.destination_port.clone(), @@ -31,14 +33,16 @@ pub fn process( ); if !source_channel_end.counterparty_matches(&counterparty) { - return Err(Error::InvalidPacketCounterparty { + return Err(PacketError::InvalidPacketCounterparty { port_id: packet.destination_port.clone(), channel_id: packet.destination_channel.clone(), }); } let source_connection_id = source_channel_end.connection_hops()[0].clone(); - let connection_end = ctx.connection_end(&source_connection_id)?; + let connection_end = ctx + .connection_end(&source_connection_id) + .map_err(PacketError::Channel)?; //verify the packet was sent, check the store let packet_commitment = @@ -50,7 +54,7 @@ pub fn process( packet.timeout_timestamp, ); if packet_commitment != expected_commitment { - return Err(Error::IncorrectPacketCommitment { + return Err(PacketError::IncorrectPacketCommitment { sequence: packet.sequence, }); } @@ -61,11 +65,12 @@ pub fn process( ); let counterparty = connection_end.counterparty(); - let ccid = counterparty - .connection_id() - .ok_or(Error::UndefinedConnectionCounterparty { - connection_id: source_channel_end.connection_hops()[0].clone(), - })?; + let ccid = + counterparty + .connection_id() + .ok_or(PacketError::UndefinedConnectionCounterparty { + connection_id: source_channel_end.connection_hops()[0].clone(), + })?; let expected_connection_hops = vec![ccid.clone()]; @@ -80,10 +85,10 @@ pub fn process( // The message's proofs have the channel proof as `other_proof` let proof_close = match msg.proofs.other_proof() { Some(p) => p.clone(), - None => return Err(Error::InvalidProof(ProofError::EmptyProof)), + None => return Err(PacketError::InvalidProof(ProofError::EmptyProof)), }; let proofs = Proofs::new(proof_close, None, None, None, msg.proofs.height()) - .map_err(Error::InvalidProof)?; + .map_err(PacketError::InvalidProof)?; verify_channel_proofs( ctx, msg.proofs.height(), @@ -91,11 +96,12 @@ pub fn process( &connection_end, &expected_channel_end, &proofs, - )?; + ) + .map_err(PacketError::Channel)?; let result = if source_channel_end.order_matches(&Order::Ordered) { if packet.sequence < msg.next_sequence_recv { - return Err(Error::InvalidPacketSequence { + return Err(PacketError::InvalidPacketSequence { given_sequence: packet.sequence, next_sequence: msg.next_sequence_recv, }); @@ -107,7 +113,8 @@ pub fn process( packet.clone(), msg.next_sequence_recv, &msg.proofs, - )?; + ) + .map_err(PacketError::Channel)?; PacketResult::Timeout(TimeoutPacketResult { port_id: packet.source_port.clone(), @@ -122,7 +129,8 @@ pub fn process( &connection_end, packet.clone(), &msg.proofs, - )?; + ) + .map_err(PacketError::Channel)?; PacketResult::Timeout(TimeoutPacketResult { port_id: packet.source_port.clone(), diff --git a/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs index bd6b77d92..21b87e6db 100644 --- a/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/write_acknowledgement.rs @@ -3,7 +3,7 @@ use crate::core::ics04_channel::commitment::AcknowledgementCommitment; use crate::core::ics04_channel::events::WriteAcknowledgement; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement; use crate::core::ics04_channel::packet::{Packet, PacketResult, Sequence}; -use crate::core::ics04_channel::{context::ChannelReader, error::Error}; +use crate::core::ics04_channel::{context::ChannelReader, error::PacketError}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::prelude::*; use crate::{ @@ -23,14 +23,15 @@ pub fn process( ctx: &Ctx, packet: Packet, ack: Acknowledgement, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); - let dest_channel_end = - ctx.channel_end(&packet.destination_port, &packet.destination_channel)?; + let dest_channel_end = ctx + .channel_end(&packet.destination_port, &packet.destination_channel) + .map_err(PacketError::Channel)?; if !dest_channel_end.state_matches(&State::Open) { - return Err(Error::InvalidChannelState { + return Err(PacketError::InvalidChannelState { channel_id: packet.source_channel, state: dest_channel_end.state, }); @@ -45,13 +46,13 @@ pub fn process( packet.sequence, ) { Ok(_) => { - return Err(Error::AcknowledgementExists { + return Err(PacketError::AcknowledgementExists { sequence: packet.sequence, }) } Err(e) if e.to_string() - == Error::PacketAcknowledgementNotFound { + == PacketError::PacketAcknowledgementNotFound { sequence: packet.sequence, } .to_string() => {} @@ -59,7 +60,7 @@ pub fn process( } if ack.is_empty() { - return Err(Error::InvalidAcknowledgement); + return Err(PacketError::InvalidAcknowledgement); } let result = PacketResult::WriteAck(WriteAckPacketResult { diff --git a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs index f78965cd4..a903a29e9 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs @@ -4,7 +4,7 @@ use derive_more::{From, Into}; use ibc_proto::ibc::core::channel::v1::MsgAcknowledgement as RawMsgAcknowledgement; use ibc_proto::protobuf::Protobuf; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::Packet; use crate::proofs::Proofs; use crate::signer::Signer; @@ -69,7 +69,7 @@ impl MsgAcknowledgement { } impl Msg for MsgAcknowledgement { - type ValidationError = Error; + type ValidationError = PacketError; type Raw = RawMsgAcknowledgement; fn route(&self) -> String { @@ -84,28 +84,31 @@ impl Msg for MsgAcknowledgement { impl Protobuf for MsgAcknowledgement {} impl TryFrom for MsgAcknowledgement { - type Error = Error; + type Error = PacketError; fn try_from(raw_msg: RawMsgAcknowledgement) -> Result { let proofs = Proofs::new( raw_msg .proof_acked .try_into() - .map_err(Error::InvalidProof)?, + .map_err(PacketError::InvalidProof)?, None, None, None, raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, + .ok_or(PacketError::MissingHeight)?, ) - .map_err(Error::InvalidProof)?; + .map_err(PacketError::InvalidProof)?; Ok(MsgAcknowledgement { - packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, + packet: raw_msg + .packet + .ok_or(PacketError::MissingPacket)? + .try_into()?, acknowledgement: raw_msg.acknowledgement.into(), - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + signer: raw_msg.signer.parse().map_err(PacketError::Signer)?, proofs, }) } @@ -163,7 +166,7 @@ mod test { use ibc_proto::ibc::core::channel::v1::MsgAcknowledgement as RawMsgAcknowledgement; - use crate::core::ics04_channel::error::Error; + use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::msgs::acknowledgement::test_util::get_dummy_raw_msg_acknowledgement; use crate::core::ics04_channel::msgs::acknowledgement::MsgAcknowledgement; use crate::test_utils::get_dummy_bech32_account; @@ -220,7 +223,7 @@ mod test { ]; for test in tests { - let res_msg: Result = test.raw.clone().try_into(); + let res_msg: Result = test.raw.clone().try_into(); assert_eq!( res_msg.is_ok(), diff --git a/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs b/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs index 1e79b4834..3bd655622 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs @@ -4,7 +4,7 @@ use ibc_proto::protobuf::Protobuf; use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::Packet; use crate::proofs::Proofs; use crate::signer::Signer; @@ -33,7 +33,7 @@ impl MsgRecvPacket { } impl Msg for MsgRecvPacket { - type ValidationError = Error; + type ValidationError = PacketError; type Raw = RawMsgRecvPacket; fn route(&self) -> String { @@ -48,28 +48,31 @@ impl Msg for MsgRecvPacket { impl Protobuf for MsgRecvPacket {} impl TryFrom for MsgRecvPacket { - type Error = Error; + type Error = PacketError; fn try_from(raw_msg: RawMsgRecvPacket) -> Result { let proofs = Proofs::new( raw_msg .proof_commitment .try_into() - .map_err(Error::InvalidProof)?, + .map_err(PacketError::InvalidProof)?, None, None, None, raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, + .ok_or(PacketError::MissingHeight)?, ) - .map_err(Error::InvalidProof)?; + .map_err(PacketError::InvalidProof)?; Ok(MsgRecvPacket { - packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, + packet: raw_msg + .packet + .ok_or(PacketError::MissingPacket)? + .try_into()?, proofs, - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + signer: raw_msg.signer.parse().map_err(PacketError::Signer)?, }) } } @@ -123,7 +126,7 @@ mod test { use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; - use crate::core::ics04_channel::error::Error; + use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::msgs::recv_packet::test_util::get_dummy_raw_msg_recv_packet; use crate::core::ics04_channel::msgs::recv_packet::MsgRecvPacket; use crate::test_utils::get_dummy_bech32_account; @@ -171,7 +174,7 @@ mod test { ]; for test in tests { - let res_msg: Result = test.raw.clone().try_into(); + let res_msg: Result = test.raw.clone().try_into(); assert_eq!( res_msg.is_ok(), diff --git a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs index 099a2aac6..5bc97ce2e 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs @@ -4,7 +4,7 @@ use ibc_proto::protobuf::Protobuf; use ibc_proto::ibc::core::channel::v1::MsgTimeout as RawMsgTimeout; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::proofs::Proofs; use crate::signer::Signer; @@ -40,7 +40,7 @@ impl MsgTimeout { } impl Msg for MsgTimeout { - type ValidationError = Error; + type ValidationError = PacketError; type Raw = RawMsgTimeout; fn route(&self) -> String { @@ -55,30 +55,33 @@ impl Msg for MsgTimeout { impl Protobuf for MsgTimeout {} impl TryFrom for MsgTimeout { - type Error = Error; + type Error = PacketError; fn try_from(raw_msg: RawMsgTimeout) -> Result { let proofs = Proofs::new( raw_msg .proof_unreceived .try_into() - .map_err(Error::InvalidProof)?, + .map_err(PacketError::InvalidProof)?, None, None, None, raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, + .ok_or(PacketError::MissingHeight)?, ) - .map_err(Error::InvalidProof)?; + .map_err(PacketError::InvalidProof)?; // TODO: Domain type verification for the next sequence: this should probably be > 0. Ok(MsgTimeout { - packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, + packet: raw_msg + .packet + .ok_or(PacketError::MissingPacket)? + .try_into()?, next_sequence_recv: Sequence::from(raw_msg.next_sequence_recv), - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + signer: raw_msg.signer.parse().map_err(PacketError::Signer)?, proofs, }) } @@ -132,7 +135,7 @@ mod test { use ibc_proto::ibc::core::channel::v1::MsgTimeout as RawMsgTimeout; - use crate::core::ics04_channel::error::Error; + use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::msgs::timeout::test_util::get_dummy_raw_msg_timeout; use crate::core::ics04_channel::msgs::timeout::MsgTimeout; use crate::test_utils::get_dummy_bech32_account; @@ -192,7 +195,7 @@ mod test { ]; for test in tests { - let res_msg: Result = test.raw.clone().try_into(); + let res_msg: Result = test.raw.clone().try_into(); assert_eq!( res_msg.is_ok(), diff --git a/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs b/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs index fe0335345..e0eda5006 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/timeout_on_close.rs @@ -3,7 +3,7 @@ use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgTimeoutOnClose as RawMsgTimeoutOnClose; use ibc_proto::protobuf::Protobuf; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::proofs::Proofs; use crate::signer::Signer; @@ -39,7 +39,7 @@ impl MsgTimeoutOnClose { } impl Msg for MsgTimeoutOnClose { - type ValidationError = Error; + type ValidationError = PacketError; type Raw = RawMsgTimeoutOnClose; fn route(&self) -> String { @@ -54,35 +54,38 @@ impl Msg for MsgTimeoutOnClose { impl Protobuf for MsgTimeoutOnClose {} impl TryFrom for MsgTimeoutOnClose { - type Error = Error; + type Error = PacketError; fn try_from(raw_msg: RawMsgTimeoutOnClose) -> Result { let proofs = Proofs::new( raw_msg .proof_unreceived .try_into() - .map_err(Error::InvalidProof)?, + .map_err(PacketError::InvalidProof)?, None, None, Some( raw_msg .proof_close .try_into() - .map_err(Error::InvalidProof)?, + .map_err(PacketError::InvalidProof)?, ), raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, + .ok_or(PacketError::MissingHeight)?, ) - .map_err(Error::InvalidProof)?; + .map_err(PacketError::InvalidProof)?; // TODO: Domain type verification for the next sequence: this should probably be > 0. Ok(MsgTimeoutOnClose { - packet: raw_msg.packet.ok_or(Error::MissingPacket)?.try_into()?, + packet: raw_msg + .packet + .ok_or(PacketError::MissingPacket)? + .try_into()?, next_sequence_recv: Sequence::from(raw_msg.next_sequence_recv), - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + signer: raw_msg.signer.parse().map_err(PacketError::Signer)?, proofs, }) } diff --git a/crates/ibc/src/core/ics04_channel/packet.rs b/crates/ibc/src/core/ics04_channel/packet.rs index 25b68443a..729ee7830 100644 --- a/crates/ibc/src/core/ics04_channel/packet.rs +++ b/crates/ibc/src/core/ics04_channel/packet.rs @@ -11,7 +11,7 @@ use super::handler::{ timeout::TimeoutPacketResult, write_acknowledgement::WriteAckPacketResult, }; use super::timeout::TimeoutHeight; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::{Error, PacketError}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::timestamp::{Expiry::Expired, Timestamp}; use crate::Height; @@ -194,11 +194,11 @@ impl core::fmt::Display for Packet { } impl TryFrom for Packet { - type Error = Error; + type Error = PacketError; fn try_from(raw_pkt: RawPacket) -> Result { if Sequence::from(raw_pkt.sequence).is_zero() { - return Err(Error::ZeroPacketSequence); + return Err(PacketError::ZeroPacketSequence); } // Note: ibc-go currently (July 2022) incorrectly treats the timeout @@ -212,27 +212,33 @@ impl TryFrom for Packet { let packet_timeout_height: TimeoutHeight = raw_pkt .timeout_height .try_into() - .map_err(|_| Error::InvalidTimeoutHeight)?; + .map_err(|_| PacketError::InvalidTimeoutHeight)?; if raw_pkt.data.is_empty() { - return Err(Error::ZeroPacketData); + return Err(PacketError::ZeroPacketData); } let timeout_timestamp = Timestamp::from_nanoseconds(raw_pkt.timeout_timestamp) - .map_err(Error::InvalidPacketTimestamp)?; + .map_err(PacketError::InvalidPacketTimestamp)?; Ok(Packet { sequence: Sequence::from(raw_pkt.sequence), - source_port: raw_pkt.source_port.parse().map_err(Error::Identifier)?, - source_channel: raw_pkt.source_channel.parse().map_err(Error::Identifier)?, + source_port: raw_pkt + .source_port + .parse() + .map_err(PacketError::Identifier)?, + source_channel: raw_pkt + .source_channel + .parse() + .map_err(PacketError::Identifier)?, destination_port: raw_pkt .destination_port .parse() - .map_err(Error::Identifier)?, + .map_err(PacketError::Identifier)?, destination_channel: raw_pkt .destination_channel .parse() - .map_err(Error::Identifier)?, + .map_err(PacketError::Identifier)?, data: raw_pkt.data, timeout_height: packet_timeout_height, timeout_timestamp, diff --git a/crates/ibc/src/core/ics26_routing/context.rs b/crates/ibc/src/core/ics26_routing/context.rs index 60f72d227..10cf3c61a 100644 --- a/crates/ibc/src/core/ics26_routing/context.rs +++ b/crates/ibc/src/core/ics26_routing/context.rs @@ -14,7 +14,7 @@ use crate::core::ics02_client::context::{ClientKeeper, ClientReader}; use crate::core::ics03_connection::context::{ConnectionKeeper, ConnectionReader}; use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::context::{ChannelKeeper, ChannelReader}; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::{Error, PacketError}; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement as GenericAcknowledgement; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; @@ -169,7 +169,7 @@ pub trait Module: Send + Sync + AsAnyMut { _packet: &Packet, _acknowledgement: &GenericAcknowledgement, _relayer: &Signer, - ) -> Result<(), Error> { + ) -> Result<(), PacketError> { Ok(()) } @@ -178,7 +178,7 @@ pub trait Module: Send + Sync + AsAnyMut { _output: &mut ModuleOutputBuilder, _packet: &Packet, _relayer: &Signer, - ) -> Result<(), Error> { + ) -> Result<(), PacketError> { Ok(()) } } diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index b31004850..fcb513022 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -13,6 +13,8 @@ pub enum Error { Connection(ics03_connection::error::ConnectionError), /// ICS04 channel error Channel(ics04_channel::error::Error), + /// ICS04 Packet error + Packet(ics04_channel::error::PacketError), /// unknown type URL `{url}` UnknownMessageTypeUrl { url: String }, /// the message is malformed and cannot be decoded @@ -28,6 +30,7 @@ impl std::error::Error for Error { Error::Channel(e) => Some(e), Error::UnknownMessageTypeUrl { .. } => None, Error::MalformedMessageBytes(e) => Some(e), + Error::Packet(e) => Some(e), } } } diff --git a/crates/ibc/src/core/ics26_routing/handler.rs b/crates/ibc/src/core/ics26_routing/handler.rs index 17cefeea6..f6784f8b0 100644 --- a/crates/ibc/src/core/ics26_routing/handler.rs +++ b/crates/ibc/src/core/ics26_routing/handler.rs @@ -111,7 +111,7 @@ where // Apply any results to the host chain store. ctx.store_channel_result(channel_result) - .map_err(Error::Channel)?; + .map_err(Error::Packet)?; dispatch_output .with_events(dispatch_events) @@ -130,18 +130,18 @@ where PacketMsg(msg) => { let module_id = get_module_for_packet_msg(ctx, &msg).map_err(Error::Channel)?; let (mut handler_builder, packet_result) = - ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::Channel)?; + ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::Packet)?; if matches!(packet_result, PacketResult::Recv(RecvPacketResult::NoOp)) { return Ok(handler_builder.with_result(())); } let cb_result = ics4_packet_callback(ctx, &module_id, &msg, &mut handler_builder); - cb_result.map_err(Error::Channel)?; + cb_result.map_err(Error::Packet)?; // Apply any results to the host chain store. ctx.store_packet_result(packet_result) - .map_err(Error::Channel)?; + .map_err(Error::Packet)?; handler_builder.with_result(()) } diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index d2746854d..54e9ba171 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -30,7 +30,7 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment}; use crate::core::ics04_channel::context::{ChannelKeeper, ChannelReader}; -use crate::core::ics04_channel::error::Error as Ics04Error; +use crate::core::ics04_channel::error::{Error as Ics04Error, PacketError}; use crate::core::ics04_channel::packet::{Receipt, Sequence}; use crate::core::ics05_port::context::PortReader; use crate::core::ics05_port::error::Error as Ics05Error; @@ -724,7 +724,7 @@ impl ChannelReader for MockContext { &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -734,7 +734,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Ics04Error::MissingNextSendSeq { + None => Err(PacketError::MissingNextSendSeq { port_id: port_id.clone(), channel_id: channel_id.clone(), }), @@ -745,7 +745,7 @@ impl ChannelReader for MockContext { &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -755,7 +755,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Ics04Error::MissingNextRecvSeq { + None => Err(PacketError::MissingNextRecvSeq { port_id: port_id.clone(), channel_id: channel_id.clone(), }), @@ -766,7 +766,7 @@ impl ChannelReader for MockContext { &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -776,7 +776,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Ics04Error::MissingNextAckSeq { + None => Err(PacketError::MissingNextAckSeq { port_id: port_id.clone(), channel_id: channel_id.clone(), }), @@ -788,7 +788,7 @@ impl ChannelReader for MockContext { port_id: &PortId, channel_id: &ChannelId, seq: Sequence, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -799,7 +799,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(&seq)) { Some(commitment) => Ok(commitment.clone()), - None => Err(Ics04Error::PacketCommitmentNotFound { sequence: seq }), + None => Err(PacketError::PacketCommitmentNotFound { sequence: seq }), } } @@ -808,7 +808,7 @@ impl ChannelReader for MockContext { port_id: &PortId, channel_id: &ChannelId, seq: Sequence, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -819,7 +819,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(&seq)) { Some(receipt) => Ok(receipt.clone()), - None => Err(Ics04Error::PacketReceiptNotFound { sequence: seq }), + None => Err(PacketError::PacketReceiptNotFound { sequence: seq }), } } @@ -828,7 +828,7 @@ impl ChannelReader for MockContext { port_id: &PortId, channel_id: &ChannelId, seq: Sequence, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -839,7 +839,7 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(&seq)) { Some(ack) => Ok(ack.clone()), - None => Err(Ics04Error::PacketAcknowledgementNotFound { sequence: seq }), + None => Err(PacketError::PacketAcknowledgementNotFound { sequence: seq }), } } @@ -922,7 +922,7 @@ impl ChannelKeeper for MockContext { channel_id: ChannelId, seq: Sequence, commitment: PacketCommitment, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -941,7 +941,7 @@ impl ChannelKeeper for MockContext { channel_id: ChannelId, seq: Sequence, ack_commitment: AcknowledgementCommitment, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -959,7 +959,7 @@ impl ChannelKeeper for MockContext { port_id: &PortId, channel_id: &ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -1007,7 +1007,7 @@ impl ChannelKeeper for MockContext { port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -1023,7 +1023,7 @@ impl ChannelKeeper for MockContext { port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -1039,7 +1039,7 @@ impl ChannelKeeper for MockContext { port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -1059,7 +1059,7 @@ impl ChannelKeeper for MockContext { port_id: &PortId, channel_id: &ChannelId, seq: Sequence, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -1076,7 +1076,7 @@ impl ChannelKeeper for MockContext { channel_id: ChannelId, seq: Sequence, receipt: Receipt, - ) -> Result<(), Ics04Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index de40b754c..25f728c34 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -16,7 +16,7 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics04_channel::context::SendPacketReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::{Error, PacketError}; use crate::core::ics04_channel::handler::ModuleExtras; use crate::core::ics04_channel::packet::Sequence; use crate::core::ics04_channel::Version; @@ -123,7 +123,7 @@ impl TokenTransferKeeper for DummyTransferModule { channel_id: ChannelId, seq: Sequence, commitment: PacketCommitment, - ) -> Result<(), Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -141,7 +141,7 @@ impl TokenTransferKeeper for DummyTransferModule { port_id: PortId, channel_id: ChannelId, seq: Sequence, - ) -> Result<(), Error> { + ) -> Result<(), PacketError> { self.ibc_store .lock() .unwrap() @@ -214,7 +214,11 @@ impl TokenTransferReader for DummyTransferModule { } impl SendPacketReader for DummyTransferModule { - fn channel_end(&self, port_id: &PortId, channel_id: &ChannelId) -> Result { + fn channel_end( + &self, + port_id: &PortId, + channel_id: &ChannelId, + ) -> Result { match self .ibc_store .lock() @@ -224,24 +228,24 @@ impl SendPacketReader for DummyTransferModule { .and_then(|map| map.get(channel_id)) { Some(channel_end) => Ok(channel_end.clone()), - None => Err(Error::ChannelNotFound { + None => Err(PacketError::ChannelNotFound { port_id: port_id.clone(), channel_id: channel_id.clone(), }), } } - fn connection_end(&self, cid: &ConnectionId) -> Result { + fn connection_end(&self, cid: &ConnectionId) -> Result { match self.ibc_store.lock().unwrap().connections.get(cid) { Some(connection_end) => Ok(connection_end.clone()), None => Err(ConnectionError::ConnectionNotFound { connection_id: cid.clone(), }), } - .map_err(Error::Connection) + .map_err(PacketError::Connection) } - fn client_state(&self, client_id: &ClientId) -> Result, Error> { + fn client_state(&self, client_id: &ClientId) -> Result, PacketError> { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => { client_record @@ -255,14 +259,14 @@ impl SendPacketReader for DummyTransferModule { client_id: client_id.clone(), }), } - .map_err(|e| Error::Connection(ConnectionError::Client(e))) + .map_err(|e| PacketError::Connection(ConnectionError::Client(e))) } fn client_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result, Error> { + ) -> Result, PacketError> { match self.ibc_store.lock().unwrap().clients.get(client_id) { Some(client_record) => match client_record.consensus_states.get(&height) { Some(consensus_state) => Ok(consensus_state.clone()), @@ -276,14 +280,14 @@ impl SendPacketReader for DummyTransferModule { height, }), } - .map_err(|e| Error::Connection(ConnectionError::Client(e))) + .map_err(|e| PacketError::Connection(ConnectionError::Client(e))) } fn get_next_sequence_send( &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -293,7 +297,7 @@ impl SendPacketReader for DummyTransferModule { .and_then(|map| map.get(channel_id)) { Some(sequence) => Ok(*sequence), - None => Err(Error::MissingNextSendSeq { + None => Err(PacketError::MissingNextSendSeq { port_id: port_id.clone(), channel_id: channel_id.clone(), }), From d3857986519587c85450b4be9df49fb355ccc0a1 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 03:41:55 +0800 Subject: [PATCH 29/43] Rename Ics04Error to ChannelError --- .../ibc/src/applications/transfer/context.rs | 6 +- crates/ibc/src/core/context.rs | 2 +- crates/ibc/src/core/ics04_channel/channel.rs | 38 +++++------ crates/ibc/src/core/ics04_channel/context.rs | 46 +++++++++----- crates/ibc/src/core/ics04_channel/error.rs | 33 +++++----- crates/ibc/src/core/ics04_channel/events.rs | 12 ++-- .../ics04_channel/events/packet_attributes.rs | 12 ++-- crates/ibc/src/core/ics04_channel/handler.rs | 24 +++---- .../handler/chan_close_confirm.rs | 18 +++--- .../ics04_channel/handler/chan_close_init.rs | 10 +-- .../ics04_channel/handler/chan_open_ack.rs | 16 ++--- .../handler/chan_open_confirm.rs | 18 +++--- .../ics04_channel/handler/chan_open_init.rs | 10 +-- .../ics04_channel/handler/chan_open_try.rs | 26 ++++---- .../src/core/ics04_channel/handler/verify.rs | 34 +++++----- crates/ibc/src/core/ics04_channel/msgs.rs | 16 ++--- .../ics04_channel/msgs/chan_close_confirm.rs | 22 ++++--- .../ics04_channel/msgs/chan_close_init.rs | 15 +++-- .../core/ics04_channel/msgs/chan_open_ack.rs | 24 ++++--- .../ics04_channel/msgs/chan_open_confirm.rs | 22 ++++--- .../core/ics04_channel/msgs/chan_open_init.rs | 15 +++-- .../core/ics04_channel/msgs/chan_open_try.rs | 2 +- crates/ibc/src/core/ics04_channel/packet.rs | 6 +- crates/ibc/src/core/ics26_routing/context.rs | 14 ++--- crates/ibc/src/core/ics26_routing/error.rs | 2 +- crates/ibc/src/events.rs | 16 ++--- crates/ibc/src/mock/context.rs | 63 ++++++++++--------- crates/ibc/src/test_utils.rs | 6 +- 28 files changed, 285 insertions(+), 243 deletions(-) diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index 26edb0821..b71d2aafa 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -343,7 +343,7 @@ pub(crate) mod test { use crate::applications::transfer::relay::send_transfer::send_transfer; use crate::applications::transfer::PrefixedCoin; use crate::core::ics04_channel::channel::{Counterparty, Order}; - use crate::core::ics04_channel::error::Error; + use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; use crate::handler::HandlerOutputBuilder; @@ -356,8 +356,8 @@ pub(crate) mod test { ctx: &mut DummyTransferModule, output: &mut HandlerOutputBuilder<()>, msg: MsgTransfer, - ) -> Result<(), Error> { - send_transfer(ctx, output, msg).map_err(|e: Ics20Error| Error::AppModule { + ) -> Result<(), ChannelError> { + send_transfer(ctx, output, msg).map_err(|e: Ics20Error| ChannelError::AppModule { description: e.to_string(), }) } diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 980f8ba33..41ccfc867 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -28,7 +28,7 @@ use super::{ channel::ChannelEnd, commitment::{AcknowledgementCommitment, PacketCommitment}, context::calculate_block_delay, - error::Error as ChannelError, + error::ChannelError, msgs::acknowledgement::Acknowledgement, packet::{Receipt, Sequence}, timeout::TimeoutHeight, diff --git a/crates/ibc/src/core/ics04_channel/channel.rs b/crates/ibc/src/core/ics04_channel/channel.rs index 8d6f730c7..2ddf222af 100644 --- a/crates/ibc/src/core/ics04_channel/channel.rs +++ b/crates/ibc/src/core/ics04_channel/channel.rs @@ -12,7 +12,7 @@ use ibc_proto::ibc::core::channel::v1::{ IdentifiedChannel as RawIdentifiedChannel, }; -use crate::core::ics04_channel::{error::Error, Version}; +use crate::core::ics04_channel::{error::ChannelError, Version}; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -35,7 +35,7 @@ impl IdentifiedChannelEnd { impl Protobuf for IdentifiedChannelEnd {} impl TryFrom for IdentifiedChannelEnd { - type Error = Error; + type Error = ChannelError; fn try_from(value: RawIdentifiedChannel) -> Result { let raw_channel_end = RawChannel { @@ -47,8 +47,8 @@ impl TryFrom for IdentifiedChannelEnd { }; Ok(IdentifiedChannelEnd { - port_id: value.port_id.parse().map_err(Error::Identifier)?, - channel_id: value.channel_id.parse().map_err(Error::Identifier)?, + port_id: value.port_id.parse().map_err(ChannelError::Identifier)?, + channel_id: value.channel_id.parse().map_err(ChannelError::Identifier)?, channel_end: raw_channel_end.try_into()?, }) } @@ -107,7 +107,7 @@ impl Default for ChannelEnd { impl Protobuf for ChannelEnd {} impl TryFrom for ChannelEnd { - type Error = Error; + type Error = ChannelError; fn try_from(value: RawChannel) -> Result { let chan_state: State = State::from_i32(value.state)?; @@ -121,7 +121,7 @@ impl TryFrom for ChannelEnd { // Assemble the 'remote' attribute of the Channel, which represents the Counterparty. let remote = value .counterparty - .ok_or(Error::MissingCounterparty)? + .ok_or(ChannelError::MissingCounterparty)? .try_into()?; // Parse each item in connection_hops into a ConnectionId. @@ -130,7 +130,7 @@ impl TryFrom for ChannelEnd { .into_iter() .map(|conn_id| ConnectionId::from_str(conn_id.as_str())) .collect::, _>>() - .map_err(Error::Identifier)?; + .map_err(ChannelError::Identifier)?; let version = value.version.into(); @@ -216,9 +216,9 @@ impl ChannelEnd { &self.version } - pub fn validate_basic(&self) -> Result<(), Error> { + pub fn validate_basic(&self) -> Result<(), ChannelError> { if self.connection_hops.len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: self.connection_hops.len(), }); @@ -272,7 +272,7 @@ impl Counterparty { self.channel_id.as_ref() } - pub fn validate_basic(&self) -> Result<(), Error> { + pub fn validate_basic(&self) -> Result<(), ChannelError> { Ok(()) } } @@ -297,16 +297,16 @@ impl Display for Counterparty { impl Protobuf for Counterparty {} impl TryFrom for Counterparty { - type Error = Error; + type Error = ChannelError; fn try_from(value: RawCounterparty) -> Result { let channel_id = Some(value.channel_id) .filter(|x| !x.is_empty()) .map(|v| FromStr::from_str(v.as_str())) .transpose() - .map_err(Error::Identifier)?; + .map_err(ChannelError::Identifier)?; Ok(Counterparty::new( - value.port_id.parse().map_err(Error::Identifier)?, + value.port_id.parse().map_err(ChannelError::Identifier)?, channel_id, )) } @@ -354,12 +354,12 @@ impl Order { } // Parses the Order out from a i32. - pub fn from_i32(nr: i32) -> Result { + pub fn from_i32(nr: i32) -> Result { match nr { 0 => Ok(Self::None), 1 => Ok(Self::Unordered), 2 => Ok(Self::Ordered), - _ => Err(Error::UnknownOrderType { + _ => Err(ChannelError::UnknownOrderType { type_id: nr.to_string(), }), } @@ -367,14 +367,14 @@ impl Order { } impl FromStr for Order { - type Err = Error; + type Err = ChannelError; fn from_str(s: &str) -> Result { match s.to_lowercase().trim_start_matches("order_") { "uninitialized" => Ok(Self::None), "unordered" => Ok(Self::Unordered), "ordered" => Ok(Self::Ordered), - _ => Err(Error::UnknownOrderType { + _ => Err(ChannelError::UnknownOrderType { type_id: s.to_string(), }), } @@ -403,14 +403,14 @@ impl State { } // Parses the State out from a i32. - pub fn from_i32(s: i32) -> Result { + pub fn from_i32(s: i32) -> Result { match s { 0 => Ok(Self::Uninitialized), 1 => Ok(Self::Init), 2 => Ok(Self::TryOpen), 3 => Ok(Self::Open), 4 => Ok(Self::Closed), - _ => Err(Error::UnknownState { state: s }), + _ => Err(ChannelError::UnknownState { state: s }), } } diff --git a/crates/ibc/src/core/ics04_channel/context.rs b/crates/ibc/src/core/ics04_channel/context.rs index 1dfd960a2..908dfafa6 100644 --- a/crates/ibc/src/core/ics04_channel/context.rs +++ b/crates/ibc/src/core/ics04_channel/context.rs @@ -13,7 +13,7 @@ use crate::core::ics04_channel::handler::recv_packet::RecvPacketResult; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement; use crate::core::ics04_channel::{ - error::{Error, PacketError}, + error::{ChannelError, PacketError}, packet::Receipt, }; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; @@ -27,22 +27,29 @@ use super::timeout::TimeoutHeight; /// A context supplying all the necessary read-only dependencies for processing any `ChannelMsg`. pub trait ChannelReader { /// Returns the ChannelEnd for the given `port_id` and `chan_id`. - fn channel_end(&self, port_id: &PortId, channel_id: &ChannelId) -> Result; + fn channel_end( + &self, + port_id: &PortId, + channel_id: &ChannelId, + ) -> 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 connection_channels(&self, cid: &ConnectionId) -> Result, Error>; + fn connection_channels( + &self, + cid: &ConnectionId, + ) -> Result, ChannelError>; /// Returns the ClientState for the given identifier `client_id`. Necessary dependency towards /// proof verification. - fn client_state(&self, client_id: &ClientId) -> Result, Error>; + fn client_state(&self, client_id: &ClientId) -> Result, ChannelError>; fn client_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result, Error>; + ) -> Result, ChannelError>; fn get_next_sequence_send( &self, @@ -116,10 +123,10 @@ pub trait ChannelReader { fn hash(&self, value: Vec) -> Vec; /// 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 { let pending_consensus_state = self .pending_host_consensus_state() .expect("host must have pending consensus state"); @@ -127,21 +134,30 @@ pub trait ChannelReader { } /// Returns the `ConsensusState` of the host (local) chain at a specific height. - fn host_consensus_state(&self, height: Height) -> Result, Error>; + fn host_consensus_state(&self, height: Height) + -> Result, ChannelError>; /// Returns the pending `ConsensusState` of the host (local) chain. - fn pending_host_consensus_state(&self) -> Result, Error>; + fn pending_host_consensus_state(&self) -> Result, ChannelError>; /// Returns the time when the client state for the given [`ClientId`] was updated with a header for the given [`Height`] - fn client_update_time(&self, client_id: &ClientId, height: Height) -> Result; + fn client_update_time( + &self, + client_id: &ClientId, + height: Height, + ) -> Result; /// Returns the height when the client state for the given [`ClientId`] was updated with a header for the given [`Height`] - fn client_update_height(&self, client_id: &ClientId, height: Height) -> Result; + fn client_update_height( + &self, + client_id: &ClientId, + height: Height, + ) -> 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 /// `ChannelKeeper::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; @@ -383,7 +399,7 @@ pub trait ChannelKeeper { conn_id: ConnectionId, port_id: PortId, channel_id: ChannelId, - ) -> Result<(), Error>; + ) -> Result<(), ChannelError>; /// Stores the given channel_end at a path associated with the port_id and channel_id. fn store_channel( @@ -391,7 +407,7 @@ pub trait ChannelKeeper { port_id: PortId, channel_id: ChannelId, channel_end: ChannelEnd, - ) -> Result<(), Error>; + ) -> Result<(), ChannelError>; fn store_next_sequence_send( &mut self, diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 7ff0053b4..53465657c 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -16,7 +16,7 @@ use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintError; #[derive(Debug, Display)] -pub enum Error { +pub enum ChannelError { /// ICS03 connection error Connection(connection_error::ConnectionError), /// ICS05 port error @@ -125,7 +125,7 @@ pub enum PacketError { /// ICS03 connection error Connection(connection_error::ConnectionError), /// ICS04 channel error - Channel(Error), + Channel(ChannelError), /// Channel `{channel_id}` is Closed ChannelClosed { channel_id: ChannelId }, /// packet destination port `{port_id}` and channel `{channel_id}` doesn't match the counterparty's port/channel @@ -225,29 +225,28 @@ pub enum PacketError { impl std::error::Error for PacketError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - PacketError::Connection(e) => Some(e), - PacketError::Channel(e) => Some(e), - PacketError::InvalidProof(e) => Some(e), - PacketError::Signer(e) => Some(e), - PacketError::Identifier(e) => Some(e), + Self::Connection(e) => Some(e), + Self::Channel(e) => Some(e), + Self::InvalidProof(e) => Some(e), + Self::Signer(e) => Some(e), + Self::Identifier(e) => Some(e), _ => None, } } } #[cfg(feature = "std")] -impl std::error::Error for Error { +impl std::error::Error for ChannelError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::Connection(e) => Some(e), - Error::Port(e) => Some(e), - // Error::Identifier(e) => Some(e), - Error::InvalidVersion(e) => Some(e), - Error::Signer(e) => Some(e), - Error::InvalidProof(e) => Some(e), - Error::PacketVerificationFailed { ics02_error: e, .. } => Some(e), - Error::InvalidStringAsSequence { error: e, .. } => Some(e), - // Error::InvalidPacketTimestamp(e) => Some(e), + Self::Connection(e) => Some(e), + Self::Port(e) => Some(e), + Self::Identifier(e) => Some(e), + Self::InvalidVersion(e) => Some(e), + Self::Signer(e) => Some(e), + Self::InvalidProof(e) => Some(e), + Self::PacketVerificationFailed { ics02_error: e, .. } => Some(e), + Self::InvalidStringAsSequence { error: e, .. } => Some(e), _ => None, } } diff --git a/crates/ibc/src/core/ics04_channel/events.rs b/crates/ibc/src/core/ics04_channel/events.rs index e77f03339..533fbd41a 100644 --- a/crates/ibc/src/core/ics04_channel/events.rs +++ b/crates/ibc/src/core/ics04_channel/events.rs @@ -5,7 +5,7 @@ mod packet_attributes; use tendermint::abci; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::packet::Packet; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; use crate::events::IbcEventType; @@ -524,7 +524,7 @@ impl SendPacket { } impl TryFrom for abci::Event { - type Error = Error; + type Error = ChannelError; fn try_from(v: SendPacket) -> Result { let mut attributes = Vec::with_capacity(11); @@ -618,7 +618,7 @@ impl ReceivePacket { } impl TryFrom for abci::Event { - type Error = Error; + type Error = ChannelError; fn try_from(v: ReceivePacket) -> Result { let mut attributes = Vec::with_capacity(11); @@ -716,7 +716,7 @@ impl WriteAcknowledgement { } impl TryFrom for abci::Event { - type Error = Error; + type Error = ChannelError; fn try_from(v: WriteAcknowledgement) -> Result { let mut attributes = Vec::with_capacity(11); @@ -804,7 +804,7 @@ impl AcknowledgePacket { } impl TryFrom for abci::Event { - type Error = Error; + type Error = ChannelError; fn try_from(v: AcknowledgePacket) -> Result { Ok(abci::Event { @@ -884,7 +884,7 @@ impl TimeoutPacket { } impl TryFrom for abci::Event { - type Error = Error; + type Error = ChannelError; fn try_from(v: TimeoutPacket) -> Result { Ok(abci::Event { diff --git a/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs b/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs index 607521b2a..d7028f5da 100644 --- a/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs +++ b/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs @@ -1,8 +1,8 @@ use crate::{ core::{ ics04_channel::{ - channel::Order, error::Error, msgs::acknowledgement::Acknowledgement, packet::Sequence, - timeout::TimeoutHeight, + channel::Order, error::ChannelError, msgs::acknowledgement::Acknowledgement, + packet::Sequence, timeout::TimeoutHeight, }, ics24_host::identifier::{ChannelId, ConnectionId, PortId}, }, @@ -38,13 +38,13 @@ pub struct PacketDataAttribute { } impl TryFrom for Vec { - type Error = Error; + type Error = ChannelError; fn try_from(attr: PacketDataAttribute) -> Result { let tags = vec![ ( PKT_DATA_ATTRIBUTE_KEY, - str::from_utf8(&attr.packet_data).map_err(|_| Error::NonUtf8PacketData)?, + str::from_utf8(&attr.packet_data).map_err(|_| ChannelError::NonUtf8PacketData)?, ) .into(), ( @@ -172,7 +172,7 @@ pub struct AcknowledgementAttribute { } impl TryFrom for Vec { - type Error = Error; + type Error = ChannelError; fn try_from(attr: AcknowledgementAttribute) -> Result { let tags = vec![ @@ -183,7 +183,7 @@ impl TryFrom for Vec { // it. It has been deprecated in ibc-go. It will be removed // in the future. str::from_utf8(attr.acknowledgement.as_bytes()) - .map_err(|_| Error::NonUtf8PacketData)?, + .map_err(|_| ChannelError::NonUtf8PacketData)?, ) .into(), ( diff --git a/crates/ibc/src/core/ics04_channel/handler.rs b/crates/ibc/src/core/ics04_channel/handler.rs index 34997b885..687a1f9ce 100644 --- a/crates/ibc/src/core/ics04_channel/handler.rs +++ b/crates/ibc/src/core/ics04_channel/handler.rs @@ -4,7 +4,7 @@ use crate::prelude::*; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::{Error, PacketError}; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::msgs::ChannelMsg; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::{msgs::PacketMsg, packet::PacketResult}; @@ -65,7 +65,7 @@ impl ModuleExtras { } } -pub fn channel_validate(ctx: &Ctx, msg: &ChannelMsg) -> Result +pub fn channel_validate(ctx: &Ctx, msg: &ChannelMsg) -> Result where Ctx: RouterContext, { @@ -73,7 +73,7 @@ where if ctx.router().has_route(&module_id) { Ok(module_id) } else { - Err(Error::RouteNotFound) + Err(ChannelError::RouteNotFound) } } @@ -82,7 +82,7 @@ where pub fn channel_dispatch( ctx: &Ctx, msg: &ChannelMsg, -) -> Result<(Vec, ChannelResult), Error> +) -> Result<(Vec, ChannelResult), ChannelError> where Ctx: ChannelReader, { @@ -104,14 +104,14 @@ pub fn channel_callback( module_id: &ModuleId, msg: &ChannelMsg, result: &mut ChannelResult, -) -> Result +) -> Result where Ctx: RouterContext, { let cb = ctx .router_mut() .get_route_mut(module_id) - .ok_or(Error::RouteNotFound)?; + .ok_or(ChannelError::RouteNotFound)?; match msg { ChannelMsg::ChannelOpenInit(msg) => { @@ -222,29 +222,29 @@ pub fn channel_events( vec![event] } -pub fn get_module_for_packet_msg(ctx: &Ctx, msg: &PacketMsg) -> Result +pub fn get_module_for_packet_msg(ctx: &Ctx, msg: &PacketMsg) -> Result where Ctx: RouterContext, { let module_id = match msg { PacketMsg::RecvPacket(msg) => ctx .lookup_module_by_port(&msg.packet.destination_port) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, PacketMsg::AckPacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, PacketMsg::TimeoutPacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, PacketMsg::TimeoutOnClosePacket(msg) => ctx .lookup_module_by_port(&msg.packet.source_port) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, }; if ctx.router().has_route(&module_id) { Ok(module_id) } else { - Err(Error::RouteNotFound) + Err(ChannelError::RouteNotFound) } } diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs b/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs index 381da4be3..760eacde2 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_close_confirm.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm; use crate::handler::{HandlerOutput, HandlerResult}; @@ -12,7 +12,7 @@ use crate::prelude::*; pub(crate) fn process( ctx_b: &Ctx, msg: &MsgChannelCloseConfirm, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); // Retrieve the old channel end and validate it against the message. @@ -20,14 +20,14 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be closed. if chan_end_on_b.state_matches(&State::Closed) { - return Err(Error::ChannelClosed { + return Err(ChannelError::ChannelClosed { channel_id: msg.chan_id_on_b.clone(), }); } // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_b.connection_hops().len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: chan_end_on_b.connection_hops().len(), }); @@ -36,7 +36,7 @@ pub(crate) fn process( let conn_end_on_b = ctx_b.connection_end(&chan_end_on_b.connection_hops()[0])?; if !conn_end_on_b.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(ChannelError::ConnectionNotOpen { connection_id: chan_end_on_b.connection_hops()[0].clone(), }); } @@ -52,16 +52,16 @@ pub(crate) fn process( let chan_id_on_a = chan_end_on_b .counterparty() .channel_id() - .ok_or(Error::InvalidCounterpartyChannelId)?; + .ok_or(ChannelError::InvalidCounterpartyChannelId)?; let conn_id_on_a = conn_end_on_b.counterparty().connection_id().ok_or( - Error::UndefinedConnectionCounterparty { + ChannelError::UndefinedConnectionCounterparty { connection_id: chan_end_on_b.connection_hops()[0].clone(), }, )?; // The client must not be frozen. if client_state_of_a_on_b.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id_on_b, }); } @@ -86,7 +86,7 @@ pub(crate) fn process( chan_id_on_a, &expected_chan_end_on_a, ) - .map_err(Error::VerifyChannelFailed)?; + .map_err(ChannelError::VerifyChannelFailed)?; } output.log("success: channel close confirm"); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs b/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs index 22c7b1f4b..745a5b261 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_close_init.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit; use crate::handler::{HandlerOutput, HandlerResult}; @@ -11,14 +11,14 @@ use crate::handler::{HandlerOutput, HandlerResult}; pub(crate) fn process( ctx_a: &Ctx, msg: &MsgChannelCloseInit, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); let chan_end_on_a = ctx_a.channel_end(&msg.port_id_on_a, &msg.chan_id_on_a)?; // Validate that the channel end is in a state where it can be closed. if chan_end_on_a.state_matches(&State::Closed) { - return Err(Error::InvalidChannelState { + return Err(ChannelError::InvalidChannelState { channel_id: msg.chan_id_on_a.clone(), state: chan_end_on_a.state, }); @@ -26,7 +26,7 @@ pub(crate) fn process( // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_a.connection_hops().len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: chan_end_on_a.connection_hops().len(), }); @@ -35,7 +35,7 @@ pub(crate) fn process( let conn_end_on_a = ctx_a.connection_end(&chan_end_on_a.connection_hops()[0])?; if !conn_end_on_a.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(ChannelError::ConnectionNotOpen { connection_id: chan_end_on_a.connection_hops()[0].clone(), }); } diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs index 140f3a043..43dde0b90 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_ack.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; use crate::handler::{HandlerOutput, HandlerResult}; @@ -12,7 +12,7 @@ use crate::prelude::*; pub(crate) fn process( ctx_a: &Ctx, msg: &MsgChannelOpenAck, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); // Unwrap the old channel end and validate it against the message. @@ -20,7 +20,7 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be ack. if !chan_end_on_a.state_matches(&State::Init) { - return Err(Error::InvalidChannelState { + return Err(ChannelError::InvalidChannelState { channel_id: msg.chan_id_on_a.clone(), state: chan_end_on_a.state, }); @@ -29,7 +29,7 @@ pub(crate) fn process( // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_a.connection_hops().len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: chan_end_on_a.connection_hops().len(), }); @@ -38,7 +38,7 @@ pub(crate) fn process( let conn_end_on_a = ctx_a.connection_end(&chan_end_on_a.connection_hops()[0])?; if !conn_end_on_a.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(ChannelError::ConnectionNotOpen { connection_id: chan_end_on_a.connection_hops()[0].clone(), }); } @@ -52,14 +52,14 @@ pub(crate) fn process( let prefix_on_b = conn_end_on_a.counterparty().prefix(); let port_id_on_b = &chan_end_on_a.counterparty().port_id; let conn_id_on_b = conn_end_on_a.counterparty().connection_id().ok_or( - Error::UndefinedConnectionCounterparty { + ChannelError::UndefinedConnectionCounterparty { connection_id: chan_end_on_a.connection_hops()[0].clone(), }, )?; // The client must not be frozen. if client_state_of_b_on_a.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id_on_a, }); } @@ -86,7 +86,7 @@ pub(crate) fn process( &msg.chan_id_on_b, &expected_chan_end_on_b, ) - .map_err(Error::VerifyChannelFailed)?; + .map_err(ChannelError::VerifyChannelFailed)?; } output.log("success: channel open ack"); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs index 905ef1609..c2f37710c 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_confirm.rs @@ -2,7 +2,7 @@ use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm; use crate::handler::{HandlerOutput, HandlerResult}; @@ -12,7 +12,7 @@ use crate::prelude::*; pub(crate) fn process( ctx_b: &Ctx, msg: &MsgChannelOpenConfirm, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); // Unwrap the old channel end and validate it against the message. @@ -20,7 +20,7 @@ pub(crate) fn process( // Validate that the channel end is in a state where it can be confirmed. if !chan_end_on_b.state_matches(&State::TryOpen) { - return Err(Error::InvalidChannelState { + return Err(ChannelError::InvalidChannelState { channel_id: msg.chan_id_on_b.clone(), state: chan_end_on_b.state, }); @@ -28,7 +28,7 @@ pub(crate) fn process( // An OPEN IBC connection running on the local (host) chain should exist. if chan_end_on_b.connection_hops().len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: chan_end_on_b.connection_hops().len(), }); @@ -37,7 +37,7 @@ pub(crate) fn process( let conn_end_on_b = ctx_b.connection_end(&chan_end_on_b.connection_hops()[0])?; if !conn_end_on_b.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(ChannelError::ConnectionNotOpen { connection_id: chan_end_on_b.connection_hops()[0].clone(), }); } @@ -53,16 +53,16 @@ pub(crate) fn process( let chan_id_on_a = chan_end_on_b .counterparty() .channel_id() - .ok_or(Error::InvalidCounterpartyChannelId)?; + .ok_or(ChannelError::InvalidCounterpartyChannelId)?; let conn_id_on_a = conn_end_on_b.counterparty().connection_id().ok_or( - Error::UndefinedConnectionCounterparty { + ChannelError::UndefinedConnectionCounterparty { connection_id: chan_end_on_b.connection_hops()[0].clone(), }, )?; // The client must not be frozen. if client_state_of_a_on_b.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id_on_b, }); } @@ -87,7 +87,7 @@ pub(crate) fn process( chan_id_on_a, &expected_chan_end_on_a, ) - .map_err(Error::VerifyChannelFailed)?; + .map_err(ChannelError::VerifyChannelFailed)?; } output.log("success: channel open confirm "); diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs index 9a97e2d54..e90a07a31 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_init.rs @@ -2,7 +2,7 @@ use crate::core::ics04_channel::channel::{ChannelEnd, State}; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; use crate::core::ics24_host::identifier::ChannelId; @@ -13,11 +13,11 @@ use crate::prelude::*; pub(crate) fn process( ctx_a: &Ctx, msg: &MsgChannelOpenInit, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); if msg.chan_end_on_a.connection_hops().len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: msg.chan_end_on_a.connection_hops().len(), }); @@ -28,12 +28,12 @@ pub(crate) fn process( let conn_version = match conn_end_on_a.versions() { [version] => version, - _ => return Err(Error::InvalidVersionLengthConnection), + _ => return Err(ChannelError::InvalidVersionLengthConnection), }; let channel_feature = msg.chan_end_on_a.ordering().to_string(); if !conn_version.is_supported_feature(channel_feature) { - return Err(Error::ChannelFeatureNotSuportedByConnection); + return Err(ChannelError::ChannelFeatureNotSuportedByConnection); } let chan_end_on_a = ChannelEnd::new( diff --git a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs index 82714a7ac..046012260 100644 --- a/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/handler/chan_open_try.rs @@ -3,7 +3,7 @@ use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::{ChannelIdState, ChannelResult}; use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; use crate::core::ics04_channel::Version; @@ -15,12 +15,12 @@ use crate::prelude::*; pub(crate) fn process( ctx_b: &Ctx, msg: &MsgChannelOpenTry, -) -> HandlerResult { +) -> HandlerResult { let mut output = HandlerOutput::builder(); // An IBC connection running on the local (host) chain should exist. if msg.chan_end_on_b.connection_hops().len() != 1 { - return Err(Error::InvalidConnectionHopsLength { + return Err(ChannelError::InvalidConnectionHopsLength { expected: 1, actual: msg.chan_end_on_b.connection_hops().len(), }); @@ -28,19 +28,19 @@ pub(crate) fn process( let conn_end_on_b = ctx_b.connection_end(&msg.chan_end_on_b.connection_hops()[0])?; if !conn_end_on_b.state_matches(&ConnectionState::Open) { - return Err(Error::ConnectionNotOpen { + return Err(ChannelError::ConnectionNotOpen { connection_id: msg.chan_end_on_b.connection_hops()[0].clone(), }); } let conn_version = match conn_end_on_b.versions() { [version] => version, - _ => return Err(Error::InvalidVersionLengthConnection), + _ => return Err(ChannelError::InvalidVersionLengthConnection), }; let channel_feature = msg.chan_end_on_b.ordering().to_string(); if !conn_version.is_supported_feature(channel_feature) { - return Err(Error::ChannelFeatureNotSuportedByConnection); + return Err(ChannelError::ChannelFeatureNotSuportedByConnection); } // Verify proofs @@ -55,16 +55,16 @@ pub(crate) fn process( .chan_end_on_b .counterparty() .channel_id() - .ok_or(Error::InvalidCounterpartyChannelId)?; + .ok_or(ChannelError::InvalidCounterpartyChannelId)?; let conn_id_on_a = conn_end_on_b.counterparty().connection_id().ok_or( - Error::UndefinedConnectionCounterparty { + ChannelError::UndefinedConnectionCounterparty { connection_id: msg.chan_end_on_b.connection_hops()[0].clone(), }, )?; // The client must not be frozen. if client_state_of_a_on_b.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id_on_b, }); } @@ -89,7 +89,7 @@ pub(crate) fn process( chan_id_on_a, &expected_chan_end_on_a, ) - .map_err(Error::VerifyChannelFailed)?; + .map_err(ChannelError::VerifyChannelFailed)?; } let chan_end_on_b = ChannelEnd::new( @@ -151,7 +151,7 @@ mod tests { ctx: MockContext, msg: ChannelMsg, want_pass: bool, - match_error: Box, + match_error: Box, } // Some general-purpose variable to parametrize the messages and the context. @@ -198,7 +198,7 @@ mod tests { match_error: { let connection_id = msg.chan_end_on_b.connection_hops()[0].clone(); Box::new(move |e| match e { - error::Error::Connection(e) => { + error::ChannelError::Connection(e) => { assert_eq!( e.to_string(), ics03_error::ConnectionError::ConnectionNotFound { connection_id } @@ -224,7 +224,7 @@ mod tests { msg: ChannelMsg::ChannelOpenTry(msg.clone()), want_pass: false, match_error: Box::new(|e| match e { - error::Error::Connection(e) => { + error::ChannelError::Connection(e) => { assert_eq!( e.to_string(), ics03_error::ConnectionError::Client( diff --git a/crates/ibc/src/core/ics04_channel/handler/verify.rs b/crates/ibc/src/core/ics04_channel/handler/verify.rs index 10667d130..b4fc42667 100644 --- a/crates/ibc/src/core/ics04_channel/handler/verify.rs +++ b/crates/ibc/src/core/ics04_channel/handler/verify.rs @@ -1,7 +1,7 @@ use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::context::ChannelReader; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::prelude::*; @@ -16,7 +16,7 @@ pub fn verify_channel_proofs( connection_end: &ConnectionEnd, expected_chan: &ChannelEnd, proofs: &Proofs, -) -> Result<(), Error> { +) -> Result<(), ChannelError> { // This is the client which will perform proof verification. let client_id = connection_end.client_id().clone(); @@ -24,7 +24,7 @@ pub fn verify_channel_proofs( // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::FrozenClient { client_id }); + return Err(ChannelError::FrozenClient { client_id }); } let consensus_state = ctx.client_consensus_state(&client_id, proofs.height())?; @@ -41,10 +41,10 @@ pub fn verify_channel_proofs( channel_end .counterparty() .channel_id() - .ok_or(Error::InvalidCounterpartyChannelId)?, + .ok_or(ChannelError::InvalidCounterpartyChannelId)?, expected_chan, ) - .map_err(Error::VerifyChannelFailed) + .map_err(ChannelError::VerifyChannelFailed) } /// Entry point for verifying all proofs bundled in a ICS4 packet recv. message. @@ -54,13 +54,13 @@ pub fn verify_packet_recv_proofs( packet: &Packet, connection_end: &ConnectionEnd, proofs: &Proofs, -) -> Result<(), Error> { +) -> Result<(), ChannelError> { let client_id = connection_end.client_id(); let client_state = ctx.client_state(client_id)?; // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id.clone(), }); } @@ -86,7 +86,7 @@ pub fn verify_packet_recv_proofs( packet.sequence, commitment, ) - .map_err(|e| Error::PacketVerificationFailed { + .map_err(|e| ChannelError::PacketVerificationFailed { sequence: packet.sequence, ics02_error: e, })?; @@ -102,13 +102,13 @@ pub fn verify_packet_acknowledgement_proofs( acknowledgement: Acknowledgement, connection_end: &ConnectionEnd, proofs: &Proofs, -) -> Result<(), Error> { +) -> Result<(), ChannelError> { let client_id = connection_end.client_id(); let client_state = ctx.client_state(client_id)?; // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id.clone(), }); } @@ -130,7 +130,7 @@ pub fn verify_packet_acknowledgement_proofs( packet.sequence, ack_commitment, ) - .map_err(|e| Error::PacketVerificationFailed { + .map_err(|e| ChannelError::PacketVerificationFailed { sequence: packet.sequence, ics02_error: e, })?; @@ -146,13 +146,13 @@ pub fn verify_next_sequence_recv( packet: Packet, seq: Sequence, proofs: &Proofs, -) -> Result<(), Error> { +) -> Result<(), ChannelError> { let client_id = connection_end.client_id(); let client_state = ctx.client_state(client_id)?; // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id.clone(), }); } @@ -171,7 +171,7 @@ pub fn verify_next_sequence_recv( &packet.destination_channel, packet.sequence, ) - .map_err(|e| Error::PacketVerificationFailed { + .map_err(|e| ChannelError::PacketVerificationFailed { sequence: seq, ics02_error: e, })?; @@ -185,13 +185,13 @@ pub fn verify_packet_receipt_absence( connection_end: &ConnectionEnd, packet: Packet, proofs: &Proofs, -) -> Result<(), Error> { +) -> Result<(), ChannelError> { let client_id = connection_end.client_id(); let client_state = ctx.client_state(client_id)?; // The client must not be frozen. if client_state.is_frozen() { - return Err(Error::FrozenClient { + return Err(ChannelError::FrozenClient { client_id: client_id.clone(), }); } @@ -210,7 +210,7 @@ pub fn verify_packet_receipt_absence( &packet.destination_channel, packet.sequence, ) - .map_err(|e| Error::PacketVerificationFailed { + .map_err(|e| ChannelError::PacketVerificationFailed { sequence: packet.sequence, ics02_error: e, })?; diff --git a/crates/ibc/src/core/ics04_channel/msgs.rs b/crates/ibc/src/core/ics04_channel/msgs.rs index 97238f99b..e85e127a3 100644 --- a/crates/ibc/src/core/ics04_channel/msgs.rs +++ b/crates/ibc/src/core/ics04_channel/msgs.rs @@ -1,7 +1,7 @@ //! Message definitions for all ICS4 domain types: channel open & close handshake datagrams, as well //! as packets. -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::msgs::acknowledgement::MsgAcknowledgement; use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm; use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit; @@ -42,26 +42,26 @@ pub enum ChannelMsg { } impl ChannelMsg { - pub(super) fn lookup_module(&self, ctx: &impl RouterContext) -> Result { + pub(super) fn lookup_module(&self, ctx: &impl RouterContext) -> Result { let module_id = match self { ChannelMsg::ChannelOpenInit(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, ChannelMsg::ChannelOpenTry(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, ChannelMsg::ChannelOpenAck(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, ChannelMsg::ChannelOpenConfirm(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, ChannelMsg::ChannelCloseInit(msg) => ctx .lookup_module_by_port(&msg.port_id_on_a) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, ChannelMsg::ChannelCloseConfirm(msg) => ctx .lookup_module_by_port(&msg.port_id_on_b) - .map_err(Error::Port)?, + .map_err(ChannelError::Port)?, }; Ok(module_id) } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs index 076f2a271..213e02f81 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_close_confirm.rs @@ -5,7 +5,7 @@ use ibc_proto::protobuf::Protobuf; use ibc_proto::ibc::core::channel::v1::MsgChannelCloseConfirm as RawMsgChannelCloseConfirm; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::signer::Signer; use crate::tx_msg::Msg; @@ -45,7 +45,7 @@ impl MsgChannelCloseConfirm { } impl Msg for MsgChannelCloseConfirm { - type ValidationError = Error; + type ValidationError = ChannelError; type Raw = RawMsgChannelCloseConfirm; fn route(&self) -> String { @@ -60,18 +60,24 @@ impl Msg for MsgChannelCloseConfirm { impl Protobuf for MsgChannelCloseConfirm {} impl TryFrom for MsgChannelCloseConfirm { - type Error = Error; + type Error = ChannelError; fn try_from(raw_msg: RawMsgChannelCloseConfirm) -> Result { Ok(MsgChannelCloseConfirm { - port_id_on_b: raw_msg.port_id.parse().map_err(Error::Identifier)?, - chan_id_on_b: raw_msg.channel_id.parse().map_err(Error::Identifier)?, - proof_chan_end_on_a: raw_msg.proof_init.try_into().map_err(Error::InvalidProof)?, + port_id_on_b: raw_msg.port_id.parse().map_err(ChannelError::Identifier)?, + chan_id_on_b: raw_msg + .channel_id + .parse() + .map_err(ChannelError::Identifier)?, + proof_chan_end_on_a: raw_msg + .proof_init + .try_into() + .map_err(ChannelError::InvalidProof)?, proof_height_on_a: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + .ok_or(ChannelError::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(ChannelError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs index a23b27a5d..c3b60e7be 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_close_init.rs @@ -4,7 +4,7 @@ use ibc_proto::protobuf::Protobuf; use ibc_proto::ibc::core::channel::v1::MsgChannelCloseInit as RawMsgChannelCloseInit; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::signer::Signer; use crate::tx_msg::Msg; @@ -33,7 +33,7 @@ impl MsgChannelCloseInit { } impl Msg for MsgChannelCloseInit { - type ValidationError = Error; + type ValidationError = ChannelError; type Raw = RawMsgChannelCloseInit; fn route(&self) -> String { @@ -48,13 +48,16 @@ impl Msg for MsgChannelCloseInit { impl Protobuf for MsgChannelCloseInit {} impl TryFrom for MsgChannelCloseInit { - type Error = Error; + type Error = ChannelError; fn try_from(raw_msg: RawMsgChannelCloseInit) -> Result { Ok(MsgChannelCloseInit { - port_id_on_a: raw_msg.port_id.parse().map_err(Error::Identifier)?, - chan_id_on_a: raw_msg.channel_id.parse().map_err(Error::Identifier)?, - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + port_id_on_a: raw_msg.port_id.parse().map_err(ChannelError::Identifier)?, + chan_id_on_a: raw_msg + .channel_id + .parse() + .map_err(ChannelError::Identifier)?, + signer: raw_msg.signer.parse().map_err(ChannelError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs index c9c0a2e33..956a9c2b0 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_ack.rs @@ -1,4 +1,4 @@ -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::Version; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::{ChannelId, PortId}; @@ -49,7 +49,7 @@ impl MsgChannelOpenAck { } impl Msg for MsgChannelOpenAck { - type ValidationError = Error; + type ValidationError = ChannelError; type Raw = RawMsgChannelOpenAck; fn route(&self) -> String { @@ -64,23 +64,29 @@ impl Msg for MsgChannelOpenAck { impl Protobuf for MsgChannelOpenAck {} impl TryFrom for MsgChannelOpenAck { - type Error = Error; + type Error = ChannelError; fn try_from(raw_msg: RawMsgChannelOpenAck) -> Result { Ok(MsgChannelOpenAck { - port_id_on_a: raw_msg.port_id.parse().map_err(Error::Identifier)?, - chan_id_on_a: raw_msg.channel_id.parse().map_err(Error::Identifier)?, + port_id_on_a: raw_msg.port_id.parse().map_err(ChannelError::Identifier)?, + chan_id_on_a: raw_msg + .channel_id + .parse() + .map_err(ChannelError::Identifier)?, chan_id_on_b: raw_msg .counterparty_channel_id .parse() - .map_err(Error::Identifier)?, + .map_err(ChannelError::Identifier)?, version_on_b: raw_msg.counterparty_version.into(), - proof_chan_end_on_b: raw_msg.proof_try.try_into().map_err(Error::InvalidProof)?, + proof_chan_end_on_b: raw_msg + .proof_try + .try_into() + .map_err(ChannelError::InvalidProof)?, proof_height_on_b: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + .ok_or(ChannelError::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(ChannelError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs index 588ca3036..a31684ce1 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_confirm.rs @@ -1,4 +1,4 @@ -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::signer::Signer; @@ -43,7 +43,7 @@ impl MsgChannelOpenConfirm { } impl Msg for MsgChannelOpenConfirm { - type ValidationError = Error; + type ValidationError = ChannelError; type Raw = RawMsgChannelOpenConfirm; fn route(&self) -> String { @@ -58,18 +58,24 @@ impl Msg for MsgChannelOpenConfirm { impl Protobuf for MsgChannelOpenConfirm {} impl TryFrom for MsgChannelOpenConfirm { - type Error = Error; + type Error = ChannelError; fn try_from(raw_msg: RawMsgChannelOpenConfirm) -> Result { Ok(MsgChannelOpenConfirm { - port_id_on_b: raw_msg.port_id.parse().map_err(Error::Identifier)?, - chan_id_on_b: raw_msg.channel_id.parse().map_err(Error::Identifier)?, - proof_chan_end_on_a: raw_msg.proof_ack.try_into().map_err(Error::InvalidProof)?, + port_id_on_b: raw_msg.port_id.parse().map_err(ChannelError::Identifier)?, + chan_id_on_b: raw_msg + .channel_id + .parse() + .map_err(ChannelError::Identifier)?, + proof_chan_end_on_a: raw_msg + .proof_ack + .try_into() + .map_err(ChannelError::InvalidProof)?, proof_height_on_a: raw_msg .proof_height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(Error::MissingHeight)?, - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + .ok_or(ChannelError::MissingHeight)?, + signer: raw_msg.signer.parse().map_err(ChannelError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs index 1954b7664..9a8fa1aed 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_init.rs @@ -1,5 +1,5 @@ use crate::core::ics04_channel::channel::ChannelEnd; -use crate::core::ics04_channel::error::Error; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics24_host::identifier::PortId; use crate::prelude::*; use crate::signer::Signer; @@ -32,7 +32,7 @@ impl MsgChannelOpenInit { } impl Msg for MsgChannelOpenInit { - type ValidationError = Error; + type ValidationError = ChannelError; type Raw = RawMsgChannelOpenInit; fn route(&self) -> String { @@ -47,13 +47,16 @@ impl Msg for MsgChannelOpenInit { impl Protobuf for MsgChannelOpenInit {} impl TryFrom for MsgChannelOpenInit { - type Error = Error; + type Error = ChannelError; fn try_from(raw_msg: RawMsgChannelOpenInit) -> Result { Ok(MsgChannelOpenInit { - port_id_on_a: raw_msg.port_id.parse().map_err(Error::Identifier)?, - chan_end_on_a: raw_msg.channel.ok_or(Error::MissingChannel)?.try_into()?, - signer: raw_msg.signer.parse().map_err(Error::Signer)?, + port_id_on_a: raw_msg.port_id.parse().map_err(ChannelError::Identifier)?, + chan_end_on_a: raw_msg + .channel + .ok_or(ChannelError::MissingChannel)? + .try_into()?, + signer: raw_msg.signer.parse().map_err(ChannelError::Signer)?, }) } } diff --git a/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs b/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs index 3557c5dc6..868a924f1 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/chan_open_try.rs @@ -1,5 +1,5 @@ use crate::core::ics04_channel::channel::ChannelEnd; -use crate::core::ics04_channel::error::Error as ChannelError; +use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::Version; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::error::ValidationError; diff --git a/crates/ibc/src/core/ics04_channel/packet.rs b/crates/ibc/src/core/ics04_channel/packet.rs index 729ee7830..fde42440a 100644 --- a/crates/ibc/src/core/ics04_channel/packet.rs +++ b/crates/ibc/src/core/ics04_channel/packet.rs @@ -11,7 +11,7 @@ use super::handler::{ timeout::TimeoutPacketResult, write_acknowledgement::WriteAckPacketResult, }; use super::timeout::TimeoutHeight; -use crate::core::ics04_channel::error::{Error, PacketError}; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::timestamp::{Expiry::Expired, Timestamp}; use crate::Height; @@ -59,11 +59,11 @@ impl core::fmt::Display for PacketMsgType { pub struct Sequence(u64); impl FromStr for Sequence { - type Err = Error; + type Err = ChannelError; fn from_str(s: &str) -> Result { Ok(Self::from(s.parse::().map_err(|e| { - Error::InvalidStringAsSequence { + ChannelError::InvalidStringAsSequence { value: s.to_string(), error: e, } diff --git a/crates/ibc/src/core/ics26_routing/context.rs b/crates/ibc/src/core/ics26_routing/context.rs index 10cf3c61a..3e5a677a5 100644 --- a/crates/ibc/src/core/ics26_routing/context.rs +++ b/crates/ibc/src/core/ics26_routing/context.rs @@ -14,7 +14,7 @@ use crate::core::ics02_client::context::{ClientKeeper, ClientReader}; use crate::core::ics03_connection::context::{ConnectionKeeper, ConnectionReader}; use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::context::{ChannelKeeper, ChannelReader}; -use crate::core::ics04_channel::error::{Error, PacketError}; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement as GenericAcknowledgement; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; @@ -108,7 +108,7 @@ pub trait Module: Send + Sync + AsAnyMut { channel_id: &ChannelId, counterparty: &Counterparty, version: &Version, - ) -> Result<(ModuleExtras, Version), Error>; + ) -> Result<(ModuleExtras, Version), ChannelError>; #[allow(clippy::too_many_arguments)] fn on_chan_open_try( @@ -119,14 +119,14 @@ pub trait Module: Send + Sync + AsAnyMut { channel_id: &ChannelId, counterparty: &Counterparty, counterparty_version: &Version, - ) -> Result<(ModuleExtras, Version), Error>; + ) -> Result<(ModuleExtras, Version), ChannelError>; fn on_chan_open_ack( &mut self, _port_id: &PortId, _channel_id: &ChannelId, _counterparty_version: &Version, - ) -> Result { + ) -> Result { Ok(ModuleExtras::empty()) } @@ -134,7 +134,7 @@ pub trait Module: Send + Sync + AsAnyMut { &mut self, _port_id: &PortId, _channel_id: &ChannelId, - ) -> Result { + ) -> Result { Ok(ModuleExtras::empty()) } @@ -142,7 +142,7 @@ pub trait Module: Send + Sync + AsAnyMut { &mut self, _port_id: &PortId, _channel_id: &ChannelId, - ) -> Result { + ) -> Result { Ok(ModuleExtras::empty()) } @@ -150,7 +150,7 @@ pub trait Module: Send + Sync + AsAnyMut { &mut self, _port_id: &PortId, _channel_id: &ChannelId, - ) -> Result { + ) -> Result { Ok(ModuleExtras::empty()) } diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index fcb513022..c8bb6c707 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -12,7 +12,7 @@ pub enum Error { /// ICS03 connection error Connection(ics03_connection::error::ConnectionError), /// ICS04 channel error - Channel(ics04_channel::error::Error), + Channel(ics04_channel::error::ChannelError), /// ICS04 Packet error Packet(ics04_channel::error::PacketError), /// unknown type URL `{url}` diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index 24682f5af..ada71ed21 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -27,7 +27,7 @@ pub enum Error { /// connection error Connection(connection_error::ConnectionError), /// channel error - Channel(channel_error::Error), + Channel(channel_error::ChannelError), /// error parsing timestamp Timestamp(ParseTimestampError), /// missing event key `{key}` @@ -50,13 +50,13 @@ pub enum Error { impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::Parse(e) => Some(e), - Error::Client(e) => Some(e), - Error::Connection(e) => Some(e), - Error::Channel(e) => Some(e), - Error::Timestamp(e) => Some(e), - Error::Decode(e) => Some(e), - Error::SubtleEncoding(e) => Some(e), + Self::Parse(e) => Some(e), + Self::Client(e) => Some(e), + Self::Connection(e) => Some(e), + Self::Channel(e) => Some(e), + Self::Timestamp(e) => Some(e), + Self::Decode(e) => Some(e), + Self::SubtleEncoding(e) => Some(e), _ => None, } } diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 54e9ba171..171567bb0 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -30,7 +30,7 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment}; use crate::core::ics04_channel::context::{ChannelKeeper, ChannelReader}; -use crate::core::ics04_channel::error::{Error as Ics04Error, PacketError}; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::packet::{Receipt, Sequence}; use crate::core::ics05_port::context::PortReader; use crate::core::ics05_port::error::Error as Ics05Error; @@ -675,7 +675,7 @@ impl ChannelReader for MockContext { &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -685,39 +685,39 @@ impl ChannelReader for MockContext { .and_then(|map| map.get(channel_id)) { Some(channel_end) => Ok(channel_end.clone()), - None => Err(Ics04Error::ChannelNotFound { + None => Err(ChannelError::ChannelNotFound { port_id: port_id.clone(), channel_id: channel_id.clone(), }), } } - fn connection_end(&self, cid: &ConnectionId) -> Result { - ConnectionReader::connection_end(self, cid).map_err(Ics04Error::Connection) + fn connection_end(&self, cid: &ConnectionId) -> Result { + ConnectionReader::connection_end(self, cid).map_err(ChannelError::Connection) } fn connection_channels( &self, cid: &ConnectionId, - ) -> Result, Ics04Error> { + ) -> Result, ChannelError> { match self.ibc_store.lock().unwrap().connection_channels.get(cid) { Some(pcid) => Ok(pcid.clone()), - None => Err(Ics04Error::MissingChannel), + None => Err(ChannelError::MissingChannel), } } - fn client_state(&self, client_id: &ClientId) -> Result, Ics04Error> { + fn client_state(&self, client_id: &ClientId) -> Result, ChannelError> { ClientReader::client_state(self, client_id) - .map_err(|e| Ics04Error::Connection(ConnectionError::Client(e))) + .map_err(|e| ChannelError::Connection(ConnectionError::Client(e))) } fn client_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result, Ics04Error> { + ) -> Result, ChannelError> { ClientReader::consensus_state(self, client_id, height) - .map_err(|e| Ics04Error::Connection(ConnectionError::Client(e))) + .map_err(|e| ChannelError::Connection(ConnectionError::Client(e))) } fn get_next_sequence_send( @@ -847,30 +847,33 @@ impl ChannelReader for MockContext { sha2::Sha256::digest(value).to_vec() } - fn host_height(&self) -> Result { + fn host_height(&self) -> Result { Ok(self.latest_height()) } - fn host_timestamp(&self) -> Result { - ClientReader::host_timestamp(self).map_err(|e| Ics04Error::Other { + fn host_timestamp(&self) -> Result { + ClientReader::host_timestamp(self).map_err(|e| ChannelError::Other { description: e.to_string(), }) } - fn host_consensus_state(&self, height: Height) -> Result, Ics04Error> { - ConnectionReader::host_consensus_state(self, height).map_err(Ics04Error::Connection) + fn host_consensus_state( + &self, + height: Height, + ) -> Result, ChannelError> { + ConnectionReader::host_consensus_state(self, height).map_err(ChannelError::Connection) } - fn pending_host_consensus_state(&self) -> Result, Ics04Error> { + fn pending_host_consensus_state(&self) -> Result, ChannelError> { ClientReader::pending_host_consensus_state(self) - .map_err(|e| Ics04Error::Connection(ConnectionError::Client(e))) + .map_err(|e| ChannelError::Connection(ConnectionError::Client(e))) } fn client_update_time( &self, client_id: &ClientId, height: Height, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -879,7 +882,7 @@ impl ChannelReader for MockContext { .get(&(client_id.clone(), height)) { Some(time) => Ok(*time), - None => Err(Ics04Error::ProcessedTimeNotFound { + None => Err(ChannelError::ProcessedTimeNotFound { client_id: client_id.clone(), height, }), @@ -890,7 +893,7 @@ impl ChannelReader for MockContext { &self, client_id: &ClientId, height: Height, - ) -> Result { + ) -> Result { match self .ibc_store .lock() @@ -899,14 +902,14 @@ impl ChannelReader for MockContext { .get(&(client_id.clone(), height)) { Some(height) => Ok(*height), - None => Err(Ics04Error::ProcessedHeightNotFound { + None => Err(ChannelError::ProcessedHeightNotFound { client_id: client_id.clone(), height, }), } } - fn channel_counter(&self) -> Result { + fn channel_counter(&self) -> Result { Ok(self.ibc_store.lock().unwrap().channel_ids_counter) } @@ -975,7 +978,7 @@ impl ChannelKeeper for MockContext { cid: ConnectionId, port_id: PortId, channel_id: ChannelId, - ) -> Result<(), Ics04Error> { + ) -> Result<(), ChannelError> { self.ibc_store .lock() .unwrap() @@ -991,7 +994,7 @@ impl ChannelKeeper for MockContext { port_id: PortId, channel_id: ChannelId, channel_end: ChannelEnd, - ) -> Result<(), Ics04Error> { + ) -> Result<(), ChannelError> { self.ibc_store .lock() .unwrap() @@ -1468,7 +1471,7 @@ mod tests { use alloc::str::FromStr; use crate::core::ics04_channel::channel::{Counterparty, Order}; - use crate::core::ics04_channel::error::Error; + use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::handler::ModuleExtras; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; @@ -1652,7 +1655,7 @@ mod tests { _channel_id: &ChannelId, _counterparty: &Counterparty, version: &Version, - ) -> Result<(ModuleExtras, Version), Error> { + ) -> Result<(ModuleExtras, Version), ChannelError> { Ok((ModuleExtras::empty(), version.clone())) } @@ -1664,7 +1667,7 @@ mod tests { _channel_id: &ChannelId, _counterparty: &Counterparty, counterparty_version: &Version, - ) -> Result<(ModuleExtras, Version), Error> { + ) -> Result<(ModuleExtras, Version), ChannelError> { Ok((ModuleExtras::empty(), counterparty_version.clone())) } @@ -1697,7 +1700,7 @@ mod tests { _channel_id: &ChannelId, _counterparty: &Counterparty, version: &Version, - ) -> Result<(ModuleExtras, Version), Error> { + ) -> Result<(ModuleExtras, Version), ChannelError> { Ok((ModuleExtras::empty(), version.clone())) } @@ -1709,7 +1712,7 @@ mod tests { _channel_id: &ChannelId, _counterparty: &Counterparty, counterparty_version: &Version, - ) -> Result<(ModuleExtras, Version), Error> { + ) -> Result<(ModuleExtras, Version), ChannelError> { Ok((ModuleExtras::empty(), counterparty_version.clone())) } } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 25f728c34..20137d254 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -16,7 +16,7 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics04_channel::context::SendPacketReader; -use crate::core::ics04_channel::error::{Error, PacketError}; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::handler::ModuleExtras; use crate::core::ics04_channel::packet::Sequence; use crate::core::ics04_channel::Version; @@ -87,7 +87,7 @@ impl Module for DummyTransferModule { _channel_id: &ChannelId, _counterparty: &Counterparty, version: &Version, - ) -> Result<(ModuleExtras, Version), Error> { + ) -> Result<(ModuleExtras, Version), ChannelError> { Ok(( ModuleExtras { events: Vec::new(), @@ -105,7 +105,7 @@ impl Module for DummyTransferModule { _channel_id: &ChannelId, _counterparty: &Counterparty, counterparty_version: &Version, - ) -> Result<(ModuleExtras, Version), Error> { + ) -> Result<(ModuleExtras, Version), ChannelError> { Ok(( ModuleExtras { events: Vec::new(), From 1d6f64e4aeaecbdadfb08f023d87c407752831cf Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 03:45:18 +0800 Subject: [PATCH 30/43] Rename Ics05Error to PortError --- crates/ibc/src/core/ics04_channel/error.rs | 2 +- crates/ibc/src/core/ics05_port/context.rs | 4 ++-- crates/ibc/src/core/ics05_port/error.rs | 4 ++-- crates/ibc/src/mock/context.rs | 7 +++---- crates/ibc/src/test_utils.rs | 2 +- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 53465657c..de54c6e21 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -20,7 +20,7 @@ pub enum ChannelError { /// ICS03 connection error Connection(connection_error::ConnectionError), /// ICS05 port error - Port(port_error::Error), + Port(port_error::PortError), /// channel state unknown: `{state}` UnknownState { state: i32 }, diff --git a/crates/ibc/src/core/ics05_port/context.rs b/crates/ibc/src/core/ics05_port/context.rs index 2c59d4a59..a1bbfb02d 100644 --- a/crates/ibc/src/core/ics05_port/context.rs +++ b/crates/ibc/src/core/ics05_port/context.rs @@ -1,4 +1,4 @@ -use crate::core::ics05_port::error::Error; +use crate::core::ics05_port::error::PortError; use crate::core::ics24_host::identifier::PortId; use crate::core::ics26_routing::context::ModuleId; use crate::prelude::*; @@ -6,5 +6,5 @@ use crate::prelude::*; /// A context supplying all the necessary read-only dependencies for processing any information regarding a port. pub trait PortReader { /// Return the module_id associated with a given port_id - fn lookup_module_by_port(&self, port_id: &PortId) -> Result; + fn lookup_module_by_port(&self, port_id: &PortId) -> Result; } diff --git a/crates/ibc/src/core/ics05_port/error.rs b/crates/ibc/src/core/ics05_port/error.rs index 335495d36..c55445f18 100644 --- a/crates/ibc/src/core/ics05_port/error.rs +++ b/crates/ibc/src/core/ics05_port/error.rs @@ -2,7 +2,7 @@ use crate::core::ics24_host::identifier::PortId; use displaydoc::Display; #[derive(Debug, Display)] -pub enum Error { +pub enum PortError { /// port `{port_id}` is unknown UnknownPort { port_id: PortId }, /// port `{port_id}` is already bound @@ -14,4 +14,4 @@ pub enum Error { } #[cfg(feature = "std")] -impl std::error::Error for Error {} +impl std::error::Error for PortError {} diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 171567bb0..c1c2e056e 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -33,8 +33,7 @@ use crate::core::ics04_channel::context::{ChannelKeeper, ChannelReader}; use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::packet::{Receipt, Sequence}; use crate::core::ics05_port::context::PortReader; -use crate::core::ics05_port::error::Error as Ics05Error; -use crate::core::ics05_port::error::Error; +use crate::core::ics05_port::error::PortError; use crate::core::ics23_commitment::commitment::CommitmentPrefix; use crate::core::ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortId}; use crate::core::ics26_routing::context::{Module, ModuleId, Router, RouterBuilder, RouterContext}; @@ -660,10 +659,10 @@ impl RouterContext for MockContext { } impl PortReader for MockContext { - fn lookup_module_by_port(&self, port_id: &PortId) -> Result { + fn lookup_module_by_port(&self, port_id: &PortId) -> Result { match self.ibc_store.lock().unwrap().port_to_module.get(port_id) { Some(mod_id) => Ok(mod_id.clone()), - None => Err(Ics05Error::UnknownPort { + None => Err(PortError::UnknownPort { port_id: port_id.clone(), }), } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 20137d254..9f4c3edb8 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -21,7 +21,7 @@ use crate::core::ics04_channel::handler::ModuleExtras; use crate::core::ics04_channel::packet::Sequence; use crate::core::ics04_channel::Version; use crate::core::ics05_port::context::PortReader; -use crate::core::ics05_port::error::Error as PortError; +use crate::core::ics05_port::error::PortError; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; use crate::core::ics26_routing::context::{Module, ModuleId}; use crate::mock::context::MockIbcStore; From e3d2d334e17feecdded90310917fa6d986c8fc1a Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 03:48:35 +0800 Subject: [PATCH 31/43] Rename Ics23Error to CommitmentError --- crates/ibc/src/core/ics02_client/error.rs | 10 +-- .../core/ics02_client/msgs/upgrade_client.rs | 10 +-- .../src/core/ics23_commitment/commitment.rs | 10 +-- crates/ibc/src/core/ics23_commitment/error.rs | 8 +-- .../ibc/src/core/ics23_commitment/merkle.rs | 61 +++++++++++-------- 5 files changed, 54 insertions(+), 45 deletions(-) diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 70857023e..4a70d7826 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -4,7 +4,7 @@ use ibc_proto::protobuf::Error as TendermintProtoError; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::height::HeightError; -use crate::core::ics23_commitment::error::Error as Ics23Error; +use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics24_host::error::ValidationError; use crate::core::ics24_host::identifier::ClientId; use crate::signer::SignerError; @@ -94,11 +94,11 @@ pub enum ClientError { /// invalid address InvalidAddress, /// invalid proof for the upgraded client state - InvalidUpgradeClientProof(Ics23Error), + InvalidUpgradeClientProof(CommitmentError), /// invalid proof for the upgraded consensus state - InvalidUpgradeConsensusStateProof(Ics23Error), + InvalidUpgradeConsensusStateProof(CommitmentError), /// invalid commitment proof bytes - InvalidCommitmentProof(Ics23Error), + InvalidCommitmentProof(CommitmentError), /// invalid packet timeout timestamp value InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), /// mismatch between client and arguments types @@ -140,7 +140,7 @@ pub enum ClientError { /// failed to parse signer Signer(SignerError), /// ics23 verification failure - Ics23Verification(Ics23Error), + Ics23Verification(CommitmentError), /// client specific error: `{description}` ClientSpecific { description: String }, /// other error: `{description}` diff --git a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs index 27d35cb08..594af2edb 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -11,7 +11,7 @@ use ibc_proto::protobuf::Protobuf; use crate::core::ics02_client::error::ClientError; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; -use crate::core::ics23_commitment::error::Error as Ics23Error; +use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics24_host::identifier::ClientId; use crate::signer::Signer; use crate::tx_msg::Msg; @@ -94,11 +94,13 @@ impl TryFrom for MsgUpgradeClient { .consensus_state .ok_or(ClientError::MissingRawConsensusState)?; - let c_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client) - .map_err(|_| ClientError::InvalidUpgradeClientProof(Ics23Error::EmptyMerkleProof))?; + let c_bytes = + CommitmentProofBytes::try_from(proto_msg.proof_upgrade_client).map_err(|_| { + ClientError::InvalidUpgradeClientProof(CommitmentError::EmptyMerkleProof) + })?; let cs_bytes = CommitmentProofBytes::try_from(proto_msg.proof_upgrade_consensus_state) .map_err(|_| { - ClientError::InvalidUpgradeConsensusStateProof(Ics23Error::EmptyMerkleProof) + ClientError::InvalidUpgradeConsensusStateProof(CommitmentError::EmptyMerkleProof) })?; Ok(MsgUpgradeClient { diff --git a/crates/ibc/src/core/ics23_commitment/commitment.rs b/crates/ibc/src/core/ics23_commitment/commitment.rs index 8ff129d95..a74816f54 100644 --- a/crates/ibc/src/core/ics23_commitment/commitment.rs +++ b/crates/ibc/src/core/ics23_commitment/commitment.rs @@ -1,4 +1,4 @@ -use crate::core::ics23_commitment::error::Error; +use crate::core::ics23_commitment::error::CommitmentError; use crate::prelude::*; use crate::proofs::ProofError; @@ -99,12 +99,12 @@ impl TryFrom for CommitmentProofBytes { } impl TryFrom for RawMerkleProof { - type Error = Error; + type Error = CommitmentError; fn try_from(value: CommitmentProofBytes) -> Result { let value: Vec = value.into(); - let res: RawMerkleProof = - prost::Message::decode(value.as_ref()).map_err(Error::InvalidRawMerkleProof)?; + let res: RawMerkleProof = prost::Message::decode(value.as_ref()) + .map_err(CommitmentError::InvalidRawMerkleProof)?; Ok(res) } } @@ -125,7 +125,7 @@ impl CommitmentPrefix { } impl TryFrom> for CommitmentPrefix { - type Error = Error; + type Error = CommitmentError; fn try_from(bytes: Vec) -> Result { if bytes.is_empty() { diff --git a/crates/ibc/src/core/ics23_commitment/error.rs b/crates/ibc/src/core/ics23_commitment/error.rs index 2ff424de6..84913768e 100644 --- a/crates/ibc/src/core/ics23_commitment/error.rs +++ b/crates/ibc/src/core/ics23_commitment/error.rs @@ -2,7 +2,7 @@ use displaydoc::Display; use prost::DecodeError; #[derive(Debug, Display)] -pub enum Error { +pub enum CommitmentError { /// invalid raw merkle proof InvalidRawMerkleProof(DecodeError), /// failed to decode commitment proof @@ -26,11 +26,11 @@ pub enum Error { } #[cfg(feature = "std")] -impl std::error::Error for Error { +impl std::error::Error for CommitmentError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::InvalidRawMerkleProof(e) => Some(e), - Error::CommitmentProofDecodingFailed(e) => Some(e), + Self::InvalidRawMerkleProof(e) => Some(e), + Self::CommitmentProofDecodingFailed(e) => Some(e), _ => None, } } diff --git a/crates/ibc/src/core/ics23_commitment/merkle.rs b/crates/ibc/src/core/ics23_commitment/merkle.rs index 649251b80..7890a15ab 100644 --- a/crates/ibc/src/core/ics23_commitment/merkle.rs +++ b/crates/ibc/src/core/ics23_commitment/merkle.rs @@ -11,7 +11,7 @@ use ics23::{ }; use crate::core::ics23_commitment::commitment::{CommitmentPrefix, CommitmentRoot}; -use crate::core::ics23_commitment::error::Error; +use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics23_commitment::specs::ProofSpecs; pub fn apply_prefix(prefix: &CommitmentPrefix, mut path: Vec) -> MerklePath { @@ -75,24 +75,24 @@ impl MerkleProof { keys: MerklePath, value: Vec, start_index: usize, - ) -> Result<(), Error> { + ) -> Result<(), CommitmentError> { // validate arguments if self.proofs.is_empty() { - return Err(Error::EmptyMerkleProof); + return Err(CommitmentError::EmptyMerkleProof); } if root.hash.is_empty() { - return Err(Error::EmptyMerkleRoot); + return Err(CommitmentError::EmptyMerkleRoot); } let num = self.proofs.len(); let ics23_specs = Vec::::from(specs.clone()); if ics23_specs.len() != num { - return Err(Error::NumberOfSpecsMismatch); + return Err(CommitmentError::NumberOfSpecsMismatch); } if keys.key_path.len() != num { - return Err(Error::NumberOfKeysMismatch); + return Err(CommitmentError::NumberOfKeysMismatch); } if value.is_empty() { - return Err(Error::EmptyVerifiedValue); + return Err(CommitmentError::EmptyVerifiedValue); } let mut subroot = value.clone(); @@ -109,7 +109,7 @@ impl MerkleProof { Some(Proof::Exist(existence_proof)) => { subroot = calculate_existence_root::(existence_proof) - .map_err(|_| Error::InvalidMerkleProof)?; + .map_err(|_| CommitmentError::InvalidMerkleProof)?; if !verify_membership::( proof, @@ -118,16 +118,16 @@ impl MerkleProof { key.as_bytes(), &value, ) { - return Err(Error::VerificationFailure); + return Err(CommitmentError::VerificationFailure); } value = subroot.clone(); } - _ => return Err(Error::InvalidMerkleProof), + _ => return Err(CommitmentError::InvalidMerkleProof), } } if root.hash != subroot { - return Err(Error::VerificationFailure); + return Err(CommitmentError::VerificationFailure); } Ok(()) @@ -138,31 +138,36 @@ impl MerkleProof { specs: &ProofSpecs, root: MerkleRoot, keys: MerklePath, - ) -> Result<(), Error> { + ) -> Result<(), CommitmentError> { // validate arguments if self.proofs.is_empty() { - return Err(Error::EmptyMerkleProof); + return Err(CommitmentError::EmptyMerkleProof); } if root.hash.is_empty() { - return Err(Error::EmptyMerkleRoot); + return Err(CommitmentError::EmptyMerkleRoot); } let num = self.proofs.len(); let ics23_specs = Vec::::from(specs.clone()); if ics23_specs.len() != num { - return Err(Error::NumberOfSpecsMismatch); + return Err(CommitmentError::NumberOfSpecsMismatch); } if keys.key_path.len() != num { - return Err(Error::NumberOfKeysMismatch); + return Err(CommitmentError::NumberOfKeysMismatch); } // verify the absence of key in lowest subtree - let proof = self.proofs.get(0).ok_or(Error::InvalidMerkleProof)?; - let spec = ics23_specs.get(0).ok_or(Error::InvalidMerkleProof)?; + let proof = self + .proofs + .get(0) + .ok_or(CommitmentError::InvalidMerkleProof)?; + let spec = ics23_specs + .get(0) + .ok_or(CommitmentError::InvalidMerkleProof)?; // keys are represented from root-to-leaf let key = keys .key_path .get(num - 1) - .ok_or(Error::InvalidMerkleProof)?; + .ok_or(CommitmentError::InvalidMerkleProof)?; match &proof.proof { Some(Proof::Nonexist(non_existence_proof)) => { let subroot = calculate_non_existence_root(non_existence_proof)?; @@ -173,27 +178,27 @@ impl MerkleProof { &subroot, key.as_bytes(), ) { - return Err(Error::VerificationFailure); + return Err(CommitmentError::VerificationFailure); } // verify membership proofs starting from index 1 with value = subroot self.verify_membership(specs, root, keys, subroot, 1) } - _ => Err(Error::InvalidMerkleProof), + _ => Err(CommitmentError::InvalidMerkleProof), } } } // TODO move to ics23 -fn calculate_non_existence_root(proof: &NonExistenceProof) -> Result, Error> { +fn calculate_non_existence_root(proof: &NonExistenceProof) -> Result, CommitmentError> { if let Some(left) = &proof.left { calculate_existence_root::(left) - .map_err(|_| Error::InvalidMerkleProof) + .map_err(|_| CommitmentError::InvalidMerkleProof) } else if let Some(right) = &proof.right { calculate_existence_root::(right) - .map_err(|_| Error::InvalidMerkleProof) + .map_err(|_| CommitmentError::InvalidMerkleProof) } else { - Err(Error::InvalidMerkleProof) + Err(CommitmentError::InvalidMerkleProof) } } @@ -249,13 +254,15 @@ fn calculate_non_existence_root(proof: &NonExistenceProof) -> Result, Er // } // } -pub fn convert_tm_to_ics_merkle_proof(tm_proof: &TendermintProof) -> Result { +pub fn convert_tm_to_ics_merkle_proof( + tm_proof: &TendermintProof, +) -> Result { let mut proofs = Vec::new(); for op in &tm_proof.ops { let mut parsed = ibc_proto::ics23::CommitmentProof { proof: None }; prost::Message::merge(&mut parsed, op.data.as_slice()) - .map_err(Error::CommitmentProofDecodingFailed)?; + .map_err(CommitmentError::CommitmentProofDecodingFailed)?; proofs.push(parsed); } From 0979e1f8f1201dab266d7ddee96745ee702a4be6 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 03:53:32 +0800 Subject: [PATCH 32/43] Rename Ics26Error to RouterError --- crates/ibc/src/core/context.rs | 2 +- crates/ibc/src/core/ics26_routing/error.rs | 16 ++++---- crates/ibc/src/core/ics26_routing/handler.rs | 36 ++++++++--------- crates/ibc/src/core/ics26_routing/msgs.rs | 40 +++++++++---------- crates/ibc/src/relayer/ics18_relayer/error.rs | 17 ++++++-- 5 files changed, 61 insertions(+), 50 deletions(-) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 41ccfc867..86e966d0b 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -3,7 +3,7 @@ use core::time::Duration; use crate::events::IbcEvent; use crate::{prelude::*, timestamp::Timestamp, Height}; -use crate::core::ics26_routing::error::Error as RouterError; +use crate::core::ics26_routing::error::RouterError; use ibc_proto::google::protobuf::Any; diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index c8bb6c707..8299f2522 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -6,7 +6,7 @@ use crate::core::ics04_channel; use displaydoc::Display; #[derive(Debug, Display)] -pub enum Error { +pub enum RouterError { /// ICS02 client error Client(ics02_client::error::ClientError), /// ICS03 connection error @@ -22,15 +22,15 @@ pub enum Error { } #[cfg(feature = "std")] -impl std::error::Error for Error { +impl std::error::Error for RouterError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::Client(e) => Some(e), - Error::Connection(e) => Some(e), - Error::Channel(e) => Some(e), - Error::UnknownMessageTypeUrl { .. } => None, - Error::MalformedMessageBytes(e) => Some(e), - Error::Packet(e) => Some(e), + Self::Client(e) => Some(e), + Self::Connection(e) => Some(e), + Self::Channel(e) => Some(e), + Self::UnknownMessageTypeUrl { .. } => None, + Self::MalformedMessageBytes(e) => Some(e), + Self::Packet(e) => Some(e), } } } diff --git a/crates/ibc/src/core/ics26_routing/handler.rs b/crates/ibc/src/core/ics26_routing/handler.rs index f6784f8b0..d63c2ad9d 100644 --- a/crates/ibc/src/core/ics26_routing/handler.rs +++ b/crates/ibc/src/core/ics26_routing/handler.rs @@ -14,7 +14,7 @@ use crate::core::ics04_channel::handler::{ }; use crate::core::ics04_channel::packet::PacketResult; use crate::core::ics26_routing::context::RouterContext; -use crate::core::ics26_routing::error::Error; +use crate::core::ics26_routing::error::RouterError; use crate::core::ics26_routing::msgs::MsgEnvelope::{ self, ChannelMsg, ClientMsg, ConnectionMsg, PacketMsg, }; @@ -30,7 +30,7 @@ pub struct MsgReceipt { /// Mimics the DeliverTx ABCI interface, but for a single message and at a slightly lower level. /// No need for authentication info or signature checks here. /// Returns a vector of all events that got generated as a byproduct of processing `message`. -pub fn deliver(ctx: &mut Ctx, message: Any) -> Result +pub fn deliver(ctx: &mut Ctx, message: Any) -> Result where Ctx: RouterContext, { @@ -44,7 +44,7 @@ where } /// Attempts to convert a message into a [MsgEnvelope] message -pub fn decode(message: Any) -> Result { +pub fn decode(message: Any) -> Result { message.try_into() } @@ -53,17 +53,17 @@ pub fn decode(message: Any) -> Result { /// and events produced after processing the input `msg`. /// If this method returns an error, the runtime is expected to rollback all state modifications to /// the `Ctx` caused by all messages from the transaction that this `msg` is a part of. -pub fn dispatch(ctx: &mut Ctx, msg: MsgEnvelope) -> Result, Error> +pub fn dispatch(ctx: &mut Ctx, msg: MsgEnvelope) -> Result, RouterError> where Ctx: RouterContext, { let output = match msg { ClientMsg(msg) => { - let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(Error::Client)?; + let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(RouterError::Client)?; // Apply the result to the context (host chain store). ctx.store_client_result(handler_output.result) - .map_err(Error::Client)?; + .map_err(RouterError::Client)?; HandlerOutput::builder() .with_log(handler_output.log) @@ -72,11 +72,11 @@ where } ConnectionMsg(msg) => { - let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(Error::Connection)?; + let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(RouterError::Connection)?; // Apply any results to the host chain store. ctx.store_connection_result(handler_output.result) - .map_err(Error::Connection)?; + .map_err(RouterError::Connection)?; HandlerOutput::builder() .with_log(handler_output.log) @@ -85,18 +85,18 @@ where } ChannelMsg(msg) => { - let module_id = channel_validate(ctx, &msg).map_err(Error::Channel)?; + let module_id = channel_validate(ctx, &msg).map_err(RouterError::Channel)?; let dispatch_output = HandlerOutputBuilder::<()>::new(); let (dispatch_log, mut channel_result) = - channel_dispatch(ctx, &msg).map_err(Error::Channel)?; + channel_dispatch(ctx, &msg).map_err(RouterError::Channel)?; // Note: `OpenInit` and `OpenTry` modify the `version` field of the `channel_result`, // so we must pass it mutably. We intend to clean this up with the implementation of // ADR 5. // See issue [#190](https://github.com/cosmos/ibc-rs/issues/190) let callback_extras = channel_callback(ctx, &module_id, &msg, &mut channel_result) - .map_err(Error::Channel)?; + .map_err(RouterError::Channel)?; // We need to construct events here instead of directly in the // `process` functions because we need to wait for the callback to @@ -111,7 +111,7 @@ where // Apply any results to the host chain store. ctx.store_channel_result(channel_result) - .map_err(Error::Packet)?; + .map_err(RouterError::Packet)?; dispatch_output .with_events(dispatch_events) @@ -128,20 +128,20 @@ where } PacketMsg(msg) => { - let module_id = get_module_for_packet_msg(ctx, &msg).map_err(Error::Channel)?; + let module_id = get_module_for_packet_msg(ctx, &msg).map_err(RouterError::Channel)?; let (mut handler_builder, packet_result) = - ics4_packet_msg_dispatcher(ctx, &msg).map_err(Error::Packet)?; + ics4_packet_msg_dispatcher(ctx, &msg).map_err(RouterError::Packet)?; if matches!(packet_result, PacketResult::Recv(RecvPacketResult::NoOp)) { return Ok(handler_builder.with_result(())); } let cb_result = ics4_packet_callback(ctx, &module_id, &msg, &mut handler_builder); - cb_result.map_err(Error::Packet)?; + cb_result.map_err(RouterError::Packet)?; // Apply any results to the host chain store. ctx.store_packet_result(packet_result) - .map_err(Error::Packet)?; + .map_err(RouterError::Packet)?; handler_builder.with_result(()) } @@ -203,7 +203,7 @@ mod tests { use crate::core::ics23_commitment::commitment::CommitmentPrefix; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; use crate::core::ics26_routing::context::{ModuleId, Router, RouterBuilder, RouterContext}; - use crate::core::ics26_routing::error::Error; + use crate::core::ics26_routing::error::RouterError; use crate::core::ics26_routing::handler::dispatch; use crate::core::ics26_routing::msgs::MsgEnvelope; use crate::events::IbcEvent; @@ -632,7 +632,7 @@ mod tests { msg, ) .map(|_| ()) - .map_err(Error::Channel) + .map_err(RouterError::Channel) } }; diff --git a/crates/ibc/src/core/ics26_routing/msgs.rs b/crates/ibc/src/core/ics26_routing/msgs.rs index 008757c3e..7d0142dcb 100644 --- a/crates/ibc/src/core/ics26_routing/msgs.rs +++ b/crates/ibc/src/core/ics26_routing/msgs.rs @@ -10,7 +10,7 @@ use crate::core::ics04_channel::msgs::{ acknowledgement, chan_close_confirm, chan_close_init, chan_open_ack, chan_open_confirm, chan_open_init, chan_open_try, recv_packet, timeout, timeout_on_close, ChannelMsg, PacketMsg, }; -use crate::core::ics26_routing::error::Error; +use crate::core::ics26_routing::error::RouterError; use ibc_proto::protobuf::Protobuf; /// Enumeration of all messages that the local ICS26 module is capable of routing. @@ -23,7 +23,7 @@ pub enum MsgEnvelope { } impl TryFrom for MsgEnvelope { - type Error = Error; + type Error = RouterError; fn try_from(any_msg: Any) -> Result { match any_msg.type_url.as_str() { @@ -31,38 +31,38 @@ impl TryFrom for MsgEnvelope { create_client::TYPE_URL => { // Pop out the message and then wrap it in the corresponding type. let domain_msg = create_client::MsgCreateClient::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ClientMsg(ClientMsg::CreateClient(domain_msg))) } update_client::TYPE_URL => { let domain_msg = update_client::MsgUpdateClient::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ClientMsg(ClientMsg::UpdateClient(domain_msg))) } upgrade_client::TYPE_URL => { let domain_msg = upgrade_client::MsgUpgradeClient::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ClientMsg(ClientMsg::UpgradeClient(domain_msg))) } // ICS03 conn_open_init::TYPE_URL => { let domain_msg = conn_open_init::MsgConnectionOpenInit::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenInit(domain_msg), )) } conn_open_try::TYPE_URL => { let domain_msg = conn_open_try::MsgConnectionOpenTry::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenTry(Box::new(domain_msg)), )) } conn_open_ack::TYPE_URL => { let domain_msg = conn_open_ack::MsgConnectionOpenAck::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenAck(Box::new(domain_msg)), )) @@ -70,7 +70,7 @@ impl TryFrom for MsgEnvelope { conn_open_confirm::TYPE_URL => { let domain_msg = conn_open_confirm::MsgConnectionOpenConfirm::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ConnectionMsg( ConnectionMsg::ConnectionOpenConfirm(domain_msg), )) @@ -79,21 +79,21 @@ impl TryFrom for MsgEnvelope { // ICS04 channel messages chan_open_init::TYPE_URL => { let domain_msg = chan_open_init::MsgChannelOpenInit::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenInit( domain_msg, ))) } chan_open_try::TYPE_URL => { let domain_msg = chan_open_try::MsgChannelOpenTry::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenTry( domain_msg, ))) } chan_open_ack::TYPE_URL => { let domain_msg = chan_open_ack::MsgChannelOpenAck::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenAck( domain_msg, ))) @@ -101,14 +101,14 @@ impl TryFrom for MsgEnvelope { chan_open_confirm::TYPE_URL => { let domain_msg = chan_open_confirm::MsgChannelOpenConfirm::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelOpenConfirm( domain_msg, ))) } chan_close_init::TYPE_URL => { let domain_msg = chan_close_init::MsgChannelCloseInit::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelCloseInit( domain_msg, ))) @@ -116,7 +116,7 @@ impl TryFrom for MsgEnvelope { chan_close_confirm::TYPE_URL => { let domain_msg = chan_close_confirm::MsgChannelCloseConfirm::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::ChannelMsg(ChannelMsg::ChannelCloseConfirm( domain_msg, ))) @@ -124,27 +124,27 @@ impl TryFrom for MsgEnvelope { // ICS04 packet messages recv_packet::TYPE_URL => { let domain_msg = recv_packet::MsgRecvPacket::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::RecvPacket(domain_msg))) } acknowledgement::TYPE_URL => { let domain_msg = acknowledgement::MsgAcknowledgement::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::AckPacket(domain_msg))) } timeout::TYPE_URL => { let domain_msg = timeout::MsgTimeout::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::TimeoutPacket(domain_msg))) } timeout_on_close::TYPE_URL => { let domain_msg = timeout_on_close::MsgTimeoutOnClose::decode_vec(&any_msg.value) - .map_err(Error::MalformedMessageBytes)?; + .map_err(RouterError::MalformedMessageBytes)?; Ok(MsgEnvelope::PacketMsg(PacketMsg::TimeoutOnClosePacket( domain_msg, ))) } - _ => Err(Error::UnknownMessageTypeUrl { + _ => Err(RouterError::UnknownMessageTypeUrl { url: any_msg.type_url, }), } diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index 61cb3a3f0..e44075821 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -1,6 +1,6 @@ use crate::core::ics03_connection; use crate::core::ics24_host::identifier::ClientId; -use crate::core::ics26_routing::error::Error as RoutingError; +use crate::core::ics26_routing::error::RouterError; use crate::Height; use displaydoc::Display; @@ -20,8 +20,19 @@ pub enum Error { source_height: Height, destination_height: Height, }, - /// transaction processing by modules failed, error(`{0}`) - TransactionFailed(RoutingError), + /// transaction processing by modules failed + TransactionFailed(RouterError), /// ics03 connection error(`{0}`) Ics03(ics03_connection::error::ConnectionError), } + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Error::TransactionFailed(e) => Some(e), + Error::Ics03(e) => Some(e), + _ => None, + } + } +} From 29e2336469254a95f42400cfcaa87d845f59bfaf Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 03:56:37 +0800 Subject: [PATCH 33/43] Rename Ics18Error to RelayerError --- crates/ibc/src/mock/context.rs | 14 +++++++------- .../ibc/src/relayer/ics18_relayer/context.rs | 6 +++--- crates/ibc/src/relayer/ics18_relayer/error.rs | 12 ++++++------ crates/ibc/src/relayer/ics18_relayer/utils.rs | 18 +++++++++--------- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index c1c2e056e..410ca763e 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -47,7 +47,7 @@ use crate::mock::consensus_state::MockConsensusState; use crate::mock::header::MockHeader; use crate::mock::host::{HostBlock, HostType}; use crate::relayer::ics18_relayer::context::RelayerContext; -use crate::relayer::ics18_relayer::error::Error as Ics18Error; +use crate::relayer::ics18_relayer::error::RelayerError; use crate::signer::Signer; use crate::timestamp::Timestamp; use crate::Height; @@ -465,8 +465,8 @@ impl MockContext { /// 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 a Ics18Error. - pub fn deliver(&mut self, msg: MsgEnvelope) -> Result<(), Ics18Error> { - dispatch(self, msg).map_err(Ics18Error::TransactionFailed)?; + pub fn deliver(&mut self, msg: MsgEnvelope) -> Result<(), RelayerError> { + dispatch(self, msg).map_err(RelayerError::TransactionFailed)?; // Create a new block. self.advance_host_chain_height(); Ok(()) @@ -1432,8 +1432,8 @@ impl ClientKeeper for MockContext { } impl RelayerContext for MockContext { - fn query_latest_height(&self) -> Result { - self.host_current_height().map_err(Ics18Error::Ics03) + fn query_latest_height(&self) -> Result { + self.host_current_height().map_err(RelayerError::Connection) } fn query_client_full_state(&self, client_id: &ClientId) -> Option> { @@ -1446,12 +1446,12 @@ impl RelayerContext for MockContext { block_ref.cloned().map(Header::into_box) } - fn send(&mut self, msgs: Vec) -> Result, Ics18Error> { + fn send(&mut self, msgs: Vec) -> Result, RelayerError> { // Forward call to Ics26 delivery method. let mut all_events = vec![]; for msg in msgs { let MsgReceipt { mut events, .. } = - deliver(self, msg).map_err(Ics18Error::TransactionFailed)?; + deliver(self, msg).map_err(RelayerError::TransactionFailed)?; all_events.append(&mut events); } self.advance_host_chain_height(); // Advance chain height diff --git a/crates/ibc/src/relayer/ics18_relayer/context.rs b/crates/ibc/src/relayer/ics18_relayer/context.rs index 9b4bf375d..111af1845 100644 --- a/crates/ibc/src/relayer/ics18_relayer/context.rs +++ b/crates/ibc/src/relayer/ics18_relayer/context.rs @@ -6,7 +6,7 @@ use crate::core::ics02_client::header::Header; use crate::events::IbcEvent; use crate::core::ics24_host::identifier::ClientId; -use crate::relayer::ics18_relayer::error::Error; +use crate::relayer::ics18_relayer::error::RelayerError; use crate::signer::Signer; use crate::Height; @@ -17,7 +17,7 @@ use crate::Height; /// types, light client, RPC client, etc.) pub trait RelayerContext { /// Returns the latest height of the chain. - fn query_latest_height(&self) -> Result; + fn query_latest_height(&self) -> Result; /// Returns this client state for the given `client_id` on this chain. /// Wrapper over the `/abci_query?path=..` endpoint. @@ -28,7 +28,7 @@ pub trait RelayerContext { /// Interface that the relayer uses to submit a datagram to this chain. /// One can think of this as wrapping around the `/broadcast_tx_commit` ABCI endpoint. - fn send(&mut self, msgs: Vec) -> Result, Error>; + fn send(&mut self, msgs: Vec) -> Result, RelayerError>; /// Temporary solution. Similar to `CosmosSDKChain::key_and_signer()` but simpler. fn signer(&self) -> Signer; diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index e44075821..9a443afe4 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -5,7 +5,7 @@ use crate::Height; use displaydoc::Display; #[derive(Debug, Display)] -pub enum Error { +pub enum RelayerError { /// client state on destination chain not found, (client id: `{client_id}`) ClientStateNotFound { client_id: ClientId }, /// the client on destination chain is already up-to-date (client id: `{client_id}`, source height: `{source_height}`, dest height: `{destination_height}`) @@ -22,16 +22,16 @@ pub enum Error { }, /// transaction processing by modules failed TransactionFailed(RouterError), - /// ics03 connection error(`{0}`) - Ics03(ics03_connection::error::ConnectionError), + /// ICS03 connection error(`{0}`) + Connection(ics03_connection::error::ConnectionError), } #[cfg(feature = "std")] -impl std::error::Error for Error { +impl std::error::Error for RelayerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::TransactionFailed(e) => Some(e), - Error::Ics03(e) => Some(e), + Self::TransactionFailed(e) => Some(e), + Self::Connection(e) => Some(e), _ => None, } } diff --git a/crates/ibc/src/relayer/ics18_relayer/utils.rs b/crates/ibc/src/relayer/ics18_relayer/utils.rs index 69ea5144a..52c47c513 100644 --- a/crates/ibc/src/relayer/ics18_relayer/utils.rs +++ b/crates/ibc/src/relayer/ics18_relayer/utils.rs @@ -3,7 +3,7 @@ use crate::core::ics02_client::msgs::update_client::MsgUpdateClient; use crate::core::ics02_client::msgs::ClientMsg; use crate::core::ics24_host::identifier::ClientId; use crate::relayer::ics18_relayer::context::RelayerContext; -use crate::relayer::ics18_relayer::error::Error; +use crate::relayer::ics18_relayer::error::RelayerError; /// Builds a `ClientMsg::UpdateClient` for a client with id `client_id` running on the `dest` /// context, assuming that the latest header on the source context is `src_header`. @@ -11,22 +11,22 @@ pub fn build_client_update_datagram( dest: &Ctx, client_id: &ClientId, src_header: &dyn Header, -) -> Result +) -> Result where Ctx: RelayerContext, { // Check if client for ibc0 on ibc1 has been updated to latest height: // - query client state on destination chain - let dest_client_state = - dest.query_client_full_state(client_id) - .ok_or_else(|| Error::ClientStateNotFound { - client_id: client_id.clone(), - })?; + let dest_client_state = dest.query_client_full_state(client_id).ok_or_else(|| { + RelayerError::ClientStateNotFound { + client_id: client_id.clone(), + } + })?; let dest_client_latest_height = dest_client_state.latest_height(); if src_header.height() == dest_client_latest_height { - return Err(Error::ClientAlreadyUpToDate { + return Err(RelayerError::ClientAlreadyUpToDate { client_id: client_id.clone(), source_height: src_header.height(), destination_height: dest_client_latest_height, @@ -34,7 +34,7 @@ where }; if dest_client_latest_height > src_header.height() { - return Err(Error::ClientAtHigherHeight { + return Err(RelayerError::ClientAtHigherHeight { client_id: client_id.clone(), source_height: src_header.height(), destination_height: dest_client_latest_height, From 00ef21722bdc5c1b831de7ed81942a71c4e2b740 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 04:09:59 +0800 Subject: [PATCH 34/43] Rename Ics20Error to TokenTransferError --- .../applications/transfer/acknowledgement.rs | 4 +- .../ibc/src/applications/transfer/amount.rs | 6 +- crates/ibc/src/applications/transfer/coin.rs | 37 +++++----- .../ibc/src/applications/transfer/context.rs | 54 +++++++-------- crates/ibc/src/applications/transfer/denom.rs | 38 ++++++----- crates/ibc/src/applications/transfer/error.rs | 68 +++++++++---------- .../applications/transfer/msgs/transfer.rs | 48 ++++++------- .../ibc/src/applications/transfer/packet.rs | 14 ++-- crates/ibc/src/applications/transfer/relay.rs | 6 +- .../transfer/relay/on_ack_packet.rs | 4 +- .../transfer/relay/on_recv_packet.rs | 8 +-- .../transfer/relay/on_timeout_packet.rs | 4 +- .../transfer/relay/send_transfer.rs | 23 ++++--- crates/ibc/src/test_utils.rs | 12 ++-- 14 files changed, 170 insertions(+), 156 deletions(-) diff --git a/crates/ibc/src/applications/transfer/acknowledgement.rs b/crates/ibc/src/applications/transfer/acknowledgement.rs index a7a19b5ed..b17cfd826 100644 --- a/crates/ibc/src/applications/transfer/acknowledgement.rs +++ b/crates/ibc/src/applications/transfer/acknowledgement.rs @@ -2,7 +2,7 @@ use core::fmt::{Display, Error as FmtError, Formatter}; use serde::{Deserialize, Serialize}; -use super::error::Error; +use super::error::TokenTransferError; use crate::core::ics26_routing::context::Acknowledgement as AckTrait; use crate::prelude::*; @@ -36,7 +36,7 @@ impl Acknowledgement { Self::Success(ConstAckSuccess::Success) } - pub fn from_error(err: Error) -> Self { + pub fn from_error(err: TokenTransferError) -> Self { Self::Error(format!("{}: {}", ACK_ERR_STR, err)) } } diff --git a/crates/ibc/src/applications/transfer/amount.rs b/crates/ibc/src/applications/transfer/amount.rs index 06fdbeb0d..674ee266c 100644 --- a/crates/ibc/src/applications/transfer/amount.rs +++ b/crates/ibc/src/applications/transfer/amount.rs @@ -2,7 +2,7 @@ use core::str::FromStr; use derive_more::{Display, From, Into}; use serde::{Deserialize, Serialize}; -use super::error::Error; +use super::error::TokenTransferError; use crate::bigint::U256; /// A type for representing token transfer amounts. @@ -22,10 +22,10 @@ impl Amount { } impl FromStr for Amount { - type Err = Error; + type Err = TokenTransferError; fn from_str(s: &str) -> Result { - let amount = U256::from_dec_str(s).map_err(Error::InvalidAmount)?; + let amount = U256::from_dec_str(s).map_err(TokenTransferError::InvalidAmount)?; Ok(Self(amount)) } } diff --git a/crates/ibc/src/applications/transfer/coin.rs b/crates/ibc/src/applications/transfer/coin.rs index 4de581d86..b6e9441e1 100644 --- a/crates/ibc/src/applications/transfer/coin.rs +++ b/crates/ibc/src/applications/transfer/coin.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use super::amount::Amount; use super::denom::{BaseDenom, PrefixedDenom}; -use super::error::Error; +use super::error::TokenTransferError; use crate::prelude::*; use crate::serializers::serde_string; @@ -30,38 +30,39 @@ pub struct Coin { impl Coin where - D::Err: Into, + D::Err: Into, { - pub fn from_string_list(coin_str: &str) -> Result, Error> { + pub fn from_string_list(coin_str: &str) -> Result, TokenTransferError> { coin_str.split(',').map(FromStr::from_str).collect() } } impl FromStr for Coin where - D::Err: Into, + D::Err: Into, { - type Err = Error; + type Err = TokenTransferError; #[allow(clippy::assign_op_pattern)] - fn from_str(coin_str: &str) -> Result { + fn from_str(coin_str: &str) -> Result { // Denominations can be 3 ~ 128 characters long and support letters, followed by either // a letter, a number or a separator ('/', ':', '.', '_' or '-'). // Loosely copy the regex from here: // https://github.com/cosmos/cosmos-sdk/blob/v0.45.5/types/coin.go#L760-L762 let matcher = regex!(br"([0-9]+)([a-zA-Z0-9/:\\._\x2d]+)"); - let (m1, m2) = - matcher - .match_slices(coin_str.as_bytes()) - .ok_or_else(|| Error::InvalidCoin { - coin: coin_str.to_string(), - })?; + let (m1, m2) = matcher.match_slices(coin_str.as_bytes()).ok_or_else(|| { + TokenTransferError::InvalidCoin { + coin: coin_str.to_string(), + } + })?; - let amount = from_utf8(m1).map_err(Error::Utf8Decode)?.parse()?; + let amount = from_utf8(m1) + .map_err(TokenTransferError::Utf8Decode)? + .parse()?; let denom = from_utf8(m2) - .map_err(Error::Utf8Decode)? + .map_err(TokenTransferError::Utf8Decode)? .parse() .map_err(Into::into)?; @@ -71,9 +72,9 @@ where impl TryFrom for Coin where - D::Err: Into, + D::Err: Into, { - type Error = Error; + type Error = TokenTransferError; fn try_from(proto: ProtoCoin) -> Result, Self::Error> { let denom = D::from_str(&proto.denom).map_err(Into::into)?; @@ -111,7 +112,7 @@ mod tests { use super::*; #[test] - fn test_parse_raw_coin() -> Result<(), Error> { + fn test_parse_raw_coin() -> Result<(), TokenTransferError> { { let coin = RawCoin::from_str("123stake")?; assert_eq!(coin.denom, "stake"); @@ -140,7 +141,7 @@ mod tests { } #[test] - fn test_parse_raw_coin_list() -> Result<(), Error> { + fn test_parse_raw_coin_list() -> Result<(), TokenTransferError> { { let coins = RawCoin::from_string_list("123stake,1a1,999den0m")?; assert_eq!(coins.len(), 3); diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index b71d2aafa..3deec331d 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -1,6 +1,6 @@ use sha2::{Digest, Sha256}; -use super::error::Error as Ics20Error; +use super::error::TokenTransferError; use crate::applications::transfer::acknowledgement::Acknowledgement; use crate::applications::transfer::events::{AckEvent, AckStatusEvent, RecvEvent, TimeoutEvent}; use crate::applications::transfer::packet::PacketData; @@ -59,14 +59,14 @@ pub trait TokenTransferReader: SendPacketReader { type AccountId: TryFrom; /// get_port returns the portID for the transfer module. - fn get_port(&self) -> Result; + fn get_port(&self) -> Result; /// Returns the escrow account id for a port and channel combination fn get_channel_escrow_address( &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result<::AccountId, Ics20Error>; + ) -> Result<::AccountId, TokenTransferError>; /// Returns true iff send is enabled. fn is_send_enabled(&self) -> bool; @@ -128,21 +128,21 @@ pub trait BankKeeper { from: &Self::AccountId, to: &Self::AccountId, amt: &PrefixedCoin, - ) -> Result<(), Ics20Error>; + ) -> Result<(), TokenTransferError>; /// This function to enable minting ibc tokens to a user account fn mint_coins( &mut self, account: &Self::AccountId, amt: &PrefixedCoin, - ) -> Result<(), Ics20Error>; + ) -> Result<(), TokenTransferError>; /// This function should enable burning of minted tokens in a user account fn burn_coins( &mut self, account: &Self::AccountId, amt: &PrefixedCoin, - ) -> Result<(), Ics20Error>; + ) -> Result<(), TokenTransferError>; } /// Captures all the dependencies which the ICS20 module requires to be able to dispatch and @@ -163,23 +163,23 @@ pub fn on_chan_open_init( _channel_id: &ChannelId, _counterparty: &Counterparty, version: &Version, -) -> Result<(ModuleExtras, Version), Ics20Error> { +) -> Result<(ModuleExtras, Version), TokenTransferError> { if order != Order::Unordered { - return Err(Ics20Error::ChannelNotUnordered { + return Err(TokenTransferError::ChannelNotUnordered { expect_order: Order::Unordered, got_order: order, }); } let bound_port = ctx.get_port()?; if port_id != &bound_port { - return Err(Ics20Error::InvalidPort { + return Err(TokenTransferError::InvalidPort { port_id: port_id.clone(), exp_port_id: bound_port, }); } if !version.is_empty() && version != &Version::ics20() { - return Err(Ics20Error::InvalidVersion { + return Err(TokenTransferError::InvalidVersion { expect_version: Version::ics20(), got_version: version.clone(), }); @@ -197,15 +197,15 @@ pub fn on_chan_open_try( _channel_id: &ChannelId, _counterparty: &Counterparty, counterparty_version: &Version, -) -> Result<(ModuleExtras, Version), Ics20Error> { +) -> Result<(ModuleExtras, Version), TokenTransferError> { if order != Order::Unordered { - return Err(Ics20Error::ChannelNotUnordered { + return Err(TokenTransferError::ChannelNotUnordered { expect_order: Order::Unordered, got_order: order, }); } if counterparty_version != &Version::ics20() { - return Err(Ics20Error::InvalidCounterpartyVersion { + return Err(TokenTransferError::InvalidCounterpartyVersion { expect_version: Version::ics20(), got_version: counterparty_version.clone(), }); @@ -219,9 +219,9 @@ pub fn on_chan_open_ack( _port_id: &PortId, _channel_id: &ChannelId, counterparty_version: &Version, -) -> Result { +) -> Result { if counterparty_version != &Version::ics20() { - return Err(Ics20Error::InvalidCounterpartyVersion { + return Err(TokenTransferError::InvalidCounterpartyVersion { expect_version: Version::ics20(), got_version: counterparty_version.clone(), }); @@ -234,7 +234,7 @@ pub fn on_chan_open_confirm( _ctx: &mut impl TokenTransferContext, _port_id: &PortId, _channel_id: &ChannelId, -) -> Result { +) -> Result { Ok(ModuleExtras::empty()) } @@ -242,15 +242,15 @@ pub fn on_chan_close_init( _ctx: &mut impl TokenTransferContext, _port_id: &PortId, _channel_id: &ChannelId, -) -> Result { - Err(Ics20Error::CantCloseChannel) +) -> Result { + Err(TokenTransferError::CantCloseChannel) } pub fn on_chan_close_confirm( _ctx: &mut impl TokenTransferContext, _port_id: &PortId, _channel_id: &ChannelId, -) -> Result { +) -> Result { Ok(ModuleExtras::empty()) } @@ -264,7 +264,7 @@ pub fn on_recv_packet( Ok(data) => data, Err(_) => { return OnRecvPacketAck::Failed(Box::new(Acknowledgement::Error( - Ics20Error::PacketDataDeserialization.to_string(), + TokenTransferError::PacketDataDeserialization.to_string(), ))); } }; @@ -291,12 +291,12 @@ pub fn on_acknowledgement_packet( packet: &Packet, acknowledgement: &GenericAcknowledgement, _relayer: &Signer, -) -> Result<(), Ics20Error> { +) -> Result<(), TokenTransferError> { let data = serde_json::from_slice::(&packet.data) - .map_err(|_| Ics20Error::PacketDataDeserialization)?; + .map_err(|_| TokenTransferError::PacketDataDeserialization)?; let acknowledgement = serde_json::from_slice::(acknowledgement.as_ref()) - .map_err(|_| Ics20Error::AckDeserialization)?; + .map_err(|_| TokenTransferError::AckDeserialization)?; process_ack_packet(ctx, packet, &data, &acknowledgement)?; @@ -317,9 +317,9 @@ pub fn on_timeout_packet( output: &mut ModuleOutputBuilder, packet: &Packet, _relayer: &Signer, -) -> Result<(), Ics20Error> { +) -> Result<(), TokenTransferError> { let data = serde_json::from_slice::(&packet.data) - .map_err(|_| Ics20Error::PacketDataDeserialization)?; + .map_err(|_| TokenTransferError::PacketDataDeserialization)?; process_timeout_packet(ctx, packet, &data)?; @@ -338,7 +338,7 @@ pub(crate) mod test { use subtle_encoding::bech32; use crate::applications::transfer::context::{cosmos_adr028_escrow_address, on_chan_open_try}; - use crate::applications::transfer::error::Error as Ics20Error; + use crate::applications::transfer::error::TokenTransferError; use crate::applications::transfer::msgs::transfer::MsgTransfer; use crate::applications::transfer::relay::send_transfer::send_transfer; use crate::applications::transfer::PrefixedCoin; @@ -357,7 +357,7 @@ pub(crate) mod test { output: &mut HandlerOutputBuilder<()>, msg: MsgTransfer, ) -> Result<(), ChannelError> { - send_transfer(ctx, output, msg).map_err(|e: Ics20Error| ChannelError::AppModule { + send_transfer(ctx, output, msg).map_err(|e: TokenTransferError| ChannelError::AppModule { description: e.to_string(), }) } diff --git a/crates/ibc/src/applications/transfer/denom.rs b/crates/ibc/src/applications/transfer/denom.rs index 148795eac..c90bf38c5 100644 --- a/crates/ibc/src/applications/transfer/denom.rs +++ b/crates/ibc/src/applications/transfer/denom.rs @@ -5,7 +5,7 @@ use derive_more::{Display, From}; use ibc_proto::ibc::applications::transfer::v1::DenomTrace as RawDenomTrace; use serde::{Deserialize, Serialize}; -use super::error::Error; +use super::error::TokenTransferError; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::prelude::*; use crate::serializers::serde_string; @@ -22,11 +22,11 @@ impl BaseDenom { } impl FromStr for BaseDenom { - type Err = Error; + type Err = TokenTransferError; fn from_str(s: &str) -> Result { if s.trim().is_empty() { - Err(Error::EmptyBaseDenom) + Err(TokenTransferError::EmptyBaseDenom) } else { Ok(BaseDenom(s.to_owned())) } @@ -86,25 +86,27 @@ impl TracePath { } impl<'a> TryFrom> for TracePath { - type Error = Error; + type Error = TokenTransferError; fn try_from(v: Vec<&'a str>) -> Result { if v.len() % 2 != 0 { - return Err(Error::InvalidTraceLength { len: v.len() }); + return Err(TokenTransferError::InvalidTraceLength { len: v.len() }); } let mut trace = vec![]; let id_pairs = v.chunks_exact(2).map(|paths| (paths[0], paths[1])); for (pos, (port_id, channel_id)) in id_pairs.rev().enumerate() { - let port_id = PortId::from_str(port_id).map_err(|e| Error::InvalidTracePortId { - pos, - validation_error: e, - })?; - let channel_id = - ChannelId::from_str(channel_id).map_err(|e| Error::InvalidTraceChannelId { + let port_id = + PortId::from_str(port_id).map_err(|e| TokenTransferError::InvalidTracePortId { pos, validation_error: e, })?; + let channel_id = ChannelId::from_str(channel_id).map_err(|e| { + TokenTransferError::InvalidTraceChannelId { + pos, + validation_error: e, + } + })?; trace.push(TracePrefix { port_id, channel_id, @@ -116,7 +118,7 @@ impl<'a> TryFrom> for TracePath { } impl FromStr for TracePath { - type Err = Error; + type Err = TokenTransferError; fn from_str(s: &str) -> Result { let parts = { @@ -216,7 +218,7 @@ pub fn is_receiver_chain_source( } impl FromStr for PrefixedDenom { - type Err = Error; + type Err = TokenTransferError; fn from_str(s: &str) -> Result { let mut parts: Vec<&str> = s.split('/').collect(); @@ -240,7 +242,7 @@ impl FromStr for PrefixedDenom { } impl TryFrom for PrefixedDenom { - type Error = Error; + type Error = TokenTransferError; fn try_from(value: RawDenomTrace) -> Result { let base_denom = BaseDenom::from_str(&value.base_denom)?; @@ -285,7 +287,7 @@ mod tests { use super::*; #[test] - fn test_denom_validation() -> Result<(), Error> { + fn test_denom_validation() -> Result<(), TokenTransferError> { assert!(BaseDenom::from_str("").is_err(), "empty base denom"); assert!(BaseDenom::from_str("uatom").is_ok(), "valid base denom"); assert!(PrefixedDenom::from_str("").is_err(), "empty denom trace"); @@ -324,7 +326,7 @@ mod tests { } #[test] - fn test_denom_trace() -> Result<(), Error> { + fn test_denom_trace() -> Result<(), TokenTransferError> { assert_eq!( PrefixedDenom::from_str("transfer/channel-0/uatom")?, PrefixedDenom { @@ -346,7 +348,7 @@ mod tests { } #[test] - fn test_denom_serde() -> Result<(), Error> { + fn test_denom_serde() -> Result<(), TokenTransferError> { let dt_str = "transfer/channel-0/uatom"; let dt = PrefixedDenom::from_str(dt_str)?; assert_eq!(dt.to_string(), dt_str, "valid single trace info"); @@ -359,7 +361,7 @@ mod tests { } #[test] - fn test_trace_path() -> Result<(), Error> { + fn test_trace_path() -> Result<(), TokenTransferError> { assert!(TracePath::from_str("").is_ok(), "empty trace path"); assert!( TracePath::from_str("transfer/uatom").is_err(), diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index e6e226ade..32eedb6b6 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -15,40 +15,8 @@ use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::prelude::*; use crate::signer::SignerError; -#[cfg(feature = "std")] -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match &self { - Error::PacketError(e) => Some(e), - Error::InvalidPortId { - validation_error: e, - .. - } => Some(e), - Error::InvalidChannelId { - validation_error: e, - .. - } => Some(e), - Error::Utf8(e) => Some(e), - Error::InvalidTracePortId { - validation_error: e, - .. - } => Some(e), - Error::InvalidTraceChannelId { - validation_error: e, - .. - } => Some(e), - Error::InvalidAmount(e) => Some(e), - Error::Signer(e) => Some(e), - Error::ParseHex(e) => Some(e), - Error::DecodeRawMsg(e) => Some(e), - Error::Utf8Decode(e) => Some(e), - _ => None, - } - } -} - #[derive(Display, Debug)] -pub enum Error { +pub enum TokenTransferError { /// unrecognized ICS-20 transfer message type URL `{url}` UnknowMessageTypeUrl { url: String }, /// ICS04 Packet error @@ -144,7 +112,39 @@ pub enum Error { Utf8Decode(Utf8Error), } -impl From for Error { +#[cfg(feature = "std")] +impl std::error::Error for TokenTransferError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self { + Self::PacketError(e) => Some(e), + Self::InvalidPortId { + validation_error: e, + .. + } => Some(e), + Self::InvalidChannelId { + validation_error: e, + .. + } => Some(e), + Self::Utf8(e) => Some(e), + Self::InvalidTracePortId { + validation_error: e, + .. + } => Some(e), + Self::InvalidTraceChannelId { + validation_error: e, + .. + } => Some(e), + Self::InvalidAmount(e) => Some(e), + Self::Signer(e) => Some(e), + Self::ParseHex(e) => Some(e), + Self::DecodeRawMsg(e) => Some(e), + Self::Utf8Decode(e) => Some(e), + _ => None, + } + } +} + +impl From for TokenTransferError { fn from(e: Infallible) -> Self { match e {} } diff --git a/crates/ibc/src/applications/transfer/msgs/transfer.rs b/crates/ibc/src/applications/transfer/msgs/transfer.rs index 64edb8293..f0ffc7b4e 100644 --- a/crates/ibc/src/applications/transfer/msgs/transfer.rs +++ b/crates/ibc/src/applications/transfer/msgs/transfer.rs @@ -7,7 +7,7 @@ use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::protobuf::Protobuf; -use crate::applications::transfer::error::Error; +use crate::applications::transfer::error::TokenTransferError; use crate::core::ics04_channel::timeout::TimeoutHeight; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::signer::Signer; @@ -44,7 +44,7 @@ pub struct MsgTransfer { } impl Msg for MsgTransfer { - type ValidationError = Error; + type ValidationError = TokenTransferError; type Raw = RawMsgTransfer; fn route(&self) -> String { @@ -57,41 +57,41 @@ impl Msg for MsgTransfer { } impl TryFrom for MsgTransfer { - type Error = Error; + type Error = TokenTransferError; fn try_from(raw_msg: RawMsgTransfer) -> Result { let timeout_timestamp = Timestamp::from_nanoseconds(raw_msg.timeout_timestamp).map_err(|_| { - Error::InvalidPacketTimeoutTimestamp { + TokenTransferError::InvalidPacketTimeoutTimestamp { timestamp: raw_msg.timeout_timestamp, } })?; - let timeout_height: TimeoutHeight = - raw_msg - .timeout_height - .try_into() - .map_err(|e| Error::InvalidPacketTimeoutHeight { - context: format!("invalid timeout height {}", e), - })?; + let timeout_height: TimeoutHeight = raw_msg.timeout_height.try_into().map_err(|e| { + TokenTransferError::InvalidPacketTimeoutHeight { + context: format!("invalid timeout height {}", e), + } + })?; Ok(MsgTransfer { - source_port: raw_msg - .source_port - .parse() - .map_err(|e| Error::InvalidPortId { + source_port: raw_msg.source_port.parse().map_err(|e| { + TokenTransferError::InvalidPortId { context: raw_msg.source_port.clone(), validation_error: e, - })?, + } + })?, source_channel: raw_msg.source_channel.parse().map_err(|e| { - Error::InvalidChannelId { + TokenTransferError::InvalidChannelId { context: raw_msg.source_channel.clone(), validation_error: e, } })?, - token: raw_msg.token.ok_or(Error::InvalidToken)?, - sender: raw_msg.sender.parse().map_err(Error::Signer)?, - receiver: raw_msg.receiver.parse().map_err(Error::Signer)?, + token: raw_msg.token.ok_or(TokenTransferError::InvalidToken)?, + sender: raw_msg.sender.parse().map_err(TokenTransferError::Signer)?, + receiver: raw_msg + .receiver + .parse() + .map_err(TokenTransferError::Signer)?, timeout_height, timeout_timestamp, }) @@ -115,12 +115,14 @@ impl From for RawMsgTransfer { impl Protobuf for MsgTransfer {} impl TryFrom for MsgTransfer { - type Error = Error; + type Error = TokenTransferError; fn try_from(raw: Any) -> Result { match raw.type_url.as_str() { - TYPE_URL => MsgTransfer::decode_vec(&raw.value).map_err(Error::DecodeRawMsg), - _ => Err(Error::UnknownMsgType { + TYPE_URL => { + MsgTransfer::decode_vec(&raw.value).map_err(TokenTransferError::DecodeRawMsg) + } + _ => Err(TokenTransferError::UnknownMsgType { msg_type: raw.type_url, }), } diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index 5e9fcce3c..525a098c0 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -5,7 +5,7 @@ use core::str::FromStr; use ibc_proto::ibc::applications::transfer::v2::FungibleTokenPacketData as RawPacketData; use serde::{Deserialize, Serialize}; -use super::error::Error; +use super::error::TokenTransferError; use super::{Amount, PrefixedCoin, PrefixedDenom}; use crate::signer::Signer; @@ -18,7 +18,7 @@ pub struct PacketData { } impl TryFrom for PacketData { - type Error = Error; + type Error = TokenTransferError; fn try_from(raw_pkt_data: RawPacketData) -> Result { // This denom may be prefixed or unprefixed. @@ -26,8 +26,14 @@ impl TryFrom for PacketData { let amount = Amount::from_str(&raw_pkt_data.amount)?; Ok(Self { token: PrefixedCoin { denom, amount }, - sender: raw_pkt_data.sender.parse().map_err(Error::Signer)?, - receiver: raw_pkt_data.receiver.parse().map_err(Error::Signer)?, + sender: raw_pkt_data + .sender + .parse() + .map_err(TokenTransferError::Signer)?, + receiver: raw_pkt_data + .receiver + .parse() + .map_err(TokenTransferError::Signer)?, }) } } diff --git a/crates/ibc/src/applications/transfer/relay.rs b/crates/ibc/src/applications/transfer/relay.rs index d664b9005..8660b24f2 100644 --- a/crates/ibc/src/applications/transfer/relay.rs +++ b/crates/ibc/src/applications/transfer/relay.rs @@ -1,6 +1,6 @@ //! This module implements the processing logic for ICS20 (token transfer) message. use crate::applications::transfer::context::TokenTransferContext; -use crate::applications::transfer::error::Error as Ics20Error; +use crate::applications::transfer::error::TokenTransferError; use crate::applications::transfer::is_sender_chain_source; use crate::applications::transfer::packet::PacketData; use crate::core::ics04_channel::packet::Packet; @@ -15,12 +15,12 @@ fn refund_packet_token( ctx: &mut impl TokenTransferContext, packet: &Packet, data: &PacketData, -) -> Result<(), Ics20Error> { +) -> Result<(), TokenTransferError> { let sender = data .sender .clone() .try_into() - .map_err(|_| Ics20Error::ParseAccountFailure)?; + .map_err(|_| TokenTransferError::ParseAccountFailure)?; if is_sender_chain_source( packet.source_port.clone(), diff --git a/crates/ibc/src/applications/transfer/relay/on_ack_packet.rs b/crates/ibc/src/applications/transfer/relay/on_ack_packet.rs index 72e147a97..14c48a4e4 100644 --- a/crates/ibc/src/applications/transfer/relay/on_ack_packet.rs +++ b/crates/ibc/src/applications/transfer/relay/on_ack_packet.rs @@ -1,6 +1,6 @@ use crate::applications::transfer::acknowledgement::Acknowledgement; use crate::applications::transfer::context::TokenTransferContext; -use crate::applications::transfer::error::Error as Ics20Error; +use crate::applications::transfer::error::TokenTransferError; use crate::applications::transfer::packet::PacketData; use crate::applications::transfer::relay::refund_packet_token; use crate::core::ics04_channel::packet::Packet; @@ -10,7 +10,7 @@ pub fn process_ack_packet( packet: &Packet, data: &PacketData, ack: &Acknowledgement, -) -> Result<(), Ics20Error> { +) -> Result<(), TokenTransferError> { if matches!(ack, Acknowledgement::Error(_)) { refund_packet_token(ctx, packet, data)?; } diff --git a/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs b/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs index c23f2ba18..2eb2928ca 100644 --- a/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs +++ b/crates/ibc/src/applications/transfer/relay/on_recv_packet.rs @@ -1,5 +1,5 @@ use crate::applications::transfer::context::TokenTransferContext; -use crate::applications::transfer::error::Error as Ics20Error; +use crate::applications::transfer::error::TokenTransferError; use crate::applications::transfer::events::DenomTraceEvent; use crate::applications::transfer::packet::PacketData; use crate::applications::transfer::{is_receiver_chain_source, TracePrefix}; @@ -12,16 +12,16 @@ pub fn process_recv_packet( output: &mut ModuleOutputBuilder, packet: &Packet, data: PacketData, -) -> Result, Ics20Error> { +) -> Result, TokenTransferError> { if !ctx.is_receive_enabled() { - return Err(Ics20Error::ReceiveDisabled); + return Err(TokenTransferError::ReceiveDisabled); } let receiver_account = data .receiver .clone() .try_into() - .map_err(|_| Ics20Error::ParseAccountFailure)?; + .map_err(|_| TokenTransferError::ParseAccountFailure)?; if is_receiver_chain_source( packet.source_port.clone(), diff --git a/crates/ibc/src/applications/transfer/relay/on_timeout_packet.rs b/crates/ibc/src/applications/transfer/relay/on_timeout_packet.rs index e35e22c6d..0f54016a4 100644 --- a/crates/ibc/src/applications/transfer/relay/on_timeout_packet.rs +++ b/crates/ibc/src/applications/transfer/relay/on_timeout_packet.rs @@ -1,5 +1,5 @@ use crate::applications::transfer::context::TokenTransferContext; -use crate::applications::transfer::error::Error as Ics20Error; +use crate::applications::transfer::error::TokenTransferError; use crate::applications::transfer::packet::PacketData; use crate::applications::transfer::relay::refund_packet_token; use crate::core::ics04_channel::packet::Packet; @@ -8,6 +8,6 @@ pub fn process_timeout_packet( ctx: &mut impl TokenTransferContext, packet: &Packet, data: &PacketData, -) -> Result<(), Ics20Error> { +) -> Result<(), TokenTransferError> { refund_packet_token(ctx, packet, data) } diff --git a/crates/ibc/src/applications/transfer/relay/send_transfer.rs b/crates/ibc/src/applications/transfer/relay/send_transfer.rs index 30c7f0f9c..1f9aeffb7 100644 --- a/crates/ibc/src/applications/transfer/relay/send_transfer.rs +++ b/crates/ibc/src/applications/transfer/relay/send_transfer.rs @@ -1,5 +1,5 @@ use crate::applications::transfer::context::TokenTransferContext; -use crate::applications::transfer::error::Error; +use crate::applications::transfer::error::TokenTransferError; use crate::applications::transfer::events::TransferEvent; use crate::applications::transfer::msgs::transfer::MsgTransfer; use crate::applications::transfer::packet::PacketData; @@ -17,24 +17,24 @@ pub fn send_transfer( ctx: &mut Ctx, output: &mut HandlerOutputBuilder<()>, msg: MsgTransfer, -) -> Result<(), Error> +) -> Result<(), TokenTransferError> where Ctx: TokenTransferContext, C: TryInto, { if !ctx.is_send_enabled() { - return Err(Error::SendDisabled); + return Err(TokenTransferError::SendDisabled); } let source_channel_end = ctx .channel_end(&msg.source_port, &msg.source_channel) - .map_err(Error::PacketError)?; + .map_err(TokenTransferError::PacketError)?; let destination_port = source_channel_end.counterparty().port_id().clone(); let destination_channel = source_channel_end .counterparty() .channel_id() - .ok_or_else(|| Error::DestinationChannelNotFound { + .ok_or_else(|| TokenTransferError::DestinationChannelNotFound { port_id: msg.source_port.clone(), channel_id: msg.source_channel.clone(), })? @@ -43,9 +43,12 @@ where // get the next sequence let sequence = ctx .get_next_sequence_send(&msg.source_port, &msg.source_channel) - .map_err(Error::PacketError)?; + .map_err(TokenTransferError::PacketError)?; - let token = msg.token.try_into().map_err(|_| Error::InvalidToken)?; + let token = msg + .token + .try_into() + .map_err(|_| TokenTransferError::InvalidToken)?; let denom = token.denom.clone(); let coin = Coin { denom: denom.clone(), @@ -56,7 +59,7 @@ where .sender .clone() .try_into() - .map_err(|_| Error::ParseAccountFailure)?; + .map_err(|_| TokenTransferError::ParseAccountFailure)?; if is_sender_chain_source(msg.source_port.clone(), msg.source_channel.clone(), &denom) { let escrow_address = @@ -90,10 +93,10 @@ where result, log, events, - } = send_packet(ctx, packet).map_err(Error::PacketError)?; + } = send_packet(ctx, packet).map_err(TokenTransferError::PacketError)?; ctx.store_send_packet_result(result) - .map_err(Error::PacketError)?; + .map_err(TokenTransferError::PacketError)?; output.merge_output( HandlerOutput::builder() diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 9f4c3edb8..86ed2e336 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -7,7 +7,7 @@ use crate::applications::transfer::context::{ cosmos_adr028_escrow_address, BankKeeper, TokenTransferContext, TokenTransferKeeper, TokenTransferReader, }; -use crate::applications::transfer::{error::Error as Ics20Error, PrefixedCoin}; +use crate::applications::transfer::{error::TokenTransferError, PrefixedCoin}; use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; @@ -167,7 +167,7 @@ impl BankKeeper for DummyTransferModule { _from: &Self::AccountId, _to: &Self::AccountId, _amt: &PrefixedCoin, - ) -> Result<(), Ics20Error> { + ) -> Result<(), TokenTransferError> { Ok(()) } @@ -175,7 +175,7 @@ impl BankKeeper for DummyTransferModule { &mut self, _account: &Self::AccountId, _amt: &PrefixedCoin, - ) -> Result<(), Ics20Error> { + ) -> Result<(), TokenTransferError> { Ok(()) } @@ -183,7 +183,7 @@ impl BankKeeper for DummyTransferModule { &mut self, _account: &Self::AccountId, _amt: &PrefixedCoin, - ) -> Result<(), Ics20Error> { + ) -> Result<(), TokenTransferError> { Ok(()) } } @@ -191,7 +191,7 @@ impl BankKeeper for DummyTransferModule { impl TokenTransferReader for DummyTransferModule { type AccountId = Signer; - fn get_port(&self) -> Result { + fn get_port(&self) -> Result { Ok(PortId::transfer()) } @@ -199,7 +199,7 @@ impl TokenTransferReader for DummyTransferModule { &self, port_id: &PortId, channel_id: &ChannelId, - ) -> Result<::AccountId, Ics20Error> { + ) -> Result<::AccountId, TokenTransferError> { let addr = cosmos_adr028_escrow_address(port_id, channel_id); Ok(bech32::encode("cosmos", addr).parse().unwrap()) } From 686a2982abf88aa38dd877622a92a7eae095433f Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 04:19:58 +0800 Subject: [PATCH 35/43] Add ContextError for ValidationContext and ExecutionContext --- crates/ibc/src/core/context.rs | 111 ++++++++++++++++++++------------- 1 file changed, 69 insertions(+), 42 deletions(-) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 86e966d0b..8cb8605c7 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -28,7 +28,7 @@ use super::{ channel::ChannelEnd, commitment::{AcknowledgementCommitment, PacketCommitment}, context::calculate_block_delay, - error::ChannelError, + error::{ChannelError, PacketError}, msgs::acknowledgement::Acknowledgement, packet::{Receipt, Sequence}, timeout::TimeoutHeight, @@ -36,6 +36,31 @@ use super::{ ics23_commitment::commitment::CommitmentPrefix, ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}, }; +use displaydoc::Display; + +#[derive(Debug, Display)] +pub enum ContextError { + /// ICS02 Client error + ClientError(ClientError), + /// ICS03 Connection error + ConnectionError(ConnectionError), + /// Ics04 Channel error + ChannelError(ChannelError), + /// ICS04 Packet error + PacketError(PacketError), +} + +#[cfg(feature = "std")] +impl std::error::Error for ContextError { + 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), + } + } +} pub trait ValidationContext { /// Validation entrypoint. @@ -60,10 +85,10 @@ pub trait ValidationContext { } /// Returns the ClientState for the given identifier `client_id`. - fn client_state(&self, client_id: &ClientId) -> Result, ClientError>; + fn client_state(&self, client_id: &ClientId) -> Result, ContextError>; /// Tries to decode the given `client_state` into a concrete light client state. - fn decode_client_state(&self, client_state: Any) -> Result, ClientError>; + fn decode_client_state(&self, client_state: Any) -> Result, ContextError>; /// Retrieve the consensus state for the given client ID at the specified /// height. @@ -73,27 +98,27 @@ pub trait ValidationContext { &self, client_id: &ClientId, height: Height, - ) -> Result, ClientError>; + ) -> Result, ContextError>; /// Search for the lowest consensus state higher than `height`. fn next_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result>, ClientError>; + ) -> Result>, ContextError>; /// Search for the highest consensus state lower than `height`. fn prev_consensus_state( &self, client_id: &ClientId, height: Height, - ) -> Result>, ClientError>; + ) -> Result>, ContextError>; /// 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 { let pending_consensus_state = self .pending_host_consensus_state() .expect("host must have pending consensus state"); @@ -101,17 +126,18 @@ pub trait ValidationContext { } /// Returns the pending `ConsensusState` of the host (local) chain. - fn pending_host_consensus_state(&self) -> Result, ClientError>; + fn pending_host_consensus_state(&self) -> Result, ContextError>; /// Returns the `ConsensusState` of the host (local) chain at a specific height. - fn host_consensus_state(&self, height: Height) -> Result, ClientError>; + fn host_consensus_state(&self, height: Height) + -> Result, ContextError>; /// Returns a natural number, counting how many clients have been created thus far. /// The value of this counter should increase only via method `ClientKeeper::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; /// Returns the oldest height available on the local chain. fn host_oldest_height(&self) -> Height; @@ -120,7 +146,7 @@ pub trait ValidationContext { 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. @@ -134,50 +160,51 @@ pub trait ValidationContext { &self, supported_versions: Vec, counterparty_candidate_versions: Vec, - ) -> Result { + ) -> Result { pick_version(supported_versions, counterparty_candidate_versions) + .map_err(ContextError::ConnectionError) } /// Returns the ChannelEnd for the given `port_id` and `chan_id`. fn channel_end( &self, port_channel_id: &(PortId, ChannelId), - ) -> Result; + ) -> Result; fn connection_channels( &self, cid: &ConnectionId, - ) -> Result, ChannelError>; + ) -> Result, ContextError>; fn get_next_sequence_send( &self, port_channel_id: &(PortId, ChannelId), - ) -> Result; + ) -> Result; fn get_next_sequence_recv( &self, port_channel_id: &(PortId, ChannelId), - ) -> Result; + ) -> Result; fn get_next_sequence_ack( &self, port_channel_id: &(PortId, ChannelId), - ) -> Result; + ) -> Result; fn get_packet_commitment( &self, key: &(PortId, ChannelId, Sequence), - ) -> Result; + ) -> Result; fn get_packet_receipt( &self, key: &(PortId, ChannelId, Sequence), - ) -> Result; + ) -> Result; fn get_packet_acknowledgement( &self, key: &(PortId, ChannelId, Sequence), - ) -> Result; + ) -> Result; /// Compute the commitment for a packet. /// Note that the absence of `timeout_height` is treated as @@ -216,19 +243,19 @@ pub trait ValidationContext { &self, client_id: &ClientId, height: Height, - ) -> Result; + ) -> Result; /// Returns the height when the client state for the given [`ClientId`] was updated with a header for the given [`Height`] fn client_update_height( &self, client_id: &ClientId, height: Height, - ) -> 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 /// `ChannelKeeper::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; @@ -267,21 +294,21 @@ pub trait ExecutionContext: ValidationContext { &mut self, client_type_path: ClientTypePath, client_type: ClientType, - ) -> Result<(), ClientError>; + ) -> Result<(), ContextError>; /// Called upon successful client creation and update fn store_client_state( &mut self, client_state_path: ClientStatePath, client_state: Box, - ) -> Result<(), ClientError>; + ) -> Result<(), ContextError>; /// Called upon successful client creation and update fn store_consensus_state( &mut self, consensus_state_path: ClientConsensusStatePath, consensus_state: Box, - ) -> Result<(), ClientError>; + ) -> Result<(), ContextError>; /// Called upon client creation. /// Increases the counter which keeps track of how many clients have been created. @@ -296,7 +323,7 @@ pub trait ExecutionContext: ValidationContext { client_id: ClientId, height: Height, timestamp: Timestamp, - ) -> Result<(), ClientError>; + ) -> Result<(), ContextError>; /// Called upon successful client update. /// Implementations are expected to use this to record the specified height as the height at @@ -306,21 +333,21 @@ pub trait ExecutionContext: ValidationContext { client_id: ClientId, height: Height, host_height: Height, - ) -> Result<(), ClientError>; + ) -> Result<(), ContextError>; /// Stores the given connection_end at path fn store_connection( &mut self, connections_path: ConnectionsPath, connection_end: &ConnectionEnd, - ) -> Result<(), ConnectionError>; + ) -> Result<(), ContextError>; /// Stores the given connection_id at a path associated with the client_id. fn store_connection_to_client( &mut self, client_connections_path: ClientConnectionsPath, client_id: &ClientId, - ) -> Result<(), ConnectionError>; + ) -> Result<(), ContextError>; /// Called upon connection identifier creation (Init or Try process). /// Increases the counter which keeps track of how many connections have been created. @@ -331,57 +358,57 @@ pub trait ExecutionContext: ValidationContext { &mut self, commitments_path: CommitmentsPath, commitment: PacketCommitment, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; - fn delete_packet_commitment(&mut self, key: CommitmentsPath) -> Result<(), ChannelError>; + fn delete_packet_commitment(&mut self, key: CommitmentsPath) -> Result<(), ContextError>; fn store_packet_receipt( &mut self, path: ReceiptsPath, receipt: Receipt, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; fn store_packet_acknowledgement( &mut self, key: (PortId, ChannelId, Sequence), ack_commitment: AcknowledgementCommitment, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; fn delete_packet_acknowledgement( &mut self, key: (PortId, ChannelId, Sequence), - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; fn store_connection_channels( &mut self, conn_id: ConnectionId, port_channel_id: &(PortId, ChannelId), - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; /// Stores the given channel_end at a path associated with the port_id and channel_id. fn store_channel( &mut self, port_channel_id: (PortId, ChannelId), channel_end: &ChannelEnd, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; fn store_next_sequence_send( &mut self, port_channel_id: (PortId, ChannelId), seq: Sequence, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; fn store_next_sequence_recv( &mut self, port_channel_id: (PortId, ChannelId), seq: Sequence, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; fn store_next_sequence_ack( &mut self, port_channel_id: (PortId, ChannelId), seq: Sequence, - ) -> Result<(), ChannelError>; + ) -> Result<(), ContextError>; /// Called upon channel identifier creation (Init or Try message processing). /// Increases the counter which keeps track of how many channels have been created. From 995d429ec7bc6e6abafcbe753376d235c58de350 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 05:00:45 +0800 Subject: [PATCH 36/43] Update RouterError --- .../clients/ics07_tendermint/client_state.rs | 34 ++++++++++++++----- crates/ibc/src/core/context.rs | 28 +++++++++++++-- .../ics02_client/handler/create_client.rs | 9 ++--- .../ics02_client/handler/update_client.rs | 10 +++--- .../ics02_client/handler/upgrade_client.rs | 10 +++--- crates/ibc/src/core/ics26_routing/error.rs | 19 +++-------- crates/ibc/src/core/ics26_routing/handler.rs | 32 +++++++++-------- 7 files changed, 90 insertions(+), 52 deletions(-) diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index ded507b2f..6ede0b581 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -1,3 +1,4 @@ +use crate::core::context::ContextError; use crate::core::ics02_client::context::ClientReader; use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment}; @@ -518,11 +519,8 @@ impl Ics2ClientState for ClientState { match ctx.consensus_state(client_id, height) { Ok(cs) => Ok(Some(cs)), Err(e) => match e { - ClientError::ConsensusStateNotFound { - client_id: _, - height: _, - } => Ok(None), - _ => Err(e), + ContextError::ClientError(e) => Err(e), + _ => Ok(None), }, } } @@ -563,7 +561,11 @@ impl Ics2ClientState for ClientState { }; let trusted_consensus_state = downcast_tm_consensus_state( - ctx.consensus_state(&client_id, header.trusted_height)? + ctx.consensus_state(&client_id, header.trusted_height) + .map_err(|e| match e { + ContextError::ClientError(e) => e, + _ => todo!(), + })? .as_ref(), )?; @@ -598,7 +600,13 @@ impl Ics2ClientState for ClientState { untrusted_state, trusted_state, &options, - ctx.host_timestamp()?.into_tm_time().unwrap(), + ctx.host_timestamp() + .map_err(|e| match e { + ContextError::ClientError(e) => e, + _ => todo!(), + })? + .into_tm_time() + .unwrap(), ); match verdict { @@ -628,7 +636,11 @@ impl Ics2ClientState for ClientState { // (cs-new, cs-next, cs-latest) if header.height() < client_state.latest_height() { let maybe_next_cs = ctx - .next_consensus_state(&client_id, header.height())? + .next_consensus_state(&client_id, header.height()) + .map_err(|e| match e { + ContextError::ClientError(e) => e, + _ => todo!(), + })? .as_ref() .map(|cs| downcast_tm_consensus_state(cs.as_ref())) .transpose()?; @@ -651,7 +663,11 @@ impl Ics2ClientState for ClientState { // (cs-trusted, cs-prev, cs-new) if header.trusted_height < header.height() { let maybe_prev_cs = ctx - .prev_consensus_state(&client_id, header.height())? + .prev_consensus_state(&client_id, header.height()) + .map_err(|e| match e { + ContextError::ClientError(e) => e, + _ => todo!(), + })? .as_ref() .map(|cs| downcast_tm_consensus_state(cs.as_ref())) .transpose()?; diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 8cb8605c7..2498b4761 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -50,6 +50,30 @@ pub enum ContextError { PacketError(PacketError), } +impl From for ContextError { + fn from(err: ClientError) -> ContextError { + Self::ClientError(err) + } +} + +impl From for ContextError { + fn from(err: ConnectionError) -> ContextError { + Self::ConnectionError(err) + } +} + +impl From for ContextError { + fn from(err: ChannelError) -> ContextError { + Self::ChannelError(err) + } +} + +impl From for ContextError { + fn from(err: PacketError) -> ContextError { + Self::PacketError(err) + } +} + #[cfg(feature = "std")] impl std::error::Error for ContextError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { @@ -77,7 +101,7 @@ pub trait ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::validate(self, message), } - .map_err(RouterError::Client), + .map_err(|e| RouterError::ContextError(e)), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), @@ -282,7 +306,7 @@ pub trait ExecutionContext: ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::execute(self, message), } - .map_err(RouterError::Client), + .map_err(|e| RouterError::ContextError(e)), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), diff --git a/crates/ibc/src/core/ics02_client/handler/create_client.rs b/crates/ibc/src/core/ics02_client/handler/create_client.rs index f601cc250..e7bac8d61 100644 --- a/crates/ibc/src/core/ics02_client/handler/create_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/create_client.rs @@ -1,5 +1,6 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgCreateClient`. +use crate::core::context::ContextError; use crate::core::ics24_host::path::ClientConsensusStatePath; use crate::core::ics24_host::path::ClientStatePath; use crate::core::ics24_host::path::ClientTypePath; @@ -34,7 +35,7 @@ pub struct CreateClientResult { pub processed_height: Height, } -pub(crate) fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), ClientError> +pub(crate) fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), ContextError> where Ctx: ValidationContext, { @@ -62,7 +63,7 @@ where Ok(()) } -pub(crate) fn execute(ctx: &mut Ctx, msg: MsgCreateClient) -> Result<(), ClientError> +pub(crate) fn execute(ctx: &mut Ctx, msg: MsgCreateClient) -> Result<(), ContextError> where Ctx: ExecutionContext, { @@ -80,11 +81,11 @@ where let client_type = client_state.client_type(); let client_id = ClientId::new(client_type.clone(), id_counter).map_err(|e| { - ClientError::ClientIdentifierConstructor { + ContextError::from(ClientError::ClientIdentifierConstructor { client_type: client_state.client_type(), counter: id_counter, validation_error: e, - } + }) })?; let consensus_state = client_state.initialise(consensus_state)?; diff --git a/crates/ibc/src/core/ics02_client/handler/update_client.rs b/crates/ibc/src/core/ics02_client/handler/update_client.rs index 49a0067f8..befd365c1 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -2,6 +2,7 @@ use tracing::debug; +use crate::core::context::ContextError; use crate::core::ics02_client::client_state::{ClientState, UpdatedState}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::context::ClientReader; @@ -29,7 +30,7 @@ pub struct UpdateClientResult { pub processed_height: Height, } -pub(crate) fn validate(ctx: &Ctx, msg: MsgUpdateClient) -> Result<(), ClientError> +pub(crate) fn validate(ctx: &Ctx, msg: MsgUpdateClient) -> Result<(), ContextError> where Ctx: ValidationContext, { @@ -44,7 +45,7 @@ where let client_state = ctx.client_state(&client_id)?; if client_state.is_frozen() { - return Err(ClientError::ClientFrozen { client_id }); + return Err(ClientError::ClientFrozen { client_id }.into()); } // Read consensus state from the host chain store. @@ -69,7 +70,8 @@ where return Err(ClientError::HeaderNotWithinTrustPeriod { latest_time: latest_consensus_state.timestamp(), update_time: now, - }); + } + .into()); } // Use client_state to validate the new header against the latest consensus_state. @@ -84,7 +86,7 @@ where Ok(()) } -pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpdateClient) -> Result<(), ClientError> +pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpdateClient) -> Result<(), ContextError> where Ctx: ExecutionContext, { diff --git a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs index 8b0afb25e..67653a7be 100644 --- a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs @@ -1,5 +1,6 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgUpgradeAnyClient`. //! +use crate::core::context::ContextError; use crate::core::ics02_client::client_state::{ClientState, UpdatedState}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::context::ClientReader; @@ -23,7 +24,7 @@ pub struct UpgradeClientResult { pub consensus_state: Box, } -pub(crate) fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), ClientError> +pub(crate) fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), ContextError> where Ctx: ValidationContext, { @@ -33,7 +34,7 @@ where let old_client_state = ctx.client_state(&client_id)?; if old_client_state.is_frozen() { - return Err(ClientError::ClientFrozen { client_id }); + return Err(ClientError::ClientFrozen { client_id }.into()); } let upgrade_client_state = ctx.decode_client_state(msg.client_state)?; @@ -42,13 +43,14 @@ where return Err(ClientError::LowUpgradeHeight { upgraded_height: old_client_state.latest_height(), client_height: upgrade_client_state.latest_height(), - }); + } + .into()); } Ok(()) } -pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpgradeClient) -> Result<(), ClientError> +pub(crate) fn execute(ctx: &mut Ctx, msg: MsgUpgradeClient) -> Result<(), ContextError> where Ctx: ExecutionContext, { diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 8299f2522..8fe95e2a2 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -1,20 +1,12 @@ +use crate::core::context::ContextError; use crate::prelude::*; -use crate::core::ics02_client; -use crate::core::ics03_connection; -use crate::core::ics04_channel; use displaydoc::Display; #[derive(Debug, Display)] pub enum RouterError { - /// ICS02 client error - Client(ics02_client::error::ClientError), - /// ICS03 connection error - Connection(ics03_connection::error::ConnectionError), - /// ICS04 channel error - Channel(ics04_channel::error::ChannelError), - /// ICS04 Packet error - Packet(ics04_channel::error::PacketError), + /// context error + ContextError(ContextError), /// unknown type URL `{url}` UnknownMessageTypeUrl { url: String }, /// the message is malformed and cannot be decoded @@ -25,12 +17,9 @@ pub enum RouterError { impl std::error::Error for RouterError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::Client(e) => Some(e), - Self::Connection(e) => Some(e), - Self::Channel(e) => Some(e), + Self::ContextError(e) => Some(e), Self::UnknownMessageTypeUrl { .. } => None, Self::MalformedMessageBytes(e) => Some(e), - Self::Packet(e) => Some(e), } } } diff --git a/crates/ibc/src/core/ics26_routing/handler.rs b/crates/ibc/src/core/ics26_routing/handler.rs index d63c2ad9d..141ba46e1 100644 --- a/crates/ibc/src/core/ics26_routing/handler.rs +++ b/crates/ibc/src/core/ics26_routing/handler.rs @@ -59,11 +59,12 @@ where { let output = match msg { ClientMsg(msg) => { - let handler_output = ics2_msg_dispatcher(ctx, msg).map_err(RouterError::Client)?; + let handler_output = + ics2_msg_dispatcher(ctx, msg).map_err(|e| RouterError::ContextError(e.into()))?; // Apply the result to the context (host chain store). ctx.store_client_result(handler_output.result) - .map_err(RouterError::Client)?; + .map_err(|e| RouterError::ContextError(e.into()))?; HandlerOutput::builder() .with_log(handler_output.log) @@ -72,11 +73,12 @@ where } ConnectionMsg(msg) => { - let handler_output = ics3_msg_dispatcher(ctx, msg).map_err(RouterError::Connection)?; + let handler_output = + ics3_msg_dispatcher(ctx, msg).map_err(|e| RouterError::ContextError(e.into()))?; // Apply any results to the host chain store. ctx.store_connection_result(handler_output.result) - .map_err(RouterError::Connection)?; + .map_err(|e| RouterError::ContextError(e.into()))?; HandlerOutput::builder() .with_log(handler_output.log) @@ -85,18 +87,19 @@ where } ChannelMsg(msg) => { - let module_id = channel_validate(ctx, &msg).map_err(RouterError::Channel)?; + let module_id = + channel_validate(ctx, &msg).map_err(|e| RouterError::ContextError(e.into()))?; let dispatch_output = HandlerOutputBuilder::<()>::new(); let (dispatch_log, mut channel_result) = - channel_dispatch(ctx, &msg).map_err(RouterError::Channel)?; + channel_dispatch(ctx, &msg).map_err(|e| RouterError::ContextError(e.into()))?; // Note: `OpenInit` and `OpenTry` modify the `version` field of the `channel_result`, // so we must pass it mutably. We intend to clean this up with the implementation of // ADR 5. // See issue [#190](https://github.com/cosmos/ibc-rs/issues/190) let callback_extras = channel_callback(ctx, &module_id, &msg, &mut channel_result) - .map_err(RouterError::Channel)?; + .map_err(|e| RouterError::ContextError(e.into()))?; // We need to construct events here instead of directly in the // `process` functions because we need to wait for the callback to @@ -111,7 +114,7 @@ where // Apply any results to the host chain store. ctx.store_channel_result(channel_result) - .map_err(RouterError::Packet)?; + .map_err(|e| RouterError::ContextError(e.into()))?; dispatch_output .with_events(dispatch_events) @@ -128,20 +131,21 @@ where } PacketMsg(msg) => { - let module_id = get_module_for_packet_msg(ctx, &msg).map_err(RouterError::Channel)?; - let (mut handler_builder, packet_result) = - ics4_packet_msg_dispatcher(ctx, &msg).map_err(RouterError::Packet)?; + let module_id = get_module_for_packet_msg(ctx, &msg) + .map_err(|e| RouterError::ContextError(e.into()))?; + let (mut handler_builder, packet_result) = ics4_packet_msg_dispatcher(ctx, &msg) + .map_err(|e| RouterError::ContextError(e.into()))?; if matches!(packet_result, PacketResult::Recv(RecvPacketResult::NoOp)) { return Ok(handler_builder.with_result(())); } let cb_result = ics4_packet_callback(ctx, &module_id, &msg, &mut handler_builder); - cb_result.map_err(RouterError::Packet)?; + cb_result.map_err(|e| RouterError::ContextError(e.into()))?; // Apply any results to the host chain store. ctx.store_packet_result(packet_result) - .map_err(RouterError::Packet)?; + .map_err(|e| RouterError::ContextError(e.into()))?; handler_builder.with_result(()) } @@ -632,7 +636,7 @@ mod tests { msg, ) .map(|_| ()) - .map_err(RouterError::Channel) + .map_err(|e| RouterError::ContextError(e.into())) } }; From d4a6c4d5ee90b7a95ffd369608b1b346196d27c4 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 05:03:45 +0800 Subject: [PATCH 37/43] fix clippy --- crates/ibc/src/core/context.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 2498b4761..4e8c36dae 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -101,7 +101,7 @@ pub trait ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::validate(self, message), } - .map_err(|e| RouterError::ContextError(e)), + .map_err(RouterError::ContextError), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), @@ -306,7 +306,7 @@ pub trait ExecutionContext: ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::execute(self, message), } - .map_err(|e| RouterError::ContextError(e)), + .map_err( RouterError::ContextError), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), From 8628899883426b504b74866644824453c3a455d3 Mon Sep 17 00:00:00 2001 From: Davirain Date: Fri, 25 Nov 2022 09:55:29 +0800 Subject: [PATCH 38/43] Update context.rs --- crates/ibc/src/core/context.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 4e8c36dae..78203cd8e 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -306,7 +306,7 @@ pub trait ExecutionContext: ValidationContext { ClientMsg::Misbehaviour(_message) => unimplemented!(), ClientMsg::UpgradeClient(message) => upgrade_client::execute(self, message), } - .map_err( RouterError::ContextError), + .map_err(RouterError::ContextError), MsgEnvelope::ConnectionMsg(_message) => todo!(), MsgEnvelope::ChannelMsg(_message) => todo!(), MsgEnvelope::PacketMsg(_message) => todo!(), From 1567a06e9452be75f3e0869c149fa7db928e1634 Mon Sep 17 00:00:00 2001 From: Davirain Date: Tue, 29 Nov 2022 10:12:47 +0800 Subject: [PATCH 39/43] Update lib.rs --- crates/ibc/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ibc/src/lib.rs b/crates/ibc/src/lib.rs index 97cd33e22..8c186b8b6 100644 --- a/crates/ibc/src/lib.rs +++ b/crates/ibc/src/lib.rs @@ -4,7 +4,6 @@ #![no_std] #![allow(clippy::large_enum_variant)] -#![allow(clippy::result_large_err)] #![deny( warnings, trivial_casts, From 8912bded10f5780e2e2ef148ffb5209c9426b20e Mon Sep 17 00:00:00 2001 From: Davirain Date: Tue, 29 Nov 2022 11:29:26 +0800 Subject: [PATCH 40/43] Secondary error display output --- crates/ibc/Cargo.toml | 2 +- crates/ibc/src/applications/transfer/error.rs | 22 +++++----- .../ibc/src/clients/ics07_tendermint/error.rs | 14 +++---- crates/ibc/src/core/ics02_client/error.rs | 42 +++++++++---------- crates/ibc/src/core/ics03_connection/error.rs | 14 +++---- crates/ibc/src/core/ics04_channel/error.rs | 10 ++--- crates/ibc/src/core/ics23_commitment/error.rs | 4 +- crates/ibc/src/core/ics26_routing/error.rs | 4 +- crates/ibc/src/events.rs | 14 +++---- crates/ibc/src/relayer/ics18_relayer/error.rs | 4 +- crates/ibc/src/timestamp.rs | 2 +- 11 files changed, 66 insertions(+), 66 deletions(-) diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 21fded570..d4e56a5d2 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -44,7 +44,7 @@ mocks = ["tendermint-testgen", "clock", "std"] [dependencies] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. -ibc-proto = { version = "0.22.0", default-features = false, git = "https://github.com/octopus-network/ibc-proto-rs.git", branch = "refactor-error-system" } +ibc-proto = { version = "0.22.0", default-features = false } ics23 = { version = "=0.8.1", default-features = false, features = ["host-functions"] } time = { version = ">=0.3.0, <0.3.18", default-features = false } serde_derive = { version = "1.0.104", default-features = false } diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index 32eedb6b6..da341b1b3 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -19,19 +19,19 @@ use crate::signer::SignerError; pub enum TokenTransferError { /// unrecognized ICS-20 transfer message type URL `{url}` UnknowMessageTypeUrl { url: String }, - /// ICS04 Packet error + /// packet error: `{0}` PacketError(channel_error::PacketError), /// destination channel not found in the counterparty of port_id `{port_id}` and channel_id `{channel_id}` DestinationChannelNotFound { port_id: PortId, channel_id: ChannelId, }, - /// invalid port identifier `{context}` + /// invalid port identifier `{context}`, validation error: `{validation_error}` InvalidPortId { context: String, validation_error: ValidationError, }, - /// invalid channel identifier `{context}` + /// invalid channel identifier `{context}`, validation error: `{validation_error}` InvalidChannelId { context: String, validation_error: ValidationError, @@ -40,33 +40,33 @@ pub enum TokenTransferError { InvalidPacketTimeoutHeight { context: String }, /// invalid packet timeout timestamp value `{timestamp}` InvalidPacketTimeoutTimestamp { timestamp: u64 }, - /// utf8 decoding error + /// utf8 decoding error: `{0}` Utf8(FromUtf8Error), /// base denomination is empty EmptyBaseDenom, - /// invalid prot id n trace at postion: `{pos}` + /// invalid prot id n trace at postion: `{pos}`, validation error: `{validation_error}` InvalidTracePortId { pos: usize, validation_error: ValidationError, }, - /// invalid channel id in trace at position: `{pos}` + /// invalid channel id in trace at position: `{pos}`, validation error: `{validation_error}` InvalidTraceChannelId { pos: usize, validation_error: ValidationError, }, /// trace length must be even but got: `{len}` InvalidTraceLength { len: usize }, - /// invalid amount error + /// invalid amount error: `{0}` InvalidAmount(FromDecStrErr), /// invalid token InvalidToken, - /// failed to parse signer error + /// failed to parse signer error: `{0}` Signer(SignerError), /// missing 'ibc/' prefix in denomination MissingDenomIbcPrefix, /// hashed denom must be of the form 'ibc/Hash' MalformedHashDenom, - /// invalid hex string error + /// invalid hex string error: `{0}` ParseHex(EncodingError), /// expected `{expect_order}` channel, got `{got_order}` ChannelNotUnordered { @@ -102,13 +102,13 @@ pub enum TokenTransferError { }, /// no trace associated with specified hash TraceNotFound, - /// error decoding raw msg + /// decoding raw msg error: `{0}` DecodeRawMsg(TendermintProtoError), /// unknown msg type: `{msg_type}` UnknownMsgType { msg_type: String }, /// invalid coin string: `{coin}` InvalidCoin { coin: String }, - /// error decoding raw bytes as UTF8 string + /// decoding raw bytes as UTF8 string error: `{0}` Utf8Decode(Utf8Error), } diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index a9aad3e59..9fc29d8b6 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -26,14 +26,14 @@ pub enum Error { InvalidUnbondingPeriod { reason: String }, /// invalid address InvalidAddress, - /// invalid header, failed basic validation: `{reason}` + /// invalid header, failed basic validation: `{reason}`, error: `{error}` InvalidHeader { reason: String, error: TendermintError, }, /// invalid client state trust threshold: `{reason}` InvalidTrustThreshold { reason: String }, - /// invalid tendermint client state trust threshold + /// invalid tendermint client state trust threshold error: `{0}` InvalidTendermintTrustThreshold(TendermintError), /// invalid client state max clock drift: `{reason}` InvalidMaxClockDrift { reason: String }, @@ -55,7 +55,7 @@ pub enum Error { MissingTrustingPeriod, /// missing unbonding period MissingUnbondingPeriod, - /// invalid chain identifier + /// invalid chain identifier error: `{0}` InvalidChainIdentifier(ValidationError), /// negative trusting period NegativeTrustingPeriod, @@ -69,7 +69,7 @@ pub enum Error { MissingLatestHeight, /// invalid frozen height InvalidFrozenHeight, - /// invalid chain identifier: `{raw_value}` + /// invalid chain identifier: `{raw_value}`, validation error: `{error}` InvalidChainId { raw_value: String, error: ValidationError, @@ -78,11 +78,11 @@ pub enum Error { InvalidRawHeight { raw_height: u64 }, /// invalid raw client consensus state: `{reason}` InvalidRawConsensusState { reason: String }, - /// invalid raw header + /// invalid raw header error: `{0}` InvalidRawHeader(TendermintError), /// invalid raw misbehaviour: `{reason}` InvalidRawMisbehaviour { reason: String }, - /// decode error + /// decode error: `{0}` Decode(prost::DecodeError), /// insufficient overlap: `{reason}` InsufficientVotingPower { reason: String }, @@ -94,7 +94,7 @@ pub enum Error { HeaderTimestampTooHigh { actual: String, max: String }, /// given other previous updates, header timestamp should be at least `{min}`, but was `{actual}` HeaderTimestampTooLow { actual: String, min: String }, - /// timestamp overflowed + /// timestamp overflowed error: `{0}` TimestampOverflow(TimestampOverflowError), /// not enough time elapsed, current timestamp `{current_time}` is still less than earliest acceptable timestamp `{earliest_time}` NotEnoughTimeElapsed { diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 4a70d7826..873d758ce 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -15,7 +15,7 @@ use crate::Height; pub enum ClientError { /// unknown client type: `{client_type}` UnknownClientType { client_type: String }, - /// Client identifier constructor failed for type `{client_type}` with counter `{counter}` + /// Client identifier constructor failed for type `{client_type}` with counter `{counter}`, validation error: `{validation_error}` ClientIdentifierConstructor { client_type: ClientType, counter: u64, @@ -51,38 +51,38 @@ pub enum ClientError { UnknownHeaderType { header_type: String }, /// unknown misbehaviour type: `{misbehavior_type}` UnknownMisbehaviourType { misbehavior_type: String }, - /// invalid raw client identifier `{client_id}` + /// invalid raw client identifier `{client_id}`, validation error: `{validation_error}` InvalidRawClientId { client_id: String, validation_error: ValidationError, }, - /// error decoding raw client state + /// decoding raw client state error: `{0}` DecodeRawClientState(TendermintProtoError), /// missing raw client state MissingRawClientState, - /// invalid raw client consensus state + /// invalid raw client consensus state error: `{0}` InvalidRawConsensusState(TendermintProtoError), /// missing raw client consensus state MissingRawConsensusState, - /// invalid client id in the update client message + /// invalid client id in the update client message: `{0}` InvalidMsgUpdateClientId(ValidationError), - /// decode error + /// decode error: `{0}` Decode(prost::DecodeError), /// invalid raw client consensus state: the height field is missing MissingHeight, - /// invalid client identifier + /// invalid client identifier error: `{0}` InvalidClientIdentifier(ValidationError), - /// invalid raw header + /// invalid raw header error: `{0}` InvalidRawHeader(TendermintProtoError), /// missing raw header MissingRawHeader, - /// invalid raw misbehaviour + /// invalid raw misbehaviour error: `{0}` DecodeRawMisbehaviour(TendermintProtoError), - /// invalid raw misbehaviour + /// invalid raw misbehaviour error: `{0}` InvalidRawMisbehaviour(ValidationError), /// missing raw misbehaviour MissingRawMisbehaviour, - /// String `{value}` cannnot be converted to height + /// String `{value}` cannnot be converted to height, height error: `{height_error}` InvalidStringAsHeight { value: String, height_error: HeightError, @@ -93,13 +93,13 @@ pub enum ClientError { InvalidHeightResult, /// invalid address InvalidAddress, - /// invalid proof for the upgraded client state + /// invalid proof for the upgraded client state error: `{0}` InvalidUpgradeClientProof(CommitmentError), - /// invalid proof for the upgraded consensus state + /// invalid proof for the upgraded consensus state error: `{0}` InvalidUpgradeConsensusStateProof(CommitmentError), - /// invalid commitment proof bytes + /// invalid commitment proof bytes error: `{0}` InvalidCommitmentProof(CommitmentError), - /// invalid packet timeout timestamp value + /// invalid packet timeout timestamp value error: `{0}` InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), /// mismatch between client and arguments types ClientArgsTypeMismatch { client_type: ClientType }, @@ -129,17 +129,17 @@ pub enum ClientError { }, /// the local consensus state could not be retrieved for height `{height}` MissingLocalConsensusState { height: Height }, - /// invalid connection end + /// invalid connection end error: `{0}` InvalidConnectionEnd(TendermintProtoError), - /// invalid channel end + /// invalid channel end error: `{0}` InvalidChannelEnd(TendermintProtoError), - /// invalid any client state + /// invalid any client state error: `{0}` InvalidAnyClientState(TendermintProtoError), - /// invalid any client consensus state + /// invalid any client consensus state error: `{0}` InvalidAnyConsensusState(TendermintProtoError), - /// failed to parse signer + /// failed to parse signer error: `{0}` Signer(SignerError), - /// ics23 verification failure + /// ics23 verification failure error: `{0}` Ics23Verification(CommitmentError), /// client specific error: `{description}` ClientSpecific { description: String }, diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 344708d62..eccf5c924 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -11,7 +11,7 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum ConnectionError { - /// ICS02 client error + /// client error: `{0}` Client(client_error::ClientError), /// connection state is unknown: `{state}` InvalidState { state: i32 }, @@ -29,7 +29,7 @@ pub enum ConnectionError { target_height: Height, oldest_height: Height, }, - /// identifier error + /// identifier error: `{0}` InvalidIdentifier(ValidationError), /// ConnectionEnd domain object could not be constructed out of empty proto object EmptyProtoConnectionEnd, @@ -47,11 +47,11 @@ pub enum ConnectionError { MissingProofHeight, /// missing consensus height MissingConsensusHeight, - /// invalid connection proof + /// invalid connection proof error: `{0}` InvalidProof(ProofError), - /// error verifying connnection state + /// verifying connnection state error: `{0}` VerifyConnectionState(client_error::ClientError), - /// invalid signer + /// invalid signer error: `{0}` Signer(SignerError), /// no connection was found for the previous connection id provided `{connection_id}` ConnectionNotFound { connection_id: ConnectionId }, @@ -74,12 +74,12 @@ pub enum ConnectionError { FrozenClient { client_id: ClientId }, /// the connection proof verification failed ConnectionVerificationFailure, - /// the consensus proof verification failed (height: `{height}`) + /// the consensus proof verification failed (height: `{height}`), client error: `{client_error}` ConsensusStateVerificationFailure { height: Height, client_error: client_error::ClientError, }, - /// the client state proof verification failed for client id `{client_id}` + /// the client state proof verification failed for client id `{client_id}`, client error: `{client_error}` ClientStateVerificationFailure { // TODO: use more specific error source client_id: ClientId, diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index de54c6e21..5586657b3 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -122,9 +122,9 @@ pub enum ChannelError { #[derive(Debug, Display)] pub enum PacketError { - /// ICS03 connection error + /// connection error: `{0}` Connection(connection_error::ConnectionError), - /// ICS04 channel error + /// channel error: `{0}` Channel(ChannelError), /// Channel `{channel_id}` is Closed ChannelClosed { channel_id: ChannelId }, @@ -181,7 +181,7 @@ pub enum PacketError { MissingHeight, /// there is no packet in this message MissingPacket, - /// invalid signer address + /// invalid signer address error: `{0}` Signer(SignerError), /// application module error: `{description}` AppModule { description: String }, @@ -193,9 +193,9 @@ pub enum PacketError { InvalidTimeoutHeight, /// packet data bytes cannot be empty ZeroPacketData, - /// Invalid packet timeout timestamp value + /// Invalid packet timeout timestamp value error: `{0}` InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), - /// identifier error + /// identifier error: `{0}` Identifier(ValidationError), /// Missing sequence number for sending packets on port `{port_id}` and channel `{channel_id}` MissingNextSendSeq { diff --git a/crates/ibc/src/core/ics23_commitment/error.rs b/crates/ibc/src/core/ics23_commitment/error.rs index 84913768e..4f598bfe8 100644 --- a/crates/ibc/src/core/ics23_commitment/error.rs +++ b/crates/ibc/src/core/ics23_commitment/error.rs @@ -3,9 +3,9 @@ use prost::DecodeError; #[derive(Debug, Display)] pub enum CommitmentError { - /// invalid raw merkle proof + /// invalid raw merkle proof error: `{0}` InvalidRawMerkleProof(DecodeError), - /// failed to decode commitment proof + /// failed to decode commitment proof error: `{0}` CommitmentProofDecodingFailed(DecodeError), /// empty commitment prefix EmptyCommitmentPrefix, diff --git a/crates/ibc/src/core/ics26_routing/error.rs b/crates/ibc/src/core/ics26_routing/error.rs index 8fe95e2a2..6122b8265 100644 --- a/crates/ibc/src/core/ics26_routing/error.rs +++ b/crates/ibc/src/core/ics26_routing/error.rs @@ -5,11 +5,11 @@ use displaydoc::Display; #[derive(Debug, Display)] pub enum RouterError { - /// context error + /// context error: `{0}` ContextError(ContextError), /// unknown type URL `{url}` UnknownMessageTypeUrl { url: String }, - /// the message is malformed and cannot be decoded + /// the message is malformed and cannot be decoded error: `{0}` MalformedMessageBytes(ibc_proto::protobuf::Error), } diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index ada71ed21..f6e4e7ecc 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -20,21 +20,21 @@ use crate::timestamp::ParseTimestampError; pub enum Error { /// error parsing height Height, - /// parse error + /// parse error: `{0}` Parse(ValidationError), - /// ICS02 client error + /// client error: `{0}` Client(client_error::ClientError), - /// connection error + /// connection error: `{0}` Connection(connection_error::ConnectionError), - /// channel error + /// channel error: `{0}` Channel(channel_error::ChannelError), - /// error parsing timestamp + /// parsing timestamp error: `{0}` Timestamp(ParseTimestampError), /// missing event key `{key}` MissingKey { key: String }, - /// error decoding protobuf + /// decoding protobuf error: `{0}` Decode(prost::DecodeError), - /// error decoding hex + /// decoding hex error: `{0}` SubtleEncoding(subtle_encoding::Error), /// missing action string MissingActionString, diff --git a/crates/ibc/src/relayer/ics18_relayer/error.rs b/crates/ibc/src/relayer/ics18_relayer/error.rs index 9a443afe4..013cf46a7 100644 --- a/crates/ibc/src/relayer/ics18_relayer/error.rs +++ b/crates/ibc/src/relayer/ics18_relayer/error.rs @@ -20,9 +20,9 @@ pub enum RelayerError { source_height: Height, destination_height: Height, }, - /// transaction processing by modules failed + /// transaction processing by modules failed error: `{0}` TransactionFailed(RouterError), - /// ICS03 connection error(`{0}`) + /// connection error: `{0}` Connection(ics03_connection::error::ConnectionError), } diff --git a/crates/ibc/src/timestamp.rs b/crates/ibc/src/timestamp.rs index 8af96731c..191a11d2d 100644 --- a/crates/ibc/src/timestamp.rs +++ b/crates/ibc/src/timestamp.rs @@ -217,7 +217,7 @@ impl Sub for Timestamp { #[derive(Debug, Display)] pub enum ParseTimestampError { - /// error parsing u64 integer from string + /// parsing u64 integer from string error: `{0}` ParseInt(ParseIntError), } From 8f2bbe79a4a48283778f985d046806d2757c8c9b Mon Sep 17 00:00:00 2001 From: Davirain Date: Tue, 29 Nov 2022 13:17:01 +0800 Subject: [PATCH 41/43] Remove unused Error variant --- crates/ibc/src/applications/transfer/error.rs | 12 ----- .../ibc/src/clients/ics07_tendermint/error.rs | 42 ----------------- crates/ibc/src/core/ics02_client/error.rs | 46 ------------------- crates/ibc/src/core/ics03_connection/error.rs | 20 -------- crates/ibc/src/core/ics04_channel/error.rs | 21 --------- crates/ibc/src/core/ics05_port/error.rs | 4 -- crates/ibc/src/core/ics24_host/error.rs | 2 - crates/ibc/src/events.rs | 9 ---- 8 files changed, 156 deletions(-) diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index da341b1b3..19f81a764 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -4,7 +4,6 @@ use core::convert::Infallible; use core::str::Utf8Error; use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; -use subtle_encoding::Error as EncodingError; use uint::FromDecStrErr; use crate::core::ics04_channel::channel::Order; @@ -17,8 +16,6 @@ use crate::signer::SignerError; #[derive(Display, Debug)] pub enum TokenTransferError { - /// unrecognized ICS-20 transfer message type URL `{url}` - UnknowMessageTypeUrl { url: String }, /// packet error: `{0}` PacketError(channel_error::PacketError), /// destination channel not found in the counterparty of port_id `{port_id}` and channel_id `{channel_id}` @@ -62,12 +59,6 @@ pub enum TokenTransferError { InvalidToken, /// failed to parse signer error: `{0}` Signer(SignerError), - /// missing 'ibc/' prefix in denomination - MissingDenomIbcPrefix, - /// hashed denom must be of the form 'ibc/Hash' - MalformedHashDenom, - /// invalid hex string error: `{0}` - ParseHex(EncodingError), /// expected `{expect_order}` channel, got `{got_order}` ChannelNotUnordered { expect_order: Order, @@ -100,8 +91,6 @@ pub enum TokenTransferError { port_id: PortId, exp_port_id: PortId, }, - /// no trace associated with specified hash - TraceNotFound, /// decoding raw msg error: `{0}` DecodeRawMsg(TendermintProtoError), /// unknown msg type: `{msg_type}` @@ -136,7 +125,6 @@ impl std::error::Error for TokenTransferError { } => Some(e), Self::InvalidAmount(e) => Some(e), Self::Signer(e) => Some(e), - Self::ParseHex(e) => Some(e), Self::DecodeRawMsg(e) => Some(e), Self::Utf8Decode(e) => Some(e), _ => None, diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index 9fc29d8b6..fc2936175 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -1,14 +1,12 @@ use crate::prelude::*; use crate::core::ics02_client::error::ClientError; -use crate::core::ics24_host::error::ValidationError; use crate::core::ics24_host::identifier::{ChainId, ClientId}; use crate::timestamp::{Timestamp, TimestampOverflowError}; use displaydoc::Display; use crate::Height; use tendermint::account::Id; -use tendermint::hash::Hash; use tendermint::Error as TendermintError; use tendermint_light_client_verifier::errors::VerificationErrorDetail as LightClientErrorDetail; @@ -20,12 +18,6 @@ pub enum Error { len: usize, max_len: usize, }, - /// invalid trusting period: `{reason}` - InvalidTrustingPeriod { reason: String }, - /// invalid unbonding period: `{reason}` - InvalidUnbondingPeriod { reason: String }, - /// invalid address - InvalidAddress, /// invalid header, failed basic validation: `{reason}`, error: `{error}` InvalidHeader { reason: String, @@ -55,27 +47,10 @@ pub enum Error { MissingTrustingPeriod, /// missing unbonding period MissingUnbondingPeriod, - /// invalid chain identifier error: `{0}` - InvalidChainIdentifier(ValidationError), - /// negative trusting period - NegativeTrustingPeriod, - /// negative unbonding period - NegativeUnbondingPeriod, - /// missing max clock drift - MissingMaxClockDrift, /// negative max clock drift NegativeMaxClockDrift, /// missing latest height MissingLatestHeight, - /// invalid frozen height - InvalidFrozenHeight, - /// invalid chain identifier: `{raw_value}`, validation error: `{error}` - InvalidChainId { - raw_value: String, - error: ValidationError, - }, - /// invalid raw height: `{raw_height}` - InvalidRawHeight { raw_height: u64 }, /// invalid raw client consensus state: `{reason}` InvalidRawConsensusState { reason: String }, /// invalid raw header error: `{0}` @@ -84,12 +59,6 @@ pub enum Error { InvalidRawMisbehaviour { reason: String }, /// decode error: `{0}` Decode(prost::DecodeError), - /// insufficient overlap: `{reason}` - InsufficientVotingPower { reason: String }, - /// header timestamp `{low}` must be greater than current client consensus state timestamp `{high}` - LowUpdateTimestamp { low: String, high: String }, - /// header timestamp `{low}` is outside the trusting period w.r.t. consensus state timestamp `{high}` - HeaderTimestampOutsideTrustingTime { low: String, high: String }, /// given other previous updates, header timestamp should be at most `{max}`, but was `{actual}` HeaderTimestampTooHigh { actual: String, max: String }, /// given other previous updates, header timestamp should be at least `{min}`, but was `{actual}` @@ -108,20 +77,11 @@ pub enum Error { }, /// header revision height = `{height}` is invalid InvalidHeaderHeight { height: u64 }, - /// header height is `{height_header}` and is lower than the trusted header height, which is `{trusted_header_height}` - InvalidTrustedHeaderHeight { - trusted_header_height: Height, - height_header: Height, - }, - /// header height is `{low}` but it must be greater than the current client height which is `{high}` - LowUpdateHeight { low: Height, high: Height }, /// the header's current/trusted revision number (`{current_revision}`) and the update's revision number (`{update_revision}`) should be the same MismatchedRevisions { current_revision: u64, update_revision: u64, }, - /// invalid validator set: header_validators_hash=`{hash1}` and validators_hash=`{hash2}` - InvalidValidatorSet { hash1: Hash, hash2: Hash }, /// not enough trust because insufficient validators overlap: `{reason}` NotEnoughTrustedValsSigned { reason: String }, /// verification failed: `{detail}` @@ -148,8 +108,6 @@ impl std::error::Error for Error { match &self { Error::InvalidHeader { error: e, .. } => Some(e), Error::InvalidTendermintTrustThreshold(e) => Some(e), - Error::InvalidChainIdentifier(e) => Some(e), - Error::InvalidChainId { error: e, .. } => Some(e), Error::InvalidRawHeader(e) => Some(e), Error::Decode(e) => Some(e), Error::TimestampOverflow(e) => Some(e), diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 873d758ce..171cd8dd1 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -3,7 +3,6 @@ use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; use crate::core::ics02_client::client_type::ClientType; -use crate::core::ics02_client::height::HeightError; use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics24_host::error::ValidationError; use crate::core::ics24_host::identifier::ClientId; @@ -13,16 +12,12 @@ use crate::Height; #[derive(Debug, Display)] pub enum ClientError { - /// unknown client type: `{client_type}` - UnknownClientType { client_type: String }, /// Client identifier constructor failed for type `{client_type}` with counter `{counter}`, validation error: `{validation_error}` ClientIdentifierConstructor { client_type: ClientType, counter: u64, validation_error: ValidationError, }, - /// client already exists: `{client_id}` - ClientAlreadyExists { client_id: ClientId }, /// client not found: `{client_id}` ClientNotFound { client_id: ClientId }, /// client is frozen: `{client_id}` @@ -39,25 +34,12 @@ pub enum ClientError { FailedTrustThresholdConversion { numerator: u64, denominator: u64 }, /// unknown client state type: `{client_state_type}` UnknownClientStateType { client_state_type: String }, - /// the client state was not found - EmptyClientStateResponse, /// empty prefix EmptyPrefix, /// unknown client consensus state type: `{consensus_state_type}` UnknownConsensusStateType { consensus_state_type: String }, - /// the client consensus state was not found - EmptyConsensusStateResponse, /// unknown header type: `{header_type}` UnknownHeaderType { header_type: String }, - /// unknown misbehaviour type: `{misbehavior_type}` - UnknownMisbehaviourType { misbehavior_type: String }, - /// invalid raw client identifier `{client_id}`, validation error: `{validation_error}` - InvalidRawClientId { - client_id: String, - validation_error: ValidationError, - }, - /// decoding raw client state error: `{0}` - DecodeRawClientState(TendermintProtoError), /// missing raw client state MissingRawClientState, /// invalid raw client consensus state error: `{0}` @@ -77,22 +59,13 @@ pub enum ClientError { /// missing raw header MissingRawHeader, /// invalid raw misbehaviour error: `{0}` - DecodeRawMisbehaviour(TendermintProtoError), - /// invalid raw misbehaviour error: `{0}` InvalidRawMisbehaviour(ValidationError), /// missing raw misbehaviour MissingRawMisbehaviour, - /// String `{value}` cannnot be converted to height, height error: `{height_error}` - InvalidStringAsHeight { - value: String, - height_error: HeightError, - }, /// revision height cannot be zero InvalidHeight, /// height cannot end up zero or negative InvalidHeightResult, - /// invalid address - InvalidAddress, /// invalid proof for the upgraded client state error: `{0}` InvalidUpgradeClientProof(CommitmentError), /// invalid proof for the upgraded consensus state error: `{0}` @@ -103,13 +76,6 @@ pub enum ClientError { InvalidPacketTimestamp(crate::timestamp::ParseTimestampError), /// mismatch between client and arguments types ClientArgsTypeMismatch { client_type: ClientType }, - /// Insufficient overlap `{reason}` - InsufficientVotingPower { reason: String }, - /// mismatch in raw client consensus state `{state_type}` with expected state `{consensus_type}` - RawClientAndConsensusStateTypesMismatch { - state_type: ClientType, - consensus_type: ClientType, - }, /// received header height (`{header_height}`) is lower than (or equal to) client latest height (`{latest_height}`) LowHeaderHeight { header_height: Height, @@ -133,8 +99,6 @@ pub enum ClientError { InvalidConnectionEnd(TendermintProtoError), /// invalid channel end error: `{0}` InvalidChannelEnd(TendermintProtoError), - /// invalid any client state error: `{0}` - InvalidAnyClientState(TendermintProtoError), /// invalid any client consensus state error: `{0}` InvalidAnyConsensusState(TendermintProtoError), /// failed to parse signer error: `{0}` @@ -155,28 +119,18 @@ impl std::error::Error for ClientError { validation_error: e, .. } => Some(e), - Self::InvalidRawClientId { - validation_error: e, - .. - } => Some(e), - Self::DecodeRawClientState(e) => Some(e), Self::InvalidRawConsensusState(e) => Some(e), Self::InvalidMsgUpdateClientId(e) => Some(e), Self::Decode(e) => Some(e), Self::InvalidClientIdentifier(e) => Some(e), Self::InvalidRawHeader(e) => Some(e), - Self::DecodeRawMisbehaviour(e) => Some(e), Self::InvalidRawMisbehaviour(e) => Some(e), - Self::InvalidStringAsHeight { - height_error: e, .. - } => Some(e), Self::InvalidUpgradeClientProof(e) => Some(e), Self::InvalidUpgradeConsensusStateProof(e) => Some(e), Self::InvalidCommitmentProof(e) => Some(e), Self::InvalidPacketTimestamp(e) => Some(e), Self::InvalidConnectionEnd(e) => Some(e), Self::InvalidChannelEnd(e) => Some(e), - Self::InvalidAnyClientState(e) => Some(e), Self::InvalidAnyConsensusState(e) => Some(e), Self::Signer(e) => Some(e), Self::Ics23Verification(e) => Some(e), diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index eccf5c924..aa5b62472 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -15,8 +15,6 @@ pub enum ConnectionError { Client(client_error::ClientError), /// connection state is unknown: `{state}` InvalidState { state: i32 }, - /// connection exists (was initialized) already: `{connection_id}` - ConnectionExistsAlready { connection_id: ConnectionId }, /// connection end for identifier `{connection_id}` was never initialized ConnectionMismatch { connection_id: ConnectionId }, /// consensus height claimed by the client on the other party is too advanced: `{target_height}` (host chain current height: `{current_height}`) @@ -24,11 +22,6 @@ pub enum ConnectionError { target_height: Height, current_height: Height, }, - /// consensus height claimed by the client on the other party has been pruned: `{target_height}` (host chain oldest height: `{oldest_height}`) - StaleConsensusHeight { - target_height: Height, - oldest_height: Height, - }, /// identifier error: `{0}` InvalidIdentifier(ValidationError), /// ConnectionEnd domain object could not be constructed out of empty proto object @@ -41,8 +34,6 @@ pub enum ConnectionError { NoCommonVersion, /// version \"`{version}`\" not supported VersionNotSupported { version: Version }, - /// invalid address - InvalidAddress, /// missing proof height MissingProofHeight, /// missing consensus height @@ -57,23 +48,12 @@ pub enum ConnectionError { ConnectionNotFound { connection_id: ConnectionId }, /// invalid counterparty InvalidCounterparty, - /// counterparty chosen connection id `{connection_id}` is different than the connection id `{counterparty_connection_id}` - ConnectionIdMismatch { - connection_id: ConnectionId, - counterparty_connection_id: ConnectionId, - }, /// missing counterparty MissingCounterparty, - /// missing counterparty prefix - MissingCounterpartyPrefix, /// missing client state MissingClientState, - /// client proof must be present - NullClientProof, /// the client id does not match any client state: `{client_id}` FrozenClient { client_id: ClientId }, - /// the connection proof verification failed - ConnectionVerificationFailure, /// the consensus proof verification failed (height: `{height}`), client error: `{client_error}` ConsensusStateVerificationFailure { height: Height, diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 5586657b3..a883f6d89 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -23,7 +23,6 @@ pub enum ChannelError { Port(port_error::PortError), /// channel state unknown: `{state}` UnknownState { state: i32 }, - /// channel order type unknown: `{type_id}` UnknownOrderType { type_id: String }, /// invalid connection hops length: expected `{expected}`; actual `{actual}` @@ -32,19 +31,14 @@ pub enum ChannelError { InvalidVersion(TendermintError), /// invalid signer address Signer(SignerError), - /// invalid proof: missing height MissingHeight, - /// packet data bytes must be valid UTF-8 (this restriction will be lifted in the future) NonUtf8PacketData, - /// invalid packet InvalidPacket, /// there is no packet in this message MissingPacket, - /// missing channel id - MissingChannelId, /// missing counterparty MissingCounterparty, /// no commong version @@ -60,9 +54,6 @@ pub enum ChannelError { port_id: PortId, channel_id: ChannelId, }, - /// a different channel exists (was initialized) already for the same channel identifier `{channel_id}` - ChannelMismatch { channel_id: ChannelId }, - /// Verification fails for the packet with the sequence number `{sequence}`, error(`{ics02_error}`) PacketVerificationFailed { sequence: Sequence, @@ -70,33 +61,21 @@ pub enum ChannelError { }, /// Error verifying channel state VerifyChannelFailed(client_error::ClientError), - /// String `{value}` cannot be converted to packet sequence InvalidStringAsSequence { value: String, error: core::num::ParseIntError, }, - - /// Invalid timestamp in consensus state; timestamp must be a positive value - ErrorInvalidConsensusState, - /// Invalid channel id in counterparty InvalidCounterpartyChannelId, - - /// Handshake proof verification fails at ChannelOpenAck - ChanOpenAckProofVerification, - /// Processed time for the client `{client_id}` at height `{height}` not found ProcessedTimeNotFound { client_id: ClientId, height: Height }, /// Processed height for the client `{client_id}` at height `{height}` not found ProcessedHeightNotFound { client_id: ClientId, height: Height }, /// route not found RouteNotFound, - /// application module error: `{description}` AppModule { description: String }, - /// Failed to convert abci event to IbcEvent: `{abci_event}` - AbciConversionFailed { abci_event: String }, /// other error: `{description}` Other { description: String }, /// Channel `{channel_id}` is Closed diff --git a/crates/ibc/src/core/ics05_port/error.rs b/crates/ibc/src/core/ics05_port/error.rs index c55445f18..df60125f2 100644 --- a/crates/ibc/src/core/ics05_port/error.rs +++ b/crates/ibc/src/core/ics05_port/error.rs @@ -5,10 +5,6 @@ use displaydoc::Display; pub enum PortError { /// port `{port_id}` is unknown UnknownPort { port_id: PortId }, - /// port `{port_id}` is already bound - PortAlreadyBound { port_id: PortId }, - /// could not retrieve module from port `{port_id}` - ModuleNotFound { port_id: PortId }, /// implementation specific error ImplementationSpecific, } diff --git a/crates/ibc/src/core/ics24_host/error.rs b/crates/ibc/src/core/ics24_host/error.rs index 5fdcf932a..dfba80610 100644 --- a/crates/ibc/src/core/ics24_host/error.rs +++ b/crates/ibc/src/core/ics24_host/error.rs @@ -17,8 +17,6 @@ pub enum ValidationError { InvalidCharacter { id: String }, /// identifier cannot be empty Empty, - /// chain identifiers are expected to be in epoch format `{id}` - ChainIdInvalidFormat { id: String }, /// Invalid channel id in counterparty InvalidCounterpartyChannelId, } diff --git a/crates/ibc/src/events.rs b/crates/ibc/src/events.rs index f6e4e7ecc..ef7793832 100644 --- a/crates/ibc/src/events.rs +++ b/crates/ibc/src/events.rs @@ -30,20 +30,12 @@ pub enum Error { Channel(channel_error::ChannelError), /// parsing timestamp error: `{0}` Timestamp(ParseTimestampError), - /// missing event key `{key}` - MissingKey { key: String }, /// decoding protobuf error: `{0}` Decode(prost::DecodeError), - /// decoding hex error: `{0}` - SubtleEncoding(subtle_encoding::Error), - /// missing action string - MissingActionString, /// incorrect event type: `{event}` IncorrectEventType { event: String }, /// module event cannot use core event types: `{event:?}` MalformedModuleEvent { event: ModuleEvent }, - /// Unable to parse abci event type `{event_type}` into IbcEvent" - UnsupportedAbciEvent { event_type: String }, } #[cfg(feature = "std")] @@ -56,7 +48,6 @@ impl std::error::Error for Error { Self::Channel(e) => Some(e), Self::Timestamp(e) => Some(e), Self::Decode(e) => Some(e), - Self::SubtleEncoding(e) => Some(e), _ => None, } } From 2eeaff75b1a64faea798c8e17049c67015deb099 Mon Sep 17 00:00:00 2001 From: Davirain Date: Wed, 30 Nov 2022 12:17:47 +0800 Subject: [PATCH 42/43] Remove unused Error variant --- crates/ibc/src/applications/transfer/error.rs | 5 --- .../ibc/src/clients/ics07_tendermint/error.rs | 12 +++--- crates/ibc/src/core/ics02_client/error.rs | 6 --- crates/ibc/src/core/ics03_connection/error.rs | 4 -- crates/ibc/src/core/ics04_channel/error.rs | 37 +++++++------------ .../src/core/ics04_channel/handler/verify.rs | 8 ++-- 6 files changed, 22 insertions(+), 50 deletions(-) diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index 19f81a764..d2f89830d 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -1,5 +1,3 @@ -use alloc::string::FromUtf8Error; - use core::convert::Infallible; use core::str::Utf8Error; use displaydoc::Display; @@ -37,8 +35,6 @@ pub enum TokenTransferError { InvalidPacketTimeoutHeight { context: String }, /// invalid packet timeout timestamp value `{timestamp}` InvalidPacketTimeoutTimestamp { timestamp: u64 }, - /// utf8 decoding error: `{0}` - Utf8(FromUtf8Error), /// base denomination is empty EmptyBaseDenom, /// invalid prot id n trace at postion: `{pos}`, validation error: `{validation_error}` @@ -114,7 +110,6 @@ impl std::error::Error for TokenTransferError { validation_error: e, .. } => Some(e), - Self::Utf8(e) => Some(e), Self::InvalidTracePortId { validation_error: e, .. diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index fc2936175..5b18f2067 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -51,8 +51,6 @@ pub enum Error { NegativeMaxClockDrift, /// missing latest height MissingLatestHeight, - /// invalid raw client consensus state: `{reason}` - InvalidRawConsensusState { reason: String }, /// invalid raw header error: `{0}` InvalidRawHeader(TendermintError), /// invalid raw misbehaviour: `{reason}` @@ -106,11 +104,11 @@ pub enum Error { impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Error::InvalidHeader { error: e, .. } => Some(e), - Error::InvalidTendermintTrustThreshold(e) => Some(e), - Error::InvalidRawHeader(e) => Some(e), - Error::Decode(e) => Some(e), - Error::TimestampOverflow(e) => Some(e), + Self::InvalidHeader { error: e, .. } => Some(e), + Self::InvalidTendermintTrustThreshold(e) => Some(e), + Self::InvalidRawHeader(e) => Some(e), + Self::Decode(e) => Some(e), + Self::TimestampOverflow(e) => Some(e), _ => None, } } diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 171cd8dd1..914c330d2 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -42,16 +42,12 @@ pub enum ClientError { UnknownHeaderType { header_type: String }, /// missing raw client state MissingRawClientState, - /// invalid raw client consensus state error: `{0}` - InvalidRawConsensusState(TendermintProtoError), /// missing raw client consensus state MissingRawConsensusState, /// invalid client id in the update client message: `{0}` InvalidMsgUpdateClientId(ValidationError), /// decode error: `{0}` Decode(prost::DecodeError), - /// invalid raw client consensus state: the height field is missing - MissingHeight, /// invalid client identifier error: `{0}` InvalidClientIdentifier(ValidationError), /// invalid raw header error: `{0}` @@ -119,9 +115,7 @@ impl std::error::Error for ClientError { validation_error: e, .. } => Some(e), - Self::InvalidRawConsensusState(e) => Some(e), Self::InvalidMsgUpdateClientId(e) => Some(e), - Self::Decode(e) => Some(e), Self::InvalidClientIdentifier(e) => Some(e), Self::InvalidRawHeader(e) => Some(e), Self::InvalidRawMisbehaviour(e) => Some(e), diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index aa5b62472..0b7da9b82 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -52,8 +52,6 @@ pub enum ConnectionError { MissingCounterparty, /// missing client state MissingClientState, - /// the client id does not match any client state: `{client_id}` - FrozenClient { client_id: ClientId }, /// the consensus proof verification failed (height: `{height}`), client error: `{client_error}` ConsensusStateVerificationFailure { height: Height, @@ -65,8 +63,6 @@ pub enum ConnectionError { client_id: ClientId, client_error: client_error::ClientError, }, - /// implementation specific error - ImplementationSpecific, /// invalid client state: `{reason}` InvalidClientState { reason: String }, /// other error: `{description}` diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index a883f6d89..4f39b6c44 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -13,13 +13,12 @@ use crate::timestamp::Timestamp; use crate::Height; use displaydoc::Display; -use ibc_proto::protobuf::Error as TendermintError; #[derive(Debug, Display)] pub enum ChannelError { - /// ICS03 connection error + /// connection error: `{0}` Connection(connection_error::ConnectionError), - /// ICS05 port error + /// port error: `{0}` Port(port_error::PortError), /// channel state unknown: `{state}` UnknownState { state: i32 }, @@ -27,18 +26,12 @@ pub enum ChannelError { UnknownOrderType { type_id: String }, /// invalid connection hops length: expected `{expected}`; actual `{actual}` InvalidConnectionHopsLength { expected: usize, actual: usize }, - /// invalid version - InvalidVersion(TendermintError), - /// invalid signer address + /// invalid signer address error: `{0}` Signer(SignerError), /// invalid proof: missing height MissingHeight, /// packet data bytes must be valid UTF-8 (this restriction will be lifted in the future) NonUtf8PacketData, - /// invalid packet - InvalidPacket, - /// there is no packet in this message - MissingPacket, /// missing counterparty MissingCounterparty, /// no commong version @@ -54,14 +47,14 @@ pub enum ChannelError { port_id: PortId, channel_id: ChannelId, }, - /// Verification fails for the packet with the sequence number `{sequence}`, error(`{ics02_error}`) + /// Verification fails for the packet with the sequence number `{sequence}`, error: `{client_error}` PacketVerificationFailed { sequence: Sequence, - ics02_error: client_error::ClientError, + client_error: client_error::ClientError, }, - /// Error verifying channel state + /// Error verifying channel state error: `{0}` VerifyChannelFailed(client_error::ClientError), - /// String `{value}` cannot be converted to packet sequence + /// String `{value}` cannot be converted to packet sequence, error: `{error}` InvalidStringAsSequence { value: String, error: core::num::ParseIntError, @@ -88,15 +81,10 @@ pub enum ChannelError { FrozenClient { client_id: ClientId }, /// Channel `{channel_id}` should not be state `{state}` InvalidChannelState { channel_id: ChannelId, state: State }, - /// invalid proof + /// invalid proof error: `{0}` InvalidProof(ProofError), - /// identifier error + /// identifier error: `{0}` Identifier(ValidationError), - /// Missing sequence number for sending packets on port `{port_id}` and channel `{channel_id}` - MissingNextSendSeq { - port_id: PortId, - channel_id: ChannelId, - }, } #[derive(Debug, Display)] @@ -138,7 +126,7 @@ pub enum PacketError { ImplementationSpecific, /// Undefined counterparty connection for `{connection_id}` UndefinedConnectionCounterparty { connection_id: ConnectionId }, - /// invalid proof + /// invalid proof: `{0}` InvalidProof(ProofError), /// Packet timeout height `{timeout_height}` > chain height `{chain_height}` PacketTimeoutHeightNotReached { @@ -221,10 +209,11 @@ impl std::error::Error for ChannelError { Self::Connection(e) => Some(e), Self::Port(e) => Some(e), Self::Identifier(e) => Some(e), - Self::InvalidVersion(e) => Some(e), Self::Signer(e) => Some(e), Self::InvalidProof(e) => Some(e), - Self::PacketVerificationFailed { ics02_error: e, .. } => Some(e), + Self::PacketVerificationFailed { + client_error: e, .. + } => Some(e), Self::InvalidStringAsSequence { error: e, .. } => Some(e), _ => None, } diff --git a/crates/ibc/src/core/ics04_channel/handler/verify.rs b/crates/ibc/src/core/ics04_channel/handler/verify.rs index b4fc42667..f52b8951c 100644 --- a/crates/ibc/src/core/ics04_channel/handler/verify.rs +++ b/crates/ibc/src/core/ics04_channel/handler/verify.rs @@ -88,7 +88,7 @@ pub fn verify_packet_recv_proofs( ) .map_err(|e| ChannelError::PacketVerificationFailed { sequence: packet.sequence, - ics02_error: e, + client_error: e, })?; Ok(()) @@ -132,7 +132,7 @@ pub fn verify_packet_acknowledgement_proofs( ) .map_err(|e| ChannelError::PacketVerificationFailed { sequence: packet.sequence, - ics02_error: e, + client_error: e, })?; Ok(()) @@ -173,7 +173,7 @@ pub fn verify_next_sequence_recv( ) .map_err(|e| ChannelError::PacketVerificationFailed { sequence: seq, - ics02_error: e, + client_error: e, })?; Ok(()) @@ -212,7 +212,7 @@ pub fn verify_packet_receipt_absence( ) .map_err(|e| ChannelError::PacketVerificationFailed { sequence: packet.sequence, - ics02_error: e, + client_error: e, })?; Ok(()) From bba5a6d659c9df8cd75c758401c2ceb8ba10107b Mon Sep 17 00:00:00 2001 From: Davirain Date: Thu, 1 Dec 2022 00:50:23 +0800 Subject: [PATCH 43/43] Update 164-refactor-error-system.md --- .changelog/unreleased/enhancement/164-refactor-error-system.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changelog/unreleased/enhancement/164-refactor-error-system.md b/.changelog/unreleased/enhancement/164-refactor-error-system.md index c8d0d1176..571f327f8 100644 --- a/.changelog/unreleased/enhancement/164-refactor-error-system.md +++ b/.changelog/unreleased/enhancement/164-refactor-error-system.md @@ -1 +1 @@ -- Refactor error system ([#164](https://github.com/cosmos/ibc-rs/issues/164)) \ No newline at end of file +- Remove `flex-error` and remove unused error variants([#164](https://github.com/cosmos/ibc-rs/issues/164)) \ No newline at end of file