From c20e4915b8b38a7a7d648e91ea0ee4f931693fee Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 14 Jul 2023 16:30:56 -0700 Subject: [PATCH 001/182] fix: use `Vec` for header attribute instead of `Any` (#766) * fix(api): use Vec for HeaderAttribute instead of Any * misc: add unclog --- .../764-use-vec-for-header-attribute.md | 2 ++ crates/ibc/src/core/ics02_client/events.rs | 11 +++++------ .../src/core/ics02_client/handler/update_client.rs | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/764-use-vec-for-header-attribute.md diff --git a/.changelog/unreleased/breaking-changes/764-use-vec-for-header-attribute.md b/.changelog/unreleased/breaking-changes/764-use-vec-for-header-attribute.md new file mode 100644 index 000000000..dcedb279d --- /dev/null +++ b/.changelog/unreleased/breaking-changes/764-use-vec-for-header-attribute.md @@ -0,0 +1,2 @@ +- Use Vec for HeaderAttribute instead of Any + ([#764](https://github.com/cosmos/ibc-rs/issues/764)) diff --git a/crates/ibc/src/core/ics02_client/events.rs b/crates/ibc/src/core/ics02_client/events.rs index c216521b1..8d9f87b65 100644 --- a/crates/ibc/src/core/ics02_client/events.rs +++ b/crates/ibc/src/core/ics02_client/events.rs @@ -2,7 +2,6 @@ use crate::prelude::*; use derive_more::From; -use ibc_proto::google::protobuf::Any; use subtle_encoding::hex; use tendermint::abci; @@ -147,14 +146,14 @@ impl From for abci::EventAttribute { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, From, PartialEq, Eq)] struct HeaderAttribute { - header: Any, + header: Vec, } impl From for abci::EventAttribute { fn from(attr: HeaderAttribute) -> Self { ( HEADER_ATTRIBUTE_KEY, - String::from_utf8(hex::encode(attr.header.value)) + String::from_utf8(hex::encode(attr.header)) .expect("Never fails because hexadecimal is valid UTF-8"), ) .into() @@ -252,7 +251,7 @@ impl UpdateClient { client_type: ClientType, consensus_height: Height, consensus_heights: Vec, - header: Any, + header: Vec, ) -> Self { Self { client_id: ClientIdAttribute::from(client_id), @@ -279,7 +278,7 @@ impl UpdateClient { self.consensus_heights.consensus_heights.as_ref() } - pub fn header(&self) -> &Any { + pub fn header(&self) -> &Vec { &self.header.header } @@ -471,7 +470,7 @@ mod tests { client_type.clone(), consensus_height, consensus_heights, - header, + header.value, ) .into(), expected_keys: expected_keys.clone(), 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 4b88d77cc..3499dac35 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -114,7 +114,7 @@ where client_state.client_type(), *consensus_height, consensus_heights, - header, + header.value, )) }; ctx.emit_ibc_event(IbcEvent::Message(MessageEvent::Client)); @@ -488,7 +488,7 @@ mod tests { assert_eq!(update_client_event.client_type(), &mock_client_type()); assert_eq!(update_client_event.consensus_height(), &height); assert_eq!(update_client_event.consensus_heights(), &vec![height]); - assert_eq!(update_client_event.header(), &header); + assert_eq!(update_client_event.header(), &header.value); } fn ensure_misbehaviour(ctx: &MockContext, client_id: &ClientId, client_type: &ClientType) { From 1be66995222fa0db750a32819153ccefac7024e3 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Mon, 17 Jul 2023 17:50:21 -0700 Subject: [PATCH 002/182] test: include `PacketData` serde test to keep proper JSON encoding (#765) * test: include PacketData test to keep proper JSON encoding * misc: add unclog * Update crates/ibc/src/applications/transfer/packet.rs Co-authored-by: Rano | Ranadeep Signed-off-by: Farhad Shabani * imp: add dummy_json_packet_data function --------- Signed-off-by: Farhad Shabani Co-authored-by: Rano | Ranadeep --- .../745-scale-encoding-for-transfer-packet.md | 0 ...3-include-PacketData-JSON-encoding-test.md | 2 + .../applications/transfer/msgs/transfer.rs | 89 +++++++------------ .../ibc/src/applications/transfer/packet.rs | 54 +++++++++++ crates/ibc/src/core/handler.rs | 32 ++----- 5 files changed, 96 insertions(+), 81 deletions(-) rename .changelog/unreleased/{improvement => improvements}/745-scale-encoding-for-transfer-packet.md (100%) create mode 100644 .changelog/unreleased/improvements/763-include-PacketData-JSON-encoding-test.md diff --git a/.changelog/unreleased/improvement/745-scale-encoding-for-transfer-packet.md b/.changelog/unreleased/improvements/745-scale-encoding-for-transfer-packet.md similarity index 100% rename from .changelog/unreleased/improvement/745-scale-encoding-for-transfer-packet.md rename to .changelog/unreleased/improvements/745-scale-encoding-for-transfer-packet.md diff --git a/.changelog/unreleased/improvements/763-include-PacketData-JSON-encoding-test.md b/.changelog/unreleased/improvements/763-include-PacketData-JSON-encoding-test.md new file mode 100644 index 000000000..1088b2467 --- /dev/null +++ b/.changelog/unreleased/improvements/763-include-PacketData-JSON-encoding-test.md @@ -0,0 +1,2 @@ +- Add test to ensure `PacketData`` keeps proper JSON encoding + ([#763](https://github.com/cosmos/ibc-rs/issues/763)) diff --git a/crates/ibc/src/applications/transfer/msgs/transfer.rs b/crates/ibc/src/applications/transfer/msgs/transfer.rs index 746386f26..0b22755aa 100644 --- a/crates/ibc/src/applications/transfer/msgs/transfer.rs +++ b/crates/ibc/src/applications/transfer/msgs/transfer.rs @@ -127,71 +127,44 @@ pub mod test_util { use core::ops::Add; use core::time::Duration; - use primitive_types::U256; use super::MsgTransfer; use crate::applications::transfer::packet::PacketData; - use crate::applications::transfer::Coin; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::core::ics04_channel::timeout::TimeoutHeight; - use crate::signer::Signer; - use crate::{ - applications::transfer::BaseCoin, - core::ics24_host::identifier::{ChannelId, PortId}, - test_utils::get_dummy_bech32_account, - }; - - // Returns a dummy ICS20 `MsgTransfer`. If no `timeout_timestamp` is - // specified, a timestamp of 10 seconds in the future is used. - pub fn get_dummy_msg_transfer( - timeout_height: TimeoutHeight, - timeout_timestamp: Option, - ) -> MsgTransfer { - let address: Signer = get_dummy_bech32_account().into(); - MsgTransfer { - port_id_on_a: PortId::default(), - chan_id_on_a: ChannelId::default(), - packet_data: PacketData { - token: BaseCoin { - denom: "uatom".parse().unwrap(), - amount: U256::from(10).into(), - } - .into(), - sender: address.clone(), - receiver: address, - memo: "".to_owned().into(), - }, - timeout_timestamp_on_b: timeout_timestamp - .unwrap_or_else(|| Timestamp::now().add(Duration::from_secs(10)).unwrap()), - timeout_height_on_b: timeout_height, + use crate::core::ics24_host::identifier::{ChannelId, PortId}; + + impl MsgTransfer { + // Returns a dummy ICS20 `MsgTransfer`. If no `timeout_timestamp` is + // specified, a timestamp of 10 seconds in the future is used. + pub fn new_dummy( + timeout_height: TimeoutHeight, + timeout_timestamp: Option, + ) -> Self { + Self { + port_id_on_a: PortId::default(), + chan_id_on_a: ChannelId::default(), + packet_data: PacketData::new_dummy(), + timeout_timestamp_on_b: timeout_timestamp + .unwrap_or_else(|| Timestamp::now().add(Duration::from_secs(10)).unwrap()), + timeout_height_on_b: timeout_height, + } } - } - pub fn get_dummy_transfer_packet(msg: MsgTransfer, sequence: Sequence) -> Packet { - let coin = Coin { - denom: msg.packet_data.token.denom.clone(), - amount: msg.packet_data.token.amount, - }; - - let data = { - let data = PacketData { - token: coin, - sender: msg.packet_data.sender.clone(), - receiver: msg.packet_data.receiver.clone(), - memo: msg.packet_data.memo.clone(), - }; - serde_json::to_vec(&data).expect("PacketData's infallible Serialize impl failed") - }; - - Packet { - seq_on_a: sequence, - port_id_on_a: msg.port_id_on_a, - chan_id_on_a: msg.chan_id_on_a, - port_id_on_b: PortId::default(), - chan_id_on_b: ChannelId::default(), - data, - timeout_height_on_b: msg.timeout_height_on_b, - timeout_timestamp_on_b: msg.timeout_timestamp_on_b, + pub fn get_transfer_packet(&self, sequence: Sequence) -> Packet { + let data = serde_json::to_vec(&self.packet_data) + .expect("PacketData's infallible Serialize impl failed"); + + Packet { + seq_on_a: sequence, + port_id_on_a: self.port_id_on_a.clone(), + chan_id_on_a: self.chan_id_on_a.clone(), + port_id_on_b: PortId::default(), + chan_id_on_b: ChannelId::default(), + data, + timeout_height_on_b: self.timeout_height_on_b, + timeout_timestamp_on_b: self.timeout_timestamp_on_b, + } } } } diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index 89f1d5b4e..882003f48 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -55,3 +55,57 @@ impl From for RawPacketData { } } } + +#[cfg(test)] +mod tests { + + use super::*; + use crate::applications::transfer::BaseCoin; + use crate::test_utils::get_dummy_bech32_account; + use primitive_types::U256; + + impl PacketData { + pub fn new_dummy() -> Self { + let address: Signer = get_dummy_bech32_account().into(); + + Self { + token: BaseCoin { + denom: "uatom".parse().unwrap(), + amount: U256::from(10).into(), + } + .into(), + sender: address.clone(), + receiver: address, + memo: "".to_string().into(), + } + } + + pub fn ser_json_assert_eq(&self, json: &str) { + let ser = serde_json::to_string(&self).unwrap(); + assert_eq!(ser, json); + } + + pub fn deser_json_assert_eq(&self, json: &str) { + let deser: Self = serde_json::from_str(json).unwrap(); + assert_eq!(&deser, self); + } + } + + pub fn dummy_json_packet_data() -> &'static str { + r#"{"denom":"uatom","amount":"10","sender":"cosmos1wxeyh7zgn4tctjzs0vtqpc6p5cxq5t2muzl7ng","receiver":"cosmos1wxeyh7zgn4tctjzs0vtqpc6p5cxq5t2muzl7ng","memo":""}"# + } + + /// Ensures `PacketData` properly encodes to JSON by first converting to a + /// `RawPacketData` and then serializing that. + #[test] + fn test_packet_data_ser() { + PacketData::new_dummy().ser_json_assert_eq(dummy_json_packet_data()); + } + + /// Ensures `PacketData` properly decodes from JSON by first deserializing to a + /// `RawPacketData` and then converting from that. + #[test] + fn test_packet_data_deser() { + PacketData::new_dummy().deser_json_assert_eq(dummy_json_packet_data()); + } +} diff --git a/crates/ibc/src/core/handler.rs b/crates/ibc/src/core/handler.rs index 8d359650b..c13072d8d 100644 --- a/crates/ibc/src/core/handler.rs +++ b/crates/ibc/src/core/handler.rs @@ -167,12 +167,8 @@ mod tests { use test_log::test; use crate::applications::transfer::error::TokenTransferError; - use crate::applications::transfer::msgs::transfer::test_util::get_dummy_transfer_packet; use crate::applications::transfer::send_transfer; - use crate::applications::transfer::{ - msgs::transfer::test_util::get_dummy_msg_transfer, msgs::transfer::MsgTransfer, - packet::PacketData, PrefixedCoin, MODULE_ID_STR, - }; + use crate::applications::transfer::{msgs::transfer::MsgTransfer, MODULE_ID_STR}; use crate::core::dispatch; use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::msgs::{ @@ -321,10 +317,10 @@ mod tests { MsgChannelCloseConfirm::try_from(get_dummy_raw_msg_chan_close_confirm(client_height)) .unwrap(); - let msg_transfer = get_dummy_msg_transfer(Height::new(0, 35).unwrap().into(), None); - let msg_transfer_two = get_dummy_msg_transfer(Height::new(0, 36).unwrap().into(), None); - let msg_transfer_no_timeout = get_dummy_msg_transfer(TimeoutHeight::no_timeout(), None); - let msg_transfer_no_timeout_or_timestamp = get_dummy_msg_transfer( + let msg_transfer = MsgTransfer::new_dummy(Height::new(0, 35).unwrap().into(), None); + let msg_transfer_two = MsgTransfer::new_dummy(Height::new(0, 36).unwrap().into(), None); + let msg_transfer_no_timeout = MsgTransfer::new_dummy(TimeoutHeight::no_timeout(), None); + let msg_transfer_no_timeout_or_timestamp = MsgTransfer::new_dummy( TimeoutHeight::no_timeout(), Some(Timestamp::from_nanoseconds(0).unwrap()), ); @@ -335,24 +331,14 @@ mod tests { msg_to_on_close.packet.timeout_height_on_b = msg_transfer_two.timeout_height_on_b; msg_to_on_close.packet.timeout_timestamp_on_b = msg_transfer_two.timeout_timestamp_on_b; - let denom = msg_transfer_two.packet_data.token.denom.clone(); - let packet_data = { - let data = PacketData { - token: PrefixedCoin { - denom, - amount: msg_transfer_two.packet_data.token.amount, - }, - sender: msg_transfer_two.packet_data.sender.clone(), - receiver: msg_transfer_two.packet_data.receiver.clone(), - memo: "".to_owned().into(), - }; - serde_json::to_vec(&data).expect("PacketData's infallible Serialize impl failed") - }; + let packet_data = serde_json::to_vec(&msg_transfer_two.packet_data) + .expect("PacketData's infallible Serialize impl failed"); + msg_to_on_close.packet.data = packet_data; let msg_recv_packet = MsgRecvPacket::try_from(get_dummy_raw_msg_recv_packet(35)).unwrap(); let msg_ack_packet = MsgAcknowledgement::try_from(get_dummy_raw_msg_ack_with_packet( - get_dummy_transfer_packet(msg_transfer.clone(), 1u64.into()).into(), + msg_transfer.get_transfer_packet(1u64.into()).into(), 35, )) .unwrap(); From b6ad8ce55954f2678b57caa0b94feaea3f8eddac Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 26 Jul 2023 16:18:24 -0700 Subject: [PATCH 003/182] Bump syn from 2.0.23 to 2.0.27 in /ci/no-std-check (#775) Bumps [syn](https://github.com/dtolnay/syn) from 2.0.23 to 2.0.27. - [Release notes](https://github.com/dtolnay/syn/releases) - [Commits](https://github.com/dtolnay/syn/compare/2.0.23...2.0.27) --- updated-dependencies: - dependency-name: syn dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- ci/no-std-check/Cargo.lock | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/ci/no-std-check/Cargo.lock b/ci/no-std-check/Cargo.lock index 313e97b68..7b976ebe8 100644 --- a/ci/no-std-check/Cargo.lock +++ b/ci/no-std-check/Cargo.lock @@ -526,7 +526,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -537,7 +537,7 @@ checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" dependencies = [ "darling_core", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -598,7 +598,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -836,7 +836,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -1088,7 +1088,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -1425,7 +1425,7 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std 7.0.0", - "syn 2.0.23", + "syn 2.0.27", "tendermint", "tendermint-light-client-verifier", "tendermint-proto", @@ -1860,7 +1860,7 @@ checksum = "8d2275aab483050ab2a7364c1a46604865ee7d6906684e08db0f090acf74f9e7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -2123,7 +2123,7 @@ checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -2145,7 +2145,7 @@ checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -2397,7 +2397,7 @@ checksum = "c7f531814d2f16995144c74428830ccf7d94ff4a7749632b83ad8199b181140c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -2562,7 +2562,7 @@ dependencies = [ "proc-macro-crate 1.3.1", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -2811,9 +2811,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.23" +version = "2.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59fb7d6d8281a51045d62b8eb3a7d1ce347b76f312af50cd3dc0af39c87c1737" +checksum = "b60f673f44a8255b9c8c657daf66a596d435f2da81a555b06dc644d080ba45e0" dependencies = [ "proc-macro2", "quote", @@ -2909,7 +2909,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -3027,7 +3027,7 @@ checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] [[package]] @@ -3218,7 +3218,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", "wasm-bindgen-shared", ] @@ -3240,7 +3240,7 @@ checksum = "e128beba882dd1eb6200e1dc92ae6c5dbaa4311aa7bb211ca035779e5efc39f8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3781,5 +3781,5 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.27", ] From 01e3ab83bd428519e7feaa3428494f94ca84a6b0 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Fri, 28 Jul 2023 11:37:57 -0700 Subject: [PATCH 004/182] imp(ics24)!: enhancements and fixes to `ChainId` impl and validation (#762) * imp(ChainId): refactor abstraction and validations * misc: add unclog * fix: clippy catches * fix: revert ChainId definition + improve checks * fix: set_revision_number --- .../761-chain-id-enhancements-and-fixes.md | 3 + .../clients/ics07_tendermint/client_state.rs | 36 ++- .../ibc/src/clients/ics07_tendermint/error.rs | 19 +- .../src/clients/ics07_tendermint/header.rs | 7 +- .../clients/ics07_tendermint/misbehaviour.rs | 9 +- .../ics02_client/handler/update_client.rs | 30 +-- .../ics03_connection/handler/conn_open_ack.rs | 2 +- .../ics03_connection/handler/conn_open_try.rs | 2 +- crates/ibc/src/core/ics24_host/identifier.rs | 209 ++++++++++-------- .../core/ics24_host/identifier/validate.rs | 78 ++++--- .../hosts/tendermint/validate_self_client.rs | 2 +- crates/ibc/src/mock/context.rs | 30 +-- crates/ibc/src/mock/host.rs | 10 +- crates/ibc/src/mock/ics18_relayer/context.rs | 4 +- crates/ibc/tests/support/signed_header.json | 2 +- 15 files changed, 240 insertions(+), 203 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/761-chain-id-enhancements-and-fixes.md diff --git a/.changelog/unreleased/breaking-changes/761-chain-id-enhancements-and-fixes.md b/.changelog/unreleased/breaking-changes/761-chain-id-enhancements-and-fixes.md new file mode 100644 index 000000000..0cb98cbb2 --- /dev/null +++ b/.changelog/unreleased/breaking-changes/761-chain-id-enhancements-and-fixes.md @@ -0,0 +1,3 @@ +- Enhancements and fixes to `ChainId` impls and validation. + ([#761](https://github.com/cosmos/ibc-rs/issues/761)) + diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index be1a1e7e0..687811ec2 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -8,6 +8,7 @@ use crate::prelude::*; use core::cmp::max; use core::convert::{TryFrom, TryInto}; +use core::str::FromStr; use core::time::Duration; use ibc_proto::google::protobuf::Any; @@ -147,13 +148,7 @@ impl ClientState { } pub fn validate(&self) -> Result<(), Error> { - if self.chain_id.as_str().len() > MaxChainIdLen { - return Err(Error::ChainIdTooLong { - chain_id: self.chain_id.clone(), - len: self.chain_id.as_str().len(), - max_len: MaxChainIdLen, - }); - } + self.chain_id.validate_length(3, MaxChainIdLen)?; // `TrustThreshold` is guaranteed to be in the range `[0, 1)`, but a `TrustThreshold::ZERO` // value is invalid in this context @@ -202,7 +197,7 @@ impl ClientState { }); } - if self.latest_height.revision_number() != self.chain_id.version() { + if self.latest_height.revision_number() != self.chain_id.revision_number() { return Err(Error::InvalidLatestHeight { reason: "ClientState latest-height revision number must match chain-id version" .to_string(), @@ -606,7 +601,7 @@ impl TryFrom for ClientState { type Error = Error; fn try_from(raw: RawTmClientState) -> Result { - let chain_id = ChainId::from_string(raw.chain_id.as_str()); + let chain_id = ChainId::from_str(raw.chain_id.as_str())?; let trust_level = { let trust_level = raw @@ -791,7 +786,7 @@ mod tests { fn client_state_new() { // Define a "default" set of parameters to reuse throughout these tests. let default_params: ClientStateParams = ClientStateParams { - id: ChainId::default(), + id: ChainId::new("ibc", 0).unwrap(), trust_level: TrustThreshold::ONE_THIRD, trusting_period: Duration::new(64000, 0), unbonding_period: Duration::new(128000, 0), @@ -834,9 +829,9 @@ mod tests { want_pass: true, }, Test { - name: "Valid long (50 chars) chain-id".to_string(), + name: "Valid long (50 chars) chain-id that satisfies revision_number length < `u16::MAX` length".to_string(), params: ClientStateParams { - id: ChainId::new(&"a".repeat(48), 0), + id: ChainId::new(&"a".repeat(29), 0).unwrap(), ..default_params.clone() }, want_pass: true, @@ -844,7 +839,7 @@ mod tests { Test { name: "Invalid too-long (51 chars) chain-id".to_string(), params: ClientStateParams { - id: ChainId::new(&"a".repeat(49), 0), + id: ChainId::new(&"a".repeat(30), 0).unwrap(), ..default_params.clone() }, want_pass: false, @@ -957,7 +952,7 @@ mod tests { fn client_state_verify_height() { // Define a "default" set of parameters to reuse throughout these tests. let default_params: ClientStateParams = ClientStateParams { - id: ChainId::new("ibc", 1), + id: ChainId::new("ibc", 1).unwrap(), trust_level: TrustThreshold::ONE_THIRD, trusting_period: Duration::new(64000, 0), unbonding_period: Duration::new(128000, 0), @@ -1095,6 +1090,7 @@ mod serde_tests { #[cfg(any(test, feature = "mocks"))] pub mod test_util { use crate::prelude::*; + use core::str::FromStr; use core::time::Duration; use tendermint::block::Header; @@ -1113,17 +1109,15 @@ pub mod test_util { } pub fn new_dummy_from_header(tm_header: Header) -> Self { + let chain_id = ChainId::from_str(tm_header.chain_id.as_str()).expect("Never fails"); Self::new( - tm_header.chain_id.to_string().into(), + chain_id.clone(), Default::default(), Duration::from_secs(64000), Duration::from_secs(128000), Duration::from_millis(3000), - Height::new( - ChainId::chain_version(tm_header.chain_id.as_str()), - u64::from(tm_header.height), - ) - .expect("Never fails"), + Height::new(chain_id.revision_number(), u64::from(tm_header.height)) + .expect("Never fails"), Default::default(), Default::default(), AllowUpdate { @@ -1138,7 +1132,7 @@ pub mod test_util { pub fn get_dummy_raw_tm_client_state(frozen_height: RawHeight) -> RawTmClientState { #[allow(deprecated)] RawTmClientState { - chain_id: ChainId::new("ibc", 0).to_string(), + chain_id: ChainId::new("ibc", 0).expect("Never fails").to_string(), trust_level: Some(Fraction { numerator: 1, denominator: 3, diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index a3a9b5b18..f89878f91 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -3,7 +3,7 @@ use crate::prelude::*; use crate::core::ics02_client::error::ClientError; -use crate::core::ics24_host::identifier::{ChainId, ClientId}; +use crate::core::ics24_host::identifier::{ClientId, IdentifierError}; use crate::Height; use core::time::Duration; @@ -17,12 +17,8 @@ use tendermint_light_client_verifier::Verdict; /// The main error type #[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 identifier: `{0}` + InvalidIdentifier(IdentifierError), /// invalid header, failed basic validation: `{reason}`, error: `{error}` InvalidHeader { reason: String, @@ -99,14 +95,13 @@ pub enum Error { MisbehaviourHeadersBlockHashesEqual, /// headers are not at same height and are monotonically increasing MisbehaviourHeadersNotAtSameHeight, - /// invalid raw client id: `{client_id}` - InvalidRawClientId { client_id: String }, } #[cfg(feature = "std")] impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { + Self::InvalidIdentifier(e) => Some(e), Self::InvalidHeader { error: e, .. } => Some(e), Self::InvalidTendermintTrustThreshold(e) => Some(e), Self::InvalidRawHeader(e) => Some(e), @@ -124,6 +119,12 @@ impl From for ClientError { } } +impl From for Error { + fn from(e: IdentifierError) -> Self { + Self::InvalidIdentifier(e) + } +} + pub(crate) trait IntoResult { fn into_result(self) -> Result; } diff --git a/crates/ibc/src/clients/ics07_tendermint/header.rs b/crates/ibc/src/clients/ics07_tendermint/header.rs index 8fd5c3e81..d24cf409c 100644 --- a/crates/ibc/src/clients/ics07_tendermint/header.rs +++ b/crates/ibc/src/clients/ics07_tendermint/header.rs @@ -3,6 +3,7 @@ use crate::prelude::*; use alloc::string::ToString; use core::fmt::{Display, Error as FmtError, Formatter}; +use core::str::FromStr; use bytes::Buf; use ibc_proto::google::protobuf::Any; @@ -54,7 +55,9 @@ impl Header { pub fn height(&self) -> Height { Height::new( - ChainId::chain_version(self.signed_header.header.chain_id.as_str()), + ChainId::from_str(self.signed_header.header.chain_id.as_str()) + .expect("chain id") + .revision_number(), u64::from(self.signed_header.header.height), ) .expect("malformed tendermint header domain type has an illegal height of 0") @@ -89,7 +92,7 @@ impl Header { } pub fn verify_chain_id_version_matches_height(&self, chain_id: &ChainId) -> Result<(), Error> { - if self.height().revision_number() != chain_id.version() { + if self.height().revision_number() != chain_id.revision_number() { return Err(Error::MismatchHeaderChainId { given: self.signed_header.header.chain_id.to_string(), expected: chain_id.to_string(), diff --git a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs index daf0c12e0..fa5f5fd51 100644 --- a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs +++ b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs @@ -76,18 +76,15 @@ impl TryFrom for Misbehaviour { type Error = Error; fn try_from(raw: RawMisbehaviour) -> Result { - let client_id = raw - .client_id - .parse() - .map_err(|_| Error::InvalidRawClientId { - client_id: raw.client_id.clone(), - })?; + let client_id = raw.client_id.parse()?; + let header1: Header = raw .header_1 .ok_or_else(|| Error::InvalidRawMisbehaviour { reason: "missing header1".into(), })? .try_into()?; + let header2: Header = raw .header_2 .ok_or_else(|| Error::InvalidRawMisbehaviour { 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 3499dac35..b487770f9 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -208,10 +208,10 @@ mod tests { let client_id = ClientId::new(tm_client_type(), 0).unwrap(); let client_height = Height::new(1, 20).unwrap(); let update_height = Height::new(1, 21).unwrap(); - let chain_id_b = ChainId::new("mockgaiaB", 1); + let chain_id_b = ChainId::new("mockgaiaB", 1).unwrap(); let mut ctx = MockContext::new( - ChainId::new("mockgaiaA", 1), + ChainId::new("mockgaiaA", 1).unwrap(), HostType::Mock, 5, Height::new(1, 1).unwrap(), @@ -254,10 +254,10 @@ mod tests { let client_id = ClientId::new(tm_client_type(), 0).unwrap(); let client_height = Height::new(1, 20).unwrap(); let update_height = Height::new(1, 21).unwrap(); - let chain_id_b = ChainId::new("mockgaiaB", 1); + let chain_id_b = ChainId::new("mockgaiaB", 1).unwrap(); let mut ctx = MockContext::new( - ChainId::new("mockgaiaA", 1), + ChainId::new("mockgaiaA", 1).unwrap(), HostType::Mock, 5, Height::new(1, 1).unwrap(), @@ -301,8 +301,8 @@ mod tests { let client_id = ClientId::new(tm_client_type(), 0).unwrap(); let client_height = Height::new(1, 20).unwrap(); - let ctx_a_chain_id = ChainId::new("mockgaiaA", 1); - let ctx_b_chain_id = ChainId::new("mockgaiaB", 1); + let ctx_a_chain_id = ChainId::new("mockgaiaA", 1).unwrap(); + let ctx_b_chain_id = ChainId::new("mockgaiaB", 1).unwrap(); let start_height = Height::new(1, 11).unwrap(); let mut ctx_a = MockContext::new(ctx_a_chain_id, HostType::Mock, 5, start_height) @@ -353,10 +353,12 @@ mod tests { let tm_block = downcast!(block.clone() => HostBlock::SyntheticTendermint).unwrap(); + let chain_id = ChainId::from_str(tm_block.header().chain_id.as_str()).unwrap(); + let client_state = { #[allow(deprecated)] let raw_client_state = RawTmClientState { - chain_id: ChainId::from(tm_block.header().chain_id.to_string()).to_string(), + chain_id: chain_id.to_string(), trust_level: Some(Fraction { numerator: 1, denominator: 3, @@ -366,7 +368,7 @@ mod tests { max_clock_drift: Some(Duration::from_millis(3000).into()), latest_height: Some( Height::new( - ChainId::chain_version(tm_block.header().chain_id.as_str()), + chain_id.revision_number(), u64::from(tm_block.header().height), ) .unwrap() @@ -426,7 +428,7 @@ mod tests { let chain_start_height = Height::new(1, 11).unwrap(); let ctx = MockContext::new( - ChainId::new("mockgaiaA", 1), + ChainId::new("mockgaiaA", 1).unwrap(), HostType::Mock, 5, chain_start_height, @@ -439,7 +441,7 @@ mod tests { ); let ctx_b = MockContext::new( - ChainId::new("mockgaiaB", 1), + ChainId::new("mockgaiaB", 1).unwrap(), HostType::SyntheticTendermint, 5, client_height, @@ -565,11 +567,11 @@ mod tests { let client_id = ClientId::new(tm_client_type(), 0).unwrap(); let client_height = Height::new(1, 20).unwrap(); let misbehaviour_height = Height::new(1, 21).unwrap(); - let chain_id_b = ChainId::new("mockgaiaB", 1); + let chain_id_b = ChainId::new("mockgaiaB", 1).unwrap(); // Create a mock context for chain-A with a synthetic tendermint light client for chain-B let mut ctx_a = MockContext::new( - ChainId::new("mockgaiaA", 1), + ChainId::new("mockgaiaA", 1).unwrap(), HostType::Mock, 5, Height::new(1, 1).unwrap(), @@ -626,11 +628,11 @@ mod tests { let client_id = ClientId::new(tm_client_type(), 0).unwrap(); let client_height = Height::new(1, 20).unwrap(); let misbehaviour_height = Height::new(1, 21).unwrap(); - let chain_id_b = ChainId::new("mockgaiaB", 1); + let chain_id_b = ChainId::new("mockgaiaB", 1).unwrap(); // Create a mock context for chain-A with a synthetic tendermint light client for chain-B let mut ctx_a = MockContext::new( - ChainId::new("mockgaiaA", 1), + ChainId::new("mockgaiaA", 1).unwrap(), HostType::Mock, 5, Height::new(1, 1).unwrap(), 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 fffb0a747..caa5c01e1 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 @@ -255,7 +255,7 @@ mod tests { let ctx_default = MockContext::default(); let ctx_new = MockContext::new( - ChainId::new("mockgaia", latest_height.revision_number()), + ChainId::new("mockgaia", latest_height.revision_number()).unwrap(), HostType::Mock, max_history_size, latest_height, 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 5608fe7c0..b26d555d2 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 @@ -254,7 +254,7 @@ mod tests { }; let ctx_new = MockContext::new( - ChainId::new("mockgaia", 0), + ChainId::new("mockgaia", 0).unwrap(), HostType::Mock, max_history_size, host_chain_height, diff --git a/crates/ibc/src/core/ics24_host/identifier.rs b/crates/ibc/src/core/ics24_host/identifier.rs index 5023faade..5cb5babf8 100644 --- a/crates/ibc/src/core/ics24_host/identifier.rs +++ b/crates/ibc/src/core/ics24_host/identifier.rs @@ -3,7 +3,6 @@ pub(crate) mod validate; use validate::*; -use core::convert::{From, Infallible}; use core::fmt::{Debug, Display, Error as FmtError, Formatter}; use core::str::FromStr; @@ -18,16 +17,17 @@ use crate::prelude::*; const CONNECTION_ID_PREFIX: &str = "connection"; const CHANNEL_ID_PREFIX: &str = "channel"; -const DEFAULT_CHAIN_ID: &str = "defaultChainId"; const DEFAULT_PORT_ID: &str = "defaultPort"; const TRANSFER_PORT_ID: &str = "transfer"; -/// A `ChainId` is in "epoch format" if it is of the form `{chain name}-{epoch number}`, -/// where the epoch number is the number of times the chain was upgraded. Chain IDs not -/// in that format will be assumed to have epoch number 0. +/// Defines the domain type for chain identifiers. /// -/// This is not standardized yet, although compatible with ibc-go. -/// See: . +/// A valid `ChainId` follows the format {chain name}-{revision number} where +/// the revision number indicates how many times the chain has been upgraded. +/// Creating `ChainId`s not in this format will result in an error. +/// +/// It should be noted this format is not standardized yet, though it is widely +/// accepted and compatible with Cosmos SDK driven chains. #[cfg_attr( feature = "parity-scale-codec", derive( @@ -44,37 +44,33 @@ const TRANSFER_PORT_ID: &str = "transfer"; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ChainId { id: String, - version: u64, + revision_number: u64, } impl ChainId { - /// Creates a new `ChainId` given a chain name and an epoch number. + /// Creates a new `ChainId` with the given chain name and revision number. /// - /// The returned `ChainId` will have the format: `{chain name}-{epoch number}`. + /// It checks the chain name for valid characters according to `ICS-24` + /// specification and returns a `ChainId` in the the format of {chain + /// name}-{revision number}. Stricter checks beyond `ICS-24` rests with + /// the users, based on their requirements. /// /// ``` /// use ibc::core::ics24_host::identifier::ChainId; /// - /// let epoch_number = 10; - /// let id = ChainId::new("chainA", epoch_number); - /// assert_eq!(id.version(), epoch_number); + /// let revision_number = 10; + /// let id = ChainId::new("chainA", revision_number).unwrap(); + /// assert_eq!(id.revision_number(), revision_number); /// ``` - pub fn new(name: &str, version: u64) -> Self { - let id = format!("{name}-{version}"); - Self { id, version } - } - - pub fn from_string(id: &str) -> Self { - let version = if Self::is_epoch_format(id) { - Self::chain_version(id) - } else { - 0 - }; - - Self { - id: id.to_string(), - version, - } + pub fn new(name: &str, revision_number: u64) -> Result { + let prefix = name.trim(); + validate_identifier_chars(prefix)?; + validate_identifier_length(prefix, 1, 43)?; + let id = format!("{prefix}-{revision_number}"); + Ok(Self { + id, + revision_number, + }) } /// Get a reference to the underlying string. @@ -82,76 +78,57 @@ impl ChainId { &self.id } - // TODO: this should probably be named epoch_number. - /// Extract the version from this chain identifier. - pub fn version(&self) -> u64 { - self.version + pub fn split_chain_id(&self) -> (&str, u64) { + parse_chain_id_string(self.as_str()) + .expect("never fails because a valid chain identifier is parsed") } - /// Extract the version from the given chain identifier. - /// ``` - /// use ibc::core::ics24_host::identifier::ChainId; - /// - /// assert_eq!(ChainId::chain_version("chain--a-0"), 0); - /// assert_eq!(ChainId::chain_version("ibc-10"), 10); - /// assert_eq!(ChainId::chain_version("cosmos-hub-97"), 97); - /// assert_eq!(ChainId::chain_version("testnet-helloworld-2"), 2); - /// ``` - pub fn chain_version(chain_id: &str) -> u64 { - if !ChainId::is_epoch_format(chain_id) { - return 0; - } - - let split: Vec<_> = chain_id.split('-').collect(); - split - .last() - .expect("get revision number from chain_id") - .parse() - .unwrap_or(0) + /// Extract the chain name from the chain identifier + pub fn chain_name(&self) -> &str { + self.split_chain_id().0 } - /// is_epoch_format() checks if a chain_id is in the format required for parsing epochs - /// The chainID must be in the form: `{chainID}-{version}` - /// ``` - /// use ibc::core::ics24_host::identifier::ChainId; - /// assert_eq!(ChainId::is_epoch_format("chainA-0"), false); - /// assert_eq!(ChainId::is_epoch_format("chainA"), false); - /// assert_eq!(ChainId::is_epoch_format("chainA-1"), true); - /// assert_eq!(ChainId::is_epoch_format("c-1"), true); - /// ``` - pub fn is_epoch_format(chain_id: &str) -> bool { - let re = safe_regex::regex!(br".*[^-]-[1-9][0-9]*"); - re.is_match(chain_id.as_bytes()) + /// Extract the revision number from the chain identifier + pub fn revision_number(&self) -> u64 { + self.revision_number } - /// with_version() checks if a chain_id is in the format required for parsing epochs, and if so - /// replaces it's version with the specified version + /// Swaps `ChainId`s revision number with the new specified revision number /// ``` /// use ibc::core::ics24_host::identifier::ChainId; - /// assert_eq!(ChainId::new("chainA", 1).with_version(2), ChainId::new("chainA", 2)); - /// assert_eq!("chain1".parse::().unwrap().with_version(2), "chain1".parse::().unwrap()); + /// let mut chain_id = ChainId::new("chainA", 1).unwrap(); + /// chain_id.set_revision_number(2); + /// assert_eq!(chain_id.revision_number(), 2); /// ``` - pub fn with_version(mut self, version: u64) -> Self { - if Self::is_epoch_format(&self.id) { - self.id = { - let mut split: Vec<&str> = self.id.split('-').collect(); - let version = version.to_string(); - if let Some(last_elem) = split.last_mut() { - *last_elem = &version; - } - split.join("-") - }; - self.version = version; - } - self + pub fn set_revision_number(&mut self, revision_number: u64) { + let chain_name = self.chain_name(); + self.id = format!("{}-{}", chain_name, revision_number); + self.revision_number = revision_number; + } + + /// A convenient method to check if the `ChainId` forms a valid identifier + /// with the desired min/max length. However, ICS-24 does not specify a + /// certain min or max lengths for chain identifiers. + pub fn validate_length( + &self, + min_length: usize, + max_length: usize, + ) -> Result<(), IdentifierError> { + validate_prefix_length(self.chain_name(), min_length, max_length) } } +/// Construct a `ChainId` from a string literal only if it forms a valid +/// identifier. impl FromStr for ChainId { - type Err = Infallible; + type Err = IdentifierError; fn from_str(id: &str) -> Result { - Ok(Self::from_string(id)) + let (_, revision_number) = parse_chain_id_string(id)?; + Ok(Self { + id: id.to_string(), + revision_number, + }) } } @@ -161,16 +138,37 @@ impl Display for ChainId { } } -impl Default for ChainId { - fn default() -> Self { - Self::from_string(DEFAULT_CHAIN_ID) - } -} +/// Parses a string intended to represent a `ChainId` and, if successful, +/// returns a tuple containing the chain name and revision number. +fn parse_chain_id_string(chain_id_str: &str) -> Result<(&str, u64), IdentifierError> { + let (name, rev_number_str) = match chain_id_str.rsplit_once('-') { + Some((name, rev_number_str)) => (name, rev_number_str), + None => { + return Err(IdentifierError::InvalidCharacter { + id: chain_id_str.to_string(), + }) + } + }; + + // Validates the chain name for allowed characters according to ICS-24. + validate_identifier_chars(name)?; -impl From for ChainId { - fn from(value: String) -> Self { - Self::from_string(&value) + // Validates the revision number not to start with leading zeros, like "01". + if rev_number_str.as_bytes().first() == Some(&b'0') && rev_number_str.len() > 1 { + return Err(IdentifierError::InvalidCharacter { + id: chain_id_str.to_string(), + }); } + + // Parses the revision number string into a `u64` and checks its validity. + let revision_number = + rev_number_str + .parse() + .map_err(|_| IdentifierError::InvalidCharacter { + id: chain_id_str.to_string(), + })?; + + Ok((name, revision_number)) } #[cfg_attr( @@ -518,3 +516,30 @@ pub enum IdentifierError { #[cfg(feature = "std")] impl std::error::Error for IdentifierError {} + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn test_valid_chain_id() { + assert!(ChainId::from_str("chainA-0").is_ok()); + assert!(ChainId::from_str("chainA-1").is_ok()); + assert!(ChainId::from_str("chainA--1").is_ok()); + assert!(ChainId::from_str("chainA-1-2").is_ok()); + } + + #[test] + fn test_invalid_chain_id() { + assert!(ChainId::from_str("1").is_err()); + assert!(ChainId::from_str("-1").is_err()); + assert!(ChainId::from_str(" -1").is_err()); + assert!(ChainId::from_str("chainA").is_err()); + assert!(ChainId::from_str("chainA-").is_err()); + assert!(ChainId::from_str("chainA-a").is_err()); + assert!(ChainId::from_str("chainA-01").is_err()); + assert!(ChainId::from_str("/chainA-1").is_err()); + assert!(ChainId::from_str("chainA-1-").is_err()); + } +} diff --git a/crates/ibc/src/core/ics24_host/identifier/validate.rs b/crates/ibc/src/core/ics24_host/identifier/validate.rs index 2e7c0fe00..f926a4c5d 100644 --- a/crates/ibc/src/core/ics24_host/identifier/validate.rs +++ b/crates/ibc/src/core/ics24_host/identifier/validate.rs @@ -6,15 +6,10 @@ use super::IdentifierError as Error; const PATH_SEPARATOR: char = '/'; const VALID_SPECIAL_CHARS: &str = "._+-#[]<>"; -/// Default validator function for identifiers. -/// -/// A valid identifier only contain valid characters, and be of a given min and -/// max length as specified in the +/// Checks if the identifier only contains valid characters as specified in the /// [`ICS-24`](https://github.com/cosmos/ibc/tree/main/spec/core/ics-024-host-requirements#paths-identifiers-separators)] /// spec. -pub fn validate_identifier(id: &str, min: usize, max: usize) -> Result<(), Error> { - assert!(max >= min); - +pub fn validate_identifier_chars(id: &str) -> Result<(), Error> { // Check identifier is not empty if id.is_empty() { return Err(Error::Empty); @@ -25,16 +20,6 @@ pub fn validate_identifier(id: &str, min: usize, max: usize) -> Result<(), Error 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::InvalidLength { - id: id.into(), - length: id.len(), - min, - max, - }); - } - // Check that the identifier comprises only valid characters: // - Alphanumeric // - `.`, `_`, `+`, `-`, `#` @@ -50,26 +35,42 @@ pub fn validate_identifier(id: &str, min: usize, max: usize) -> Result<(), Error Ok(()) } -/// Checks if the prefix can form a valid identifier with the given min/max identifier's length. -fn validate_prefix_epoch_format( +/// Checks if the identifier forms a valid identifier with the given min/max length as specified in the +/// [`ICS-24`](https://github.com/cosmos/ibc/tree/main/spec/core/ics-024-host-requirements#paths-identifiers-separators)] +/// spec. +pub fn validate_identifier_length(id: &str, min: usize, max: usize) -> Result<(), Error> { + assert!(max >= min); + + // Check identifier length is between given min/max + if id.len() < min || id.len() > max { + return Err(Error::InvalidLength { + id: id.into(), + length: id.len(), + min, + max, + }); + } + + Ok(()) +} + +/// Checks if a prefix forms a valid identifier with the given min/max identifier's length. +/// The prefix must be between `min_id_length - 2`, considering `u64::MIN` (1 char) and "-" +/// and `max_id_length - 21` characters, considering `u64::MAX` (20 chars) and "-". +pub fn validate_prefix_length( prefix: &str, min_id_length: usize, max_id_length: usize, ) -> Result<(), Error> { - // Checks if the prefix is not blank - if prefix.is_empty() { - return Err(Error::Empty)?; - } - - // Checks if the prefix forms a valid identifier when used with `0` - validate_identifier( + // Checks if the prefix forms a valid identifier length when constructed with `u64::MIN` + validate_identifier_length( &format!("{prefix}-{}", u64::MIN), min_id_length, max_id_length, )?; - // Checks if the prefix forms a valid identifier when used with `u64::MAX` - validate_identifier( + // Checks if the prefix forms a valid identifier length when constructed with `u64::MAX` + validate_identifier_length( &format!("{prefix}-{}", u64::MAX), min_id_length, max_id_length, @@ -80,7 +81,8 @@ fn validate_prefix_epoch_format( /// Default validator function for the Client types. pub fn validate_client_type(id: &str) -> Result<(), Error> { - validate_prefix_epoch_format(id, 9, 64) + validate_identifier_chars(id)?; + validate_prefix_length(id, 9, 64) } /// Default validator function for Client identifiers. @@ -88,7 +90,8 @@ pub fn validate_client_type(id: &str) -> Result<(), Error> { /// A valid client identifier must be between 9-64 characters as specified in /// the ICS-24 spec. pub fn validate_client_identifier(id: &str) -> Result<(), Error> { - validate_identifier(id, 9, 64) + validate_identifier_chars(id)?; + validate_identifier_length(id, 9, 64) } /// Default validator function for Connection identifiers. @@ -96,7 +99,8 @@ pub fn validate_client_identifier(id: &str) -> Result<(), Error> { /// A valid connection identifier must be between 10-64 characters as specified /// in the ICS-24 spec. pub fn validate_connection_identifier(id: &str) -> Result<(), Error> { - validate_identifier(id, 10, 64) + validate_identifier_chars(id)?; + validate_identifier_length(id, 10, 64) } /// Default validator function for Port identifiers. @@ -104,7 +108,8 @@ pub fn validate_connection_identifier(id: &str) -> Result<(), Error> { /// A valid port identifier must be between 2-128 characters as specified in the /// ICS-24 spec. pub fn validate_port_identifier(id: &str) -> Result<(), Error> { - validate_identifier(id, 2, 128) + validate_identifier_chars(id)?; + validate_identifier_length(id, 2, 128) } /// Default validator function for Channel identifiers. @@ -112,7 +117,8 @@ pub fn validate_port_identifier(id: &str) -> Result<(), Error> { /// A valid channel identifier must be between 8-64 characters as specified in /// the ICS-24 spec. pub fn validate_channel_identifier(id: &str) -> Result<(), Error> { - validate_identifier(id, 8, 64) + validate_identifier_chars(id)?; + validate_identifier_length(id, 8, 64) } #[cfg(test)] @@ -188,21 +194,21 @@ mod tests { #[test] fn parse_invalid_id_chars() { // invalid id chars - let id = validate_identifier("channel@01", 1, 10); + let id = validate_identifier_chars("channel@01"); assert!(id.is_err()) } #[test] fn parse_invalid_id_empty() { // invalid id empty - let id = validate_identifier("", 1, 10); + let id = validate_identifier_chars(""); assert!(id.is_err()) } #[test] fn parse_invalid_id_path_separator() { // invalid id with path separator - let id = validate_identifier("id/1", 1, 10); + let id = validate_identifier_chars("id/1"); assert!(id.is_err()) } diff --git a/crates/ibc/src/hosts/tendermint/validate_self_client.rs b/crates/ibc/src/hosts/tendermint/validate_self_client.rs index b305027d4..ce8a6c3f6 100644 --- a/crates/ibc/src/hosts/tendermint/validate_self_client.rs +++ b/crates/ibc/src/hosts/tendermint/validate_self_client.rs @@ -43,7 +43,7 @@ pub trait ValidateSelfClientContext { .map_err(ContextError::ConnectionError); } - let self_revision_number = self_chain_id.version(); + let self_revision_number = self_chain_id.revision_number(); if self_revision_number != tm_client_state.latest_height().revision_number() { return Err(ConnectionError::InvalidClientState { reason: format!( diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 78b5bc802..04e49752a 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -234,7 +234,7 @@ pub struct MockContext { impl Default for MockContext { fn default() -> Self { Self::new( - ChainId::new("mockgaia", 0), + ChainId::new("mockgaia", 0).expect("Never fails"), HostType::Mock, 5, Height::new(0, 5).expect("Never fails"), @@ -293,7 +293,7 @@ impl MockContext { let n = min(max_history_size as u64, latest_height.revision_height()); assert_eq!( - host_id.version(), + host_id.revision_number(), latest_height.revision_number(), "The version in the chain identifier must match the version in the latest height" ); @@ -900,7 +900,7 @@ impl ValidationContext for MockContext { mock_client_state.confirm_not_frozen()?; let self_chain_id = &self.host_chain_id; - let self_revision_number = self_chain_id.version(); + let self_revision_number = self_chain_id.revision_number(); if self_revision_number != mock_client_state.latest_height().revision_number() { return Err(ConnectionError::InvalidClientState { reason: format!( @@ -1395,11 +1395,13 @@ mod tests { } let cv = 1; // The version to use for all chains. + let mock_chain_id = ChainId::new("mockgaia", cv).unwrap(); + let tests: Vec = vec![ Test { name: "Empty history, small pruning window".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::Mock, 2, Height::new(cv, 1).expect("Never fails"), @@ -1408,7 +1410,7 @@ mod tests { Test { name: "[Synthetic TM host] Empty history, small pruning window".to_string(), ctx: MockContext::new( - ChainId::new("mocksgaia", cv), + mock_chain_id.clone(), HostType::SyntheticTendermint, 2, Height::new(cv, 1).expect("Never fails"), @@ -1417,7 +1419,7 @@ mod tests { Test { name: "Large pruning window".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::Mock, 30, Height::new(cv, 2).expect("Never fails"), @@ -1426,7 +1428,7 @@ mod tests { Test { name: "[Synthetic TM host] Large pruning window".to_string(), ctx: MockContext::new( - ChainId::new("mocksgaia", cv), + mock_chain_id.clone(), HostType::SyntheticTendermint, 30, Height::new(cv, 2).expect("Never fails"), @@ -1435,7 +1437,7 @@ mod tests { Test { name: "Small pruning window".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::Mock, 3, Height::new(cv, 30).expect("Never fails"), @@ -1444,7 +1446,7 @@ mod tests { Test { name: "[Synthetic TM host] Small pruning window".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::SyntheticTendermint, 3, Height::new(cv, 30).expect("Never fails"), @@ -1453,7 +1455,7 @@ mod tests { Test { name: "Small pruning window, small starting height".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::Mock, 3, Height::new(cv, 2).expect("Never fails"), @@ -1462,7 +1464,7 @@ mod tests { Test { name: "[Synthetic TM host] Small pruning window, small starting height".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::SyntheticTendermint, 3, Height::new(cv, 2).expect("Never fails"), @@ -1471,7 +1473,7 @@ mod tests { Test { name: "Large pruning window, large starting height".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id.clone(), HostType::Mock, 50, Height::new(cv, 2000).expect("Never fails"), @@ -1480,7 +1482,7 @@ mod tests { Test { name: "[Synthetic TM host] Large pruning window, large starting height".to_string(), ctx: MockContext::new( - ChainId::new("mockgaia", cv), + mock_chain_id, HostType::SyntheticTendermint, 50, Height::new(cv, 2000).expect("Never fails"), @@ -1732,7 +1734,7 @@ mod tests { } let mut ctx = MockContext::new( - ChainId::new("mockgaia", 1), + ChainId::new("mockgaia", 1).unwrap(), HostType::Mock, 1, Height::new(1, 1).expect("Never fails"), diff --git a/crates/ibc/src/mock/host.rs b/crates/ibc/src/mock/host.rs index 1c52e2700..6a964ea90 100644 --- a/crates/ibc/src/mock/host.rs +++ b/crates/ibc/src/mock/host.rs @@ -1,5 +1,7 @@ //! Host chain types and methods, used by context mock. +use core::str::FromStr; + use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Header as RawHeader; use ibc_proto::protobuf::Protobuf as ErasedProtobuf; @@ -59,7 +61,9 @@ impl HostBlock { match self { HostBlock::Mock(header) => header.height(), HostBlock::SyntheticTendermint(light_block) => Height::new( - ChainId::chain_version(light_block.header().chain_id.as_str()), + ChainId::from_str(light_block.header().chain_id.as_str()) + .expect("Never fails") + .revision_number(), light_block.header().height.value(), ) .expect("Never fails"), @@ -90,7 +94,7 @@ impl HostBlock { ) -> HostBlock { match chain_type { HostType::Mock => HostBlock::Mock(Box::new(MockHeader { - height: Height::new(chain_id.version(), height).expect("Never fails"), + height: Height::new(chain_id.revision_number(), height).expect("Never fails"), timestamp, })), HostType::SyntheticTendermint => HostBlock::SyntheticTendermint(Box::new( @@ -112,7 +116,7 @@ impl HostBlock { .generate() .expect("Never fails"); SyntheticTmBlock { - trusted_height: Height::new(chain_id.version(), 1).expect("Never fails"), + trusted_height: Height::new(chain_id.revision_number(), 1).expect("Never fails"), light_block, } } diff --git a/crates/ibc/src/mock/ics18_relayer/context.rs b/crates/ibc/src/mock/ics18_relayer/context.rs index d9ec46f1e..3b569eff1 100644 --- a/crates/ibc/src/mock/ics18_relayer/context.rs +++ b/crates/ibc/src/mock/ics18_relayer/context.rs @@ -100,8 +100,8 @@ mod tests { let client_on_a_for_b = ClientId::new(tm_client_type(), 0).unwrap(); let client_on_b_for_a = ClientId::new(mock_client_type(), 0).unwrap(); - let chain_id_a = ChainId::new("mockgaiaA", 1); - let chain_id_b = ChainId::new("mockgaiaB", 1); + let chain_id_a = ChainId::new("mockgaiaA", 1).unwrap(); + let chain_id_b = ChainId::new("mockgaiaB", 1).unwrap(); // Create two mock contexts, one for each chain. let mut ctx_a = diff --git a/crates/ibc/tests/support/signed_header.json b/crates/ibc/tests/support/signed_header.json index 9416df80c..c4fe96713 100644 --- a/crates/ibc/tests/support/signed_header.json +++ b/crates/ibc/tests/support/signed_header.json @@ -4,7 +4,7 @@ "block": "0", "app": "0" }, - "chain_id": "test-chain-01", + "chain_id": "test-chain-1", "height": "20", "time": "2019-11-02T15:04:10Z", "last_block_id": { From 17c42c3ced7428da82fa5681ca634a759c79ecf2 Mon Sep 17 00:00:00 2001 From: dzmitry-lahoda Date: Mon, 31 Jul 2023 14:26:58 +0100 Subject: [PATCH 005/182] Json schema for Coin and some parts of Transfer (#772) * support for optional json schema * some comment about using json schema * more schema * prefixed denom schema and amount fixes * final transfer things * release note * connection is needed too * std is for schema * fixed de of u256 * tests behind flag * clean up --- .../772-json-schema-for-channels-and-coin.md | 2 ++ crates/ibc/Cargo.toml | 5 +++ .../ibc/src/applications/transfer/amount.rs | 36 ++++++++++++++++++- crates/ibc/src/applications/transfer/coin.rs | 5 +-- crates/ibc/src/applications/transfer/denom.rs | 7 ++++ crates/ibc/src/applications/transfer/memo.rs | 1 + .../ibc/src/applications/transfer/packet.rs | 4 +++ crates/ibc/src/core/ics02_client/height.rs | 1 + crates/ibc/src/core/ics04_channel/timeout.rs | 3 +- crates/ibc/src/core/ics24_host/identifier.rs | 3 ++ crates/ibc/src/signer.rs | 1 + 11 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/772-json-schema-for-channels-and-coin.md diff --git a/.changelog/unreleased/breaking-changes/772-json-schema-for-channels-and-coin.md b/.changelog/unreleased/breaking-changes/772-json-schema-for-channels-and-coin.md new file mode 100644 index 000000000..e7603beb7 --- /dev/null +++ b/.changelog/unreleased/breaking-changes/772-json-schema-for-channels-and-coin.md @@ -0,0 +1,2 @@ +- Serde: Schema for Coin/Transfer, Amount is string + ([#772](https://github.com/cosmos/ibc-rs/issues/772)) \ No newline at end of file diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index bc8ff0222..3cfb03102 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -41,6 +41,9 @@ borsh = ["dep:borsh", "ibc-proto/borsh"] # This feature is required for token transfer (ICS-20) serde = ["dep:serde", "dep:serde_derive", "serde_json", "ics23/serde"] +# CosmWasm message API generator compatible, should not be inside on chain code +schema = ["dep:schemars", "serde", "std"] + # This feature grants access to development-time mocking libraries, such as `MockContext` or `MockHeader`. # Depends on the `testgen` suite for generating Tendermint light blocks. mocks = ["tendermint-testgen", "tendermint/clock", "parking_lot"] @@ -74,6 +77,8 @@ parking_lot = { version = "0.12.1", default-features = false, optional = true } ibc-derive = { version = "0.1.0", path = "../ibc-derive"} +schemars = { version = "0.8.12", optional = true } + [dependencies.tendermint] version = "0.32" default-features = false diff --git a/crates/ibc/src/applications/transfer/amount.rs b/crates/ibc/src/applications/transfer/amount.rs index 2b266a5ca..740e24d0c 100644 --- a/crates/ibc/src/applications/transfer/amount.rs +++ b/crates/ibc/src/applications/transfer/amount.rs @@ -6,10 +6,19 @@ use derive_more::{Display, From, Into}; use super::error::TokenTransferError; use primitive_types::U256; +#[cfg(feature = "schema")] +use crate::alloc::{borrow::ToOwned, string::String}; + /// A type for representing token transfer amounts. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Display, From, Into)] -pub struct Amount(U256); +pub struct Amount( + #[cfg_attr(feature = "schema", schemars(with = "String"))] + #[serde(serialize_with = "crate::serializers::serde_string::serialize")] + #[serde(deserialize_with = "deserialize")] + U256, +); #[cfg(feature = "parity-scale-codec")] impl parity_scale_codec::WrapperTypeDecode for Amount { @@ -63,3 +72,28 @@ impl From for Amount { Self(v.into()) } } + +#[cfg(feature = "serde")] +fn deserialize<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + use serde::Deserialize; + U256::from_dec_str(<&str>::deserialize(deserializer)?).map_err(serde::de::Error::custom) +} + +#[cfg(test)] +#[cfg(feature = "serde")] +mod tests { + use super::Amount; + + #[test] + fn serde_amount() { + let value = Amount::from(42); + let string = serde_json::to_string(&value).expect("can serde string"); + assert_eq!(string, "\"42\""); + let binary = serde_json::to_vec(&value).expect("can serde binary"); + let de: Amount = serde_json::from_slice(binary.as_ref()).expect("can deserialize"); + assert_eq!(de, value); + } +} diff --git a/crates/ibc/src/applications/transfer/coin.rs b/crates/ibc/src/applications/transfer/coin.rs index f95988093..cad624121 100644 --- a/crates/ibc/src/applications/transfer/coin.rs +++ b/crates/ibc/src/applications/transfer/coin.rs @@ -10,9 +10,6 @@ use super::denom::{BaseDenom, PrefixedDenom}; use super::error::TokenTransferError; use crate::prelude::*; -#[cfg(feature = "serde")] -use crate::serializers::serde_string; - /// A `Coin` type with fully qualified `PrefixedDenom`. pub type PrefixedCoin = Coin; @@ -23,6 +20,7 @@ pub type RawCoin = Coin; /// Coin defines a token with a denomination and an amount. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr( feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode,) @@ -32,7 +30,6 @@ pub struct Coin { /// Denomination pub denom: D, /// Amount - #[cfg_attr(feature = "serde", serde(with = "serde_string"))] pub amount: Amount, } diff --git a/crates/ibc/src/applications/transfer/denom.rs b/crates/ibc/src/applications/transfer/denom.rs index b97b007c5..963f6b1d7 100644 --- a/crates/ibc/src/applications/transfer/denom.rs +++ b/crates/ibc/src/applications/transfer/denom.rs @@ -27,6 +27,7 @@ use crate::serializers::serde_string; scale_info::TypeInfo ) )] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Display)] pub struct BaseDenom(String); @@ -61,6 +62,8 @@ impl FromStr for BaseDenom { scale_info::TypeInfo ) )] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] pub struct TracePrefix { port_id: PortId, @@ -94,6 +97,8 @@ impl Display for TracePrefix { scale_info::TypeInfo ) )] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, From)] pub struct TracePath(Vec); @@ -184,6 +189,7 @@ impl Display for TracePath { /// A type that contains the base denomination for ICS20 and the source tracing information path. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr( feature = "parity-scale-codec", derive( @@ -196,6 +202,7 @@ impl Display for TracePath { pub struct PrefixedDenom { /// A series of `{port-id}/{channel-id}`s for tracing the source of the token. #[cfg_attr(feature = "serde", serde(with = "serde_string"))] + #[cfg_attr(feature = "schema", schemars(with = "String"))] pub trace_path: TracePath, /// Base denomination of the relayed fungible token. pub base_denom: BaseDenom, diff --git a/crates/ibc/src/applications/transfer/memo.rs b/crates/ibc/src/applications/transfer/memo.rs index 261828e13..04bc75584 100644 --- a/crates/ibc/src/applications/transfer/memo.rs +++ b/crates/ibc/src/applications/transfer/memo.rs @@ -21,6 +21,7 @@ use crate::prelude::*; derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct Memo(String); diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index 882003f48..569ce90bd 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -4,6 +4,9 @@ use alloc::string::ToString; use core::convert::TryFrom; use core::str::FromStr; +#[cfg(feature = "schema")] +use crate::alloc::borrow::ToOwned; + use ibc_proto::ibc::applications::transfer::v2::FungibleTokenPacketData as RawPacketData; use super::error::TokenTransferError; @@ -16,6 +19,7 @@ use crate::signer::Signer; feature = "serde", serde(try_from = "RawPacketData", into = "RawPacketData") )] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr( feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode,) diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index 3adced7a9..21297a49d 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -29,6 +29,7 @@ use crate::core::ics02_client::error::ClientError; derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Height { /// Previously known as "epoch" diff --git a/crates/ibc/src/core/ics04_channel/timeout.rs b/crates/ibc/src/core/ics04_channel/timeout.rs index f215dc7fe..96f3096b5 100644 --- a/crates/ibc/src/core/ics04_channel/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/timeout.rs @@ -29,6 +29,7 @@ use crate::prelude::*; feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] pub enum TimeoutHeight { Never, @@ -148,7 +149,7 @@ impl Display for TimeoutHeight { } #[cfg(feature = "serde")] -mod serde { +mod tests { use super::TimeoutHeight; use serde::{Deserialize, Serialize}; diff --git a/crates/ibc/src/core/ics24_host/identifier.rs b/crates/ibc/src/core/ics24_host/identifier.rs index 5cb5babf8..6ce2f4b18 100644 --- a/crates/ibc/src/core/ics24_host/identifier.rs +++ b/crates/ibc/src/core/ics24_host/identifier.rs @@ -266,6 +266,7 @@ impl PartialEq for ClientId { derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ConnectionId(String); @@ -349,6 +350,7 @@ impl PartialEq for ConnectionId { derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PortId(String); @@ -417,6 +419,7 @@ impl Default for PortId { derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ChannelId(String); diff --git a/crates/ibc/src/signer.rs b/crates/ibc/src/signer.rs index 4f225593c..672492675 100644 --- a/crates/ibc/src/signer.rs +++ b/crates/ibc/src/signer.rs @@ -16,6 +16,7 @@ use derive_more::Display; derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display)] pub struct Signer(String); From 5b50da01dfe5a5e56b6980f2486b86a84346f971 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Mon, 31 Jul 2023 07:27:29 -0700 Subject: [PATCH 006/182] test: include deserialization test for token transfer with no memo field (#793) * test: include deserialization test for no memo condition * deps: bump ibc-proto-rs version --- crates/ibc/Cargo.toml | 2 +- crates/ibc/src/applications/transfer/packet.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 3cfb03102..48e3f02bb 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -50,7 +50,7 @@ mocks = ["tendermint-testgen", "tendermint/clock", "parking_lot"] [dependencies] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. -ibc-proto = { version = "0.32.0", default-features = false } +ibc-proto = { version = "0.32.1", default-features = false } ics23 = { version = "0.10.1", default-features = false, features = ["host-functions"] } time = { version = ">=0.3.0, <0.3.24", default-features = false } serde_derive = { version = "1.0.104", default-features = false, optional = true } diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index 569ce90bd..4b7ffb4be 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -99,6 +99,10 @@ mod tests { r#"{"denom":"uatom","amount":"10","sender":"cosmos1wxeyh7zgn4tctjzs0vtqpc6p5cxq5t2muzl7ng","receiver":"cosmos1wxeyh7zgn4tctjzs0vtqpc6p5cxq5t2muzl7ng","memo":""}"# } + pub fn dummy_json_packet_data_without_memo() -> &'static str { + r#"{"denom":"uatom","amount":"10","sender":"cosmos1wxeyh7zgn4tctjzs0vtqpc6p5cxq5t2muzl7ng","receiver":"cosmos1wxeyh7zgn4tctjzs0vtqpc6p5cxq5t2muzl7ng"}"# + } + /// Ensures `PacketData` properly encodes to JSON by first converting to a /// `RawPacketData` and then serializing that. #[test] @@ -111,5 +115,6 @@ mod tests { #[test] fn test_packet_data_deser() { PacketData::new_dummy().deser_json_assert_eq(dummy_json_packet_data()); + PacketData::new_dummy().deser_json_assert_eq(dummy_json_packet_data_without_memo()); } } From 9b9cbd04ee3abd0e7da31a06e5477c16ae612466 Mon Sep 17 00:00:00 2001 From: Davirain Date: Tue, 1 Aug 2023 00:48:40 +0800 Subject: [PATCH 007/182] Add serde serialization and deserialization to Packet Receipt (#794) * Add serde serialization and deserialization to PacketMsgType * Create 794-add-ser-der-for-packet-receipt.md --- .changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md | 2 ++ crates/ibc/src/core/ics04_channel/packet.rs | 1 + 2 files changed, 3 insertions(+) create mode 100644 .changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md diff --git a/.changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md b/.changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md new file mode 100644 index 000000000..615c392eb --- /dev/null +++ b/.changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md @@ -0,0 +1,2 @@ +- Add serde serialization and deserialization to Packet Receipt + ([#794](https://github.com/cosmos/ibc-rs/pull/794)) \ No newline at end of file diff --git a/crates/ibc/src/core/ics04_channel/packet.rs b/crates/ibc/src/core/ics04_channel/packet.rs index e369c9ab4..91ca8fd88 100644 --- a/crates/ibc/src/core/ics04_channel/packet.rs +++ b/crates/ibc/src/core/ics04_channel/packet.rs @@ -35,6 +35,7 @@ pub enum PacketMsgType { feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug)] pub enum Receipt { Ok, From db7e21e4b6355cc39c9e78a3ce054b6b695f9a98 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Mon, 31 Jul 2023 11:41:52 -0700 Subject: [PATCH 008/182] Release v0.43.0 (#798) --- .../717-organize-ack-types-under-ics04.md | 0 ...nc-ics04-events-namings-with-convention.md | 0 .../breaking-changes/754-fix-issue-747.md | 0 .../761-chain-id-enhancements-and-fixes.md | 0 .../764-use-vec-for-header-attribute.md | 0 .../772-json-schema-for-channels-and-coin.md | 0 .../bug/747-fix-747-Protobuf-out-of-memory.md | 0 .../bug/752-fix-752.md | 0 .../bug/794-add-ser-der-for-packet-receipt.md | 0 .../745-scale-encoding-for-transfer-packet.md | 0 ...3-include-PacketData-JSON-encoding-test.md | 0 .changelog/v0.43.0/summary.md | 7 +++ CHANGELOG.md | 44 +++++++++++++++++++ CONTRIBUTING.md | 2 +- ci/no-std-check/Cargo.lock | 4 +- ci/no-std-check/Cargo.toml | 2 +- crates/ibc/Cargo.toml | 4 +- 17 files changed, 57 insertions(+), 6 deletions(-) rename .changelog/{unreleased => v0.43.0}/breaking-changes/717-organize-ack-types-under-ics04.md (100%) rename .changelog/{unreleased => v0.43.0}/breaking-changes/750-sync-ics04-events-namings-with-convention.md (100%) rename .changelog/{unreleased => v0.43.0}/breaking-changes/754-fix-issue-747.md (100%) rename .changelog/{unreleased => v0.43.0}/breaking-changes/761-chain-id-enhancements-and-fixes.md (100%) rename .changelog/{unreleased => v0.43.0}/breaking-changes/764-use-vec-for-header-attribute.md (100%) rename .changelog/{unreleased => v0.43.0}/breaking-changes/772-json-schema-for-channels-and-coin.md (100%) rename .changelog/{unreleased => v0.43.0}/bug/747-fix-747-Protobuf-out-of-memory.md (100%) rename .changelog/{unreleased => v0.43.0}/bug/752-fix-752.md (100%) rename .changelog/{unreleased => v0.43.0}/bug/794-add-ser-der-for-packet-receipt.md (100%) rename .changelog/{unreleased => v0.43.0}/improvements/745-scale-encoding-for-transfer-packet.md (100%) rename .changelog/{unreleased => v0.43.0}/improvements/763-include-PacketData-JSON-encoding-test.md (100%) create mode 100644 .changelog/v0.43.0/summary.md diff --git a/.changelog/unreleased/breaking-changes/717-organize-ack-types-under-ics04.md b/.changelog/v0.43.0/breaking-changes/717-organize-ack-types-under-ics04.md similarity index 100% rename from .changelog/unreleased/breaking-changes/717-organize-ack-types-under-ics04.md rename to .changelog/v0.43.0/breaking-changes/717-organize-ack-types-under-ics04.md diff --git a/.changelog/unreleased/breaking-changes/750-sync-ics04-events-namings-with-convention.md b/.changelog/v0.43.0/breaking-changes/750-sync-ics04-events-namings-with-convention.md similarity index 100% rename from .changelog/unreleased/breaking-changes/750-sync-ics04-events-namings-with-convention.md rename to .changelog/v0.43.0/breaking-changes/750-sync-ics04-events-namings-with-convention.md diff --git a/.changelog/unreleased/breaking-changes/754-fix-issue-747.md b/.changelog/v0.43.0/breaking-changes/754-fix-issue-747.md similarity index 100% rename from .changelog/unreleased/breaking-changes/754-fix-issue-747.md rename to .changelog/v0.43.0/breaking-changes/754-fix-issue-747.md diff --git a/.changelog/unreleased/breaking-changes/761-chain-id-enhancements-and-fixes.md b/.changelog/v0.43.0/breaking-changes/761-chain-id-enhancements-and-fixes.md similarity index 100% rename from .changelog/unreleased/breaking-changes/761-chain-id-enhancements-and-fixes.md rename to .changelog/v0.43.0/breaking-changes/761-chain-id-enhancements-and-fixes.md diff --git a/.changelog/unreleased/breaking-changes/764-use-vec-for-header-attribute.md b/.changelog/v0.43.0/breaking-changes/764-use-vec-for-header-attribute.md similarity index 100% rename from .changelog/unreleased/breaking-changes/764-use-vec-for-header-attribute.md rename to .changelog/v0.43.0/breaking-changes/764-use-vec-for-header-attribute.md diff --git a/.changelog/unreleased/breaking-changes/772-json-schema-for-channels-and-coin.md b/.changelog/v0.43.0/breaking-changes/772-json-schema-for-channels-and-coin.md similarity index 100% rename from .changelog/unreleased/breaking-changes/772-json-schema-for-channels-and-coin.md rename to .changelog/v0.43.0/breaking-changes/772-json-schema-for-channels-and-coin.md diff --git a/.changelog/unreleased/bug/747-fix-747-Protobuf-out-of-memory.md b/.changelog/v0.43.0/bug/747-fix-747-Protobuf-out-of-memory.md similarity index 100% rename from .changelog/unreleased/bug/747-fix-747-Protobuf-out-of-memory.md rename to .changelog/v0.43.0/bug/747-fix-747-Protobuf-out-of-memory.md diff --git a/.changelog/unreleased/bug/752-fix-752.md b/.changelog/v0.43.0/bug/752-fix-752.md similarity index 100% rename from .changelog/unreleased/bug/752-fix-752.md rename to .changelog/v0.43.0/bug/752-fix-752.md diff --git a/.changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md b/.changelog/v0.43.0/bug/794-add-ser-der-for-packet-receipt.md similarity index 100% rename from .changelog/unreleased/bug/794-add-ser-der-for-packet-receipt.md rename to .changelog/v0.43.0/bug/794-add-ser-der-for-packet-receipt.md diff --git a/.changelog/unreleased/improvements/745-scale-encoding-for-transfer-packet.md b/.changelog/v0.43.0/improvements/745-scale-encoding-for-transfer-packet.md similarity index 100% rename from .changelog/unreleased/improvements/745-scale-encoding-for-transfer-packet.md rename to .changelog/v0.43.0/improvements/745-scale-encoding-for-transfer-packet.md diff --git a/.changelog/unreleased/improvements/763-include-PacketData-JSON-encoding-test.md b/.changelog/v0.43.0/improvements/763-include-PacketData-JSON-encoding-test.md similarity index 100% rename from .changelog/unreleased/improvements/763-include-PacketData-JSON-encoding-test.md rename to .changelog/v0.43.0/improvements/763-include-PacketData-JSON-encoding-test.md diff --git a/.changelog/v0.43.0/summary.md b/.changelog/v0.43.0/summary.md new file mode 100644 index 000000000..836724110 --- /dev/null +++ b/.changelog/v0.43.0/summary.md @@ -0,0 +1,7 @@ +This release bumps ibc-proto to v0.32.1, resolving issue with token transfer +deserialization for cases with no memo field provided. It also includes various +enhancements and bug fixes, such as reorganized acknowledgement types, enhanced +`ChainId` validation, improved `from_str` height creation, synchronized channel +event namings for consistency. + +There are consensus-breaking changes. diff --git a/CHANGELOG.md b/CHANGELOG.md index 33ab163dd..f64adc79d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,49 @@ # CHANGELOG +## v0.43.0 + +*July 31, 2023* + +This release bumps ibc-proto to v0.32.1, resolving issue with token transfer +deserialization for cases with no memo field provided. It also includes various +enhancements and bug fixes, such as reorganized acknowledgement types, enhanced +`ChainId` validation, improved `from_str` height creation, synchronized channel +event namings for consistency. + +There are consensus-breaking changes. + +### BREAKING CHANGES + +- Organize acknowledgement types under the `ics04_channel` module to get + accessible by any applications. + ([#717](https://github.com/cosmos/ibc-rs/issues/717)) +- Sync field and method namings of ics04 events with the convention + ([#750](https://github.com/cosmos/ibc-rs/issues/750)) +- use ibc_proto::protobuf::Protobuf to replace tendermint_proto::Protobuf + ([#754](https://github.com/cosmos/ibc-rs/pull/754)) +- Enhancements and fixes to `ChainId` impls and validation. + ([#761](https://github.com/cosmos/ibc-rs/issues/761)) +- Use `Vec` for HeaderAttribute instead of `Any` + ([#764](https://github.com/cosmos/ibc-rs/issues/764)) +- Serde: Schema for Coin/Transfer, Amount is string + ([#772](https://github.com/cosmos/ibc-rs/issues/772)) + +### BUG-FIXES + +- Tendermint ConsensusState -> Any can crash if out of memory + ([#747](https://github.com/cosmos/ibc-rs/issues/747)) +- `Height::from_str` accepts invalid heights + ([#752](https://github.com/cosmos/ibc-rs/issues/752)) +- Add serde serialization and deserialization to Packet Receipt + ([#794](https://github.com/cosmos/ibc-rs/pull/794)) + +### IMPROVEMENTS + +- Scale encoding for ICS-20 transfer message + ([#745](https://github.com/cosmos/ibc-rs/issues/745)) +- Add test to ensure `PacketData` keeps proper JSON encoding + ([#763](https://github.com/cosmos/ibc-rs/issues/763)) + ## v0.42.0 *July 5, 2023* diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 33afc0de7..a73a2d289 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -243,7 +243,7 @@ Our release process is as follows: 1. Running `unclog build -u` and copy pasting the output at the top of the `CHANGELOG.md` file, making sure to update the header with the new version. - 2. Running `unclog release --editor vX.Y.Z` to create a summary of all of the changes + 2. Running `unclog release --editor --version vX.Y.Z` to create a summary of all of the changes in this release. 1. Your text editor will open. Write the release summary, and close the editor. 1. Make sure to include a comment on whether or not the release contains consensus-breaking changes. diff --git a/ci/no-std-check/Cargo.lock b/ci/no-std-check/Cargo.lock index 7b976ebe8..609ee9079 100644 --- a/ci/no-std-check/Cargo.lock +++ b/ci/no-std-check/Cargo.lock @@ -1093,9 +1093,9 @@ dependencies = [ [[package]] name = "ibc-proto" -version = "0.32.0" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c888103095b45bee90cb9104513ade30abd69902153b0682b5ad81940ae1f865" +checksum = "11c352715b36685c2543556a77091fb16af5d26257d5ce9c28e6756c1ccd71aa" dependencies = [ "base64 0.21.2", "borsh", diff --git a/ci/no-std-check/Cargo.toml b/ci/no-std-check/Cargo.toml index 1b9f07446..b6911b057 100644 --- a/ci/no-std-check/Cargo.toml +++ b/ci/no-std-check/Cargo.toml @@ -6,7 +6,7 @@ resolver = "2" [dependencies] ibc = { path = "../../crates/ibc", default-features = false } -ibc-proto = { version = "0.32.0", default-features = false, features = [ +ibc-proto = { version = "0.32.1", default-features = false, features = [ "parity-scale-codec", "borsh", ] } diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 48e3f02bb..045999611 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ibc" -version = "0.42.0" +version = "0.43.0" edition = "2021" license = "Apache-2.0" readme = "README.md" @@ -52,7 +52,7 @@ mocks = ["tendermint-testgen", "tendermint/clock", "parking_lot"] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. ibc-proto = { version = "0.32.1", default-features = false } ics23 = { version = "0.10.1", default-features = false, features = ["host-functions"] } -time = { version = ">=0.3.0, <0.3.24", default-features = false } +time = { version = ">=0.3.0, <0.3.25", default-features = false } serde_derive = { version = "1.0.104", default-features = false, optional = true } serde = { version = "1.0", default-features = false, optional = true } serde_json = { version = "1", default-features = false, optional = true } From b116d40dd78181382e95073c226907b73ff61c69 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Mon, 31 Jul 2023 13:36:25 -0700 Subject: [PATCH 009/182] Release v0.43.1 (#799) * bump ibc-derive version to 0.2.0 * bump ibc version to v0.43.1 * dep: fetch ibc-derive from crates-io * bump ibc-derive version --- CHANGELOG.md | 2 +- crates/ibc-derive/Cargo.toml | 2 +- crates/ibc/Cargo.toml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f64adc79d..7297db6fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # CHANGELOG -## v0.43.0 +## v0.43.1 *July 31, 2023* diff --git a/crates/ibc-derive/Cargo.toml b/crates/ibc-derive/Cargo.toml index aa18910e4..5463fc8bb 100644 --- a/crates/ibc-derive/Cargo.toml +++ b/crates/ibc-derive/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ibc-derive" -version = "0.1.0" +version = "0.2.0" license = "Apache-2.0" readme = "README.md" description = "Macros implementation of #[derive(ClientState)] and #[derive(ConsensusState)]" diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 045999611..5fca810d1 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ibc" -version = "0.43.0" +version = "0.43.1" edition = "2021" license = "Apache-2.0" readme = "README.md" @@ -75,7 +75,7 @@ scale-info = { version = "2.1.2", default-features = false, features = ["derive" borsh = {version = "0.9.0", default-features = false, optional = true } parking_lot = { version = "0.12.1", default-features = false, optional = true } -ibc-derive = { version = "0.1.0", path = "../ibc-derive"} +ibc-derive = "0.2.0" schemars = { version = "0.8.12", optional = true } From 7191d8839eb2ff8c9e95a455a5727e233ea2b28a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Tue, 1 Aug 2023 14:55:03 -0400 Subject: [PATCH 010/182] Decouple `Router` from `ValidationContext` (#789) * fix mocks * clippy * changelog * move module retrieval outside of handlers --- .../breaking-changes/788-decouple-router.md | 2 + crates/ibc/src/core/context.rs | 3 +- crates/ibc/src/core/handler.rs | 139 ++++++++++++------ .../ics04_channel/handler/acknowledgement.rs | 33 +++-- .../handler/chan_close_confirm.rs | 23 ++- .../ics04_channel/handler/chan_close_init.rs | 36 +++-- .../ics04_channel/handler/chan_open_ack.rs | 32 ++-- .../handler/chan_open_confirm.rs | 31 ++-- .../ics04_channel/handler/chan_open_init.rs | 30 ++-- .../ics04_channel/handler/chan_open_try.rs | 31 ++-- .../core/ics04_channel/handler/recv_packet.rs | 25 ++-- .../src/core/ics04_channel/handler/timeout.rs | 35 +++-- crates/ibc/src/mock/context.rs | 84 ++--------- crates/ibc/src/mock/ics18_relayer/context.rs | 10 +- crates/ibc/src/mock/mod.rs | 2 + crates/ibc/src/mock/router.rs | 54 +++++++ 16 files changed, 319 insertions(+), 251 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/788-decouple-router.md create mode 100644 crates/ibc/src/mock/router.rs diff --git a/.changelog/unreleased/breaking-changes/788-decouple-router.md b/.changelog/unreleased/breaking-changes/788-decouple-router.md new file mode 100644 index 000000000..15e21c2e5 --- /dev/null +++ b/.changelog/unreleased/breaking-changes/788-decouple-router.md @@ -0,0 +1,2 @@ +- Decouple `Router` from `ValidationContext` + ([#788](https://github.com/cosmos/ibc-rs/pull/788)) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index c1409449f..67420200a 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -27,7 +27,6 @@ use crate::core::ics24_host::path::{ AckPath, ChannelEndPath, ClientConnectionPath, ClientConsensusStatePath, CommitmentPath, ConnectionPath, ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, }; -use crate::core::router::Router; use crate::core::timestamp::Timestamp; use crate::Height; @@ -92,7 +91,7 @@ impl std::error::Error for RouterError { /// Context to be implemented by the host that provides all "read-only" methods. /// /// Trait used for the top-level [`validate`](crate::core::validate) -pub trait ValidationContext: Router { +pub trait ValidationContext { type ClientValidationContext; type E: ClientExecutionContext; type AnyConsensusState: ConsensusState; diff --git a/crates/ibc/src/core/handler.rs b/crates/ibc/src/core/handler.rs index c13072d8d..8bd035848 100644 --- a/crates/ibc/src/core/handler.rs +++ b/crates/ibc/src/core/handler.rs @@ -5,6 +5,7 @@ use super::ics03_connection::handler::{ conn_open_ack, conn_open_confirm, conn_open_init, conn_open_try, }; use super::ics03_connection::msgs::ConnectionMsg; +use super::ics04_channel::error::ChannelError; use super::ics04_channel::handler::acknowledgement::{ acknowledgement_packet_execute, acknowledgement_packet_validate, }; @@ -28,12 +29,17 @@ use super::ics04_channel::handler::timeout::{ }; use super::ics04_channel::msgs::{ChannelMsg, PacketMsg}; use super::msgs::MsgEnvelope; +use super::router::Router; use super::{ContextError, ExecutionContext, ValidationContext}; /// Entrypoint which performs both validation and message execution -pub fn dispatch(ctx: &mut impl ExecutionContext, msg: MsgEnvelope) -> Result<(), RouterError> { - validate(ctx, msg.clone())?; - execute(ctx, msg) +pub fn dispatch( + ctx: &mut impl ExecutionContext, + router: &mut impl Router, + msg: MsgEnvelope, +) -> Result<(), RouterError> { + validate(ctx, router, msg.clone())?; + execute(ctx, router, msg) } /// Entrypoint which only performs message validation @@ -44,7 +50,11 @@ pub fn dispatch(ctx: &mut impl ExecutionContext, msg: MsgEnvelope) -> Result<(), /// That is, the state transition of message `i` must be applied before /// message `i+1` is validated. This is equivalent to calling /// `dispatch()` on each successively. -pub fn validate(ctx: &Ctx, msg: MsgEnvelope) -> Result<(), RouterError> +pub fn validate( + ctx: &Ctx, + router: &mut impl Router, + msg: MsgEnvelope, +) -> Result<(), RouterError> where Ctx: ValidationContext, { @@ -68,31 +78,39 @@ where } .map_err(RouterError::ContextError), MsgEnvelope::Channel(msg) => { - let module_id = ctx + let module_id = router .lookup_module_channel(&msg) .map_err(ContextError::from)?; + let module = router + .get_route(&module_id) + .ok_or(ContextError::from(ChannelError::RouteNotFound))?; match msg { - ChannelMsg::OpenInit(msg) => chan_open_init_validate(ctx, module_id, msg), - ChannelMsg::OpenTry(msg) => chan_open_try_validate(ctx, module_id, msg), - ChannelMsg::OpenAck(msg) => chan_open_ack_validate(ctx, module_id, msg), - ChannelMsg::OpenConfirm(msg) => chan_open_confirm_validate(ctx, module_id, msg), - ChannelMsg::CloseInit(msg) => chan_close_init_validate(ctx, module_id, msg), - ChannelMsg::CloseConfirm(msg) => chan_close_confirm_validate(ctx, module_id, msg), + ChannelMsg::OpenInit(msg) => chan_open_init_validate(ctx, module, msg), + ChannelMsg::OpenTry(msg) => chan_open_try_validate(ctx, module, msg), + ChannelMsg::OpenAck(msg) => chan_open_ack_validate(ctx, module, msg), + ChannelMsg::OpenConfirm(msg) => chan_open_confirm_validate(ctx, module, msg), + ChannelMsg::CloseInit(msg) => chan_close_init_validate(ctx, module, msg), + ChannelMsg::CloseConfirm(msg) => chan_close_confirm_validate(ctx, module, msg), } .map_err(RouterError::ContextError) } MsgEnvelope::Packet(msg) => { - let module_id = ctx.lookup_module_packet(&msg).map_err(ContextError::from)?; + let module_id = router + .lookup_module_packet(&msg) + .map_err(ContextError::from)?; + let module = router + .get_route(&module_id) + .ok_or(ContextError::from(ChannelError::RouteNotFound))?; match msg { PacketMsg::Recv(msg) => recv_packet_validate(ctx, msg), - PacketMsg::Ack(msg) => acknowledgement_packet_validate(ctx, module_id, msg), + PacketMsg::Ack(msg) => acknowledgement_packet_validate(ctx, module, msg), PacketMsg::Timeout(msg) => { - timeout_packet_validate(ctx, module_id, TimeoutMsgType::Timeout(msg)) + timeout_packet_validate(ctx, module, TimeoutMsgType::Timeout(msg)) } PacketMsg::TimeoutOnClose(msg) => { - timeout_packet_validate(ctx, module_id, TimeoutMsgType::TimeoutOnClose(msg)) + timeout_packet_validate(ctx, module, TimeoutMsgType::TimeoutOnClose(msg)) } } .map_err(RouterError::ContextError) @@ -101,7 +119,11 @@ where } /// Entrypoint which only performs message execution -pub fn execute(ctx: &mut Ctx, msg: MsgEnvelope) -> Result<(), RouterError> +pub fn execute( + ctx: &mut Ctx, + router: &mut impl Router, + msg: MsgEnvelope, +) -> Result<(), RouterError> where Ctx: ExecutionContext, { @@ -125,31 +147,39 @@ where } .map_err(RouterError::ContextError), MsgEnvelope::Channel(msg) => { - let module_id = ctx + let module_id = router .lookup_module_channel(&msg) .map_err(ContextError::from)?; + let module = router + .get_route_mut(&module_id) + .ok_or(ContextError::from(ChannelError::RouteNotFound))?; match msg { - ChannelMsg::OpenInit(msg) => chan_open_init_execute(ctx, module_id, msg), - ChannelMsg::OpenTry(msg) => chan_open_try_execute(ctx, module_id, msg), - ChannelMsg::OpenAck(msg) => chan_open_ack_execute(ctx, module_id, msg), - ChannelMsg::OpenConfirm(msg) => chan_open_confirm_execute(ctx, module_id, msg), - ChannelMsg::CloseInit(msg) => chan_close_init_execute(ctx, module_id, msg), - ChannelMsg::CloseConfirm(msg) => chan_close_confirm_execute(ctx, module_id, msg), + ChannelMsg::OpenInit(msg) => chan_open_init_execute(ctx, module, msg), + ChannelMsg::OpenTry(msg) => chan_open_try_execute(ctx, module, msg), + ChannelMsg::OpenAck(msg) => chan_open_ack_execute(ctx, module, msg), + ChannelMsg::OpenConfirm(msg) => chan_open_confirm_execute(ctx, module, msg), + ChannelMsg::CloseInit(msg) => chan_close_init_execute(ctx, module, msg), + ChannelMsg::CloseConfirm(msg) => chan_close_confirm_execute(ctx, module, msg), } .map_err(RouterError::ContextError) } MsgEnvelope::Packet(msg) => { - let module_id = ctx.lookup_module_packet(&msg).map_err(ContextError::from)?; + let module_id = router + .lookup_module_packet(&msg) + .map_err(ContextError::from)?; + let module = router + .get_route_mut(&module_id) + .ok_or(ContextError::from(ChannelError::RouteNotFound))?; match msg { - PacketMsg::Recv(msg) => recv_packet_execute(ctx, module_id, msg), - PacketMsg::Ack(msg) => acknowledgement_packet_execute(ctx, module_id, msg), + PacketMsg::Recv(msg) => recv_packet_execute(ctx, module, msg), + PacketMsg::Ack(msg) => acknowledgement_packet_execute(ctx, module, msg), PacketMsg::Timeout(msg) => { - timeout_packet_execute(ctx, module_id, TimeoutMsgType::Timeout(msg)) + timeout_packet_execute(ctx, module, TimeoutMsgType::Timeout(msg)) } PacketMsg::TimeoutOnClose(msg) => { - timeout_packet_execute(ctx, module_id, TimeoutMsgType::TimeoutOnClose(msg)) + timeout_packet_execute(ctx, module, TimeoutMsgType::TimeoutOnClose(msg)) } } .map_err(RouterError::ContextError) @@ -216,6 +246,7 @@ mod tests { use crate::mock::consensus_state::MockConsensusState; use crate::mock::context::MockContext; use crate::mock::header::MockHeader; + use crate::mock::router::MockRouter; use crate::prelude::*; use crate::test_utils::{get_dummy_account_id, DummyTransferModule}; use crate::Height; @@ -267,13 +298,12 @@ mod tests { let transfer_module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); // We reuse this same context across all tests. Nothing in particular needs parametrizing. - let mut ctx = { - let mut ctx = MockContext::default(); - let module = DummyTransferModule::new(); - ctx.add_route(transfer_module_id.clone(), module).unwrap(); + let mut ctx = MockContext::default(); - ctx - }; + let mut router = MockRouter::default(); + router + .add_route(transfer_module_id.clone(), DummyTransferModule::new()) + .unwrap(); let create_client_msg = MsgCreateClient::new( MockClientState::new(MockHeader::new(start_client_height)).into(), @@ -346,6 +376,7 @@ mod tests { // First, create a client.. let res = dispatch( &mut ctx, + &mut router, MsgEnvelope::Client(ClientMsg::CreateClient(create_client_msg.clone())), ); @@ -354,7 +385,7 @@ mod tests { "ICS26 routing dispatch test 'client creation' failed for message {create_client_msg:?} with result: {res:?}", ); - ctx.scope_port_to_module(msg_chan_init.port_id_on_a.clone(), transfer_module_id); + router.scope_port_to_module(msg_chan_init.port_id_on_a.clone(), transfer_module_id); // Figure out the ID of the client that was just created. assert!(matches!( @@ -576,7 +607,7 @@ mod tests { for test in tests { let res = match test.msg.clone() { - TestMsg::Ics26(msg) => dispatch(&mut ctx, msg).map(|_| ()), + TestMsg::Ics26(msg) => dispatch(&mut ctx, &mut router, msg).map(|_| ()), TestMsg::Ics20(msg) => send_transfer(&mut ctx, msg) .map_err(|e: TokenTransferError| ChannelError::AppModule { description: e.to_string(), @@ -606,9 +637,9 @@ mod tests { } } - fn get_channel_events_ctx() -> MockContext { + fn get_channel_events_ctx_router() -> (MockContext, MockRouter) { let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - let mut ctx = MockContext::default() + let ctx = MockContext::default() .with_client(&ClientId::default(), Height::new(0, 1).unwrap()) .with_connection( ConnectionId::new(0), @@ -625,25 +656,28 @@ mod tests { ) .unwrap(), ); - let module = DummyTransferModule::new(); + let mut router = MockRouter::default(); - ctx.add_route(module_id.clone(), module).unwrap(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); // Note: messages will be using the default port - ctx.scope_port_to_module(PortId::default(), module_id); + router.scope_port_to_module(PortId::default(), module_id); - ctx + (ctx, router) } #[test] fn test_chan_open_init_event() { - let mut ctx = get_channel_events_ctx(); + let (mut ctx, mut router) = get_channel_events_ctx_router(); let msg_chan_open_init = MsgChannelOpenInit::try_from(get_dummy_raw_msg_chan_open_init(None)).unwrap(); dispatch( &mut ctx, + &mut router, MsgEnvelope::Channel(ChannelMsg::OpenInit(msg_chan_open_init)), ) .unwrap(); @@ -658,13 +692,14 @@ mod tests { #[test] fn test_chan_open_try_event() { - let mut ctx = get_channel_events_ctx(); + let (mut ctx, mut router) = get_channel_events_ctx_router(); let msg_chan_open_try = MsgChannelOpenTry::try_from(get_dummy_raw_msg_chan_open_try(1)).unwrap(); dispatch( &mut ctx, + &mut router, MsgEnvelope::Channel(ChannelMsg::OpenTry(msg_chan_open_try)), ) .unwrap(); @@ -679,7 +714,8 @@ mod tests { #[test] fn test_chan_open_ack_event() { - let mut ctx = get_channel_events_ctx().with_channel( + let (ctx, mut router) = get_channel_events_ctx_router(); + let mut ctx = ctx.with_channel( PortId::default(), ChannelId::default(), ChannelEnd::new( @@ -697,6 +733,7 @@ mod tests { dispatch( &mut ctx, + &mut router, MsgEnvelope::Channel(ChannelMsg::OpenAck(msg_chan_open_ack)), ) .unwrap(); @@ -711,7 +748,8 @@ mod tests { #[test] fn test_chan_open_confirm_event() { - let mut ctx = get_channel_events_ctx().with_channel( + let (ctx, mut router) = get_channel_events_ctx_router(); + let mut ctx = ctx.with_channel( PortId::default(), ChannelId::default(), ChannelEnd::new( @@ -729,6 +767,7 @@ mod tests { dispatch( &mut ctx, + &mut router, MsgEnvelope::Channel(ChannelMsg::OpenConfirm(msg_chan_open_confirm)), ) .unwrap(); @@ -743,7 +782,8 @@ mod tests { #[test] fn test_chan_close_init_event() { - let mut ctx = get_channel_events_ctx().with_channel( + let (ctx, mut router) = get_channel_events_ctx_router(); + let mut ctx = ctx.with_channel( PortId::default(), ChannelId::default(), ChannelEnd::new( @@ -761,6 +801,7 @@ mod tests { dispatch( &mut ctx, + &mut router, MsgEnvelope::Channel(ChannelMsg::CloseInit(msg_chan_close_init)), ) .unwrap(); @@ -775,7 +816,8 @@ mod tests { #[test] fn test_chan_close_confirm_event() { - let mut ctx = get_channel_events_ctx().with_channel( + let (ctx, mut router) = get_channel_events_ctx_router(); + let mut ctx = ctx.with_channel( PortId::default(), ChannelId::default(), ChannelEnd::new( @@ -793,6 +835,7 @@ mod tests { dispatch( &mut ctx, + &mut router, MsgEnvelope::Channel(ChannelMsg::CloseConfirm(msg_chan_close_confirm)), ) .unwrap(); diff --git a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs index e65cbecaa..9a92398ab 100644 --- a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs @@ -14,12 +14,13 @@ use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqAckPath, }; -use crate::core::{events::IbcEvent, ics04_channel::events::AcknowledgePacket, router::ModuleId}; +use crate::core::router::Module; +use crate::core::{events::IbcEvent, ics04_channel::events::AcknowledgePacket}; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn acknowledgement_packet_validate( ctx_a: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgAcknowledgement, ) -> Result<(), ContextError> where @@ -27,10 +28,6 @@ where { validate(ctx_a, &msg)?; - let module = ctx_a - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - module .on_acknowledgement_packet_validate(&msg.packet, &msg.acknowledgement, &msg.signer) .map_err(ContextError::PacketError) @@ -38,7 +35,7 @@ where pub(crate) fn acknowledgement_packet_execute( ctx_a: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgAcknowledgement, ) -> Result<(), ContextError> where @@ -73,10 +70,6 @@ where return Ok(()); }; - let module = ctx_a - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - let (extras, cb_result) = module.on_acknowledgement_packet_execute(&msg.packet, &msg.acknowledgement, &msg.signer); @@ -236,14 +229,18 @@ mod tests { use crate::core::ics24_host::identifier::ChannelId; use crate::core::ics24_host::identifier::PortId; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::Timestamp; use crate::core::timestamp::ZERO_DURATION; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::{applications::transfer::MODULE_ID_STR, test_utils::DummyTransferModule}; struct Fixture { ctx: MockContext, + router: MockRouter, client_height: Height, module_id: ModuleId, msg: MsgAcknowledgement, @@ -256,11 +253,12 @@ mod tests { #[fixture] fn fixture() -> Fixture { let client_height = Height::new(0, 2).unwrap(); - let mut ctx = MockContext::default().with_client(&ClientId::default(), client_height); + let ctx = MockContext::default().with_client(&ClientId::default(), client_height); + let mut router = MockRouter::default(); let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); let module = DummyTransferModule::new(); - ctx.add_route(module_id.clone(), module).unwrap(); + router.add_route(module_id.clone(), module).unwrap(); let msg = MsgAcknowledgement::try_from(get_dummy_raw_msg_acknowledgement( client_height.revision_height(), @@ -302,6 +300,7 @@ mod tests { Fixture { ctx, + router, client_height, module_id, msg, @@ -402,6 +401,7 @@ mod tests { fn ack_unordered_chan_execute(fixture: Fixture) { let Fixture { ctx, + mut router, module_id, msg, packet_commitment, @@ -423,7 +423,8 @@ mod tests { packet_commitment, ); - let res = acknowledgement_packet_execute(&mut ctx, module_id, msg); + let module = router.get_route_mut(&module_id).unwrap(); + let res = acknowledgement_packet_execute(&mut ctx, module, msg); assert!(res.is_ok()); @@ -439,6 +440,7 @@ mod tests { fn ack_ordered_chan_execute(fixture: Fixture) { let Fixture { ctx, + mut router, module_id, msg, packet_commitment, @@ -460,7 +462,8 @@ mod tests { packet_commitment, ); - let res = acknowledgement_packet_execute(&mut ctx, module_id, msg); + let module = router.get_route_mut(&module_id).unwrap(); + let res = acknowledgement_packet_execute(&mut ctx, module, msg); assert!(res.is_ok()); 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 85f5df02f..de945d5b5 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 @@ -14,12 +14,12 @@ use crate::core::ics04_channel::events::CloseConfirm; use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm; use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; -use crate::core::router::ModuleId; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_close_confirm_validate( ctx_b: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgChannelCloseConfirm, ) -> Result<(), ContextError> where @@ -27,9 +27,6 @@ where { validate(ctx_b, &msg)?; - let module = ctx_b - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; module.on_chan_close_confirm_validate(&msg.port_id_on_b, &msg.chan_id_on_b)?; Ok(()) @@ -37,15 +34,12 @@ where pub(crate) fn chan_close_confirm_execute( ctx_b: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgChannelCloseConfirm, ) -> Result<(), ContextError> where ExecCtx: ExecutionContext, { - let module = ctx_b - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; let extras = module.on_chan_close_confirm_execute(&msg.port_id_on_b, &msg.chan_id_on_b)?; let chan_end_path_on_b = ChannelEndPath::new(&msg.port_id_on_b, &msg.chan_id_on_b); let chan_end_on_b = ctx_b.channel_end(&chan_end_path_on_b)?; @@ -181,12 +175,14 @@ mod tests { use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::ZERO_DURATION; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; use crate::applications::transfer::MODULE_ID_STR; + use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; #[test] @@ -279,12 +275,15 @@ mod tests { msg_chan_close_confirm.chan_id_on_b.clone(), chan_end, ); + let mut router = MockRouter::default(); - let module = DummyTransferModule::new(); let module_id = ModuleId::new(MODULE_ID_STR.to_string()); - context.add_route(module_id.clone(), module).unwrap(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); - let res = chan_close_confirm_execute(&mut context, module_id, msg_chan_close_confirm); + let module = router.get_route_mut(&module_id).unwrap(); + let res = chan_close_confirm_execute(&mut context, module, msg_chan_close_confirm); assert!(res.is_ok(), "Execution success: happy path"); assert_eq!(context.events.len(), 2); 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 448801a15..114f2d16f 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 @@ -9,12 +9,12 @@ use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::events::CloseInit; use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit; use crate::core::ics24_host::path::ChannelEndPath; -use crate::core::router::ModuleId; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_close_init_validate( ctx_a: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgChannelCloseInit, ) -> Result<(), ContextError> where @@ -22,9 +22,6 @@ where { validate(ctx_a, &msg)?; - let module = ctx_a - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; module.on_chan_close_init_validate(&msg.port_id_on_a, &msg.chan_id_on_a)?; Ok(()) @@ -32,15 +29,12 @@ where pub(crate) fn chan_close_init_execute( ctx_a: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgChannelCloseInit, ) -> Result<(), ContextError> where ExecCtx: ExecutionContext, { - let module = ctx_a - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; let extras = module.on_chan_close_init_execute(&msg.port_id_on_a, &msg.chan_id_on_a)?; let chan_end_path_on_a = ChannelEndPath::new(&msg.port_id_on_a, &msg.chan_id_on_a); let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; @@ -137,11 +131,14 @@ mod tests { use crate::core::ics04_channel::msgs::chan_close_init::test_util::get_dummy_raw_msg_chan_close_init; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::ZERO_DURATION; use crate::applications::transfer::MODULE_ID_STR; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; #[test] @@ -224,13 +221,9 @@ mod tests { .unwrap(); let mut context = { - let mut default_context = MockContext::default(); + let default_context = MockContext::default(); let client_consensus_state_height = default_context.host_height().unwrap(); - let module = DummyTransferModule::new(); - let module_id = ModuleId::new(MODULE_ID_STR.to_string()); - default_context.add_route(module_id, module).unwrap(); - default_context .with_client(&client_id, client_consensus_state_height) .with_connection(conn_id, conn_end) @@ -241,11 +234,16 @@ mod tests { ) }; - let res = chan_close_init_execute( - &mut context, - ModuleId::new(MODULE_ID_STR.to_string()), - msg_chan_close_init, - ); + let mut router = MockRouter::default(); + router + .add_route( + ModuleId::new(MODULE_ID_STR.to_string()), + DummyTransferModule::new(), + ) + .unwrap(); + let module_id = ModuleId::new(MODULE_ID_STR.to_string()); + let module = router.get_route_mut(&module_id).unwrap(); + let res = chan_close_init_execute(&mut context, module, msg_chan_close_init); assert!(res.is_ok(), "Execution happy path"); assert_eq!(context.events.len(), 2); 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 b1d229cdb..0356c40a2 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 @@ -1,5 +1,6 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenAck`. +use crate::core::router::Module; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; @@ -14,12 +15,11 @@ use crate::core::ics04_channel::events::OpenAck; use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; -use crate::core::router::ModuleId; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_open_ack_validate( ctx_a: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgChannelOpenAck, ) -> Result<(), ContextError> where @@ -27,9 +27,6 @@ where { validate(ctx_a, &msg)?; - let module = ctx_a - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; module.on_chan_open_ack_validate(&msg.port_id_on_a, &msg.chan_id_on_a, &msg.version_on_b)?; Ok(()) @@ -37,15 +34,12 @@ where pub(crate) fn chan_open_ack_execute( ctx_a: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgChannelOpenAck, ) -> Result<(), ContextError> where ExecCtx: ExecutionContext, { - let module = ctx_a - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; let extras = module.on_chan_open_ack_execute(&msg.port_id_on_a, &msg.chan_id_on_a, &msg.version_on_b)?; let chan_end_path_on_a = ChannelEndPath::new(&msg.port_id_on_a, &msg.chan_id_on_a); @@ -180,15 +174,19 @@ mod tests { use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; use crate::core::ics24_host::identifier::ClientId; use crate::core::ics24_host::identifier::ConnectionId; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::ZERO_DURATION; use crate::Height; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; pub struct Fixture { pub context: MockContext, + pub router: MockRouter, pub module_id: ModuleId, pub msg: MsgChannelOpenAck, pub client_id_on_a: ClientId, @@ -201,10 +199,13 @@ mod tests { #[fixture] fn fixture() -> Fixture { let proof_height = 10; - let mut context = MockContext::default(); - let module = DummyTransferModule::new(); - let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - context.add_route(module_id.clone(), module).unwrap(); + let context = MockContext::default(); + + let module_id = ModuleId::new(MODULE_ID_STR.to_string()); + let mut router = MockRouter::default(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); let client_id_on_a = ClientId::new(mock_client_type(), 45).unwrap(); let conn_id_on_a = ConnectionId::new(2); @@ -231,6 +232,7 @@ mod tests { Fixture { context, + router, module_id, msg, client_id_on_a, @@ -359,6 +361,7 @@ mod tests { fn chan_open_ack_execute_happy_path(fixture: Fixture) { let Fixture { context, + mut router, module_id, msg, client_id_on_a, @@ -378,7 +381,8 @@ mod tests { chan_end_on_a, ); - let res = chan_open_ack_execute(&mut context, module_id, msg); + let module = router.get_route_mut(&module_id).unwrap(); + let res = chan_open_ack_execute(&mut context, module, msg); assert!(res.is_ok(), "Execution happy path"); 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 dd8e52463..c30c4041c 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 @@ -14,12 +14,12 @@ use crate::core::ics04_channel::events::OpenConfirm; use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm; use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; -use crate::core::router::ModuleId; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_open_confirm_validate( ctx_b: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgChannelOpenConfirm, ) -> Result<(), ContextError> where @@ -27,9 +27,6 @@ where { validate(ctx_b, &msg)?; - let module = ctx_b - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; module.on_chan_open_confirm_validate(&msg.port_id_on_b, &msg.chan_id_on_b)?; Ok(()) @@ -37,16 +34,12 @@ where pub(crate) fn chan_open_confirm_execute( ctx_b: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgChannelOpenConfirm, ) -> Result<(), ContextError> where ExecCtx: ExecutionContext, { - let module = ctx_b - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - let extras = module.on_chan_open_confirm_execute(&msg.port_id_on_b, &msg.chan_id_on_b)?; let chan_end_path_on_b = ChannelEndPath::new(&msg.port_id_on_b, &msg.chan_id_on_b); let chan_end_on_b = ctx_b.channel_end(&chan_end_path_on_b)?; @@ -185,15 +178,19 @@ mod tests { use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::ChannelId; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::ZERO_DURATION; use crate::Height; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::{applications::transfer::MODULE_ID_STR, test_utils::DummyTransferModule}; pub struct Fixture { pub context: MockContext, + pub router: MockRouter, pub module_id: ModuleId, pub msg: MsgChannelOpenConfirm, pub client_id_on_b: ClientId, @@ -206,10 +203,13 @@ mod tests { #[fixture] fn fixture() -> Fixture { let proof_height = 10; - let mut context = MockContext::default(); - let module = DummyTransferModule::new(); + let context = MockContext::default(); + let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - context.add_route(module_id.clone(), module).unwrap(); + let mut router = MockRouter::default(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); let client_id_on_b = ClientId::new(mock_client_type(), 45).unwrap(); let conn_id_on_b = ConnectionId::new(2); @@ -237,6 +237,7 @@ mod tests { Fixture { context, + router, module_id, msg, client_id_on_b, @@ -338,6 +339,7 @@ mod tests { fn chan_open_confirm_execute_happy_path(fixture: Fixture) { let Fixture { context, + mut router, module_id, msg, client_id_on_b, @@ -357,7 +359,8 @@ mod tests { chan_end_on_b, ); - let res = chan_open_confirm_execute(&mut context, module_id, msg); + let module = router.get_route_mut(&module_id).unwrap(); + let res = chan_open_confirm_execute(&mut context, module, msg); assert!(res.is_ok(), "Execution happy path"); 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 95e9ba3e9..d4f7e5d92 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 @@ -5,17 +5,16 @@ use crate::prelude::*; use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::ClientStateCommon; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; -use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::events::OpenInit; use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; use crate::core::ics24_host::identifier::ChannelId; use crate::core::ics24_host::path::{ChannelEndPath, SeqAckPath, SeqRecvPath, SeqSendPath}; -use crate::core::router::ModuleId; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_open_init_validate( ctx_a: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgChannelOpenInit, ) -> Result<(), ContextError> where @@ -24,9 +23,6 @@ where validate(ctx_a, &msg)?; let chan_id_on_a = ChannelId::new(ctx_a.channel_counter()?); - let module = ctx_a - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; module.on_chan_open_init_validate( msg.ordering, &msg.connection_hops_on_a, @@ -41,16 +37,13 @@ where pub(crate) fn chan_open_init_execute( ctx_a: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgChannelOpenInit, ) -> Result<(), ContextError> where ExecCtx: ExecutionContext, { let chan_id_on_a = ChannelId::new(ctx_a.channel_counter()?); - let module = ctx_a - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; let (extras, version) = module.on_chan_open_init_execute( msg.ordering, &msg.connection_hops_on_a, @@ -155,12 +148,16 @@ mod tests { use crate::core::ics24_host::identifier::ConnectionId; use crate::applications::transfer::MODULE_ID_STR; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; use test_log::test; pub struct Fixture { pub ctx: MockContext, + pub router: MockRouter, pub module_id: ModuleId, pub msg: MsgChannelOpenInit, } @@ -169,10 +166,12 @@ mod tests { fn fixture() -> Fixture { let msg = MsgChannelOpenInit::try_from(get_dummy_raw_msg_chan_open_init(None)).unwrap(); - let mut default_ctx = MockContext::default(); + let default_ctx = MockContext::default(); let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - let module = DummyTransferModule::new(); - default_ctx.add_route(module_id.clone(), module).unwrap(); + let mut router = MockRouter::default(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); let msg_conn_init = MsgConnectionOpenInit::new_dummy(); @@ -194,6 +193,7 @@ mod tests { Fixture { ctx, + router, module_id, msg, } @@ -238,11 +238,13 @@ mod tests { fn chan_open_init_execute_happy_path(fixture: Fixture) { let Fixture { mut ctx, + mut router, module_id, msg, } = fixture; + let module = router.get_route_mut(&module_id).unwrap(); - let res = chan_open_init_execute(&mut ctx, module_id, msg); + let res = chan_open_init_execute(&mut ctx, module, msg); assert!(res.is_ok(), "Execution succeeds; good parameters"); 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 a9ca05e43..44ff9bf8d 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 @@ -1,5 +1,6 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenTry`. +use crate::core::router::Module; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; @@ -16,12 +17,11 @@ use crate::core::ics24_host::identifier::ChannelId; use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; use crate::core::ics24_host::path::{SeqAckPath, SeqRecvPath, SeqSendPath}; -use crate::core::router::ModuleId; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_open_try_validate( ctx_b: &ValCtx, - module_id: ModuleId, + module: &dyn Module, msg: MsgChannelOpenTry, ) -> Result<(), ContextError> where @@ -31,9 +31,6 @@ where let chan_id_on_b = ChannelId::new(ctx_b.channel_counter()?); - let module = ctx_b - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; module.on_chan_open_try_validate( msg.ordering, &msg.connection_hops_on_b, @@ -48,17 +45,13 @@ where pub(crate) fn chan_open_try_execute( ctx_b: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgChannelOpenTry, ) -> Result<(), ContextError> where ExecCtx: ExecutionContext, { let chan_id_on_b = ChannelId::new(ctx_b.channel_counter()?); - let module = ctx_b - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - let (extras, version) = module.on_chan_open_try_execute( msg.ordering, &msg.connection_hops_on_b, @@ -199,16 +192,20 @@ mod tests { use crate::core::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try; use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::ZERO_DURATION; use crate::Height; use crate::applications::transfer::MODULE_ID_STR; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; pub struct Fixture { pub ctx: MockContext, + pub router: MockRouter, pub module_id: ModuleId, pub msg: MsgChannelOpenTry, pub client_id_on_b: ClientId, @@ -241,13 +238,17 @@ mod tests { let hops = vec![conn_id_on_b.clone()]; msg.connection_hops_on_b = hops; - let mut ctx = MockContext::default(); - let module = DummyTransferModule::new(); + let ctx = MockContext::default(); + let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - ctx.add_route(module_id.clone(), module).unwrap(); + let mut router = MockRouter::default(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); Fixture { ctx, + router, module_id, msg, client_id_on_b, @@ -313,6 +314,7 @@ mod tests { fn chan_open_try_execute_happy_path(fixture: Fixture) { let Fixture { ctx, + mut router, module_id, msg, client_id_on_b, @@ -326,7 +328,8 @@ mod tests { .with_client(&client_id_on_b, Height::new(0, proof_height).unwrap()) .with_connection(conn_id_on_b, conn_end_on_b); - let res = chan_open_try_execute(&mut ctx, module_id, msg); + let module = router.get_route_mut(&module_id).unwrap(); + let res = chan_open_try_execute(&mut ctx, module, msg); assert!(res.is_ok(), "Execution success: happy path"); 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 fe0f0d131..936b81b97 100644 --- a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs @@ -16,7 +16,7 @@ use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, ReceiptPath, SeqRecvPath, }; -use crate::core::router::ModuleId; +use crate::core::router::Module; use crate::core::timestamp::Expiry; use crate::core::{ContextError, ExecutionContext, ValidationContext}; @@ -36,7 +36,7 @@ where pub(crate) fn recv_packet_execute( ctx_b: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, msg: MsgRecvPacket, ) -> Result<(), ContextError> where @@ -74,10 +74,6 @@ where } } - let module = ctx_b - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - let (extras, acknowledgement) = module.on_recv_packet_execute(&msg.packet, &msg.signer); // state changes @@ -295,17 +291,21 @@ mod tests { use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::Timestamp; use crate::core::timestamp::ZERO_DURATION; use crate::Height; use crate::mock::context::MockContext; use crate::mock::ics18_relayer::context::RelayerContext; + use crate::mock::router::MockRouter; use crate::test_utils::get_dummy_account_id; use crate::{applications::transfer::MODULE_ID_STR, test_utils::DummyTransferModule}; pub struct Fixture { pub context: MockContext, + pub router: MockRouter, pub module_id: ModuleId, pub client_height: Height, pub host_height: Height, @@ -316,11 +316,13 @@ mod tests { #[fixture] fn fixture() -> Fixture { - let mut context = MockContext::default(); + let context = MockContext::default(); let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - let module = DummyTransferModule::new(); - context.add_route(module_id.clone(), module).unwrap(); + let mut router = MockRouter::default(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); let host_height = context.query_latest_height().unwrap().increment(); @@ -357,6 +359,7 @@ mod tests { Fixture { context, + router, module_id, client_height, host_height, @@ -483,6 +486,7 @@ mod tests { fn recv_packet_execute_happy_path(fixture: Fixture) { let Fixture { context, + mut router, module_id, msg, conn_end_on_b, @@ -495,7 +499,8 @@ mod tests { .with_connection(ConnectionId::default(), conn_end_on_b) .with_channel(PortId::default(), ChannelId::default(), chan_end_on_b); - let res = recv_packet_execute(&mut ctx, module_id, msg); + let module = router.get_route_mut(&module_id).unwrap(); + let res = recv_packet_execute(&mut ctx, module, msg); assert!(res.is_ok()); diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout.rs b/crates/ibc/src/core/ics04_channel/handler/timeout.rs index 8a142d9fc..1f61da24c 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout.rs @@ -19,7 +19,7 @@ use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ ChannelEndPath, ClientConsensusStatePath, CommitmentPath, ReceiptPath, SeqRecvPath, }; -use crate::core::router::ModuleId; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) enum TimeoutMsgType { @@ -29,7 +29,7 @@ pub(crate) enum TimeoutMsgType { pub(crate) fn timeout_packet_validate( ctx_a: &ValCtx, - module_id: ModuleId, + module: &dyn Module, timeout_msg_type: TimeoutMsgType, ) -> Result<(), ContextError> where @@ -40,10 +40,6 @@ where TimeoutMsgType::TimeoutOnClose(msg) => timeout_on_close::validate(ctx_a, msg), }?; - let module = ctx_a - .get_route(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - let (packet, signer) = match timeout_msg_type { TimeoutMsgType::Timeout(msg) => (msg.packet, msg.signer), TimeoutMsgType::TimeoutOnClose(msg) => (msg.packet, msg.signer), @@ -56,7 +52,7 @@ where pub(crate) fn timeout_packet_execute( ctx_a: &mut ExecCtx, - module_id: ModuleId, + module: &mut dyn Module, timeout_msg_type: TimeoutMsgType, ) -> Result<(), ContextError> where @@ -86,10 +82,6 @@ where return Ok(()); }; - let module = ctx_a - .get_route_mut(&module_id) - .ok_or(ChannelError::RouteNotFound)?; - let (extras, cb_result) = module.on_timeout_packet_execute(&packet, &signer); cb_result?; @@ -288,15 +280,19 @@ mod tests { use crate::core::ics04_channel::msgs::timeout::MsgTimeout; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; + use crate::core::router::ModuleId; + use crate::core::router::Router; use crate::core::timestamp::Timestamp; use crate::core::timestamp::ZERO_DURATION; use crate::applications::transfer::MODULE_ID_STR; use crate::mock::context::MockContext; + use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; struct Fixture { ctx: MockContext, + pub router: MockRouter, client_height: Height, module_id: ModuleId, msg: MsgTimeout, @@ -309,13 +305,15 @@ mod tests { #[fixture] fn fixture() -> Fixture { let client_height = Height::new(0, 2).unwrap(); - let mut ctx = MockContext::default().with_client(&ClientId::default(), client_height); + let ctx = MockContext::default().with_client(&ClientId::default(), client_height); let client_height = Height::new(0, 2).unwrap(); let module_id: ModuleId = ModuleId::new(MODULE_ID_STR.to_string()); - let module = DummyTransferModule::new(); - ctx.add_route(module_id.clone(), module).unwrap(); + let mut router = MockRouter::default(); + router + .add_route(module_id.clone(), DummyTransferModule::new()) + .unwrap(); let msg_proof_height = 2; let msg_timeout_height = 5; @@ -363,6 +361,7 @@ mod tests { Fixture { ctx, + router, client_height, module_id, msg, @@ -608,6 +607,7 @@ mod tests { fn timeout_unordered_chan_execute(fixture: Fixture) { let Fixture { ctx, + mut router, module_id, msg, packet_commitment, @@ -629,7 +629,8 @@ mod tests { packet_commitment, ); - let res = timeout_packet_execute(&mut ctx, module_id, TimeoutMsgType::Timeout(msg)); + let module = router.get_route_mut(&module_id).unwrap(); + let res = timeout_packet_execute(&mut ctx, module, TimeoutMsgType::Timeout(msg)); assert!(res.is_ok()); @@ -646,6 +647,7 @@ mod tests { fn timeout_ordered_chan_execute(fixture: Fixture) { let Fixture { ctx, + mut router, module_id, msg, packet_commitment, @@ -667,7 +669,8 @@ mod tests { packet_commitment, ); - let res = timeout_packet_execute(&mut ctx, module_id, TimeoutMsgType::Timeout(msg)); + let module = router.get_route_mut(&module_id).unwrap(); + let res = timeout_packet_execute(&mut ctx, module, TimeoutMsgType::Timeout(msg)); assert!(res.is_ok()); diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 04e49752a..c6f34e122 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -44,7 +44,6 @@ use crate::core::ics04_channel::packet::{Receipt, Sequence}; use crate::core::ics23_commitment::commitment::CommitmentPrefix; use crate::core::ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortId}; use crate::core::router::Router; -use crate::core::router::{Module, ModuleId}; use crate::core::timestamp::Timestamp; use crate::core::{ContextError, ValidationContext}; use crate::core::{ExecutionContext, MsgEnvelope}; @@ -188,9 +187,6 @@ pub struct MockIbcStore { pub packet_acknowledgement: PortChannelIdMap>, - /// Maps ports to the the module that owns it - pub port_to_module: BTreeMap, - /// Constant-size commitments to packets data fields pub packet_commitment: PortChannelIdMap>, @@ -220,9 +216,6 @@ pub struct MockContext { /// An object that stores all IBC related data. pub ibc_store: Arc>, - /// To implement ValidationContext Router - router: BTreeMap>, - pub events: Vec, pub logs: Vec, @@ -258,7 +251,6 @@ impl Clone for MockContext { history: self.history.clone(), block_time: self.block_time, ibc_store, - router: self.router.clone(), events: self.events.clone(), logs: self.logs.clone(), } @@ -321,7 +313,6 @@ impl MockContext { .collect(), block_time, ibc_store: Arc::new(Mutex::new(MockIbcStore::default())), - router: BTreeMap::new(), events: Vec::new(), logs: Vec::new(), } @@ -608,17 +599,6 @@ impl MockContext { self } - pub fn add_route( - &mut self, - module_id: ModuleId, - module: impl Module + 'static, - ) -> Result<(), String> { - match self.router.insert(module_id, Arc::new(module)) { - None => Ok(()), - Some(_) => Err("Duplicate module_id".to_owned()), - } - } - /// Accessor for a block of the local (host) chain from this context. /// Returns `None` if the block at the requested height does not exist. pub fn host_block(&self, target_height: &Height) -> Option<&HostBlock> { @@ -660,8 +640,12 @@ 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<(), RelayerError> { - dispatch(self, msg).map_err(RelayerError::TransactionFailed)?; + pub fn deliver( + &mut self, + router: &mut impl Router, + msg: MsgEnvelope, + ) -> Result<(), RelayerError> { + dispatch(self, router, msg).map_err(RelayerError::TransactionFailed)?; // Create a new block. self.advance_host_chain_height(); Ok(()) @@ -695,21 +679,6 @@ impl MockContext { Ok(()) } - pub fn add_port(&mut self, port_id: PortId) { - let module_id = ModuleId::new(format!("module{port_id}")); - self.ibc_store - .lock() - .port_to_module - .insert(port_id, module_id); - } - - pub fn scope_port_to_module(&mut self, port_id: PortId, module_id: ModuleId) { - self.ibc_store - .lock() - .port_to_module - .insert(port_id, module_id); - } - pub fn latest_client_states(&self, client_id: &ClientId) -> AnyClientState { self.ibc_store.lock().clients[client_id] .client_state @@ -766,31 +735,6 @@ impl RelayerContext for MockContext { } } -impl Router for MockContext { - fn get_route(&self, module_id: &ModuleId) -> Option<&dyn Module> { - self.router.get(module_id).map(Arc::as_ref) - } - fn get_route_mut(&mut self, module_id: &ModuleId) -> Option<&mut dyn Module> { - // NOTE: The following: - - // self.router.get_mut(module_id).and_then(Arc::get_mut) - - // doesn't work due to a compiler bug. So we expand it out manually. - - match self.router.get_mut(module_id) { - Some(arc_mod) => match Arc::get_mut(arc_mod) { - Some(m) => Some(m), - None => None, - }, - None => None, - } - } - - fn lookup_module_by_port(&self, port_id: &PortId) -> Option { - self.ibc_store.lock().port_to_module.get(port_id).cloned() - } -} - impl ValidationContext for MockContext { type ClientValidationContext = Self; type E = Self; @@ -1383,6 +1327,7 @@ mod tests { use crate::core::router::{Module, ModuleExtras, ModuleId}; use crate::mock::context::MockContext; use crate::mock::host::HostType; + use crate::mock::router::MockRouter; use crate::signer::Signer; use crate::test_utils::get_dummy_bech32_account; use crate::Height; @@ -1733,20 +1678,17 @@ mod tests { } } - let mut ctx = MockContext::new( - ChainId::new("mockgaia", 1).unwrap(), - HostType::Mock, - 1, - Height::new(1, 1).expect("Never fails"), - ); - ctx.add_route(ModuleId::new("foomodule".to_string()), FooModule::default()) + let mut router = MockRouter::default(); + router + .add_route(ModuleId::new("foomodule".to_string()), FooModule::default()) .expect("Never fails"); - ctx.add_route(ModuleId::new("barmodule".to_string()), BarModule) + router + .add_route(ModuleId::new("barmodule".to_string()), BarModule) .expect("Never fails"); let mut on_recv_packet_result = |module_id: &'static str| { let module_id = ModuleId::new(module_id.to_string()); - let m = ctx.get_route_mut(&module_id).expect("Never fails"); + let m = router.get_route_mut(&module_id).expect("Never fails"); let result = m.on_recv_packet_execute(&Packet::default(), &get_dummy_bech32_account().into()); (module_id, result) diff --git a/crates/ibc/src/mock/ics18_relayer/context.rs b/crates/ibc/src/mock/ics18_relayer/context.rs index 3b569eff1..73b9b3f3b 100644 --- a/crates/ibc/src/mock/ics18_relayer/context.rs +++ b/crates/ibc/src/mock/ics18_relayer/context.rs @@ -36,6 +36,7 @@ mod tests { use crate::mock::host::{HostBlock, HostType}; use crate::mock::ics18_relayer::context::RelayerContext; use crate::mock::ics18_relayer::error::RelayerError; + use crate::mock::router::MockRouter; use crate::prelude::*; use crate::Height; @@ -113,6 +114,9 @@ mod tests { Some(tm_client_type()), // The target host chain (B) is synthetic TM. Some(client_on_a_for_b_height), ); + // dummy; not actually used in client updates + let mut router_a = MockRouter::default(); + let mut ctx_b = MockContext::new( chain_id_b, HostType::SyntheticTendermint, @@ -126,6 +130,8 @@ mod tests { Some(mock_client_type()), // The target host chain is mock. Some(client_on_b_for_a_height), ); + // dummy; not actually used in client updates + let mut router_b = MockRouter::default(); for _i in 0..num_iterations { // Update client on chain B to latest height of A. @@ -143,7 +149,7 @@ mod tests { // - send the message to B. We bypass ICS18 interface and call directly into // MockContext `recv` method (to avoid additional serialization steps). - let dispatch_res_b = ctx_b.deliver(MsgEnvelope::Client(client_msg_b)); + let dispatch_res_b = ctx_b.deliver(&mut router_b, MsgEnvelope::Client(client_msg_b)); let validation_res = ctx_b.validate(); assert!( validation_res.is_ok(), @@ -182,7 +188,7 @@ mod tests { debug!("client_msg_a = {:?}", client_msg_a); // - send the message to A - let dispatch_res_a = ctx_a.deliver(MsgEnvelope::Client(client_msg_a)); + let dispatch_res_a = ctx_a.deliver(&mut router_a, MsgEnvelope::Client(client_msg_a)); let validation_res = ctx_a.validate(); assert!( validation_res.is_ok(), diff --git a/crates/ibc/src/mock/mod.rs b/crates/ibc/src/mock/mod.rs index 8547ce3fe..a2450b5a2 100644 --- a/crates/ibc/src/mock/mod.rs +++ b/crates/ibc/src/mock/mod.rs @@ -14,3 +14,5 @@ pub mod host; pub mod ics18_relayer; #[cfg(any(test, feature = "mocks", feature = "mocks-no-std"))] pub mod misbehaviour; +#[cfg(any(test, feature = "mocks"))] +pub mod router; diff --git a/crates/ibc/src/mock/router.rs b/crates/ibc/src/mock/router.rs new file mode 100644 index 000000000..8433fc9f2 --- /dev/null +++ b/crates/ibc/src/mock/router.rs @@ -0,0 +1,54 @@ +use crate::{core::ics24_host::identifier::PortId, prelude::*}; +use alloc::{collections::BTreeMap, sync::Arc}; + +use crate::core::router::{Module, ModuleId, Router}; + +#[derive(Default)] +pub struct MockRouter { + router: BTreeMap>, + + /// Maps ports to the the module that owns it + pub port_to_module: BTreeMap, +} + +impl MockRouter { + pub fn add_route( + &mut self, + module_id: ModuleId, + module: impl Module + 'static, + ) -> Result<(), String> { + match self.router.insert(module_id, Arc::new(module)) { + None => Ok(()), + Some(_) => Err("Duplicate module_id".to_owned()), + } + } + + pub fn scope_port_to_module(&mut self, port_id: PortId, module_id: ModuleId) { + self.port_to_module.insert(port_id, module_id); + } +} + +impl Router for MockRouter { + fn get_route(&self, module_id: &ModuleId) -> Option<&dyn Module> { + self.router.get(module_id).map(Arc::as_ref) + } + fn get_route_mut(&mut self, module_id: &ModuleId) -> Option<&mut dyn Module> { + // NOTE: The following: + + // self.router.get_mut(module_id).and_then(Arc::get_mut) + + // doesn't work due to a compiler bug. So we expand it out manually. + + match self.router.get_mut(module_id) { + Some(arc_mod) => match Arc::get_mut(arc_mod) { + Some(m) => Some(m), + None => None, + }, + None => None, + } + } + + fn lookup_module_by_port(&self, port_id: &PortId) -> Option { + self.port_to_module.get(port_id).cloned() + } +} From e0f256892b1daf0d7e77dd2c745ba082bea9e275 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Thu, 3 Aug 2023 12:13:12 -0700 Subject: [PATCH 011/182] imp(Router)!: simplify `Module` lookup (#806) * imp(router): simplify Module lookup * fix: clippy catches * imp: discard ModuleId and use PortId::transfer everywhere instead * Revert "imp: discard ModuleId and use PortId::transfer everywhere instead" This reverts commit 9227ef7557aa8437b4eec5dc6fd1311fa1af0333. * nit: RouterError variants * fix: cargo test --- .../802-simplify-module-lookup.md | 2 + crates/ibc/src/core/context.rs | 7 ++- crates/ibc/src/core/handler.rs | 43 ++++++++++++------- crates/ibc/src/core/ics04_channel/error.rs | 16 ------- crates/ibc/src/core/ics04_channel/msgs.rs | 22 ++++++++++ crates/ibc/src/core/router.rs | 37 +--------------- crates/ibc/src/mock/router.rs | 2 +- 7 files changed, 60 insertions(+), 69 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/802-simplify-module-lookup.md diff --git a/.changelog/unreleased/breaking-changes/802-simplify-module-lookup.md b/.changelog/unreleased/breaking-changes/802-simplify-module-lookup.md new file mode 100644 index 000000000..68dc850cc --- /dev/null +++ b/.changelog/unreleased/breaking-changes/802-simplify-module-lookup.md @@ -0,0 +1,2 @@ +- Simplify Module lookup in the `Router` trait + ([#802](https://github.com/cosmos/ibc-rs/issues/802)) diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index 67420200a..b74437af1 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -33,6 +33,7 @@ use crate::Height; use super::ics02_client::client_state::ClientState; use super::ics02_client::consensus_state::ConsensusState; use super::ics02_client::ClientExecutionContext; +use super::ics24_host::identifier::PortId; /// Top-level error #[derive(Debug, Display, From)] @@ -69,6 +70,10 @@ pub enum RouterError { UnknownMessageTypeUrl { url: String }, /// the message is malformed and cannot be decoded error: `{0}` MalformedMessageBytes(ibc_proto::protobuf::Error), + /// port `{port_id}` is unknown + UnknownPort { port_id: PortId }, + /// module not found + ModuleNotFound, } impl From for RouterError { @@ -82,8 +87,8 @@ impl std::error::Error for RouterError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { Self::ContextError(e) => Some(e), - Self::UnknownMessageTypeUrl { .. } => None, Self::MalformedMessageBytes(e) => Some(e), + _ => None, } } } diff --git a/crates/ibc/src/core/handler.rs b/crates/ibc/src/core/handler.rs index 8bd035848..1a7530e73 100644 --- a/crates/ibc/src/core/handler.rs +++ b/crates/ibc/src/core/handler.rs @@ -5,7 +5,6 @@ use super::ics03_connection::handler::{ conn_open_ack, conn_open_confirm, conn_open_init, conn_open_try, }; use super::ics03_connection::msgs::ConnectionMsg; -use super::ics04_channel::error::ChannelError; use super::ics04_channel::handler::acknowledgement::{ acknowledgement_packet_execute, acknowledgement_packet_validate, }; @@ -27,10 +26,12 @@ use super::ics04_channel::handler::recv_packet::{recv_packet_execute, recv_packe use super::ics04_channel::handler::timeout::{ timeout_packet_execute, timeout_packet_validate, TimeoutMsgType, }; -use super::ics04_channel::msgs::{ChannelMsg, PacketMsg}; +use super::ics04_channel::msgs::{ + channel_msg_to_port_id, packet_msg_to_port_id, ChannelMsg, PacketMsg, +}; use super::msgs::MsgEnvelope; use super::router::Router; -use super::{ContextError, ExecutionContext, ValidationContext}; +use super::{ExecutionContext, ValidationContext}; /// Entrypoint which performs both validation and message execution pub fn dispatch( @@ -78,12 +79,15 @@ where } .map_err(RouterError::ContextError), MsgEnvelope::Channel(msg) => { + let port_id = channel_msg_to_port_id(&msg); let module_id = router - .lookup_module_channel(&msg) - .map_err(ContextError::from)?; + .lookup_module(port_id) + .ok_or(RouterError::UnknownPort { + port_id: port_id.clone(), + })?; let module = router .get_route(&module_id) - .ok_or(ContextError::from(ChannelError::RouteNotFound))?; + .ok_or(RouterError::ModuleNotFound)?; match msg { ChannelMsg::OpenInit(msg) => chan_open_init_validate(ctx, module, msg), @@ -96,12 +100,15 @@ where .map_err(RouterError::ContextError) } MsgEnvelope::Packet(msg) => { + let port_id = packet_msg_to_port_id(&msg); let module_id = router - .lookup_module_packet(&msg) - .map_err(ContextError::from)?; + .lookup_module(port_id) + .ok_or(RouterError::UnknownPort { + port_id: port_id.clone(), + })?; let module = router .get_route(&module_id) - .ok_or(ContextError::from(ChannelError::RouteNotFound))?; + .ok_or(RouterError::ModuleNotFound)?; match msg { PacketMsg::Recv(msg) => recv_packet_validate(ctx, msg), @@ -147,12 +154,15 @@ where } .map_err(RouterError::ContextError), MsgEnvelope::Channel(msg) => { + let port_id = channel_msg_to_port_id(&msg); let module_id = router - .lookup_module_channel(&msg) - .map_err(ContextError::from)?; + .lookup_module(port_id) + .ok_or(RouterError::UnknownPort { + port_id: port_id.clone(), + })?; let module = router .get_route_mut(&module_id) - .ok_or(ContextError::from(ChannelError::RouteNotFound))?; + .ok_or(RouterError::ModuleNotFound)?; match msg { ChannelMsg::OpenInit(msg) => chan_open_init_execute(ctx, module, msg), @@ -165,12 +175,15 @@ where .map_err(RouterError::ContextError) } MsgEnvelope::Packet(msg) => { + let port_id = packet_msg_to_port_id(&msg); let module_id = router - .lookup_module_packet(&msg) - .map_err(ContextError::from)?; + .lookup_module(port_id) + .ok_or(RouterError::UnknownPort { + port_id: port_id.clone(), + })?; let module = router .get_route_mut(&module_id) - .ok_or(ContextError::from(ChannelError::RouteNotFound))?; + .ok_or(RouterError::ModuleNotFound)?; match msg { PacketMsg::Recv(msg) => recv_packet_execute(ctx, module, msg), diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index 905e37722..d8a98a2a7 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -16,21 +16,8 @@ use crate::Height; use displaydoc::Display; -#[derive(Debug, Display)] -pub enum PortError { - /// port `{port_id}` is unknown - UnknownPort { port_id: PortId }, - /// implementation specific error - ImplementationSpecific, -} - -#[cfg(feature = "std")] -impl std::error::Error for PortError {} - #[derive(Debug, Display)] pub enum ChannelError { - /// port error: `{0}` - Port(PortError), /// invalid channel end: `{channel_end}` InvalidChannelEnd { channel_end: String }, /// invalid channel id: expected `{expected}`, actual `{actual}` @@ -79,8 +66,6 @@ pub enum ChannelError { 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 }, /// other error: `{description}` @@ -216,7 +201,6 @@ impl std::error::Error for PacketError { impl std::error::Error for ChannelError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - Self::Port(e) => Some(e), Self::InvalidIdentifier(e) => Some(e), Self::PacketVerificationFailed { client_error: e, .. diff --git a/crates/ibc/src/core/ics04_channel/msgs.rs b/crates/ibc/src/core/ics04_channel/msgs.rs index fdffdeeda..fad6922d3 100644 --- a/crates/ibc/src/core/ics04_channel/msgs.rs +++ b/crates/ibc/src/core/ics04_channel/msgs.rs @@ -28,6 +28,8 @@ pub use recv_packet::MsgRecvPacket; pub use timeout::MsgTimeout; pub use timeout_on_close::MsgTimeoutOnClose; +use crate::core::ics24_host::identifier::PortId; + /// All channel messages #[derive(Clone, Debug, PartialEq, Eq)] pub enum ChannelMsg { @@ -47,3 +49,23 @@ pub enum PacketMsg { Timeout(MsgTimeout), TimeoutOnClose(MsgTimeoutOnClose), } + +pub(crate) fn channel_msg_to_port_id(msg: &ChannelMsg) -> &PortId { + match msg { + ChannelMsg::OpenInit(msg) => &msg.port_id_on_a, + ChannelMsg::OpenTry(msg) => &msg.port_id_on_b, + ChannelMsg::OpenAck(msg) => &msg.port_id_on_a, + ChannelMsg::OpenConfirm(msg) => &msg.port_id_on_b, + ChannelMsg::CloseInit(msg) => &msg.port_id_on_a, + ChannelMsg::CloseConfirm(msg) => &msg.port_id_on_b, + } +} + +pub(crate) fn packet_msg_to_port_id(msg: &PacketMsg) -> &PortId { + match msg { + PacketMsg::Recv(msg) => &msg.packet.port_id_on_b, + PacketMsg::Ack(msg) => &msg.packet.port_id_on_a, + PacketMsg::Timeout(msg) => &msg.packet.port_id_on_a, + PacketMsg::TimeoutOnClose(msg) => &msg.packet.port_id_on_a, + } +} diff --git a/crates/ibc/src/core/router.rs b/crates/ibc/src/core/router.rs index 34421ae38..81adbf99d 100644 --- a/crates/ibc/src/core/router.rs +++ b/crates/ibc/src/core/router.rs @@ -7,10 +7,7 @@ use core::fmt::{Debug, Display, Error as FmtError, Formatter}; use crate::core::events::ModuleEvent; use crate::core::ics04_channel::acknowledgement::Acknowledgement; use crate::core::ics04_channel::channel::{Counterparty, Order}; -use crate::core::ics04_channel::error::PortError::UnknownPort; use crate::core::ics04_channel::error::{ChannelError, PacketError}; -use crate::core::ics04_channel::msgs::ChannelMsg; -use crate::core::ics04_channel::msgs::PacketMsg; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::PortId; @@ -26,39 +23,7 @@ pub trait Router { fn get_route_mut(&mut self, module_id: &ModuleId) -> Option<&mut dyn Module>; /// Return the module_id associated with a given port_id - fn lookup_module_by_port(&self, port_id: &PortId) -> Option; - - fn lookup_module_channel(&self, msg: &ChannelMsg) -> Result { - let port_id = match msg { - ChannelMsg::OpenInit(msg) => &msg.port_id_on_a, - ChannelMsg::OpenTry(msg) => &msg.port_id_on_b, - ChannelMsg::OpenAck(msg) => &msg.port_id_on_a, - ChannelMsg::OpenConfirm(msg) => &msg.port_id_on_b, - ChannelMsg::CloseInit(msg) => &msg.port_id_on_a, - ChannelMsg::CloseConfirm(msg) => &msg.port_id_on_b, - }; - let module_id = self - .lookup_module_by_port(port_id) - .ok_or(ChannelError::Port(UnknownPort { - port_id: port_id.clone(), - }))?; - Ok(module_id) - } - - fn lookup_module_packet(&self, msg: &PacketMsg) -> Result { - let port_id = match msg { - PacketMsg::Recv(msg) => &msg.packet.port_id_on_b, - PacketMsg::Ack(msg) => &msg.packet.port_id_on_a, - PacketMsg::Timeout(msg) => &msg.packet.port_id_on_a, - PacketMsg::TimeoutOnClose(msg) => &msg.packet.port_id_on_a, - }; - let module_id = self - .lookup_module_by_port(port_id) - .ok_or(ChannelError::Port(UnknownPort { - port_id: port_id.clone(), - }))?; - Ok(module_id) - } + fn lookup_module(&self, port_id: &PortId) -> Option; } /// Module name, internal to the chain. diff --git a/crates/ibc/src/mock/router.rs b/crates/ibc/src/mock/router.rs index 8433fc9f2..b2c4c3270 100644 --- a/crates/ibc/src/mock/router.rs +++ b/crates/ibc/src/mock/router.rs @@ -48,7 +48,7 @@ impl Router for MockRouter { } } - fn lookup_module_by_port(&self, port_id: &PortId) -> Option { + fn lookup_module(&self, port_id: &PortId) -> Option { self.port_to_module.get(port_id).cloned() } } From 79cb166e2d0fd3cb69621574b2590975cff79d0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Fri, 4 Aug 2023 10:01:01 -0400 Subject: [PATCH 012/182] Decouple `TokenTransfer*` and `SendPacket*` (#787) * modify traits and send_transfer * fix mocks * changelog * Remove MockTokenTransferModule * remove ctx from get_defaults --- .../786-decouple-token-sendpacket.md | 2 + .../ibc/src/applications/transfer/context.rs | 16 ++-- .../transfer/relay/send_transfer.rs | 69 ++++++++------ crates/ibc/src/core/handler.rs | 2 +- crates/ibc/src/mock/context.rs | 1 - crates/ibc/src/mock/context/applications.rs | 89 ------------------- crates/ibc/src/test_utils.rs | 83 +++++++++++++++++ 7 files changed, 134 insertions(+), 128 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/786-decouple-token-sendpacket.md delete mode 100644 crates/ibc/src/mock/context/applications.rs diff --git a/.changelog/unreleased/breaking-changes/786-decouple-token-sendpacket.md b/.changelog/unreleased/breaking-changes/786-decouple-token-sendpacket.md new file mode 100644 index 000000000..9441d8582 --- /dev/null +++ b/.changelog/unreleased/breaking-changes/786-decouple-token-sendpacket.md @@ -0,0 +1,2 @@ +- Decouple TokenTransfer{Validation,Execution} from SendPacket{Validation,Execution} + ([#786](https://github.com/cosmos/ibc-rs/issues/786)) diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index 16f0d50ab..6b3b25880 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -15,9 +15,6 @@ use crate::applications::transfer::{PrefixedCoin, PrefixedDenom, VERSION}; use crate::core::ics04_channel::acknowledgement::Acknowledgement; use crate::core::ics04_channel::acknowledgement::AcknowledgementStatus; use crate::core::ics04_channel::channel::{Counterparty, Order}; -use crate::core::ics04_channel::context::{ - SendPacketExecutionContext, SendPacketValidationContext, -}; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; @@ -26,7 +23,7 @@ use crate::core::ContextError; use crate::signer::Signer; /// Methods required in token transfer validation, to be implemented by the host -pub trait TokenTransferValidationContext: SendPacketValidationContext { +pub trait TokenTransferValidationContext { type AccountId: TryFrom; /// get_port returns the portID for the transfer module. @@ -75,9 +72,7 @@ pub trait TokenTransferValidationContext: SendPacketValidationContext { } /// Methods required in token transfer execution, to be implemented by the host -pub trait TokenTransferExecutionContext: - TokenTransferValidationContext + SendPacketExecutionContext -{ +pub trait TokenTransferExecutionContext: TokenTransferValidationContext { /// This function should enable sending ibc fungible tokens from one account to another fn send_coins_execute( &mut self, @@ -426,17 +421,16 @@ pub(crate) mod test { use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; - use crate::mock::context::MockContext; + use crate::test_utils::DummyTransferModule; fn get_defaults() -> ( - MockContext, + DummyTransferModule, Order, Vec, PortId, ChannelId, Counterparty, ) { - let ctx = MockContext::default(); let order = Order::Unordered; let connection_hops = vec![ConnectionId::new(1)]; let port_id = PortId::transfer(); @@ -444,7 +438,7 @@ pub(crate) mod test { let counterparty = Counterparty::new(port_id.clone(), Some(channel_id.clone())); ( - ctx, + DummyTransferModule, order, connection_hops, port_id, diff --git a/crates/ibc/src/applications/transfer/relay/send_transfer.rs b/crates/ibc/src/applications/transfer/relay/send_transfer.rs index 20a2c6c7c..7fba81117 100644 --- a/crates/ibc/src/applications/transfer/relay/send_transfer.rs +++ b/crates/ibc/src/applications/transfer/relay/send_transfer.rs @@ -6,29 +6,42 @@ use crate::applications::transfer::events::TransferEvent; use crate::applications::transfer::msgs::transfer::MsgTransfer; use crate::applications::transfer::{is_sender_chain_source, MODULE_ID_STR}; use crate::core::events::{MessageEvent, ModuleEvent}; +use crate::core::ics04_channel::context::{ + SendPacketExecutionContext, SendPacketValidationContext, +}; use crate::core::ics04_channel::handler::send_packet::{send_packet_execute, send_packet_validate}; use crate::core::ics04_channel::packet::Packet; use crate::core::ics24_host::path::{ChannelEndPath, SeqSendPath}; use crate::prelude::*; /// Initiate a token transfer. Equivalent to calling [`send_transfer_validate`], followed by [`send_transfer_execute`]. -pub fn send_transfer(ctx_a: &mut Ctx, msg: MsgTransfer) -> Result<(), TokenTransferError> +pub fn send_transfer( + send_packet_ctx_a: &mut SendPacketCtx, + token_ctx_a: &mut TokenCtx, + msg: MsgTransfer, +) -> Result<(), TokenTransferError> where - Ctx: TokenTransferExecutionContext, + SendPacketCtx: SendPacketExecutionContext, + TokenCtx: TokenTransferExecutionContext, { - send_transfer_validate(ctx_a, msg.clone())?; - send_transfer_execute(ctx_a, msg) + send_transfer_validate(send_packet_ctx_a, token_ctx_a, msg.clone())?; + send_transfer_execute(send_packet_ctx_a, token_ctx_a, msg) } /// Validates the token tranfer. If this succeeds, then it is legal to initiate the transfer with [`send_transfer_execute`]. -pub fn send_transfer_validate(ctx_a: &Ctx, msg: MsgTransfer) -> Result<(), TokenTransferError> +pub fn send_transfer_validate( + send_packet_ctx_a: &SendPacketCtx, + token_ctx_a: &TokenCtx, + msg: MsgTransfer, +) -> Result<(), TokenTransferError> where - Ctx: TokenTransferValidationContext, + SendPacketCtx: SendPacketValidationContext, + TokenCtx: TokenTransferValidationContext, { - ctx_a.can_send_coins()?; + token_ctx_a.can_send_coins()?; let chan_end_path_on_a = ChannelEndPath::new(&msg.port_id_on_a, &msg.chan_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; + let chan_end_on_a = send_packet_ctx_a.channel_end(&chan_end_path_on_a)?; let port_id_on_b = chan_end_on_a.counterparty().port_id().clone(); let chan_id_on_b = chan_end_on_a @@ -41,11 +54,11 @@ where .clone(); let seq_send_path_on_a = SeqSendPath::new(&msg.port_id_on_a, &msg.chan_id_on_a); - let sequence = ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; + let sequence = send_packet_ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; let token = &msg.packet_data.token; - let sender: Ctx::AccountId = msg + let sender: TokenCtx::AccountId = msg .packet_data .sender .clone() @@ -57,10 +70,11 @@ where msg.chan_id_on_a.clone(), &token.denom, ) { - let escrow_address = ctx_a.get_escrow_account(&msg.port_id_on_a, &msg.chan_id_on_a)?; - ctx_a.send_coins_validate(&sender, &escrow_address, token)?; + let escrow_address = + token_ctx_a.get_escrow_account(&msg.port_id_on_a, &msg.chan_id_on_a)?; + token_ctx_a.send_coins_validate(&sender, &escrow_address, token)?; } else { - ctx_a.burn_coins_validate(&sender, token)?; + token_ctx_a.burn_coins_validate(&sender, token)?; } let packet = { @@ -79,21 +93,23 @@ where } }; - send_packet_validate(ctx_a, &packet)?; + send_packet_validate(send_packet_ctx_a, &packet)?; Ok(()) } /// Executes the token transfer. A prior call to [`send_transfer_validate`] MUST have succeeded. -pub fn send_transfer_execute( - ctx_a: &mut Ctx, +pub fn send_transfer_execute( + send_packet_ctx_a: &mut SendPacketCtx, + token_ctx_a: &mut TokenCtx, msg: MsgTransfer, ) -> Result<(), TokenTransferError> where - Ctx: TokenTransferExecutionContext, + SendPacketCtx: SendPacketExecutionContext, + TokenCtx: TokenTransferExecutionContext, { let chan_end_path_on_a = ChannelEndPath::new(&msg.port_id_on_a, &msg.chan_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; + let chan_end_on_a = send_packet_ctx_a.channel_end(&chan_end_path_on_a)?; let port_on_b = chan_end_on_a.counterparty().port_id().clone(); let chan_on_b = chan_end_on_a @@ -107,7 +123,7 @@ where // get the next sequence let seq_send_path_on_a = SeqSendPath::new(&msg.port_id_on_a, &msg.chan_id_on_a); - let sequence = ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; + let sequence = send_packet_ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; let token = &msg.packet_data.token; @@ -123,10 +139,11 @@ where msg.chan_id_on_a.clone(), &token.denom, ) { - let escrow_address = ctx_a.get_escrow_account(&msg.port_id_on_a, &msg.chan_id_on_a)?; - ctx_a.send_coins_execute(&sender, &escrow_address, token)?; + let escrow_address = + token_ctx_a.get_escrow_account(&msg.port_id_on_a, &msg.chan_id_on_a)?; + token_ctx_a.send_coins_execute(&sender, &escrow_address, token)?; } else { - ctx_a.burn_coins_execute(&sender, token)?; + token_ctx_a.burn_coins_execute(&sender, token)?; } let packet = { @@ -147,10 +164,10 @@ where } }; - send_packet_execute(ctx_a, packet)?; + send_packet_execute(send_packet_ctx_a, packet)?; { - ctx_a.log_message(format!( + send_packet_ctx_a.log_message(format!( "IBC fungible token transfer: {} --({})--> {}", msg.packet_data.sender, token, msg.packet_data.receiver )); @@ -162,9 +179,9 @@ where denom: msg.packet_data.token.denom, memo: msg.packet_data.memo, }; - ctx_a.emit_ibc_event(ModuleEvent::from(transfer_event).into()); + send_packet_ctx_a.emit_ibc_event(ModuleEvent::from(transfer_event).into()); - ctx_a.emit_ibc_event(MessageEvent::Module(MODULE_ID_STR.to_string()).into()); + send_packet_ctx_a.emit_ibc_event(MessageEvent::Module(MODULE_ID_STR.to_string()).into()); } Ok(()) diff --git a/crates/ibc/src/core/handler.rs b/crates/ibc/src/core/handler.rs index 1a7530e73..027723b90 100644 --- a/crates/ibc/src/core/handler.rs +++ b/crates/ibc/src/core/handler.rs @@ -621,7 +621,7 @@ mod tests { for test in tests { let res = match test.msg.clone() { TestMsg::Ics26(msg) => dispatch(&mut ctx, &mut router, msg).map(|_| ()), - TestMsg::Ics20(msg) => send_transfer(&mut ctx, msg) + TestMsg::Ics20(msg) => send_transfer(&mut ctx, &mut DummyTransferModule, msg) .map_err(|e: TokenTransferError| ChannelError::AppModule { description: e.to_string(), }) diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index c6f34e122..18e996eaf 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -1,6 +1,5 @@ //! Implementation of a global context mock. Used in testing handlers of all IBC modules. -mod applications; mod clients; use crate::clients::ics07_tendermint::TENDERMINT_CLIENT_TYPE; diff --git a/crates/ibc/src/mock/context/applications.rs b/crates/ibc/src/mock/context/applications.rs deleted file mode 100644 index 219604de0..000000000 --- a/crates/ibc/src/mock/context/applications.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Application context implementations for `MockContext` - -use subtle_encoding::bech32; - -use super::MockContext; -use crate::applications::transfer::context::cosmos_adr028_escrow_address; -use crate::applications::transfer::context::TokenTransferExecutionContext; -use crate::applications::transfer::context::TokenTransferValidationContext; -use crate::applications::transfer::error::TokenTransferError; -use crate::applications::transfer::PrefixedCoin; -use crate::core::ics24_host::identifier::{ChannelId, PortId}; -use crate::Signer; - -impl TokenTransferValidationContext for MockContext { - type AccountId = Signer; - - fn get_port(&self) -> Result { - Ok(PortId::transfer()) - } - - fn get_escrow_account( - &self, - port_id: &PortId, - channel_id: &ChannelId, - ) -> Result { - let addr = cosmos_adr028_escrow_address(port_id, channel_id); - Ok(bech32::encode("cosmos", addr).into()) - } - - fn can_send_coins(&self) -> Result<(), TokenTransferError> { - Ok(()) - } - - fn can_receive_coins(&self) -> Result<(), TokenTransferError> { - Ok(()) - } - - fn send_coins_validate( - &self, - _from_account: &Self::AccountId, - _to_account: &Self::AccountId, - _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { - Ok(()) - } - - fn mint_coins_validate( - &self, - _account: &Self::AccountId, - _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { - Ok(()) - } - - fn burn_coins_validate( - &self, - _account: &Self::AccountId, - _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { - Ok(()) - } -} - -impl TokenTransferExecutionContext for MockContext { - fn send_coins_execute( - &mut self, - _from_account: &Self::AccountId, - _to_account: &Self::AccountId, - _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { - Ok(()) - } - - fn mint_coins_execute( - &mut self, - _account: &Self::AccountId, - _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { - Ok(()) - } - - fn burn_coins_execute( - &mut self, - _account: &Self::AccountId, - _coin: &PrefixedCoin, - ) -> Result<(), TokenTransferError> { - Ok(()) - } -} diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 6235039cc..6cc73f801 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -1,5 +1,11 @@ +use subtle_encoding::bech32; use tendermint::{block, consensus, evidence, public_key::Algorithm}; +use crate::applications::transfer::context::{ + cosmos_adr028_escrow_address, TokenTransferExecutionContext, TokenTransferValidationContext, +}; +use crate::applications::transfer::error::TokenTransferError; +use crate::applications::transfer::PrefixedCoin; use crate::core::ics04_channel::acknowledgement::Acknowledgement; use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::error::{ChannelError, PacketError}; @@ -158,3 +164,80 @@ impl Module for DummyTransferModule { (ModuleExtras::empty(), Ok(())) } } + +impl TokenTransferValidationContext for DummyTransferModule { + type AccountId = Signer; + + fn get_port(&self) -> Result { + Ok(PortId::transfer()) + } + + fn get_escrow_account( + &self, + port_id: &PortId, + channel_id: &ChannelId, + ) -> Result { + let addr = cosmos_adr028_escrow_address(port_id, channel_id); + Ok(bech32::encode("cosmos", addr).into()) + } + + fn can_send_coins(&self) -> Result<(), TokenTransferError> { + Ok(()) + } + + fn can_receive_coins(&self) -> Result<(), TokenTransferError> { + Ok(()) + } + + fn send_coins_validate( + &self, + _from_account: &Self::AccountId, + _to_account: &Self::AccountId, + _coin: &PrefixedCoin, + ) -> Result<(), TokenTransferError> { + Ok(()) + } + + fn mint_coins_validate( + &self, + _account: &Self::AccountId, + _coin: &PrefixedCoin, + ) -> Result<(), TokenTransferError> { + Ok(()) + } + + fn burn_coins_validate( + &self, + _account: &Self::AccountId, + _coin: &PrefixedCoin, + ) -> Result<(), TokenTransferError> { + Ok(()) + } +} + +impl TokenTransferExecutionContext for DummyTransferModule { + fn send_coins_execute( + &mut self, + _from_account: &Self::AccountId, + _to_account: &Self::AccountId, + _coin: &PrefixedCoin, + ) -> Result<(), TokenTransferError> { + Ok(()) + } + + fn mint_coins_execute( + &mut self, + _account: &Self::AccountId, + _coin: &PrefixedCoin, + ) -> Result<(), TokenTransferError> { + Ok(()) + } + + fn burn_coins_execute( + &mut self, + _account: &Self::AccountId, + _coin: &PrefixedCoin, + ) -> Result<(), TokenTransferError> { + Ok(()) + } +} From c9ebc26bc86a95861f80fd565ee58aede8df9f27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Fri, 4 Aug 2023 12:07:50 -0400 Subject: [PATCH 013/182] Implement `ClientState::status()` (#774) * Status enum * implement status API * replace most confirm_not_frozen * validate_self_client no longer uses confirm_not_frozen * remove confirm_not_frozen * clippy * fix test * remove expired() * changelog * Remove `Status::Unknown` * don't consider the client expired if consensus state is in the future * Status methods * remove redundant check * Remove error variant * update changelog --- .../536-clientstate-status.md | 2 + .../traits/client_state_common.rs | 22 ----- .../traits/client_state_validation.rs | 19 +++++ crates/ibc-derive/src/utils.rs | 4 + crates/ibc/Cargo.toml | 2 +- .../clients/ics07_tendermint/client_state.rs | 59 ++++++++++--- .../ibc/src/core/ics02_client/client_state.rs | 50 +++++++++-- crates/ibc/src/core/ics02_client/error.rs | 17 ++-- .../ics02_client/handler/update_client.rs | 25 ++++-- .../ics02_client/handler/upgrade_client.rs | 29 ++----- .../ics03_connection/handler/conn_open_ack.rs | 11 ++- .../handler/conn_open_confirm.rs | 11 ++- .../handler/conn_open_init.rs | 12 ++- .../ics03_connection/handler/conn_open_try.rs | 11 ++- crates/ibc/src/core/ics04_channel/context.rs | 7 ++ .../ics04_channel/handler/acknowledgement.rs | 11 ++- .../handler/chan_close_confirm.rs | 11 ++- .../ics04_channel/handler/chan_close_init.rs | 11 ++- .../ics04_channel/handler/chan_open_ack.rs | 13 ++- .../handler/chan_open_confirm.rs | 11 ++- .../ics04_channel/handler/chan_open_init.rs | 12 ++- .../ics04_channel/handler/chan_open_try.rs | 13 ++- .../core/ics04_channel/handler/recv_packet.rs | 11 ++- .../core/ics04_channel/handler/send_packet.rs | 10 ++- .../src/core/ics04_channel/handler/timeout.rs | 11 ++- .../ics04_channel/handler/timeout_on_close.rs | 11 ++- .../hosts/tendermint/validate_self_client.rs | 7 +- crates/ibc/src/mock/client_state.rs | 85 ++++++++++++++++--- crates/ibc/src/mock/context.rs | 8 +- crates/ibc/src/mock/context/clients.rs | 17 ++++ 30 files changed, 399 insertions(+), 124 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/536-clientstate-status.md diff --git a/.changelog/unreleased/breaking-changes/536-clientstate-status.md b/.changelog/unreleased/breaking-changes/536-clientstate-status.md new file mode 100644 index 000000000..dc414758f --- /dev/null +++ b/.changelog/unreleased/breaking-changes/536-clientstate-status.md @@ -0,0 +1,2 @@ +- [ibc-derive] Replace `ClientState::{confirm_not_frozen, expired}()` with `ClientState::status()` + ([#536](https://github.com/cosmos/ibc-rs/issues/536)) diff --git a/crates/ibc-derive/src/client_state/traits/client_state_common.rs b/crates/ibc-derive/src/client_state/traits/client_state_common.rs index 3c9f4f4b6..b1dc37731 100644 --- a/crates/ibc-derive/src/client_state/traits/client_state_common.rs +++ b/crates/ibc-derive/src/client_state/traits/client_state_common.rs @@ -32,16 +32,6 @@ pub(crate) fn impl_ClientStateCommon( enum_variants.iter(), quote! {validate_proof_height(cs, proof_height)}, ); - let confirm_not_frozen_impl = delegate_call_in_match( - client_state_enum_name, - enum_variants.iter(), - quote! {confirm_not_frozen(cs)}, - ); - let expired_impl = delegate_call_in_match( - client_state_enum_name, - enum_variants.iter(), - quote! {expired(cs, elapsed)}, - ); let verify_upgrade_client_impl = delegate_call_in_match( client_state_enum_name, enum_variants.iter(), @@ -95,18 +85,6 @@ pub(crate) fn impl_ClientStateCommon( } } - fn confirm_not_frozen(&self) -> core::result::Result<(), #ClientError> { - match self { - #(#confirm_not_frozen_impl),* - } - } - - fn expired(&self, elapsed: core::time::Duration) -> bool { - match self { - #(#expired_impl),* - } - } - fn verify_upgrade_client( &self, upgraded_client_state: #Any, diff --git a/crates/ibc-derive/src/client_state/traits/client_state_validation.rs b/crates/ibc-derive/src/client_state/traits/client_state_validation.rs index 3bc90958c..38c8ba397 100644 --- a/crates/ibc-derive/src/client_state/traits/client_state_validation.rs +++ b/crates/ibc-derive/src/client_state/traits/client_state_validation.rs @@ -30,6 +30,13 @@ pub(crate) fn impl_ClientStateValidation( quote! { check_for_misbehaviour(cs, ctx, client_id, client_message, update_kind) }, ); + let status_impl = delegate_call_in_match( + client_state_enum_name, + enum_variants.iter(), + opts, + quote! { status(cs, ctx, client_id) }, + ); + let HostClientState = client_state_enum_name; let ClientValidationContext = &opts.client_validation_context; @@ -37,6 +44,7 @@ pub(crate) fn impl_ClientStateValidation( let ClientId = Imports::ClientId(); let ClientError = Imports::ClientError(); let ClientStateValidation = Imports::ClientStateValidation(); + let Status = Imports::Status(); let UpdateKind = Imports::UpdateKind(); quote! { @@ -64,6 +72,17 @@ pub(crate) fn impl_ClientStateValidation( #(#check_for_misbehaviour_impl),* } } + + fn status( + &self, + ctx: &#ClientValidationContext, + client_id: &#ClientId, + ) -> core::result::Result<#Status, #ClientError> { + match self { + #(#status_impl),* + } + + } } } diff --git a/crates/ibc-derive/src/utils.rs b/crates/ibc-derive/src/utils.rs index 4dc30ad29..fca155424 100644 --- a/crates/ibc-derive/src/utils.rs +++ b/crates/ibc-derive/src/utils.rs @@ -68,6 +68,10 @@ impl Imports { pub fn UpdateKind() -> TokenStream { quote! {ibc::core::ics02_client::client_state::UpdateKind} } + + pub fn Status() -> TokenStream { + quote! {ibc::core::ics02_client::client_state::Status} + } } /// Retrieves the field of a given enum variant. Outputs an error message if the enum variant diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 5fca810d1..e47745faa 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -75,7 +75,7 @@ scale-info = { version = "2.1.2", default-features = false, features = ["derive" borsh = {version = "0.9.0", default-features = false, optional = true } parking_lot = { version = "0.12.1", default-features = false, optional = true } -ibc-derive = "0.2.0" +ibc-derive = { version ="0.2.0", path = "../ibc-derive" } schemars = { version = "0.8.12", optional = true } diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index 687811ec2..3e60b86b8 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -28,7 +28,7 @@ use crate::clients::ics07_tendermint::error::Error; use crate::clients::ics07_tendermint::header::Header as TmHeader; use crate::clients::ics07_tendermint::misbehaviour::Misbehaviour as TmMisbehaviour; use crate::core::ics02_client::client_state::{ - ClientStateCommon, ClientStateExecution, ClientStateValidation, UpdateKind, + ClientStateCommon, ClientStateExecution, ClientStateValidation, Status, UpdateKind, }; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; @@ -248,6 +248,10 @@ impl ClientState { self.chain_id.clone() } + pub fn is_frozen(&self) -> bool { + self.frozen_height.is_some() + } + // Resets custom fields to zero values (used in `update_client`) pub fn zero_custom_fields(&mut self) { self.trusting_period = ZERO_DURATION; @@ -289,19 +293,6 @@ impl ClientStateCommon for ClientState { Ok(()) } - fn confirm_not_frozen(&self) -> Result<(), ClientError> { - if let Some(frozen_height) = self.frozen_height { - return Err(ClientError::ClientFrozen { - description: format!("the client is frozen at height {frozen_height}"), - }); - } - Ok(()) - } - - fn expired(&self, elapsed: Duration) -> bool { - elapsed > self.trusting_period - } - /// Perform client-specific verifications and check all data in the new /// client state to be the same across all valid Tendermint clients for the /// new chain. @@ -422,6 +413,9 @@ impl ClientStateCommon for ClientState { impl ClientStateValidation for ClientState where ClientValidationContext: TmValidationContext, + ClientValidationContext::AnyConsensusState: TryInto, + ClientError: + From<>::Error>, { fn verify_client_message( &self, @@ -460,6 +454,43 @@ where } } } + + fn status( + &self, + ctx: &ClientValidationContext, + client_id: &ClientId, + ) -> Result { + if self.is_frozen() { + return Ok(Status::Frozen); + } + + let latest_consensus_state: TmConsensusState = { + let any_latest_consensus_state = match ctx.consensus_state( + &ClientConsensusStatePath::new(client_id, &self.latest_height), + ) { + Ok(cs) => cs, + // if the client state does not have an associated consensus state for its latest height + // then it must be expired + Err(_) => return Ok(Status::Expired), + }; + + any_latest_consensus_state.try_into()? + }; + + // Note: if the `duration_since()` is `None`, indicating that the latest + // consensus state is in the future, then we don't consider the client + // to be expired. + let now = ctx.host_timestamp()?; + if let Some(elapsed_since_latest_consensus_state) = + now.duration_since(&latest_consensus_state.timestamp()) + { + if elapsed_since_latest_consensus_state > self.trusting_period { + return Ok(Status::Expired); + } + } + + Ok(Status::Active) + } } impl ClientStateExecution for ClientState diff --git a/crates/ibc/src/core/ics02_client/client_state.rs b/crates/ibc/src/core/ics02_client/client_state.rs index bc79de426..441e97b2b 100644 --- a/crates/ibc/src/core/ics02_client/client_state.rs +++ b/crates/ibc/src/core/ics02_client/client_state.rs @@ -1,8 +1,7 @@ //! Defines `ClientState`, the core type to be implemented by light clients -use core::fmt::Debug; +use core::fmt::{Debug, Display, Formatter}; use core::marker::{Send, Sync}; -use core::time::Duration; use ibc_proto::google::protobuf::Any; @@ -30,6 +29,39 @@ pub enum UpdateKind { SubmitMisbehaviour, } +/// Represents the status of a client +#[derive(Debug, PartialEq, Eq)] +pub enum Status { + /// The client is active and allowed to be used + Active, + /// The client is frozen and not allowed to be used + Frozen, + /// The client is expired and not allowed to be used + Expired, + /// Unauthorized indicates that the client type is not registered as an allowed client type. + Unauthorized, +} + +impl Status { + pub fn is_active(&self) -> bool { + *self == Status::Active + } + + pub fn is_frozen(&self) -> bool { + *self == Status::Frozen + } + + pub fn is_expired(&self) -> bool { + *self == Status::Expired + } +} + +impl Display for Status { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { + write!(f, "{self:?}") + } +} + /// `ClientState` methods needed in both validation and execution. /// /// They do not require access to a client `ValidationContext` nor @@ -50,13 +82,6 @@ pub trait ClientStateCommon { /// Validate that the client is at a sufficient height fn validate_proof_height(&self, proof_height: Height) -> Result<(), ClientError>; - /// Assert that the client is not frozen - fn confirm_not_frozen(&self) -> Result<(), ClientError>; - - /// Check if the state is expired when `elapsed` time has passed since the latest consensus - /// state timestamp - fn expired(&self, elapsed: Duration) -> bool; - /// Verify the upgraded client and consensus states and validate proofs /// against the given root. /// @@ -140,6 +165,13 @@ pub trait ClientStateValidation { client_message: Any, update_kind: &UpdateKind, ) -> Result; + + /// Returns the status of the client. Only Active clients are allowed to process packets. + fn status( + &self, + ctx: &ClientValidationContext, + client_id: &ClientId, + ) -> Result; } /// `ClientState` methods which require access to the client's diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index efda51a0f..2ee0b4831 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -12,6 +12,8 @@ use crate::core::timestamp::Timestamp; use crate::core::ContextError; use crate::Height; +use super::client_state::Status; + /// Encodes all the possible client errors #[derive(Debug, Display)] pub enum ClientError { @@ -25,6 +27,8 @@ pub enum ClientError { }, /// client is frozen with description: `{description}` ClientFrozen { description: String }, + /// client is not active. Status=`{status}` + ClientNotActive { status: Status }, /// client state not found: `{client_id}` ClientStateNotFound { client_id: ClientId }, /// client state already exists: `{client_id}` @@ -91,11 +95,6 @@ pub enum ClientError { }, /// timestamp is invalid or missing, timestamp=`{time1}`, now=`{time2}` InvalidConsensusStateTimestamp { time1: Timestamp, time2: Timestamp }, - /// header not within 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 signer error: `{reason}` @@ -121,6 +120,14 @@ impl From for ClientError { } } +impl From<&'static str> for ClientError { + fn from(s: &'static str) -> Self { + Self::Other { + description: s.to_string(), + } + } +} + #[cfg(feature = "std")] impl std::error::Error for ClientError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 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 b487770f9..594a6154b 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -28,7 +28,12 @@ where // Read client state from the host chain store. The client should already exist. let client_state = ctx.client_state(&client_id)?; - client_state.confirm_not_frozen()?; + { + let status = client_state.status(ctx.get_client_validation_context(), &client_id)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } let client_message = msg.client_message(); @@ -245,7 +250,10 @@ mod tests { assert!(res.is_ok(), "result: {res:?}"); let client_state = ctx.client_state(&msg.client_id).unwrap(); - assert!(client_state.confirm_not_frozen().is_ok()); + assert!(client_state + .status(&ctx, &msg.client_id) + .unwrap() + .is_active()); assert_eq!(client_state.latest_height(), latest_header_height); } @@ -292,7 +300,10 @@ mod tests { assert!(res.is_ok(), "result: {res:?}"); let client_state = ctx.client_state(&msg.client_id).unwrap(); - assert!(client_state.confirm_not_frozen().is_ok()); + assert!(client_state + .status(&ctx, &msg.client_id) + .unwrap() + .is_active()); assert_eq!(client_state.latest_height(), latest_header_height); } @@ -413,7 +424,10 @@ mod tests { assert!(res.is_ok(), "result: {res:?}"); let client_state = ctx_a.client_state(&msg.client_id).unwrap(); - assert!(client_state.confirm_not_frozen().is_ok()); + assert!(client_state + .status(&ctx_a, &msg.client_id) + .unwrap() + .is_active()); assert_eq!(client_state.latest_height(), latest_header_height); assert_eq!(client_state, ctx_a.latest_client_states(&msg.client_id)); } @@ -496,7 +510,8 @@ mod tests { fn ensure_misbehaviour(ctx: &MockContext, client_id: &ClientId, client_type: &ClientType) { let client_state = ctx.client_state(client_id).unwrap(); - assert!(client_state.confirm_not_frozen().is_err()); + let status = client_state.status(ctx, client_id).unwrap(); + assert!(status.is_frozen(), "client_state status: {status}"); // check events assert_eq!(ctx.events.len(), 2); 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 70035c5b3..3980d5b77 100644 --- a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs @@ -4,8 +4,8 @@ use crate::prelude::*; use crate::core::context::ContextError; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; use crate::core::ics02_client::client_state::ClientStateExecution; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::events::UpgradeClient; @@ -26,8 +26,13 @@ where // Read the current latest client state from the host chain store. let old_client_state = ctx.client_state(&client_id)?; - // Check if the client is frozen. - old_client_state.confirm_not_frozen()?; + // Check if the client is active. + { + let status = old_client_state.status(ctx.get_client_validation_context(), &client_id)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } // Read the latest consensus state from the host chain store. let old_client_cons_state_path = @@ -39,24 +44,6 @@ where height: old_client_state.latest_height(), })?; - let now = ctx.host_timestamp()?; - let duration = now - .duration_since(&old_consensus_state.timestamp()) - .ok_or_else(|| ClientError::InvalidConsensusStateTimestamp { - time1: old_consensus_state.timestamp(), - time2: now, - })?; - - // Check if the latest consensus state is within the trust period. - if old_client_state.expired(duration) { - return Err(ContextError::ClientError( - ClientError::HeaderNotWithinTrustPeriod { - latest_time: old_consensus_state.timestamp(), - update_time: now, - }, - )); - }; - // Validate the upgraded client state and consensus state and verify proofs against the root old_client_state.verify_upgrade_client( msg.upgraded_client_state.clone(), 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 caa5c01e1..8ca94b4a1 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 @@ -4,8 +4,9 @@ use ibc_proto::protobuf::Protobuf; use prost::Message; use crate::core::context::ContextError; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenAck; @@ -58,7 +59,13 @@ where { let client_state_of_b_on_a = ctx_a.client_state(vars.client_id_on_a())?; - client_state_of_b_on_a.confirm_not_frozen()?; + { + let status = client_state_of_b_on_a + .status(ctx_a.get_client_validation_context(), vars.client_id_on_a())?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_b_on_a.validate_proof_height(msg.proofs_height_on_b)?; let client_cons_state_path_on_a = 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 3f7d88f23..56a96b45b 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 @@ -3,8 +3,9 @@ use ibc_proto::protobuf::Protobuf; use crate::core::context::ContextError; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenConfirm; @@ -47,7 +48,13 @@ where { let client_state_of_a_on_b = ctx_b.client_state(client_id_on_b)?; - client_state_of_a_on_b.confirm_not_frozen()?; + { + let status = client_state_of_a_on_b + .status(ctx_b.get_client_validation_context(), client_id_on_b)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = 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 ec64be11b..1d7e11a5c 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 @@ -1,9 +1,10 @@ //! Protocol logic specific to ICS3 messages of type `MsgConnectionOpenInit`. +use crate::core::ics02_client::client_state::ClientStateValidation; +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use crate::core::context::ContextError; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::events::OpenInit; use crate::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; @@ -19,7 +20,14 @@ where // An IBC client running on the local (host) chain should exist. let client_state_of_b_on_a = ctx_a.client_state(&msg.client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + + { + let status = client_state_of_b_on_a + .status(ctx_a.get_client_validation_context(), &msg.client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } if let Some(version) = msg.version { version.verify_is_supported(&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 b26d555d2..090f3ede5 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 @@ -4,8 +4,9 @@ use ibc_proto::protobuf::Protobuf; use prost::Message; use crate::core::context::ContextError; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenTry; @@ -59,7 +60,13 @@ where { let client_state_of_a_on_b = ctx_b.client_state(vars.conn_end_on_b.client_id())?; - client_state_of_a_on_b.confirm_not_frozen()?; + { + let status = client_state_of_a_on_b + .status(ctx_b.get_client_validation_context(), &msg.client_id_on_b)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_a_on_b.validate_proof_height(msg.proofs_height_on_a)?; let client_cons_state_path_on_b = diff --git a/crates/ibc/src/core/ics04_channel/context.rs b/crates/ibc/src/core/ics04_channel/context.rs index 1f95c6521..3e24e1729 100644 --- a/crates/ibc/src/core/ics04_channel/context.rs +++ b/crates/ibc/src/core/ics04_channel/context.rs @@ -26,6 +26,9 @@ pub trait SendPacketValidationContext { type AnyConsensusState: ConsensusState; type AnyClientState: ClientState; + /// Retrieve the context that implements all clients' `ValidationContext`. + fn get_client_validation_context(&self) -> &Self::ClientValidationContext; + /// Returns the ChannelEnd for the given `port_id` and `chan_id`. fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; @@ -54,6 +57,10 @@ where type AnyConsensusState = T::AnyConsensusState; type AnyClientState = T::AnyClientState; + fn get_client_validation_context(&self) -> &Self::ClientValidationContext { + self.get_client_validation_context() + } + fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { self.channel_end(channel_end_path) } diff --git a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs index 9a92398ab..64d7b31f4 100644 --- a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs @@ -1,7 +1,8 @@ +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use crate::core::events::MessageEvent; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics03_connection::delay::verify_conn_delay_passed; @@ -179,7 +180,13 @@ where let client_id_on_a = conn_end_on_a.client_id(); let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + { + let status = client_state_of_b_on_a + .status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; let client_cons_state_path_on_a = 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 de945d5b5..11974a118 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 @@ -1,10 +1,11 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelCloseConfirm`. +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; @@ -116,7 +117,13 @@ where let client_id_on_b = conn_end_on_b.client_id(); let client_state_of_a_on_b = ctx_b.client_state(client_id_on_b)?; - client_state_of_a_on_b.confirm_not_frozen()?; + { + let status = client_state_of_a_on_b + .status(ctx_b.get_client_validation_context(), client_id_on_b)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = 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 114f2d16f..976456696 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 @@ -1,8 +1,9 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelCloseInit`. +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::ClientStateValidation; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; use crate::core::ics04_channel::error::ChannelError; @@ -111,7 +112,13 @@ where let client_id_on_a = conn_end_on_a.client_id(); let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + { + let status = + client_state_of_b_on_a.status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } Ok(()) } 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 0356c40a2..8e522ebe0 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 @@ -1,12 +1,12 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenAck`. -use crate::core::router::Module; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State as ChannelState}; @@ -15,6 +15,7 @@ use crate::core::ics04_channel::events::OpenAck; use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_open_ack_validate( @@ -114,7 +115,13 @@ where let client_id_on_a = conn_end_on_a.client_id(); let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + { + let status = client_state_of_b_on_a + .status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; let client_cons_state_path_on_a = 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 c30c4041c..b38a937c7 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 @@ -1,10 +1,11 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenConfirm`. +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; @@ -118,7 +119,13 @@ where let client_id_on_b = conn_end_on_b.client_id(); let client_state_of_a_on_b = ctx_b.client_state(client_id_on_b)?; - client_state_of_a_on_b.confirm_not_frozen()?; + { + let status = client_state_of_a_on_b + .status(ctx_b.get_client_validation_context(), client_id_on_b)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = 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 d4f7e5d92..1cd8583e8 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 @@ -1,9 +1,10 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenInit`. +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::ClientStateValidation; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; use crate::core::ics04_channel::events::OpenInit; use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; @@ -121,7 +122,14 @@ where let client_id_on_a = conn_end_on_a.client_id(); let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + + { + let status = + client_state_of_b_on_a.status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } let conn_version = conn_end_on_a.versions(); 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 44ff9bf8d..3cda49710 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 @@ -1,12 +1,12 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenTry`. -use crate::core::router::Module; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State as ChannelState}; @@ -17,6 +17,7 @@ use crate::core::ics24_host::identifier::ChannelId; use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; use crate::core::ics24_host::path::{SeqAckPath, SeqRecvPath, SeqSendPath}; +use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; pub(crate) fn chan_open_try_validate( @@ -138,7 +139,13 @@ where let client_id_on_b = conn_end_on_b.client_id(); let client_state_of_a_on_b = ctx_b.client_state(client_id_on_b)?; - client_state_of_a_on_b.confirm_not_frozen()?; + { + let status = client_state_of_a_on_b + .status(ctx_b.get_client_validation_context(), client_id_on_b)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = 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 936b81b97..d2f024612 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,8 @@ +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics03_connection::delay::verify_conn_delay_passed; @@ -185,7 +186,13 @@ where let client_id_on_b = conn_end_on_b.client_id(); let client_state_of_a_on_b = ctx_b.client_state(client_id_on_b)?; - client_state_of_a_on_b.confirm_not_frozen()?; + { + let status = client_state_of_a_on_b + .status(ctx_b.get_client_validation_context(), client_id_on_b)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = 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 009f6ee99..59cb14c6d 100644 --- a/crates/ibc/src/core/ics04_channel/handler/send_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/send_packet.rs @@ -1,3 +1,5 @@ +use crate::core::ics02_client::client_state::ClientStateValidation; +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use crate::core::events::IbcEvent; @@ -56,7 +58,13 @@ pub fn send_packet_validate( let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + { + let status = + client_state_of_b_on_a.status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } let latest_height_on_a = client_state_of_b_on_a.latest_height(); diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout.rs b/crates/ibc/src/core/ics04_channel/handler/timeout.rs index 1f61da24c..12d479744 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout.rs @@ -1,3 +1,5 @@ +use crate::core::ics02_client::client_state::ClientStateValidation; +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use prost::Message; @@ -192,7 +194,14 @@ where { let client_id_on_a = conn_end_on_a.client_id(); let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + + { + let status = client_state_of_b_on_a + .status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; // check that timeout height or timeout timestamp has passed on the other end 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 5630a1f2a..9215d588a 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 @@ -1,8 +1,9 @@ +use crate::core::ics02_client::error::ClientError; use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use prost::Message; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics03_connection::delay::verify_conn_delay_passed; use crate::core::ics04_channel::channel::State; @@ -70,7 +71,13 @@ where let client_id_on_a = conn_end_on_a.client_id(); let client_state_of_b_on_a = ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a.confirm_not_frozen()?; + { + let status = client_state_of_b_on_a + .status(ctx_a.get_client_validation_context(), client_id_on_a)?; + if !status.is_active() { + return Err(ClientError::ClientNotActive { status }.into()); + } + } client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; let client_cons_state_path_on_a = diff --git a/crates/ibc/src/hosts/tendermint/validate_self_client.rs b/crates/ibc/src/hosts/tendermint/validate_self_client.rs index ce8a6c3f6..5ac4a1cf5 100644 --- a/crates/ibc/src/hosts/tendermint/validate_self_client.rs +++ b/crates/ibc/src/hosts/tendermint/validate_self_client.rs @@ -30,7 +30,12 @@ pub trait ValidateSelfClientContext { tm_client_state.validate().map_err(ClientError::from)?; - tm_client_state.confirm_not_frozen()?; + if tm_client_state.is_frozen() { + return Err(ClientError::ClientFrozen { + description: String::new(), + } + .into()); + } let self_chain_id = self.chain_id(); if self_chain_id != &tm_client_state.chain_id { diff --git a/crates/ibc/src/mock/client_state.rs b/crates/ibc/src/mock/client_state.rs index 24b2bd688..9f31e8d26 100644 --- a/crates/ibc/src/mock/client_state.rs +++ b/crates/ibc/src/mock/client_state.rs @@ -1,3 +1,6 @@ +use crate::core::ics02_client::client_state::Status; +use crate::core::timestamp::Timestamp; +use crate::core::ContextError; use crate::prelude::*; use core::str::FromStr; @@ -66,6 +69,14 @@ impl MockClientState { ..self } } + + pub fn is_frozen(&self) -> bool { + self.frozen_height.is_some() + } + + fn expired(&self, _elapsed: Duration) -> bool { + false + } } impl Protobuf for MockClientState {} @@ -125,6 +136,23 @@ impl From for Any { } } +pub trait MockClientContext { + type ConversionError: ToString; + type AnyConsensusState: TryInto; + + /// Retrieve the consensus state for the given client ID at the specified + /// height. + /// + /// Returns an error if no such state exists. + fn consensus_state( + &self, + client_cons_state_path: &ClientConsensusStatePath, + ) -> Result; + + /// Returns the current timestamp of the local chain. + fn host_timestamp(&self) -> Result; +} + impl ClientStateCommon for MockClientState { fn verify_consensus_state(&self, consensus_state: Any) -> Result<(), ClientError> { let _mock_consensus_state = MockConsensusState::try_from(consensus_state)?; @@ -150,19 +178,6 @@ impl ClientStateCommon for MockClientState { Ok(()) } - fn confirm_not_frozen(&self) -> Result<(), ClientError> { - if let Some(frozen_height) = self.frozen_height { - return Err(ClientError::ClientFrozen { - description: format!("The client is frozen at height {frozen_height}"), - }); - } - Ok(()) - } - - fn expired(&self, _elapsed: Duration) -> bool { - false - } - fn verify_upgrade_client( &self, upgraded_client_state: Any, @@ -204,7 +219,13 @@ impl ClientStateCommon for MockClientState { } } -impl ClientStateValidation for MockClientState { +impl ClientStateValidation for MockClientState +where + ClientValidationContext: MockClientContext, + ClientValidationContext::AnyConsensusState: TryInto, + ClientError: + From<>::Error>, +{ fn verify_client_message( &self, _ctx: &ClientValidationContext, @@ -252,6 +273,42 @@ impl ClientStateValidation for } } } + + fn status( + &self, + ctx: &ClientValidationContext, + client_id: &ClientId, + ) -> Result { + if self.is_frozen() { + return Ok(Status::Frozen); + } + + let latest_consensus_state: MockConsensusState = { + let any_latest_consensus_state = match ctx.consensus_state( + &ClientConsensusStatePath::new(client_id, &self.latest_height()), + ) { + Ok(cs) => cs, + // if the client state does not have an associated consensus state for its latest height + // then it must be expired + Err(_) => return Ok(Status::Expired), + }; + + any_latest_consensus_state.try_into()? + }; + + let now = ctx.host_timestamp()?; + let elapsed_since_latest_consensus_state = now + .duration_since(&latest_consensus_state.timestamp()) + .ok_or(ClientError::Other { + description: format!("latest consensus state is in the future. now: {now}, latest consensus state: {}", latest_consensus_state.timestamp()), + })?; + + if self.expired(elapsed_since_latest_consensus_state) { + return Ok(Status::Expired); + } + + Ok(Status::Active) + } } impl ClientStateExecution for MockClientState diff --git a/crates/ibc/src/mock/context.rs b/crates/ibc/src/mock/context.rs index 18e996eaf..ff7de4c93 100644 --- a/crates/ibc/src/mock/context.rs +++ b/crates/ibc/src/mock/context.rs @@ -30,7 +30,6 @@ use crate::clients::ics07_tendermint::consensus_state::TENDERMINT_CONSENSUS_STAT use crate::core::dispatch; use crate::core::events::IbcEvent; use crate::core::ics02_client::client_state::ClientState; -use crate::core::ics02_client::client_state::ClientStateCommon; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; @@ -840,7 +839,12 @@ impl ValidationContext for MockContext { }) .map_err(ContextError::ConnectionError)?; - mock_client_state.confirm_not_frozen()?; + if mock_client_state.is_frozen() { + return Err(ClientError::ClientFrozen { + description: String::new(), + } + .into()); + } let self_chain_id = &self.host_chain_id; let self_revision_number = self_chain_id.revision_number(); diff --git a/crates/ibc/src/mock/context/clients.rs b/crates/ibc/src/mock/context/clients.rs index f9b13fd25..448195902 100644 --- a/crates/ibc/src/mock/context/clients.rs +++ b/crates/ibc/src/mock/context/clients.rs @@ -1,5 +1,6 @@ //! Client context implementations for `MockContext` +use crate::mock::client_state::MockClientContext; use crate::prelude::*; use super::{AnyClientState, AnyConsensusState, MockClientRecord, MockContext}; @@ -15,6 +16,22 @@ use crate::core::ContextError; use crate::core::ValidationContext; use crate::Height; +impl MockClientContext for MockContext { + type ConversionError = &'static str; + type AnyConsensusState = AnyConsensusState; + + fn consensus_state( + &self, + client_cons_state_path: &ClientConsensusStatePath, + ) -> Result { + ValidationContext::consensus_state(self, client_cons_state_path) + } + + fn host_timestamp(&self) -> Result { + ValidationContext::host_timestamp(self) + } +} + impl TmCommonContext for MockContext { type ConversionError = &'static str; type AnyConsensusState = AnyConsensusState; From b44270399697866b44e9124ca1c2dbea42120b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Fri, 4 Aug 2023 12:25:56 -0400 Subject: [PATCH 014/182] Release v0.44.0 (#818) * changelog * update ibc-derive * bump ibc-rs --- .../536-clientstate-status.md | 0 .../786-decouple-token-sendpacket.md | 0 .../breaking-changes/788-decouple-router.md | 0 .../802-simplify-module-lookup.md | 0 .changelog/v0.44.0/summary.md | 3 +++ CHANGELOG.md | 19 +++++++++++++++++++ crates/ibc-derive/Cargo.toml | 2 +- crates/ibc/Cargo.toml | 4 ++-- 8 files changed, 25 insertions(+), 3 deletions(-) rename .changelog/{unreleased => v0.44.0}/breaking-changes/536-clientstate-status.md (100%) rename .changelog/{unreleased => v0.44.0}/breaking-changes/786-decouple-token-sendpacket.md (100%) rename .changelog/{unreleased => v0.44.0}/breaking-changes/788-decouple-router.md (100%) rename .changelog/{unreleased => v0.44.0}/breaking-changes/802-simplify-module-lookup.md (100%) create mode 100644 .changelog/v0.44.0/summary.md diff --git a/.changelog/unreleased/breaking-changes/536-clientstate-status.md b/.changelog/v0.44.0/breaking-changes/536-clientstate-status.md similarity index 100% rename from .changelog/unreleased/breaking-changes/536-clientstate-status.md rename to .changelog/v0.44.0/breaking-changes/536-clientstate-status.md diff --git a/.changelog/unreleased/breaking-changes/786-decouple-token-sendpacket.md b/.changelog/v0.44.0/breaking-changes/786-decouple-token-sendpacket.md similarity index 100% rename from .changelog/unreleased/breaking-changes/786-decouple-token-sendpacket.md rename to .changelog/v0.44.0/breaking-changes/786-decouple-token-sendpacket.md diff --git a/.changelog/unreleased/breaking-changes/788-decouple-router.md b/.changelog/v0.44.0/breaking-changes/788-decouple-router.md similarity index 100% rename from .changelog/unreleased/breaking-changes/788-decouple-router.md rename to .changelog/v0.44.0/breaking-changes/788-decouple-router.md diff --git a/.changelog/unreleased/breaking-changes/802-simplify-module-lookup.md b/.changelog/v0.44.0/breaking-changes/802-simplify-module-lookup.md similarity index 100% rename from .changelog/unreleased/breaking-changes/802-simplify-module-lookup.md rename to .changelog/v0.44.0/breaking-changes/802-simplify-module-lookup.md diff --git a/.changelog/v0.44.0/summary.md b/.changelog/v0.44.0/summary.md new file mode 100644 index 000000000..87b8f04ba --- /dev/null +++ b/.changelog/v0.44.0/summary.md @@ -0,0 +1,3 @@ +The goal with this release was to replace `ClientState::{confirm_not_frozen, expired}()` with `ClientState::status()` ([#536](https://github.com/cosmos/ibc-rs/issues/536)). Updating basecoin-rs with the new changes exposed the shortcomings of having `SendPacket*Context` be supertraits of `TokenTransfer*Context`, which in turned exposed the shortcomings of having `Router` be a supertrait of `ValidationContext`. Hence, we decoupled everything! + +There are consensus-breaking changes. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7297db6fd..f12eb3418 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # CHANGELOG +## v0.44.0 + +*August 4, 2023* + +The goal with this release was to replace `ClientState::{confirm_not_frozen, expired}()` with `ClientState::status()` ([#536](https://github.com/cosmos/ibc-rs/issues/536)). Updating basecoin-rs with the new changes exposed the shortcomings of having `SendPacket*Context` be supertraits of `TokenTransfer*Context`, which in turned exposed the shortcomings of having `Router` be a supertrait of `ValidationContext`. Hence, we decoupled everything! + +There are consensus-breaking changes. + +### BREAKING CHANGES + +- [ibc-derive] Replace `ClientState::{confirm_not_frozen, expired}()` with `ClientState::status()` + ([#536](https://github.com/cosmos/ibc-rs/issues/536)) +- Decouple `TokenTransfer{Validation,Execution}` from `SendPacket{Validation,Execution}` + ([#786](https://github.com/cosmos/ibc-rs/issues/786)) +- Decouple `Router` from `ValidationContext` + ([#788](https://github.com/cosmos/ibc-rs/pull/788)) +- Simplify Module lookup in the `Router` trait + ([#802](https://github.com/cosmos/ibc-rs/issues/802)) + ## v0.43.1 *July 31, 2023* diff --git a/crates/ibc-derive/Cargo.toml b/crates/ibc-derive/Cargo.toml index 5463fc8bb..e89af7e67 100644 --- a/crates/ibc-derive/Cargo.toml +++ b/crates/ibc-derive/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ibc-derive" -version = "0.2.0" +version = "0.3.0" license = "Apache-2.0" readme = "README.md" description = "Macros implementation of #[derive(ClientState)] and #[derive(ConsensusState)]" diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index e47745faa..142d14b6a 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ibc" -version = "0.43.1" +version = "0.44.0" edition = "2021" license = "Apache-2.0" readme = "README.md" @@ -75,7 +75,7 @@ scale-info = { version = "2.1.2", default-features = false, features = ["derive" borsh = {version = "0.9.0", default-features = false, optional = true } parking_lot = { version = "0.12.1", default-features = false, optional = true } -ibc-derive = { version ="0.2.0", path = "../ibc-derive" } +ibc-derive = { version ="0.3.0", path = "../ibc-derive" } schemars = { version = "0.8.12", optional = true } From 5c48d1552ed66ca50ae751e5fb0d426146bb28aa Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Tue, 8 Aug 2023 09:08:51 -0700 Subject: [PATCH 015/182] fix: utilize encoded bytes from `Any` for header of `UpdateClient` event (#822) * fix: utilize encoded bytes from Any for header of UpdateClient event * nit: use header_bytes * nit: edit unclog * nit: add a docstring for UpdateClient event * imp: use encode_to_vec --- ...21-fix-header-decoding-from-update-client-event.md | 3 +++ crates/ibc/src/core/ics02_client/events.rs | 11 +++++++++-- .../src/core/ics02_client/handler/update_client.rs | 5 +++-- 3 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 .changelog/unreleased/bug-fixes/821-fix-header-decoding-from-update-client-event.md diff --git a/.changelog/unreleased/bug-fixes/821-fix-header-decoding-from-update-client-event.md b/.changelog/unreleased/bug-fixes/821-fix-header-decoding-from-update-client-event.md new file mode 100644 index 000000000..e54aa1ea9 --- /dev/null +++ b/.changelog/unreleased/bug-fixes/821-fix-header-decoding-from-update-client-event.md @@ -0,0 +1,3 @@ +- Utilize encoded bytes from `Any` for the `header` field of `UpdateClient` + event + ([#821](https://github.com/cosmos/ibc-rs/issues/821)) diff --git a/crates/ibc/src/core/ics02_client/events.rs b/crates/ibc/src/core/ics02_client/events.rs index 8d9f87b65..01e4c586a 100644 --- a/crates/ibc/src/core/ics02_client/events.rs +++ b/crates/ibc/src/core/ics02_client/events.rs @@ -146,6 +146,8 @@ impl From for abci::EventAttribute { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, From, PartialEq, Eq)] struct HeaderAttribute { + /// NOTE: The header is encoded as bytes of the + /// [`Any`](ibc_proto::google::protobuf::Any) type. header: Vec, } @@ -246,6 +248,10 @@ pub struct UpdateClient { } impl UpdateClient { + /// Constructs a new UpdateClient event. + /// + /// NOTE: the `header` is the encoded bytes of the + /// [`Any`](ibc_proto::google::protobuf::Any) type. pub fn new( client_id: ClientId, client_type: ClientType, @@ -419,6 +425,7 @@ mod tests { use crate::core::timestamp::Timestamp; use crate::mock::header::MockHeader; use ibc_proto::google::protobuf::Any; + use prost::Message; use std::str::FromStr; use tendermint::abci::Event as AbciEvent; @@ -452,7 +459,7 @@ mod tests { "07-tendermint", "0-5", "0-5,0-7", - "0a021005", + "0a102f6962632e6d6f636b2e48656164657212040a021005", ]; let tests: Vec = vec![ @@ -470,7 +477,7 @@ mod tests { client_type.clone(), consensus_height, consensus_heights, - header.value, + header.encode_to_vec(), ) .into(), expected_keys: expected_keys.clone(), 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 594a6154b..cad4bde1d 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -1,6 +1,7 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgUpdateAnyClient`. use crate::prelude::*; +use prost::Message; use crate::core::context::ContextError; use crate::core::events::{IbcEvent, MessageEvent}; @@ -119,7 +120,7 @@ where client_state.client_type(), *consensus_height, consensus_heights, - header.value, + header.encode_to_vec(), )) }; ctx.emit_ibc_event(IbcEvent::Message(MessageEvent::Client)); @@ -504,7 +505,7 @@ mod tests { assert_eq!(update_client_event.client_type(), &mock_client_type()); assert_eq!(update_client_event.consensus_height(), &height); assert_eq!(update_client_event.consensus_heights(), &vec![height]); - assert_eq!(update_client_event.header(), &header.value); + assert_eq!(update_client_event.header(), &header.encode_to_vec()); } fn ensure_misbehaviour(ctx: &MockContext, client_id: &ClientId, client_type: &ClientType) { From 580fc1dc6d25bb850cb03f7661535244fd7a56bf Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Thu, 10 Aug 2023 07:28:09 -0700 Subject: [PATCH 016/182] fix: remove traces of deprecated `mocks-no-std` feature (#825) * fix: remove mocks-no-std leftovers * misc: add unclog * nit: typo --- .../bug-fixes/819-remove-mocks-no-std-traces.md | 2 ++ crates/ibc/src/lib.rs | 2 +- crates/ibc/src/mock/mod.rs | 8 ++++---- 3 files changed, 7 insertions(+), 5 deletions(-) create mode 100644 .changelog/unreleased/bug-fixes/819-remove-mocks-no-std-traces.md diff --git a/.changelog/unreleased/bug-fixes/819-remove-mocks-no-std-traces.md b/.changelog/unreleased/bug-fixes/819-remove-mocks-no-std-traces.md new file mode 100644 index 000000000..4aadca5b1 --- /dev/null +++ b/.changelog/unreleased/bug-fixes/819-remove-mocks-no-std-traces.md @@ -0,0 +1,2 @@ +- Remove traces of deprecated `mocks-no-std` feature + ([#819](https://github.com/cosmos/ibc-rs/issues/821)) diff --git a/crates/ibc/src/lib.rs b/crates/ibc/src/lib.rs index 234af7a48..68004e69f 100644 --- a/crates/ibc/src/lib.rs +++ b/crates/ibc/src/lib.rs @@ -53,7 +53,7 @@ pub mod clients; pub mod core; pub mod hosts; -#[cfg(any(test, feature = "mocks", feature = "mocks-no-std"))] +#[cfg(any(test, feature = "mocks"))] pub mod mock; #[cfg(any(test, feature = "mocks"))] pub mod test_utils; // Context mock, the underlying host chain, and client types: for testing all handlers. diff --git a/crates/ibc/src/mock/mod.rs b/crates/ibc/src/mock/mod.rs index a2450b5a2..9492569c2 100644 --- a/crates/ibc/src/mock/mod.rs +++ b/crates/ibc/src/mock/mod.rs @@ -1,18 +1,18 @@ //! Implementation of mocks for context, host chain, and client. -#[cfg(any(test, feature = "mocks", feature = "mocks-no-std"))] +#[cfg(any(test, feature = "mocks"))] pub mod client_state; -#[cfg(any(test, feature = "mocks", feature = "mocks-no-std"))] +#[cfg(any(test, feature = "mocks"))] pub mod consensus_state; #[cfg(any(test, feature = "mocks"))] pub mod context; -#[cfg(any(test, feature = "mocks", feature = "mocks-no-std"))] +#[cfg(any(test, feature = "mocks"))] pub mod header; #[cfg(any(test, feature = "mocks"))] pub mod host; #[cfg(any(test, feature = "mocks"))] pub mod ics18_relayer; -#[cfg(any(test, feature = "mocks", feature = "mocks-no-std"))] +#[cfg(any(test, feature = "mocks"))] pub mod misbehaviour; #[cfg(any(test, feature = "mocks"))] pub mod router; From 5a794919ee8d4ee87bad99b9e745e974aac82b90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Thu, 10 Aug 2023 11:00:58 -0400 Subject: [PATCH 017/182] Release v0.44.1 (#826) * unclog release * bump version --- .../bug-fixes/819-remove-mocks-no-std-traces.md | 0 ...-header-decoding-from-update-client-event.md | 0 .changelog/v0.44.1/summary.md | 3 +++ CHANGELOG.md | 17 +++++++++++++++++ crates/ibc/Cargo.toml | 2 +- 5 files changed, 21 insertions(+), 1 deletion(-) rename .changelog/{unreleased => v0.44.1}/bug-fixes/819-remove-mocks-no-std-traces.md (100%) rename .changelog/{unreleased => v0.44.1}/bug-fixes/821-fix-header-decoding-from-update-client-event.md (100%) create mode 100644 .changelog/v0.44.1/summary.md diff --git a/.changelog/unreleased/bug-fixes/819-remove-mocks-no-std-traces.md b/.changelog/v0.44.1/bug-fixes/819-remove-mocks-no-std-traces.md similarity index 100% rename from .changelog/unreleased/bug-fixes/819-remove-mocks-no-std-traces.md rename to .changelog/v0.44.1/bug-fixes/819-remove-mocks-no-std-traces.md diff --git a/.changelog/unreleased/bug-fixes/821-fix-header-decoding-from-update-client-event.md b/.changelog/v0.44.1/bug-fixes/821-fix-header-decoding-from-update-client-event.md similarity index 100% rename from .changelog/unreleased/bug-fixes/821-fix-header-decoding-from-update-client-event.md rename to .changelog/v0.44.1/bug-fixes/821-fix-header-decoding-from-update-client-event.md diff --git a/.changelog/v0.44.1/summary.md b/.changelog/v0.44.1/summary.md new file mode 100644 index 000000000..51b5400fe --- /dev/null +++ b/.changelog/v0.44.1/summary.md @@ -0,0 +1,3 @@ +This release fixes a bug with the `UpdateClient` event where the `header` field was not properly encoded. + +There are no consensus-breaking changes. diff --git a/CHANGELOG.md b/CHANGELOG.md index f12eb3418..5be073407 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # CHANGELOG + +# v0.44.1 + +*August 4, 2023* + +This release fixes a bug with the `UpdateClient` event where the `header` field was not properly encoded. + +There are no consensus-breaking changes. + +### BUG FIXES + +- Remove traces of deprecated `mocks-no-std` feature + ([#819](https://github.com/cosmos/ibc-rs/issues/821)) +- Utilize encoded bytes from `Any` for the `header` field of `UpdateClient` + event + ([#821](https://github.com/cosmos/ibc-rs/issues/821)) + ## v0.44.0 *August 4, 2023* diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 142d14b6a..2217b395e 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ibc" -version = "0.44.0" +version = "0.44.1" edition = "2021" license = "Apache-2.0" readme = "README.md" From a9cfd86134b7630809c1639d4f0c455b0d9f8f53 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Thu, 17 Aug 2023 10:49:59 -0700 Subject: [PATCH 018/182] deps: update tendermint to v0.33.0 (#831) * deps: update tendermint to v0.33.0 * fix: clippy catches * misc: add unclog --- .../785-bump-tendermint-to-v0.33.0.md | 2 ++ ci/no-std-check/Cargo.toml | 14 +++++++------- crates/ibc/Cargo.toml | 16 ++++++++-------- crates/ibc/src/test_utils.rs | 3 +++ 4 files changed, 20 insertions(+), 15 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/785-bump-tendermint-to-v0.33.0.md diff --git a/.changelog/unreleased/breaking-changes/785-bump-tendermint-to-v0.33.0.md b/.changelog/unreleased/breaking-changes/785-bump-tendermint-to-v0.33.0.md new file mode 100644 index 000000000..09e838b68 --- /dev/null +++ b/.changelog/unreleased/breaking-changes/785-bump-tendermint-to-v0.33.0.md @@ -0,0 +1,2 @@ +- Bump tendermint-rs to v0.33.0 + ([#785](https://github.com/cosmos/ibc-rs/issues/785)) diff --git a/ci/no-std-check/Cargo.toml b/ci/no-std-check/Cargo.toml index b6911b057..51a50fb51 100644 --- a/ci/no-std-check/Cargo.toml +++ b/ci/no-std-check/Cargo.toml @@ -6,17 +6,17 @@ resolver = "2" [dependencies] ibc = { path = "../../crates/ibc", default-features = false } -ibc-proto = { version = "0.32.1", default-features = false, features = [ +ibc-proto = { version = "0.33.0", default-features = false, features = [ "parity-scale-codec", "borsh", ] } -tendermint = { version = "0.32.0", default-features = false } -tendermint-proto = { version = "0.32.0", default-features = false } -tendermint-light-client-verifier = { version = "0.32.0", default-features = false, features = ["rust-crypto"] } +tendermint = { version = "0.33.0", default-features = false } +tendermint-proto = { version = "0.33.0", default-features = false } +tendermint-light-client-verifier = { version = "0.33.0", default-features = false, features = ["rust-crypto"] } -sp-core = { version = "21.0.0", default-features = false, optional = true } -sp-io = { version = "22.0.0", default-features = false, optional = true } -sp-runtime = { version = "23.0.0", default-features = false, optional = true } +sp-core = { version = "22.0.0", default-features = false, optional = true } +sp-io = { version = "24.0.0", default-features = false, optional = true } +sp-runtime = { version = "25.0.0", default-features = false, optional = true } sp-std = { version = "7.0.0", default-features = false, optional = true } # The indirect dependency `syn` 2.0.4 has a bug that causes diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 2217b395e..48b589378 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -50,9 +50,9 @@ mocks = ["tendermint-testgen", "tendermint/clock", "parking_lot"] [dependencies] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. -ibc-proto = { version = "0.32.1", default-features = false } +ibc-proto = { version = "0.33.0", default-features = false } ics23 = { version = "0.10.1", default-features = false, features = ["host-functions"] } -time = { version = ">=0.3.0, <0.3.25", default-features = false } +time = { version = ">=0.3.0, <0.3.26", default-features = false } serde_derive = { version = "1.0.104", default-features = false, optional = true } serde = { version = "1.0", default-features = false, optional = true } serde_json = { version = "1", default-features = false, optional = true } @@ -80,20 +80,20 @@ ibc-derive = { version ="0.3.0", path = "../ibc-derive" } schemars = { version = "0.8.12", optional = true } [dependencies.tendermint] -version = "0.32" +version = "0.33" default-features = false [dependencies.tendermint-proto] -version = "0.32" +version = "0.33" default-features = false [dependencies.tendermint-light-client-verifier] -version = "0.32" +version = "0.33" default-features = false features = ["rust-crypto"] [dependencies.tendermint-testgen] -version = "0.32" +version = "0.33" optional = true default-features = false @@ -102,6 +102,6 @@ env_logger = "0.10.0" rstest = "0.18.1" tracing-subscriber = { version = "0.3.14", features = ["fmt", "env-filter", "json"]} test-log = { version = "0.2.10", features = ["trace"] } -tendermint-rpc = { version = "0.32", features = ["http-client", "websocket-client"] } -tendermint-testgen = { version = "0.32" } # Needed for generating (synthetic) light blocks. +tendermint-rpc = { version = "0.33", features = ["http-client", "websocket-client"] } +tendermint-testgen = { version = "0.33" } # Needed for generating (synthetic) light blocks. parking_lot = { version = "0.12.1" } diff --git a/crates/ibc/src/test_utils.rs b/crates/ibc/src/test_utils.rs index 6cc73f801..9d814e3e6 100644 --- a/crates/ibc/src/test_utils.rs +++ b/crates/ibc/src/test_utils.rs @@ -33,6 +33,9 @@ pub fn default_consensus_params() -> consensus::Params { pub_key_types: vec![Algorithm::Ed25519], }, version: Some(consensus::params::VersionParams::default()), + abci: consensus::params::AbciParams { + vote_extensions_enable_height: None, + }, } } From d8d4973089baf802cd61e22b629b687b8cd0ffc4 Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Wed, 23 Aug 2023 07:13:37 -0700 Subject: [PATCH 019/182] fix: restore `no_std` support for `serde` feature (#790) * fix: restore no_std support for serde feature * deps: bump ibc-proto-rs to v0.34.0 * fix: reflect changes b/c of ibc-proto-rs * imp: comply naming + use better domain type for host_consensus_state * fix: apply host_cons_state_proof changes for conn_open_ack * fix: use domain TmEvent instead of proto for upgrade client proposal handler * misc: add a unclog for ibc-proto-rs upgrade --- .../790-bump-ibc-proto-rs-to-v0.34.0.md | 2 + .../bug-fixes/741-restore-no-std-support.md | 2 + ...ent-for-upgrade-client-proposal-handler.md | 3 + ci/no-std-check/Cargo.lock | 732 ++++-------------- ci/no-std-check/Cargo.toml | 5 +- crates/ibc/Cargo.toml | 2 +- .../clients/ics07_tendermint/misbehaviour.rs | 3 +- crates/ibc/src/core/handler.rs | 8 +- crates/ibc/src/core/ics02_client/error.rs | 4 +- .../ics02_client/handler/update_client.rs | 14 +- crates/ibc/src/core/ics02_client/msgs.rs | 2 +- .../core/ics02_client/msgs/update_client.rs | 12 +- .../ics03_connection/msgs/conn_open_ack.rs | 17 + .../ics03_connection/msgs/conn_open_try.rs | 17 + .../tendermint/upgrade_proposal/handler.rs | 11 +- crates/ibc/src/mock/header.rs | 2 +- crates/ibc/src/mock/ics18_relayer/context.rs | 2 +- 17 files changed, 218 insertions(+), 620 deletions(-) create mode 100644 .changelog/unreleased/breaking-changes/790-bump-ibc-proto-rs-to-v0.34.0.md create mode 100644 .changelog/unreleased/bug-fixes/741-restore-no-std-support.md create mode 100644 .changelog/unreleased/improvements/838-switch-to-tm-event-for-upgrade-client-proposal-handler.md diff --git a/.changelog/unreleased/breaking-changes/790-bump-ibc-proto-rs-to-v0.34.0.md b/.changelog/unreleased/breaking-changes/790-bump-ibc-proto-rs-to-v0.34.0.md new file mode 100644 index 000000000..5f41eb65a --- /dev/null +++ b/.changelog/unreleased/breaking-changes/790-bump-ibc-proto-rs-to-v0.34.0.md @@ -0,0 +1,2 @@ +- Bump ibc-proto-rs to v0.34.0 + ([#790](https://github.com/cosmos/ibc-rs/issues/790)) diff --git a/.changelog/unreleased/bug-fixes/741-restore-no-std-support.md b/.changelog/unreleased/bug-fixes/741-restore-no-std-support.md new file mode 100644 index 000000000..41cfaa7ff --- /dev/null +++ b/.changelog/unreleased/bug-fixes/741-restore-no-std-support.md @@ -0,0 +1,2 @@ +- Fix compilation error of v0.41.0 by restoring no_std support for serde + feature ([#741](https://github.com/cosmos/ibc-rs/issues/741)) diff --git a/.changelog/unreleased/improvements/838-switch-to-tm-event-for-upgrade-client-proposal-handler.md b/.changelog/unreleased/improvements/838-switch-to-tm-event-for-upgrade-client-proposal-handler.md new file mode 100644 index 000000000..69247e866 --- /dev/null +++ b/.changelog/unreleased/improvements/838-switch-to-tm-event-for-upgrade-client-proposal-handler.md @@ -0,0 +1,3 @@ +- Switch to domain Tendermint event type instead of proto for the + `upgrade_client_proposal_handler` return + ([#838](https://github.com/cosmos/ibc-rs/issues/838)) diff --git a/ci/no-std-check/Cargo.lock b/ci/no-std-check/Cargo.lock index 609ee9079..4915d7e39 100644 --- a/ci/no-std-check/Cargo.lock +++ b/ci/no-std-check/Cargo.lock @@ -12,22 +12,13 @@ dependencies = [ "regex", ] -[[package]] -name = "addr2line" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" -dependencies = [ - "gimli 0.26.2", -] - [[package]] name = "addr2line" version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" dependencies = [ - "gimli 0.27.2", + "gimli", ] [[package]] @@ -100,9 +91,9 @@ checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" [[package]] name = "array-bytes" -version = "4.2.0" +version = "6.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f52f63c5c1316a16a4b35eaac8b76a98248961a533f061684cb2a7cb0eafb6c6" +checksum = "d9b1c5a481ec30a5abd8dfbd94ab5cf1bb4e9a66be7f1b3b322f2f1170c200fd" [[package]] name = "arrayref" @@ -134,12 +125,12 @@ version = "0.3.67" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" dependencies = [ - "addr2line 0.19.0", + "addr2line", "cc", "cfg-if", "libc", "miniz_oxide", - "object 0.30.4", + "object", "rustc-demangle", ] @@ -403,15 +394,6 @@ dependencies = [ "libc", ] -[[package]] -name = "cranelift-entity" -version = "0.93.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f42ea692c7b450ad18b8c9889661505d51c09ec4380cf1c2d278dbb2da22cae1" -dependencies = [ - "serde", -] - [[package]] name = "cranelift-entity" version = "0.95.1" @@ -601,12 +583,6 @@ dependencies = [ "syn 2.0.27", ] -[[package]] -name = "downcast-rs" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" - [[package]] name = "dyn-clonable" version = "0.9.0" @@ -910,16 +886,6 @@ dependencies = [ "wasi 0.11.0+wasi-snapshot-preview1", ] -[[package]] -name = "gimli" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" -dependencies = [ - "fallible-iterator", - "stable_deref_trait", -] - [[package]] name = "gimli" version = "0.27.2" @@ -1059,7 +1025,7 @@ dependencies = [ [[package]] name = "ibc" -version = "0.42.0" +version = "0.44.1" dependencies = [ "bytes", "derive_more", @@ -1071,6 +1037,9 @@ dependencies = [ "primitive-types", "prost", "safe-regex", + "serde", + "serde_derive", + "serde_json", "sha2 0.10.6", "subtle-encoding", "tendermint", @@ -1083,7 +1052,7 @@ dependencies = [ [[package]] name = "ibc-derive" -version = "0.1.0" +version = "0.3.0" dependencies = [ "darling", "proc-macro2", @@ -1093,9 +1062,9 @@ dependencies = [ [[package]] name = "ibc-proto" -version = "0.32.1" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11c352715b36685c2543556a77091fb16af5d26257d5ce9c28e6756c1ccd71aa" +checksum = "f6e8625e1aa28e4da4a33505c6469747a9201f14ccd9012e2481313dfbbf9e2f" dependencies = [ "base64 0.21.2", "borsh", @@ -1112,15 +1081,17 @@ dependencies = [ [[package]] name = "ics23" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af9e8f569c5cc88e08b8d076dc207e0748aa1f52d4b84910ec919c8f2bed6ea7" +checksum = "442d4bab37956e76f739c864f246c825d87c0bb7f9afa65660c57833c91bf6d4" dependencies = [ "anyhow", "bytes", "hex", + "informalsystems-pbjson", "prost", "ripemd", + "serde", "sha2 0.10.6", "sha3", ] @@ -1181,6 +1152,16 @@ dependencies = [ "serde", ] +[[package]] +name = "informalsystems-pbjson" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eecd90f87bea412eac91c6ef94f6b1e390128290898cbe14f2b926787ae1fb" +dependencies = [ + "base64 0.13.1", + "serde", +] + [[package]] name = "integer-sqrt" version = "0.1.5" @@ -1246,12 +1227,6 @@ version = "0.2.146" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" -[[package]] -name = "libm" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" - [[package]] name = "libsecp256k1" version = "0.7.1" @@ -1361,15 +1336,6 @@ dependencies = [ "rustix 0.37.20", ] -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - [[package]] name = "memoffset" version = "0.8.0" @@ -1388,12 +1354,6 @@ dependencies = [ "hash-db", ] -[[package]] -name = "memory_units" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" - [[package]] name = "merlin" version = "2.0.1" @@ -1421,7 +1381,7 @@ version = "0.1.0" dependencies = [ "ibc", "ibc-proto", - "sp-core 21.0.0", + "sp-core", "sp-io", "sp-runtime", "sp-std 7.0.0", @@ -1437,17 +1397,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - [[package]] name = "num-derive" version = "0.3.3" @@ -1469,28 +1418,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-rational" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" -dependencies = [ - "autocfg", - "num-bigint", - "num-integer", - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.15" @@ -1510,18 +1437,6 @@ dependencies = [ "libc", ] -[[package]] -name = "object" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" -dependencies = [ - "crc32fast", - "hashbrown 0.12.3", - "indexmap", - "memchr", -] - [[package]] name = "object" version = "0.30.4" @@ -1554,9 +1469,9 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "parity-scale-codec" -version = "3.5.0" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ddb756ca205bd108aee3c62c6d3c994e1df84a59b9d6d4a5ea42ee1fd5a9a28" +checksum = "dd8e946cc0cc711189c0b0249fb8b599cbeeab9784d83c415719368bb8d4ac64" dependencies = [ "arrayvec 0.7.2", "bitvec", @@ -1569,9 +1484,9 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "3.1.4" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b26a931f824dd4eca30b3e43bb4f31cd5f0d3a403c5f5ff27106b805bfde7b" +checksum = "2a296c3079b5fefbc499e1de58dc26c09b1b9a5952d26694ee89f04a43ebbb3e" dependencies = [ "proc-macro-crate 1.3.1", "proc-macro2", @@ -1579,12 +1494,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "parity-wasm" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1ad0aff30c1da14b1254fcb2af73e1fa9a28670e584a626f53a369d0e157304" - [[package]] name = "parking_lot" version = "0.12.1" @@ -1700,9 +1609,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.63" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" +checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" dependencies = [ "unicode-ident", ] @@ -1750,9 +1659,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.28" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" +checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" dependencies = [ "proc-macro2", ] @@ -2099,9 +2008,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.164" +version = "1.0.179" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" +checksum = "0a5bf42b8d227d4abf38a1ddb08602e229108a517cd4e5bb28f9c7eaafdce5c0" dependencies = [ "serde_derive", ] @@ -2117,9 +2026,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.164" +version = "1.0.179" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" +checksum = "741e124f5485c7e60c03b043f79f320bff3527f4bbf12cf3831750dc46a0ec2c" dependencies = [ "proc-macro2", "quote", @@ -2232,82 +2141,38 @@ checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" [[package]] name = "sp-application-crypto" -version = "22.0.0" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf23435a4bbd6eeec2bbbc346719ba4f3200e0ddb5f9e9f06c1724db03a8410" +checksum = "6b49d62089ef6fdd52a6f90f670d533ccb365235258cf517dbd5bd571febcfbd" dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 20.0.0", + "sp-core", "sp-io", - "sp-std 7.0.0", + "sp-std 9.0.0", ] [[package]] name = "sp-arithmetic" -version = "15.0.0" +version = "17.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c3d3507a803e8bc332fa290ed3015a7b51d4436ce2b836744642fc412040456" +checksum = "0241327405688cac3fcc29114fd35f99224e321daa37e19920e50e4b2fdd0645" dependencies = [ "integer-sqrt", "num-traits", "parity-scale-codec", "scale-info", "serde", - "sp-std 7.0.0", + "sp-std 9.0.0", "static_assertions", ] [[package]] name = "sp-core" -version = "20.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7789372146f8ad40d0b40fad0596cb1db5771187a258eabe19b06f00767fcbd6" -dependencies = [ - "array-bytes", - "bitflags", - "blake2", - "bounded-collections", - "bs58", - "dyn-clonable", - "ed25519-zebra", - "futures", - "hash-db", - "hash256-std-hasher", - "impl-serde", - "lazy_static", - "libsecp256k1", - "log", - "merlin", - "parity-scale-codec", - "parking_lot", - "primitive-types", - "rand 0.8.5", - "regex", - "scale-info", - "schnorrkel", - "secp256k1", - "secrecy", - "serde", - "sp-core-hashing 8.0.0", - "sp-debug-derive 7.0.0", - "sp-externalities 0.18.0", - "sp-runtime-interface 16.0.0", - "sp-std 7.0.0", - "sp-storage 12.0.0", - "ss58-registry", - "substrate-bip39", - "thiserror", - "tiny-bip39", - "zeroize", -] - -[[package]] -name = "sp-core" -version = "21.0.0" +version = "22.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f18d9e2f67d8661f9729f35347069ac29d92758b59135176799db966947a7336" +checksum = "d0de478e02efd547693b33ad02515e09933d5b69b7f3036fa890b92e50fd9dfc" dependencies = [ "array-bytes", "bitflags", @@ -2335,65 +2200,39 @@ dependencies = [ "secp256k1", "secrecy", "serde", - "sp-core-hashing 9.0.0", - "sp-debug-derive 8.0.0", - "sp-externalities 0.19.0", - "sp-runtime-interface 17.0.0", - "sp-std 8.0.0", - "sp-storage 13.0.0", + "sp-core-hashing", + "sp-debug-derive", + "sp-externalities", + "sp-runtime-interface", + "sp-std 9.0.0", + "sp-storage", "ss58-registry", "substrate-bip39", "thiserror", "tiny-bip39", + "tracing", "zeroize", ] [[package]] name = "sp-core-hashing" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27449abdfbe41b473e625bce8113745e81d65777dd1d5a8462cf24137930dad8" -dependencies = [ - "blake2b_simd", - "byteorder", - "digest 0.10.7", - "sha2 0.10.6", - "sha3", - "sp-std 7.0.0", - "twox-hash", -] - -[[package]] -name = "sp-core-hashing" -version = "9.0.0" +version = "10.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee599a8399448e65197f9a6cee338ad192e9023e35e31f22382964c3c174c68" +checksum = "e360755a2706a76886d58776665cad0db793dece3c7d390455b28e8a1efd6285" dependencies = [ "blake2b_simd", "byteorder", "digest 0.10.7", "sha2 0.10.6", "sha3", - "sp-std 8.0.0", "twox-hash", ] [[package]] name = "sp-debug-derive" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62211eed9ef9dac4b9d837c56ccc9f8ee4fc49d9d9b7e6b9daf098fe173389ab" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "sp-debug-derive" -version = "8.0.0" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f531814d2f16995144c74428830ccf7d94ff4a7749632b83ad8199b181140c" +checksum = "f12dae7cf6c1e825d13ffd4ce16bd9309db7c539929d0302b4443ed451a9f4e5" dependencies = [ "proc-macro2", "quote", @@ -2402,50 +2241,37 @@ dependencies = [ [[package]] name = "sp-externalities" -version = "0.18.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae0f275760689aaefe967943331d458cd99f5169d18364365d4cb584b246d1c" +checksum = "3313e2c5f2523b06062e541dff9961bde88ad5a28861621dc7b7b47a32bb0f7c" dependencies = [ "environmental", "parity-scale-codec", - "sp-std 7.0.0", - "sp-storage 12.0.0", -] - -[[package]] -name = "sp-externalities" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0f71c671e01a8ca60da925d43a1b351b69626e268b8837f8371e320cf1dd100" -dependencies = [ - "environmental", - "parity-scale-codec", - "sp-std 8.0.0", - "sp-storage 13.0.0", + "sp-std 9.0.0", + "sp-storage", ] [[package]] name = "sp-io" -version = "22.0.0" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd3431c245992fe51b8256c838fc2e981f8d3b0afc1d1377ca7dbe0a3287a764" +checksum = "ff6194309bfe055d93177c6c9d2ed4c7b66040617cf3003a15e509c432cf3b62" dependencies = [ "bytes", "ed25519 1.5.3", "ed25519-dalek", - "futures", "libsecp256k1", "log", "parity-scale-codec", "rustversion", "secp256k1", - "sp-core 20.0.0", - "sp-externalities 0.18.0", + "sp-core", + "sp-externalities", "sp-keystore", - "sp-runtime-interface 16.0.0", + "sp-runtime-interface", "sp-state-machine", - "sp-std 7.0.0", - "sp-tracing 9.0.0", + "sp-std 9.0.0", + "sp-tracing", "sp-trie", "tracing", "tracing-core", @@ -2453,25 +2279,22 @@ dependencies = [ [[package]] name = "sp-keystore" -version = "0.26.0" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "452d079f592c97369c9ca8a5083b25f146751c6b5af10cbcacc2b24dc53fd72a" +checksum = "6eda1d2572a15340927a9f7db75ffe74366b645eaf9212015b4a96ad8e9d4c46" dependencies = [ - "futures", - "merlin", "parity-scale-codec", "parking_lot", - "schnorrkel", - "sp-core 20.0.0", - "sp-externalities 0.18.0", + "sp-core", + "sp-externalities", "thiserror", ] [[package]] name = "sp-panic-handler" -version = "7.0.0" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75986cc917d897e0f6d0c848088064df4c74ccbb8f1c1848700b725f5ca7fe04" +checksum = "57c67eb0a0d11d3017ef43c975068ba76c7b0e83aca1ee3d68ba0ce270ecebe7" dependencies = [ "backtrace", "lazy_static", @@ -2480,9 +2303,9 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "23.0.0" +version = "25.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6220216caa67e3d931c693b06a3590dfcaa255f19bb3c3e3150f1672b8bc53f6" +checksum = "3d056e4cccf36a45be5d471b47c09e8be91b825f1d8352f20aa01f9f693176e7" dependencies = [ "either", "hash256-std-hasher", @@ -2495,68 +2318,36 @@ dependencies = [ "serde", "sp-application-crypto", "sp-arithmetic", - "sp-core 20.0.0", + "sp-core", "sp-io", - "sp-std 7.0.0", + "sp-std 9.0.0", "sp-weights", ] [[package]] name = "sp-runtime-interface" -version = "16.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca5d0cd80200bf85b8b064238b2508b69b6146b13adf36066ec5d924825af737" -dependencies = [ - "bytes", - "impl-trait-for-tuples", - "parity-scale-codec", - "primitive-types", - "sp-externalities 0.18.0", - "sp-runtime-interface-proc-macro 10.0.0", - "sp-std 7.0.0", - "sp-storage 12.0.0", - "sp-tracing 9.0.0", - "sp-wasm-interface 13.0.0", - "static_assertions", -] - -[[package]] -name = "sp-runtime-interface" -version = "17.0.0" +version = "18.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e676128182f90015e916f806cba635c8141e341e7abbc45d25525472e1bbce8" +checksum = "bf9781c72848efe6750116eb96edaeb105ee7e0bd7f38a4e46371bf810b3db7b" dependencies = [ "bytes", "impl-trait-for-tuples", "parity-scale-codec", "primitive-types", - "sp-externalities 0.19.0", - "sp-runtime-interface-proc-macro 11.0.0", - "sp-std 8.0.0", - "sp-storage 13.0.0", - "sp-tracing 10.0.0", - "sp-wasm-interface 14.0.0", + "sp-externalities", + "sp-runtime-interface-proc-macro", + "sp-std 9.0.0", + "sp-storage", + "sp-tracing", + "sp-wasm-interface", "static_assertions", ] [[package]] name = "sp-runtime-interface-proc-macro" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ae5b00aef477127ddb6177b3464ad1e2bdcc12ee913fc5dfc9d065c6cea89b" -dependencies = [ - "Inflector", - "proc-macro-crate 1.3.1", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "11.0.0" +version = "12.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d5bd5566fe5633ec48dfa35ab152fd29f8a577c21971e1c6db9f28afb9bbb9" +checksum = "7402572a08aa1ae421ea5bab10918764b0ae72301b27710913e5d804862f2448" dependencies = [ "Inflector", "proc-macro-crate 1.3.1", @@ -2567,9 +2358,9 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.27.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e49c3bfcc8c832c34552cd8194180cc60508c6d3d9b0b9615d6b7c3e275019" +checksum = "f2e84d8ed3acc6aed5a3d5cfd500fb5b99c1e299c86086b2fe82c3e4be93178f" dependencies = [ "hash-db", "log", @@ -2577,13 +2368,14 @@ dependencies = [ "parking_lot", "rand 0.8.5", "smallvec", - "sp-core 20.0.0", - "sp-externalities 0.18.0", + "sp-core", + "sp-externalities", "sp-panic-handler", - "sp-std 7.0.0", + "sp-std 9.0.0", "sp-trie", "thiserror", "tracing", + "trie-db", ] [[package]] @@ -2594,59 +2386,32 @@ checksum = "1de8eef39962b5b97478719c493bed2926cf70cb621005bbf68ebe58252ff986" [[package]] name = "sp-std" -version = "8.0.0" +version = "9.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53458e3c57df53698b3401ec0934bea8e8cfce034816873c0b0abbd83d7bac0d" +checksum = "2d5bbc9339227d1b6a9b7ccd9b2920c818653d40eef1512f1e2e824d72e7a336" [[package]] name = "sp-storage" -version = "12.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ad1f8c52d4700ac7bc42b3375679a6c6fc1fe876f4b40c6efdf36f933ef0291" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "ref-cast", - "serde", - "sp-debug-derive 7.0.0", - "sp-std 7.0.0", -] - -[[package]] -name = "sp-storage" -version = "13.0.0" +version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94294be83f11d4958cfea89ed5798f0b6605f5defc3a996948848458abbcc18e" +checksum = "a21245c3a7799ff6d3f1f159b496f9ac72eb32cd6fe68c6f73013155289aa9f1" dependencies = [ "impl-serde", "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive 8.0.0", - "sp-std 8.0.0", -] - -[[package]] -name = "sp-tracing" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00fab60bf3d42255ce3f678903d3a2564662371c75623de4a1ffc7cac46143df" -dependencies = [ - "parity-scale-codec", - "sp-std 7.0.0", - "tracing", - "tracing-core", - "tracing-subscriber", + "sp-debug-derive", + "sp-std 9.0.0", ] [[package]] name = "sp-tracing" -version = "10.0.0" +version = "11.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357f7591980dd58305956d32f8f6646d0a8ea9ea0e7e868e46f53b68ddf00cec" +checksum = "6f5ba26db1f7513d5975970d1ba1f0580d7a1b8da8c86ea3f9f0f8dbe2cfa96e" dependencies = [ "parity-scale-codec", - "sp-std 8.0.0", + "sp-std 9.0.0", "tracing", "tracing-core", "tracing-subscriber", @@ -2654,9 +2419,9 @@ dependencies = [ [[package]] name = "sp-trie" -version = "21.0.0" +version = "23.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58401c53c08b6ecad83acd7e14534c8bbcb3fa73e81e26685e0ac70e51b00c56" +checksum = "bf63ea90ffb5d61048d8fb2fac669114dac198fc2739e913e615f0fd2c36c3e7" dependencies = [ "ahash 0.8.3", "hash-db", @@ -2668,8 +2433,8 @@ dependencies = [ "parking_lot", "scale-info", "schnellru", - "sp-core 20.0.0", - "sp-std 7.0.0", + "sp-core", + "sp-std 9.0.0", "thiserror", "tracing", "trie-db", @@ -2678,47 +2443,32 @@ dependencies = [ [[package]] name = "sp-wasm-interface" -version = "13.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "153b7374179439e2aa783c66ed439bd86920c67bbc95d34c76390561972bc02f" -dependencies = [ - "anyhow", - "impl-trait-for-tuples", - "log", - "parity-scale-codec", - "sp-std 7.0.0", - "wasmi", - "wasmtime 6.0.2", -] - -[[package]] -name = "sp-wasm-interface" -version = "14.0.0" +version = "15.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19c122609ca5d8246be6386888596320d03c7bc880959eaa2c36bcd5acd6846" +checksum = "d07945f592d2792632e6f030108769757e928a0fd78cf8659c9c210a5e341e55" dependencies = [ "anyhow", "impl-trait-for-tuples", "log", "parity-scale-codec", - "sp-std 8.0.0", - "wasmtime 8.0.1", + "sp-std 9.0.0", + "wasmtime", ] [[package]] name = "sp-weights" -version = "19.0.0" +version = "21.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "123c661915e1bf328e21f8ecbe4e5247feba86f9149b782ea4348004547ce8ef" +checksum = "0b7699b853471c2eb5dc06ea1d8ea847bfa1415371218ebb4c86325c9d0232bc" dependencies = [ "parity-scale-codec", "scale-info", "serde", "smallvec", "sp-arithmetic", - "sp-core 20.0.0", - "sp-debug-derive 7.0.0", - "sp-std 7.0.0", + "sp-core", + "sp-debug-derive", + "sp-std 9.0.0", ] [[package]] @@ -2834,9 +2584,9 @@ checksum = "fd1ba337640d60c3e96bc6f0638a939b9c9a7f2c316a1598c279828b3d1dc8c5" [[package]] name = "tendermint" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a46ec6b25b028097ab682ffae11d09d64fe1e2535833b902f26a278a0f88a705" +checksum = "f6d550db02d6bec4ebcbbebc4301ec22181bc489c37fb3f167e64b14c1be8321" dependencies = [ "bytes", "digest 0.10.7", @@ -2863,9 +2613,9 @@ dependencies = [ [[package]] name = "tendermint-light-client-verifier" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4bc4c47cf36e740645e04128bd14ff5723aef86f5377fbd4d3b0149198dfc7e" +checksum = "6bc1e4e3dd6f65cfa7979cf721b5afa1d79d32c4a2fe5fddb6416a98638634a9" dependencies = [ "derive_more", "flex-error", @@ -2876,9 +2626,9 @@ dependencies = [ [[package]] name = "tendermint-proto" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce23c8ff0e6634eb4c3c4aeed45076dc97dac91aac5501a905a67fa222e165b" +checksum = "1834fa2eb884ba69b9c0eea55f0178270bed421217596ca4e54c19ef75dcb660" dependencies = [ "bytes", "flex-error", @@ -3251,49 +3001,6 @@ version = "0.2.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed9d5b4305409d1fc9482fee2d7f9bcbf24b3972bf59817ef757e23982242a93" -[[package]] -name = "wasmi" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c326c93fbf86419608361a2c925a31754cf109da1b8b55737070b4d6669422" -dependencies = [ - "parity-wasm", - "wasmi-validation", - "wasmi_core", -] - -[[package]] -name = "wasmi-validation" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ff416ad1ff0c42e5a926ed5d5fab74c0f098749aa0ad8b2a34b982ce0e867b" -dependencies = [ - "parity-wasm", -] - -[[package]] -name = "wasmi_core" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d20cb3c59b788653d99541c646c561c9dd26506f25c0cebfe810659c54c6d7" -dependencies = [ - "downcast-rs", - "libm", - "memory_units", - "num-rational", - "num-traits", -] - -[[package]] -name = "wasmparser" -version = "0.100.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64b20236ab624147dfbb62cf12a19aaf66af0e41b8398838b66e997d07d269d4" -dependencies = [ - "indexmap", - "url", -] - [[package]] name = "wasmparser" version = "0.102.0" @@ -3304,31 +3011,6 @@ dependencies = [ "url", ] -[[package]] -name = "wasmtime" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a222f5fa1e14b2cefc286f1b68494d7a965f4bf57ec04c59bb62673d639af6" -dependencies = [ - "anyhow", - "bincode", - "cfg-if", - "indexmap", - "libc", - "log", - "object 0.29.0", - "once_cell", - "paste", - "psm", - "serde", - "target-lexicon", - "wasmparser 0.100.0", - "wasmtime-environ 6.0.2", - "wasmtime-jit 6.0.2", - "wasmtime-runtime 6.0.2", - "windows-sys 0.42.0", -] - [[package]] name = "wasmtime" version = "8.0.1" @@ -3341,28 +3023,19 @@ dependencies = [ "indexmap", "libc", "log", - "object 0.30.4", + "object", "once_cell", "paste", "psm", "serde", "target-lexicon", - "wasmparser 0.102.0", - "wasmtime-environ 8.0.1", - "wasmtime-jit 8.0.1", - "wasmtime-runtime 8.0.1", + "wasmparser", + "wasmtime-environ", + "wasmtime-jit", + "wasmtime-runtime", "windows-sys 0.45.0", ] -[[package]] -name = "wasmtime-asm-macros" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4407a7246e7d2f3d8fb1cf0c72fda8dbafdb6dd34d555ae8bea0e5ae031089cc" -dependencies = [ - "cfg-if", -] - [[package]] name = "wasmtime-asm-macros" version = "8.0.1" @@ -3372,25 +3045,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "wasmtime-environ" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b8b50962eae38ee319f7b24900b7cf371f03eebdc17400c1dc8575fc10c9a7" -dependencies = [ - "anyhow", - "cranelift-entity 0.93.2", - "gimli 0.26.2", - "indexmap", - "log", - "object 0.29.0", - "serde", - "target-lexicon", - "thiserror", - "wasmparser 0.100.0", - "wasmtime-types 6.0.2", -] - [[package]] name = "wasmtime-environ" version = "8.0.1" @@ -3398,39 +3052,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a990198cee4197423045235bf89d3359e69bd2ea031005f4c2d901125955c949" dependencies = [ "anyhow", - "cranelift-entity 0.95.1", - "gimli 0.27.2", + "cranelift-entity", + "gimli", "indexmap", "log", - "object 0.30.4", + "object", "serde", "target-lexicon", "thiserror", - "wasmparser 0.102.0", - "wasmtime-types 8.0.1", -] - -[[package]] -name = "wasmtime-jit" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffaed4f9a234ba5225d8e64eac7b4a5d13b994aeb37353cde2cbeb3febda9eaa" -dependencies = [ - "addr2line 0.17.0", - "anyhow", - "bincode", - "cfg-if", - "cpp_demangle", - "gimli 0.26.2", - "log", - "object 0.29.0", - "rustc-demangle", - "serde", - "target-lexicon", - "wasmtime-environ 6.0.2", - "wasmtime-jit-icache-coherence 6.0.2", - "wasmtime-runtime 6.0.2", - "windows-sys 0.42.0", + "wasmparser", + "wasmtime-types", ] [[package]] @@ -3439,32 +3070,23 @@ version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0de48df552cfca1c9b750002d3e07b45772dd033b0b206d5c0968496abf31244" dependencies = [ - "addr2line 0.19.0", + "addr2line", "anyhow", "bincode", "cfg-if", "cpp_demangle", - "gimli 0.27.2", + "gimli", "log", - "object 0.30.4", + "object", "rustc-demangle", "serde", "target-lexicon", - "wasmtime-environ 8.0.1", - "wasmtime-jit-icache-coherence 8.0.1", - "wasmtime-runtime 8.0.1", + "wasmtime-environ", + "wasmtime-jit-icache-coherence", + "wasmtime-runtime", "windows-sys 0.45.0", ] -[[package]] -name = "wasmtime-jit-debug" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed41cbcbf74ce3ff6f1d07d1b707888166dc408d1a880f651268f4f7c9194b2" -dependencies = [ - "once_cell", -] - [[package]] name = "wasmtime-jit-debug" version = "8.0.1" @@ -3474,17 +3096,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "wasmtime-jit-icache-coherence" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a28ae1e648461bfdbb79db3efdaee1bca5b940872e4175390f465593a2e54c" -dependencies = [ - "cfg-if", - "libc", - "windows-sys 0.42.0", -] - [[package]] name = "wasmtime-jit-icache-coherence" version = "8.0.1" @@ -3496,30 +3107,6 @@ dependencies = [ "windows-sys 0.45.0", ] -[[package]] -name = "wasmtime-runtime" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e704b126e4252788ccfc3526d4d4511d4b23c521bf123e447ac726c14545217b" -dependencies = [ - "anyhow", - "cc", - "cfg-if", - "indexmap", - "libc", - "log", - "mach", - "memfd", - "memoffset 0.6.5", - "paste", - "rand 0.8.5", - "rustix 0.36.14", - "wasmtime-asm-macros 6.0.2", - "wasmtime-environ 6.0.2", - "wasmtime-jit-debug 6.0.2", - "windows-sys 0.42.0", -] - [[package]] name = "wasmtime-runtime" version = "8.0.1" @@ -3534,38 +3121,26 @@ dependencies = [ "log", "mach", "memfd", - "memoffset 0.8.0", + "memoffset", "paste", "rand 0.8.5", "rustix 0.36.14", - "wasmtime-asm-macros 8.0.1", - "wasmtime-environ 8.0.1", - "wasmtime-jit-debug 8.0.1", + "wasmtime-asm-macros", + "wasmtime-environ", + "wasmtime-jit-debug", "windows-sys 0.45.0", ] -[[package]] -name = "wasmtime-types" -version = "6.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83e5572c5727c1ee7e8f28717aaa8400e4d22dcbd714ea5457d85b5005206568" -dependencies = [ - "cranelift-entity 0.93.2", - "serde", - "thiserror", - "wasmparser 0.100.0", -] - [[package]] name = "wasmtime-types" version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4f6fffd2a1011887d57f07654dd112791e872e3ff4a2e626aee8059ee17f06f" dependencies = [ - "cranelift-entity 0.95.1", + "cranelift-entity", "serde", "thiserror", - "wasmparser 0.102.0", + "wasmparser", ] [[package]] @@ -3599,21 +3174,6 @@ dependencies = [ "windows-targets 0.48.0", ] -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-sys" version = "0.45.0" diff --git a/ci/no-std-check/Cargo.toml b/ci/no-std-check/Cargo.toml index 51a50fb51..691df2bae 100644 --- a/ci/no-std-check/Cargo.toml +++ b/ci/no-std-check/Cargo.toml @@ -5,10 +5,11 @@ edition = "2021" resolver = "2" [dependencies] -ibc = { path = "../../crates/ibc", default-features = false } -ibc-proto = { version = "0.33.0", default-features = false, features = [ +ibc = { path = "../../crates/ibc", default-features = false, features = ["serde"] } +ibc-proto = { version = "0.34.0", default-features = false, features = [ "parity-scale-codec", "borsh", + "serde", ] } tendermint = { version = "0.33.0", default-features = false } tendermint-proto = { version = "0.33.0", default-features = false } diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 48b589378..12291754b 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -50,7 +50,7 @@ mocks = ["tendermint-testgen", "tendermint/clock", "parking_lot"] [dependencies] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. -ibc-proto = { version = "0.33.0", default-features = false } +ibc-proto = { version = "0.34.0", default-features = false, features = ["serde"] } ics23 = { version = "0.10.1", default-features = false, features = ["host-functions"] } time = { version = ">=0.3.0, <0.3.26", default-features = false } serde_derive = { version = "1.0.104", default-features = false, optional = true } diff --git a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs index fa5f5fd51..d81a47621 100644 --- a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs +++ b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs @@ -74,7 +74,7 @@ impl Protobuf for Misbehaviour {} impl TryFrom for Misbehaviour { type Error = Error; - + #[allow(deprecated)] fn try_from(raw: RawMisbehaviour) -> Result { let client_id = raw.client_id.parse()?; @@ -98,6 +98,7 @@ impl TryFrom for Misbehaviour { impl From for RawMisbehaviour { fn from(value: Misbehaviour) -> Self { + #[allow(deprecated)] RawMisbehaviour { client_id: value.client_id.to_string(), header_1: Some(value.header1.into()), diff --git a/crates/ibc/src/core/handler.rs b/crates/ibc/src/core/handler.rs index 027723b90..faa3216a6 100644 --- a/crates/ibc/src/core/handler.rs +++ b/crates/ibc/src/core/handler.rs @@ -421,7 +421,7 @@ mod tests { name: "Client update successful".to_string(), msg: MsgEnvelope::Client(ClientMsg::UpdateClient(MsgUpdateClient { client_id: client_id.clone(), - header: MockHeader::new(update_client_height) + client_message: MockHeader::new(update_client_height) .with_timestamp(Timestamp::now()) .into(), signer: default_signer.clone(), @@ -434,7 +434,7 @@ mod tests { name: "Client update fails due to stale header".to_string(), msg: MsgEnvelope::Client(ClientMsg::UpdateClient(MsgUpdateClient { client_id: client_id.clone(), - header: MockHeader::new(update_client_height).into(), + client_message: MockHeader::new(update_client_height).into(), signer: default_signer.clone(), })) .into(), @@ -509,7 +509,7 @@ mod tests { name: "Client update successful #2".to_string(), msg: MsgEnvelope::Client(ClientMsg::UpdateClient(MsgUpdateClient { client_id: client_id.clone(), - header: MockHeader::new(update_client_height_after_send) + client_message: MockHeader::new(update_client_height_after_send) .with_timestamp(Timestamp::now()) .into(), signer: default_signer.clone(), @@ -554,7 +554,7 @@ mod tests { name: "Client update successful".to_string(), msg: MsgEnvelope::Client(ClientMsg::UpdateClient(MsgUpdateClient { client_id: client_id.clone(), - header: MockHeader::new(update_client_height_after_second_send).into(), + client_message: MockHeader::new(update_client_height_after_second_send).into(), signer: default_signer, })) .into(), diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 2ee0b4831..826341c34 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -67,8 +67,8 @@ pub enum ClientError { InvalidClientIdentifier(IdentifierError), /// invalid raw header error: `{0}` InvalidRawHeader(TendermintProtoError), - /// missing raw header - MissingRawHeader, + /// missing raw client message + MissingClientMessage, /// invalid raw misbehaviour error: `{0}` InvalidRawMisbehaviour(IdentifierError), /// missing raw misbehaviour 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 cad4bde1d..d0e2e0712 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -174,7 +174,7 @@ mod tests { let height = Height::new(0, 46).unwrap(); let msg = MsgUpdateClient { client_id, - header: MockHeader::new(height).with_timestamp(timestamp).into(), + client_message: MockHeader::new(height).with_timestamp(timestamp).into(), signer, }; @@ -200,7 +200,7 @@ mod tests { let msg = MsgUpdateClient { client_id: ClientId::from_str("nonexistingclient").unwrap(), - header: MockHeader::new(Height::new(0, 46).unwrap()).into(), + client_message: MockHeader::new(Height::new(0, 46).unwrap()).into(), signer, }; @@ -240,7 +240,7 @@ mod tests { let latest_header_height = block.height(); let msg = MsgUpdateClient { client_id, - header: block.into(), + client_message: block.into(), signer, }; @@ -290,7 +290,7 @@ mod tests { let latest_header_height = block.height(); let msg = MsgUpdateClient { client_id, - header: block.into(), + client_message: block.into(), signer, }; @@ -411,7 +411,7 @@ mod tests { let latest_header_height = block.height(); let msg = MsgUpdateClient { client_id, - header: block.into(), + client_message: block.into(), signer, }; @@ -468,7 +468,7 @@ mod tests { let msg = MsgUpdateClient { client_id, - header: block_ref.clone().into(), + client_message: block_ref.clone().into(), signer, }; @@ -488,7 +488,7 @@ mod tests { let header: Any = MockHeader::new(height).with_timestamp(timestamp).into(); let msg = MsgUpdateClient { client_id: client_id.clone(), - header: header.clone(), + client_message: header.clone(), signer, }; diff --git a/crates/ibc/src/core/ics02_client/msgs.rs b/crates/ibc/src/core/ics02_client/msgs.rs index 87f81fde0..9bb0375a8 100644 --- a/crates/ibc/src/core/ics02_client/msgs.rs +++ b/crates/ibc/src/core/ics02_client/msgs.rs @@ -39,7 +39,7 @@ impl MsgUpdateOrMisbehaviour { pub(crate) fn client_message(self) -> Any { match self { - MsgUpdateOrMisbehaviour::UpdateClient(msg) => msg.header, + MsgUpdateOrMisbehaviour::UpdateClient(msg) => msg.client_message, MsgUpdateOrMisbehaviour::Misbehaviour(msg) => msg.misbehaviour, } } 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 8597f106c..3adfa716f 100644 --- a/crates/ibc/src/core/ics02_client/msgs/update_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/update_client.rs @@ -20,7 +20,7 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgUpdateClient"; #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgUpdateClient { pub client_id: ClientId, - pub header: Any, + pub client_message: Any, pub signer: Signer, } @@ -43,7 +43,9 @@ impl TryFrom for MsgUpdateClient { .client_id .parse() .map_err(ClientError::InvalidMsgUpdateClientId)?, - header: raw.header.ok_or(ClientError::MissingRawHeader)?, + client_message: raw + .client_message + .ok_or(ClientError::MissingClientMessage)?, signer: raw.signer.into(), }) } @@ -53,7 +55,7 @@ impl From for RawMsgUpdateClient { fn from(ics_msg: MsgUpdateClient) -> Self { RawMsgUpdateClient { client_id: ics_msg.client_id.to_string(), - header: Some(ics_msg.header), + client_message: Some(ics_msg.client_message), signer: ics_msg.signer.to_string(), } } @@ -75,10 +77,10 @@ mod tests { use crate::test_utils::get_dummy_account_id; impl MsgUpdateClient { - pub fn new(client_id: ClientId, header: Any, signer: Signer) -> Self { + pub fn new(client_id: ClientId, client_message: Any, signer: Signer) -> Self { MsgUpdateClient { client_id, - header, + client_message, signer, } } 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 1f674c499..ad5613d13 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 @@ -36,6 +36,9 @@ pub struct MsgConnectionOpenAck { pub consensus_height_of_a_on_b: Height, pub version: Version, pub signer: Signer, + /// optional proof of host state machines (chain A) that are unable to + /// introspect their own consensus state + pub proof_consensus_state_of_a: Option, } impl Msg for MsgConnectionOpenAck { @@ -89,6 +92,15 @@ impl TryFrom for MsgConnectionOpenAck { .and_then(|raw_height| raw_height.try_into().ok()) .ok_or(ConnectionError::MissingConsensusHeight)?, signer: msg.signer.into(), + proof_consensus_state_of_a: if msg.host_consensus_state_proof.is_empty() { + None + } else { + Some( + msg.host_consensus_state_proof + .try_into() + .map_err(|_| ConnectionError::InvalidProof)?, + ) + }, }) } } @@ -106,6 +118,10 @@ impl From for RawMsgConnectionOpenAck { consensus_height: Some(msg.consensus_height_of_a_on_b.into()), version: Some(msg.version.into()), signer: msg.signer.to_string(), + host_consensus_state_proof: match msg.proof_consensus_state_of_a { + Some(proof) => proof.into(), + None => vec![], + }, } } } @@ -159,6 +175,7 @@ pub mod test_util { proof_client: get_dummy_proof(), version: Some(Version::default().into()), signer: get_dummy_bech32_account(), + host_consensus_state_proof: vec![], } } } 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 075ca9122..264aff846 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 @@ -44,6 +44,9 @@ pub struct MsgConnectionOpenTry { pub consensus_height_of_b_on_a: Height, pub delay_period: Duration, pub signer: Signer, + /// optional proof of host state machines (chain B) that are unable to + /// introspect their own consensus state + pub proof_consensus_state_of_b: Option, #[deprecated(since = "0.22.0")] /// Only kept here for proper conversion to/from the raw type @@ -113,6 +116,15 @@ impl TryFrom for MsgConnectionOpenTry { .ok_or(ConnectionError::MissingConsensusHeight)?, delay_period: Duration::from_nanos(msg.delay_period), signer: msg.signer.into(), + proof_consensus_state_of_b: if msg.host_consensus_state_proof.is_empty() { + None + } else { + Some( + msg.host_consensus_state_proof + .try_into() + .map_err(|_| ConnectionError::InvalidProof)?, + ) + }, }) } } @@ -133,6 +145,10 @@ impl From for RawMsgConnectionOpenTry { proof_consensus: msg.proof_consensus_state_of_b_on_a.into(), consensus_height: Some(msg.consensus_height_of_b_on_a.into()), signer: msg.signer.to_string(), + host_consensus_state_proof: match msg.proof_consensus_state_of_b { + Some(proof) => proof.into(), + None => vec![], + }, } } } @@ -204,6 +220,7 @@ pub mod test_util { }), proof_client: get_dummy_proof(), signer: get_dummy_bech32_account(), + host_consensus_state_proof: vec![], } } } diff --git a/crates/ibc/src/hosts/tendermint/upgrade_proposal/handler.rs b/crates/ibc/src/hosts/tendermint/upgrade_proposal/handler.rs index 9b6026f5c..53437d780 100644 --- a/crates/ibc/src/hosts/tendermint/upgrade_proposal/handler.rs +++ b/crates/ibc/src/hosts/tendermint/upgrade_proposal/handler.rs @@ -1,8 +1,5 @@ -use core::convert::Infallible; - use alloc::string::ToString; use tendermint::abci::Event as TmEvent; -use tendermint_proto::abci::Event as ProtoEvent; use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState; use crate::core::ics02_client::error::UpgradeClientError; @@ -19,7 +16,7 @@ use crate::hosts::tendermint::upgrade_proposal::UpgradeProposal; pub fn upgrade_client_proposal_handler( ctx: &mut Ctx, proposal: UpgradeProposal, -) -> Result +) -> Result where Ctx: UpgradeExecutionContext, Ctx::AnyClientState: From, @@ -45,11 +42,7 @@ where ctx.store_upgraded_client_state(upgraded_client_state_path, client_state.into())?; - let event = TmEvent::from(UpgradeClientProposal::new(proposal.title, plan.height)) - .try_into() - .map_err(|e: Infallible| UpgradeClientError::Other { - reason: e.to_string(), - })?; + let event = TmEvent::from(UpgradeClientProposal::new(proposal.title, plan.height)); Ok(event) } diff --git a/crates/ibc/src/mock/header.rs b/crates/ibc/src/mock/header.rs index fa459d193..46ce0a785 100644 --- a/crates/ibc/src/mock/header.rs +++ b/crates/ibc/src/mock/header.rs @@ -47,7 +47,7 @@ impl TryFrom for MockHeader { height: raw .height .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(ClientError::MissingRawHeader)?, + .ok_or(ClientError::MissingClientMessage)?, timestamp: Timestamp::from_nanoseconds(raw.timestamp) .map_err(ClientError::InvalidPacketTimestamp)?, diff --git a/crates/ibc/src/mock/ics18_relayer/context.rs b/crates/ibc/src/mock/ics18_relayer/context.rs index 73b9b3f3b..69e252c10 100644 --- a/crates/ibc/src/mock/ics18_relayer/context.rs +++ b/crates/ibc/src/mock/ics18_relayer/context.rs @@ -82,7 +82,7 @@ mod tests { // Client on destination chain can be updated. Ok(ClientMsg::UpdateClient(MsgUpdateClient { client_id: client_id.clone(), - header: (*src_header).clone().into(), + client_message: (*src_header).clone().into(), signer: dest.signer(), })) } From 56e7e62110501becb42e1bf91946605cca451b12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Tue, 29 Aug 2023 16:21:23 -0400 Subject: [PATCH 020/182] bump ibc-proto to v0.34.1 and borsh to v0.10 (#844) * bump ibc-proto and borsh * changelog --- .changelog/unreleased/improvements/844-bump-borsh.md | 2 ++ crates/ibc/Cargo.toml | 4 ++-- crates/ibc/src/core/ics03_connection/connection.rs | 6 ++++-- crates/ibc/src/core/timestamp.rs | 6 ++++-- 4 files changed, 12 insertions(+), 6 deletions(-) create mode 100644 .changelog/unreleased/improvements/844-bump-borsh.md diff --git a/.changelog/unreleased/improvements/844-bump-borsh.md b/.changelog/unreleased/improvements/844-bump-borsh.md new file mode 100644 index 000000000..de58be506 --- /dev/null +++ b/.changelog/unreleased/improvements/844-bump-borsh.md @@ -0,0 +1,2 @@ +- Bump ibc-proto to v0.34.1 and borsh to v0.10 + ([#844](https://github.com/cosmos/ibc-rs/issues/844)) diff --git a/crates/ibc/Cargo.toml b/crates/ibc/Cargo.toml index 12291754b..ef9d36fb9 100644 --- a/crates/ibc/Cargo.toml +++ b/crates/ibc/Cargo.toml @@ -50,7 +50,7 @@ mocks = ["tendermint-testgen", "tendermint/clock", "parking_lot"] [dependencies] # Proto definitions for all IBC-related interfaces, e.g., connections or channels. -ibc-proto = { version = "0.34.0", default-features = false, features = ["serde"] } +ibc-proto = { version = "0.34.1", default-features = false, features = ["serde"] } ics23 = { version = "0.10.1", default-features = false, features = ["host-functions"] } time = { version = ">=0.3.0, <0.3.26", default-features = false } serde_derive = { version = "1.0.104", default-features = false, optional = true } @@ -72,7 +72,7 @@ primitive-types = { version = "0.12.0", default-features = false, features = ["s parity-scale-codec = { version = "3.0.0", default-features = false, features = ["full"], optional = true } scale-info = { version = "2.1.2", default-features = false, features = ["derive"], optional = true } ## for borsh encode or decode -borsh = {version = "0.9.0", default-features = false, optional = true } +borsh = {version = "0.10", default-features = false, optional = true } parking_lot = { version = "0.12.1", default-features = false, optional = true } ibc-derive = { version ="0.3.0", path = "../ibc-derive" } diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index e70ae400c..6ab1513ec 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -167,8 +167,10 @@ mod sealed { #[cfg(feature = "borsh")] impl borsh::BorshDeserialize for ConnectionEnd { - fn deserialize(reader: &mut &[u8]) -> borsh::maybestd::io::Result { - let inner_conn_end = InnerConnectionEnd::deserialize(reader)?; + fn deserialize_reader( + reader: &mut R, + ) -> borsh::maybestd::io::Result { + let inner_conn_end = InnerConnectionEnd::deserialize_reader(reader)?; Ok(ConnectionEnd::from(inner_conn_end)) } } diff --git a/crates/ibc/src/core/timestamp.rs b/crates/ibc/src/core/timestamp.rs index 510af94ee..e0c6079fb 100644 --- a/crates/ibc/src/core/timestamp.rs +++ b/crates/ibc/src/core/timestamp.rs @@ -41,8 +41,10 @@ impl borsh::BorshSerialize for Timestamp { #[cfg(feature = "borsh")] impl borsh::BorshDeserialize for Timestamp { - fn deserialize(reader: &mut &[u8]) -> borsh::maybestd::io::Result { - let timestamp = u64::deserialize(reader)?; + fn deserialize_reader( + reader: &mut R, + ) -> borsh::maybestd::io::Result { + let timestamp = u64::deserialize_reader(reader)?; Ok(Timestamp::from_nanoseconds(timestamp) .map_err(|_| borsh::maybestd::io::ErrorKind::Other)?) } From 1833df51985e1752a90e909a0e7377f8b10524e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Wed, 30 Aug 2023 17:09:04 -0400 Subject: [PATCH 021/182] Add borsh derive for `MsgTransfer` (#845) * add borsh derive for `MsgTransfer` * changelog --- .../845-borsh-derive-msgtransfer.md | 2 + .../ibc/src/applications/transfer/amount.rs | 67 ++++++++++++++++++- crates/ibc/src/applications/transfer/coin.rs | 4 ++ crates/ibc/src/applications/transfer/denom.rs | 16 +++++ .../applications/transfer/msgs/transfer.rs | 4 ++ .../ibc/src/applications/transfer/packet.rs | 4 ++ 6 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 .changelog/unreleased/improvements/845-borsh-derive-msgtransfer.md diff --git a/.changelog/unreleased/improvements/845-borsh-derive-msgtransfer.md b/.changelog/unreleased/improvements/845-borsh-derive-msgtransfer.md new file mode 100644 index 000000000..1bbcc3ed8 --- /dev/null +++ b/.changelog/unreleased/improvements/845-borsh-derive-msgtransfer.md @@ -0,0 +1,2 @@ +- Add borsh derive for `MsgTransfer` + ([#845](https://github.com/cosmos/ibc-rs/pull/845)) diff --git a/crates/ibc/src/applications/transfer/amount.rs b/crates/ibc/src/applications/transfer/amount.rs index 740e24d0c..9cee50d29 100644 --- a/crates/ibc/src/applications/transfer/amount.rs +++ b/crates/ibc/src/applications/transfer/amount.rs @@ -1,5 +1,6 @@ //! Contains the `Amount` type, which represents amounts of tokens transferred. +use crate::prelude::*; use core::{ops::Deref, str::FromStr}; use derive_more::{Display, From, Into}; @@ -28,6 +29,54 @@ impl parity_scale_codec::WrapperTypeDecode for Amount { #[cfg(feature = "parity-scale-codec")] impl parity_scale_codec::WrapperTypeEncode for Amount {} +#[cfg(feature = "borsh")] +impl borsh::BorshSerialize for Amount { + fn serialize( + &self, + writer: &mut W, + ) -> borsh::maybestd::io::Result<()> { + // Note: a "word" is 8 bytes (i.e. a u64) + let words = self.as_slice(); + let bytes: Vec = words.iter().flat_map(|word| word.to_be_bytes()).collect(); + + writer.write_all(&bytes) + } +} +#[cfg(feature = "borsh")] +impl borsh::BorshDeserialize for Amount { + fn deserialize_reader( + reader: &mut R, + ) -> borsh::maybestd::io::Result { + const NUM_BYTES_IN_U64: usize = 8; + const NUM_WORDS_IN_U256: usize = 4; + + let mut buf = [0; 32]; + let bytes_read = reader.read(&mut buf)?; + if bytes_read != 32 { + return Err(borsh::maybestd::io::Error::new( + borsh::maybestd::io::ErrorKind::InvalidInput, + format!("Expected to read 32 bytes, read {bytes_read}"), + )); + } + + let words: Vec = buf + .chunks_exact(NUM_BYTES_IN_U64) + .map(|word| { + let word: [u8; NUM_BYTES_IN_U64] = word + .try_into() + .expect("exact chunks of 8 bytes are expected to be 8 bytes"); + u64::from_be_bytes(word) + }) + .collect(); + + let four_words: [u64; NUM_WORDS_IN_U256] = words + .try_into() + .expect("U256 is always 4 four words, and we confirmed that we read 32 bytes"); + + Ok(four_words.into()) + } +} + impl Deref for Amount { type Target = [u64; 4]; @@ -83,10 +132,10 @@ where } #[cfg(test)] -#[cfg(feature = "serde")] mod tests { use super::Amount; + #[cfg(feature = "serde")] #[test] fn serde_amount() { let value = Amount::from(42); @@ -96,4 +145,20 @@ mod tests { let de: Amount = serde_json::from_slice(binary.as_ref()).expect("can deserialize"); assert_eq!(de, value); } + + #[cfg(feature = "borsh")] + #[test] + fn borsh_amount() { + use borsh::BorshDeserialize; + + let value = Amount::from(42); + let serialized = borsh::to_vec(&value).unwrap(); + + // Amount is supposed to be a U256 according to the spec, which is 32 bytes + assert_eq!(serialized.len(), 32); + + let value_deserialized = Amount::try_from_slice(&serialized).unwrap(); + + assert_eq!(value, value_deserialized); + } } diff --git a/crates/ibc/src/applications/transfer/coin.rs b/crates/ibc/src/applications/transfer/coin.rs index cad624121..7fd429640 100644 --- a/crates/ibc/src/applications/transfer/coin.rs +++ b/crates/ibc/src/applications/transfer/coin.rs @@ -25,6 +25,10 @@ pub type RawCoin = Coin; feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode,) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] pub struct Coin { /// Denomination diff --git a/crates/ibc/src/applications/transfer/denom.rs b/crates/ibc/src/applications/transfer/denom.rs index 963f6b1d7..77ab685ee 100644 --- a/crates/ibc/src/applications/transfer/denom.rs +++ b/crates/ibc/src/applications/transfer/denom.rs @@ -27,6 +27,10 @@ use crate::serializers::serde_string; scale_info::TypeInfo ) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Display)] pub struct BaseDenom(String); @@ -62,6 +66,10 @@ impl FromStr for BaseDenom { scale_info::TypeInfo ) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] @@ -97,6 +105,10 @@ impl Display for TracePrefix { scale_info::TypeInfo ) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, From)] @@ -198,6 +210,10 @@ impl Display for TracePath { scale_info::TypeInfo ) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] pub struct PrefixedDenom { /// A series of `{port-id}/{channel-id}`s for tracing the source of the token. diff --git a/crates/ibc/src/applications/transfer/msgs/transfer.rs b/crates/ibc/src/applications/transfer/msgs/transfer.rs index 0b22755aa..a5d9024c5 100644 --- a/crates/ibc/src/applications/transfer/msgs/transfer.rs +++ b/crates/ibc/src/applications/transfer/msgs/transfer.rs @@ -29,6 +29,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.applications.transfer.v1.MsgTransfer"; feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode,) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] pub struct MsgTransfer { /// the port on which the packet will be sent pub port_id_on_a: PortId, diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index 4b7ffb4be..fdcede335 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -24,6 +24,10 @@ use crate::signer::Signer; feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode,) )] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct PacketData { pub token: PrefixedCoin, From 2c28380918f1000fd4f509fc2f9fcd4aeb189984 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Fri, 1 Sep 2023 09:08:45 -0400 Subject: [PATCH 022/182] Derive borsh for `MsgEnvelope` (#846) * Add BorshSerialize/Deserialize to MsgEnvelope * add tests * changelog --- .../846-borsh-derive-msgenvelope.md | 2 + crates/ibc/src/core/ics02_client/msgs.rs | 4 + .../core/ics02_client/msgs/create_client.rs | 4 + .../core/ics02_client/msgs/misbehaviour.rs | 4 + .../core/ics02_client/msgs/update_client.rs | 4 + .../core/ics02_client/msgs/upgrade_client.rs | 4 + crates/ibc/src/core/ics03_connection/msgs.rs | 4 + .../ics03_connection/msgs/conn_open_ack.rs | 4 + .../msgs/conn_open_confirm.rs | 4 + .../ics03_connection/msgs/conn_open_init.rs | 75 ++++++++++++ .../ics03_connection/msgs/conn_open_try.rs | 109 ++++++++++++++++++ crates/ibc/src/core/ics04_channel/msgs.rs | 8 ++ .../ics04_channel/msgs/acknowledgement.rs | 4 + .../ics04_channel/msgs/chan_close_confirm.rs | 4 + .../ics04_channel/msgs/chan_close_init.rs | 4 + .../core/ics04_channel/msgs/chan_open_ack.rs | 4 + .../ics04_channel/msgs/chan_open_confirm.rs | 4 + .../core/ics04_channel/msgs/chan_open_init.rs | 4 + .../core/ics04_channel/msgs/chan_open_try.rs | 4 + .../core/ics04_channel/msgs/recv_packet.rs | 4 + .../src/core/ics04_channel/msgs/timeout.rs | 4 + .../ics04_channel/msgs/timeout_on_close.rs | 4 + .../src/core/ics23_commitment/commitment.rs | 4 + crates/ibc/src/core/msgs.rs | 4 + 24 files changed, 274 insertions(+) create mode 100644 .changelog/unreleased/improvements/846-borsh-derive-msgenvelope.md diff --git a/.changelog/unreleased/improvements/846-borsh-derive-msgenvelope.md b/.changelog/unreleased/improvements/846-borsh-derive-msgenvelope.md new file mode 100644 index 000000000..cc5ccad7d --- /dev/null +++ b/.changelog/unreleased/improvements/846-borsh-derive-msgenvelope.md @@ -0,0 +1,2 @@ +- Add borsh derive for `MsgEnvelope` + ([#846](https://github.com/cosmos/ibc-rs/pull/846)) diff --git a/crates/ibc/src/core/ics02_client/msgs.rs b/crates/ibc/src/core/ics02_client/msgs.rs index 9bb0375a8..b432211c9 100644 --- a/crates/ibc/src/core/ics02_client/msgs.rs +++ b/crates/ibc/src/core/ics02_client/msgs.rs @@ -16,6 +16,10 @@ pub mod upgrade_client; /// Encodes all the different client messages #[allow(dead_code)] +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug)] pub enum ClientMsg { CreateClient(MsgCreateClient), 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 de3de83f2..c55e8668c 100644 --- a/crates/ibc/src/core/ics02_client/msgs/create_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/create_client.rs @@ -13,6 +13,10 @@ use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgCreateClient"; /// A type of message that triggers the creation of a new on-chain (IBC) client. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgCreateClient { pub client_state: Any, diff --git a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs index 011db59dd..6ab10266b 100644 --- a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs +++ b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs @@ -14,6 +14,10 @@ use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgSubmitMisbehaviour"; /// A type of message that submits client misbehaviour proof. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgSubmitMisbehaviour { /// client unique identifier 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 3adfa716f..74e365a44 100644 --- a/crates/ibc/src/core/ics02_client/msgs/update_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/update_client.rs @@ -17,6 +17,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgUpdateClient"; /// either with new headers, or evidence of misbehaviour. /// Note that some types of misbehaviour can be detected when a headers /// are updated (`UpdateKind::UpdateClient`). +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgUpdateClient { pub client_id: ClientId, 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 b5c49613b..c87976e53 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -18,6 +18,10 @@ use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgUpgradeClient"; /// A type of message that triggers the upgrade of an on-chain (IBC) client. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq)] pub struct MsgUpgradeClient { // client unique identifier diff --git a/crates/ibc/src/core/ics03_connection/msgs.rs b/crates/ibc/src/core/ics03_connection/msgs.rs index 55f445ea3..486ce3956 100644 --- a/crates/ibc/src/core/ics03_connection/msgs.rs +++ b/crates/ibc/src/core/ics03_connection/msgs.rs @@ -23,6 +23,10 @@ pub mod conn_open_init; pub mod conn_open_try; /// Enumeration of all possible messages that the ICS3 protocol processes. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub enum ConnectionMsg { OpenInit(MsgConnectionOpenInit), 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 ad5613d13..5b57756f7 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 @@ -16,6 +16,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenAck" /// Per our convention, this message is sent to chain A. /// The handler will check proofs of chain B. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgConnectionOpenAck { /// ConnectionId that chain A has chosen for it's ConnectionEnd 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 69592e31b..4f0337a69 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 @@ -14,6 +14,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenConf /// Per our convention, this message is sent to chain B. /// The handler will check proofs of chain A. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgConnectionOpenConfirm { /// ConnectionId that chain B has chosen for it's ConnectionEnd 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 ae7c0e0a9..d6732f258 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 @@ -34,6 +34,64 @@ impl Msg for MsgConnectionOpenInit { } } +/// This module encapsulates the workarounds we need to do to implement +/// `BorshSerialize` and `BorshDeserialize` on `MsgConnectionOpenInit` +#[cfg(feature = "borsh")] +mod borsh_impls { + use borsh::{ + maybestd::io::{self, Read}, + BorshDeserialize, BorshSerialize, + }; + + use super::*; + + #[derive(BorshSerialize, BorshDeserialize)] + pub struct InnerMsgConnectionOpenInit { + /// ClientId on chain A that the connection is being opened for + pub client_id_on_a: ClientId, + pub counterparty: Counterparty, + pub version: Option, + pub delay_period_nanos: u64, + pub signer: Signer, + } + + impl BorshSerialize for MsgConnectionOpenInit { + fn serialize(&self, writer: &mut W) -> io::Result<()> { + let delay_period_nanos: u64 = + self.delay_period.as_nanos().try_into().map_err(|_| { + io::Error::new( + io::ErrorKind::Other, + format!("Duration too long: {} nanos", self.delay_period.as_nanos()), + ) + })?; + + let inner = InnerMsgConnectionOpenInit { + client_id_on_a: self.client_id_on_a.clone(), + counterparty: self.counterparty.clone(), + version: self.version.clone(), + delay_period_nanos, + signer: self.signer.clone(), + }; + + inner.serialize(writer) + } + } + + impl BorshDeserialize for MsgConnectionOpenInit { + fn deserialize_reader(reader: &mut R) -> io::Result { + let inner = InnerMsgConnectionOpenInit::deserialize_reader(reader)?; + + Ok(MsgConnectionOpenInit { + client_id_on_a: inner.client_id_on_a, + counterparty: inner.counterparty, + version: inner.version, + delay_period: Duration::from_nanos(inner.delay_period_nanos), + signer: inner.signer, + }) + } + } +} + impl Protobuf for MsgConnectionOpenInit {} impl TryFrom for MsgConnectionOpenInit { @@ -239,4 +297,21 @@ mod tests { msg_with_counterpary_conn_id_some_back ); } + + /// Test that borsh serialization/deserialization works well with delay periods up to u64::MAX + #[cfg(feature = "borsh")] + #[test] + fn test_borsh() { + let mut raw = get_dummy_raw_msg_conn_open_init(); + raw.delay_period = u64::MAX; + let msg = MsgConnectionOpenInit::try_from(raw.clone()).unwrap(); + + let serialized = borsh::to_vec(&msg).unwrap(); + + let msg_deserialized = + ::try_from_slice(&serialized) + .unwrap(); + + assert_eq!(msg, msg_deserialized); + } } 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 264aff846..11f7fb884 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 @@ -60,6 +60,99 @@ impl Msg for MsgConnectionOpenTry { TYPE_URL.to_string() } } +#[allow(deprecated)] +#[cfg(feature = "borsh")] +mod borsh_impls { + use borsh::{ + maybestd::io::{self, Read}, + BorshDeserialize, BorshSerialize, + }; + + use super::*; + + #[derive(BorshSerialize, BorshDeserialize)] + pub struct InnerMsgConnectionOpenTry { + /// ClientId on B that the connection is being opened for + pub client_id_on_b: ClientId, + /// ClientState of client tracking chain B on chain A + pub client_state_of_b_on_a: Any, + /// ClientId, ConnectionId and prefix of chain A + pub counterparty: Counterparty, + /// Versions supported by chain A + pub versions_on_a: Vec, + /// proof of ConnectionEnd stored on Chain A during ConnOpenInit + pub proof_conn_end_on_a: CommitmentProofBytes, + /// proof that chain A has stored ClientState of chain B on its client + pub proof_client_state_of_b_on_a: CommitmentProofBytes, + /// proof that chain A has stored ConsensusState of chain B on its client + pub proof_consensus_state_of_b_on_a: CommitmentProofBytes, + /// Height at which all proofs in this message were taken + pub proofs_height_on_a: Height, + /// height of latest header of chain A that updated the client on chain B + pub consensus_height_of_b_on_a: Height, + pub delay_period_nanos: u64, + pub signer: Signer, + /// optional proof of host state machines (chain B) that are unable to + /// introspect their own consensus state + pub proof_consensus_state_of_b: Option, + + #[deprecated(since = "0.22.0")] + /// Only kept here for proper conversion to/from the raw type + previous_connection_id: String, + } + + impl BorshSerialize for MsgConnectionOpenTry { + fn serialize(&self, writer: &mut W) -> io::Result<()> { + let delay_period_nanos: u64 = + self.delay_period.as_nanos().try_into().map_err(|_| { + io::Error::new( + io::ErrorKind::Other, + format!("Duration too long: {} nanos", self.delay_period.as_nanos()), + ) + })?; + + let inner = InnerMsgConnectionOpenTry { + client_id_on_b: self.client_id_on_b.clone(), + client_state_of_b_on_a: self.client_state_of_b_on_a.clone(), + counterparty: self.counterparty.clone(), + versions_on_a: self.versions_on_a.clone(), + proof_conn_end_on_a: self.proof_conn_end_on_a.clone(), + proof_client_state_of_b_on_a: self.proof_client_state_of_b_on_a.clone(), + proof_consensus_state_of_b_on_a: self.proof_consensus_state_of_b_on_a.clone(), + proofs_height_on_a: self.proofs_height_on_a, + consensus_height_of_b_on_a: self.consensus_height_of_b_on_a, + delay_period_nanos, + signer: self.signer.clone(), + proof_consensus_state_of_b: self.proof_consensus_state_of_b.clone(), + previous_connection_id: self.previous_connection_id.clone(), + }; + + inner.serialize(writer) + } + } + + impl BorshDeserialize for MsgConnectionOpenTry { + fn deserialize_reader(reader: &mut R) -> io::Result { + let inner = InnerMsgConnectionOpenTry::deserialize_reader(reader)?; + + Ok(MsgConnectionOpenTry { + client_id_on_b: inner.client_id_on_b, + client_state_of_b_on_a: inner.client_state_of_b_on_a, + counterparty: inner.counterparty, + versions_on_a: inner.versions_on_a, + proof_conn_end_on_a: inner.proof_conn_end_on_a, + proof_client_state_of_b_on_a: inner.proof_client_state_of_b_on_a, + proof_consensus_state_of_b_on_a: inner.proof_consensus_state_of_b_on_a, + proofs_height_on_a: inner.proofs_height_on_a, + consensus_height_of_b_on_a: inner.consensus_height_of_b_on_a, + delay_period: Duration::from_nanos(inner.delay_period_nanos), + signer: inner.signer, + proof_consensus_state_of_b: inner.proof_consensus_state_of_b, + previous_connection_id: inner.previous_connection_id, + }) + } + } +} impl Protobuf for MsgConnectionOpenTry {} @@ -357,4 +450,20 @@ mod tests { assert_eq!(raw, raw_back); assert_eq!(msg, msg_back); } + + /// Test that borsh serialization/deserialization works well with delay periods up to u64::MAX + #[cfg(feature = "borsh")] + #[test] + fn test_borsh() { + let mut raw = get_dummy_raw_msg_conn_open_try(10, 34); + raw.delay_period = u64::MAX; + let msg = MsgConnectionOpenTry::try_from(raw.clone()).unwrap(); + + let serialized = borsh::to_vec(&msg).unwrap(); + + let msg_deserialized = + ::try_from_slice(&serialized).unwrap(); + + assert_eq!(msg, msg_deserialized); + } } diff --git a/crates/ibc/src/core/ics04_channel/msgs.rs b/crates/ibc/src/core/ics04_channel/msgs.rs index fad6922d3..728c8926c 100644 --- a/crates/ibc/src/core/ics04_channel/msgs.rs +++ b/crates/ibc/src/core/ics04_channel/msgs.rs @@ -31,6 +31,10 @@ pub use timeout_on_close::MsgTimeoutOnClose; use crate::core::ics24_host::identifier::PortId; /// All channel messages +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub enum ChannelMsg { OpenInit(MsgChannelOpenInit), @@ -42,6 +46,10 @@ pub enum ChannelMsg { } /// All packet messages +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub enum PacketMsg { Recv(MsgRecvPacket), diff --git a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs index 7e414263e..6f448d6fc 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs @@ -16,6 +16,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgAcknowledgement"; /// /// Message definition for packet acknowledgements. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgAcknowledgement { pub packet: Packet, 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 6d73b3492..c40c88c5a 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 @@ -17,6 +17,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelCloseConfirm"; /// datagram). /// Per our convention, this message is sent to chain B. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgChannelCloseConfirm { pub port_id_on_b: PortId, 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 98c8c694c..d3a569217 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 @@ -15,6 +15,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelCloseInit"; /// Message definition for the first step in the channel close handshake (`ChanCloseInit` datagram). /// Per our convention, this message is sent to chain A. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgChannelCloseInit { pub port_id_on_a: PortId, 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 2f8587ef3..9fca241ff 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 @@ -14,6 +14,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenAck"; /// Message definition for the third step in the channel open handshake (`ChanOpenAck` datagram). /// /// Per our convention, this message is sent to chain A. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgChannelOpenAck { pub port_id_on_a: PortId, 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 aeaa39706..4bd43bd39 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 @@ -15,6 +15,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenConfirm"; /// datagram). /// Per our convention, this message is sent to chain B. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgChannelOpenConfirm { pub port_id_on_b: PortId, 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 a7dd63505..08f034eb2 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 @@ -18,6 +18,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenInit"; /// Message definition for the first step in the channel open handshake (`ChanOpenInit` datagram). /// Per our convention, this message is sent to chain A. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgChannelOpenInit { pub port_id_on_a: PortId, 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 1759b2deb..ad0e93ca4 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 @@ -19,6 +19,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenTry"; /// Message definition for the second step in the channel open handshake (`ChanOpenTry` datagram). /// Per our convention, this message is sent to chain B. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgChannelOpenTry { pub port_id_on_b: PortId, 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 ae96fe80f..241c67976 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs @@ -16,6 +16,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgRecvPacket"; /// /// Message definition for the "packet receiving" datagram. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgRecvPacket { /// The packet to be received diff --git a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs index 5595a27ee..b3104bca3 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs @@ -17,6 +17,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgTimeout"; /// Message definition for packet timeout domain type, /// which is sent on chain A and needs to prove that a previously sent packet was not received on chain B /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgTimeout { pub packet: Packet, 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 90401c4c4..e299d9a18 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 @@ -15,6 +15,10 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgTimeoutOnClose"; /// /// Message definition for packet timeout domain type. /// +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgTimeoutOnClose { pub packet: Packet, diff --git a/crates/ibc/src/core/ics23_commitment/commitment.rs b/crates/ibc/src/core/ics23_commitment/commitment.rs index 98a4d5d9a..b5b876b71 100644 --- a/crates/ibc/src/core/ics23_commitment/commitment.rs +++ b/crates/ibc/src/core/ics23_commitment/commitment.rs @@ -61,6 +61,10 @@ impl From> for CommitmentRoot { /// /// For example, in the case of a proof of membership in a Merkle tree, /// this encodes a Merkle proof. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] #[derive(Clone, PartialEq, Eq)] diff --git a/crates/ibc/src/core/msgs.rs b/crates/ibc/src/core/msgs.rs index b15a0a39d..212d08304 100644 --- a/crates/ibc/src/core/msgs.rs +++ b/crates/ibc/src/core/msgs.rs @@ -36,6 +36,10 @@ pub trait Msg: Clone { } /// Enumeration of all messages that the local ICS26 module is capable of routing. +#[cfg_attr( + feature = "borsh", + derive(borsh::BorshSerialize, borsh::BorshDeserialize) +)] #[derive(Clone, Debug)] pub enum MsgEnvelope { Client(ClientMsg), From 2d610b6782a31bc7651fdfb7a0f1cb25cb061977 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Laferri=C3=A8re?= Date: Fri, 1 Sep 2023 09:30:41 -0400 Subject: [PATCH 023/182] derive `PartialEq`, `Eq` for `MsgEnvelope` (#847) * derive PartialEq, Eq * changelog --- .changelog/unreleased/improvements/847-derive-msgenvelope-eq.md | 2 ++ crates/ibc/src/core/ics02_client/msgs.rs | 2 +- crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs | 2 +- crates/ibc/src/core/msgs.rs | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 .changelog/unreleased/improvements/847-derive-msgenvelope-eq.md diff --git a/.changelog/unreleased/improvements/847-derive-msgenvelope-eq.md b/.changelog/unreleased/improvements/847-derive-msgenvelope-eq.md new file mode 100644 index 000000000..e7580e0a7 --- /dev/null +++ b/.changelog/unreleased/improvements/847-derive-msgenvelope-eq.md @@ -0,0 +1,2 @@ +- Derive `PartialEq`, `Eq` for `MsgEnvelope` + ([#847](https://github.com/cosmos/ibc-rs/pull/847)) diff --git a/crates/ibc/src/core/ics02_client/msgs.rs b/crates/ibc/src/core/ics02_client/msgs.rs index b432211c9..b1b29ac82 100644 --- a/crates/ibc/src/core/ics02_client/msgs.rs +++ b/crates/ibc/src/core/ics02_client/msgs.rs @@ -20,7 +20,7 @@ pub mod upgrade_client; feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum ClientMsg { CreateClient(MsgCreateClient), UpdateClient(MsgUpdateClient), 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 c87976e53..f18160f89 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -22,7 +22,7 @@ pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgUpgradeClient"; feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct MsgUpgradeClient { // client unique identifier pub client_id: ClientId, diff --git a/crates/ibc/src/core/msgs.rs b/crates/ibc/src/core/msgs.rs index 212d08304..66a2c6eaf 100644 --- a/crates/ibc/src/core/msgs.rs +++ b/crates/ibc/src/core/msgs.rs @@ -40,7 +40,7 @@ pub trait Msg: Clone { feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize) )] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum MsgEnvelope { Client(ClientMsg), Connection(ConnectionMsg), From dc8e4161dd5e00a2031cf3feb58dad1ed7e26bdb Mon Sep 17 00:00:00 2001 From: Farhad Shabani Date: Tue, 5 Sep 2023 07:24:07 -0700 Subject: [PATCH 024/182] imp: organize imports using `rustfmt.toml` (#849) * imp: organize imports using rustfmt.toml * fix: use nightly toolchain for fmt * fix: add fmt component * nix: add reorder_imports --- .../improvements/848-configure-cargo-fmt.md | 2 + .github/workflows/rust.yml | 3 +- crates/ibc-derive/src/client_state.rs | 8 +-- .../traits/client_state_common.rs | 8 +-- .../traits/client_state_execution.rs | 14 ++--- .../traits/client_state_validation.rs | 14 ++--- crates/ibc-derive/src/consensus_state.rs | 3 +- .../ibc/src/applications/transfer/amount.rs | 13 +++-- crates/ibc/src/applications/transfer/coin.rs | 1 + .../ibc/src/applications/transfer/context.rs | 12 ++-- crates/ibc/src/applications/transfer/denom.rs | 1 - crates/ibc/src/applications/transfer/error.rs | 1 + .../ibc/src/applications/transfer/events.rs | 3 +- crates/ibc/src/applications/transfer/memo.rs | 4 +- .../applications/transfer/msgs/transfer.rs | 7 +-- .../ibc/src/applications/transfer/packet.rs | 8 +-- crates/ibc/src/applications/transfer/relay.rs | 3 +- .../clients/ics07_tendermint/client_state.rs | 38 ++++++------ .../client_state/misbehaviour.rs | 6 +- .../client_state/update_client.rs | 6 +- .../ics07_tendermint/consensus_state.rs | 10 ++-- .../src/clients/ics07_tendermint/context.rs | 16 ++--- .../ibc/src/clients/ics07_tendermint/error.rs | 11 ++-- .../src/clients/ics07_tendermint/header.rs | 8 +-- .../clients/ics07_tendermint/misbehaviour.rs | 3 +- .../ibc/src/clients/ics07_tendermint/mod.rs | 3 +- .../ics07_tendermint/trust_threshold.rs | 6 +- crates/ibc/src/core/context.rs | 21 +++---- crates/ibc/src/core/events.rs | 28 ++++----- crates/ibc/src/core/handler.rs | 58 ++++++++++--------- .../ibc/src/core/ics02_client/client_type.rs | 13 ++--- .../src/core/ics02_client/consensus_state.rs | 9 ++- crates/ibc/src/core/ics02_client/context.rs | 3 +- crates/ibc/src/core/ics02_client/error.rs | 6 +- crates/ibc/src/core/ics02_client/events.rs | 13 +++-- .../ics02_client/handler/create_client.rs | 15 ++--- .../ics02_client/handler/update_client.rs | 21 +++---- .../ics02_client/handler/upgrade_client.rs | 14 ++--- crates/ibc/src/core/ics02_client/height.rs | 6 +- .../core/ics02_client/msgs/create_client.rs | 6 +- .../core/ics02_client/msgs/misbehaviour.rs | 3 +- .../core/ics02_client/msgs/update_client.rs | 11 ++-- .../core/ics02_client/msgs/upgrade_client.rs | 14 ++--- .../src/core/ics03_connection/connection.rs | 11 ++-- crates/ibc/src/core/ics03_connection/delay.rs | 7 ++- crates/ibc/src/core/ics03_connection/error.rs | 9 +-- .../ibc/src/core/ics03_connection/events.rs | 8 ++- .../ibc/src/core/ics03_connection/handler.rs | 6 +- .../ics03_connection/handler/conn_open_ack.rs | 15 +++-- .../handler/conn_open_confirm.rs | 10 ++-- .../handler/conn_open_init.rs | 11 ++-- .../ics03_connection/handler/conn_open_try.rs | 12 ++-- crates/ibc/src/core/ics03_connection/msgs.rs | 5 +- .../ics03_connection/msgs/conn_open_ack.rs | 20 +++---- .../msgs/conn_open_confirm.rs | 19 +++--- .../ics03_connection/msgs/conn_open_init.rs | 22 +++---- .../ics03_connection/msgs/conn_open_try.rs | 34 +++++------ .../ibc/src/core/ics03_connection/version.rs | 11 ++-- .../src/core/ics04_channel/acknowledgement.rs | 4 +- crates/ibc/src/core/ics04_channel/channel.rs | 22 +++---- .../ibc/src/core/ics04_channel/commitment.rs | 3 +- crates/ibc/src/core/ics04_channel/context.rs | 20 +++---- crates/ibc/src/core/ics04_channel/error.rs | 4 +- crates/ibc/src/core/ics04_channel/events.rs | 15 +++-- .../events/channel_attributes.rs | 6 +- .../ics04_channel/events/packet_attributes.rs | 4 +- .../ics04_channel/handler/acknowledgement.rs | 37 +++++------- .../handler/chan_close_confirm.rs | 24 +++----- .../ics04_channel/handler/chan_close_init.rs | 18 +++--- .../ics04_channel/handler/chan_open_ack.rs | 28 ++++----- .../handler/chan_open_confirm.rs | 30 +++++----- .../ics04_channel/handler/chan_open_init.rs | 21 +++---- .../ics04_channel/handler/chan_open_try.rs | 27 ++++----- .../core/ics04_channel/handler/recv_packet.rs | 33 +++++------ .../core/ics04_channel/handler/send_packet.rs | 36 +++++------- .../src/core/ics04_channel/handler/timeout.rs | 40 +++++-------- .../ics04_channel/handler/timeout_on_close.rs | 32 +++++----- crates/ibc/src/core/ics04_channel/msgs.rs | 12 ++-- .../ics04_channel/msgs/acknowledgement.rs | 14 ++--- .../ics04_channel/msgs/chan_close_confirm.rs | 14 ++--- .../ics04_channel/msgs/chan_close_init.rs | 14 ++--- .../core/ics04_channel/msgs/chan_open_ack.rs | 18 +++--- .../ics04_channel/msgs/chan_open_confirm.rs | 18 +++--- .../core/ics04_channel/msgs/chan_open_init.rs | 21 ++++--- .../core/ics04_channel/msgs/chan_open_try.rs | 28 ++++----- .../core/ics04_channel/msgs/recv_packet.rs | 17 +++--- .../src/core/ics04_channel/msgs/timeout.rs | 12 ++-- .../ics04_channel/msgs/timeout_on_close.rs | 5 +- crates/ibc/src/core/ics04_channel/packet.rs | 14 ++--- crates/ibc/src/core/ics04_channel/timeout.rs | 6 +- crates/ibc/src/core/ics04_channel/version.rs | 3 +- .../src/core/ics23_commitment/commitment.rs | 12 ++-- crates/ibc/src/core/ics23_commitment/error.rs | 1 + .../ibc/src/core/ics23_commitment/merkle.rs | 7 +-- crates/ibc/src/core/ics23_commitment/specs.rs | 3 +- crates/ibc/src/core/ics24_host/identifier.rs | 4 +- .../core/ics24_host/identifier/validate.rs | 7 +-- crates/ibc/src/core/ics24_host/path.rs | 11 ++-- crates/ibc/src/core/mod.rs | 10 +--- crates/ibc/src/core/msgs.rs | 5 +- crates/ibc/src/core/router.rs | 5 +- crates/ibc/src/core/timestamp.rs | 8 +-- .../tendermint/upgrade_proposal/events.rs | 1 + .../tendermint/upgrade_proposal/handler.rs | 7 ++- .../hosts/tendermint/upgrade_proposal/plan.rs | 1 + .../tendermint/upgrade_proposal/proposal.rs | 1 + .../hosts/tendermint/validate_self_client.rs | 7 +-- crates/ibc/src/lib.rs | 3 +- crates/ibc/src/mock/client_state.rs | 22 +++---- crates/ibc/src/mock/consensus_state.rs | 6 +- crates/ibc/src/mock/context.rs | 42 ++++++-------- crates/ibc/src/mock/context/clients.rs | 16 +++-- crates/ibc/src/mock/header.rs | 3 +- crates/ibc/src/mock/host.rs | 4 +- crates/ibc/src/mock/ics18_relayer/context.rs | 9 ++- crates/ibc/src/mock/ics18_relayer/error.rs | 3 +- crates/ibc/src/mock/misbehaviour.rs | 3 +- crates/ibc/src/mock/router.rs | 6 +- crates/ibc/src/prelude.rs | 7 +-- crates/ibc/src/signer.rs | 4 +- crates/ibc/src/test.rs | 4 +- crates/ibc/src/test_utils.rs | 3 +- crates/ibc/src/utils/pretty.rs | 3 +- rustfmt.toml | 5 ++ 124 files changed, 658 insertions(+), 828 deletions(-) create mode 100644 .changelog/unreleased/improvements/848-configure-cargo-fmt.md create mode 100644 rustfmt.toml diff --git a/.changelog/unreleased/improvements/848-configure-cargo-fmt.md b/.changelog/unreleased/improvements/848-configure-cargo-fmt.md new file mode 100644 index 000000000..51ad15851 --- /dev/null +++ b/.changelog/unreleased/improvements/848-configure-cargo-fmt.md @@ -0,0 +1,2 @@ +- Organize imports grouping and granularity using `rustfmt.toml` + ([#848](https://github.com/cosmos/ibc-rs/issues/848)) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 740d384c1..4671367c2 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -37,7 +37,8 @@ jobs: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: - toolchain: stable + toolchain: nightly # Since fmt uses unstable features for organizing imports + components: rustfmt override: true - uses: actions-rs/cargo@v1 with: diff --git a/crates/ibc-derive/src/client_state.rs b/crates/ibc-derive/src/client_state.rs index a6bb0e83c..46917ce2e 100644 --- a/crates/ibc-derive/src/client_state.rs +++ b/crates/ibc-derive/src/client_state.rs @@ -4,11 +4,9 @@ use darling::FromDeriveInput; use proc_macro2::TokenStream; use quote::quote; use syn::DeriveInput; - -use traits::{ - client_state_common::impl_ClientStateCommon, client_state_execution::impl_ClientStateExecution, - client_state_validation::impl_ClientStateValidation, -}; +use traits::client_state_common::impl_ClientStateCommon; +use traits::client_state_execution::impl_ClientStateExecution; +use traits::client_state_validation::impl_ClientStateValidation; #[derive(FromDeriveInput)] #[darling(attributes(generics))] diff --git a/crates/ibc-derive/src/client_state/traits/client_state_common.rs b/crates/ibc-derive/src/client_state/traits/client_state_common.rs index b1dc37731..8176743e3 100644 --- a/crates/ibc-derive/src/client_state/traits/client_state_common.rs +++ b/crates/ibc-derive/src/client_state/traits/client_state_common.rs @@ -1,10 +1,8 @@ use proc_macro2::{Ident, TokenStream}; use quote::quote; -use syn::{ - punctuated::{Iter, Punctuated}, - token::Comma, - Variant, -}; +use syn::punctuated::{Iter, Punctuated}; +use syn::token::Comma; +use syn::Variant; use crate::utils::{get_enum_variant_type_path, Imports}; diff --git a/crates/ibc-derive/src/client_state/traits/client_state_execution.rs b/crates/ibc-derive/src/client_state/traits/client_state_execution.rs index 7b6903122..1a92c8f79 100644 --- a/crates/ibc-derive/src/client_state/traits/client_state_execution.rs +++ b/crates/ibc-derive/src/client_state/traits/client_state_execution.rs @@ -1,15 +1,11 @@ use proc_macro2::{Ident, TokenStream}; use quote::quote; -use syn::{ - punctuated::{Iter, Punctuated}, - token::Comma, - Variant, -}; +use syn::punctuated::{Iter, Punctuated}; +use syn::token::Comma; +use syn::Variant; -use crate::{ - client_state::Opts, - utils::{get_enum_variant_type_path, Imports}, -}; +use crate::client_state::Opts; +use crate::utils::{get_enum_variant_type_path, Imports}; pub(crate) fn impl_ClientStateExecution( client_state_enum_name: &Ident, diff --git a/crates/ibc-derive/src/client_state/traits/client_state_validation.rs b/crates/ibc-derive/src/client_state/traits/client_state_validation.rs index 38c8ba397..a0c920bd3 100644 --- a/crates/ibc-derive/src/client_state/traits/client_state_validation.rs +++ b/crates/ibc-derive/src/client_state/traits/client_state_validation.rs @@ -1,15 +1,11 @@ use proc_macro2::{Ident, TokenStream}; use quote::quote; -use syn::{ - punctuated::{Iter, Punctuated}, - token::Comma, - Variant, -}; +use syn::punctuated::{Iter, Punctuated}; +use syn::token::Comma; +use syn::Variant; -use crate::{ - client_state::Opts, - utils::{get_enum_variant_type_path, Imports}, -}; +use crate::client_state::Opts; +use crate::utils::{get_enum_variant_type_path, Imports}; pub(crate) fn impl_ClientStateValidation( client_state_enum_name: &Ident, diff --git a/crates/ibc-derive/src/consensus_state.rs b/crates/ibc-derive/src/consensus_state.rs index 3a00ea2de..99feb69ce 100644 --- a/crates/ibc-derive/src/consensus_state.rs +++ b/crates/ibc-derive/src/consensus_state.rs @@ -1,6 +1,7 @@ use proc_macro2::TokenStream; use quote::quote; -use syn::{punctuated::Iter, DeriveInput, Ident, Variant}; +use syn::punctuated::Iter; +use syn::{DeriveInput, Ident, Variant}; use crate::utils::{get_enum_variant_type_path, Imports}; diff --git a/crates/ibc/src/applications/transfer/amount.rs b/crates/ibc/src/applications/transfer/amount.rs index 9cee50d29..fe21574fa 100644 --- a/crates/ibc/src/applications/transfer/amount.rs +++ b/crates/ibc/src/applications/transfer/amount.rs @@ -1,14 +1,17 @@ //! Contains the `Amount` type, which represents amounts of tokens transferred. -use crate::prelude::*; -use core::{ops::Deref, str::FromStr}; -use derive_more::{Display, From, Into}; +use core::ops::Deref; +use core::str::FromStr; -use super::error::TokenTransferError; +use derive_more::{Display, From, Into}; use primitive_types::U256; +use super::error::TokenTransferError; +#[cfg(feature = "schema")] +use crate::alloc::borrow::ToOwned; #[cfg(feature = "schema")] -use crate::alloc::{borrow::ToOwned, string::String}; +use crate::alloc::string::String; +use crate::prelude::*; /// A type for representing token transfer amounts. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/ibc/src/applications/transfer/coin.rs b/crates/ibc/src/applications/transfer/coin.rs index 7fd429640..406e01b43 100644 --- a/crates/ibc/src/applications/transfer/coin.rs +++ b/crates/ibc/src/applications/transfer/coin.rs @@ -2,6 +2,7 @@ use core::fmt::{Display, Error as FmtError, Formatter}; use core::str::{from_utf8, FromStr}; + use ibc_proto::cosmos::base::v1beta1::Coin as ProtoCoin; use safe_regex::regex; diff --git a/crates/ibc/src/applications/transfer/context.rs b/crates/ibc/src/applications/transfer/context.rs index 6b3b25880..81b4030af 100644 --- a/crates/ibc/src/applications/transfer/context.rs +++ b/crates/ibc/src/applications/transfer/context.rs @@ -1,25 +1,23 @@ //! Defines the main context traits and IBC module callbacks -use crate::prelude::*; - use sha2::{Digest, Sha256}; use super::ack_success_b64; use super::error::TokenTransferError; use crate::applications::transfer::events::{AckEvent, AckStatusEvent, RecvEvent, TimeoutEvent}; use crate::applications::transfer::packet::PacketData; -use crate::applications::transfer::relay::refund_packet_token_execute; +use crate::applications::transfer::relay::on_recv_packet::process_recv_packet_execute; use crate::applications::transfer::relay::{ - on_recv_packet::process_recv_packet_execute, refund_packet_token_validate, + refund_packet_token_execute, refund_packet_token_validate, }; use crate::applications::transfer::{PrefixedCoin, PrefixedDenom, VERSION}; -use crate::core::ics04_channel::acknowledgement::Acknowledgement; -use crate::core::ics04_channel::acknowledgement::AcknowledgementStatus; +use crate::core::ics04_channel::acknowledgement::{Acknowledgement, AcknowledgementStatus}; use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; use crate::core::router::ModuleExtras; use crate::core::ContextError; +use crate::prelude::*; use crate::signer::Signer; /// Methods required in token transfer validation, to be implemented by the host @@ -414,9 +412,9 @@ pub fn on_timeout_packet_execute( #[cfg(test)] pub(crate) mod test { - use super::*; use subtle_encoding::bech32; + use super::*; use crate::applications::transfer::context::cosmos_adr028_escrow_address; use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::Version; diff --git a/crates/ibc/src/applications/transfer/denom.rs b/crates/ibc/src/applications/transfer/denom.rs index 77ab685ee..73d46745d 100644 --- a/crates/ibc/src/applications/transfer/denom.rs +++ b/crates/ibc/src/applications/transfer/denom.rs @@ -9,7 +9,6 @@ use ibc_proto::ibc::applications::transfer::v1::DenomTrace as RawDenomTrace; use super::error::TokenTransferError; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::prelude::*; - #[cfg(feature = "serde")] use crate::serializers::serde_string; diff --git a/crates/ibc/src/applications/transfer/error.rs b/crates/ibc/src/applications/transfer/error.rs index 479820bc7..0c25654ce 100644 --- a/crates/ibc/src/applications/transfer/error.rs +++ b/crates/ibc/src/applications/transfer/error.rs @@ -2,6 +2,7 @@ use core::convert::Infallible; use core::str::Utf8Error; + use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; use uint::FromDecStrErr; diff --git a/crates/ibc/src/applications/transfer/events.rs b/crates/ibc/src/applications/transfer/events.rs index 23476f3d2..45eff108a 100644 --- a/crates/ibc/src/applications/transfer/events.rs +++ b/crates/ibc/src/applications/transfer/events.rs @@ -1,13 +1,12 @@ //! Defines all token transfer event types +use super::Memo; use crate::applications::transfer::{Amount, PrefixedDenom, MODULE_ID_STR}; use crate::core::events::ModuleEvent; use crate::core::ics04_channel::acknowledgement::AcknowledgementStatus; use crate::prelude::*; use crate::signer::Signer; -use super::Memo; - const EVENT_TYPE_PACKET: &str = "fungible_token_packet"; const EVENT_TYPE_TIMEOUT: &str = "timeout"; const EVENT_TYPE_DENOM_TRACE: &str = "denomination_trace"; diff --git a/crates/ibc/src/applications/transfer/memo.rs b/crates/ibc/src/applications/transfer/memo.rs index 04bc75584..3d31f206e 100644 --- a/crates/ibc/src/applications/transfer/memo.rs +++ b/crates/ibc/src/applications/transfer/memo.rs @@ -2,7 +2,9 @@ //! with a token transfer use core::convert::Infallible; -use core::fmt::{self, Display}; +use core::fmt::{ + Display, {self}, +}; use core::str::FromStr; use crate::prelude::*; diff --git a/crates/ibc/src/applications/transfer/msgs/transfer.rs b/crates/ibc/src/applications/transfer/msgs/transfer.rs index a5d9024c5..f3ef9172e 100644 --- a/crates/ibc/src/applications/transfer/msgs/transfer.rs +++ b/crates/ibc/src/applications/transfer/msgs/transfer.rs @@ -1,7 +1,5 @@ //! Defines the token transfer message type -use crate::prelude::*; - use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::applications::transfer::v1::MsgTransfer as RawMsgTransfer; use ibc_proto::protobuf::Protobuf; @@ -13,6 +11,7 @@ use crate::core::ics04_channel::timeout::TimeoutHeight; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::core::timestamp::Timestamp; use crate::core::{ContextError, Msg}; +use crate::prelude::*; pub(crate) const TYPE_URL: &str = "/ibc.applications.transfer.v1.MsgTransfer"; @@ -127,12 +126,10 @@ impl TryFrom for MsgTransfer { #[cfg(test)] pub mod test_util { - use super::*; - use core::ops::Add; use core::time::Duration; - use super::MsgTransfer; + use super::{MsgTransfer, *}; use crate::applications::transfer::packet::PacketData; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::core::ics04_channel::timeout::TimeoutHeight; diff --git a/crates/ibc/src/applications/transfer/packet.rs b/crates/ibc/src/applications/transfer/packet.rs index fdcede335..758af8439 100644 --- a/crates/ibc/src/applications/transfer/packet.rs +++ b/crates/ibc/src/applications/transfer/packet.rs @@ -4,13 +4,12 @@ use alloc::string::ToString; use core::convert::TryFrom; use core::str::FromStr; -#[cfg(feature = "schema")] -use crate::alloc::borrow::ToOwned; - use ibc_proto::ibc::applications::transfer::v2::FungibleTokenPacketData as RawPacketData; use super::error::TokenTransferError; use super::{Amount, Memo, PrefixedCoin, PrefixedDenom}; +#[cfg(feature = "schema")] +use crate::alloc::borrow::ToOwned; use crate::signer::Signer; /// Defines the structure of token transfers' packet bytes @@ -67,10 +66,11 @@ impl From for RawPacketData { #[cfg(test)] mod tests { + use primitive_types::U256; + use super::*; use crate::applications::transfer::BaseCoin; use crate::test_utils::get_dummy_bech32_account; - use primitive_types::U256; impl PacketData { pub fn new_dummy() -> Self { diff --git a/crates/ibc/src/applications/transfer/relay.rs b/crates/ibc/src/applications/transfer/relay.rs index 2d2fce7d1..227ac8243 100644 --- a/crates/ibc/src/applications/transfer/relay.rs +++ b/crates/ibc/src/applications/transfer/relay.rs @@ -1,13 +1,12 @@ //! Implements the processing logic for ICS20 (token transfer) message. +use super::context::{TokenTransferExecutionContext, TokenTransferValidationContext}; 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; use crate::prelude::*; -use super::context::{TokenTransferExecutionContext, TokenTransferValidationContext}; - pub mod on_recv_packet; pub mod send_transfer; diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state.rs b/crates/ibc/src/clients/ics07_tendermint/client_state.rs index 3e60b86b8..f9709e38d 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state.rs @@ -4,8 +4,6 @@ mod misbehaviour; mod update_client; -use crate::prelude::*; - use core::cmp::max; use core::convert::{TryFrom, TryInto}; use core::str::FromStr; @@ -17,12 +15,16 @@ use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; use ibc_proto::ibc::lightclients::tendermint::v1::ClientState as RawTmClientState; use ibc_proto::protobuf::Protobuf; use prost::Message; - use tendermint::chain::id::MAX_LENGTH as MaxChainIdLen; use tendermint::trust_threshold::TrustThresholdFraction as TendermintTrustThresholdFraction; use tendermint_light_client_verifier::options::Options; use tendermint_light_client_verifier::ProdVerifier; +use super::trust_threshold::TrustThreshold; +use super::{ + client_type as tm_client_type, ExecutionContext as TmExecutionContext, + ValidationContext as TmValidationContext, +}; use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; use crate::clients::ics07_tendermint::error::Error; use crate::clients::ics07_tendermint::header::Header as TmHeader; @@ -40,17 +42,13 @@ use crate::core::ics23_commitment::commitment::{ use crate::core::ics23_commitment::merkle::{apply_prefix, MerkleProof}; use crate::core::ics23_commitment::specs::ProofSpecs; use crate::core::ics24_host::identifier::{ChainId, ClientId}; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ClientConsensusStatePath, ClientStatePath, UpgradeClientPath}; +use crate::core::ics24_host::path::{ + ClientConsensusStatePath, ClientStatePath, Path, UpgradeClientPath, +}; use crate::core::timestamp::ZERO_DURATION; +use crate::prelude::*; use crate::Height; -use super::trust_threshold::TrustThreshold; -use super::{ - client_type as tm_client_type, ExecutionContext as TmExecutionContext, - ValidationContext as TmValidationContext, -}; - pub const TENDERMINT_CLIENT_STATE_TYPE_URL: &str = "/ibc.lightclients.tendermint.v1.ClientState"; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -735,9 +733,10 @@ impl TryFrom for ClientState { type Error = ClientError; fn try_from(raw: Any) -> Result { - use bytes::Buf; use core::ops::Deref; + use bytes::Buf; + fn decode_client_state(buf: B) -> Result { RawTmClientState::decode(buf) .map_err(Error::Decode)? @@ -783,22 +782,21 @@ fn check_header_trusted_next_validator_set( #[cfg(test)] mod tests { - use super::*; - - use crate::clients::ics07_tendermint::header::test_util::get_dummy_tendermint_header; - use crate::Height; use core::time::Duration; - use test_log::test; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use ibc_proto::ics23::ProofSpec as Ics23ProofSpec; + use test_log::test; + use super::*; use crate::clients::ics07_tendermint::client_state::AllowUpdate; use crate::clients::ics07_tendermint::error::Error; + use crate::clients::ics07_tendermint::header::test_util::get_dummy_tendermint_header; use crate::core::ics23_commitment::specs::ProofSpecs; use crate::core::ics24_host::identifier::ChainId; use crate::core::timestamp::ZERO_DURATION; + use crate::Height; #[derive(Clone, Debug, PartialEq)] struct ClientStateParams { @@ -1120,10 +1118,11 @@ mod serde_tests { #[cfg(any(test, feature = "mocks"))] pub mod test_util { - use crate::prelude::*; use core::str::FromStr; use core::time::Duration; + use ibc_proto::ibc::core::client::v1::Height as RawHeight; + use ibc_proto::ibc::lightclients::tendermint::v1::{ClientState as RawTmClientState, Fraction}; use tendermint::block::Header; use crate::clients::ics07_tendermint::client_state::{AllowUpdate, ClientState}; @@ -1131,8 +1130,7 @@ pub mod test_util { use crate::core::ics02_client::height::Height; use crate::core::ics23_commitment::specs::ProofSpecs; use crate::core::ics24_host::identifier::ChainId; - use ibc_proto::ibc::core::client::v1::Height as RawHeight; - use ibc_proto::ibc::lightclients::tendermint::v1::{ClientState as RawTmClientState, Fraction}; + use crate::prelude::*; impl ClientState { pub fn new_dummy_from_raw(frozen_height: RawHeight) -> Result { diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state/misbehaviour.rs b/crates/ibc/src/clients/ics07_tendermint/client_state/misbehaviour.rs index 5dc2aa02e..9e3c3141a 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state/misbehaviour.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state/misbehaviour.rs @@ -1,7 +1,6 @@ use tendermint_light_client_verifier::Verifier; -use crate::prelude::*; - +use super::{check_header_trusted_next_validator_set, ClientState}; use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; use crate::clients::ics07_tendermint::error::{Error, IntoResult}; use crate::clients::ics07_tendermint::header::Header as TmHeader; @@ -12,8 +11,7 @@ use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ClientId; use crate::core::ics24_host::path::ClientConsensusStatePath; use crate::core::timestamp::Timestamp; - -use super::{check_header_trusted_next_validator_set, ClientState}; +use crate::prelude::*; impl ClientState { // verify_misbehaviour determines whether or not two conflicting headers at diff --git a/crates/ibc/src/clients/ics07_tendermint/client_state/update_client.rs b/crates/ibc/src/clients/ics07_tendermint/client_state/update_client.rs index 86050de97..34c10e464 100644 --- a/crates/ibc/src/clients/ics07_tendermint/client_state/update_client.rs +++ b/crates/ibc/src/clients/ics07_tendermint/client_state/update_client.rs @@ -1,8 +1,7 @@ -use crate::prelude::*; - use tendermint_light_client_verifier::types::{TrustedBlockState, UntrustedBlockState}; use tendermint_light_client_verifier::Verifier; +use super::{check_header_trusted_next_validator_set, ClientState}; use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; use crate::clients::ics07_tendermint::error::{Error, IntoResult}; use crate::clients::ics07_tendermint::header::Header as TmHeader; @@ -10,8 +9,7 @@ use crate::clients::ics07_tendermint::ValidationContext as TmValidationContext; use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ClientId; use crate::core::ics24_host::path::ClientConsensusStatePath; - -use super::{check_header_trusted_next_validator_set, ClientState}; +use crate::prelude::*; impl ClientState { pub fn verify_header( diff --git a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs index b5b7f476e..39c654364 100644 --- a/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs +++ b/crates/ibc/src/clients/ics07_tendermint/consensus_state.rs @@ -1,11 +1,11 @@ //! Defines Tendermint's `ConsensusState` type -use crate::prelude::*; - use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::ConsensusState as RawConsensusState; use ibc_proto::protobuf::Protobuf; -use tendermint::{hash::Algorithm, time::Time, Hash}; +use tendermint::hash::Algorithm; +use tendermint::time::Time; +use tendermint::Hash; use tendermint_proto::google::protobuf as tpb; use crate::clients::ics07_tendermint::error::Error; @@ -14,6 +14,7 @@ use crate::core::ics02_client::consensus_state::ConsensusState as ConsensusState use crate::core::ics02_client::error::ClientError; use crate::core::ics23_commitment::commitment::CommitmentRoot; use crate::core::timestamp::Timestamp; +use crate::prelude::*; pub const TENDERMINT_CONSENSUS_STATE_TYPE_URL: &str = "/ibc.lightclients.tendermint.v1.ConsensusState"; @@ -99,8 +100,9 @@ impl TryFrom for ConsensusState { type Error = ClientError; fn try_from(raw: Any) -> Result { - use bytes::Buf; use core::ops::Deref; + + use bytes::Buf; use prost::Message; fn decode_consensus_state(buf: B) -> Result { diff --git a/crates/ibc/src/clients/ics07_tendermint/context.rs b/crates/ibc/src/clients/ics07_tendermint/context.rs index 3c3674389..b62cc1680 100644 --- a/crates/ibc/src/clients/ics07_tendermint/context.rs +++ b/crates/ibc/src/clients/ics07_tendermint/context.rs @@ -1,16 +1,12 @@ use alloc::string::ToString; -use crate::{ - core::{ - ics02_client::ClientExecutionContext, - ics24_host::{identifier::ClientId, path::ClientConsensusStatePath}, - timestamp::Timestamp, - ContextError, - }, - Height, -}; - use super::consensus_state::ConsensusState as TmConsensusState; +use crate::core::ics02_client::ClientExecutionContext; +use crate::core::ics24_host::identifier::ClientId; +use crate::core::ics24_host::path::ClientConsensusStatePath; +use crate::core::timestamp::Timestamp; +use crate::core::ContextError; +use crate::Height; /// Client's context required during both validation and execution pub trait CommonContext { diff --git a/crates/ibc/src/clients/ics07_tendermint/error.rs b/crates/ibc/src/clients/ics07_tendermint/error.rs index f89878f91..135cb1948 100644 --- a/crates/ibc/src/clients/ics07_tendermint/error.rs +++ b/crates/ibc/src/clients/ics07_tendermint/error.rs @@ -1,11 +1,5 @@ //! Defines the Tendermint light client's error type -use crate::prelude::*; - -use crate::core::ics02_client::error::ClientError; -use crate::core::ics24_host::identifier::{ClientId, IdentifierError}; -use crate::Height; - use core::time::Duration; use displaydoc::Display; @@ -14,6 +8,11 @@ use tendermint_light_client_verifier::errors::VerificationErrorDetail as LightCl use tendermint_light_client_verifier::operations::VotingPowerTally; use tendermint_light_client_verifier::Verdict; +use crate::core::ics02_client::error::ClientError; +use crate::core::ics24_host::identifier::{ClientId, IdentifierError}; +use crate::prelude::*; +use crate::Height; + /// The main error type #[derive(Debug, Display)] pub enum Error { diff --git a/crates/ibc/src/clients/ics07_tendermint/header.rs b/crates/ibc/src/clients/ics07_tendermint/header.rs index d24cf409c..614f4dd5a 100644 --- a/crates/ibc/src/clients/ics07_tendermint/header.rs +++ b/crates/ibc/src/clients/ics07_tendermint/header.rs @@ -1,6 +1,5 @@ //! Defines the domain type for tendermint headers -use crate::prelude::*; use alloc::string::ToString; use core::fmt::{Display, Error as FmtError, Formatter}; use core::str::FromStr; @@ -9,6 +8,7 @@ use bytes::Buf; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Header as RawHeader; use ibc_proto::protobuf::Protobuf; +use pretty::{PrettySignedHeader, PrettyValidatorSet}; use prost::Message; use tendermint::block::signed_header::SignedHeader; use tendermint::chain::Id as TmChainId; @@ -20,10 +20,9 @@ use crate::clients::ics07_tendermint::error::Error; use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ChainId; use crate::core::timestamp::Timestamp; +use crate::prelude::*; use crate::Height; -use pretty::{PrettySignedHeader, PrettyValidatorSet}; - pub(crate) const TENDERMINT_HEADER_TYPE_URL: &str = "/ibc.lightclients.tendermint.v1.Header"; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -263,8 +262,7 @@ pub mod test_util { use subtle_encoding::hex; use tendermint::block::signed_header::SignedHeader; - use tendermint::validator::Info as ValidatorInfo; - use tendermint::validator::Set as ValidatorSet; + use tendermint::validator::{Info as ValidatorInfo, Set as ValidatorSet}; use tendermint::PublicKey; use crate::clients::ics07_tendermint::header::Header; diff --git a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs index d81a47621..646eb6781 100644 --- a/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs +++ b/crates/ibc/src/clients/ics07_tendermint/misbehaviour.rs @@ -1,7 +1,5 @@ //! Defines the misbehaviour type for the tendermint light client -use crate::prelude::*; - use bytes::Buf; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::lightclients::tendermint::v1::Misbehaviour as RawMisbehaviour; @@ -12,6 +10,7 @@ use crate::clients::ics07_tendermint::error::Error; use crate::clients::ics07_tendermint::header::Header; use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ClientId; +use crate::prelude::*; const TENDERMINT_MISBEHAVIOUR_TYPE_URL: &str = "/ibc.lightclients.tendermint.v1.Misbehaviour"; diff --git a/crates/ibc/src/clients/ics07_tendermint/mod.rs b/crates/ibc/src/clients/ics07_tendermint/mod.rs index 2bb58ec4b..803e7814e 100644 --- a/crates/ibc/src/clients/ics07_tendermint/mod.rs +++ b/crates/ibc/src/clients/ics07_tendermint/mod.rs @@ -1,9 +1,10 @@ //! ICS 07: Tendermint Client implements a client verification algorithm for blockchains which use //! the Tendermint consensus algorithm. -use crate::core::ics02_client::client_type::ClientType; use core::str::FromStr; +use crate::core::ics02_client::client_type::ClientType; + pub mod client_state; pub mod consensus_state; pub mod error; diff --git a/crates/ibc/src/clients/ics07_tendermint/trust_threshold.rs b/crates/ibc/src/clients/ics07_tendermint/trust_threshold.rs index 2ae58f3d6..d4e4e9c86 100644 --- a/crates/ibc/src/clients/ics07_tendermint/trust_threshold.rs +++ b/crates/ibc/src/clients/ics07_tendermint/trust_threshold.rs @@ -2,10 +2,8 @@ //! represented as a fraction with valid values in the //! range `[0, 1)`. -use core::{ - convert::TryFrom, - fmt::{Display, Error as FmtError, Formatter}, -}; +use core::convert::TryFrom; +use core::fmt::{Display, Error as FmtError, Formatter}; use ibc_proto::ibc::lightclients::tendermint::v1::Fraction; use ibc_proto::protobuf::Protobuf; diff --git a/crates/ibc/src/core/context.rs b/crates/ibc/src/core/context.rs index b74437af1..9d9ae5e77 100644 --- a/crates/ibc/src/core/context.rs +++ b/crates/ibc/src/core/context.rs @@ -1,12 +1,14 @@ -use crate::prelude::*; - -use crate::signer::Signer; use alloc::string::String; use core::time::Duration; + use derive_more::From; use displaydoc::Display; use ibc_proto::google::protobuf::Any; +use super::ics02_client::client_state::ClientState; +use super::ics02_client::consensus_state::ConsensusState; +use super::ics02_client::ClientExecutionContext; +use super::ics24_host::identifier::PortId; use crate::core::events::IbcEvent; use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::ConnectionEnd; @@ -17,24 +19,19 @@ use crate::core::ics03_connection::version::{ use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment}; use crate::core::ics04_channel::context::calculate_block_delay; -use crate::core::ics04_channel::error::ChannelError; -use crate::core::ics04_channel::error::PacketError; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::packet::{Receipt, Sequence}; use crate::core::ics23_commitment::commitment::CommitmentPrefix; -use crate::core::ics24_host::identifier::ClientId; -use crate::core::ics24_host::identifier::ConnectionId; +use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; use crate::core::ics24_host::path::{ AckPath, ChannelEndPath, ClientConnectionPath, ClientConsensusStatePath, CommitmentPath, ConnectionPath, ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, }; use crate::core::timestamp::Timestamp; +use crate::prelude::*; +use crate::signer::Signer; use crate::Height; -use super::ics02_client::client_state::ClientState; -use super::ics02_client::consensus_state::ConsensusState; -use super::ics02_client::ClientExecutionContext; -use super::ics24_host::identifier::PortId; - /// Top-level error #[derive(Debug, Display, From)] pub enum ContextError { diff --git a/crates/ibc/src/core/events.rs b/crates/ibc/src/core/events.rs index 0d8d654a9..6b451c960 100644 --- a/crates/ibc/src/core/events.rs +++ b/crates/ibc/src/core/events.rs @@ -1,20 +1,17 @@ //! Events emitted during message handling -use crate::prelude::*; - use core::convert::{TryFrom, TryInto}; + use displaydoc::Display; use tendermint::abci; +use super::ics24_host::identifier::IdentifierError; use crate::core::ics02_client::error as client_error; use crate::core::ics02_client::events::{self as ClientEvents}; -use crate::core::ics03_connection::error as connection_error; -use crate::core::ics03_connection::events as ConnectionEvents; -use crate::core::ics04_channel::error as channel_error; -use crate::core::ics04_channel::events as ChannelEvents; +use crate::core::ics03_connection::{error as connection_error, events as ConnectionEvents}; +use crate::core::ics04_channel::{error as channel_error, events as ChannelEvents}; use crate::core::timestamp::ParseTimestampError; - -use super::ics24_host::identifier::IdentifierError; +use crate::prelude::*; /// All error variants related to IBC events #[derive(Debug, Display)] @@ -284,17 +281,14 @@ impl From for IbcEvent { #[cfg(test)] pub mod tests { - use super::*; use alloc::vec; - use crate::core::{ - ics04_channel::{ - channel::Order, - events::SendPacket, - packet::{test_utils::get_dummy_raw_packet, Packet}, - }, - ics24_host::identifier::ConnectionId, - }; + use super::*; + use crate::core::ics04_channel::channel::Order; + use crate::core::ics04_channel::events::SendPacket; + use crate::core::ics04_channel::packet::test_utils::get_dummy_raw_packet; + use crate::core::ics04_channel::packet::Packet; + use crate::core::ics24_host::identifier::ConnectionId; #[test] /// Ensures that we don't panic when packet data is not valid UTF-8. diff --git a/crates/ibc/src/core/handler.rs b/crates/ibc/src/core/handler.rs index faa3216a6..5ddebcf97 100644 --- a/crates/ibc/src/core/handler.rs +++ b/crates/ibc/src/core/handler.rs @@ -202,51 +202,53 @@ where #[cfg(test)] mod tests { - use super::*; - use core::default::Default; use core::time::Duration; use test_log::test; + use super::*; use crate::applications::transfer::error::TokenTransferError; - use crate::applications::transfer::send_transfer; - use crate::applications::transfer::{msgs::transfer::MsgTransfer, MODULE_ID_STR}; + use crate::applications::transfer::msgs::transfer::MsgTransfer; + use crate::applications::transfer::{send_transfer, MODULE_ID_STR}; use crate::core::dispatch; use crate::core::events::{IbcEvent, MessageEvent}; - use crate::core::ics02_client::msgs::{ - create_client::MsgCreateClient, update_client::MsgUpdateClient, - upgrade_client::MsgUpgradeClient, ClientMsg, - }; + use crate::core::ics02_client::msgs::create_client::MsgCreateClient; + use crate::core::ics02_client::msgs::update_client::MsgUpdateClient; + use crate::core::ics02_client::msgs::upgrade_client::MsgUpgradeClient; + use crate::core::ics02_client::msgs::ClientMsg; use crate::core::ics03_connection::connection::{ ConnectionEnd, Counterparty as ConnCounterparty, State as ConnState, }; - use crate::core::ics03_connection::msgs::{ - conn_open_ack::MsgConnectionOpenAck, conn_open_init::MsgConnectionOpenInit, - conn_open_try::MsgConnectionOpenTry, ConnectionMsg, - }; + use crate::core::ics03_connection::msgs::conn_open_ack::MsgConnectionOpenAck; + use crate::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; + use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry; + use crate::core::ics03_connection::msgs::ConnectionMsg; use crate::core::ics03_connection::version::Version as ConnVersion; - use crate::core::ics04_channel::channel::ChannelEnd; - use crate::core::ics04_channel::channel::Counterparty as ChannelCounterparty; - use crate::core::ics04_channel::channel::Order as ChannelOrder; - use crate::core::ics04_channel::channel::State as ChannelState; + use crate::core::ics04_channel::channel::{ + ChannelEnd, Counterparty as ChannelCounterparty, Order as ChannelOrder, + State as ChannelState, + }; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::msgs::acknowledgement::test_util::get_dummy_raw_msg_ack_with_packet; use crate::core::ics04_channel::msgs::acknowledgement::MsgAcknowledgement; + use crate::core::ics04_channel::msgs::chan_close_confirm::test_util::get_dummy_raw_msg_chan_close_confirm; + use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm; + use crate::core::ics04_channel::msgs::chan_close_init::test_util::get_dummy_raw_msg_chan_close_init; + use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit; + use crate::core::ics04_channel::msgs::chan_open_ack::test_util::get_dummy_raw_msg_chan_open_ack; + use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; use crate::core::ics04_channel::msgs::chan_open_confirm::test_util::get_dummy_raw_msg_chan_open_confirm; use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm; - use crate::core::ics04_channel::msgs::{ - chan_close_confirm::{ - test_util::get_dummy_raw_msg_chan_close_confirm, MsgChannelCloseConfirm, - }, - chan_close_init::{test_util::get_dummy_raw_msg_chan_close_init, MsgChannelCloseInit}, - chan_open_ack::{test_util::get_dummy_raw_msg_chan_open_ack, MsgChannelOpenAck}, - chan_open_init::{test_util::get_dummy_raw_msg_chan_open_init, MsgChannelOpenInit}, - chan_open_try::{test_util::get_dummy_raw_msg_chan_open_try, MsgChannelOpenTry}, - recv_packet::{test_util::get_dummy_raw_msg_recv_packet, MsgRecvPacket}, - timeout_on_close::{test_util::get_dummy_raw_msg_timeout_on_close, MsgTimeoutOnClose}, - ChannelMsg, PacketMsg, - }; + use crate::core::ics04_channel::msgs::chan_open_init::test_util::get_dummy_raw_msg_chan_open_init; + use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; + use crate::core::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try; + use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; + 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::core::ics04_channel::msgs::timeout_on_close::test_util::get_dummy_raw_msg_timeout_on_close; + use crate::core::ics04_channel::msgs::timeout_on_close::MsgTimeoutOnClose; + use crate::core::ics04_channel::msgs::{ChannelMsg, PacketMsg}; use crate::core::ics04_channel::timeout::TimeoutHeight; use crate::core::ics04_channel::Version as ChannelVersion; use crate::core::ics23_commitment::commitment::CommitmentPrefix; diff --git a/crates/ibc/src/core/ics02_client/client_type.rs b/crates/ibc/src/core/ics02_client/client_type.rs index d842e84b3..b223fbdae 100644 --- a/crates/ibc/src/core/ics02_client/client_type.rs +++ b/crates/ibc/src/core/ics02_client/client_type.rs @@ -1,14 +1,11 @@ //! Defines the `ClientType` format, typically used in chain IDs. +use core::fmt::{Display, Error as FmtError, Formatter}; +use core::str::FromStr; + +use crate::core::ics24_host::identifier::validate::validate_client_type; +use crate::core::ics24_host::identifier::IdentifierError; use crate::prelude::*; -use core::{ - fmt::{Display, Error as FmtError, Formatter}, - str::FromStr, -}; - -use crate::core::ics24_host::{ - identifier::validate::validate_client_type, identifier::IdentifierError, -}; #[cfg_attr( feature = "parity-scale-codec", diff --git a/crates/ibc/src/core/ics02_client/consensus_state.rs b/crates/ibc/src/core/ics02_client/consensus_state.rs index 377272b0d..17a4ebbec 100644 --- a/crates/ibc/src/core/ics02_client/consensus_state.rs +++ b/crates/ibc/src/core/ics02_client/consensus_state.rs @@ -1,16 +1,15 @@ //! Defines the trait to be implemented by all concrete consensus state types -use crate::prelude::*; - use core::marker::{Send, Sync}; -use crate::core::ics23_commitment::commitment::CommitmentRoot; -use crate::core::timestamp::Timestamp; - /// Derive macro that implements [`ConsensusState`] for enums containing /// variants that implement [`ConsensusState`] pub use ibc_derive::ConsensusState; +use crate::core::ics23_commitment::commitment::CommitmentRoot; +use crate::core::timestamp::Timestamp; +use crate::prelude::*; + /// Defines methods that all `ConsensusState`s should provide. /// /// One can think of a "consensus state" as a pruned header, to be stored on chain. In other words, diff --git a/crates/ibc/src/core/ics02_client/context.rs b/crates/ibc/src/core/ics02_client/context.rs index 4423d4690..f07c51e9e 100644 --- a/crates/ibc/src/core/ics02_client/context.rs +++ b/crates/ibc/src/core/ics02_client/context.rs @@ -1,7 +1,6 @@ use super::client_state::ClientState; use super::consensus_state::ConsensusState; -use crate::core::ics24_host::path::ClientConsensusStatePath; -use crate::core::ics24_host::path::ClientStatePath; +use crate::core::ics24_host::path::{ClientConsensusStatePath, ClientStatePath}; use crate::core::ContextError; /// Defines the methods that all client `ExecutionContext`s (precisely the diff --git a/crates/ibc/src/core/ics02_client/error.rs b/crates/ibc/src/core/ics02_client/error.rs index 826341c34..c055863cf 100644 --- a/crates/ibc/src/core/ics02_client/error.rs +++ b/crates/ibc/src/core/ics02_client/error.rs @@ -1,19 +1,17 @@ //! Defines the client error type -use crate::prelude::*; - use displaydoc::Display; use ibc_proto::protobuf::Error as TendermintProtoError; +use super::client_state::Status; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics24_host::identifier::{ClientId, IdentifierError}; use crate::core::timestamp::Timestamp; use crate::core::ContextError; +use crate::prelude::*; use crate::Height; -use super::client_state::Status; - /// Encodes all the possible client errors #[derive(Debug, Display)] pub enum ClientError { diff --git a/crates/ibc/src/core/ics02_client/events.rs b/crates/ibc/src/core/ics02_client/events.rs index 01e4c586a..8b9f027cb 100644 --- a/crates/ibc/src/core/ics02_client/events.rs +++ b/crates/ibc/src/core/ics02_client/events.rs @@ -1,6 +1,4 @@ //! Types for the IBC events emitted from Tendermint Websocket by the client module. -use crate::prelude::*; - use derive_more::From; use subtle_encoding::hex; use tendermint::abci; @@ -8,6 +6,7 @@ use tendermint::abci; use crate::core::ics02_client::client_type::ClientType; use crate::core::ics02_client::height::Height; use crate::core::ics24_host::identifier::ClientId; +use crate::prelude::*; /// Client event types const CREATE_CLIENT_EVENT: &str = "create_client"; @@ -421,14 +420,16 @@ impl From for abci::Event { #[cfg(test)] mod tests { - use super::*; - use crate::core::timestamp::Timestamp; - use crate::mock::header::MockHeader; + use std::str::FromStr; + use ibc_proto::google::protobuf::Any; use prost::Message; - use std::str::FromStr; use tendermint::abci::Event as AbciEvent; + use super::*; + use crate::core::timestamp::Timestamp; + use crate::mock::header::MockHeader; + #[test] fn ibc_to_abci_client_events() { struct Test { 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 e3ee280ab..ff770a22b 100644 --- a/crates/ibc/src/core/ics02_client/handler/create_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/create_client.rs @@ -1,18 +1,14 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgCreateClient`. -use crate::prelude::*; - use crate::core::context::ContextError; -use crate::core::events::IbcEvent; -use crate::core::events::MessageEvent; -use crate::core::ics02_client::client_state::ClientStateCommon; -use crate::core::ics02_client::client_state::ClientStateExecution; +use crate::core::events::{IbcEvent, MessageEvent}; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateExecution}; use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::events::CreateClient; use crate::core::ics02_client::msgs::create_client::MsgCreateClient; use crate::core::ics24_host::identifier::ClientId; -use crate::core::ExecutionContext; -use crate::core::ValidationContext; +use crate::core::{ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn validate(ctx: &Ctx, msg: MsgCreateClient) -> Result<(), ContextError> where @@ -104,10 +100,9 @@ where #[cfg(test)] mod tests { - use super::*; - use test_log::test; + use super::*; use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState; use crate::clients::ics07_tendermint::client_type as tm_client_type; use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; 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 d0e2e0712..1aa200b1e 100644 --- a/crates/ibc/src/core/ics02_client/handler/update_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/update_client.rs @@ -1,18 +1,17 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgUpdateAnyClient`. -use crate::prelude::*; use prost::Message; use crate::core::context::ContextError; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateCommon; -use crate::core::ics02_client::client_state::ClientStateExecution; -use crate::core::ics02_client::client_state::ClientStateValidation; -use crate::core::ics02_client::client_state::UpdateKind; +use crate::core::ics02_client::client_state::{ + ClientStateCommon, ClientStateExecution, ClientStateValidation, UpdateKind, +}; use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::events::{ClientMisbehaviour, UpdateClient}; use crate::core::ics02_client::msgs::MsgUpdateOrMisbehaviour; use crate::core::{ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn validate(ctx: &Ctx, msg: MsgUpdateOrMisbehaviour) -> Result<(), ContextError> where @@ -133,13 +132,14 @@ where #[cfg(test)] mod tests { - use super::*; - use core::str::FromStr; use core::time::Duration; + use ibc_proto::google::protobuf::Any; + use ibc_proto::ibc::lightclients::tendermint::v1::{ClientState as RawTmClientState, Fraction}; use test_log::test; + use super::*; use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState; use crate::clients::ics07_tendermint::client_type as tm_client_type; use crate::clients::ics07_tendermint::header::Header as TmHeader; @@ -152,16 +152,13 @@ mod tests { use crate::core::ics23_commitment::specs::ProofSpecs; use crate::core::ics24_host::identifier::{ChainId, ClientId}; use crate::core::timestamp::Timestamp; - use crate::downcast; - use crate::mock::client_state::client_type as mock_client_type; - use crate::mock::client_state::MockClientState; + use crate::mock::client_state::{client_type as mock_client_type, MockClientState}; use crate::mock::context::{AnyConsensusState, MockContext}; use crate::mock::header::MockHeader; use crate::mock::host::{HostBlock, HostType}; use crate::mock::misbehaviour::Misbehaviour as MockMisbehaviour; use crate::test_utils::get_dummy_account_id; - use crate::Height; - use ibc_proto::ibc::lightclients::tendermint::v1::{ClientState as RawTmClientState, Fraction}; + use crate::{downcast, Height}; #[test] fn test_update_client_ok() { 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 3980d5b77..5e43dc008 100644 --- a/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/handler/upgrade_client.rs @@ -1,17 +1,17 @@ //! Protocol logic specific to processing ICS2 messages of type `MsgUpgradeAnyClient`. //! -use crate::prelude::*; - use crate::core::context::ContextError; use crate::core::events::{IbcEvent, MessageEvent}; -use crate::core::ics02_client::client_state::ClientStateExecution; -use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; +use crate::core::ics02_client::client_state::{ + ClientStateCommon, ClientStateExecution, ClientStateValidation, +}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; use crate::core::ics02_client::events::UpgradeClient; use crate::core::ics02_client::msgs::upgrade_client::MsgUpgradeClient; use crate::core::ics24_host::path::ClientConsensusStatePath; use crate::core::{ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn validate(ctx: &Ctx, msg: MsgUpgradeClient) -> Result<(), ContextError> where @@ -85,19 +85,15 @@ where #[cfg(test)] mod tests { use super::*; - use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState; use crate::clients::ics07_tendermint::client_type; use crate::clients::ics07_tendermint::header::test_util::get_dummy_tendermint_header; - use crate::core::ics02_client::error::UpgradeClientError; use crate::core::ics03_connection::handler::test_util::{Expect, Fixture}; use crate::core::ics24_host::identifier::ClientId; - use crate::downcast; - use crate::Height; - use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::{AnyClientState, AnyConsensusState, MockContext}; + use crate::{downcast, Height}; enum Ctx { Default, diff --git a/crates/ibc/src/core/ics02_client/height.rs b/crates/ibc/src/core/ics02_client/height.rs index 21297a49d..469337917 100644 --- a/crates/ibc/src/core/ics02_client/height.rs +++ b/crates/ibc/src/core/ics02_client/height.rs @@ -1,17 +1,15 @@ //! Defines the core `Height` type used throughout the library -use crate::prelude::*; use core::cmp::Ordering; - use core::num::ParseIntError; use core::str::FromStr; use displaydoc::Display; -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::client::v1::Height as RawHeight; +use ibc_proto::protobuf::Protobuf; use crate::core::ics02_client::error::ClientError; +use crate::prelude::*; /// The core IBC height type, which represents the height of a chain, /// which typically is the number of blocks since genesis 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 c55e8668c..93cbc126f 100644 --- a/crates/ibc/src/core/ics02_client/msgs/create_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/create_client.rs @@ -1,13 +1,12 @@ //! Definition of domain type message `MsgCreateClient`. -use crate::prelude::*; - 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::ClientError; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgCreateClient"; @@ -75,9 +74,8 @@ impl From for RawMsgCreateClient { #[cfg(test)] mod tests { - use test_log::test; - use ibc_proto::ibc::core::client::v1::MsgCreateClient as RawMsgCreateClient; + use test_log::test; use crate::clients::ics07_tendermint::client_state::ClientState as TmClientState; use crate::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; diff --git a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs index 6ab10266b..02fe61905 100644 --- a/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs +++ b/crates/ibc/src/core/ics02_client/msgs/misbehaviour.rs @@ -1,7 +1,5 @@ //! Definition of domain type message `MsgSubmitMisbehaviour`. -use crate::prelude::*; - use ibc_proto::google::protobuf::Any as ProtoAny; use ibc_proto::ibc::core::client::v1::MsgSubmitMisbehaviour as RawMsgSubmitMisbehaviour; use ibc_proto::protobuf::Protobuf; @@ -9,6 +7,7 @@ use ibc_proto::protobuf::Protobuf; use crate::core::ics02_client::error::ClientError; use crate::core::ics24_host::identifier::ClientId; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgSubmitMisbehaviour"; 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 74e365a44..36ef02b36 100644 --- a/crates/ibc/src/core/ics02_client/msgs/update_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/update_client.rs @@ -1,14 +1,13 @@ //! Definition of domain type message `MsgUpdateClient`. -use crate::core::Msg; -use crate::prelude::*; - 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::ClientError; use crate::core::ics24_host::identifier::ClientId; +use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgUpdateClient"; @@ -67,13 +66,11 @@ impl From for RawMsgUpdateClient { #[cfg(test)] mod tests { - use super::*; - - use test_log::test; - use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::client::v1::MsgUpdateClient as RawMsgUpdateClient; + use test_log::test; + use super::*; use crate::clients::ics07_tendermint::header::test_util::get_dummy_ics07_header; use crate::core::ics02_client::msgs::MsgUpdateClient; use crate::core::ics24_host::identifier::ClientId; 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 f18160f89..55da7a238 100644 --- a/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs +++ b/crates/ibc/src/core/ics02_client/msgs/upgrade_client.rs @@ -1,7 +1,5 @@ //! Definition of domain type msg `MsgUpgradeClient`. -use crate::prelude::*; - use core::str::FromStr; use ibc_proto::google::protobuf::Any; @@ -13,6 +11,7 @@ use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics24_host::identifier::ClientId; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.client.v1.MsgUpgradeClient"; @@ -100,13 +99,12 @@ impl TryFrom for MsgUpgradeClient { #[cfg(test)] pub mod test_util { use super::*; - + use crate::core::ics02_client::height::Height; use crate::core::ics23_commitment::commitment::test_util::get_dummy_commitment_proof_bytes; - use crate::core::{ics02_client::height::Height, ics24_host::identifier::ClientId}; - use crate::mock::client_state::client_type as mock_client_type; - use crate::mock::{ - client_state::MockClientState, consensus_state::MockConsensusState, header::MockHeader, - }; + use crate::core::ics24_host::identifier::ClientId; + use crate::mock::client_state::{client_type as mock_client_type, MockClientState}; + use crate::mock::consensus_state::MockConsensusState; + use crate::mock::header::MockHeader; use crate::test_utils::{get_dummy_account_id, get_dummy_bech32_account, get_dummy_proof}; /// Extends the implementation with additional helper methods. diff --git a/crates/ibc/src/core/ics03_connection/connection.rs b/crates/ibc/src/core/ics03_connection/connection.rs index 6ab1513ec..bfb73b645 100644 --- a/crates/ibc/src/core/ics03_connection/connection.rs +++ b/crates/ibc/src/core/ics03_connection/connection.rs @@ -1,18 +1,14 @@ //! Defines the types that define a connection -use crate::prelude::*; -use ibc_proto::protobuf::Protobuf; - +use core::fmt::{Display, Error as FmtError, Formatter}; use core::time::Duration; -use core::{ - fmt::{Display, Error as FmtError, Formatter}, - u64, -}; +use core::u64; use ibc_proto::ibc::core::connection::v1::{ ConnectionEnd as RawConnectionEnd, Counterparty as RawCounterparty, IdentifiedConnection as RawIdentifiedConnection, }; +use ibc_proto::protobuf::Protobuf; use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::error::ConnectionError; @@ -20,6 +16,7 @@ use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentPrefix; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; use crate::core::timestamp::ZERO_DURATION; +use crate::prelude::*; #[cfg_attr( feature = "parity-scale-codec", diff --git a/crates/ibc/src/core/ics03_connection/delay.rs b/crates/ibc/src/core/ics03_connection/delay.rs index 4536a6d2b..067a84282 100644 --- a/crates/ibc/src/core/ics03_connection/delay.rs +++ b/crates/ibc/src/core/ics03_connection/delay.rs @@ -1,6 +1,7 @@ -use crate::core::{ics02_client::height::Height, ContextError, ValidationContext}; - -use super::{connection::ConnectionEnd, error::ConnectionError}; +use super::connection::ConnectionEnd; +use super::error::ConnectionError; +use crate::core::ics02_client::height::Height; +use crate::core::{ContextError, ValidationContext}; pub fn verify_conn_delay_passed( ctx: &Ctx, diff --git a/crates/ibc/src/core/ics03_connection/error.rs b/crates/ibc/src/core/ics03_connection/error.rs index 28512f9dd..3364a274c 100644 --- a/crates/ibc/src/core/ics03_connection/error.rs +++ b/crates/ibc/src/core/ics03_connection/error.rs @@ -1,15 +1,16 @@ //! Defines the connection error type +use alloc::string::String; + +use displaydoc::Display; +use ibc_proto::protobuf::Error as ProtoError; + use crate::core::ics02_client::error as client_error; use crate::core::ics03_connection::version::Version; use crate::core::ics24_host::identifier::{ClientId, ConnectionId, IdentifierError}; use crate::core::timestamp::{Timestamp, TimestampOverflowError}; use crate::Height; -use alloc::string::String; -use displaydoc::Display; -use ibc_proto::protobuf::Error as ProtoError; - #[derive(Debug, Display)] pub enum ConnectionError { /// client error: `{0}` diff --git a/crates/ibc/src/core/ics03_connection/events.rs b/crates/ibc/src/core/ics03_connection/events.rs index ed8dcd2c9..dcc0f38f9 100644 --- a/crates/ibc/src/core/ics03_connection/events.rs +++ b/crates/ibc/src/core/ics03_connection/events.rs @@ -1,9 +1,9 @@ //! Types for the IBC events emitted from Tendermint Websocket by the connection module. -use crate::prelude::*; use tendermint::abci; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; +use crate::prelude::*; /// Connection event types const CONNECTION_OPEN_INIT_EVENT: &str = "connection_open_init"; @@ -306,11 +306,13 @@ impl From for abci::Event { #[cfg(test)] mod tests { - use super::*; - use crate::core::ics02_client::client_type::ClientType; use std::str::FromStr; + use tendermint::abci::Event as AbciEvent; + use super::*; + use crate::core::ics02_client::client_type::ClientType; + #[test] fn ibc_to_abci_connection_events() { struct Test { diff --git a/crates/ibc/src/core/ics03_connection/handler.rs b/crates/ibc/src/core/ics03_connection/handler.rs index 8946943c6..a79a2d87b 100644 --- a/crates/ibc/src/core/ics03_connection/handler.rs +++ b/crates/ibc/src/core/ics03_connection/handler.rs @@ -8,10 +8,12 @@ pub mod conn_open_try; #[cfg(test)] pub mod test_util { + use alloc::format; use core::fmt::Debug; - use crate::{core::ContextError, mock::context::MockContext, prelude::String}; - use alloc::format; + use crate::core::ContextError; + use crate::mock::context::MockContext; + use crate::prelude::String; pub enum Expect { Success, 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 8ca94b4a1..1aee37d96 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 @@ -4,6 +4,7 @@ use ibc_proto::protobuf::Protobuf; use prost::Message; use crate::core::context::ContextError; +use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; @@ -12,13 +13,12 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenAck; use crate::core::ics03_connection::msgs::conn_open_ack::MsgConnectionOpenAck; use crate::core::ics24_host::identifier::ClientId; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ClientConsensusStatePath, ClientStatePath, ConnectionPath}; +use crate::core::ics24_host::path::{ + ClientConsensusStatePath, ClientStatePath, ConnectionPath, Path, +}; use crate::core::{ExecutionContext, ValidationContext}; use crate::prelude::*; -use crate::core::events::{IbcEvent, MessageEvent}; - pub(crate) fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenAck) -> Result<(), ContextError> where Ctx: ValidationContext, @@ -205,19 +205,18 @@ impl LocalVars { #[cfg(test)] mod tests { - use super::*; - use core::str::FromStr; + use test_log::test; + use super::*; + use crate::core::events::IbcEvent; use crate::core::ics02_client::height::Height; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::handler::test_util::{Expect, Fixture}; use crate::core::ics03_connection::msgs::conn_open_ack::MsgConnectionOpenAck; use crate::core::ics23_commitment::commitment::CommitmentPrefix; use crate::core::ics24_host::identifier::{ChainId, ClientId}; - - use crate::core::events::IbcEvent; use crate::core::timestamp::ZERO_DURATION; use crate::mock::context::MockContext; use crate::mock::host::HostType; 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 56a96b45b..e5c1251c6 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 @@ -3,6 +3,7 @@ use ibc_proto::protobuf::Protobuf; use crate::core::context::ContextError; +use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; @@ -11,13 +12,10 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenConfirm; use crate::core::ics03_connection::msgs::conn_open_confirm::MsgConnectionOpenConfirm; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ClientConsensusStatePath, ConnectionPath}; +use crate::core::ics24_host::path::{ClientConsensusStatePath, ConnectionPath, Path}; use crate::core::{ExecutionContext, ValidationContext}; use crate::prelude::*; -use crate::core::events::{IbcEvent, MessageEvent}; - pub(crate) fn validate(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), ContextError> where Ctx: ValidationContext, @@ -173,11 +171,11 @@ impl LocalVars { #[cfg(test)] mod tests { - use super::*; - use core::str::FromStr; + use test_log::test; + use super::*; use crate::core::events::IbcEvent; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::handler::test_util::{Expect, Fixture}; 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 1d7e11a5c..6ee7daedc 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 @@ -1,16 +1,15 @@ //! Protocol logic specific to ICS3 messages of type `MsgConnectionOpenInit`. -use crate::core::ics02_client::client_state::ClientStateValidation; -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; - use crate::core::context::ContextError; use crate::core::events::{IbcEvent, MessageEvent}; +use crate::core::ics02_client::client_state::ClientStateValidation; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State}; use crate::core::ics03_connection::events::OpenInit; use crate::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; use crate::core::ics24_host::identifier::ConnectionId; use crate::core::ics24_host::path::{ClientConnectionPath, ConnectionPath}; use crate::core::{ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenInit) -> Result<(), ContextError> where @@ -90,8 +89,9 @@ where #[cfg(test)] mod tests { - use super::*; + use test_log::test; + use super::*; use crate::core::events::IbcEvent; use crate::core::ics03_connection::connection::State; use crate::core::ics03_connection::handler::test_util::{Expect, Fixture}; @@ -99,7 +99,6 @@ mod tests { use crate::core::ics03_connection::version::Version; use crate::mock::context::MockContext; use crate::Height; - use test_log::test; enum Ctx { Default, 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 090f3ede5..2cdd5da8c 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 @@ -4,6 +4,7 @@ use ibc_proto::protobuf::Protobuf; use prost::Message; use crate::core::context::ContextError; +use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; @@ -11,17 +12,13 @@ use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, Sta use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::events::OpenTry; use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry; -use crate::core::ics24_host::identifier::ClientId; -use crate::core::ics24_host::identifier::ConnectionId; -use crate::core::ics24_host::path::Path; +use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; use crate::core::ics24_host::path::{ - ClientConnectionPath, ClientConsensusStatePath, ClientStatePath, ConnectionPath, + ClientConnectionPath, ClientConsensusStatePath, ClientStatePath, ConnectionPath, Path, }; use crate::core::{ExecutionContext, ValidationContext}; use crate::prelude::*; -use crate::core::events::{IbcEvent, MessageEvent}; - pub(crate) fn validate(ctx_b: &Ctx, msg: MsgConnectionOpenTry) -> Result<(), ContextError> where Ctx: ValidationContext, @@ -208,10 +205,9 @@ impl LocalVars { #[cfg(test)] mod tests { - use super::*; - use test_log::test; + use super::*; use crate::core::events::IbcEvent; use crate::core::ics03_connection::connection::State; use crate::core::ics03_connection::handler::test_util::{Expect, Fixture}; diff --git a/crates/ibc/src/core/ics03_connection/msgs.rs b/crates/ibc/src/core/ics03_connection/msgs.rs index 486ce3956..4adae4c9b 100644 --- a/crates/ibc/src/core/ics03_connection/msgs.rs +++ b/crates/ibc/src/core/ics03_connection/msgs.rs @@ -38,11 +38,12 @@ pub enum ConnectionMsg { #[cfg(test)] pub mod test_util { - use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - use crate::prelude::*; use ibc_proto::ibc::core::commitment::v1::MerklePrefix; use ibc_proto::ibc::core::connection::v1::Counterparty as RawCounterparty; + use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::prelude::*; + pub fn get_dummy_raw_counterparty(conn_id: Option) -> RawCounterparty { let connection_id = match conn_id { Some(id) => ConnectionId::new(id).to_string(), 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 5b57756f7..415cd3983 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 @@ -1,5 +1,3 @@ -use crate::prelude::*; - use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenAck as RawMsgConnectionOpenAck; use ibc_proto::protobuf::Protobuf; @@ -9,6 +7,7 @@ use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::ConnectionId; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; use crate::Height; @@ -132,19 +131,18 @@ impl From for RawMsgConnectionOpenAck { #[cfg(test)] pub mod test_util { - use crate::core::ics02_client::height::Height; - use crate::mock::client_state::MockClientState; - use crate::mock::header::MockHeader; - use crate::prelude::*; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenAck as RawMsgConnectionOpenAck; + use super::MsgConnectionOpenAck; + use crate::core::ics02_client::height::Height; use crate::core::ics03_connection::version::Version; use crate::core::ics24_host::identifier::ConnectionId; + use crate::mock::client_state::MockClientState; + use crate::mock::header::MockHeader; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; - use super::MsgConnectionOpenAck; - /// Testing-specific helper methods. impl MsgConnectionOpenAck { /// Returns a new `MsgConnectionOpenAck` with dummy values. @@ -186,15 +184,13 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::client::v1::Height; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenAck as RawMsgConnectionOpenAck; + use test_log::test; use crate::core::ics03_connection::msgs::conn_open_ack::test_util::get_dummy_raw_msg_conn_open_ack; use crate::core::ics03_connection::msgs::conn_open_ack::MsgConnectionOpenAck; + use crate::prelude::*; #[test] fn parse_connection_open_ack_msg() { 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 4f0337a69..cb1528dc3 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 @@ -1,14 +1,13 @@ -use crate::core::ics23_commitment::commitment::CommitmentProofBytes; -use crate::{prelude::*, Height}; - -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenConfirm as RawMsgConnectionOpenConfirm; +use ibc_proto::protobuf::Protobuf; use crate::core::ics03_connection::error::ConnectionError; +use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::ConnectionId; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; +use crate::Height; pub(crate) const TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenConfirm"; @@ -74,11 +73,11 @@ impl From for RawMsgConnectionOpenConfirm { #[cfg(test)] pub mod test_util { - use super::MsgConnectionOpenConfirm; - use crate::prelude::*; use ibc_proto::ibc::core::client::v1::Height; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenConfirm as RawMsgConnectionOpenConfirm; + use super::MsgConnectionOpenConfirm; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; /// Testing-specific helper methods. @@ -104,15 +103,13 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::client::v1::Height; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenConfirm as RawMsgConnectionOpenConfirm; + use test_log::test; use crate::core::ics03_connection::msgs::conn_open_confirm::test_util::get_dummy_raw_msg_conn_open_confirm; use crate::core::ics03_connection::msgs::conn_open_confirm::MsgConnectionOpenConfirm; + use crate::prelude::*; #[test] fn parse_connection_open_confirm_msg() { 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 d6732f258..322f28cc2 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 @@ -1,5 +1,3 @@ -use crate::prelude::*; - use core::time::Duration; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenInit as RawMsgConnectionOpenInit; @@ -10,6 +8,7 @@ use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::Version; use crate::core::ics24_host::identifier::ClientId; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenInit"; @@ -38,10 +37,8 @@ impl Msg for MsgConnectionOpenInit { /// `BorshSerialize` and `BorshDeserialize` on `MsgConnectionOpenInit` #[cfg(feature = "borsh")] mod borsh_impls { - use borsh::{ - maybestd::io::{self, Read}, - BorshDeserialize, BorshSerialize, - }; + use borsh::maybestd::io::{self, Read}; + use borsh::{BorshDeserialize, BorshSerialize}; use super::*; @@ -132,16 +129,16 @@ impl From for RawMsgConnectionOpenInit { #[cfg(test)] pub mod test_util { - use crate::core::ics03_connection::connection::Counterparty; - use crate::prelude::*; use ibc_proto::ibc::core::connection::v1::{ MsgConnectionOpenInit as RawMsgConnectionOpenInit, Version as RawVersion, }; + use crate::core::ics03_connection::connection::Counterparty; use crate::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::Version; use crate::core::ics24_host::identifier::ClientId; + use crate::prelude::*; use crate::test_utils::get_dummy_bech32_account; /// Extends the implementation with additional helper methods. @@ -199,16 +196,15 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - + use ibc_proto::ibc::core::connection::v1::{ + Counterparty as RawCounterparty, MsgConnectionOpenInit as RawMsgConnectionOpenInit, + }; use test_log::test; - use ibc_proto::ibc::core::connection::v1::Counterparty as RawCounterparty; - use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenInit as RawMsgConnectionOpenInit; - use super::MsgConnectionOpenInit; use crate::core::ics03_connection::msgs::conn_open_init::test_util::get_dummy_raw_msg_conn_open_init; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; + use crate::prelude::*; #[test] fn parse_connection_open_init_msg() { 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 11f7fb884..64269f075 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 @@ -1,9 +1,5 @@ -use crate::prelude::*; - -use core::{ - convert::{TryFrom, TryInto}, - time::Duration, -}; +use core::convert::{TryFrom, TryInto}; +use core::time::Duration; use ibc_proto::google::protobuf::Any; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenTry as RawMsgConnectionOpenTry; @@ -15,6 +11,7 @@ use crate::core::ics03_connection::version::Version; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::ClientId; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; use crate::Height; @@ -63,10 +60,8 @@ impl Msg for MsgConnectionOpenTry { #[allow(deprecated)] #[cfg(feature = "borsh")] mod borsh_impls { - use borsh::{ - maybestd::io::{self, Read}, - BorshDeserialize, BorshSerialize, - }; + use borsh::maybestd::io::{self, Read}; + use borsh::{BorshDeserialize, BorshSerialize}; use super::*; @@ -248,17 +243,17 @@ impl From for RawMsgConnectionOpenTry { #[cfg(test)] pub mod test_util { - use crate::core::ics02_client::height::Height; - use crate::mock::client_state::MockClientState; - use crate::mock::header::MockHeader; - use crate::prelude::*; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenTry as RawMsgConnectionOpenTry; + use crate::core::ics02_client::height::Height; use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::mock::client_state::MockClientState; + use crate::mock::header::MockHeader; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; /// Testing-specific helper methods. @@ -320,17 +315,16 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::client::v1::Height; - use ibc_proto::ibc::core::connection::v1::Counterparty as RawCounterparty; - use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenTry as RawMsgConnectionOpenTry; + use ibc_proto::ibc::core::connection::v1::{ + Counterparty as RawCounterparty, MsgConnectionOpenTry as RawMsgConnectionOpenTry, + }; + use test_log::test; use crate::core::ics03_connection::msgs::conn_open_try::test_util::get_dummy_raw_msg_conn_open_try; use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; + use crate::prelude::*; #[test] fn parse_connection_open_try_msg() { diff --git a/crates/ibc/src/core/ics03_connection/version.rs b/crates/ibc/src/core/ics03_connection/version.rs index ba6fdb9a6..dcdb2b9f8 100644 --- a/crates/ibc/src/core/ics03_connection/version.rs +++ b/crates/ibc/src/core/ics03_connection/version.rs @@ -2,14 +2,13 @@ use core::fmt::Display; -use crate::prelude::*; -use crate::utils::pretty::PrettySlice; - use ibc_proto::ibc::core::connection::v1::Version as RawVersion; use ibc_proto::protobuf::Protobuf; use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics04_channel::channel::Order; +use crate::prelude::*; +use crate::utils::pretty::PrettySlice; /// Stores the identifier and the features supported by a version #[cfg_attr( @@ -189,14 +188,12 @@ fn get_feature_set_intersection( #[cfg(test)] mod tests { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::connection::v1::Version as RawVersion; + use test_log::test; use crate::core::ics03_connection::error::ConnectionError; use crate::core::ics03_connection::version::{get_compatible_versions, pick_version, Version}; + use crate::prelude::*; fn get_dummy_features() -> Vec { vec!["ORDER_RANDOM".to_string(), "ORDER_UNORDERED".to_string()] diff --git a/crates/ibc/src/core/ics04_channel/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/acknowledgement.rs index 3b3ebb844..4c5d08cd7 100644 --- a/crates/ibc/src/core/ics04_channel/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/acknowledgement.rs @@ -1,6 +1,7 @@ //! Defines acknowledgment types used by various IBC messages and applications. use core::fmt::{Display, Error as FmtError, Formatter}; + use derive_more::Into; use super::error::PacketError; @@ -142,7 +143,8 @@ impl From for Acknowledgement { #[cfg(test)] mod test { use super::*; - use crate::applications::transfer::{ack_success_b64, error::TokenTransferError}; + use crate::applications::transfer::ack_success_b64; + use crate::applications::transfer::error::TokenTransferError; #[test] fn test_ack_ser() { diff --git a/crates/ibc/src/core/ics04_channel/channel.rs b/crates/ibc/src/core/ics04_channel/channel.rs index 0c77c99be..7cfac5265 100644 --- a/crates/ibc/src/core/ics04_channel/channel.rs +++ b/crates/ibc/src/core/ics04_channel/channel.rs @@ -1,20 +1,19 @@ //! Implementation of IBC channels, as described in ICS 4. -use crate::prelude::*; -use crate::utils::pretty::PrettySlice; - use core::fmt::{Display, Error as FmtError, Formatter}; use core::str::FromStr; -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::channel::v1::{ Channel as RawChannel, Counterparty as RawCounterparty, IdentifiedChannel as RawIdentifiedChannel, }; +use ibc_proto::protobuf::Protobuf; -use crate::core::ics04_channel::{error::ChannelError, Version}; +use crate::core::ics04_channel::error::ChannelError; +use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; +use crate::prelude::*; +use crate::utils::pretty::PrettySlice; /// A [`ChannelEnd`] along with its ID and the port it is bound to #[cfg_attr( @@ -573,10 +572,12 @@ impl Display for State { #[cfg(test)] pub mod test_util { + use ibc_proto::ibc::core::channel::v1::{ + Channel as RawChannel, Counterparty as RawCounterparty, + }; + use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; use crate::prelude::*; - use ibc_proto::ibc::core::channel::v1::Channel as RawChannel; - use ibc_proto::ibc::core::channel::v1::Counterparty as RawCounterparty; /// Returns a dummy `RawCounterparty`, for testing only! /// Can be optionally parametrized with a specific channel identifier. @@ -605,15 +606,14 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - use core::str::FromStr; - use test_log::test; use ibc_proto::ibc::core::channel::v1::Channel as RawChannel; + use test_log::test; use crate::core::ics04_channel::channel::test_util::get_dummy_raw_channel_end; use crate::core::ics04_channel::channel::ChannelEnd; + use crate::prelude::*; #[test] fn channel_end_try_from_raw() { diff --git a/crates/ibc/src/core/ics04_channel/commitment.rs b/crates/ibc/src/core/ics04_channel/commitment.rs index f389673e6..c2979e910 100644 --- a/crates/ibc/src/core/ics04_channel/commitment.rs +++ b/crates/ibc/src/core/ics04_channel/commitment.rs @@ -1,11 +1,10 @@ //! Types and utilities related to packet commitments. +use super::acknowledgement::Acknowledgement; use crate::core::ics04_channel::timeout::TimeoutHeight; use crate::core::timestamp::Timestamp; use crate::prelude::*; -use super::acknowledgement::Acknowledgement; - /// Packet commitment #[cfg_attr( feature = "parity-scale-codec", diff --git a/crates/ibc/src/core/ics04_channel/context.rs b/crates/ibc/src/core/ics04_channel/context.rs index 3e24e1729..aa7794a2e 100644 --- a/crates/ibc/src/core/ics04_channel/context.rs +++ b/crates/ibc/src/core/ics04_channel/context.rs @@ -1,23 +1,23 @@ //! ICS4 (channel) context. -use crate::core::events::IbcEvent; -use crate::core::ics02_client::client_state::ClientState; -use crate::core::ics02_client::ClientExecutionContext; -use crate::core::ics24_host::path::{ - ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqSendPath, -}; -use crate::core::{ContextError, ExecutionContext, ValidationContext}; -use crate::prelude::*; use core::time::Duration; + use num_traits::float::FloatCore; +use super::packet::Sequence; +use crate::core::events::IbcEvent; +use crate::core::ics02_client::client_state::ClientState; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::ClientExecutionContext; use crate::core::ics03_connection::connection::ConnectionEnd; use crate::core::ics04_channel::channel::ChannelEnd; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - -use super::packet::Sequence; +use crate::core::ics24_host::path::{ + ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqSendPath, +}; +use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; /// Methods required in send packet validation, to be implemented by the host pub trait SendPacketValidationContext { diff --git a/crates/ibc/src/core/ics04_channel/error.rs b/crates/ibc/src/core/ics04_channel/error.rs index d8a98a2a7..669a54e2f 100644 --- a/crates/ibc/src/core/ics04_channel/error.rs +++ b/crates/ibc/src/core/ics04_channel/error.rs @@ -1,5 +1,7 @@ //! Defines the main channel, port and packet error types +use displaydoc::Display; + use super::channel::Counterparty; use super::packet::Sequence; use super::timeout::TimeoutHeight; @@ -14,8 +16,6 @@ use crate::core::timestamp::{ParseTimestampError, Timestamp}; use crate::prelude::*; use crate::Height; -use displaydoc::Display; - #[derive(Debug, Display)] pub enum ChannelError { /// invalid channel end: `{channel_end}` diff --git a/crates/ibc/src/core/ics04_channel/events.rs b/crates/ibc/src/core/ics04_channel/events.rs index 86b360734..58baab970 100644 --- a/crates/ibc/src/core/ics04_channel/events.rs +++ b/crates/ibc/src/core/ics04_channel/events.rs @@ -5,12 +5,6 @@ mod packet_attributes; use tendermint::abci; -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::core::timestamp::Timestamp; -use crate::prelude::*; - use self::channel_attributes::{ ChannelIdAttribute, ConnectionIdAttribute, CounterpartyChannelIdAttribute, CounterpartyPortIdAttribute, PortIdAttribute, VersionAttribute, @@ -21,12 +15,16 @@ use self::packet_attributes::{ PacketConnectionIdAttribute, PacketDataAttribute, SequenceAttribute, SrcChannelIdAttribute, SrcPortIdAttribute, TimeoutHeightAttribute, TimeoutTimestampAttribute, }; - use super::acknowledgement::Acknowledgement; use super::channel::Order; use super::packet::Sequence; use super::timeout::TimeoutHeight; use super::Version; +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::core::timestamp::Timestamp; +use crate::prelude::*; /// Channel event types const CHANNEL_OPEN_INIT_EVENT: &str = "channel_open_init"; @@ -1121,9 +1119,10 @@ impl TryFrom for abci::Event { #[cfg(test)] mod tests { - use super::*; use tendermint::abci::Event as AbciEvent; + use super::*; + #[test] fn ibc_to_abci_channel_events() { struct Test { diff --git a/crates/ibc/src/core/ics04_channel/events/channel_attributes.rs b/crates/ibc/src/core/ics04_channel/events/channel_attributes.rs index dad056755..d802a50b0 100644 --- a/crates/ibc/src/core/ics04_channel/events/channel_attributes.rs +++ b/crates/ibc/src/core/ics04_channel/events/channel_attributes.rs @@ -3,10 +3,8 @@ use derive_more::From; use tendermint::abci; -use crate::core::{ - ics04_channel::Version, - ics24_host::identifier::{ChannelId, ConnectionId, PortId}, -}; +use crate::core::ics04_channel::Version; +use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; const CONNECTION_ID_ATTRIBUTE_KEY: &str = "connection_id"; const CHANNEL_ID_ATTRIBUTE_KEY: &str = "channel_id"; 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 8e53ebfdc..58d820635 100644 --- a/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs +++ b/crates/ibc/src/core/ics04_channel/events/packet_attributes.rs @@ -2,12 +2,11 @@ //! during packet-related datagrams. //! use core::str; + use derive_more::From; use subtle_encoding::hex; use tendermint::abci; -use crate::prelude::*; - use crate::core::ics04_channel::acknowledgement::Acknowledgement; use crate::core::ics04_channel::channel::Order; use crate::core::ics04_channel::error::ChannelError; @@ -15,6 +14,7 @@ use crate::core::ics04_channel::packet::Sequence; use crate::core::ics04_channel::timeout::TimeoutHeight; use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; use crate::core::timestamp::Timestamp; +use crate::prelude::*; const PKT_SEQ_ATTRIBUTE_KEY: &str = "packet_sequence"; const PKT_DATA_ATTRIBUTE_KEY: &str = "packet_data"; diff --git a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs index 64d7b31f4..65c14fd40 100644 --- a/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/handler/acknowledgement.rs @@ -1,23 +1,20 @@ -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; - -use crate::core::events::MessageEvent; +use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics03_connection::delay::verify_conn_delay_passed; use crate::core::ics04_channel::channel::{Counterparty, Order, State as ChannelState}; use crate::core::ics04_channel::commitment::{compute_ack_commitment, compute_packet_commitment}; -use crate::core::ics04_channel::error::ChannelError; -use crate::core::ics04_channel::error::PacketError; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; +use crate::core::ics04_channel::events::AcknowledgePacket; use crate::core::ics04_channel::msgs::acknowledgement::MsgAcknowledgement; -use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ - AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqAckPath, + AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, SeqAckPath, }; use crate::core::router::Module; -use crate::core::{events::IbcEvent, ics04_channel::events::AcknowledgePacket}; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn acknowledgement_packet_validate( ctx_a: &ValCtx, @@ -219,31 +216,27 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; use test_log::test; + use super::*; + use crate::applications::transfer::MODULE_ID_STR; use crate::core::ics02_client::height::Height; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::commitment::PacketCommitment; use crate::core::ics04_channel::msgs::acknowledgement::test_util::get_dummy_raw_msg_acknowledgement; use crate::core::ics04_channel::msgs::acknowledgement::MsgAcknowledgement; use crate::core::ics04_channel::Version; - use crate::core::ics24_host::identifier::ChannelId; - use crate::core::ics24_host::identifier::PortId; - use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; - use crate::core::timestamp::Timestamp; - use crate::core::timestamp::ZERO_DURATION; - + use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; + use crate::core::router::{ModuleId, Router}; + use crate::core::timestamp::{Timestamp, ZERO_DURATION}; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; - use crate::{applications::transfer::MODULE_ID_STR, test_utils::DummyTransferModule}; + use crate::test_utils::DummyTransferModule; struct Fixture { ctx: MockContext, 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 11974a118..57ca51e55 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 @@ -1,22 +1,20 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelCloseConfirm`. -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; -use crate::core::ics04_channel::channel::State; -use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State as ChannelState}; +use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State, State as ChannelState}; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::events::CloseConfirm; use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; +use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath, Path}; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn chan_close_confirm_validate( ctx_b: &ValCtx, @@ -169,10 +167,10 @@ where #[cfg(test)] mod tests { use super::*; - - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::applications::transfer::MODULE_ID_STR; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ @@ -181,14 +179,10 @@ mod tests { use crate::core::ics04_channel::msgs::chan_close_confirm::test_util::get_dummy_raw_msg_chan_close_confirm; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; + use crate::core::router::{ModuleId, Router}; use crate::core::timestamp::ZERO_DURATION; - use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; - - use crate::applications::transfer::MODULE_ID_STR; use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; 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 976456696..01aaac7e1 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 @@ -1,9 +1,7 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelCloseInit`. -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; - use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::ClientStateValidation; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics04_channel::channel::State; use crate::core::ics04_channel::error::ChannelError; @@ -12,6 +10,7 @@ use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit; use crate::core::ics24_host::path::ChannelEndPath; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn chan_close_init_validate( ctx_a: &ValCtx, @@ -126,10 +125,10 @@ where #[cfg(test)] mod tests { use super::*; - - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::applications::transfer::MODULE_ID_STR; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ @@ -138,11 +137,8 @@ mod tests { use crate::core::ics04_channel::msgs::chan_close_init::test_util::get_dummy_raw_msg_chan_close_init; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; + use crate::core::router::{ModuleId, Router}; use crate::core::timestamp::ZERO_DURATION; - - use crate::applications::transfer::MODULE_ID_STR; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; 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 8e522ebe0..910441015 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 @@ -1,6 +1,5 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenAck`. -use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; @@ -8,15 +7,14 @@ use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateVali use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; -use crate::core::ics04_channel::channel::State; -use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State as ChannelState}; +use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State, State as ChannelState}; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::events::OpenAck; use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; +use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath, Path}; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn chan_open_ack_validate( ctx_a: &ValCtx, @@ -165,31 +163,27 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; use test_log::test; + use super::*; use crate::applications::transfer::MODULE_ID_STR; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::get_compatible_versions; - use crate::core::ics04_channel::channel::Order; - use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; + use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::msgs::chan_open_ack::test_util::get_dummy_raw_msg_chan_open_ack; use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; - use crate::core::ics24_host::identifier::ClientId; - use crate::core::ics24_host::identifier::ConnectionId; - use crate::core::router::ModuleId; - use crate::core::router::Router; + use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::core::router::{ModuleId, Router}; use crate::core::timestamp::ZERO_DURATION; - use crate::Height; - use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; + use crate::Height; pub struct Fixture { pub context: MockContext, 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 b38a937c7..9461f55aa 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 @@ -1,22 +1,20 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenConfirm`. -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; -use crate::core::ics04_channel::channel::State; -use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State as ChannelState}; +use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State, State as ChannelState}; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::events::OpenConfirm; use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; +use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath, Path}; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn chan_open_confirm_validate( ctx_b: &ValCtx, @@ -170,30 +168,28 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; use test_log::test; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use super::*; + use crate::applications::transfer::MODULE_ID_STR; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::msgs::chan_open_confirm::test_util::get_dummy_raw_msg_chan_open_confirm; use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm; use crate::core::ics04_channel::Version; - use crate::core::ics24_host::identifier::ChannelId; - use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; + use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId}; + use crate::core::router::{ModuleId, Router}; use crate::core::timestamp::ZERO_DURATION; - use crate::Height; - use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; - use crate::{applications::transfer::MODULE_ID_STR, test_utils::DummyTransferModule}; + use crate::test_utils::DummyTransferModule; + use crate::Height; pub struct Fixture { pub context: MockContext, 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 1cd8583e8..15d5792ac 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 @@ -1,10 +1,8 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenInit`. -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; - use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::ClientStateValidation; +use crate::core::ics02_client::error::ClientError; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State}; use crate::core::ics04_channel::events::OpenInit; use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; @@ -12,6 +10,7 @@ use crate::core::ics24_host::identifier::ChannelId; use crate::core::ics24_host::path::{ChannelEndPath, SeqAckPath, SeqRecvPath, SeqSendPath}; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn chan_open_init_validate( ctx_a: &ValCtx, @@ -140,28 +139,24 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; + use test_log::test; + use super::*; + use crate::applications::transfer::MODULE_ID_STR; use crate::clients::ics07_tendermint::client_type as tm_client_type; use crate::core::ics02_client::height::Height; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::core::ics03_connection::connection::{ConnectionEnd, State as ConnectionState}; use crate::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::handler::chan_open_init::validate; use crate::core::ics04_channel::msgs::chan_open_init::test_util::get_dummy_raw_msg_chan_open_init; use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; - use crate::core::ics24_host::identifier::ClientId; - use crate::core::ics24_host::identifier::ConnectionId; - - use crate::applications::transfer::MODULE_ID_STR; - use crate::core::router::ModuleId; - use crate::core::router::Router; + use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; + use crate::core::router::{ModuleId, Router}; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; - use test_log::test; pub struct Fixture { pub ctx: MockContext, 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 3cda49710..4cf78dce7 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 @@ -1,6 +1,5 @@ //! Protocol logic specific to ICS4 messages of type `MsgChannelOpenTry`. -use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use crate::core::events::{IbcEvent, MessageEvent}; @@ -8,17 +7,17 @@ use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateVali use crate::core::ics02_client::consensus_state::ConsensusState; use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; -use crate::core::ics04_channel::channel::State; -use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State as ChannelState}; +use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State, State as ChannelState}; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::events::OpenTry; use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; use crate::core::ics24_host::identifier::ChannelId; -use crate::core::ics24_host::path::Path; -use crate::core::ics24_host::path::{ChannelEndPath, ClientConsensusStatePath}; -use crate::core::ics24_host::path::{SeqAckPath, SeqRecvPath, SeqSendPath}; +use crate::core::ics24_host::path::{ + ChannelEndPath, ClientConsensusStatePath, Path, SeqAckPath, SeqRecvPath, SeqSendPath, +}; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn chan_open_try_validate( ctx_b: &ValCtx, @@ -187,28 +186,26 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; use test_log::test; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use super::*; + use crate::applications::transfer::MODULE_ID_STR; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::msgs::test_util::get_dummy_raw_counterparty; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try; use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; use crate::core::ics24_host::identifier::{ClientId, ConnectionId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; + use crate::core::router::{ModuleId, Router}; use crate::core::timestamp::ZERO_DURATION; - use crate::Height; - - use crate::applications::transfer::MODULE_ID_STR; use crate::mock::client_state::client_type as mock_client_type; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; + use crate::Height; pub struct Fixture { pub ctx: MockContext, 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 d2f024612..81009c800 100644 --- a/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/recv_packet.rs @@ -1,25 +1,23 @@ -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; - use crate::core::events::{IbcEvent, MessageEvent}; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::connection::State as ConnectionState; use crate::core::ics03_connection::delay::verify_conn_delay_passed; use crate::core::ics04_channel::channel::{Counterparty, Order, State as ChannelState}; use crate::core::ics04_channel::commitment::{compute_ack_commitment, compute_packet_commitment}; -use crate::core::ics04_channel::error::ChannelError; -use crate::core::ics04_channel::error::PacketError; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::events::{ReceivePacket, WriteAcknowledgement}; use crate::core::ics04_channel::msgs::recv_packet::MsgRecvPacket; use crate::core::ics04_channel::packet::Receipt; -use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ - AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, ReceiptPath, SeqRecvPath, + AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, + SeqRecvPath, }; use crate::core::router::Module; use crate::core::timestamp::Expiry; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) fn recv_packet_validate( ctx_b: &ValCtx, @@ -284,13 +282,14 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; use test_log::test; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use super::*; + use crate::applications::transfer::MODULE_ID_STR; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::msgs::recv_packet::test_util::get_dummy_raw_msg_recv_packet; @@ -298,17 +297,13 @@ mod tests { use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; - use crate::core::timestamp::Timestamp; - use crate::core::timestamp::ZERO_DURATION; - use crate::Height; - + use crate::core::router::{ModuleId, Router}; + use crate::core::timestamp::{Timestamp, ZERO_DURATION}; use crate::mock::context::MockContext; use crate::mock::ics18_relayer::context::RelayerContext; use crate::mock::router::MockRouter; - use crate::test_utils::get_dummy_account_id; - use crate::{applications::transfer::MODULE_ID_STR, test_utils::DummyTransferModule}; + use crate::test_utils::{get_dummy_account_id, DummyTransferModule}; + use crate::Height; pub struct Fixture { pub context: MockContext, 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 59cb14c6d..c978935d8 100644 --- a/crates/ibc/src/core/ics04_channel/handler/send_packet.rs +++ b/crates/ibc/src/core/ics04_channel/handler/send_packet.rs @@ -1,24 +1,21 @@ -use crate::core::ics02_client::client_state::ClientStateValidation; -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; - -use crate::core::events::IbcEvent; -use crate::core::events::MessageEvent; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::events::{IbcEvent, MessageEvent}; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics04_channel::channel::Counterparty; use crate::core::ics04_channel::commitment::compute_packet_commitment; -use crate::core::ics04_channel::context::SendPacketExecutionContext; +use crate::core::ics04_channel::context::{ + SendPacketExecutionContext, SendPacketValidationContext, +}; +use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::events::SendPacket; -use crate::core::ics04_channel::{ - context::SendPacketValidationContext, error::PacketError, packet::Packet, +use crate::core::ics04_channel::packet::Packet; +use crate::core::ics24_host::path::{ + ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqSendPath, }; -use crate::core::ics24_host::path::ChannelEndPath; -use crate::core::ics24_host::path::ClientConsensusStatePath; -use crate::core::ics24_host::path::CommitmentPath; -use crate::core::ics24_host::path::SeqSendPath; use crate::core::timestamp::Expiry; use crate::core::ContextError; +use crate::prelude::*; /// Send the given packet, including all necessary validation. /// @@ -143,17 +140,17 @@ pub fn send_packet_execute( #[cfg(test)] mod tests { - use super::*; use core::ops::Add; use core::time::Duration; use test_log::test; + use super::*; use crate::core::events::IbcEvent; use crate::core::ics02_client::height::Height; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::handler::send_packet::send_packet; @@ -161,8 +158,7 @@ mod tests { use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; - use crate::core::timestamp::Timestamp; - use crate::core::timestamp::ZERO_DURATION; + use crate::core::timestamp::{Timestamp, ZERO_DURATION}; use crate::mock::context::MockContext; #[test] diff --git a/crates/ibc/src/core/ics04_channel/handler/timeout.rs b/crates/ibc/src/core/ics04_channel/handler/timeout.rs index 12d479744..f8b68814a 100644 --- a/crates/ibc/src/core/ics04_channel/handler/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/handler/timeout.rs @@ -1,28 +1,23 @@ -use crate::core::ics02_client::client_state::ClientStateValidation; -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; use prost::Message; -use crate::core::events::IbcEvent; -use crate::core::events::MessageEvent; -use crate::core::ics02_client::client_state::ClientStateCommon; +use crate::core::events::{IbcEvent, MessageEvent}; +use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::delay::verify_conn_delay_passed; -use crate::core::ics04_channel::channel::State; -use crate::core::ics04_channel::channel::{Counterparty, Order}; +use crate::core::ics04_channel::channel::{Counterparty, Order, State}; use crate::core::ics04_channel::commitment::compute_packet_commitment; -use crate::core::ics04_channel::error::ChannelError; -use crate::core::ics04_channel::error::PacketError; -use crate::core::ics04_channel::events::ChannelClosed; +use crate::core::ics04_channel::error::{ChannelError, PacketError}; +use crate::core::ics04_channel::events::{ChannelClosed, TimeoutPacket}; +use crate::core::ics04_channel::handler::timeout_on_close; use crate::core::ics04_channel::msgs::timeout::MsgTimeout; use crate::core::ics04_channel::msgs::timeout_on_close::MsgTimeoutOnClose; -use crate::core::ics04_channel::{events::TimeoutPacket, handler::timeout_on_close}; -use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ - ChannelEndPath, ClientConsensusStatePath, CommitmentPath, ReceiptPath, SeqRecvPath, + ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, }; use crate::core::router::Module; use crate::core::{ContextError, ExecutionContext, ValidationContext}; +use crate::prelude::*; pub(crate) enum TimeoutMsgType { Timeout(MsgTimeout), @@ -274,13 +269,14 @@ where #[cfg(test)] mod tests { - use super::*; use rstest::*; + use super::*; + use crate::applications::transfer::MODULE_ID_STR; use crate::core::ics02_client::height::Height; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::commitment::PacketCommitment; @@ -289,12 +285,8 @@ mod tests { use crate::core::ics04_channel::msgs::timeout::MsgTimeout; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; - use crate::core::router::ModuleId; - use crate::core::router::Router; - use crate::core::timestamp::Timestamp; - use crate::core::timestamp::ZERO_DURATION; - - use crate::applications::transfer::MODULE_ID_STR; + use crate::core::router::{ModuleId, Router}; + use crate::core::timestamp::{Timestamp, ZERO_DURATION}; use crate::mock::context::MockContext; use crate::mock::router::MockRouter; use crate::test_utils::DummyTransferModule; 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 9215d588a..5a37f8de5 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 @@ -1,21 +1,19 @@ -use crate::core::ics02_client::error::ClientError; -use crate::prelude::*; use ibc_proto::protobuf::Protobuf; use prost::Message; use crate::core::ics02_client::client_state::{ClientStateCommon, ClientStateValidation}; use crate::core::ics02_client::consensus_state::ConsensusState; +use crate::core::ics02_client::error::ClientError; use crate::core::ics03_connection::delay::verify_conn_delay_passed; -use crate::core::ics04_channel::channel::State; -use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order}; +use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; use crate::core::ics04_channel::commitment::compute_packet_commitment; use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::msgs::timeout_on_close::MsgTimeoutOnClose; -use crate::core::ics24_host::path::Path; use crate::core::ics24_host::path::{ - ChannelEndPath, ClientConsensusStatePath, CommitmentPath, ReceiptPath, SeqRecvPath, + ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, }; use crate::core::{ContextError, ValidationContext}; +use crate::prelude::*; pub fn validate(ctx_a: &Ctx, msg: &MsgTimeoutOnClose) -> Result<(), ContextError> where @@ -175,26 +173,24 @@ where #[cfg(test)] mod tests { - use crate::core::ics04_channel::commitment::compute_packet_commitment; - use crate::core::ics04_channel::commitment::PacketCommitment; - use crate::core::ics04_channel::handler::timeout_on_close::validate; - use crate::core::timestamp::Timestamp; - use crate::core::ExecutionContext; - use crate::mock::context::MockContext; - use crate::prelude::*; - use crate::Height; use rstest::*; - use crate::core::ics03_connection::connection::ConnectionEnd; - use crate::core::ics03_connection::connection::Counterparty as ConnectionCounterparty; - use crate::core::ics03_connection::connection::State as ConnectionState; + use crate::core::ics03_connection::connection::{ + ConnectionEnd, Counterparty as ConnectionCounterparty, State as ConnectionState, + }; use crate::core::ics03_connection::version::get_compatible_versions; use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, Order, State}; + use crate::core::ics04_channel::commitment::{compute_packet_commitment, PacketCommitment}; + use crate::core::ics04_channel::handler::timeout_on_close::validate; use crate::core::ics04_channel::msgs::timeout_on_close::test_util::get_dummy_raw_msg_timeout_on_close; use crate::core::ics04_channel::msgs::timeout_on_close::MsgTimeoutOnClose; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; - use crate::core::timestamp::ZERO_DURATION; + use crate::core::timestamp::{Timestamp, ZERO_DURATION}; + use crate::core::ExecutionContext; + use crate::mock::context::MockContext; + use crate::prelude::*; + use crate::Height; pub struct Fixture { pub context: MockContext, diff --git a/crates/ibc/src/core/ics04_channel/msgs.rs b/crates/ibc/src/core/ics04_channel/msgs.rs index 728c8926c..a5e87c6e5 100644 --- a/crates/ibc/src/core/ics04_channel/msgs.rs +++ b/crates/ibc/src/core/ics04_channel/msgs.rs @@ -13,17 +13,15 @@ pub(crate) mod timeout; pub(crate) mod timeout_on_close; // Opening handshake messages. +// Packet specific messages. +pub use acknowledgement::MsgAcknowledgement; +// Closing handshake messages. +pub use chan_close_confirm::MsgChannelCloseConfirm; +pub use chan_close_init::MsgChannelCloseInit; pub use chan_open_ack::MsgChannelOpenAck; pub use chan_open_confirm::MsgChannelOpenConfirm; pub use chan_open_init::MsgChannelOpenInit; pub use chan_open_try::MsgChannelOpenTry; - -// Closing handshake messages. -pub use chan_close_confirm::MsgChannelCloseConfirm; -pub use chan_close_init::MsgChannelCloseInit; - -// Packet specific messages. -pub use acknowledgement::MsgAcknowledgement; pub use recv_packet::MsgRecvPacket; pub use timeout::MsgTimeout; pub use timeout_on_close::MsgTimeoutOnClose; diff --git a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs index 6f448d6fc..250c33921 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/acknowledgement.rs @@ -1,5 +1,3 @@ -use crate::prelude::*; - use ibc_proto::ibc::core::channel::v1::MsgAcknowledgement as RawMsgAcknowledgement; use ibc_proto::protobuf::Protobuf; @@ -8,6 +6,7 @@ use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::Packet; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; use crate::Height; @@ -78,8 +77,9 @@ impl From for RawMsgAcknowledgement { #[cfg(test)] pub mod test_util { - use ibc_proto::ibc::core::channel::v1::MsgAcknowledgement as RawMsgAcknowledgement; - use ibc_proto::ibc::core::channel::v1::Packet as RawPacket; + use ibc_proto::ibc::core::channel::v1::{ + MsgAcknowledgement as RawMsgAcknowledgement, Packet as RawPacket, + }; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use crate::core::ics04_channel::packet::test_utils::get_dummy_raw_packet; @@ -110,15 +110,13 @@ pub mod test_util { #[cfg(test)] mod test { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::channel::v1::MsgAcknowledgement as RawMsgAcknowledgement; + use test_log::test; 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::prelude::*; use crate::test_utils::get_dummy_bech32_account; #[test] 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 c40c88c5a..ed03904f6 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 @@ -1,14 +1,13 @@ -use crate::core::ics23_commitment::commitment::CommitmentProofBytes; -use crate::{prelude::*, Height}; - -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::channel::v1::MsgChannelCloseConfirm as RawMsgChannelCloseConfirm; +use ibc_proto::protobuf::Protobuf; use crate::core::ics04_channel::error::ChannelError; +use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; +use crate::Height; pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelCloseConfirm"; @@ -74,11 +73,11 @@ impl From for RawMsgChannelCloseConfirm { #[cfg(test)] pub mod test_util { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelCloseConfirm as RawMsgChannelCloseConfirm; use ibc_proto::ibc::core::client::v1::Height; use crate::core::ics24_host::identifier::{ChannelId, PortId}; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; /// Returns a dummy `RawMsgChannelCloseConfirm`, for testing only! @@ -98,13 +97,12 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - use ibc_proto::ibc::core::channel::v1::MsgChannelCloseConfirm as RawMsgChannelCloseConfirm; use ibc_proto::ibc::core::client::v1::Height; use crate::core::ics04_channel::msgs::chan_close_confirm::test_util::get_dummy_raw_msg_chan_close_confirm; use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm; + use crate::prelude::*; #[test] fn parse_channel_close_confirm_msg() { 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 d3a569217..4ad83ef81 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 @@ -1,12 +1,10 @@ -use crate::prelude::*; - -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::channel::v1::MsgChannelCloseInit as RawMsgChannelCloseInit; +use ibc_proto::protobuf::Protobuf; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelCloseInit"; @@ -60,10 +58,10 @@ impl From for RawMsgChannelCloseInit { #[cfg(test)] pub mod test_util { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelCloseInit as RawMsgChannelCloseInit; use crate::core::ics24_host::identifier::{ChannelId, PortId}; + use crate::prelude::*; use crate::test_utils::get_dummy_bech32_account; /// Returns a dummy `RawMsgChannelCloseInit`, for testing only! @@ -78,14 +76,12 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::channel::v1::MsgChannelCloseInit as RawMsgChannelCloseInit; + use test_log::test; use crate::core::ics04_channel::msgs::chan_close_init::test_util::get_dummy_raw_msg_chan_close_init; use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit; + use crate::prelude::*; #[test] fn parse_channel_close_init_msg() { 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 9fca241ff..56dc166e4 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,13 +1,14 @@ +use ibc_proto::ibc::core::channel::v1::MsgChannelOpenAck as RawMsgChannelOpenAck; +use ibc_proto::protobuf::Protobuf; + 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}; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; -use crate::{prelude::*, Height}; - -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenAck as RawMsgChannelOpenAck; -use ibc_proto::protobuf::Protobuf; +use crate::Height; pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenAck"; @@ -77,12 +78,12 @@ impl From for RawMsgChannelOpenAck { #[cfg(test)] pub mod test_util { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelOpenAck as RawMsgChannelOpenAck; + use ibc_proto::ibc::core::client::v1::Height; use crate::core::ics24_host::identifier::{ChannelId, PortId}; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; - use ibc_proto::ibc::core::client::v1::Height; /// Returns a dummy `RawMsgChannelOpenAck`, for testing only! pub fn get_dummy_raw_msg_chan_open_ack(proof_height: u64) -> RawMsgChannelOpenAck { @@ -103,14 +104,13 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelOpenAck as RawMsgChannelOpenAck; + use ibc_proto::ibc::core::client::v1::Height; use test_log::test; use crate::core::ics04_channel::msgs::chan_open_ack::test_util::get_dummy_raw_msg_chan_open_ack; use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck; - - use ibc_proto::ibc::core::client::v1::Height; + use crate::prelude::*; #[test] fn parse_channel_open_ack_msg() { 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 4bd43bd39..a0daea61d 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,12 +1,13 @@ +use ibc_proto::ibc::core::channel::v1::MsgChannelOpenConfirm as RawMsgChannelOpenConfirm; +use ibc_proto::protobuf::Protobuf; + use crate::core::ics04_channel::error::ChannelError; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::ics24_host::identifier::{ChannelId, PortId}; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; -use crate::{prelude::*, Height}; - -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenConfirm as RawMsgChannelOpenConfirm; -use ibc_proto::protobuf::Protobuf; +use crate::Height; pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenConfirm"; @@ -72,12 +73,12 @@ impl From for RawMsgChannelOpenConfirm { #[cfg(test)] pub mod test_util { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelOpenConfirm as RawMsgChannelOpenConfirm; + use ibc_proto::ibc::core::client::v1::Height; use crate::core::ics24_host::identifier::{ChannelId, PortId}; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; - use ibc_proto::ibc::core::client::v1::Height; /// Returns a dummy `RawMsgChannelOpenConfirm`, for testing only! pub fn get_dummy_raw_msg_chan_open_confirm(proof_height: u64) -> RawMsgChannelOpenConfirm { @@ -96,14 +97,13 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelOpenConfirm as RawMsgChannelOpenConfirm; + use ibc_proto::ibc::core::client::v1::Height; use test_log::test; use crate::core::ics04_channel::msgs::chan_open_confirm::test_util::get_dummy_raw_msg_chan_open_confirm; use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm; - - use ibc_proto::ibc::core::client::v1::Height; + use crate::prelude::*; #[test] fn parse_channel_open_confirm_msg() { 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 08f034eb2..f2c081252 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,7 +1,9 @@ -use crate::core::ics04_channel::channel::verify_connection_hops_length; -use crate::core::ics04_channel::channel::ChannelEnd; -use crate::core::ics04_channel::channel::Counterparty; -use crate::core::ics04_channel::channel::{Order, State}; +use ibc_proto::ibc::core::channel::v1::MsgChannelOpenInit as RawMsgChannelOpenInit; +use ibc_proto::protobuf::Protobuf; + +use crate::core::ics04_channel::channel::{ + verify_connection_hops_length, ChannelEnd, Counterparty, Order, State, +}; use crate::core::ics04_channel::error::ChannelError; use crate::core::ics04_channel::Version; use crate::core::ics24_host::identifier::{ConnectionId, PortId}; @@ -9,9 +11,6 @@ use crate::core::Msg; use crate::prelude::*; use crate::signer::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenInit as RawMsgChannelOpenInit; -use ibc_proto::protobuf::Protobuf; - pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenInit"; /// @@ -93,11 +92,11 @@ impl From for RawMsgChannelOpenInit { #[cfg(test)] pub mod test_util { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelOpenInit as RawMsgChannelOpenInit; use crate::core::ics04_channel::channel::test_util::get_dummy_raw_channel_end; use crate::core::ics24_host::identifier::PortId; + use crate::prelude::*; use crate::test_utils::get_dummy_bech32_account; /// Returns a dummy `RawMsgChannelOpenInit`, for testing only! @@ -114,13 +113,13 @@ pub mod test_util { #[cfg(test)] mod tests { + use ibc_proto::ibc::core::channel::v1::MsgChannelOpenInit as RawMsgChannelOpenInit; + use test_log::test; + use crate::core::ics04_channel::msgs::chan_open_init::test_util::get_dummy_raw_msg_chan_open_init; use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit; use crate::prelude::*; - use ibc_proto::ibc::core::channel::v1::MsgChannelOpenInit as RawMsgChannelOpenInit; - use test_log::test; - #[test] fn channel_open_init_from_raw() { struct Test { 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 ad0e93ca4..6e2876332 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,17 +1,17 @@ -use crate::core::ics04_channel::channel::verify_connection_hops_length; -use crate::core::ics04_channel::channel::ChannelEnd; -use crate::core::ics04_channel::channel::Counterparty; -use crate::core::ics04_channel::channel::{Order, State}; +use ibc_proto::ibc::core::channel::v1::MsgChannelOpenTry as RawMsgChannelOpenTry; +use ibc_proto::protobuf::Protobuf; + +use crate::core::ics04_channel::channel::{ + verify_connection_hops_length, ChannelEnd, Counterparty, Order, State, +}; 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, ConnectionId, PortId}; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; -use crate::{prelude::*, Height}; - -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenTry as RawMsgChannelOpenTry; -use ibc_proto::protobuf::Protobuf; +use crate::Height; pub(crate) const TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenTry"; @@ -129,13 +129,13 @@ impl From for RawMsgChannelOpenTry { #[cfg(test)] pub mod test_util { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgChannelOpenTry as RawMsgChannelOpenTry; + use ibc_proto::ibc::core::client::v1::Height; use crate::core::ics04_channel::channel::test_util::get_dummy_raw_channel_end; use crate::core::ics24_host::identifier::PortId; + use crate::prelude::*; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; - use ibc_proto::ibc::core::client::v1::Height; /// Returns a dummy `RawMsgChannelOpenTry`, for testing only! pub fn get_dummy_raw_msg_chan_open_try(proof_height: u64) -> RawMsgChannelOpenTry { @@ -157,14 +157,14 @@ pub mod test_util { #[cfg(test)] mod tests { - use crate::core::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try; - use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; - use crate::prelude::*; - use ibc_proto::ibc::core::channel::v1::MsgChannelOpenTry as RawMsgChannelOpenTry; use ibc_proto::ibc::core::client::v1::Height; use test_log::test; + use crate::core::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try; + use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry; + use crate::prelude::*; + #[test] fn channel_open_try_from_raw() { struct Test { 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 241c67976..9b342a7d1 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/recv_packet.rs @@ -1,13 +1,11 @@ -use crate::prelude::*; - -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; +use ibc_proto::protobuf::Protobuf; use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::Packet; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; use crate::Height; @@ -77,6 +75,9 @@ impl From for RawMsgRecvPacket { #[cfg(test)] pub mod test_util { + use core::ops::Add; + use core::time::Duration; + use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; use ibc_proto::ibc::core::client::v1::Height as RawHeight; @@ -87,8 +88,6 @@ pub mod test_util { use crate::core::timestamp::Timestamp; use crate::signer::Signer; use crate::test_utils::{get_dummy_bech32_account, get_dummy_proof}; - use core::ops::Add; - use core::time::Duration; impl MsgRecvPacket { pub fn new( @@ -127,15 +126,13 @@ pub mod test_util { #[cfg(test)] mod test { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::channel::v1::MsgRecvPacket as RawMsgRecvPacket; + use test_log::test; 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::prelude::*; use crate::test_utils::get_dummy_bech32_account; #[test] diff --git a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs index b3104bca3..b2244b268 100644 --- a/crates/ibc/src/core/ics04_channel/msgs/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/msgs/timeout.rs @@ -1,13 +1,11 @@ -use crate::prelude::*; - -use ibc_proto::protobuf::Protobuf; - use ibc_proto::ibc::core::channel::v1::MsgTimeout as RawMsgTimeout; +use ibc_proto::protobuf::Protobuf; use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; use crate::Height; @@ -108,15 +106,13 @@ pub mod test_util { #[cfg(test)] mod test { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::channel::v1::MsgTimeout as RawMsgTimeout; + use test_log::test; 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::prelude::*; use crate::test_utils::get_dummy_bech32_account; #[test] 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 e299d9a18..6e965edc4 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 @@ -1,5 +1,3 @@ -use crate::prelude::*; - use ibc_proto::ibc::core::channel::v1::MsgTimeoutOnClose as RawMsgTimeoutOnClose; use ibc_proto::protobuf::Protobuf; @@ -7,6 +5,7 @@ use crate::core::ics04_channel::error::PacketError; use crate::core::ics04_channel::packet::{Packet, Sequence}; use crate::core::ics23_commitment::commitment::CommitmentProofBytes; use crate::core::Msg; +use crate::prelude::*; use crate::signer::Signer; use crate::Height; @@ -85,12 +84,12 @@ impl From for RawMsgTimeoutOnClose { #[cfg(test)] mod tests { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::MsgTimeoutOnClose as RawMsgTimeoutOnClose; use test_log::test; use crate::core::ics04_channel::msgs::timeout_on_close::test_util::get_dummy_raw_msg_timeout_on_close; use crate::core::ics04_channel::msgs::timeout_on_close::MsgTimeoutOnClose; + use crate::prelude::*; #[test] fn msg_timeout_on_close_try_from_raw() { diff --git a/crates/ibc/src/core/ics04_channel/packet.rs b/crates/ibc/src/core/ics04_channel/packet.rs index 91ca8fd88..b80069acc 100644 --- a/crates/ibc/src/core/ics04_channel/packet.rs +++ b/crates/ibc/src/core/ics04_channel/packet.rs @@ -1,7 +1,5 @@ //! Defines the packet type -use crate::prelude::*; - use core::str::FromStr; use ibc_proto::ibc::core::channel::v1::Packet as RawPacket; @@ -9,7 +7,9 @@ use ibc_proto::ibc::core::channel::v1::Packet as RawPacket; use super::timeout::TimeoutHeight; use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics24_host::identifier::{ChannelId, PortId}; -use crate::core::timestamp::{Expiry::Expired, Timestamp}; +use crate::core::timestamp::Expiry::Expired; +use crate::core::timestamp::Timestamp; +use crate::prelude::*; use crate::Height; /// Enumeration of proof carrying ICS4 message, helper for relayer. @@ -287,11 +287,11 @@ impl From for RawPacket { #[cfg(test)] pub mod test_utils { - use crate::prelude::*; use ibc_proto::ibc::core::channel::v1::Packet as RawPacket; use ibc_proto::ibc::core::client::v1::Height as RawHeight; use crate::core::ics24_host::identifier::{ChannelId, PortId}; + use crate::prelude::*; /// Returns a dummy `RawPacket`, for testing only! pub fn get_dummy_raw_packet(timeout_height: u64, timeout_timestamp: u64) -> RawPacket { @@ -313,15 +313,13 @@ pub mod test_utils { #[cfg(test)] mod tests { - use crate::prelude::*; - - use test_log::test; - use ibc_proto::ibc::core::channel::v1::Packet as RawPacket; use ibc_proto::ibc::core::client::v1::Height as RawHeight; + use test_log::test; use crate::core::ics04_channel::packet::test_utils::get_dummy_raw_packet; use crate::core::ics04_channel::packet::Packet; + use crate::prelude::*; #[test] fn packet_try_from_raw() { diff --git a/crates/ibc/src/core/ics04_channel/timeout.rs b/crates/ibc/src/core/ics04_channel/timeout.rs index 96f3096b5..e70a1efd7 100644 --- a/crates/ibc/src/core/ics04_channel/timeout.rs +++ b/crates/ibc/src/core/ics04_channel/timeout.rs @@ -4,7 +4,8 @@ use core::fmt::{Display, Error as FmtError, Formatter}; use ibc_proto::ibc::core::client::v1::Height as RawHeight; -use crate::core::ics02_client::{error::ClientError, height::Height}; +use crate::core::ics02_client::error::ClientError; +use crate::core::ics02_client::height::Height; use crate::prelude::*; /// Indicates a consensus height on the destination chain after which the packet @@ -150,9 +151,10 @@ impl Display for TimeoutHeight { #[cfg(feature = "serde")] mod tests { - use super::TimeoutHeight; use serde::{Deserialize, Serialize}; + use super::TimeoutHeight; + impl Serialize for TimeoutHeight { fn serialize(&self, serializer: S) -> Result where diff --git a/crates/ibc/src/core/ics04_channel/version.rs b/crates/ibc/src/core/ics04_channel/version.rs index dd3e39bf7..84feb5e7e 100644 --- a/crates/ibc/src/core/ics04_channel/version.rs +++ b/crates/ibc/src/core/ics04_channel/version.rs @@ -6,9 +6,8 @@ use core::convert::Infallible; use core::fmt::{Display, Error as FmtError, Formatter}; use core::str::FromStr; -use crate::prelude::*; - use super::error::ChannelError; +use crate::prelude::*; /// The version field for a `ChannelEnd`. /// diff --git a/crates/ibc/src/core/ics23_commitment/commitment.rs b/crates/ibc/src/core/ics23_commitment/commitment.rs index b5b876b71..1b8af341e 100644 --- a/crates/ibc/src/core/ics23_commitment/commitment.rs +++ b/crates/ibc/src/core/ics23_commitment/commitment.rs @@ -1,13 +1,14 @@ //! Defines core commitment types -use crate::core::ics23_commitment::error::CommitmentError; -use crate::prelude::*; +use core::convert::TryFrom; +use core::fmt; -use core::{convert::TryFrom, fmt}; use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; use subtle_encoding::{Encoding, Hex}; use super::merkle::MerkleProof; +use crate::core::ics23_commitment::error::CommitmentError; +use crate::prelude::*; /// Encodes a commitment root; most often a Merkle tree root hash. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -198,11 +199,12 @@ impl serde::Serialize for CommitmentPrefix { #[cfg(test)] pub mod test_util { - use super::CommitmentProofBytes; - use crate::prelude::*; use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; use ibc_proto::ics23::CommitmentProof; + use super::CommitmentProofBytes; + use crate::prelude::*; + /// Returns a dummy `CommitmentProofBytes`, for testing only! pub fn get_dummy_commitment_proof_bytes() -> CommitmentProofBytes { let parsed = CommitmentProof { proof: None }; diff --git a/crates/ibc/src/core/ics23_commitment/error.rs b/crates/ibc/src/core/ics23_commitment/error.rs index 5d70fac03..1a4bcaaeb 100644 --- a/crates/ibc/src/core/ics23_commitment/error.rs +++ b/crates/ibc/src/core/ics23_commitment/error.rs @@ -1,6 +1,7 @@ //! Defines the commitment error type use alloc::string::String; + use displaydoc::Display; use prost::DecodeError; diff --git a/crates/ibc/src/core/ics23_commitment/merkle.rs b/crates/ibc/src/core/ics23_commitment/merkle.rs index 81f679851..3f5bfb437 100644 --- a/crates/ibc/src/core/ics23_commitment/merkle.rs +++ b/crates/ibc/src/core/ics23_commitment/merkle.rs @@ -1,10 +1,6 @@ //! Merkle proof utilities -use crate::prelude::*; - -use ibc_proto::ibc::core::commitment::v1::MerklePath; -use ibc_proto::ibc::core::commitment::v1::MerkleProof as RawMerkleProof; -use ibc_proto::ibc::core::commitment::v1::MerkleRoot; +use ibc_proto::ibc::core::commitment::v1::{MerklePath, MerkleProof as RawMerkleProof, MerkleRoot}; use ibc_proto::ics23::commitment_proof::Proof; use ibc_proto::ics23::{ calculate_existence_root, verify_membership, verify_non_membership, CommitmentProof, @@ -14,6 +10,7 @@ use ibc_proto::ics23::{ use crate::core::ics23_commitment::commitment::{CommitmentPrefix, CommitmentRoot}; use crate::core::ics23_commitment::error::CommitmentError; use crate::core::ics23_commitment::specs::ProofSpecs; +use crate::prelude::*; pub fn apply_prefix(prefix: &CommitmentPrefix, mut path: Vec) -> MerklePath { let mut key_path: Vec = vec![format!("{prefix:?}")]; diff --git a/crates/ibc/src/core/ics23_commitment/specs.rs b/crates/ibc/src/core/ics23_commitment/specs.rs index 902a97315..ae7787a39 100644 --- a/crates/ibc/src/core/ics23_commitment/specs.rs +++ b/crates/ibc/src/core/ics23_commitment/specs.rs @@ -1,7 +1,8 @@ //! Defines proof specs, which encode the structure of proofs -use crate::prelude::*; use ibc_proto::ics23::{InnerSpec as RawInnerSpec, LeafOp as RawLeafOp, ProofSpec as RawProofSpec}; + +use crate::prelude::*; /// An array of proof specifications. /// /// This type encapsulates different types of proof specifications, mostly predefined, e.g., for diff --git a/crates/ibc/src/core/ics24_host/identifier.rs b/crates/ibc/src/core/ics24_host/identifier.rs index 6ce2f4b18..d669d8731 100644 --- a/crates/ibc/src/core/ics24_host/identifier.rs +++ b/crates/ibc/src/core/ics24_host/identifier.rs @@ -1,17 +1,15 @@ //! Defines identifier types pub(crate) mod validate; -use validate::*; - use core::fmt::{Debug, Display, Error as FmtError, Formatter}; use core::str::FromStr; use derive_more::Into; use displaydoc::Display; +use validate::*; use crate::clients::ics07_tendermint::client_type as tm_client_type; use crate::core::ics02_client::client_type::ClientType; - use crate::prelude::*; const CONNECTION_ID_PREFIX: &str = "connection"; diff --git a/crates/ibc/src/core/ics24_host/identifier/validate.rs b/crates/ibc/src/core/ics24_host/identifier/validate.rs index f926a4c5d..ddf8c98b8 100644 --- a/crates/ibc/src/core/ics24_host/identifier/validate.rs +++ b/crates/ibc/src/core/ics24_host/identifier/validate.rs @@ -1,6 +1,5 @@ -use crate::prelude::*; - use super::IdentifierError as Error; +use crate::prelude::*; /// Path separator (ie. forward slash '/') const PATH_SEPARATOR: char = '/'; @@ -123,10 +122,10 @@ pub fn validate_channel_identifier(id: &str) -> Result<(), Error> { #[cfg(test)] mod tests { - use super::*; - use test_log::test; + use super::*; + #[test] fn parse_invalid_port_id_min() { // invalid min port id diff --git a/crates/ibc/src/core/ics24_host/path.rs b/crates/ibc/src/core/ics24_host/path.rs index 24dc1bb48..c01eb5797 100644 --- a/crates/ibc/src/core/ics24_host/path.rs +++ b/crates/ibc/src/core/ics24_host/path.rs @@ -1,17 +1,17 @@ //! Defines all store paths used by IBC -use crate::{prelude::*, Height}; - /// Path-space as listed in ICS-024 /// https://github.com/cosmos/ibc/tree/master/spec/core/ics-024-host-requirements#path-space /// Some of these are implemented in other ICSs, but ICS-024 has a nice summary table. /// use core::str::FromStr; +use derive_more::{Display, From}; + use crate::core::ics04_channel::packet::Sequence; use crate::core::ics24_host::identifier::{ChannelId, ClientId, ConnectionId, PortId}; - -use derive_more::{Display, From}; +use crate::prelude::*; +use crate::Height; /// ABCI client upgrade keys /// - The key identifying the upgraded IBC state within the upgrade sub-store @@ -834,9 +834,10 @@ fn parse_upgrades(components: &[&str]) -> Option { #[cfg(test)] mod tests { - use super::*; use core::str::FromStr; + use super::*; + #[test] fn invalid_path_doesnt_parse() { let invalid_path = Path::from_str("clients/clientType"); diff --git a/crates/ibc/src/core/mod.rs b/crates/ibc/src/core/mod.rs index 66d10b0dd..3bef22053 100644 --- a/crates/ibc/src/core/mod.rs +++ b/crates/ibc/src/core/mod.rs @@ -36,15 +36,9 @@ mod context; mod handler; mod msgs; -pub use handler::dispatch; -pub use handler::execute; -pub use handler::validate; - pub use context::*; - -pub use msgs::Msg; -pub use msgs::MsgEnvelope; - +pub use handler::{dispatch, execute, validate}; pub use ics04_channel::handler::send_packet::{ send_packet, send_packet_execute, send_packet_validate, }; +pub use msgs::{Msg, MsgEnvelope}; diff --git a/crates/ibc/src/core/msgs.rs b/crates/ibc/src/core/msgs.rs index 66a2c6eaf..7f8fe8a53 100644 --- a/crates/ibc/src/core/msgs.rs +++ b/crates/ibc/src/core/msgs.rs @@ -1,6 +1,5 @@ -use crate::prelude::*; - use ibc_proto::google::protobuf::Any; +use ibc_proto::protobuf::Protobuf; use crate::core::context::RouterError; use crate::core::ics02_client::msgs::{ @@ -13,7 +12,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 ibc_proto::protobuf::Protobuf; +use crate::prelude::*; /// Trait to be implemented by all IBC messages pub trait Msg: Clone { diff --git a/crates/ibc/src/core/router.rs b/crates/ibc/src/core/router.rs index 81adbf99d..4cdb66524 100644 --- a/crates/ibc/src/core/router.rs +++ b/crates/ibc/src/core/router.rs @@ -1,6 +1,5 @@ //! Defines the `Router`, which binds modules to ports -use crate::prelude::*; use alloc::borrow::Borrow; use core::fmt::{Debug, Display, Error as FmtError, Formatter}; @@ -10,8 +9,8 @@ use crate::core::ics04_channel::channel::{Counterparty, Order}; use crate::core::ics04_channel::error::{ChannelError, PacketError}; use crate::core::ics04_channel::packet::Packet; use crate::core::ics04_channel::Version; -use crate::core::ics24_host::identifier::PortId; -use crate::core::ics24_host::identifier::{ChannelId, ConnectionId}; +use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; +use crate::prelude::*; use crate::signer::Signer; /// Router as defined in ICS-26, which binds modules to ports. diff --git a/crates/ibc/src/core/timestamp.rs b/crates/ibc/src/core/timestamp.rs index e0c6079fb..64add0694 100644 --- a/crates/ibc/src/core/timestamp.rs +++ b/crates/ibc/src/core/timestamp.rs @@ -1,7 +1,5 @@ //! Defines the representation of timestamps used in packet timeouts -use crate::prelude::*; - use core::fmt::{Display, Error as FmtError, Formatter}; use core::hash::{Hash, Hasher}; use core::num::ParseIntError; @@ -13,6 +11,8 @@ use displaydoc::Display; use tendermint::Time; use time::OffsetDateTime; +use crate::prelude::*; + pub const ZERO_DURATION: Duration = Duration::from_secs(0); /// A newtype wrapper over `Option