Skip to content

Commit

Permalink
divide LpMessage trait in subtraits (#1977)
Browse files Browse the repository at this point in the history
  • Loading branch information
lemunozm authored Aug 18, 2024
1 parent f1af973 commit 7126ef9
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 95 deletions.
30 changes: 24 additions & 6 deletions libs/traits/src/liquidity_pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ pub type MessageHash = [u8; 32];

/// An encoding & decoding trait for the purpose of meeting the
/// LiquidityPools General Message Passing Format
pub trait LpMessage: Sized {
type Domain;

pub trait LpMessageSerializer: Sized {
/// Serialize the message
fn serialize(&self) -> Vec<u8>;

/// Deserialize the message
fn deserialize(input: &[u8]) -> Result<Self, DispatchError>;
}

/// Behavior or a message that can be batched
pub trait LpMessageBatch: Sized {
/// Extend this message with a new one
fn pack_with(&mut self, other: Self) -> DispatchResult;

Expand All @@ -36,16 +40,25 @@ pub trait LpMessage: Sized {
/// Creates an empty message.
/// It's the identity message for composing messages with pack_with
fn empty() -> Self;
}

/// Returns whether the message is a proof or not.
fn is_proof_message(&self) -> bool;

/// Support for hashing
pub trait LpMessageHash {
/// Retrieves the message hash, if the message is a proof type.
fn get_message_hash(&self) -> MessageHash;
}

/// Behavior of a message that can support proofs
pub trait LpMessageProof: LpMessageHash {
/// Returns whether the message is a proof or not.
fn is_proof_message(&self) -> bool;

/// Converts the message into a message proof type.
fn to_proof_message(&self) -> Self;
}

//Behavior of a message that support recovery
pub trait LpMessageRecovery: LpMessageHash {
/// Creates a message used for initiating message recovery.
///
/// Hash - hash of the message that should be recovered.
Expand All @@ -57,6 +70,11 @@ pub trait LpMessage: Sized {
/// Hash - hash of the message that should be disputed.
/// Router - the address of the recovery router.
fn dispute_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self;
}

/// Behavior of a message that can be forwarded
pub trait LpMessageForwarded: Sized {
type Domain;

/// Checks whether a message is a forwarded one.
fn is_forwarded(&self) -> bool;
Expand Down
4 changes: 2 additions & 2 deletions pallets/liquidity-pools-forwarder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ mod tests;

use core::fmt::Debug;

use cfg_traits::liquidity_pools::{LpMessage as LpMessageT, MessageReceiver, MessageSender};
use cfg_traits::liquidity_pools::{LpMessageForwarded, MessageReceiver, MessageSender};
use cfg_types::domain_address::{Domain, DomainAddress};
use frame_support::{dispatch::DispatchResult, pallet_prelude::*};
use frame_system::pallet_prelude::OriginFor;
Expand Down Expand Up @@ -77,7 +77,7 @@ pub mod pallet {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

/// The Liquidity Pools message type.
type Message: LpMessageT<Domain = Domain>
type Message: LpMessageForwarded<Domain = Domain>
+ Clone
+ Debug
+ PartialEq
Expand Down
54 changes: 2 additions & 52 deletions pallets/liquidity-pools-forwarder/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use cfg_traits::liquidity_pools::{LpMessage, MessageHash};
use cfg_traits::liquidity_pools::LpMessageForwarded;
use cfg_types::domain_address::{Domain, DomainAddress};
use frame_support::{
derive_impl,
dispatch::DispatchResult,
pallet_prelude::{Decode, Encode, MaxEncodedLen, TypeInfo},
weights::constants::RocksDbWeight,
};
Expand All @@ -25,8 +24,6 @@ pub const SOURCE_DOMAIN_ADDRESS: DomainAddress =
DomainAddress::Evm(SOURCE_CHAIN_ID, FORWARD_CONTRACT);
pub const FORWARD_CONTRACT: H160 = H160::repeat_byte(2);
pub const ROUTER_ID: RouterId = 1u32;
const FORWARD_SERIALIZED_MESSAGE_BYTES: [u8; 1] = [0x42];
const NON_FORWARD_SERIALIZED_MESSAGE_BYTES: [u8; 1] = [0x43];
pub const ERROR_NESTING: DispatchError = DispatchError::Other("Nesting forward msg not allowed");

#[derive(Eq, PartialEq, Debug, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Hash)]
Expand All @@ -35,56 +32,9 @@ pub enum Message {
Forward,
}

impl LpMessage for Message {
impl LpMessageForwarded for Message {
type Domain = Domain;

fn serialize(&self) -> Vec<u8> {
match self {
Message::NonForward => NON_FORWARD_SERIALIZED_MESSAGE_BYTES.to_vec(),
Message::Forward => FORWARD_SERIALIZED_MESSAGE_BYTES.to_vec(),
}
}

fn deserialize(input: &[u8]) -> Result<Self, DispatchError> {
match input {
x if x == &NON_FORWARD_SERIALIZED_MESSAGE_BYTES[..] => Ok(Self::NonForward),
x if x == &FORWARD_SERIALIZED_MESSAGE_BYTES[..] => Ok(Self::Forward),
_ => unimplemented!(),
}
}

fn pack_with(&mut self, _: Self) -> DispatchResult {
unimplemented!("out of scope")
}

fn submessages(&self) -> Vec<Self> {
unimplemented!("out of scope")
}

fn empty() -> Self {
unimplemented!("out of scope")
}

fn to_proof_message(&self) -> Self {
unimplemented!("out of scope")
}

fn is_proof_message(&self) -> bool {
unimplemented!("out of scope")
}

fn get_message_hash(&self) -> MessageHash {
unimplemented!("out of scope")
}

fn initiate_recovery_message(_: [u8; 32], _: [u8; 32]) -> Self {
unimplemented!("out of scope")
}

fn dispute_recovery_message(_: [u8; 32], _: [u8; 32]) -> Self {
unimplemented!("out of scope")
}

fn is_forwarded(&self) -> bool {
matches!(self, Self::Forward)
}
Expand Down
10 changes: 7 additions & 3 deletions pallets/liquidity-pools-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ use core::fmt::Debug;

use cfg_primitives::LP_DEFENSIVE_WEIGHT;
use cfg_traits::liquidity_pools::{
InboundMessageHandler, LpMessage, MessageHash, MessageProcessor, MessageQueue, MessageReceiver,
MessageSender, OutboundMessageHandler, RouterProvider,
InboundMessageHandler, LpMessageBatch, LpMessageProof, LpMessageRecovery, LpMessageSerializer,
MessageHash, MessageProcessor, MessageQueue, MessageReceiver, MessageSender,
OutboundMessageHandler, RouterProvider,
};
use cfg_types::domain_address::{Domain, DomainAddress};
use frame_support::{dispatch::DispatchResult, pallet_prelude::*};
Expand Down Expand Up @@ -97,7 +98,10 @@ pub mod pallet {
type AdminOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;

/// The Liquidity Pools message type.
type Message: LpMessage
type Message: LpMessageSerializer
+ LpMessageBatch
+ LpMessageProof
+ LpMessageRecovery
+ Clone
+ Debug
+ PartialEq
Expand Down
3 changes: 2 additions & 1 deletion pallets/liquidity-pools-gateway/src/message_processing.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use cfg_traits::liquidity_pools::{
InboundMessageHandler, LpMessage, MessageHash, MessageQueue, RouterProvider,
InboundMessageHandler, LpMessageBatch, LpMessageHash, LpMessageProof, MessageHash,
MessageQueue, RouterProvider,
};
use cfg_types::domain_address::{Domain, DomainAddress};
use frame_support::{
Expand Down
37 changes: 17 additions & 20 deletions pallets/liquidity-pools-gateway/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::fmt::{Debug, Formatter};

use cfg_mocks::pallet_mock_liquidity_pools;
use cfg_traits::liquidity_pools::{LpMessage, MessageHash, RouterProvider};
use cfg_traits::liquidity_pools::{
LpMessageBatch, LpMessageHash, LpMessageProof, LpMessageRecovery, LpMessageSerializer,
MessageHash, RouterProvider,
};
use cfg_types::{
domain_address::{Domain, DomainAddress},
EVMChainId,
Expand Down Expand Up @@ -59,9 +62,7 @@ impl MaxEncodedLen for Message {
}
}

impl LpMessage for Message {
type Domain = Domain;

impl LpMessageSerializer for Message {
fn serialize(&self) -> Vec<u8> {
match self {
Self::Pack(list) => list.iter().map(|_| 0x42).collect(),
Expand All @@ -76,7 +77,9 @@ impl LpMessage for Message {
n => Self::Pack(sp_std::iter::repeat(Self::Simple).take(n).collect()),
})
}
}

impl LpMessageBatch for Message {
fn pack_with(&mut self, other: Self) -> DispatchResult {
match self {
Self::Pack(list) if list.len() == MAX_PACKED_MESSAGES => {
Expand All @@ -103,41 +106,35 @@ impl LpMessage for Message {
fn empty() -> Self {
Self::Pack(vec![])
}
}

fn is_proof_message(&self) -> bool {
matches!(self, Message::Proof(..))
}

impl LpMessageHash for Message {
fn get_message_hash(&self) -> MessageHash {
MESSAGE_HASH
}
}

impl LpMessageProof for Message {
fn is_proof_message(&self) -> bool {
matches!(self, Message::Proof(..))
}

fn to_proof_message(&self) -> Self {
match self {
Message::Proof(_) => self.clone(),
_ => Message::Proof(self.get_message_hash()),
}
}
}

impl LpMessageRecovery for Message {
fn initiate_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self {
Self::InitiateMessageRecovery((hash, router))
}

fn dispute_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self {
Self::DisputeMessageRecovery((hash, router))
}

fn is_forwarded(&self) -> bool {
unimplemented!("out of scope")
}

fn unwrap_forwarded(self) -> Option<(Self::Domain, H160, Self)> {
unimplemented!("out of scope")
}

fn try_wrap_forward(_: Self::Domain, _: H160, _: Self) -> Result<Self, DispatchError> {
unimplemented!("out of scope")
}
}

#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo, MaxEncodedLen, Hash)]
Expand Down
4 changes: 3 additions & 1 deletion pallets/liquidity-pools-gateway/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::collections::HashMap;

use cfg_primitives::LP_DEFENSIVE_WEIGHT;
use cfg_traits::liquidity_pools::{LpMessage, MessageProcessor, OutboundMessageHandler};
use cfg_traits::liquidity_pools::{
LpMessageHash, LpMessageSerializer, MessageProcessor, OutboundMessageHandler,
};
use cfg_types::domain_address::*;
use frame_support::{assert_err, assert_noop, assert_ok};
use itertools::Itertools;
Expand Down
29 changes: 21 additions & 8 deletions pallets/liquidity-pools/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
//! representation for each message variant.

use cfg_traits::{
liquidity_pools::{LpMessage, MessageHash},
liquidity_pools::{
LpMessageBatch, LpMessageForwarded, LpMessageHash, LpMessageProof, LpMessageRecovery,
LpMessageSerializer, MessageHash,
},
Seconds,
};
use cfg_types::domain_address::Domain;
Expand Down Expand Up @@ -574,17 +577,17 @@ pub enum Message<BatchContent = BatchMessages, ForwardContent = NonForwardMessag
},
}

impl LpMessage for Message {
type Domain = Domain;

impl LpMessageSerializer for Message {
fn serialize(&self) -> Vec<u8> {
gmpf::to_vec(self).unwrap_or_default()
}

fn deserialize(data: &[u8]) -> Result<Self, DispatchError> {
gmpf::from_slice(data).map_err(|_| DispatchError::Other("LP Deserialization issue"))
}
}

impl LpMessageBatch for Message {
fn pack_with(&mut self, other: Self) -> Result<(), DispatchError> {
match self {
Message::Batch(content) => content.try_add(other),
Expand All @@ -605,28 +608,38 @@ impl LpMessage for Message {
fn empty() -> Message {
Message::Batch(BatchMessages::default())
}
}

fn is_proof_message(&self) -> bool {
matches!(self, Message::MessageProof { .. })
impl LpMessageHash for Message {
fn get_message_hash(&self) -> MessageHash {
keccak_256(&LpMessageSerializer::serialize(self))
}
}

fn get_message_hash(&self) -> MessageHash {
keccak_256(&LpMessage::serialize(self))
impl LpMessageProof for Message {
fn is_proof_message(&self) -> bool {
matches!(self, Message::MessageProof { .. })
}

fn to_proof_message(&self) -> Self {
Message::MessageProof {
hash: self.get_message_hash(),
}
}
}

impl LpMessageRecovery for Message {
fn initiate_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self {
Message::InitiateMessageRecovery { hash, router }
}

fn dispute_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self {
Message::DisputeMessageRecovery { hash, router }
}
}

impl LpMessageForwarded for Message {
type Domain = Domain;

fn is_forwarded(&self) -> bool {
matches!(self, Message::Forwarded { .. })
Expand Down
4 changes: 3 additions & 1 deletion runtime/common/src/routing.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cfg_traits::{
liquidity_pools::{LpMessage, MessageReceiver, MessageSender, RouterProvider},
liquidity_pools::{LpMessageSerializer, MessageReceiver, MessageSender, RouterProvider},
PreConditions,
};
use cfg_types::domain_address::{Domain, DomainAddress};
Expand Down Expand Up @@ -71,6 +71,7 @@ where
}
}

/// A precondition to ensure an evm account code is configured for a contract
pub struct EvmAccountCodeChecker<Runtime>(PhantomData<Runtime>);
impl<Runtime: pallet_evm::Config> PreConditions<(H160, H256)> for EvmAccountCodeChecker<Runtime> {
type Result = bool;
Expand All @@ -81,6 +82,7 @@ impl<Runtime: pallet_evm::Config> PreConditions<(H160, H256)> for EvmAccountCode
}
}

/// Entity in charge of serializing and deserializing messages
pub struct MessageSerializer<Sender, Receiver>(PhantomData<(Sender, Receiver)>);

impl<Sender, Receiver> MessageSender for MessageSerializer<Sender, Receiver>
Expand Down
2 changes: 1 addition & 1 deletion runtime/integration-tests/src/cases/routers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cfg_primitives::Balance;
use cfg_traits::liquidity_pools::{LpMessage, MessageProcessor};
use cfg_traits::liquidity_pools::{LpMessageSerializer, MessageProcessor};
use cfg_types::{
domain_address::{Domain, DomainAddress},
EVMChainId,
Expand Down

0 comments on commit 7126ef9

Please sign in to comment.