From 5f8c79b450039cc40ebf72f031706013a126aef1 Mon Sep 17 00:00:00 2001 From: Jun Kimura Date: Wed, 6 Nov 2024 18:31:49 +0900 Subject: [PATCH] add type conversion between `Any` and `ClientMessage` Signed-off-by: Jun Kimura --- crates/ibc/src/errors.rs | 2 ++ crates/ibc/src/header.rs | 37 +++++++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/ibc/src/errors.rs b/crates/ibc/src/errors.rs index 1b7595b..78a9e70 100644 --- a/crates/ibc/src/errors.rs +++ b/crates/ibc/src/errors.rs @@ -107,6 +107,8 @@ pub enum Error { }, /// proto missing field error: `{0}` ProtoMissingFieldError(String), + /// unknown message type: `{0}` + UnknownMessageType(String), } impl Error { diff --git a/crates/ibc/src/header.rs b/crates/ibc/src/header.rs index 239f2e0..4befa36 100644 --- a/crates/ibc/src/header.rs +++ b/crates/ibc/src/header.rs @@ -1,6 +1,9 @@ use crate::errors::Error; use crate::internal_prelude::*; -use crate::misbehaviour::Misbehaviour; +use crate::misbehaviour::{ + Misbehaviour, ETHEREUM_FINALIZED_HEADER_MISBEHAVIOUR_TYPE_URL, + ETHEREUM_NEXT_SYNC_COMMITTEE_MISBEHAVIOUR_TYPE_URL, +}; use crate::types::{ convert_consensus_update_to_proto, convert_execution_update_to_proto, convert_proto_to_consensus_update, convert_proto_to_execution_update, AccountUpdateInfo, @@ -18,12 +21,42 @@ use prost::Message; pub const ETHEREUM_HEADER_TYPE_URL: &str = "/ibc.lightclients.ethereum.v1.Header"; #[allow(clippy::large_enum_variant)] -#[derive(serde::Serialize, serde::Deserialize)] +#[derive(Clone, serde::Serialize, serde::Deserialize)] pub enum ClientMessage { Header(Header), Misbehaviour(Misbehaviour), } +impl Protobuf for ClientMessage {} + +impl TryFrom for ClientMessage { + type Error = Error; + + fn try_from(raw: IBCAny) -> Result { + match raw.type_url.as_str() { + ETHEREUM_HEADER_TYPE_URL => { + let header = Header::::try_from(raw)?; + Ok(Self::Header(header)) + } + ETHEREUM_FINALIZED_HEADER_MISBEHAVIOUR_TYPE_URL + | ETHEREUM_NEXT_SYNC_COMMITTEE_MISBEHAVIOUR_TYPE_URL => { + let misbehaviour = Misbehaviour::::try_from(raw)?; + Ok(Self::Misbehaviour(misbehaviour)) + } + _ => Err(Error::UnknownMessageType(raw.type_url)), + } + } +} + +impl From> for IBCAny { + fn from(msg: ClientMessage) -> Self { + match msg { + ClientMessage::Header(header) => IBCAny::from(header), + ClientMessage::Misbehaviour(misbehaviour) => IBCAny::from(misbehaviour), + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Header { pub trusted_sync_committee: TrustedSyncCommittee,