From 256e50deec353a832b87d3c735d68ff446c2f9d9 Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Fri, 24 Nov 2023 22:45:23 +0100 Subject: [PATCH 1/7] update ibc --- Cargo.toml | 4 +- .../solana-ibc/programs/solana-ibc/Cargo.toml | 6 +- .../programs/solana-ibc/src/client_state.rs | 227 +++++++-------- .../solana-ibc/src/consensus_state.rs | 96 +++---- .../programs/solana-ibc/src/error.rs | 4 +- .../programs/solana-ibc/src/events.rs | 4 +- .../solana-ibc/src/execution_context.rs | 128 ++++----- .../programs/solana-ibc/src/host.rs | 17 +- .../solana-ibc/programs/solana-ibc/src/ibc.rs | 80 ++++++ .../solana-ibc/programs/solana-ibc/src/lib.rs | 40 +-- .../programs/solana-ibc/src/storage.rs | 16 +- .../programs/solana-ibc/src/storage/ids.rs | 6 +- .../programs/solana-ibc/src/tests.rs | 69 +++-- .../programs/solana-ibc/src/transfer/impls.rs | 22 +- .../programs/solana-ibc/src/transfer/mod.rs | 260 +++++++++--------- .../solana-ibc/src/validation_context.rs | 169 ++++++------ 16 files changed, 589 insertions(+), 559 deletions(-) create mode 100644 solana/solana-ibc/programs/solana-ibc/src/ibc.rs diff --git a/Cargo.toml b/Cargo.toml index 16ca351a..19c4c4ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,8 +30,8 @@ borsh = { version = "0.10.3", default-features = false } bytemuck = { version = "1.14", default-features = false } derive_more = "0.99.17" hex-literal = "0.4.1" -ibc = { version = "0.47.0", default-features = false, features = ["borsh", "serde"] } -ibc-proto = { version = "0.37.1", default-features = false } +ibc = { version = "0.48.0", default-features = false, features = ["borsh", "serde"] } +ibc-testkit = { version = "0.48.0", default-features = false } pretty_assertions = "1.4.0" rand = { version = "0.8.5" } serde = "1" diff --git a/solana/solana-ibc/programs/solana-ibc/Cargo.toml b/solana/solana-ibc/programs/solana-ibc/Cargo.toml index 73886b13..157d2117 100644 --- a/solana/solana-ibc/programs/solana-ibc/Cargo.toml +++ b/solana/solana-ibc/programs/solana-ibc/Cargo.toml @@ -13,14 +13,14 @@ no-entrypoint = [] no-idl = [] no-log-ix-name = [] cpi = ["no-entrypoint"] -mocks = ["ibc/mocks", "ibc/std"] +mocks = ["ibc-testkit"] [dependencies] anchor-lang.workspace = true base64.workspace = true bytemuck.workspace = true derive_more.workspace = true -ibc-proto.workspace = true +ibc-testkit = { workspace = true, optional = true } ibc.workspace = true serde.workspace = true serde_json.workspace = true @@ -35,4 +35,4 @@ stdx.workspace = true [dev-dependencies] anchor-client.workspace = true anyhow.workspace = true -ibc = { workspace = true, features = ["mocks"] } +ibc-testkit.workspace = true diff --git a/solana/solana-ibc/programs/solana-ibc/src/client_state.rs b/solana/solana-ibc/programs/solana-ibc/src/client_state.rs index 099a8c39..1d34acc0 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/client_state.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/client_state.rs @@ -1,40 +1,22 @@ use anchor_lang::prelude::borsh; use anchor_lang::prelude::borsh::maybestd::io; use anchor_lang::solana_program::msg; -use ibc::clients::ics07_tendermint::client_state::ClientState as TmClientState; -use ibc::core::ics02_client::client_state::{ - ClientStateCommon, ClientStateExecution, ClientStateValidation, Status, - UpdateKind, -}; -use ibc::core::ics02_client::client_type::ClientType; -use ibc::core::ics02_client::error::ClientError; -use ibc::core::ics23_commitment::commitment::{ - CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, -}; -use ibc::core::ics24_host::identifier::ClientId; -use ibc::core::ics24_host::path::{ClientConsensusStatePath, Path}; -use ibc::core::timestamp::Timestamp; -use ibc::core::{ContextError, ValidationContext}; -#[cfg(any(test, feature = "mocks"))] -use ibc::mock::client_state::{MockClientContext, MockClientState}; -use ibc::Height; -use ibc_proto::google::protobuf::Any; -use ibc_proto::ibc::lightclients::tendermint::v1::ClientState as RawTmClientState; -#[cfg(any(test, feature = "mocks"))] -use ibc_proto::ibc::mock::ClientState as RawMockClientState; -use ibc_proto::protobuf::Protobuf; use crate::consensus_state::AnyConsensusState; +use crate::ibc; +use crate::ibc::{ + ClientStateCommon, ClientStateExecution, ClientStateValidation, Protobuf, +}; use crate::storage::IbcStorage; #[derive(Clone, Debug, PartialEq, derive_more::From, derive_more::TryInto)] pub enum AnyClientState { - Tendermint(TmClientState), + Tendermint(ibc::tm::ClientState), #[cfg(any(test, feature = "mocks"))] - Mock(MockClientState), + Mock(ibc::mock::MockClientState), } -impl Protobuf for AnyClientState {} +impl ibc::Protobuf for AnyClientState {} /// Discriminants used when borsh-encoding [`AnyClientState`]. #[derive(Clone, Copy, PartialEq, Eq, strum::FromRepr)] @@ -60,12 +42,10 @@ impl AnyClientStateTag { impl AnyClientState { /// Protobuf type URL for Tendermint client state used in Any message. - const TENDERMINT_TYPE: &'static str = - ibc::clients::ics07_tendermint::client_state::TENDERMINT_CLIENT_STATE_TYPE_URL; + const TENDERMINT_TYPE: &str = ibc::tm::TENDERMINT_CLIENT_STATE_TYPE_URL; #[cfg(any(test, feature = "mocks"))] /// Protobuf type URL for Mock client state used in Any message. - const MOCK_TYPE: &'static str = - ibc::mock::client_state::MOCK_CLIENT_STATE_TYPE_URL; + const MOCK_TYPE: &'static str = ibc::mock::MOCK_CLIENT_STATE_TYPE_URL; /// Encodes the payload and returns discriminants that allow decoding the /// value later. @@ -79,18 +59,18 @@ impl AnyClientState { /// in Any protobuf message. To decode value [`Self::from_tagged`] can be /// used potentially going through [`AnyClientStateTag::from_type_url`] if /// necessary. - fn to_any(&self) -> (AnyClientStateTag, &str, Vec) { + fn into_any(self) -> (AnyClientStateTag, &'static str, Vec) { match self { AnyClientState::Tendermint(state) => ( AnyClientStateTag::Tendermint, Self::TENDERMINT_TYPE, - Protobuf::::encode_vec(state), + Protobuf::::encode_vec(state), ), #[cfg(any(test, feature = "mocks"))] AnyClientState::Mock(state) => ( AnyClientStateTag::Mock, Self::MOCK_TYPE, - Protobuf::::encode_vec(state), + Protobuf::::encode_vec(state), ), } } @@ -99,45 +79,45 @@ impl AnyClientState { fn from_tagged( tag: AnyClientStateTag, value: Vec, - ) -> Result { + ) -> Result { match tag { AnyClientStateTag::Tendermint => { - Protobuf::::decode_vec(&value) + Protobuf::::decode_vec(&value) .map(Self::Tendermint) } #[cfg(any(test, feature = "mocks"))] AnyClientStateTag::Mock => { - Protobuf::::decode_vec(&value) + Protobuf::::decode_vec(&value) .map(Self::Mock) } } } } -impl From for Any { +impl From for ibc::Any { fn from(value: AnyClientState) -> Self { - let (_, type_url, value) = value.to_any(); - Any { type_url: type_url.into(), value } + let (_, type_url, value) = value.into_any(); + ibc::Any { type_url: type_url.into(), value } } } -impl TryFrom for AnyClientState { - type Error = ClientError; +impl TryFrom for AnyClientState { + type Error = ibc::ClientError; - fn try_from(raw: Any) -> Result { + fn try_from(raw: ibc::Any) -> Result { let tag = AnyClientStateTag::from_type_url(raw.type_url.as_str()) - .ok_or(ClientError::UnknownClientStateType { + .ok_or(ibc::ClientError::UnknownClientStateType { client_state_type: raw.type_url, })?; Self::from_tagged(tag, raw.value).map_err(|err| { - ClientError::ClientSpecific { description: err.to_string() } + ibc::ClientError::ClientSpecific { description: err.to_string() } }) } } impl borsh::BorshSerialize for AnyClientState { fn serialize(&self, wr: &mut W) -> io::Result<()> { - let (tag, _, value) = self.to_any(); + let (tag, _, value) = self.clone().into_any(); (tag as u8, value).serialize(wr) } } @@ -162,10 +142,10 @@ impl ClientStateValidation> for AnyClientState { fn verify_client_message( &self, ctx: &IbcStorage, - client_id: &ClientId, - client_message: Any, - update_kind: &UpdateKind, - ) -> Result<(), ClientError> { + client_id: &ibc::ClientId, + client_message: ibc::Any, + update_kind: &ibc::UpdateKind, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => client_state .verify_client_message( @@ -188,10 +168,10 @@ impl ClientStateValidation> for AnyClientState { fn check_for_misbehaviour( &self, ctx: &IbcStorage, - client_id: &ClientId, - client_message: Any, - update_kind: &UpdateKind, - ) -> Result { + client_id: &ibc::ClientId, + client_message: ibc::Any, + update_kind: &ibc::UpdateKind, + ) -> Result { match self { AnyClientState::Tendermint(client_state) => client_state .check_for_misbehaviour( @@ -213,23 +193,22 @@ impl ClientStateValidation> for AnyClientState { fn status( &self, - _ctx: &IbcStorage, - _client_id: &ClientId, - ) -> Result { - let is_frozen = match self { - AnyClientState::Tendermint(state) => state.is_frozen(), + ctx: &IbcStorage, + client_id: &ibc::ClientId, + ) -> Result { + match self { + AnyClientState::Tendermint(state) => state.status(ctx, client_id), #[cfg(any(test, feature = "mocks"))] - AnyClientState::Mock(state) => state.is_frozen(), - }; - Ok(if is_frozen { Status::Frozen } else { Status::Active }) + AnyClientState::Mock(state) => state.status(ctx, client_id), + } } } impl ClientStateCommon for AnyClientState { fn verify_consensus_state( &self, - consensus_state: Any, - ) -> Result<(), ClientError> { + consensus_state: ibc::Any, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => { client_state.verify_consensus_state(consensus_state) @@ -241,7 +220,7 @@ impl ClientStateCommon for AnyClientState { } } - fn client_type(&self) -> ClientType { + fn client_type(&self) -> ibc::ClientType { match self { AnyClientState::Tendermint(client_state) => { client_state.client_type() @@ -253,7 +232,7 @@ impl ClientStateCommon for AnyClientState { } } - fn latest_height(&self) -> Height { + fn latest_height(&self) -> ibc::Height { msg!("Fetching the height"); let height = match self { AnyClientState::Tendermint(client_state) => { @@ -274,8 +253,8 @@ impl ClientStateCommon for AnyClientState { fn validate_proof_height( &self, - proof_height: Height, - ) -> Result<(), ClientError> { + proof_height: ibc::Height, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => { client_state.validate_proof_height(proof_height) @@ -289,12 +268,12 @@ impl ClientStateCommon for AnyClientState { fn verify_upgrade_client( &self, - upgraded_client_state: Any, - upgraded_consensus_state: Any, - proof_upgrade_client: CommitmentProofBytes, - proof_upgrade_consensus_state: CommitmentProofBytes, - root: &CommitmentRoot, - ) -> Result<(), ClientError> { + upgraded_client_state: ibc::Any, + upgraded_consensus_state: ibc::Any, + proof_upgrade_client: ibc::CommitmentProofBytes, + proof_upgrade_consensus_state: ibc::CommitmentProofBytes, + root: &ibc::CommitmentRoot, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => client_state .verify_upgrade_client( @@ -318,12 +297,12 @@ impl ClientStateCommon for AnyClientState { fn verify_membership( &self, - prefix: &CommitmentPrefix, - proof: &CommitmentProofBytes, - root: &CommitmentRoot, - path: Path, + prefix: &ibc::CommitmentPrefix, + proof: &ibc::CommitmentProofBytes, + root: &ibc::CommitmentRoot, + path: ibc::path::Path, value: Vec, - ) -> Result<(), ClientError> { + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => { client_state.verify_membership(prefix, proof, root, path, value) @@ -337,11 +316,11 @@ impl ClientStateCommon for AnyClientState { fn verify_non_membership( &self, - prefix: &CommitmentPrefix, - proof: &CommitmentProofBytes, - root: &CommitmentRoot, - path: Path, - ) -> Result<(), ClientError> { + prefix: &ibc::CommitmentPrefix, + proof: &ibc::CommitmentProofBytes, + root: &ibc::CommitmentRoot, + path: ibc::path::Path, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => { client_state.verify_non_membership(prefix, proof, root, path) @@ -358,9 +337,9 @@ impl ClientStateExecution> for AnyClientState { fn initialise( &self, ctx: &mut IbcStorage, - client_id: &ClientId, - consensus_state: Any, - ) -> Result<(), ClientError> { + client_id: &ibc::ClientId, + consensus_state: ibc::Any, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => { client_state.initialise(ctx, client_id, consensus_state) @@ -375,9 +354,9 @@ impl ClientStateExecution> for AnyClientState { fn update_state( &self, ctx: &mut IbcStorage, - client_id: &ClientId, - header: Any, - ) -> Result, ClientError> { + client_id: &ibc::ClientId, + header: ibc::Any, + ) -> Result, ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => { client_state.update_state(ctx, client_id, header) @@ -392,10 +371,10 @@ impl ClientStateExecution> for AnyClientState { fn update_state_on_misbehaviour( &self, ctx: &mut IbcStorage, - client_id: &ClientId, - client_message: Any, - update_kind: &UpdateKind, - ) -> Result<(), ClientError> { + client_id: &ibc::ClientId, + client_message: ibc::Any, + update_kind: &ibc::UpdateKind, + ) -> Result<(), ibc::ClientError> { match self { AnyClientState::Tendermint(client_state) => client_state .update_state_on_misbehaviour( @@ -418,10 +397,10 @@ impl ClientStateExecution> for AnyClientState { fn update_state_on_upgrade( &self, ctx: &mut IbcStorage, - client_id: &ClientId, - upgraded_client_state: Any, - upgraded_consensus_state: Any, - ) -> Result { + client_id: &ibc::ClientId, + upgraded_client_state: ibc::Any, + upgraded_consensus_state: ibc::Any, + ) -> Result { match self { AnyClientState::Tendermint(client_state) => client_state .update_state_on_upgrade( @@ -442,22 +421,22 @@ impl ClientStateExecution> for AnyClientState { } } -impl ibc::clients::ics07_tendermint::CommonContext for IbcStorage<'_, '_> { +impl ibc::tm::CommonContext for IbcStorage<'_, '_> { type ConversionError = &'static str; type AnyConsensusState = AnyConsensusState; fn consensus_state( &self, - client_cons_state_path: &ClientConsensusStatePath, - ) -> Result { - ValidationContext::consensus_state(self, client_cons_state_path) + client_cons_state_path: &ibc::path::ClientConsensusStatePath, + ) -> Result { + ibc::ValidationContext::consensus_state(self, client_cons_state_path) } fn consensus_state_heights( &self, - client_id: &ClientId, - ) -> Result, ContextError> { + client_id: &ibc::ClientId, + ) -> Result, ibc::ContextError> { Ok(self .borrow() .private @@ -468,50 +447,50 @@ impl ibc::clients::ics07_tendermint::CommonContext for IbcStorage<'_, '_> { .collect()) } - fn host_timestamp(&self) -> Result { - ValidationContext::host_timestamp(self) + fn host_timestamp(&self) -> Result { + ibc::ValidationContext::host_timestamp(self) } - fn host_height(&self) -> Result { - ValidationContext::host_height(self) + fn host_height(&self) -> Result { + ibc::ValidationContext::host_height(self) } } #[cfg(any(test, feature = "mocks"))] -impl MockClientContext for IbcStorage<'_, '_> { +impl ibc::mock::MockClientContext for IbcStorage<'_, '_> { type ConversionError = &'static str; type AnyConsensusState = AnyConsensusState; fn consensus_state( &self, - client_cons_state_path: &ClientConsensusStatePath, - ) -> Result { - ValidationContext::consensus_state(self, client_cons_state_path) + client_cons_state_path: &ibc::path::ClientConsensusStatePath, + ) -> Result { + ibc::ValidationContext::consensus_state(self, client_cons_state_path) } - fn host_timestamp(&self) -> Result { - ValidationContext::host_timestamp(self) + fn host_timestamp(&self) -> Result { + ibc::ValidationContext::host_timestamp(self) } - fn host_height(&self) -> Result { - ValidationContext::host_height(self) + fn host_height(&self) -> Result { + ibc::ValidationContext::host_height(self) } } -impl ibc::clients::ics07_tendermint::ValidationContext for IbcStorage<'_, '_> { +impl ibc::tm::ValidationContext for IbcStorage<'_, '_> { fn next_consensus_state( &self, - client_id: &ClientId, - height: &Height, - ) -> Result, ContextError> { + client_id: &ibc::ClientId, + height: &ibc::Height, + ) -> Result, ibc::ContextError> { self.get_consensus_state(client_id, height, Direction::Next) } fn prev_consensus_state( &self, - client_id: &ClientId, - height: &Height, - ) -> Result, ContextError> { + client_id: &ibc::ClientId, + height: &ibc::Height, + ) -> Result, ibc::ContextError> { self.get_consensus_state(client_id, height, Direction::Prev) } } @@ -525,10 +504,10 @@ enum Direction { impl IbcStorage<'_, '_> { fn get_consensus_state( &self, - client_id: &ClientId, - height: &Height, + client_id: &ibc::ClientId, + height: &ibc::Height, dir: Direction, - ) -> Result, ContextError> { + ) -> Result, ibc::ContextError> { use core::ops::Bound; let pivot = Bound::Excluded(*height); diff --git a/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs b/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs index 27c681a3..a56bb92c 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs @@ -1,28 +1,14 @@ use anchor_lang::prelude::borsh; use anchor_lang::prelude::borsh::maybestd::io; -use ibc::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState; -use ibc::core::ics02_client::consensus_state::ConsensusState; -use ibc::core::ics02_client::error::ClientError; -use ibc::core::ics23_commitment::commitment::CommitmentRoot; -use ibc::core::timestamp::Timestamp; -#[cfg(any(test, feature = "mocks"))] -use ibc::mock::consensus_state::{ - MockConsensusState, MOCK_CONSENSUS_STATE_TYPE_URL, -}; -use ibc_proto::google::protobuf::Any; -use ibc_proto::ibc::lightclients::tendermint::v1::ConsensusState as RawTmConsensusState; -#[cfg(any(test, feature = "mocks"))] -use ibc_proto::ibc::mock::ConsensusState as RawMockConsensusState; -use ibc_proto::protobuf::Protobuf; - -const TENDERMINT_CONSENSUS_STATE_TYPE_URL: &str = - "/ibc.lightclients.tendermint.v1.ConsensusState"; + +use crate::ibc; +use crate::ibc::{ConsensusState, Protobuf}; #[derive(Clone, Debug, PartialEq, derive_more::From, derive_more::TryInto)] pub enum AnyConsensusState { - Tendermint(TmConsensusState), + Tendermint(ibc::tm::ConsensusState), #[cfg(any(test, feature = "mocks"))] - Mock(MockConsensusState), + Mock(ibc::mock::MockConsensusState), } /// Discriminants used when borsh-encoding [`AnyConsensusState`]. @@ -50,12 +36,10 @@ impl AnyConsensusStateTag { impl AnyConsensusState { /// Protobuf type URL for Tendermint client state used in Any message. - const TENDERMINT_TYPE: &'static str = - ibc::clients::ics07_tendermint::consensus_state::TENDERMINT_CONSENSUS_STATE_TYPE_URL; + const TENDERMINT_TYPE: &str = ibc::tm::TENDERMINT_CONSENSUS_STATE_TYPE_URL; #[cfg(any(test, feature = "mocks"))] /// Protobuf type URL for Mock client state used in Any message. - const MOCK_TYPE: &'static str = - ibc::mock::consensus_state::MOCK_CONSENSUS_STATE_TYPE_URL; + const MOCK_TYPE: &str = ibc::mock::MOCK_CONSENSUS_STATE_TYPE_URL; /// Encodes the payload and returns discriminants that allow decoding the /// value later. @@ -69,18 +53,18 @@ impl AnyConsensusState { /// in Any protobuf message. To decode value [`Self::from_tagged`] can be /// used potentially going through [`AnyConsensusStateTag::from_type_url`] if /// necessary. - fn to_any(&self) -> (AnyConsensusStateTag, &str, Vec) { + fn into_any(self) -> (AnyConsensusStateTag, &'static str, Vec) { match self { AnyConsensusState::Tendermint(state) => ( AnyConsensusStateTag::Tendermint, Self::TENDERMINT_TYPE, - Protobuf::::encode_vec(state), + Protobuf::::encode_vec(state), ), #[cfg(any(test, feature = "mocks"))] AnyConsensusState::Mock(state) => ( AnyConsensusStateTag::Mock, Self::MOCK_TYPE, - Protobuf::::encode_vec(state), + Protobuf::::encode_vec(state), ), } } @@ -89,15 +73,15 @@ impl AnyConsensusState { fn from_tagged( tag: AnyConsensusStateTag, value: Vec, - ) -> Result { + ) -> Result { match tag { AnyConsensusStateTag::Tendermint => { - Protobuf::::decode_vec(&value) + Protobuf::::decode_vec(&value) .map(Self::Tendermint) } #[cfg(any(test, feature = "mocks"))] AnyConsensusStateTag::Mock => { - Protobuf::::decode_vec(&value) + Protobuf::::decode_vec(&value) .map(Self::Mock) } } @@ -105,45 +89,47 @@ impl AnyConsensusState { } -impl Protobuf for AnyConsensusState {} +impl Protobuf for AnyConsensusState {} -impl TryFrom for AnyConsensusState { - type Error = ClientError; +impl TryFrom for AnyConsensusState { + type Error = ibc::ClientError; - fn try_from(value: Any) -> Result { + fn try_from(value: ibc::Any) -> Result { match value.type_url.as_str() { - TENDERMINT_CONSENSUS_STATE_TYPE_URL => { - Ok(AnyConsensusState::Tendermint( - Protobuf::::decode_vec(&value.value) - .map_err(|e| ClientError::ClientSpecific { + Self::TENDERMINT_TYPE => Ok(AnyConsensusState::Tendermint( + Protobuf::::decode_vec(&value.value) + .map_err(|e| ibc::ClientError::ClientSpecific { description: e.to_string(), })?, - )) - } + )), #[cfg(any(test, feature = "mocks"))] - MOCK_CONSENSUS_STATE_TYPE_URL => Ok(AnyConsensusState::Mock( - Protobuf::::decode_vec(&value.value) - .map_err(|e| ClientError::ClientSpecific { + Self::MOCK_TYPE => Ok(AnyConsensusState::Mock( + Protobuf::::decode_vec( + &value.value, + ) + .map_err(|e| { + ibc::ClientError::ClientSpecific { description: e.to_string(), - })?, + } + })?, )), - _ => Err(ClientError::UnknownConsensusStateType { + _ => Err(ibc::ClientError::UnknownConsensusStateType { consensus_state_type: value.type_url.clone(), }), } } } -impl From for Any { +impl From for ibc::Any { fn from(value: AnyConsensusState) -> Self { - let (_, type_url, value) = value.to_any(); - Any { type_url: type_url.into(), value } + let (_, type_url, value) = value.into_any(); + ibc::Any { type_url: type_url.into(), value } } } impl borsh::BorshSerialize for AnyConsensusState { fn serialize(&self, wr: &mut W) -> io::Result<()> { - let (tag, _, value) = self.to_any(); + let (tag, _, value) = self.clone().into_any(); (tag as u8, value).serialize(wr) } } @@ -165,7 +151,7 @@ impl borsh::BorshDeserialize for AnyConsensusState { } impl ConsensusState for AnyConsensusState { - fn root(&self) -> &CommitmentRoot { + fn root(&self) -> &ibc::CommitmentRoot { match self { AnyConsensusState::Tendermint(value) => value.root(), #[cfg(any(test, feature = "mocks"))] @@ -173,22 +159,22 @@ impl ConsensusState for AnyConsensusState { } } - fn timestamp(&self) -> Timestamp { + fn timestamp(&self) -> ibc::Timestamp { match self { - AnyConsensusState::Tendermint(value) => value.timestamp(), + AnyConsensusState::Tendermint(value) => value.timestamp().into(), #[cfg(any(test, feature = "mocks"))] AnyConsensusState::Mock(value) => value.timestamp(), } } - fn encode_vec(&self) -> Vec { + fn encode_vec(self) -> Vec { match self { AnyConsensusState::Tendermint(value) => { - ibc::core::ics02_client::consensus_state::ConsensusState::encode_vec(value) - }, + ibc::ConsensusState::encode_vec(value) + } #[cfg(any(test, feature = "mocks"))] AnyConsensusState::Mock(value) => { - ibc::core::ics02_client::consensus_state::ConsensusState::encode_vec(value) + ibc::ConsensusState::encode_vec(value) } } } diff --git a/solana/solana-ibc/programs/solana-ibc/src/error.rs b/solana/solana-ibc/programs/solana-ibc/src/error.rs index c62d4231..f6c45343 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/error.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/error.rs @@ -11,7 +11,7 @@ pub(crate) enum Error { Internal(&'static str), /// Error handling an IBC request. - RouterError(ibc::core::RouterError), + ContextError(crate::ibc::ContextError), /// Guest block hasn’t been initialised yet. ChainNotInitialised, @@ -67,7 +67,7 @@ impl core::fmt::Display for Error { fn fmt(&self, fmtr: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Internal(msg) => fmtr.write_str(msg.as_ref()), - Self::RouterError(err) => err.fmt(fmtr), + Self::ContextError(err) => err.fmt(fmtr), err => fmtr.write_str(&err.name()), } } diff --git a/solana/solana-ibc/programs/solana-ibc/src/events.rs b/solana/solana-ibc/programs/solana-ibc/src/events.rs index 5b845a97..4a217c56 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/events.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/events.rs @@ -2,12 +2,14 @@ use anchor_lang::prelude::borsh; use anchor_lang::solana_program; use lib::hash::CryptoHash; +use crate::ibc; + /// Possible events emitted by the smart contract. /// /// The events are logged in their borsh-serialised form. #[derive(Clone, PartialEq, Eq, borsh::BorshSerialize, derive_more::From)] pub enum Event<'a> { - IbcEvent(ibc::core::events::IbcEvent), + IbcEvent(ibc::IbcEvent), Initialised(Initialised<'a>), NewBlock(NewBlock<'a>), BlockSigned(BlockSigned<'a>), diff --git a/solana/solana-ibc/programs/solana-ibc/src/execution_context.rs b/solana/solana-ibc/programs/solana-ibc/src/execution_context.rs index c303c8e2..ca7a7c62 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/execution_context.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/execution_context.rs @@ -2,42 +2,24 @@ use alloc::collections::BTreeMap; use anchor_lang::prelude::borsh; use anchor_lang::solana_program::msg; -use ibc::core::events::IbcEvent; -use ibc::core::ics02_client::error::ClientError; -use ibc::core::ics02_client::ClientExecutionContext; -use ibc::core::ics03_connection::connection::ConnectionEnd; -use ibc::core::ics03_connection::error::ConnectionError; -use ibc::core::ics04_channel::channel::ChannelEnd; -use ibc::core::ics04_channel::commitment::{ - AcknowledgementCommitment, PacketCommitment, -}; -use ibc::core::ics04_channel::packet::{Receipt, Sequence}; -use ibc::core::ics24_host::identifier::{ClientId, ConnectionId}; -use ibc::core::ics24_host::path::{ - AckPath, ChannelEndPath, ClientConnectionPath, ClientConsensusStatePath, - ClientStatePath, CommitmentPath, ConnectionPath, ReceiptPath, SeqAckPath, - SeqRecvPath, SeqSendPath, -}; -use ibc::core::timestamp::Timestamp; -use ibc::core::{ContextError, ExecutionContext}; -use ibc::Height; use lib::hash::CryptoHash; use crate::client_state::AnyClientState; use crate::consensus_state::AnyConsensusState; +use crate::ibc; use crate::storage::trie_key::TrieKey; use crate::storage::{self, ids, IbcStorage}; -type Result = core::result::Result; +type Result = core::result::Result; -impl ClientExecutionContext for IbcStorage<'_, '_> { +impl ibc::ClientExecutionContext for IbcStorage<'_, '_> { type V = Self; // ClientValidationContext type AnyClientState = AnyClientState; type AnyConsensusState = AnyConsensusState; fn store_client_state( &mut self, - path: ClientStatePath, + path: ibc::path::ClientStatePath, state: Self::AnyClientState, ) -> Result { msg!("store_client_state({}, {:?})", path, state); @@ -56,11 +38,12 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { fn store_consensus_state( &mut self, - path: ClientConsensusStatePath, + path: ibc::path::ClientConsensusStatePath, state: Self::AnyConsensusState, ) -> Result { msg!("store_consensus_state({}, {:?})", path, state); - let height = Height::new(path.epoch, path.height)?; + let height = + ibc::Height::new(path.revision_number, path.revision_height)?; let mut store = self.borrow_mut(); let mut client = store.private.client_mut(&path.client_id, false)?; let serialised = storage::Serialised::new(&state)?; @@ -73,10 +56,11 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { fn delete_consensus_state( &mut self, - path: ClientConsensusStatePath, - ) -> Result<(), ContextError> { + path: ibc::path::ClientConsensusStatePath, + ) -> Result { msg!("delete_consensus_state({})", path); - let height = Height::new(path.epoch, path.height)?; + let height = + ibc::Height::new(path.revision_number, path.revision_height)?; let mut store = self.borrow_mut(); let mut client = store.private.client_mut(&path.client_id, false)?; client.consensus_states.remove(&height); @@ -88,9 +72,9 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { fn delete_update_height( &mut self, - client_id: ClientId, - height: Height, - ) -> Result<(), ContextError> { + client_id: ibc::ClientId, + height: ibc::Height, + ) -> Result { self.borrow_mut() .private .client_mut(&client_id, false)? @@ -101,9 +85,9 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { fn delete_update_time( &mut self, - client_id: ClientId, - height: Height, - ) -> Result<(), ContextError> { + client_id: ibc::ClientId, + height: ibc::Height, + ) -> Result { self.borrow_mut() .private .client_mut(&client_id, false)? @@ -114,10 +98,10 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { fn store_update_time( &mut self, - client_id: ClientId, - height: Height, - timestamp: Timestamp, - ) -> Result<(), ContextError> { + client_id: ibc::ClientId, + height: ibc::Height, + timestamp: ibc::Timestamp, + ) -> Result { msg!("store_update_time({}, {}, {})", client_id, height, timestamp); self.borrow_mut() .private @@ -129,10 +113,10 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { fn store_update_height( &mut self, - client_id: ClientId, - height: Height, - host_height: Height, - ) -> Result<(), ContextError> { + client_id: ibc::ClientId, + height: ibc::Height, + host_height: ibc::Height, + ) -> Result { msg!("store_update_height({}, {}, {})", client_id, height, host_height); self.borrow_mut() .private @@ -143,13 +127,13 @@ impl ClientExecutionContext for IbcStorage<'_, '_> { } } -impl ExecutionContext for IbcStorage<'_, '_> { +impl ibc::ExecutionContext for IbcStorage<'_, '_> { fn increase_client_counter(&mut self) -> Result { Ok(()) } fn store_connection( &mut self, - path: &ConnectionPath, - connection_end: ConnectionEnd, + path: &ibc::path::ConnectionPath, + connection_end: ibc::ConnectionEnd, ) -> Result { use core::cmp::Ordering; @@ -166,7 +150,7 @@ impl ExecutionContext for IbcStorage<'_, '_> { Ordering::Less => connections[index] = serialised, Ordering::Equal => connections.push(serialised), Ordering::Greater => { - return Err(ConnectionError::ConnectionNotFound { + return Err(ibc::ConnectionError::ConnectionNotFound { connection_id: path.0.clone(), } .into()) @@ -183,8 +167,8 @@ impl ExecutionContext for IbcStorage<'_, '_> { fn store_connection_to_client( &mut self, - path: &ClientConnectionPath, - conn_id: ConnectionId, + path: &ibc::path::ClientConnectionPath, + conn_id: ibc::ConnectionId, ) -> Result { msg!("store_connection_to_client({}, {:?})", path, conn_id); let conn_id = ids::ConnectionIdx::try_from(&conn_id)?; @@ -197,23 +181,26 @@ impl ExecutionContext for IbcStorage<'_, '_> { fn store_packet_commitment( &mut self, - path: &CommitmentPath, - commitment: PacketCommitment, + path: &ibc::path::CommitmentPath, + commitment: ibc::PacketCommitment, ) -> Result { msg!("store_packet_commitment({}, {:?})", path, commitment); - // Note: PacketCommitment is always 32-byte long. + // Note: ibc::PacketCommitment is always 32-byte long. self.store_commitment(TrieKey::try_from(path)?, commitment.as_ref()) } - fn delete_packet_commitment(&mut self, path: &CommitmentPath) -> Result { + fn delete_packet_commitment( + &mut self, + path: &ibc::path::CommitmentPath, + ) -> Result { msg!("delete_packet_commitment({})", path); self.delete_commitment(TrieKey::try_from(path)?) } fn store_packet_receipt( &mut self, - path: &ReceiptPath, - Receipt::Ok: Receipt, + path: &ibc::path::ReceiptPath, + ibc::Receipt::Ok: ibc::Receipt, ) -> Result { msg!("store_packet_receipt({}, Ok)", path); self.store_commitment(TrieKey::try_from(path)?, &[0; 32][..]) @@ -221,23 +208,26 @@ impl ExecutionContext for IbcStorage<'_, '_> { fn store_packet_acknowledgement( &mut self, - path: &AckPath, - commitment: AcknowledgementCommitment, + path: &ibc::path::AckPath, + commitment: ibc::AcknowledgementCommitment, ) -> Result { msg!("store_packet_acknowledgement({}, {:?})", path, commitment); - // Note: AcknowledgementCommitment is always 32-byte long. + // Note: ibc::AcknowledgementCommitment is always 32-byte long. self.store_commitment(TrieKey::try_from(path)?, commitment.as_ref()) } - fn delete_packet_acknowledgement(&mut self, path: &AckPath) -> Result { + fn delete_packet_acknowledgement( + &mut self, + path: &ibc::path::AckPath, + ) -> Result { msg!("delete_packet_acknowledgement({})", path); self.delete_commitment(TrieKey::try_from(path)?) } fn store_channel( &mut self, - path: &ChannelEndPath, - channel_end: ChannelEnd, + path: &ibc::path::ChannelEndPath, + channel_end: ibc::ChannelEnd, ) -> Result { msg!("store_channel({}, {:?})", path, channel_end); let port_channel = ids::PortChannelPK::try_from(&path.0, &path.1)?; @@ -252,8 +242,8 @@ impl ExecutionContext for IbcStorage<'_, '_> { fn store_next_sequence_send( &mut self, - path: &SeqSendPath, - seq: Sequence, + path: &ibc::path::SeqSendPath, + seq: ibc::Sequence, ) -> Result { msg!("store_next_sequence_send: path: {}, seq: {}", path, seq); self.store_next_sequence( @@ -265,8 +255,8 @@ impl ExecutionContext for IbcStorage<'_, '_> { fn store_next_sequence_recv( &mut self, - path: &SeqRecvPath, - seq: Sequence, + path: &ibc::path::SeqRecvPath, + seq: ibc::Sequence, ) -> Result { msg!("store_next_sequence_recv: path: {}, seq: {}", path, seq); self.store_next_sequence( @@ -278,8 +268,8 @@ impl ExecutionContext for IbcStorage<'_, '_> { fn store_next_sequence_ack( &mut self, - path: &SeqAckPath, - seq: Sequence, + path: &ibc::path::SeqAckPath, + seq: ibc::Sequence, ) -> Result { msg!("store_next_sequence_ack: path: {}, seq: {}", path, seq); self.store_next_sequence( @@ -299,7 +289,7 @@ impl ExecutionContext for IbcStorage<'_, '_> { Ok(()) } - fn emit_ibc_event(&mut self, event: IbcEvent) -> Result { + fn emit_ibc_event(&mut self, event: ibc::IbcEvent) -> Result { crate::events::emit(event).map_err(error) } @@ -326,7 +316,7 @@ impl storage::IbcStorage<'_, '_> { &mut self, path: storage::trie_key::SequencePath<'_>, index: storage::SequenceTripleIdx, - seq: Sequence, + seq: ibc::Sequence, ) -> Result { let key = ids::PortChannelPK::try_from(path.port_id, path.channel_id)?; let trie_key = TrieKey::for_next_sequence(&key); @@ -364,6 +354,6 @@ impl storage::IbcStorageInner<'_, '_> { } } -fn error(description: impl ToString) -> ContextError { - ClientError::Other { description: description.to_string() }.into() +fn error(description: impl ToString) -> ibc::ContextError { + ibc::ClientError::Other { description: description.to_string() }.into() } diff --git a/solana/solana-ibc/programs/solana-ibc/src/host.rs b/solana/solana-ibc/programs/solana-ibc/src/host.rs index 1b0cb3f5..efb229e9 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/host.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/host.rs @@ -1,6 +1,6 @@ use anchor_lang::solana_program; -use ibc::core::ics02_client::error::ClientError; -use ibc::core::timestamp::Timestamp; + +use crate::ibc; /// Representation of Solana’s head. #[derive(Clone, Copy, Debug)] @@ -21,15 +21,16 @@ impl Head { /// Returns height as an IBC type. #[inline] - pub fn ibc_height(&self) -> Result { + pub fn ibc_height(&self) -> Result { ibc::Height::new(0, self.height.into()) } /// Returns timestamp as an IBC type. #[inline] - pub fn ibc_timestamp(&self) -> Result { - Timestamp::from_nanoseconds(self.timestamp) - .map_err(|err| ClientError::Other { description: err.to_string() }) + pub fn ibc_timestamp(&self) -> Result { + ibc::Timestamp::from_nanoseconds(self.timestamp).map_err(|err| { + ibc::ClientError::Other { description: err.to_string() } + }) } } @@ -55,14 +56,14 @@ impl From for anchor_lang::error::Error { fn from(error: Error) -> Self { Self::from(error.0) } } -impl From for ClientError { +impl From for ibc::ClientError { #[inline] fn from(error: Error) -> Self { Self::Other { description: error.0.to_string() } } } -impl From for ibc::core::ContextError { +impl From for ibc::ContextError { #[inline] fn from(error: Error) -> Self { Self::ClientError(error.into()) } } diff --git a/solana/solana-ibc/programs/solana-ibc/src/ibc.rs b/solana/solana-ibc/programs/solana-ibc/src/ibc.rs new file mode 100644 index 00000000..3abf6e67 --- /dev/null +++ b/solana/solana-ibc/programs/solana-ibc/src/ibc.rs @@ -0,0 +1,80 @@ +pub use ibc::apps; +pub use ibc::core::channel::types::acknowledgement::Acknowledgement; +pub use ibc::core::channel::types::channel::ChannelEnd; +pub use ibc::core::channel::types::commitment::{ + AcknowledgementCommitment, PacketCommitment, +}; +pub use ibc::core::channel::types::error::{ChannelError, PacketError}; +pub use ibc::core::channel::types::msgs::PacketMsg; +pub use ibc::core::channel::types::packet::{Packet, Receipt}; +pub use ibc::core::channel::types::Version; +pub use ibc::core::client::context::client_state::{ + ClientStateCommon, ClientStateExecution, ClientStateValidation, +}; +pub use ibc::core::client::context::consensus_state::ConsensusState; +pub use ibc::core::client::context::types::error::ClientError; +pub use ibc::core::client::context::types::msgs::{ClientMsg, MsgCreateClient}; +pub use ibc::core::client::context::{ + ClientExecutionContext, ClientValidationContext, +}; +pub use ibc::core::client::types::{Height, Status, UpdateKind}; +pub use ibc::core::commitment_types::commitment::{ + CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, +}; +pub use ibc::core::connection::types::error::ConnectionError; +pub use ibc::core::connection::types::msgs::{ + ConnectionMsg, MsgConnectionOpenInit, +}; +pub use ibc::core::connection::types::ConnectionEnd; +pub use ibc::core::handler::types::error::ContextError; +pub use ibc::core::handler::types::events::IbcEvent; +pub use ibc::core::handler::types::msgs::MsgEnvelope; +pub use ibc::core::host::types::identifiers::{ + ChannelId, ClientId, ClientType, ConnectionId, PortId, Sequence, +}; +pub use ibc::core::host::types::path; +pub use ibc::core::host::{ExecutionContext, ValidationContext}; +pub use ibc::core::router::module::Module; +pub use ibc::core::router::router::Router; +pub use ibc::core::router::types::error::RouterError; +pub use ibc::core::router::types::module::{ModuleExtras, ModuleId}; +pub use ibc::primitives::{Signer, Timestamp}; + +pub mod connection { + pub use ibc::core::connection::types::version::{ + get_compatible_versions, pick_version, Version, + }; + pub use ibc::core::connection::types::Counterparty; +} +pub use ibc::primitives::proto::{Any, Protobuf}; + +pub mod channel { + pub use ibc::core::channel::types::channel::{Counterparty, Order}; +} + +#[cfg(any(test, feature = "mocks"))] +pub mod mock { + pub use ibc_testkit::testapp::ibc::clients::mock::client_state::{ + MockClientContext, MockClientState, MOCK_CLIENT_STATE_TYPE_URL, + }; + pub use ibc_testkit::testapp::ibc::clients::mock::consensus_state::{ + MockConsensusState, MOCK_CONSENSUS_STATE_TYPE_URL, + }; + pub use ibc_testkit::testapp::ibc::clients::mock::proto::{ + ClientState as ClientStatePB, ConsensusState as ConsensusStatePB, + }; +} + +pub mod tm { + pub use ibc::clients::tendermint::client_state::ClientState; + pub use ibc::clients::tendermint::consensus_state::ConsensusState; + pub use ibc::clients::tendermint::context::{ + CommonContext, ValidationContext, + }; + pub use ibc::clients::tendermint::types::proto::v1::{ + ClientState as ClientStatePB, ConsensusState as ConsensusStatePB, + }; + pub use ibc::clients::tendermint::types::{ + TENDERMINT_CLIENT_STATE_TYPE_URL, TENDERMINT_CONSENSUS_STATE_TYPE_URL, + }; +} diff --git a/solana/solana-ibc/programs/solana-ibc/src/lib.rs b/solana/solana-ibc/programs/solana-ibc/src/lib.rs index 30c98617..e92383f7 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/lib.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/lib.rs @@ -7,9 +7,6 @@ extern crate alloc; use anchor_lang::prelude::*; use anchor_lang::solana_program; -use ibc::core::ics24_host::identifier::PortId; -use ibc::core::router::{Module, ModuleId, Router}; -use ibc::core::MsgEnvelope; pub const CHAIN_SEED: &[u8] = b"chain"; pub const PACKET_SEED: &[u8] = b"packet"; @@ -26,6 +23,7 @@ mod error; pub mod events; mod execution_context; mod host; +mod ibc; pub mod storage; #[cfg(test)] mod tests; @@ -108,7 +106,7 @@ pub mod solana_ibc { pub fn deliver( ctx: Context, - message: ibc::core::MsgEnvelope, + message: ibc::MsgEnvelope, ) -> Result<()> { msg!("Called deliver method: {:?}", message); let _sender = ctx.accounts.sender.to_account_info(); @@ -133,11 +131,15 @@ pub mod solana_ibc { { let mut router = store.clone(); - ibc::core::dispatch(&mut store, &mut router, message.clone()) - .map_err(error::Error::RouterError) - .map_err(|err| error!((&err)))?; + ::ibc::core::entrypoint::dispatch( + &mut store, + &mut router, + message.clone(), + ) + .map_err(error::Error::ContextError) + .map_err(|err| error!((&err)))?; } - if let MsgEnvelope::Packet(packet) = message { + if let ibc::MsgEnvelope::Packet(packet) = message { // store the packet if not exists // TODO(dhruvja) Store in a PDA with channelId, portId and Sequence let mut store = store.borrow_mut(); @@ -230,32 +232,34 @@ pub struct Deliver<'info> { system_program: Program<'info, System>, } -impl Router for storage::IbcStorage<'_, '_> { +impl ibc::Router for storage::IbcStorage<'_, '_> { // - fn get_route(&self, module_id: &ModuleId) -> Option<&dyn Module> { + fn get_route(&self, module_id: &ibc::ModuleId) -> Option<&dyn ibc::Module> { let module_id = core::borrow::Borrow::borrow(module_id); match module_id { - ibc::applications::transfer::MODULE_ID_STR => Some(self), + ibc::apps::transfer::types::MODULE_ID_STR => Some(self), _ => None, } } // fn get_route_mut( &mut self, - module_id: &ModuleId, - ) -> Option<&mut dyn Module> { + module_id: &ibc::ModuleId, + ) -> Option<&mut dyn ibc::Module> { let module_id = core::borrow::Borrow::borrow(module_id); match module_id { - ibc::applications::transfer::MODULE_ID_STR => Some(self), + ibc::apps::transfer::types::MODULE_ID_STR => Some(self), _ => None, } } // - fn lookup_module(&self, port_id: &PortId) -> Option { + fn lookup_module(&self, port_id: &ibc::PortId) -> Option { match port_id.as_str() { - ibc::applications::transfer::PORT_ID_STR => Some(ModuleId::new( - ibc::applications::transfer::MODULE_ID_STR.to_string(), - )), + ibc::apps::transfer::types::PORT_ID_STR => { + Some(ibc::ModuleId::new( + ibc::apps::transfer::types::MODULE_ID_STR.to_string(), + )) + } _ => None, } } diff --git a/solana/solana-ibc/programs/solana-ibc/src/storage.rs b/solana/solana-ibc/programs/solana-ibc/src/storage.rs index 48b1719d..d972d25c 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/storage.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/storage.rs @@ -10,21 +10,7 @@ type Result = core::result::Result; use crate::client_state::AnyClientState; use crate::consensus_state::AnyConsensusState; - -mod ibc { - pub use ibc::core::ics02_client::error::ClientError; - pub use ibc::core::ics03_connection::connection::ConnectionEnd; - pub use ibc::core::ics03_connection::error::ConnectionError; - pub use ibc::core::ics04_channel::channel::ChannelEnd; - pub use ibc::core::ics04_channel::error::ChannelError; - pub use ibc::core::ics04_channel::msgs::PacketMsg; - pub use ibc::core::ics04_channel::packet::Sequence; - pub use ibc::core::ics24_host::identifier::{ - ChannelId, ClientId, ConnectionId, PortId, - }; - pub use ibc::core::ics24_host::path; - pub use ibc::Height; -} +use crate::ibc; pub mod ids; pub mod trie_key; diff --git a/solana/solana-ibc/programs/solana-ibc/src/storage/ids.rs b/solana/solana-ibc/programs/solana-ibc/src/storage/ids.rs index dd9ebe89..8d74645c 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/storage/ids.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/storage/ids.rs @@ -3,7 +3,7 @@ use core::str::FromStr; use anchor_lang::prelude::borsh; use base64::engine::{general_purpose, Engine}; -use super::ibc; +use crate::ibc; type Result = core::result::Result; @@ -70,7 +70,7 @@ pub struct ConnectionIdx(u32); impl ConnectionIdx { /// Prefix of IBC connection ids. /// - /// Note: We’re not using ConnectionId::prefix() because it returns the + /// Note: We’re not using ibc::ConnectionId::prefix() because it returns the /// prefix without trailing `-` which we want included to simplify stripping /// of the prefix. const IBC_PREFIX: &'static str = "connection-"; @@ -135,7 +135,7 @@ pub struct PortChannelPK { impl PortChannelPK { /// Prefix of IBC channel ids. /// - /// Note: We’re not using ChannelId::prefix() because it returns the + /// Note: We’re not using ibc::ChannelId::prefix() because it returns the /// prefix without trailing `-` which we want included to simplify stripping /// of the prefix. const CHANNEL_IBC_PREFIX: &'static str = "channel-"; diff --git a/solana/solana-ibc/programs/solana-ibc/src/tests.rs b/solana/solana-ibc/programs/solana-ibc/src/tests.rs index 53a439d2..a7ee308d 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/tests.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/tests.rs @@ -10,20 +10,10 @@ use anchor_client::solana_sdk::pubkey::Pubkey; use anchor_client::solana_sdk::signature::{Keypair, Signature, Signer}; use anchor_client::{Client, Cluster}; use anyhow::Result; -use ibc::core::ics02_client::client_state::ClientStateCommon; -use ibc::core::ics02_client::msgs::create_client::MsgCreateClient; -use ibc::core::ics03_connection::connection::Counterparty; -use ibc::core::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit; -use ibc::core::ics03_connection::version::Version; -use ibc::core::ics23_commitment::commitment::CommitmentPrefix; -use ibc::core::ics24_host::identifier::ClientId; -use ibc::mock::client_state::MockClientState; -use ibc::mock::consensus_state::MockConsensusState; -use ibc::mock::header::MockHeader; -use ibc_proto::google::protobuf::Any; +use crate::ibc::ClientStateCommon; use crate::storage::PrivateStorage; -use crate::{accounts, instruction}; +use crate::{accounts, ibc, instruction}; const IBC_TRIE_PREFIX: &[u8] = b"ibc/"; @@ -40,9 +30,10 @@ fn airdrop(client: &RpcClient, account: Pubkey, lamports: u64) -> Signature { airdrop_signature } -fn create_mock_client_and_cs_state() -> (MockClientState, MockConsensusState) { - let mock_client_state = MockClientState::new(MockHeader::default()); - let mock_cs_state = MockConsensusState::new(MockHeader::default()); +fn create_mock_client_and_cs_state( +) -> (ibc::mock::MockClientState, ibc::mock::MockConsensusState) { + let mock_client_state = ibc::mock::MockClientState::new(Default::default()); + let mock_cs_state = ibc::mock::MockConsensusState::new(Default::default()); (mock_client_state, mock_cs_state) } @@ -85,15 +76,16 @@ fn anchor_test_deliver() -> Result<()> { Pubkey::find_program_address(&[crate::CHAIN_SEED], &crate::ID).0; let (mock_client_state, mock_cs_state) = create_mock_client_and_cs_state(); - let _client_id = ClientId::new(mock_client_state.client_type(), 0).unwrap(); + let _client_id = + ibc::ClientId::new(mock_client_state.client_type(), 0).unwrap(); let message = make_message!( - MsgCreateClient::new( - Any::from(mock_client_state), - Any::from(mock_cs_state), + ibc::MsgCreateClient::new( + ibc::Any::from(mock_client_state), + ibc::Any::from(mock_cs_state), ibc::Signer::from(authority.pubkey().to_string()), ), - ibc::core::ics02_client::msgs::ClientMsg::CreateClient, - ibc::core::MsgEnvelope::Client, + ibc::ClientMsg::CreateClient, + ibc::MsgEnvelope::Client, ); let sig = program @@ -123,17 +115,20 @@ fn anchor_test_deliver() -> Result<()> { println!("This is solana storage account {:?}", solana_ibc_storage_account); let counter_party_client_id = - ClientId::new(mock_client_state.client_type(), 1).unwrap(); + ibc::ClientId::new(mock_client_state.client_type(), 1).unwrap(); - let commitment_prefix: CommitmentPrefix = + let commitment_prefix: ibc::CommitmentPrefix = IBC_TRIE_PREFIX.to_vec().try_into().unwrap(); let message = make_message!( - MsgConnectionOpenInit { - client_id_on_a: ClientId::new(mock_client_state.client_type(), 0) - .unwrap(), - version: Some(Version::default()), - counterparty: Counterparty::new( + ibc::MsgConnectionOpenInit { + client_id_on_a: ibc::ClientId::new( + mock_client_state.client_type(), + 0 + ) + .unwrap(), + version: Some(Default::default()), + counterparty: ibc::connection::Counterparty::new( counter_party_client_id, None, commitment_prefix, @@ -141,8 +136,8 @@ fn anchor_test_deliver() -> Result<()> { delay_period: Duration::from_secs(5), signer: ibc::Signer::from(authority.pubkey().to_string()), }, - ibc::core::ics03_connection::msgs::ConnectionMsg::OpenInit, - ibc::core::MsgEnvelope::Connection, + ibc::ConnectionMsg::OpenInit, + ibc::MsgEnvelope::Connection, ); let sig = program @@ -172,12 +167,12 @@ fn anchor_test_deliver() -> Result<()> { // fn internal_test() { // let authority = Keypair::new(); // let mut solana_ibc_store = IbcStorage::new(authority.pubkey()); -// let mock_client_state = MockClientState::new(MockHeader::default()); -// let mock_cs_state = MockConsensusState::new(MockHeader::default()); -// let client_id = ClientId::new(mock_client_state.client_type(), 0).unwrap(); -// let msg = MsgCreateClient::new( -// Any::from(mock_client_state), -// Any::from(mock_cs_state), +// let mock_client_state = MockClientState::new(Default::default()); +// let mock_cs_state = MockConsensusState::new(Default::default()); +// let client_id = ibc::ClientId::new(mock_client_state.client_type(), 0).unwrap(); +// let msg = ibc::MsgCreateClient::new( +// ibc::Any::from(mock_client_state), +// ibc::Any::from(mock_cs_state), // ibc::Signer::from(authority.pubkey().to_string()), // ); // let messages = ibc::Any { @@ -188,7 +183,7 @@ fn anchor_test_deliver() -> Result<()> { // let all_messages = [messages]; // let errors = all_messages.into_iter().fold(vec![], |mut errors, msg| { -// match ibc::core::MsgEnvelope::try_from(msg) { +// match ibc::core::ibc::MsgEnvelope::try_from(msg) { // Ok(msg) => { // match ibc::core::dispatch(&mut solana_ibc_store.clone(), &mut solana_ibc_store, msg) // { diff --git a/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs b/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs index 7b11a453..d2076d33 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs @@ -1,13 +1,11 @@ use anchor_lang::solana_program::msg; -use ibc::applications::transfer::context::{ +use ibc::apps::transfer::context::{ TokenTransferExecutionContext, TokenTransferValidationContext, }; -use ibc::applications::transfer::error::TokenTransferError; -use ibc::applications::transfer::PrefixedCoin; -use ibc::core::ics24_host::identifier::{ChannelId, PortId}; -use ibc::Signer; +use ibc::apps::transfer::types::error::TokenTransferError; +use ibc::apps::transfer::types::PrefixedCoin; -// use crate::module_holder::IbcStorage<'_,'_>; +use crate::ibc; use crate::storage::IbcStorage; impl TokenTransferExecutionContext for IbcStorage<'_, '_> { @@ -57,20 +55,20 @@ impl TokenTransferExecutionContext for IbcStorage<'_, '_> { } impl TokenTransferValidationContext for IbcStorage<'_, '_> { - type AccountId = Signer; + type AccountId = ibc::Signer; - fn get_port(&self) -> Result { - Ok(PortId::transfer()) + fn get_port(&self) -> Result { + Ok(ibc::PortId::transfer()) } fn get_escrow_account( &self, - port_id: &PortId, - channel_id: &ChannelId, + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, ) -> Result { let escrow_account = format!("{}.ef.{}", channel_id.as_str(), port_id.as_str(),); - Ok(Signer::from(escrow_account)) + Ok(ibc::Signer::from(escrow_account)) } fn can_send_coins(&self) -> Result<(), TokenTransferError> { diff --git a/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs b/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs index bd38ef8a..145e8910 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs @@ -2,33 +2,26 @@ use std::result::Result; use std::str; use anchor_lang::prelude::*; -use ibc::applications::transfer::packet::PacketData; -use ibc::core::ics04_channel::acknowledgement::Acknowledgement; -use ibc::core::ics04_channel::channel::{Counterparty, Order}; -use ibc::core::ics04_channel::error::{ChannelError, PacketError}; -use ibc::core::ics04_channel::packet::Packet; -use ibc::core::ics04_channel::Version; -use ibc::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId}; -use ibc::core::router::{Module, ModuleExtras}; -use ibc::Signer; -use ibc_proto::ibc::apps::transfer::v2::FungibleTokenPacketData; +use ibc::apps::transfer::types::packet::PacketData; +use ibc::apps::transfer::types::proto::transfer::v2::FungibleTokenPacketData; use serde::{Deserialize, Serialize}; +use crate::ibc; use crate::storage::IbcStorage; mod impls; -impl Module for IbcStorage<'_, '_> { +impl ibc::Module for IbcStorage<'_, '_> { fn on_chan_open_init_validate( &self, - order: Order, - connection_hops: &[ConnectionId], - port_id: &PortId, - channel_id: &ChannelId, - counterparty: &Counterparty, - version: &Version, - ) -> Result { - ibc::applications::transfer::context::on_chan_open_init_validate( + order: ibc::channel::Order, + connection_hops: &[ibc::ConnectionId], + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + counterparty: &ibc::channel::Counterparty, + version: &ibc::Version, + ) -> Result { + ibc::apps::transfer::module::on_chan_open_init_validate( self, order, connection_hops, @@ -37,20 +30,22 @@ impl Module for IbcStorage<'_, '_> { counterparty, version, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() })?; + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + })?; Ok(version.clone()) } fn on_chan_open_try_validate( &self, - order: Order, - connection_hops: &[ConnectionId], - port_id: &PortId, - channel_id: &ChannelId, - counterparty: &Counterparty, - counterparty_version: &Version, - ) -> Result { - ibc::applications::transfer::context::on_chan_open_try_validate( + order: ibc::channel::Order, + connection_hops: &[ibc::ConnectionId], + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + counterparty: &ibc::channel::Counterparty, + counterparty_version: &ibc::Version, + ) -> Result { + ibc::apps::transfer::module::on_chan_open_try_validate( self, order, connection_hops, @@ -59,66 +54,76 @@ impl Module for IbcStorage<'_, '_> { counterparty, counterparty_version, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() })?; + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + })?; Ok(counterparty_version.clone()) } fn on_chan_open_ack_validate( &self, - port_id: &PortId, - channel_id: &ChannelId, - counterparty_version: &Version, - ) -> Result<(), ChannelError> { - ibc::applications::transfer::context::on_chan_open_ack_validate( + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + counterparty_version: &ibc::Version, + ) -> Result<(), ibc::ChannelError> { + ibc::apps::transfer::module::on_chan_open_ack_validate( self, port_id, channel_id, counterparty_version, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + }) } fn on_chan_open_confirm_validate( &self, - port_id: &PortId, - channel_id: &ChannelId, - ) -> Result<(), ChannelError> { + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + ) -> Result<(), ibc::ChannelError> { // Create and initialize the escrow sub-account for this channel. // Call default implementation. - ibc::applications::transfer::context::on_chan_open_confirm_validate( + ibc::apps::transfer::module::on_chan_open_confirm_validate( self, port_id, channel_id, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + }) } fn on_chan_close_init_validate( &self, - port_id: &PortId, - channel_id: &ChannelId, - ) -> Result<(), ChannelError> { - ibc::applications::transfer::context::on_chan_close_init_validate( + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + ) -> Result<(), ibc::ChannelError> { + ibc::apps::transfer::module::on_chan_close_init_validate( self, port_id, channel_id, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + }) } fn on_chan_close_confirm_validate( &self, - port_id: &PortId, - channel_id: &ChannelId, - ) -> Result<(), ChannelError> { - ibc::applications::transfer::context::on_chan_close_confirm_validate( + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + ) -> Result<(), ibc::ChannelError> { + ibc::apps::transfer::module::on_chan_close_confirm_validate( self, port_id, channel_id, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + }) } fn on_recv_packet_execute( &mut self, - packet: &Packet, - _relayer: &Signer, - ) -> (ModuleExtras, Acknowledgement) { + packet: &ibc::Packet, + _relayer: &ibc::Signer, + ) -> (ibc::ModuleExtras, ibc::Acknowledgement) { msg!( "Received packet: {:?}", str::from_utf8(packet.data.as_ref()).expect("Invalid packet data") @@ -126,7 +131,7 @@ impl Module for IbcStorage<'_, '_> { let ft_packet_data = serde_json::from_slice::(&packet.data) .expect("Invalid packet data"); - let maybe_ft_packet = Packet { + let maybe_ft_packet = ibc::Packet { data: serde_json::to_string( &PacketData::try_from(FungibleTokenPacketData::from( ft_packet_data, @@ -137,55 +142,52 @@ impl Module for IbcStorage<'_, '_> { .into_bytes(), ..packet.clone() }; - let (extras, ack) = - ibc::applications::transfer::context::on_recv_packet_execute( - self, - &maybe_ft_packet, - ); + let (extras, ack) = ibc::apps::transfer::module::on_recv_packet_execute( + self, + &maybe_ft_packet, + ); let ack_status = str::from_utf8(ack.as_bytes()) .expect("Invalid acknowledgement string"); - msg!("Packet acknowledgement: {}", ack_status); + msg!("ibc::Packet acknowledgement: {}", ack_status); (extras, ack) } fn on_acknowledgement_packet_validate( &self, - packet: &Packet, - acknowledgement: &Acknowledgement, - relayer: &Signer, - ) -> Result<(), PacketError> { - ibc::applications::transfer::context::on_acknowledgement_packet_validate( + packet: &ibc::Packet, + acknowledgement: &ibc::Acknowledgement, + relayer: &ibc::Signer, + ) -> Result<(), ibc::PacketError> { + ibc::apps::transfer::module::on_acknowledgement_packet_validate( self, packet, acknowledgement, relayer, ) - .map_err(|e| PacketError::AppModule { - description: e.to_string(), - }) + .map_err(|e| ibc::PacketError::AppModule { description: e.to_string() }) } fn on_timeout_packet_validate( &self, - packet: &Packet, - relayer: &Signer, - ) -> Result<(), PacketError> { - ibc::applications::transfer::context::on_timeout_packet_validate( + packet: &ibc::Packet, + relayer: &ibc::Signer, + ) -> Result<(), ibc::PacketError> { + ibc::apps::transfer::module::on_timeout_packet_validate( self, packet, relayer, ) - .map_err(|e| PacketError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::PacketError::AppModule { description: e.to_string() }) } 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> { - ibc::applications::transfer::context::on_chan_open_init_execute( + order: ibc::channel::Order, + connection_hops: &[ibc::ConnectionId], + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + counterparty: &ibc::channel::Counterparty, + version: &ibc::Version, + ) -> Result<(ibc::ModuleExtras, ibc::Version), ibc::ChannelError> { + ibc::apps::transfer::module::on_chan_open_init_execute( self, order, connection_hops, @@ -194,19 +196,21 @@ impl Module for IbcStorage<'_, '_> { counterparty, version, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + }) } 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> { - ibc::applications::transfer::context::on_chan_open_try_execute( + order: ibc::channel::Order, + connection_hops: &[ibc::ConnectionId], + port_id: &ibc::PortId, + channel_id: &ibc::ChannelId, + counterparty: &ibc::channel::Counterparty, + counterparty_version: &ibc::Version, + ) -> Result<(ibc::ModuleExtras, ibc::Version), ibc::ChannelError> { + ibc::apps::transfer::module::on_chan_open_try_execute( self, order, connection_hops, @@ -215,24 +219,27 @@ impl Module for IbcStorage<'_, '_> { counterparty, counterparty_version, ) - .map_err(|e| ChannelError::AppModule { description: e.to_string() }) + .map_err(|e| ibc::ChannelError::AppModule { + description: e.to_string(), + }) } fn on_acknowledgement_packet_execute( &mut self, - packet: &Packet, - acknowledgement: &Acknowledgement, - relayer: &Signer, - ) -> (ModuleExtras, Result<(), PacketError>) { - let result = ibc::applications::transfer::context::on_acknowledgement_packet_execute( - self, - packet, - acknowledgement, - relayer, - ); + packet: &ibc::Packet, + acknowledgement: &ibc::Acknowledgement, + relayer: &ibc::Signer, + ) -> (ibc::ModuleExtras, Result<(), ibc::PacketError>) { + let result = + ibc::apps::transfer::module::on_acknowledgement_packet_execute( + self, + packet, + acknowledgement, + relayer, + ); ( result.0, - result.1.map_err(|e| PacketError::AppModule { + result.1.map_err(|e| ibc::PacketError::AppModule { description: e.to_string(), }), ) @@ -240,16 +247,15 @@ impl Module for IbcStorage<'_, '_> { fn on_timeout_packet_execute( &mut self, - packet: &Packet, - relayer: &Signer, - ) -> (ModuleExtras, Result<(), PacketError>) { - let result = - ibc::applications::transfer::context::on_timeout_packet_execute( - self, packet, relayer, - ); + packet: &ibc::Packet, + relayer: &ibc::Signer, + ) -> (ibc::ModuleExtras, Result<(), ibc::PacketError>) { + let result = ibc::apps::transfer::module::on_timeout_packet_execute( + self, packet, relayer, + ); ( result.0, - result.1.map_err(|e| PacketError::AppModule { + result.1.map_err(|e| ibc::PacketError::AppModule { description: e.to_string(), }), ) @@ -257,39 +263,39 @@ impl Module for IbcStorage<'_, '_> { fn on_chan_open_ack_execute( &mut self, - _port_id: &PortId, - _channel_id: &ChannelId, - _counterparty_version: &Version, - ) -> Result { + _port_id: &ibc::PortId, + _channel_id: &ibc::ChannelId, + _counterparty_version: &ibc::Version, + ) -> Result { // TODO(#35): Verify port_id is valid. - Ok(ModuleExtras::empty()) + Ok(ibc::ModuleExtras::empty()) } fn on_chan_open_confirm_execute( &mut self, - _port_id: &PortId, - _channel_id: &ChannelId, - ) -> Result { + _port_id: &ibc::PortId, + _channel_id: &ibc::ChannelId, + ) -> Result { // TODO(#35): Verify port_id is valid. - Ok(ModuleExtras::empty()) + Ok(ibc::ModuleExtras::empty()) } fn on_chan_close_init_execute( &mut self, - _port_id: &PortId, - _channel_id: &ChannelId, - ) -> Result { + _port_id: &ibc::PortId, + _channel_id: &ibc::ChannelId, + ) -> Result { // TODO(#35): Verify port_id is valid. - Ok(ModuleExtras::empty()) + Ok(ibc::ModuleExtras::empty()) } fn on_chan_close_confirm_execute( &mut self, - _port_id: &PortId, - _channel_id: &ChannelId, - ) -> Result { + _port_id: &ibc::PortId, + _channel_id: &ibc::ChannelId, + ) -> Result { // TODO(#35): Verify port_id is valid. - Ok(ModuleExtras::empty()) + Ok(ibc::ModuleExtras::empty()) } } diff --git a/solana/solana-ibc/programs/solana-ibc/src/validation_context.rs b/solana/solana-ibc/programs/solana-ibc/src/validation_context.rs index c4ecc30c..63f34a38 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/validation_context.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/validation_context.rs @@ -2,77 +2,61 @@ use std::str::FromStr; use std::time::Duration; use anchor_lang::prelude::Pubkey; -use ibc::core::ics02_client::error::ClientError; -use ibc::core::ics03_connection::connection::ConnectionEnd; -use ibc::core::ics03_connection::error::ConnectionError; -use ibc::core::ics04_channel::channel::ChannelEnd; -use ibc::core::ics04_channel::commitment::{ - AcknowledgementCommitment, PacketCommitment, -}; -use ibc::core::ics04_channel::error::{ChannelError, PacketError}; -use ibc::core::ics04_channel::packet::{Receipt, Sequence}; -use ibc::core::ics23_commitment::commitment::CommitmentPrefix; -use ibc::core::ics24_host::identifier::{ClientId, ConnectionId}; -use ibc::core::ics24_host::path::{ - AckPath, ChannelEndPath, ClientConsensusStatePath, CommitmentPath, - ReceiptPath, SeqAckPath, SeqRecvPath, SeqSendPath, -}; -use ibc::core::timestamp::Timestamp; -use ibc::core::{ContextError, ValidationContext}; -use ibc::Height; use lib::hash::CryptoHash; use crate::client_state::AnyClientState; use crate::consensus_state::AnyConsensusState; +use crate::ibc; use crate::storage::trie_key::TrieKey; use crate::storage::{self, ids, IbcStorage}; -type Result = core::result::Result; +type Result = core::result::Result; -impl ValidationContext for IbcStorage<'_, '_> { +impl ibc::ValidationContext for IbcStorage<'_, '_> { type V = Self; // ClientValidationContext - type E = Self; // ClientExecutionContext + type E = Self; // ibc::ClientExecutionContext type AnyConsensusState = AnyConsensusState; type AnyClientState = AnyClientState; fn client_state( &self, - client_id: &ClientId, + client_id: &ibc::ClientId, ) -> Result { Ok(self.borrow().private.client(client_id)?.client_state.get()?) } fn decode_client_state( &self, - client_state: ibc_proto::google::protobuf::Any, + client_state: ibc::Any, ) -> Result { Ok(Self::AnyClientState::try_from(client_state)?) } fn consensus_state( &self, - path: &ClientConsensusStatePath, + path: &ibc::path::ClientConsensusStatePath, ) -> Result { - let height = Height::new(path.epoch, path.height)?; + let height = + ibc::Height::new(path.revision_number, path.revision_height)?; self.borrow() .private .client(&path.client_id)? .consensus_states .get(&height) .cloned() - .ok_or_else(|| ClientError::ConsensusStateNotFound { + .ok_or_else(|| ibc::ClientError::ConsensusStateNotFound { client_id: path.client_id.clone(), height, }) .and_then(|data| data.get()) - .map_err(ibc::core::ContextError::from) + .map_err(ibc::ContextError::from) } fn host_height(&self) -> Result { self.borrow().host_head.ibc_height().map_err(Into::into) } - fn host_timestamp(&self) -> Result { + fn host_timestamp(&self) -> Result { self.borrow().host_head.ibc_timestamp().map_err(Into::into) } @@ -80,7 +64,7 @@ impl ValidationContext for IbcStorage<'_, '_> { &self, _height: &ibc::Height, ) -> Result { - Err(ContextError::ClientError(ClientError::ClientSpecific { + Err(ibc::ContextError::ClientError(ibc::ClientError::ClientSpecific { description: "The `host_consensus_state` is not supported on \ Solana protocol." .into(), @@ -91,13 +75,16 @@ impl ValidationContext for IbcStorage<'_, '_> { Ok(self.borrow().private.client_counter()) } - fn connection_end(&self, conn_id: &ConnectionId) -> Result { + fn connection_end( + &self, + conn_id: &ibc::ConnectionId, + ) -> Result { let idx = ids::ConnectionIdx::try_from(conn_id)?; self.borrow() .private .connections .get(usize::from(idx)) - .ok_or_else(|| ConnectionError::ConnectionNotFound { + .ok_or_else(|| ibc::ConnectionError::ConnectionNotFound { connection_id: conn_id.clone(), })? .get() @@ -106,10 +93,10 @@ impl ValidationContext for IbcStorage<'_, '_> { fn validate_self_client( &self, - client_state_of_host_on_counterparty: ibc_proto::google::protobuf::Any, + client_state_of_host_on_counterparty: ibc::Any, ) -> Result { Self::AnyClientState::try_from(client_state_of_host_on_counterparty) - .map_err(|e| ClientError::Other { + .map_err(|e| ibc::ClientError::Other { description: format!("Decode ClientState failed: {:?}", e) .to_string(), })?; @@ -117,23 +104,26 @@ impl ValidationContext for IbcStorage<'_, '_> { Ok(()) } - fn commitment_prefix(&self) -> CommitmentPrefix { - CommitmentPrefix::try_from(b"ibc".to_vec()).unwrap() + fn commitment_prefix(&self) -> ibc::CommitmentPrefix { + ibc::CommitmentPrefix::try_from(b"ibc".to_vec()).unwrap() } fn connection_counter(&self) -> Result { u64::try_from(self.borrow().private.connections.len()).map_err(|err| { - ConnectionError::Other { description: err.to_string() }.into() + ibc::ConnectionError::Other { description: err.to_string() }.into() }) } - fn channel_end(&self, path: &ChannelEndPath) -> Result { + fn channel_end( + &self, + path: &ibc::path::ChannelEndPath, + ) -> Result { let key = ids::PortChannelPK::try_from(&path.0, &path.1)?; self.borrow() .private .channel_ends .get(&key) - .ok_or_else(|| ChannelError::ChannelNotFound { + .ok_or_else(|| ibc::ChannelError::ChannelNotFound { port_id: path.0.clone(), channel_id: path.1.clone(), })? @@ -141,33 +131,42 @@ impl ValidationContext for IbcStorage<'_, '_> { .map_err(Into::into) } - fn get_next_sequence_send(&self, path: &SeqSendPath) -> Result { + fn get_next_sequence_send( + &self, + path: &ibc::path::SeqSendPath, + ) -> Result { self.get_next_sequence( path, storage::SequenceTripleIdx::Send, - |port_id, channel_id| PacketError::MissingNextSendSeq { + |port_id, channel_id| ibc::PacketError::MissingNextSendSeq { port_id, channel_id, }, ) } - fn get_next_sequence_recv(&self, path: &SeqRecvPath) -> Result { + fn get_next_sequence_recv( + &self, + path: &ibc::path::SeqRecvPath, + ) -> Result { self.get_next_sequence( path, storage::SequenceTripleIdx::Recv, - |port_id, channel_id| PacketError::MissingNextRecvSeq { + |port_id, channel_id| ibc::PacketError::MissingNextRecvSeq { port_id, channel_id, }, ) } - fn get_next_sequence_ack(&self, path: &SeqAckPath) -> Result { + fn get_next_sequence_ack( + &self, + path: &ibc::path::SeqAckPath, + ) -> Result { self.get_next_sequence( path, storage::SequenceTripleIdx::Ack, - |port_id, channel_id| PacketError::MissingNextAckSeq { + |port_id, channel_id| ibc::PacketError::MissingNextAckSeq { port_id, channel_id, }, @@ -176,36 +175,43 @@ impl ValidationContext for IbcStorage<'_, '_> { fn get_packet_commitment( &self, - path: &CommitmentPath, - ) -> Result { + path: &ibc::path::CommitmentPath, + ) -> Result { let trie_key = TrieKey::try_from(path)?; match self.borrow().provable.get(&trie_key).ok().flatten() { Some(hash) => Ok(hash.as_slice().to_vec().into()), - None => Err(ContextError::PacketError( - PacketError::PacketReceiptNotFound { sequence: path.sequence }, + None => Err(ibc::ContextError::PacketError( + ibc::PacketError::PacketReceiptNotFound { + sequence: path.sequence, + }, )), } } - fn get_packet_receipt(&self, path: &ReceiptPath) -> Result { + fn get_packet_receipt( + &self, + path: &ibc::path::ReceiptPath, + ) -> Result { let trie_key = TrieKey::try_from(path)?; match self.borrow().provable.get(&trie_key).ok().flatten() { - Some(hash) if hash == CryptoHash::DEFAULT => Ok(Receipt::Ok), - _ => Err(ContextError::PacketError( - PacketError::PacketReceiptNotFound { sequence: path.sequence }, + Some(hash) if hash == CryptoHash::DEFAULT => Ok(ibc::Receipt::Ok), + _ => Err(ibc::ContextError::PacketError( + ibc::PacketError::PacketReceiptNotFound { + sequence: path.sequence, + }, )), } } fn get_packet_acknowledgement( &self, - path: &AckPath, - ) -> Result { + path: &ibc::path::AckPath, + ) -> Result { let trie_key = TrieKey::try_from(path)?; match self.borrow().provable.get(&trie_key).ok().flatten() { Some(hash) => Ok(hash.as_slice().to_vec().into()), - None => Err(ContextError::PacketError( - PacketError::PacketAcknowledgementNotFound { + None => Err(ibc::ContextError::PacketError( + ibc::PacketError::PacketAcknowledgementNotFound { sequence: path.sequence, }, )), @@ -226,25 +232,25 @@ impl ValidationContext for IbcStorage<'_, '_> { fn validate_message_signer(&self, signer: &ibc::Signer) -> Result { match Pubkey::from_str(signer.as_ref()) { Ok(_) => Ok(()), - Err(e) => Err(ContextError::ClientError(ClientError::Other { - description: format!("Invalid signer: {e:?}"), - })), + Err(e) => { + Err(ibc::ContextError::ClientError(ibc::ClientError::Other { + description: format!("Invalid signer: {e:?}"), + })) + } } } fn get_client_validation_context(&self) -> &Self::V { self } - fn get_compatible_versions( - &self, - ) -> Vec { - ibc::core::ics03_connection::version::get_compatible_versions() + fn get_compatible_versions(&self) -> Vec { + ibc::connection::get_compatible_versions() } fn pick_version( &self, - counterparty_candidate_versions: &[ibc::core::ics03_connection::version::Version], - ) -> Result { - let version = ibc::core::ics03_connection::version::pick_version( + counterparty_candidate_versions: &[ibc::connection::Version], + ) -> Result { + let version = ibc::connection::pick_version( &self.get_compatible_versions(), counterparty_candidate_versions, )?; @@ -259,21 +265,21 @@ impl ValidationContext for IbcStorage<'_, '_> { } } -impl ibc::core::ics02_client::ClientValidationContext for IbcStorage<'_, '_> { +impl ibc::ClientValidationContext for IbcStorage<'_, '_> { fn client_update_time( &self, - client_id: &ClientId, - height: &Height, - ) -> Result { + client_id: &ibc::ClientId, + height: &ibc::Height, + ) -> Result { let store = self.borrow(); store .private .client(client_id)? .processed_times .get(height) - .map(|ts| Timestamp::from_nanoseconds(*ts).unwrap()) + .map(|ts| ibc::Timestamp::from_nanoseconds(*ts).unwrap()) .ok_or_else(|| { - ContextError::ClientError(ClientError::Other { + ibc::ContextError::ClientError(ibc::ClientError::Other { description: format!( "Client update time not found. client_id: {}, height: \ {}", @@ -285,9 +291,9 @@ impl ibc::core::ics02_client::ClientValidationContext for IbcStorage<'_, '_> { fn client_update_height( &self, - client_id: &ClientId, - height: &Height, - ) -> Result { + client_id: &ibc::ClientId, + height: &ibc::Height, + ) -> Result { self.borrow() .private .client(client_id)? @@ -295,7 +301,7 @@ impl ibc::core::ics02_client::ClientValidationContext for IbcStorage<'_, '_> { .get(height) .copied() .ok_or_else(|| { - ContextError::ClientError(ClientError::Other { + ibc::ContextError::ClientError(ibc::ClientError::Other { description: format!( "Client update height not found. client_id: {}, \ height: {}", @@ -311,16 +317,13 @@ impl IbcStorage<'_, '_> { &self, path: impl Into>, index: storage::SequenceTripleIdx, - make_err: impl FnOnce( - ibc::core::ics24_host::identifier::PortId, - ibc::core::ics24_host::identifier::ChannelId, - ) -> PacketError, - ) -> Result { + make_err: impl FnOnce(ibc::PortId, ibc::ChannelId) -> ibc::PacketError, + ) -> Result { fn get( this: &IbcStorage<'_, '_>, port_channel: &ids::PortChannelPK, index: storage::SequenceTripleIdx, - ) -> Option { + ) -> Option { this.borrow() .private .next_sequence @@ -334,7 +337,7 @@ impl IbcStorage<'_, '_> { .ok_or_else(|| { make_err(path.port_id.clone(), path.channel_id.clone()) }) - .map_err(ContextError::from) + .map_err(ibc::ContextError::from) } } From bd8f489d7598aab8cb6609b311fbb8a7d465ddbf Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Sat, 25 Nov 2023 02:48:02 +0100 Subject: [PATCH 2/7] wip --- solana/solana-ibc/programs/solana-ibc/src/client_state.rs | 2 +- solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs | 4 ++-- solana/solana-ibc/programs/solana-ibc/src/ibc.rs | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/solana/solana-ibc/programs/solana-ibc/src/client_state.rs b/solana/solana-ibc/programs/solana-ibc/src/client_state.rs index 1d34acc0..14af4f30 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/client_state.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/client_state.rs @@ -42,7 +42,7 @@ impl AnyClientStateTag { impl AnyClientState { /// Protobuf type URL for Tendermint client state used in Any message. - const TENDERMINT_TYPE: &str = ibc::tm::TENDERMINT_CLIENT_STATE_TYPE_URL; + const TENDERMINT_TYPE: &'static str = ibc::tm::TENDERMINT_CLIENT_STATE_TYPE_URL; #[cfg(any(test, feature = "mocks"))] /// Protobuf type URL for Mock client state used in Any message. const MOCK_TYPE: &'static str = ibc::mock::MOCK_CLIENT_STATE_TYPE_URL; diff --git a/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs b/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs index a56bb92c..22fa8e8c 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs @@ -36,10 +36,10 @@ impl AnyConsensusStateTag { impl AnyConsensusState { /// Protobuf type URL for Tendermint client state used in Any message. - const TENDERMINT_TYPE: &str = ibc::tm::TENDERMINT_CONSENSUS_STATE_TYPE_URL; + const TENDERMINT_TYPE: &'static str = ibc::tm::TENDERMINT_CONSENSUS_STATE_TYPE_URL; #[cfg(any(test, feature = "mocks"))] /// Protobuf type URL for Mock client state used in Any message. - const MOCK_TYPE: &str = ibc::mock::MOCK_CONSENSUS_STATE_TYPE_URL; + const MOCK_TYPE: &'static str = ibc::mock::MOCK_CONSENSUS_STATE_TYPE_URL; /// Encodes the payload and returns discriminants that allow decoding the /// value later. diff --git a/solana/solana-ibc/programs/solana-ibc/src/ibc.rs b/solana/solana-ibc/programs/solana-ibc/src/ibc.rs index 3abf6e67..8f50e3fa 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/ibc.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/ibc.rs @@ -13,6 +13,7 @@ pub use ibc::core::client::context::client_state::{ }; pub use ibc::core::client::context::consensus_state::ConsensusState; pub use ibc::core::client::context::types::error::ClientError; +#[cfg(test)] pub use ibc::core::client::context::types::msgs::{ClientMsg, MsgCreateClient}; pub use ibc::core::client::context::{ ClientExecutionContext, ClientValidationContext, @@ -22,6 +23,7 @@ pub use ibc::core::commitment_types::commitment::{ CommitmentPrefix, CommitmentProofBytes, CommitmentRoot, }; pub use ibc::core::connection::types::error::ConnectionError; +#[cfg(test)] pub use ibc::core::connection::types::msgs::{ ConnectionMsg, MsgConnectionOpenInit, }; @@ -36,7 +38,6 @@ pub use ibc::core::host::types::path; pub use ibc::core::host::{ExecutionContext, ValidationContext}; pub use ibc::core::router::module::Module; pub use ibc::core::router::router::Router; -pub use ibc::core::router::types::error::RouterError; pub use ibc::core::router::types::module::{ModuleExtras, ModuleId}; pub use ibc::primitives::{Signer, Timestamp}; @@ -44,6 +45,7 @@ pub mod connection { pub use ibc::core::connection::types::version::{ get_compatible_versions, pick_version, Version, }; + #[cfg(test)] pub use ibc::core::connection::types::Counterparty; } pub use ibc::primitives::proto::{Any, Protobuf}; From 23ce57f955579aa75c30d31f8c44b5427c689c83 Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Sat, 25 Nov 2023 03:03:08 +0100 Subject: [PATCH 3/7] fmt --- solana/solana-ibc/programs/solana-ibc/src/client_state.rs | 3 ++- solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/solana/solana-ibc/programs/solana-ibc/src/client_state.rs b/solana/solana-ibc/programs/solana-ibc/src/client_state.rs index 14af4f30..43ab317b 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/client_state.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/client_state.rs @@ -42,7 +42,8 @@ impl AnyClientStateTag { impl AnyClientState { /// Protobuf type URL for Tendermint client state used in Any message. - const TENDERMINT_TYPE: &'static str = ibc::tm::TENDERMINT_CLIENT_STATE_TYPE_URL; + const TENDERMINT_TYPE: &'static str = + ibc::tm::TENDERMINT_CLIENT_STATE_TYPE_URL; #[cfg(any(test, feature = "mocks"))] /// Protobuf type URL for Mock client state used in Any message. const MOCK_TYPE: &'static str = ibc::mock::MOCK_CLIENT_STATE_TYPE_URL; diff --git a/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs b/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs index 22fa8e8c..035d09ba 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/consensus_state.rs @@ -36,7 +36,8 @@ impl AnyConsensusStateTag { impl AnyConsensusState { /// Protobuf type URL for Tendermint client state used in Any message. - const TENDERMINT_TYPE: &'static str = ibc::tm::TENDERMINT_CONSENSUS_STATE_TYPE_URL; + const TENDERMINT_TYPE: &'static str = + ibc::tm::TENDERMINT_CONSENSUS_STATE_TYPE_URL; #[cfg(any(test, feature = "mocks"))] /// Protobuf type URL for Mock client state used in Any message. const MOCK_TYPE: &'static str = ibc::mock::MOCK_CONSENSUS_STATE_TYPE_URL; From d568e974b2657a07073a4dc42442a8d6aa0cca58 Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Sat, 25 Nov 2023 03:34:29 +0100 Subject: [PATCH 4/7] fix ambiguity --- .../programs/solana-ibc/src/transfer/impls.rs | 10 +++++----- .../solana-ibc/programs/solana-ibc/src/transfer/mod.rs | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs b/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs index d2076d33..fd3493c8 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/transfer/impls.rs @@ -1,11 +1,11 @@ use anchor_lang::solana_program::msg; -use ibc::apps::transfer::context::{ - TokenTransferExecutionContext, TokenTransferValidationContext, -}; -use ibc::apps::transfer::types::error::TokenTransferError; -use ibc::apps::transfer::types::PrefixedCoin; use crate::ibc; +use crate::ibc::apps::transfer::context::{ + TokenTransferExecutionContext, TokenTransferValidationContext, +}; +use crate::ibc::apps::transfer::types::error::TokenTransferError; +use crate::ibc::apps::transfer::types::PrefixedCoin; use crate::storage::IbcStorage; impl TokenTransferExecutionContext for IbcStorage<'_, '_> { diff --git a/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs b/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs index 145e8910..66b69e8e 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/transfer/mod.rs @@ -2,11 +2,11 @@ use std::result::Result; use std::str; use anchor_lang::prelude::*; -use ibc::apps::transfer::types::packet::PacketData; -use ibc::apps::transfer::types::proto::transfer::v2::FungibleTokenPacketData; use serde::{Deserialize, Serialize}; use crate::ibc; +use crate::ibc::apps::transfer::types::packet::PacketData; +use crate::ibc::apps::transfer::types::proto::transfer::v2::FungibleTokenPacketData; use crate::storage::IbcStorage; mod impls; From 7269ae70a24913e60c10ed649ee9ac1b77c4f2ff Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Tue, 28 Nov 2023 14:16:26 +0100 Subject: [PATCH 5/7] 0.48.1 --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 19c4c4ae..78c95f66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,8 +30,8 @@ borsh = { version = "0.10.3", default-features = false } bytemuck = { version = "1.14", default-features = false } derive_more = "0.99.17" hex-literal = "0.4.1" -ibc = { version = "0.48.0", default-features = false, features = ["borsh", "serde"] } -ibc-testkit = { version = "0.48.0", default-features = false } +ibc = { version = "0.48.1", default-features = false, features = ["borsh", "serde"] } +ibc-testkit = { version = "0.48.1", default-features = false } pretty_assertions = "1.4.0" rand = { version = "0.8.5" } serde = "1" From b7b9e6d85ad2e03b1ccfa81668f84b983058ef87 Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Tue, 28 Nov 2023 15:23:46 +0100 Subject: [PATCH 6/7] clippy --- solana/solana-ibc/programs/solana-ibc/src/ibc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solana/solana-ibc/programs/solana-ibc/src/ibc.rs b/solana/solana-ibc/programs/solana-ibc/src/ibc.rs index 3fa898a7..c43ffbab 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/ibc.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/ibc.rs @@ -1,4 +1,4 @@ -#![cfg_attr(not(any(test, feature = "mocks")), allow(unused_imports))] +#![allow(unused_imports)] pub use ibc::apps; pub use ibc::core::channel::types::acknowledgement::Acknowledgement; From 9c1dc1b83d8f49658413cf406e6da24d364e4d19 Mon Sep 17 00:00:00 2001 From: dhruvja Date: Tue, 28 Nov 2023 19:59:44 +0530 Subject: [PATCH 7/7] fix ambiguity --- solana/solana-ibc/programs/solana-ibc/src/mocks.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solana/solana-ibc/programs/solana-ibc/src/mocks.rs b/solana/solana-ibc/programs/solana-ibc/src/mocks.rs index d93ae9d2..14cd5cf5 100644 --- a/solana/solana-ibc/programs/solana-ibc/src/mocks.rs +++ b/solana/solana-ibc/programs/solana-ibc/src/mocks.rs @@ -2,8 +2,8 @@ extern crate alloc; use anchor_lang::prelude::*; use anchor_spl::token::MintTo; -use ibc::{ClientExecutionContext, ExecutionContext, ValidationContext}; +use crate::ibc::{ClientExecutionContext, ExecutionContext, ValidationContext}; use crate::{error, host, ibc, storage, MockDeliver, MINT_ESCROW_SEED};