diff --git a/Cargo.toml b/Cargo.toml index c5ba0fbff..27c6452bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,12 +95,12 @@ ibc-core-handler = { version = "0.55.1", path = "./ibc-core/ics25-handler", d ibc-core-router = { version = "0.55.1", path = "./ibc-core/ics26-routing", default-features = false } ibc-query = { version = "0.55.1", path = "./ibc-query", default-features = false } -ibc-eureka-core-client = { version = "0.55.1", path = "./ibc-eureka-core/ics02-client", default-features = false } -ibc-eureka-core-connection = { version = "0.55.1", path = "./ibc-eureka-core/ics03-connection", default-features = false } -ibc-eureka-core-channel = { version = "0.55.1", path = "./ibc-eureka-core/ics04-channel", default-features = false } -ibc-eureka-core-host = { version = "0.55.1", path = "./ibc-eureka-core/ics24-host", default-features = false } -ibc-eureka-core-handler = { version = "0.55.1", path = "./ibc-eureka-core/ics25-handler", default-features = false } -ibc-eureka-core-router = { version = "0.55.1", path = "./ibc-eureka-core/ics26-routing", default-features = false } +ibc-eureka-core-client = { version = "0.55.1", path = "./ibc-eureka-core/ics02-client", default-features = false } +# ibc-eureka-core-connection = { version = "0.55.1", path = "./ibc-eureka-core/ics03-connection", default-features = false } +ibc-eureka-core-channel = { version = "0.55.1", path = "./ibc-eureka-core/ics04-channel", default-features = false } +ibc-eureka-core-host = { version = "0.55.1", path = "./ibc-eureka-core/ics24-host", default-features = false } +ibc-eureka-core-handler = { version = "0.55.1", path = "./ibc-eureka-core/ics25-handler", default-features = false } +ibc-eureka-core-router = { version = "0.55.1", path = "./ibc-eureka-core/ics26-routing", default-features = false } ibc-client-tendermint = { version = "0.55.1", path = "./ibc-clients/ics07-tendermint", default-features = false } @@ -121,10 +121,10 @@ ibc-client-wasm-types = { version = "0.55.1", path = "./ibc-clients/ics08- ibc-app-transfer-types = { version = "0.55.1", path = "./ibc-apps/ics20-transfer/types", default-features = false } ibc-app-nft-transfer-types = { version = "0.55.1", path = "./ibc-apps/ics721-nft-transfer/types", default-features = false } -ibc-eureka-core-client-context = { version = "0.55.1", path = "./ibc-eureka-core/ics02-client/context", default-features = false } -ibc-eureka-core-client-types = { version = "0.55.1", path = "./ibc-eureka-core/ics02-client/types", default-features = false } -ibc-eureka-core-channel-types = { version = "0.55.1", path = "./ibc-eureka-core/ics04-channel/types", default-features = false } -ibc-eureka-core-connection-types = { version = "0.55.1", path = "./ibc-eureka-core/ics03-connection/types", default-features = false } +ibc-eureka-core-client-context = { version = "0.55.1", path = "./ibc-eureka-core/ics02-client/context", default-features = false } +ibc-eureka-core-client-types = { version = "0.55.1", path = "./ibc-eureka-core/ics02-client/types", default-features = false } +ibc-eureka-core-channel-types = { version = "0.55.1", path = "./ibc-eureka-core/ics04-channel/types", default-features = false } +# ibc-eureka-core-connection-types = { version = "0.55.1", path = "./ibc-eureka-core/ics03-connection/types", default-features = false } ibc-eureka-core-commitment-types = { version = "0.55.1", path = "./ibc-eureka-core/ics23-commitment/types", default-features = false } ibc-eureka-core-host-cosmos = { version = "0.55.1", path = "./ibc-eureka-core/ics24-host/cosmos", default-features = false } ibc-eureka-core-host-types = { version = "0.55.1", path = "./ibc-eureka-core/ics24-host/types", default-features = false } diff --git a/ibc-eureka-core/Cargo.toml b/ibc-eureka-core/Cargo.toml index e017a9395..650574894 100644 --- a/ibc-eureka-core/Cargo.toml +++ b/ibc-eureka-core/Cargo.toml @@ -19,7 +19,6 @@ all-features = true [dependencies] ibc-eureka-core-client = { workspace = true } -ibc-eureka-core-connection = { workspace = true } ibc-eureka-core-channel = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-host = { workspace = true } @@ -32,7 +31,6 @@ ibc-primitives = { workspace = true } default = [ "std" ] std = [ "ibc-eureka-core-client/std", - "ibc-eureka-core-connection/std", "ibc-eureka-core-channel/std", "ibc-eureka-core-commitment-types/std", "ibc-eureka-core-host/std", @@ -42,7 +40,6 @@ std = [ ] serde = [ "ibc-eureka-core-client/serde", - "ibc-eureka-core-connection/serde", "ibc-eureka-core-channel/serde", "ibc-eureka-core-commitment-types/serde", "ibc-eureka-core-host/serde", @@ -52,7 +49,6 @@ serde = [ ] borsh = [ "ibc-eureka-core-client/borsh", - "ibc-eureka-core-connection/borsh", "ibc-eureka-core-channel/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host/borsh", @@ -62,7 +58,6 @@ borsh = [ ] schema = [ "ibc-eureka-core-client/schema", - "ibc-eureka-core-connection/schema", "ibc-eureka-core-channel/schema", "ibc-eureka-core-commitment-types/schema", "ibc-eureka-core-host/schema", @@ -74,7 +69,6 @@ schema = [ ] parity-scale-codec = [ "ibc-eureka-core-client/parity-scale-codec", - "ibc-eureka-core-connection/parity-scale-codec", "ibc-eureka-core-channel/parity-scale-codec", "ibc-eureka-core-commitment-types/parity-scale-codec", "ibc-eureka-core-host/parity-scale-codec", diff --git a/ibc-eureka-core/ics03-connection/Cargo.toml b/ibc-eureka-core/ics03-connection/Cargo.toml deleted file mode 100644 index e24b0be06..000000000 --- a/ibc-eureka-core/ics03-connection/Cargo.toml +++ /dev/null @@ -1,73 +0,0 @@ -[package] -name = "ibc-eureka-core-connection" -version = { workspace = true } -authors = { workspace = true } -edition = { workspace = true } -rust-version = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -keywords = [ "blockchain", "cosmos", "ibc", "connection" ] -readme = "./../README.md" - -description = """ - Maintained by `ibc-rs`, contains the implementation of the ICS-03 Connection Semantics and - re-exports essential data structures and domain types from `ibc-eureka-core-connection-types` crate. -""" - -[package.metadata.docs.rs] -all-features = true - -[dependencies] -ibc-eureka-core-client = { workspace = true } -ibc-eureka-core-connection-types = { workspace = true } -ibc-eureka-core-host = { workspace = true } -ibc-eureka-core-handler-types = { workspace = true } -ibc-primitives = { workspace = true } -ibc-client-wasm-types = { workspace = true, optional = true } - -prost = { workspace = true, optional = true } - -[features] -default = [ "std" ] -std = [ - "ibc-eureka-core-client/std", - "ibc-eureka-core-connection-types/std", - "ibc-eureka-core-host/std", - "ibc-eureka-core-handler-types/std", - "ibc-primitives/std", - "wasm-client", -] -serde = [ - "ibc-eureka-core-client/serde", - "ibc-eureka-core-connection-types/serde", - "ibc-eureka-core-host/serde", - "ibc-eureka-core-handler-types/serde", - "ibc-primitives/serde", -] -schema = [ - "ibc-eureka-core-client/schema", - "ibc-eureka-core-connection-types/schema", - "ibc-eureka-core-host/schema", - "ibc-eureka-core-handler-types/schema", - "ibc-primitives/schema", - "serde", - "std", -] -borsh = [ - "ibc-eureka-core-client/borsh", - "ibc-eureka-core-connection-types/borsh", - "ibc-eureka-core-host/borsh", - "ibc-eureka-core-handler-types/borsh", - "ibc-primitives/borsh", -] -parity-scale-codec = [ - "ibc-eureka-core-client/parity-scale-codec", - "ibc-eureka-core-connection-types/parity-scale-codec", - "ibc-eureka-core-host/parity-scale-codec", - "ibc-eureka-core-handler-types/parity-scale-codec", - "ibc-primitives/parity-scale-codec", -] -wasm-client = [ - "dep:ibc-client-wasm-types", - "dep:prost", -] diff --git a/ibc-eureka-core/ics03-connection/src/delay.rs b/ibc-eureka-core/ics03-connection/src/delay.rs deleted file mode 100644 index d49cdb6ad..000000000 --- a/ibc-eureka-core/ics03-connection/src/delay.rs +++ /dev/null @@ -1,48 +0,0 @@ -use ibc_eureka_core_client::context::ClientValidationContext; -use ibc_eureka_core_client::types::Height; -use ibc_eureka_core_connection_types::error::ConnectionError; -use ibc_eureka_core_connection_types::ConnectionEnd; -use ibc_eureka_core_host::ValidationContext; - -pub fn verify_conn_delay_passed( - ctx: &Ctx, - packet_proof_height: Height, - connection_end: &ConnectionEnd, -) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, -{ - // Fetch the current host chain time and height. - let current_host_time = ctx.host_timestamp()?; - let current_host_height = ctx.host_height()?; - - // Fetch the latest time and height that the counterparty client was updated on the host chain. - let client_id = connection_end.client_id(); - let last_client_update = ctx - .get_client_validation_context() - .client_update_meta(client_id, &packet_proof_height)?; - - // Fetch the connection delay time and height periods. - let conn_delay_time_period = connection_end.delay_period(); - let conn_delay_height_period = ctx.block_delay(&conn_delay_time_period); - - // Verify that the current host chain time is later than the last client update time - let earliest_valid_time = (last_client_update.0 + conn_delay_time_period)?; - if current_host_time < earliest_valid_time { - return Err(ConnectionError::InsufficientTimeElapsed { - current_host_time, - earliest_valid_time, - }); - } - - // Verify that the current host chain height is later than the last client update height - let earliest_valid_height = last_client_update.1.add(conn_delay_height_period); - if current_host_height < earliest_valid_height { - return Err(ConnectionError::InsufficientBlocksElapsed { - current_host_height, - earliest_valid_height, - }); - }; - - Ok(()) -} diff --git a/ibc-eureka-core/ics03-connection/src/handler/conn_open_ack.rs b/ibc-eureka-core/ics03-connection/src/handler/conn_open_ack.rs deleted file mode 100644 index da8a1318a..000000000 --- a/ibc-eureka-core/ics03-connection/src/handler/conn_open_ack.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Protocol logic specific to processing ICS3 messages of type `MsgConnectionOpenAck`. - -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_client::types::error::ClientError; -use ibc_eureka_core_connection_types::error::ConnectionError; -use ibc_eureka_core_connection_types::events::OpenAck; -use ibc_eureka_core_connection_types::msgs::MsgConnectionOpenAck; -use ibc_eureka_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::identifiers::ClientId; -use ibc_eureka_core_host::types::path::{ - ClientConsensusStatePath, ClientStatePath, ConnectionPath, Path, -}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::{Any, Protobuf}; -use ibc_primitives::ToVec; - -use crate::handler::{pack_host_consensus_state, unpack_host_client_state}; - -pub fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenAck) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, - >::Error: Into, -{ - let vars = LocalVars::new(ctx_a, &msg)?; - validate_impl(ctx_a, &msg, &vars) -} - -fn validate_impl( - ctx_a: &Ctx, - msg: &MsgConnectionOpenAck, - vars: &LocalVars, -) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, - >::Error: Into, -{ - ctx_a.validate_message_signer(&msg.signer)?; - - let host_height = ctx_a.host_height()?; - - if msg.consensus_height_of_a_on_b > host_height { - return Err(ConnectionError::InsufficientConsensusHeight { - target_height: msg.consensus_height_of_a_on_b, - current_height: host_height, - }); - } - - let client_val_ctx_a = ctx_a.get_client_validation_context(); - - let client_state_of_a_on_b = unpack_host_client_state::( - msg.client_state_of_a_on_b.clone(), - vars.client_id_on_b(), - )?; - - ctx_a.validate_self_client(client_state_of_a_on_b)?; - - msg.version - .verify_is_supported(vars.conn_end_on_a.versions())?; - - vars.conn_end_on_a.verify_state_matches(&State::Init)?; - - // Proof verification. - { - let client_state_of_b_on_a = client_val_ctx_a.client_state(vars.client_id_on_a())?; - - client_state_of_b_on_a - .status(client_val_ctx_a, vars.client_id_on_a())? - .verify_is_active()?; - - client_state_of_b_on_a.validate_proof_height(msg.proofs_height_on_b)?; - - let client_cons_state_path_on_a = ClientConsensusStatePath::new( - vars.client_id_on_a().clone(), - msg.proofs_height_on_b.revision_number(), - msg.proofs_height_on_b.revision_height(), - ); - - let consensus_state_of_b_on_a = - client_val_ctx_a.consensus_state(&client_cons_state_path_on_a)?; - - let prefix_on_a = ctx_a.commitment_prefix(); - let prefix_on_b = vars.conn_end_on_a.counterparty().prefix(); - - { - let expected_conn_end_on_b = ConnectionEnd::new( - State::TryOpen, - vars.client_id_on_b().clone(), - Counterparty::new( - vars.client_id_on_a().clone(), - Some(msg.conn_id_on_a.clone()), - prefix_on_a, - ), - vec![msg.version.clone()], - vars.conn_end_on_a.delay_period(), - )?; - - client_state_of_b_on_a.verify_membership( - prefix_on_b, - &msg.proof_conn_end_on_b, - consensus_state_of_b_on_a.root(), - Path::Connection(ConnectionPath::new(&msg.conn_id_on_b)), - expected_conn_end_on_b.encode_vec(), - )?; - } - - client_state_of_b_on_a.verify_membership( - prefix_on_b, - &msg.proof_client_state_of_a_on_b, - consensus_state_of_b_on_a.root(), - Path::ClientState(ClientStatePath::new(vars.client_id_on_b().clone())), - msg.client_state_of_a_on_b.to_vec(), - )?; - - let expected_consensus_state_of_a_on_b = - ctx_a.host_consensus_state(&msg.consensus_height_of_a_on_b)?; - - let stored_consensus_state_of_a_on_b = - pack_host_consensus_state(expected_consensus_state_of_a_on_b, vars.client_id_on_b()); - - let client_cons_state_path_on_b = ClientConsensusStatePath::new( - vars.client_id_on_b().clone(), - msg.consensus_height_of_a_on_b.revision_number(), - msg.consensus_height_of_a_on_b.revision_height(), - ); - - client_state_of_b_on_a.verify_membership( - prefix_on_b, - &msg.proof_consensus_state_of_a_on_b, - consensus_state_of_b_on_a.root(), - Path::ClientConsensusState(client_cons_state_path_on_b), - stored_consensus_state_of_a_on_b.to_vec(), - )?; - } - - Ok(()) -} - -pub fn execute(ctx_a: &mut Ctx, msg: MsgConnectionOpenAck) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let vars = LocalVars::new(ctx_a, &msg)?; - execute_impl(ctx_a, msg, vars) -} - -fn execute_impl( - ctx_a: &mut Ctx, - msg: MsgConnectionOpenAck, - vars: LocalVars, -) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let event = IbcEvent::OpenAckConnection(OpenAck::new( - msg.conn_id_on_a.clone(), - vars.client_id_on_a().clone(), - msg.conn_id_on_b.clone(), - vars.client_id_on_b().clone(), - )); - ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Connection))?; - ctx_a.emit_ibc_event(event)?; - - ctx_a.log_message("success: conn_open_ack verification passed".to_string())?; - - { - let new_conn_end_on_a = { - let mut counterparty = vars.conn_end_on_a.counterparty().clone(); - counterparty.connection_id = Some(msg.conn_id_on_b.clone()); - - let mut new_conn_end_on_a = vars.conn_end_on_a; - new_conn_end_on_a.set_state(State::Open); - new_conn_end_on_a.set_version(msg.version.clone()); - new_conn_end_on_a.set_counterparty(counterparty); - new_conn_end_on_a - }; - - ctx_a.store_connection(&ConnectionPath::new(&msg.conn_id_on_a), new_conn_end_on_a)?; - } - - Ok(()) -} - -struct LocalVars { - conn_end_on_a: ConnectionEnd, -} - -impl LocalVars { - fn new(ctx_a: &Ctx, msg: &MsgConnectionOpenAck) -> Result - where - Ctx: ValidationContext, - { - Ok(LocalVars { - conn_end_on_a: ctx_a.connection_end(&msg.conn_id_on_a)?, - }) - } - - fn client_id_on_a(&self) -> &ClientId { - self.conn_end_on_a.client_id() - } - - fn client_id_on_b(&self) -> &ClientId { - self.conn_end_on_a.counterparty().client_id() - } -} diff --git a/ibc-eureka-core/ics03-connection/src/handler/conn_open_confirm.rs b/ibc-eureka-core/ics03-connection/src/handler/conn_open_confirm.rs deleted file mode 100644 index fcdcadaef..000000000 --- a/ibc-eureka-core/ics03-connection/src/handler/conn_open_confirm.rs +++ /dev/null @@ -1,164 +0,0 @@ -//! Protocol logic specific to processing ICS3 messages of type `MsgConnectionOpenConfirm`. - -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection_types::error::ConnectionError; -use ibc_eureka_core_connection_types::events::OpenConfirm; -use ibc_eureka_core_connection_types::msgs::MsgConnectionOpenConfirm; -use ibc_eureka_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::identifiers::{ClientId, ConnectionId}; -use ibc_eureka_core_host::types::path::{ClientConsensusStatePath, ConnectionPath, Path}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::Protobuf; - -pub fn validate(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, -{ - let vars = LocalVars::new(ctx_b, msg)?; - validate_impl(ctx_b, msg, &vars) -} - -fn validate_impl( - ctx_b: &Ctx, - msg: &MsgConnectionOpenConfirm, - vars: &LocalVars, -) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, -{ - ctx_b.validate_message_signer(&msg.signer)?; - - let conn_end_on_b = vars.conn_end_on_b(); - - conn_end_on_b.verify_state_matches(&State::TryOpen)?; - - let client_id_on_a = vars.client_id_on_a(); - let client_id_on_b = vars.client_id_on_b(); - let conn_id_on_a = vars.conn_id_on_a()?; - - // Verify proofs - { - let client_val_ctx_b = ctx_b.get_client_validation_context(); - - let client_state_of_a_on_b = client_val_ctx_b.client_state(client_id_on_b)?; - - client_state_of_a_on_b - .status(client_val_ctx_b, client_id_on_b)? - .verify_is_active()?; - - client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; - - let client_cons_state_path_on_b = ClientConsensusStatePath::new( - client_id_on_b.clone(), - msg.proof_height_on_a.revision_number(), - msg.proof_height_on_a.revision_height(), - ); - let consensus_state_of_a_on_b = - client_val_ctx_b.consensus_state(&client_cons_state_path_on_b)?; - - let prefix_on_a = conn_end_on_b.counterparty().prefix(); - let prefix_on_b = ctx_b.commitment_prefix(); - - let expected_conn_end_on_a = ConnectionEnd::new( - State::Open, - client_id_on_a.clone(), - Counterparty::new( - client_id_on_b.clone(), - Some(msg.conn_id_on_b.clone()), - prefix_on_b, - ), - conn_end_on_b.versions().to_vec(), - conn_end_on_b.delay_period(), - )?; - - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_conn_end_on_a, - consensus_state_of_a_on_b.root(), - Path::Connection(ConnectionPath::new(conn_id_on_a)), - expected_conn_end_on_a.encode_vec(), - )?; - } - - Ok(()) -} - -pub fn execute(ctx_b: &mut Ctx, msg: &MsgConnectionOpenConfirm) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let vars = LocalVars::new(ctx_b, msg)?; - execute_impl(ctx_b, msg, vars) -} - -fn execute_impl( - ctx_b: &mut Ctx, - msg: &MsgConnectionOpenConfirm, - vars: LocalVars, -) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let client_id_on_a = vars.client_id_on_a(); - let client_id_on_b = vars.client_id_on_b(); - let conn_id_on_a = vars.conn_id_on_a()?; - - let event = IbcEvent::OpenConfirmConnection(OpenConfirm::new( - msg.conn_id_on_b.clone(), - client_id_on_b.clone(), - conn_id_on_a.clone(), - client_id_on_a.clone(), - )); - ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Connection))?; - ctx_b.emit_ibc_event(event)?; - ctx_b.log_message("success: conn_open_confirm verification passed".to_string())?; - - { - let new_conn_end_on_b = { - let mut new_conn_end_on_b = vars.conn_end_on_b; - - new_conn_end_on_b.set_state(State::Open); - new_conn_end_on_b - }; - - ctx_b.store_connection(&ConnectionPath(msg.conn_id_on_b.clone()), new_conn_end_on_b)?; - } - - Ok(()) -} - -struct LocalVars { - conn_end_on_b: ConnectionEnd, -} - -impl LocalVars { - fn new(ctx_b: &Ctx, msg: &MsgConnectionOpenConfirm) -> Result - where - Ctx: ValidationContext, - { - Ok(Self { - conn_end_on_b: ctx_b.connection_end(&msg.conn_id_on_b)?, - }) - } - - fn conn_end_on_b(&self) -> &ConnectionEnd { - &self.conn_end_on_b - } - - fn client_id_on_a(&self) -> &ClientId { - self.conn_end_on_b.counterparty().client_id() - } - - fn client_id_on_b(&self) -> &ClientId { - self.conn_end_on_b.client_id() - } - - fn conn_id_on_a(&self) -> Result<&ConnectionId, ConnectionError> { - self.conn_end_on_b - .counterparty() - .connection_id() - .ok_or(ConnectionError::InvalidCounterparty) - } -} diff --git a/ibc-eureka-core/ics03-connection/src/handler/conn_open_init.rs b/ibc-eureka-core/ics03-connection/src/handler/conn_open_init.rs deleted file mode 100644 index 3be0b2800..000000000 --- a/ibc-eureka-core/ics03-connection/src/handler/conn_open_init.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Protocol logic specific to ICS3 messages of type `MsgConnectionOpenInit`. -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection_types::error::ConnectionError; -use ibc_eureka_core_connection_types::events::OpenInit; -use ibc_eureka_core_connection_types::msgs::MsgConnectionOpenInit; -use ibc_eureka_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::identifiers::ConnectionId; -use ibc_eureka_core_host::types::path::{ClientConnectionPath, ConnectionPath}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_primitives::prelude::*; - -pub fn validate(ctx_a: &Ctx, msg: MsgConnectionOpenInit) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, -{ - ctx_a.validate_message_signer(&msg.signer)?; - - let client_val_ctx_a = ctx_a.get_client_validation_context(); - - // An IBC client running on the local (host) chain should exist. - let client_state_of_b_on_a = client_val_ctx_a.client_state(&msg.client_id_on_a)?; - - client_state_of_b_on_a - .status(client_val_ctx_a, &msg.client_id_on_a)? - .verify_is_active()?; - - if let Some(version) = msg.version { - version.verify_is_supported(&ctx_a.get_compatible_versions())?; - } - - Ok(()) -} - -pub fn execute(ctx_a: &mut Ctx, msg: MsgConnectionOpenInit) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let versions = if let Some(version) = msg.version { - version.verify_is_supported(&ctx_a.get_compatible_versions())?; - vec![version] - } else { - ctx_a.get_compatible_versions() - }; - - let conn_end_on_a = ConnectionEnd::new( - State::Init, - msg.client_id_on_a.clone(), - Counterparty::new( - msg.counterparty.client_id().clone(), - None, - msg.counterparty.prefix().clone(), - ), - versions, - msg.delay_period, - )?; - - // Construct the identifier for the new connection. - let conn_id_on_a = ConnectionId::new(ctx_a.connection_counter()?); - - ctx_a.log_message(format!( - "success: conn_open_init: generated new connection identifier: {conn_id_on_a}" - ))?; - - { - let client_id_on_b = msg.counterparty.client_id().clone(); - - let event = IbcEvent::OpenInitConnection(OpenInit::new( - conn_id_on_a.clone(), - msg.client_id_on_a.clone(), - client_id_on_b, - )); - ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Connection))?; - ctx_a.emit_ibc_event(event)?; - } - - ctx_a.increase_connection_counter()?; - ctx_a.store_connection_to_client( - &ClientConnectionPath::new(msg.client_id_on_a), - conn_id_on_a.clone(), - )?; - ctx_a.store_connection(&ConnectionPath::new(&conn_id_on_a), conn_end_on_a)?; - - Ok(()) -} diff --git a/ibc-eureka-core/ics03-connection/src/handler/conn_open_try.rs b/ibc-eureka-core/ics03-connection/src/handler/conn_open_try.rs deleted file mode 100644 index 49193a6c7..000000000 --- a/ibc-eureka-core/ics03-connection/src/handler/conn_open_try.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Protocol logic specific to processing ICS3 messages of type `MsgConnectionOpenTry`.; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_client::types::error::ClientError; -use ibc_eureka_core_connection_types::error::ConnectionError; -use ibc_eureka_core_connection_types::events::OpenTry; -use ibc_eureka_core_connection_types::msgs::MsgConnectionOpenTry; -use ibc_eureka_core_connection_types::{ConnectionEnd, Counterparty, State}; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::identifiers::{ClientId, ConnectionId}; -use ibc_eureka_core_host::types::path::{ - ClientConnectionPath, ClientConsensusStatePath, ClientStatePath, ConnectionPath, Path, -}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::{Any, Protobuf}; -use ibc_primitives::ToVec; - -use crate::handler::{pack_host_consensus_state, unpack_host_client_state}; - -pub fn validate(ctx_b: &Ctx, msg: MsgConnectionOpenTry) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, - >::Error: Into, -{ - let vars = LocalVars::new(ctx_b, &msg)?; - validate_impl(ctx_b, &msg, &vars) -} - -fn validate_impl( - ctx_b: &Ctx, - msg: &MsgConnectionOpenTry, - vars: &LocalVars, -) -> Result<(), ConnectionError> -where - Ctx: ValidationContext, - >::Error: Into, -{ - ctx_b.validate_message_signer(&msg.signer)?; - - let client_val_ctx_b = ctx_b.get_client_validation_context(); - - let client_state_of_b_on_a = unpack_host_client_state::( - msg.client_state_of_b_on_a.clone(), - &vars.client_id_on_a, - )?; - - ctx_b.validate_self_client(client_state_of_b_on_a)?; - - let host_height = ctx_b.host_height()?; - - if msg.consensus_height_of_b_on_a > host_height { - // Fail if the consensus height is too advanced. - return Err(ConnectionError::InsufficientConsensusHeight { - target_height: msg.consensus_height_of_b_on_a, - current_height: host_height, - }); - } - - let client_id_on_a = msg.counterparty.client_id(); - - // Verify proofs - { - let client_state_of_a_on_b = - client_val_ctx_b.client_state(vars.conn_end_on_b.client_id())?; - - client_state_of_a_on_b - .status(client_val_ctx_b, &msg.client_id_on_b)? - .verify_is_active()?; - - client_state_of_a_on_b.validate_proof_height(msg.proofs_height_on_a)?; - - let client_cons_state_path_on_b = ClientConsensusStatePath::new( - msg.client_id_on_b.clone(), - msg.proofs_height_on_a.revision_number(), - msg.proofs_height_on_a.revision_height(), - ); - - let consensus_state_of_a_on_b = - client_val_ctx_b.consensus_state(&client_cons_state_path_on_b)?; - - let prefix_on_a = vars.conn_end_on_b.counterparty().prefix(); - let prefix_on_b = ctx_b.commitment_prefix(); - - { - let expected_conn_end_on_a = ConnectionEnd::new( - State::Init, - client_id_on_a.clone(), - Counterparty::new(msg.client_id_on_b.clone(), None, prefix_on_b), - msg.versions_on_a.clone(), - msg.delay_period, - )?; - - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_conn_end_on_a, - consensus_state_of_a_on_b.root(), - Path::Connection(ConnectionPath::new(&vars.conn_id_on_a)), - expected_conn_end_on_a.encode_vec(), - )?; - } - - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_client_state_of_b_on_a, - consensus_state_of_a_on_b.root(), - Path::ClientState(ClientStatePath::new(client_id_on_a.clone())), - msg.client_state_of_b_on_a.to_vec(), - )?; - - let expected_consensus_state_of_b_on_a = - ctx_b.host_consensus_state(&msg.consensus_height_of_b_on_a)?; - - let stored_consensus_state_of_b_on_a = - pack_host_consensus_state(expected_consensus_state_of_b_on_a, &vars.client_id_on_a); - - let client_cons_state_path_on_a = ClientConsensusStatePath::new( - client_id_on_a.clone(), - msg.consensus_height_of_b_on_a.revision_number(), - msg.consensus_height_of_b_on_a.revision_height(), - ); - - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_consensus_state_of_b_on_a, - consensus_state_of_a_on_b.root(), - Path::ClientConsensusState(client_cons_state_path_on_a), - stored_consensus_state_of_b_on_a.to_vec(), - )?; - } - - Ok(()) -} - -pub fn execute(ctx_b: &mut Ctx, msg: MsgConnectionOpenTry) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let vars = LocalVars::new(ctx_b, &msg)?; - execute_impl(ctx_b, msg, vars) -} - -fn execute_impl( - ctx_b: &mut Ctx, - msg: MsgConnectionOpenTry, - vars: LocalVars, -) -> Result<(), ConnectionError> -where - Ctx: ExecutionContext, -{ - let conn_id_on_a = vars - .conn_end_on_b - .counterparty() - .connection_id() - .ok_or(ConnectionError::InvalidCounterparty)?; - let event = IbcEvent::OpenTryConnection(OpenTry::new( - vars.conn_id_on_b.clone(), - msg.client_id_on_b.clone(), - conn_id_on_a.clone(), - vars.client_id_on_a.clone(), - )); - ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Connection))?; - ctx_b.emit_ibc_event(event)?; - ctx_b.log_message("success: conn_open_try verification passed".to_string())?; - - ctx_b.increase_connection_counter()?; - ctx_b.store_connection_to_client( - &ClientConnectionPath::new(msg.client_id_on_b), - vars.conn_id_on_b.clone(), - )?; - ctx_b.store_connection(&ConnectionPath::new(&vars.conn_id_on_b), vars.conn_end_on_b)?; - - Ok(()) -} - -struct LocalVars { - conn_id_on_b: ConnectionId, - conn_end_on_b: ConnectionEnd, - client_id_on_a: ClientId, - conn_id_on_a: ConnectionId, -} - -impl LocalVars { - fn new(ctx_b: &Ctx, msg: &MsgConnectionOpenTry) -> Result - where - Ctx: ValidationContext, - { - let version_on_b = ctx_b.pick_version(&msg.versions_on_a)?; - - Ok(Self { - conn_id_on_b: ConnectionId::new(ctx_b.connection_counter()?), - conn_end_on_b: ConnectionEnd::new( - State::TryOpen, - msg.client_id_on_b.clone(), - msg.counterparty.clone(), - vec![version_on_b], - msg.delay_period, - )?, - client_id_on_a: msg.counterparty.client_id().clone(), - conn_id_on_a: msg - .counterparty - .connection_id() - .ok_or(ConnectionError::InvalidCounterparty)? - .clone(), - }) - } -} diff --git a/ibc-eureka-core/ics03-connection/src/handler/mod.rs b/ibc-eureka-core/ics03-connection/src/handler/mod.rs deleted file mode 100644 index 0d2a0cb4a..000000000 --- a/ibc-eureka-core/ics03-connection/src/handler/mod.rs +++ /dev/null @@ -1,82 +0,0 @@ -use ibc_eureka_core_client::types::error::ClientError; -use ibc_eureka_core_connection_types::error::ConnectionError; -#[cfg(feature = "wasm-client")] -use ibc_eureka_core_host::types::error::DecodingError; -use ibc_eureka_core_host::types::identifiers::ClientId; -use ibc_primitives::proto::Any; - -pub mod conn_open_ack; -pub mod conn_open_confirm; -pub mod conn_open_init; -pub mod conn_open_try; - -/// Unpacks the client state from the format that is stored at the counterparty chain. -/// -/// Currently, the IBC-go enabled chains stores Wasm LightClient states in a WasmClientState -/// wrapper. This function unpacks the client state from the WasmClientState wrapper -/// if the client identifier at counterparty is of Wasm client type. -pub(crate) fn unpack_host_client_state( - value: Any, - host_client_id_at_counterparty: &ClientId, -) -> Result -where - CS: TryFrom, - >::Error: Into, -{ - #[cfg(feature = "wasm-client")] - if host_client_id_at_counterparty.is_wasm_client_id() { - use ibc_client_wasm_types::client_state::ClientState as WasmClientState; - use prost::Message; - - let wasm_client_state = - WasmClientState::try_from(value).expect("TODO(rano): propagate the error"); - - let any_client_state = ::decode(wasm_client_state.data.as_slice()) - .map_err(|e| ConnectionError::Decoding(DecodingError::Prost(e)))?; - - Ok(CS::try_from(any_client_state).map_err(Into::::into)?) - } else { - Ok(CS::try_from(value).map_err(Into::::into)?) - } - - #[cfg(not(feature = "wasm-client"))] - { - // this avoids lint warning for unused variable. - let _ = host_client_id_at_counterparty; - Ok(CS::try_from(value).map_err(Into::::into)?) - } -} - -/// Pack the host consensus state in the expected format stored at the counterparty chain. -/// -/// Currently, the IBC-go enabled chains stores Wasm LightClient states in a WasmConsensusState -/// wrapper. This function packs the consensus state in the WasmConsensusState wrapper -/// if the client identifier at counterparty is of Wasm client type. -pub(crate) fn pack_host_consensus_state( - value: CS, - host_client_id_at_counterparty: &ClientId, -) -> Any -where - CS: Into, -{ - let any_value = value.into(); - - #[cfg(feature = "wasm-client")] - if host_client_id_at_counterparty.is_wasm_client_id() { - use ibc_client_wasm_types::consensus_state::ConsensusState as WasmConsensusState; - use prost::Message; - - let wasm_consensus_state = WasmConsensusState::new(any_value.encode_to_vec()); - - wasm_consensus_state.into() - } else { - any_value - } - - #[cfg(not(feature = "wasm-client"))] - { - // this avoids lint warning for unused variable. - let _ = host_client_id_at_counterparty; - any_value - } -} diff --git a/ibc-eureka-core/ics03-connection/src/lib.rs b/ibc-eureka-core/ics03-connection/src/lib.rs deleted file mode 100644 index 01f0cdbac..000000000 --- a/ibc-eureka-core/ics03-connection/src/lib.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! ICS-03: Connection Semantics implementation to process connection open -//! handshake. Exports data structures and implementations of IBC core -//! connection module. -#![no_std] -#![forbid(unsafe_code)] -#![cfg_attr(not(test), deny(clippy::unwrap_used))] -#![cfg_attr(not(test), deny(clippy::disallowed_methods, clippy::disallowed_types,))] -#![deny( - warnings, - trivial_numeric_casts, - unused_import_braces, - unused_qualifications, - rust_2018_idioms -)] - -#[cfg(feature = "std")] -extern crate std; - -pub mod delay; -pub mod handler; - -/// Re-exports ICS-03 data structures from the `ibc-eureka-core-connection-types` crate -pub mod types { - #[doc(inline)] - pub use ibc_eureka_core_connection_types::*; -} diff --git a/ibc-eureka-core/ics03-connection/types/Cargo.toml b/ibc-eureka-core/ics03-connection/types/Cargo.toml deleted file mode 100644 index 34b05d79d..000000000 --- a/ibc-eureka-core/ics03-connection/types/Cargo.toml +++ /dev/null @@ -1,91 +0,0 @@ -[package] -name = "ibc-eureka-core-connection-types" -version = { workspace = true } -authors = { workspace = true } -edition = { workspace = true } -rust-version = { workspace = true } -license = { workspace = true } -repository = { workspace = true } -keywords = [ "blockchain", "cosmos", "ibc", "connection", "types" ] -readme = "./../../README.md" - -description = """ - Maintained by `ibc-rs`, encapsulates essential ICS-03 Connection Semantics data structures and domain types, - as specified in the Inter-Blockchain Communication (IBC) protocol. Designed for universal applicability - to facilitate development and integration across diverse IBC-enabled projects. -""" - -[package.metadata.docs.rs] -all-features = true - -[dependencies] -# external dependencies -borsh = { workspace = true, optional = true } -derive_more = { workspace = true } -displaydoc = { workspace = true } -schemars = { workspace = true, optional = true } -serde = { workspace = true, optional = true } -subtle-encoding = { workspace = true } - -# ibc dependencies -ibc-eureka-core-client-types = { workspace = true } -ibc-eureka-core-commitment-types = { workspace = true } -ibc-eureka-core-host-types = { workspace = true } -ibc-primitives = { workspace = true } -ibc-proto = { workspace = true } - -# cosmos dependencies -tendermint = { workspace = true } - -# parity dependencies -parity-scale-codec = { workspace = true, optional = true } -scale-info = { workspace = true, optional = true } - -[features] -default = [ "std" ] -std = [ - "displaydoc/std", - "subtle-encoding/std", - "serde/std", - "ibc-eureka-core-client-types/std", - "ibc-eureka-core-commitment-types/std", - "ibc-eureka-core-host-types/std", - "ibc-primitives/std", - "ibc-proto/std", - "tendermint/std", -] -serde = [ - "dep:serde", - "ibc-eureka-core-client-types/serde", - "ibc-eureka-core-commitment-types/serde", - "ibc-eureka-core-host-types/serde", - "ibc-primitives/serde", - "ibc-proto/serde", -] -schema = [ - "dep:schemars", - "ibc-eureka-core-client-types/schema", - "ibc-eureka-core-commitment-types/schema", - "ibc-eureka-core-host-types/schema", - "ibc-primitives/schema", - "ibc-proto/json-schema", - "serde", - "std", -] -borsh = [ - "dep:borsh", - "ibc-eureka-core-client-types/borsh", - "ibc-eureka-core-commitment-types/borsh", - "ibc-eureka-core-host-types/borsh", - "ibc-primitives/borsh", - "ibc-proto/borsh", -] -parity-scale-codec = [ - "dep:parity-scale-codec", - "dep:scale-info", - "ibc-eureka-core-client-types/parity-scale-codec", - "ibc-eureka-core-commitment-types/parity-scale-codec", - "ibc-eureka-core-host-types/parity-scale-codec", - "ibc-primitives/parity-scale-codec", - "ibc-proto/parity-scale-codec", -] diff --git a/ibc-eureka-core/ics03-connection/types/src/connection.rs b/ibc-eureka-core/ics03-connection/types/src/connection.rs deleted file mode 100644 index 81991d548..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/connection.rs +++ /dev/null @@ -1,523 +0,0 @@ -//! Defines the types that define a connection - -use core::fmt::{Display, Error as FmtError, Formatter}; -use core::time::Duration; - -use ibc_eureka_core_commitment_types::commitment::CommitmentPrefix; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ClientId, ConnectionId}; -use ibc_primitives::prelude::*; -use ibc_proto::ibc::core::connection::v1::{ - ConnectionEnd as RawConnectionEnd, Counterparty as RawCounterparty, - IdentifiedConnection as RawIdentifiedConnection, -}; -use ibc_proto::Protobuf; - -use crate::error::ConnectionError; -use crate::version::Version; - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq, Hash)] -pub struct IdentifiedConnectionEnd { - pub connection_id: ConnectionId, - pub connection_end: ConnectionEnd, -} - -impl IdentifiedConnectionEnd { - pub fn new(connection_id: ConnectionId, connection_end: ConnectionEnd) -> Self { - IdentifiedConnectionEnd { - connection_id, - connection_end, - } - } - - pub fn id(&self) -> &ConnectionId { - &self.connection_id - } - - pub fn end(&self) -> &ConnectionEnd { - &self.connection_end - } -} - -impl Protobuf for IdentifiedConnectionEnd {} - -impl TryFrom for IdentifiedConnectionEnd { - type Error = DecodingError; - - fn try_from(value: RawIdentifiedConnection) -> Result { - let raw_connection_end = RawConnectionEnd { - client_id: value.client_id.to_string(), - versions: value.versions, - state: value.state, - counterparty: value.counterparty, - delay_period: value.delay_period, - }; - - Ok(IdentifiedConnectionEnd { - connection_id: value.id.parse()?, - connection_end: raw_connection_end.try_into()?, - }) - } -} - -impl From for RawIdentifiedConnection { - fn from(value: IdentifiedConnectionEnd) -> Self { - RawIdentifiedConnection { - id: value.connection_id.to_string(), - client_id: value.connection_end.client_id.to_string(), - versions: value - .connection_end - .versions - .iter() - .map(|v| From::from(v.clone())) - .collect(), - state: value.connection_end.state as i32, - delay_period: value.connection_end.delay_period.as_nanos() as u64, - counterparty: Some(value.connection_end.counterparty().clone().into()), - } - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive(parity_scale_codec::Encode, parity_scale_codec::Decode,) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct ConnectionEnd { - pub state: State, - client_id: ClientId, - counterparty: Counterparty, - versions: Vec, - delay_period: Duration, -} - -mod sealed { - use super::*; - - #[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) - )] - struct InnerConnectionEnd { - pub state: State, - client_id: ClientId, - counterparty: Counterparty, - versions: Vec, - delay_period_secs: u64, - delay_period_nanos: u32, - } - - impl From for ConnectionEnd { - fn from(value: InnerConnectionEnd) -> Self { - Self { - state: value.state, - client_id: value.client_id, - counterparty: value.counterparty, - versions: value.versions, - delay_period: Duration::new(value.delay_period_secs, value.delay_period_nanos), - } - } - } - - impl From for InnerConnectionEnd { - fn from(value: ConnectionEnd) -> Self { - Self { - state: value.state, - client_id: value.client_id, - counterparty: value.counterparty, - versions: value.versions, - delay_period_secs: value.delay_period.as_secs(), - delay_period_nanos: value.delay_period.subsec_nanos(), - } - } - } - - #[cfg(feature = "borsh")] - impl borsh::BorshSerialize for ConnectionEnd { - fn serialize(&self, writer: &mut W) -> borsh::io::Result<()> { - let value = InnerConnectionEnd::from(self.clone()); - borsh::BorshSerialize::serialize(&value, writer) - } - } - - #[cfg(feature = "borsh")] - impl borsh::BorshDeserialize for ConnectionEnd { - fn deserialize_reader(reader: &mut R) -> borsh::io::Result { - let inner_conn_end = InnerConnectionEnd::deserialize_reader(reader)?; - Ok(ConnectionEnd::from(inner_conn_end)) - } - } - - #[cfg(feature = "parity-scale-codec")] - impl scale_info::TypeInfo for ConnectionEnd { - type Identity = Self; - - fn type_info() -> scale_info::Type { - scale_info::Type::builder() - .path(scale_info::Path::new("ConnectionEnd", module_path!())) - .composite( - scale_info::build::Fields::named() - .field(|f| f.ty::().name("state").type_name("State")) - .field(|f| f.ty::().name("client_id").type_name("ClientId")) - .field(|f| { - f.ty::() - .name("counterparty") - .type_name("Counterparty") - }) - .field(|f| { - f.ty::>() - .name("versions") - .type_name("Vec") - }) - .field(|f| f.ty::().name("delay_period_secs").type_name("u64")) - .field(|f| f.ty::().name("delay_period_nanos").type_name("u32")), - ) - } - } -} - -impl Protobuf for ConnectionEnd {} - -impl TryFrom for ConnectionEnd { - type Error = DecodingError; - - fn try_from(value: RawConnectionEnd) -> Result { - let state = value.state.try_into()?; - - if value.client_id.is_empty() { - return Err(DecodingError::missing_raw_data("connection end client ID"))?; - } - - if value.versions.is_empty() { - return Err(DecodingError::missing_raw_data("connection end versions"))?; - } - - Self::new( - state, - value.client_id.parse()?, - value - .counterparty - .ok_or(DecodingError::missing_raw_data("counterparty"))? - .try_into()?, - value - .versions - .into_iter() - .map(Version::try_from) - .collect::, _>>()?, - Duration::from_nanos(value.delay_period), - ) - .map_err(|_| DecodingError::invalid_raw_data("connection end")) - } -} - -impl From for RawConnectionEnd { - fn from(value: ConnectionEnd) -> Self { - RawConnectionEnd { - client_id: value.client_id.to_string(), - versions: value - .versions - .iter() - .map(|v| From::from(v.clone())) - .collect(), - state: value.state as i32, - counterparty: Some(value.counterparty.into()), - delay_period: value.delay_period.as_nanos() as u64, - } - } -} - -impl ConnectionEnd { - pub fn new( - state: State, - client_id: ClientId, - counterparty: Counterparty, - versions: Vec, - delay_period: Duration, - ) -> Result { - // Note: `versions`'s semantics vary based on the `State` of the connection: - // + Init: contains the set of compatible versions, - // + TryOpen/Open: contains the single version chosen by the handshake protocol. - if state != State::Init && versions.len() != 1 { - return Err(ConnectionError::InvalidState { description: "failed to initialize new ConnectionEnd; expected `Init` connection state and a single version".to_string() }); - } - - Ok(Self { - state, - client_id, - counterparty, - versions, - delay_period, - }) - } - - /// Getter for the state of this connection end. - pub fn state(&self) -> &State { - &self.state - } - - /// Setter for the `state` field. - pub fn set_state(&mut self, new_state: State) { - self.state = new_state; - } - - /// Setter for the `counterparty` field. - pub fn set_counterparty(&mut self, new_cparty: Counterparty) { - self.counterparty = new_cparty; - } - - /// Setter for the `version` field. - pub fn set_version(&mut self, new_version: Version) { - self.versions = vec![new_version]; - } - - /// Helper function to compare the counterparty of this end with another counterparty. - pub fn counterparty_matches(&self, other: &Counterparty) -> bool { - self.counterparty.eq(other) - } - - /// Helper function to compare the client id of this end with another client identifier. - pub fn client_id_matches(&self, other: &ClientId) -> bool { - self.client_id.eq(other) - } - - /// Helper function to determine whether the connection is open. - pub fn is_open(&self) -> bool { - self.state == State::Open - } - - /// Helper function to determine whether the connection is uninitialized. - pub fn is_uninitialized(&self) -> bool { - self.state == State::Uninitialized - } - - /// Checks if the state of this connection end matches with an expected state. - pub fn verify_state_matches(&self, expected: &State) -> Result<(), ConnectionError> { - if !self.state.eq(expected) { - return Err(ConnectionError::MismatchedConnectionStates { - expected: expected.to_string(), - actual: self.state.to_string(), - }); - } - Ok(()) - } - - /// Getter for the client id on the local party of this connection end. - pub fn client_id(&self) -> &ClientId { - &self.client_id - } - - /// Getter for the list of versions in this connection end. - pub fn versions(&self) -> &[Version] { - &self.versions - } - - /// Getter for the counterparty. - pub fn counterparty(&self) -> &Counterparty { - &self.counterparty - } - - /// Getter for the delay_period field. This represents the duration, at minimum, - /// to delay the sending of a packet after the client update for that packet has been submitted. - pub fn delay_period(&self) -> Duration { - self.delay_period - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq, Hash)] -pub struct Counterparty { - pub client_id: ClientId, - pub connection_id: Option, - pub prefix: CommitmentPrefix, -} - -impl Protobuf for Counterparty {} - -// Converts from the wire format RawCounterparty. Typically used from the relayer side -// during queries for response validation and to extract the Counterparty structure. -impl TryFrom for Counterparty { - type Error = DecodingError; - - fn try_from(raw_counterparty: RawCounterparty) -> Result { - let connection_id: Option = if raw_counterparty.connection_id.is_empty() { - None - } else { - Some(raw_counterparty.connection_id.parse()?) - }; - Ok(Counterparty::new( - raw_counterparty.client_id.parse()?, - connection_id, - raw_counterparty - .prefix - .ok_or(DecodingError::missing_raw_data("counterparty prefix"))? - .key_prefix - .into(), - )) - } -} - -impl From for RawCounterparty { - fn from(value: Counterparty) -> Self { - RawCounterparty { - client_id: value.client_id.as_str().to_string(), - connection_id: value - .connection_id - .map_or_else(|| "".to_string(), |v| v.as_str().to_string()), - prefix: Some(ibc_proto::ibc::core::commitment::v1::MerklePrefix { - key_prefix: value.prefix.into_vec(), - }), - } - } -} - -impl Counterparty { - pub fn new( - client_id: ClientId, - connection_id: Option, - prefix: CommitmentPrefix, - ) -> Self { - Self { - client_id, - connection_id, - prefix, - } - } - - /// Getter for the client id. - pub fn client_id(&self) -> &ClientId { - &self.client_id - } - - /// Getter for connection id. - pub fn connection_id(&self) -> Option<&ConnectionId> { - self.connection_id.as_ref() - } - - pub fn prefix(&self) -> &CommitmentPrefix { - &self.prefix - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize), - borsh(use_discriminant = false) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] -pub enum State { - Uninitialized = 0isize, - Init = 1isize, - TryOpen = 2isize, - Open = 3isize, -} - -impl State { - /// Yields the State as a string. - pub fn as_str(&self) -> &'static str { - match self { - Self::Uninitialized => "UNINITIALIZED", - Self::Init => "INIT", - Self::TryOpen => "TRYOPEN", - Self::Open => "OPEN", - } - } - - /// Parses the State out from an i32. - pub fn from_i32(s: i32) -> Result { - match s { - 0 => Ok(Self::Uninitialized), - 1 => Ok(Self::Init), - 2 => Ok(Self::TryOpen), - 3 => Ok(Self::Open), - _ => Err(ConnectionError::MismatchedConnectionStates { - expected: "0, 1, 2, or 3".to_string(), - actual: s.to_string(), - }), - } - } - - /// Returns if this connection state is `Open`. - pub fn is_open(self) -> bool { - self == State::Open - } - - /// Returns if this connection with this state - /// has progressed less than or the same as the argument. - /// - /// # Example - /// ```rust,ignore - /// assert!(State::Init.less_or_equal_progress(State::Open)); - /// assert!(State::TryOpen.less_or_equal_progress(State::TryOpen)); - /// assert!(!State::Open.less_or_equal_progress(State::Uninitialized)); - /// ``` - pub fn less_or_equal_progress(self, other: Self) -> bool { - self as u32 <= other as u32 - } -} - -impl Display for State { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { - write!(f, "{}", self.as_str()) - } -} - -impl TryFrom for State { - type Error = DecodingError; - - fn try_from(value: i32) -> Result { - match value { - 0 => Ok(Self::Uninitialized), - 1 => Ok(Self::Init), - 2 => Ok(Self::TryOpen), - 3 => Ok(Self::Open), - _ => Err(DecodingError::invalid_raw_data(format!( - "connection state expected to be 0, 1, 2, or 3, actual {value}", - ))), - } - } -} - -impl From for i32 { - fn from(value: State) -> Self { - value as i32 - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/error.rs b/ibc-eureka-core/ics03-connection/types/src/error.rs deleted file mode 100644 index b466594de..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/error.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Defines the connection error type - -use displaydoc::Display; -use ibc_eureka_core_client_types::error::ClientError; -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_host_types::error::{DecodingError, HostError, IdentifierError}; -use ibc_primitives::prelude::*; -use ibc_primitives::{Timestamp, TimestampError}; - -#[derive(Debug, Display)] -pub enum ConnectionError { - /// client error: {0} - Client(ClientError), - /// decoding error: {0} - Decoding(DecodingError), - /// host error: {0} - Host(HostError), - /// timestamp error: {0} - Timestamp(TimestampError), - /// invalid counterparty - InvalidCounterparty, - /// invalid connection state: {description} - InvalidState { description: String }, - /// mismatched connection states: expected `{expected}`, actual `{actual}` - MismatchedConnectionStates { expected: String, actual: String }, - /// missing supported features - MissingFeatures, - /// missing common version - MissingCommonVersion, - /// missing counterparty - MissingCounterparty, - /// insufficient consensus height `{current_height}` for host chain; needs to meet counterparty's height `{target_height}` - InsufficientConsensusHeight { - target_height: Height, - current_height: Height, - }, - /// insufficient blocks elapsed: current height `{current_host_height}` needs to meet `{earliest_valid_height}` - InsufficientBlocksElapsed { - current_host_height: Height, - earliest_valid_height: Height, - }, - /// insufficient time elapsed: current timestamp `{current_host_time}` needs to meet `{earliest_valid_time}` - InsufficientTimeElapsed { - current_host_time: Timestamp, - earliest_valid_time: Timestamp, - }, -} - -impl From for ConnectionError { - fn from(e: DecodingError) -> Self { - Self::Decoding(e) - } -} - -impl From for ConnectionError { - fn from(e: IdentifierError) -> Self { - Self::Decoding(DecodingError::Identifier(e)) - } -} - -impl From for ConnectionError { - fn from(e: TimestampError) -> Self { - Self::Timestamp(e) - } -} - -impl From for ConnectionError { - fn from(e: ClientError) -> Self { - Self::Client(e) - } -} - -impl From for ConnectionError { - fn from(e: HostError) -> Self { - Self::Host(e) - } -} - -#[cfg(feature = "std")] -impl std::error::Error for ConnectionError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match &self { - Self::Host(e) => Some(e), - Self::Client(e) => Some(e), - Self::Decoding(e) => Some(e), - Self::Timestamp(e) => Some(e), - _ => None, - } - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/events.rs b/ibc-eureka-core/ics03-connection/types/src/events.rs deleted file mode 100644 index 8a9f46495..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/events.rs +++ /dev/null @@ -1,413 +0,0 @@ -//! Types for the IBC events emitted from Tendermint Websocket by the connection module. - -use ibc_eureka_core_host_types::identifiers::{ClientId, ConnectionId}; -use ibc_primitives::prelude::*; -use tendermint::abci; - -/// Connection event types -const CONNECTION_OPEN_INIT_EVENT: &str = "connection_open_init"; -const CONNECTION_OPEN_TRY_EVENT: &str = "connection_open_try"; -const CONNECTION_OPEN_ACK_EVENT: &str = "connection_open_ack"; -const CONNECTION_OPEN_CONFIRM_EVENT: &str = "connection_open_confirm"; - -/// The content of the `key` field for the attribute containing the connection identifier. -pub const CONN_ID_ATTRIBUTE_KEY: &str = "connection_id"; -pub const CLIENT_ID_ATTRIBUTE_KEY: &str = "client_id"; -pub const COUNTERPARTY_CONN_ID_ATTRIBUTE_KEY: &str = "counterparty_connection_id"; -pub const COUNTERPARTY_CLIENT_ID_ATTRIBUTE_KEY: &str = "counterparty_client_id"; - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -struct Attributes { - pub connection_id: ConnectionId, - pub client_id: ClientId, - pub counterparty_connection_id: Option, - pub counterparty_client_id: ClientId, -} - -/// Convert attributes to Tendermint ABCI tags -impl From for Vec { - fn from(a: Attributes) -> Self { - let conn_id = (CONN_ID_ATTRIBUTE_KEY, a.connection_id.as_str()).into(); - let client_id = (CLIENT_ID_ATTRIBUTE_KEY, a.client_id.as_str()).into(); - - let counterparty_conn_id = ( - COUNTERPARTY_CONN_ID_ATTRIBUTE_KEY, - a.counterparty_connection_id - .as_ref() - .map(|id| id.as_str()) - .unwrap_or(""), - ) - .into(); - - let counterparty_client_id = ( - COUNTERPARTY_CLIENT_ID_ATTRIBUTE_KEY, - a.counterparty_client_id.as_str(), - ) - .into(); - - vec![ - conn_id, - client_id, - counterparty_client_id, - counterparty_conn_id, - ] - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct OpenInit(Attributes); - -impl OpenInit { - /// Per our convention, this event is generated on chain A. - pub fn new( - conn_id_on_a: ConnectionId, - client_id_on_a: ClientId, - client_id_on_b: ClientId, - ) -> Self { - Self(Attributes { - connection_id: conn_id_on_a, - client_id: client_id_on_a, - counterparty_connection_id: None, - counterparty_client_id: client_id_on_b, - }) - } - - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.0.connection_id - } - pub fn client_id_on_a(&self) -> &ClientId { - &self.0.client_id - } - pub fn conn_id_on_b(&self) -> Option<&ConnectionId> { - self.0.counterparty_connection_id.as_ref() - } - pub fn client_id_on_b(&self) -> &ClientId { - &self.0.counterparty_client_id - } - - pub fn event_type(&self) -> &str { - CONNECTION_OPEN_INIT_EVENT - } -} - -impl From for abci::Event { - fn from(v: OpenInit) -> Self { - abci::Event { - kind: CONNECTION_OPEN_INIT_EVENT.to_string(), - attributes: v.0.into(), - } - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct OpenTry(Attributes); - -impl OpenTry { - /// Per our convention, this event is generated on chain B. - pub fn new( - conn_id_on_b: ConnectionId, - client_id_on_b: ClientId, - conn_id_on_a: ConnectionId, - client_id_on_a: ClientId, - ) -> Self { - Self(Attributes { - connection_id: conn_id_on_b, - client_id: client_id_on_b, - counterparty_connection_id: Some(conn_id_on_a), - counterparty_client_id: client_id_on_a, - }) - } - - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.0.connection_id - } - pub fn client_id_on_b(&self) -> &ClientId { - &self.0.client_id - } - pub fn conn_id_on_a(&self) -> Option<&ConnectionId> { - self.0.counterparty_connection_id.as_ref() - } - pub fn client_id_on_a(&self) -> &ClientId { - &self.0.counterparty_client_id - } - - pub fn event_type(&self) -> &str { - CONNECTION_OPEN_TRY_EVENT - } -} - -impl From for abci::Event { - fn from(v: OpenTry) -> Self { - abci::Event { - kind: CONNECTION_OPEN_TRY_EVENT.to_string(), - attributes: v.0.into(), - } - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct OpenAck(Attributes); - -impl OpenAck { - /// Per our convention, this event is generated on chain A. - pub fn new( - conn_id_on_a: ConnectionId, - client_id_on_a: ClientId, - conn_id_on_b: ConnectionId, - client_id_on_b: ClientId, - ) -> Self { - Self(Attributes { - connection_id: conn_id_on_a, - client_id: client_id_on_a, - counterparty_connection_id: Some(conn_id_on_b), - counterparty_client_id: client_id_on_b, - }) - } - - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.0.connection_id - } - pub fn client_id_on_a(&self) -> &ClientId { - &self.0.client_id - } - pub fn conn_id_on_b(&self) -> Option<&ConnectionId> { - self.0.counterparty_connection_id.as_ref() - } - pub fn client_id_on_b(&self) -> &ClientId { - &self.0.counterparty_client_id - } - - pub fn event_type(&self) -> &str { - CONNECTION_OPEN_ACK_EVENT - } -} - -impl From for abci::Event { - fn from(v: OpenAck) -> Self { - abci::Event { - kind: CONNECTION_OPEN_ACK_EVENT.to_string(), - attributes: v.0.into(), - } - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct OpenConfirm(Attributes); - -impl OpenConfirm { - /// Per our convention, this event is generated on chain B. - pub fn new( - conn_id_on_b: ConnectionId, - client_id_on_b: ClientId, - conn_id_on_a: ConnectionId, - client_id_on_a: ClientId, - ) -> Self { - Self(Attributes { - connection_id: conn_id_on_b, - client_id: client_id_on_b, - counterparty_connection_id: Some(conn_id_on_a), - counterparty_client_id: client_id_on_a, - }) - } - - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.0.connection_id - } - pub fn client_id_on_b(&self) -> &ClientId { - &self.0.client_id - } - pub fn conn_id_on_a(&self) -> Option<&ConnectionId> { - self.0.counterparty_connection_id.as_ref() - } - pub fn client_id_on_a(&self) -> &ClientId { - &self.0.counterparty_client_id - } - - pub fn event_type(&self) -> &str { - CONNECTION_OPEN_CONFIRM_EVENT - } -} - -impl From for abci::Event { - fn from(v: OpenConfirm) -> Self { - abci::Event { - kind: CONNECTION_OPEN_CONFIRM_EVENT.to_string(), - attributes: v.0.into(), - } - } -} - -#[cfg(test)] -mod tests { - - use core::str::FromStr; - - use ibc_eureka_core_host_types::identifiers::ClientType; - use tendermint::abci::Event as AbciEvent; - - use super::*; - - #[test] - fn ibc_to_abci_connection_events() { - struct Test { - kind: &'static str, - event: AbciEvent, - expected_keys: Vec<&'static str>, - expected_values: Vec<&'static str>, - } - - let client_type = ClientType::from_str("07-tendermint") - .expect("never fails because it's a valid client type"); - let conn_id_on_a = ConnectionId::zero(); - let client_id_on_a = client_type.build_client_id(0); - let conn_id_on_b = ConnectionId::new(1); - let client_id_on_b = client_type.build_client_id(1); - let expected_keys = vec![ - "connection_id", - "client_id", - "counterparty_client_id", - "counterparty_connection_id", - ]; - let expected_values = vec![ - "connection-0", - "07-tendermint-0", - "07-tendermint-1", - "connection-1", - ]; - - let tests: Vec = vec![ - Test { - kind: CONNECTION_OPEN_INIT_EVENT, - event: OpenInit::new( - conn_id_on_a.clone(), - client_id_on_a.clone(), - client_id_on_b.clone(), - ) - .into(), - expected_keys: expected_keys.clone(), - expected_values: expected_values - .iter() - .enumerate() - .map(|(i, v)| if i == 3 { "" } else { v }) - .collect(), - }, - Test { - kind: CONNECTION_OPEN_TRY_EVENT, - event: OpenTry::new( - conn_id_on_b.clone(), - client_id_on_b.clone(), - conn_id_on_a.clone(), - client_id_on_a.clone(), - ) - .into(), - expected_keys: expected_keys.clone(), - expected_values: expected_values.iter().rev().copied().collect(), - }, - Test { - kind: CONNECTION_OPEN_ACK_EVENT, - event: OpenAck::new( - conn_id_on_a.clone(), - client_id_on_a.clone(), - conn_id_on_b.clone(), - client_id_on_b.clone(), - ) - .into(), - expected_keys: expected_keys.clone(), - expected_values: expected_values.clone(), - }, - Test { - kind: CONNECTION_OPEN_CONFIRM_EVENT, - event: OpenConfirm::new(conn_id_on_b, client_id_on_b, conn_id_on_a, client_id_on_a) - .into(), - expected_keys: expected_keys.clone(), - expected_values: expected_values.iter().rev().copied().collect(), - }, - ]; - - for t in tests { - assert_eq!(t.kind, t.event.kind); - assert_eq!(t.expected_keys.len(), t.event.attributes.len()); - for (i, e) in t.event.attributes.iter().enumerate() { - assert_eq!( - e.key_str().unwrap(), - t.expected_keys[i], - "key mismatch for {:?}", - t.kind - ); - } - for (i, e) in t.event.attributes.iter().enumerate() { - assert_eq!( - e.value_str().unwrap(), - t.expected_values[i], - "value mismatch for {:?}", - t.kind - ); - } - } - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/lib.rs b/ibc-eureka-core/ics03-connection/types/src/lib.rs deleted file mode 100644 index 345e7eee1..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! Implementation of the Connection Semantics (ICS-03) data structures. -#![no_std] -#![forbid(unsafe_code)] -#![cfg_attr(not(test), deny(clippy::unwrap_used))] -#![cfg_attr(not(test), deny(clippy::disallowed_methods, clippy::disallowed_types,))] -#![deny( - warnings, - trivial_numeric_casts, - unused_import_braces, - unused_qualifications, - rust_2018_idioms -)] - -#[cfg(feature = "std")] -extern crate std; - -mod connection; -pub use connection::*; - -pub mod error; -pub mod events; -pub mod msgs; -pub mod version; - -/// Re-exports ICS-03 proto types from the `ibc-proto` crate for added -/// convenience -pub mod proto { - pub use ibc_proto::ibc::core::connection::*; -} diff --git a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_ack.rs b/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_ack.rs deleted file mode 100644 index 79b5843ea..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_ack.rs +++ /dev/null @@ -1,103 +0,0 @@ -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::ConnectionId; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::google::protobuf::Any; -use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenAck as RawMsgConnectionOpenAck; -use ibc_proto::Protobuf; - -use crate::version::Version; - -pub const CONN_OPEN_ACK_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) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgConnectionOpenAck { - /// ConnectionId that chain A has chosen for its ConnectionEnd - pub conn_id_on_a: ConnectionId, - /// ConnectionId that chain B has chosen for its ConnectionEnd - pub conn_id_on_b: ConnectionId, - /// ClientState of client tracking chain A on chain B - pub client_state_of_a_on_b: Any, - /// proof of ConnectionEnd stored on Chain B during ConnOpenTry - pub proof_conn_end_on_b: CommitmentProofBytes, - /// proof of ClientState tracking chain A on chain B - pub proof_client_state_of_a_on_b: CommitmentProofBytes, - /// proof that chain B has stored ConsensusState of chain A on its client - pub proof_consensus_state_of_a_on_b: CommitmentProofBytes, - /// Height at which all proofs in this message were taken - pub proofs_height_on_b: Height, - /// height of latest header of chain A that updated the client on chain B - 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 Protobuf for MsgConnectionOpenAck {} - -impl TryFrom for MsgConnectionOpenAck { - type Error = DecodingError; - - fn try_from(msg: RawMsgConnectionOpenAck) -> Result { - Ok(Self { - conn_id_on_a: msg.connection_id.parse()?, - conn_id_on_b: msg.counterparty_connection_id.parse()?, - client_state_of_a_on_b: msg - .client_state - .ok_or(DecodingError::missing_raw_data("client state"))?, - version: msg - .version - .ok_or(DecodingError::missing_raw_data("connection version"))? - .try_into()?, - proof_conn_end_on_b: msg.proof_try.try_into()?, - proof_client_state_of_a_on_b: msg.proof_client.try_into()?, - proof_consensus_state_of_a_on_b: msg.proof_consensus.try_into()?, - proofs_height_on_b: msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::missing_raw_data("proof height"))?, - consensus_height_of_a_on_b: msg - .consensus_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::missing_raw_data("consensus height"))?, - 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()?) - }, - }) - } -} - -impl From for RawMsgConnectionOpenAck { - fn from(msg: MsgConnectionOpenAck) -> Self { - RawMsgConnectionOpenAck { - connection_id: msg.conn_id_on_a.as_str().to_string(), - counterparty_connection_id: msg.conn_id_on_b.as_str().to_string(), - client_state: Some(msg.client_state_of_a_on_b), - proof_height: Some(msg.proofs_height_on_b.into()), - proof_try: msg.proof_conn_end_on_b.into(), - proof_client: msg.proof_client_state_of_a_on_b.into(), - proof_consensus: msg.proof_consensus_state_of_a_on_b.into(), - 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![], - }, - } - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_confirm.rs b/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_confirm.rs deleted file mode 100644 index 853da6708..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_confirm.rs +++ /dev/null @@ -1,59 +0,0 @@ -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::ConnectionId; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenConfirm as RawMsgConnectionOpenConfirm; -use ibc_proto::Protobuf; - -pub const CONN_OPEN_CONFIRM_TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenConfirm"; - -/// 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) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgConnectionOpenConfirm { - /// ConnectionId that chain B has chosen for its ConnectionEnd - pub conn_id_on_b: ConnectionId, - /// proof of ConnectionEnd stored on Chain A during ConnOpenInit - pub proof_conn_end_on_a: CommitmentProofBytes, - /// Height at which `proof_conn_end_on_a` in this message was taken - pub proof_height_on_a: Height, - pub signer: Signer, -} - -impl Protobuf for MsgConnectionOpenConfirm {} - -impl TryFrom for MsgConnectionOpenConfirm { - type Error = DecodingError; - - fn try_from(msg: RawMsgConnectionOpenConfirm) -> Result { - Ok(Self { - conn_id_on_b: msg.connection_id.parse()?, - proof_conn_end_on_a: msg.proof_ack.try_into()?, - proof_height_on_a: msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::invalid_raw_data( - "msg conn open confirm proof height", - ))?, - signer: msg.signer.into(), - }) - } -} - -impl From for RawMsgConnectionOpenConfirm { - fn from(msg: MsgConnectionOpenConfirm) -> Self { - RawMsgConnectionOpenConfirm { - connection_id: msg.conn_id_on_b.as_str().to_string(), - proof_ack: msg.proof_conn_end_on_a.into(), - proof_height: Some(msg.proof_height_on_a.into()), - signer: msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_init.rs b/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_init.rs deleted file mode 100644 index 146ac1891..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_init.rs +++ /dev/null @@ -1,126 +0,0 @@ -use core::time::Duration; - -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::ClientId; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenInit as RawMsgConnectionOpenInit; -use ibc_proto::Protobuf; - -use crate::connection::Counterparty; -use crate::version::Version; - -pub const CONN_OPEN_INIT_TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenInit"; - -/// Per our convention, this message is sent to chain A. -/// The handler will check proofs of chain B. -#[derive(Clone, Debug, PartialEq, Eq)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -pub struct MsgConnectionOpenInit { - /// 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: Duration, - pub signer: Signer, -} - -/// This module encapsulates the workarounds we need to do to implement -/// `BorshSerialize` and `BorshDeserialize` on `MsgConnectionOpenInit` -#[cfg(feature = "borsh")] -mod borsh_impls { - use borsh::io::{self, Read}; - use borsh::{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 { - type Error = DecodingError; - - fn try_from(msg: RawMsgConnectionOpenInit) -> Result { - let counterparty: Counterparty = msg - .counterparty - .ok_or(DecodingError::missing_raw_data( - "msg conn open init counterparty", - ))? - .try_into()?; - - if let Some(cid) = counterparty.connection_id() { - return Err(DecodingError::invalid_raw_data(format!( - "expected msg conn open init connection ID to be empty, actual `{cid}`", - ))); - } - - Ok(Self { - client_id_on_a: msg.client_id.parse()?, - counterparty, - version: msg.version.map(TryInto::try_into).transpose()?, - delay_period: Duration::from_nanos(msg.delay_period), - signer: msg.signer.into(), - }) - } -} - -impl From for RawMsgConnectionOpenInit { - fn from(ics_msg: MsgConnectionOpenInit) -> Self { - RawMsgConnectionOpenInit { - client_id: ics_msg.client_id_on_a.as_str().to_string(), - counterparty: Some(ics_msg.counterparty.into()), - version: ics_msg.version.map(Into::into), - delay_period: ics_msg.delay_period.as_nanos() as u64, - signer: ics_msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_try.rs b/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_try.rs deleted file mode 100644 index 281d299ac..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/msgs/conn_open_try.rs +++ /dev/null @@ -1,226 +0,0 @@ -use core::time::Duration; - -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::ClientId; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::google::protobuf::Any; -use ibc_proto::ibc::core::connection::v1::MsgConnectionOpenTry as RawMsgConnectionOpenTry; -use ibc_proto::Protobuf; - -use crate::connection::Counterparty; -use crate::version::Version; - -pub const CONN_OPEN_TRY_TYPE_URL: &str = "/ibc.core.connection.v1.MsgConnectionOpenTry"; - -/// Per our convention, this message is sent to chain B. -/// The handler will check proofs of chain A. -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgConnectionOpenTry { - /// 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: 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 - pub previous_connection_id: String, -} - -#[allow(deprecated)] -#[cfg(feature = "borsh")] -mod borsh_impls { - use borsh::io::{self, Read}; - use borsh::{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 {} - -impl TryFrom for MsgConnectionOpenTry { - type Error = DecodingError; - - fn try_from(msg: RawMsgConnectionOpenTry) -> Result { - let counterparty_versions = msg - .counterparty_versions - .into_iter() - .map(Version::try_from) - .collect::, _>>()?; - - if counterparty_versions.is_empty() { - return Err(DecodingError::missing_raw_data( - "msg conn open try connection versions", - )); - } - - // We set the deprecated `previous_connection_id` field so that we can - // properly convert `MsgConnectionOpenTry` into its raw form - #[allow(deprecated)] - Ok(Self { - previous_connection_id: msg.previous_connection_id, - client_id_on_b: msg.client_id.parse()?, - client_state_of_b_on_a: msg.client_state.ok_or(DecodingError::missing_raw_data( - "msg conn open try client state", - ))?, - counterparty: msg - .counterparty - .ok_or(DecodingError::missing_raw_data( - "msg conn open try counterparty", - ))? - .try_into()?, - versions_on_a: counterparty_versions, - proof_conn_end_on_a: msg.proof_init.try_into()?, - proof_client_state_of_b_on_a: msg.proof_client.try_into()?, - proof_consensus_state_of_b_on_a: msg.proof_consensus.try_into()?, - proofs_height_on_a: msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::invalid_raw_data( - "msg conn open try proof height", - ))?, - consensus_height_of_b_on_a: msg - .consensus_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::invalid_raw_data( - "msg conn open try consensus height", - ))?, - 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()?) - }, - }) - } -} - -impl From for RawMsgConnectionOpenTry { - fn from(msg: MsgConnectionOpenTry) -> Self { - #[allow(deprecated)] - RawMsgConnectionOpenTry { - client_id: msg.client_id_on_b.as_str().to_string(), - previous_connection_id: msg.previous_connection_id, - client_state: Some(msg.client_state_of_b_on_a), - counterparty: Some(msg.counterparty.into()), - delay_period: msg.delay_period.as_nanos() as u64, - counterparty_versions: msg.versions_on_a.iter().map(|v| v.clone().into()).collect(), - proof_height: Some(msg.proofs_height_on_a.into()), - proof_init: msg.proof_conn_end_on_a.into(), - proof_client: msg.proof_client_state_of_b_on_a.into(), - 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![], - }, - } - } -} diff --git a/ibc-eureka-core/ics03-connection/types/src/msgs/mod.rs b/ibc-eureka-core/ics03-connection/types/src/msgs/mod.rs deleted file mode 100644 index d3be3dcf6..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/msgs/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Message definitions for the connection handshake datagrams. -//! -//! We define each of the four messages in the connection handshake protocol as a `struct`. -//! Each such message comprises the same fields as the datagrams defined in ICS3 English spec: -//! . -//! -//! One departure from ICS3 is that we abstract the three counterparty fields (connection id, -//! prefix, and client id) into a single field of type `Counterparty`; this applies to messages -//! `MsgConnectionOpenInit` and `MsgConnectionOpenTry`. One other difference with regard to -//! abstraction is that all proof-related attributes in a message are encapsulated in `Proofs` type. -//! -//! Another difference to ICS3 specs is that each message comprises an additional field called -//! `signer` which is specific to Cosmos-SDK. - -use ibc_primitives::prelude::*; - -mod conn_open_ack; -mod conn_open_confirm; -mod conn_open_init; -mod conn_open_try; - -pub use conn_open_ack::*; -pub use conn_open_confirm::*; -pub use conn_open_init::*; -pub use conn_open_try::*; - -/// Enumeration of all possible messages that the ICS3 protocol processes. -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq, derive_more::From)] -pub enum ConnectionMsg { - OpenInit(MsgConnectionOpenInit), - OpenTry(MsgConnectionOpenTry), - OpenAck(MsgConnectionOpenAck), - OpenConfirm(MsgConnectionOpenConfirm), -} diff --git a/ibc-eureka-core/ics03-connection/types/src/version.rs b/ibc-eureka-core/ics03-connection/types/src/version.rs deleted file mode 100644 index 78e7c9582..000000000 --- a/ibc-eureka-core/ics03-connection/types/src/version.rs +++ /dev/null @@ -1,403 +0,0 @@ -//! Defines connection versioning type and functions - -use core::fmt::Display; - -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_primitives::prelude::*; -use ibc_primitives::utils::PrettySlice; -use ibc_proto::ibc::core::connection::v1::Version as RawVersion; -use ibc_proto::Protobuf; - -use crate::error::ConnectionError; - -/// Stores the identifier and the features supported by a version -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq, Hash)] -pub struct Version { - /// unique version identifier - identifier: String, - /// list of features compatible with the specified identifier - features: Vec, -} - -impl Version { - /// Checks whether the version has a matching version identifier and its - /// feature set is a subset of the supported features - pub fn verify_is_supported( - &self, - supported_versions: &[Version], - ) -> Result<(), ConnectionError> { - let maybe_supported_version = find_supported_version(self, supported_versions)?; - - if self.features.is_empty() { - return Err(ConnectionError::MissingFeatures); - } - - for feature in self.features.iter() { - maybe_supported_version.verify_feature_supported(feature.to_string())?; - } - Ok(()) - } - - /// Checks whether the given feature is supported in this version - pub fn verify_feature_supported(&self, feature: String) -> Result<(), ConnectionError> { - if !self.features.contains(&feature) { - return Err(ConnectionError::MissingFeatures); - } - Ok(()) - } - - /// Returns the lists of supported versions - pub fn compatibles() -> Vec { - vec![Self { - identifier: "1".to_string(), - features: vec!["ORDER_ORDERED".to_string(), "ORDER_UNORDERED".to_string()], - }] - } -} - -impl Protobuf for Version {} - -impl TryFrom for Version { - type Error = DecodingError; - - fn try_from(value: RawVersion) -> Result { - if value.identifier.trim().is_empty() { - return Err(DecodingError::missing_raw_data("version identifier")); - } - for feature in value.features.iter() { - if feature.trim().is_empty() { - return Err(DecodingError::missing_raw_data("version features")); - } - } - Ok(Version { - identifier: value.identifier, - features: value.features, - }) - } -} - -impl From for RawVersion { - fn from(value: Version) -> Self { - Self { - identifier: value.identifier, - features: value.features, - } - } -} - -impl Display for Version { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!( - f, - "Version {{ identifier: {}, features: {} }}", - self.identifier, - PrettySlice(&self.features) - ) - } -} - -/// Iterates over the descending ordered set of compatible IBC versions and -/// selects the first version with a version identifier that is supported by the -/// counterparty. The returned version contains a feature set with the -/// intersection of the features supported by the source and counterparty -/// chains. If the feature set intersection is nil, the search for a -/// compatible version continues. This function is called in the `conn_open_try` -/// handshake procedure. -/// -/// NOTE: Empty feature sets are not currently allowed for a chosen version. -pub fn pick_version( - supported_versions: &[Version], - counterparty_versions: &[Version], -) -> Result { - let mut intersection: Vec = Vec::new(); - - for sv in supported_versions.iter() { - if let Ok(cv) = find_supported_version(sv, counterparty_versions) { - if let Ok(feature_set) = get_feature_set_intersection(&sv.features, &cv.features) { - intersection.push(Version { - identifier: cv.identifier, - features: feature_set, - }) - } - } - } - - if intersection.is_empty() { - return Err(ConnectionError::MissingCommonVersion); - } - - intersection.sort_by(|a, b| a.identifier.cmp(&b.identifier)); - - Ok(intersection[0].clone()) -} - -/// Returns the version from the list of supported versions that matches the -/// given reference version. -fn find_supported_version( - version: &Version, - supported_versions: &[Version], -) -> Result { - supported_versions - .iter() - .find(|sv| sv.identifier == version.identifier) - .ok_or(ConnectionError::MissingCommonVersion) - .cloned() -} - -/// Returns the intersections of supported features by a host and the -/// counterparty features. This is done by iterating over all the features in -/// the host supported version and seeing if they exist in the feature set for -/// the counterparty version. -fn get_feature_set_intersection( - supported_features: &[String], - counterparty_features: &[String], -) -> Result, ConnectionError> { - let feature_set_intersection: Vec = supported_features - .iter() - .filter(|f| counterparty_features.contains(f)) - .cloned() - .collect(); - - if feature_set_intersection.is_empty() { - return Err(ConnectionError::MissingFeatures); - } - - Ok(feature_set_intersection) -} - -#[cfg(test)] -mod tests { - use ibc_primitives::prelude::*; - use ibc_proto::ibc::core::connection::v1::Version as RawVersion; - - use crate::error::ConnectionError; - use crate::version::{pick_version, Version}; - - fn get_dummy_features() -> Vec { - vec!["ORDER_RANDOM".to_string(), "ORDER_UNORDERED".to_string()] - } - - fn good_versions() -> Vec { - vec![ - Version { - identifier: "1".to_string(), - features: vec!["ORDER_ORDERED".to_string(), "ORDER_UNORDERED".to_string()], - } - .into(), - RawVersion { - identifier: "2".to_string(), - features: get_dummy_features(), - }, - ] - .into_iter() - .collect() - } - - fn bad_versions_identifier() -> Vec { - vec![RawVersion { - identifier: "".to_string(), - features: get_dummy_features(), - }] - .into_iter() - .collect() - } - - fn bad_versions_features() -> Vec { - vec![RawVersion { - identifier: "2".to_string(), - features: vec!["".to_string()], - }] - .into_iter() - .collect() - } - - fn overlapping() -> (Vec, Vec, Version) { - ( - vec![ - Version { - identifier: "1".to_string(), - features: vec!["ORDER_ORDERED".to_string(), "ORDER_UNORDERED".to_string()], - }, - Version { - identifier: "3".to_string(), - features: get_dummy_features(), - }, - Version { - identifier: "4".to_string(), - features: get_dummy_features(), - }, - ] - .into_iter() - .collect(), - vec![ - Version { - identifier: "2".to_string(), - features: get_dummy_features(), - }, - Version { - identifier: "4".to_string(), - features: get_dummy_features(), - }, - Version { - identifier: "3".to_string(), - features: get_dummy_features(), - }, - ] - .into_iter() - .collect(), - // Should pick version 3 as it's the lowest of the intersection {3, 4} - Version { - identifier: "3".to_string(), - features: get_dummy_features(), - }, - ) - } - - fn disjoint() -> (Vec, Vec) { - ( - vec![Version { - identifier: "1".to_string(), - features: Vec::new(), - }] - .into_iter() - .collect(), - vec![Version { - identifier: "2".to_string(), - features: Vec::new(), - }] - .into_iter() - .collect(), - ) - } - - #[test] - fn verify() { - struct Test { - name: String, - versions: Vec, - want_pass: bool, - } - let tests: Vec = vec![ - Test { - name: "Compatible versions".to_string(), - versions: vec![Version { - identifier: "1".to_string(), - features: get_dummy_features(), - } - .into()], - want_pass: true, - }, - Test { - name: "Multiple versions".to_string(), - versions: good_versions(), - want_pass: true, - }, - Test { - name: "Bad version identifier".to_string(), - versions: bad_versions_identifier(), - want_pass: false, - }, - Test { - name: "Bad version feature".to_string(), - versions: bad_versions_features(), - want_pass: false, - }, - Test { - name: "Bad versions empty".to_string(), - versions: Vec::new(), - want_pass: true, - }, - ]; - - for test in tests { - let versions = test - .versions - .into_iter() - .map(Version::try_from) - .collect::, _>>(); - - assert_eq!( - test.want_pass, - versions.is_ok(), - "Validate versions failed for test {} with error {:?}", - test.name, - versions.err(), - ); - } - } - #[test] - fn pick() { - struct Test { - name: String, - supported: Vec, - counterparty: Vec, - picked: Result, - want_pass: bool, - } - let tests: Vec = vec![ - Test { - name: "Compatible versions".to_string(), - supported: Version::compatibles(), - counterparty: Version::compatibles(), - picked: Ok(Version { - identifier: "1".to_string(), - features: vec!["ORDER_ORDERED".to_string(), "ORDER_UNORDERED".to_string()], - }), - want_pass: true, - }, - Test { - name: "Overlapping versions".to_string(), - supported: overlapping().0, - counterparty: overlapping().1, - picked: Ok(overlapping().2), - want_pass: true, - }, - Test { - name: "Disjoint versions".to_string(), - supported: disjoint().0, - counterparty: disjoint().1, - picked: Err(ConnectionError::MissingCommonVersion), - want_pass: false, - }, - ]; - - for test in tests { - let version = pick_version(&test.supported, &test.counterparty); - - assert_eq!( - test.want_pass, - version.is_ok(), - "Validate versions failed for test {}", - test.name, - ); - - if test.want_pass { - assert_eq!(version.unwrap(), test.picked.unwrap()); - } - } - } - #[test] - fn serialize() { - let def = Version { - identifier: "1".to_string(), - features: vec!["ORDER_ORDERED".to_string(), "ORDER_UNORDERED".to_string()], - }; - let def_raw: RawVersion = def.clone().into(); - let def_back = def_raw.try_into().unwrap(); - assert_eq!(def, def_back); - } -} diff --git a/ibc-eureka-core/ics04-channel/Cargo.toml b/ibc-eureka-core/ics04-channel/Cargo.toml index b008bc10a..71f345cbe 100644 --- a/ibc-eureka-core/ics04-channel/Cargo.toml +++ b/ibc-eureka-core/ics04-channel/Cargo.toml @@ -19,7 +19,6 @@ all-features = true [dependencies] ibc-eureka-core-client = { workspace = true } -ibc-eureka-core-connection = { workspace = true } ibc-eureka-core-channel-types = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-host = { workspace = true } @@ -31,7 +30,6 @@ ibc-primitives = { workspace = true } default = [ "std" ] std = [ "ibc-eureka-core-client/std", - "ibc-eureka-core-connection/std", "ibc-eureka-core-channel-types/std", "ibc-eureka-core-commitment-types/std", "ibc-eureka-core-host/std", @@ -41,7 +39,6 @@ std = [ ] serde = [ "ibc-eureka-core-client/serde", - "ibc-eureka-core-connection/serde", "ibc-eureka-core-channel-types/serde", "ibc-eureka-core-commitment-types/serde", "ibc-eureka-core-host/serde", @@ -51,7 +48,6 @@ serde = [ ] schema = [ "ibc-eureka-core-client/schema", - "ibc-eureka-core-connection/schema", "ibc-eureka-core-channel-types/schema", "ibc-eureka-core-commitment-types/schema", "ibc-eureka-core-host/schema", @@ -63,7 +59,6 @@ schema = [ ] borsh = [ "ibc-eureka-core-client/borsh", - "ibc-eureka-core-connection/borsh", "ibc-eureka-core-channel-types/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host/borsh", @@ -73,7 +68,6 @@ borsh = [ ] parity-scale-codec = [ "ibc-eureka-core-client/parity-scale-codec", - "ibc-eureka-core-connection/parity-scale-codec", "ibc-eureka-core-channel-types/parity-scale-codec", "ibc-eureka-core-commitment-types/parity-scale-codec", "ibc-eureka-core-host/parity-scale-codec", diff --git a/ibc-eureka-core/ics04-channel/src/context.rs b/ibc-eureka-core/ics04-channel/src/context.rs index cf5ecfe46..87b0ab296 100644 --- a/ibc-eureka-core/ics04-channel/src/context.rs +++ b/ibc-eureka-core/ics04-channel/src/context.rs @@ -1,13 +1,11 @@ //! ICS4 (channel) context. -use ibc_eureka_core_channel_types::channel::ChannelEnd; use ibc_eureka_core_channel_types::commitment::PacketCommitment; use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::types::ConnectionEnd; use ibc_eureka_core_handler_types::events::IbcEvent; use ibc_eureka_core_host::types::error::HostError; -use ibc_eureka_core_host::types::identifiers::{ConnectionId, Sequence}; -use ibc_eureka_core_host::types::path::{ChannelEndPath, CommitmentPath, SeqSendPath}; +use ibc_eureka_core_host::types::identifiers::Sequence; +use ibc_eureka_core_host::types::path::{CommitmentPath, SeqSendPath}; use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; use ibc_primitives::prelude::*; @@ -18,12 +16,6 @@ pub trait SendPacketValidationContext { /// Retrieve the context that implements all clients' `ValidationContext`. fn get_client_validation_context(&self) -> &Self::V; - /// Returns the ChannelEnd for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; - - /// Returns the ConnectionState for the given identifier `connection_id`. - fn connection_end(&self, connection_id: &ConnectionId) -> Result; - fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result; } @@ -37,14 +29,6 @@ where self.get_client_validation_context() } - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result { - self.channel_end(channel_end_path) - } - - fn connection_end(&self, connection_id: &ConnectionId) -> Result { - self.connection_end(connection_id) - } - fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result { self.get_next_sequence_send(seq_send_path) } diff --git a/ibc-eureka-core/ics04-channel/src/handler/acknowledgement.rs b/ibc-eureka-core/ics04-channel/src/handler/acknowledgement.rs index e14618cb3..1c0f32e5d 100644 --- a/ibc-eureka-core/ics04-channel/src/handler/acknowledgement.rs +++ b/ibc-eureka-core/ics04-channel/src/handler/acknowledgement.rs @@ -1,4 +1,3 @@ -use ibc_eureka_core_channel_types::channel::{Counterparty, Order, State as ChannelState}; use ibc_eureka_core_channel_types::commitment::{ compute_ack_commitment, compute_packet_commitment, }; @@ -6,12 +5,8 @@ use ibc_eureka_core_channel_types::error::ChannelError; use ibc_eureka_core_channel_types::events::AcknowledgePacket; use ibc_eureka_core_channel_types::msgs::MsgAcknowledgement; use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::delay::verify_conn_delay_passed; -use ibc_eureka_core_connection::types::State as ConnectionState; use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::path::{ - AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, SeqAckPath, -}; +use ibc_eureka_core_host::types::path::{AckPath, ClientConsensusStatePath, CommitmentPath, Path}; use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; use ibc_eureka_core_router::module::Module; use ibc_primitives::prelude::*; @@ -37,27 +32,19 @@ pub fn acknowledgement_packet_execute( where ExecCtx: ExecutionContext, { - let payload = &msg.packet.payloads[0]; - - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &msg.packet.header.source_client; - let seq_on_a = &msg.packet.header.seq_on_a; + let packet = &msg.packet; + let payload = &packet.payloads[0]; - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, channel_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - let conn_id_on_a = &chan_end_on_a.connection_hops()[0]; + let (_, port_id_on_a) = &payload.header.source_port; + let channel_id_on_a = &packet.header.target_client_on_source; + let seq_on_a = &packet.header.seq_on_a; // In all cases, this event is emitted - let event = IbcEvent::AcknowledgePacket(AcknowledgePacket::new( - msg.packet.clone(), - chan_end_on_a.ordering, - conn_id_on_a.clone(), - )); + let event = IbcEvent::AcknowledgePacket(AcknowledgePacket::new(packet.clone())); ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; ctx_a.emit_ibc_event(event)?; - let commitment_path_on_a = - CommitmentPath::new(port_id_on_a, channel_id_on_a, msg.packet.header.seq_on_a); + let commitment_path_on_a = CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a); // check if we're in the NO-OP case if ctx_a.get_packet_commitment(&commitment_path_on_a).is_err() { @@ -69,20 +56,13 @@ where }; let (extras, cb_result) = - module.on_acknowledgement_packet_execute(&msg.packet, &msg.acknowledgement, &msg.signer); + module.on_acknowledgement_packet_execute(packet, &msg.acknowledgement, &msg.signer); cb_result?; // apply state changes { ctx_a.delete_packet_commitment(&commitment_path_on_a)?; - - if let Order::Ordered = chan_end_on_a.ordering { - // Note: in validation, we verified that `msg.packet.sequence == nextSeqRecv` - // (where `nextSeqRecv` is the value in the store) - let seq_ack_path_on_a = SeqAckPath::new(port_id_on_a, channel_id_on_a); - ctx_a.store_next_sequence_ack(&seq_ack_path_on_a, (*seq_on_a).increment())?; - } } // emit events and logs @@ -112,27 +92,13 @@ where let packet = &msg.packet; let payload = &packet.payloads[0]; - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; + let (prefix_on_a, port_id_on_a) = &payload.header.source_port; + let channel_id_on_a = &packet.header.target_client_on_source; + let (_, port_id_on_b) = &payload.header.target_port; + let channel_id_on_b = &packet.header.source_client_on_target; let seq_on_a = &packet.header.seq_on_a; let data = &payload.data; - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, channel_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - - chan_end_on_a.verify_state_matches(&ChannelState::Open)?; - - let counterparty = Counterparty::new(port_id_on_b.clone(), Some(channel_id_on_b.clone())); - - chan_end_on_a.verify_counterparty_matches(&counterparty)?; - - let conn_id_on_a = &chan_end_on_a.connection_hops()[0]; - let conn_end_on_a = ctx_a.connection_end(conn_id_on_a)?; - - conn_end_on_a.verify_state_matches(&ConnectionState::Open)?; - let commitment_path_on_a = CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a); // Verify packet commitment @@ -157,20 +123,10 @@ where }); } - if let Order::Ordered = chan_end_on_a.ordering { - let seq_ack_path_on_a = SeqAckPath::new(port_id_on_a, channel_id_on_a); - let next_seq_ack = ctx_a.get_next_sequence_ack(&seq_ack_path_on_a)?; - if seq_on_a != &next_seq_ack { - return Err(ChannelError::MismatchedPacketSequence { - actual: *seq_on_a, - expected: next_seq_ack, - }); - } - } - // Verify proofs { - let client_id_on_a = conn_end_on_a.client_id(); + // TODO(rano): avoid a vs b confusion + let client_id_on_a = channel_id_on_b.as_ref(); let client_val_ctx_a = ctx_a.get_client_validation_context(); @@ -192,11 +148,9 @@ where let ack_commitment = compute_ack_commitment(&msg.acknowledgement); let ack_path_on_b = AckPath::new(port_id_on_b, channel_id_on_b, *seq_on_a); - verify_conn_delay_passed(ctx_a, msg.proof_height_on_b, &conn_end_on_a)?; - // Verify the proof for the packet against the chain store. client_state_of_b_on_a.verify_membership( - conn_end_on_a.counterparty().prefix(), + prefix_on_a, &msg.proof_acked_on_b, consensus_state_of_b_on_a.root(), Path::Ack(ack_path_on_b), diff --git a/ibc-eureka-core/ics04-channel/src/handler/chan_close_confirm.rs b/ibc-eureka-core/ics04-channel/src/handler/chan_close_confirm.rs deleted file mode 100644 index 04c694b2c..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/chan_close_confirm.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! Protocol logic specific to ICS4 messages of type `MsgChannelCloseConfirm`. - -use ibc_eureka_core_channel_types::channel::{ - ChannelEnd, Counterparty, State, State as ChannelState, -}; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::CloseConfirm; -use ibc_eureka_core_channel_types::msgs::MsgChannelCloseConfirm; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::types::error::ConnectionError; -use ibc_eureka_core_connection::types::State as ConnectionState; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::path::{ChannelEndPath, ClientConsensusStatePath, Path}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_eureka_core_router::module::Module; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::Protobuf; - -pub fn chan_close_confirm_validate( - ctx_b: &ValCtx, - module: &dyn Module, - msg: MsgChannelCloseConfirm, -) -> Result<(), ChannelError> -where - ValCtx: ValidationContext, -{ - validate(ctx_b, &msg)?; - - module.on_chan_close_confirm_validate(&msg.port_id_on_b, &msg.chan_id_on_b)?; - - Ok(()) -} - -pub fn chan_close_confirm_execute( - ctx_b: &mut ExecCtx, - module: &mut dyn Module, - msg: MsgChannelCloseConfirm, -) -> Result<(), ChannelError> -where - ExecCtx: ExecutionContext, -{ - 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)?; - - // state changes - { - let chan_end_on_b = { - let mut chan_end_on_b = chan_end_on_b.clone(); - chan_end_on_b.set_state(State::Closed); - chan_end_on_b - }; - ctx_b.store_channel(&chan_end_path_on_b, chan_end_on_b)?; - } - - // emit events and logs - { - ctx_b.log_message("success: channel close confirm".to_string())?; - - let core_event = { - let port_id_on_a = chan_end_on_b.counterparty().port_id.clone(); - let chan_id_on_a = chan_end_on_b - .counterparty() - .channel_id - .clone() - .ok_or(ChannelError::MissingCounterparty)?; - let conn_id_on_b = chan_end_on_b.connection_hops[0].clone(); - - IbcEvent::CloseConfirmChannel(CloseConfirm::new( - msg.port_id_on_b.clone(), - msg.chan_id_on_b.clone(), - port_id_on_a, - chan_id_on_a, - conn_id_on_b, - )) - }; - ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_b.emit_ibc_event(core_event)?; - - for module_event in extras.events { - ctx_b.emit_ibc_event(IbcEvent::Module(module_event))?; - } - - for log_message in extras.log { - ctx_b.log_message(log_message)?; - } - } - - Ok(()) -} - -fn validate(ctx_b: &Ctx, msg: &MsgChannelCloseConfirm) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_b.validate_message_signer(&msg.signer)?; - - // Retrieve the old channel end and validate it against the message. - 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)?; - - // Validate that the channel end is in a state where it can be closed. - chan_end_on_b.verify_not_closed()?; - - let conn_end_on_b = ctx_b.connection_end(&chan_end_on_b.connection_hops()[0])?; - - conn_end_on_b.verify_state_matches(&ConnectionState::Open)?; - - // Verify proofs - { - let client_id_on_b = conn_end_on_b.client_id(); - - let client_val_ctx_b = ctx_b.get_client_validation_context(); - - let client_state_of_a_on_b = client_val_ctx_b.client_state(client_id_on_b)?; - - client_state_of_a_on_b - .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; - - client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; - - let client_cons_state_path_on_b = ClientConsensusStatePath::new( - client_id_on_b.clone(), - msg.proof_height_on_a.revision_number(), - msg.proof_height_on_a.revision_height(), - ); - let consensus_state_of_a_on_b = - client_val_ctx_b.consensus_state(&client_cons_state_path_on_b)?; - let prefix_on_a = conn_end_on_b.counterparty().prefix(); - let port_id_on_a = &chan_end_on_b.counterparty().port_id; - let chan_id_on_a = chan_end_on_b - .counterparty() - .channel_id() - .ok_or(ChannelError::MissingCounterparty)?; - let conn_id_on_a = conn_end_on_b - .counterparty() - .connection_id() - .ok_or(ConnectionError::MissingCounterparty)?; - - let expected_chan_end_on_a = ChannelEnd::new( - ChannelState::Closed, - *chan_end_on_b.ordering(), - Counterparty::new(msg.port_id_on_b.clone(), Some(msg.chan_id_on_b.clone())), - vec![conn_id_on_a.clone()], - chan_end_on_b.version().clone(), - )?; - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, chan_id_on_a); - - // Verify the proof for the channel state against the expected channel end. - // A counterparty channel id of None in not possible, and is checked by validate_basic in msg. - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_chan_end_on_a, - consensus_state_of_a_on_b.root(), - Path::ChannelEnd(chan_end_path_on_a), - expected_chan_end_on_a.encode_vec(), - )?; - } - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/src/handler/chan_close_init.rs b/ibc-eureka-core/ics04-channel/src/handler/chan_close_init.rs deleted file mode 100644 index acee3b3e1..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/chan_close_init.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! Protocol logic specific to ICS4 messages of type `MsgChannelCloseInit`. -use ibc_eureka_core_channel_types::channel::State; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::CloseInit; -use ibc_eureka_core_channel_types::msgs::MsgChannelCloseInit; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::types::State as ConnectionState; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::path::ChannelEndPath; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_eureka_core_router::module::Module; -use ibc_primitives::prelude::*; - -pub fn chan_close_init_validate( - ctx_a: &ValCtx, - module: &dyn Module, - msg: MsgChannelCloseInit, -) -> Result<(), ChannelError> -where - ValCtx: ValidationContext, -{ - validate(ctx_a, &msg)?; - - module.on_chan_close_init_validate(&msg.port_id_on_a, &msg.chan_id_on_a)?; - - Ok(()) -} - -pub fn chan_close_init_execute( - ctx_a: &mut ExecCtx, - module: &mut dyn Module, - msg: MsgChannelCloseInit, -) -> Result<(), ChannelError> -where - ExecCtx: ExecutionContext, -{ - 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)?; - - // state changes - { - let chan_end_on_a = { - let mut chan_end_on_a = chan_end_on_a.clone(); - chan_end_on_a.set_state(State::Closed); - chan_end_on_a - }; - - ctx_a.store_channel(&chan_end_path_on_a, chan_end_on_a)?; - } - - // emit events and logs - { - ctx_a.log_message("success: channel close init".to_string())?; - - let core_event = { - let port_id_on_b = chan_end_on_a.counterparty().port_id.clone(); - let chan_id_on_b = chan_end_on_a - .counterparty() - .channel_id - .clone() - .ok_or(ChannelError::MissingCounterparty)?; - let conn_id_on_a = chan_end_on_a.connection_hops[0].clone(); - - IbcEvent::CloseInitChannel(CloseInit::new( - msg.port_id_on_a.clone(), - msg.chan_id_on_a.clone(), - port_id_on_b, - chan_id_on_b, - conn_id_on_a, - )) - }; - ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_a.emit_ibc_event(core_event)?; - - for module_event in extras.events { - ctx_a.emit_ibc_event(IbcEvent::Module(module_event))?; - } - - for log_message in extras.log { - ctx_a.log_message(log_message)?; - } - } - - Ok(()) -} - -fn validate(ctx_a: &Ctx, msg: &MsgChannelCloseInit) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_a.validate_message_signer(&msg.signer)?; - - 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)?; - - // Validate that the channel end is in a state where it can be closed. - chan_end_on_a.verify_not_closed()?; - - // An OPEN IBC connection running on the local (host) chain should exist. - chan_end_on_a.verify_connection_hops_length()?; - - let conn_end_on_a = ctx_a.connection_end(&chan_end_on_a.connection_hops()[0])?; - - conn_end_on_a.verify_state_matches(&ConnectionState::Open)?; - - let client_id_on_a = conn_end_on_a.client_id(); - - let client_val_ctx_a = ctx_a.get_client_validation_context(); - - let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; - client_state_of_b_on_a - .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/src/handler/chan_open_ack.rs b/ibc-eureka-core/ics04-channel/src/handler/chan_open_ack.rs deleted file mode 100644 index 729cd27d7..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/chan_open_ack.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! Protocol logic specific to ICS4 messages of type `MsgChannelOpenAck`. -use ibc_eureka_core_channel_types::channel::{ - ChannelEnd, Counterparty, State, State as ChannelState, -}; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::OpenAck; -use ibc_eureka_core_channel_types::msgs::MsgChannelOpenAck; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::types::error::ConnectionError; -use ibc_eureka_core_connection::types::State as ConnectionState; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::path::{ChannelEndPath, ClientConsensusStatePath, Path}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_eureka_core_router::module::Module; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::Protobuf; - -pub fn chan_open_ack_validate( - ctx_a: &ValCtx, - module: &dyn Module, - msg: MsgChannelOpenAck, -) -> Result<(), ChannelError> -where - ValCtx: ValidationContext, -{ - validate(ctx_a, &msg)?; - - module.on_chan_open_ack_validate(&msg.port_id_on_a, &msg.chan_id_on_a, &msg.version_on_b)?; - - Ok(()) -} - -pub fn chan_open_ack_execute( - ctx_a: &mut ExecCtx, - module: &mut dyn Module, - msg: MsgChannelOpenAck, -) -> Result<(), ChannelError> -where - ExecCtx: ExecutionContext, -{ - 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); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - - // state changes - { - let chan_end_on_a = { - let mut chan_end_on_a = chan_end_on_a.clone(); - - chan_end_on_a.set_state(State::Open); - chan_end_on_a.set_version(msg.version_on_b.clone()); - chan_end_on_a.set_counterparty_channel_id(msg.chan_id_on_b.clone()); - - chan_end_on_a - }; - ctx_a.store_channel(&chan_end_path_on_a, chan_end_on_a)?; - } - - // emit events and logs - { - ctx_a.log_message("success: channel open ack".to_string())?; - - let core_event = { - let port_id_on_b = chan_end_on_a.counterparty().port_id.clone(); - let conn_id_on_a = chan_end_on_a.connection_hops[0].clone(); - - IbcEvent::OpenAckChannel(OpenAck::new( - msg.port_id_on_a.clone(), - msg.chan_id_on_a.clone(), - port_id_on_b, - msg.chan_id_on_b, - conn_id_on_a, - )) - }; - ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_a.emit_ibc_event(core_event)?; - - for module_event in extras.events { - ctx_a.emit_ibc_event(IbcEvent::Module(module_event))?; - } - - for log_message in extras.log { - ctx_a.log_message(log_message)?; - } - } - - Ok(()) -} - -fn validate(ctx_a: &Ctx, msg: &MsgChannelOpenAck) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_a.validate_message_signer(&msg.signer)?; - - 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)?; - - // Validate that the channel end is in a state where it can be ack. - chan_end_on_a.verify_state_matches(&ChannelState::Init)?; - - // An OPEN IBC connection running on the local (host) chain should exist. - chan_end_on_a.verify_connection_hops_length()?; - - let conn_end_on_a = ctx_a.connection_end(&chan_end_on_a.connection_hops()[0])?; - - conn_end_on_a.verify_state_matches(&ConnectionState::Open)?; - - // Verify proofs - { - let client_id_on_a = conn_end_on_a.client_id(); - let client_val_ctx_a = ctx_a.get_client_validation_context(); - let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; - - client_state_of_b_on_a - .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; - - client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; - - let client_cons_state_path_on_a = ClientConsensusStatePath::new( - client_id_on_a.clone(), - msg.proof_height_on_b.revision_number(), - msg.proof_height_on_b.revision_height(), - ); - let consensus_state_of_b_on_a = - client_val_ctx_a.consensus_state(&client_cons_state_path_on_a)?; - let prefix_on_b = conn_end_on_a.counterparty().prefix(); - let port_id_on_b = &chan_end_on_a.counterparty().port_id; - let conn_id_on_b = conn_end_on_a - .counterparty() - .connection_id() - .ok_or(ConnectionError::MissingCounterparty)?; - - let expected_chan_end_on_b = ChannelEnd::new( - ChannelState::TryOpen, - // Note: Both ends of a channel must have the same ordering, so it's - // fine to use A's ordering here - *chan_end_on_a.ordering(), - Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())), - vec![conn_id_on_b.clone()], - msg.version_on_b.clone(), - )?; - let chan_end_path_on_b = ChannelEndPath::new(port_id_on_b, &msg.chan_id_on_b); - - // Verify the proof for the channel state against the expected channel end. - // A counterparty channel id of None in not possible, and is checked by validate_basic in msg. - client_state_of_b_on_a.verify_membership( - prefix_on_b, - &msg.proof_chan_end_on_b, - consensus_state_of_b_on_a.root(), - Path::ChannelEnd(chan_end_path_on_b), - expected_chan_end_on_b.encode_vec(), - )?; - } - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/src/handler/chan_open_confirm.rs b/ibc-eureka-core/ics04-channel/src/handler/chan_open_confirm.rs deleted file mode 100644 index 4347c3bb0..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/chan_open_confirm.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! Protocol logic specific to ICS4 messages of type `MsgChannelOpenConfirm`. - -use ibc_eureka_core_channel_types::channel::{ - ChannelEnd, Counterparty, State, State as ChannelState, -}; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::OpenConfirm; -use ibc_eureka_core_channel_types::msgs::MsgChannelOpenConfirm; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::types::error::ConnectionError; -use ibc_eureka_core_connection::types::State as ConnectionState; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::path::{ChannelEndPath, ClientConsensusStatePath, Path}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_eureka_core_router::module::Module; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::Protobuf; - -pub fn chan_open_confirm_validate( - ctx_b: &ValCtx, - module: &dyn Module, - msg: MsgChannelOpenConfirm, -) -> Result<(), ChannelError> -where - ValCtx: ValidationContext, -{ - validate(ctx_b, &msg)?; - - module.on_chan_open_confirm_validate(&msg.port_id_on_b, &msg.chan_id_on_b)?; - - Ok(()) -} - -pub fn chan_open_confirm_execute( - ctx_b: &mut ExecCtx, - module: &mut dyn Module, - msg: MsgChannelOpenConfirm, -) -> Result<(), ChannelError> -where - ExecCtx: ExecutionContext, -{ - 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)?; - - // state changes - { - let chan_end_on_b = { - let mut chan_end_on_b = chan_end_on_b.clone(); - chan_end_on_b.set_state(State::Open); - - chan_end_on_b - }; - ctx_b.store_channel(&chan_end_path_on_b, chan_end_on_b)?; - } - - // emit events and logs - { - ctx_b.log_message("success: channel open confirm".to_string())?; - - let conn_id_on_b = chan_end_on_b.connection_hops[0].clone(); - let port_id_on_a = chan_end_on_b.counterparty().port_id.clone(); - let chan_id_on_a = chan_end_on_b - .counterparty() - .channel_id - .clone() - .ok_or(ChannelError::MissingCounterparty)?; - - let core_event = IbcEvent::OpenConfirmChannel(OpenConfirm::new( - msg.port_id_on_b.clone(), - msg.chan_id_on_b.clone(), - port_id_on_a, - chan_id_on_a, - conn_id_on_b, - )); - ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_b.emit_ibc_event(core_event)?; - - for module_event in extras.events { - ctx_b.emit_ibc_event(IbcEvent::Module(module_event))?; - } - - for log_message in extras.log { - ctx_b.log_message(log_message)?; - } - } - - Ok(()) -} - -fn validate(ctx_b: &Ctx, msg: &MsgChannelOpenConfirm) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_b.validate_message_signer(&msg.signer)?; - - // Unwrap the old channel end and validate it against the message. - 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)?; - - // Validate that the channel end is in a state where it can be confirmed. - chan_end_on_b.verify_state_matches(&ChannelState::TryOpen)?; - - // An OPEN IBC connection running on the local (host) chain should exist. - chan_end_on_b.verify_connection_hops_length()?; - - let conn_end_on_b = ctx_b.connection_end(&chan_end_on_b.connection_hops()[0])?; - - conn_end_on_b.verify_state_matches(&ConnectionState::Open)?; - - // Verify proofs - { - let client_id_on_b = conn_end_on_b.client_id(); - let client_val_ctx_b = ctx_b.get_client_validation_context(); - let client_state_of_a_on_b = client_val_ctx_b.client_state(client_id_on_b)?; - - client_state_of_a_on_b - .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; - - client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; - - let client_cons_state_path_on_b = ClientConsensusStatePath::new( - client_id_on_b.clone(), - msg.proof_height_on_a.revision_number(), - msg.proof_height_on_a.revision_height(), - ); - let consensus_state_of_a_on_b = - client_val_ctx_b.consensus_state(&client_cons_state_path_on_b)?; - let prefix_on_a = conn_end_on_b.counterparty().prefix(); - let port_id_on_a = &chan_end_on_b.counterparty().port_id; - let chan_id_on_a = chan_end_on_b - .counterparty() - .channel_id() - .ok_or(ChannelError::MissingCounterparty)?; - let conn_id_on_a = conn_end_on_b - .counterparty() - .connection_id() - .ok_or(ConnectionError::MissingCounterparty)?; - - let expected_chan_end_on_a = ChannelEnd::new( - ChannelState::Open, - *chan_end_on_b.ordering(), - Counterparty::new(msg.port_id_on_b.clone(), Some(msg.chan_id_on_b.clone())), - vec![conn_id_on_a.clone()], - chan_end_on_b.version.clone(), - )?; - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, chan_id_on_a); - - // Verify the proof for the channel state against the expected channel end. - // A counterparty channel id of None in not possible, and is checked in msg. - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_chan_end_on_a, - consensus_state_of_a_on_b.root(), - Path::ChannelEnd(chan_end_path_on_a), - expected_chan_end_on_a.encode_vec(), - )?; - } - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/src/handler/chan_open_init.rs b/ibc-eureka-core/ics04-channel/src/handler/chan_open_init.rs deleted file mode 100644 index f6ba84811..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/chan_open_init.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! Protocol logic specific to ICS4 messages of type `MsgChannelOpenInit`. - -use core::str::FromStr; - -use ibc_eureka_core_channel_types::channel::{ChannelEnd, Counterparty, State}; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::OpenInit; -use ibc_eureka_core_channel_types::msgs::MsgChannelOpenInit; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::identifiers::ChannelId; -use ibc_eureka_core_host::types::path::{ChannelEndPath, SeqAckPath, SeqRecvPath, SeqSendPath}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_eureka_core_router::module::Module; -use ibc_primitives::prelude::*; - -pub fn chan_open_init_validate( - ctx_a: &ValCtx, - module: &dyn Module, - msg: MsgChannelOpenInit, -) -> Result<(), ChannelError> -where - ValCtx: ValidationContext, -{ - validate(ctx_a, &msg)?; - // todo(rano): hack - let chan_id_on_a = ChannelId::from_str("00-dummy-0")?; - - module.on_chan_open_init_validate( - msg.ordering, - &msg.connection_hops_on_a, - &msg.port_id_on_a, - &chan_id_on_a, - &Counterparty::new(msg.port_id_on_b.clone(), None), - &msg.version_proposal, - )?; - - Ok(()) -} - -pub fn chan_open_init_execute( - ctx_a: &mut ExecCtx, - module: &mut dyn Module, - msg: MsgChannelOpenInit, -) -> Result<(), ChannelError> -where - ExecCtx: ExecutionContext, -{ - // todo(rano): hack - let chan_id_on_a = ChannelId::from_str("00-dummy-0")?; - let (extras, version) = module.on_chan_open_init_execute( - msg.ordering, - &msg.connection_hops_on_a, - &msg.port_id_on_a, - &chan_id_on_a, - &Counterparty::new(msg.port_id_on_b.clone(), None), - &msg.version_proposal, - )?; - - let conn_id_on_a = msg.connection_hops_on_a[0].clone(); - - // state changes - { - let chan_end_on_a = ChannelEnd::new( - State::Init, - msg.ordering, - Counterparty::new(msg.port_id_on_b.clone(), None), - msg.connection_hops_on_a.clone(), - msg.version_proposal.clone(), - )?; - let chan_end_path_on_a = ChannelEndPath::new(&msg.port_id_on_a, &chan_id_on_a); - ctx_a.store_channel(&chan_end_path_on_a, chan_end_on_a)?; - - ctx_a.increase_channel_counter()?; - - // Initialize send, recv, and ack sequence numbers. - let seq_send_path = SeqSendPath::new(&msg.port_id_on_a, &chan_id_on_a); - ctx_a.store_next_sequence_send(&seq_send_path, 1.into())?; - - let seq_recv_path = SeqRecvPath::new(&msg.port_id_on_a, &chan_id_on_a); - ctx_a.store_next_sequence_recv(&seq_recv_path, 1.into())?; - - let seq_ack_path = SeqAckPath::new(&msg.port_id_on_a, &chan_id_on_a); - ctx_a.store_next_sequence_ack(&seq_ack_path, 1.into())?; - } - - // emit events and logs - { - ctx_a.log_message(format!( - "success: channel open init with channel identifier: {chan_id_on_a}" - ))?; - let core_event = IbcEvent::OpenInitChannel(OpenInit::new( - msg.port_id_on_a.clone(), - chan_id_on_a.clone(), - msg.port_id_on_b, - conn_id_on_a, - version, - )); - ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_a.emit_ibc_event(core_event)?; - - for module_event in extras.events { - ctx_a.emit_ibc_event(IbcEvent::Module(module_event))?; - } - - for log_message in extras.log { - ctx_a.log_message(log_message)?; - } - } - - Ok(()) -} - -fn validate(ctx_a: &Ctx, msg: &MsgChannelOpenInit) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_a.validate_message_signer(&msg.signer)?; - - msg.verify_connection_hops_length()?; - // An IBC connection running on the local (host) chain should exist. - let conn_end_on_a = ctx_a.connection_end(&msg.connection_hops_on_a[0])?; - - // Note: Not needed check if the connection end is OPEN. Optimistic channel handshake is allowed. - - let client_id_on_a = conn_end_on_a.client_id(); - let client_val_ctx_a = ctx_a.get_client_validation_context(); - let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; - - client_state_of_b_on_a - .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; - - let conn_version = conn_end_on_a.versions(); - - conn_version[0].verify_feature_supported(msg.ordering.to_string())?; - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/src/handler/chan_open_try.rs b/ibc-eureka-core/ics04-channel/src/handler/chan_open_try.rs deleted file mode 100644 index b6c2dec68..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/chan_open_try.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! Protocol logic specific to ICS4 messages of type `MsgChannelOpenTry`. - -use core::str::FromStr; - -use ibc_eureka_core_channel_types::channel::{ChannelEnd, Counterparty, State as ChannelState}; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::OpenTry; -use ibc_eureka_core_channel_types::msgs::MsgChannelOpenTry; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::types::error::ConnectionError; -use ibc_eureka_core_connection::types::State as ConnectionState; -use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::identifiers::ChannelId; -use ibc_eureka_core_host::types::path::{ - ChannelEndPath, ClientConsensusStatePath, Path, SeqAckPath, SeqRecvPath, SeqSendPath, -}; -use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; -use ibc_eureka_core_router::module::Module; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::Protobuf; - -pub fn chan_open_try_validate( - ctx_b: &ValCtx, - module: &dyn Module, - msg: MsgChannelOpenTry, -) -> Result<(), ChannelError> -where - ValCtx: ValidationContext, -{ - validate(ctx_b, &msg)?; - - // todo(rano): hack - let chan_id_on_b = ChannelId::from_str("00-dummy-0")?; - - module.on_chan_open_try_validate( - msg.ordering, - &msg.connection_hops_on_b, - &msg.port_id_on_b, - &chan_id_on_b, - &Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())), - &msg.version_supported_on_a, - )?; - - Ok(()) -} - -pub fn chan_open_try_execute( - ctx_b: &mut ExecCtx, - module: &mut dyn Module, - msg: MsgChannelOpenTry, -) -> Result<(), ChannelError> -where - ExecCtx: ExecutionContext, -{ - // todo(rano): hack - let chan_id_on_b = ChannelId::from_str("00-dummy-0")?; - let (extras, version) = module.on_chan_open_try_execute( - msg.ordering, - &msg.connection_hops_on_b, - &msg.port_id_on_b, - &chan_id_on_b, - &Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())), - &msg.version_supported_on_a, - )?; - - let conn_id_on_b = msg.connection_hops_on_b[0].clone(); - - // state changes - { - let chan_end_on_b = ChannelEnd::new( - ChannelState::TryOpen, - msg.ordering, - Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())), - msg.connection_hops_on_b.clone(), - version.clone(), - )?; - - let chan_end_path_on_b = ChannelEndPath::new(&msg.port_id_on_b, &chan_id_on_b); - ctx_b.store_channel(&chan_end_path_on_b, chan_end_on_b)?; - ctx_b.increase_channel_counter()?; - - // Initialize send, recv, and ack sequence numbers. - let seq_send_path = SeqSendPath::new(&msg.port_id_on_b, &chan_id_on_b); - ctx_b.store_next_sequence_send(&seq_send_path, 1.into())?; - - let seq_recv_path = SeqRecvPath::new(&msg.port_id_on_b, &chan_id_on_b); - ctx_b.store_next_sequence_recv(&seq_recv_path, 1.into())?; - - let seq_ack_path = SeqAckPath::new(&msg.port_id_on_b, &chan_id_on_b); - ctx_b.store_next_sequence_ack(&seq_ack_path, 1.into())?; - } - - // emit events and logs - { - ctx_b.log_message(format!( - "success: channel open try with channel identifier: {chan_id_on_b}" - ))?; - - let core_event = IbcEvent::OpenTryChannel(OpenTry::new( - msg.port_id_on_b.clone(), - chan_id_on_b.clone(), - msg.port_id_on_a.clone(), - msg.chan_id_on_a.clone(), - conn_id_on_b, - version, - )); - ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_b.emit_ibc_event(core_event)?; - - for module_event in extras.events { - ctx_b.emit_ibc_event(IbcEvent::Module(module_event))?; - } - - for log_message in extras.log { - ctx_b.log_message(log_message)?; - } - } - - Ok(()) -} - -fn validate(ctx_b: &Ctx, msg: &MsgChannelOpenTry) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_b.validate_message_signer(&msg.signer)?; - - msg.verify_connection_hops_length()?; - - let conn_end_on_b = ctx_b.connection_end(&msg.connection_hops_on_b[0])?; - - conn_end_on_b.verify_state_matches(&ConnectionState::Open)?; - - let conn_version = conn_end_on_b.versions(); - - conn_version[0].verify_feature_supported(msg.ordering.to_string())?; - - // Verify proofs - { - let client_id_on_b = conn_end_on_b.client_id(); - let client_val_ctx_b = ctx_b.get_client_validation_context(); - let client_state_of_a_on_b = client_val_ctx_b.client_state(client_id_on_b)?; - - client_state_of_a_on_b - .status(ctx_b.get_client_validation_context(), client_id_on_b)? - .verify_is_active()?; - - client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; - - let client_cons_state_path_on_b = ClientConsensusStatePath::new( - client_id_on_b.clone(), - msg.proof_height_on_a.revision_number(), - msg.proof_height_on_a.revision_height(), - ); - let consensus_state_of_a_on_b = - client_val_ctx_b.consensus_state(&client_cons_state_path_on_b)?; - let prefix_on_a = conn_end_on_b.counterparty().prefix(); - let port_id_on_a = msg.port_id_on_a.clone(); - let chan_id_on_a = msg.chan_id_on_a.clone(); - let conn_id_on_a = conn_end_on_b - .counterparty() - .connection_id() - .ok_or(ConnectionError::MissingCounterparty)?; - - let expected_chan_end_on_a = ChannelEnd::new( - ChannelState::Init, - msg.ordering, - Counterparty::new(msg.port_id_on_b.clone(), None), - vec![conn_id_on_a.clone()], - msg.version_supported_on_a.clone(), - )?; - let chan_end_path_on_a = ChannelEndPath::new(&port_id_on_a, &chan_id_on_a); - - // Verify the proof for the channel state against the expected channel end. - // A counterparty channel id of None in not possible, and is checked by validate_basic in msg. - client_state_of_a_on_b.verify_membership( - prefix_on_a, - &msg.proof_chan_end_on_a, - consensus_state_of_a_on_b.root(), - Path::ChannelEnd(chan_end_path_on_a), - expected_chan_end_on_a.encode_vec(), - )?; - } - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/src/handler/mod.rs b/ibc-eureka-core/ics04-channel/src/handler/mod.rs index b1ea237a1..adc56c5cb 100644 --- a/ibc-eureka-core/ics04-channel/src/handler/mod.rs +++ b/ibc-eureka-core/ics04-channel/src/handler/mod.rs @@ -1,24 +1,10 @@ //! This module implements the processing logic for ICS4 (channel) messages. mod acknowledgement; -mod chan_close_confirm; -mod chan_close_init; -mod chan_open_ack; -mod chan_open_confirm; -mod chan_open_init; -mod chan_open_try; mod recv_packet; mod send_packet; mod timeout; -mod timeout_on_close; pub use acknowledgement::*; -pub use chan_close_confirm::*; -pub use chan_close_init::*; -pub use chan_open_ack::*; -pub use chan_open_confirm::*; -pub use chan_open_init::*; -pub use chan_open_try::*; pub use recv_packet::*; pub use send_packet::*; pub use timeout::*; -pub use timeout_on_close::*; diff --git a/ibc-eureka-core/ics04-channel/src/handler/recv_packet.rs b/ibc-eureka-core/ics04-channel/src/handler/recv_packet.rs index 4cf70bf11..ea76af1e3 100644 --- a/ibc-eureka-core/ics04-channel/src/handler/recv_packet.rs +++ b/ibc-eureka-core/ics04-channel/src/handler/recv_packet.rs @@ -1,18 +1,13 @@ -use ibc_eureka_core_channel_types::channel::{Counterparty, Order, State as ChannelState}; use ibc_eureka_core_channel_types::commitment::{ compute_ack_commitment, compute_packet_commitment, }; use ibc_eureka_core_channel_types::error::ChannelError; use ibc_eureka_core_channel_types::events::{ReceivePacket, WriteAcknowledgement}; use ibc_eureka_core_channel_types::msgs::MsgRecvPacket; -use ibc_eureka_core_channel_types::packet::Receipt; use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::delay::verify_conn_delay_passed; -use ibc_eureka_core_connection::types::State as ConnectionState; use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_eureka_core_host::types::path::{ - AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, - SeqRecvPath, + AckPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, }; use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; use ibc_eureka_core_router::module::Module; @@ -40,31 +35,17 @@ where let packet = &msg.packet; let payload = &packet.payloads[0]; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; + let (_, target_port) = &payload.header.target_port; + let channel_source_client_on_target = &packet.header.source_client_on_target; let seq_on_a = &packet.header.seq_on_a; - let chan_end_path_on_b = ChannelEndPath::new(port_id_on_b, channel_id_on_b); - let chan_end_on_b = ctx_b.channel_end(&chan_end_path_on_b)?; - // Check if another relayer already relayed the packet. // We don't want to fail the transaction in this case. { - let packet_already_received = match chan_end_on_b.ordering { - // Note: ibc-go doesn't make the check for `Order::None` channels - Order::None => false, - Order::Unordered => { - let receipt_path_on_b = ReceiptPath::new(port_id_on_b, channel_id_on_b, *seq_on_a); - ctx_b.get_packet_receipt(&receipt_path_on_b)?.is_ok() - } - Order::Ordered => { - let seq_recv_path_on_b = SeqRecvPath::new(port_id_on_b, channel_id_on_b); - let next_seq_recv = ctx_b.get_next_sequence_recv(&seq_recv_path_on_b)?; - - // the sequence number has already been incremented, so - // another relayer already relayed the packet - seq_on_a < &next_seq_recv - } + let packet_already_received = { + let receipt_path_on_b = + ReceiptPath::new(target_port, channel_source_client_on_target, *seq_on_a); + ctx_b.get_packet_receipt(&receipt_path_on_b)?.is_ok() }; if packet_already_received { @@ -77,24 +58,12 @@ where // state changes { // `recvPacket` core handler state changes - match chan_end_on_b.ordering { - Order::Unordered => { - let receipt_path_on_b = ReceiptPath { - port_id: port_id_on_b.clone(), - channel_id: channel_id_on_b.clone(), - sequence: *seq_on_a, - }; - - ctx_b.store_packet_receipt(&receipt_path_on_b, Receipt::Ok)?; - } - Order::Ordered => { - let seq_recv_path_on_b = SeqRecvPath::new(port_id_on_b, channel_id_on_b); - let next_seq_recv = ctx_b.get_next_sequence_recv(&seq_recv_path_on_b)?; - ctx_b.store_next_sequence_recv(&seq_recv_path_on_b, next_seq_recv.increment())?; - } - _ => {} + { + let seq_recv_path_on_b = SeqRecvPath::new(target_port, channel_source_client_on_target); + let next_seq_recv = ctx_b.get_next_sequence_recv(&seq_recv_path_on_b)?; + ctx_b.store_next_sequence_recv(&seq_recv_path_on_b, next_seq_recv.increment())?; } - let ack_path_on_b = AckPath::new(port_id_on_b, channel_id_on_b, *seq_on_a); + let ack_path_on_b = AckPath::new(target_port, channel_source_client_on_target, *seq_on_a); // `writeAcknowledgement` handler state changes ctx_b.store_packet_acknowledgement( &ack_path_on_b, @@ -107,19 +76,11 @@ where ctx_b.log_message("success: packet receive".to_string())?; ctx_b.log_message("success: packet write acknowledgement".to_string())?; - let conn_id_on_b = &chan_end_on_b.connection_hops()[0]; - let event = IbcEvent::ReceivePacket(ReceivePacket::new( - msg.packet.clone(), - chan_end_on_b.ordering, - conn_id_on_b.clone(), - )); + let event = IbcEvent::ReceivePacket(ReceivePacket::new(msg.packet.clone())); ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; ctx_b.emit_ibc_event(event)?; - let event = IbcEvent::WriteAcknowledgement(WriteAcknowledgement::new( - msg.packet, - acknowledgement, - conn_id_on_b.clone(), - )); + let event = + IbcEvent::WriteAcknowledgement(WriteAcknowledgement::new(msg.packet, acknowledgement)); ctx_b.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; ctx_b.emit_ibc_event(event)?; @@ -144,27 +105,12 @@ where let packet = &msg.packet; let payload = &packet.payloads[0]; - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; + let (prefix_source, source_port) = &payload.header.source_port; + let channel_target_client_on_source = &packet.header.target_client_on_source; + let channel_source_client_on_target = &packet.header.source_client_on_target; let seq_on_a = &packet.header.seq_on_a; let data = &payload.data; - let chan_end_path_on_b = ChannelEndPath::new(port_id_on_b, channel_id_on_b); - let chan_end_on_b = ctx_b.channel_end(&chan_end_path_on_b)?; - - chan_end_on_b.verify_state_matches(&ChannelState::Open)?; - - let counterparty = Counterparty::new(port_id_on_a.clone(), Some(channel_id_on_a.clone())); - - chan_end_on_b.verify_counterparty_matches(&counterparty)?; - - let conn_id_on_b = &chan_end_on_b.connection_hops()[0]; - let conn_end_on_b = ctx_b.connection_end(conn_id_on_b)?; - - conn_end_on_b.verify_state_matches(&ConnectionState::Open)?; - let latest_height = ctx_b.host_height()?; if packet.header.timeout_height_on_b.has_expired(latest_height) { return Err(ChannelError::InsufficientPacketHeight { @@ -184,18 +130,21 @@ where // Verify proofs { - let client_id_on_b = conn_end_on_b.client_id(); + let id_source_client_on_target = channel_source_client_on_target.as_ref(); let client_val_ctx_b = ctx_b.get_client_validation_context(); - let client_state_of_a_on_b = client_val_ctx_b.client_state(client_id_on_b)?; + let source_client_on_target = client_val_ctx_b.client_state(id_source_client_on_target)?; - client_state_of_a_on_b - .status(ctx_b.get_client_validation_context(), client_id_on_b)? + source_client_on_target + .status( + ctx_b.get_client_validation_context(), + id_source_client_on_target, + )? .verify_is_active()?; - client_state_of_a_on_b.validate_proof_height(msg.proof_height_on_a)?; + source_client_on_target.validate_proof_height(msg.proof_height_on_a)?; let client_cons_state_path_on_b = ClientConsensusStatePath::new( - client_id_on_b.clone(), + id_source_client_on_target.clone(), msg.proof_height_on_a.revision_number(), msg.proof_height_on_a.revision_height(), ); @@ -208,13 +157,12 @@ where &packet.header.timeout_height_on_b, &packet.header.timeout_timestamp_on_b, ); - let commitment_path_on_a = CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a); - - verify_conn_delay_passed(ctx_b, msg.proof_height_on_a, &conn_end_on_b)?; + let commitment_path_on_a = + CommitmentPath::new(source_port, channel_target_client_on_source, *seq_on_a); // Verify the proof for the packet against the chain store. - client_state_of_a_on_b.verify_membership( - conn_end_on_b.counterparty().prefix(), + source_client_on_target.verify_membership( + prefix_source, &msg.proof_commitment_on_a, consensus_state_of_a_on_b.root(), Path::Commitment(commitment_path_on_a), @@ -222,39 +170,15 @@ where )?; } - match chan_end_on_b.ordering { - Order::Ordered => { - let seq_recv_path_on_b = SeqRecvPath::new(port_id_on_b, channel_id_on_b); - let next_seq_recv = ctx_b.get_next_sequence_recv(&seq_recv_path_on_b)?; - if seq_on_a > &next_seq_recv { - return Err(ChannelError::MismatchedPacketSequence { - actual: *seq_on_a, - expected: next_seq_recv, - }); - } - - if seq_on_a == &next_seq_recv { - // Case where the recvPacket is successful and an - // acknowledgement will be written (not a no-op) - validate_write_acknowledgement(ctx_b, msg)?; - } - } - Order::Unordered => { - // Note: We don't check for the packet receipt here because another - // relayer may have already relayed the packet. If that's the case, - // we want to avoid failing the transaction and consuming - // unnecessary fees. - - // Case where the recvPacket is successful and an - // acknowledgement will be written (not a no-op) - validate_write_acknowledgement(ctx_b, msg)?; - } - Order::None => { - return Err(ChannelError::InvalidState { - expected: "Channel ordering to not be None".to_string(), - actual: chan_end_on_b.ordering.to_string(), - }) - } + { + // Note: We don't check for the packet receipt here because another + // relayer may have already relayed the packet. If that's the case, + // we want to avoid failing the transaction and consuming + // unnecessary fees. + + // Case where the recvPacket is successful and an + // acknowledgement will be written (not a no-op) + validate_write_acknowledgement(ctx_b, msg)?; } Ok(()) @@ -267,11 +191,11 @@ where let packet = &msg.packet; let payload = &packet.payloads[0]; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; + let (_, target_port) = &payload.header.target_port; + let channel_source_client_on_target = &packet.header.source_client_on_target; let seq_on_a = &packet.header.seq_on_a; - let ack_path_on_b = AckPath::new(port_id_on_b, channel_id_on_b, *seq_on_a); + let ack_path_on_b = AckPath::new(target_port, channel_source_client_on_target, *seq_on_a); if ctx_b.get_packet_acknowledgement(&ack_path_on_b).is_ok() { return Err(ChannelError::DuplicateAcknowledgment(*seq_on_a)); } diff --git a/ibc-eureka-core/ics04-channel/src/handler/send_packet.rs b/ibc-eureka-core/ics04-channel/src/handler/send_packet.rs index 1415ca2b1..6e9747ebe 100644 --- a/ibc-eureka-core/ics04-channel/src/handler/send_packet.rs +++ b/ibc-eureka-core/ics04-channel/src/handler/send_packet.rs @@ -1,13 +1,10 @@ -use ibc_eureka_core_channel_types::channel::Counterparty; use ibc_eureka_core_channel_types::commitment::compute_packet_commitment; use ibc_eureka_core_channel_types::error::ChannelError; use ibc_eureka_core_channel_types::events::SendPacket; use ibc_eureka_core_channel_types::packet::Packet; use ibc_eureka_core_client::context::prelude::*; use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; -use ibc_eureka_core_host::types::path::{ - ChannelEndPath, ClientConsensusStatePath, CommitmentPath, SeqSendPath, -}; +use ibc_eureka_core_host::types::path::{ClientConsensusStatePath, CommitmentPath, SeqSendPath}; use ibc_primitives::prelude::*; use crate::context::{SendPacketExecutionContext, SendPacketValidationContext}; @@ -35,64 +32,50 @@ pub fn send_packet_validate( let payload = &packet.payloads[0]; - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; + let (_, source_port) = &payload.header.source_port; + let channel_target_client_on_source = &packet.header.target_client_on_source; let seq_on_a = &packet.header.seq_on_a; - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, channel_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - - // Checks the channel end not be `Closed`. - // This allows for optimistic packet processing before a channel opens - chan_end_on_a.verify_not_closed()?; - - let counterparty = Counterparty::new(port_id_on_b.clone(), Some(channel_id_on_b.clone())); - - chan_end_on_a.verify_counterparty_matches(&counterparty)?; - - let conn_id_on_a = &chan_end_on_a.connection_hops()[0]; - - let conn_end_on_a = ctx_a.connection_end(conn_id_on_a)?; - - let client_id_on_a = conn_end_on_a.client_id(); + let id_target_client_on_source = channel_target_client_on_source.as_ref(); let client_val_ctx_a = ctx_a.get_client_validation_context(); - let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; + let target_client_on_source = client_val_ctx_a.client_state(id_target_client_on_source)?; - client_state_of_b_on_a - .status(ctx_a.get_client_validation_context(), client_id_on_a)? + target_client_on_source + .status( + ctx_a.get_client_validation_context(), + id_target_client_on_source, + )? .verify_is_active()?; - let latest_height_on_a = client_state_of_b_on_a.latest_height(); + let latest_height_on_target = target_client_on_source.latest_height(); if packet .header .timeout_height_on_b - .has_expired(latest_height_on_a) + .has_expired(latest_height_on_target) { return Err(ChannelError::InsufficientPacketHeight { - chain_height: latest_height_on_a, + chain_height: latest_height_on_target, timeout_height: packet.header.timeout_height_on_b, }); } let client_cons_state_path_on_a = ClientConsensusStatePath::new( - client_id_on_a.clone(), - latest_height_on_a.revision_number(), - latest_height_on_a.revision_height(), + id_target_client_on_source.clone(), + latest_height_on_target.revision_number(), + latest_height_on_target.revision_height(), ); - let consensus_state_of_b_on_a = - client_val_ctx_a.consensus_state(&client_cons_state_path_on_a)?; - let latest_timestamp = consensus_state_of_b_on_a.timestamp()?; + let target_consensus_state = client_val_ctx_a.consensus_state(&client_cons_state_path_on_a)?; + let latest_timestamp = target_consensus_state.timestamp()?; let packet_timestamp = packet.header.timeout_timestamp_on_b; if packet_timestamp.has_expired(&latest_timestamp) { return Err(ChannelError::ExpiredPacketTimestamp); } - let seq_send_path_on_a = SeqSendPath::new(port_id_on_a, channel_id_on_a); + // TODO(rano): include full channel identifier in the path + let seq_send_path_on_a = SeqSendPath::new(source_port, channel_target_client_on_source); let next_seq_send_on_a = ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; if seq_on_a != &next_seq_send_on_a { @@ -114,20 +97,20 @@ pub fn send_packet_execute( ) -> Result<(), ChannelError> { let payload = &packet.payloads[0]; - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; + let (_, source_port) = &payload.header.source_port; + let channel_target_client_on_source = &packet.header.target_client_on_source; let seq_on_a = &packet.header.seq_on_a; let data = &payload.data; { - let seq_send_path_on_a = SeqSendPath::new(port_id_on_a, channel_id_on_a); + let seq_send_path_on_a = SeqSendPath::new(source_port, channel_target_client_on_source); let next_seq_send_on_a = ctx_a.get_next_sequence_send(&seq_send_path_on_a)?; ctx_a.store_next_sequence_send(&seq_send_path_on_a, next_seq_send_on_a.increment())?; } ctx_a.store_packet_commitment( - &CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a), + &CommitmentPath::new(source_port, channel_target_client_on_source, *seq_on_a), compute_packet_commitment( data, &packet.header.timeout_height_on_b, @@ -137,16 +120,8 @@ pub fn send_packet_execute( // emit events and logs { - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, channel_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - let conn_id_on_a = &chan_end_on_a.connection_hops()[0]; - ctx_a.log_message("success: packet send".to_string())?; - let event = IbcEvent::SendPacket(SendPacket::new( - packet, - chan_end_on_a.ordering, - conn_id_on_a.clone(), - )); + let event = IbcEvent::SendPacket(SendPacket::new(packet)); ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; ctx_a.emit_ibc_event(event)?; } diff --git a/ibc-eureka-core/ics04-channel/src/handler/timeout.rs b/ibc-eureka-core/ics04-channel/src/handler/timeout.rs index 3ac0190e8..0166dffc8 100644 --- a/ibc-eureka-core/ics04-channel/src/handler/timeout.rs +++ b/ibc-eureka-core/ics04-channel/src/handler/timeout.rs @@ -1,42 +1,27 @@ -use ibc_eureka_core_channel_types::channel::{Counterparty, Order, State}; use ibc_eureka_core_channel_types::commitment::compute_packet_commitment; use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::events::{ChannelClosed, TimeoutPacket}; -use ibc_eureka_core_channel_types::msgs::{MsgTimeout, MsgTimeoutOnClose}; +use ibc_eureka_core_channel_types::events::TimeoutPacket; +use ibc_eureka_core_channel_types::msgs::MsgTimeout; use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::delay::verify_conn_delay_passed; use ibc_eureka_core_handler_types::events::{IbcEvent, MessageEvent}; use ibc_eureka_core_host::types::path::{ - ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, + ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, }; use ibc_eureka_core_host::{ExecutionContext, ValidationContext}; use ibc_eureka_core_router::module::Module; use ibc_primitives::prelude::*; -use super::timeout_on_close; - -pub enum TimeoutMsgType { - Timeout(MsgTimeout), - TimeoutOnClose(MsgTimeoutOnClose), -} - pub fn timeout_packet_validate( ctx_a: &ValCtx, module: &dyn Module, - timeout_msg_type: TimeoutMsgType, + msg: MsgTimeout, ) -> Result<(), ChannelError> where ValCtx: ValidationContext, { - match &timeout_msg_type { - TimeoutMsgType::Timeout(msg) => validate(ctx_a, msg), - TimeoutMsgType::TimeoutOnClose(msg) => timeout_on_close::validate(ctx_a, msg), - }?; - - let (packet, signer) = match timeout_msg_type { - TimeoutMsgType::Timeout(msg) => (msg.packet, msg.signer), - TimeoutMsgType::TimeoutOnClose(msg) => (msg.packet, msg.signer), - }; + validate(ctx_a, &msg)?; + + let (packet, signer) = (msg.packet, msg.signer); module.on_timeout_packet_validate(&packet, &signer) } @@ -44,31 +29,26 @@ where pub fn timeout_packet_execute( ctx_a: &mut ExecCtx, module: &mut dyn Module, - timeout_msg_type: TimeoutMsgType, + msg: MsgTimeout, ) -> Result<(), ChannelError> where ExecCtx: ExecutionContext, { - let (packet, signer) = match timeout_msg_type { - TimeoutMsgType::Timeout(msg) => (msg.packet, msg.signer), - TimeoutMsgType::TimeoutOnClose(msg) => (msg.packet, msg.signer), - }; + let (packet, signer) = (msg.packet, msg.signer); let payload = &packet.payloads[0]; - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; + let (_, source_port) = &payload.header.source_port; + let channel_target_client_on_source = &packet.header.target_client_on_source; let seq_on_a = &packet.header.seq_on_a; - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, channel_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - // In all cases, this event is emitted - let event = IbcEvent::TimeoutPacket(TimeoutPacket::new(packet.clone(), chan_end_on_a.ordering)); + let event = IbcEvent::TimeoutPacket(TimeoutPacket::new(packet.clone())); ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; ctx_a.emit_ibc_event(event)?; - let commitment_path_on_a = CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a); + let commitment_path_on_a = + CommitmentPath::new(source_port, channel_target_client_on_source, *seq_on_a); // check if we're in the NO-OP case if ctx_a.get_packet_commitment(&commitment_path_on_a).is_err() { @@ -83,40 +63,10 @@ where cb_result?; - // apply state changes - let chan_end_on_a = { - ctx_a.delete_packet_commitment(&commitment_path_on_a)?; - - if let Order::Ordered = chan_end_on_a.ordering { - let mut chan_end_on_a = chan_end_on_a; - chan_end_on_a.state = State::Closed; - ctx_a.store_channel(&chan_end_path_on_a, chan_end_on_a.clone())?; - - chan_end_on_a - } else { - chan_end_on_a - } - }; - // emit events and logs { ctx_a.log_message("success: packet timeout".to_string())?; - if let Order::Ordered = chan_end_on_a.ordering { - let conn_id_on_a = chan_end_on_a.connection_hops()[0].clone(); - - let event = IbcEvent::ChannelClosed(ChannelClosed::new( - port_id_on_a.clone(), - channel_id_on_a.clone(), - chan_end_on_a.counterparty().port_id.clone(), - chan_end_on_a.counterparty().channel_id.clone(), - conn_id_on_a, - chan_end_on_a.ordering, - )); - ctx_a.emit_ibc_event(IbcEvent::Message(MessageEvent::Channel))?; - ctx_a.emit_ibc_event(event)?; - } - for module_event in extras.events { ctx_a.emit_ibc_event(IbcEvent::Module(module_event))?; } @@ -138,26 +88,16 @@ where let packet = &msg.packet; let payload = &packet.payloads[0]; - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; + let (_, source_port) = &payload.header.source_port; + let channel_target_client_on_source = &packet.header.target_client_on_source; + let (target_prefix, target_port) = &payload.header.target_port; + let channel_source_client_on_target = &packet.header.source_client_on_target; let seq_on_a = &packet.header.seq_on_a; let data = &payload.data; - let chan_end_on_a = ctx_a.channel_end(&ChannelEndPath::new(port_id_on_a, channel_id_on_a))?; - - chan_end_on_a.verify_state_matches(&State::Open)?; - - let counterparty = Counterparty::new(port_id_on_b.clone(), Some(channel_id_on_b.clone())); - - chan_end_on_a.verify_counterparty_matches(&counterparty)?; - - let conn_id_on_a = chan_end_on_a.connection_hops()[0].clone(); - let conn_end_on_a = ctx_a.connection_end(&conn_id_on_a)?; - //verify packet commitment - let commitment_path_on_a = CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a); + let commitment_path_on_a = + CommitmentPath::new(source_port, channel_target_client_on_source, *seq_on_a); let Ok(commitment_on_a) = ctx_a.get_packet_commitment(&commitment_path_on_a) else { // This error indicates that the timeout has already been relayed // or there is a misconfigured relayer attempting to prove a timeout @@ -181,19 +121,22 @@ where // Verify proofs { - let client_id_on_a = conn_end_on_a.client_id(); + let id_target_client_on_source = channel_target_client_on_source.as_ref(); let client_val_ctx_a = ctx_a.get_client_validation_context(); - let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; + let target_client_on_source = client_val_ctx_a.client_state(id_target_client_on_source)?; - client_state_of_b_on_a - .status(ctx_a.get_client_validation_context(), client_id_on_a)? + target_client_on_source + .status( + ctx_a.get_client_validation_context(), + id_target_client_on_source, + )? .verify_is_active()?; - client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; + target_client_on_source.validate_proof_height(msg.proof_height_on_b)?; // check that timeout height or timeout timestamp has passed on the other end let client_cons_state_path_on_a = ClientConsensusStatePath::new( - client_id_on_a.clone(), + id_target_client_on_source.clone(), msg.proof_height_on_b.revision_number(), msg.proof_height_on_b.revision_height(), ); @@ -210,42 +153,16 @@ where }); } - verify_conn_delay_passed(ctx_a, msg.proof_height_on_b, &conn_end_on_a)?; - - let next_seq_recv_verification_result = match chan_end_on_a.ordering { - Order::Ordered => { - if seq_on_a < &msg.next_seq_recv_on_b { - return Err(ChannelError::MismatchedPacketSequence { - actual: *seq_on_a, - expected: msg.next_seq_recv_on_b, - }); - } - let seq_recv_path_on_b = SeqRecvPath::new(port_id_on_b, channel_id_on_b); - - client_state_of_b_on_a.verify_membership( - conn_end_on_a.counterparty().prefix(), - &msg.proof_unreceived_on_b, - consensus_state_of_b_on_a.root(), - Path::SeqRecv(seq_recv_path_on_b), - seq_on_a.to_vec(), - ) - } - Order::Unordered => { - let receipt_path_on_b = ReceiptPath::new(port_id_on_b, channel_id_on_b, *seq_on_a); - - client_state_of_b_on_a.verify_non_membership( - conn_end_on_a.counterparty().prefix(), - &msg.proof_unreceived_on_b, - consensus_state_of_b_on_a.root(), - Path::Receipt(receipt_path_on_b), - ) - } - Order::None => { - return Err(ChannelError::InvalidState { - expected: "Channel ordering to not be None".to_string(), - actual: chan_end_on_a.ordering.to_string(), - }) - } + let next_seq_recv_verification_result = { + let receipt_path_on_b = + ReceiptPath::new(target_port, channel_source_client_on_target, *seq_on_a); + + target_client_on_source.verify_non_membership( + target_prefix, + &msg.proof_unreceived_on_b, + consensus_state_of_b_on_a.root(), + Path::Receipt(receipt_path_on_b), + ) }; next_seq_recv_verification_result?; diff --git a/ibc-eureka-core/ics04-channel/src/handler/timeout_on_close.rs b/ibc-eureka-core/ics04-channel/src/handler/timeout_on_close.rs deleted file mode 100644 index 353e2b44b..000000000 --- a/ibc-eureka-core/ics04-channel/src/handler/timeout_on_close.rs +++ /dev/null @@ -1,158 +0,0 @@ -use ibc_eureka_core_channel_types::channel::{ChannelEnd, Counterparty, Order, State}; -use ibc_eureka_core_channel_types::commitment::compute_packet_commitment; -use ibc_eureka_core_channel_types::error::ChannelError; -use ibc_eureka_core_channel_types::msgs::MsgTimeoutOnClose; -use ibc_eureka_core_client::context::prelude::*; -use ibc_eureka_core_connection::delay::verify_conn_delay_passed; -use ibc_eureka_core_connection::types::error::ConnectionError; -use ibc_eureka_core_host::types::path::{ - ChannelEndPath, ClientConsensusStatePath, CommitmentPath, Path, ReceiptPath, SeqRecvPath, -}; -use ibc_eureka_core_host::ValidationContext; -use ibc_primitives::prelude::*; -use ibc_primitives::proto::Protobuf; - -pub fn validate(ctx_a: &Ctx, msg: &MsgTimeoutOnClose) -> Result<(), ChannelError> -where - Ctx: ValidationContext, -{ - ctx_a.validate_message_signer(&msg.signer)?; - - let packet = &msg.packet; - let payload = &packet.payloads[0]; - - let port_id_on_a = &payload.header.source_port.1; - let channel_id_on_a = &packet.header.source_client; - let port_id_on_b = &payload.header.target_port.1; - let channel_id_on_b = &packet.header.target_client; - let seq_on_a = &packet.header.seq_on_a; - let data = &payload.data; - - let chan_end_path_on_a = ChannelEndPath::new(port_id_on_a, channel_id_on_a); - let chan_end_on_a = ctx_a.channel_end(&chan_end_path_on_a)?; - - let counterparty = Counterparty::new(port_id_on_b.clone(), Some(channel_id_on_b.clone())); - - chan_end_on_a.verify_counterparty_matches(&counterparty)?; - - let commitment_path_on_a = CommitmentPath::new(port_id_on_a, channel_id_on_a, *seq_on_a); - - //verify the packet was sent, check the store - let Ok(commitment_on_a) = ctx_a.get_packet_commitment(&commitment_path_on_a) else { - // This error indicates that the timeout has already been relayed - // or there is a misconfigured relayer attempting to prove a timeout - // for a packet never sent. Core IBC will treat this error as a no-op in order to - // prevent an entire relay transaction from failing and consuming unnecessary fees. - return Ok(()); - }; - - let expected_commitment_on_a = compute_packet_commitment( - data, - &packet.header.timeout_height_on_b, - &packet.header.timeout_timestamp_on_b, - ); - if commitment_on_a != expected_commitment_on_a { - return Err(ChannelError::MismatchedPacketCommitment { - expected: expected_commitment_on_a, - actual: commitment_on_a, - }); - } - - let conn_id_on_a = chan_end_on_a.connection_hops()[0].clone(); - let conn_end_on_a = ctx_a.connection_end(&conn_id_on_a)?; - - // Verify proofs - { - let client_id_on_a = conn_end_on_a.client_id(); - let client_val_ctx_a = ctx_a.get_client_validation_context(); - let client_state_of_b_on_a = client_val_ctx_a.client_state(client_id_on_a)?; - - client_state_of_b_on_a - .status(ctx_a.get_client_validation_context(), client_id_on_a)? - .verify_is_active()?; - - client_state_of_b_on_a.validate_proof_height(msg.proof_height_on_b)?; - - let client_cons_state_path_on_a = ClientConsensusStatePath::new( - client_id_on_a.clone(), - msg.proof_height_on_b.revision_number(), - msg.proof_height_on_b.revision_height(), - ); - let consensus_state_of_b_on_a = - client_val_ctx_a.consensus_state(&client_cons_state_path_on_a)?; - let prefix_on_b = conn_end_on_a.counterparty().prefix(); - let port_id_on_b = chan_end_on_a.counterparty().port_id.clone(); - let channel_id_on_b = chan_end_on_a - .counterparty() - .channel_id() - .ok_or(ChannelError::MissingCounterparty)?; - let conn_id_on_b = conn_end_on_a - .counterparty() - .connection_id() - .ok_or(ConnectionError::MissingCounterparty)?; - let expected_conn_hops_on_b = vec![conn_id_on_b.clone()]; - let expected_counterparty = - Counterparty::new(port_id_on_a.clone(), Some(channel_id_on_a.clone())); - let expected_chan_end_on_b = ChannelEnd::new( - State::Closed, - *chan_end_on_a.ordering(), - expected_counterparty, - expected_conn_hops_on_b, - chan_end_on_a.version().clone(), - )?; - - let chan_end_path_on_b = ChannelEndPath(port_id_on_b.clone(), channel_id_on_b.clone()); - - // Verify the proof for the channel state against the expected channel end. - // A counterparty channel id of None in not possible, and is checked by validate_basic in msg. - client_state_of_b_on_a.verify_membership( - prefix_on_b, - &msg.proof_close_on_b, - consensus_state_of_b_on_a.root(), - Path::ChannelEnd(chan_end_path_on_b), - expected_chan_end_on_b.encode_vec(), - )?; - - verify_conn_delay_passed(ctx_a, msg.proof_height_on_b, &conn_end_on_a)?; - - let next_seq_recv_verification_result = match chan_end_on_a.ordering { - Order::Ordered => { - if seq_on_a < &msg.next_seq_recv_on_b { - return Err(ChannelError::MismatchedPacketSequence { - actual: *seq_on_a, - expected: msg.next_seq_recv_on_b, - }); - } - let seq_recv_path_on_b = SeqRecvPath::new(&port_id_on_b, channel_id_on_b); - - client_state_of_b_on_a.verify_membership( - conn_end_on_a.counterparty().prefix(), - &msg.proof_unreceived_on_b, - consensus_state_of_b_on_a.root(), - Path::SeqRecv(seq_recv_path_on_b), - seq_on_a.to_vec(), - ) - } - Order::Unordered => { - let receipt_path_on_b = ReceiptPath::new(&port_id_on_b, channel_id_on_b, *seq_on_a); - - client_state_of_b_on_a.verify_non_membership( - conn_end_on_a.counterparty().prefix(), - &msg.proof_unreceived_on_b, - consensus_state_of_b_on_a.root(), - Path::Receipt(receipt_path_on_b), - ) - } - Order::None => { - return Err(ChannelError::InvalidState { - expected: "Channel ordering to not be None".to_string(), - actual: chan_end_on_a.ordering.to_string(), - }) - } - }; - - next_seq_recv_verification_result?; - }; - - Ok(()) -} diff --git a/ibc-eureka-core/ics04-channel/types/Cargo.toml b/ibc-eureka-core/ics04-channel/types/Cargo.toml index 2c8e280ba..e316fa6bd 100644 --- a/ibc-eureka-core/ics04-channel/types/Cargo.toml +++ b/ibc-eureka-core/ics04-channel/types/Cargo.toml @@ -30,7 +30,6 @@ subtle-encoding = { workspace = true } # ibc dependencies ibc-eureka-core-client-types = { workspace = true } -ibc-eureka-core-connection-types = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-host-types = { workspace = true } ibc-primitives = { workspace = true } @@ -55,7 +54,6 @@ std = [ "serde/std", "subtle-encoding/std", "ibc-eureka-core-client-types/std", - "ibc-eureka-core-connection-types/std", "ibc-eureka-core-host-types/std", "ibc-eureka-core-commitment-types/std", "ibc-primitives/std", @@ -65,7 +63,6 @@ std = [ serde = [ "dep:serde", "ibc-eureka-core-client-types/serde", - "ibc-eureka-core-connection-types/serde", "ibc-eureka-core-host-types/serde", "ibc-eureka-core-commitment-types/serde", "ibc-primitives/serde", @@ -74,7 +71,6 @@ serde = [ schema = [ "dep:schemars", "ibc-eureka-core-client-types/schema", - "ibc-eureka-core-connection-types/schema", "ibc-eureka-core-host-types/schema", "ibc-eureka-core-commitment-types/schema", "ibc-primitives/schema", @@ -85,7 +81,6 @@ schema = [ borsh = [ "dep:borsh", "ibc-eureka-core-client-types/borsh", - "ibc-eureka-core-connection-types/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host-types/borsh", "ibc-primitives/borsh", @@ -95,7 +90,6 @@ parity-scale-codec = [ "dep:parity-scale-codec", "dep:scale-info", "ibc-eureka-core-client-types/parity-scale-codec", - "ibc-eureka-core-connection-types/parity-scale-codec", "ibc-eureka-core-commitment-types/parity-scale-codec", "ibc-eureka-core-host-types/parity-scale-codec", "ibc-primitives/parity-scale-codec", diff --git a/ibc-eureka-core/ics04-channel/types/src/channel.rs b/ibc-eureka-core/ics04-channel/types/src/channel.rs deleted file mode 100644 index 5aa0208b2..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/channel.rs +++ /dev/null @@ -1,578 +0,0 @@ -//! Implementation of IBC channels, as described in ICS-04. - -use core::fmt::{Display, Error as FmtError, Formatter}; -use core::str::FromStr; - -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, ConnectionId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::utils::PrettySlice; -use ibc_proto::ibc::core::channel::v1::{ - Channel as RawChannel, Counterparty as RawCounterparty, - IdentifiedChannel as RawIdentifiedChannel, -}; -use ibc_proto::Protobuf; - -use crate::error::ChannelError; -use crate::Version; - -/// A [`ChannelEnd`] along with its ID and the port it is bound to -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq)] -pub struct IdentifiedChannelEnd { - pub port_id: PortId, - pub channel_id: ChannelId, - pub channel_end: ChannelEnd, -} - -impl IdentifiedChannelEnd { - pub fn new(port_id: PortId, channel_id: ChannelId, channel_end: ChannelEnd) -> Self { - IdentifiedChannelEnd { - port_id, - channel_id, - channel_end, - } - } -} - -impl Protobuf for IdentifiedChannelEnd {} - -impl TryFrom for IdentifiedChannelEnd { - type Error = DecodingError; - - fn try_from(value: RawIdentifiedChannel) -> Result { - if value.upgrade_sequence != 0 { - return Err(DecodingError::invalid_raw_data( - "channel upgrade sequence expected to be 0", - )); - } - - let raw_channel_end = RawChannel { - state: value.state, - ordering: value.ordering, - counterparty: value.counterparty, - connection_hops: value.connection_hops, - version: value.version, - upgrade_sequence: value.upgrade_sequence, - }; - - Ok(IdentifiedChannelEnd { - port_id: value.port_id.parse()?, - channel_id: value.channel_id.parse()?, - channel_end: raw_channel_end.try_into()?, - }) - } -} - -impl From for RawIdentifiedChannel { - fn from(value: IdentifiedChannelEnd) -> Self { - RawIdentifiedChannel { - state: value.channel_end.state as i32, - ordering: value.channel_end.ordering as i32, - counterparty: Some(value.channel_end.counterparty().clone().into()), - connection_hops: value - .channel_end - .connection_hops - .iter() - .map(|v| v.as_str().to_string()) - .collect(), - version: value.channel_end.version.to_string(), - port_id: value.port_id.to_string(), - channel_id: value.channel_id.to_string(), - upgrade_sequence: 0, - } - } -} - -/// One end of a channel -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq)] -pub struct ChannelEnd { - pub state: State, - pub ordering: Order, - pub remote: Counterparty, - pub connection_hops: Vec, - pub version: Version, -} - -impl Display for ChannelEnd { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { - write!( - f, - "ChannelEnd {{ state: {}, ordering: {}, remote: {}, connection_hops: {}, version: {} }}", - self.state, self.ordering, self.remote, PrettySlice(&self.connection_hops), self.version - ) - } -} - -impl Protobuf for ChannelEnd {} - -impl TryFrom for ChannelEnd { - type Error = DecodingError; - - fn try_from(value: RawChannel) -> Result { - let chan_state: State = State::from_i32(value.state) - .map_err(|e| DecodingError::invalid_raw_data(format!("channel state: {e}")))?; - - let chan_ordering = Order::from_i32(value.ordering) - .map_err(|e| DecodingError::invalid_raw_data(format!("channel ordering: {e}")))?; - // Assemble the 'remote' attribute of the Channel, which represents the Counterparty. - let remote = value - .counterparty - .ok_or(DecodingError::missing_raw_data("channel counterparty"))? - .try_into()?; - - // Parse each item in connection_hops into a ConnectionId. - let connection_hops = value - .connection_hops - .into_iter() - .map(|conn_id| ConnectionId::from_str(conn_id.as_str())) - .collect::, _>>()?; - - let version = value.version.into(); - - let channel = ChannelEnd::new(chan_state, chan_ordering, remote, connection_hops, version) - .map_err(|e| DecodingError::invalid_raw_data(format!("channel end: {e}")))?; - - Ok(channel) - } -} - -impl From for RawChannel { - fn from(value: ChannelEnd) -> Self { - RawChannel { - state: value.state as i32, - ordering: value.ordering as i32, - counterparty: Some(value.counterparty().clone().into()), - connection_hops: value - .connection_hops - .iter() - .map(|v| v.as_str().to_string()) - .collect(), - version: value.version.to_string(), - upgrade_sequence: 0, - } - } -} - -impl ChannelEnd { - /// Creates a new `ChannelEnd` without performing basic validation on its arguments. - /// - /// NOTE: This method is meant for the proto message conversion from the domain - /// `MsgChannelOpenInit` and `MsgChannelOpenTry` types to satisfy their `Protobuf` - /// trait bounds. - pub(super) fn new_without_validation( - state: State, - ordering: Order, - remote: Counterparty, - connection_hops: Vec, - version: Version, - ) -> Self { - Self { - state, - ordering, - remote, - connection_hops, - version, - } - } - - /// Creates a new `ChannelEnd` with performing basic validation on its arguments. - pub fn new( - state: State, - ordering: Order, - remote: Counterparty, - connection_hops: Vec, - version: Version, - ) -> Result { - let channel_end = - Self::new_without_validation(state, ordering, remote, connection_hops, version); - channel_end.validate_basic()?; - Ok(channel_end) - } - - /// Updates the ChannelEnd to assume a new State 's'. - pub fn set_state(&mut self, s: State) { - self.state = s; - } - - pub fn set_version(&mut self, v: Version) { - self.version = v; - } - - pub fn set_counterparty_channel_id(&mut self, c: ChannelId) { - self.remote.channel_id = Some(c); - } - - /// Returns `true` if this `ChannelEnd` is in state [`State::Open`]. - pub fn is_open(&self) -> bool { - self.state == State::Open - } - - pub fn state(&self) -> &State { - &self.state - } - - pub fn ordering(&self) -> &Order { - &self.ordering - } - - pub fn counterparty(&self) -> &Counterparty { - &self.remote - } - - pub fn connection_hops(&self) -> &Vec { - &self.connection_hops - } - - pub fn version(&self) -> &Version { - &self.version - } - - pub fn validate_basic(&self) -> Result<(), ChannelError> { - if self.state == State::Uninitialized { - return Err(ChannelError::InvalidState { - expected: "Channel state to not be Uninitialized".to_string(), - actual: self.state.to_string(), - }); - } - - if self.ordering == Order::None { - return Err(ChannelError::InvalidState { - expected: "Channel ordering to not be None".to_string(), - actual: self.ordering.to_string(), - }); - } - - Ok(()) - } - - /// Checks if the state of this channel end matches the expected state. - pub fn verify_state_matches(&self, expected: &State) -> Result<(), ChannelError> { - if !self.state.eq(expected) { - return Err(ChannelError::InvalidState { - expected: expected.to_string(), - actual: self.state.to_string(), - }); - } - Ok(()) - } - - /// Checks if the state of this channel end is not closed. - pub fn verify_not_closed(&self) -> Result<(), ChannelError> { - if self.state.eq(&State::Closed) { - return Err(ChannelError::InvalidState { - expected: "Channel state to not be Closed".to_string(), - actual: self.state.to_string(), - }); - } - Ok(()) - } - - /// Helper function to compare the order of this end with another order. - #[deprecated( - since = "0.50.1", - note = "Use `Eq` or `match` directly on the `Order` enum instead" - )] - pub fn order_matches(&self, other: &Order) -> bool { - self.ordering.eq(other) - } - - pub fn connection_hops_matches(&self, other: &Vec) -> bool { - self.connection_hops.eq(other) - } - - /// Checks if the counterparty of this channel end matches with an expected counterparty. - pub fn verify_counterparty_matches(&self, expected: &Counterparty) -> Result<(), ChannelError> { - if !self.counterparty().eq(expected) { - return Err(ChannelError::MismatchedCounterparty { - expected: expected.clone(), - actual: self.counterparty().clone(), - }); - } - Ok(()) - } - - /// Checks if the `connection_hops` has a length of `expected`. - /// - /// Note: The current IBC version only supports one connection hop. - pub fn verify_connection_hops_length(&self) -> Result<(), ChannelError> { - verify_connection_hops_length(&self.connection_hops, 1) - } - - pub fn version_matches(&self, other: &Version) -> bool { - self.version().eq(other) - } -} - -/// Checks if the `connection_hops` has a length of `expected`. -pub(crate) fn verify_connection_hops_length( - connection_hops: &[ConnectionId], - expected: u64, -) -> Result<(), ChannelError> { - if connection_hops.len() as u64 != expected { - return Err(ChannelError::InvalidConnectionHopsLength { - expected, - actual: connection_hops.len() as u64, - }); - } - Ok(()) -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq)] -pub struct Counterparty { - pub port_id: PortId, - pub channel_id: Option, -} - -impl Counterparty { - pub fn new(port_id: PortId, channel_id: Option) -> Self { - Self { - port_id, - channel_id, - } - } - - pub fn port_id(&self) -> &PortId { - &self.port_id - } - - pub fn channel_id(&self) -> Option<&ChannelId> { - self.channel_id.as_ref() - } -} - -impl Display for Counterparty { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { - match &self.channel_id { - Some(channel_id) => write!( - f, - "Counterparty(port_id: {}, channel_id: {})", - self.port_id, channel_id - ), - None => write!( - f, - "Counterparty(port_id: {}, channel_id: None)", - self.port_id - ), - } - } -} - -impl Protobuf for Counterparty {} - -impl TryFrom for Counterparty { - type Error = DecodingError; - - fn try_from(raw_counterparty: RawCounterparty) -> Result { - let channel_id: Option = if raw_counterparty.channel_id.is_empty() { - None - } else { - Some(raw_counterparty.channel_id.parse()?) - }; - - Ok(Counterparty::new( - raw_counterparty.port_id.parse()?, - channel_id, - )) - } -} - -impl From for RawCounterparty { - fn from(value: Counterparty) -> Self { - RawCounterparty { - port_id: value.port_id.as_str().to_string(), - channel_id: value - .channel_id - .map_or_else(|| "".to_string(), |v| v.to_string()), - } - } -} - -/// Represents the channel ordering -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize), - borsh(use_discriminant = false) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Order { - None = 0isize, - Unordered = 1isize, - Ordered = 2isize, -} - -impl Display for Order { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { - write!(f, "{}", self.as_str()) - } -} - -impl Order { - /// Yields the Order as a string - pub fn as_str(&self) -> &'static str { - match self { - // Note: taken from [ibc-go](https://github.com/cosmos/ibc-go/blob/e3a32a61098d463cd00b8937e18cb671bd20c6b7/modules/core/04-channel/types/channel.pb.go#L95-L97) - Self::None => "ORDER_NONE_UNSPECIFIED", - Self::Unordered => "ORDER_UNORDERED", - Self::Ordered => "ORDER_ORDERED", - } - } - - // Parses the Order out from a i32. - pub fn from_i32(nr: i32) -> Result { - match nr { - 0 => Ok(Self::None), - 1 => Ok(Self::Unordered), - 2 => Ok(Self::Ordered), - _ => Err(ChannelError::InvalidState { - expected: "to be one of 0, 1, 2".to_string(), - actual: nr.to_string(), - }), - } - } -} - -impl FromStr for Order { - type Err = ChannelError; - - fn from_str(s: &str) -> Result { - match s.to_lowercase().trim_start_matches("order_") { - "uninitialized" => Ok(Self::None), - "unordered" => Ok(Self::Unordered), - "ordered" => Ok(Self::Ordered), - _ => Err(ChannelError::InvalidState { - expected: "to be one of 'uninitialized', 'unordered', 'ordered'".to_string(), - actual: s.to_string(), - }), - } - } -} - -/// Represents the state of a [`ChannelEnd`] -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize), - borsh(use_discriminant = false) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum State { - Uninitialized = 0isize, - Init = 1isize, - TryOpen = 2isize, - Open = 3isize, - Closed = 4isize, -} - -impl State { - /// Yields the state as a string - pub fn as_string(&self) -> &'static str { - match self { - Self::Uninitialized => "UNINITIALIZED", - Self::Init => "INIT", - Self::TryOpen => "TRYOPEN", - Self::Open => "OPEN", - Self::Closed => "CLOSED", - } - } - - // Parses the State out from a i32. - pub fn from_i32(s: i32) -> Result { - match s { - 0 => Ok(Self::Uninitialized), - 1 => Ok(Self::Init), - 2 => Ok(Self::TryOpen), - 3 => Ok(Self::Open), - 4 => Ok(Self::Closed), - _ => Err(ChannelError::InvalidState { - expected: "to be one of: 0, 1, 2, 3, 4".to_string(), - actual: s.to_string(), - }), - } - } - - /// Returns if this channel state is `Open`. - pub fn is_open(self) -> bool { - self == State::Open - } - - /// Returns if the channel with this state - /// has progressed less than or the same as the argument. - /// - /// # Example - /// ```rust,ignore - /// assert!(State::Init.less_or_equal_progress(State::Open)); - /// assert!(State::TryOpen.less_or_equal_progress(State::TryOpen)); - /// assert!(!State::Closed.less_or_equal_progress(State::Open)); - /// ``` - pub fn less_or_equal_progress(self, other: Self) -> bool { - self as u32 <= other as u32 - } -} - -/// Provides a `to_string` method. -impl Display for State { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { - write!(f, "{}", self.as_string()) - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/error.rs b/ibc-eureka-core/ics04-channel/types/src/error.rs index 7792494a2..bcaad7b9a 100644 --- a/ibc-eureka-core/ics04-channel/types/src/error.rs +++ b/ibc-eureka-core/ics04-channel/types/src/error.rs @@ -3,13 +3,11 @@ use displaydoc::Display; use ibc_eureka_core_client_types::error::ClientError; use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_connection_types::error::ConnectionError; use ibc_eureka_core_host_types::error::{DecodingError, HostError, IdentifierError}; use ibc_eureka_core_host_types::identifiers::Sequence; use ibc_primitives::prelude::*; use ibc_primitives::{Timestamp, TimestampError}; -use super::channel::Counterparty; use super::timeout::TimeoutHeight; use crate::commitment::PacketCommitment; use crate::timeout::TimeoutTimestamp; @@ -24,8 +22,6 @@ pub enum ChannelError { Host(HostError), /// client error: {0} Client(ClientError), - /// connection error: {0} - Connection(ConnectionError), /// timestamp error: {0} Timestamp(TimestampError), /// packet acknowledgment for sequence `{0}` already exists @@ -54,11 +50,6 @@ pub enum ChannelError { MissingCounterparty, /// missing timeout MissingTimeout, - /// mismatched counterparty: expected `{expected}`, actual `{actual}` - MismatchedCounterparty { - expected: Counterparty, - actual: Counterparty, - }, /// mismatched packet sequence: expected `{expected}`, actual `{actual}` MismatchedPacketSequence { expected: Sequence, @@ -87,7 +78,6 @@ impl std::error::Error for ChannelError { match &self { Self::Decoding(e) => Some(e), Self::Client(e) => Some(e), - Self::Connection(e) => Some(e), Self::Host(e) => Some(e), Self::Timestamp(e) => Some(e), _ => None, diff --git a/ibc-eureka-core/ics04-channel/types/src/events/channel_attributes.rs b/ibc-eureka-core/ics04-channel/types/src/events/channel_attributes.rs index b8b993be8..cc6cfa5e2 100644 --- a/ibc-eureka-core/ics04-channel/types/src/events/channel_attributes.rs +++ b/ibc-eureka-core/ics04-channel/types/src/events/channel_attributes.rs @@ -1,12 +1,12 @@ //! This module holds all the abci event attributes for IBC events emitted //! during the channel handshake. use derive_more::From; -use ibc_eureka_core_host_types::identifiers::{ChannelId, ConnectionId, PortId}; +use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId}; use tendermint::abci; use crate::Version; -const CONNECTION_ID_ATTRIBUTE_KEY: &str = "connection_id"; +// const CONNECTION_ID_ATTRIBUTE_KEY: &str = "connection_id"; const CHANNEL_ID_ATTRIBUTE_KEY: &str = "channel_id"; const PORT_ID_ATTRIBUTE_KEY: &str = "port_id"; /// This attribute key is public so that OpenInit can use it to convert itself @@ -123,30 +123,6 @@ impl AsRef for CounterpartyChannelIdAttribute { } } -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, From, PartialEq, Eq)] -pub struct ConnectionIdAttribute { - pub connection_id: ConnectionId, -} - -impl From for abci::EventAttribute { - fn from(attr: ConnectionIdAttribute) -> Self { - (CONNECTION_ID_ATTRIBUTE_KEY, attr.connection_id.as_str()).into() - } -} - #[cfg_attr( feature = "parity-scale-codec", derive( diff --git a/ibc-eureka-core/ics04-channel/types/src/events/mod.rs b/ibc-eureka-core/ics04-channel/types/src/events/mod.rs index 252a76f73..f8ccd293a 100644 --- a/ibc-eureka-core/ics04-channel/types/src/events/mod.rs +++ b/ibc-eureka-core/ics04-channel/types/src/events/mod.rs @@ -4,22 +4,20 @@ mod channel_attributes; mod packet_attributes; use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, ConnectionId, PortId, Sequence}; +use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId, Sequence}; use ibc_primitives::prelude::*; use tendermint::abci; use self::channel_attributes::{ - ChannelIdAttribute, ConnectionIdAttribute, CounterpartyChannelIdAttribute, - CounterpartyPortIdAttribute, PortIdAttribute, VersionAttribute, - COUNTERPARTY_CHANNEL_ID_ATTRIBUTE_KEY, + ChannelIdAttribute, CounterpartyChannelIdAttribute, CounterpartyPortIdAttribute, + PortIdAttribute, VersionAttribute, COUNTERPARTY_CHANNEL_ID_ATTRIBUTE_KEY, }; use self::packet_attributes::{ - AcknowledgementAttribute, ChannelOrderingAttribute, DstChannelIdAttribute, DstPortIdAttribute, - PacketConnectionIdAttribute, PacketDataAttribute, SequenceAttribute, SrcChannelIdAttribute, - SrcPortIdAttribute, TimeoutHeightAttribute, TimeoutTimestampAttribute, + AcknowledgementAttribute, DstChannelIdAttribute, DstPortIdAttribute, PacketDataAttribute, + SequenceAttribute, SrcChannelIdAttribute, SrcPortIdAttribute, TimeoutHeightAttribute, + TimeoutTimestampAttribute, }; use super::acknowledgement::Acknowledgement; -use super::channel::Order; use super::timeout::TimeoutHeight; use super::Version; use crate::packet::Packet; @@ -60,7 +58,6 @@ pub struct OpenInit { port_id_attr_on_a: PortIdAttribute, chan_id_attr_on_a: ChannelIdAttribute, port_id_attr_on_b: CounterpartyPortIdAttribute, - conn_id_attr_on_a: ConnectionIdAttribute, version_attr_on_a: VersionAttribute, } @@ -69,14 +66,12 @@ impl OpenInit { port_id_on_a: PortId, chan_id_on_a: ChannelId, port_id_on_b: PortId, - conn_id_on_a: ConnectionId, version_on_a: Version, ) -> Self { Self { port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), port_id_attr_on_b: port_id_on_b.into(), - conn_id_attr_on_a: conn_id_on_a.into(), version_attr_on_a: version_on_a.into(), } } @@ -89,9 +84,6 @@ impl OpenInit { pub fn port_id_on_b(&self) -> &PortId { &self.port_id_attr_on_b.counterparty_port_id } - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.conn_id_attr_on_a.connection_id - } pub fn version_on_a(&self) -> &Version { &self.version_attr_on_a.version } @@ -110,7 +102,6 @@ impl From for abci::Event { o.chan_id_attr_on_a.into(), o.port_id_attr_on_b.into(), (COUNTERPARTY_CHANNEL_ID_ATTRIBUTE_KEY, "").into(), - o.conn_id_attr_on_a.into(), o.version_attr_on_a.into(), ], } @@ -136,7 +127,6 @@ pub struct OpenTry { chan_id_attr_on_b: ChannelIdAttribute, port_id_attr_on_a: CounterpartyPortIdAttribute, chan_id_attr_on_a: CounterpartyChannelIdAttribute, - conn_id_attr_on_b: ConnectionIdAttribute, version_attr_on_b: VersionAttribute, } @@ -146,7 +136,6 @@ impl OpenTry { chan_id_on_b: ChannelId, port_id_on_a: PortId, chan_id_on_a: ChannelId, - conn_id_on_b: ConnectionId, version_on_b: Version, ) -> Self { Self { @@ -154,7 +143,6 @@ impl OpenTry { chan_id_attr_on_b: chan_id_on_b.into(), port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), - conn_id_attr_on_b: conn_id_on_b.into(), version_attr_on_b: version_on_b.into(), } } @@ -170,9 +158,6 @@ impl OpenTry { pub fn chan_id_on_a(&self) -> &ChannelId { &self.chan_id_attr_on_a.counterparty_channel_id } - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.conn_id_attr_on_b.connection_id - } pub fn version_on_b(&self) -> &Version { &self.version_attr_on_b.version } @@ -191,7 +176,6 @@ impl From for abci::Event { o.chan_id_attr_on_b.into(), o.port_id_attr_on_a.into(), o.chan_id_attr_on_a.into(), - o.conn_id_attr_on_b.into(), o.version_attr_on_b.into(), ], } @@ -217,7 +201,6 @@ pub struct OpenAck { chan_id_attr_on_a: ChannelIdAttribute, port_id_attr_on_b: CounterpartyPortIdAttribute, chan_id_attr_on_b: CounterpartyChannelIdAttribute, - conn_id_attr_on_a: ConnectionIdAttribute, } impl OpenAck { @@ -226,14 +209,12 @@ impl OpenAck { chan_id_on_a: ChannelId, port_id_on_b: PortId, chan_id_on_b: ChannelId, - conn_id_on_a: ConnectionId, ) -> Self { Self { port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), port_id_attr_on_b: port_id_on_b.into(), chan_id_attr_on_b: chan_id_on_b.into(), - conn_id_attr_on_a: conn_id_on_a.into(), } } pub fn port_id_on_a(&self) -> &PortId { @@ -248,9 +229,6 @@ impl OpenAck { pub fn chan_id_on_b(&self) -> &ChannelId { &self.chan_id_attr_on_b.counterparty_channel_id } - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.conn_id_attr_on_a.connection_id - } pub fn event_type(&self) -> &str { CHANNEL_OPEN_ACK_EVENT @@ -266,7 +244,6 @@ impl From for abci::Event { o.chan_id_attr_on_a.into(), o.port_id_attr_on_b.into(), o.chan_id_attr_on_b.into(), - o.conn_id_attr_on_a.into(), ], } } @@ -291,7 +268,6 @@ pub struct OpenConfirm { chan_id_attr_on_b: ChannelIdAttribute, port_id_attr_on_a: CounterpartyPortIdAttribute, chan_id_attr_on_a: CounterpartyChannelIdAttribute, - conn_id_attr_on_b: ConnectionIdAttribute, } impl OpenConfirm { @@ -300,14 +276,12 @@ impl OpenConfirm { chan_id_on_b: ChannelId, port_id_on_a: PortId, chan_id_on_a: ChannelId, - conn_id_on_b: ConnectionId, ) -> Self { Self { port_id_attr_on_b: port_id_on_b.into(), chan_id_attr_on_b: chan_id_on_b.into(), port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), - conn_id_attr_on_b: conn_id_on_b.into(), } } pub fn port_id_on_b(&self) -> &PortId { @@ -322,9 +296,6 @@ impl OpenConfirm { pub fn chan_id_on_a(&self) -> &ChannelId { &self.chan_id_attr_on_a.counterparty_channel_id } - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.conn_id_attr_on_b.connection_id - } pub fn event_type(&self) -> &str { CHANNEL_OPEN_CONFIRM_EVENT @@ -340,7 +311,6 @@ impl From for abci::Event { o.chan_id_attr_on_b.into(), o.port_id_attr_on_a.into(), o.chan_id_attr_on_a.into(), - o.conn_id_attr_on_b.into(), ], } } @@ -365,7 +335,6 @@ pub struct CloseInit { chan_id_attr_on_a: ChannelIdAttribute, port_id_attr_on_b: CounterpartyPortIdAttribute, chan_id_attr_on_b: CounterpartyChannelIdAttribute, - conn_id_attr_on_a: ConnectionIdAttribute, } impl CloseInit { @@ -374,14 +343,12 @@ impl CloseInit { chan_id_on_a: ChannelId, port_id_on_b: PortId, chan_id_on_b: ChannelId, - conn_id_on_a: ConnectionId, ) -> Self { Self { port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), port_id_attr_on_b: port_id_on_b.into(), chan_id_attr_on_b: chan_id_on_b.into(), - conn_id_attr_on_a: conn_id_on_a.into(), } } pub fn port_id_on_a(&self) -> &PortId { @@ -396,10 +363,6 @@ impl CloseInit { pub fn chan_id_on_b(&self) -> &ChannelId { &self.chan_id_attr_on_b.counterparty_channel_id } - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.conn_id_attr_on_a.connection_id - } - pub fn event_type(&self) -> &str { CHANNEL_CLOSE_INIT_EVENT } @@ -414,7 +377,6 @@ impl From for abci::Event { o.chan_id_attr_on_a.into(), o.port_id_attr_on_b.into(), o.chan_id_attr_on_b.into(), - o.conn_id_attr_on_a.into(), ], } } @@ -439,7 +401,6 @@ pub struct CloseConfirm { chan_id_attr_on_b: ChannelIdAttribute, port_id_attr_on_a: CounterpartyPortIdAttribute, chan_id_attr_on_a: CounterpartyChannelIdAttribute, - conn_id_attr_on_b: ConnectionIdAttribute, } impl CloseConfirm { @@ -448,14 +409,12 @@ impl CloseConfirm { chan_id_on_b: ChannelId, port_id_on_a: PortId, chan_id_on_a: ChannelId, - conn_id_on_b: ConnectionId, ) -> Self { Self { port_id_attr_on_b: port_id_on_b.into(), chan_id_attr_on_b: chan_id_on_b.into(), port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), - conn_id_attr_on_b: conn_id_on_b.into(), } } pub fn port_id_on_b(&self) -> &PortId { @@ -470,10 +429,6 @@ impl CloseConfirm { pub fn chan_id_on_a(&self) -> &ChannelId { &self.chan_id_attr_on_a.counterparty_channel_id } - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.conn_id_attr_on_b.connection_id - } - pub fn event_type(&self) -> &str { CHANNEL_CLOSE_CONFIRM_EVENT } @@ -488,7 +443,6 @@ impl From for abci::Event { o.chan_id_attr_on_b.into(), o.port_id_attr_on_a.into(), o.chan_id_attr_on_a.into(), - o.conn_id_attr_on_b.into(), ], } } @@ -517,8 +471,6 @@ pub struct ChannelClosed { chan_id_attr_on_a: ChannelIdAttribute, port_id_attr_on_b: CounterpartyPortIdAttribute, maybe_chan_id_attr_on_b: Option, - conn_id_attr_on_a: ConnectionIdAttribute, - channel_ordering_attr: ChannelOrderingAttribute, } impl ChannelClosed { @@ -527,16 +479,12 @@ impl ChannelClosed { chan_id_on_a: ChannelId, port_id_on_b: PortId, maybe_chan_id_on_b: Option, - conn_id_on_a: ConnectionId, - channel_ordering: Order, ) -> Self { Self { port_id_attr_on_a: port_id_on_a.into(), chan_id_attr_on_a: chan_id_on_a.into(), port_id_attr_on_b: port_id_on_b.into(), maybe_chan_id_attr_on_b: maybe_chan_id_on_b.map(Into::into), - conn_id_attr_on_a: conn_id_on_a.into(), - channel_ordering_attr: channel_ordering.into(), } } pub fn port_id_on_b(&self) -> &PortId { @@ -551,13 +499,6 @@ impl ChannelClosed { pub fn chan_id_on_a(&self) -> Option<&ChannelId> { self.maybe_chan_id_attr_on_b.as_ref().map(AsRef::as_ref) } - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.conn_id_attr_on_a.connection_id - } - pub fn channel_ordering(&self) -> &Order { - &self.channel_ordering_attr.order - } - pub fn event_type(&self) -> &str { CHANNEL_CLOSED_EVENT } @@ -575,8 +516,6 @@ impl From for abci::Event { || (COUNTERPARTY_CHANNEL_ID_ATTRIBUTE_KEY, "").into(), Into::into, ), - ev.conn_id_attr_on_a.into(), - ev.channel_ordering_attr.into(), ], } } @@ -605,12 +544,10 @@ pub struct SendPacket { chan_id_attr_on_a: SrcChannelIdAttribute, port_id_attr_on_b: DstPortIdAttribute, chan_id_attr_on_b: DstChannelIdAttribute, - channel_ordering_attr: ChannelOrderingAttribute, - conn_id_attr_on_a: PacketConnectionIdAttribute, } impl SendPacket { - pub fn new(packet: Packet, channel_ordering: Order, src_connection_id: ConnectionId) -> Self { + pub fn new(packet: Packet) -> Self { let payload = packet.payloads[0].clone(); Self { packet_data_attr: payload.data.into(), @@ -618,11 +555,9 @@ impl SendPacket { timeout_timestamp_attr_on_b: packet.header.timeout_timestamp_on_b.into(), seq_attr_on_a: packet.header.seq_on_a.into(), port_id_attr_on_a: payload.header.source_port.1.into(), - chan_id_attr_on_a: packet.header.source_client.into(), + chan_id_attr_on_a: packet.header.target_client_on_source.into(), port_id_attr_on_b: payload.header.target_port.1.into(), - chan_id_attr_on_b: packet.header.target_client.into(), - channel_ordering_attr: channel_ordering.into(), - conn_id_attr_on_a: src_connection_id.into(), + chan_id_attr_on_b: packet.header.source_client_on_target.into(), } } @@ -658,14 +593,6 @@ impl SendPacket { &self.chan_id_attr_on_b.dst_channel_id } - pub fn channel_ordering(&self) -> &Order { - &self.channel_ordering_attr.order - } - - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.conn_id_attr_on_a.connection_id - } - pub fn event_type(&self) -> &str { SEND_PACKET_EVENT } @@ -684,8 +611,6 @@ impl TryFrom for abci::Event { attributes.push(v.chan_id_attr_on_a.into()); attributes.push(v.port_id_attr_on_b.into()); attributes.push(v.chan_id_attr_on_b.into()); - attributes.push(v.channel_ordering_attr.into()); - attributes.push(v.conn_id_attr_on_a.into()); Ok(abci::Event { kind: SEND_PACKET_EVENT.to_string(), @@ -717,12 +642,10 @@ pub struct ReceivePacket { chan_id_attr_on_a: SrcChannelIdAttribute, port_id_attr_on_b: DstPortIdAttribute, chan_id_attr_on_b: DstChannelIdAttribute, - channel_ordering_attr: ChannelOrderingAttribute, - conn_id_attr_on_b: PacketConnectionIdAttribute, } impl ReceivePacket { - pub fn new(packet: Packet, channel_ordering: Order, dst_connection_id: ConnectionId) -> Self { + pub fn new(packet: Packet) -> Self { let payload = packet.payloads[0].clone(); Self { packet_data_attr: payload.data.into(), @@ -730,11 +653,9 @@ impl ReceivePacket { timeout_timestamp_attr_on_b: packet.header.timeout_timestamp_on_b.into(), seq_attr_on_a: packet.header.seq_on_a.into(), port_id_attr_on_a: payload.header.source_port.1.into(), - chan_id_attr_on_a: packet.header.source_client.into(), + chan_id_attr_on_a: packet.header.target_client_on_source.into(), port_id_attr_on_b: payload.header.target_port.1.into(), - chan_id_attr_on_b: packet.header.target_client.into(), - channel_ordering_attr: channel_ordering.into(), - conn_id_attr_on_b: dst_connection_id.into(), + chan_id_attr_on_b: packet.header.source_client_on_target.into(), } } @@ -770,14 +691,6 @@ impl ReceivePacket { &self.chan_id_attr_on_b.dst_channel_id } - pub fn channel_ordering(&self) -> &Order { - &self.channel_ordering_attr.order - } - - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.conn_id_attr_on_b.connection_id - } - pub fn event_type(&self) -> &str { RECEIVE_PACKET_EVENT } @@ -796,8 +709,6 @@ impl TryFrom for abci::Event { attributes.push(v.chan_id_attr_on_a.into()); attributes.push(v.port_id_attr_on_b.into()); attributes.push(v.chan_id_attr_on_b.into()); - attributes.push(v.channel_ordering_attr.into()); - attributes.push(v.conn_id_attr_on_b.into()); Ok(abci::Event { kind: RECEIVE_PACKET_EVENT.to_string(), @@ -830,15 +741,10 @@ pub struct WriteAcknowledgement { port_id_attr_on_b: DstPortIdAttribute, chan_id_attr_on_b: DstChannelIdAttribute, acknowledgement: AcknowledgementAttribute, - conn_id_attr_on_b: PacketConnectionIdAttribute, } impl WriteAcknowledgement { - pub fn new( - packet: Packet, - acknowledgement: Acknowledgement, - conn_id_on_b: ConnectionId, - ) -> Self { + pub fn new(packet: Packet, acknowledgement: Acknowledgement) -> Self { let payload = packet.payloads[0].clone(); Self { packet_data: payload.data.into(), @@ -846,11 +752,10 @@ impl WriteAcknowledgement { timeout_timestamp_attr_on_b: packet.header.timeout_timestamp_on_b.into(), seq_attr_on_a: packet.header.seq_on_a.into(), port_id_attr_on_a: payload.header.source_port.1.into(), - chan_id_attr_on_a: packet.header.source_client.into(), + chan_id_attr_on_a: packet.header.target_client_on_source.into(), port_id_attr_on_b: payload.header.target_port.1.into(), - chan_id_attr_on_b: packet.header.target_client.into(), + chan_id_attr_on_b: packet.header.source_client_on_target.into(), acknowledgement: acknowledgement.into(), - conn_id_attr_on_b: conn_id_on_b.into(), } } @@ -890,10 +795,6 @@ impl WriteAcknowledgement { &self.acknowledgement.acknowledgement } - pub fn conn_id_on_b(&self) -> &ConnectionId { - &self.conn_id_attr_on_b.connection_id - } - pub fn event_type(&self) -> &str { WRITE_ACK_EVENT } @@ -913,7 +814,6 @@ impl TryFrom for abci::Event { attributes.push(v.port_id_attr_on_b.into()); attributes.push(v.chan_id_attr_on_b.into()); attributes.append(&mut v.acknowledgement.try_into()?); - attributes.push(v.conn_id_attr_on_b.into()); Ok(abci::Event { kind: WRITE_ACK_EVENT.to_string(), @@ -944,23 +844,19 @@ pub struct AcknowledgePacket { chan_id_attr_on_a: SrcChannelIdAttribute, port_id_attr_on_b: DstPortIdAttribute, chan_id_attr_on_b: DstChannelIdAttribute, - channel_ordering_attr: ChannelOrderingAttribute, - conn_id_attr_on_a: PacketConnectionIdAttribute, } impl AcknowledgePacket { - pub fn new(packet: Packet, channel_ordering: Order, src_connection_id: ConnectionId) -> Self { + pub fn new(packet: Packet) -> Self { let payload = packet.payloads[0].clone(); Self { timeout_height_attr_on_b: packet.header.timeout_height_on_b.into(), timeout_timestamp_attr_on_b: packet.header.timeout_timestamp_on_b.into(), seq_on_a: packet.header.seq_on_a.into(), port_id_attr_on_a: payload.header.source_port.1.into(), - chan_id_attr_on_a: packet.header.source_client.into(), + chan_id_attr_on_a: packet.header.target_client_on_source.into(), port_id_attr_on_b: payload.header.target_port.1.into(), - chan_id_attr_on_b: packet.header.target_client.into(), - channel_ordering_attr: channel_ordering.into(), - conn_id_attr_on_a: src_connection_id.into(), + chan_id_attr_on_b: packet.header.source_client_on_target.into(), } } @@ -992,14 +888,6 @@ impl AcknowledgePacket { &self.chan_id_attr_on_b.dst_channel_id } - pub fn channel_ordering(&self) -> &Order { - &self.channel_ordering_attr.order - } - - pub fn conn_id_on_a(&self) -> &ConnectionId { - &self.conn_id_attr_on_a.connection_id - } - pub fn event_type(&self) -> &str { ACK_PACKET_EVENT } @@ -1019,8 +907,6 @@ impl TryFrom for abci::Event { v.chan_id_attr_on_a.into(), v.port_id_attr_on_b.into(), v.chan_id_attr_on_b.into(), - v.channel_ordering_attr.into(), - v.conn_id_attr_on_a.into(), ], }) } @@ -1048,21 +934,19 @@ pub struct TimeoutPacket { chan_id_attr_on_a: SrcChannelIdAttribute, port_id_attr_on_b: DstPortIdAttribute, chan_id_attr_on_b: DstChannelIdAttribute, - channel_ordering_attr: ChannelOrderingAttribute, } impl TimeoutPacket { - pub fn new(packet: Packet, channel_ordering: Order) -> Self { + pub fn new(packet: Packet) -> Self { let payload = packet.payloads[0].clone(); Self { timeout_height_attr_on_b: packet.header.timeout_height_on_b.into(), timeout_timestamp_attr_on_b: packet.header.timeout_timestamp_on_b.into(), seq_attr_on_a: packet.header.seq_on_a.into(), port_id_attr_on_a: payload.header.source_port.1.into(), - chan_id_attr_on_a: packet.header.source_client.into(), + chan_id_attr_on_a: packet.header.target_client_on_source.into(), port_id_attr_on_b: payload.header.target_port.1.into(), - chan_id_attr_on_b: packet.header.target_client.into(), - channel_ordering_attr: channel_ordering.into(), + chan_id_attr_on_b: packet.header.source_client_on_target.into(), } } @@ -1094,10 +978,6 @@ impl TimeoutPacket { &self.chan_id_attr_on_b.dst_channel_id } - pub fn channel_ordering(&self) -> &Order { - &self.channel_ordering_attr.order - } - pub fn event_type(&self) -> &str { TIMEOUT_EVENT } @@ -1117,7 +997,6 @@ impl TryFrom for abci::Event { v.chan_id_attr_on_a.into(), v.port_id_attr_on_b.into(), v.chan_id_attr_on_b.into(), - v.channel_ordering_attr.into(), ], }) } diff --git a/ibc-eureka-core/ics04-channel/types/src/events/packet_attributes.rs b/ibc-eureka-core/ics04-channel/types/src/events/packet_attributes.rs index f27941ccf..19fc8181c 100644 --- a/ibc-eureka-core/ics04-channel/types/src/events/packet_attributes.rs +++ b/ibc-eureka-core/ics04-channel/types/src/events/packet_attributes.rs @@ -5,13 +5,12 @@ use core::str; use derive_more::From; use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, ConnectionId, PortId, Sequence}; +use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId, Sequence}; use ibc_primitives::prelude::*; use subtle_encoding::hex; use tendermint::abci; use crate::acknowledgement::Acknowledgement; -use crate::channel::Order; use crate::timeout::{TimeoutHeight, TimeoutTimestamp}; const PKT_SEQ_ATTRIBUTE_KEY: &str = "packet_sequence"; @@ -21,12 +20,12 @@ const PKT_SRC_PORT_ATTRIBUTE_KEY: &str = "packet_src_port"; const PKT_SRC_CHANNEL_ATTRIBUTE_KEY: &str = "packet_src_channel"; const PKT_DST_PORT_ATTRIBUTE_KEY: &str = "packet_dst_port"; const PKT_DST_CHANNEL_ATTRIBUTE_KEY: &str = "packet_dst_channel"; -const PKT_CHANNEL_ORDERING_ATTRIBUTE_KEY: &str = "packet_channel_ordering"; +// const PKT_CHANNEL_ORDERING_ATTRIBUTE_KEY: &str = "packet_channel_ordering"; const PKT_TIMEOUT_HEIGHT_ATTRIBUTE_KEY: &str = "packet_timeout_height"; const PKT_TIMEOUT_TIMESTAMP_ATTRIBUTE_KEY: &str = "packet_timeout_timestamp"; const PKT_ACK_ATTRIBUTE_KEY: &str = "packet_ack"; const PKT_ACK_HEX_ATTRIBUTE_KEY: &str = "packet_ack_hex"; -const PKT_CONNECTION_ID_ATTRIBUTE_KEY: &str = "packet_connection"; +// const PKT_CONNECTION_ID_ATTRIBUTE_KEY: &str = "packet_connection"; #[cfg_attr( feature = "parity-scale-codec", @@ -241,54 +240,6 @@ impl From for abci::EventAttribute { } } -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, From, PartialEq, Eq)] -pub struct ChannelOrderingAttribute { - pub order: Order, -} - -impl From for abci::EventAttribute { - fn from(attr: ChannelOrderingAttribute) -> Self { - (PKT_CHANNEL_ORDERING_ATTRIBUTE_KEY, attr.order.as_str()).into() - } -} - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, From, PartialEq, Eq)] -pub struct PacketConnectionIdAttribute { - pub connection_id: ConnectionId, -} - -impl From for abci::EventAttribute { - fn from(attr: PacketConnectionIdAttribute) -> Self { - (PKT_CONNECTION_ID_ATTRIBUTE_KEY, attr.connection_id.as_str()).into() - } -} - #[cfg_attr( feature = "parity-scale-codec", derive( diff --git a/ibc-eureka-core/ics04-channel/types/src/lib.rs b/ibc-eureka-core/ics04-channel/types/src/lib.rs index 6e7a0b3c6..d732996c3 100644 --- a/ibc-eureka-core/ics04-channel/types/src/lib.rs +++ b/ibc-eureka-core/ics04-channel/types/src/lib.rs @@ -16,7 +16,7 @@ extern crate alloc; #[cfg(feature = "std")] extern crate std; -pub mod channel; +// pub mod channel; pub mod error; pub mod events; diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_close_confirm.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/chan_close_confirm.rs deleted file mode 100644 index 014aa4dab..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_close_confirm.rs +++ /dev/null @@ -1,69 +0,0 @@ -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelCloseConfirm as RawMsgChannelCloseConfirm; -use ibc_proto::Protobuf; - -pub const CHAN_CLOSE_CONFIRM_TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelCloseConfirm"; - -/// -/// Message definition for the second step in the channel close handshake (the `ChanCloseConfirm` -/// datagram). -/// Per our convention, this message is sent to chain B. -/// -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgChannelCloseConfirm { - pub port_id_on_b: PortId, - pub chan_id_on_b: ChannelId, - pub proof_chan_end_on_a: CommitmentProofBytes, - pub proof_height_on_a: Height, - pub signer: Signer, -} - -impl Protobuf for MsgChannelCloseConfirm {} - -impl TryFrom for MsgChannelCloseConfirm { - type Error = DecodingError; - - fn try_from(raw_msg: RawMsgChannelCloseConfirm) -> Result { - if raw_msg.counterparty_upgrade_sequence != 0 { - return Err(DecodingError::invalid_raw_data( - "counterparty upgrade sequence must be 0", - )); - } - - Ok(MsgChannelCloseConfirm { - port_id_on_b: raw_msg.port_id.parse()?, - chan_id_on_b: raw_msg.channel_id.parse()?, - proof_chan_end_on_a: raw_msg.proof_init.try_into()?, - proof_height_on_a: raw_msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::invalid_raw_data( - "msg channel close confirm proof height", - ))?, - signer: raw_msg.signer.into(), - }) - } -} - -impl From for RawMsgChannelCloseConfirm { - fn from(domain_msg: MsgChannelCloseConfirm) -> Self { - RawMsgChannelCloseConfirm { - port_id: domain_msg.port_id_on_b.to_string(), - channel_id: domain_msg.chan_id_on_b.to_string(), - proof_init: domain_msg.proof_chan_end_on_a.clone().into(), - proof_height: Some(domain_msg.proof_height_on_a.into()), - signer: domain_msg.signer.to_string(), - counterparty_upgrade_sequence: 0, - } - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_close_init.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/chan_close_init.rs deleted file mode 100644 index f7800e60e..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_close_init.rs +++ /dev/null @@ -1,48 +0,0 @@ -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelCloseInit as RawMsgChannelCloseInit; -use ibc_proto::Protobuf; - -pub const CHAN_CLOSE_INIT_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) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgChannelCloseInit { - pub port_id_on_a: PortId, - pub chan_id_on_a: ChannelId, - pub signer: Signer, -} - -impl Protobuf for MsgChannelCloseInit {} - -impl TryFrom for MsgChannelCloseInit { - type Error = DecodingError; - - fn try_from(raw_msg: RawMsgChannelCloseInit) -> Result { - Ok(MsgChannelCloseInit { - port_id_on_a: raw_msg.port_id.parse()?, - chan_id_on_a: raw_msg.channel_id.parse()?, - signer: raw_msg.signer.into(), - }) - } -} - -impl From for RawMsgChannelCloseInit { - fn from(domain_msg: MsgChannelCloseInit) -> Self { - RawMsgChannelCloseInit { - port_id: domain_msg.port_id_on_a.to_string(), - channel_id: domain_msg.chan_id_on_a.to_string(), - signer: domain_msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_ack.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_ack.rs deleted file mode 100644 index a6c1693a3..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_ack.rs +++ /dev/null @@ -1,66 +0,0 @@ -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenAck as RawMsgChannelOpenAck; -use ibc_proto::Protobuf; - -use crate::Version; - -pub const CHAN_OPEN_ACK_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) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgChannelOpenAck { - pub port_id_on_a: PortId, - pub chan_id_on_a: ChannelId, - pub chan_id_on_b: ChannelId, - pub version_on_b: Version, - pub proof_chan_end_on_b: CommitmentProofBytes, - pub proof_height_on_b: Height, - pub signer: Signer, -} - -impl Protobuf for MsgChannelOpenAck {} - -impl TryFrom for MsgChannelOpenAck { - type Error = DecodingError; - - fn try_from(raw_msg: RawMsgChannelOpenAck) -> Result { - Ok(MsgChannelOpenAck { - port_id_on_a: raw_msg.port_id.parse()?, - chan_id_on_a: raw_msg.channel_id.parse()?, - chan_id_on_b: raw_msg.counterparty_channel_id.parse()?, - version_on_b: raw_msg.counterparty_version.into(), - proof_chan_end_on_b: raw_msg.proof_try.try_into()?, - proof_height_on_b: raw_msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::missing_raw_data("proof height"))?, - signer: raw_msg.signer.into(), - }) - } -} - -impl From for RawMsgChannelOpenAck { - fn from(domain_msg: MsgChannelOpenAck) -> Self { - RawMsgChannelOpenAck { - port_id: domain_msg.port_id_on_a.to_string(), - channel_id: domain_msg.chan_id_on_a.to_string(), - counterparty_channel_id: domain_msg.chan_id_on_b.to_string(), - counterparty_version: domain_msg.version_on_b.to_string(), - proof_try: domain_msg.proof_chan_end_on_b.into(), - proof_height: Some(domain_msg.proof_height_on_b.into()), - signer: domain_msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_confirm.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_confirm.rs deleted file mode 100644 index 28309e7ca..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_confirm.rs +++ /dev/null @@ -1,62 +0,0 @@ -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenConfirm as RawMsgChannelOpenConfirm; -use ibc_proto::Protobuf; - -pub const CHAN_OPEN_CONFIRM_TYPE_URL: &str = "/ibc.core.channel.v1.MsgChannelOpenConfirm"; - -/// -/// Message definition for the fourth step in the channel open handshake (`ChanOpenConfirm` -/// datagram). -/// Per our convention, this message is sent to chain B. -/// -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgChannelOpenConfirm { - pub port_id_on_b: PortId, - pub chan_id_on_b: ChannelId, - pub proof_chan_end_on_a: CommitmentProofBytes, - pub proof_height_on_a: Height, - pub signer: Signer, -} - -impl Protobuf for MsgChannelOpenConfirm {} - -impl TryFrom for MsgChannelOpenConfirm { - type Error = DecodingError; - - fn try_from(raw_msg: RawMsgChannelOpenConfirm) -> Result { - Ok(MsgChannelOpenConfirm { - port_id_on_b: raw_msg.port_id.parse()?, - chan_id_on_b: raw_msg.channel_id.parse()?, - proof_chan_end_on_a: raw_msg.proof_ack.try_into()?, - proof_height_on_a: raw_msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::invalid_raw_data( - "msg channel open confirm proof height", - ))?, - signer: raw_msg.signer.into(), - }) - } -} - -impl From for RawMsgChannelOpenConfirm { - fn from(domain_msg: MsgChannelOpenConfirm) -> Self { - RawMsgChannelOpenConfirm { - port_id: domain_msg.port_id_on_b.to_string(), - channel_id: domain_msg.chan_id_on_b.to_string(), - proof_ack: domain_msg.proof_chan_end_on_a.into(), - proof_height: Some(domain_msg.proof_height_on_a.into()), - signer: domain_msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_init.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_init.rs deleted file mode 100644 index 526ad2fe1..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_init.rs +++ /dev/null @@ -1,95 +0,0 @@ -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ConnectionId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenInit as RawMsgChannelOpenInit; -use ibc_proto::Protobuf; - -use crate::channel::{verify_connection_hops_length, ChannelEnd, Counterparty, Order, State}; -use crate::error::ChannelError; -use crate::Version; - -pub const CHAN_OPEN_INIT_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) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgChannelOpenInit { - pub port_id_on_a: PortId, - pub connection_hops_on_a: Vec, - pub port_id_on_b: PortId, - pub ordering: Order, - pub signer: Signer, - /// Allow a relayer to specify a particular version by providing a non-empty version string - pub version_proposal: Version, -} - -impl MsgChannelOpenInit { - /// Checks if the `connection_hops` has a length of `expected`. - /// - /// Note: Current IBC version only supports one connection hop. - pub fn verify_connection_hops_length(&self) -> Result<(), ChannelError> { - verify_connection_hops_length(&self.connection_hops_on_a, 1) - } -} - -impl Protobuf for MsgChannelOpenInit {} - -impl TryFrom for MsgChannelOpenInit { - type Error = DecodingError; - - fn try_from(raw_msg: RawMsgChannelOpenInit) -> Result { - let chan_end_on_a: ChannelEnd = raw_msg - .channel - .ok_or(DecodingError::missing_raw_data("channel end"))? - .try_into()?; - - chan_end_on_a - .verify_state_matches(&State::Init) - .map_err(|_| { - DecodingError::invalid_raw_data(format!( - "expected channel end to be in `Init` state but it is in `{}` instead", - chan_end_on_a.state - )) - })?; - - if let Some(cid) = chan_end_on_a.counterparty().channel_id() { - return Err(DecodingError::invalid_raw_data(format!( - "expected counterparty channel ID to be empty, actual `{cid}`", - ))); - } - - Ok(MsgChannelOpenInit { - port_id_on_a: raw_msg.port_id.parse()?, - connection_hops_on_a: chan_end_on_a.connection_hops, - port_id_on_b: chan_end_on_a.remote.port_id, - ordering: chan_end_on_a.ordering, - signer: raw_msg.signer.into(), - version_proposal: chan_end_on_a.version, - }) - } -} - -impl From for RawMsgChannelOpenInit { - fn from(domain_msg: MsgChannelOpenInit) -> Self { - let chan_end_on_a = ChannelEnd::new_without_validation( - State::Init, - domain_msg.ordering, - Counterparty::new(domain_msg.port_id_on_b, None), - domain_msg.connection_hops_on_a, - domain_msg.version_proposal, - ); - RawMsgChannelOpenInit { - port_id: domain_msg.port_id_on_a.to_string(), - channel: Some(chan_end_on_a.into()), - signer: domain_msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_try.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_try.rs deleted file mode 100644 index cbdebfcea..000000000 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/chan_open_try.rs +++ /dev/null @@ -1,121 +0,0 @@ -use ibc_eureka_core_client_types::Height; -use ibc_eureka_core_commitment_types::commitment::CommitmentProofBytes; -use ibc_eureka_core_host_types::error::DecodingError; -use ibc_eureka_core_host_types::identifiers::{ChannelId, ConnectionId, PortId}; -use ibc_primitives::prelude::*; -use ibc_primitives::Signer; -use ibc_proto::ibc::core::channel::v1::MsgChannelOpenTry as RawMsgChannelOpenTry; -use ibc_proto::Protobuf; - -use crate::channel::{verify_connection_hops_length, ChannelEnd, Counterparty, Order, State}; -use crate::error::ChannelError; -use crate::Version; - -pub const CHAN_OPEN_TRY_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) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MsgChannelOpenTry { - pub port_id_on_b: PortId, - pub connection_hops_on_b: Vec, - pub port_id_on_a: PortId, - pub chan_id_on_a: ChannelId, - pub version_supported_on_a: Version, - pub proof_chan_end_on_a: CommitmentProofBytes, - pub proof_height_on_a: Height, - pub ordering: Order, - pub signer: Signer, - - #[deprecated(since = "0.22.0")] - /// Only kept here for proper conversion to/from the raw type - pub version_proposal: Version, -} - -impl MsgChannelOpenTry { - /// Checks if the `connection_hops` has a length of `expected`. - /// - /// Note: The current IBC version only supports one connection hop. - pub fn verify_connection_hops_length(&self) -> Result<(), ChannelError> { - verify_connection_hops_length(&self.connection_hops_on_b, 1) - } -} - -impl Protobuf for MsgChannelOpenTry {} - -impl TryFrom for MsgChannelOpenTry { - type Error = DecodingError; - - fn try_from(raw_msg: RawMsgChannelOpenTry) -> Result { - let chan_end_on_b: ChannelEnd = raw_msg - .channel - .ok_or(DecodingError::missing_raw_data("channel end not set"))? - .try_into()?; - - chan_end_on_b - .verify_state_matches(&State::TryOpen) - .map_err(|_| { - DecodingError::invalid_raw_data(format!( - "channel state expected to be in `TryOpen` state, actual `{}`", - chan_end_on_b.state() - )) - })?; - - #[allow(deprecated)] - if !raw_msg.previous_channel_id.is_empty() { - return Err(DecodingError::invalid_raw_data("previous channel id must be empty; it has been deprecated as crossing hellos are no longer supported"))?; - } - - #[allow(deprecated)] - let msg = MsgChannelOpenTry { - port_id_on_b: raw_msg.port_id.parse()?, - ordering: chan_end_on_b.ordering, - connection_hops_on_b: chan_end_on_b.connection_hops, - port_id_on_a: chan_end_on_b.remote.port_id, - chan_id_on_a: chan_end_on_b.remote.channel_id.ok_or( - DecodingError::missing_raw_data("msg channel open try counterparty channel ID"), - )?, - version_supported_on_a: raw_msg.counterparty_version.into(), - proof_chan_end_on_a: raw_msg.proof_init.try_into()?, - proof_height_on_a: raw_msg - .proof_height - .and_then(|raw_height| raw_height.try_into().ok()) - .ok_or(DecodingError::invalid_raw_data( - "msg channel open try proof height", - ))?, - signer: raw_msg.signer.into(), - version_proposal: chan_end_on_b.version, - }; - - Ok(msg) - } -} - -impl From for RawMsgChannelOpenTry { - fn from(domain_msg: MsgChannelOpenTry) -> Self { - let chan_end_on_b = ChannelEnd::new_without_validation( - State::TryOpen, - domain_msg.ordering, - Counterparty::new(domain_msg.port_id_on_a, Some(domain_msg.chan_id_on_a)), - domain_msg.connection_hops_on_b, - Version::empty(), // Excessive field to satisfy the type conversion - ); - #[allow(deprecated)] - RawMsgChannelOpenTry { - port_id: domain_msg.port_id_on_b.to_string(), - previous_channel_id: "".to_string(), // Excessive field to satisfy the type conversion", - channel: Some(chan_end_on_b.into()), - counterparty_version: domain_msg.version_supported_on_a.to_string(), - proof_init: domain_msg.proof_chan_end_on_a.clone().into(), - proof_height: Some(domain_msg.proof_height_on_a.into()), - signer: domain_msg.signer.to_string(), - } - } -} diff --git a/ibc-eureka-core/ics04-channel/types/src/msgs/mod.rs b/ibc-eureka-core/ics04-channel/types/src/msgs/mod.rs index e88d30a8e..69981fb5d 100644 --- a/ibc-eureka-core/ics04-channel/types/src/msgs/mod.rs +++ b/ibc-eureka-core/ics04-channel/types/src/msgs/mod.rs @@ -2,12 +2,6 @@ //! as packets. mod acknowledgement; -mod chan_close_confirm; -mod chan_close_init; -mod chan_open_ack; -mod chan_open_confirm; -mod chan_open_init; -mod chan_open_try; mod recv_packet; mod timeout; mod timeout_on_close; @@ -15,35 +9,12 @@ mod timeout_on_close; // Opening handshake messages. // Packet specific messages. pub use acknowledgement::*; -// Closing handshake messages. -pub use chan_close_confirm::*; -pub use chan_close_init::*; -pub use chan_open_ack::*; -pub use chan_open_confirm::*; -pub use chan_open_init::*; -pub use chan_open_try::*; use ibc_eureka_core_host_types::identifiers::*; use ibc_primitives::prelude::*; pub use recv_packet::*; pub use timeout::*; pub use timeout_on_close::*; -/// All channel messages -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq, derive_more::From)] -pub enum ChannelMsg { - OpenInit(MsgChannelOpenInit), - OpenTry(MsgChannelOpenTry), - OpenAck(MsgChannelOpenAck), - OpenConfirm(MsgChannelOpenConfirm), - CloseInit(MsgChannelCloseInit), - CloseConfirm(MsgChannelCloseConfirm), -} - /// All packet messages #[cfg_attr( feature = "borsh", @@ -55,18 +26,6 @@ pub enum PacketMsg { Recv(MsgRecvPacket), Ack(MsgAcknowledgement), Timeout(MsgTimeout), - TimeoutOnClose(MsgTimeoutOnClose), -} - -pub 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 fn packet_msg_to_port_id(msg: &PacketMsg) -> &PortId { @@ -74,6 +33,5 @@ pub fn packet_msg_to_port_id(msg: &PacketMsg) -> &PortId { PacketMsg::Recv(msg) => &msg.packet.payloads[0].header.target_port.1, PacketMsg::Ack(msg) => &msg.packet.payloads[0].header.source_port.1, PacketMsg::Timeout(msg) => &msg.packet.payloads[0].header.source_port.1, - PacketMsg::TimeoutOnClose(msg) => &msg.packet.payloads[0].header.source_port.1, } } diff --git a/ibc-eureka-core/ics04-channel/types/src/packet.rs b/ibc-eureka-core/ics04-channel/types/src/packet.rs index d8e6dbeb5..bec1b78cc 100644 --- a/ibc-eureka-core/ics04-channel/types/src/packet.rs +++ b/ibc-eureka-core/ics04-channel/types/src/packet.rs @@ -83,8 +83,8 @@ impl core::fmt::Display for PacketMsgType { #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct PacketHeader { pub seq_on_a: Sequence, - pub source_client: ChannelId, - pub target_client: ChannelId, + pub target_client_on_source: ChannelId, + pub source_client_on_target: ChannelId, pub timeout_height_on_b: TimeoutHeight, pub timeout_timestamp_on_b: TimeoutTimestamp, } @@ -188,7 +188,9 @@ impl core::fmt::Display for Packet { write!( f, "seq:{}, path:{}/{}", - self.header.seq_on_a, self.header.source_client, self.header.target_client + self.header.seq_on_a, + self.header.target_client_on_source, + self.header.source_client_on_target )?; for payload in &self.payloads { write!( @@ -237,8 +239,8 @@ impl TryFrom for Packet { Ok(Packet { header: PacketHeader { seq_on_a: Sequence::from(raw_pkt.sequence), - source_client: raw_pkt.source_channel.parse()?, - target_client: raw_pkt.destination_channel.parse()?, + target_client_on_source: raw_pkt.source_channel.parse()?, + source_client_on_target: raw_pkt.destination_channel.parse()?, timeout_height_on_b: packet_timeout_height, timeout_timestamp_on_b, }, @@ -258,8 +260,8 @@ impl From for RawPacket { fn from(packet: Packet) -> Self { Self { sequence: packet.header.seq_on_a.value(), - source_channel: packet.header.source_client.to_string(), - destination_channel: packet.header.target_client.to_string(), + source_channel: packet.header.target_client_on_source.to_string(), + destination_channel: packet.header.source_client_on_target.to_string(), timeout_height: packet.header.timeout_height_on_b.into(), timeout_timestamp: packet.header.timeout_timestamp_on_b.nanoseconds(), // TODO(rano): support multi payload; currently only one payload is supported diff --git a/ibc-eureka-core/ics24-host/Cargo.toml b/ibc-eureka-core/ics24-host/Cargo.toml index 142c0f7bf..2fd9a69de 100644 --- a/ibc-eureka-core/ics24-host/Cargo.toml +++ b/ibc-eureka-core/ics24-host/Cargo.toml @@ -27,7 +27,6 @@ subtle-encoding = { workspace = true } # ibc dependencies ibc-eureka-core-client-types = { workspace = true } ibc-eureka-core-client-context = { workspace = true } -ibc-eureka-core-connection-types = { workspace = true } ibc-eureka-core-channel-types = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-host-types = { workspace = true } @@ -44,7 +43,6 @@ std = [ "subtle-encoding/std", "ibc-eureka-core-client-types/std", "ibc-eureka-core-client-context/std", - "ibc-eureka-core-connection-types/std", "ibc-eureka-core-channel-types/std", "ibc-eureka-core-commitment-types/std", "ibc-eureka-core-host-types/std", @@ -54,7 +52,6 @@ std = [ serde = [ "ibc-eureka-core-client-types/serde", "ibc-eureka-core-client-context/serde", - "ibc-eureka-core-connection-types/serde", "ibc-eureka-core-channel-types/serde", "ibc-eureka-core-commitment-types/serde", "ibc-eureka-core-host-types/serde", @@ -64,7 +61,6 @@ serde = [ schema = [ "ibc-eureka-core-client-types/schema", "ibc-eureka-core-client-context/schema", - "ibc-eureka-core-connection-types/schema", "ibc-eureka-core-channel-types/schema", "ibc-eureka-core-commitment-types/schema", "ibc-eureka-core-host-types/schema", @@ -76,7 +72,6 @@ schema = [ borsh = [ "ibc-eureka-core-client-types/borsh", "ibc-eureka-core-client-context/borsh", - "ibc-eureka-core-connection-types/borsh", "ibc-eureka-core-channel-types/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host-types/borsh", @@ -85,7 +80,6 @@ borsh = [ ] parity-scale-codec = [ "ibc-eureka-core-client-types/parity-scale-codec", - "ibc-eureka-core-connection-types/parity-scale-codec", "ibc-eureka-core-channel-types/parity-scale-codec", "ibc-eureka-core-commitment-types/parity-scale-codec", "ibc-eureka-core-host-types/parity-scale-codec", diff --git a/ibc-eureka-core/ics24-host/cosmos/Cargo.toml b/ibc-eureka-core/ics24-host/cosmos/Cargo.toml index 6145d0d9c..3ce0eba98 100644 --- a/ibc-eureka-core/ics24-host/cosmos/Cargo.toml +++ b/ibc-eureka-core/ics24-host/cosmos/Cargo.toml @@ -32,7 +32,6 @@ ibc-client-tendermint = { workspace = true } ibc-app-transfer-types = { workspace = true } ibc-eureka-core-client-types = { workspace = true } ibc-eureka-core-client-context = { workspace = true } -ibc-eureka-core-connection-types = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-host-types = { workspace = true } ibc-eureka-core-handler-types = { workspace = true } @@ -55,7 +54,6 @@ std = [ "subtle-encoding/std", "ibc-eureka-core-client-types/std", "ibc-eureka-core-client-context/std", - "ibc-eureka-core-connection-types/std", "ibc-eureka-core-commitment-types/std", "ibc-eureka-core-host-types/std", "ibc-eureka-core-handler-types/std", @@ -67,7 +65,6 @@ serde = [ "ibc-client-tendermint/serde", "ibc-eureka-core-client-types/serde", "ibc-eureka-core-client-context/serde", - "ibc-eureka-core-connection-types/serde", "ibc-eureka-core-commitment-types/serde", "ibc-eureka-core-host-types/serde", "ibc-eureka-core-handler-types/serde", @@ -78,7 +75,6 @@ schema = [ "ibc-client-tendermint/schema", "ibc-eureka-core-client-types/schema", "ibc-eureka-core-client-context/schema", - "ibc-eureka-core-connection-types/schema", "ibc-eureka-core-commitment-types/schema", "ibc-eureka-core-host-types/schema", "ibc-eureka-core-handler-types/schema", @@ -92,7 +88,6 @@ borsh = [ "ibc-client-tendermint/borsh", "ibc-eureka-core-client-types/borsh", "ibc-eureka-core-client-context/borsh", - "ibc-eureka-core-connection-types/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host-types/borsh", "ibc-primitives/borsh", @@ -103,7 +98,6 @@ parity-scale-codec = [ "dep:scale-info", "ibc-client-tendermint/parity-scale-codec", "ibc-eureka-core-client-types/parity-scale-codec", - "ibc-eureka-core-connection-types/parity-scale-codec", "ibc-eureka-core-commitment-types/parity-scale-codec", "ibc-eureka-core-host-types/parity-scale-codec", "ibc-eureka-core-handler-types/parity-scale-codec", diff --git a/ibc-eureka-core/ics24-host/src/context.rs b/ibc-eureka-core/ics24-host/src/context.rs index 8b9440d6a..8638a5ec9 100644 --- a/ibc-eureka-core/ics24-host/src/context.rs +++ b/ibc-eureka-core/ics24-host/src/context.rs @@ -1,19 +1,15 @@ use core::time::Duration; -use ibc_eureka_core_channel_types::channel::ChannelEnd; use ibc_eureka_core_channel_types::commitment::{AcknowledgementCommitment, PacketCommitment}; use ibc_eureka_core_channel_types::packet::Receipt; use ibc_eureka_core_client_context::prelude::*; use ibc_eureka_core_client_types::Height; use ibc_eureka_core_commitment_types::commitment::CommitmentPrefix; -use ibc_eureka_core_connection_types::version::{pick_version, Version as ConnectionVersion}; -use ibc_eureka_core_connection_types::ConnectionEnd; use ibc_eureka_core_handler_types::events::IbcEvent; use ibc_eureka_core_host_types::error::HostError; -use ibc_eureka_core_host_types::identifiers::{ConnectionId, Sequence}; +use ibc_eureka_core_host_types::identifiers::Sequence; use ibc_eureka_core_host_types::path::{ - AckPath, ChannelEndPath, ClientConnectionPath, CommitmentPath, ConnectionPath, ReceiptPath, - SeqAckPath, SeqRecvPath, SeqSendPath, + AckPath, CommitmentPath, ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, }; use ibc_primitives::prelude::*; use ibc_primitives::{Signer, Timestamp}; @@ -47,9 +43,6 @@ pub trait ValidationContext { /// `ExecutionContext::increase_client_counter`. fn client_counter(&self) -> Result; - /// Returns the ConnectionEnd for the given identifier `conn_id`. - fn connection_end(&self, conn_id: &ConnectionId) -> Result; - /// Validates the `ClientState` of the host chain stored on the counterparty /// chain against the host's internal state. /// @@ -67,31 +60,6 @@ pub trait ValidationContext { /// Returns the prefix that the local chain uses in the KV store. fn commitment_prefix(&self) -> CommitmentPrefix; - /// Returns a counter on how many connections have been created thus far. - fn connection_counter(&self) -> Result; - - /// Function required by ICS-03. Returns the list of all possible versions that the connection - /// handshake protocol supports. - fn get_compatible_versions(&self) -> Vec { - ConnectionVersion::compatibles() - } - - /// Function required by ICS-03. Returns one version out of the supplied list of versions, which the - /// connection handshake protocol prefers. - fn pick_version( - &self, - counterparty_candidate_versions: &[ConnectionVersion], - ) -> Result { - pick_version( - &self.get_compatible_versions(), - counterparty_candidate_versions, - ) - .map_err(HostError::missing_state) - } - - /// Returns the `ChannelEnd` for the given `port_id` and `chan_id`. - fn channel_end(&self, channel_end_path: &ChannelEndPath) -> Result; - /// Returns the sequence number for the next packet to be sent for the given store path fn get_next_sequence_send(&self, seq_send_path: &SeqSendPath) -> Result; @@ -155,20 +123,6 @@ pub trait ExecutionContext: ValidationContext { /// Increases the counter, that keeps track of how many clients have been created. fn increase_client_counter(&mut self) -> Result<(), HostError>; - /// Stores the given connection_end at path - fn store_connection( - &mut self, - connection_path: &ConnectionPath, - connection_end: ConnectionEnd, - ) -> Result<(), HostError>; - - /// Stores the given connection_id at a path associated with the client_id. - fn store_connection_to_client( - &mut self, - client_connection_path: &ClientConnectionPath, - conn_id: ConnectionId, - ) -> Result<(), HostError>; - /// Called upon connection identifier creation (Init or Try process). /// Increases the counter which keeps track of how many connections have been created. fn increase_connection_counter(&mut self) -> Result<(), HostError>; @@ -203,13 +157,6 @@ pub trait ExecutionContext: ValidationContext { /// Deletes the packet acknowledgement at the given store path fn delete_packet_acknowledgement(&mut self, ack_path: &AckPath) -> Result<(), HostError>; - /// Stores the given channel_end at a path associated with the port_id and channel_id. - fn store_channel( - &mut self, - channel_end_path: &ChannelEndPath, - channel_end: ChannelEnd, - ) -> Result<(), HostError>; - /// Stores the given `nextSequenceSend` number at the given store path fn store_next_sequence_send( &mut self, diff --git a/ibc-eureka-core/ics24-host/types/src/identifiers/channel_id.rs b/ibc-eureka-core/ics24-host/types/src/identifiers/channel_id.rs index 154977d09..dcf8c8e59 100644 --- a/ibc-eureka-core/ics24-host/types/src/identifiers/channel_id.rs +++ b/ibc-eureka-core/ics24-host/types/src/identifiers/channel_id.rs @@ -1,7 +1,7 @@ use core::fmt::{Debug, Display, Error as FmtError, Formatter}; use core::str::FromStr; -use derive_more::Into; +use derive_more::{From, Into}; use ibc_primitives::prelude::*; use crate::error::IdentifierError; @@ -23,15 +23,9 @@ const CHANNEL_ID_PREFIX: &str = "channel"; )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Into)] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, From, Into)] pub struct ChannelId(ClientId); -impl From for ChannelId { - fn from(client_id: ClientId) -> Self { - Self(client_id) - } -} - impl ChannelId { /// Returns the static prefix to be used across all channel identifiers. pub fn prefix() -> &'static str { @@ -70,6 +64,12 @@ impl AsRef for ChannelId { } } +impl AsRef for ChannelId { + fn as_ref(&self) -> &ClientId { + &self.0 + } +} + /// Equality check against string literal (satisfies &ChannelId == &str). /// ``` /// use core::str::FromStr; diff --git a/ibc-eureka-core/ics24-host/types/src/identifiers/connection_id.rs b/ibc-eureka-core/ics24-host/types/src/identifiers/connection_id.rs deleted file mode 100644 index 9fbd7e7af..000000000 --- a/ibc-eureka-core/ics24-host/types/src/identifiers/connection_id.rs +++ /dev/null @@ -1,93 +0,0 @@ -use core::fmt::{Display, Error as FmtError, Formatter}; -use core::str::FromStr; - -use derive_more::Into; -use ibc_primitives::prelude::*; - -use crate::error::IdentifierError; -use crate::validate::validate_connection_identifier; - -const CONNECTION_ID_PREFIX: &str = "connection"; - -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - 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, PartialEq, Eq, PartialOrd, Ord, Hash, Into)] -pub struct ConnectionId(String); - -impl ConnectionId { - /// Builds a new connection identifier. Connection identifiers are deterministically formed from - /// two elements: a prefix `prefix`, and a monotonically increasing `counter`; these are - /// separated by a dash "-". The prefix is currently determined statically (see - /// `ConnectionId::prefix()`) so this method accepts a single argument, the `counter`. - /// - /// ``` - /// # use ibc_eureka_core_host_types::identifiers::ConnectionId; - /// let conn_id = ConnectionId::new(11); - /// assert_eq!(&conn_id, "connection-11"); - /// ``` - pub fn new(identifier: u64) -> Self { - let id = format!("{}-{}", Self::prefix(), identifier); - Self(id) - } - - /// Returns the static prefix to be used across all connection identifiers. - pub fn prefix() -> &'static str { - CONNECTION_ID_PREFIX - } - - /// Get this identifier as a borrowed `&str` - pub fn as_str(&self) -> &str { - &self.0 - } - - /// Get this identifier as a borrowed byte slice - pub fn as_bytes(&self) -> &[u8] { - self.0.as_bytes() - } - - /// Return ConnectionId with identifier 0 - pub fn zero() -> Self { - Self::new(0) - } -} - -/// This implementation provides a `to_string` method. -impl Display for ConnectionId { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { - write!(f, "{}", self.0) - } -} - -impl FromStr for ConnectionId { - type Err = IdentifierError; - - fn from_str(s: &str) -> Result { - validate_connection_identifier(s).map(|_| Self(s.to_string())) - } -} - -/// Equality check against string literal (satisfies &ConnectionId == &str). -/// ``` -/// use core::str::FromStr; -/// use ibc_eureka_core_host_types::identifiers::ConnectionId; -/// let conn_id = ConnectionId::from_str("connection-0"); -/// assert!(conn_id.is_ok()); -/// conn_id.map(|id| {assert_eq!(&id, "connection-0")}); -/// ``` -impl PartialEq for ConnectionId { - fn eq(&self, other: &str) -> bool { - self.as_str().eq(other) - } -} diff --git a/ibc-eureka-core/ics24-host/types/src/identifiers/mod.rs b/ibc-eureka-core/ics24-host/types/src/identifiers/mod.rs index 9ae79f673..653c37f91 100644 --- a/ibc-eureka-core/ics24-host/types/src/identifiers/mod.rs +++ b/ibc-eureka-core/ics24-host/types/src/identifiers/mod.rs @@ -4,7 +4,7 @@ mod chain_id; mod channel_id; mod client_id; mod client_type; -mod connection_id; +// mod connection_id; mod port_id; mod sequence; @@ -12,6 +12,6 @@ pub use chain_id::ChainId; pub use channel_id::ChannelId; pub use client_id::ClientId; pub use client_type::ClientType; -pub use connection_id::ConnectionId; +// pub use connection_id::ConnectionId; pub use port_id::PortId; pub use sequence::Sequence; diff --git a/ibc-eureka-core/ics24-host/types/src/path.rs b/ibc-eureka-core/ics24-host/types/src/path.rs index bbc8c79c6..750fb3bf6 100644 --- a/ibc-eureka-core/ics24-host/types/src/path.rs +++ b/ibc-eureka-core/ics24-host/types/src/path.rs @@ -9,7 +9,7 @@ use core::str::FromStr; use derive_more::{Display, From}; use ibc_primitives::prelude::*; -use crate::identifiers::{ChannelId, ClientId, ConnectionId, PortId, Sequence}; +use crate::identifiers::{ChannelId, ClientId, PortId, Sequence}; pub const NEXT_CLIENT_SEQUENCE: &str = "nextClientSequence"; pub const NEXT_CONNECTION_SEQUENCE: &str = "nextConnectionSequence"; @@ -90,7 +90,6 @@ pub enum Path { ClientUpdateTime(ClientUpdateTimePath), ClientUpdateHeight(ClientUpdateHeightPath), ClientConnection(ClientConnectionPath), - Connection(ConnectionPath), Ports(PortPath), ChannelEnd(ChannelEndPath), SeqSend(SeqSendPath), @@ -392,35 +391,6 @@ impl ClientConnectionPath { } } -#[cfg_attr( - feature = "parity-scale-codec", - derive( - parity_scale_codec::Encode, - parity_scale_codec::Decode, - scale_info::TypeInfo - ) -)] -#[cfg_attr( - feature = "borsh", - derive(borsh::BorshSerialize, borsh::BorshDeserialize) -)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display)] -#[display(fmt = "{CONNECTION_PREFIX}/{_0}")] -pub struct ConnectionPath(pub ConnectionId); - -impl ConnectionPath { - pub fn new(connection_id: &ConnectionId) -> ConnectionPath { - ConnectionPath(connection_id.clone()) - } - - /// Returns the connection store prefix under which all the connections are - /// stored: "connections". - pub fn prefix() -> String { - CONNECTION_PREFIX.to_string() - } -} - #[cfg_attr( feature = "parity-scale-codec", derive( @@ -792,7 +762,6 @@ impl FromStr for Path { parse_next_sequence(&components) .or_else(|| parse_client_paths(&components)) - .or_else(|| parse_connections(&components)) .or_else(|| parse_ports(&components)) .or_else(|| parse_channel_ends(&components)) .or_else(|| parse_seqs(&components)) @@ -889,24 +858,6 @@ fn parse_client_paths(components: &[&str]) -> Option { } } -fn parse_connections(components: &[&str]) -> Option { - if components.len() != 2 { - return None; - } - - let first = *components.first()?; - - if first != CONNECTION_PREFIX { - return None; - } - - let connection_id = *components.last()?; - - let connection_id = ConnectionId::from_str(connection_id).ok()?; - - Some(ConnectionPath(connection_id).into()) -} - fn parse_ports(components: &[&str]) -> Option { if components.len() != 2 { return None; diff --git a/ibc-eureka-core/ics24-host/types/src/validate.rs b/ibc-eureka-core/ics24-host/types/src/validate.rs index 614cfd8a4..8090cd02f 100644 --- a/ibc-eureka-core/ics24-host/types/src/validate.rs +++ b/ibc-eureka-core/ics24-host/types/src/validate.rs @@ -1,7 +1,7 @@ use ibc_primitives::prelude::*; use crate::error::IdentifierError as Error; -use crate::identifiers::{ChannelId, ConnectionId}; +use crate::identifiers::ChannelId; const VALID_SPECIAL_CHARS: &str = "._+-#[]<>"; @@ -97,16 +97,16 @@ pub fn validate_client_identifier(id: &str) -> Result<(), Error> { validate_identifier_length(id, 9, 64) } -/// Default validator function for Connection identifiers. -/// -/// 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_chars(id)?; - validate_identifier_length(id, 10, 64)?; - validate_named_u64_index(id, ConnectionId::prefix())?; - Ok(()) -} +// /// Default validator function for Connection identifiers. +// /// +// /// 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_chars(id)?; +// validate_identifier_length(id, 10, 64)?; +// validate_named_u64_index(id, ConnectionId::prefix())?; +// Ok(()) +// } /// Default validator function for Port identifiers. /// @@ -150,39 +150,39 @@ mod tests { assert!(id.is_err()) } - #[test] - fn parse_invalid_connection_id_min() { - // invalid min connection id - let id = validate_connection_identifier("connect01"); - assert!(id.is_err()) - } - - #[test] - fn parse_connection_id_max() { - // invalid max connection id (test string length is 65) - let id = validate_connection_identifier( - "ihhankr30iy4nna65hjl2wjod7182io1t2s7u3ip3wqtbbn1sl0rgcntqc540r36r", - ); - assert!(id.is_err()) - } - - #[test] - fn parse_invalid_connection_id_indexed() { - // valid connection id with index - validate_connection_identifier("connection-0").expect("success"); - validate_connection_identifier("connection-123").expect("success"); - validate_connection_identifier("connection-18446744073709551615").expect("success"); - } - - #[test] - fn parse_invalid_connection_id_non_indexed() { - // invalid indexing for connection id - validate_connection_identifier("connection-0123").expect_err("failure"); - validate_connection_identifier("connection0123").expect_err("failure"); - validate_connection_identifier("connection000").expect_err("failure"); - // 1 << 64 = 18446744073709551616 - validate_connection_identifier("connection-18446744073709551616").expect_err("failure"); - } + // #[test] + // fn parse_invalid_connection_id_min() { + // // invalid min connection id + // let id = validate_connection_identifier("connect01"); + // assert!(id.is_err()) + // } + + // #[test] + // fn parse_connection_id_max() { + // // invalid max connection id (test string length is 65) + // let id = validate_connection_identifier( + // "ihhankr30iy4nna65hjl2wjod7182io1t2s7u3ip3wqtbbn1sl0rgcntqc540r36r", + // ); + // assert!(id.is_err()) + // } + + // #[test] + // fn parse_invalid_connection_id_indexed() { + // // valid connection id with index + // validate_connection_identifier("connection-0").expect("success"); + // validate_connection_identifier("connection-123").expect("success"); + // validate_connection_identifier("connection-18446744073709551615").expect("success"); + // } + + // #[test] + // fn parse_invalid_connection_id_non_indexed() { + // // invalid indexing for connection id + // validate_connection_identifier("connection-0123").expect_err("failure"); + // validate_connection_identifier("connection0123").expect_err("failure"); + // validate_connection_identifier("connection000").expect_err("failure"); + // // 1 << 64 = 18446744073709551616 + // validate_connection_identifier("connection-18446744073709551616").expect_err("failure"); + // } #[test] fn parse_invalid_channel_id_min() { diff --git a/ibc-eureka-core/ics25-handler/Cargo.toml b/ibc-eureka-core/ics25-handler/Cargo.toml index 886388cd8..957327d9b 100644 --- a/ibc-eureka-core/ics25-handler/Cargo.toml +++ b/ibc-eureka-core/ics25-handler/Cargo.toml @@ -20,7 +20,6 @@ all-features = true [dependencies] ibc-eureka-core-client = { workspace = true } -ibc-eureka-core-connection = { workspace = true } ibc-eureka-core-channel = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-router = { workspace = true } @@ -32,7 +31,6 @@ ibc-primitives = { workspace = true } default = [ "std" ] std = [ "ibc-eureka-core-client/std", - "ibc-eureka-core-connection/std", "ibc-eureka-core-channel/std", "ibc-eureka-core-commitment-types/std", "ibc-eureka-core-host/std", @@ -42,7 +40,6 @@ std = [ ] serde = [ "ibc-eureka-core-client/serde", - "ibc-eureka-core-connection/serde", "ibc-eureka-core-channel/serde", "ibc-eureka-core-commitment-types/serde", "ibc-eureka-core-host/serde", @@ -52,7 +49,6 @@ serde = [ ] borsh = [ "ibc-eureka-core-client/borsh", - "ibc-eureka-core-connection/borsh", "ibc-eureka-core-channel/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host/borsh", @@ -62,7 +58,6 @@ borsh = [ ] schema = [ "ibc-eureka-core-client/schema", - "ibc-eureka-core-connection/schema", "ibc-eureka-core-channel/schema", "ibc-eureka-core-commitment-types/schema", "ibc-eureka-core-host/schema", @@ -74,7 +69,6 @@ schema = [ ] parity-scale-codec = [ "ibc-eureka-core-client/parity-scale-codec", - "ibc-eureka-core-connection/parity-scale-codec", "ibc-eureka-core-channel/parity-scale-codec", "ibc-eureka-core-host/parity-scale-codec", "ibc-eureka-core-router/parity-scale-codec", diff --git a/ibc-eureka-core/ics25-handler/src/entrypoint.rs b/ibc-eureka-core/ics25-handler/src/entrypoint.rs index 5d128b67d..69010d5d6 100644 --- a/ibc-eureka-core/ics25-handler/src/entrypoint.rs +++ b/ibc-eureka-core/ics25-handler/src/entrypoint.rs @@ -1,22 +1,12 @@ use ibc_eureka_core_channel::handler::{ - acknowledgement_packet_execute, acknowledgement_packet_validate, chan_close_confirm_execute, - chan_close_confirm_validate, chan_close_init_execute, chan_close_init_validate, - chan_open_ack_execute, chan_open_ack_validate, chan_open_confirm_execute, - chan_open_confirm_validate, chan_open_init_execute, chan_open_init_validate, - chan_open_try_execute, chan_open_try_validate, recv_packet_execute, recv_packet_validate, - timeout_packet_execute, timeout_packet_validate, TimeoutMsgType, -}; -use ibc_eureka_core_channel::types::msgs::{ - channel_msg_to_port_id, packet_msg_to_port_id, ChannelMsg, PacketMsg, + acknowledgement_packet_execute, acknowledgement_packet_validate, recv_packet_execute, + recv_packet_validate, timeout_packet_execute, timeout_packet_validate, }; +use ibc_eureka_core_channel::types::msgs::{packet_msg_to_port_id, PacketMsg}; use ibc_eureka_core_client::context::{ClientExecutionContext, ClientValidationContext}; use ibc_eureka_core_client::handler::{create_client, update_client, upgrade_client}; use ibc_eureka_core_client::types::error::ClientError; use ibc_eureka_core_client::types::msgs::{ClientMsg, MsgUpdateOrMisbehaviour}; -use ibc_eureka_core_connection::handler::{ - conn_open_ack, conn_open_confirm, conn_open_init, conn_open_try, -}; -use ibc_eureka_core_connection::types::msgs::ConnectionMsg; use ibc_eureka_core_handler_types::error::HandlerError; use ibc_eureka_core_handler_types::msgs::MsgEnvelope; use ibc_eureka_core_host::types::error::HostError; @@ -71,30 +61,6 @@ where // authorized via a passing governance proposal } }, - MsgEnvelope::Connection(msg) => match msg { - ConnectionMsg::OpenInit(msg) => conn_open_init::validate(ctx, msg)?, - ConnectionMsg::OpenTry(msg) => conn_open_try::validate(ctx, msg)?, - ConnectionMsg::OpenAck(msg) => conn_open_ack::validate(ctx, msg)?, - ConnectionMsg::OpenConfirm(msg) => conn_open_confirm::validate(ctx, &msg)?, - }, - MsgEnvelope::Channel(msg) => { - let port_id = channel_msg_to_port_id(&msg); - let module_id = router.lookup_module(port_id).ok_or(RouterError::Host( - HostError::missing_state(format!("missing module ID for port {}", port_id.clone())), - ))?; - let module = router - .get_route(&module_id) - .ok_or(RouterError::MissingModule)?; - - match 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)?, - } - } MsgEnvelope::Packet(msg) => { let port_id = packet_msg_to_port_id(&msg); let module_id = router.lookup_module(port_id).ok_or(RouterError::Host( @@ -107,12 +73,7 @@ where match msg { PacketMsg::Recv(msg) => recv_packet_validate(ctx, msg)?, PacketMsg::Ack(msg) => acknowledgement_packet_validate(ctx, module, msg)?, - PacketMsg::Timeout(msg) => { - timeout_packet_validate(ctx, module, TimeoutMsgType::Timeout(msg))? - } - PacketMsg::TimeoutOnClose(msg) => { - timeout_packet_validate(ctx, module, TimeoutMsgType::TimeoutOnClose(msg))? - } + PacketMsg::Timeout(msg) => timeout_packet_validate(ctx, module, msg)?, } } }; @@ -145,30 +106,6 @@ where // authorized via a passing governance proposal } }, - MsgEnvelope::Connection(msg) => match msg { - ConnectionMsg::OpenInit(msg) => conn_open_init::execute(ctx, msg)?, - ConnectionMsg::OpenTry(msg) => conn_open_try::execute(ctx, msg)?, - ConnectionMsg::OpenAck(msg) => conn_open_ack::execute(ctx, msg)?, - ConnectionMsg::OpenConfirm(msg) => conn_open_confirm::execute(ctx, &msg)?, - }, - MsgEnvelope::Channel(msg) => { - let port_id = channel_msg_to_port_id(&msg); - let module_id = router.lookup_module(port_id).ok_or(RouterError::Host( - HostError::missing_state(format!("missing module ID for port {}", port_id.clone())), - ))?; - let module = router - .get_route_mut(&module_id) - .ok_or(RouterError::MissingModule)?; - - match 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)?, - } - } MsgEnvelope::Packet(msg) => { let port_id = packet_msg_to_port_id(&msg); let module_id = router.lookup_module(port_id).ok_or(RouterError::Host( @@ -181,12 +118,7 @@ where match 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, TimeoutMsgType::Timeout(msg))? - } - PacketMsg::TimeoutOnClose(msg) => { - timeout_packet_execute(ctx, module, TimeoutMsgType::TimeoutOnClose(msg))? - } + PacketMsg::Timeout(msg) => timeout_packet_execute(ctx, module, msg)?, } } } diff --git a/ibc-eureka-core/ics25-handler/types/Cargo.toml b/ibc-eureka-core/ics25-handler/types/Cargo.toml index 9fd8e6418..bae6ce5f5 100644 --- a/ibc-eureka-core/ics25-handler/types/Cargo.toml +++ b/ibc-eureka-core/ics25-handler/types/Cargo.toml @@ -29,7 +29,6 @@ subtle-encoding = { workspace = true } # ibc dependencies ibc-eureka-core-client-types = { workspace = true } -ibc-eureka-core-connection-types = { workspace = true } ibc-eureka-core-channel-types = { workspace = true } ibc-eureka-core-commitment-types = { workspace = true } ibc-eureka-core-host-types = { workspace = true } @@ -51,7 +50,6 @@ std = [ "serde/std", "subtle-encoding/std", "ibc-eureka-core-client-types/std", - "ibc-eureka-core-connection-types/std", "ibc-eureka-core-channel-types/std", "ibc-eureka-core-commitment-types/std", "ibc-eureka-core-host-types/std", @@ -63,7 +61,6 @@ std = [ serde = [ "dep:serde", "ibc-eureka-core-client-types/serde", - "ibc-eureka-core-connection-types/serde", "ibc-eureka-core-channel-types/serde", "ibc-eureka-core-commitment-types/serde", "ibc-eureka-core-host-types/serde", @@ -74,7 +71,6 @@ serde = [ schema = [ "dep:schemars", "ibc-eureka-core-client-types/schema", - "ibc-eureka-core-connection-types/schema", "ibc-eureka-core-channel-types/schema", "ibc-eureka-core-commitment-types/schema", "ibc-eureka-core-host-types/schema", @@ -87,7 +83,6 @@ schema = [ borsh = [ "dep:borsh", "ibc-eureka-core-client-types/borsh", - "ibc-eureka-core-connection-types/borsh", "ibc-eureka-core-channel-types/borsh", "ibc-eureka-core-commitment-types/borsh", "ibc-eureka-core-host-types/borsh", @@ -99,7 +94,6 @@ parity-scale-codec = [ "dep:parity-scale-codec", "dep:scale-info", "ibc-eureka-core-client-types/parity-scale-codec", - "ibc-eureka-core-connection-types/parity-scale-codec", "ibc-eureka-core-channel-types/parity-scale-codec", "ibc-eureka-core-commitment-types/parity-scale-codec", "ibc-eureka-core-host-types/parity-scale-codec", diff --git a/ibc-eureka-core/ics25-handler/types/src/error.rs b/ibc-eureka-core/ics25-handler/types/src/error.rs index 2ce21e1b9..5a3477408 100644 --- a/ibc-eureka-core/ics25-handler/types/src/error.rs +++ b/ibc-eureka-core/ics25-handler/types/src/error.rs @@ -4,7 +4,6 @@ use derive_more::From; use displaydoc::Display; use ibc_eureka_core_channel_types::error::ChannelError; use ibc_eureka_core_client_types::error::ClientError; -use ibc_eureka_core_connection_types::error::ConnectionError; use ibc_eureka_core_router_types::error::RouterError; use ibc_primitives::prelude::*; @@ -13,8 +12,6 @@ use ibc_primitives::prelude::*; pub enum HandlerError { /// ICS02 Client error: {0} Client(ClientError), - /// ICS03 Connection error: {0} - Connection(ConnectionError), /// ICS04 Channel error: {0} Channel(ChannelError), /// ICS26 Routing error: {0} @@ -26,7 +23,6 @@ impl std::error::Error for HandlerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Client(e) => Some(e), - Self::Connection(e) => Some(e), Self::Channel(e) => Some(e), Self::Router(e) => Some(e), } diff --git a/ibc-eureka-core/ics25-handler/types/src/events.rs b/ibc-eureka-core/ics25-handler/types/src/events.rs index 40c29e456..6a86ad948 100644 --- a/ibc-eureka-core/ics25-handler/types/src/events.rs +++ b/ibc-eureka-core/ics25-handler/types/src/events.rs @@ -2,7 +2,6 @@ use ibc_eureka_core_channel_types::events as ChannelEvents; use ibc_eureka_core_client_types::events::{self as ClientEvents}; -use ibc_eureka_core_connection_types::events as ConnectionEvents; use ibc_eureka_core_host_types::error::DecodingError; use ibc_eureka_core_router_types::event::ModuleEvent; use ibc_primitives::prelude::*; @@ -31,11 +30,6 @@ pub enum IbcEvent { UpgradeClient(ClientEvents::UpgradeClient), ClientMisbehaviour(ClientEvents::ClientMisbehaviour), - OpenInitConnection(ConnectionEvents::OpenInit), - OpenTryConnection(ConnectionEvents::OpenTry), - OpenAckConnection(ConnectionEvents::OpenAck), - OpenConfirmConnection(ConnectionEvents::OpenConfirm), - OpenInitChannel(ChannelEvents::OpenInit), OpenTryChannel(ChannelEvents::OpenTry), OpenAckChannel(ChannelEvents::OpenAck), @@ -63,10 +57,6 @@ impl TryFrom for abci::Event { IbcEvent::UpdateClient(event) => event.into(), IbcEvent::UpgradeClient(event) => event.into(), IbcEvent::ClientMisbehaviour(event) => event.into(), - IbcEvent::OpenInitConnection(event) => event.into(), - IbcEvent::OpenTryConnection(event) => event.into(), - IbcEvent::OpenAckConnection(event) => event.into(), - IbcEvent::OpenConfirmConnection(event) => event.into(), IbcEvent::OpenInitChannel(event) => event.into(), IbcEvent::OpenTryChannel(event) => event.into(), IbcEvent::OpenAckChannel(event) => event.into(), @@ -95,10 +85,6 @@ impl IbcEvent { IbcEvent::UpdateClient(event) => event.event_type(), IbcEvent::ClientMisbehaviour(event) => event.event_type(), IbcEvent::UpgradeClient(event) => event.event_type(), - IbcEvent::OpenInitConnection(event) => event.event_type(), - IbcEvent::OpenTryConnection(event) => event.event_type(), - IbcEvent::OpenAckConnection(event) => event.event_type(), - IbcEvent::OpenConfirmConnection(event) => event.event_type(), IbcEvent::OpenInitChannel(event) => event.event_type(), IbcEvent::OpenTryChannel(event) => event.event_type(), IbcEvent::OpenAckChannel(event) => event.event_type(), diff --git a/ibc-eureka-core/ics25-handler/types/src/msgs.rs b/ibc-eureka-core/ics25-handler/types/src/msgs.rs index e615328d9..8745e634c 100644 --- a/ibc-eureka-core/ics25-handler/types/src/msgs.rs +++ b/ibc-eureka-core/ics25-handler/types/src/msgs.rs @@ -1,10 +1,6 @@ use ibc_eureka_core_channel_types::msgs::{ - ChannelMsg, MsgAcknowledgement, MsgChannelCloseConfirm, MsgChannelCloseInit, MsgChannelOpenAck, - MsgChannelOpenConfirm, MsgChannelOpenInit, MsgChannelOpenTry, MsgRecvPacket, MsgTimeout, - MsgTimeoutOnClose, PacketMsg, ACKNOWLEDGEMENT_TYPE_URL, CHAN_CLOSE_CONFIRM_TYPE_URL, - CHAN_CLOSE_INIT_TYPE_URL, CHAN_OPEN_ACK_TYPE_URL, CHAN_OPEN_CONFIRM_TYPE_URL, - CHAN_OPEN_INIT_TYPE_URL, CHAN_OPEN_TRY_TYPE_URL, RECV_PACKET_TYPE_URL, - TIMEOUT_ON_CLOSE_TYPE_URL, TIMEOUT_TYPE_URL, + MsgAcknowledgement, MsgRecvPacket, MsgTimeout, PacketMsg, ACKNOWLEDGEMENT_TYPE_URL, + RECV_PACKET_TYPE_URL, TIMEOUT_TYPE_URL, }; #[allow(deprecated)] use ibc_eureka_core_client_types::msgs::{ @@ -12,11 +8,6 @@ use ibc_eureka_core_client_types::msgs::{ CREATE_CLIENT_TYPE_URL, SUBMIT_MISBEHAVIOUR_TYPE_URL, UPDATE_CLIENT_TYPE_URL, UPGRADE_CLIENT_TYPE_URL, }; -use ibc_eureka_core_connection_types::msgs::{ - ConnectionMsg, MsgConnectionOpenAck, MsgConnectionOpenConfirm, MsgConnectionOpenInit, - MsgConnectionOpenTry, CONN_OPEN_ACK_TYPE_URL, CONN_OPEN_CONFIRM_TYPE_URL, - CONN_OPEN_INIT_TYPE_URL, CONN_OPEN_TRY_TYPE_URL, -}; use ibc_eureka_core_host_types::error::DecodingError; use ibc_primitives::prelude::*; use ibc_proto::google::protobuf::Any; @@ -31,8 +22,7 @@ use ibc_proto::Protobuf; #[derive(Clone, Debug, PartialEq, Eq, derive_more::From)] pub enum MsgEnvelope { Client(ClientMsg), - Connection(ConnectionMsg), - Channel(ChannelMsg), + // Channel(ChannelMsg), Packet(PacketMsg), } @@ -61,51 +51,6 @@ impl TryFrom for MsgEnvelope { Ok(MsgEnvelope::Client(ClientMsg::Misbehaviour(domain_msg))) } - // ICS03 - CONN_OPEN_INIT_TYPE_URL => { - let domain_msg = MsgConnectionOpenInit::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Connection(ConnectionMsg::OpenInit(domain_msg))) - } - CONN_OPEN_TRY_TYPE_URL => { - let domain_msg = MsgConnectionOpenTry::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Connection(ConnectionMsg::OpenTry(domain_msg))) - } - CONN_OPEN_ACK_TYPE_URL => { - let domain_msg = MsgConnectionOpenAck::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Connection(ConnectionMsg::OpenAck(domain_msg))) - } - CONN_OPEN_CONFIRM_TYPE_URL => { - let domain_msg = MsgConnectionOpenConfirm::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Connection(ConnectionMsg::OpenConfirm( - domain_msg, - ))) - } - - // ICS04 channel messages - CHAN_OPEN_INIT_TYPE_URL => { - let domain_msg = MsgChannelOpenInit::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Channel(ChannelMsg::OpenInit(domain_msg))) - } - CHAN_OPEN_TRY_TYPE_URL => { - let domain_msg = MsgChannelOpenTry::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Channel(ChannelMsg::OpenTry(domain_msg))) - } - CHAN_OPEN_ACK_TYPE_URL => { - let domain_msg = MsgChannelOpenAck::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Channel(ChannelMsg::OpenAck(domain_msg))) - } - CHAN_OPEN_CONFIRM_TYPE_URL => { - let domain_msg = MsgChannelOpenConfirm::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Channel(ChannelMsg::OpenConfirm(domain_msg))) - } - CHAN_CLOSE_INIT_TYPE_URL => { - let domain_msg = MsgChannelCloseInit::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Channel(ChannelMsg::CloseInit(domain_msg))) - } - CHAN_CLOSE_CONFIRM_TYPE_URL => { - let domain_msg = MsgChannelCloseConfirm::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Channel(ChannelMsg::CloseConfirm(domain_msg))) - } // ICS04 packet messages RECV_PACKET_TYPE_URL => { let domain_msg = MsgRecvPacket::decode_vec(&any_msg.value)?; @@ -119,11 +64,6 @@ impl TryFrom for MsgEnvelope { let domain_msg = MsgTimeout::decode_vec(&any_msg.value)?; Ok(MsgEnvelope::Packet(PacketMsg::Timeout(domain_msg))) } - TIMEOUT_ON_CLOSE_TYPE_URL => { - let domain_msg = MsgTimeoutOnClose::decode_vec(&any_msg.value)?; - Ok(MsgEnvelope::Packet(PacketMsg::TimeoutOnClose(domain_msg))) - } - _ => Err(DecodingError::UnknownTypeUrl(any_msg.type_url))?, } } diff --git a/ibc-eureka-core/ics26-routing/src/module.rs b/ibc-eureka-core/ics26-routing/src/module.rs index c488a5c04..714bcdccf 100644 --- a/ibc-eureka-core/ics26-routing/src/module.rs +++ b/ibc-eureka-core/ics26-routing/src/module.rs @@ -2,11 +2,10 @@ use core::fmt::Debug; use ibc_eureka_core_channel_types::acknowledgement::Acknowledgement; -use ibc_eureka_core_channel_types::channel::{Counterparty, Order}; use ibc_eureka_core_channel_types::error::ChannelError; use ibc_eureka_core_channel_types::packet::Packet; use ibc_eureka_core_channel_types::Version; -use ibc_eureka_core_host_types::identifiers::{ChannelId, ConnectionId, PortId}; +use ibc_eureka_core_host_types::identifiers::{ChannelId, PortId}; use ibc_eureka_core_router_types::module::ModuleExtras; use ibc_primitives::prelude::*; use ibc_primitives::Signer; @@ -14,41 +13,29 @@ use ibc_primitives::Signer; pub trait Module: Debug { fn on_chan_open_init_validate( &self, - order: Order, - connection_hops: &[ConnectionId], port_id: &PortId, channel_id: &ChannelId, - counterparty: &Counterparty, version: &Version, ) -> Result; fn on_chan_open_init_execute( &mut self, - order: Order, - connection_hops: &[ConnectionId], port_id: &PortId, channel_id: &ChannelId, - counterparty: &Counterparty, version: &Version, ) -> Result<(ModuleExtras, Version), ChannelError>; fn on_chan_open_try_validate( &self, - order: Order, - connection_hops: &[ConnectionId], port_id: &PortId, channel_id: &ChannelId, - counterparty: &Counterparty, counterparty_version: &Version, ) -> Result; fn on_chan_open_try_execute( &mut self, - order: Order, - connection_hops: &[ConnectionId], port_id: &PortId, channel_id: &ChannelId, - counterparty: &Counterparty, counterparty_version: &Version, ) -> Result<(ModuleExtras, Version), ChannelError>; diff --git a/ibc-eureka-core/src/lib.rs b/ibc-eureka-core/src/lib.rs index 2b9b50a86..38d2097bd 100644 --- a/ibc-eureka-core/src/lib.rs +++ b/ibc-eureka-core/src/lib.rs @@ -30,12 +30,6 @@ pub mod client { pub use ibc_eureka_core_client::*; } -/// Re-exports ICS-03 implementation from the `ibc-eureka-core-connection` crate -pub mod connection { - #[doc(inline)] - pub use ibc_eureka_core_connection::*; -} - /// Re-exports ICS-04 implementation from the `ibc-eureka-core-channel` crate pub mod channel { #[doc(inline)]